Merge branch 'upstream' into tizen 80/66480/4 accepted/tizen/common/20160422.171753 accepted/tizen/ivi/20160423.060536 accepted/tizen/mobile/20160423.055559 accepted/tizen/tv/20160423.060010 accepted/tizen/wearable/20160423.060300 submit/tizen/20160421.063352
authoryoungman <yman.jung@samsung.com>
Tue, 19 Apr 2016 06:36:04 +0000 (15:36 +0900)
committeryoungman <yman.jung@samsung.com>
Tue, 19 Apr 2016 07:54:53 +0000 (16:54 +0900)
Change-Id: I5f0484c94f6b5da87c54c54e1f78eaafba10f8e1

1634 files changed:
.gitignore
LICENSE.md
README-building-and-running-remote-access-sample.txt [new file with mode: 0644]
Readme.scons.txt
SConstruct
android/android_api/SConscript
android/android_api/base/build.gradle
android/android_api/base/jni/Android.mk
android/android_api/base/jni/JniCaInterface.c
android/android_api/base/jni/JniCaInterface.h
android/android_api/base/jni/JniOcProvisioning.cpp
android/android_api/base/jni/JniOcResource.cpp
android/android_api/base/jni/JniOcResourceResponse.cpp
android/android_api/base/jni/JniOcSecureResource.cpp
android/android_api/base/jni/JniOcStack.cpp
android/android_api/base/jni/JniOcStack.h
android/android_api/base/jni/JniSecureUtils.cpp
android/android_api/base/jni/JniUtils.h
android/android_api/base/src/main/java/org/iotivity/base/ErrorCode.java
android/android_api/base/src/main/java/org/iotivity/base/OcConnectivityType.java
android/android_api/base/src/main/java/org/iotivity/base/OcPlatform.java
android/android_api/base/src/main/java/org/iotivity/base/OicSecAcl.java
android/android_api/base/src/main/java/org/iotivity/base/PlatformConfig.java
android/android_api/base/src/main/java/org/iotivity/ca/CaBtPairingInterface.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/ca/CaEdrInterface.java
android/android_api/base/src/main/java/org/iotivity/ca/CaInterface.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/CaLeServerInterface.java
android/android_api/base/src/main/java/org/iotivity/ca/CaNfcInterface.java [new file with mode: 0644]
android/examples/devicediscoveryclient/devicediscoveryclient.iml
android/examples/devicediscoveryserver/devicediscoveryserver.iml
android/examples/examples.iml
android/examples/fridgeclient/build.gradle
android/examples/fridgeclient/fridgeclient.iml [changed mode: 0755->0644]
android/examples/fridgegroupserver/build.gradle
android/examples/fridgeserver/build.gradle
android/examples/fridgeserver/fridgeserver.iml [changed mode: 0755->0644]
android/examples/groupclient/groupclient.iml
android/examples/groupserver/groupserver.iml
android/examples/guiclient/guiclient.iml
android/examples/presenceclient/presenceclient.iml
android/examples/presenceserver/presenceserver.iml
android/examples/provisioningclient/provisioningclient.iml
android/examples/provisioningclient/src/main/assets/oic_svr_db_client.dat [new file with mode: 0644]
android/examples/provisioningclient/src/main/assets/oic_svr_db_client.json
android/examples/provisioningclient/src/main/java/org/iotivity/base/examples/provisioningclient/ProvisioningClient.java
android/examples/provisioningclient/src/main/java/org/iotivity/base/examples/provisioningclient/StringConstants.java
android/examples/settings.gradle
android/examples/simpleclient/simpleclient.iml
android/examples/simpleclient/src/main/AndroidManifest.xml
android/examples/simpleclient/src/main/assets/oic_svr_db_client.dat [new file with mode: 0644]
android/examples/simpleclient/src/main/assets/oic_svr_db_client.json
android/examples/simpleclient/src/main/java/org/iotivity/base/examples/SimpleClient.java
android/examples/simpleserver/simpleserver.iml
android/examples/simpleserver/src/main/AndroidManifest.xml
android/examples/simpleserver/src/main/assets/oic_svr_db_server.dat [new file with mode: 0644]
android/examples/simpleserver/src/main/assets/oic_svr_db_server.json [changed mode: 0755->0644]
android/examples/simpleserver/src/main/java/org/iotivity/base/examples/Light.java
android/examples/simpleserver/src/main/java/org/iotivity/base/examples/SimpleServer.java
arduino.scons
auto_build.sh
build_common/SConscript
build_common/android/SConscript
build_common/android/compatibility/c_compat.c
build_common/external_libs.scons
build_common/linux/SConscript
cloud/.gitignore [new file with mode: 0644]
cloud/README [new file with mode: 0644]
cloud/SConscript [new file with mode: 0644]
cloud/account/.classpath [new file with mode: 0644]
cloud/account/.gitignore [new file with mode: 0644]
cloud/account/.project [new file with mode: 0644]
cloud/account/README [new file with mode: 0644]
cloud/account/pom.xml [new file with mode: 0644]
cloud/account/src/main/java/org/iotivity/cloud/accountserver/AccountServer.java [new file with mode: 0644]
cloud/account/src/main/java/org/iotivity/cloud/accountserver/AccountServerManager.java [new file with mode: 0644]
cloud/account/src/main/java/org/iotivity/cloud/accountserver/Constants.java [new file with mode: 0644]
cloud/account/src/main/java/org/iotivity/cloud/accountserver/db/AccountDBManager.java [new file with mode: 0644]
cloud/account/src/main/java/org/iotivity/cloud/accountserver/db/MongoDB.java [new file with mode: 0644]
cloud/account/src/main/java/org/iotivity/cloud/accountserver/db/UserDevice.java [new file with mode: 0644]
cloud/account/src/main/java/org/iotivity/cloud/accountserver/db/UserSession.java [new file with mode: 0644]
cloud/account/src/main/java/org/iotivity/cloud/accountserver/oauth/GitHub.java [new file with mode: 0644]
cloud/account/src/main/java/org/iotivity/cloud/accountserver/oauth/OAuthServer.java [new file with mode: 0644]
cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/AccountResource.java [new file with mode: 0644]
cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/AuthResource.java [new file with mode: 0644]
cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/ResponseObject.java [new file with mode: 0644]
cloud/account/src/main/java/org/iotivity/cloud/accountserver/util/CoapMessageBuilder.java [new file with mode: 0644]
cloud/account/src/test/java/org/iotivity/cloud/testaccountserver/TestAccountServer.java [new file with mode: 0644]
cloud/interface/.classpath [new file with mode: 0644]
cloud/interface/.gitignore [new file with mode: 0644]
cloud/interface/.project [new file with mode: 0644]
cloud/interface/README [new file with mode: 0644]
cloud/interface/pom.xml [new file with mode: 0644]
cloud/interface/src/main/java/org/iotivity/cloud/ciserver/CloudInterfaceServer.java [new file with mode: 0644]
cloud/interface/src/main/java/org/iotivity/cloud/ciserver/Constants.java [new file with mode: 0644]
cloud/interface/src/main/java/org/iotivity/cloud/ciserver/protocols/CoapAuthHandler.java [new file with mode: 0644]
cloud/interface/src/main/java/org/iotivity/cloud/ciserver/protocols/CoapRelayHandler.java [new file with mode: 0644]
cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/KeepAliveResource.java [new file with mode: 0644]
cloud/interface/src/test/java/org/iotivity/cloud/ciserver/testci/TestCloudInterface.java [new file with mode: 0644]
cloud/resourcedirectory/.classpath [new file with mode: 0644]
cloud/resourcedirectory/.gitignore [new file with mode: 0644]
cloud/resourcedirectory/.project [new file with mode: 0644]
cloud/resourcedirectory/README [new file with mode: 0644]
cloud/resourcedirectory/pom.xml [new file with mode: 0644]
cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/Constants.java [new file with mode: 0644]
cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/MongoDB.java [new file with mode: 0644]
cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/ResourceDirectoryServer.java [new file with mode: 0644]
cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/LinksPayloadFormat.java [new file with mode: 0644]
cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/PublishPayloadFormat.java [new file with mode: 0644]
cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/ResourceDirectoryResource.java [new file with mode: 0644]
cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/RDServerTest.java [new file with mode: 0644]
cloud/samples/client/README [new file with mode: 0644]
cloud/samples/client/SConscript [new file with mode: 0644]
cloud/samples/client/cloud_connector.c [new file with mode: 0644]
cloud/samples/client/cloud_connector.h [new file with mode: 0644]
cloud/samples/client/sample_device.cpp [new file with mode: 0644]
cloud/stack/.classpath [new file with mode: 0644]
cloud/stack/.gitignore [new file with mode: 0644]
cloud/stack/.project [new file with mode: 0644]
cloud/stack/README [new file with mode: 0644]
cloud/stack/pom.xml [new file with mode: 0644]
cloud/stack/src/main/java/org/iotivity/cloud/base/CoapClient.java [new file with mode: 0644]
cloud/stack/src/main/java/org/iotivity/cloud/base/CoapServer.java [new file with mode: 0644]
cloud/stack/src/main/java/org/iotivity/cloud/base/HttpClient.java [new file with mode: 0644]
cloud/stack/src/main/java/org/iotivity/cloud/base/HttpServer.java [new file with mode: 0644]
cloud/stack/src/main/java/org/iotivity/cloud/base/Resource.java [new file with mode: 0644]
cloud/stack/src/main/java/org/iotivity/cloud/base/ResourceManager.java [new file with mode: 0644]
cloud/stack/src/main/java/org/iotivity/cloud/base/SessionManager.java [new file with mode: 0644]
cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapDecoder.java [new file with mode: 0644]
cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapEncoder.java [new file with mode: 0644]
cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapMessage.java [new file with mode: 0644]
cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapRequest.java [new file with mode: 0644]
cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapResponse.java [new file with mode: 0644]
cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/enums/CoapMethod.java [new file with mode: 0644]
cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/enums/CoapOption.java [new file with mode: 0644]
cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/enums/CoapStatus.java [new file with mode: 0644]
cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/proxy/CoapHttpProxyHandler.java [new file with mode: 0644]
cloud/stack/src/main/java/org/iotivity/cloud/util/Cbor.java [new file with mode: 0644]
cloud/stack/src/main/java/org/iotivity/cloud/util/CoapLogHandler.java [new file with mode: 0644]
cloud/stack/src/main/java/org/iotivity/cloud/util/JSONUtil.java [new file with mode: 0644]
cloud/stack/src/main/java/org/iotivity/cloud/util/Logger.java [new file with mode: 0644]
cloud/stack/src/test/java/org/iotivity/cloud/base/CoapClientTest.java [new file with mode: 0644]
cloud/stack/src/test/java/org/iotivity/cloud/base/CoapServerTest.java [new file with mode: 0644]
cloud/stack/src/test/java/org/iotivity/cloud/base/ResourceManagerTest.java [new file with mode: 0644]
cloud/stack/src/test/java/org/iotivity/cloud/base/ResourceTest.java [new file with mode: 0644]
cloud/stack/src/test/java/org/iotivity/cloud/base/SessionManagerTest.java [new file with mode: 0644]
cloud/stack/src/test/java/org/iotivity/cloud/base/protocols/coap/CoapRequestTest.java [new file with mode: 0644]
cloud/stack/src/test/java/org/iotivity/cloud/base/protocols/coap/CoapResponseTest.java [new file with mode: 0644]
cloud/stack/src/test/java/org/iotivity/cloud/util/UtilTest.java [new file with mode: 0644]
examples/OICSensorBoard/namedefs.h
extlibs/expat/SConscript [deleted file]
extlibs/libstrophe/SConscript [new file with mode: 0644]
extlibs/libstrophe/strophe-xmpp_conn_is_secured.patch [new file with mode: 0644]
extlibs/raxmpp/SConscript
extlibs/timer/SConscript [new file with mode: 0644]
extlibs/timer/timer.c
extlibs/tinycbor/SConscript
extlibs/tinycbor/tinycbor/.tag [new file with mode: 0644]
extlibs/tinycbor/tinycbor/.travis.yml [new file with mode: 0644]
extlibs/tinycbor/tinycbor/LICENSE [new file with mode: 0644]
extlibs/tinycbor/tinycbor/examples/simplereader.c
extlibs/tinycbor/tinycbor/src/cborparser.c
extlibs/tinycbor/tinycbor/src/extract_number_p.h
extlibs/tinydtls/SConscript
extlibs/tinydtls/dtls.c
extlibs/tinydtls/global.h
extlibs/tinydtls/hmac.h
extlibs/tinydtls/sha2/sha2.c
extlibs/tinydtls/sha2/sha2.h
extlibs/tinydtls/sha2/sha2prog.c
extlibs/tinydtls/sha2/sha2speed.c
extlibs/tinydtls/tests/pcap.c
extlibs/wksxmppxep/SConscript [new file with mode: 0644]
gbsbuild.sh
iotivity.pc.in
packaging/iotivity-test.manifest
packaging/iotivity.spec
plugins/SConscript
plugins/include/internal/pluginlist.h
plugins/include/internal/plugintranslatortypes.h
plugins/include/plugininterface.h
plugins/samples/linux/IotivityandZigbeeClient.c
plugins/samples/linux/IotivityandZigbeeClient.h
plugins/samples/linux/IotivityandZigbeeServer.c
plugins/src/SConscript
plugins/src/plugininterface.c
plugins/src/pluginlist.c
plugins/zigbee_wrapper/src/zigbee_wrapper.c
plugins/zigbee_wrapper/telegesis_wrapper/include/telegesis_socket.h
plugins/zigbee_wrapper/telegesis_wrapper/include/telegesis_wrapper.h
plugins/zigbee_wrapper/telegesis_wrapper/include/twsocketlist.h
plugins/zigbee_wrapper/telegesis_wrapper/include/twtypes.h
plugins/zigbee_wrapper/telegesis_wrapper/src/telegesis_socket.c
plugins/zigbee_wrapper/telegesis_wrapper/src/telegesis_wrapper.c
plugins/zigbee_wrapper/telegesis_wrapper/src/twsocketlist.c
resource/SConscript
resource/android/SConscript
resource/c_common/SConscript
resource/c_common/ocrandom/src/ocrandom.c
resource/c_common/oic_malloc/src/oic_malloc.c
resource/c_common/oic_time/include/oic_time.h [new file with mode: 0644]
resource/c_common/oic_time/src/oic_time.c [new file with mode: 0644]
resource/c_common/oic_time/test/SConscript [new file with mode: 0644]
resource/c_common/oic_time/test/linux/oic_time_tests.cpp [new file with mode: 0644]
resource/csdk/SConscript
resource/csdk/connectivity/SConscript
resource/csdk/connectivity/api/cacommon.h
resource/csdk/connectivity/api/cainterface.h
resource/csdk/connectivity/api/casecurityinterface.h
resource/csdk/connectivity/api/cautilinterface.h [new file with mode: 0644]
resource/csdk/connectivity/build/SConscript
resource/csdk/connectivity/build/android/jni/Android.mk
resource/csdk/connectivity/build/arduino/arduinomega.properties
resource/csdk/connectivity/build/tizen/gbsbuild.sh
resource/csdk/connectivity/build/tizen/packaging/com.oic.ca.spec
resource/csdk/connectivity/common/SConscript
resource/csdk/connectivity/common/inc/cacommonutil.h [new file with mode: 0644]
resource/csdk/connectivity/common/inc/logger.h [deleted file]
resource/csdk/connectivity/common/inc/oic_console_logger.h [deleted file]
resource/csdk/connectivity/common/inc/oic_logger.h [deleted file]
resource/csdk/connectivity/common/inc/oic_logger_types.h [deleted file]
resource/csdk/connectivity/common/src/camutex_pthreads.c
resource/csdk/connectivity/common/src/caremotehandler.c
resource/csdk/connectivity/common/src/cathreadpool_pthreads.c
resource/csdk/connectivity/common/src/logger.c [deleted file]
resource/csdk/connectivity/common/src/oic_console_logger.c [deleted file]
resource/csdk/connectivity/common/src/oic_logger.c [deleted file]
resource/csdk/connectivity/common/src/ulinklist.c
resource/csdk/connectivity/inc/caadapterinterface.h
resource/csdk/connectivity/inc/caadapternetdtls.h
resource/csdk/connectivity/inc/caadapterutils.h
resource/csdk/connectivity/inc/cablockwisetransfer.h
resource/csdk/connectivity/inc/caedrinterface.h
resource/csdk/connectivity/inc/cafragmentation.h [deleted file]
resource/csdk/connectivity/inc/cainterfacecontroller.h
resource/csdk/connectivity/inc/caipinterface.h
resource/csdk/connectivity/inc/caleinterface.h
resource/csdk/connectivity/inc/camessagehandler.h
resource/csdk/connectivity/inc/canfcadapter.h [new file with mode: 0644]
resource/csdk/connectivity/inc/canfcinterface.h [new file with mode: 0644]
resource/csdk/connectivity/inc/caprotocolmessage.h
resource/csdk/connectivity/inc/caraadapter.h
resource/csdk/connectivity/inc/catcpadapter.h
resource/csdk/connectivity/inc/catcpinterface.h
resource/csdk/connectivity/inc/pkix/byte_array.h
resource/csdk/connectivity/inc/pkix/cert.h
resource/csdk/connectivity/inc/pkix/crypto_adapter.h
resource/csdk/connectivity/lib/libcoap-4.1.1/SConscript
resource/csdk/connectivity/lib/libcoap-4.1.1/pdu.c
resource/csdk/connectivity/lib/libcoap-4.1.1/pdu.h
resource/csdk/connectivity/lib/tizen/ble/inc/bluetooth.h [deleted file]
resource/csdk/connectivity/lib/tizen/ble/inc/bluetooth_private.h [deleted file]
resource/csdk/connectivity/lib/tizen/ble/inc/bluetooth_type.h [deleted file]
resource/csdk/connectivity/lib/tizen/ble/inc/mobile/bluetooth_product.h [deleted file]
resource/csdk/connectivity/lib/tizen/ble/inc/mobile/bluetooth_type_product.h [deleted file]
resource/csdk/connectivity/samples/android/SConscript [deleted file]
resource/csdk/connectivity/samples/android/casample/.gitignore [deleted file]
resource/csdk/connectivity/samples/android/casample/SConscript [deleted file]
resource/csdk/connectivity/samples/android/casample/build.gradle [deleted file]
resource/csdk/connectivity/samples/android/casample/cAInterface/.gitignore [deleted file]
resource/csdk/connectivity/samples/android/casample/cAInterface/build.gradle [deleted file]
resource/csdk/connectivity/samples/android/casample/cAInterface/cAInterface.iml [deleted file]
resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/.gitignore [deleted file]
resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/AndroidManifest.xml [deleted file]
resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/java/org/iotivity/ca/CaEdrInterface.java [deleted file]
resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/java/org/iotivity/ca/CaIpInterface.java [deleted file]
resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/java/org/iotivity/ca/CaLeClientInterface.java [deleted file]
resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/java/org/iotivity/ca/CaLeServerInterface.java [deleted file]
resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/res/drawable-hdpi/ic_launcher.png [deleted file]
resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/res/drawable-mdpi/ic_launcher.png [deleted file]
resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/res/drawable-xhdpi/ic_launcher.png [deleted file]
resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/res/values-v11/styles.xml [deleted file]
resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/res/values-v14/styles.xml [deleted file]
resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/res/values/strings.xml [deleted file]
resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/res/values/styles.xml [deleted file]
resource/csdk/connectivity/samples/android/casample/casample.iml [deleted file]
resource/csdk/connectivity/samples/android/casample/gradle.properties [deleted file]
resource/csdk/connectivity/samples/android/casample/gradle/wrapper/gradle-wrapper.properties [deleted file]
resource/csdk/connectivity/samples/android/casample/sampleService/.gitignore [deleted file]
resource/csdk/connectivity/samples/android/casample/sampleService/build.gradle [deleted file]
resource/csdk/connectivity/samples/android/casample/sampleService/sampleService.iml [deleted file]
resource/csdk/connectivity/samples/android/casample/sampleService/src/main/.gitignore [deleted file]
resource/csdk/connectivity/samples/android/casample/sampleService/src/main/AndroidManifest.xml [deleted file]
resource/csdk/connectivity/samples/android/casample/sampleService/src/main/java/org/iotivity/ca/service/DLog.java [deleted file]
resource/csdk/connectivity/samples/android/casample/sampleService/src/main/java/org/iotivity/ca/service/FileChooser.java [deleted file]
resource/csdk/connectivity/samples/android/casample/sampleService/src/main/java/org/iotivity/ca/service/MainActivity.java [deleted file]
resource/csdk/connectivity/samples/android/casample/sampleService/src/main/java/org/iotivity/ca/service/RMInterface.java [deleted file]
resource/csdk/connectivity/samples/android/casample/sampleService/src/main/jni/Android.mk [deleted file]
resource/csdk/connectivity/samples/android/casample/sampleService/src/main/jni/Application.mk [deleted file]
resource/csdk/connectivity/samples/android/casample/sampleService/src/main/jni/ResourceModel.c [deleted file]
resource/csdk/connectivity/samples/android/casample/sampleService/src/main/jni/org_iotivity_ca_service_RMInterface.h [deleted file]
resource/csdk/connectivity/samples/android/casample/sampleService/src/main/res/layout/activity_main.xml [deleted file]
resource/csdk/connectivity/samples/android/casample/sampleService/src/main/res/menu/main.xml [deleted file]
resource/csdk/connectivity/samples/android/casample/sampleService/src/main/res/values-v11/styles.xml [deleted file]
resource/csdk/connectivity/samples/android/casample/sampleService/src/main/res/values-v14/styles.xml [deleted file]
resource/csdk/connectivity/samples/android/casample/sampleService/src/main/res/values-w820dp/dimens.xml [deleted file]
resource/csdk/connectivity/samples/android/casample/sampleService/src/main/res/values/dimens.xml [deleted file]
resource/csdk/connectivity/samples/android/casample/sampleService/src/main/res/values/strings.xml [deleted file]
resource/csdk/connectivity/samples/android/casample/sampleService/src/main/res/values/styles.xml [deleted file]
resource/csdk/connectivity/samples/android/casample/settings.gradle [deleted file]
resource/csdk/connectivity/samples/arduino/SConscript [deleted file]
resource/csdk/connectivity/samples/arduino/casample.cpp [deleted file]
resource/csdk/connectivity/samples/linux/README [deleted file]
resource/csdk/connectivity/samples/linux/SConscript [deleted file]
resource/csdk/connectivity/samples/linux/sample_main.c [deleted file]
resource/csdk/connectivity/samples/linux/threadpool/main.c [deleted file]
resource/csdk/connectivity/samples/tizen/README.txt [deleted file]
resource/csdk/connectivity/samples/tizen/SConscript [deleted file]
resource/csdk/connectivity/samples/tizen/casample.c [deleted file]
resource/csdk/connectivity/samples/tizen/com.oic.ca.sample.manifest [deleted file]
resource/csdk/connectivity/samples/tizen/com.oic.ca.sample.xml [deleted file]
resource/csdk/connectivity/samples/tizen/gbsbuild.sh [deleted file]
resource/csdk/connectivity/samples/tizen/packaging/com.oic.ca.sample.spec [deleted file]
resource/csdk/connectivity/samples/tizen/scons/SConscript [deleted file]
resource/csdk/connectivity/src/SConscript
resource/csdk/connectivity/src/adapter_util/caadapternetdtls.c
resource/csdk/connectivity/src/adapter_util/caadapterutils.c
resource/csdk/connectivity/src/adapter_util/cafragmentation.c [deleted file]
resource/csdk/connectivity/src/adapter_util/pkix/der_dec.c
resource/csdk/connectivity/src/adapter_util/pkix/sn_store.c
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrclient.c
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrclient.h
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrnwmonitor.c
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrserver.c
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrserver.h
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrutils.c
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrutils.h
resource/csdk/connectivity/src/bt_edr_adapter/caedradapter.c
resource/csdk/connectivity/src/bt_edr_adapter/linux/caedradapter.c
resource/csdk/connectivity/src/bt_edr_adapter/tizen/SConscript
resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrclient.c
resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrendpoint.c
resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrnwmonitor.c
resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrserver.c
resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrutils.c
resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrutils.h
resource/csdk/connectivity/src/bt_le_adapter/android/caleclient.c
resource/csdk/connectivity/src/bt_le_adapter/android/caleclient.h
resource/csdk/connectivity/src/bt_le_adapter/android/calenwmonitor.c
resource/csdk/connectivity/src/bt_le_adapter/android/calenwmonitor.h
resource/csdk/connectivity/src/bt_le_adapter/android/caleserver.c
resource/csdk/connectivity/src/bt_le_adapter/android/caleserver.h
resource/csdk/connectivity/src/bt_le_adapter/android/caleutils.c
resource/csdk/connectivity/src/bt_le_adapter/android/caleutils.h
resource/csdk/connectivity/src/bt_le_adapter/android/org_iotivity_ca_CaLeClientInterface.h
resource/csdk/connectivity/src/bt_le_adapter/android/org_iotivity_ca_CaLeServerInterface.h
resource/csdk/connectivity/src/bt_le_adapter/arduino/cableclient.cpp
resource/csdk/connectivity/src/bt_le_adapter/arduino/cablenwmonitor.cpp
resource/csdk/connectivity/src/bt_le_adapter/arduino/cableserver.cpp
resource/csdk/connectivity/src/bt_le_adapter/caleadapter.c
resource/csdk/connectivity/src/bt_le_adapter/linux/.gitignore [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/linux/SConscript
resource/csdk/connectivity/src/bt_le_adapter/linux/caleinterface.c
resource/csdk/connectivity/src/bt_le_adapter/linux/central.h
resource/csdk/connectivity/src/bt_le_adapter/linux/characteristic.c
resource/csdk/connectivity/src/bt_le_adapter/linux/client.c
resource/csdk/connectivity/src/bt_le_adapter/linux/client.h
resource/csdk/connectivity/src/bt_le_adapter/linux/context.h
resource/csdk/connectivity/src/bt_le_adapter/linux/descriptor.c
resource/csdk/connectivity/src/bt_le_adapter/linux/peripheral.c
resource/csdk/connectivity/src/bt_le_adapter/linux/peripheral.h
resource/csdk/connectivity/src/bt_le_adapter/linux/recv.c
resource/csdk/connectivity/src/bt_le_adapter/linux/server.c
resource/csdk/connectivity/src/bt_le_adapter/linux/server.h
resource/csdk/connectivity/src/bt_le_adapter/linux/service.c
resource/csdk/connectivity/src/bt_le_adapter/linux/service.h
resource/csdk/connectivity/src/bt_le_adapter/linux/utils.c
resource/csdk/connectivity/src/bt_le_adapter/tizen/SConscript
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableclient.c [deleted file]
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableclient.h [deleted file]
resource/csdk/connectivity/src/bt_le_adapter/tizen/cablenwmonitor.c [deleted file]
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableserver.c [deleted file]
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableserver.h [deleted file]
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableutil.c [deleted file]
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableutil.h [deleted file]
resource/csdk/connectivity/src/bt_le_adapter/tizen/caleclient.c [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/tizen/caleclient.h [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/tizen/calenwmonitor.c [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/tizen/caleserver.c [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/tizen/caleserver.h [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/tizen/caleutil.c [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/tizen/caleutil.h [new file with mode: 0644]
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/canetworkconfigurator.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 [changed mode: 0755->0644]
resource/csdk/connectivity/src/ip_adapter/arduino/caipserver_eth.cpp
resource/csdk/connectivity/src/ip_adapter/arduino/caipserver_wifi.cpp
resource/csdk/connectivity/src/ip_adapter/caipadapter.c
resource/csdk/connectivity/src/ip_adapter/caipserver.c
resource/csdk/connectivity/src/ip_adapter/linux/caipnwmonitor.c
resource/csdk/connectivity/src/ip_adapter/tizen/caipnwmonitor.c
resource/csdk/connectivity/src/nfc_adapter/SConscript [new file with mode: 0644]
resource/csdk/connectivity/src/nfc_adapter/android/SConscript [new file with mode: 0644]
resource/csdk/connectivity/src/nfc_adapter/android/canfcserver.c [new file with mode: 0644]
resource/csdk/connectivity/src/nfc_adapter/canfcadapter.c [new file with mode: 0644]
resource/csdk/connectivity/src/ra_adapter/SConscript
resource/csdk/connectivity/src/ra_adapter/caraadapter.c
resource/csdk/connectivity/src/tcp_adapter/SConscript
resource/csdk/connectivity/src/tcp_adapter/catcpadapter.c
resource/csdk/connectivity/src/tcp_adapter/catcpserver.c
resource/csdk/connectivity/test/ca_api_unittest.cpp
resource/csdk/connectivity/util/SConscript [new file with mode: 0644]
resource/csdk/connectivity/util/inc/cabtpairinginterface.h [new file with mode: 0644]
resource/csdk/connectivity/util/inc/camanagerleinterface.h [new file with mode: 0644]
resource/csdk/connectivity/util/src/btpairing/android/cabtpairing.c [new file with mode: 0644]
resource/csdk/connectivity/util/src/btpairing/android/cabtpairing.h [new file with mode: 0644]
resource/csdk/connectivity/util/src/camanager/android/caleautoconnector.c [new file with mode: 0644]
resource/csdk/connectivity/util/src/camanager/android/caleautoconnector.h [new file with mode: 0644]
resource/csdk/connectivity/util/src/camanager/android/caleconnectionmanager.c [new file with mode: 0644]
resource/csdk/connectivity/util/src/camanager/android/camanagerdevice.c [new file with mode: 0644]
resource/csdk/connectivity/util/src/camanager/android/camanagerdevice.h [new file with mode: 0644]
resource/csdk/connectivity/util/src/camanager/android/camanagerleutil.c [new file with mode: 0644]
resource/csdk/connectivity/util/src/camanager/android/camanagerleutil.h [new file with mode: 0644]
resource/csdk/connectivity/util/src/camanager/arduino/caleconnectionmanager.c [new file with mode: 0644]
resource/csdk/connectivity/util/src/camanager/linux/caleconnectionmanager.c [new file with mode: 0644]
resource/csdk/connectivity/util/src/camanager/tizen/caleconnectionmanager.c [new file with mode: 0644]
resource/csdk/connectivity/util/src/cautilinterface.c [new file with mode: 0644]
resource/csdk/logger/SConscript [new file with mode: 0644]
resource/csdk/logger/include/logger.h
resource/csdk/logger/include/logger_types.h [new file with mode: 0644]
resource/csdk/logger/src/logger.c
resource/csdk/logger/test/android/loggertests.cpp
resource/csdk/logger/test/arduino/ArduinoLoggerTest.cpp
resource/csdk/logger/test/loggertests.cpp
resource/csdk/routing/SConscript
resource/csdk/routing/include/routingmanager.h
resource/csdk/routing/include/routingutility.h
resource/csdk/routing/src/routingmanager.c
resource/csdk/routing/src/routingmanagerinterface.c
resource/csdk/routing/src/routingmessageparser.c
resource/csdk/routing/src/routingtablemanager.c
resource/csdk/routing/src/routingutility.c
resource/csdk/security/SConscript [changed mode: 0755->0644]
resource/csdk/security/include/base64.h
resource/csdk/security/include/internal/aclresource.h
resource/csdk/security/include/internal/amaclresource.h [changed mode: 0755->0644]
resource/csdk/security/include/internal/amsmgr.h
resource/csdk/security/include/internal/credresource.h
resource/csdk/security/include/internal/crlresource.h
resource/csdk/security/include/internal/directpairing.h [new file with mode: 0644]
resource/csdk/security/include/internal/doxmresource.h
resource/csdk/security/include/internal/dpairingresource.h [new file with mode: 0644]
resource/csdk/security/include/internal/pconfresource.h [new file with mode: 0644]
resource/csdk/security/include/internal/policyengine.h
resource/csdk/security/include/internal/psinterface.h
resource/csdk/security/include/internal/pstatresource.h
resource/csdk/security/include/internal/resourcemanager.h
resource/csdk/security/include/internal/secureresourcemanager.h
resource/csdk/security/include/internal/security_internals.h [new file with mode: 0644]
resource/csdk/security/include/internal/srmresourcestrings.h [changed mode: 0755->0644]
resource/csdk/security/include/internal/svcresource.h
resource/csdk/security/include/internal/verresource.h [new file with mode: 0644]
resource/csdk/security/include/iotvticalendar.h
resource/csdk/security/include/pbkdf2.h
resource/csdk/security/include/pinoxmcommon.h
resource/csdk/security/include/securevirtualresourcetypes.h [changed mode: 0755->0644]
resource/csdk/security/include/srmutility.h
resource/csdk/security/provisioning/SConscript
resource/csdk/security/provisioning/ck_manager/SConscript
resource/csdk/security/provisioning/ck_manager/include/ck_manager.h
resource/csdk/security/provisioning/ck_manager/include/ckm_info.h
resource/csdk/security/provisioning/ck_manager/sample/Door_sample.cpp [changed mode: 0755->0644]
resource/csdk/security/provisioning/ck_manager/sample/Light_sample.cpp
resource/csdk/security/provisioning/ck_manager/sample/SConscript
resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.dat [new file with mode: 0755]
resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.json [changed mode: 0644->0755]
resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.dat [new file with mode: 0755]
resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.json [changed mode: 0644->0755]
resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.dat [new file with mode: 0755]
resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.json [changed mode: 0644->0755]
resource/csdk/security/provisioning/ck_manager/sample/provisioningclient.c
resource/csdk/security/provisioning/ck_manager/src/cert_generator.c
resource/csdk/security/provisioning/ck_manager/src/ck_manager.c
resource/csdk/security/provisioning/ck_manager/src/ckm_info.c
resource/csdk/security/provisioning/ck_manager/src/crl_generator.c
resource/csdk/security/provisioning/ck_manager/tools/x509_check.c [deleted file]
resource/csdk/security/provisioning/ck_manager/tools/x509_issue.c [deleted file]
resource/csdk/security/provisioning/ck_manager/unittest/SConscript
resource/csdk/security/provisioning/ck_manager/unittest/pki_test.cpp
resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.dat [new file with mode: 0644]
resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.json
resource/csdk/security/provisioning/include/internal/ownershiptransfermanager.h
resource/csdk/security/provisioning/include/internal/provisioningdatabasemanager.h
resource/csdk/security/provisioning/include/internal/secureresourceprovider.h
resource/csdk/security/provisioning/include/ocprovisioningmanager.h
resource/csdk/security/provisioning/include/oxm/oxmjustworks.h
resource/csdk/security/provisioning/include/oxm/oxmrandompin.h
resource/csdk/security/provisioning/include/pmtypes.h
resource/csdk/security/provisioning/include/pmutility.h
resource/csdk/security/provisioning/sample/README-Provisioning-Tool.txt
resource/csdk/security/provisioning/sample/SConscript
resource/csdk/security/provisioning/sample/oic_svr_db_client.dat [new file with mode: 0644]
resource/csdk/security/provisioning/sample/oic_svr_db_client.json
resource/csdk/security/provisioning/sample/oic_svr_db_prov_tool.json [deleted file]
resource/csdk/security/provisioning/sample/oic_svr_db_randompin_with_empty_deviceid.dat [new file with mode: 0644]
resource/csdk/security/provisioning/sample/oic_svr_db_randompin_with_empty_deviceid.json [new file with mode: 0644]
resource/csdk/security/provisioning/sample/oic_svr_db_server_justworks.dat [new file with mode: 0644]
resource/csdk/security/provisioning/sample/oic_svr_db_server_justworks.json
resource/csdk/security/provisioning/sample/oic_svr_db_server_randompin.dat [new file with mode: 0644]
resource/csdk/security/provisioning/sample/oic_svr_db_server_randompin.json [changed mode: 0755->0644]
resource/csdk/security/provisioning/sample/oic_svr_db_unowned_server.json [deleted file]
resource/csdk/security/provisioning/sample/provisioningclient.c
resource/csdk/security/provisioning/sample/sampleserver_justworks.cpp
resource/csdk/security/provisioning/sample/sampleserver_randompin.cpp
resource/csdk/security/provisioning/src/credentialgenerator.c
resource/csdk/security/provisioning/src/ocprovisioningmanager.c
resource/csdk/security/provisioning/src/ownershiptransfermanager.c [changed mode: 0755->0644]
resource/csdk/security/provisioning/src/oxmjustworks.c
resource/csdk/security/provisioning/src/oxmrandompin.c
resource/csdk/security/provisioning/src/pmutility.c [changed mode: 0755->0644]
resource/csdk/security/provisioning/src/provisioningdatabasemanager.c
resource/csdk/security/provisioning/src/secureresourceprovider.c [changed mode: 0755->0644]
resource/csdk/security/provisioning/unittest/SConscript
resource/csdk/security/provisioning/unittest/ocprovisioningmanager.cpp
resource/csdk/security/provisioning/unittest/otmunittest.cpp
resource/csdk/security/provisioning/unittest/provisioningdatabasemanager.cpp
resource/csdk/security/provisioning/unittest/secureresourceprovider.cpp
resource/csdk/security/src/aclresource.c
resource/csdk/security/src/amaclresource.c
resource/csdk/security/src/amsmgr.c
resource/csdk/security/src/base64.c
resource/csdk/security/src/credresource.c
resource/csdk/security/src/crlresource.c
resource/csdk/security/src/directpairing.c [new file with mode: 0644]
resource/csdk/security/src/doxmresource.c
resource/csdk/security/src/dpairingresource.c [new file with mode: 0644]
resource/csdk/security/src/iotvticalendar.c
resource/csdk/security/src/oxmpincommon.c
resource/csdk/security/src/pbkdf2.c
resource/csdk/security/src/pconfresource.c [new file with mode: 0644]
resource/csdk/security/src/policyengine.c
resource/csdk/security/src/psinterface.c
resource/csdk/security/src/pstatresource.c
resource/csdk/security/src/resourcemanager.c
resource/csdk/security/src/secureresourcemanager.c
resource/csdk/security/src/srmresourcestrings.c [changed mode: 0755->0644]
resource/csdk/security/src/srmutility.c
resource/csdk/security/src/svcresource.c
resource/csdk/security/src/verresource.c [new file with mode: 0644]
resource/csdk/security/tool/SConscript [new file with mode: 0644]
resource/csdk/security/tool/json2cbor.c [new file with mode: 0644]
resource/csdk/security/unittest/SConscript
resource/csdk/security/unittest/aclresourcetest.cpp
resource/csdk/security/unittest/amaclresourcetest.cpp [new file with mode: 0644]
resource/csdk/security/unittest/base64tests.cpp
resource/csdk/security/unittest/credentialresource.cpp
resource/csdk/security/unittest/directpairingtest.cpp [new file with mode: 0644]
resource/csdk/security/unittest/doxmresource.cpp
resource/csdk/security/unittest/iotvticalendartest.cpp
resource/csdk/security/unittest/oic_svr_db.dat [new file with mode: 0644]
resource/csdk/security/unittest/oic_svr_db.json
resource/csdk/security/unittest/oic_unittest.dat [new file with mode: 0644]
resource/csdk/security/unittest/oic_unittest.json
resource/csdk/security/unittest/oic_unittest_acl1.dat [new file with mode: 0644]
resource/csdk/security/unittest/oic_unittest_acl1.json
resource/csdk/security/unittest/oic_unittest_default_acl.dat [new file with mode: 0644]
resource/csdk/security/unittest/oic_unittest_default_acl.json
resource/csdk/security/unittest/policyengine.cpp
resource/csdk/security/unittest/pstatresource.cpp
resource/csdk/security/unittest/srmtestcommon.cpp
resource/csdk/security/unittest/srmtestcommon.h
resource/csdk/security/unittest/svcresourcetest.cpp
resource/csdk/stack/include/internal/ocresource.h [changed mode: 0644->0755]
resource/csdk/stack/include/internal/ocresourcehandler.h
resource/csdk/stack/include/internal/ocstackinternal.h
resource/csdk/stack/include/internal/oicgroup.h [changed mode: 0644->0755]
resource/csdk/stack/include/internal/oickeepalive.h [new file with mode: 0644]
resource/csdk/stack/include/ocpayload.h
resource/csdk/stack/include/ocstack.h
resource/csdk/stack/include/octypes.h
resource/csdk/stack/include/payload_logging.h
resource/csdk/stack/include/rdpayload.h
resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/SConscript
resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/ocserver.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/occlient.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/occlientbasicops.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/occlientcoll.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/occlientslow.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/ocremoteaccessclient.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/ocrouting.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/ocserver.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/ocserverbasicops.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/ocservercoll.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/ocserverslow.cpp
resource/csdk/stack/samples/linux/secure/SConscript
resource/csdk/stack/samples/linux/secure/ocamsservice.cpp
resource/csdk/stack/samples/linux/secure/occlientbasicops.cpp
resource/csdk/stack/samples/linux/secure/occlientdirectpairing.cpp [new file with mode: 0644]
resource/csdk/stack/samples/linux/secure/ocserverbasicops.cpp
resource/csdk/stack/samples/linux/secure/oic_amss_db.dat [new file with mode: 0644]
resource/csdk/stack/samples/linux/secure/oic_amss_db.json
resource/csdk/stack/samples/linux/secure/oic_svr_db_client.dat [new file with mode: 0644]
resource/csdk/stack/samples/linux/secure/oic_svr_db_client.json
resource/csdk/stack/samples/linux/secure/oic_svr_db_client_directpairing.dat [new file with mode: 0644]
resource/csdk/stack/samples/linux/secure/oic_svr_db_client_directpairing.json [new file with mode: 0644]
resource/csdk/stack/samples/linux/secure/oic_svr_db_server.dat [new file with mode: 0644]
resource/csdk/stack/samples/linux/secure/oic_svr_db_server.json
resource/csdk/stack/samples/linux/secure/oic_svr_db_server_justworks.dat [new file with mode: 0644]
resource/csdk/stack/samples/tizen/README.txt [new file with mode: 0644]
resource/csdk/stack/samples/tizen/SimpleClientServer/occlient.cpp
resource/csdk/stack/samples/tizen/SimpleClientServer/ocserver.cpp
resource/csdk/stack/samples/tizen/build/gbsbuild.sh
resource/csdk/stack/samples/tizen/build/packaging/com.oic.ri.spec
resource/csdk/stack/src/occlientcb.c
resource/csdk/stack/src/occollection.c [changed mode: 0644->0755]
resource/csdk/stack/src/ocobserve.c
resource/csdk/stack/src/ocpayload.c [changed mode: 0755->0644]
resource/csdk/stack/src/ocpayloadconvert.c
resource/csdk/stack/src/ocpayloadparse.c
resource/csdk/stack/src/ocresource.c [changed mode: 0644->0755]
resource/csdk/stack/src/ocserverrequest.c
resource/csdk/stack/src/ocstack.c [changed mode: 0755->0644]
resource/csdk/stack/src/oicgroup.c
resource/csdk/stack/src/oickeepalive.c [new file with mode: 0644]
resource/csdk/stack/src/rdpayload.c
resource/csdk/stack/test/README
resource/csdk/stack/test/android/stacktests.cpp
resource/csdk/stack/test/arduino/ArduinoStackTest.cpp
resource/csdk/stack/test/arduino/ocserver.cpp
resource/csdk/stack/test/linux/occlient.c
resource/csdk/stack/test/linux/ocserver.c
resource/csdk/stack/test/stacktests.cpp
resource/docs/Doxyfile [deleted file]
resource/docs/c-doc/Doxyfile [new file with mode: 0644]
resource/docs/c-doc/devdocs.doxyfile [moved from resource/docs/devdocs.doxyfile with 100% similarity]
resource/docs/c-doc/devdox/ca_functional.dox [moved from resource/docs/devdox/ca_functional.dox with 100% similarity]
resource/docs/c-doc/devdox/ca_overview.dox [moved from resource/docs/devdox/ca_overview.dox with 100% similarity]
resource/docs/c-doc/devdox/dot/ca_arch.gv [moved from resource/docs/devdox/dot/ca_arch.gv with 100% similarity]
resource/docs/c-doc/devdox/dot/ca_arch_sketch.gv [moved from resource/docs/devdox/dot/ca_arch_sketch.gv with 100% similarity]
resource/docs/c-doc/devdox/dot/ca_overview.gv [moved from resource/docs/devdox/dot/ca_overview.gv with 100% similarity]
resource/docs/c-doc/devdox/mainpage.dox [moved from resource/docs/devdox/mainpage.dox with 100% similarity]
resource/docs/c-doc/doxygenLayout.xml [moved from resource/docs/doxygenLayout.xml with 100% similarity]
resource/docs/c-doc/guides/Home.txt [moved from resource/docs/guides/Home.txt with 100% similarity]
resource/docs/c-doc/html/footer.html [moved from resource/docs/html/footer.html with 100% similarity]
resource/docs/c-doc/img/seq_find_resource.png [moved from resource/docs/img/seq_find_resource.png with 100% similarity]
resource/docs/c-doc/img/seq_find_resource_2.png [moved from resource/docs/img/seq_find_resource_2.png with 100% similarity]
resource/docs/c-doc/img/seq_find_resource_3.png [moved from resource/docs/img/seq_find_resource_3.png with 100% similarity]
resource/docs/c-doc/img/seq_find_resource_4.png [moved from resource/docs/img/seq_find_resource_4.png with 100% similarity]
resource/docs/c-doc/img/seq_get.png [moved from resource/docs/img/seq_get.png with 100% similarity]
resource/docs/c-doc/img/seq_observe.png [moved from resource/docs/img/seq_observe.png with 100% similarity]
resource/docs/c-doc/img/seq_put.png [moved from resource/docs/img/seq_put.png with 100% similarity]
resource/docs/c-doc/img/seq_register_resource.png [moved from resource/docs/img/seq_register_resource.png with 100% similarity]
resource/docs/c-doc/img/seq_register_resource_2.png [moved from resource/docs/img/seq_register_resource_2.png with 100% similarity]
resource/docs/c-doc/img/seq_stack_init.png [moved from resource/docs/img/seq_stack_init.png with 100% similarity]
resource/docs/c-doc/img/stack_diagram.png [moved from resource/docs/img/stack_diagram.png with 100% similarity]
resource/docs/cpp-doc/Doxyfile [new file with mode: 0644]
resource/docs/cpp-doc/devdocs.doxyfile [new file with mode: 0644]
resource/docs/cpp-doc/devdox/ca_functional.dox [new file with mode: 0644]
resource/docs/cpp-doc/devdox/ca_overview.dox [new file with mode: 0644]
resource/docs/cpp-doc/devdox/dot/ca_arch.gv [new file with mode: 0644]
resource/docs/cpp-doc/devdox/dot/ca_arch_sketch.gv [new file with mode: 0644]
resource/docs/cpp-doc/devdox/dot/ca_overview.gv [new file with mode: 0644]
resource/docs/cpp-doc/devdox/mainpage.dox [new file with mode: 0644]
resource/docs/cpp-doc/doxygenLayout.xml [new file with mode: 0644]
resource/docs/cpp-doc/guides/Home.txt [new file with mode: 0644]
resource/docs/cpp-doc/html/footer.html [new file with mode: 0644]
resource/docs/cpp-doc/img/seq_find_resource.png [new file with mode: 0644]
resource/docs/cpp-doc/img/seq_find_resource_2.png [new file with mode: 0644]
resource/docs/cpp-doc/img/seq_find_resource_3.png [new file with mode: 0644]
resource/docs/cpp-doc/img/seq_find_resource_4.png [new file with mode: 0644]
resource/docs/cpp-doc/img/seq_get.png [new file with mode: 0644]
resource/docs/cpp-doc/img/seq_observe.png [new file with mode: 0644]
resource/docs/cpp-doc/img/seq_put.png [new file with mode: 0644]
resource/docs/cpp-doc/img/seq_register_resource.png [new file with mode: 0644]
resource/docs/cpp-doc/img/seq_register_resource_2.png [new file with mode: 0644]
resource/docs/cpp-doc/img/seq_stack_init.png [new file with mode: 0644]
resource/docs/cpp-doc/img/stack_diagram.png [new file with mode: 0644]
resource/docs/javadocGen.sh
resource/examples/SConscript
resource/examples/devicediscoveryserver.cpp
resource/examples/fridgeclient.cpp
resource/examples/groupserver.cpp [changed mode: 0644->0755]
resource/examples/oic_svr_db_client.dat [new file with mode: 0644]
resource/examples/oic_svr_db_client.json
resource/examples/oic_svr_db_server.dat [new file with mode: 0644]
resource/examples/oic_svr_db_server.json
resource/examples/simpleclient.cpp
resource/examples/simpleserver.cpp
resource/include/AttributeValue.h
resource/include/CAManager.h [new file with mode: 0644]
resource/include/IClientWrapper.h
resource/include/IServerWrapper.h
resource/include/InProcClientWrapper.h
resource/include/InProcServerWrapper.h
resource/include/InitializeException.h
resource/include/OCAndroid.h
resource/include/OCApi.h
resource/include/OCException.h
resource/include/OCHeaderOption.h
resource/include/OCPlatform.h
resource/include/OCPlatform_impl.h
resource/include/OCProvisioningManager.h
resource/include/OCRepresentation.h
resource/include/OCResource.h
resource/include/OCResourceRequest.h
resource/include/OCResourceResponse.h
resource/include/OCSerialization.h
resource/include/OCUtilities.h
resource/include/OutOfProcClientWrapper.h
resource/include/OutOfProcServerWrapper.h
resource/include/ResourceInitException.h
resource/include/StringConstants.h
resource/include/WrapperFactory.h
resource/oc_logger/SConscript
resource/oc_logger/include/oc_console_logger.h
resource/oc_logger/include/oc_log.hpp
resource/oc_logger/include/oc_log_stream.hpp
resource/oc_logger/include/oc_logger.h
resource/oc_logger/include/oc_logger.hpp
resource/oc_logger/include/oc_logger_types.h
resource/oc_logger/include/targets/oc_console_logger.h
resource/oc_logger/include/targets/oc_ostream_logger.h
resource/oc_logger/samples/linux/README [deleted file]
resource/oc_logger/samples/linux/test_logging.c [deleted file]
resource/provisioning/SConscript
resource/provisioning/examples/README-Provisioning-Tool-CPP.txt [new file with mode: 0644]
resource/provisioning/examples/SConscript
resource/provisioning/examples/oic_svr_db_client.dat [new file with mode: 0644]
resource/provisioning/examples/oic_svr_db_client.json
resource/provisioning/examples/provisioningclient.cpp
resource/provisioning/src/OCProvisioningManager.cpp
resource/provisioning/unittests/OCProvisioningTest.cpp
resource/provisioning/unittests/SConscript [changed mode: 0644->0755]
resource/src/CAManager.cpp [new file with mode: 0644]
resource/src/InProcClientWrapper.cpp
resource/src/OCException.cpp
resource/src/OCRepresentation.cpp
resource/src/OCResource.cpp
resource/src/OCUtilities.cpp
resource/src/SConscript
resource/unit_tests.scons
resource/unittests/OCExceptionTest.cpp
resource/unittests/OCPlatformTest.cpp
resource/unittests/OCRepresentationEncodingTest.cpp
resource/unittests/OCResourceTest.cpp
resource/unittests/SConscript
scons_script_how_to.txt
service/SConscript [changed mode: 0644->0755]
service/easy-setup/Build_Instructions_Android_Arduino.txt [changed mode: 0755->0644]
service/easy-setup/SConscript [changed mode: 0644->0755]
service/easy-setup/enrollee/SConscript [new file with mode: 0644]
service/easy-setup/enrollee/arduino/easysetup.cpp [new file with mode: 0644]
service/easy-setup/enrollee/arduino/onboarding.cpp [new file with mode: 0644]
service/easy-setup/enrollee/arduino/resourcehandler.cpp [new file with mode: 0644]
service/easy-setup/enrollee/arduino/softap.cpp [new file with mode: 0644]
service/easy-setup/enrollee/arduino/wifi/networkhandler.cpp [new file with mode: 0644]
service/easy-setup/enrollee/arduino/wifi/networkhandler.h [new file with mode: 0644]
service/easy-setup/enrollee/inc/easysetup.h [new file with mode: 0755]
service/easy-setup/enrollee/linux/wifi/networkhandler.c [new file with mode: 0644]
service/easy-setup/enrollee/linux/wifi/networkhandler.h [new file with mode: 0644]
service/easy-setup/enrollee/linux/wifi/softapnative.c [new file with mode: 0644]
service/easy-setup/enrollee/linux/wifi/softapnative.h [new file with mode: 0644]
service/easy-setup/enrollee/src/easysetup.c [new file with mode: 0644]
service/easy-setup/enrollee/src/easysetupcallbacks.h [new file with mode: 0644]
service/easy-setup/enrollee/src/onboarding.c [new file with mode: 0644]
service/easy-setup/enrollee/src/onboarding.h [new file with mode: 0644]
service/easy-setup/enrollee/src/resourcehandler.c [new file with mode: 0644]
service/easy-setup/enrollee/src/resourcehandler.h [new file with mode: 0644]
service/easy-setup/enrollee/src/softap.c [new file with mode: 0644]
service/easy-setup/enrollee/src/softap.h [new file with mode: 0644]
service/easy-setup/enrollee/tizen/wifi/networkhandler.c [new file with mode: 0644]
service/easy-setup/enrollee/tizen/wifi/networkhandler.h [new file with mode: 0644]
service/easy-setup/enrollee/tizen/wifi/softapnative.c [new file with mode: 0644]
service/easy-setup/enrollee/tizen/wifi/softapnative.h [new file with mode: 0644]
service/easy-setup/enrollee/unittests/SConscript [new file with mode: 0644]
service/easy-setup/enrollee/unittests/enrolleetests.cpp [new file with mode: 0644]
service/easy-setup/enrollee/unittests/gtesthelper.h [new file with mode: 0644]
service/easy-setup/inc/escommon.h [new file with mode: 0755]
service/easy-setup/mediator/SConscript [new file with mode: 0644]
service/easy-setup/mediator/csdk/SConscript [new file with mode: 0644]
service/easy-setup/mediator/csdk/inc/provisioning.h [new file with mode: 0755]
service/easy-setup/mediator/csdk/inc/provisioningapi.h [new file with mode: 0755]
service/easy-setup/mediator/csdk/src/provisioning.cpp [new file with mode: 0755]
service/easy-setup/mediator/csdk/src/provisioningapi.cpp [new file with mode: 0755]
service/easy-setup/mediator/csdk/src/wifiprovisioning.cpp [new file with mode: 0755]
service/easy-setup/mediator/csdk/unittests/MediatorCSDKTest.cpp [new file with mode: 0644]
service/easy-setup/mediator/csdk/unittests/SConscript [new file with mode: 0644]
service/easy-setup/mediator/csdk/unittests/UnitTestHelper.h [new file with mode: 0644]
service/easy-setup/mediator/richsdk/SConscript [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/EasySetupCore/build.gradle [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/androidTest/androidTest.iml [moved from service/easy-setup/sdk/mediator/android/EasySetupCore/src/androidTest/androidTest.iml with 100% similarity]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/EasySetupServiceConfigTest.java [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/EasySetupServiceTest.java [new file with mode: 0755]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/EasySetupStatusTest.java [new file with mode: 0755]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/EnrolleeDeviceFactoryTest.java [new file with mode: 0755]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/Utility.java [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/AndroidManifest.xml [moved from service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/AndroidManifest.xml with 100% similarity]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/core/EnrolleeInfo.java [moved from service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/core/EnrolleeInfo.java with 100% similarity, mode: 0644]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/core/EnrolleeOnBoardingInfo.java [moved from service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/core/EnrolleeOnBoardingInfo.java with 100% similarity, mode: 0644]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/core/IOnBoardingStatus.java [moved from service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/core/IOnBoardingStatus.java with 100% similarity, mode: 0644]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/core/ip/WiFiSoftAPManager.java [moved from service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/core/ip/WiFiSoftAPManager.java with 100% similarity, mode: 0644]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ESException.java [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EasySetupService.java [new file with mode: 0755]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EasySetupStatus.java [moved from service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EasySetupStatus.java with 100% similarity, mode: 0644]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeDevice.java [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeDeviceFactory.java [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeDeviceWiFiOnboarding.java [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeSetupError.java [moved from service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeSetupError.java with 100% similarity, mode: 0644]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeState.java [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/IProvisionStatusNativeHandler.java [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/IpOnBoardingConnection.java [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/OnBoardingCallback.java [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/OnBoardingConfig.java [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/OnBoardingConnection.java [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ProvisioningCallback.java [moved from service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ProvisioningCallback.java with 100% similarity, mode: 0644]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ProvisioningConfig.java [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/RemoteEnrollee.java [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/WiFiOnBoardingConfig.java [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/WiFiProvConfig.java [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/main.iml [moved from service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/main.iml with 100% similarity]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/res/drawable-hdpi/ic_launcher.png [moved from service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/res/drawable-hdpi/ic_launcher.png with 100% similarity]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/res/values/strings.xml [moved from service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/res/values/strings.xml with 100% similarity]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/res/values/styles.xml [moved from service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/res/values/styles.xml with 100% similarity]
service/easy-setup/mediator/richsdk/android/jni/Android.mk [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/jni/Application.mk [moved from service/easy-setup/sdk/mediator/android/jni/Application.mk with 100% similarity]
service/easy-setup/mediator/richsdk/android/jni/JniEasySetup.cpp [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/jni/JniEasySetup.h [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/jni/JniEsListenerManager.h [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/jni/JniEsUtils.cpp [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/jni/JniEsUtils.h [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/jni/JniJvm.cpp [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/jni/JniJvm.h [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/jni/JniProvisioningStatusLisener.cpp [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/jni/JniProvisioningStatusListener.h [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/jni/JniRemoteEnrollee.cpp [new file with mode: 0644]
service/easy-setup/mediator/richsdk/android/jni/JniRemoteEnrollee.h [new file with mode: 0644]
service/easy-setup/mediator/richsdk/inc/ESException.h [new file with mode: 0644]
service/easy-setup/mediator/richsdk/inc/ESRichCommon.h [new file with mode: 0755]
service/easy-setup/mediator/richsdk/inc/EasySetup.h [new file with mode: 0644]
service/easy-setup/mediator/richsdk/inc/EnrolleeSecurity.h [new file with mode: 0755]
service/easy-setup/mediator/richsdk/inc/RemoteEnrollee.h [new file with mode: 0644]
service/easy-setup/mediator/richsdk/inc/RemoteEnrolleeResource.h [new file with mode: 0755]
service/easy-setup/mediator/richsdk/src/ESException.cpp [new file with mode: 0644]
service/easy-setup/mediator/richsdk/src/EasySetup.cpp [new file with mode: 0644]
service/easy-setup/mediator/richsdk/src/EnrolleeSecurity.cpp [new file with mode: 0755]
service/easy-setup/mediator/richsdk/src/RemoteEnrollee.cpp [new file with mode: 0755]
service/easy-setup/mediator/richsdk/src/RemoteEnrolleeResource.cpp [new file with mode: 0755]
service/easy-setup/mediator/richsdk/unittests/MediatorRichTest.cpp [new file with mode: 0644]
service/easy-setup/mediator/richsdk/unittests/SConscript [new file with mode: 0644]
service/easy-setup/mediator/richsdk/unittests/UnitTestHelper.h [new file with mode: 0644]
service/easy-setup/sampleapp/SConscript [deleted file]
service/easy-setup/sampleapp/enrollee/arduino/SConscript [changed mode: 0644->0755]
service/easy-setup/sampleapp/enrollee/arduino/enrollee_wifi.cpp [deleted file]
service/easy-setup/sampleapp/enrollee/arduino/enrolleewifi.cpp [new file with mode: 0644]
service/easy-setup/sampleapp/enrollee/linux/SConscript [new file with mode: 0644]
service/easy-setup/sampleapp/enrollee/linux/enrolleewifi.c [new file with mode: 0644]
service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/SConscript [new file with mode: 0644]
service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/SConstruct [moved from resource/csdk/connectivity/samples/tizen/SConstruct with 100% similarity]
service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/SConscript [new file with mode: 0644]
service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/tizen/Makefile [new file with mode: 0644]
service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/tizen/SConscript [new file with mode: 0644]
service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/tizen/SConstruct [new file with mode: 0644]
service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/tizen/gbsbuild.sh [new file with mode: 0644]
service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/com.oic.es.sample.manifest [new file with mode: 0644]
service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/com.oic.es.sample.xml [new file with mode: 0644]
service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/enrolleewifi.cpp [new file with mode: 0755]
service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/packaging/com.oic.es.sample.spec [new file with mode: 0644]
service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/scons/SConscript [new file with mode: 0644]
service/easy-setup/sampleapp/enrollee/tizen-sdb/README.txt [new file with mode: 0644]
service/easy-setup/sampleapp/mediator/android/EasySetup/app/build.gradle
service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/AndroidManifest.xml [changed mode: 0644->0755]
service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/assets/oic_svr_db_client.dat [new file with mode: 0644]
service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/assets/oic_svr_db_client.json [new file with mode: 0644]
service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/java/org/iotivity/service/easysetup/MainActivity.java
service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/res/layout/activity_main.xml [changed mode: 0644->0755]
service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/res/menu/main.xml [changed mode: 0644->0755]
service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/res/values/strings.xml
service/easy-setup/sampleapp/mediator/linux/SConscript [deleted file]
service/easy-setup/sampleapp/mediator/linux/csdk_sample/SConscript [new file with mode: 0644]
service/easy-setup/sampleapp/mediator/linux/csdk_sample/mediator.cpp [new file with mode: 0755]
service/easy-setup/sampleapp/mediator/linux/mediator.cpp [deleted file]
service/easy-setup/sampleapp/mediator/linux/richsdk_sample/SConscript [new file with mode: 0644]
service/easy-setup/sampleapp/mediator/linux/richsdk_sample/mediator_cpp.cpp [new file with mode: 0755]
service/easy-setup/sdk/common/escommon.h [deleted file]
service/easy-setup/sdk/enrollee/api/easysetup.h [deleted file]
service/easy-setup/sdk/enrollee/arduino/wifi/networkHandler.cpp [deleted file]
service/easy-setup/sdk/enrollee/arduino/wifi/networkHandler.h [deleted file]
service/easy-setup/sdk/enrollee/inc/resourceHandler.h [deleted file]
service/easy-setup/sdk/enrollee/src/easysetup.cpp [deleted file]
service/easy-setup/sdk/enrollee/src/resourceHandler.cpp [deleted file]
service/easy-setup/sdk/mediator/android/.gitignore [deleted file]
service/easy-setup/sdk/mediator/android/EasySetupCore/build.gradle [deleted file]
service/easy-setup/sdk/mediator/android/EasySetupCore/settings.gradle [deleted file]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/EasySetupServiceConfigTest.java [deleted file]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/EasySetupServiceTest.java [deleted file]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/EasySetupStatusTest.java [deleted file]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/EnrolleeDeviceFactoryTest.java [deleted file]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/Utility.java [deleted file]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/core/EasySetupCallbackHandler.java [deleted file]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/core/EasySetupManager.java [deleted file]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/core/IProvisioningListener.java [deleted file]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/core/ProvisionEnrollee.java [deleted file]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EasySetupService.java [deleted file]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeDevice.java [deleted file]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeDeviceFactory.java [deleted file]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeDeviceWiFiOnboarding.java [deleted file]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeState.java [deleted file]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/IpOnBoardingConnection.java [deleted file]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/OnBoardingCallback.java [deleted file]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/OnBoardingConfig.java [deleted file]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/OnBoardingConnection.java [deleted file]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ProvisioningConfig.java [deleted file]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/WiFiOnBoardingConfig.java [deleted file]
service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/WiFiProvConfig.java [deleted file]
service/easy-setup/sdk/mediator/android/jni/Android.mk [deleted file]
service/easy-setup/sdk/mediator/android/jni/jni_easy_setup.cpp [deleted file]
service/easy-setup/sdk/mediator/android/jni/jni_easy_setup.h [deleted file]
service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_easy_setup_jvm.h [deleted file]
service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_getter.h [deleted file]
service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_object.h [deleted file]
service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_setter.h [deleted file]
service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_string.h [deleted file]
service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_easy_setup_jvm.cpp [deleted file]
service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_getter.cpp [deleted file]
service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_object.cpp [deleted file]
service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_setter.cpp [deleted file]
service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_string.cpp [deleted file]
service/easy-setup/sdk/mediator/inc/prov_adapter.h [deleted file]
service/easy-setup/sdk/mediator/inc/provisioning.h [deleted file]
service/easy-setup/sdk/mediator/src/prov_adapter.cpp [deleted file]
service/easy-setup/sdk/mediator/src/provisioning.cpp [deleted file]
service/easy-setup/sdk/mediator/src/wifi_provisioning.cpp [deleted file]
service/resource-container/SConscript
service/resource-container/android/.gitignore
service/resource-container/android/SConscript
service/resource-container/android/resource-container/build.gradle
service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/BundleActivator.java [new file with mode: 0644]
service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/BundleResource.java [new file with mode: 0644]
service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/BundleSoftSensorResource.java [new file with mode: 0644]
service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/RcsBundleInfo.java
service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/RcsResourceAttributes.java [new file with mode: 0644]
service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/RcsResourceContainer.java
service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/RcsResourceContainerBundleAPI.java [new file with mode: 0644]
service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/RcsValue.java [new file with mode: 0644]
service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/ResourceConfig.java [new file with mode: 0644]
service/resource-container/android/resource-container/src/main/java/org/iotivity/service/utils/RcsException.java [deleted file]
service/resource-container/android/resource-container/src/main/java/org/iotivity/service/utils/RcsIllegalStateException.java [deleted file]
service/resource-container/android/resource-container/src/main/java/org/iotivity/service/utils/RcsObject.java [deleted file]
service/resource-container/android/resource-container/src/main/java/org/iotivity/service/utils/RcsPlatformException.java [deleted file]
service/resource-container/android/resource-container/src/main/jni/Android.mk
service/resource-container/android/resource-container/src/main/jni/JniBundleResource.cpp [new file with mode: 0644]
service/resource-container/android/resource-container/src/main/jni/JniBundleResource.h [new file with mode: 0644]
service/resource-container/android/resource-container/src/main/jni/JniMain.cpp
service/resource-container/android/resource-container/src/main/jni/JniRcsBundleInfo.cpp [deleted file]
service/resource-container/android/resource-container/src/main/jni/JniRcsBundleInfo.h [deleted file]
service/resource-container/android/resource-container/src/main/jni/JniRcsObject.cpp [deleted file]
service/resource-container/android/resource-container/src/main/jni/JniRcsObject.h [deleted file]
service/resource-container/android/resource-container/src/main/jni/JniRcsResourceAttributes.cpp [new file with mode: 0644]
service/resource-container/android/resource-container/src/main/jni/JniRcsResourceAttributes.h [new file with mode: 0644]
service/resource-container/android/resource-container/src/main/jni/JniRcsResourceContainer.cpp
service/resource-container/android/resource-container/src/main/jni/JniRcsResourceContainer.h
service/resource-container/android/resource-container/src/main/jni/JniRcsValue.cpp [new file with mode: 0644]
service/resource-container/android/resource-container/src/main/jni/JniRcsValue.h [new file with mode: 0644]
service/resource-container/android/resource-container/src/main/jni/util/JavaClasses.cpp
service/resource-container/android/resource-container/src/main/jni/util/JavaClasses.h
service/resource-container/android/resource-container/src/main/jni/util/JavaExceptions.cpp
service/resource-container/android/resource-container/src/main/jni/util/JavaExceptions.h
service/resource-container/android/resource-container/src/main/jni/util/JavaGlobalRef.h [deleted file]
service/resource-container/android/resource-container/src/main/jni/util/JavaLocalRef.h
service/resource-container/android/resource-container/src/main/jni/util/ScopedEnv.h
service/resource-container/bundle-api/include/BundleActivator.h
service/resource-container/bundle-api/include/BundleResource.h
service/resource-container/bundle-api/include/ProtocolBridgeConnector.h
service/resource-container/bundle-api/include/ProtocolBridgeResource.h
service/resource-container/bundle-api/include/ResourceContainerBundleAPI.h
service/resource-container/bundle-api/include/SoftSensorResource.h
service/resource-container/bundle-java-api/src/main/java/org/iotivity/resourcecontainer/bundle/api/BaseActivator.java
service/resource-container/bundle-java-api/src/main/java/org/iotivity/resourcecontainer/bundle/api/BundleActivator.java
service/resource-container/examples/BMISensorBundle/include/BMISensorResource.h
service/resource-container/examples/BMISensorBundle/src/BMISensorResource.cpp
service/resource-container/examples/ContainerSample.cpp
service/resource-container/examples/ContainerSampleClient.cpp
service/resource-container/examples/DiscomfortIndexSensorBundle/include/DiscomfortIndexSensorResource.h
service/resource-container/examples/DiscomfortIndexSensorBundle/src/DiscomfortIndexSensorResource.cpp
service/resource-container/examples/HueSampleBundle/include/HueLight.h
service/resource-container/examples/HueSampleBundle/src/HueLight.cpp
service/resource-container/examples/HueSampleBundle/src/HueSampleBundleActivator.cpp
service/resource-container/examples/ResourceContainerConfig.xml
service/resource-container/examples/android/AndroidBundle/AndroidBundle.iml [new file with mode: 0755]
service/resource-container/examples/android/AndroidBundle/app/app.iml [new file with mode: 0755]
service/resource-container/examples/android/AndroidBundle/app/build.gradle [new file with mode: 0755]
service/resource-container/examples/android/AndroidBundle/app/src/androidTest/java/org/iotivity/service/sample/androidbundle/ApplicationTest.java [new file with mode: 0755]
service/resource-container/examples/android/AndroidBundle/app/src/main/AndroidManifest.xml [new file with mode: 0755]
service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/DummyActivity.java [new file with mode: 0755]
service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/SampleActivator.java [new file with mode: 0755]
service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/resources/DiscomfortIndexResource.java [new file with mode: 0755]
service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/resources/GyroscopeResource.java [new file with mode: 0755]
service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/resources/HumidityResource.java [new file with mode: 0755]
service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/resources/LightIntensityResource.java [new file with mode: 0755]
service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/resources/TemperatureResource.java [new file with mode: 0755]
service/resource-container/examples/android/AndroidBundle/app/src/main/res/layout/activity_main.xml [new file with mode: 0755]
service/resource-container/examples/android/AndroidBundle/app/src/main/res/menu/menu_main.xml [new file with mode: 0755]
service/resource-container/examples/android/AndroidBundle/app/src/main/res/mipmap-hdpi/ic_launcher.png [new file with mode: 0755]
service/resource-container/examples/android/AndroidBundle/app/src/main/res/mipmap-mdpi/ic_launcher.png [new file with mode: 0755]
service/resource-container/examples/android/AndroidBundle/app/src/main/res/mipmap-xhdpi/ic_launcher.png [new file with mode: 0755]
service/resource-container/examples/android/AndroidBundle/app/src/main/res/mipmap-xxhdpi/ic_launcher.png [new file with mode: 0755]
service/resource-container/examples/android/AndroidBundle/app/src/main/res/values-v21/styles.xml [new file with mode: 0755]
service/resource-container/examples/android/AndroidBundle/app/src/main/res/values-w820dp/dimens.xml [new file with mode: 0755]
service/resource-container/examples/android/AndroidBundle/app/src/main/res/values/dimens.xml [new file with mode: 0755]
service/resource-container/examples/android/AndroidBundle/app/src/main/res/values/strings.xml [new file with mode: 0755]
service/resource-container/examples/android/AndroidBundle/app/src/main/res/values/styles.xml [new file with mode: 0755]
service/resource-container/examples/android/AndroidBundle/build.gradle [new file with mode: 0755]
service/resource-container/examples/android/AndroidBundle/gradle/wrapper/gradle-wrapper.jar [moved from resource/csdk/connectivity/samples/android/casample/gradle/wrapper/gradle-wrapper.jar with 100% similarity]
service/resource-container/examples/android/AndroidBundle/gradle/wrapper/gradle-wrapper.properties [new file with mode: 0755]
service/resource-container/examples/android/AndroidBundle/gradlew [moved from resource/csdk/connectivity/samples/android/casample/gradlew with 100% similarity]
service/resource-container/examples/android/AndroidBundle/gradlew.bat [moved from resource/csdk/connectivity/samples/android/casample/gradlew.bat with 100% similarity]
service/resource-container/examples/android/AndroidBundle/settings.gradle [new file with mode: 0755]
service/resource-container/examples/android/RCSampleClientApp/.gitignore [deleted file]
service/resource-container/examples/android/RCSampleClientApp/RCSampleClientApp.iml [deleted file]
service/resource-container/examples/android/RCSampleClientApp/app/.gitignore [deleted file]
service/resource-container/examples/android/RCSampleClientApp/app/build.gradle
service/resource-container/examples/android/RCSampleClientApp/app/src/main/java/org/iotivity/service/sample/client/ContainerClientActivity.java
service/resource-container/examples/android/RCSampleClientApp/app/src/main/java/org/iotivity/service/sample/client/ResourceListAdapter.java [new file with mode: 0644]
service/resource-container/examples/android/RCSampleClientApp/app/src/main/java/org/iotivity/service/sample/client/ResourceListItem.java [new file with mode: 0644]
service/resource-container/examples/android/RCSampleClientApp/app/src/main/java/org/iotivity/service/sample/client/Utils.java
service/resource-container/examples/android/RCSampleClientApp/app/src/main/res/layout/activity_container_client.xml
service/resource-container/examples/android/RCSampleClientApp/app/src/main/res/layout/discovered_resource.xml [new file with mode: 0644]
service/resource-container/examples/android/RCSampleServerApp/.gitignore [deleted file]
service/resource-container/examples/android/RCSampleServerApp/RCSampleServerApp.iml [changed mode: 0644->0755]
service/resource-container/examples/android/RCSampleServerApp/README [changed mode: 0644->0755]
service/resource-container/examples/android/RCSampleServerApp/app/.gitignore [deleted file]
service/resource-container/examples/android/RCSampleServerApp/app/app.iml [changed mode: 0644->0755]
service/resource-container/examples/android/RCSampleServerApp/app/build.gradle [changed mode: 0644->0755]
service/resource-container/examples/android/RCSampleServerApp/app/src/androidTest/assets/lib/ResourceContainerConfig.xml [new file with mode: 0755]
service/resource-container/examples/android/RCSampleServerApp/app/src/androidTest/java/org/iotivity/service/sample/container/ResourceContainerTest.java [new file with mode: 0755]
service/resource-container/examples/android/RCSampleServerApp/app/src/main/AndroidManifest.xml [changed mode: 0644->0755]
service/resource-container/examples/android/RCSampleServerApp/app/src/main/assets/lib/ResourceContainerConfig.xml [changed mode: 0644->0755]
service/resource-container/examples/android/RCSampleServerApp/app/src/main/java/org/iotivity/service/sample/container/ResourceContainer.java [changed mode: 0644->0755]
service/resource-container/examples/android/RCSampleServerApp/app/src/main/java/org/iotivity/service/sample/container/ResourceContainerActivity.java [changed mode: 0644->0755]
service/resource-container/examples/android/RCSampleServerApp/app/src/main/res/layout/group.xml [changed mode: 0644->0755]
service/resource-container/examples/android/RCSampleServerApp/app/src/main/res/layout/list_item.xml [changed mode: 0644->0755]
service/resource-container/examples/android/RCSampleServerApp/app/src/main/res/layout/resource_container.xml [changed mode: 0644->0755]
service/resource-container/examples/android/RCSampleServerApp/app/src/main/res/mipmap-hdpi/ic_launcher.png [changed mode: 0644->0755]
service/resource-container/examples/android/RCSampleServerApp/app/src/main/res/mipmap-mdpi/ic_launcher.png [changed mode: 0644->0755]
service/resource-container/examples/android/RCSampleServerApp/app/src/main/res/mipmap-xhdpi/ic_launcher.png [changed mode: 0644->0755]
service/resource-container/examples/android/RCSampleServerApp/app/src/main/res/mipmap-xxhdpi/ic_launcher.png [changed mode: 0644->0755]
service/resource-container/examples/android/RCSampleServerApp/app/src/main/res/values-v21/styles.xml [changed mode: 0644->0755]
service/resource-container/examples/android/RCSampleServerApp/app/src/main/res/values/strings.xml [changed mode: 0644->0755]
service/resource-container/examples/android/RCSampleServerApp/app/src/main/res/values/styles.xml [changed mode: 0644->0755]
service/resource-container/examples/android/RCSampleServerApp/build.gradle [changed mode: 0644->0755]
service/resource-container/examples/android/RCSampleServerApp/gradlew [new file with mode: 0755]
service/resource-container/examples/android/RCSampleServerApp/gradlew.bat [new file with mode: 0755]
service/resource-container/examples/android/RCSampleServerApp/settings.gradle [changed mode: 0644->0755]
service/resource-container/examples/tizen/ContainerServerApp/lib/ResourceContainerConfig.xml
service/resource-container/examples/tizen/ContainerServerApp/src/container.cpp
service/resource-container/include/RCSBundleInfo.h
service/resource-container/src/AndroidBundleResource.h [new file with mode: 0644]
service/resource-container/src/BaseActivator.cpp
service/resource-container/src/BundleActivator.cpp [deleted file]
service/resource-container/src/BundleInfoInternal.cpp
service/resource-container/src/BundleInfoInternal.h
service/resource-container/src/BundleResource.cpp
service/resource-container/src/Configuration.cpp
service/resource-container/src/Configuration.h
service/resource-container/src/DiscoverResourceUnit.cpp
service/resource-container/src/DiscoverResourceUnit.h
service/resource-container/src/InternalTypes.h
service/resource-container/src/JavaBundleResource.cpp
service/resource-container/src/JavaBundleResource.h
service/resource-container/src/ProtocolBridgeConnector.cpp [deleted file]
service/resource-container/src/ProtocolBridgeResource.cpp [deleted file]
service/resource-container/src/RCSBundleInfo.cpp [deleted file]
service/resource-container/src/RemoteResourceUnit.cpp
service/resource-container/src/ResourceContainerImpl.cpp
service/resource-container/src/ResourceContainerImpl.h
service/resource-container/unittests/ResourceContainerTest.cpp
service/resource-container/unittests/ResourceContainerTestSimulator.h
service/resource-container/unittests/TestBundle/include/TestBundleActivator.h
service/resource-directory/SConscript
service/resource-directory/include/rd_client.h
service/resource-directory/include/rd_server.h
service/resource-directory/samples/rd_publishingClient.cpp
service/resource-directory/src/internal/rd_storage.c
service/resource-directory/src/internal/rd_storage.h
service/resource-directory/src/rd_client.c
service/resource-directory/src/rd_server.c
service/resource-encapsulation/SConscript
service/resource-encapsulation/android/service/src/main/java/org/iotivity/service/server/RcsResourceObject.java
service/resource-encapsulation/android/service/src/main/jni/Android.mk
service/resource-encapsulation/android/service/src/main/jni/JniRcsLockedAttributes.cpp
service/resource-encapsulation/android/service/src/main/jni/JniRcsResourceObject.cpp
service/resource-encapsulation/examples/android/RESampleClientApp/app/build.gradle
service/resource-encapsulation/examples/android/RESampleClientApp/app/src/main/java/org/iotivity/service/sample/client/ResourceClientActivity.java
service/resource-encapsulation/examples/android/RESampleServerApp/app/build.gradle
service/resource-encapsulation/examples/linux/NestedAttributeClient.cpp [deleted file]
service/resource-encapsulation/examples/linux/NestedAttributeServer.cpp [deleted file]
service/resource-encapsulation/examples/linux/NestedAttributesClient.cpp [new file with mode: 0644]
service/resource-encapsulation/examples/linux/NestedAttributesServer.cpp [new file with mode: 0644]
service/resource-encapsulation/examples/linux/SConscript
service/resource-encapsulation/examples/linux/SampleResourceClient.cpp
service/resource-encapsulation/examples/linux/SampleResourceServer.cpp [changed mode: 0644->0755]
service/resource-encapsulation/examples/linux/SeparateResponseServer.cpp [new file with mode: 0755]
service/resource-encapsulation/examples/linux/secureResourceExample/README [new file with mode: 0644]
service/resource-encapsulation/examples/linux/secureResourceExample/SConscript [new file with mode: 0644]
service/resource-encapsulation/examples/linux/secureResourceExample/SampleAuthorizedClient.cpp [new file with mode: 0644]
service/resource-encapsulation/examples/linux/secureResourceExample/SampleSecureServer.cpp [new file with mode: 0644]
service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_client.dat [new file with mode: 0644]
service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_client.json [new file with mode: 0644]
service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_server.dat [new file with mode: 0644]
service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_server.json [new file with mode: 0644]
service/resource-encapsulation/examples/tizen/NestedAttributeClientApp/edc_resource/re_container_control.edc
service/resource-encapsulation/examples/tizen/NestedAttributeClientApp/src/recontainerclient.cpp
service/resource-encapsulation/examples/tizen/RESampleClientApp/.cproject
service/resource-encapsulation/examples/tizen/RESampleClientApp/src/reclient.cpp
service/resource-encapsulation/include/RCSDiscoveryManager.h
service/resource-encapsulation/include/RCSException.h
service/resource-encapsulation/include/RCSRemoteResourceObject.h
service/resource-encapsulation/include/RCSRepresentation.h [new file with mode: 0644]
service/resource-encapsulation/include/RCSRequest.h
service/resource-encapsulation/include/RCSResourceAttributes.h
service/resource-encapsulation/include/RCSResourceObject.h
service/resource-encapsulation/include/RCSResponse.h
service/resource-encapsulation/include/RCSSeparateResponse.h [new file with mode: 0755]
service/resource-encapsulation/src/common/SConscript
service/resource-encapsulation/src/common/primitiveResource/include/AssertUtils.h
service/resource-encapsulation/src/common/primitiveResource/include/PrimitiveResource.h
service/resource-encapsulation/src/common/primitiveResource/include/PrimitiveResourceImpl.h
service/resource-encapsulation/src/common/primitiveResource/include/RCSAddressDetail.h
service/resource-encapsulation/src/common/primitiveResource/include/ResponseStatement.h
service/resource-encapsulation/src/common/primitiveResource/src/PrimitiveResource.cpp
service/resource-encapsulation/src/common/primitiveResource/src/RCSAddress.cpp
service/resource-encapsulation/src/common/primitiveResource/src/RCSRepresentation.cpp [new file with mode: 0644]
service/resource-encapsulation/src/common/primitiveResource/src/RCSResourceAttributes.cpp
service/resource-encapsulation/src/common/primitiveResource/src/ResponseStatement.cpp [deleted file]
service/resource-encapsulation/src/common/primitiveResource/unittests/PrimitiveResourceTest.cpp
service/resource-encapsulation/src/common/utils/include/ScopeLogger.h
service/resource-encapsulation/src/resourceBroker/include/DevicePresence.h
service/resource-encapsulation/src/resourceBroker/src/DeviceAssociation.cpp
service/resource-encapsulation/src/resourceBroker/src/DevicePresence.cpp
service/resource-encapsulation/src/resourceBroker/src/ResourceBroker.cpp
service/resource-encapsulation/src/resourceBroker/src/ResourcePresence.cpp
service/resource-encapsulation/src/resourceCache/include/DataCache.h
service/resource-encapsulation/src/resourceCache/src/DataCache.cpp
service/resource-encapsulation/src/resourceCache/unittests/DataCacheTest.cpp
service/resource-encapsulation/src/resourceCache/unittests/ResourceCacheTest.cpp
service/resource-encapsulation/src/resourceClient/RCSDiscoveryManager.cpp [changed mode: 0755->0644]
service/resource-encapsulation/src/resourceClient/RCSDiscoveryManagerImpl.cpp
service/resource-encapsulation/src/resourceClient/RCSDiscoveryManagerImpl.h [changed mode: 0644->0755]
service/resource-encapsulation/src/resourceClient/RCSRemoteResourceObject.cpp
service/resource-encapsulation/src/serverBuilder/include/InterfaceHandler.h [new file with mode: 0644]
service/resource-encapsulation/src/serverBuilder/include/RequestHandler.h
service/resource-encapsulation/src/serverBuilder/src/InterfaceHandler.cpp [new file with mode: 0644]
service/resource-encapsulation/src/serverBuilder/src/RCSRequest.cpp
service/resource-encapsulation/src/serverBuilder/src/RCSResourceObject.cpp
service/resource-encapsulation/src/serverBuilder/src/RCSResponse.cpp
service/resource-encapsulation/src/serverBuilder/src/RCSSeparateResponse.cpp [new file with mode: 0755]
service/resource-encapsulation/src/serverBuilder/src/RequestHandler.cpp
service/resource-encapsulation/src/serverBuilder/unittests/RCSResourceObjectTest.cpp
service/resource-encapsulation/src/serverBuilder/unittests/RCSResponseTest.cpp
service/resource-encapsulation/src/serverBuilder/unittests/RequestHandlerTest.cpp
service/resource-encapsulation/unittests/DiscoveryManagerTest.cpp [changed mode: 0644->0755]
service/resource-encapsulation/unittests/ResourceClientTest.cpp
service/resource-hosting/SConscript
service/resource-hosting/SampleApp/linux/sampleConsumer/SampleConsumer.cpp
service/resource-hosting/SampleApp/linux/sampleProvider/SampleProvider.cpp
service/resource-hosting/SampleApp/tizen/RHSampleApp/.cproject
service/resource-hosting/android/resource_hosting/jni/ResourceHosing_JNI.cpp
service/resource-hosting/src/Hosting.cpp
service/resource-hosting/src/HostingObject.cpp
service/resource-hosting/src/HostingObject.h [changed mode: 0644->0755]
service/resource-hosting/src/RequestObject.cpp
service/resource-hosting/src/RequestObject.h
service/resource-hosting/src/ResourceHosting.cpp [changed mode: 0644->0755]
service/resource-hosting/src/ResourceHosting.h [changed mode: 0644->0755]
service/resource-hosting/src/unittest/HostingObjectUnitTest.cpp [deleted file]
service/resource-hosting/src/unittest/RequestObjectUnitTest.cpp [deleted file]
service/resource-hosting/src/unittest/ResourceEncapsulationTestSimulator.h [deleted file]
service/resource-hosting/src/unittest/ResourceHostingUnitTest.cpp [deleted file]
service/resource-hosting/src/unittest/SConscript [deleted file]
service/resource-hosting/unittest/HostingObjectUnitTest.cpp [new file with mode: 0755]
service/resource-hosting/unittest/RequestObjectUnitTest.cpp [new file with mode: 0755]
service/resource-hosting/unittest/ResourceEncapsulationTestSimulator.h [new file with mode: 0755]
service/resource-hosting/unittest/ResourceHostingUnitTest.cpp [new file with mode: 0755]
service/resource-hosting/unittest/SConscript [new file with mode: 0644]
service/scene-manager/README.txt [new file with mode: 0755]
service/scene-manager/SConscript [new file with mode: 0755]
service/scene-manager/include/RemoteScene.h [new file with mode: 0644]
service/scene-manager/include/RemoteSceneAction.h [new file with mode: 0644]
service/scene-manager/include/RemoteSceneCollection.h [new file with mode: 0644]
service/scene-manager/include/RemoteSceneList.h [new file with mode: 0644]
service/scene-manager/include/Scene.h [new file with mode: 0755]
service/scene-manager/include/SceneAction.h [new file with mode: 0755]
service/scene-manager/include/SceneCollection.h [new file with mode: 0755]
service/scene-manager/include/SceneList.h [new file with mode: 0755]
service/scene-manager/sampleapp/SConscript [new file with mode: 0755]
service/scene-manager/sampleapp/linux/SConscript [new file with mode: 0755]
service/scene-manager/sampleapp/linux/fanserver.cpp [new file with mode: 0755]
service/scene-manager/sampleapp/linux/lightserver.cpp [moved from service/things-manager/sampleapp/linux/groupaction/lightserver.cpp with 100% similarity]
service/scene-manager/sampleapp/linux/sceneclient.cpp [new file with mode: 0755]
service/scene-manager/sampleapp/linux/sceneserver.cpp [new file with mode: 0755]
service/scene-manager/src/RemoteScene.cpp [new file with mode: 0644]
service/scene-manager/src/RemoteSceneAction.cpp [new file with mode: 0644]
service/scene-manager/src/RemoteSceneCollection.cpp [new file with mode: 0644]
service/scene-manager/src/RemoteSceneList.cpp [new file with mode: 0644]
service/scene-manager/src/RemoteSceneUtils.h [new file with mode: 0644]
service/scene-manager/src/Scene.cpp [new file with mode: 0755]
service/scene-manager/src/SceneAction.cpp [new file with mode: 0755]
service/scene-manager/src/SceneCollection.cpp [new file with mode: 0755]
service/scene-manager/src/SceneCollectionResource.cpp [new file with mode: 0755]
service/scene-manager/src/SceneCollectionResource.h [new file with mode: 0644]
service/scene-manager/src/SceneCollectionResourceRequestor.cpp [new file with mode: 0644]
service/scene-manager/src/SceneCollectionResourceRequestor.h [new file with mode: 0644]
service/scene-manager/src/SceneCommons.h [new file with mode: 0644]
service/scene-manager/src/SceneList.cpp [new file with mode: 0755]
service/scene-manager/src/SceneListResource.cpp [new file with mode: 0644]
service/scene-manager/src/SceneListResource.h [new file with mode: 0644]
service/scene-manager/src/SceneListResourceRequestor.cpp [new file with mode: 0644]
service/scene-manager/src/SceneListResourceRequestor.h [new file with mode: 0644]
service/scene-manager/src/SceneMemberResource.cpp [new file with mode: 0644]
service/scene-manager/src/SceneMemberResource.h [new file with mode: 0644]
service/scene-manager/src/SceneMemberResourceRequestor.cpp [new file with mode: 0644]
service/scene-manager/src/SceneMemberResourceRequestor.h [new file with mode: 0644]
service/scene-manager/src/SceneUtils.cpp [new file with mode: 0644]
service/scene-manager/unittests/RemoteSceneActionTest.cpp [new file with mode: 0755]
service/scene-manager/unittests/RemoteSceneCollectionTest.cpp [new file with mode: 0644]
service/scene-manager/unittests/RemoteSceneListTest.cpp [new file with mode: 0644]
service/scene-manager/unittests/RemoteSceneTest.cpp [new file with mode: 0644]
service/scene-manager/unittests/SConscript [new file with mode: 0755]
service/scene-manager/unittests/SceneActionTest.cpp [new file with mode: 0755]
service/scene-manager/unittests/SceneCollectionTest.cpp [new file with mode: 0755]
service/scene-manager/unittests/SceneListTest.cpp [new file with mode: 0755]
service/scene-manager/unittests/SceneTest.cpp [new file with mode: 0755]
service/simulator/SConscript [changed mode: 0644->0755]
service/simulator/examples/README.txt [deleted file]
service/simulator/examples/client-controller/SConscript [deleted file]
service/simulator/examples/client-controller/client_controller.cpp [deleted file]
service/simulator/examples/client/SConscript [new file with mode: 0644]
service/simulator/examples/client/simulator_client.cpp [new file with mode: 0644]
service/simulator/examples/server/SConscript
service/simulator/examples/server/service_provider.cpp [deleted file]
service/simulator/examples/server/simulator_server.cpp [new file with mode: 0644]
service/simulator/inc/simulator_client_types.h
service/simulator/inc/simulator_collection_resource.h [new file with mode: 0644]
service/simulator/inc/simulator_error_codes.h
service/simulator/inc/simulator_manager.h
service/simulator/inc/simulator_remote_resource.h
service/simulator/inc/simulator_request_model.h [new file with mode: 0644]
service/simulator/inc/simulator_resource.h [new file with mode: 0644]
service/simulator/inc/simulator_resource_model.h
service/simulator/inc/simulator_resource_model_schema.h [new file with mode: 0644]
service/simulator/inc/simulator_resource_server.h [deleted file]
service/simulator/inc/simulator_server_types.h [deleted file]
service/simulator/inc/simulator_single_resource.h [new file with mode: 0644]
service/simulator/inc/simulator_uncopyable.h [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/.classpath
service/simulator/java/eclipse-plugin/ClientControllerPlugin/.project
service/simulator/java/eclipse-plugin/ClientControllerPlugin/META-INF/MANIFEST.MF
service/simulator/java/eclipse-plugin/ClientControllerPlugin/build.properties
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/light_16x16.png [deleted file]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/plugin.xml
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/Activator.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IDevicePlatformInfoUIListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IGetUIListener.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IObserveUIListener.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IPostUIListener.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IPutUIListener.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IVerificationUIListener.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/manager/ImageManager.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/manager/LogManager.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/manager/ResourceManager.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/manager/UiListenerHandler.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/perspective/PerspectiveFactory.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/AttributeElement.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/DeviceAndPlatformInfo.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/PutPostAttributeModel.java [deleted file]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/RemoteResource.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/RemoteResourceAttribute.java [deleted file]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/ResourceRepresentation.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/SerializedClientController.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/utils/AttributeValueBuilder.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/utils/AttributeValueStringConverter.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/utils/Constants.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/utils/Utility.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/AttributeEditingSupport.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/AttributeView.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/LogView.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/MetaPropertiesView.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/MultiResourceOrchestrationView.java [deleted file]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/ResourceManagerView.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/FilterDialog.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/FindResourcePage.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/FindResourceWizard.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/GetRequestDialog.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/LoadRAMLDialog.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/LogDetailsDialog.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/ModelArrayAddItemDialog.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/PostRequestDialog.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/PutRequestDialog.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/UpdatePrimitiveArrayAttributeDialog.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/VerificationDialog.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/logger/LogContentProvider.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/logger/LogLabelProvider.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/logger/LoggerCallback.java
service/simulator/java/eclipse-plugin/README.txt
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/.classpath
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/META-INF/MANIFEST.MF
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/build.properties
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/single_resource.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/plugin.xml
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/resource/Light/simple-light-error.json [deleted file]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/resource/Light/simple-light.json [deleted file]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/resource/Light/simple-light.raml [deleted file]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LogContentProvider.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LogLabelProvider.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LoggerCallback.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/Activator.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IAutomationListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IAutomationUIListener.java [deleted file]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IDataChangeListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IDeviceInfoListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/ILogListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/ILogUIListener.java [deleted file]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IObserverListChangedListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IObserverListChangedUIListener.java [deleted file]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IPropertiesChangedListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceListChangedListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceListChangedUIListener.java [deleted file]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceModelChangedUIListener.java [deleted file]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceSelectionChangedUIListener.java [deleted file]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/ISelectionChangedListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/Data.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/ImageManager.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/LogManager.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/ResourceManager.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/UiListenerHandler.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/AttributeElement.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/AttributeHelper.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/AutomationSettingHelper.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/MetaProperty.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/ObserverDetail.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/Resource.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/ResourceRepresentation.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/ResourceType.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/SerializedServiceProvider.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/SingleResource.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/perspective/PerspectiveFactory.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/AutomationSettingHelper.java [deleted file]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/DeleteCategory.java [deleted file]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/LocalResourceAttribute.java [deleted file]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/MetaProperty.java [deleted file]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/ModelChangeNotificationType.java [deleted file]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/ObserverDetail.java [deleted file]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/SimulatorResource.java [deleted file]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/StandardConfiguration.java [deleted file]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/AttributeValueBuilder.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/AttributeValueStringConverter.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/Constants.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/Utility.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/AttributeEditingSupport.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/AttributeView.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/DevicePlatformInfoView.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/LogView.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/MetaPropertiesView.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/MultiResourceOrchestrationView.java [deleted file]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/ResourceManagerView.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/ResourceObserverView.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddAttributeDialog.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddInterfaceTypeDialog.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AutomationSettingDialog.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/CreateResourcePage.java [deleted file]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/CreateResourceWizard.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/DeleteResourcePage.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/DeleteResourceWizard.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/FilterDialog.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/LoadRamlPage.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/LogDetailsDialog.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/MainPage.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/ModelArrayAddItemDialog.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/ResourceWizardDialog.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourceAddAttributePage.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourceBasicDetailsPage.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourceOtherDetailsPage.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SingleTextInputDialog.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/UpdatePrimitiveArrayAttributeDialog.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/UpdatePropertiesPage.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/UpdateResourceInterfaceDialog.java [new file with mode: 0644]
service/simulator/java/jni/jni_listener_holder.h [new file with mode: 0644]
service/simulator/java/jni/jni_map.cpp [new file with mode: 0644]
service/simulator/java/jni/jni_map.h [new file with mode: 0644]
service/simulator/java/jni/jni_queryparam.cpp [new file with mode: 0644]
service/simulator/java/jni/jni_queryparam.h [new file with mode: 0644]
service/simulator/java/jni/jni_sharedobject_holder.h [new file with mode: 0644]
service/simulator/java/jni/jni_string.cpp [new file with mode: 0644]
service/simulator/java/jni/jni_string.h [new file with mode: 0644]
service/simulator/java/jni/jni_vector.cpp [new file with mode: 0644]
service/simulator/java/jni/jni_vector.h [new file with mode: 0644]
service/simulator/java/jni/resource_attributes_jni.cpp [deleted file]
service/simulator/java/jni/resource_attributes_jni.h [deleted file]
service/simulator/java/jni/simulator_collection_resource_jni.cpp [new file with mode: 0644]
service/simulator/java/jni/simulator_common_jni.h [deleted file]
service/simulator/java/jni/simulator_device_info_jni.cpp
service/simulator/java/jni/simulator_device_info_jni.h
service/simulator/java/jni/simulator_exceptions_jni.cpp [new file with mode: 0644]
service/simulator/java/jni/simulator_exceptions_jni.h [new file with mode: 0644]
service/simulator/java/jni/simulator_init_jni.cpp [new file with mode: 0644]
service/simulator/java/jni/simulator_jni_utils.cpp [deleted file]
service/simulator/java/jni/simulator_jni_utils.h [deleted file]
service/simulator/java/jni/simulator_manager_jni.cpp
service/simulator/java/jni/simulator_manager_jni.h [deleted file]
service/simulator/java/jni/simulator_platform_info_jni.cpp
service/simulator/java/jni/simulator_platform_info_jni.h
service/simulator/java/jni/simulator_remote_resource_jni.cpp
service/simulator/java/jni/simulator_remote_resource_jni.h [deleted file]
service/simulator/java/jni/simulator_resource_attribute_jni.cpp [new file with mode: 0644]
service/simulator/java/jni/simulator_resource_attribute_jni.h [new file with mode: 0644]
service/simulator/java/jni/simulator_resource_jni.cpp [new file with mode: 0644]
service/simulator/java/jni/simulator_resource_jni_util.cpp [deleted file]
service/simulator/java/jni/simulator_resource_jni_util.h [deleted file]
service/simulator/java/jni/simulator_resource_model_jni.cpp
service/simulator/java/jni/simulator_resource_model_jni.h
service/simulator/java/jni/simulator_resource_model_schema_jni.cpp [new file with mode: 0644]
service/simulator/java/jni/simulator_resource_model_schema_jni.h [new file with mode: 0644]
service/simulator/java/jni/simulator_resource_server_jni.cpp [deleted file]
service/simulator/java/jni/simulator_resource_server_jni.h [deleted file]
service/simulator/java/jni/simulator_resource_utils_jni.cpp [new file with mode: 0644]
service/simulator/java/jni/simulator_resource_utils_jni.h [new file with mode: 0644]
service/simulator/java/jni/simulator_single_resource_jni.cpp [new file with mode: 0644]
service/simulator/java/jni/simulator_utils_jni.cpp [new file with mode: 0644]
service/simulator/java/jni/simulator_utils_jni.h [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/ArrayProperty.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/ArrayValueValidator.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/AttributeProperty.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/AttributeValue.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/AttributeValueVisitor.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/BooleanProperty.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/DeviceInfo.java
service/simulator/java/sdk/src/org/oic/simulator/DeviceListener.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/DoubleProperty.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/DoubleValueValidator.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/IAutomation.java [deleted file]
service/simulator/java/sdk/src/org/oic/simulator/IDeviceInfo.java [deleted file]
service/simulator/java/sdk/src/org/oic/simulator/ILogger.java
service/simulator/java/sdk/src/org/oic/simulator/IPlatformInfo.java [deleted file]
service/simulator/java/sdk/src/org/oic/simulator/IntegerProperty.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/IntegerValueValidator.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/InvalidArgsException.java
service/simulator/java/sdk/src/org/oic/simulator/ModelProperty.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/ModelValueValidator.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/NoSupportException.java
service/simulator/java/sdk/src/org/oic/simulator/OperationInProgressException.java
service/simulator/java/sdk/src/org/oic/simulator/PlatformInfo.java
service/simulator/java/sdk/src/org/oic/simulator/PlatformListener.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/ResourceAttribute.java [deleted file]
service/simulator/java/sdk/src/org/oic/simulator/SimulatorException.java
service/simulator/java/sdk/src/org/oic/simulator/SimulatorManager.java
service/simulator/java/sdk/src/org/oic/simulator/SimulatorManagerNativeInterface.java [deleted file]
service/simulator/java/sdk/src/org/oic/simulator/SimulatorResourceAttribute.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/SimulatorResourceModel.java
service/simulator/java/sdk/src/org/oic/simulator/SimulatorResult.java
service/simulator/java/sdk/src/org/oic/simulator/StringProperty.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/StringValueValidator.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/client/FindResourceListener.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/client/SimulatorConnectivityType.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/client/SimulatorRemoteResource.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/client/SimulatorRequestModel.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IFindResourceListener.java [deleted file]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IGetListener.java [deleted file]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IObserveListener.java [deleted file]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IPostListener.java [deleted file]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IPutListener.java [deleted file]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IVerificationListener.java [deleted file]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorConnectivityType.java [deleted file]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorObserveType.java [deleted file]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorRemoteResource.java [deleted file]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorVerificationType.java [deleted file]
service/simulator/java/sdk/src/org/oic/simulator/server/Observer.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/server/SimulatorCollectionResource.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/server/SimulatorResource.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/server/SimulatorSingleResource.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/AutomationType.java [deleted file]
service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/IObserver.java [deleted file]
service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/IResourceModelChangedListener.java [deleted file]
service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/ObserverInfo.java [deleted file]
service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/SimulatorResourceServer.java [deleted file]
service/simulator/ramlparser/SConscript
service/simulator/ramlparser/example/SConscript [deleted file]
service/simulator/ramlparser/example/raml_parser.cpp [deleted file]
service/simulator/ramlparser/raml/IncludeResolver.h
service/simulator/ramlparser/raml/RamlParser.cpp
service/simulator/ramlparser/raml/RamlParser.h
service/simulator/ramlparser/raml/RamlUtils.h [new file with mode: 0755]
service/simulator/ramlparser/raml/Utils.h [deleted file]
service/simulator/ramlparser/raml/jsonSchemaParser/AllowedValues.h [deleted file]
service/simulator/ramlparser/raml/jsonSchemaParser/Definitions.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/jsonSchemaParser/Definitions.h
service/simulator/ramlparser/raml/jsonSchemaParser/Helpers.h [deleted file]
service/simulator/ramlparser/raml/jsonSchemaParser/Items.h [deleted file]
service/simulator/ramlparser/raml/jsonSchemaParser/JsonSchema.cpp
service/simulator/ramlparser/raml/jsonSchemaParser/JsonSchema.h
service/simulator/ramlparser/raml/jsonSchemaParser/Properties.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/jsonSchemaParser/Properties.h
service/simulator/ramlparser/raml/model/AbstractParam.h
service/simulator/ramlparser/raml/model/Action.h
service/simulator/ramlparser/raml/model/Raml.h
service/simulator/ramlparser/raml/model/RamlResource.h
service/simulator/ramlparser/raml/model/RequestResponseBody.h
service/simulator/ramlparser/raml/model/Response.h
service/simulator/ramlparser/raml/model/Schema.h
service/simulator/src/client-controller/attribute_generator.cpp [deleted file]
service/simulator/src/client-controller/attribute_generator.h [deleted file]
service/simulator/src/client-controller/auto_request_gen.cpp [deleted file]
service/simulator/src/client-controller/auto_request_gen.h [deleted file]
service/simulator/src/client-controller/auto_request_gen_mngr.cpp [deleted file]
service/simulator/src/client-controller/auto_request_gen_mngr.h [deleted file]
service/simulator/src/client-controller/get_request_generator.cpp [deleted file]
service/simulator/src/client-controller/get_request_generator.h [deleted file]
service/simulator/src/client-controller/post_request_generator.cpp [deleted file]
service/simulator/src/client-controller/post_request_generator.h [deleted file]
service/simulator/src/client-controller/put_request_generator.cpp [deleted file]
service/simulator/src/client-controller/put_request_generator.h [deleted file]
service/simulator/src/client-controller/request_sender.cpp [deleted file]
service/simulator/src/client-controller/request_sender.h [deleted file]
service/simulator/src/client-controller/simulator_client.cpp [deleted file]
service/simulator/src/client-controller/simulator_client.h [deleted file]
service/simulator/src/client-controller/simulator_remote_resource_impl.cpp [deleted file]
service/simulator/src/client-controller/simulator_remote_resource_impl.h [deleted file]
service/simulator/src/client/get_request_generator.cpp [new file with mode: 0644]
service/simulator/src/client/get_request_generator.h [new file with mode: 0644]
service/simulator/src/client/post_request_generator.cpp [new file with mode: 0644]
service/simulator/src/client/post_request_generator.h [new file with mode: 0644]
service/simulator/src/client/put_request_generator.cpp [new file with mode: 0644]
service/simulator/src/client/put_request_generator.h [new file with mode: 0644]
service/simulator/src/client/query_param_generator.cpp [moved from service/simulator/src/client-controller/query_param_generator.cpp with 100% similarity]
service/simulator/src/client/query_param_generator.h [moved from service/simulator/src/client-controller/query_param_generator.h with 100% similarity]
service/simulator/src/client/request_automation_manager.cpp [new file with mode: 0644]
service/simulator/src/client/request_automation_manager.h [new file with mode: 0644]
service/simulator/src/client/request_generation.cpp [new file with mode: 0644]
service/simulator/src/client/request_generation.h [new file with mode: 0644]
service/simulator/src/client/request_list.h [moved from service/simulator/src/client-controller/request_list.h with 100% similarity]
service/simulator/src/client/request_sender.cpp [new file with mode: 0644]
service/simulator/src/client/request_sender.h [new file with mode: 0644]
service/simulator/src/client/simulator_remote_resource_impl.cpp [new file with mode: 0644]
service/simulator/src/client/simulator_remote_resource_impl.h [new file with mode: 0644]
service/simulator/src/client/simulator_request_model.cpp [new file with mode: 0644]
service/simulator/src/common/attribute_generator.cpp [new file with mode: 0644]
service/simulator/src/common/attribute_generator.h [new file with mode: 0644]
service/simulator/src/common/attribute_value_generator.cpp [new file with mode: 0644]
service/simulator/src/common/attribute_value_generator.h [new file with mode: 0644]
service/simulator/src/common/request_model.cpp
service/simulator/src/common/request_model.h
service/simulator/src/common/request_model_builder.cpp [changed mode: 0644->0755]
service/simulator/src/common/request_model_builder.h [changed mode: 0644->0755]
service/simulator/src/common/resource_model_schema_builder.cpp [new file with mode: 0644]
service/simulator/src/common/resource_model_schema_builder.h [new file with mode: 0644]
service/simulator/src/common/response_model.cpp
service/simulator/src/common/response_model.h
service/simulator/src/common/simulator_resource_model.cpp
service/simulator/src/common/simulator_resource_model_schema.cpp [new file with mode: 0644]
service/simulator/src/common/simulator_utils.cpp
service/simulator/src/common/simulator_utils.h
service/simulator/src/server/oc_interface_details.cpp [new file with mode: 0644]
service/simulator/src/server/oc_interface_details.h [new file with mode: 0644]
service/simulator/src/server/resource_update_automation.cpp [new file with mode: 0644]
service/simulator/src/server/resource_update_automation.h [new file with mode: 0644]
service/simulator/src/server/resource_update_automation_mngr.cpp [new file with mode: 0644]
service/simulator/src/server/resource_update_automation_mngr.h [new file with mode: 0644]
service/simulator/src/server/simulator_collection_resource_impl.cpp [new file with mode: 0755]
service/simulator/src/server/simulator_collection_resource_impl.h [new file with mode: 0755]
service/simulator/src/server/simulator_resource.cpp [new file with mode: 0644]
service/simulator/src/server/simulator_resource_factory.cpp [new file with mode: 0644]
service/simulator/src/server/simulator_resource_factory.h [new file with mode: 0755]
service/simulator/src/server/simulator_single_resource_impl.cpp [new file with mode: 0755]
service/simulator/src/server/simulator_single_resource_impl.h [new file with mode: 0755]
service/simulator/src/service-provider/resource_manager.cpp [deleted file]
service/simulator/src/service-provider/resource_manager.h [deleted file]
service/simulator/src/service-provider/resource_update_automation.cpp [deleted file]
service/simulator/src/service-provider/resource_update_automation.h [deleted file]
service/simulator/src/service-provider/resource_update_automation_mngr.cpp [deleted file]
service/simulator/src/service-provider/resource_update_automation_mngr.h [deleted file]
service/simulator/src/service-provider/simulator_resource_creator.cpp [deleted file]
service/simulator/src/service-provider/simulator_resource_creator.h [deleted file]
service/simulator/src/service-provider/simulator_resource_server.cpp [deleted file]
service/simulator/src/service-provider/simulator_resource_server_impl.cpp [deleted file]
service/simulator/src/service-provider/simulator_resource_server_impl.h [deleted file]
service/simulator/src/simulator_manager.cpp
service/simulator/unittests/SimulatorTest/.gitignore [new file with mode: 0644]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/client/test/SimulatorRemoteResourceTest.java [new file with mode: 0644]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/GetListener.java [deleted file]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/ListenerObject.java [deleted file]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/ObserveListener.java [deleted file]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/ObserveListenerObject.java [deleted file]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/PostListener.java [deleted file]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/PutListener.java [deleted file]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/SimulatorRemoteResourceTest.java [deleted file]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/VerifyListener.java [deleted file]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/VerifyListenerObject.java [deleted file]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/server/test/SimulatorCollectionResourceTest.java [new file with mode: 0644]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/server/test/SimulatorResourceTest.java [new file with mode: 0644]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/server/test/SimulatorSingleResourceTest.java [new file with mode: 0644]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/AutomationListener.java [deleted file]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/AutomationObject.java [deleted file]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/Observer.java [deleted file]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/ObserverObject.java [deleted file]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/SimlatorResourceServerTest.java [deleted file]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ArrayPropertyTest.java [new file with mode: 0644]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/AttributeValueTest.java [new file with mode: 0644]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/BooleanPropertyTest.java [new file with mode: 0644]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/DoublePropertyTest.java [new file with mode: 0644]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ExceptionType.java [new file with mode: 0644]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/FindResourceListener.java [deleted file]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/IntegerPropertyTest.java [new file with mode: 0644]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ModelPropertyTest.java [new file with mode: 0644]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ResourceModelChangeListener.java [deleted file]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ResourceModelObject.java [deleted file]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/SimulatorManagerTest.java
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/SimulatorRemoteResourceObject.java [deleted file]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/SimulatorResourceModelTest.java
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/StringPropertyTest.java [new file with mode: 0644]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/utils/ObjectHolder.java [new file with mode: 0644]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/utils/SampleSingleResource.java [new file with mode: 0644]
service/things-manager/SConscript
service/things-manager/sampleapp/SConscript
service/things-manager/sampleapp/linux/configuration/MaintenanceCollection.cpp [changed mode: 0644->0755]
service/things-manager/sampleapp/linux/configuration/con-client.cpp
service/things-manager/sampleapp/linux/groupaction/SConscript [deleted file]
service/things-manager/sampleapp/linux/groupaction/bookmark.cpp [deleted file]
service/things-manager/sampleapp/linux/groupaction/groupserver.cpp [deleted file]
service/things-manager/sdk/inc/ActionSet.h [changed mode: 0644->0755]
service/things-manager/sdk/inc/GroupManager.h
service/things-manager/sdk/inc/ThingsConfiguration.h
service/things-manager/sdk/inc/ThingsMaintenance.h
service/things-manager/sdk/java/jni/SConscript
service/things-manager/sdk/src/ActionSet.cpp [changed mode: 0644->0755]
service/things-manager/sdk/src/GroupManager.cpp
service/things-manager/unittests/ThingsManagerTest.cpp
service/third_party_libs.scons
tools/valgrind/iotivity.supp

index 2478306..eadac8f 100644 (file)
@@ -92,7 +92,6 @@ extlibs/gtest/gtest-*
 extlibs/hippomocks-master/
 extlibs/master.zip
 extlibs/cereal/cereal
-extlibs/expat/expat*
 extlibs/cereal
 extlibs/android/gradle/gradle-2.2.1
 extlibs/android/ndk/android-ndk-r10d
index e9e1f02..a0884f9 100644 (file)
@@ -1,5 +1,5 @@
 Copyright (c) 2014, 2015 IoTivity
-<http://www.iotivity.com/>
+<http://www.iotivity.org/>
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
diff --git a/README-building-and-running-remote-access-sample.txt b/README-building-and-running-remote-access-sample.txt
new file mode 100644 (file)
index 0000000..27e5b69
--- /dev/null
@@ -0,0 +1,42 @@
+== Quick guide: build and run IoTivity(remote access) projects on Ubuntu ==
+
+1. Build
+       Go to the top directory of 'iotivity' project
+    (Note: should always run 'scons' command in this directory)
+
+    Install external libraries:
+      $ sudo apt-get install libboost-dev libboost-program-options-dev libboost-thread-dev uuid-dev libssl-dev
+      $ sudo apt-get install libglib2.0-dev autoconf libtool
+
+    Build release binaries:
+      $ scons WITH_RA=1 WITH_RA_IBB=1
+(Note: C sdk requires tiny-cbor. Please follow the instruction in the build
+message to install tiny-cbor)
+
+    Build debug binaries:
+      $ scons WITH_RA=1 WITH_RA_IBB=1 RELEASE=false
+
+    Help:
+      $ scons -h
+
+    Clear:
+      $ scons -c
+
+2. Run the remote access testing
+    remote access samples in <iotivity>/out/linux/x86_64/release/resource/csdk/stack/samples/linux/SimpleClientServer
+
+    before testing,
+      setup a XMPP server and create an account in XMPP server
+      ex: account: user1@localhost / password: 1234
+
+    oic server:
+      $ ocserver -o 1 -u user1 -d localhost -w 1234 -s localhost
+
+    oic client:
+      $ ocremoteaccessclient -t 1 -u user1 -d localhost -w 1234 -s localhost
+
+    test steps:
+      1. run ocserver, and copy the bound jid
+      2. run ocremoteaccessclient on the another term, and paste the bound jid of ocserver and press 'Enter'
+        use '-t' to change testcase.
+
index aac7c90..56f5f02 100644 (file)
@@ -1,11 +1,14 @@
 == Quick guide: build and run IoTivity projects on Ubuntu ==
 
 1. Build
-       Go to the top directory of 'iotivity' project(Note: should always run 'scons'
-command in this directory)
+    Go to the top directory of 'iotivity' project(Note: should always run 'scons'
+    command in this directory)
+
+    Install build tools:
+      $ sudo apt-get install git-core scons ssh build-essential g++ doxygen valgrind
 
     Install external libraries:
-      $ sudo apt-get install libboost-dev libboost-program-options-dev libexpat1-dev libboost-thread-dev uuid-dev libssl-dev
+      $ sudo apt-get install libboost-dev libboost-program-options-dev libboost-thread-dev uuid-dev libssl-dev libtool libglib2.0-dev
 
     Build release binaries:
       $ scons
@@ -123,7 +126,7 @@ by doing the following:
 
 
 * 3. External libraries
-IoTivity project depends on some external libraries, such as boost, expat ...
+IoTivity project depends on some external libraries, such as boost ...
 During building, the existence of external library will be checked, if it doesn't
 exist, the build script will try to download, unpack and build the library or
 notify user to install it.
@@ -199,7 +202,7 @@ Tizen:
     $ scons TARGET_OS=tizen TARGET_TRANSPORT=ALL -c (for clean)
 
 (we provide the spec file required by gbs tool at toools/tizen directory.
-gbs is default build tool for Tizen platfrom, we can refer the following
+gbs is default build tool for Tizen platform, we can refer the following
 wiki to setup Tizen development environment:
 https://source.tizen.org/documentation/developer-guide/getting-started-guide)
 
index 0ebc436..35ff720 100644 (file)
@@ -62,6 +62,9 @@ if target_os not in ['arduino','darwin','ios', 'android']:
 # Build 'service' sub-project
 SConscript(build_dir + 'service/SConscript')
 
+# Build "cloud" sub-project
+SConscript(build_dir + 'cloud/SConscript')
+
 # Build "plugin interface" sub-project
 SConscript(build_dir + 'plugins/SConscript')
 
index 38fd526..32ffb22 100644 (file)
@@ -48,11 +48,11 @@ def ensure_libs(target, source, env):
 
 # build android_api
 jdk_env = Environment(ENV=os.environ)
-jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') + ' build -b' + os.getcwd()+'/build.gradle -PTARGET_ARCH=%s -PRELEASE=%s -PSECURED=%s --stacktrace' %(ANDROID_TARGET_ARCH, ANDROID_RELEASE, ANDROID_SECURED), emitter = ensure_libs)
+jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') + ' build -b' + os.getcwd()+'/build.gradle -PTARGET_ARCH=%s -PRELEASE=%s -PSECURED=%s -DSECURE=%s --stacktrace' %(ANDROID_TARGET_ARCH, ANDROID_RELEASE, ANDROID_SECURED, ANDROID_SECURED), emitter = ensure_libs)
 jdk_env['BUILD_DIR'] = env.get('BUILD_DIR')
 cmdBuildApi=jdk_env.Gradle(target="base/objs", source="base/src/main/java/org/iotivity/base/OcResource.java")
 
-jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') + ' build -b' + 'android/examples/build.gradle -PTARGET_ARCH=%s -PRELEASE=%s -PSECURED=%s --stacktrace' %(ANDROID_TARGET_ARCH, ANDROID_RELEASE, ANDROID_SECURED))
+jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') + ' build -b' + 'android/examples/build.gradle -PTARGET_ARCH=%s -PRELEASE=%s -PSECURED=%s -DSECURE=%s --stacktrace' %(ANDROID_TARGET_ARCH, ANDROID_RELEASE, ANDROID_SECURED, ANDROID_SECURED))
 cmdBuildExamples=jdk_env.Gradle(target="../examples/devicediscoveryclient/apk", source="../examples/devicediscoveryclient/src/main/java/org/iotivity/base/examples/DeviceDiscoveryClient.java")
 
 # android examples require android api to be built before being invoked
index 82fb651..7deb01c 100755 (executable)
@@ -41,7 +41,8 @@ android {
         minSdkVersion 21\r
         targetSdkVersion 21\r
         versionCode 1\r
-        versionName "1.0"\r
+        versionName "1.1"\r
+        buildConfigField 'int', 'SECURED', SECURED\r
     }\r
     buildTypes {\r
         release {\r
@@ -101,4 +102,4 @@ task buildNative(type: Exec) {
         println 'Reason: ANDROID_NDK_HOME not set.'\r
         println '##################'\r
     }\r
-}
\ No newline at end of file
+}\r
index e07b671..cc43275 100644 (file)
@@ -1,6 +1,6 @@
 LOCAL_PATH := $(call my-dir)\r
 TARGET_ARCH_ABI := $(APP_ABI)\r
-SECURED := $(SECURE)
+SECURED := $(SECURE)\r
 \r
 include $(CLEAR_VARS)\r
 OIC_LIB_PATH := ../../../../out/android/$(APP_ABI)/$(APP_OPTIM)\r
@@ -26,20 +26,20 @@ LOCAL_MODULE := libandroid-ca
 LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libconnectivity_abstraction.so\r
 include $(PREBUILT_SHARED_LIBRARY)\r
 \r
-ifeq ($(SECURED), 1)
-include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../out/android/$(APP_ABI)/$(APP_OPTIM)
-LOCAL_MODULE := libandroid-ocprovision
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libocprovision.a
-include $(PREBUILT_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../out/android/$(APP_ABI)/$(APP_OPTIM)
-LOCAL_MODULE := libandroid-ocpmapi
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libocpmapi.a
-include $(PREBUILT_STATIC_LIBRARY)
-endif
-
+ifeq ($(SECURED), 1)\r
+include $(CLEAR_VARS)\r
+OIC_LIB_PATH := ../../../../out/android/$(APP_ABI)/$(APP_OPTIM)\r
+LOCAL_MODULE := libandroid-ocprovision\r
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libocprovision.so\r
+include $(PREBUILT_SHARED_LIBRARY)\r
+\r
+include $(CLEAR_VARS)\r
+OIC_LIB_PATH := ../../../../out/android/$(APP_ABI)/$(APP_OPTIM)\r
+LOCAL_MODULE := libandroid-ocpmapi\r
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libocpmapi.so\r
+include $(PREBUILT_SHARED_LIBRARY)\r
+endif\r
+\r
 include $(CLEAR_VARS)\r
 OIC_SRC_PATH := ../../../resource\r
 LOCAL_MODULE := libca-interface\r
@@ -73,16 +73,16 @@ LOCAL_SRC_FILES :=  JniOcStack.cpp \
                     JniOcResourceResponse.cpp \\r
                     JniOcPlatform.cpp \\r
                     JniOcResource.cpp \\r
-                    JniOcResourceIdentifier.cpp \
-                    JniOcSecurity.cpp
-ifeq ($(SECURED), 1)
-LOCAL_SRC_FILES +=  JniOcSecureResource.cpp \
-                    JniOcProvisioning.cpp \
-                    JniSecureUtils.cpp \
-                    JniProvisionResultListner.cpp \
-                    JniPinCheckListener.cpp \
-                    JniDisplayPinListener.cpp
-endif
+                    JniOcResourceIdentifier.cpp \\r
+                    JniOcSecurity.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
 \r
 LOCAL_LDLIBS := -llog\r
 LOCAL_STATIC_LIBRARIES := android-oc\r
@@ -91,24 +91,27 @@ LOCAL_STATIC_LIBRARIES += android-coap
 LOCAL_STATIC_LIBRARIES += android-oc_logger\r
 LOCAL_STATIC_LIBRARIES += android-ca\r
 LOCAL_STATIC_LIBRARIES += android_cpp11_compat\r
-ifeq ($(SECURED), 1)
-LOCAL_STATIC_LIBRARIES += android-ocprovision
-LOCAL_STATIC_LIBRARIES += android-ocpmapi
-endif
+ifeq ($(SECURED), 1)\r
+LOCAL_STATIC_LIBRARIES += android-ocprovision\r
+LOCAL_STATIC_LIBRARIES += android-ocpmapi\r
+endif\r
 \r
 LOCAL_CPPFLAGS += -std=c++0x\r
 LOCAL_CPP_FEATURES := rtti exceptions\r
 LOCAL_C_INCLUDES := $(OIC_SRC_PATH)/include\r
 LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/c_common\r
-LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/c_common/oic_string/include
-LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/c_common/oic_malloc/include
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/c_common/oic_string/include\r
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/c_common/oic_malloc/include\r
 LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/stack/include\r
 LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/ocsocket/include\r
 LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/oc_logger/include\r
 LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/../extlibs/boost/boost_1_58_0\r
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/../extlibs/cjson\r
 LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/../build_common/android/compatibility\r
-LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/security/provisioning/include
-LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/security/provisioning/include/oxm/
-LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/security/provisioning/include/internal
-LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/security/include
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/security/provisioning/include\r
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/security/provisioning/include/oxm/\r
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/security/provisioning/include/internal\r
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/security/include\r
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/connectivity/api\r
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/connectivity/lib/libcoap-4.1.1\r
 include $(BUILD_SHARED_LIBRARY)\r
index 0972278..d641f3d 100644 (file)
 #include <stdio.h>
 #include "cainterface.h"
 #include "JniCaInterface.h"
+#include "cautilinterface.h"
+#include "cacommon.h"
 
 #define  LOG_TAG   "JNI_CA_INTERFACE"
 #define  LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
 #define  LOGE(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
 
+static jobject g_foundDeviceListenerObject = NULL;
+static jobject g_listenerObject = NULL;
+static JavaVM *g_jvm = NULL;
+
 JNIEXPORT jint JNI_OnLoad(JavaVM *jvm, void *reserved)
 {
     LOGI("CaInterface_initialize");
+    g_jvm = jvm;
     CANativeJNISetJavaVM(jvm);
 
     return JNI_VERSION_1_6;
@@ -45,9 +52,280 @@ void JNI_OnUnload(JavaVM *jvm, void *reserved)
 
 JNIEXPORT void JNICALL
 Java_org_iotivity_ca_CaInterface_initialize
-(JNIEnv *env, jclass clazz, jobject context)
+(JNIEnv *env, jclass clazz, jobject activity, jobject context)
 {
     LOGI("CaInterface_initialize");
 
+    CANativeSetActivity(env, activity);
     CANativeJNISetContext(env, context);
-}
\ No newline at end of file
+}
+
+void CAManagerConnectionStateChangedCB(CATransportAdapter_t adapter,
+                                       const char *remote_address,
+                                       bool connected)
+{
+    LOGI("Callback - CAManagerConnectionStateChangedCB : type(%d), address(%s), connected(%d)",
+         adapter, remote_address, connected);
+
+    if (!g_listenerObject)
+    {
+        LOGE("g_listener is NULL, cannot have callback");
+        return;
+    }
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        LOGI("AttachCurrentThread will be called for JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            LOGE("AttachCurrentThread has failed");
+            return;
+        }
+        isAttached = true;
+    }
+
+    jclass jni_cls_listener = (*env)->GetObjectClass(env, g_listenerObject);
+    if (!jni_cls_listener)
+    {
+        LOGE("could not get jni_cls_listener");
+        goto exit_error;
+    }
+
+    jmethodID jni_mid_listener = (*env)->GetMethodID(env, jni_cls_listener,
+                                                     "onConnectionStateChanged",
+                                                     "(Lorg/iotivity/base/OcConnectivityType;"
+                                                     "Ljava/lang/String;Z)V");
+    if (!jni_mid_listener)
+    {
+        LOGE("could not get Method ID");
+        goto exit_error;
+    }
+
+    jstring jni_address = (*env)->NewStringUTF(env, remote_address);
+    if (!jni_address)
+    {
+        LOGE("jni_address is null");
+        goto exit_error;
+    }
+
+    jclass jni_cls_enum = (*env)->FindClass(env, "org/iotivity/base/OcConnectivityType");
+    if (!jni_cls_enum)
+    {
+        LOGE("could not get jni_cls_enum");
+        goto exit_error;
+    }
+
+    jmethodID jni_mid_enum = (*env)->GetStaticMethodID(env, jni_cls_enum, "getInstance",
+                                                       "(I)Lorg/iotivity/base/OcConnectivityType;");
+    if (!jni_mid_enum)
+    {
+        LOGE("could not get Method ID (getInstance)");
+        goto exit_error;
+    }
+
+    jobject jni_adaptertype = (*env)->CallStaticObjectMethod(env, jni_cls_enum,
+                                                             jni_mid_enum, adapter);
+    (*env)->CallVoidMethod(env, g_listenerObject, jni_mid_listener,
+                           jni_adaptertype, jni_address,
+                           (jboolean)connected);
+
+exit_error:
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    LOGI("OUT - CAManagerConnectionStateChangedCB");
+}
+
+void CAManagerAdapterStateChangedCB(CATransportAdapter_t adapter, bool enabled)
+{
+    LOGI("Callback - CAManagerAdapterStateChangedCB : type(%d), enabled(%d)",
+         adapter, enabled);
+
+    if (!g_listenerObject)
+    {
+        LOGE("g_listener is NULL, cannot have callback");
+        return;
+    }
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        LOGI("AttachCurrentThread will be called for JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            LOGE("AttachCurrentThread has failed");
+            return;
+        }
+        isAttached = true;
+    }
+
+    jclass jni_cls_listener = (*env)->GetObjectClass(env, g_listenerObject);
+    if (!jni_cls_listener)
+    {
+        LOGE("could not get jni_cls_listener");
+        goto exit_error;
+    }
+
+    jmethodID jni_mid_listener = (*env)->GetMethodID(env, jni_cls_listener,
+                                                     "onAdapterStateChanged",
+                                                     "(Lorg/iotivity/base/OcConnectivityType;Z)V");
+    if (!jni_mid_listener)
+    {
+        LOGE("could not get Method ID");
+        goto exit_error;
+    }
+
+    jclass jni_cls_enum = (*env)->FindClass(env, "org/iotivity/base/OcConnectivityType");
+    if (!jni_cls_enum)
+    {
+        LOGE("could not get jni_cls_enum");
+        goto exit_error;
+    }
+
+    jmethodID jni_mid_enum = (*env)->GetStaticMethodID(env, jni_cls_enum, "getInstance",
+                                                       "(I)Lorg/iotivity/base/OcConnectivityType;");
+    if (!jni_mid_enum)
+    {
+        LOGE("could not get Method ID (getInstance)");
+        goto exit_error;
+    }
+
+    jobject jni_adaptertype = (*env)->CallStaticObjectMethod(env, jni_cls_enum,
+                                                             jni_mid_enum, adapter);
+
+    (*env)->CallVoidMethod(env, g_listenerObject, jni_mid_listener,
+                           jni_adaptertype, (jboolean)enabled);
+
+exit_error:
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+    LOGI("OUT -  CAManagerAdapterStateChangedCB");
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaInterface_caManagerInitialize(JNIEnv *env, jclass clazz,
+                                                     jobject context, jobject listener)
+{
+    LOGI("CaManagere_initialize");
+
+    CAUtilClientInitialize(env, g_jvm, context);
+
+    g_listenerObject = (*env)->NewGlobalRef(env, listener);
+
+    CARegisterNetworkMonitorHandler(CAManagerAdapterStateChangedCB,
+                                    CAManagerConnectionStateChangedCB);
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaInterface_caManagerTerminate(JNIEnv *env, jclass clazz)
+{
+    LOGI("CaManager_terminate");
+
+    CAUtilClientTerminate(env);
+
+    if (g_listenerObject)
+    {
+        (*env)->DeleteGlobalRef(env, g_listenerObject);
+        g_listenerObject = NULL;
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaInterface_caManagerSetAutoConnectionDeviceInfo(JNIEnv *env,
+                                                                      jclass clazz,
+                                                                      jstring jaddress)
+{
+    LOGI("CaManager_setAutoConnectionDeviceInfo");
+
+    const char* address = (*env)->GetStringUTFChars(env, jaddress, NULL);
+    if (!address)
+    {
+        LOGE("address is null");
+        return;
+    }
+
+    CASetAutoConnectionDeviceInfo(address);
+
+    (*env)->ReleaseStringUTFChars(env, jaddress, address);
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaInterface_caManagerUnsetAutoConnectionDeviceInfo(JNIEnv *env,
+                                                                        jclass clazz,
+                                                                        jstring jaddress)
+{
+    LOGI("CaManager_unsetAutoConnectionDeviceInfo");
+
+    const char* address = (*env)->GetStringUTFChars(env, jaddress, NULL);
+    if (!address)
+    {
+        LOGE("address is null");
+        return;
+    }
+
+    CAUnsetAutoConnectionDeviceInfo(address);
+
+    (*env)->ReleaseStringUTFChars(env, jaddress, address);
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaInterface_caBtPairingInitialize(JNIEnv *env, jclass clazz,
+                                                       jobject context, jobject listener)
+{
+    LOGI("caBtPairingInitialize");
+    (void)clazz;
+
+    CAUtilClientInitialize(env, g_jvm, context);
+
+    g_foundDeviceListenerObject = (*env)->NewGlobalRef(env, listener);
+    CAUtilSetFoundDeviceListener(g_foundDeviceListenerObject);
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaInterface_caBtPairingTerminate(JNIEnv *env, jclass clazz)
+{
+    LOGI("caBtPairingTerminate");
+    (void)clazz;
+
+    if (g_foundDeviceListenerObject)
+    {
+        (*env)->DeleteGlobalRef(env, g_foundDeviceListenerObject);
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaInterface_caBtPairingStartScan(JNIEnv *env, jclass clazz)
+{
+    LOGI("caBtPairingStartScan");
+    (void)clazz;
+    CAUtilStartScan(env);
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaInterface_caBtPairingStopScan(JNIEnv *env, jclass clazz)
+{
+    LOGI("caBtPairingStopScan");
+    (void)clazz;
+    CAUtilStopScan(env);
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaInterface_caBtPairingCreateBond(JNIEnv *env, jclass clazz, jobject device)
+{
+    LOGI("caBtPairingCreateBond");
+    (void)clazz;
+    CAUtilCreateBond(env, device);
+}
index ee77a97..20dc995 100644 (file)
 #ifdef __cplusplus
 extern "C" {
 #endif
+
+    void CAManagerConnectionStateChangedCB(CATransportAdapter_t adapter,
+                                           const char *remote_address, bool connected);
+
+    void CAManagerAdapterStateChangedCB(CATransportAdapter_t adapter, bool enabled);
+
+    /*
+     * Class:     Java_org_iotivity_ca_CaInterface_caManagerInitialize
+     * Method:    caManagerInitialize
+     * Signature: (Landroid/content/Context;)V
+     */
+    JNIEXPORT void JNICALL
+    Java_org_iotivity_ca_CaInterface_caManagerInitialize(JNIEnv *env, jclass clazz,
+                                                         jobject context, jobject listener);
+
+    /*
+     * Class:     Java_org_iotivity_ca_CaInterface_caManagerTerminate
+     * Method:    caManagerTerminate
+     * Signature: ()V
+     */
+    JNIEXPORT void JNICALL
+    Java_org_iotivity_ca_CaInterface_caManagerTerminate(JNIEnv *env, jclass clazz);
+
+    /*
+     * Class:     Java_org_iotivity_ca_CaInterface_caManagerSetAutoConnectionDeviceInfo
+     * Method:    caManagerSetAutoConnectionDeviceInfo
+     * Signature: (Ljava/lang/String;)V
+     */
+    JNIEXPORT void JNICALL
+    Java_org_iotivity_ca_CaInterface_caManagerSetAutoConnectionDeviceInfo(JNIEnv *env,
+                                                                          jclass clazz,
+                                                                          jstring jaddress);
+
+    /*
+     * Class:     Java_org_iotivity_ca_CaInterface_caManagerUnsetAutoConnectionDeviceInfo
+     * Method:    caManagerUnsetAutoConnectionDeviceInfo
+     * Signature: (Ljava/lang/String;)V
+     */
+    JNIEXPORT void JNICALL
+    Java_org_iotivity_ca_CaInterface_caManagerUnsetAutoConnectionDeviceInfo(JNIEnv *env,
+                                                                            jclass clazz,
+                                                                            jstring jaddress);
+
+    /*
+     * Class:     Java_org_iotivity_ca_CaInterface_caBtPairingInitialize
+     * Method:    caBtPairingInitialize
+     * Signature: (Landroid/content/Context;)V
+     */
+    JNIEXPORT void JNICALL
+    Java_org_iotivity_ca_CaInterface_caBtPairingInitialize(JNIEnv *, jclass, jobject, jobject);
+
+    /*
+     * Class:     Java_org_iotivity_ca_CaInterface_caBtPairingTerminate
+     * Method:    caBtPairingTerminate
+     * Signature: ()V
+     */
+    JNIEXPORT void JNICALL
+    Java_org_iotivity_ca_CaInterface_caBtPairingTerminate(JNIEnv *env, jclass clazz);
+
+    /*
+     * Class:     Java_org_iotivity_ca_CaInterface_caBtPairingStartScan
+     * Method:    caBtPairingStartScan
+     * Signature: ()V
+     */
+    JNIEXPORT void JNICALL
+    Java_org_iotivity_ca_CaInterface_caBtPairingStartScan(JNIEnv *, jclass);
+
+    /*
+     * Class:     Java_org_iotivity_ca_CaInterface_caBtPairingStopScan
+     * Method:    caBtPairingStopScan
+     * Signature: ()V
+     */
+    JNIEXPORT void JNICALL
+    Java_org_iotivity_ca_CaInterface_caBtPairingStopScan(JNIEnv *, jclass);
+
+    /*
+     * Class:     Java_org_iotivity_ca_CaInterface_caBtPairingCreateBond
+     * Method:    caBtPairingCreateBond
+     * Signature: (Landroid/bluetooth/BluetoothDevice;)V
+     */
+    JNIEXPORT void JNICALL
+    Java_org_iotivity_ca_CaInterface_caBtPairingCreateBond(JNIEnv *, jclass, jobject);
+
     /*
      * Class:     org_iotivity_ca_CaInterface_Initialize
      * Method:    Initialize
      * Signature: (Landroid/content/Context;)V
      */
     JNIEXPORT void JNICALL Java_org_iotivity_ca_CaInterface_initialize
-        (JNIEnv *, jclass, jobject);
+        (JNIEnv *, jclass, jobject, jobject);
 
 #ifdef __cplusplus
 }
 #endif
-#endif
\ No newline at end of file
+#endif
index eb3e990..52d5bc9 100644 (file)
@@ -85,7 +85,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcProvisioning_ownershipTransferCB
                 delete jniPinListener;
                 jniPinListener = new JniPinCheckListener(env, jListener);
                 CBData.loadSecretCB = InputPinCodeCallback;
-                CBData.createSecureSessionCB = CreateSecureSessionRandomPinCallbak;
+                CBData.createSecureSessionCB = CreateSecureSessionRandomPinCallback;
                 CBData.createSelectOxmPayloadCB = CreatePinBasedSelectOxmPayload;
                 CBData.createOwnerTransferPayloadCB = CreatePinBasedOwnerTransferPayload;
                 result = OCSecure::setOwnerTransferCallbackData((OicSecOxm_t)OxmType,
@@ -123,6 +123,11 @@ JNIEXPORT jobjectArray JNICALL Java_org_iotivity_base_OcProvisioning_discoverUno
 
     try
     {
+        if (timeout < 0)
+        {
+            ThrowOcException(OC_STACK_INVALID_PARAM, "Timeout value cannot be negative");
+            return nullptr;
+        }
         OCStackResult result = OCSecure::discoverUnownedDevices((unsigned short)timeout, list);
 
         if (OC_STACK_OK != result)
@@ -137,6 +142,7 @@ JNIEXPORT jobjectArray JNICALL Java_org_iotivity_base_OcProvisioning_discoverUno
     {
         LOGE("%s", e.reason().c_str());
         ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        return nullptr;
     }
 }
 
@@ -190,6 +196,11 @@ JNIEXPORT jobjectArray JNICALL Java_org_iotivity_base_OcProvisioning_discoverOwn
 
     try
     {
+        if (timeout < 0)
+        {
+            ThrowOcException(OC_STACK_INVALID_PARAM, "Timeout value cannot be negative");
+            return nullptr;
+        }
         OCStackResult result = OCSecure::discoverOwnedDevices((unsigned short)timeout, list);
         if (OC_STACK_OK != result)
         {
@@ -203,6 +214,7 @@ JNIEXPORT jobjectArray JNICALL Java_org_iotivity_base_OcProvisioning_discoverOwn
     {
         LOGE("%s", e.reason().c_str());
         ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        return nullptr;
     }
 }
 
@@ -219,6 +231,11 @@ JNIEXPORT jobjectArray JNICALL Java_org_iotivity_base_OcProvisioning_getDeviceSt
 
     try
     {
+        if (timeout < 0)
+        {
+            ThrowOcException(OC_STACK_INVALID_PARAM, "Timeout value cannot be negative");
+            return nullptr;
+        }
         OCStackResult result = OCSecure::getDevInfoFromNetwork((unsigned short)timeout,
                 ownedDevList, unownedDevList);
         if (OC_STACK_OK != result)
@@ -233,6 +250,7 @@ JNIEXPORT jobjectArray JNICALL Java_org_iotivity_base_OcProvisioning_getDeviceSt
     {
         LOGE("%s", e.reason().c_str());
         ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        return nullptr;
     }
 }
 
index 4d15fe0..9e6925a 100644 (file)
@@ -1485,4 +1485,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 b871176..0781d9f 100644 (file)
@@ -42,7 +42,7 @@ void JniOcResourceResponse::setErrorCode(const int eCode)
 
 std::string JniOcResourceResponse::getNewResourceUri(void)
 {
-    this->m_response->getNewResourceUri();
+    return this->m_response->getNewResourceUri();
 }
 
 void
index f06b9bb..77c8dc6 100644 (file)
@@ -211,12 +211,14 @@ OCStackResult JniOcSecureResource::provisionACL(JNIEnv* env, jobject _acl, jobje
     OCStackResult ret;
     JniProvisionResultListner *resultListener = AddProvisionResultListener(env, jListener);
     OicSecAcl_t *acl = new OicSecAcl_t;
-    acl->next = nullptr;
+
     if (!acl)
     {
         return OC_STACK_NO_MEMORY;
     }
 
+    acl->next = nullptr;
+
     if (OC_STACK_OK != JniSecureUtils::convertJavaACLToOCAcl(env, _acl, acl))
     {
         delete acl;
@@ -354,6 +356,12 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_removeDevice
 (JNIEnv *env, jobject thiz, jint timeout, jobject jListener)
 {
     LOGD("OcSecureResource_removeDevice");
+    if (timeout < 0)
+    {
+        ThrowOcException(OC_STACK_INVALID_PARAM, "Timeout value cannot be negative");
+        return;
+    }
+
     if (!jListener)
     {
         ThrowOcException(OC_STACK_INVALID_PARAM, "provisionResultListener cannot be null");
@@ -564,6 +572,7 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcSecureResource_getLinkedDevic
     {
         LOGE("%s", e.reason().c_str());
         ThrowOcException(e.code(), e.reason().c_str());
+        return nullptr;
     }
 }
 
index affc4dd..c5c3d7d 100644 (file)
@@ -102,8 +102,7 @@ jmethodID g_mid_OcOicSecAcl_get_permission = nullptr;
 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_owners_cnt = nullptr;
-jmethodID g_mid_OcOicSecAcl_get_owners = nullptr;
+jmethodID g_mid_OcOicSecAcl_get_rownerID = nullptr;
 
 jobject getOcException(JNIEnv* env, const char* file, const char* functionName,
     const int line, const int code, const char* message)
@@ -458,11 +457,8 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
     g_mid_OcOicSecAcl_get_recurrences = env->GetMethodID(g_cls_OcOicSecAcl, "getRecurrences", "(I)Ljava/lang/String;");
     if (!g_mid_OcOicSecAcl_get_recurrences) return JNI_ERR;
 
-    g_mid_OcOicSecAcl_get_owners_cnt = env->GetMethodID(g_cls_OcOicSecAcl, "getOwnersCount", "()I");
-    if (!g_mid_OcOicSecAcl_get_owners_cnt) return JNI_ERR;
-
-    g_mid_OcOicSecAcl_get_owners = env->GetMethodID(g_cls_OcOicSecAcl, "getOwners", "(I)Ljava/lang/String;");
-    if (!g_mid_OcOicSecAcl_get_owners) return JNI_ERR;
+    g_mid_OcOicSecAcl_get_rownerID = env->GetMethodID(g_cls_OcOicSecAcl, "getRownerID", "()Ljava/lang/String;");
+    if (!g_mid_OcOicSecAcl_get_rownerID) return JNI_ERR;
 
     return JNI_CURRENT_VERSION;
 }
index 79ede36..b9f2ccd 100644 (file)
@@ -121,8 +121,7 @@ extern jmethodID g_mid_OcOicSecAcl_get_permission;
 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_owners_cnt;
-extern jmethodID g_mid_OcOicSecAcl_get_owners;
+extern jmethodID g_mid_OcOicSecAcl_get_rownerID;
 
 typedef void(*RemoveListenerCallback)(JNIEnv* env, jobject jListener);
 
index dc7ca43..24e4f57 100644 (file)
@@ -22,6 +22,7 @@
 
 #include "JniSecureUtils.h"
 #include "JniOcSecureResource.h"
+#include "srmutility.h"
 #include "base64.h"
 
 jobject JniSecureUtils::convertProvisionresultVectorToJavaList(JNIEnv *env, const OC::PMResultList_t *result)
@@ -107,16 +108,6 @@ std::string JniSecureUtils::convertUUIDtoStr(OicUuid_t uuid)
     return deviceId.str();
 }
 
-void JniSecureUtils::convertStrToUUID(char *str, OicUuid_t &uuid)
-{
-    unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
-    uint32_t outLen = 0;
-    B64Result b64Ret = B64_OK;
-
-    b64Ret = b64Decode(str, strlen(str), base64Buff, sizeof(base64Buff), &outLen);
-    memcpy(uuid.id, base64Buff, outLen);
-}
-
 jobject JniSecureUtils::convertUUIDVectorToJavaStrList(JNIEnv *env, UuidList_t &vector)
 {
     jobject jList = env->NewObject(g_cls_LinkedList, g_mid_LinkedList_ctor);
@@ -153,8 +144,14 @@ OCStackResult JniSecureUtils::convertJavaACLToOCAcl(JNIEnv *env, jobject in, Oic
     }
 
     char *str = (char*) env->GetStringUTFChars(jData, 0);
-    convertStrToUUID(str, acl->subject);
-    env->ReleaseStringUTFChars(jData, str);
+    if (OC_STACK_OK == ConvertStrToUuid(str, &acl->subject))
+    {
+        env->ReleaseStringUTFChars(jData, str);
+    }
+    else
+    {
+        return OC_STACK_ERROR;
+    }
 
     jint jCount = (jint) env->CallIntMethod(in, g_mid_OcOicSecAcl_get_resources_cnt);
     if (!jCount || env->ExceptionCheck())
@@ -216,31 +213,22 @@ OCStackResult JniSecureUtils::convertJavaACLToOCAcl(JNIEnv *env, jobject in, Oic
         acl->recurrences[i] = (char*) env->GetStringUTFChars(jData, 0);
     }
 
-    jCount = (jint) env->CallIntMethod(in, g_mid_OcOicSecAcl_get_owners_cnt);
-    if (!jCount ||  env->ExceptionCheck())
+    jData = (jstring) env->CallObjectMethod(in, g_mid_OcOicSecAcl_get_rownerID);
+    if (!jData || env->ExceptionCheck())
     {
         return OC_STACK_ERROR;
     }
 
-    acl->ownersLen = jCount;
-    acl->owners = new OicUuid_t[acl->ownersLen];
-    if (!acl->owners)
-    {
-        return OC_STACK_ERROR;
-    }
+    str = (char*) env->GetStringUTFChars(jData, 0);
 
-    for (jint i = 0; i < jCount; ++i)
+    if (OC_STACK_OK == ConvertStrToUuid(str, &acl->rownerID))
     {
-        args[0].i = i;
-        jData = (jstring) env->CallObjectMethodA(in, g_mid_OcOicSecAcl_get_owners, args);
-        if (!jData ||  env->ExceptionCheck())
-        {
-            return OC_STACK_ERROR;
-        }
-
-        str = (char*) env->GetStringUTFChars(jData, 0);
-        convertStrToUUID(str, acl->owners[i]);
         env->ReleaseStringUTFChars(jData, str);
     }
+    else
+    {
+        return OC_STACK_ERROR;
+    }
+
     return OC_STACK_OK;
 }
index 25e769c..fcfa2a1 100644 (file)
@@ -209,6 +209,9 @@ public:
             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:
index 5433c86..bba664e 100644 (file)
@@ -61,6 +61,9 @@ public enum ErrorCode {
     PDM_IS_NOT_INITIALIZED("PDM_IS_NOT_INITIALIZED", ""),
     DUPLICATE_UUID("DUPLICATE_UUID", ""),
     INCONSISTENT_DB("INCONSISTENT_DB", ""),
+    /** Error code from OTM */
+    AUTHENTICATION_FAILURE("AUTHENTICATION_FAILURE",
+        "This error is pushed from DTLS interface when handshake failure happens"),
     /** Insert all new error codes here!.*/
     PRESENCE_STOPPED("PRESENCE_STOPPED", ""),
     PRESENCE_TIMEOUT("PRESENCE_TIMEOUT", ""),
index 7d42144..2d42a3e 100644 (file)
@@ -41,6 +41,12 @@ public enum OcConnectivityType {
     /** Remote Access over XMPP.*/
     CT_ADAPTER_REMOTE_ACCESS(1 << 19),
 
+    /** CoAP over TCP.*/
+    CT_ADAPTER_TCP(1 << 20),
+
+    /** NFC Transport.*/
+    CT_ADAPTER_NFC(1 << 21),
+
     /** Insecure transport is the default (subject to change).*/
 
     /** secure the transport path.*/
@@ -108,4 +114,21 @@ public enum OcConnectivityType {
 
         return typeSet;
     }
-}
+
+    public static OcConnectivityType getInstance(int caTransportAdapter) {
+        switch (caTransportAdapter) {
+            case (1 << 0):
+                return CT_ADAPTER_IP;
+            case (1 << 1):
+                return CT_ADAPTER_GATT_BTLE;
+            case (1 << 2):
+                return CT_ADAPTER_RFCOMM_BTEDR;
+            case (1 << 3):
+                return CT_ADAPTER_REMOTE_ACCESS;
+            case (1 << 4):
+                return CT_ADAPTER_TCP;
+            default:
+                return CT_DEFAULT;
+        }
+    }
+}
\ No newline at end of file
index 8733878..c8678ff 100644 (file)
@@ -23,6 +23,7 @@
 package org.iotivity.base;
 
 import org.iotivity.ca.CaInterface;
+import org.iotivity.base.BuildConfig;
 
 import java.util.EnumSet;
 import java.util.Iterator;
@@ -40,6 +41,10 @@ public final class OcPlatform {
         System.loadLibrary("octbstack");
         System.loadLibrary("connectivity_abstraction");
         System.loadLibrary("oc");
+        if (0 != BuildConfig.SECURED)
+        {
+            System.loadLibrary("ocprovision");
+        }
         System.loadLibrary("ocstack-jni");
     }
 
@@ -85,7 +90,7 @@ public final class OcPlatform {
      */
     public synchronized static void Configure(PlatformConfig platformConfig) {
         if (!sIsPlatformInitialized) {
-            CaInterface.initialize(platformConfig.getContext());
+            CaInterface.initialize(platformConfig.getActivity(), platformConfig.getContext());
 
             sPlatformQualityOfService = platformConfig.getQualityOfService();
 
index 5ca6d96..a47ffaa 100644 (file)
@@ -33,16 +33,16 @@ public class OicSecAcl implements Serializable {
     private List<String> resources;
     private List<String> periods;
     private List<String> recurrences;
-    private List<String> owners;
+    private String rownerID;
 
     public OicSecAcl(String subject, List<String> recurrences, List<String> periods, int permission,
-            List<String> resources, List<String> owners) {
+            List<String> resources, String rownerID) {
         this.subject = subject;
         this.recurrences = recurrences;
         this.periods = periods;
         this.permission = permission;
         this.resources = resources;
-        this.owners = owners;
+        this.rownerID = rownerID;
     }
 
     public String getSubject() {
@@ -53,12 +53,9 @@ public class OicSecAcl implements Serializable {
         this.subject = subject;
     }
 
-    public List<String> getOwners() {
-        return owners;
-    }
 
-    public void setOwners(List<String> owners) {
-        this.owners = owners;
+    public void setRownerID(String rownerID) {
+        this.rownerID = rownerID;
     }
 
     public List<String> getRecurrences() {
@@ -113,11 +110,7 @@ public class OicSecAcl implements Serializable {
         return this.recurrences.get(i);
     }
 
-    public int getOwnersCount() {
-        return this.owners.size();
-    }
-
-    public String getOwners(int i) {
-        return this.owners.get(i);
+    public String getRownerID() {
+        return this.rownerID;
     }
 }
index 4ffacd4..487f6a9 100644 (file)
 package org.iotivity.base;
 
 import android.content.Context;
+import android.app.Activity;
 
 /**
  * Data structure to provide the configuration.
  */
 public class PlatformConfig {
-
+    private Activity mActivity;
     private Context mContext;
     private ServiceType mServiceType;
     private ModeType mModeType;
@@ -37,8 +38,8 @@ public class PlatformConfig {
     private QualityOfService mQualityOfService;
     private String mSvrDbPath; //TODO: Instead of SVRDB file, it should be Persistent Storage.
                               //this is only for 0.9.2
-
     /**
+     * @param activity         app activity
      * @param context          app context
      * @param serviceType      indicate IN_PROC or OUT_OF_PROC
      * @param modeType         indicate whether we want to do server, client or both
@@ -51,13 +52,15 @@ public class PlatformConfig {
      * @param qualityOfService quality of service
      * @param dbPath           Persistant storage file for SVR Database.
      */
-    public PlatformConfig(Context context,
+    public PlatformConfig(Activity activity,
+                          Context context,
                           ServiceType serviceType,
                           ModeType modeType,
                           String ipAddress,
                           int port,
                           QualityOfService qualityOfService,
                           String dbPath) {
+        this.mActivity=activity;
         this.mContext = context;
         this.mServiceType = serviceType;
         this.mModeType = modeType;
@@ -78,17 +81,63 @@ public class PlatformConfig {
      *                         if you specify 5683 : client discovery can work even if they don't
      *                         specify port
      * @param qualityOfService quality of service
+     * @param dbPath           Persistant storage file for SVR Database.
+     */
+    public PlatformConfig(Context context,
+                          ServiceType serviceType,
+                          ModeType modeType,
+                          String ipAddress,
+                          int port,
+                          QualityOfService qualityOfService,
+                          String dbPath) {
+        this(null,context,serviceType,modeType,ipAddress,port,qualityOfService, dbPath);
+    }
+
+    /**
+     * @param context          app context
+     * @param serviceType      indicate IN_PROC or OUT_OF_PROC
+     * @param modeType         indicate whether we want to do server, client or both
+     * @param ipAddress        ip address of server
+     *                         if you specify 0.0.0.0 : it listens on any interface
+     * @param port             port of server
+     *                         if you specifiy 0 : next available random port is used
+     *                         if you specify 5683 : client discovery can work even if they don't
+     *                         specify port
+     * @param qualityOfService quality of service
      */
-    //Avoid breaking building java samples due to persistent storage SVR DB changes.
+    // Avoid breaking building java samples due to persistent storage SVR DB changes.
     public PlatformConfig(Context context,
                           ServiceType serviceType,
                           ModeType modeType,
                           String ipAddress,
                           int port,
                           QualityOfService qualityOfService) {
-        this(context,serviceType,modeType,ipAddress,port,qualityOfService, "");
+        this(null,context,serviceType,modeType,ipAddress,port,qualityOfService, "");
     }
 
+    /**
+     * @param activity         app activity
+     * @param context          app context
+     * @param serviceType      indicate IN_PROC or OUT_OF_PROC
+     * @param modeType         indicate whether we want to do server, client or both
+     * @param ipAddress        ip address of server
+     *                         if you specify 0.0.0.0 : it listens on any interface
+     * @param port             port of server
+     *                         if you specifiy 0 : next available random port is used
+     *                         if you specify 5683 : client discovery can work even if they don't
+     *                         specify port
+     * @param qualityOfService quality of service
+     */
+    // Avoid breaking building java samples due to persistent storage SVR DB changes.
+    public PlatformConfig(Activity activity,
+                          Context context,
+                          ServiceType serviceType,
+                          ModeType modeType,
+                          String ipAddress,
+                          int port,
+                          QualityOfService qualityOfService) {
+        this(activity,context,serviceType,modeType,ipAddress,port,qualityOfService, "");
+    }
     public Context getContext() {
         return mContext;
     }
@@ -116,4 +165,9 @@ public class PlatformConfig {
     public String getSvrDbPath() {
         return mSvrDbPath;
     }
+
+    public Activity getActivity() {
+        return mActivity;
+    }
+
 }
diff --git a/android/android_api/base/src/main/java/org/iotivity/ca/CaBtPairingInterface.java b/android/android_api/base/src/main/java/org/iotivity/ca/CaBtPairingInterface.java
new file mode 100644 (file)
index 0000000..57b8738
--- /dev/null
@@ -0,0 +1,105 @@
+/******************************************************************
+ *
+ * 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.ca;
+
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothDevice;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+
+public class CaBtPairingInterface {
+    private static Context mContext;
+
+    private CaBtPairingInterface(Context context) {
+        mContext = context;
+        registerIntentFilter();
+    }
+
+    private static IntentFilter registerIntentFilter() {
+        IntentFilter filter = new IntentFilter();
+        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
+        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
+        filter.addAction(BluetoothDevice.ACTION_FOUND);
+        mContext.registerReceiver(mReceiver, filter);
+        return filter;
+    }
+
+    public static void destroyEdrInterface() {
+        mContext.unregisterReceiver(mReceiver);
+    }
+
+    private native static void oicEdrStateChangedCallback(int state);
+
+    private native static void oicEdrBondStateChangedCallback(String addr);
+
+    private native static void oicEdrFoundDeviceCallback(BluetoothDevice device);
+
+    private static final BroadcastReceiver mReceiver = new BroadcastReceiver() {
+
+        @Override
+        public void onReceive(Context context, Intent intent) {
+
+            String action = intent.getAction();
+
+            if (action != null && action.equals(BluetoothDevice.ACTION_FOUND)) {
+                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
+
+                // if found device is not paired with this device
+                if (device.getBondState() != BluetoothDevice.BOND_BONDED)
+                {
+                    oicEdrFoundDeviceCallback(device);
+                }
+            }
+
+            if (action != null && action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
+
+                int state =
+                        intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
+
+                // STATE_ON:12, STATE_OFF:10
+                if (state == BluetoothAdapter.STATE_ON || state == BluetoothAdapter.STATE_OFF)
+                {
+                    oicEdrStateChangedCallback(state);
+                }
+            }
+
+            if (action != null && action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
+
+                int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE,
+                                                   BluetoothDevice.ERROR);
+
+                // unpairing event
+                if (bondState == BluetoothDevice.BOND_NONE) {
+                    if ((intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE,
+                                            BluetoothDevice.ERROR)
+                                                == BluetoothDevice.BOND_BONDED)) {
+                        BluetoothDevice device
+                            = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
+
+                        oicEdrBondStateChangedCallback(device.getAddress());
+                    }
+                }
+            }
+        }
+    };
+}
index 1e4d47c..7a07b24 100644 (file)
@@ -28,20 +28,25 @@ import android.content.Intent;
 import android.content.IntentFilter;
 
 public class CaEdrInterface {
+    private static Context mContext;
 
     private CaEdrInterface(Context context) {
-
-        registerIntentFilter(context);
+        mContext = context;
+        registerIntentFilter();
     }
 
-    private static IntentFilter registerIntentFilter(Context context) {
+    private static IntentFilter registerIntentFilter() {
         IntentFilter filter = new IntentFilter();
         filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
         filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
-        context.registerReceiver(mReceiver, filter);
+        mContext.registerReceiver(mReceiver, filter);
         return filter;
     }
 
+    public static void destroyEdrInterface() {
+        mContext.unregisterReceiver(mReceiver);
+    }
+
     // Network Monitor
     private native static void caEdrStateChangedCallback(int state);
 
index 196fadf..3711f97 100644 (file)
 package org.iotivity.ca;
 
 import android.content.Context;
+import android.app.Activity;
+import android.bluetooth.BluetoothDevice;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcConnectivityType;
 
 public class CaInterface {
     static {
         System.loadLibrary("connectivity_abstraction");
         System.loadLibrary("ca-interface");
     }
+    private static volatile boolean isConnectionManagerInitialized = false;
+    private static volatile boolean isBtPairingInitialized = false;
 
-    public static native void initialize(Context context);
+    public static native void initialize(Activity activity, Context context);
+
+    /**
+     *  Method start connection manager service.
+     *  this method has to be called before other API call.
+     *  @param context                                application context
+     *  @param onConnectionManagerStateListener       connection state callback listener
+     */
+    public synchronized static void startManagerService(Context context,
+            OnConnectionManagerStateListener onConnectionManagerStateListener) {
+        if (!isConnectionManagerInitialized) {
+            CaInterface.caManagerInitialize(context, onConnectionManagerStateListener);
+            isConnectionManagerInitialized = true;
+        }
+    }
+
+    /**
+     *  Method stop connection manager service.
+     *  this method must be called, when Application is destroied.
+     */
+    public synchronized static void stopManagerService() {
+        if (isConnectionManagerInitialized) {
+            CaInterface.caManagerTerminate();
+            isConnectionManagerInitialized = false;
+        }
+    }
+
+    /**
+     *  Method set device information for Auto-Connection.
+     *  this method has to be called before FindResource is called.
+     *  @param address                      LE address of scanned bluetooth device.
+     */
+    public synchronized static void setAutoConnectionDevice(String address)
+            throws OcException {
+        CaInterface.initCheckForConnectionManager();
+        CaInterface.caManagerSetAutoConnectionDeviceInfo(address);
+    }
+
+    /**
+     *  Method unset device information for Auto-Connection.
+     *  @param address                      LE address of scanned bluetooth device.
+     */
+    public synchronized static void unsetAutoConnectionDevice(String address)
+            throws OcException {
+        CaInterface.initCheckForConnectionManager();
+        CaInterface.caManagerUnsetAutoConnectionDeviceInfo(address);
+    }
+
+    /**
+     *  Interface for connection manager state listener.
+     *  Event listeners are notified asynchronously.
+     */
+    public interface OnConnectionManagerStateListener {
+        public void onAdapterStateChanged(OcConnectivityType type, boolean enabled);
+        public void onConnectionStateChanged(OcConnectivityType type, String address,
+                boolean connected);
+    }
+
+    private static void initCheckForConnectionManager() {
+        if (!isConnectionManagerInitialized) {
+            throw new IllegalStateException("ConnectionManager must be started by making "
+                    + "a call to CaInterface.startManagerService before any other API "
+                    + "calls are permitted");
+        }
+    }
+
+    private static native void caManagerInitialize(Context context,
+            OnConnectionManagerStateListener onConnectionManagerStateListener);
+    private static native void caManagerTerminate();
+    private static native void caManagerSetAutoConnectionDeviceInfo(String address);
+    private static native void caManagerUnsetAutoConnectionDeviceInfo(String address);
+
+    /**
+     *  start bluetooth pairing service.
+     *  @param context                      application context
+     */
+    public synchronized static void startBtPairingService(Context context,
+            OnBtDeviceFoundListener listener) {
+        if (!isBtPairingInitialized) {
+            CaInterface.caBtPairingInitialize(context, listener);
+
+            isBtPairingInitialized = true;
+        }
+    }
+
+    /**
+     *  stop bluetooth pairing service.
+     */
+    public synchronized static void stopBtPairingService() {
+        if (isBtPairingInitialized) {
+            CaInterface.caBtPairingTerminate();
+
+            isBtPairingInitialized = false;
+        }
+    }
+
+    /**
+     *  start bluetooth device scan.
+     */
+    public synchronized static void startScan()
+            throws OcException {
+        CaInterface.initCheckForBtPairingUtil();
+        CaInterface.caBtPairingStartScan();
+    }
+
+    /**
+     *  stop bluetooth device scan.
+     */
+    public synchronized static void stopScan()
+            throws OcException {
+        CaInterface.initCheckForBtPairingUtil();
+        CaInterface.caBtPairingStopScan();
+    }
+
+    /**
+     *  create bond
+     */
+    public synchronized static void createBond(BluetoothDevice device)
+            throws OcException {
+        CaInterface.initCheckForBtPairingUtil();
+        CaInterface.caBtPairingCreateBond(device);
+    }
+
+    public interface OnBtDeviceFoundListener {
+        public void onBtDeviceFound(BluetoothDevice device) throws OcException;
+    }
+
+    private static void initCheckForBtPairingUtil() {
+        if (!isBtPairingInitialized) {
+            throw new IllegalStateException("BT pairing Util must be started by making "
+                    + "a call to CaInterface.startBtPairingService before any other API "
+                    + "calls are permitted");
+        }
+    }
+
+    private static native void caBtPairingInitialize(Context context,
+            OnBtDeviceFoundListener listener);
+    private static native void caBtPairingTerminate();
+    private static native void caBtPairingStartScan();
+    private static native void caBtPairingStopScan();
+    private static native void caBtPairingCreateBond(BluetoothDevice device);
 }
\ No newline at end of file
index a011dfe..81ab7d5 100644 (file)
@@ -66,6 +66,10 @@ public class CaIpInterface {
         mContext.registerReceiver(mReceiver, intentFilter);\r
     }\r
 \r
+    public static void destroyIpInterface() {\r
+        mContext.unregisterReceiver(mReceiver);\r
+    }\r
+\r
     private static BroadcastReceiver mReceiver = new BroadcastReceiver() {\r
         @Override\r
         public void onReceive(Context context, Intent intent) {\r
index ef20573..0801bdb 100644 (file)
@@ -42,13 +42,13 @@ public class CaLeClientInterface {
 
     private static String SERVICE_UUID = "ADE3D529-C784-4F63-A987-EB69F70EE816";
     private static String TAG          = "Sample_Service : CaLeClientInterface";
+    private static Context mContext;
 
     private CaLeClientInterface(Context context) {
-
         caLeRegisterLeScanCallback(mLeScanCallback);
         caLeRegisterGattCallback(mGattCallback);
-
-        registerIntentFilter(context);
+        mContext = context;
+        registerIntentFilter();
     }
 
     public static void getLeScanCallback() {
@@ -59,14 +59,18 @@ public class CaLeClientInterface {
         caLeRegisterGattCallback(mGattCallback);
     }
 
-    private static IntentFilter registerIntentFilter(Context context) {
+    private static IntentFilter registerIntentFilter() {
         IntentFilter filter = new IntentFilter();
         filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
         filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
-        context.registerReceiver(mReceiver, filter);
+        mContext.registerReceiver(mReceiver, filter);
         return filter;
     }
 
+    public static void destroyLeInterface() {
+        mContext.unregisterReceiver(mReceiver);
+    }
+
     private native static void caLeRegisterLeScanCallback(BluetoothAdapter.LeScanCallback callback);
 
     private native static void caLeRegisterGattCallback(BluetoothGattCallback callback);
@@ -78,6 +82,13 @@ public class CaLeClientInterface {
     private native static void caLeGattConnectionStateChangeCallback(
             BluetoothGatt gatt, int status, int newState);
 
+    // BluetoothGattCallback for Connection Manager
+    private native static void caManagerLeGattConnectionStateChangeCB(
+            BluetoothGatt gatt, int status, int newState);
+
+    private native static void caLeGattNWConnectionStateChangeCallback(
+            BluetoothGatt gatt, int status, int newState);
+
     private native static void caLeGattServicesDiscoveredCallback(BluetoothGatt gatt, int status);
 
     private native static void caLeGattCharacteristicWriteCallback(
@@ -100,6 +111,18 @@ public class CaLeClientInterface {
     // bond state
     private native static void caLeBondStateChangedCallback(String address);
 
+    // adapter state
+    private native static void caManagerAdapterStateChangedCallback(int state);
+
+    // bond state
+    private native static void caManagerBondStateChangedCallback(BluetoothDevice address);
+
+    private native static void caManagerLeServicesDiscoveredCallback(BluetoothGatt gatt,
+                                                                     int status);
+
+    private native static void caManagerLeRemoteRssiCallback(BluetoothGatt gatt, int rssi,
+                                                             int status);
+
     // Callback
     private static BluetoothAdapter.LeScanCallback mLeScanCallback =
                    new BluetoothAdapter.LeScanCallback() {
@@ -113,6 +136,7 @@ public class CaLeClientInterface {
                     Log.d(TAG, "UUID : " + uuid.toString());
                     if(uuid.toString().contains(SERVICE_UUID.toLowerCase())) {
                         Log.d(TAG, "we found that has the Device");
+                        Log.d(TAG, "scanned device address : " + device.getAddress());
                         caLeScanCallback(device);
                     }
                 }
@@ -177,6 +201,8 @@ public class CaLeClientInterface {
             super.onConnectionStateChange(gatt, status, newState);
 
             caLeGattConnectionStateChangeCallback(gatt, status, newState);
+            caManagerLeGattConnectionStateChangeCB(gatt, status, newState);
+            caLeGattNWConnectionStateChangeCallback(gatt, status, newState);
         }
 
         @Override
@@ -184,6 +210,7 @@ public class CaLeClientInterface {
             super.onServicesDiscovered(gatt, status);
 
             caLeGattServicesDiscoveredCallback(gatt, status);
+            caManagerLeServicesDiscoveredCallback(gatt, status);
         }
 
         @Override
@@ -230,6 +257,7 @@ public class CaLeClientInterface {
         @Override
         public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
             super.onReadRemoteRssi(gatt, rssi, status);
+            caManagerLeRemoteRssiCallback(gatt, rssi, status);
         }
     };
 
@@ -245,9 +273,11 @@ public class CaLeClientInterface {
                 int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                                                BluetoothAdapter.ERROR);
 
-                if (state == BluetoothAdapter.STATE_ON || state == BluetoothAdapter.STATE_OFF)
+                if (state == BluetoothAdapter.STATE_ON || state == BluetoothAdapter.STATE_OFF
+                        || state == BluetoothAdapter.STATE_TURNING_OFF)
                 {
                     caLeStateChangedCallback(state);
+                    caManagerAdapterStateChangedCallback(state);
                 }
             }
 
@@ -262,6 +292,7 @@ public class CaLeClientInterface {
                             BluetoothDevice device = intent
                                 .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
 
+                        caManagerBondStateChangedCallback(device);
                         caLeBondStateChangedCallback(device.getAddress());
                     }
                 }
index 281beac..0a4bb5c 100644 (file)
@@ -52,6 +52,9 @@ public class CaLeServerInterface {
     private native static void caLeGattServerConnectionStateChangeCallback(
             BluetoothDevice device, int status, int newState);
 
+    private native static void caLeGattServerNWConnectionStateChangeCallback(
+            BluetoothDevice device, int status, int newState);
+
     private native static void caLeGattServerServiceAddedCallback(int status,
                                                                   BluetoothGattService service);
 
@@ -79,6 +82,7 @@ public class CaLeServerInterface {
             super.onConnectionStateChange(device, status, newState);
 
             caLeGattServerConnectionStateChangeCallback(device, status, newState);
+            caLeGattServerNWConnectionStateChangeCallback(device, status, newState);
         }
 
         @Override
diff --git a/android/android_api/base/src/main/java/org/iotivity/ca/CaNfcInterface.java b/android/android_api/base/src/main/java/org/iotivity/ca/CaNfcInterface.java
new file mode 100644 (file)
index 0000000..ebb273b
--- /dev/null
@@ -0,0 +1,140 @@
+/* *****************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+package org.iotivity.ca;
+
+import java.util.ArrayList;
+
+import android.app.Activity;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.app.PendingIntent;
+import android.content.IntentFilter.MalformedMimeTypeException;
+import android.net.NetworkInfo;
+import android.nfc.NdefMessage;
+import android.nfc.NdefRecord;
+import android.nfc.NfcAdapter;
+import android.nfc.NfcEvent;
+import android.os.Parcelable;
+import android.util.Log;
+
+
+
+public class CaNfcInterface implements NfcAdapter.CreateNdefMessageCallback {
+    private final static String MYTAG = CaNfcInterface.class.getSimpleName();
+    private static Context mContext;
+    private Activity  mActivity;
+    private NfcAdapter mAdapter;
+    private NdefMessage mMessage;
+    private boolean misInvokeBeam;
+
+    private CaNfcInterface(Context context, Activity activity) {
+        Log.d(MYTAG, "NFC  registerNfcReceiver");
+        mContext = context;
+        mActivity = activity;
+
+        mAdapter = NfcAdapter.getDefaultAdapter(mContext);
+        if (null == mAdapter)
+        {
+            Log.e(MYTAG, "Failed to get the Adapter");
+            return;
+        }
+    }
+
+    private native static void caNativeNfcPacketReceived(byte[] receivedData);
+    private native static NdefMessage caNativeNfcCreateNdefMessage(byte[] sendData);
+    private native static boolean caNativeNfcInvokeBeam();
+
+    @Override
+    public NdefMessage createNdefMessage(NfcEvent event) {
+        Log.d(MYTAG, "NFC  createNdefMessage");
+
+        // Returns the already created message
+        return mMessage;
+    }
+
+    public void processSendRquest(byte[] sendData) {
+
+        Log.d(MYTAG, "NFC  processSendRquest IN");
+
+        mMessage = caNativeNfcCreateNdefMessage(sendData);
+        misInvokeBeam = caNativeNfcInvokeBeam();
+
+        if (!misInvokeBeam)
+        {
+            Log.e(MYTAG, "NFC  Beam error");
+        }
+    }
+
+    public void caNfcInitialize() {
+        Log.d(MYTAG, "caNfcInitialize");
+
+        if ((null == mActivity) || (null == mContext) || (null == mAdapter)) {
+            Log.e(MYTAG, "caNfcInitialize failed, invalid parameters");
+            return;
+        }
+
+        PendingIntent pendingIntent = PendingIntent.getActivity(mActivity, 0,
+                                                    new Intent(mActivity, mActivity.getClass())
+                                                    .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
+                                                    | Intent.FLAG_ACTIVITY_CLEAR_TOP), 0);
+
+        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
+
+        try {
+            ndef.addDataType("*/*");    /* Handles all MIME based dispatches.
+                                           You should specify only the ones that you need. */
+        } catch (MalformedMimeTypeException e) {
+            throw new RuntimeException("fail", e);
+        }
+
+        IntentFilter[] intentFiltersArray = new IntentFilter[] {ndef, };
+
+        mAdapter.enableForegroundDispatch(mActivity, pendingIntent, intentFiltersArray, null);
+        Log.d(MYTAG, " enableForegroundDispatch ");
+
+        mContext.registerReceiver(mReceiver, new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED));
+        Log.d(MYTAG, "NFC  caNfcInitialize OUT");
+    }
+
+    private static BroadcastReceiver mReceiver = new BroadcastReceiver() {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            Log.d(MYTAG, "onReceive broadcast intent updated - disable callback");
+
+            if (intent.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED))
+            {
+                processIntent(intent);
+            }
+        }
+
+        private void processIntent(Intent intent) {
+
+            Log.d(MYTAG, "processIntent");
+            Parcelable[] rawMsgs = intent
+                    .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
+            NdefMessage msg = (NdefMessage) rawMsgs[0];
+            Log.d(MYTAG, msg.getRecords()[0].toMimeType().toString());
+            caNativeNfcPacketReceived(msg.getRecords()[0].getPayload());
+        }
+    };
+}
index ee457b3..c67ee6b 100644 (file)
         <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="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
-        <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugTest" />
-        <option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugTestSources" />
-        <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />
+        <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" />
@@ -24,9 +26,9 @@
       </configuration>
     </facet>
   </component>
-  <component name="NewModuleRootManager" inherit-compiler-output="false">
+  <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/test/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/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/generated/debug" type="java-resource" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/test/debug" type="java-test-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" />
       <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 22 Platform" jdkType="Android SDK" />
+    <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
     <orderEntry type="sourceFolder" forTests="false" />
-    <orderEntry type="library" exported="" name="iotivity-armeabi-base-debug-unspecified" level="project" />
+    <orderEntry type="library" exported="" name="iotivity-base-armeabi-release-" level="project" />
+    <orderEntry type="library" exported="" name="android-android-21" level="project" />
   </component>
 </module>
\ No newline at end of file
index 56b2db8..9ab9ead 100644 (file)
         <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="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
-        <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugTest" />
-        <option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugTestSources" />
-        <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />
+        <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" />
@@ -24,9 +26,9 @@
       </configuration>
     </facet>
   </component>
-  <component name="NewModuleRootManager" inherit-compiler-output="false">
+  <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/test/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/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/generated/debug" type="java-resource" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/test/debug" type="java-test-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" />
       <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 22 Platform" jdkType="Android SDK" />
+    <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
     <orderEntry type="sourceFolder" forTests="false" />
-    <orderEntry type="library" exported="" name="iotivity-armeabi-base-debug-unspecified" level="project" />
+    <orderEntry type="library" exported="" name="iotivity-base-armeabi-release-" level="project" />
+    <orderEntry type="library" exported="" name="android-android-21" level="project" />
   </component>
 </module>
\ No newline at end of file
index c659f4f..2f8281b 100755 (executable)
@@ -7,18 +7,8 @@
         <option name="BUILDABLE" value="false" />\r
       </configuration>\r
     </facet>\r
-    <facet type="android-gradle" name="Android-Gradle">\r
-      <configuration>\r
-        <option name="GRADLE_PROJECT_PATH" value=":" />\r
-      </configuration>\r
-    </facet>\r
-    <facet type="android" name="Android">\r
-      <configuration>\r
-        <option name="ALLOW_USER_CONFIGURATION" value="false" />\r
-      </configuration>\r
-    </facet>\r
   </component>\r
-  <component name="NewModuleRootManager" inherit-compiler-output="true">\r
+  <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="true">\r
     <exclude-output />\r
     <content url="file://$MODULE_DIR$">\r
       <excludeFolder url="file://$MODULE_DIR$/.gradle" />\r
index 751d6d2..fed8552 100755 (executable)
@@ -32,4 +32,4 @@ try {
 } catch (all) {
     print "${ERROR_MSG}"
     assert all
-}
\ No newline at end of file
+}
old mode 100755 (executable)
new mode 100644 (file)
index cf42050..15ffbd0
         <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="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
         <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugAndroidTest" />
         <option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugAndroidTestSources" />
-        <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugAndroidTestSources" />
+        <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" />
@@ -24,7 +26,7 @@
       </configuration>
     </facet>
   </component>
-  <component name="NewModuleRootManager" inherit-compiler-output="false">
+  <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 />
@@ -69,7 +71,6 @@
       <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/exploded-aar/examples/iotivity-base-armeabi-release/unspecified/jars" />
       <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/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="module" module-name="iotivity-base-armeabi-release" exported="" />
-    <orderEntry type="library" exported="" name="iotivity-base-armeabi-release-unspecified" level="project" />
+    <orderEntry type="library" exported="" name="iotivity-base-armeabi-release-" level="project" />
+    <orderEntry type="library" exported="" name="android-android-21" level="project" />
   </component>
 </module>
\ No newline at end of file
index d72b630..9bcce28 100755 (executable)
@@ -32,4 +32,4 @@ try {
 } catch (all) {\r
     print "${ERROR_MSG}"\r
     assert all\r
-}
\ No newline at end of file
+}\r
index 930e26a..2afacf0 100755 (executable)
@@ -32,4 +32,4 @@ try {
 } catch (all) {
     print "${ERROR_MSG}"
     assert all
-}
\ No newline at end of file
+}
old mode 100755 (executable)
new mode 100644 (file)
index e479d5f..d5434e2
         <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="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
         <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugAndroidTest" />
         <option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugAndroidTestSources" />
-        <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugAndroidTestSources" />
+        <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" />
@@ -24,7 +26,7 @@
       </configuration>
     </facet>
   </component>
-  <component name="NewModuleRootManager" inherit-compiler-output="false">
+  <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 />
       <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="module" module-name="iotivity-base-armeabi-release" exported="" />
-    <orderEntry type="library" exported="" name="iotivity-base-armeabi-release-unspecified" level="project" />
+    <orderEntry type="library" exported="" name="iotivity-base-armeabi-release-" level="project" />
+    <orderEntry type="library" exported="" name="android-android-21" level="project" />
   </component>
 </module>
\ No newline at end of file
index 440b831..cd5063b 100644 (file)
         <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="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
-        <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugTest" />
-        <option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugTestSources" />
-        <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />
+        <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" />
@@ -24,9 +26,9 @@
       </configuration>
     </facet>
   </component>
-  <component name="NewModuleRootManager" inherit-compiler-output="false">
+  <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/test/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/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/generated/debug" type="java-resource" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/test/debug" type="java-test-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" />
       <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 22 Platform" jdkType="Android SDK" />
+    <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
     <orderEntry type="sourceFolder" forTests="false" />
-    <orderEntry type="library" exported="" name="iotivity-armeabi-base-debug-unspecified" level="project" />
+    <orderEntry type="library" exported="" name="iotivity-base-armeabi-release-" level="project" />
+    <orderEntry type="library" exported="" name="android-android-21" level="project" />
   </component>
 </module>
\ No newline at end of file
index b648b2f..25e9d88 100644 (file)
         <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="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
-        <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugTest" />
-        <option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugTestSources" />
-        <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />
+        <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" />
@@ -24,9 +26,9 @@
       </configuration>
     </facet>
   </component>
-  <component name="NewModuleRootManager" inherit-compiler-output="false">
+  <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/test/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/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/generated/debug" type="java-resource" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/test/debug" type="java-test-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" />
       <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 22 Platform" jdkType="Android SDK" />
+    <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
     <orderEntry type="sourceFolder" forTests="false" />
-    <orderEntry type="library" exported="" name="iotivity-armeabi-base-debug-unspecified" level="project" />
+    <orderEntry type="library" exported="" name="iotivity-base-armeabi-release-" level="project" />
+    <orderEntry type="library" exported="" name="android-android-21" level="project" />
   </component>
 </module>
\ No newline at end of file
index 668427c..a971e49 100644 (file)
@@ -1,92 +1,25 @@
-<?xml version="1.0" encoding="UTF-8"?>\r
-<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" type="JAVA_MODULE" version="4">\r
-  <component name="FacetManager">\r
-    <facet type="android-gradle" name="Android-Gradle">\r
-      <configuration>\r
-        <option name="GRADLE_PROJECT_PATH" value=":guiclient" />\r
-      </configuration>\r
-    </facet>\r
-    <facet type="android" name="Android">\r
-      <configuration>\r
-        <option name="SELECTED_BUILD_VARIANT" value="debug" />\r
-        <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />\r
-        <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />\r
-        <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugTest" />\r
-        <option name="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />\r
-        <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />\r
-        <option name="ALLOW_USER_CONFIGURATION" value="false" />\r
-        <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />\r
-        <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />\r
-        <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />\r
-        <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />\r
-      </configuration>\r
-    </facet>\r
-  </component>\r
-  <component name="NewModuleRootManager" inherit-compiler-output="false">\r
-    <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />\r
-    <exclude-output />\r
-    <content url="file://$MODULE_DIR$">\r
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />\r
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />\r
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />\r
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />\r
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />\r
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/debug" type="java-resource" />\r
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/test/debug" isTestSource="true" generated="true" />\r
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/test/debug" isTestSource="true" generated="true" />\r
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug" isTestSource="true" generated="true" />\r
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/test/debug" isTestSource="true" generated="true" />\r
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />\r
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/test/debug" type="java-test-resource" />\r
-      <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />\r
-      <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />\r
-      <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />\r
-      <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />\r
-      <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />\r
-      <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />\r
-      <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />\r
-      <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />\r
-      <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />\r
-      <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />\r
-      <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />\r
-      <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />\r
-      <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />\r
-      <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />\r
-      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />\r
-      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />\r
-      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />\r
-      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />\r
-      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />\r
-      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />\r
-      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />\r
-      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />\r
-      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />\r
-      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />\r
-      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />\r
-      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />\r
-      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />\r
-      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />\r
-      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />\r
-      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />\r
-      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />\r
-      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />\r
-      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />\r
-      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />\r
-      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />\r
-      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />\r
-      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />\r
-      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />\r
-      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />\r
-      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />\r
-      <excludeFolder url="file://$MODULE_DIR$/build/outputs" />\r
-      <excludeFolder url="file://$MODULE_DIR$/build/tmp" />\r
-    </content>\r
-    <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />\r
-    <orderEntry type="sourceFolder" forTests="false" />\r
-    <orderEntry type="library" exported="" name="support-annotations-21.0.2" level="project" />\r
-    <orderEntry type="library" exported="" name="support-v4-21.0.2" level="project" />\r
-    <orderEntry type="library" exported="" name="iotivity-armeabi-base-release-unspecified" level="project" />\r
-    <orderEntry type="library" exported="" name="appcompat-v7-21.0.2" level="project" />\r
-  </component>\r
-</module>\r
-\r
+<?xml version="1.0" encoding="UTF-8"?>
+<module external.linked.project.id=":guiclient" 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=":guiclient" />
+      </configuration>
+    </facet>
+    <facet type="java-gradle" name="Java-Gradle">
+      <configuration>
+        <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />
+        <option name="BUILDABLE" value="false" />
+      </configuration>
+    </facet>
+  </component>
+  <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="true">
+    <exclude-output />
+    <content url="file://$MODULE_DIR$">
+      <excludeFolder url="file://$MODULE_DIR$/.gradle" />
+      <excludeFolder url="file://$MODULE_DIR$/build" />
+    </content>
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+  </component>
+</module>
\ No newline at end of file
index e92011c..f7aaab7 100644 (file)
         <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="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
-        <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugTest" />
-        <option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugTestSources" />
-        <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />
+        <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" />
@@ -24,9 +26,9 @@
       </configuration>
     </facet>
   </component>
-  <component name="NewModuleRootManager" inherit-compiler-output="false">
+  <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/test/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/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/generated/debug" type="java-resource" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/test/debug" type="java-test-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" />
       <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 22 Platform" jdkType="Android SDK" />
+    <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
     <orderEntry type="sourceFolder" forTests="false" />
-    <orderEntry type="library" exported="" name="iotivity-armeabi-base-debug-unspecified" level="project" />
+    <orderEntry type="library" exported="" name="iotivity-base-armeabi-release-" level="project" />
+    <orderEntry type="library" exported="" name="android-android-21" level="project" />
   </component>
 </module>
\ No newline at end of file
index 7b8aee8..5764176 100644 (file)
         <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="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
-        <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugTest" />
-        <option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugTestSources" />
-        <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />
+        <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" />
@@ -24,9 +26,9 @@
       </configuration>
     </facet>
   </component>
-  <component name="NewModuleRootManager" inherit-compiler-output="false">
+  <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/test/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/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/generated/debug" type="java-resource" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/test/debug" type="java-test-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" />
       <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 22 Platform" jdkType="Android SDK" />
+    <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
     <orderEntry type="sourceFolder" forTests="false" />
-    <orderEntry type="library" exported="" name="iotivity-armeabi-base-debug-unspecified" level="project" />
+    <orderEntry type="library" exported="" name="iotivity-base-armeabi-release-" level="project" />
+    <orderEntry type="library" exported="" name="android-android-21" level="project" />
   </component>
 </module>
\ No newline at end of file
index c44426e..f96f777 100644 (file)
@@ -1,9 +1,9 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<module 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">
+<module external.linked.project.id=":provisioningclient" 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=":secureprovisionclient" />
+        <option name="GRADLE_PROJECT_PATH" value=":provisioningclient" />
       </configuration>
     </facet>
     <facet type="android" name="Android">
         <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="assembleDebugTest" />
-        <option name="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
-        <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />
+        <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" />
@@ -23,9 +26,9 @@
       </configuration>
     </facet>
   </component>
-  <component name="NewModuleRootManager" inherit-compiler-output="false">
+  <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/test/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/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/generated/debug" type="java-resource" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/test/debug" type="java-test-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" />
       <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 22 Platform" jdkType="Android SDK" />
+    <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
     <orderEntry type="sourceFolder" forTests="false" />
-    <orderEntry type="library" exported="" name="appcompat-v7-21.0.3" level="project" />
-    <orderEntry type="library" exported="" name="iotivity-armeabi-base-debug-" level="project" />
-    <orderEntry type="library" exported="" name="support-annotations-21.0.3" level="project" />
-    <orderEntry type="library" exported="" name="support-v4-21.0.3" level="project" />
-    <orderEntry type="module" module-name="message" exported="" />
+    <orderEntry type="library" exported="" name="iotivity-base-armeabi-release-" level="project" />
+    <orderEntry type="library" exported="" name="android-android-21" level="project" />
   </component>
-</module>
-
+</module>
\ No newline at end of file
diff --git a/android/examples/provisioningclient/src/main/assets/oic_svr_db_client.dat b/android/examples/provisioningclient/src/main/assets/oic_svr_db_client.dat
new file mode 100644 (file)
index 0000000..b8d249c
Binary files /dev/null and b/android/examples/provisioningclient/src/main/assets/oic_svr_db_client.dat differ
index 1219d6a..22dfeba 100644 (file)
@@ -1,43 +1,88 @@
-{
-    "acl": [
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/res",
-                "/oic/d",
-                "/oic/p",
-                "/oic/res/types/d",
-                "/oic/ad",
-                "/oic/sec/amacl"
-                       ],
-                       "perms": 2,
-                       "ownrs" : ["YWRtaW5EZXZpY2VVVUlEMA=="]
-               },
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/sec/doxm",
-                "/oic/sec/pstat"
-             ],
-             "perms": 2,
-             "ownrs" : ["YWRtaW5EZXZpY2VVVUlEMA=="]
-        }
-       ],
-       "pstat":        {
-               "isop": true,
-               "deviceid":     "YWRtaW5EZXZpY2VVVUlEMA==",
-               "ch": 0,
-               "cm":   0,
-               "tm":   0,
-               "om":   3,
-               "sm":   [3]
-       },
-       "doxm": {
-               "oxm":  [0],
-               "oxmsel": 0,
-               "sct": 1,
-               "owned": true,
-               "deviceid":     "YWRtaW5EZXZpY2VVVUlEMA==",
-               "ownr": "YWRtaW5EZXZpY2VVVUlEMA=="
-       }
-}
+{\r
+    "acl": {\r
+        "aclist": {\r
+            "aces": [\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/res",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/p",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/types/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/ad",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/amacl",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/doxm",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/pstat",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }                  \r
+                    ],\r
+                    "permission": 2\r
+                }\r
+            ]\r
+        },\r
+        "rowneruuid" : "61646D69-6E44-6576-6963-655575696430"\r
+    },    \r
+    "pstat": {\r
+        "isop": true,\r
+        "cm": 2,\r
+        "tm": 0,\r
+        "om": 3,\r
+        "sm": 3,\r
+        "deviceuuid": "61646D69-6E44-6576-6963-655575696430",\r
+        "rowneruuid": "61646D69-6E44-6576-6963-655575696430"\r
+    },\r
+    "doxm": {\r
+        "oxms": [0],\r
+        "oxmsel": 0,\r
+        "sct": 1,\r
+        "owned": true,\r
+        "deviceuuid": "61646D69-6E44-6576-6963-655575696430",\r
+        "dpc": false,\r
+        "devowneruuid": "61646D69-6E44-6576-6963-655575696430",\r
+        "rowneruuid": "61646D69-6E44-6576-6963-655575696430"\r
+    }\r
+}\r
index df92e2f..fbd8eda 100644 (file)
@@ -14,20 +14,22 @@ import android.util.Log;
 import android.view.Gravity;
 import android.widget.LinearLayout;
 import android.widget.TextView;
+
+import org.iotivity.base.CredType;
+import org.iotivity.base.DeviceStatus;
+import org.iotivity.base.KeySize;
 import org.iotivity.base.ModeType;
 import org.iotivity.base.OcException;
 import org.iotivity.base.OcPlatform;
-import org.iotivity.base.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ServiceType;
 import org.iotivity.base.OcProvisioning;
 import org.iotivity.base.OcSecureResource;
-import org.iotivity.base.ProvisionResult;
-import org.iotivity.base.OxmType;
 import org.iotivity.base.OicSecAcl;
-import org.iotivity.base.CredType;
-import org.iotivity.base.KeySize;
-import org.iotivity.base.DeviceStatus;
+import org.iotivity.base.OxmType;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.ProvisionResult;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+
 import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
@@ -39,41 +41,11 @@ import java.util.EnumSet;
 import java.util.List;
 
 public class ProvisioningClient extends Activity implements
-    OcSecureResource.DoOwnershipTransferListener,OcSecureResource.ProvisionPairwiseDevicesListener {
+        OcSecureResource.DoOwnershipTransferListener, OcSecureResource.ProvisionPairwiseDevicesListener {
 
     private static final String TAG = "Provisioning Client: ";
     private static final int BUFFER_SIZE = 1024;
     int unownedDevCount = StringConstants.NUMBER_ZERO;
-    private String filePath = "";
-    private OcSecureResource newSecureResource;
-    private List<OcSecureResource> deviceList;
-    private List<OcSecureResource> ownedDeviceList;
-    private TextView mEventsTextView;
-
-    @Override
-    protected void onCreate(Bundle savedInstanceState) {
-        super.onCreate(savedInstanceState);
-        setContentView(R.layout.activity_secure_provision_client);
-        mEventsTextView = new TextView(this);
-        mEventsTextView.setGravity(Gravity.BOTTOM);
-        mEventsTextView.setMovementMethod(new ScrollingMovementMethod());
-        LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
-        layout.addView(mEventsTextView, new LinearLayout.LayoutParams(
-                        LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)
-        );
-        filePath = getFilesDir().getPath() + "/"; //  data/data/<package>/files/
-        //copy json when application runs first time
-        SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(this);
-        boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
-        if (isFirstRun) {
-            copyJsonFromAsset();
-            SharedPreferences.Editor editor = wmbPreference.edit();
-            editor.putBoolean("FIRSTRUN", false);
-            editor.commit();
-        }
-        initOICStack();
-    }
-
     OcProvisioning.PinCallbackListener pinCallbackListener =
             new OcProvisioning.PinCallbackListener() {
                 @Override
@@ -82,7 +54,11 @@ public class ProvisioningClient extends Activity implements
                     return "";
                 }
             };
-
+    private String filePath = "";
+    private OcSecureResource newSecureResource;
+    private List<OcSecureResource> deviceList;
+    private List<OcSecureResource> ownedDeviceList;
+    private TextView mEventsTextView;
     OcSecureResource.ProvisionAclListener provisionAclListener =
             new OcSecureResource.ProvisionAclListener() {
                 @Override
@@ -97,7 +73,6 @@ public class ProvisioningClient extends Activity implements
                     }
                 }
             };
-
     OcSecureResource.ProvisionCredentialsListener provisionCredentialsListener =
             new OcSecureResource.ProvisionCredentialsListener() {
                 @Override
@@ -112,7 +87,6 @@ public class ProvisioningClient extends Activity implements
                     }
                 }
             };
-
     OcSecureResource.UnlinkDevicesListener unlinkDevicesListener =
             new OcSecureResource.UnlinkDevicesListener() {
                 @Override
@@ -127,7 +101,6 @@ public class ProvisioningClient extends Activity implements
                     }
                 }
             };
-
     OcSecureResource.RemoveDeviceListener removeDeviceListener =
             new OcSecureResource.RemoveDeviceListener() {
                 @Override
@@ -141,6 +114,30 @@ public class ProvisioningClient extends Activity implements
                 }
             };
 
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.activity_secure_provision_client);
+        mEventsTextView = new TextView(this);
+        mEventsTextView.setGravity(Gravity.BOTTOM);
+        mEventsTextView.setMovementMethod(new ScrollingMovementMethod());
+        LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
+        layout.addView(mEventsTextView, new LinearLayout.LayoutParams(
+                        LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)
+        );
+        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();
+    }
+
     /**
      * configure OIC platform and call findResource
      */
@@ -152,7 +149,7 @@ public class ProvisioningClient extends Activity implements
                 ModeType.CLIENT_SERVER,
                 "0.0.0.0", // bind to all available interfaces
                 0,
-                QualityOfService.LOW, filePath + StringConstants.OIC_CLIENT_JSON_DB_FILE);
+                QualityOfService.LOW, filePath + StringConstants.OIC_CLIENT_CBOR_DB_FILE);
         OcPlatform.Configure(cfg);
         try {
             /*
@@ -198,17 +195,15 @@ public class ProvisioningClient extends Activity implements
             newSecureResource = ownedDeviceList.get(0);
             OcSecureResource newSecureResource2 = ownedDeviceList.get(1);
             List<String> resources = new ArrayList<String>();
-            List<String> owners = new ArrayList<String>();
             List<String> periods = new ArrayList<String>();
             List<String> recurrences = new ArrayList<String>();
-            recurrences.add("Daily");
-            resources.add("*");
-            owners.add("adminDeviceUUID0");
-            periods.add("01-01-15");
+            recurrences.add(StringConstants.DEFAULT_RECURRENCES);
+            resources.add(StringConstants.DEFAULT_RESOURCES);
+            periods.add(StringConstants.DEFAULT_PERIOD);
             OicSecAcl acl1 = new OicSecAcl(newSecureResource.getDeviceID(), recurrences, periods,
-                    31, resources, owners);
+                    StringConstants.DEFAULT_PERMISSION, resources, StringConstants.DEFAULT_ROWNER_ID);
             OicSecAcl acl2 = new OicSecAcl(newSecureResource2.getDeviceID(), recurrences, periods,
-                    31, resources, owners);
+                    StringConstants.DEFAULT_PERMISSION, resources, StringConstants.DEFAULT_ROWNER_ID);
             newSecureResource.provisionPairwiseDevices(EnumSet.of(CredType.SYMMETRIC_PAIR_WISE_KEY),
                     KeySize.OWNER_PSK_LENGTH_128, acl1, newSecureResource2, acl2, this);
         } catch (Exception e) {
@@ -233,21 +228,21 @@ public class ProvisioningClient extends Activity implements
     }
 
     /**
-     * Copy svr db json file from assets folder to app data files dir
+     * Copy svr db CBOR dat file from assets folder to app data files dir
      */
-    private void copyJsonFromAsset() {
+    private void copyCborFromAsset() {
         InputStream inputStream = null;
         OutputStream outputStream = null;
         int length;
         byte[] buffer = new byte[BUFFER_SIZE];
         try {
-            inputStream = getAssets().open(StringConstants.OIC_CLIENT_JSON_DB_FILE);
+            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_JSON_DB_FILE);
+            outputStream = new FileOutputStream(filePath + StringConstants.OIC_CLIENT_CBOR_DB_FILE);
             while ((length = inputStream.read(buffer)) != -1) {
                 outputStream.write(buffer, 0, length);
             }
@@ -255,10 +250,10 @@ public class ProvisioningClient extends Activity implements
             logMessage(TAG + "Null pointer exception " + e.getMessage());
             Log.e(TAG, e.getMessage());
         } catch (FileNotFoundException e) {
-            logMessage(TAG + "Json svr db file not found " + e.getMessage());
+            logMessage(TAG + "CBOR svr db file not found " + e.getMessage());
             Log.e(TAG, e.getMessage());
         } catch (IOException e) {
-            logMessage(TAG + StringConstants.OIC_CLIENT_JSON_DB_FILE + " file copy failed");
+            logMessage(TAG + StringConstants.OIC_CLIENT_CBOR_DB_FILE + " file copy failed");
             Log.e(TAG, e.getMessage());
         } finally {
             if (inputStream != null) {
@@ -369,15 +364,14 @@ public class ProvisioningClient extends Activity implements
                     OcSecureResource ocSecureResourceDest = ownedDeviceList.get(1);
                     publishProgress(TAG + "ACL Provision for " + ocSecureResource.getDeviceID());
                     List<String> resources = new ArrayList<String>();
-                    List<String> owners = new ArrayList<String>();
                     List<String> periods = new ArrayList<String>();
                     List<String> recurrences = new ArrayList<String>();
-                    recurrences.add("Daily");
-                    resources.add("*");
-                    owners.add("adminDeviceUUID0");
-                    periods.add("01-01-15");
+                    recurrences.add(StringConstants.DEFAULT_RECURRENCES);
+                    resources.add(StringConstants.DEFAULT_RESOURCES);
+                    periods.add(StringConstants.DEFAULT_PERIOD);
                     OicSecAcl aclObject = new OicSecAcl(ocSecureResourceDest.getDeviceID(),
-                            recurrences, periods, 31, resources, owners);
+                            recurrences, periods, StringConstants.DEFAULT_PERMISSION, resources,
+                            StringConstants.DEFAULT_ROWNER_ID);
                     ocSecureResource.provisionACL(aclObject, provisionAclListener);
                 } else {
                     publishProgress(TAG + "No Owned devices present");
@@ -444,7 +438,7 @@ public class ProvisioningClient extends Activity implements
                     List<String> linkedDevices = ocSecureResource.getLinkedDevices();
                     if (linkedDevices.size() > 0) {
                         for (int i = 0; i < linkedDevices.size(); i++) {
-                            publishProgress(TAG + "Linked Devices "+
+                            publishProgress(TAG + "Linked Devices " +
                                     (i + 1) + "= " + linkedDevices.get(i));
                         }
                     } else {
@@ -546,7 +540,7 @@ public class ProvisioningClient extends Activity implements
             try {
                 publishProgress(TAG + "Initiate Owned device Discovery");
                 ownedDeviceList = OcProvisioning.discoverOwnedDevices
-                    (StringConstants.DISCOVERY_TIMEOUT_10);
+                        (StringConstants.DISCOVERY_TIMEOUT_10);
                 if (ownedDeviceList.size() > 0) {
                     for (int i = 0; i < ownedDeviceList.size(); i++) {
                         publishProgress(TAG + "Owned Discovered Device " + (i + 1) + "= " +
index 9c9baed..eb3a189 100644 (file)
@@ -6,7 +6,12 @@ public interface StringConstants {
     public static final int DISCOVERY_TIMEOUT_10 =  10;
     public static final int DISCOVERY_TIMEOUT_20 =  20;
     public static final int ERROR_CODE =  1;
-    public static final String OIC_CLIENT_JSON_DB_FILE =  "oic_svr_db_client.json";
+    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.dat";
     public static final String MESSAGE = "message";
     public static final String OIC_SQL_DB_FILE =  "Pdm.db";
     public static final int  CREDENTIAL_TYPE=1;
index ded7b86..5a0364c 100755 (executable)
@@ -1 +1,5 @@
-include ':simpleserver', ':simpleclient', ':fridgeserver', ':fridgeclient', ':guiclient', ':provisioningclient', ':presenceserver', ':presenceclient', ':devicediscoveryclient', ':devicediscoveryserver', ':groupclient', ':groupserver', ':fridgegroupclient', ':fridgegroupserver'
+include ':simpleserver', ':simpleclient', ':fridgeserver', ':fridgeclient', ':guiclient', ':presenceserver', ':presenceclient', ':devicediscoveryclient', ':devicediscoveryserver', ':groupclient', ':groupserver', ':fridgegroupclient', ':fridgegroupserver'
+SECURED=System.getProperty('SECURE')
+if(SECURED== "1"){
+        include ':provisioningclient'
+}
index 2a0ba77..45ce648 100644 (file)
         <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="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
-        <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugTest" />
-        <option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugTestSources" />
-        <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />
+        <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" />
@@ -24,9 +26,9 @@
       </configuration>
     </facet>
   </component>
-  <component name="NewModuleRootManager" inherit-compiler-output="false">
+  <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/test/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/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/generated/debug" type="java-resource" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/test/debug" type="java-test-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" />
       <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 22 Platform" jdkType="Android SDK" />
+    <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
     <orderEntry type="sourceFolder" forTests="false" />
-    <orderEntry type="library" exported="" name="iotivity-armeabi-base-debug-unspecified" level="project" />
+    <orderEntry type="library" exported="" name="iotivity-base-armeabi-release-" level="project" />
+    <orderEntry type="library" exported="" name="android-android-21" level="project" />
   </component>
 </module>
\ No newline at end of file
index e696b3d..97a323b 100644 (file)
@@ -1,7 +1,7 @@
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="org.iotivity.base.examples" >
-
+    <uses-feature android:name="android.hardware.nfc" />
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.BLUETOOTH"/>
@@ -12,7 +12,7 @@
     <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
     <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
-
+    <uses-permission android:name="android.permission.NFC" />
     <application
         android:allowBackup="true"
         android:icon="@mipmap/iotivityicon"
diff --git a/android/examples/simpleclient/src/main/assets/oic_svr_db_client.dat b/android/examples/simpleclient/src/main/assets/oic_svr_db_client.dat
new file mode 100644 (file)
index 0000000..9de47b8
Binary files /dev/null and b/android/examples/simpleclient/src/main/assets/oic_svr_db_client.dat differ
index c16acb8..5052bd1 100644 (file)
-{
-    "acl": [
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/res",
-                "/oic/d",
-                "/oic/p",
-                "/oic/res/types/d",
-                "/oic/ad",
-                "/oic/sec/acl"
-                       ],
-                       "perms": 2,
-                       "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-               },
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/sec/doxm",
-                "/oic/sec/pstat"
-             ],
-             "perms": 2,
-             "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-        }
-       ],
-       "pstat":        {
-               "isop": true,
-               "deviceid":     "ZGV2aWNlaWQAAAAAABhanw==",
-               "ch": 0,
-               "cm":   0,
-               "tm":   0,
-               "om":   3,
-               "sm":   [3]
-       },
-       "doxm": {
-               "oxm":  [0],
-               "oxmsel": 0,
-               "sct": 1,
-               "owned": true,
-               "deviceid":     "MjIyMjIyMjIyMjIyMjIyMg==",
-               "ownr": "MjIyMjIyMjIyMjIyMjIyMg=="
-       },
-    "cred":    [{
-               "credid": 1,
-               "sub": "MTExMTExMTExMTExMTExMQ==",
-               "credtyp": 1,
-               "pvdata": "QUFBQUFBQUFBQUFBQUFBQQ==",
-        "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-       }]
-}
+{\r
+    "acl": {\r
+        "aclist": {\r
+            "aces": [\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/res",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/p",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/types/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/ad",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/acl",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/doxm",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        } ,\r
+                        {\r
+                            "href": "/oic/sec/pstat",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                }\r
+            ]\r
+        },\r
+        "rowneruuid" : "32323232-3232-3232-3232-323232323232"\r
+    },\r
+    "pstat": {\r
+        "isop": true,\r
+        "deviceuuid": "32323232-3232-3232-3232-323232323232",\r
+        "rowneruuid": "32323232-3232-3232-3232-323232323232",\r
+        "cm": 0,\r
+        "tm": 0,\r
+        "om": 3,\r
+        "sm": 3\r
+        },\r
+    "doxm": {\r
+        "oxms": [0],\r
+        "oxmsel": 0,\r
+        "sct": 1,\r
+        "owned": true,\r
+        "deviceuuid": "32323232-3232-3232-3232-323232323232",\r
+        "devowneruuid": "32323232-3232-3232-3232-323232323232",\r
+        "rowneruuid": "32323232-3232-3232-3232-323232323232",\r
+        "dpc": false\r
+    },\r
+    "cred": {\r
+        "creds": [\r
+            {\r
+                "credid": 1,\r
+                "subjectuuid": "31313131-3131-3131-3131-313131313131",\r
+                "credtype": 1,\r
+                "privatedata": {\r
+                    "data": "AAAAAAAAAAAAAAAA",\r
+                    "encoding": "oic.sec.encoding.raw"\r
+                }\r
+            }\r
+        ],\r
+        "rowneruuid": "32323232-3232-3232-3232-323232323232"\r
+    }\r
+}
\ No newline at end of file
index 4d1bde3..a9d06a2 100644 (file)
@@ -23,6 +23,8 @@ package org.iotivity.base.examples;
 
 import android.app.Activity;
 import android.content.Context;
+import android.content.Intent;
+import android.nfc.NfcAdapter;
 import android.os.Bundle;
 import android.text.method.ScrollingMovementMethod;
 import android.util.Log;
@@ -76,6 +78,7 @@ public class SimpleClient extends Activity implements
         Context context = this;
 
         PlatformConfig platformConfig = new PlatformConfig(
+                this,
                 context,
                 ServiceType.IN_PROC,
                 ModeType.CLIENT,
@@ -83,7 +86,6 @@ public class SimpleClient extends Activity implements
                 0,         // Uses randomly available port
                 QualityOfService.LOW
         );
-
         msg("Configuring platform.");
         OcPlatform.Configure(platformConfig);
 
@@ -488,7 +490,7 @@ public class SimpleClient extends Activity implements
         }
         msg(mLight.toString());
 
-        if (++mObserveCount == 11) {
+        if ((++mObserveCount) == 11) {
             msg("Cancelling Observe...");
             try {
                 mFoundLightResource.cancelObserve();
@@ -611,4 +613,18 @@ public class SimpleClient extends Activity implements
         mLight = new Light();
         mObserveCount = 0;
     }
+
+    @Override
+    public void onNewIntent(Intent intent) {
+        super.onNewIntent(intent);
+        Log.d(TAG, "onNewIntent with changes sending broadcast IN ");
+
+        Intent i = new Intent();
+        i.setAction(intent.getAction());
+        i.putExtra(NfcAdapter.EXTRA_NDEF_MESSAGES,
+                intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES));
+        sendBroadcast(i);
+        Log.d(TAG, "Initialize Context again resetting");
+    }
+
 }
index 3f80e30..920a418 100644 (file)
         <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="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
-        <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugTest" />
-        <option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugTestSources" />
-        <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />
+        <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" />
@@ -24,9 +26,9 @@
       </configuration>
     </facet>
   </component>
-  <component name="NewModuleRootManager" inherit-compiler-output="false">
+  <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/test/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/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/generated/debug" type="java-resource" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/test/debug" type="java-test-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" />
       <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 22 Platform" jdkType="Android SDK" />
+    <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
     <orderEntry type="sourceFolder" forTests="false" />
-    <orderEntry type="library" exported="" name="iotivity-armeabi-base-debug-unspecified" level="project" />
+    <orderEntry type="library" exported="" name="iotivity-base-armeabi-release-" level="project" />
+    <orderEntry type="library" exported="" name="android-android-21" level="project" />
   </component>
 </module>
\ No newline at end of file
index 758daae..fcd971b 100644 (file)
@@ -1,7 +1,7 @@
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="org.iotivity.base.examples" >
-
+    <uses-feature android:name="android.hardware.nfc" />
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.BLUETOOTH"/>
@@ -12,8 +12,7 @@
     <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
     <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
-
-
+    <uses-permission android:name="android.permission.NFC" />
     <application
         android:allowBackup="true"
         android:icon="@mipmap/iotivityicon"
diff --git a/android/examples/simpleserver/src/main/assets/oic_svr_db_server.dat b/android/examples/simpleserver/src/main/assets/oic_svr_db_server.dat
new file mode 100644 (file)
index 0000000..31e1814
Binary files /dev/null and b/android/examples/simpleserver/src/main/assets/oic_svr_db_server.dat differ
old mode 100755 (executable)
new mode 100644 (file)
index 729138c..0e1bf23
-{
-    "acl": [
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/res",
-                "/oic/d",
-                "/oic/p",
-                "/oic/res/types/d",
-                "/oic/ad",
-                "/oic/sec/acl"
-                       ],
-                       "perms": 2,
-                       "ownrs" : ["MTExMTExMTExMTExMTExMQ=="]
-               },
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/sec/doxm",
-                "/oic/sec/pstat"
-             ],
-             "perms": 2,
-             "ownrs" : ["MTExMTExMTExMTExMTExMQ=="]
-        },
-        {
-            "sub": "Kg==",
-            "rsrc": ["/light0", "/light1", "/a/light"],
-            "perms": 6,
-            "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-        }
-       ],
-       "pstat":        {
-               "isop": true,
-               "deviceid":     "ZGV2aWNlaWQAAAAAABhanw==",
-               "ch": 0,
-               "cm":   0,
-               "tm":   0,
-               "om":   3,
-               "sm":   [3]
-       },
-       "doxm": {
-               "oxm":  [0],
-               "oxmsel": 0,
-               "sct": 1,
-               "owned": true,
-               "deviceid":     "MTExMTExMTExMTExMTExMQ==",
-               "ownr": "MjIyMjIyMjIyMjIyMjIyMg=="
-       },
-    "cred":    [{
-               "credid": 1,
-               "sub": "MjIyMjIyMjIyMjIyMjIyMg==",
-               "credtyp": 1,
-               "pvdata": "QUFBQUFBQUFBQUFBQUFBQQ==",
-        "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-       }]
-}
+{\r
+    "acl": {\r
+        "aclist": {\r
+            "aces": [\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/res",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/p",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/types/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/ad",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/acl",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/doxm",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        } ,\r
+                        {\r
+                            "href": "/oic/sec/pstat",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/a/light",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/a/light0",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/a/light1",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 6\r
+                }\r
+            ]\r
+        },\r
+        "rowneruuid" : "31313131-3131-3131-3131-313131313131"\r
+    },\r
+    "pstat": {\r
+        "isop": true,\r
+        "deviceuuid": "31313131-3131-3131-3131-313131313131",\r
+        "rowneruuid": "31313131-3131-3131-3131-313131313131",\r
+        "cm": 0,\r
+        "tm": 0,\r
+        "om": 3,\r
+        "sm": 3\r
+        },\r
+    "doxm": {\r
+        "oxms": [0],\r
+        "oxmsel": 0,\r
+        "sct": 1,\r
+        "owned": true,\r
+        "deviceuuid": "31313131-3131-3131-3131-313131313131",\r
+        "devowneruuid": "32323232-3232-3232-3232-323232323232",\r
+        "rowneruuid": "31313131-3131-3131-3131-313131313131",\r
+        "dpc": false\r
+    },\r
+    "cred": {\r
+        "creds": [\r
+            {\r
+                "credid": 1,\r
+                "subjectuuid": "32323232-3232-3232-3232-323232323232",\r
+                "credtype": 1,\r
+                "privatedata": {\r
+                    "data": "AAAAAAAAAAAAAAAA",\r
+                    "encoding": "oic.sec.encoding.raw"\r
+                }\r
+            }\r
+        ],\r
+        "rowneruuid": "31313131-3131-3131-3131-313131313131"\r
+    }\r
+}\r
+\r
index 515284e..e9b1fb4 100644 (file)
@@ -246,7 +246,7 @@ public class Light implements OcPlatform.EntityHandler {
                 mObservationIds.add(observationInfo.getOcObservationId());
                 break;
             case UNREGISTER:
-                mObservationIds.remove(observationInfo.getOcObservationId());
+                mObservationIds.remove((Byte)observationInfo.getOcObservationId());
                 break;
         }
         // Observation happens on a different thread in notifyObservers method.
index 2dbd033..707e1a1 100644 (file)
@@ -27,6 +27,7 @@ import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
+import android.nfc.NfcAdapter;
 import android.os.Bundle;
 import android.text.method.ScrollingMovementMethod;
 import android.util.Log;
@@ -64,6 +65,7 @@ public class SimpleServer extends Activity {
         Context context = this;
 
         PlatformConfig platformConfig = new PlatformConfig(
+                this,
                 context,
                 ServiceType.IN_PROC,
                 ModeType.SERVER,
@@ -242,4 +244,17 @@ public class SimpleServer extends Activity {
             msg(message);
         }
     }
+
+    @Override
+    public void onNewIntent(Intent intent) {
+        super.onNewIntent(intent);
+        Log.d(TAG, "onNewIntent with changes sending broadcast IN ");
+
+        Intent i = new Intent();
+        i.setAction(intent.getAction());
+        i.putExtra(NfcAdapter.EXTRA_NDEF_MESSAGES,
+                intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES));
+        sendBroadcast(i);
+        Log.d(TAG, "Initialize Context again resetting");
+    }
 }
index ae3b53f..4329775 100644 (file)
@@ -35,6 +35,7 @@ Help(vars.GenerateHelpText(env))
 env.ImportLib('SPI')
 if 'ETH' in env.get('SHIELD'):
        env.ImportLib('Ethernet')
+       env.AppendUnique(CPPDEFINES = ['ARDUINOETH'])
 if 'WIFI' in env.get('SHIELD'):
        env.ImportLib('WiFi')
        env.AppendUnique(CPPDEFINES = ['ARDUINOWIFI'])
index 61928d6..aa2dcd4 100755 (executable)
@@ -12,8 +12,10 @@ function build_all()
                build_linux_secured $1 $2
                build_linux_unsecured_with_ra $1 $2
                build_linux_secured_with_ra $1 $2
+               build_linux_unsecured_with_rm $1 $2
                build_linux_unsecured_with_rd $1 $2
                build_linux_secured_with_rd $1 $2
+               build_simulator $1 $2
        fi
 
        build_android $1 $2
@@ -41,6 +43,12 @@ function build_linux_unsecured()
        scons RELEASE=$1 $2
 }
 
+function build_linux_unsecured_with_rm()
+{
+       echo "*********** Build for linux with RoutingManager************"
+       scons ROUTING=GW RELEASE=$1 $2
+}
+
 function build_linux_secured()
 {
        echo "*********** Build for linux with Security *************"
@@ -51,13 +59,13 @@ function build_linux_unsecured_with_ra()
 {
 
        echo "*********** Build for linux With Remote Access *************"
-       scons RELEASE=$1 WITH_RA=1 $2
+       scons RELEASE=$1 WITH_RA=1 WITH_RA_IBB=1 $2
 }
 
 function build_linux_secured_with_ra()
 {
        echo "*********** Build for linux With Remote Access & Security ************"
-       scons RELEASE=$1 WITH_RA=1 SECURED=1 $2
+       scons RELEASE=$1 WITH_RA=1 WITH_RA_IBB=1 SECURED=1 $2
 }
 
 function build_linux_unsecured_with_rd()
@@ -79,7 +87,9 @@ function build_android()
        # and windows android-ndk-r10(64bit target version) support these features.
 
        build_android_x86 $1 $2
+       build_android_x86_with_rm $1 $2
        build_android_armeabi $1 $2
+       build_android_armeabi_with_rm $1 $2
 }
 
 function build_android_x86()
@@ -90,6 +100,14 @@ function build_android_x86()
        scons TARGET_OS=android TARGET_ARCH=x86 RELEASE=$1 TARGET_TRANSPORT=BLE $2
 }
 
+function build_android_x86_with_rm()
+{
+       echo "*********** Build for android x86 with Routing Manager *************"
+       scons TARGET_OS=android TARGET_ARCH=x86 ROUTING=GW RELEASE=$1 TARGET_TRANSPORT=IP $2
+       scons TARGET_OS=android TARGET_ARCH=x86 ROUTING=GW RELEASE=$1 TARGET_TRANSPORT=BT $2
+       scons TARGET_OS=android TARGET_ARCH=x86 ROUTING=GW RELEASE=$1 TARGET_TRANSPORT=BLE $2
+}
+
 function build_android_armeabi()
 {
        echo "*********** Build for android armeabi *************"
@@ -98,6 +116,14 @@ function build_android_armeabi()
        scons TARGET_OS=android TARGET_ARCH=armeabi RELEASE=$1 TARGET_TRANSPORT=BLE $2
 }
 
+function build_android_armeabi_with_rm()
+{
+       echo "*********** Build for android armeabi with Routing Manager*************"
+       scons TARGET_OS=android TARGET_ARCH=armeabi ROUTING=GW RELEASE=$1 TARGET_TRANSPORT=IP $2
+       scons TARGET_OS=android TARGET_ARCH=armeabi ROUTING=GW RELEASE=$1 TARGET_TRANSPORT=BT $2
+       scons TARGET_OS=android TARGET_ARCH=armeabi ROUTING=GW RELEASE=$1 TARGET_TRANSPORT=BLE $2
+}
+
 function build_arduino()
 {
        echo "*********** Build for arduino avr *************"
@@ -116,11 +142,14 @@ function build_tizen()
        echo "*********** Build for Tizen *************"
        ./gbsbuild.sh
 
-       echo "*********** Build for Tizen CA lib and sample *************"
-       scons -f resource/csdk/connectivity/build/tizen/SConscript TARGET_OS=tizen TARGET_TRANSPORT=IP LOGGING=true RELEASE=$1 $2
+       echo "*********** Build for Tizen octbstack lib and sample *************"
+       scons -f resource/csdk/stack/samples/tizen/build/SConscript TARGET_OS=tizen TARGET_TRANSPORT=IP LOGGING=true RELEASE=$1 $2
+
+       echo "*********** Build for Tizen octbstack lib and sample with Security*************"
+       scons -f resource/csdk/stack/samples/tizen/build/SConscript TARGET_OS=tizen TARGET_TRANSPORT=IP LOGGING=true SECURED=1 RELEASE=$1 $2
 
-       echo "*********** Build for Tizen CA lib and sample with Security *************"
-       scons -f resource/csdk/connectivity/build/tizen/SConscript TARGET_OS=tizen TARGET_TRANSPORT=IP LOGGING=true SECURED=1 RELEASE=$1 $2
+       echo "*********** Build for Tizen octbstack lib and sample with Routing Manager*************"
+       scons -f resource/csdk/stack/samples/tizen/build/SConscript TARGET_OS=tizen TARGET_TRANSPORT=IP LOGGING=true ROUTING=GW RELEASE=$1 $2
 }
 
 function build_darwin() # Mac OSx and iOS
@@ -144,6 +173,12 @@ function build_darwin() # Mac OSx and iOS
        scons TARGET_OS=ios TARGET_ARCH=arm64 SYS_VERSION=7.0 RELEASE=$1 $2
 }
 
+function build_simulator()
+{
+       echo "*********** Build for simulator plugin *************"
+       scons SIMULATOR=1 RELEASE=$1 $2
+}
+
 function unit_tests()
 {
        echo "*********** Unit test Start *************"
@@ -158,7 +193,7 @@ function  help()
        echo "Usage:"
         echo "  build:"
         echo "     `basename $0` <target_build>"
-       echo "      Allowed values for <target_build>: all, linux_unsecured, linux_secured, linux_unsecured_with_ra, linux_secured_with_ra, linux_unsecured_with_rd, linux_secured_with_rd, android, arduino, tizen, darwin"
+       echo "      Allowed values for <target_build>: all, linux_unsecured, linux_secured, linux_unsecured_with_ra, linux_secured_with_ra, linux_unsecured_with_rd, linux_secured_with_rd, android, arduino, tizen, simulator darwin"
        echo "      Note: \"linux\" will build \"linux_unsecured\", \"linux_secured\", \"linux_unsecured_with_ra\", \"linux_secured_with_ra\", \"linux_secured_with_rd\" & \"linux_unsecured_with_rd\"."
        echo "      Any selection will build both debug and release versions of all available targets in the scope you've"
        echo "      selected. To choose any specific command, please use the SCons commandline directly. Please refer"
@@ -190,6 +225,8 @@ then
        then
                build_linux_unsecured true
                build_linux_unsecured false
+               build_linux_unsecured_with_rm true
+               build_linux_unsecured_with_rm false
        elif [ $1 = 'linux_secured' ]
        then
                build_linux_secured true
@@ -218,10 +255,14 @@ then
        then
         build_android_x86 true
         build_android_x86 false
+               build_android_x86_with_rm true
+               build_android_x86_with_rm false
        elif [ $1 = 'android_armeabi' ]
        then
         build_android_armeabi true
         build_android_armeabi false
+               build_android_armeabi_with_rm true
+               build_android_armeabi_with_rm false
        elif [ $1 = 'arduino' ]
        then
                build_arduino true
@@ -230,6 +271,10 @@ then
        then
                build_tizen true
                build_tizen false
+       elif [ $1 = 'simulator' ]
+    then
+               build_simulator true
+               build_simulator false
        elif [ $1 = 'darwin' ]
        then
                build_darwin true
index 0ec3f60..2be70ce 100644 (file)
@@ -80,13 +80,18 @@ help_vars.Add(EnumVariable('TARGET_OS', 'Target platform', host, host_target_map
 
 help_vars.Add(BoolVariable('WITH_RA', 'Build with Remote Access module', False))
 help_vars.Add(BoolVariable('WITH_TCP', 'Build with TCP adapter', False))
-help_vars.Add(BoolVariable('SIMULATOR', 'Build with simulator module', False))
 help_vars.Add(EnumVariable('WITH_RD', 'Build including Resource Directory', '0', allowed_values=('0', '1')))
+help_vars.Add(BoolVariable('WITH_CLOUD', 'Build including Cloud client sample', False))
+
+help_vars.Add(BoolVariable('SIMULATOR', 'Build with simulator module', False))
+
+help_vars.Add(BoolVariable('WITH_RA_IBB', 'Build with Remote Access module(workssys)', False))
+
 
 if target_os in targets_disallow_multitransport:
-       help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'IP', ['BT', 'BLE', 'IP']))
+       help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'IP', ['BT', 'BLE', 'IP', 'NFC']))
 else:
-       help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'BT', 'BLE', 'IP']))
+       help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'BT', 'BLE', 'IP', 'NFC']))
 
 help_vars.Add(EnumVariable('TARGET_ARCH', 'Target architecture', default_arch, os_arch_map[target_os]))
 help_vars.Add(EnumVariable('SECURED', 'Build with DTLS', '0', allowed_values=('0', '1')))
@@ -100,6 +105,12 @@ help_vars.AddVariables(('DEVICE_NAME', 'Network display name for device (For Ard
 help_vars.Add(PathVariable('ANDROID_NDK', 'Android NDK path', None, PathVariable.PathAccept))
 help_vars.Add(PathVariable('ANDROID_HOME', 'Android SDK path', None, PathVariable.PathAccept))
 help_vars.Add(PathVariable('ANDROID_GRADLE', 'Gradle binary file', None, PathVariable.PathIsFile))
+#ES_TARGET_ENROLLEE is for specifying what is our target enrollee (Arduino or rest of platforms which support Multicast)
+help_vars.Add(EnumVariable('ES_TARGET_ENROLLEE', 'Target Enrollee', 'arduino', allowed_values=('arduino', 'tizen', 'linux')))
+#ES_ROLE is for specifying the role (Enrollee or Mediator) for which scons is being executed
+help_vars.Add(EnumVariable('ES_ROLE', 'Target build mode', 'mediator', allowed_values=('mediator', 'enrollee')))
+#ES_SOFT_MODE is for specifying MODE (Mode 1 : Enrollee with  Soft AP or Mode 2  : Mediator with Soft AP)
+help_vars.Add(EnumVariable('ES_SOFTAP_MODE', 'Target build mode', 'ENROLLEE_SOFTAP', allowed_values=('ENROLLEE_SOFTAP', 'MEDIATOR_SOFTAP')))
 
 AddOption('--prefix',
                   dest='prefix',
@@ -129,7 +140,7 @@ else:
        env = Environment(variables = help_vars, tools = ['default', 'textfile'],
                        TARGET_ARCH = target_arch, TARGET_OS = target_os,
                        PREFIX = GetOption('prefix'),
-                       LIB_INSTALL_DIR = ARGUMENTS.get('LIB_INSTALL_DIR', '/usr/lib')
+                       LIB_INSTALL_DIR = ARGUMENTS.get('LIB_INSTALL_DIR') #for 64bit build
                        )
 Help(help_vars.GenerateHelpText(env))
 
@@ -213,34 +224,34 @@ def __install(ienv, targets, name):
 def __installlib(ienv, targets, name):
        user_prefix = env.get('PREFIX')
        if user_prefix:
-               i_n = ienv.Install(env.get('LIB_INSTALL_DIR'), targets)
-       else:
-               i_n = ienv.Install(env.get('BUILD_DIR'), targets)
-       ienv.Alias("install", i_n)
+               user_lib = env.get('LIB_INSTALL_DIR')
+               if user_lib:
+                       i_n = ienv.Install(user_lib, targets)
+               else:
+                       i_n = ienv.Install(user_prefix + '/lib', targets)
+               ienv.Alias("install", i_n)
 
 def __installbin(ienv, targets, name):
        user_prefix = env.get('PREFIX')
        if user_prefix:
                i_n = ienv.Install(user_prefix + '/bin', targets)
-       else:
-               i_n = ienv.Install(env.get('BUILD_DIR'), targets)
-       ienv.Alias("install", i_n)
+               ienv.Alias("install", i_n)
 
 def __installheader(ienv, targets, dir, name):
        user_prefix = env.get('PREFIX')
        if user_prefix:
-               i_n = ienv.Install(user_prefix + '/include/' + dir, targets)
-       else:
-               i_n = ienv.Install(env.get('BUILD_DIR'), targets)
-       ienv.Alias("install", i_n)
+               i_n = ienv.Install(user_prefix + '/include/' + dir ,targets)
+               ienv.Alias("install", i_n)
 
 def __installpcfile(ienv, targets, name):
        user_prefix = env.get('PREFIX')
        if user_prefix:
-               i_n = ienv.Install(env.get('LIB_INSTALL_DIR') + '/pkgconfig', targets)
-       else:
-               i_n = ienv.Install(env.get('BUILD_DIR'), targets)
-       ienv.Alias("install", i_n)
+               user_lib = env.get('LIB_INSTALL_DIR')
+               if user_lib:
+                       i_n = ienv.Install(user_lib + '/pkgconfig', targets)
+               else:
+                       i_n = ienv.Install(user_prefix + '/lib/pkgconfig', targets)
+               ienv.Alias("install", i_n)
 
 def __append_target(ienv, name, targets = None):
        if targets:
@@ -285,14 +296,22 @@ elif env.get('ROUTING') == 'EP':
        routing_define = 'ROUTING_EP'
 
 user_prefix = env.get('PREFIX')
+user_lib = env.get('LIB_INSTALL_DIR')
+if not user_lib:
+       user_lib = '$${prefix}/lib'
 
 if user_prefix:
        pc_vars = {'\@PREFIX\@': user_prefix,
-                               '\@LIB_INSTALL_DIR\@': env.get('LIB_INSTALL_DIR'),
-                               '\@VERSION\@': '1.0.1', '\@ROUTING_DEFINE\@': routing_define
+                               '\@EXEC_PREFIX\@':user_prefix,
+                               '\@VERSION\@': '1.0.1',
+                               '\@LIB_INSTALL_DIR\@': user_lib,
+                               '\@ROUTING_DEFINE\@': routing_define
                                }
 else:
-       pc_vars = {'\@PREFIX\@': env.get('BUILD_DIR'), '\@VERSION\@': '1.0.1',
+       pc_vars = {'\@PREFIX\@': env.get('BUILD_DIR'),
+                               '\@EXEC_PREFIX\@': env.get('BUILD_DIR'),
+                               '\@VERSION\@': '1.0.1',
+                               '\@LIB_INSTALL_DIR\@': user_lib,
                                '\@ROUTING_DEFINE\@': routing_define
                                }
 
index 8210026..ef6715f 100644 (file)
@@ -239,4 +239,3 @@ SConscript('compatibility/cpp11_compat.scons')
 
 # Make sure that boost for android is available
 SConscript(env.get('SRC_DIR') + '/extlibs/boost/SConscript')
-SConscript(env.get('SRC_DIR') + '/extlibs/expat/SConscript')
index b76c739..1a36575 100644 (file)
@@ -1,4 +1,5 @@
 #include <stdlib.h>
+#include <sys/socket.h>
 
 /* from stdlib.h */
 float strtof(const char *nptr, char **endptr)
@@ -45,3 +46,25 @@ void srandom(unsigned int __s)
 {
     srand48(__s);
 }
+
+/* from __cmsg_nxthdr.cpp */
+/*
+ * The function __cmsg_nxthd() is missing in Android 4.4, but the Android NDK
+ * header files in the version we are using are referencing it and we use it in
+ * our code, this functions was added in version 5.0. To make IoTivity
+ * dynamically loadable at load time on Android KitKat 4.4 add this functions
+ * as a weak symbol, so it will be used if the c lib does not provide it, like
+ * on Android < 5.0 This code was taken from these two resources:
+ * https://raw.githubusercontent.com/android/platform_bionic/master/libc/bionic/__cmsg_nxthdr.cpp
+ * https://github.com/android/platform_bionic/commit/ff64831b0965c16c95c9f81a148f30a6ef3a6c64
+ */
+struct cmsghdr* __attribute__((weak)) __cmsg_nxthdr(struct msghdr* msg, struct cmsghdr* cmsg)
+{
+    struct cmsghdr* ptr;
+    ptr = (struct cmsghdr*)(((unsigned char*) cmsg) + CMSG_ALIGN(cmsg->cmsg_len));
+    size_t len = (unsigned long)((char*)(ptr+1) - (char*) msg->msg_control);
+    if (len > msg->msg_controllen) {
+        return NULL;
+    }
+    return ptr;
+}
index 62d2816..99a64ff 100644 (file)
@@ -128,6 +128,10 @@ with_ra = env.get('WITH_RA')
 if with_ra:
        SConscript(os.path.join(env.get('SRC_DIR'), 'extlibs', 'raxmpp', 'SConscript'))
 
+with_ra_ibb = env.get('WITH_RA_IBB')
+if with_ra_ibb:
+       SConscript(os.path.join(env.get('SRC_DIR'), 'extlibs', 'wksxmppxep', 'SConscript'))
+
 
 env.AddMethod(__prepare_lib, "PrepareLib")
 env.AddMethod(__configure, "Configure")
@@ -136,4 +140,4 @@ env.AddMethod(__install_head_file, "InstallHeadFile")
 env.AddMethod(__install_lib, "InstallLib")
 
 if env.get('SECURED') == '1' and target_os != 'tizen':
-       SConscript(os.path.join(env.get('SRC_DIR'), 'extlibs', 'sqlite3', 'SConscript'))
\ No newline at end of file
+       SConscript(os.path.join(env.get('SRC_DIR'), 'extlibs', 'sqlite3', 'SConscript'))
index 2cb51b5..6a9393b 100644 (file)
@@ -22,7 +22,7 @@ env.AppendUnique(CCFLAGS = ['-Wall', '-Wextra', '-fPIC'])
 env.AppendUnique(LIBS = ['uuid'])
 env.AppendUnique(LINKFLAGS = ['-ldl', '-lpthread'])
 
-# Set arch flags
+# Set arch flags that match best TARGET_ARCH variable
 target_arch = env.get('TARGET_ARCH')
 if target_arch in ['x86']:
        env.AppendUnique(CCFLAGS = ['-m32'])
@@ -30,6 +30,8 @@ if target_arch in ['x86']:
 elif target_arch in ['x86_64']:
        env.AppendUnique(CCFLAGS = ['-m64'])
        env.AppendUnique(LINKFLAGS = ['-m64'])
+elif target_arch in ['arm'] or target_arch.find('v5') > 0:
+       env.AppendUnique(CPPFLAGS = ['-march=armv5te'])
 elif target_arch.find('v7a-hard') > 0:
        env.AppendUnique(CPPFLAGS = ['-march=armv7-a'])
        env.AppendUnique(CPPFLAGS = ['-mfloat-abi=hard'])
@@ -39,5 +41,3 @@ elif target_arch.find('v7a') > 0:
        env.AppendUnique(CPPFLAGS = ['-march=armv7-a'])
 elif target_arch.find('arm64') >= 0:
        env.AppendUnique(CPPFLAGS = ['-march=armv8-a'])
-else:
-       env.AppendUnique(CPPFLAGS = ['-march=armv5te'])
diff --git a/cloud/.gitignore b/cloud/.gitignore
new file mode 100644 (file)
index 0000000..9f1d3ca
--- /dev/null
@@ -0,0 +1,2 @@
+/target/
+*.class
\ No newline at end of file
diff --git a/cloud/README b/cloud/README
new file mode 100644 (file)
index 0000000..81b45a2
--- /dev/null
@@ -0,0 +1,18 @@
+This project contains series of modules for building cloud services.
+
+Modules
+
+1. stack - Java 1.7 based CoAP over TCP implementation.
+2. interface - cloud interface server that accept incoming IoTivity clients connection.
+3. resource_directory - resource directory server that store clients resource models.
+4. account - account server that handle clients credential using OAuth2.
+5. samples - sample IoTivity clients that show how clients working with cloud.
+
+Each cloud modules has README file how to install and run.
+You can run each modules on single computer or PAAS.
+
+Note. resource_directory should launched before interface and account.
+
+Architecture
+client--------interface_server--------resource_directory_server--------mongo_db
+                      \---------------account_server-------------------mongo_db
\ No newline at end of file
diff --git a/cloud/SConscript b/cloud/SConscript
new file mode 100644 (file)
index 0000000..2c60f5c
--- /dev/null
@@ -0,0 +1,32 @@
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+##
+# 'cloud' sub-project main build script
+#
+##
+Import('env')
+
+target_os = env.get('TARGET_OS')
+
+if target_os in ['linux']:
+    # Build sample cloud client project
+    if env.get('WITH_CLOUD') == True:
+        SConscript('samples/client/SConscript')
\ No newline at end of file
diff --git a/cloud/account/.classpath b/cloud/account/.classpath
new file mode 100644 (file)
index 0000000..f619a53
--- /dev/null
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+       <classpathentry kind="src" output="target/classes" path="src/main/java">
+               <attributes>
+                       <attribute name="optional" value="true"/>
+                       <attribute name="maven.pomderived" value="true"/>
+               </attributes>
+       </classpathentry>
+       <classpathentry kind="src" output="target/test-classes" path="src/test/java">
+               <attributes>
+                       <attribute name="optional" value="true"/>
+                       <attribute name="maven.pomderived" value="true"/>
+               </attributes>
+       </classpathentry>
+       <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
+               <attributes>
+                       <attribute name="maven.pomderived" value="true"/>
+               </attributes>
+       </classpathentry>
+       <classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
+               <attributes>
+                       <attribute name="maven.pomderived" value="true"/>
+               </attributes>
+       </classpathentry>
+       <classpathentry kind="output" path="target/classes"/>
+</classpath>
diff --git a/cloud/account/.gitignore b/cloud/account/.gitignore
new file mode 100644 (file)
index 0000000..b83d222
--- /dev/null
@@ -0,0 +1 @@
+/target/
diff --git a/cloud/account/.project b/cloud/account/.project
new file mode 100644 (file)
index 0000000..336bb80
--- /dev/null
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+       <name>CloudAccount</name>
+       <comment></comment>
+       <projects>
+       </projects>
+       <buildSpec>
+               <buildCommand>
+                       <name>org.eclipse.jdt.core.javabuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+               <buildCommand>
+                       <name>org.eclipse.m2e.core.maven2Builder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+       </buildSpec>
+       <natures>
+               <nature>org.eclipse.jdt.core.javanature</nature>
+               <nature>org.eclipse.m2e.core.maven2Nature</nature>
+       </natures>
+</projectDescription>
diff --git a/cloud/account/README b/cloud/account/README
new file mode 100644 (file)
index 0000000..08ac84c
--- /dev/null
@@ -0,0 +1,29 @@
+This project contains the Account Server code.
+
+
+Build and Run
+
+1) Install Apache Maven if you don't have it
+
+       http://maven.apache.org
+
+2) Build a CloudStack. If you are building first time, then build the stack.
+
+       go to "stack" folder in root directory
+       $ mvn install -Dmaven.test.skip=true
+
+3) Build a .jar file
+
+       $ mvn install -Dmaven.test.skip=true
+
+       - The CloudAccount-0.0.1-SNAPSHOT.jar file will be placed in the "target" folder
+
+4) Run .jar file
+
+       go to "target" folder
+       $ java -jar CloudAccount-0.0.1-SNAPSHOT.jar arg1(AccountServer CoAP Server Port)
+       e.g. java -jar CloudAccount-0.0.1-SNAPSHOT.jar 5685
+
+       - Before you run a Accout server, You need to set up following steps.
+          1) Install MongoDB
+          2) Install Github certificates for github.com and *.github.com.
diff --git a/cloud/account/pom.xml b/cloud/account/pom.xml
new file mode 100644 (file)
index 0000000..e4d08ab
--- /dev/null
@@ -0,0 +1,79 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.iotivity.cloud</groupId>
+  <artifactId>CloudAccount</artifactId>
+  <version>0.0.1-SNAPSHOT</version>
+  
+  <properties>
+               <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+       </properties>
+       
+  <dependencies>
+               <dependency>
+                       <groupId>org.iotivity.cloud</groupId>
+                       <artifactId>CloudStack</artifactId>
+                       <version>0.0.1-SNAPSHOT</version>
+               </dependency>
+               <dependency>
+                       <groupId>org.mongodb</groupId>
+                       <artifactId>mongo-java-driver</artifactId>
+                       <version>3.2.0</version>
+               </dependency>
+               <dependency>
+                       <groupId>junit</groupId>
+                       <artifactId>junit</artifactId>
+                       <version>4.12</version>
+               </dependency>
+               <dependency>
+                       <groupId>org.apache.oltu.oauth2</groupId>
+                       <artifactId>org.apache.oltu.oauth2.client</artifactId>
+                       <version>1.0.1</version>
+               </dependency>
+  </dependencies>
+       
+  <build>
+               <plugins>
+                       <plugin>
+                               <inherited>true</inherited>
+                               <groupId>org.apache.maven.plugins</groupId>
+                               <artifactId>maven-compiler-plugin</artifactId>
+                               <configuration>
+                                       <source>1.7</source>
+                                       <target>1.7</target>
+                                       <encoding>UTF-8</encoding>
+                               </configuration>
+                       </plugin>
+                       <plugin>
+                               <groupId>org.apache.maven.plugins</groupId>
+                               <artifactId>maven-jar-plugin</artifactId>
+                               <configuration>
+                                       <archive>
+                                               <manifest>
+                                                       <mainClass>org.iotivity.cloud.accountserver.AccountServer</mainClass>
+                                                       <addClasspath>true</addClasspath>
+                                                       <classpathPrefix>lib/</classpathPrefix>
+                                               </manifest>
+                                       </archive>
+                               </configuration>
+                       </plugin>
+                       <plugin>
+                               <groupId>org.apache.maven.plugins</groupId>
+                               <artifactId>maven-dependency-plugin</artifactId>
+                               <executions>
+                                       <execution>
+                                               <id>copy-dependencies</id>
+                                               <phase>package</phase>
+                                               <goals>
+                                                       <goal>copy-dependencies</goal>
+                                               </goals>
+                                       </execution>
+                               </executions>
+                               <configuration>
+                                       <outputDirectory>target/lib</outputDirectory>
+                                       <overWriteIfNewer>true</overWriteIfNewer>
+                               </configuration>
+                       </plugin>
+               </plugins>              
+       </build>
+  
+</project>
\ No newline at end of file
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/AccountServer.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/AccountServer.java
new file mode 100644 (file)
index 0000000..a9d6925
--- /dev/null
@@ -0,0 +1,78 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.accountserver;
+
+import java.net.InetSocketAddress;
+import java.util.Scanner;
+
+import org.iotivity.cloud.accountserver.resources.AccountResource;
+import org.iotivity.cloud.accountserver.resources.AuthResource;
+import org.iotivity.cloud.base.CoapServer;
+import org.iotivity.cloud.base.ResourceManager;
+import org.iotivity.cloud.util.Logger;
+
+/**
+ *
+ * This class is in charge of running of account server.
+ *
+ */
+public class AccountServer {
+
+    public static void main(String[] args) throws Exception {
+
+        System.out.println("-----Account SERVER-----");
+
+        if (args.length != 1) {
+            Logger.e("coap server port required");
+            return;
+        }
+
+        ResourceManager resourceManager = null;
+
+        CoapServer coapServer = null;
+
+        coapServer = new CoapServer();
+
+        resourceManager = new ResourceManager();
+        coapServer.addHandler(resourceManager);
+
+        resourceManager.registerResource(new AuthResource());
+        resourceManager.registerResource(new AccountResource());
+
+        coapServer
+                .startServer(new InetSocketAddress(Integer.parseInt(args[0])));
+
+        Scanner in = new Scanner(System.in, "UTF-8");
+
+        System.out.println("press 'q' to terminate");
+
+        while (!in.nextLine().equals("q"));
+
+        in.close();
+
+        System.out.println("Terminating...");
+
+        coapServer.stopServer();
+
+        System.out.println("Terminated");
+    }
+}
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/AccountServerManager.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/AccountServerManager.java
new file mode 100644 (file)
index 0000000..b2b29a8
--- /dev/null
@@ -0,0 +1,197 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.accountserver;
+
+import java.util.ArrayList;
+import java.util.Random;
+
+import org.iotivity.cloud.accountserver.db.AccountDBManager;
+import org.iotivity.cloud.accountserver.oauth.GitHub;
+import org.iotivity.cloud.util.Logger;
+
+/**
+ *
+ * This class provides a set of APIs to handle requests about account
+ * information of authorized user.
+ *
+ */
+public class AccountServerManager {
+
+    /**
+     * API for requesting user account
+     *
+     * @param userId
+     *            user identifier
+     * @param deviceId
+     *            device identifier
+     * @return Boolean - true if registered, otherwise false
+     */
+    public Boolean registerUserAccount(String userId, String deviceId) {
+
+        Boolean ret = false;
+
+        // store info to OAuthDBManager
+        ret = AccountDBManager.getInstance().registerUserDevice(userId,
+                deviceId);
+
+        return ret;
+    }
+
+    /**
+     * API for requesting user account and getting session code for registered
+     * user.
+     *
+     * @param userId
+     *            user identifier
+     * @return String - session code for registered user
+     */
+    public String registerUserAccount(String userId) {
+
+        String sessionCode = null;
+        sessionCode = generateSessionCode();
+
+        // store info to OAuthDBManager
+        AccountDBManager.getInstance().registerUserSessionCode(userId,
+                sessionCode);
+
+        return sessionCode;
+    }
+
+    /**
+     * API for requesting user identifier corresponding with authorization
+     * information.
+     *
+     * @param authCode
+     *            authorization code
+     * @param authServer
+     *            authorization server
+     * @return String - user identifier
+     */
+    public String requestUserId(String authCode, String authServer) {
+
+        String userId = null;
+
+        String accessToken = getAccessToken(authCode, authServer);
+        userId = getUserId(accessToken, authServer);
+
+        return userId;
+    }
+
+    /**
+     * API for requesting user identifier corresponding with session code.
+     *
+     * @param sessionCode
+     *            session code
+     * @return String - user identifier
+     */
+    public String requestUserId(String sessionCode) {
+
+        String userId = null;
+
+        // get userId from MongDB
+        userId = AccountDBManager.getInstance().getUserId(sessionCode);
+
+        return userId;
+    }
+
+    /**
+     * API for getting devices corresponding with user identifier.
+     *
+     * @param userId
+     *            user identifier
+     * @return ArrayList<String> - list of devices
+     */
+    public ArrayList<String> requestAccountDevices(String userId) {
+
+        Logger.d("userId= " + userId);
+
+        ArrayList<String> deviceList = AccountDBManager.getInstance()
+                .getDevices(userId);
+
+        return deviceList;
+    }
+
+    private String getAccessToken(String authCode, String authServer) {
+
+        String accessToken = null;
+
+        if (authServer.equals(Constants.GITHUB)) {
+
+            GitHub gitHub = new GitHub();
+            accessToken = gitHub.requestAccessToken(authCode);
+
+        } else {
+
+            Logger.e("unsupported auth.server = " + authServer);
+        }
+
+        return accessToken;
+    }
+
+    private String getUserId(String accessToken, String authServer) {
+
+        String userId = null;
+
+        if (authServer.equals(Constants.GITHUB)) {
+
+            GitHub gitHub = new GitHub();
+            userId = gitHub.requestGetUserInfo(accessToken);
+
+        } else {
+
+            Logger.e("unsupported auth.server = " + authServer);
+        }
+
+        return userId;
+    }
+
+    private String generateSessionCode() {
+
+        StringBuffer sessionCode = new StringBuffer();
+
+        Random random = new Random();
+        int randomNum = random.nextInt(122);
+        char code;
+
+        // generate 16byte key with 0-9, A-Z, a-z
+        for (int k = 0; k < 16; k++) {
+            while (true) {
+                if ((randomNum >= 48 && randomNum <= 57)
+                        || (randomNum >= 65 && randomNum <= 90)
+                        || (randomNum >= 97 && randomNum <= 122)) {
+
+                    code = (char) randomNum;
+                    sessionCode.append(code);
+
+                    randomNum = random.nextInt(122);
+                    break;
+
+                } else {
+
+                    randomNum = random.nextInt(122);
+                }
+            }
+        }
+
+        return sessionCode.toString();
+    }
+}
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/Constants.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/Constants.java
new file mode 100644 (file)
index 0000000..2d8ab4f
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.accountserver;
+
+public class Constants {
+
+    // MongoDB
+    public static final String DEVICE_TABLE          = "USER_DEVICE";
+    public static final String SESSION_TABLE         = "USER_SESSION";
+    public static final String DB_NAME               = "ACCOUNTSERVER_DB";
+    public static final String USER_ID               = "userId";
+    public static final String DEVICE_ID             = "deviceId";
+    public static final String SESSION_CODE          = "sessionCode";
+
+    // Resource Uri
+    public static final String AUTH_URI              = "oic/auth";
+    public static final String ACCOUNT_URI           = "oic/account";
+
+    // query parameter
+    public static final String REQ_TYPE              = "reqtype";
+
+    // request type
+    public static final String TYPE_REGISTER         = "register";
+    public static final String TYPE_LOGIN            = "login";
+    public static final String TYPE_PUBLISH          = "publish";
+    public static final String TYPE_FIND             = "find";
+
+    // request payload
+    public static final String REQUEST_AUTH_CODE     = "authcode";
+    public static final String REQUEST_AUTH_SERVER   = "authprovider";
+    public static final String REQUEST_DEVICE_ID     = "deviceid";
+    public static final String REQUEST_USER_ID       = "userid";
+    public static final String REQUEST_SESSION_CODE  = "session";
+
+    // response
+    public static final String RESPONSE_SESSION_CODE = "session";
+    public static final String RESPONSE_USER_ID      = "userid";
+    public static final String RESPONSE_STATE        = "state";
+    public static final String RESPONSE_DEVICES      = "devices";
+
+    // auth servers
+    public static final String GITHUB                = "github";
+    public static final String GOOGLE                = "google";
+    public static final String FACEBOOK              = "facebook";
+}
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/db/AccountDBManager.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/db/AccountDBManager.java
new file mode 100644 (file)
index 0000000..8569753
--- /dev/null
@@ -0,0 +1,151 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.accountserver.db;
+
+import java.util.ArrayList;
+
+import org.iotivity.cloud.accountserver.Constants;
+
+/**
+ *
+ * This class provides a set of APIs managing database.
+ *
+ */
+public class AccountDBManager {
+
+    private static AccountDBManager accoutDBManager = new AccountDBManager();
+    private MongoDB                 mongoDB;
+
+    private AccountDBManager() {
+
+        try {
+
+            mongoDB = new MongoDB(Constants.DB_NAME);
+
+            mongoDB.createTable(Constants.DEVICE_TABLE);
+            mongoDB.createTable(Constants.SESSION_TABLE);
+
+            registerAdminAccount();
+
+        } catch (Exception e) {
+
+            e.printStackTrace();
+
+        }
+    }
+
+    public static AccountDBManager getInstance() {
+
+        return accoutDBManager;
+    }
+
+    /**
+     * API for storing session information of authorized user
+     *
+     * @param userId
+     *            user identifier
+     * @param sessionCode
+     *            session code
+     * @return Boolean - true if stored, otherwise false
+     */
+    public Boolean registerUserSessionCode(String userId, String sessionCode) {
+
+        UserSession userSession = new UserSession();
+
+        userSession.setUserId(userId);
+        userSession.setSessionCode(sessionCode);
+
+        mongoDB.createResource(userSession);
+        mongoDB.printResources();
+
+        return true;
+    }
+
+    /**
+     * API for storing device information of authorized user
+     *
+     * @param userId
+     *            user identifier
+     * @param deviceId
+     *            device identifier
+     * @return Boolean - true if stored, otherwise false
+     */
+    public Boolean registerUserDevice(String userId, String deviceId) {
+
+        UserDevice userDevice = new UserDevice();
+
+        userDevice.setUserId(userId);
+        userDevice.setDeviceId(deviceId);
+
+        mongoDB.createResource(userDevice);
+        mongoDB.printResources();
+
+        return true;
+    }
+
+    /**
+     * API for getting user identifier information corresponding with session
+     * code
+     *
+     * @param userId
+     *            identifier of authorized user
+     * @param sessionCode
+     *            session code
+     * @return Boolean - true if stored, otherwise false
+     */
+    public String getUserId(String sessionCode) {
+
+        String userId = null;
+
+        userId = mongoDB.getUserId(sessionCode);
+
+        return userId;
+    }
+
+    /**
+     * API for getting devices corresponding with user identifier
+     *
+     * @param userId
+     *            user identifier
+     * @return ArrayList<String> - list of devices
+     */
+    public ArrayList<String> getDevices(String userId) {
+
+        ArrayList<String> deviceList = mongoDB.getDevices(userId);
+
+        return deviceList;
+    }
+
+    private void registerAdminAccount() {
+
+        String adminId = "admin";
+        String adminSessionCode = "00000000";
+
+        UserSession userSession = new UserSession();
+
+        userSession.setUserId(adminId);
+        userSession.setSessionCode(adminSessionCode);
+
+        mongoDB.createResource(userSession);
+        mongoDB.printResources();
+    }
+}
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/db/MongoDB.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/db/MongoDB.java
new file mode 100644 (file)
index 0000000..049a3f3
--- /dev/null
@@ -0,0 +1,310 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.accountserver.db;
+
+import java.util.ArrayList;
+
+import org.bson.Document;
+import org.iotivity.cloud.accountserver.Constants;
+import org.iotivity.cloud.util.Logger;
+
+import com.mongodb.MongoClient;
+import com.mongodb.client.MongoCollection;
+import com.mongodb.client.MongoCursor;
+import com.mongodb.client.MongoDatabase;
+import com.mongodb.client.model.Filters;
+
+/**
+ *
+ * This class provides a set of APIs to use MongoDB APIs.
+ *
+ */
+public class MongoDB {
+
+    private MongoClient   mongoClient = null;
+    private MongoDatabase db          = null;
+
+    /**
+     * API creating MongoClient and initializing MongoDatabase
+     * 
+     * @param dbname
+     *            database name to create MongoDatabase
+     * @throws Exception
+     */
+    public MongoDB(String dbname) throws Exception {
+
+        mongoClient = new MongoClient();
+        mongoClient.dropDatabase(dbname);
+        db = mongoClient.getDatabase(dbname);
+    }
+
+    /**
+     * API creating collection
+     * 
+     * @param tableName
+     *            collection name
+     */
+    public void createTable(String tableName) {
+
+        db.createCollection(tableName);
+    }
+
+    /**
+     * API deleting collection
+     * 
+     * @param tableName
+     *            collection name
+     */
+    public void deleteTable(String tableName) {
+
+        db.getCollection(tableName).drop();
+    }
+
+    /**
+     * API getting database object
+     * 
+     */
+    public MongoDatabase getMongoDatabase() {
+
+        return db;
+    }
+
+    /**
+     * API for storing session information of user
+     * 
+     * @param UserSession
+     *            session information of user
+     */
+    public void createResource(UserSession userSession) {
+
+        Document doc = createDocument(userSession);
+        MongoCollection<Document> collection = db
+                .getCollection(Constants.SESSION_TABLE);
+
+        if (collection.findOneAndReplace(Filters.and(
+                Filters.eq(Constants.USER_ID, doc.get(Constants.USER_ID)),
+                Filters.eq(Constants.SESSION_CODE, doc.get(Constants.SESSION_CODE))),
+                doc) == null) {
+
+            collection.insertOne(doc);
+        }
+
+        return;
+    }
+
+    /**
+     * API for inserting device information of user
+     * 
+     * @param UserDevice
+     *            device information of user
+     */
+    public void createResource(UserDevice userDevice) {
+
+        Document doc = createDocument(userDevice);
+        MongoCollection<Document> collection = db
+                .getCollection(Constants.DEVICE_TABLE);
+
+        if (collection.findOneAndReplace(Filters.and(
+                Filters.eq(Constants.USER_ID, doc.get(Constants.USER_ID)),
+                Filters.eq(Constants.DEVICE_ID, doc.get(Constants.DEVICE_ID))), doc) == null) {
+
+            collection.insertOne(doc);
+        }
+
+        return;
+    }
+
+    /**
+     * API for getting user identifier corresponding with session code from
+     * database
+     * 
+     * @param sessionCode
+     *            session code
+     * @return String - user identifier
+     */
+    public String getUserId(String sessionCode) {
+
+        String userId = null;
+
+        MongoCollection<Document> collection = db
+                .getCollection(Constants.SESSION_TABLE);
+
+        MongoCursor<Document> cursor = collection.find(
+                Filters.eq(Constants.SESSION_CODE, sessionCode)).iterator();
+
+        try {
+
+            while (cursor.hasNext()) {
+
+                Document doc = cursor.next();
+                UserSession userSession = convertSessionDocToResource(doc);
+
+                userId = userSession.getUserId();
+                break;
+            }
+
+        } finally {
+
+            cursor.close();
+        }
+
+        return userId;
+    }
+
+    /**
+     * API for getting devices corresponding with user identifier from database
+     * 
+     * @param userId
+     *            user identifier
+     */
+    public ArrayList<String> getDevices(String userId) {
+
+        ArrayList<String> deviceList = new ArrayList<String>();
+
+        MongoCollection<Document> collection = db
+                .getCollection(Constants.DEVICE_TABLE);
+
+        MongoCursor<Document> cursor = collection.find(
+                Filters.eq(Constants.USER_ID, userId)).iterator();
+
+        try {
+
+            while (cursor.hasNext()) {
+
+                Document doc = cursor.next();
+                UserDevice userDeivce = convertDeviceDocToResource(doc);
+
+                deviceList.add(userDeivce.getDeviceId());
+            }
+
+        } finally {
+
+            cursor.close();
+        }
+
+        return deviceList;
+    }
+
+    public void printResources() {
+
+        ArrayList<UserDevice> dlist = readDeviceResources();
+        int size = dlist.size();
+
+        Logger.i("*Table: " + Constants.DEVICE_TABLE);
+        for (int i = 0; i < size; i++) {
+
+            UserDevice item = dlist.get(i);
+
+            Logger.i("[" + i + "]" + item.getUserId() + ", "
+                    + item.getDeviceId());
+        }
+
+        ArrayList<UserSession> slist = readSessionResources();
+        size = slist.size();
+
+        Logger.i("*Table: " + Constants.SESSION_TABLE);
+
+        for (int i = 0; i < size; i++) {
+
+            UserSession item = slist.get(i);
+
+            Logger.i("[" + i + "]" + item.getUserId() + ", "
+                    + item.getSessionCode());
+
+        }
+    }
+
+    private Document createDocument(UserSession userSession) {
+
+        Document doc = new Document(Constants.USER_ID, userSession.getUserId())
+                .append(Constants.SESSION_CODE, userSession.getSessionCode());
+
+        return doc;
+    }
+
+    private Document createDocument(UserDevice userDevice) {
+
+        Document doc = new Document(Constants.USER_ID, userDevice.getUserId())
+                .append(Constants.DEVICE_ID, userDevice.getDeviceId());
+
+        return doc;
+    }
+
+    private UserSession convertSessionDocToResource(Document doc) {
+
+        UserSession userSession = new UserSession();
+
+        userSession.setUserId(doc.getString(Constants.USER_ID));
+        userSession.setSessionCode(doc.getString(Constants.SESSION_CODE));
+
+        return userSession;
+    }
+
+    private UserDevice convertDeviceDocToResource(Document doc) {
+
+        UserDevice userDevice = new UserDevice();
+
+        userDevice.setUserId(doc.getString(Constants.USER_ID));
+        userDevice.setDeviceId(doc.getString(Constants.DEVICE_ID));
+
+        return userDevice;
+    }
+
+    private ArrayList<UserSession> readSessionResources() {
+
+        ArrayList<UserSession> userSessionList = new ArrayList<UserSession>();
+
+        MongoCollection<Document> collection = db
+                .getCollection(Constants.SESSION_TABLE);
+        MongoCursor<Document> cursor = collection.find().iterator();
+
+        while (cursor.hasNext()) {
+
+            Document doc = cursor.next();
+            userSessionList.add(convertSessionDocToResource(doc));
+        }
+
+        cursor.close();
+
+        return userSessionList;
+    }
+
+    private ArrayList<UserDevice> readDeviceResources() {
+
+        ArrayList<UserDevice> userDeviceList = new ArrayList<UserDevice>();
+
+        MongoCollection<Document> collection = db
+                .getCollection(Constants.DEVICE_TABLE);
+        MongoCursor<Document> cursor = collection.find().iterator();
+
+        while (cursor.hasNext()) {
+
+            Document doc = cursor.next();
+            userDeviceList.add(convertDeviceDocToResource(doc));
+        }
+
+        cursor.close();
+
+        return userDeviceList;
+    }
+
+}
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/db/UserDevice.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/db/UserDevice.java
new file mode 100644 (file)
index 0000000..b0cc3c6
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.accountserver.db;
+
+/**
+ *
+ * This class provides a set of APIs storing device information of authorized
+ * user.
+ *
+ */
+public class UserDevice {
+
+    private String userId   = null;
+    private String deviceId = null;
+
+    public void setUserId(String id) {
+        this.userId = id;
+    }
+
+    public void setDeviceId(String id) {
+        this.deviceId = id;
+    }
+
+    public String getUserId() {
+        return this.userId;
+    }
+
+    public String getDeviceId() {
+        return this.deviceId;
+    }
+}
\ No newline at end of file
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/db/UserSession.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/db/UserSession.java
new file mode 100644 (file)
index 0000000..f254dcc
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.accountserver.db;
+
+/**
+ *
+ * This class provides a set of APIs storing session information of authorized
+ * user.
+ *
+ */
+public class UserSession {
+
+    private String userId      = null;
+    private String sessionCode = null;
+
+    public void setUserId(String id) {
+        this.userId = id;
+    }
+
+    public void setSessionCode(String code) {
+        this.sessionCode = code;
+    }
+
+    public String getUserId() {
+        return this.userId;
+    }
+
+    public String getSessionCode() {
+        return this.sessionCode;
+    }
+}
\ No newline at end of file
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/oauth/GitHub.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/oauth/GitHub.java
new file mode 100644 (file)
index 0000000..e682257
--- /dev/null
@@ -0,0 +1,109 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.accountserver.oauth;
+
+import org.apache.oltu.oauth2.client.OAuthClient;
+import org.apache.oltu.oauth2.client.URLConnectionClient;
+import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest;
+import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
+import org.apache.oltu.oauth2.client.response.GitHubTokenResponse;
+import org.apache.oltu.oauth2.client.response.OAuthResourceResponse;
+import org.apache.oltu.oauth2.common.OAuth;
+import org.apache.oltu.oauth2.common.OAuthProviderType;
+import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
+import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
+import org.apache.oltu.oauth2.common.message.types.GrantType;
+import org.iotivity.cloud.util.JSONUtil;
+import org.iotivity.cloud.util.Logger;
+
+/**
+ *
+ * This class provides APIs relating authorization for GitHub.
+ *
+ */
+public class GitHub extends OAuthServer {
+
+    final static private String client_id    = "ea9c18f540323b0213d0";
+    final static private String secret       = "4bc0cd9fe21269507eb8eba3a32664a0f598dbc9";
+    final static private String resource_url = "https://api.github.com/user";
+
+    @Override
+    public String requestAccessToken(String authCode) {
+
+        String accessToken = null;
+
+        try {
+
+            OAuthClientRequest request = OAuthClientRequest
+                    .tokenProvider(OAuthProviderType.GITHUB)
+                    .setGrantType(GrantType.AUTHORIZATION_CODE)
+                    .setClientId(client_id).setClientSecret(secret)
+                    .setCode(authCode).buildBodyMessage();
+
+            OAuthClient oAuthClient = new OAuthClient(
+                    new URLConnectionClient());
+            GitHubTokenResponse oAuthResponse = oAuthClient.accessToken(request,
+                    GitHubTokenResponse.class);
+
+            accessToken = oAuthResponse.getAccessToken();
+
+        } catch (OAuthSystemException | OAuthProblemException e) {
+            e.printStackTrace();
+        }
+
+        return accessToken;
+    }
+
+    @Override
+    public String requestGetUserInfo(String accessToken) {
+
+        String userInfo = null;
+
+        if (accessToken == null) {
+            Logger.w("accessToken is null!");
+            return null;
+        }
+
+        try {
+
+            OAuthClientRequest request = new OAuthBearerClientRequest(
+                    resource_url).setAccessToken(accessToken)
+                    .buildQueryMessage();
+
+            OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
+            
+            OAuthResourceResponse resourceResponse = oAuthClient.resource(
+                    request, OAuth.HttpMethod.GET, OAuthResourceResponse.class);
+
+            userInfo = resourceResponse.getBody();
+            Logger.d("userInfo: " + userInfo);
+
+        } catch (OAuthSystemException | OAuthProblemException e) {
+            e.printStackTrace();
+        }
+
+        String userIdKey = "login";
+        String userId = JSONUtil.parseJSON(userInfo, userIdKey);
+
+        return userId;
+    }
+}
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/oauth/OAuthServer.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/oauth/OAuthServer.java
new file mode 100644 (file)
index 0000000..a6f3efc
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.accountserver.oauth;
+
+/**
+ *
+ * This class provides abstraction of APIs relating authorization for OAuth 2.0
+ *
+ */
+public abstract class OAuthServer {
+
+    /**
+     * API for requesting access token
+     * 
+     * @param authCode
+     *            authorization code
+     * @return access token
+     */
+    public abstract String requestAccessToken(String authCode);
+
+    /**
+     * API for getting user's information
+     * 
+     * @param accessToken
+     *            access token
+     * @return String - user information of json type
+     */
+    public abstract String requestGetUserInfo(String accessToken);
+}
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/AccountResource.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/AccountResource.java
new file mode 100644 (file)
index 0000000..bde32bf
--- /dev/null
@@ -0,0 +1,253 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.accountserver.resources;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+import org.iotivity.cloud.accountserver.AccountServerManager;
+import org.iotivity.cloud.accountserver.Constants;
+import org.iotivity.cloud.accountserver.util.CoapMessageBuilder;
+import org.iotivity.cloud.base.Resource;
+import org.iotivity.cloud.base.protocols.coap.CoapRequest;
+import org.iotivity.cloud.base.protocols.coap.CoapResponse;
+import org.iotivity.cloud.base.protocols.coap.enums.CoapMethod;
+import org.iotivity.cloud.base.protocols.coap.enums.CoapStatus;
+import org.iotivity.cloud.util.JSONUtil;
+import org.iotivity.cloud.util.Logger;
+
+import io.netty.channel.ChannelHandlerContext;
+
+/**
+ *
+ * This class provides a set of APIs to manage resources corresponding with user
+ * account
+ *
+ */
+public class AccountResource extends Resource {
+
+    public AccountResource() {
+        setUri(Constants.ACCOUNT_URI);
+    }
+
+    @Override
+    public void onRequestReceived(ChannelHandlerContext ctx,
+            CoapRequest request) {
+
+        Logger.d("AccountResource IN");
+
+        if (ctx == null || request == null) {
+            Logger.d("ctx or request msg is null");
+        }
+
+        else {
+            CoapMethod method = request.getRequestMethod();
+
+            switch (method) {
+                case GET:
+                    try {
+                        handleGetRequest(ctx, request);
+                    } catch (Exception e) {
+                        e.printStackTrace();
+                    }
+                    break;
+
+                case POST:
+                    try {
+                        handlePostRequest(ctx, request);
+                    } catch (Exception e) {
+                        e.printStackTrace();
+                    }
+                    break;
+
+                default:
+                    Logger.w("method[" + method + "] is not supported");
+                    break;
+            }
+        }
+    }
+
+    private void handleGetRequest(ChannelHandlerContext ctx,
+            CoapRequest request) throws Exception {
+
+        String reqType = extractQuery(request, Constants.REQ_TYPE);
+
+        if (reqType == null)
+            throw new IllegalArgumentException(
+                    "request type is null in query!");
+
+        CoapResponse response = null;
+
+        switch (reqType) {
+            case Constants.TYPE_FIND:
+                response = handleFindRequest(request);
+                break;
+            default:
+                Logger.w("reqType[" + reqType + "] is not supported");
+        }
+        if (response != null) {
+            ctx.writeAndFlush(response);
+        }
+
+    }
+
+    private void handlePostRequest(ChannelHandlerContext ctx,
+            CoapRequest request) throws Exception {
+
+        String reqType = extractQuery(request, Constants.REQ_TYPE);
+
+        if (reqType == null)
+            throw new IllegalArgumentException(
+                    "request type is null in query!");
+
+        CoapResponse response;
+
+        switch (reqType) {
+            case Constants.TYPE_PUBLISH:
+                response = handlePublishRequest(request);
+                break;
+            default:
+                throw new IllegalArgumentException(
+                        "request type is not supported");
+        }
+
+        ctx.writeAndFlush(response);
+    }
+
+    /**
+     * API for handling request for publishing resource corresponding with user
+     * account
+     *
+     * @param requeset
+     *            CoAP request message
+     * @return CoapResponse - CoAP response message with response result
+     *         information
+     */
+    private CoapResponse handlePublishRequest(CoapRequest request) {
+
+        String payload = request.getPayloadString();
+
+        String userId = JSONUtil.parseJSON(payload, Constants.REQUEST_USER_ID);
+        String deviceId = JSONUtil.parseJSON(payload,
+                Constants.REQUEST_DEVICE_ID);
+
+        Logger.d("userId: " + userId + ", deviceId: " + deviceId);
+
+        AccountServerManager oauthServerManager = new AccountServerManager();
+        Boolean status = oauthServerManager.registerUserAccount(userId,
+                deviceId);
+
+        Logger.d("status : " + status);
+
+        CoapMessageBuilder responseMessage = new CoapMessageBuilder();
+        CoapResponse coapResponse;
+
+        if (status) {
+            coapResponse = responseMessage.buildCoapResponse(request.getToken(),
+                    CoapStatus.CREATED);
+        } else {
+            coapResponse = responseMessage.buildCoapResponse(request.getToken(),
+                    CoapStatus.INTERNAL_SERVER_ERROR);
+        }
+
+        return coapResponse;
+    }
+
+    /**
+     * API for handling request for finding resource corresponding with user
+     * account
+     *
+     * @param requeset
+     *            CoAP request message
+     * @return CoapResponse - CoAP response message with response result
+     *         information
+     */
+    private CoapResponse handleFindRequest(CoapRequest request) {
+
+        String payload = request.getPayloadString();
+        // String payload = getPayloadString(request.getPayload());
+
+        JSONUtil util = new JSONUtil();
+        String userId = util.parseJSON(payload, Constants.REQUEST_USER_ID);
+
+        Logger.d("userId: " + userId);
+
+        AccountServerManager oauthServerManager = new AccountServerManager();
+        ArrayList<String> deviceList = oauthServerManager
+                .requestAccountDevices(userId);
+
+        ResponseObject response = new ResponseObject();
+        response.setDeviceList(deviceList);
+
+        String responseJson = convertFindResponseToJson(response);
+        Logger.d("responseJson: " + responseJson);
+
+        CoapMessageBuilder responseMessage = new CoapMessageBuilder();
+        CoapResponse coapResponse = responseMessage.buildCoapResponse(
+                request.getToken(), responseJson, CoapStatus.CONTENT);
+
+        return coapResponse;
+    }
+
+    private String convertFindResponseToJson(ResponseObject response) {
+
+        HashMap<Object, Object> responseMap = new HashMap<Object, Object>();
+
+        ArrayList<String> deviceList = response.getDeviceList();
+        responseMap.put(Constants.RESPONSE_DEVICES, deviceList);
+
+        String responseJson = JSONUtil.writeJSON(responseMap);
+
+        return responseJson;
+    }
+
+    private String extractQuery(CoapRequest request, String key) {
+
+        String value = null;
+
+        List<String> Segments = request.getUriQuerySegments();
+
+        if (Segments != null) {
+            for (String s : Segments) {
+
+                String pair[] = s.split("=");
+
+                if (pair[0].equals(key)) {
+
+                    value = pair[1];
+                }
+            }
+        }
+
+        return value;
+    }
+
+    /*
+     * private static String getPayloadString(byte[] payload) {
+     *
+     * if (payload == null) return "";
+     *
+     * return new String(payload, Charset.forName("UTF-8")); }
+     */
+
+}
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/AuthResource.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/AuthResource.java
new file mode 100644 (file)
index 0000000..a88bcf8
--- /dev/null
@@ -0,0 +1,273 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.accountserver.resources;
+
+import java.util.HashMap;
+import java.util.List;
+
+import org.iotivity.cloud.accountserver.AccountServerManager;
+import org.iotivity.cloud.accountserver.Constants;
+import org.iotivity.cloud.accountserver.util.CoapMessageBuilder;
+import org.iotivity.cloud.base.Resource;
+import org.iotivity.cloud.base.protocols.coap.CoapRequest;
+import org.iotivity.cloud.base.protocols.coap.CoapResponse;
+import org.iotivity.cloud.base.protocols.coap.enums.CoapMethod;
+import org.iotivity.cloud.base.protocols.coap.enums.CoapStatus;
+import org.iotivity.cloud.util.JSONUtil;
+import org.iotivity.cloud.util.Logger;
+
+import io.netty.channel.ChannelHandlerContext;
+
+/**
+ *
+ * This class provides a set of APIs to manage user account with authorization
+ * process.
+ *
+ */
+public class AuthResource extends Resource {
+
+    public AuthResource() {
+        setUri(Constants.AUTH_URI);
+    }
+
+    @Override
+    public void onRequestReceived(ChannelHandlerContext ctx,
+            CoapRequest request) {
+
+        Logger.d("AuthResource IN");
+
+        if (ctx == null || request == null) {
+            Logger.d("ctx or request msg is null");
+        }
+
+        else {
+            CoapMethod method = request.getRequestMethod();
+
+            switch (method) {
+                case POST:
+                    try {
+                        handlePostRequest(ctx, request);
+                    } catch (Exception e) {
+                        e.printStackTrace();
+                    }
+                    break;
+
+                default:
+                    Logger.w("method(" + method + ") is not supported");
+                    break;
+            }
+        }
+    }
+
+    private void handlePostRequest(ChannelHandlerContext ctx,
+            CoapRequest request) throws Exception {
+
+        String reqType = extractQuery(request, Constants.REQ_TYPE);
+
+        if (reqType == null)
+            throw new IllegalArgumentException(
+                    "request type is null in query!");
+
+        CoapResponse response;
+
+        switch (reqType) {
+            case Constants.TYPE_REGISTER:
+                response = handleRegisterRequest(request);
+                break;
+            case Constants.TYPE_LOGIN:
+                response = handleLoginRequest(request);
+                break;
+            default:
+                throw new IllegalArgumentException(
+                        "request type is not supported");
+        }
+
+        ctx.writeAndFlush(response);
+    }
+
+    /**
+     * API for handling request for login by user account
+     *
+     * @param request
+     *            CoAP request message
+     * @return CoapResponse - CoAP response message with response result
+     *         information
+     */
+    private CoapResponse handleLoginRequest(CoapRequest request) {
+
+        String payload = request.getPayloadString();
+
+        String sessionCode = JSONUtil.parseJSON(payload,
+                Constants.REQUEST_SESSION_CODE);
+
+        Logger.d("sessionCode: " + sessionCode);
+
+        AccountServerManager oauthServerManager = new AccountServerManager();
+        String userId = oauthServerManager.requestUserId(sessionCode);
+        Logger.d("userId: " + userId);
+
+        CoapMessageBuilder responseMessage = new CoapMessageBuilder();
+        CoapResponse coapResponse;
+
+        if (userId != null) {
+
+            ResponseObject response = new ResponseObject();
+            response.setUserId(userId);
+
+            String responseJson = convertLoginResponseToJson(response);
+            Logger.d("responseJson: " + responseJson);
+
+            coapResponse = responseMessage.buildCoapResponse(request.getToken(),
+                    responseJson, CoapStatus.CREATED);
+
+        } else {
+
+            coapResponse = responseMessage.buildCoapResponse(request.getToken(),
+                    CoapStatus.INTERNAL_SERVER_ERROR);
+
+        }
+
+        return coapResponse;
+    }
+
+    /**
+     * API for handling request for registering user account
+     *
+     * @param request
+     *            CoAP request message
+     * @return CoapResponse - CoAP response message with response result
+     *         information
+     */
+    private CoapResponse handleRegisterRequest(CoapRequest request) {
+
+        String payload = request.getPayloadString();
+
+        String authCode = JSONUtil.parseJSON(payload,
+                Constants.REQUEST_AUTH_CODE);
+        String authServer = JSONUtil.parseJSON(payload,
+                Constants.REQUEST_AUTH_SERVER);
+
+        Logger.d("authCode: " + authCode + ", authServer: " + authServer);
+
+        AccountServerManager oauthServerManager = new AccountServerManager();
+        String userId = null;
+        if (authCode != null && authServer != null) {
+            userId = oauthServerManager.requestUserId(authCode, authServer);
+        }
+        
+        CoapMessageBuilder responseMessage = new CoapMessageBuilder();
+        CoapResponse coapResponse;
+
+        if (userId != null) {
+            
+            String sessionCode = oauthServerManager.registerUserAccount(userId);
+
+            Logger.d("userId: " + userId + ", sessionCode: " + sessionCode);
+
+            if (sessionCode != null) {
+
+                ResponseObject response = new ResponseObject();
+                response.setSessionCode(sessionCode);
+                response.setUserId(userId);
+
+                String responseJson = convertRegisterResponseToJson(response);
+                Logger.d("responseJson: " + responseJson);
+
+                coapResponse = responseMessage.buildCoapResponse(
+                        request.getToken(), responseJson, CoapStatus.CREATED);
+            }
+            else  {
+                coapResponse = responseMessage.buildCoapResponse(request.getToken(),
+                        CoapStatus.UNAUTHORIZED);                
+            }
+
+        } else {
+
+            coapResponse = responseMessage.buildCoapResponse(request.getToken(),
+                    CoapStatus.UNAUTHORIZED);
+        }
+
+        return coapResponse;
+    }
+
+    private String convertRegisterResponseToJson(ResponseObject response) {
+
+        HashMap<Object, Object> responseMap = new HashMap<Object, Object>();
+
+        String sessionCode = response.getSessionCode();
+        String userId = response.getUserId();
+
+        if (userId != null)
+            responseMap.put(Constants.RESPONSE_USER_ID, userId);
+
+        if (sessionCode != null)
+            responseMap.put(Constants.RESPONSE_SESSION_CODE, sessionCode);
+
+        String responseJson = JSONUtil.writeJSON(responseMap);
+
+        return responseJson;
+    }
+
+    private String convertLoginResponseToJson(ResponseObject response) {
+
+        HashMap<Object, Object> responseMap = new HashMap<Object, Object>();
+
+        String userId = response.getUserId();
+
+        if (userId != null)
+            responseMap.put(Constants.RESPONSE_USER_ID, userId);
+
+        String responseJson = JSONUtil.writeJSON(responseMap);
+
+        return responseJson;
+    }
+
+    private String extractQuery(CoapRequest request, String key) {
+
+        String value = null;
+
+        List<String> Segments = request.getUriQuerySegments();
+
+        if (Segments != null) {
+            for (String s : Segments) {
+
+                String pair[] = s.split("=");
+
+                if (pair[0].equals(key)) {
+
+                    value = pair[1];
+                }
+            }
+        }
+
+        return value;
+    }
+
+    /*
+     * private static String getPayloadString(byte[] payload) {
+     *
+     * if (payload == null) return "";
+     *
+     * return new String(payload, Charset.forName("UTF-8")); }
+     */
+
+}
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/ResponseObject.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/ResponseObject.java
new file mode 100644 (file)
index 0000000..4a506e8
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.accountserver.resources;
+
+import java.util.ArrayList;
+
+/**
+ * 
+ * This class provides a set of APIs to manage data for response according to
+ * request.
+ * 
+ */
+public class ResponseObject {
+    // private String channel = null;
+    private String            sessionCode = null;
+    private String            userId      = null;
+    private ArrayList<String> deviceList  = null;
+
+    ResponseObject() {
+        deviceList = new ArrayList<String>();
+    }
+
+    public String getUserId() {
+        return this.userId;
+    }
+
+    public void setUserId(String id) {
+        this.userId = id;
+    }
+
+    public String getSessionCode() {
+        return this.sessionCode;
+    }
+
+    public void setSessionCode(String code) {
+        this.sessionCode = code;
+    }
+
+    public void setDeviceList(ArrayList<String> list) {
+        this.deviceList = list;
+    }
+
+    public ArrayList<String> getDeviceList() {
+        return this.deviceList;
+    }
+}
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/util/CoapMessageBuilder.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/util/CoapMessageBuilder.java
new file mode 100644 (file)
index 0000000..47cbe58
--- /dev/null
@@ -0,0 +1,136 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.accountserver.util;
+
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+
+import org.iotivity.cloud.base.protocols.coap.CoapRequest;
+import org.iotivity.cloud.base.protocols.coap.CoapResponse;
+import org.iotivity.cloud.base.protocols.coap.enums.CoapMethod;
+import org.iotivity.cloud.base.protocols.coap.enums.CoapOption;
+import org.iotivity.cloud.base.protocols.coap.enums.CoapStatus;
+
+/**
+ * 
+ * This class provides a set of APIs to build build data of CoAP request and
+ * response type.
+ * 
+ */
+public class CoapMessageBuilder {
+
+    public static final int APPLICATION_JSON = 50;
+
+    /**
+     * API for building data of CoAP response type without payload.
+     * 
+     * @param token
+     *            token
+     * @param status
+     *            response status
+     * @return CoapResponse - data of CoAP response type
+     */
+    public CoapResponse buildCoapResponse(byte[] token, CoapStatus status) {
+
+        return buildCoapResponse(token, null, status);
+    }
+
+    /**
+     * API for building data of CoAP response type with payload.
+     * 
+     * @param token
+     *            token
+     * @param jsonString
+     *            payload data
+     * @param status
+     *            response status
+     * @return CoapResponse - data of CoAP response type
+     */
+    public CoapResponse buildCoapResponse(byte[] token, String jsonString,
+            CoapStatus status) {
+
+        CoapResponse coapResponse = new CoapResponse(status);
+
+        coapResponse.setToken(token);
+
+        byte[] bytes = ByteBuffer.allocate(4)
+                .putInt(CoapMessageBuilder.APPLICATION_JSON).array();
+        coapResponse.addOption(CoapOption.CONTENT_FORMAT.getvalue(), bytes);
+
+        if (jsonString != null)
+            coapResponse
+                    .setPayload(jsonString.getBytes(StandardCharsets.UTF_8));
+
+        return coapResponse;
+    }
+
+    /**
+     * API for building data of CoAP requeset type with payload.
+     * 
+     * @param token
+     *            token
+     * @param jsonString
+     *            payload data
+     * @return CoapRequest - data of CoAP request type
+     */
+    public CoapRequest buildCoapRequest(byte[] token, String jsonString) {
+
+        CoapRequest coapRequest = new CoapRequest(CoapMethod.GET);
+
+        coapRequest.setToken(token);
+
+        byte[] bytes = ByteBuffer.allocate(4)
+                .putInt(CoapMessageBuilder.APPLICATION_JSON).array();
+        coapRequest.addOption(CoapOption.CONTENT_FORMAT.getvalue(), bytes);
+
+        coapRequest.setPayload(jsonString.getBytes(StandardCharsets.UTF_8));
+
+        return coapRequest;
+    }
+
+    /*
+     * 
+     * public String getJsonAuthServerResponse() {
+     * 
+     * return "{ \"" + OAuthConstant.AUTH_SERVER + "\" : \"" +
+     * OAuthConstant.AUTH_SERVER_GITHUB + "\" }"; }
+     * 
+     * public String getJsonAuthInfoResponse() {
+     * 
+     * return "\n{\n" + " \"" + OAuthConstant.AUTH_ADDRESS + "\" : \"" +
+     * OAuthConstant.GITHUB_ADDRESS + "\",\n" + " \"" +
+     * OAuthConstant.AUTH_RESPONSE_TYPE + "\" : \"" +
+     * OAuthConstant.AUTH_CODE_VALUE + "\",\n" + " \"" +
+     * OAuthConstant.AUTH_CLIENT_ID + "\" : \"" + OAuthConstant.GITHUB_CLIENT_ID
+     * + "\",\n" + " \"" + OAuthConstant.AUTH_REDIRECT_URI + "\" : \"" +
+     * OAuthConstant.GITHUB_REDIRECT_URL + "\"" + "\n}"; }
+     * 
+     * public String getJsonAuthQueryRequest(String auth_server, String
+     * auth_code, String auth_di) {
+     * 
+     * return "\n{\n" + " \"" + OAuthConstant.AUTH_TYPE + "\" : \"" +
+     * OAuthConstant.AUTH_TYPE_QUERY + "\",\n" + " \"" +
+     * OAuthConstant.AUTH_SERVER + "\" : \"" + auth_server + "\",\n" + " \"" +
+     * OAuthConstant.AUTH_CODE + "\" : \"" + auth_code + "\",\n" + " \"" +
+     * OAuthConstant.AUTH_DEVICE_ID + "\" : \"" + auth_di + "\"" + "\n}"; }
+     */
+}
diff --git a/cloud/account/src/test/java/org/iotivity/cloud/testaccountserver/TestAccountServer.java b/cloud/account/src/test/java/org/iotivity/cloud/testaccountserver/TestAccountServer.java
new file mode 100644 (file)
index 0000000..aebada9
--- /dev/null
@@ -0,0 +1,168 @@
+package org.iotivity.cloud.testaccountserver;
+
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.SimpleChannelInboundHandler;
+
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+
+import org.junit.Test;
+import org.iotivity.cloud.accountserver.Constants;
+import org.iotivity.cloud.accountserver.resources.AccountResource;
+import org.iotivity.cloud.accountserver.resources.AuthResource;
+import org.iotivity.cloud.base.CoapClient;
+import org.iotivity.cloud.base.CoapServer;
+import org.iotivity.cloud.base.ResourceManager;
+import org.iotivity.cloud.base.protocols.coap.CoapRequest;
+import org.iotivity.cloud.base.protocols.coap.CoapResponse;
+import org.iotivity.cloud.base.protocols.coap.enums.CoapMethod;
+import org.iotivity.cloud.util.JSONUtil;
+
+public class TestAccountServer {
+
+    private AuthResource    authResource    = new AuthResource();
+    private AccountResource accountResource = new AccountResource();
+
+    private CoapServer      coapServer      = null;
+    private CoapClient      coapClient      = null;
+    private static String   sessionCode     = null;
+
+    static class CoapClientHandler extends
+            SimpleChannelInboundHandler<CoapResponse> {
+
+        ChannelHandlerContext connectCtx = null;
+
+        @Override
+        public void channelActive(ChannelHandlerContext ctx) throws Exception {
+            connectCtx = ctx;
+        }
+
+        @Override
+        protected void channelRead0(ChannelHandlerContext arg0,
+                CoapResponse arg1) throws Exception {
+
+            if (arg1.getTokenString().equals("1111")) {
+
+                String json = arg1.getPayloadString();
+
+                sessionCode = JSONUtil.parseJSON(json, "session");
+            }
+
+        }
+    }
+
+    public void startServer() throws Exception {
+
+        coapServer = new CoapServer();
+
+        ResourceManager resourceManager = new ResourceManager();
+        coapServer.addHandler(resourceManager);
+
+        resourceManager.registerResource(new AuthResource());
+        resourceManager.registerResource(new AccountResource());
+
+        coapServer.startServer(new InetSocketAddress(5685));
+    }
+
+    public ChannelHandlerContext startClient() throws Exception {
+
+        coapClient = new CoapClient();
+
+        CoapClientHandler coapHandler = new CoapClientHandler();
+        coapClient.addHandler(coapHandler);
+
+        coapClient.startClient(new InetSocketAddress("127.0.0.1", 5685));
+
+        return coapHandler.connectCtx;
+    }
+
+    @Test
+    public void testHandleRegisterRequest() throws Exception {
+
+        System.out.println("Write your authCode before test by following url.");
+        System.out
+                .println("https://github.com/login?return_to=%2Flogin%2Foauth%2Fauthorize%3Fclient_id%3Dea9c18f540323b0213d0%26redirect_uri%3Dhttp%253A%252F%252Fwww.example.com%252Foauth_callback%252F");
+
+        String authCode = "7243699de9726d05e74c"; // write your authCode here.
+        String authServer = "github";
+
+        String json = "{\"authcode\":\"" + authCode + "\",\"authprovider\":\""
+                + authServer + "\"}";
+
+        CoapRequest request = new CoapRequest(CoapMethod.POST);
+        request.setUriPath(Constants.AUTH_URI);
+        request.setUriQuery("reqtype=register");
+        request.setToken("1111".getBytes(StandardCharsets.UTF_8));
+        request.setPayload(json.getBytes(StandardCharsets.UTF_8));
+
+        startServer();
+        ChannelHandlerContext ctx = startClient();
+        authResource.onRequestReceived(ctx, request);
+
+        coapClient.stopClient();
+        coapServer.stopServer();
+    }
+
+    @Test
+    public void testHandlerLoginReqeust() throws Exception {
+
+        String json = "{\"session\":\"" + sessionCode + "\"}";
+
+        CoapRequest request = new CoapRequest(CoapMethod.POST);
+        request.setUriPath(Constants.AUTH_URI);
+        request.setUriQuery("reqtype=login");
+        request.setToken("1234".getBytes(StandardCharsets.UTF_8));
+        request.setPayload(json.getBytes(StandardCharsets.UTF_8));
+
+        startServer();
+        ChannelHandlerContext ctx = startClient();
+        authResource.onRequestReceived(ctx, request);
+
+        coapClient.sendRequest(request);
+
+        coapClient.stopClient();
+        coapServer.stopServer();
+    }
+
+    @Test
+    public void testHandlerPublishReqeust() throws Exception {
+
+        String userId = "eyedglen";
+        String deviceId = "d0001";
+        String json = "{\"userid\":\"" + userId + "\",\"deviceId\":\""
+                + deviceId + "\"}";
+
+        CoapRequest request = new CoapRequest(CoapMethod.POST);
+        request.setUriPath(Constants.ACCOUNT_URI);
+        request.setUriQuery("reqtype=publish");
+        request.setToken("1234".getBytes(StandardCharsets.UTF_8));
+        request.setPayload(json.getBytes(StandardCharsets.UTF_8));
+
+        startServer();
+        ChannelHandlerContext ctx = startClient();
+        accountResource.onRequestReceived(ctx, request);
+
+        coapClient.stopClient();
+        coapServer.stopServer();
+    }
+
+    @Test
+    public void testHandlerFindReqeust() throws Exception {
+
+        String userId = "eyedglen";
+        String json = "{\"userid\":\"" + userId + "\"}";
+
+        CoapRequest request = new CoapRequest(CoapMethod.GET);
+        request.setUriPath(Constants.ACCOUNT_URI);
+        request.setUriQuery("reqtype=find");
+        request.setToken("1234".getBytes(StandardCharsets.UTF_8));
+        request.setPayload(json.getBytes(StandardCharsets.UTF_8));
+
+        startServer();
+        ChannelHandlerContext ctx = startClient();
+        accountResource.onRequestReceived(ctx, request);
+
+        coapClient.stopClient();
+        coapServer.stopServer();
+    }
+}
diff --git a/cloud/interface/.classpath b/cloud/interface/.classpath
new file mode 100644 (file)
index 0000000..f619a53
--- /dev/null
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+       <classpathentry kind="src" output="target/classes" path="src/main/java">
+               <attributes>
+                       <attribute name="optional" value="true"/>
+                       <attribute name="maven.pomderived" value="true"/>
+               </attributes>
+       </classpathentry>
+       <classpathentry kind="src" output="target/test-classes" path="src/test/java">
+               <attributes>
+                       <attribute name="optional" value="true"/>
+                       <attribute name="maven.pomderived" value="true"/>
+               </attributes>
+       </classpathentry>
+       <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
+               <attributes>
+                       <attribute name="maven.pomderived" value="true"/>
+               </attributes>
+       </classpathentry>
+       <classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
+               <attributes>
+                       <attribute name="maven.pomderived" value="true"/>
+               </attributes>
+       </classpathentry>
+       <classpathentry kind="output" path="target/classes"/>
+</classpath>
diff --git a/cloud/interface/.gitignore b/cloud/interface/.gitignore
new file mode 100644 (file)
index 0000000..b83d222
--- /dev/null
@@ -0,0 +1 @@
+/target/
diff --git a/cloud/interface/.project b/cloud/interface/.project
new file mode 100644 (file)
index 0000000..92dcbdb
--- /dev/null
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+       <name>CloudInterface</name>
+       <comment></comment>
+       <projects>
+       </projects>
+       <buildSpec>
+               <buildCommand>
+                       <name>org.eclipse.jdt.core.javabuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+               <buildCommand>
+                       <name>org.eclipse.m2e.core.maven2Builder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+       </buildSpec>
+       <natures>
+               <nature>org.eclipse.jdt.core.javanature</nature>
+               <nature>org.eclipse.m2e.core.maven2Nature</nature>
+       </natures>
+</projectDescription>
diff --git a/cloud/interface/README b/cloud/interface/README
new file mode 100644 (file)
index 0000000..0ff3f64
--- /dev/null
@@ -0,0 +1,26 @@
+This project contains the Cloud Interface(CI) Server code.
+
+Build and Run
+
+1) Install Apache Maven if you don't have it
+
+       http://maven.apache.org
+
+2) Build a CloudStack. If you are building first time, then build the stack.
+
+       go to "stack" folder in root directory
+       $ mvn install -Dmaven.test.skip=true
+
+3) Build a .jar file
+
+       $ mvn install -Dmaven.test.skip=true
+
+       - The CloudInterface-0.0.1-SNAPSHOT.jar file will be placed in the "target" folder
+
+4) Run .jar file
+
+       go to "target" folder
+       $ java -jar CloudInterface-0.0.1-SNAPSHOT.jar arg1(CI CoAP Server Port) arg2(RD CoAP Server IP) arg3(RD CoAP Server Port) arg4(Account Server IP) arg5(Account Server Port)
+       e.g. java -jar CloudInterface-0.0.1-SNAPSHOT.jar 5683 127.0.0.1 5684 127.0.0.1 5685
+
+       - Before running a CI server, you should run a RD server and a Acccount server first.
diff --git a/cloud/interface/pom.xml b/cloud/interface/pom.xml
new file mode 100644 (file)
index 0000000..3c29dfd
--- /dev/null
@@ -0,0 +1,64 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.iotivity.cloud</groupId>
+  <artifactId>CloudInterface</artifactId>
+  <version>0.0.1-SNAPSHOT</version>
+  
+  <properties>
+               <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+       </properties>
+       
+  <dependencies>
+               <dependency>
+                       <groupId>org.iotivity.cloud</groupId>
+                       <artifactId>CloudStack</artifactId>
+                       <version>0.0.1-SNAPSHOT</version>
+               </dependency>   
+       </dependencies>
+       
+  <build>
+               <plugins>
+                       <plugin>
+                               <inherited>true</inherited>
+                               <groupId>org.apache.maven.plugins</groupId>
+                               <artifactId>maven-compiler-plugin</artifactId>
+                               <configuration>
+                                       <source>1.7</source>
+                                       <target>1.7</target>
+                                       <encoding>UTF-8</encoding>
+                               </configuration>
+                       </plugin>
+                       <plugin>
+                               <groupId>org.apache.maven.plugins</groupId>
+                               <artifactId>maven-jar-plugin</artifactId>
+                               <configuration>
+                                       <archive>
+                                               <manifest>
+                                                       <mainClass>org.iotivity.cloud.ciserver.CloudInterfaceServer</mainClass>
+                                                       <addClasspath>true</addClasspath>
+                                                       <classpathPrefix>lib/</classpathPrefix>
+                                               </manifest>
+                                       </archive>
+                               </configuration>
+                       </plugin>
+                       <plugin>
+                               <groupId>org.apache.maven.plugins</groupId>
+                               <artifactId>maven-dependency-plugin</artifactId>
+                               <executions>
+                                       <execution>
+                                               <id>copy-dependencies</id>
+                                               <phase>package</phase>
+                                               <goals>
+                                                       <goal>copy-dependencies</goal>
+                                               </goals>
+                                       </execution>
+                               </executions>
+                               <configuration>
+                                       <outputDirectory>target/lib</outputDirectory>
+                                       <overWriteIfNewer>true</overWriteIfNewer>
+                               </configuration>
+                       </plugin>
+               </plugins>
+       </build>
+  
+</project>
\ No newline at end of file
diff --git a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/CloudInterfaceServer.java b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/CloudInterfaceServer.java
new file mode 100644 (file)
index 0000000..ca6aa00
--- /dev/null
@@ -0,0 +1,111 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.ciserver;
+
+import java.net.InetSocketAddress;
+import java.util.Scanner;
+
+import org.iotivity.cloud.base.CoapServer;
+import org.iotivity.cloud.base.ResourceManager;
+import org.iotivity.cloud.base.SessionManager;
+import org.iotivity.cloud.ciserver.protocols.CoapAuthHandler;
+import org.iotivity.cloud.ciserver.protocols.CoapRelayHandler;
+import org.iotivity.cloud.ciserver.resources.KeepAliveResource;
+import org.iotivity.cloud.util.CoapLogHandler;
+import org.iotivity.cloud.util.Logger;
+
+public class CloudInterfaceServer {
+
+    public static void main(String[] args) throws Exception {
+
+        System.out.println("-----CI SERVER-------");
+
+        if (args.length != 5) {
+            Logger.e(
+                    "coap server port and RDServer_Address port AccountServer_Address Port required\n"
+                            + "ex) 5683 127.0.0.1 5684 127.0.0.1 5685\n");
+            return;
+        }
+
+        ResourceManager resourceManager = null;
+        SessionManager sessionManager = null;
+        CoapServer coapServer = null;
+
+        CoapRelayHandler relayHandler = null;
+        CoapAuthHandler authHandler = null;
+
+        KeepAliveResource keepAliveResource = null;
+
+        coapServer = new CoapServer();
+
+        sessionManager = new SessionManager();
+
+        resourceManager = new ResourceManager();
+
+        relayHandler = new CoapRelayHandler(sessionManager);
+
+        authHandler = new CoapAuthHandler();
+
+        keepAliveResource = new KeepAliveResource(sessionManager,
+                new int[] { 1, 2, 4, 8 });
+
+        coapServer.addHandler(new CoapLogHandler());
+
+        coapServer.addHandler(authHandler);
+
+        coapServer.addHandler(relayHandler);
+
+        coapServer.addHandler(resourceManager);
+
+        resourceManager.registerResource(keepAliveResource);
+
+        authHandler.startHandler(args[3], Integer.parseInt(args[4]));
+
+        relayHandler.startHandler(args[1], Integer.parseInt(args[2]), args[3],
+                Integer.parseInt(args[4]));
+
+        coapServer
+                .startServer(new InetSocketAddress(Integer.parseInt(args[0])));
+
+        keepAliveResource.startSessionChecker();
+
+        Scanner in = new Scanner(System.in, "UTF-8");
+
+        System.out.println("press 'q' to terminate");
+
+        while (!in.nextLine().equals("q"));
+
+        in.close();
+
+        System.out.println("Terminating...");
+
+        keepAliveResource.stopSessionChecker();
+
+        coapServer.stopServer();
+
+        relayHandler.stopHandler();
+
+        authHandler.stopHandler();
+
+        System.out.println("Terminated");
+    }
+}
diff --git a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/Constants.java b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/Constants.java
new file mode 100644 (file)
index 0000000..918fab8
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.ciserver;
+
+import io.netty.util.AttributeKey;
+
+public class Constants {
+    public static final String RD_URI         = "oic/rd";   // resource
+                                                            // publish uri
+    public static final String KEEP_ALIVE_URI = "oic/ping"; // keepalive
+                                                            // resource uri
+    public static final String WELL_KNOWN_URI = "oic/res";  // resource
+                                                            // discover uri
+
+    public static final String DEVICE_LIST = "st=didList"; // oauth device
+                                                           // list riquery
+
+    public static final String AUTH_URI    = "oic/auth";
+    public static final String ACCOUNT_URI = "oic/account";
+
+    public static final AttributeKey<String> Attribute_UserId = AttributeKey
+            .newInstance("userId");
+}
diff --git a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/protocols/CoapAuthHandler.java b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/protocols/CoapAuthHandler.java
new file mode 100644 (file)
index 0000000..3e626e3
--- /dev/null
@@ -0,0 +1,153 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.ciserver.protocols;
+
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.iotivity.cloud.base.CoapClient;
+import org.iotivity.cloud.base.protocols.coap.CoapRequest;
+import org.iotivity.cloud.base.protocols.coap.CoapResponse;
+import org.iotivity.cloud.base.protocols.coap.enums.CoapStatus;
+import org.iotivity.cloud.ciserver.Constants;
+import org.iotivity.cloud.util.Cbor;
+import org.iotivity.cloud.util.JSONUtil;
+import org.iotivity.cloud.util.Logger;
+
+import io.netty.channel.ChannelDuplexHandler;
+import io.netty.channel.ChannelHandler.Sharable;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.SimpleChannelInboundHandler;
+import io.netty.util.AttributeKey;
+
+@Sharable
+public class CoapAuthHandler extends ChannelDuplexHandler {
+
+    private static final AttributeKey<ChannelHandlerContext> keyAuthClient = AttributeKey
+            .newInstance("authCtx");
+
+    private class AccountHandler
+            extends SimpleChannelInboundHandler<CoapResponse> {
+
+        @Override
+        public void channelRead0(ChannelHandlerContext ctx, CoapResponse msg)
+                throws Exception {
+            Logger.d("Receive response from account, forward to client");
+
+            ChannelHandlerContext ctxToDevice = ctx.channel()
+                    .attr(keyAuthClient).get();
+
+            if (msg.getResponseCode() == CoapStatus.CREATED) {
+                Map<String, String> response = JSONUtil.parseJSON(
+                        new String(msg.getPayload(), StandardCharsets.UTF_8));
+
+                if (response != null) {
+                    String userId = response.get("userid");
+                    if (userId != null) {
+                        ctxToDevice.channel().attr(Constants.Attribute_UserId)
+                                .set(userId);
+                    }
+                    msg.setPayload(cbor.encodingPayloadToCbor(response));
+
+                    CoapAuthHandler authHandler = ctxToDevice.channel()
+                            .pipeline().get(CoapAuthHandler.class);
+
+                    ctxToDevice.channel().pipeline().remove(authHandler);
+                }
+            }
+
+            ctxToDevice.writeAndFlush(msg);
+
+            if (msg.getResponseCode() != CoapStatus.CREATED)
+                ctxToDevice.close();
+        }
+
+        @Override
+        public void exceptionCaught(ChannelHandlerContext ctx,
+                Throwable cause) {
+            cause.printStackTrace();
+            ctx.close();
+        }
+    }
+
+    private CoapClient asClient = new CoapClient();
+
+    public CoapAuthHandler() {
+
+        asClient.addHandler(new AccountHandler());
+
+    }
+
+    public void startHandler(String acAddress, int acPort) throws Exception {
+        asClient.startClient(new InetSocketAddress(acAddress, acPort));
+    }
+
+    public void stopHandler() throws Exception {
+        asClient.stopClient();
+    }
+
+    private Cbor<HashMap<Object, Object>> cbor = new Cbor<HashMap<Object, Object>>();
+
+    @Override
+    public void channelRead(ChannelHandlerContext ctx, Object msg)
+            throws Exception {
+
+        if (msg instanceof CoapRequest) {
+            CoapRequest request = (CoapRequest) msg;
+            String uriPath = request.getUriPath();
+            if (uriPath != null) {
+                switch (uriPath) {
+                    // This handler only used for initial handshake
+                    case Constants.AUTH_URI:
+                        HashMap<Object, Object> payloadData = cbor
+                                .parsePayloadFromCbor(request.getPayload(),
+                                        HashMap.class);
+                        String writejson = JSONUtil.writeJSON(payloadData);
+                        if (writejson != null) {
+                            request.setPayload(
+                                    writejson.getBytes(StandardCharsets.UTF_8));
+                            asClient.getChannelFuture().channel()
+                                    .attr(keyAuthClient).set(ctx);
+                            asClient.sendRequest(request);
+                        }
+                        return;
+
+                    case Constants.KEEP_ALIVE_URI:
+                        super.channelRead(ctx, msg);
+                        return;
+
+                    default:
+                        CoapResponse response = new CoapResponse(
+                                CoapStatus.UNAUTHORIZED);
+                        Logger.e("Sending UNAUTHORIZED to client");
+                        ctx.writeAndFlush(response);
+                        break;
+                }
+            }
+        }
+
+        Logger.d("Invalid packet for authenticating");
+        ctx.close();
+    }
+}
diff --git a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/protocols/CoapRelayHandler.java b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/protocols/CoapRelayHandler.java
new file mode 100644 (file)
index 0000000..97c6051
--- /dev/null
@@ -0,0 +1,341 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.ciserver.protocols;
+
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.iotivity.cloud.base.CoapClient;
+import org.iotivity.cloud.base.SessionManager;
+import org.iotivity.cloud.base.protocols.coap.CoapRequest;
+import org.iotivity.cloud.base.protocols.coap.CoapResponse;
+import org.iotivity.cloud.base.protocols.coap.enums.CoapMethod;
+import org.iotivity.cloud.base.protocols.coap.enums.CoapStatus;
+import org.iotivity.cloud.ciserver.Constants;
+import org.iotivity.cloud.util.Logger;
+
+import io.netty.channel.ChannelDuplexHandler;
+import io.netty.channel.ChannelHandler.Sharable;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.SimpleChannelInboundHandler;
+import io.netty.util.AttributeKey;
+
+/**
+ *
+ * This class is relay handler relating Cloud Interface
+ *
+ */
+@Sharable
+public class CoapRelayHandler extends ChannelDuplexHandler {
+
+    /////////// Handler for Resource Directory
+    private static final AttributeKey<ChannelHandlerContext> keyRDClient = AttributeKey
+            .newInstance("rdCtx");
+
+    private static class RDHandler
+            extends SimpleChannelInboundHandler<CoapResponse> {
+        @Override
+        public void channelRead0(ChannelHandlerContext ctx, CoapResponse msg)
+                throws Exception {
+            Logger.d("Receive response from RD, forward to client");
+
+            ChannelHandlerContext ctxToDevice = ctx.channel().attr(keyRDClient)
+                    .get();
+            ctxToDevice.writeAndFlush(msg);
+        }
+
+        @Override
+        public void exceptionCaught(ChannelHandlerContext ctx,
+                Throwable cause) {
+            cause.printStackTrace();
+            ctx.close();
+        }
+    }
+
+    private CoapClient                                   rdClient         = null;
+                                                                          ///////////
+
+    ////////// Handler for Account Server
+    private static final AttributeKey<List<CoapRequest>> keyAccountClient = AttributeKey
+            .newInstance("accountCtx");
+
+    private class AccountHandler
+            extends SimpleChannelInboundHandler<CoapResponse> {
+        @Override
+        public void channelRead0(ChannelHandlerContext ctx, CoapResponse msg)
+                throws Exception {
+            Logger.d("Receive response from AS, make request to RD");
+
+            CoapRequest rdRequest = null;
+
+            switch (msg.getResponseCode()) {
+                case CREATED:
+                    // response of POST request
+                    rdRequest = ctx.channel().attr(keyAccountClient).get()
+                            .remove(0);
+                    rdClient.sendRequest(rdRequest);
+                    break;
+
+                case CONTENT:
+                    // response of GET request, contains did list
+                    rdRequest = ctx.channel().attr(keyAccountClient).get()
+                            .remove(0);
+                    // change uri to send RD
+                    rdRequest.setUriPath(Constants.RD_URI);
+                    rdRequest.setUriQuery(Constants.DEVICE_LIST);
+                    rdRequest.setPayload(msg.getPayload());
+                    rdClient.sendRequest(rdRequest);
+                    break;
+
+                default:
+                    break;
+            }
+        }
+
+        @Override
+        public void exceptionCaught(ChannelHandlerContext ctx,
+                Throwable cause) {
+            cause.printStackTrace();
+            ctx.close();
+        }
+    }
+
+    private CoapClient     asClient       = null;
+    //////////
+
+    private SessionManager sessionManager = null;
+
+    public CoapRelayHandler(SessionManager sessionManager) {
+        this.sessionManager = sessionManager;
+
+        rdClient = new CoapClient();
+
+        rdClient.addHandler(new RDHandler());
+
+        asClient = new CoapClient();
+
+        asClient.addHandler(new AccountHandler());
+    }
+
+    public void startHandler(String rdAddress, int rdPort, String acAddress,
+            int acPort) throws Exception {
+        rdClient.startClient(new InetSocketAddress(rdAddress, rdPort));
+
+        asClient.startClient(new InetSocketAddress(acAddress, acPort));
+
+        asClient.getChannelFuture().channel().attr(keyAccountClient)
+                .set(new ArrayList<CoapRequest>());
+    }
+
+    public void stopHandler() throws Exception {
+        asClient.stopClient();
+
+        rdClient.stopClient();
+    }
+
+    private static final AttributeKey<ChannelHandlerContext> keyDevice = AttributeKey
+            .newInstance("deviceCtx");
+
+    @Override
+    public void channelRead(ChannelHandlerContext ctx, Object msg)
+            throws Exception {
+
+        if (msg instanceof CoapRequest) {
+            CoapRequest request = (CoapRequest) msg;
+            // Parse uri, send to RD
+            String uriPath = request.getUriPath();
+            CoapRequest accountRequest = null;
+            String userId, deviceId, authPayload;
+            CoapResponse response;
+
+            Logger.d("Request received, URI: " + uriPath);
+            if (uriPath != null) {
+                switch (uriPath) {
+                    case Constants.AUTH_URI:
+                        // This case user wants to logout
+                        String uriQuery = request.getUriQuery();
+                        if (uriQuery != null) {
+                            if (uriQuery.endsWith("logout")) {
+                                ctx.channel().attr(Constants.Attribute_UserId)
+                                        .remove();
+                                response = new CoapResponse(CoapStatus.DELETED);
+                            } else {
+                                response = new CoapResponse(
+                                        CoapStatus.BAD_REQUEST);
+                            }
+                            ctx.writeAndFlush(response);
+                        }
+                        break;
+
+                    case Constants.RD_URI:
+                        // RD POST means publish device to server
+                        switch (request.getRequestMethod()) {
+                            case POST:
+                                userId = ctx.channel()
+                                        .attr(Constants.Attribute_UserId).get();
+                                deviceId = request.decodeDeviceId();
+                                authPayload = String.format(
+                                        "{\"userid\":\"%s\",\"deviceid\":\"%s\"}",
+                                        userId, deviceId);
+                                accountRequest = new CoapRequest(
+                                        CoapMethod.POST);
+                                accountRequest
+                                        .setUriPath(Constants.ACCOUNT_URI);
+                                accountRequest.setUriQuery("reqtype=publish");
+                                accountRequest.setToken(request.getToken());
+                                accountRequest.setPayload(authPayload
+                                        .getBytes(StandardCharsets.UTF_8));
+
+                                // TODO: deviceId must be registered after
+                                // session
+                                // granted
+                                Logger.d("Adding deviceId to session: "
+                                        + deviceId);
+                                sessionManager.addSession(deviceId, ctx);
+                                break;
+
+                            default:
+                                Logger.e("Unsupported request type");
+                                break;
+                        }
+
+                        rdClient.getChannelFuture().channel().attr(keyRDClient)
+                                .set(ctx);
+
+                        // Add original request to list for future use
+                        asClient.getChannelFuture().channel()
+                                .attr(keyAccountClient).get().add(request);
+                        asClient.sendRequest(accountRequest);
+                        return;
+
+                    case Constants.WELL_KNOWN_URI:
+                        switch (request.getRequestMethod()) {
+                            case GET:
+                                userId = ctx.channel()
+                                        .attr(Constants.Attribute_UserId).get();
+                                authPayload = String
+                                        .format("{\"userid\":\"%s\"}", userId);
+                                accountRequest = new CoapRequest(
+                                        CoapMethod.GET);
+                                accountRequest
+                                        .setUriPath(Constants.ACCOUNT_URI);
+                                accountRequest.setUriQuery("reqtype=find");
+                                accountRequest.setToken(request.getToken());
+                                accountRequest.setPayload(authPayload
+                                        .getBytes(StandardCharsets.UTF_8));
+                                break;
+
+                            default:
+                                Logger.e("Unsupported request type");
+                                break;
+                        }
+
+                        rdClient.getChannelFuture().channel().attr(keyRDClient)
+                                .set(ctx);
+
+                        // Add original request to list for future use
+                        asClient.getChannelFuture().channel()
+                                .attr(keyAccountClient).get().add(request);
+                        asClient.sendRequest(accountRequest);
+                        return;
+
+                    case Constants.KEEP_ALIVE_URI:
+                        break;
+
+                    default:
+                        List<String> uriPathList = request.getUriPathSegments();
+                        if (uriPathList != null) {
+                            Logger.i("uriPahtList: " + uriPathList.toString());
+
+                            String did = uriPathList.get(0);
+
+                            Logger.i("did: " + did);
+
+                            // TODO: Clustering algorithm required
+                            // find ctx about did, and send msg
+                            StringBuffer resource = new StringBuffer();
+                            List<String> pathSegments = uriPathList.subList(1,
+                                    uriPathList.size());
+                            for (String path : pathSegments) {
+                                resource.append("/");
+                                resource.append(path);
+                            }
+                            Logger.i("resource: " + resource);
+                            request.setUriPath(resource.toString());
+
+                            ChannelHandlerContext deviceCtx = sessionManager
+                                    .querySession(did);
+                            if (deviceCtx != null) {
+                                deviceCtx.attr(keyDevice).set(ctx);
+                                deviceCtx.writeAndFlush(request);
+                            } else {
+                                Logger.e("deviceCtx is null");
+                                response = new CoapResponse(
+                                        CoapStatus.FORBIDDEN);
+                                response.setToken(request.getToken());
+                                ctx.writeAndFlush(response);
+                            }
+                        }
+                        return;
+                }
+            }
+
+        } else if (msg instanceof CoapResponse) {
+            ChannelHandlerContext resourceClient = ctx.attr(keyDevice).get();
+            if (resourceClient != null) {
+                Logger.i("Forwards message to client");
+
+                CoapResponse response = (CoapResponse) msg;
+
+                // If response contains path, add di
+                String did = sessionManager.queryDid(ctx);
+                if (response.getOption(11) != null && did != null) {
+                    response.getOption(11).add(0,
+                            did.getBytes(StandardCharsets.UTF_8));
+                }
+
+                Logger.i(
+                        "ctx.channel : " + resourceClient.channel().toString());
+                resourceClient.writeAndFlush(response);
+                return;
+            }
+        }
+
+        super.channelRead(ctx, msg);
+    }
+
+    @Override
+    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
+        Logger.d("Channel Inactive");
+        sessionManager.removeSessionByChannel(ctx);
+        super.channelInactive(ctx);
+    }
+
+    @Override
+    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
+
+        cause.printStackTrace();
+        ctx.close();
+    }
+}
diff --git a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/KeepAliveResource.java b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/KeepAliveResource.java
new file mode 100644 (file)
index 0000000..c809850
--- /dev/null
@@ -0,0 +1,214 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.ciserver.resources;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.Timer;
+import java.util.TimerTask;
+
+import org.iotivity.cloud.base.Resource;
+import org.iotivity.cloud.base.SessionManager;
+import org.iotivity.cloud.base.protocols.coap.CoapRequest;
+import org.iotivity.cloud.base.protocols.coap.CoapResponse;
+import org.iotivity.cloud.base.protocols.coap.enums.CoapStatus;
+import org.iotivity.cloud.ciserver.Constants;
+import org.iotivity.cloud.util.Cbor;
+import org.iotivity.cloud.util.Logger;
+
+import io.netty.channel.ChannelHandlerContext;
+
+/**
+ *
+ * This class provides a set of APIs to use KeepAlive Resource for ensuring the
+ * connection.
+ *
+ */
+public class KeepAliveResource extends Resource {
+
+    private int[]                                intervals;
+    private HashMap<ChannelHandlerContext, Long> connectPool;
+    private Timer                                timer;
+    private Cbor<HashMap<String, Integer>>       cbor;
+    private SessionManager                       sessionManager = null;
+
+    public void setIntervals(int[] intervals) {
+        this.intervals = intervals;
+    }
+
+    public int[] getIntervals() {
+        return this.intervals;
+    }
+
+    public KeepAliveResource(SessionManager sessionManager, int[] intervals) {
+        setUri(Constants.KEEP_ALIVE_URI);
+        setIntervals(intervals);
+        this.sessionManager = sessionManager;
+        connectPool = new HashMap<ChannelHandlerContext, Long>();
+        timer = new Timer();
+        cbor = new Cbor<HashMap<String, Integer>>();
+    }
+
+    public void startSessionChecker() {
+        timer.schedule(new KeepAliveTask(), 30000, 60000);
+    }
+
+    public void stopSessionChecker() {
+        timer.cancel();
+    }
+
+    /**
+     * API for receiving message(message to keepalive resource)
+     *
+     * @param ctx
+     *            ChannelHandlerContext of request message
+     * @param request
+     *            CoAP request message
+     */
+    @Override
+    public void onRequestReceived(ChannelHandlerContext ctx,
+            CoapRequest request) {
+
+        CoapResponse response = null;
+
+        switch (request.getRequestMethod()) {
+            // First message to KeepAlive from resource
+            case GET:
+                if (intervals != null) {
+                    response = makePingConfigMessage(request);
+                    connectPool.put(ctx, System.currentTimeMillis()
+                            + (intervals[0] * (long) 60000));
+                }
+                break;
+            // interval Message to KeepAlive After receiving GET Message
+            case PUT:
+                HashMap<String, Integer> payloadData = null;
+                payloadData = cbor.parsePayloadFromCbor(request.getPayload(),
+                        HashMap.class);
+
+                Logger.d("Receive payloadData : " + payloadData);
+                if (payloadData != null) {
+                    if (payloadData.containsKey("in")) {
+                        Logger.d("interval : " + payloadData.get("in"));
+
+                        connectPool.put(ctx, System.currentTimeMillis()
+                                + (payloadData.get("in") * (long) 60000));
+                    }
+                }
+                response = makeResponse(request);
+                break;
+
+            case POST:
+                break;
+
+            case DELETE:
+                break;
+        }
+
+        ctx.writeAndFlush(response);
+    }
+
+    /**
+     * API for making response to Resource
+     *
+     * @param request
+     *            ChannelHandlerContext of request message
+     */
+    private CoapResponse makeResponse(CoapRequest request) {
+        CoapResponse response = new CoapResponse(CoapStatus.VALID);
+        response.setToken(request.getToken());
+
+        return response;
+    }
+
+    /**
+     * API for making interval and first response to Resource
+     *
+     * @param request
+     *            ChannelHandlerContext of request message
+     */
+    private CoapResponse makePingConfigMessage(CoapRequest request) {
+        CoapResponse response = new CoapResponse(CoapStatus.CONTENT);
+        response.setToken(request.getToken());
+
+        HashMap<String, int[]> payloadData = new HashMap<String, int[]>();
+        payloadData.put("inarray", intervals);
+
+        byte[] cborData = cbor.encodingPayloadToCbor(payloadData);
+
+        response.setPayload(cborData);
+
+        Logger.d("Send payloadData : " + payloadData);
+
+        return response;
+    }
+
+    /**
+     * API for managing session
+     */
+    public class KeepAliveTask extends TimerTask {
+
+        @Override
+        public void run() {
+            Map<ChannelHandlerContext, Long> map = Collections
+                    .synchronizedMap(connectPool);
+            Set<ChannelHandlerContext> keySet = map.keySet();
+            ArrayList<ChannelHandlerContext> deleteList = new ArrayList<ChannelHandlerContext>();
+            Iterator<ChannelHandlerContext> iterator = null;
+            synchronized (map) {
+                iterator = keySet.iterator();
+                Long currentTime = System.currentTimeMillis();
+                // check interval
+                while (iterator.hasNext()) {
+                    ChannelHandlerContext key = iterator.next();
+                    if (map.containsKey(key)) {
+                        if (map.get(key) != null) {
+                            Long lifeTime = (Long) map.get(key);
+                            if (lifeTime != null) {
+                                Logger.d("KeepAliveTask Operating : "
+                                        + key.channel().toString() + ", Time : "
+                                        + (lifeTime - currentTime));
+                                if (lifeTime < currentTime) {
+                                    deleteList.add(key);
+                                }
+                            }
+                        }
+                    }
+                }
+
+            }
+            iterator = deleteList.iterator();
+            // remove session
+            while (iterator.hasNext()) {
+                ChannelHandlerContext key = iterator.next();
+                Logger.d("KeepAliveTask Remove");
+                connectPool.remove(key);
+                sessionManager.removeSessionByChannel(key);
+                key.close();
+            }
+        }
+    }
+}
diff --git a/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/testci/TestCloudInterface.java b/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/testci/TestCloudInterface.java
new file mode 100644 (file)
index 0000000..311dec9
--- /dev/null
@@ -0,0 +1,275 @@
+package org.iotivity.cloud.ciserver.testci;
+
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+
+import org.iotivity.cloud.base.CoapClient;
+import org.iotivity.cloud.base.CoapServer;
+import org.iotivity.cloud.base.ResourceManager;
+import org.iotivity.cloud.base.SessionManager;
+import org.iotivity.cloud.base.protocols.coap.CoapRequest;
+import org.iotivity.cloud.base.protocols.coap.CoapResponse;
+import org.iotivity.cloud.base.protocols.coap.enums.CoapMethod;
+import org.iotivity.cloud.ciserver.Constants;
+import org.iotivity.cloud.ciserver.protocols.CoapAuthHandler;
+import org.iotivity.cloud.ciserver.protocols.CoapRelayHandler;
+import org.iotivity.cloud.ciserver.resources.KeepAliveResource;
+import org.iotivity.cloud.util.Cbor;
+import org.iotivity.cloud.util.CoapLogHandler;
+import org.junit.Test;
+
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.SimpleChannelInboundHandler;
+
+public class TestCloudInterface {
+
+    private SessionManager  sessionManager  = new SessionManager();
+    private ResourceManager resourceManager = new ResourceManager();
+
+    private CoapServer        coapServer        = null;
+    private CoapClient        coapClient        = null;
+    private CoapRelayHandler  coapRelayHandler  = new CoapRelayHandler(
+            sessionManager);
+    private KeepAliveResource keepAliveResource = new KeepAliveResource(
+            sessionManager, new int[] { 1, 2, 4, 8 });
+
+    static class CoapClientHandler
+            extends SimpleChannelInboundHandler<CoapResponse> {
+
+        ChannelHandlerContext connectCtx = null;
+
+        @Override
+        public void channelActive(ChannelHandlerContext ctx) throws Exception {
+            connectCtx = ctx;
+        }
+
+        @Override
+        protected void channelRead0(ChannelHandlerContext arg0,
+                CoapResponse arg1) throws Exception {
+            // TODO : receive response
+            System.out.println("Get Response");
+        }
+    }
+
+    public void startServer() throws Exception {
+
+        coapServer = new CoapServer();
+
+        coapServer.addHandler(new CoapLogHandler());
+        coapServer.addHandler(coapRelayHandler);
+
+        coapServer.addHandler(resourceManager);
+        resourceManager.registerResource(keepAliveResource);
+
+        coapServer.startServer(new InetSocketAddress(5683));
+    }
+
+    public ChannelHandlerContext startClient() throws Exception {
+
+        coapClient = new CoapClient();
+
+        CoapClientHandler coapHandler = new CoapClientHandler();
+        coapClient.addHandler(coapHandler);
+
+        coapClient.addHandler(new CoapAuthHandler());
+
+        coapClient.startClient(new InetSocketAddress("127.0.0.1", 5683));
+
+        return coapHandler.connectCtx;
+    }
+
+    public CoapRequest makePayload(CoapRequest request) throws Exception {
+        ArrayList<Object> payload = new ArrayList<Object>();
+
+        HashMap<Object, Object> tags = new HashMap<Object, Object>();
+        tags.put("di", "98f7483c-5a31-4161-ba7e-9c13e0d");
+        tags.put("bm", (int) 1);
+        tags.put("ttl", (int) 86400);
+
+        ArrayList<LinkedHashMap<Object, Object>> publishLinks = new ArrayList<LinkedHashMap<Object, Object>>();
+        LinkedHashMap<Object, Object> link = new LinkedHashMap<Object, Object>();
+        link.put("href", "/a/light");
+        ArrayList<String> rt = new ArrayList<String>();
+        ArrayList<String> itf = new ArrayList<String>();
+        ArrayList<String> mt = new ArrayList<String>();
+        rt.add("core.light");
+        link.put("rt", rt);
+
+        itf.add("oic.if.baseline");
+        link.put("if", itf);
+
+        mt.add("application/json");
+        link.put("mt", mt);
+
+        link.put("ins", 1);
+
+        publishLinks.add(link);
+
+        payload.add(tags);
+        payload.add(publishLinks);
+
+        Cbor<ArrayList<Object>> cbor = new Cbor<ArrayList<Object>>();
+
+        request.setPayload(cbor.encodingPayloadToCbor(payload));
+
+        return request;
+    }
+
+    public CoapRequest makeinterval(CoapRequest request) throws Exception {
+
+        HashMap<Object, Object> payload = new HashMap<Object, Object>();
+        payload.put("in", 1);
+
+        Cbor<ArrayList<Object>> cbor = new Cbor<ArrayList<Object>>();
+
+        request.setPayload(cbor.encodingPayloadToCbor(payload));
+
+        return request;
+    }
+
+    @Test
+    public void TestKeepAlivePutInterval() throws Exception {
+
+        CoapRequest request = new CoapRequest(CoapMethod.PUT);
+        request.setUriPath(Constants.KEEP_ALIVE_URI);
+        request.setToken("1234".getBytes(StandardCharsets.UTF_8));
+        makeinterval(request);
+
+        startServer();
+        startClient();
+
+        coapClient.sendRequest(request);
+
+        System.out.println("Waiting for KeepAliveTask..");
+        Thread.sleep(30000);
+
+        coapClient.stopClient();
+        coapServer.stopServer();
+    }
+
+    @Test
+    public void TestKeepAliveGetFirst() throws Exception {
+
+        CoapRequest request = new CoapRequest(CoapMethod.GET);
+        request.setUriPath(Constants.KEEP_ALIVE_URI);
+        request.setToken("1234".getBytes(StandardCharsets.UTF_8));
+
+        startServer();
+        startClient();
+
+        coapClient.sendRequest(request);
+
+        coapClient.stopClient();
+        coapServer.stopServer();
+    }
+
+    @Test
+    public void TestDiscoveryDevice() throws Exception {
+
+        CoapRequest request = new CoapRequest(CoapMethod.GET);
+        request.setUriPath(Constants.WELL_KNOWN_URI);
+        request.setUriQuery("rt=oic.wk.rdpub");
+        request.setToken("1234".getBytes(StandardCharsets.UTF_8));
+
+        startServer();
+        startClient();
+
+        coapClient.sendRequest(request);
+
+        coapClient.stopClient();
+        coapServer.stopServer();
+    }
+
+    @Test
+    public void TestPublishDevice() throws Exception {
+
+        CoapRequest request = new CoapRequest(CoapMethod.POST);
+        request.setUriPath(Constants.RD_URI);
+        request.setUriQuery("rt=oic.wk.rdpub");
+        request.setToken("1234".getBytes(StandardCharsets.UTF_8));
+        makePayload(request);
+
+        startServer();
+        startClient();
+
+        coapClient.sendRequest(request);
+
+        coapClient.stopClient();
+        coapServer.stopServer();
+    }
+
+    @Test
+    public void TestAuthURI() throws Exception {
+
+        CoapRequest request = new CoapRequest(CoapMethod.GET);
+        request.setUriPath(Constants.AUTH_URI);
+        request.setUriQuery("rt=oic.wk.rdpub");
+        request.setToken("1234".getBytes(StandardCharsets.UTF_8));
+        makePayload(request);
+
+        startServer();
+        startClient();
+
+        coapClient.sendRequest(request);
+
+        coapClient.stopClient();
+        coapServer.stopServer();
+    }
+
+    @Test
+    public void TestRequestGetMessageToDeviceCIOwner() throws Exception {
+
+        CoapRequest request = new CoapRequest(CoapMethod.GET);
+        request.setUriPath(
+                "/10.113.64.98/98f7483c-5a31-4161-ba7e-9c13e0d/a/light");
+        request.setToken("1234".getBytes(StandardCharsets.UTF_8));
+        makePayload(request);
+
+        startServer();
+        startClient();
+
+        coapClient.sendRequest(request);
+
+        coapServer.stopServer();
+        coapClient.stopClient();
+    }
+
+    @Test
+    public void TestRequestGetMessageToDeviceNotCIOwner() throws Exception {
+
+        CoapRequest request = new CoapRequest(CoapMethod.GET);
+        request.setUriPath(
+                "/98f7483c-5a31-4161-ba7e-9c13e0d/a/light");
+        request.setToken("1234".getBytes(StandardCharsets.UTF_8));
+        makePayload(request);
+
+        startServer();
+        startClient();
+
+        coapClient.sendRequest(request);
+
+        coapServer.stopServer();
+        coapClient.stopClient();
+    }
+
+    @Test
+    public void TestRequestPutMessageToDevice() throws Exception {
+
+        CoapRequest request = new CoapRequest(CoapMethod.PUT);
+        request.setUriPath(
+                "/98f7483c-5a31-4161-ba7e-9c13e0d/a/light");
+        request.setToken("1234".getBytes(StandardCharsets.UTF_8));
+        makePayload(request);
+
+        startServer();
+        startClient();
+
+        coapClient.sendRequest(request);
+
+        coapServer.stopServer();
+        coapClient.stopClient();
+    }
+}
diff --git a/cloud/resourcedirectory/.classpath b/cloud/resourcedirectory/.classpath
new file mode 100644 (file)
index 0000000..f619a53
--- /dev/null
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+       <classpathentry kind="src" output="target/classes" path="src/main/java">
+               <attributes>
+                       <attribute name="optional" value="true"/>
+                       <attribute name="maven.pomderived" value="true"/>
+               </attributes>
+       </classpathentry>
+       <classpathentry kind="src" output="target/test-classes" path="src/test/java">
+               <attributes>
+                       <attribute name="optional" value="true"/>
+                       <attribute name="maven.pomderived" value="true"/>
+               </attributes>
+       </classpathentry>
+       <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
+               <attributes>
+                       <attribute name="maven.pomderived" value="true"/>
+               </attributes>
+       </classpathentry>
+       <classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
+               <attributes>
+                       <attribute name="maven.pomderived" value="true"/>
+               </attributes>
+       </classpathentry>
+       <classpathentry kind="output" path="target/classes"/>
+</classpath>
diff --git a/cloud/resourcedirectory/.gitignore b/cloud/resourcedirectory/.gitignore
new file mode 100644 (file)
index 0000000..b83d222
--- /dev/null
@@ -0,0 +1 @@
+/target/
diff --git a/cloud/resourcedirectory/.project b/cloud/resourcedirectory/.project
new file mode 100644 (file)
index 0000000..a12b34d
--- /dev/null
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+       <name>CloudResourceDirectory</name>
+       <comment></comment>
+       <projects>
+       </projects>
+       <buildSpec>
+               <buildCommand>
+                       <name>org.eclipse.jdt.core.javabuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+               <buildCommand>
+                       <name>org.eclipse.m2e.core.maven2Builder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+       </buildSpec>
+       <natures>
+               <nature>org.eclipse.jdt.core.javanature</nature>
+               <nature>org.eclipse.m2e.core.maven2Nature</nature>
+       </natures>
+</projectDescription>
diff --git a/cloud/resourcedirectory/README b/cloud/resourcedirectory/README
new file mode 100644 (file)
index 0000000..c283f66
--- /dev/null
@@ -0,0 +1,29 @@
+This project contains the Resource Directory(RD) Server code.
+
+Build and Run
+
+1) Install Apache Maven if you don't have it
+
+       http://maven.apache.org
+
+2) Install Mongo DB if you don't have it
+
+       http://www.mongodb.org/downloads
+
+3) Build a CloudStack. If you are building first time, then build the stack.
+
+       go to "stack" folder in root directory
+       $ mvn install -Dmaven.test.skip=true
+
+4) Build a .jar file
+
+       $ mvn install -Dmaven.test.skip=true
+
+       - The CloudResourceDirectory-0.0.1-SNAPSHOT.jar file will be placed in the "target" folder
+
+5) Run .jar file
+
+       go to "target" folder
+       $ java -jar CloudResourceDirectory-0.0.1-SNAPSHOT.jar arg1(RD CoAP Server Port)
+       e.g java -jar CloudResourceDirectory-0.0.1-SNAPSHOT.jar 5684
+
diff --git a/cloud/resourcedirectory/pom.xml b/cloud/resourcedirectory/pom.xml
new file mode 100644 (file)
index 0000000..8976aba
--- /dev/null
@@ -0,0 +1,75 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+       <modelVersion>4.0.0</modelVersion>
+       <groupId>org.iotivity.cloud</groupId>
+       <artifactId>CloudResourceDirectory</artifactId>
+       <version>0.0.1-SNAPSHOT</version>
+
+       <properties>
+               <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+       </properties>
+
+       <dependencies>
+               <dependency>
+                       <groupId>org.iotivity.cloud</groupId>
+                       <artifactId>CloudStack</artifactId>
+                       <version>0.0.1-SNAPSHOT</version>
+               </dependency>
+               <dependency>
+                       <groupId>org.mongodb</groupId>
+                       <artifactId>mongo-java-driver</artifactId>
+                       <version>3.2.0</version>
+               </dependency>
+               <dependency>
+                       <groupId>junit</groupId>
+                       <artifactId>junit</artifactId>
+                       <version>4.12</version>
+               </dependency>
+       </dependencies>
+
+       <build>
+               <plugins>
+                       <plugin>
+                               <inherited>true</inherited>
+                               <groupId>org.apache.maven.plugins</groupId>
+                               <artifactId>maven-compiler-plugin</artifactId>
+                               <configuration>
+                                       <source>1.7</source>
+                                       <target>1.7</target>
+                                       <encoding>UTF-8</encoding>
+                               </configuration>
+                       </plugin>
+                       <plugin>
+                               <groupId>org.apache.maven.plugins</groupId>
+                               <artifactId>maven-jar-plugin</artifactId>
+                               <configuration>
+                                       <archive>
+                                               <manifest>
+                                                       <mainClass>org.iotivity.cloud.rdserver.ResourceDirectoryServer</mainClass>
+                                                       <addClasspath>true</addClasspath>
+                                                       <classpathPrefix>lib/</classpathPrefix>
+                                               </manifest>
+                                       </archive>
+                               </configuration>
+                       </plugin>
+                       <plugin>
+                               <groupId>org.apache.maven.plugins</groupId>
+                               <artifactId>maven-dependency-plugin</artifactId>
+                               <executions>
+                                       <execution>
+                                               <id>copy-dependencies</id>
+                                               <phase>package</phase>
+                                               <goals>
+                                                       <goal>copy-dependencies</goal>
+                                               </goals>
+                                       </execution>
+                               </executions>
+                               <configuration>
+                                       <outputDirectory>target/lib</outputDirectory>
+                                       <overWriteIfNewer>true</overWriteIfNewer>
+                               </configuration>
+                       </plugin>
+               </plugins>
+       </build>
+
+</project>
\ No newline at end of file
diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/Constants.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/Constants.java
new file mode 100644 (file)
index 0000000..9aa54b0
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.rdserver;
+
+public class Constants {
+    public static final String RD_TABLE   = "RD_TABLE";
+    public static final String RD_DB_NAME = "RDDB";
+
+    public static final String RD_URI = "oic/rd";
+
+    public static final String RS_DEVICE_NAME             = "n";
+    public static final String RS_DEVICE_ID               = "di";
+    public static final String RS_BASE_URI                = "baseURI";
+    public static final String RS_BITMAP                  = "bm";
+    public static final String RS_HOSTING_PORT            = "port";
+    public static final String RS_INS                     = "ins";
+    public static final String RS_RTS                     = "rts";
+    public static final String RS_DREL                    = "drel";
+    public static final String RS_TTL                     = "ttl";
+    public static final String RS_HREF                    = "href";
+    public static final String RS_RESOURCE_TYPE           = "rt";
+    public static final String RS_INTERFACE               = "if";
+    public static final String RS_REL                     = "rel";
+    public static final String RS_OBS                     = "obs";
+    public static final String RS_TITLE                   = "title";
+    public static final String RS_URI                     = "uri";
+    public static final String RS_MEDIA_TYPE              = "mt";
+    public static final String RS_RESOURCE_TYPE_RDPUBLISH = "oic.wk.rdpub";
+
+    public static final String RS_SEARCH_TYPE             = "st";
+    public static final String RS_SEARCH_TYPE_DEVICE_LIST = "didList";
+    public static final String RS_DEVICE_LIST_KEY         = "devices";
+}
diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/MongoDB.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/MongoDB.java
new file mode 100644 (file)
index 0000000..890e116
--- /dev/null
@@ -0,0 +1,359 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.rdserver;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+
+import org.bson.Document;
+import org.iotivity.cloud.rdserver.resources.LinksPayloadFormat;
+import org.iotivity.cloud.rdserver.resources.PublishPayloadFormat;
+
+import com.mongodb.MongoClient;
+import com.mongodb.client.MongoCollection;
+import com.mongodb.client.MongoCursor;
+import com.mongodb.client.MongoDatabase;
+import com.mongodb.client.model.Filters;
+
+/**
+ *
+ * This class provides a set of APIs to use MongoDB APIs.
+ *
+ */
+public class MongoDB {
+
+    private MongoClient   mongoClient = null;
+    private MongoDatabase db          = null;
+
+    /**
+     * API creating MongoClient and initializing MongoDatabase
+     *
+     * @param dbname
+     *            database name to create MongoDatabase
+     * @throws Exception
+     */
+    public MongoDB(String dbname) throws Exception {
+        mongoClient = new MongoClient();
+        mongoClient.dropDatabase(dbname);
+        db = mongoClient.getDatabase(dbname);
+    }
+
+    /**
+     * API creating collection
+     *
+     * @param tableName
+     *            collection name
+     */
+    public void createTable(String tableName) {
+        db.createCollection(tableName);
+    }
+
+    /**
+     * API deleting collection
+     *
+     * @param tableName
+     *            collection name
+     */
+    public void deleteTable(String tableName) {
+        db.getCollection(tableName).drop();
+    }
+
+    private ArrayList<Document> createDocuments(
+            PublishPayloadFormat publishPayloadFormat) {
+
+        Iterator<LinksPayloadFormat> linksPayloadFormatIter = publishPayloadFormat
+                .getLinks().iterator();
+        ArrayList<Document> docList = new ArrayList<Document>();
+
+        while (linksPayloadFormatIter.hasNext()) {
+            LinksPayloadFormat links = linksPayloadFormatIter.next();
+            Document doc = new Document(Constants.RS_DEVICE_NAME,
+                    publishPayloadFormat.getDeviceName())
+                            .append(Constants.RS_DEVICE_ID,
+                                    publishPayloadFormat.getDi())
+                            .append(Constants.RS_BASE_URI,
+                                    publishPayloadFormat.getBaseUri())
+                            .append(Constants.RS_BITMAP,
+                                    publishPayloadFormat.getBitmap())
+                            .append(Constants.RS_HOSTING_PORT,
+                                    publishPayloadFormat.getPort())
+                            .append(Constants.RS_INS,
+                                    publishPayloadFormat.getIns())
+                            .append(Constants.RS_RTS,
+                                    publishPayloadFormat.getRts())
+                            .append(Constants.RS_DREL,
+                                    publishPayloadFormat.getDrel())
+                            .append(Constants.RS_TTL,
+                                    publishPayloadFormat.getTtl())
+                            .append(Constants.RS_HREF, links.getHref())
+                            .append(Constants.RS_RESOURCE_TYPE, links.getRt())
+                            .append(Constants.RS_INTERFACE, links.getItf())
+                            .append(Constants.RS_REL, links.getRel())
+                            .append(Constants.RS_OBS, links.isObs())
+                            .append(Constants.RS_TITLE, links.getTitle())
+                            .append(Constants.RS_URI, links.getUri())
+                            .append(Constants.RS_INS, links.getIns())
+                            .append(Constants.RS_MEDIA_TYPE, links.getMt());
+            docList.add(doc);
+        }
+
+        return docList;
+    }
+
+    private PublishPayloadFormat convertDocumentToResourceFormat(Document doc) {
+        PublishPayloadFormat publishPayloadFormat = new PublishPayloadFormat();
+        LinksPayloadFormat linksPayloadFormat = new LinksPayloadFormat();
+        ArrayList<LinksPayloadFormat> list = new ArrayList<LinksPayloadFormat>();
+
+        Object tmp = null;
+        
+        tmp = doc.get(Constants.RS_DEVICE_NAME);
+        if(tmp != null) {
+            publishPayloadFormat
+            .setDeviceName(tmp.toString());
+        }
+        
+        tmp = doc.get(Constants.RS_DEVICE_ID);
+        if(tmp != null) {
+            publishPayloadFormat.setDi(tmp.toString());
+        }
+        
+        tmp = doc.get(Constants.RS_BASE_URI);
+        if(tmp != null) {
+            publishPayloadFormat.setBaseUri(tmp.toString());
+        }
+        
+        tmp = doc.get(Constants.RS_BITMAP);
+        if(tmp != null) {
+            publishPayloadFormat.setBitmap((int)tmp);
+        }
+        
+        tmp = doc.get(Constants.RS_HOSTING_PORT);
+        if(tmp != null) {
+            publishPayloadFormat.setPort((int)tmp);
+        }
+       
+        tmp = doc.get(Constants.RS_INS);
+        if(tmp != null) {
+            publishPayloadFormat.setIns((int)tmp);
+        }
+        
+        tmp = doc.get(Constants.RS_RTS);
+        if(tmp != null) {
+            publishPayloadFormat.setRts(tmp.toString());
+        }
+        
+        tmp = doc.get(Constants.RS_DREL);
+        if(tmp != null) {
+            publishPayloadFormat.setDrel(tmp.toString());
+        }
+        
+        tmp = doc.get(Constants.RS_TTL);
+        if(tmp != null) {
+            publishPayloadFormat.setTtl((int)tmp);
+        }
+        
+        tmp = doc.get(Constants.RS_HREF);
+        if(tmp != null) {
+            linksPayloadFormat.setHref(tmp.toString());
+        }
+        
+        tmp = doc.get(Constants.RS_RESOURCE_TYPE);
+        if(tmp != null) {
+            linksPayloadFormat
+            .setRt((ArrayList<String>) tmp);
+        }
+
+        tmp = doc.get(Constants.RS_INTERFACE);
+        if(tmp != null) {
+            linksPayloadFormat
+            .setItf((ArrayList<String>) tmp);
+        }
+        
+        tmp = doc.get(Constants.RS_REL);
+        if(tmp != null) {
+            linksPayloadFormat.setRel(tmp.toString());
+        }
+        
+        tmp = doc.get(Constants.RS_OBS);
+        if(tmp != null) {
+            linksPayloadFormat.setObs((boolean)tmp);
+        }
+        
+        tmp = doc.get(Constants.RS_TITLE);
+        if(tmp != null) {
+            linksPayloadFormat.setTitle(tmp.toString());
+        }
+        
+        tmp = doc.get(Constants.RS_URI);
+        if(tmp != null) {
+            linksPayloadFormat.setUri(tmp.toString());
+        }
+        
+        tmp = doc.get(Constants.RS_INS);
+        if(tmp != null) {
+            linksPayloadFormat.setIns((int)tmp);
+        }
+        
+        tmp = doc.get(Constants.RS_MEDIA_TYPE);
+        if(tmp != null) {
+            linksPayloadFormat
+            .setMt((ArrayList<String>) tmp);
+        }
+
+        list.add(linksPayloadFormat);
+        publishPayloadFormat.setLinks(list);
+
+        return publishPayloadFormat;
+    }
+
+    /**
+     * API for storing information of published resources
+     *
+     * @param publishPayloadFormat
+     *            information of published resources to store in collection
+     * @param tablename
+     *            collection name
+     */
+    public void createResource(PublishPayloadFormat publishPayloadFormat,
+            String tablename) {
+        ArrayList<Document> docList = createDocuments(publishPayloadFormat);
+        Iterator<Document> docIter = docList.iterator();
+
+        MongoCollection<Document> collection = db.getCollection(tablename);
+
+        while (docIter.hasNext()) {
+            Document doc = docIter.next();
+
+            if (collection.findOneAndReplace(
+                    Filters.and(Filters.eq(Constants.RS_DEVICE_ID,
+                            doc.get(Constants.RS_DEVICE_ID)),
+                    Filters.eq(Constants.RS_INS, doc.get(Constants.RS_INS))),
+                    doc) == null) {
+
+                collection.insertOne(doc);
+            }
+        }
+    }
+
+    /**
+     * API for finding resources matched filterValue of filterKey in collection
+     *
+     * @param filterKey
+     *            field name in collection
+     * @param filterValue
+     *            field value about field name
+     * @param tablename
+     *            collection name
+     * @return ArrayList<PublishPayloadFormat> - array list of resource
+     *         information
+     */
+    public ArrayList<PublishPayloadFormat> readResource(String filterKey,
+            String filterValue, String tablename) {
+        MongoCollection<Document> collection = db.getCollection(tablename);
+        ArrayList<PublishPayloadFormat> resourceFormatList = new ArrayList<PublishPayloadFormat>();
+        MongoCursor<Document> cursor = collection
+                .find(Filters.eq(filterKey, filterValue)).iterator();
+        try {
+            while (cursor.hasNext()) {
+                Document doc = cursor.next();
+                resourceFormatList.add(convertDocumentToResourceFormat(doc));
+            }
+        } finally {
+            cursor.close();
+        }
+
+        return resourceFormatList;
+    }
+
+    /**
+     * API for finding resources matched filterValue of filterKey and a
+     * particular device ID in collection
+     *
+     * @param di
+     *            device id
+     * @param filterKey
+     *            field name in collection
+     * @param filterValue
+     *            field value about field name
+     * @param tablename
+     *            collection name
+     * @return ArrayList<PublishPayloadFormat> - array list of resource
+     *         information
+     */
+    public ArrayList<PublishPayloadFormat> readResourceAboutDid(String di,
+            String filterKey, String filterValue, String tablename) {
+        MongoCollection<Document> collection = db.getCollection(tablename);
+        ArrayList<PublishPayloadFormat> resourceFormatList = new ArrayList<PublishPayloadFormat>();
+        MongoCursor<Document> cursor = collection
+                .find(Filters.and(Filters.eq(Constants.RS_DEVICE_ID, di),
+                        Filters.eq(filterKey, filterValue)))
+                .iterator();
+        try {
+            while (cursor.hasNext()) {
+                Document doc = cursor.next();
+                resourceFormatList.add(convertDocumentToResourceFormat(doc));
+            }
+        } finally {
+            cursor.close();
+        }
+
+        return resourceFormatList;
+    }
+
+    /**
+     * API for deleting resources about a particular device ID in collection
+     *
+     * @param di
+     *            device id
+     * @param tablename
+     *            collection name
+     */
+    public void deleteResourceAboutDid(String di, String tablename) {
+
+        MongoCollection<Document> collection = db.getCollection(tablename);
+
+        collection.findOneAndDelete(Filters.eq(Constants.RS_DEVICE_ID, di));
+    }
+
+    /**
+     * API for deleting resources about a particular device ID and ins in
+     * collection
+     *
+     * @param di
+     *            device id
+     * @param ins
+     *            ins
+     * @param tablename
+     *            collection name
+     */
+    public void deleteResourceAboutDidAndIns(String di, String ins,
+            String tablename) {
+
+        MongoCollection<Document> collection = db.getCollection(tablename);
+
+        collection.findOneAndDelete(
+                Filters.and(Filters.eq(Constants.RS_DEVICE_ID, di),
+                        Filters.eq(Constants.RS_INS, ins)));
+
+    }
+}
diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/ResourceDirectoryServer.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/ResourceDirectoryServer.java
new file mode 100644 (file)
index 0000000..8f58000
--- /dev/null
@@ -0,0 +1,72 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.rdserver;
+
+import java.net.InetSocketAddress;
+import java.util.Scanner;
+
+import org.iotivity.cloud.base.CoapServer;
+import org.iotivity.cloud.base.ResourceManager;
+import org.iotivity.cloud.rdserver.resources.ResourceDirectoryResource;
+import org.iotivity.cloud.util.Logger;
+
+public class ResourceDirectoryServer {
+
+    public static void main(String[] args) throws Exception {
+
+        System.out.println("-----RD SERVER-----");
+
+        if (args.length != 1) {
+            Logger.e("coap server port required");
+            return;
+        }
+
+        ResourceManager resourceManager = null;
+
+        CoapServer coapServer = null;
+
+        coapServer = new CoapServer();
+
+        resourceManager = new ResourceManager();
+
+        coapServer.addHandler(resourceManager);
+
+        resourceManager.registerResource(new ResourceDirectoryResource());
+
+        coapServer
+                .startServer(new InetSocketAddress(Integer.parseInt(args[0])));
+
+        Scanner in = new Scanner(System.in, "UTF-8");
+
+        System.out.println("press 'q' to terminate");
+
+        while (!in.nextLine().equals("q"));
+
+        in.close();
+
+        System.out.println("Terminating...");
+
+        coapServer.stopServer();
+
+        System.out.println("Terminated");
+    }
+}
diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/LinksPayloadFormat.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/LinksPayloadFormat.java
new file mode 100644 (file)
index 0000000..0f6a6c5
--- /dev/null
@@ -0,0 +1,147 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.rdserver.resources;
+
+import java.util.ArrayList;
+
+public class LinksPayloadFormat {
+    /** This is the target relative URI. */
+    String            href;
+    /**
+     * Resource Type - A standard OIC specified or vendor defined resource type
+     * of the resource referenced by the target URI.
+     */
+    ArrayList<String> rt;
+    /**
+     * Interface - The interfaces supported by the resource referenced by the
+     * target URI.
+     */
+    ArrayList<String> itf;
+    /**
+     * The relation of the target URI referenced by the link to the context URI;
+     * The default value is null.
+     */
+    String            rel;
+    /**
+     * Specifies if the resource referenced by the target URIis observable or
+     * not.
+     */
+    boolean           obs;
+    /**
+     * A title for the link relation. Can be used by the UI to provide a
+     * context.
+     */
+    String            title;
+    /**
+     * This is used to override the context URI e.g. override the URI of the
+     * containing collection.
+     */
+    String            uri;
+    /**
+     * The instance identifier for this web link in an array of web links - used
+     * in links.
+     */
+    int               ins;
+    /**
+     * A hint of the media type of the representation of the resource referenced
+     * by the target URI.
+     */
+    ArrayList<String> mt;
+
+    public LinksPayloadFormat() {
+        rt = new ArrayList<String>();
+        itf = new ArrayList<String>();
+        mt = new ArrayList<String>();
+    }
+
+    public String getHref() {
+        return href;
+    }
+
+    public void setHref(String href) {
+        this.href = href;
+    }
+
+    public ArrayList<String> getRt() {
+        return rt;
+    }
+
+    public void setRt(ArrayList<String> rt) {
+        this.rt = rt;
+    }
+
+    public ArrayList<String> getItf() {
+        return itf;
+    }
+
+    public void setItf(ArrayList<String> itf) {
+        this.itf = itf;
+    }
+
+    public String getRel() {
+        return rel;
+    }
+
+    public void setRel(String rel) {
+        this.rel = rel;
+    }
+
+    public boolean isObs() {
+        return obs;
+    }
+
+    public void setObs(boolean obs) {
+        this.obs = obs;
+    }
+
+    public String getTitle() {
+        return title;
+    }
+
+    public void setTitle(String title) {
+        this.title = title;
+    }
+
+    public String getUri() {
+        return uri;
+    }
+
+    public void setUri(String uri) {
+        this.uri = uri;
+    }
+
+    public int getIns() {
+        return ins;
+    }
+
+    public void setIns(int ins) {
+        this.ins = ins;
+    }
+
+    public ArrayList<String> getMt() {
+        return mt;
+    }
+
+    public void setMt(ArrayList<String> mt) {
+        this.mt = mt;
+    }
+}
\ No newline at end of file
diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/PublishPayloadFormat.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/PublishPayloadFormat.java
new file mode 100644 (file)
index 0000000..1fe0191
--- /dev/null
@@ -0,0 +1,139 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.rdserver.resources;
+
+import java.util.ArrayList;
+
+public class PublishPayloadFormat {
+
+    /** Name of tags. */
+    String deviceName;
+    /** Device identifier. */
+    String di;
+    /** The base URI where the resources are hold. */
+    String baseUri;
+    /** Bitmap holds observable, discoverable, secure option flag. */
+    int    bitmap;
+    /** Port set in case, the secure flag is set above. */
+    int    port;
+    /** Id for each set of links i.e. tag. */
+    int    ins;
+    /**
+     * Defines the list of allowable resource types (for Target and anchors) in
+     * links included in the collection; new links being created can only be
+     * from this list.
+     */
+    String rts;
+    /**
+     * When specified this is the default relationship to use when an OIC Link
+     * does not specify an explicit relationship with *rel* parameter.
+     */
+    String drel;
+    /** Time to keep holding resource. */
+    int    ttl;
+
+    ArrayList<LinksPayloadFormat> links;
+
+    public PublishPayloadFormat() {
+        links = new ArrayList<LinksPayloadFormat>();
+    }
+
+    public String getDeviceName() {
+        return deviceName;
+    }
+
+    public void setDeviceName(String deviceName) {
+        this.deviceName = deviceName;
+    }
+
+    public String getDi() {
+        return di;
+    }
+
+    public void setDi(String di) {
+        this.di = di;
+    }
+
+    public String getBaseUri() {
+        return baseUri;
+    }
+
+    public void setBaseUri(String baseUri) {
+        this.baseUri = baseUri;
+    }
+
+    public int getBitmap() {
+        return bitmap;
+    }
+
+    public void setBitmap(int bitmap) {
+        this.bitmap = bitmap;
+    }
+
+    public int getPort() {
+        return port;
+    }
+
+    public void setPort(int port) {
+        this.port = port;
+    }
+
+    public int getIns() {
+        return ins;
+    }
+
+    public void setIns(int ins) {
+        this.ins = ins;
+    }
+
+    public String getRts() {
+        return rts;
+    }
+
+    public void setRts(String rts) {
+        this.rts = rts;
+    }
+
+    public String getDrel() {
+        return drel;
+    }
+
+    public void setDrel(String drel) {
+        this.drel = drel;
+    }
+
+    public int getTtl() {
+        return ttl;
+    }
+
+    public void setTtl(int ttl) {
+        this.ttl = ttl;
+    }
+
+    public ArrayList<LinksPayloadFormat> getLinks() {
+        return links;
+    }
+
+    public void setLinks(ArrayList<LinksPayloadFormat> links) {
+        this.links = links;
+    }
+}
diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/ResourceDirectoryResource.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/ResourceDirectoryResource.java
new file mode 100644 (file)
index 0000000..09d3471
--- /dev/null
@@ -0,0 +1,530 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.rdserver.resources;
+
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.StringTokenizer;
+
+import org.iotivity.cloud.base.Resource;
+import org.iotivity.cloud.base.protocols.coap.CoapRequest;
+import org.iotivity.cloud.base.protocols.coap.CoapResponse;
+import org.iotivity.cloud.base.protocols.coap.enums.CoapOption;
+import org.iotivity.cloud.base.protocols.coap.enums.CoapStatus;
+import org.iotivity.cloud.rdserver.Constants;
+import org.iotivity.cloud.rdserver.MongoDB;
+import org.iotivity.cloud.util.Cbor;
+import org.iotivity.cloud.util.JSONUtil;
+import org.iotivity.cloud.util.Logger;
+
+import io.netty.channel.ChannelHandlerContext;
+
+/**
+ *
+ * This class provides a set of APIs relating Resource Directory
+ *
+ */
+public class ResourceDirectoryResource extends Resource {
+
+    private Cbor<ArrayList<Object>> cbor;
+    private MongoDB                 mongoDB;
+
+    public ResourceDirectoryResource() {
+        setUri(Constants.RD_URI);
+        cbor = new Cbor<ArrayList<Object>>();
+        try {
+            mongoDB = new MongoDB(Constants.RD_DB_NAME);
+            mongoDB.createTable(Constants.RD_TABLE);
+        } catch (Exception e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+    }
+
+    @Override
+    public void onRequestReceived(ChannelHandlerContext ctx,
+            CoapRequest request) {
+
+        Logger.d("ResourceDirectoryResource IN");
+
+        if (ctx == null || request == null) {
+            Logger.d("ctx or request msg is null");
+        }
+
+        else {
+            switch (request.getRequestMethod()) {
+                case GET:
+                    Logger.d("Request message is GET message");
+                    try {
+                        handleGetRequest(ctx, request);
+                    } catch (Exception e) {
+                        e.printStackTrace();
+                    }
+                    break;
+
+                case PUT:
+                    Logger.d("Request message is PUT message");
+                    break;
+
+                case POST:
+                    Logger.d("Request message is POST message");
+                    try {
+                        handlePostRequest(ctx, request);
+                    } catch (Exception e) {
+                        e.printStackTrace();
+                    }
+                    break;
+
+                case DELETE:
+                    Logger.d("Request message is DELETE message");
+                    try {
+                        handleDeleteRequest(ctx, request);
+                    } catch (Exception e) {
+                        e.printStackTrace();
+                    }
+                    break;
+            }
+        }
+    }
+
+    private CoapResponse makePublishResponse(CoapRequest request)
+            throws Exception {
+        CoapResponse response = new CoapResponse(CoapStatus.CREATED);
+        response.setToken(request.getToken());
+        return response;
+    }
+
+    private CoapResponse makeDeleteResponse(CoapRequest request)
+            throws Exception {
+        CoapResponse response = new CoapResponse(CoapStatus.DELETED);
+        response.setToken(request.getToken());
+        return response;
+    }
+
+    private CoapResponse makeDiscoveryResponse(CoapRequest request,
+            ArrayList<PublishPayloadFormat> foundResource) throws Exception {
+
+        CoapResponse response = new CoapResponse(CoapStatus.CONTENT);
+        response.setToken(request.getToken());
+
+        // make payload
+        ArrayList<HashMap<Object, Object>> discoverPayload = new ArrayList<HashMap<Object, Object>>();
+
+        for (PublishPayloadFormat pubPayload : foundResource) {
+
+            LinksPayloadFormat links = pubPayload.links.get(0);
+            LinkedHashMap<Object, Object> discoverLinks = new LinkedHashMap<Object, Object>();
+            discoverLinks.put(Constants.RS_HREF, links.getHref());
+            discoverLinks.put(Constants.RS_RESOURCE_TYPE, links.getRt().get(0));
+            discoverLinks.put(Constants.RS_INTERFACE, links.getItf().get(0));
+            HashMap<Object, Object> pres = new HashMap<Object, Object>();
+            pres.put(Constants.RS_BITMAP, pubPayload.getBitmap());
+            discoverLinks.put("p", pres);
+
+            ArrayList<Object> linksArray = null;
+            for (HashMap<Object, Object> segmentPayload : discoverPayload) {
+                // exist di
+                if (segmentPayload.get(Constants.RS_DEVICE_ID)
+                        .equals(pubPayload.getDi())) {
+                    linksArray = new ArrayList<Object>();
+                    linksArray = (ArrayList<Object>) segmentPayload
+                            .get("links");
+                    linksArray.add(discoverLinks);
+                    segmentPayload.put("links", linksArray);
+                }
+            }
+            if (linksArray == null) {
+                HashMap<Object, Object> discoverRes = new HashMap<Object, Object>();
+                linksArray = new ArrayList<Object>();
+                discoverRes.put(Constants.RS_DEVICE_ID, pubPayload.getDi());
+                linksArray.add(discoverLinks);
+                discoverRes.put("links", linksArray);
+                discoverPayload.add(discoverRes);
+            }
+        }
+
+        // TODO : device id is decoded to byte in IoTivity. So, temporarily we
+        // cast the type of device id to byte.
+        for (HashMap<Object, Object> segmentPayload : discoverPayload) {
+            String stringDi = segmentPayload.get(Constants.RS_DEVICE_ID)
+                    .toString();
+            segmentPayload.put(Constants.RS_DEVICE_ID,
+                    stringDi.getBytes(StandardCharsets.UTF_8));
+        }
+
+        Logger.i("discoverPayload :" + discoverPayload.toString());
+
+        byte[] bytes = ByteBuffer.allocate(4).putInt(60).array();
+        response.addOption(CoapOption.CONTENT_FORMAT.getvalue(), bytes);
+
+        byte[] encodedPaylod = cbor.encodingPayloadToCbor(discoverPayload);
+        response.setPayload(encodedPaylod);
+
+        return response;
+
+    }
+
+    private HashMap<String, String> extractFiltersFromQuery(List<String> query)
+            throws Exception {
+
+        if (query == null) {
+            throw new IllegalArgumentException("query is null!");
+        }
+
+        HashMap<String, String> filters = new HashMap<String, String>();
+        for (String queryPara : query) {
+            StringTokenizer keyValuePair = new StringTokenizer(queryPara, "=");
+            if (keyValuePair.countTokens() < 2) {
+                // query error
+                filters = null;
+            } else {
+                String key = keyValuePair.nextToken();
+                String value = keyValuePair.nextToken();
+                if (key.equals(Constants.RS_INTERFACE)) {
+                    filters.put(Constants.RS_INTERFACE, value);
+                } else if (key.equals(Constants.RS_RESOURCE_TYPE)) {
+                    filters.put(Constants.RS_RESOURCE_TYPE, value);
+                } else if (key.equals(Constants.RS_DEVICE_ID)) {
+                    filters.put(Constants.RS_DEVICE_ID, value);
+                } else if (key.equals(Constants.RS_INS)) {
+                    filters.put(Constants.RS_INS, value);
+                } else if (key.equals(Constants.RS_SEARCH_TYPE)) {
+                    filters.put(Constants.RS_SEARCH_TYPE, value);
+                }
+            }
+        }
+
+        return filters;
+    }
+
+    /**
+     * API for handling GET message(message to discovery resources)
+     *
+     * @param ctx
+     *            ChannelHandlerContext of request message
+     * @param request
+     *            CoAP request message
+     * @throws Exception
+     */
+    public void handleGetRequest(ChannelHandlerContext ctx, CoapRequest request)
+            throws Exception {
+        HashMap<String, String> filters = extractFiltersFromQuery(
+                request.getUriQuerySegments());
+
+        ArrayList<PublishPayloadFormat> foundResource = null;
+
+        if (filters == null) {
+            throw new IllegalArgumentException("filters is null");
+        } else if (filters.get(Constants.RS_SEARCH_TYPE) == null) {
+            Logger.d("st is null, so this is the get msg about public devices");
+            if (filters.get(Constants.RS_INTERFACE) != null) {
+                foundResource = mongoDB.readResource(Constants.RS_INTERFACE,
+                        filters.get(Constants.RS_INTERFACE),
+                        Constants.RD_TABLE);
+            } else if (filters.get(Constants.RS_RESOURCE_TYPE) != null) {
+                foundResource = mongoDB.readResource(Constants.RS_RESOURCE_TYPE,
+                        filters.get(Constants.RS_RESOURCE_TYPE),
+                        Constants.RD_TABLE);
+            } else {
+                throw new IllegalArgumentException("rt & if is null");
+            }
+
+            CoapResponse response = makeDiscoveryResponse(request,
+                    foundResource);
+            ctx.writeAndFlush(response);
+
+        } else {
+            if (filters.get(Constants.RS_SEARCH_TYPE)
+                    .equals(Constants.RS_SEARCH_TYPE_DEVICE_LIST)) {
+                Logger.d(
+                        "st is not null, so this is the get msg about private devices");
+                // parse payload
+                byte[] payload = request.getPayload();
+                ArrayList<String> deviceList = JSONUtil.parseJSON(payload,
+                        Constants.RS_DEVICE_LIST_KEY);
+                if (deviceList == null) {
+                    throw new IllegalArgumentException("deviceList is null");
+                }
+
+                if (filters.get(Constants.RS_INTERFACE) != null) {
+                    foundResource = new ArrayList<PublishPayloadFormat>();
+                    for (String deviceId : deviceList) {
+                        foundResource.addAll(mongoDB.readResourceAboutDid(
+                                deviceId, Constants.RS_INTERFACE,
+                                filters.get(Constants.RS_INTERFACE),
+                                Constants.RD_TABLE));
+                    }
+                } else if (filters.get(Constants.RS_RESOURCE_TYPE) != null) {
+                    foundResource = new ArrayList<PublishPayloadFormat>();
+                    for (String deviceId : deviceList) {
+                        foundResource.addAll(mongoDB.readResourceAboutDid(
+                                deviceId, Constants.RS_RESOURCE_TYPE,
+                                filters.get(Constants.RS_RESOURCE_TYPE),
+                                Constants.RD_TABLE));
+                    }
+                } else {
+                    throw new IllegalArgumentException("rt & if is null");
+                }
+
+                CoapResponse response = makeDiscoveryResponse(request,
+                        foundResource);
+                ctx.writeAndFlush(response);
+            } else {
+                throw new IllegalArgumentException("value of st is not corret");
+            }
+        }
+    }
+
+    /**
+     * API for handling POST message(message to publish or update resources)
+     *
+     * @param ctx
+     *            ChannelHandlerContext of request message
+     * @param request
+     *            CoAP request message
+     * @throws Exception
+     */
+    public void handlePostRequest(ChannelHandlerContext ctx,
+            CoapRequest request) throws Exception {
+
+        HashMap<String, String> filters = extractFiltersFromQuery(
+                request.getUriQuerySegments());
+
+        if (filters == null) {
+            throw new IllegalArgumentException("filters is null");
+        } else if (filters.get(Constants.RS_RESOURCE_TYPE) == null) {
+            throw new IllegalArgumentException("rt is null");
+        } else if (filters.get(Constants.RS_RESOURCE_TYPE)
+                .equals(Constants.RS_RESOURCE_TYPE_RDPUBLISH)) {
+            Logger.d("This request is publish msg!");
+
+            PublishPayloadFormat pubPayload = new PublishPayloadFormat();
+
+            ArrayList<Object> payloadData = cbor.parsePayloadFromCbor(
+                    request.getPayload(), ArrayList.class);
+
+            if (payloadData == null) {
+                throw new IllegalArgumentException("parsed payload is null");
+            } else {
+                Logger.i("payloadData: " + payloadData.toString());
+            }
+
+            HashMap<Object, Object> tags = (HashMap<Object, Object>) payloadData
+                    .get(0);
+
+            if (tags == null) {
+                throw new IllegalArgumentException("tags is null!");
+            }
+
+            Object di = tags.get(Constants.RS_DEVICE_ID);
+            if (di != null) {
+                pubPayload.setDi(di.toString());
+                Logger.i("di : " + pubPayload.getDi());
+            } else {
+                throw new IllegalArgumentException("device id is null!");
+            }
+
+            Object deviceName = tags.get(Constants.RS_DEVICE_NAME);
+            if (deviceName != null) {
+                pubPayload.setDeviceName(deviceName.toString());
+                Logger.i("device name : " + pubPayload.getDeviceName());
+            }
+
+            Object baseUri = tags.get(Constants.RS_BASE_URI);
+            if (baseUri != null) {
+                pubPayload.setBaseUri(baseUri.toString());
+                Logger.i("baseURI : " + pubPayload.getBaseUri());
+            }
+
+            Object bitMap = tags.get(Constants.RS_BITMAP);
+            if (bitMap != null) {
+                pubPayload.setBitmap((int) bitMap);
+                Logger.i("bm : " + pubPayload.getBitmap());
+            }
+
+            Object hostingPort = tags.get(Constants.RS_HOSTING_PORT);
+            if (hostingPort != null) {
+                pubPayload.setPort((int) hostingPort);
+                Logger.i("port : " + pubPayload.getPort());
+            }
+
+            Object ins = tags.get(Constants.RS_INS);
+            if (ins != null) {
+                pubPayload.setIns((int) ins);
+                Logger.i("ins : " + pubPayload.getIns());
+            }
+
+            Object rts = tags.get(Constants.RS_RTS);
+            if (rts != null) {
+                pubPayload.setRts(rts.toString());
+                Logger.i("rts : " + pubPayload.getRts());
+            }
+
+            Object drel = tags.get(Constants.RS_DREL);
+            if (drel != null) {
+                pubPayload.setDrel(drel.toString());
+                Logger.i("drel : " + pubPayload.getDrel());
+            }
+
+            // Object ttl = tags.get(Constants.RS_TTL);
+            // if (ttl != null) {
+            // pubPayload.setTtl((int) ttl);
+            // Logger.i("ttl : " + pubPayload.getTtl());
+            // }
+
+            ArrayList<LinkedHashMap<Object, Object>> publishLinks = (ArrayList<LinkedHashMap<Object, Object>>) payloadData
+                    .get(1);
+
+            if (publishLinks == null) {
+                throw new IllegalArgumentException("publishLinks is null!");
+            }
+
+            for (LinkedHashMap<Object, Object> o : publishLinks) {
+
+                LinksPayloadFormat storeLinks = new LinksPayloadFormat();
+
+                Object href = o.get(Constants.RS_HREF);
+                if (href != null) {
+                    String prefix = "/" + pubPayload.getDi();
+                    storeLinks.setHref(prefix + href.toString());
+                    Logger.i("href : " + storeLinks.getHref());
+                }
+
+                if (o.get(Constants.RS_RESOURCE_TYPE) != null) {
+                    Object obj = o.get(Constants.RS_RESOURCE_TYPE);
+                    if (obj != null) {
+                        storeLinks.setRt((ArrayList<String>) obj);
+                    }
+                    Object rt = storeLinks.getRt();
+                    if (rt != null) {
+                        Logger.i("rt : " + storeLinks.getRt().toString());
+                    }
+                }
+
+                if (o.get(Constants.RS_INTERFACE) != null) {
+                    storeLinks.setItf(
+                            (ArrayList<String>) o.get(Constants.RS_INTERFACE));
+                    Object itf = storeLinks.getItf();
+                    if (itf != null) {
+                        Logger.i("if : " + storeLinks.getItf().toString());
+                    }
+                }
+
+                Object rel = o.get(Constants.RS_REL);
+                if (rel != null) {
+                    storeLinks.setRel(rel.toString());
+                    Logger.i("rel : " + storeLinks.getRel());
+                }
+
+                if (o.get(Constants.RS_OBS) != null) {
+                    Object obj = o.get(Constants.RS_OBS);
+                    if (obj != null) {
+                        storeLinks.setObs((boolean) obj);
+                    }
+                    Logger.i("obs : " + storeLinks.isObs());
+                }
+
+                if (o.get(Constants.RS_TITLE) != null) {
+                    Object obj = o.get(Constants.RS_TITLE);
+                    if (obj != null) {
+                        storeLinks.setTitle(obj.toString());
+                    }
+                    Logger.i("title : " + storeLinks.getTitle());
+                }
+
+                if (o.get(Constants.RS_URI) != null) {
+                    Object obj = o.get(Constants.RS_URI);
+                    if (obj != null) {
+                        storeLinks.setUri(obj.toString());
+                    }
+                    Logger.i("uri : " + storeLinks.getUri());
+                }
+
+                if (o.get(Constants.RS_INS) != null) {
+                    Object obj = o.get(Constants.RS_INS);
+                    if (obj != null) {
+                        storeLinks.setIns((int) obj);
+                    }
+                    Logger.i("ins : " + storeLinks.getIns());
+                }
+
+                if (o.get(Constants.RS_MEDIA_TYPE) != null) {
+                    Object obj = o.get(Constants.RS_MEDIA_TYPE);
+                    if (obj != null) {
+                        storeLinks.setMt((ArrayList<String>) obj);
+                    }
+                    Object mt = storeLinks.getMt();
+                    if (mt != null) {
+                        Logger.i("mt : " + mt.toString());
+                    }
+                }
+
+                pubPayload.links.add(storeLinks);
+            }
+
+            mongoDB.createResource(pubPayload, Constants.RD_TABLE);
+
+            CoapResponse response = makePublishResponse(request);
+            ctx.writeAndFlush(response);
+
+        } else {
+            throw new IllegalArgumentException("rt is not correct");
+        }
+    }
+
+    /**
+     * API for handling Delete message(message to delete published resources)
+     *
+     * @param ctx
+     *            ChannelHandlerContext of request message
+     * @param request
+     *            CoAP request message
+     * @throws Exception
+     */
+    public void handleDeleteRequest(ChannelHandlerContext ctx,
+            CoapRequest request) throws Exception {
+        HashMap<String, String> filters = extractFiltersFromQuery(
+                request.getUriQuerySegments());
+
+        if (filters == null) {
+            throw new IllegalArgumentException("filters is null");
+        } else if (filters.get(Constants.RS_DEVICE_ID) == null) {
+            throw new IllegalArgumentException("di is null");
+        } else {
+            if (filters.get(Constants.RS_INS) == null) {
+                mongoDB.deleteResourceAboutDid(
+                        filters.get(Constants.RS_DEVICE_ID),
+                        Constants.RD_TABLE);
+            } else {
+                mongoDB.deleteResourceAboutDidAndIns(
+                        filters.get(Constants.RS_DEVICE_ID),
+                        filters.get(Constants.RS_INS), Constants.RD_TABLE);
+            }
+            CoapResponse response = makeDeleteResponse(request);
+            ctx.writeAndFlush(response);
+        }
+    }
+}
diff --git a/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/RDServerTest.java b/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/RDServerTest.java
new file mode 100644 (file)
index 0000000..bf8ada3
--- /dev/null
@@ -0,0 +1,281 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.testrdserver;
+
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import org.iotivity.cloud.base.CoapClient;
+import org.iotivity.cloud.base.CoapServer;
+import org.iotivity.cloud.base.ResourceManager;
+import org.iotivity.cloud.base.protocols.coap.CoapRequest;
+import org.iotivity.cloud.base.protocols.coap.CoapResponse;
+import org.iotivity.cloud.base.protocols.coap.enums.CoapMethod;
+import org.iotivity.cloud.rdserver.Constants;
+import org.iotivity.cloud.rdserver.resources.ResourceDirectoryResource;
+import org.iotivity.cloud.util.Cbor;
+import org.iotivity.cloud.util.JSONUtil;
+import org.junit.Test;
+
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.SimpleChannelInboundHandler;
+
+public class RDServerTest {
+
+    private ResourceDirectoryResource rdResource = new ResourceDirectoryResource();
+    private CoapServer                coapServer = null;
+    private CoapClient                coapClient = null;
+
+    static class CoapClientHandler
+            extends SimpleChannelInboundHandler<CoapResponse> {
+
+        ChannelHandlerContext connectCtx = null;
+
+        @Override
+        public void channelActive(ChannelHandlerContext ctx) throws Exception {
+            connectCtx = ctx;
+        }
+
+        @Override
+        protected void channelRead0(ChannelHandlerContext arg0,
+                CoapResponse arg1) throws Exception {
+            // TODO Auto-generated method stub
+
+        }
+    }
+
+    public void startServer() throws Exception {
+        coapServer = new CoapServer();
+        ResourceManager resourceManager = new ResourceManager();
+        coapServer.addHandler(resourceManager);
+        resourceManager.registerResource(new ResourceDirectoryResource());
+        coapServer.startServer(new InetSocketAddress(5683));
+    }
+
+    public ChannelHandlerContext startClient() throws Exception {
+        coapClient = new CoapClient();
+        CoapClientHandler coapHandler = new CoapClientHandler();
+        coapClient.addHandler(coapHandler);
+        coapClient.startClient(new InetSocketAddress("127.0.0.1", 5683));
+        if (coapHandler.connectCtx == null) {
+                throw new IllegalArgumentException("connectCtx is null");
+        }
+        return coapHandler.connectCtx;
+    }
+
+    public CoapRequest makePublishPayload() throws Exception {
+
+        CoapRequest request = new CoapRequest(CoapMethod.POST);
+        request.setUriPath(Constants.RD_URI);
+        request.setUriQuery("rt=oic.wk.rdpub");
+        request.setToken("1234".getBytes(StandardCharsets.UTF_8));
+
+        ArrayList<Object> payload = new ArrayList<Object>();
+
+        HashMap<Object, Object> tags = new HashMap<Object, Object>();
+        tags.put("di", "98f7483c-5a31-4161-ba7e-9c13e0d");
+        tags.put("bm", (int) 1);
+        tags.put("ttl", (int) 86400);
+
+        ArrayList<LinkedHashMap<Object, Object>> publishLinks = new ArrayList<LinkedHashMap<Object, Object>>();
+        LinkedHashMap<Object, Object> link = new LinkedHashMap<Object, Object>();
+        link.put("href", "/a/light");
+        ArrayList<String> rt = new ArrayList<String>();
+        ArrayList<String> itf = new ArrayList<String>();
+        ArrayList<String> mt = new ArrayList<String>();
+        rt.add("core.light");
+        link.put("rt", rt);
+
+        itf.add("oic.if.baseline");
+        link.put("if", itf);
+
+        mt.add("application/json");
+        link.put("mt", mt);
+
+        link.put("ins", 1);
+
+        publishLinks.add(link);
+
+        payload.add(tags);
+        payload.add(publishLinks);
+
+        Cbor<ArrayList<Object>> cbor = new Cbor<ArrayList<Object>>();
+
+        request.setPayload(cbor.encodingPayloadToCbor(payload));
+
+        return request;
+    }
+
+    @Test
+    public void testHandlePostRequest() throws Exception {
+
+        startServer();
+        ChannelHandlerContext ctx = startClient();
+
+        rdResource.handlePostRequest(ctx, makePublishPayload());
+
+        coapClient.stopClient();
+        coapServer.stopServer();
+
+    }
+
+    @Test
+    public void testHandleGetRequest_notExistVaule() throws Exception {
+
+        CoapRequest request = new CoapRequest(CoapMethod.GET);
+        request.setUriPath(Constants.RD_URI);
+        request.setUriQuery("rt=core.light");
+        request.setToken("1234".getBytes(StandardCharsets.UTF_8));
+
+        startServer();
+        ChannelHandlerContext ctx = startClient();
+
+        rdResource.handleGetRequest(ctx, request);
+
+        coapClient.stopClient();
+        coapServer.stopServer();
+    }
+
+    @Test
+    public void testHandleGetRequest_existValue() throws Exception {
+
+        CoapRequest request = new CoapRequest(CoapMethod.GET);
+        request.setUriPath(Constants.RD_URI);
+        request.setUriQuery("rt=core.light");
+        request.setToken("1234".getBytes(StandardCharsets.UTF_8));
+
+        startServer();
+        ChannelHandlerContext ctx = startClient();
+
+        rdResource.handlePostRequest(ctx, makePublishPayload());
+
+        rdResource.handleGetRequest(ctx, request);
+
+        coapClient.stopClient();
+        coapServer.stopServer();
+    }
+
+    @Test
+    public void testHandleGetRequestBySt_existValue() throws Exception {
+
+        CoapRequest request = new CoapRequest(CoapMethod.GET);
+        request.setUriPath(Constants.RD_URI);
+        request.setUriQuery("rt=core.light&st=didList");
+        request.setToken("1234".getBytes(StandardCharsets.UTF_8));
+
+        HashMap<Object, Object> data = new HashMap<Object, Object>();
+        ArrayList<String> didList = new ArrayList<String>();
+        didList.add("98f7483c-5a31-4161-ba7e-9c13e0d");
+        data.put("devices", didList);
+        String payload = JSONUtil.writeJSON(data);
+        if (payload != null) {
+            request.setPayload(payload.getBytes(StandardCharsets.UTF_8));
+        }
+        else {
+                throw new IllegalArgumentException("payload writeJson error");
+        }
+
+        startServer();
+        ChannelHandlerContext ctx = startClient();
+
+        rdResource.handlePostRequest(ctx, makePublishPayload());
+
+        rdResource.handleGetRequest(ctx, request);
+
+        coapClient.stopClient();
+        coapServer.stopServer();
+    }
+
+    @Test
+    public void testHandleDeleteRequestByDi_notExistVaule() throws Exception {
+
+        CoapRequest request = new CoapRequest(CoapMethod.DELETE);
+        request.setUriPath(Constants.RD_URI);
+        request.setUriQuery("di=98f7483c-5a31-4161-ba7e-9c13e0d");
+        request.setToken("1234".getBytes(StandardCharsets.UTF_8));
+
+        startServer();
+        ChannelHandlerContext ctx = startClient();
+
+        rdResource.handlePostRequest(ctx, makePublishPayload());
+
+        rdResource.handleDeleteRequest(ctx, request);
+
+        coapClient.stopClient();
+        coapServer.stopServer();
+    }
+
+    @Test
+    public void testHandleDeleteRequestByDi_existVaule() throws Exception {
+
+        CoapRequest request = new CoapRequest(CoapMethod.DELETE);
+        request.setUriPath(Constants.RD_URI);
+        request.setUriQuery("di=98f7483c-5a31-4161-ba7e-9c13e0d");
+        request.setToken("1234".getBytes(StandardCharsets.UTF_8));
+
+        startServer();
+        ChannelHandlerContext ctx = startClient();
+
+        rdResource.handleDeleteRequest(ctx, request);
+
+        coapClient.stopClient();
+        coapServer.stopServer();
+    }
+
+    @Test
+    public void testHandleDeleteRequestByIns_notExistVaule() throws Exception {
+
+        CoapRequest request = new CoapRequest(CoapMethod.DELETE);
+        request.setUriPath(Constants.RD_URI);
+        request.setUriQuery("di=98f7483c-5a31-4161-ba7e-9c13e0d&ins=1");
+        request.setToken("1234".getBytes(StandardCharsets.UTF_8));
+
+        startServer();
+        ChannelHandlerContext ctx = startClient();
+
+        rdResource.handleDeleteRequest(ctx, request);
+
+        coapClient.stopClient();
+        coapServer.stopServer();
+    }
+
+    @Test
+    public void testHandleDeleteRequestByIns_existVaule() throws Exception {
+
+        CoapRequest request = new CoapRequest(CoapMethod.DELETE);
+        request.setUriPath(Constants.RD_URI);
+        request.setUriQuery("di=98f7483c-5a31-4161-ba7e-9c13e0d&ins=1");
+        request.setToken("1234".getBytes(StandardCharsets.UTF_8));
+
+        startServer();
+        ChannelHandlerContext ctx = startClient();
+
+        rdResource.handlePostRequest(ctx, makePublishPayload());
+
+        rdResource.handleDeleteRequest(ctx, request);
+
+        coapClient.stopClient();
+        coapServer.stopServer();
+    }
+}
diff --git a/cloud/samples/client/README b/cloud/samples/client/README
new file mode 100644 (file)
index 0000000..5f6dbbb
--- /dev/null
@@ -0,0 +1,25 @@
+To build cloud client sample, add WITH_TCP, TARGET_TRANSPORT=IP and WITH_CLOUD option to build command
+
+ex) scons WITH_TCP=yes TARGET_TRANSPORT=IP WITH_CLOUD=yes
+
+Cloud client runs using CoAP over TCP transport. So you should add WITH_TCP option.
+
+Once you get sample which file name is 'cloud_device', you need 'Auth Code' to register resources on cloud with account scenario.
+
+Cloud stack has sample github oauth2 adaptor.
+
+So you can instantly test sample using 'Auth Code'.
+
+Paste below URL to your browser
+
+https://github.com/login?return_to=%2Flogin%2Foauth%2Fauthorize%3Fclient_id%3Dea9c18f540323b0213d0%26redirect_uri%3Dhttp%253A%252F%252Fwww.example.com%252Foauth_callback%252F
+
+And you'll see login page provided by github, and after logged in, you'll be redirectd to below site.
+
+http://www.example.com/oauth_callback/?code=bf9beb5db17ea476fa46
+
+You can get 'Auth Code', value of '?code' query string.
+
+The 'Auth Code' is one time token. So you need other token to run other device.
+
+Account server has pre-coded admin credential which session is '00000000'. You can use this credential for immediate tests.
\ No newline at end of file
diff --git a/cloud/samples/client/SConscript b/cloud/samples/client/SConscript
new file mode 100644 (file)
index 0000000..7a4ae09
--- /dev/null
@@ -0,0 +1,55 @@
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+##
+# IoTivity Cloud project sample client build script
+##
+
+Import('env')
+
+lib_env = env.Clone()
+
+cc_sample_app_env = lib_env.Clone()
+
+######################################################################
+# Build flags
+######################################################################
+cc_sample_app_env.AppendUnique(CPPPATH = [
+               '../../../resource/include/',
+               '../../../resource/csdk/stack/include',
+               '../../../resource/c_common/ocrandom/include',
+               '../../../resource/csdk/logger/include',
+               '../../../resource/oc_logger/include'
+               ])
+
+cc_sample_app_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-Wextra', '-std=c++0x', '-pthread'])
+cc_sample_app_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+cc_sample_app_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
+cc_sample_app_env.PrependUnique(LIBS = ['octbstack', 'pthread'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+cc_sample_src = [
+        'cloud_connector.c',
+        'sample_device.cpp',
+         ]
+
+cc_client = cc_sample_app_env.Program('cloud_device', cc_sample_src)
\ No newline at end of file
diff --git a/cloud/samples/client/cloud_connector.c b/cloud/samples/client/cloud_connector.c
new file mode 100644 (file)
index 0000000..1312ff3
--- /dev/null
@@ -0,0 +1,292 @@
+//******************************************************************
+//
+// 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 "cloud_connector.h"
+
+#include <stdarg.h>
+#include <stdlib.h>
+
+#include "oic_string.h"
+#include "oic_malloc.h"
+
+#include "ocpayload.h"
+
+#include "rdpayload.h"
+
+#define OC_RD_PUBLISH_TTL 86400
+#define DEFAULT_CONTEXT_VALUE 0x99
+
+#define DEFAULT_COAP_TCP_HOST "coap+tcp://"
+#define DEFAULT_COAP_TCP_PORT 5683
+
+#define DEFAULT_COAP_TCP_SECURE_HOST "coaps+tcp://"
+#define DEFAULT_COAP_TCP_SECURE_PORT 5864
+
+#define DEFAULT_AUTH_REGISTER_LOGIN "/oic/auth/?reqtype=register"
+#define DEFAULT_AUTH_LOGIN "/oic/auth/?reqtype=login"
+#define DEFAULT_AUTH_LOGOUT "/oic/auth/?reqtype=logout"
+
+static OCStackResult createStringLL(uint8_t numElements, OCResourceHandle handle,
+                                    const char *(*getValue)(OCResourceHandle handle, uint8_t i), OCStringLL **stringLL)
+{
+    for (uint8_t i = 0; i < numElements; ++i)
+    {
+        const char *value = getValue(handle, i);
+        if (!*stringLL)
+        {
+            *stringLL = (OCStringLL *)OICCalloc(1, sizeof(OCStringLL));
+            if (!*stringLL)
+            {
+                return OC_STACK_NO_MEMORY;
+            }
+            (*stringLL)->value = OICStrdup(value);
+            if (!(*stringLL)->value)
+            {
+                return OC_STACK_NO_MEMORY;
+            }
+        }
+        else
+        {
+            OCStringLL *cur = *stringLL;
+            while (cur->next)
+            {
+                cur = cur->next;
+            }
+            cur->next = (OCStringLL *)OICCalloc(1, sizeof(OCStringLL));
+            if (!cur->next)
+            {
+                return OC_STACK_NO_MEMORY;
+            }
+            cur->next->value = OICStrdup(value);
+            if (!cur->next->value)
+            {
+                return OC_STACK_NO_MEMORY;
+            }
+        }
+    }
+    return OC_STACK_OK;
+}
+
+OCStackResult OCCloudRegisterLogin(const char *host, const char *auth_provider,
+                                   const char *auth_code, OCClientResponseHandler response)
+{
+    char    targetUri[MAX_URI_LENGTH * 2] = { 0, };
+    snprintf(targetUri, MAX_URI_LENGTH * 2, "%s%s", host, DEFAULT_AUTH_REGISTER_LOGIN);
+
+    OCCallbackData cbData;
+    memset(&cbData, 0, sizeof(OCCallbackData));
+    cbData.cb = response;
+    cbData.cd = NULL;
+    cbData.context = (void *)DEFAULT_CONTEXT_VALUE;
+
+    OCRepPayload *registerPayload = OCRepPayloadCreate();
+    if (!registerPayload)
+    {
+        goto no_memory;
+    }
+
+    OCRepPayloadSetPropString(registerPayload, "authprovider", auth_provider);
+    OCRepPayloadSetPropString(registerPayload, "authcode", auth_code);
+
+    return OCDoResource(NULL, OC_REST_POST, targetUri, NULL, (OCPayload *)registerPayload,
+                        CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+
+no_memory:
+    OCRepPayloadDestroy(registerPayload);
+    return OC_STACK_NO_MEMORY;
+}
+
+OCStackResult OCCloudLoginout(const char *host, const char *query, const char *auth_session,
+                              OCClientResponseHandler response)
+{
+    char    targetUri[MAX_URI_LENGTH * 2] = { 0, };
+    snprintf(targetUri, MAX_URI_LENGTH * 2, "%s%s", host, query);
+
+    OCCallbackData cbData;
+    memset(&cbData, 0, sizeof(OCCallbackData));
+    cbData.cb = response;
+    cbData.cd = NULL;
+    cbData.context = (void *)DEFAULT_CONTEXT_VALUE;
+
+    OCRepPayload *loginoutPayload = OCRepPayloadCreate();
+    if (!loginoutPayload)
+    {
+        goto no_memory;
+    }
+
+    OCRepPayloadSetPropString(loginoutPayload, "session", auth_session);
+
+    return OCDoResource(NULL, OC_REST_POST, targetUri, NULL, (OCPayload *)loginoutPayload,
+                        CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+
+no_memory:
+    OCRepPayloadDestroy(loginoutPayload);
+    return OC_STACK_NO_MEMORY;
+}
+
+
+OCStackResult OCCloudLogin(const char *host, const char *auth_session,
+                           OCClientResponseHandler response)
+{
+    return OCCloudLoginout(host, DEFAULT_AUTH_LOGIN, auth_session, response);
+}
+
+OCStackResult OCCloudLogout(const char *host, const char *auth_session,
+                            OCClientResponseHandler response)
+{
+    return OCCloudLoginout(host, DEFAULT_AUTH_LOGOUT, auth_session, response);
+}
+
+OCStackResult OCCloudPublish(const char *host, const char *query,
+                             OCClientResponseHandler response, int numArg, ...)
+{
+    char    targetUri[MAX_URI_LENGTH * 2] = { 0, };
+    snprintf(targetUri, MAX_URI_LENGTH * 2, "%s%s", host, query);
+
+    // Gather all resources locally and do publish
+    OCCallbackData cbData;
+    memset(&cbData, 0, sizeof(OCCallbackData));
+    cbData.cb = response;
+    cbData.cd = NULL;
+    cbData.context = (void *)DEFAULT_CONTEXT_VALUE;
+
+    OCTagsPayload *tagsPayload = NULL;
+    OCLinksPayload *linksPayload = NULL;
+    OCStringLL *rt = NULL;
+    OCStringLL *itf = NULL;
+    OCStringLL *mt = NULL;
+
+    OCRDPayload *rdPayload = OCRDPayloadCreate();
+    if (!rdPayload)
+    {
+        goto no_memory;
+    }
+
+    const unsigned char *id = (unsigned char *)OCGetServerInstanceIDString();
+    tagsPayload = OCCopyTagsResources(NULL, id,
+                                      NULL, OC_DISCOVERABLE, 0, 0, NULL, NULL, OC_RD_PUBLISH_TTL);
+    if (!tagsPayload)
+    {
+        goto no_memory;
+    }
+
+    va_list arguments;
+    va_start(arguments, numArg);
+
+    for (int j = 0; j < numArg; j++)
+    {
+        OCResourceHandle handle = va_arg(arguments, OCResourceHandle);
+        if (handle)
+        {
+            rt = itf = mt = NULL;
+            const char *uri = OCGetResourceUri(handle);
+            uint8_t numElement;
+            if (OC_STACK_OK == OCGetNumberOfResourceTypes(handle, &numElement))
+            {
+                OCStackResult res = createStringLL(numElement, handle, OCGetResourceTypeName, &rt);
+                if (res != OC_STACK_OK || !rt)
+                {
+                    goto no_memory;
+                }
+            }
+
+            if (OC_STACK_OK == OCGetNumberOfResourceInterfaces(handle, &numElement))
+            {
+                OCStackResult res = createStringLL(numElement, handle, OCGetResourceInterfaceName, &itf);
+                if (res != OC_STACK_OK || !itf)
+                {
+                    goto no_memory;
+                }
+            }
+
+            mt = (OCStringLL *)OICCalloc(1, sizeof(OCStringLL));
+            if (!mt)
+            {
+                goto no_memory;
+            }
+            mt->value = OICStrdup("application/cbor");
+            if (!mt->value)
+            {
+                goto no_memory;
+            }
+
+            if (!linksPayload)
+            {
+                linksPayload = OCCopyLinksResources(uri, rt, itf, NULL, 0, NULL,
+                                                    NULL, j, mt);;
+                if (!linksPayload)
+                {
+                    goto no_memory;
+                }
+            }
+            else
+            {
+                OCLinksPayload *temp = linksPayload;
+                while (temp->next)
+                {
+                    temp = temp->next;
+                }
+                temp->next = OCCopyLinksResources(uri, rt, itf, NULL, 0, NULL,
+                                                  NULL, j, mt);
+                if (!temp->next)
+                {
+                    goto no_memory;
+                }
+            }
+            OCFreeOCStringLL(rt);
+            OCFreeOCStringLL(itf);
+            OCFreeOCStringLL(mt);
+        }
+    }
+    va_end(arguments);
+
+    rdPayload->rdPublish = OCCopyCollectionResource(tagsPayload, linksPayload);
+    if (!rdPayload->rdPublish)
+    {
+        goto no_memory;
+    }
+
+    return OCDoResource(NULL, OC_REST_POST, targetUri, NULL, (OCPayload *)rdPayload,
+                        CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+
+no_memory:
+    va_end(arguments);
+    if (rt)
+    {
+        OCFreeOCStringLL(rt);
+    }
+    if (itf)
+    {
+        OCFreeOCStringLL(itf);
+    }
+    if (mt)
+    {
+        OCFreeOCStringLL(mt);
+    }
+    if (tagsPayload)
+    {
+        OCFreeTagsResource(tagsPayload);
+    }
+    if (linksPayload)
+    {
+        OCFreeLinksResource(linksPayload);
+    }
+    OCRDPayloadDestroy(rdPayload);
+    return OC_STACK_NO_MEMORY;
+}
diff --git a/cloud/samples/client/cloud_connector.h b/cloud/samples/client/cloud_connector.h
new file mode 100644 (file)
index 0000000..2f26a5b
--- /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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef _CLOUD_CONNECTOR_H_
+#define _CLOUD_CONNECTOR_H_
+
+#include "ocstack.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+OCStackResult OCCloudRegisterLogin(const char *host, const char *auth_provider,
+                                   const char *auth_code, OCClientResponseHandler response);
+OCStackResult OCCloudLogin(const char *host, const char *auth_session,
+                           OCClientResponseHandler response);
+OCStackResult OCCloudLogout(const char *host, const char *auth_session,
+                            OCClientResponseHandler response);
+OCStackResult OCCloudPublish(const char *host, const char *query,
+                             OCClientResponseHandler response, int numArg, ...);
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+#endif
diff --git a/cloud/samples/client/sample_device.cpp b/cloud/samples/client/sample_device.cpp
new file mode 100644 (file)
index 0000000..b7f60cb
--- /dev/null
@@ -0,0 +1,853 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+///
+/// This sample provides the way to create cloud sample
+///
+#include <memory>
+#include <iostream>
+#include <stdexcept>
+#include <condition_variable>
+#include <map>
+#include <vector>
+#include <string>
+#include <pthread.h>
+#include <unistd.h>
+
+#include "ocstack.h"
+#include "ocpayload.h"
+
+#include "cloud_connector.h"
+
+#define DEFAULT_CONTEXT_VALUE 0x99
+#define DEFAULT_PUBLISH_QUERY "/oic/rd?rt=oic.wk.rdpub"
+#define DEFAULT_DISCOVER_QUERY "/oic/res?rt=core.light"
+
+////////////////////////////////////////Device Sample
+#define SAMPLE_MAX_NUM_POST_INSTANCE  2
+typedef struct LIGHTRESOURCE
+{
+    OCResourceHandle handle;
+    bool state;
+    int power;
+} LightResource;
+static LightResource gLightInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
+
+
+OCRepPayload *responsePayload(int64_t power, bool state)
+{
+    OCRepPayload *payload = OCRepPayloadCreate();
+    if (!payload)
+    {
+        std::cout << "Failed to allocate Payload" << std::endl;
+        return nullptr;
+    }
+
+    OCRepPayloadSetPropBool(payload, "state", state);
+    OCRepPayloadSetPropInt(payload, "power", power);
+
+    return payload;
+}
+
+OCRepPayload *constructResponse(OCEntityHandlerRequest *ehRequest)
+{
+    if (ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
+    {
+        std::cout << "Incoming payload not a representation" << std::endl;
+        return nullptr;
+    }
+
+    LightResource *currLightResource = NULL;
+
+    if (ehRequest->resource == gLightInstance[0].handle)
+    {
+        currLightResource = &gLightInstance[0];
+    }
+    else if (ehRequest->resource == gLightInstance[1].handle)
+    {
+        currLightResource = &gLightInstance[1];
+    }
+
+    if (OC_REST_PUT == ehRequest->method)
+    {
+        // Get pointer to query
+        int64_t pow;
+        OCRepPayload *input = reinterpret_cast<OCRepPayload *>(ehRequest->payload);
+
+        if (OCRepPayloadGetPropInt(input, "power", &pow))
+        {
+            currLightResource->power = pow;
+        }
+
+        bool state;
+        if (OCRepPayloadGetPropBool(input, "state", &state))
+        {
+            currLightResource->state = state;
+        }
+    }
+
+    return responsePayload(currLightResource->power, currLightResource->state);
+}
+
+OCEntityHandlerResult ProcessGetRequest(OCEntityHandlerRequest *ehRequest,
+                                        OCRepPayload **payload)
+{
+    OCRepPayload *getResp = constructResponse(ehRequest);
+    if (!getResp)
+    {
+        std::cout << "constructResponse failed" << std::endl;
+        return OC_EH_ERROR;
+    }
+
+    *payload = getResp;
+
+    return OC_EH_OK;
+}
+
+OCEntityHandlerResult ProcessPutRequest(OCEntityHandlerRequest *ehRequest,
+                                        OCRepPayload **payload)
+{
+    OCEntityHandlerResult ehResult;
+    OCRepPayload *putResp = constructResponse(ehRequest);
+
+    if (!putResp)
+    {
+        std::cout << "Failed to construct Json response" << std::endl;
+        return OC_EH_ERROR;
+    }
+
+    *payload = putResp;
+    ehResult = OC_EH_OK;
+
+    return ehResult;
+}
+
+#define SAMPLE_MAX_NUM_OBSERVATIONS  2
+static bool observeThreadStarted = false;
+int gLightUnderObservation = 0;
+pthread_t threadId_observe;
+typedef struct
+{
+    OCObservationId observationId;
+    bool valid;
+    OCResourceHandle resourceHandle;
+} Observers;
+Observers interestedObservers[SAMPLE_MAX_NUM_OBSERVATIONS];
+
+void *ChangeLightRepresentation(void *param)
+{
+    (void)param;
+    OCStackResult result = OC_STACK_ERROR;
+
+    while (true)
+    {
+        sleep(3);
+        gLightInstance[0].power += 1;
+        gLightInstance[1].power += 3;
+
+        if (gLightUnderObservation)
+        {
+            std::cout << " =====> Notifying stack of new power level " << gLightInstance[0].power << std::endl;
+            std::cout << " =====> Notifying stack of new power level " << gLightInstance[1].power << std::endl;
+            // Notifying all observers
+            result = OCNotifyAllObservers(gLightInstance[0].handle, OC_NA_QOS);
+            result = OCNotifyAllObservers(gLightInstance[1].handle, OC_NA_QOS);
+
+            std::cout << " =====> Notifying result " << result << std::endl;
+        }
+    }
+    return NULL;
+}
+
+void ProcessObserveRegister(OCEntityHandlerRequest *ehRequest)
+{
+    std::cout << "Received observation registration request with observation Id " <<
+              ehRequest->obsInfo.obsId << std::endl;
+
+    if (!observeThreadStarted)
+    {
+        pthread_create(&threadId_observe, NULL, ChangeLightRepresentation, (void *)NULL);
+        observeThreadStarted = 1;
+    }
+    for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
+    {
+        if (interestedObservers[i].valid == false)
+        {
+            interestedObservers[i].observationId = ehRequest->obsInfo.obsId;
+            interestedObservers[i].valid = true;
+            gLightUnderObservation = 1;
+            break;
+        }
+    }
+}
+
+void ProcessObserveDeregister(OCEntityHandlerRequest *ehRequest)
+{
+    bool clientStillObserving = false;
+
+    std::cout << "Received observation deregistration request for observation Id " <<
+              ehRequest->obsInfo.obsId << std::endl;
+    for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
+    {
+        if (interestedObservers[i].observationId == ehRequest->obsInfo.obsId)
+        {
+            interestedObservers[i].valid = false;
+        }
+        if (interestedObservers[i].valid == true)
+        {
+            // Even if there is one single client observing we continue notifying entity handler
+            clientStillObserving = true;
+        }
+    }
+    if (clientStillObserving == false)
+        gLightUnderObservation = 0;
+}
+
+OCEntityHandlerResult
+OCEntityHandlerCb(OCEntityHandlerFlag flag,
+                  OCEntityHandlerRequest *entityHandlerRequest, void * /*callback*/)
+{
+    OCEntityHandlerResult ehResult = OC_EH_OK;
+    OCEntityHandlerResponse response = { 0, 0, OC_EH_ERROR, 0, 0, {}, { 0 }, false };
+
+    // Validate pointer
+    if (!entityHandlerRequest)
+    {
+        std::cout << "Invalid request pointer" << std::endl;
+        return OC_EH_ERROR;
+    }
+
+    // Initialize certain response fields
+    response.numSendVendorSpecificHeaderOptions = 0;
+    memset(response.sendVendorSpecificHeaderOptions,
+           0, sizeof response.sendVendorSpecificHeaderOptions);
+    memset(response.resourceUri, 0, sizeof response.resourceUri);
+    OCRepPayload *payload = nullptr;
+
+    if (flag & OC_REQUEST_FLAG)
+    {
+        std::cout << "Flag includes OC_REQUEST_FLAG" << std::endl;
+
+        if (OC_REST_GET == entityHandlerRequest->method)
+        {
+            std::cout << "Received OC_REST_GET from client" << std::endl;
+            ehResult = ProcessGetRequest(entityHandlerRequest, &payload);
+        }
+        else if (OC_REST_PUT == entityHandlerRequest->method)
+        {
+            std::cout << "Received OC_REST_PUT from client" << std::endl;
+            ehResult = ProcessPutRequest(entityHandlerRequest, &payload);
+        }
+        else
+        {
+            std::cout << "Received unsupported method %d from client " << entityHandlerRequest->method <<
+                      std::endl;
+            ehResult = OC_EH_ERROR;
+        }
+        // If the result isn't an error or forbidden, send response
+        if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN)))
+        {
+            // Format the response.  Note this requires some info about the request
+            response.requestHandle = entityHandlerRequest->requestHandle;
+            response.resourceHandle = entityHandlerRequest->resource;
+            response.ehResult = ehResult;
+            response.payload = reinterpret_cast<OCPayload *>(payload);
+            // Indicate that response is NOT in a persistent buffer
+            response.persistentBufferFlag = 0;
+
+            // Send the response
+            if (OCDoResponse(&response) != OC_STACK_OK)
+            {
+                std::cout << "Error sending response" << std::endl;
+                ehResult = OC_EH_ERROR;
+            }
+        }
+    }
+
+    if (flag & OC_OBSERVE_FLAG)
+    {
+        std::cout << "Flag includes OC_OBSERVE_FLAG" << std::endl;
+        if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
+        {
+            std::cout << "Received OC_OBSERVE_REGISTER from client" << std::endl;
+            ProcessObserveRegister(entityHandlerRequest);
+        }
+        else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
+        {
+            std::cout << "Received OC_OBSERVE_DEREGISTER from client" << std::endl;
+            ProcessObserveDeregister(entityHandlerRequest);
+        }
+    }
+
+    OCPayloadDestroy(response.payload);
+    return ehResult;
+}
+
+int createLightResource(char *uri, LightResource *lightResource)
+{
+    if (!uri)
+    {
+        std::cout << "Resource URI cannot be NULL" << std::endl;
+        return -1;
+    }
+
+    lightResource->state = false;
+    lightResource->power = 0;
+    OCStackResult res = OCCreateResource(&(lightResource->handle),
+                                         "core.light",
+                                         "oc.mi.def",
+                                         uri,
+                                         OCEntityHandlerCb,
+                                         NULL,
+                                         OC_DISCOVERABLE | OC_OBSERVABLE);
+    std::cout << "Created Light resource with result:" << res << std::endl;
+
+    return res;
+}
+
+OCStackApplicationResult handlePublishCB(void *ctx,
+        OCDoHandle /*handle*/,
+        OCClientResponse *clientResponse)
+{
+    if (ctx != (void *)DEFAULT_CONTEXT_VALUE)
+    {
+        std::cout << "Invalid Publish callback received" << std::endl;
+    }
+
+    std::cout << "Publish resource response received, code: " << clientResponse->result << std::endl;
+
+    return OC_STACK_KEEP_TRANSACTION;
+}
+
+void PublishResources(std::string host, std::string additionalQuery)
+{
+    std::cout << "Running as Server mode" << std::endl;
+
+    std::string requestQuery = DEFAULT_PUBLISH_QUERY;
+    requestQuery += additionalQuery;
+
+    std::cout << "Publishing resources..." << std::endl;
+    std::cout << host.c_str() << requestQuery.c_str() << std::endl;
+
+    if (createLightResource((char *)"/a/light/0", &gLightInstance[0]) != 0)
+    {
+        std::cout << "Unable to create sample resource" << std::endl;
+    }
+
+    if (createLightResource((char *)"/a/light/1", &gLightInstance[1]) != 0)
+    {
+        std::cout << "Unable to create sample resource" << std::endl;
+    }
+
+    if (OCCloudPublish(host.c_str(), requestQuery.c_str(), &handlePublishCB, 2,
+                       gLightInstance[0].handle, gLightInstance[1].handle) != OC_STACK_OK)
+    {
+        std::cout << "Unable to publish resources to cloud" << std::endl;
+    }
+}
+
+////////////////////////////////////////Client Sample
+std::string g_host = "coap+tcp://";
+
+void PrintRepresentation(OCRepPayloadValue *val)
+{
+    while (val)
+    {
+        std::cout << "Key: " << val->name << " Value: ";
+        switch (val->type)
+        {
+            case OCREP_PROP_NULL:
+                std::cout << "NULL" << std::endl;
+                break;
+
+            case OCREP_PROP_INT:
+                std::cout << val->i << std::endl;
+                break;
+
+            case OCREP_PROP_DOUBLE:
+                std::cout << val->d << std::endl;
+                break;
+
+            case OCREP_PROP_BOOL:
+                std::cout << val->b << std::endl;
+                break;
+
+            case OCREP_PROP_STRING:
+                std::cout << val->str << std::endl;
+                break;
+
+            case OCREP_PROP_BYTE_STRING:
+                std::cout << "[ByteString]" << std::endl;
+                break;
+
+            case OCREP_PROP_OBJECT:
+                std::cout << "[Object]" << std::endl;
+                break;
+
+            case OCREP_PROP_ARRAY:
+                std::cout << "[Array]" << std::endl;
+                break;
+        }
+
+        val = val->next;
+    }
+}
+
+
+int gNumObserveNotifies = 0;
+
+OCStackApplicationResult obsReqCB(void *ctx, OCDoHandle handle,
+                                  OCClientResponse *clientResponse)
+{
+    std::cout << "Observe response received from " << clientResponse->resourceUri << std::endl;
+
+    if (ctx != (void *)DEFAULT_CONTEXT_VALUE)
+    {
+        std::cout << "Invalid Put callback received" << std::endl;
+    }
+
+    if (clientResponse)
+    {
+        if (clientResponse->payload == NULL)
+        {
+            std::cout << "No payload received" << std::endl;
+        }
+
+        OCRepPayloadValue *val = ((OCRepPayload *)clientResponse->payload)->values;
+
+        PrintRepresentation(val);
+
+        gNumObserveNotifies++;
+        if (gNumObserveNotifies > 5) //large number to test observing in DELETE case.
+        {
+            std::cout << "Cancelling with OC_HIGH_QOS" << std::endl;
+            if (OCCancel(handle, OC_HIGH_QOS, NULL, 0) != OC_STACK_OK)
+            {
+                std::cout << "Observe cancel error" << std::endl;
+            }
+        }
+        if (clientResponse->sequenceNumber == OC_OBSERVE_REGISTER)
+        {
+            std::cout << "This also serves as a registration confirmation" << std::endl;
+        }
+        else if (clientResponse->sequenceNumber == OC_OBSERVE_DEREGISTER)
+        {
+            std::cout << "This also serves as a deregistration confirmation" << std::endl;
+            return OC_STACK_DELETE_TRANSACTION;
+        }
+        else if (clientResponse->sequenceNumber == OC_OBSERVE_NO_OPTION)
+        {
+            std::cout << "This also tells you that registration/deregistration failed" << std::endl;
+            return OC_STACK_DELETE_TRANSACTION;
+        }
+    }
+    else
+    {
+        std::cout << "obsReqCB received Null clientResponse" << std::endl;
+    }
+
+    return OC_STACK_KEEP_TRANSACTION;
+}
+
+void ObserveResource(std::string uri, std::string additionalQuery)
+{
+    OCCallbackData cbData;
+    cbData.cb = obsReqCB;
+    cbData.context = (void *)DEFAULT_CONTEXT_VALUE;
+    cbData.cd = NULL;
+
+    uri += additionalQuery;
+
+    std::cout << "Request OBSERVE to resource " << uri.c_str() << std::endl;
+
+    OCStackResult res = OCDoResource(NULL, OC_REST_OBSERVE, uri.c_str(), NULL, NULL,
+                                     CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+
+    std::cout << "Requesting OBSERVE res=" << res << std::endl;
+}
+
+OCStackApplicationResult putReqCB(void *ctx, OCDoHandle /*handle*/,
+                                  OCClientResponse *clientResponse)
+{
+    std::cout << "Put response received from " << clientResponse->resourceUri << std::endl;
+
+    if (ctx != (void *)DEFAULT_CONTEXT_VALUE)
+    {
+        std::cout << "Invalid Put callback received" << std::endl;
+    }
+
+    if (clientResponse->payload == NULL)
+    {
+        std::cout << "No payload received" << std::endl;
+    }
+
+    OCRepPayloadValue *val = ((OCRepPayload *)clientResponse->payload)->values;
+
+    PrintRepresentation(val);
+
+    std::string requestUri = g_host;
+    requestUri += clientResponse->resourceUri;
+
+    ObserveResource(requestUri, "");
+
+    return OC_STACK_KEEP_TRANSACTION;
+}
+
+OCPayload *putRequestPayload()
+{
+    OCRepPayload *payload = OCRepPayloadCreate();
+
+    if (!payload)
+    {
+        std::cout << "Failed to create put payload object" << std::endl;
+        std::exit(1);
+    }
+
+    OCRepPayloadSetPropInt(payload, "power", 15);
+    OCRepPayloadSetPropBool(payload, "state", true);
+
+    return (OCPayload *)payload;
+}
+
+void PutResource(std::string uri, std::string additionalQuery)
+{
+    OCCallbackData cbData;
+    cbData.cb = putReqCB;
+    cbData.context = (void *)DEFAULT_CONTEXT_VALUE;
+    cbData.cd = NULL;
+
+    uri += additionalQuery;
+
+    std::cout << "Request PUT to resource " << uri.c_str() << std::endl;
+
+    OCStackResult res = OCDoResource(NULL, OC_REST_PUT, uri.c_str(), NULL, putRequestPayload(),
+                                     CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+
+    std::cout << "Requesting PUT res=" << res << std::endl;
+}
+
+OCStackApplicationResult handleGetCB(void *ctx,
+                                     OCDoHandle /*handle*/,
+                                     OCClientResponse *clientResponse)
+{
+    std::cout << "Get response received from " << clientResponse->resourceUri << std::endl;
+
+    if (ctx != (void *)DEFAULT_CONTEXT_VALUE)
+    {
+        std::cout << "Invalid Get callback received" << std::endl;
+    }
+
+    if (clientResponse->payload == NULL)
+    {
+        std::cout << "No payload received" << std::endl;
+    }
+
+    if (clientResponse->payload != NULL &&
+        clientResponse->payload->type == PAYLOAD_TYPE_REPRESENTATION)
+    {
+        OCRepPayloadValue *val = ((OCRepPayload *)clientResponse->payload)->values;
+
+        PrintRepresentation(val);
+
+        std::string requestUri = g_host;
+        requestUri += clientResponse->resourceUri;
+
+        PutResource(requestUri, "");
+    }
+
+    return OC_STACK_KEEP_TRANSACTION;
+}
+
+void GetResource(std::string uri, std::string additionalQuery)
+{
+    OCCallbackData cbData;
+    cbData.cb = handleGetCB;
+    cbData.context = (void *)DEFAULT_CONTEXT_VALUE;
+    cbData.cd = NULL;
+
+    uri += additionalQuery;
+
+    std::cout << "Request GET to resource " << uri.c_str() << std::endl;
+
+    OCStackResult res = OCDoResource(NULL, OC_REST_GET, uri.c_str(), NULL, NULL,
+                                     CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+
+    std::cout << "Requesting GET res=" << res << std::endl;
+}
+
+// This is a function called back when a device is discovered
+OCStackApplicationResult discoveryReqCB(void *ctx, OCDoHandle /*handle*/,
+                                        OCClientResponse *clientResponse)
+{
+    if (ctx == (void *)DEFAULT_CONTEXT_VALUE)
+    {
+        std::cout << "Callback Context for DISCOVER query recvd successfully" << std::endl;
+    }
+
+    if (clientResponse)
+    {
+        std::cout << "StackResult: " << clientResponse->result << std::endl;
+
+        OCDiscoveryPayload *payload = (OCDiscoveryPayload *)clientResponse->payload;
+        if (!payload)
+        {
+            std::cout << "Empty payload" << std::endl;
+            return OC_STACK_DELETE_TRANSACTION;
+        }
+
+        OCResourcePayload *resource = (OCResourcePayload *)payload->resources;
+        if (!resource)
+        {
+            std::cout << "No resources in payload" << std::endl;
+            return OC_STACK_DELETE_TRANSACTION;
+        }
+
+        while (resource)
+        {
+            std::cout << "Found Resource " << resource->uri << std::endl;
+
+            std::string requestUri = g_host;
+            requestUri += resource->uri;
+
+            GetResource(requestUri, "");
+
+            resource = resource->next;
+        }
+    }
+    else
+    {
+        std::cout << "discoveryReqCB received Null clientResponse" << std::endl;
+    }
+    return OC_STACK_KEEP_TRANSACTION;
+}
+
+void DiscoverResources(std::string host, std::string additionalQuery)
+{
+    std::cout << "Running as Client mode" << std::endl;
+
+    std::string requestQuery = host;
+    requestQuery += DEFAULT_DISCOVER_QUERY;
+    requestQuery += additionalQuery;
+
+    std::cout << "Finding resources..." << std::endl;
+    std::cout << requestQuery.c_str() << std::endl;
+
+    OCCallbackData cbData;
+
+    cbData.cb = discoveryReqCB;
+    cbData.context = (void *)DEFAULT_CONTEXT_VALUE;
+    cbData.cd = NULL;
+
+    if (OCDoResource(NULL, OC_REST_DISCOVER, requestQuery.c_str(), NULL, 0, CT_ADAPTER_TCP,
+                     OC_LOW_QOS, &cbData, NULL, 0) != OC_STACK_OK)
+    {
+        std::cout << "Unable to find resources from cloud" << std::endl;
+    }
+}
+
+
+
+/////////////////////////////////////////////Common sample
+
+int g_runningMode = 0;
+
+OCStackApplicationResult handleLoginoutCB(void *ctx,
+        OCDoHandle /*handle*/,
+        OCClientResponse *clientResponse)
+{
+    if (ctx != (void *)DEFAULT_CONTEXT_VALUE)
+    {
+        std::cout << "Invalid Login/out callback received" << std::endl;
+    }
+
+    std::cout << "Login/out response received code: " << clientResponse->result << std::endl;
+
+    if (clientResponse->payload != NULL &&
+        clientResponse->payload->type == PAYLOAD_TYPE_REPRESENTATION)
+    {
+        std::cout << "PAYLOAD_TYPE_REPRESENTATION received" << std::endl;
+
+        OCRepPayloadValue *val = ((OCRepPayload *)clientResponse->payload)->values;
+
+        while (val)
+        {
+            std::cout << "Key: " << val->name << " Value: " << val->str << std::endl;
+            val = val->next;
+        }
+
+        if (g_runningMode == 1)
+        {
+            PublishResources(g_host, "");
+        }
+        else if (g_runningMode == 2)
+        {
+            DiscoverResources(g_host, "");
+        }
+
+    }
+
+    return OC_STACK_KEEP_TRANSACTION;
+}
+
+OCStackApplicationResult handleRegisterCB(void *ctx,
+        OCDoHandle /*handle*/,
+        OCClientResponse *clientResponse)
+{
+    if (ctx != (void *)DEFAULT_CONTEXT_VALUE)
+    {
+        std::cout << "Invalid Register callback received" << std::endl;
+    }
+
+    std::cout << "Register response received code: " << clientResponse->result << std::endl;
+
+    if (clientResponse->payload != NULL &&
+        clientResponse->payload->type == PAYLOAD_TYPE_REPRESENTATION)
+    {
+        std::cout << "PAYLOAD_TYPE_REPRESENTATION received" << std::endl;
+        std::cout << "You can login using received session variable after disconnected or reboot" <<
+                  std::endl;
+
+        OCRepPayloadValue *val = ((OCRepPayload *)clientResponse->payload)->values;
+
+        while (val)
+        {
+            std::cout << "Key: " << val->name << " Value: " << val->str << std::endl;
+            val = val->next;
+        }
+    }
+
+    return OC_STACK_KEEP_TRANSACTION;
+}
+
+void PrintUsage()
+{
+    std::cout << std::endl;
+    std::cout << "Usage : cloud_device <addr:port> <session> <mode>\n";
+    std::cout << "<addr:port>: Cloud Address, \"127.0.0.1:5683\"\n";
+    std::cout <<
+              "<session>: String value, Provided by response of onboarding scenario\n\tor kind of registration portal\n\n";
+    std::cout <<
+              "<mode>: String value, 's' for publish resource, 'c' for start discovery\n\n";
+    std::cout <<
+              "If you want to get session key using OAuth 2 auth code,\n\tleave blank to <session>, <mode> fields\n";
+    std::cout <<
+              "sample: \"cloud_device 127.0.0.1:5683\"\n\t-OAuth 2 registration mode\n\n";
+    std::cout <<
+              "sample: \"cloud_device 127.0.0.1:5683 1234567890123456 s\"\n\t-Publish resource under registered session\n\n";
+    std::cout <<
+              "sample: \"cloud_device 127.0.0.1:5683 1234567890123456 c\"\n\t-Discover resource under registered session\n\n";
+}
+
+int main(int argc, char *argv[])
+{
+    std::string session;
+
+    std::string authProvider;
+    std::string authCode;
+
+    OCMode      stackMode = OC_CLIENT;
+
+    switch (argc)
+    {
+        case 2:
+            std::cout << "Put auth provider name(ex: github)" << std::endl;
+            std::cin >> authProvider;
+            std::cout << "Put auth code(provided by auth provider)" << std::endl;
+            std::cin >> authCode;
+            break;
+
+        case 4:
+            session = argv[2];
+            if (strlen(argv[3]) != 1)
+            {
+                std::cout << "OCStack init error" << std::endl;
+                return 0;
+            }
+            if (strcmp(argv[3], "s") == 0)
+            {
+                stackMode = OC_CLIENT_SERVER;
+                g_runningMode = 1;
+            }
+            else if (strcmp(argv[3], "c") == 0)
+            {
+                g_runningMode = 2;
+            }
+            else
+            {
+                std::cout << "Invalid <mode>, 's' or 'c' required" << std::endl;
+                return 0;
+            }
+            break;
+
+        default:
+            PrintUsage();
+            return 0;
+    }
+
+    g_host += argv[1];
+
+    std::cout << "Host " << g_host.c_str() << std::endl;
+
+    if (OCInit(NULL, 0, stackMode) != OC_STACK_OK)
+    {
+        std::cout << "OCStack init error" << std::endl;
+        return 0;
+    }
+
+    OCStackResult   res = OC_STACK_ERROR;
+
+    switch (argc)
+    {
+        case 2:
+            std::cout << "Register account to cloud using " << authProvider << " " << authCode << std::endl;
+            res = OCCloudRegisterLogin(g_host.c_str(), authProvider.c_str(), authCode.c_str(),
+                                       handleRegisterCB);
+            std::cout << "OCCloudRegisterLogin return " << res << std::endl;
+            break;
+
+        case 4:
+            res = OCCloudLogin(g_host.c_str(), session.c_str(), handleLoginoutCB);
+            std::cout << "OCCloudLogin return " << res << std::endl;
+            break;
+
+        default:
+            PrintUsage();
+            return 0;
+    }
+
+    std::cout << "Waiting response.." << std::endl;
+
+    while (true)
+    {
+        if (OCProcess() != OC_STACK_OK)
+        {
+            std::cout << "OCProcess process error" << std::endl;
+        }
+
+        sleep(1);
+    }
+
+    if (OCStop() != OC_STACK_OK)
+    {
+        std::cout << "OCStop process error" << std::endl;
+    }
+
+    return 0;
+}
\ No newline at end of file
diff --git a/cloud/stack/.classpath b/cloud/stack/.classpath
new file mode 100644 (file)
index 0000000..366f061
--- /dev/null
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+       <classpathentry kind="src" output="target/classes" path="src/main/java">
+               <attributes>
+                       <attribute name="optional" value="true"/>
+                       <attribute name="maven.pomderived" value="true"/>
+               </attributes>
+       </classpathentry>
+       <classpathentry kind="src" path="src/test/java"/>
+       <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
+               <attributes>
+                       <attribute name="maven.pomderived" value="true"/>
+               </attributes>
+       </classpathentry>
+       <classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
+               <attributes>
+                       <attribute name="maven.pomderived" value="true"/>
+               </attributes>
+       </classpathentry>
+       <classpathentry kind="output" path="target/classes"/>
+</classpath>
diff --git a/cloud/stack/.gitignore b/cloud/stack/.gitignore
new file mode 100644 (file)
index 0000000..b83d222
--- /dev/null
@@ -0,0 +1 @@
+/target/
diff --git a/cloud/stack/.project b/cloud/stack/.project
new file mode 100644 (file)
index 0000000..c3fbeb0
--- /dev/null
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+       <name>CloudStack</name>
+       <comment></comment>
+       <projects>
+       </projects>
+       <buildSpec>
+               <buildCommand>
+                       <name>org.eclipse.jdt.core.javabuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+               <buildCommand>
+                       <name>org.eclipse.m2e.core.maven2Builder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+       </buildSpec>
+       <natures>
+               <nature>org.eclipse.jdt.core.javanature</nature>
+               <nature>org.eclipse.m2e.core.maven2Nature</nature>
+       </natures>
+</projectDescription>
diff --git a/cloud/stack/README b/cloud/stack/README
new file mode 100644 (file)
index 0000000..b8b2710
--- /dev/null
@@ -0,0 +1,13 @@
+This project contains the common stack for all server instances.
+
+Build
+
+1) Install Apache Maven if you don't have it
+
+       http://maven.apache.org
+
+2) Build a .jar file
+
+       $ mvn install -Dmaven.test.skip=true
+
+       - The CloudStack-0.0.1-SNAPSHOT.jar file will be placed in the "target" folder.
diff --git a/cloud/stack/pom.xml b/cloud/stack/pom.xml
new file mode 100644 (file)
index 0000000..f04a936
--- /dev/null
@@ -0,0 +1,69 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.iotivity.cloud</groupId>
+  <artifactId>CloudStack</artifactId>
+  <version>0.0.1-SNAPSHOT</version>
+  
+  <properties>
+               <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+       </properties>
+       
+  <dependencies>
+               <dependency>
+                       <groupId>org.apache.maven.plugins</groupId>
+                       <artifactId>maven-resources-plugin</artifactId>
+                       <version>2.4.3</version>
+               </dependency>
+               <dependency>
+                       <groupId>org.apache.maven.plugins</groupId>
+                       <artifactId>maven-compiler-plugin</artifactId>
+                       <version>3.1</version>
+               </dependency>
+               <dependency>
+                       <groupId>io.netty</groupId>
+                       <artifactId>netty-all</artifactId>
+                       <version>4.0.29.Final</version>
+               </dependency>
+               <dependency>
+                       <groupId>commons-codec</groupId>
+                       <artifactId>commons-codec</artifactId>
+                       <version>1.9</version>
+               </dependency>
+               <dependency>
+                       <groupId>org.json</groupId>
+                       <artifactId>json</artifactId>
+                       <version>20140107</version>
+               </dependency>
+               <dependency>
+                       <groupId>junit</groupId>
+                       <artifactId>junit</artifactId>
+                       <version>4.12</version>
+               </dependency>
+               <dependency>
+               <groupId>com.fasterxml.jackson.core</groupId>
+               <artifactId>jackson-databind</artifactId>
+               <version>2.4.0</version>
+               </dependency>
+               <dependency>
+                       <groupId>com.fasterxml.jackson.dataformat</groupId>
+                       <artifactId>jackson-dataformat-cbor</artifactId>
+                       <version>2.4.0</version>
+               </dependency>
+       </dependencies>
+       
+  <build>
+               <plugins>
+                       <plugin>
+                               <inherited>true</inherited>
+                               <groupId>org.apache.maven.plugins</groupId>
+                               <artifactId>maven-compiler-plugin</artifactId>
+                               <configuration>
+                                       <source>1.7</source>
+                                       <target>1.7</target>
+                                       <encoding>UTF-8</encoding>
+                               </configuration>
+                       </plugin>
+               </plugins>
+       </build>
+  
+</project>
\ No newline at end of file
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/CoapClient.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/CoapClient.java
new file mode 100644 (file)
index 0000000..d038565
--- /dev/null
@@ -0,0 +1,123 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.base;
+
+import java.net.InetSocketAddress;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.iotivity.cloud.base.protocols.coap.CoapDecoder;
+import org.iotivity.cloud.base.protocols.coap.CoapEncoder;
+import org.iotivity.cloud.base.protocols.coap.CoapRequest;
+import org.iotivity.cloud.util.Logger;
+
+import io.netty.bootstrap.Bootstrap;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelHandler;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelOption;
+import io.netty.channel.ChannelPipeline;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.channel.socket.nio.NioSocketChannel;
+import io.netty.util.concurrent.GenericFutureListener;
+
+public class CoapClient {
+
+    private static class CoAPClientInitializer
+            extends ChannelInitializer<SocketChannel> {
+
+        private List<ChannelHandler> additionalHandlers = new ArrayList<ChannelHandler>();
+
+        public CoAPClientInitializer() {
+        }
+
+        public void addHandler(ChannelHandler handler) {
+            additionalHandlers.add(handler);
+        }
+
+        @Override
+        public void initChannel(SocketChannel ch) {
+            ChannelPipeline p = ch.pipeline();
+            /*
+             * if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc())); }
+             */
+            p.addLast(new CoapDecoder());
+            p.addLast(new CoapEncoder());
+            for (ChannelHandler handler : additionalHandlers) {
+                p.addLast(handler);
+            }
+        }
+    }
+
+    ChannelFuture channelFuture;
+
+    EventLoopGroup connectorGroup = new NioEventLoopGroup();
+
+    CoAPClientInitializer initializer = new CoAPClientInitializer();
+
+    public void addHandler(ChannelHandler handler) {
+        initializer.addHandler(handler);
+    }
+
+    public void startClient(final InetSocketAddress inetSocketAddress)
+            throws InterruptedException {
+                
+        try {
+            Bootstrap b = new Bootstrap();
+            b.group(connectorGroup);
+            b.channel(NioSocketChannel.class);
+            b.option(ChannelOption.TCP_NODELAY, true);
+            b.option(ChannelOption.SO_KEEPALIVE, true);
+            b.option(ChannelOption.SO_REUSEADDR, true);
+
+            b.handler(initializer);
+
+            channelFuture = b.connect(inetSocketAddress).sync();
+
+            channelFuture
+                    .addListener(new GenericFutureListener<ChannelFuture>() {
+                        @Override
+                        public void operationComplete(ChannelFuture future)
+                                throws Exception {
+                            Logger.d(
+                                    "Connection status of TCP CoAP CLIENT  : "
+                                            + future.isSuccess());
+                        }
+                    });
+        } finally {
+        }
+    }
+
+    public ChannelFuture getChannelFuture() {
+        return channelFuture;
+    }
+
+    public void sendRequest(CoapRequest request) {
+        channelFuture.channel().writeAndFlush(request);
+    }
+
+    public void stopClient() throws Exception {
+        connectorGroup.shutdownGracefully().await();
+    }
+}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/CoapServer.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/CoapServer.java
new file mode 100644 (file)
index 0000000..9274f1e
--- /dev/null
@@ -0,0 +1,119 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.base;
+
+import java.net.InetSocketAddress;
+import java.security.cert.CertificateException;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.net.ssl.SSLException;
+
+import org.iotivity.cloud.base.protocols.coap.CoapDecoder;
+import org.iotivity.cloud.base.protocols.coap.CoapEncoder;
+import org.iotivity.cloud.util.Logger;
+
+import io.netty.bootstrap.ServerBootstrap;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelHandler;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelOption;
+import io.netty.channel.ChannelPipeline;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.channel.socket.nio.NioServerSocketChannel;
+import io.netty.handler.logging.LogLevel;
+import io.netty.handler.logging.LoggingHandler;
+import io.netty.util.concurrent.GenericFutureListener;
+
+public class CoapServer {
+
+    private static class CoAPServerInitializer
+            extends ChannelInitializer<SocketChannel> {
+
+        private List<ChannelHandler> additionalHandlers = new ArrayList<ChannelHandler>();
+
+        public CoAPServerInitializer() {
+        }
+
+        public void addHandler(ChannelHandler handler) {
+            additionalHandlers.add(handler);
+        }
+
+        @Override
+        public void initChannel(SocketChannel ch) {
+            ChannelPipeline p = ch.pipeline();
+            /*
+             * if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc())); }
+             */
+            p.addLast(new CoapDecoder());
+            p.addLast(new CoapEncoder());
+            for (ChannelHandler handler : additionalHandlers) {
+                p.addLast(handler);
+            }
+        }
+    }
+
+    EventLoopGroup acceptorGroup = new NioEventLoopGroup(1);
+
+    EventLoopGroup workerGroup = new NioEventLoopGroup();
+
+    CoAPServerInitializer initializer = new CoAPServerInitializer();
+    
+    public void addHandler(ChannelHandler handler) {
+        initializer.addHandler(handler);
+    }
+
+    public void startServer(InetSocketAddress inetSocketAddress)
+            throws CertificateException, SSLException, InterruptedException {
+
+        try {
+            ServerBootstrap b = new ServerBootstrap();
+            b.group(acceptorGroup, workerGroup);
+            b.channel(NioServerSocketChannel.class);
+            b.option(ChannelOption.TCP_NODELAY, true);
+            b.option(ChannelOption.SO_KEEPALIVE, true);
+            b.handler(new LoggingHandler(LogLevel.INFO));
+
+            b.childHandler(initializer);
+
+            ChannelFuture channelFuture = b.bind(inetSocketAddress).sync();
+
+            channelFuture.addListener(new GenericFutureListener<ChannelFuture>() {
+                @Override
+                public void operationComplete(ChannelFuture future)
+                        throws Exception {
+                    // TODO Auto-generated method stub
+                    Logger.d("Connection status of TCP CoAP SERVER  : "
+                                    + future.isSuccess());
+                }
+            });
+        } finally {
+        }
+    }
+
+    public void stopServer() throws Exception {
+       acceptorGroup.shutdownGracefully().await();
+       workerGroup.shutdownGracefully().await();
+    }
+}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/HttpClient.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/HttpClient.java
new file mode 100644 (file)
index 0000000..add75a4
--- /dev/null
@@ -0,0 +1,200 @@
+/*
+ * //****************************************************************** // //
+ * 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.cloud.base;
+//
+// import java.net.URI;
+// import java.net.URISyntaxException;
+//
+// import javax.net.ssl.SSLException;
+//
+// import io.netty.bootstrap.Bootstrap;
+// import io.netty.channel.Channel;
+// import io.netty.channel.ChannelHandlerContext;
+// import io.netty.channel.ChannelInitializer;
+// import io.netty.channel.ChannelPipeline;
+// import io.netty.channel.EventLoopGroup;
+// import io.netty.channel.SimpleChannelInboundHandler;
+// import io.netty.channel.nio.NioEventLoopGroup;
+// import io.netty.channel.socket.SocketChannel;
+// import io.netty.channel.socket.nio.NioSocketChannel;
+// import io.netty.handler.codec.http.ClientCookieEncoder;
+// import io.netty.handler.codec.http.DefaultCookie;
+// import io.netty.handler.codec.http.DefaultFullHttpRequest;
+// import io.netty.handler.codec.http.HttpClientCodec;
+// import io.netty.handler.codec.http.HttpContent;
+// import io.netty.handler.codec.http.HttpContentDecompressor;
+// import io.netty.handler.codec.http.HttpHeaders;
+// import io.netty.handler.codec.http.HttpMethod;
+// import io.netty.handler.codec.http.HttpObject;
+// import io.netty.handler.codec.http.HttpRequest;
+// import io.netty.handler.codec.http.HttpResponse;
+// import io.netty.handler.codec.http.HttpVersion;
+// import io.netty.handler.codec.http.LastHttpContent;
+// import io.netty.handler.ssl.SslContext;
+// import io.netty.handler.ssl.SslContextBuilder;
+// import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
+// import io.netty.util.CharsetUtil;
+//
+// public class HttpClient {
+//
+// private static class HttpClientInitializer
+// extends ChannelInitializer<SocketChannel> {
+//
+// public static class HttpSnoopClientHandler
+// extends SimpleChannelInboundHandler<HttpObject> {
+//
+// @Override
+// public void channelRead0(ChannelHandlerContext ctx,
+// HttpObject msg) {
+// if (msg instanceof HttpResponse) {
+// HttpResponse response = (HttpResponse) msg;
+//
+// System.err.println("STATUS: " + response.getStatus());
+// System.err.println(
+// "VERSION: " + response.getProtocolVersion());
+// System.err.println();
+//
+// if (!response.headers().isEmpty()) {
+// for (String name : response.headers().names()) {
+// for (String value : response.headers()
+// .getAll(name)) {
+// System.err.println(
+// "HEADER: " + name + " = " + value);
+// }
+// }
+// System.err.println();
+// }
+//
+// if (HttpHeaders.isTransferEncodingChunked(response)) {
+// System.err.println("CHUNKED CONTENT {");
+// } else {
+// System.err.println("CONTENT {");
+// }
+// }
+// if (msg instanceof HttpContent) {
+// HttpContent content = (HttpContent) msg;
+//
+// System.err.print(
+// content.content().toString(CharsetUtil.UTF_8));
+// System.err.flush();
+//
+// if (content instanceof LastHttpContent) {
+// System.err.println("} END OF CONTENT");
+// ctx.close();
+// }
+// }
+// }
+//
+// @Override
+// public void exceptionCaught(ChannelHandlerContext ctx,
+// Throwable cause) {
+// cause.printStackTrace();
+// ctx.close();
+// }
+// }
+//
+// private final SslContext sslCtx;
+//
+// public HttpClientInitializer(SslContext sslCtx) {
+// this.sslCtx = sslCtx;
+// }
+//
+// @Override
+// public void initChannel(SocketChannel ch) {
+// ChannelPipeline p = ch.pipeline();
+//
+// // Enable HTTPS if necessary.
+// if (sslCtx != null) {
+// p.addLast(sslCtx.newHandler(ch.alloc()));
+// }
+//
+// p.addLast(new HttpClientCodec());
+//
+// // Remove the following line if you don't want automatic content
+// // decompression.
+// p.addLast(new HttpContentDecompressor());
+//
+// // Uncomment the following line if you don't want to handle
+// // HttpContents.
+// // p.addLast(new HttpObjectAggregator(1048576));
+//
+// p.addLast(new HttpSnoopClientHandler());
+// }
+// }
+//
+// public void connect(String strUrl)
+// throws URISyntaxException, InterruptedException, SSLException {
+// URI uri = new URI(strUrl);
+//
+// String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
+// String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
+//
+// int port = uri.getPort();
+//
+// if (port == -1) {
+// if ("http".equalsIgnoreCase(scheme)) {
+// port = 80;
+// } else if ("https".equalsIgnoreCase(scheme)) {
+// port = 443;
+// }
+// }
+//
+// if (!"http".equalsIgnoreCase(scheme)
+// && !"https".equalsIgnoreCase(scheme)) {
+// return;
+// }
+//
+// final boolean ssl = "https".equalsIgnoreCase(scheme);
+// final SslContext sslCtx;
+//
+// if (ssl) {
+// sslCtx = SslContextBuilder.forClient()
+// .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
+// } else {
+// sslCtx = null;
+// }
+//
+// EventLoopGroup group = new NioEventLoopGroup();
+//
+// try {
+// Bootstrap b = new Bootstrap();
+// b.group(group);
+// b.channel(NioSocketChannel.class);
+// b.handler(new HttpClientInitializer(sslCtx));
+//
+// Channel ch = b.connect(host, port).sync().channel();
+//
+// HttpRequest request = new DefaultFullHttpRequest(
+// HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
+// request.headers().set(HttpHeaders.Names.HOST, host);
+// request.headers().set(HttpHeaders.Names.CONNECTION,
+// HttpHeaders.Values.CLOSE);
+// request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING,
+// HttpHeaders.Values.GZIP);
+//
+// request.headers().set(HttpHeaders.Names.COOKIE,
+// ClientCookieEncoder.encode(
+// new DefaultCookie("my-cookie", "foo"),
+// new DefaultCookie("another-cookie", "bar")));
+//
+// ch.writeAndFlush(request);
+//
+// ch.closeFuture().sync();
+// } finally {
+// group.shutdownGracefully();
+// }
+// }
+//
+// }
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/HttpServer.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/HttpServer.java
new file mode 100644 (file)
index 0000000..3f4498f
--- /dev/null
@@ -0,0 +1,139 @@
+/*
+ * //****************************************************************** // //
+ * 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.cloud.base;
+//
+// import java.net.InetSocketAddress;
+// import java.security.cert.CertificateException;
+// import java.util.ArrayList;
+// import java.util.List;
+//
+// import javax.net.ssl.SSLException;
+//
+// import io.netty.bootstrap.ServerBootstrap;
+// import io.netty.channel.ChannelFuture;
+// import io.netty.channel.ChannelHandler;
+// import io.netty.channel.ChannelInitializer;
+// import io.netty.channel.ChannelPipeline;
+// import io.netty.channel.EventLoopGroup;
+// import io.netty.channel.nio.NioEventLoopGroup;
+// import io.netty.channel.socket.SocketChannel;
+// import io.netty.channel.socket.nio.NioServerSocketChannel;
+// import io.netty.handler.codec.http.HttpRequestDecoder;
+// import io.netty.handler.codec.http.HttpResponseEncoder;
+// import io.netty.handler.logging.LogLevel;
+// import io.netty.handler.logging.LoggingHandler;
+// import io.netty.util.concurrent.GenericFutureListener;
+//
+// public class HttpServer {
+//
+// private static class HttpServerInitializer
+// extends ChannelInitializer<SocketChannel> {
+//
+// private List<ChannelHandler> additionalHandlers = new
+// ArrayList<ChannelHandler>();
+//
+// public HttpServerInitializer() {
+// }
+//
+// public void addHandler(ChannelHandler handler) {
+// additionalHandlers.add(handler);
+// }
+//
+// @Override
+// public void initChannel(SocketChannel ch) {
+// ChannelPipeline p = ch.pipeline();
+// /*
+// * if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc())); }
+// */
+// p.addLast(new HttpRequestDecoder());
+// // Uncomment the following line if you don't want to handle
+// // HttpChunks.
+// // p.addLast(new HttpObjectAggregator(1048576));
+// p.addLast(new HttpResponseEncoder());
+// // Remove the following line if you don't want automatic content
+// // compression.
+// // p.addLast(new HttpContentCompressor());
+// for (ChannelHandler handler : additionalHandlers) {
+// p.addLast(handler);
+// }
+// }
+//
+// }
+//
+// EventLoopGroup bossGroup = new NioEventLoopGroup(1);
+//
+// EventLoopGroup workerGroup = new NioEventLoopGroup();
+//
+// HttpServerInitializer initializer = new HttpServerInitializer();
+//
+// public void addHandler(ChannelHandler handler) {
+// initializer.addHandler(handler);
+// }
+//
+// public void startServer(InetSocketAddress inetSocketAddress)
+// throws CertificateException, SSLException, InterruptedException {
+//
+// try {
+// ServerBootstrap b = new ServerBootstrap();
+// b.group(bossGroup, workerGroup);
+// b.channel(NioServerSocketChannel.class);
+// b.handler(new LoggingHandler(LogLevel.INFO));
+//
+// b.childHandler(initializer);
+//
+// ChannelFuture ch = b.bind(inetSocketAddress).sync();
+// ch.addListener(new GenericFutureListener<ChannelFuture>() {
+//
+// @Override
+// public void operationComplete(ChannelFuture future)
+// throws Exception {
+// // TODO Auto-generated method stub
+// System.out
+// .println("Connection status of TCP Http SERVER : "
+// + future.isSuccess());
+// }
+//
+// });
+// } finally {
+// }
+//
+// }
+//
+// public void stopServer() {
+// // shut down all event loops
+// if (bossGroup != null) {
+// bossGroup.shutdownGracefully();
+//
+// try {
+// bossGroup.terminationFuture().sync();
+// } catch (InterruptedException e) {
+// // TODO Auto-generated catch block
+// e.printStackTrace();
+// }
+// }
+//
+// if (workerGroup != null) {
+// workerGroup.shutdownGracefully();
+//
+// try {
+// workerGroup.terminationFuture().sync();
+// } catch (InterruptedException e) {
+// // TODO Auto-generated catch block
+// e.printStackTrace();
+// }
+// }
+// }
+//
+// }
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/Resource.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/Resource.java
new file mode 100644 (file)
index 0000000..cdf249c
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.base;
+
+import org.iotivity.cloud.base.protocols.coap.CoapRequest;
+
+import io.netty.channel.ChannelHandlerContext;
+
+public abstract class Resource {
+
+    public Resource() {
+    }
+
+    private String uri;
+    private String type;
+    private String rif; // resource interface
+
+    public String getUri() {
+        return uri;
+    }
+
+    public void setUri(String uri) {
+        this.uri = uri;
+    }
+
+    public String getType() {
+        return type;
+    }
+
+    public void setType(String type) {
+        this.type = type;
+    }
+
+    public String getRif() {
+        return rif;
+    }
+
+    public void setRif(String rif) {
+        this.rif = rif;
+    }
+
+    public abstract void onRequestReceived(ChannelHandlerContext ctx,
+            CoapRequest request);
+}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/ResourceManager.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/ResourceManager.java
new file mode 100644 (file)
index 0000000..0ca806f
--- /dev/null
@@ -0,0 +1,77 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.base;
+
+import java.util.ArrayList;
+
+import org.iotivity.cloud.base.protocols.coap.CoapRequest;
+
+import io.netty.channel.ChannelHandler.Sharable;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.SimpleChannelInboundHandler;
+
+@Sharable
+public class ResourceManager extends SimpleChannelInboundHandler<CoapRequest> {
+
+    private ArrayList<Resource> resources = new ArrayList<Resource>();
+
+    @Override
+    public void channelRead0(ChannelHandlerContext ctx, CoapRequest request)
+            throws Exception {
+
+        Resource res = queryResourceHandler(request.getUriPath());
+
+        if (res != null) {
+            res.onRequestReceived(ctx, request);
+        }
+    }
+
+    private Resource queryResourceHandler(String query_uri) {
+
+        Resource res = null;
+
+        for (Resource r : resources) {
+
+            String uri = r.getUri();
+            if (uri.contains(query_uri)) {
+                res = r;
+                break;
+            }
+        }
+
+        return res;
+    }
+
+    public void registerResource(Resource res) {
+
+        synchronized (this) {
+            resources.add(res);
+        }
+    }
+
+    public void unregisterResource(Resource res) {
+
+        synchronized (this) {
+            resources.remove(res);
+        }
+    }
+}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/SessionManager.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/SessionManager.java
new file mode 100644 (file)
index 0000000..ca371f7
--- /dev/null
@@ -0,0 +1,86 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.base;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map.Entry;
+import java.util.Objects;
+
+import io.netty.channel.ChannelHandlerContext;
+
+public class SessionManager {
+
+    HashMap<String, ChannelHandlerContext> sessions = new HashMap<String, ChannelHandlerContext>();
+
+    public void addSession(String did, ChannelHandlerContext ctx) {
+        synchronized (sessions) {
+            sessions.put(did, ctx);
+        }
+    }
+
+    public void removeSession(String did) {
+
+        synchronized (sessions) {
+            sessions.remove(did);
+        }
+    }
+
+    public void removeSessionByChannel(ChannelHandlerContext ctx) {
+
+        String did = queryDid(ctx);
+        if (did != null) {
+            removeSession(did);
+        }
+    }
+
+    public ChannelHandlerContext querySession(String did) {
+        ChannelHandlerContext ctx = null;
+
+        synchronized (sessions) {
+            ctx = sessions.get(did);
+        }
+
+        return ctx;
+    }
+
+    public String queryDid(ChannelHandlerContext ctx) {
+        synchronized (sessions) {
+            for (Entry<String, ChannelHandlerContext> entry : sessions
+                    .entrySet()) {
+                if (Objects.equals(ctx, entry.getValue())) {
+                    return entry.getKey();
+                }
+            }
+        }
+
+        return null;
+    }
+
+    public List<String> getSessions() {
+        synchronized (sessions) {
+            List<String> list = new ArrayList<String>(sessions.keySet());
+            return list;
+        }
+    }
+}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapDecoder.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapDecoder.java
new file mode 100644 (file)
index 0000000..46d618f
--- /dev/null
@@ -0,0 +1,199 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.base.protocols.coap;
+
+import java.util.List;
+
+import org.iotivity.cloud.base.protocols.coap.enums.CoapMethod;
+import org.iotivity.cloud.base.protocols.coap.enums.CoapStatus;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.handler.codec.ByteToMessageDecoder;
+
+public class CoapDecoder extends ByteToMessageDecoder {
+
+    private enum ParsingState {
+        SHIM_HEADER, OPTION_PAYLOAD_LENGTH, CODE_TOKEN_OPTION, PAYLOAD, FINISH
+    }
+
+    private ParsingState nextState           = ParsingState.SHIM_HEADER;
+    private int          bufferToRead        = 1;
+    private int          tokenLength         = 0;
+    private int          optionPayloadLength = 0;
+    private CoapMessage  partialMsg          = null;
+
+    @Override
+    protected void decode(ChannelHandlerContext ctx, ByteBuf in,
+            List<Object> out) throws Exception {
+
+        while (in.isReadable(bufferToRead)) {
+
+            switch (nextState) {
+                case SHIM_HEADER:
+                    int shimHeader = in.readByte();
+                    bufferToRead = (shimHeader >>> 4) & 0x0F;
+                    tokenLength = (shimHeader) & 0x0F;
+                    switch (bufferToRead) {
+                        case 13:
+                            bufferToRead = 1;
+                            nextState = ParsingState.OPTION_PAYLOAD_LENGTH;
+                            break;
+                        case 14:
+                            bufferToRead = 2;
+                            nextState = ParsingState.OPTION_PAYLOAD_LENGTH;
+                            break;
+                        case 15:
+                            bufferToRead = 4;
+                            nextState = ParsingState.OPTION_PAYLOAD_LENGTH;
+                            break;
+                        default:
+                            optionPayloadLength = bufferToRead;
+                            bufferToRead += 1 + tokenLength; // code + tkl
+                            nextState = ParsingState.CODE_TOKEN_OPTION;
+                            break;
+                    }
+                    break;
+
+                case OPTION_PAYLOAD_LENGTH:
+                    switch (bufferToRead) {
+                        case 1:
+                            optionPayloadLength = 13 + (in.readByte() & 0xFF);
+                            break;
+
+                        case 2:
+                            optionPayloadLength = 269
+                                    + (((in.readByte() & 0xFF) << 8)
+                                            + (in.readByte() & 0xFF));
+                            break;
+
+                        case 4:
+                            optionPayloadLength = 65805
+                                    + (((in.readByte() & 0xFF) << 24)
+                                            + ((in.readByte() & 0xFF) << 16)
+                                            + ((in.readByte() & 0xFF) << 8)
+                                            + (in.readByte() & 0xFF));
+                            break;
+                    }
+                    nextState = ParsingState.CODE_TOKEN_OPTION;
+                    bufferToRead = 1 + tokenLength + optionPayloadLength; // code
+                                                                          // +
+                                                                          // tkl
+                    break;
+
+                case CODE_TOKEN_OPTION:
+                    int code = in.readByte() & 0xFF;
+
+                    if (code <= 31) {
+                        partialMsg = new CoapRequest(CoapMethod.valueOf(code));
+                    } else {
+                        partialMsg = new CoapResponse(CoapStatus.valueOf(code));
+                    }
+
+                    if (tokenLength > 0) {
+                        byte[] token = new byte[tokenLength];
+                        in.readBytes(token);
+                        partialMsg.setToken(token);
+                    }
+
+                    if (optionPayloadLength > 0) {
+                        int optionLen = parseOptions(partialMsg, in,
+                                optionPayloadLength);
+                        if (optionPayloadLength > optionLen) {
+                            nextState = ParsingState.PAYLOAD;
+                            bufferToRead = optionPayloadLength - optionLen;
+                            continue;
+                        }
+                    }
+
+                    nextState = ParsingState.FINISH;
+                    bufferToRead = 0;
+
+                    break;
+
+                case PAYLOAD:
+                    byte[] payload = new byte[bufferToRead];
+                    in.readBytes(payload);
+                    partialMsg.setPayload(payload);
+                    nextState = ParsingState.FINISH;
+                    bufferToRead = 0;
+                    break;
+
+                case FINISH:
+                    nextState = ParsingState.SHIM_HEADER;
+                    bufferToRead = 1;
+                    out.add(partialMsg);
+                    break;
+
+                default:
+                    break;
+            }
+        }
+
+        in.discardReadBytes();
+    }
+
+    private int parseOptions(CoapMessage coapMessage, ByteBuf byteBuf,
+            int maxLength) {
+
+        int preOptionNum = 0;
+
+        int startPos = byteBuf.readerIndex();
+
+        int firstByte = byteBuf.readByte() & 0xFF;
+
+        while (firstByte != 0xFF && maxLength > 0) {
+            int optionDelta = (firstByte & 0xF0) >>> 4;
+            int optionLength = firstByte & 0x0F;
+
+            if (optionDelta == 13) {
+                optionDelta = 13 + byteBuf.readByte() & 0xFF;
+            } else if (optionDelta == 14) {
+                optionDelta = 269 + ((byteBuf.readByte() & 0xFF) << 8)
+                        + (byteBuf.readByte() & 0xFF);
+            }
+
+            if (optionLength == 13) {
+                optionLength = 13 + byteBuf.readByte() & 0xFF;
+            } else if (optionLength == 14) {
+                optionLength = 269 + ((byteBuf.readByte() & 0xFF) << 8)
+                        + (byteBuf.readByte() & 0xFF);
+            }
+
+            int curOptionNum = preOptionNum + optionDelta;
+            byte[] optionValue = new byte[optionLength];
+            byteBuf.readBytes(optionValue);
+
+            coapMessage.addOption(curOptionNum, optionValue);
+
+            preOptionNum = curOptionNum;
+            if (maxLength > byteBuf.readerIndex() - startPos) {
+                firstByte = byteBuf.readByte() & 0xFF;
+            } else {
+                break;
+            }
+        }
+
+        /// return option length
+        return byteBuf.readerIndex() - startPos;
+    }
+}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapEncoder.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapEncoder.java
new file mode 100644 (file)
index 0000000..2aee0dd
--- /dev/null
@@ -0,0 +1,183 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.base.protocols.coap;
+
+import java.util.List;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.handler.codec.MessageToByteEncoder;
+
+public class CoapEncoder extends MessageToByteEncoder<CoapMessage> {
+
+    @Override
+    protected void encode(ChannelHandlerContext ctx, CoapMessage msg,
+            ByteBuf out) throws Exception {
+
+        CoapMessage coapMessage = (CoapMessage) msg;
+
+        ByteBuf optBuf = Unpooled.directBuffer();
+
+        /**
+         * encode options
+         */
+        encodeOptions(optBuf, coapMessage);
+        long length = optBuf.readableBytes();
+
+        if (coapMessage.getPayloadSize() > 0) {
+            // + 1 means 8bits delimiter
+            length += 1 + coapMessage.getPayloadSize();
+        }
+
+        calcShimHeader(coapMessage, out, length);
+
+        out.writeByte(coapMessage.getCode());
+
+        if (coapMessage.getTokenLength() > 0) {
+            out.writeBytes(coapMessage.getToken());
+        }
+
+        // Write option
+        if (optBuf.readableBytes() > 0) {
+            out.writeBytes(optBuf);
+        }
+
+        optBuf.release();
+
+        if (coapMessage.getPayloadSize() > 0) {
+            out.writeByte(255);
+            out.writeBytes(coapMessage.getPayload());
+        }
+    }
+
+    private void calcShimHeader(CoapMessage coapMessage, ByteBuf byteBuf,
+            long length) {
+        if (length < 13) {
+            byteBuf.writeByte(((int) length & 0x0F) << 4
+                    | (coapMessage.getTokenLength() & 0x0F));
+        } else if (length < 269) {
+            byteBuf.writeShort((13 & 0x0F) << 12
+                    | (coapMessage.getTokenLength() & 0x0F) << 8
+                    | (((int) length - 13) & 0xFF));
+        } else if (length < 65805) {
+            byteBuf.writeByte(
+                    (14 & 0x0F) << 4 | (coapMessage.getTokenLength() & 0x0F));
+            byteBuf.writeShort(((int) length - 269) & 0xFFFF);
+        } else if (length < Integer.MAX_VALUE * 2) {
+            byteBuf.writeByte(
+                    (15 & 0x0F) << 4 | (coapMessage.getTokenLength() & 0x0F));
+            byteBuf.writeLong((length - 65805) & 0xFFFFFFFF);
+        } else {
+            throw new IllegalArgumentException(
+                    "Length must be less than 4GB " + length);
+        }
+    }
+
+    private void encodeOptions(ByteBuf byteBuf, CoapMessage coapMessage)
+            throws Exception {
+        int preOptionNum = 0;
+
+        for (int i = 0; i < 40; i++) {
+            List<byte[]> values = coapMessage.getOption(i);
+            if (values != null) {
+                if (values.size() > 0) {
+                    for (byte[] value : values) {
+                        writeOption(i - preOptionNum,
+                                value != null ? value.length : 0, byteBuf,
+                                value);
+                        preOptionNum = i;
+                    }
+
+                } else {
+                    writeOption(i - preOptionNum, 0, byteBuf, null);
+                    preOptionNum = i;
+                }
+            }
+        }
+    }
+
+    private void writeOption(int optionDelta, int optionLength, ByteBuf byteBuf,
+            byte[] value) {
+
+        if (optionDelta < 13) {
+            if (optionLength < 13) {
+                byteBuf.writeByte(
+                        ((optionDelta & 0xFF) << 4) | (optionLength & 0xFF));
+            } else if (optionLength < 269) {
+                byteBuf.writeByte(((optionDelta << 4) & 0xFF) | (13 & 0xFF));
+                byteBuf.writeByte((optionLength - 13) & 0xFF);
+            } else {
+                byteBuf.writeByte(((optionDelta << 4) & 0xFF) | (14 & 0xFF));
+                byteBuf.writeByte(((optionLength - 269) & 0xFF00) >>> 8);
+                byteBuf.writeByte((optionLength - 269) & 0xFF);
+            }
+        }
+
+        else if (optionDelta < 269) {
+            if (optionLength < 13) {
+                byteBuf.writeByte(((13 & 0xFF) << 4) | (optionLength & 0xFF));
+                byteBuf.writeByte((optionDelta - 13) & 0xFF);
+            } else if (optionLength < 269) {
+                byteBuf.writeByte(((13 & 0xFF) << 4) | (13 & 0xFF));
+                byteBuf.writeByte((optionDelta - 13) & 0xFF);
+                byteBuf.writeByte((optionLength - 13) & 0xFF);
+            } else {
+                byteBuf.writeByte((13 & 0xFF) << 4 | (14 & 0xFF));
+                byteBuf.writeByte((optionDelta - 13) & 0xFF);
+                byteBuf.writeByte(((optionLength - 269) & 0xFF00) >>> 8);
+                byteBuf.writeByte((optionLength - 269) & 0xFF);
+            }
+        }
+
+        else if (optionDelta < 65805) {
+
+            if (optionLength < 13) {
+                byteBuf.writeByte(((14 & 0xFF) << 4) | (optionLength & 0xFF));
+                byteBuf.writeByte(((optionDelta - 269) & 0xFF00) >>> 8);
+                byteBuf.writeByte((optionDelta - 269) & 0xFF);
+            }
+
+            else if (optionLength < 269) {
+                byteBuf.writeByte(((14 & 0xFF) << 4) | (13 & 0xFF));
+                byteBuf.writeByte(((optionDelta - 269) & 0xFF00) >>> 8);
+                byteBuf.writeByte((optionDelta - 269) & 0xFF);
+                byteBuf.writeByte((optionLength - 13) & 0xFF);
+            }
+
+            else {
+                byteBuf.writeByte(((14 & 0xFF) << 4) | (14 & 0xFF));
+                byteBuf.writeByte(((optionDelta - 269) & 0xFF00) >>> 8);
+                byteBuf.writeByte((optionDelta - 269) & 0xFF);
+                byteBuf.writeByte(((optionLength - 269) & 0xFF00) >>> 8);
+                byteBuf.writeByte((optionLength - 269) & 0xFF);
+            }
+        } else {
+            throw new IllegalArgumentException(
+                    "Unsupported option delta " + optionDelta);
+        }
+
+        if (optionLength > 0) {
+            byteBuf.writeBytes(value);
+        }
+    }
+}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapMessage.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapMessage.java
new file mode 100644 (file)
index 0000000..fb77b06
--- /dev/null
@@ -0,0 +1,321 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.base.protocols.coap;
+
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+
+import org.iotivity.cloud.base.protocols.coap.enums.CoapOption;
+import org.iotivity.cloud.util.Cbor;
+import org.iotivity.cloud.util.Logger;
+
+public class CoapMessage {
+
+    private int            tokenLength    = 0;
+    protected int          code           = 0;
+    private byte[]         token          = null;
+
+    private byte[]         payload        = null;
+
+    // Option fields
+    protected List<byte[]> if_match       = null;
+    protected byte[]       uri_host       = null;
+    protected List<byte[]> etag           = null;
+    protected boolean      if_none_match  = false;
+    protected byte[]       uri_port       = null;
+    protected List<byte[]> location_path  = null;
+    protected List<byte[]> uri_path       = null;
+    protected byte[]       content_format = null;
+    protected byte[]       max_age        = null;
+    protected List<byte[]> uri_query      = null;
+    protected byte[]       accept         = null;
+    protected List<byte[]> location_query = null;
+    protected byte[]       proxy_uri      = null;
+    protected byte[]       proxy_scheme   = null;
+    protected byte[]       size1          = null;
+    protected byte[]       observe        = null;
+
+    public CoapMessage() {
+    }
+
+    public int getTokenLength() {
+        return this.tokenLength;
+    }
+
+    public int getCode() {
+        return code;
+    }
+
+    public byte[] getToken() {
+        return token;
+    }
+
+    public void setToken(byte[] token) {
+        this.token = token;
+        this.tokenLength = token.length;
+    }
+
+    public int getPayloadSize() {
+        return payload == null ? 0 : payload.length;
+    }
+
+    public byte[] getPayload() {
+        return payload;
+    }
+
+    public void setPayload(byte[] payload) {
+        this.payload = payload;
+    }
+
+    public void addOption(int optnum, byte[] value) {
+        switch (optnum) {
+            // IF_MATCH
+            case 1:
+                if (if_match == null) {
+                    if_match = new ArrayList<byte[]>();
+                }
+                if_match.add(value);
+                break;
+
+            // URI_HOST
+            case 3:
+                uri_host = value;
+                break;
+
+            // ETAG
+            case 4:
+                if (etag == null) {
+                    etag = new ArrayList<byte[]>();
+                }
+                etag.add(value);
+                break;
+
+            // IF_NONE_MATCH
+            case 5:
+                if_none_match = true;
+                break;
+
+            // URI_PORT
+            case 7:
+                uri_port = value;
+                break;
+
+            // LOCATION_PATH
+            case 8:
+                if (location_path == null) {
+                    location_path = new ArrayList<byte[]>();
+                }
+                location_path.add(value);
+                break;
+
+            // URI_PATH
+            case 11:
+                if (uri_path == null) {
+                    uri_path = new ArrayList<byte[]>();
+                }
+                uri_path.add(value);
+                break;
+
+            // CONTENT_FORMAT
+            case 12:
+                content_format = value;
+                break;
+
+            // MAX_AGE
+            case 14:
+                max_age = value;
+                break;
+
+            // URI_QUERY
+            case 15:
+                if (uri_query == null) {
+                    uri_query = new ArrayList<byte[]>();
+                }
+                uri_query.add(value);
+                break;
+
+            // ACCEPT
+            case 17:
+                accept = value;
+                break;
+
+            // LOCATION_QUERY
+            case 20:
+                if (location_query == null) {
+                    location_query = new ArrayList<byte[]>();
+                }
+                location_query.add(value);
+                break;
+
+            // PROXY_URI
+            case 35:
+                proxy_uri = value;
+                break;
+
+            // PROXY_SCHEME
+            case 39:
+                proxy_scheme = value;
+                break;
+
+            // SIZE1
+            case 60:
+                size1 = value;
+                break;
+
+            // OBSERVE
+            case 6:
+                observe = value;
+                break;
+        }
+    }
+
+    public List<byte[]> getOption(int optnum) {
+        switch (optnum) {
+            // IF_MATCH
+            case 1:
+                return if_match;
+
+            // URI_HOST
+            case 3:
+                return uri_host != null ? Arrays.asList(uri_host) : null;
+
+            // ETAG
+            case 4:
+                return etag;
+
+            // IF_NONE_MATCH
+            case 5:
+                return if_none_match == true ? new ArrayList<byte[]>() : null;
+
+            // URI_PORT
+            case 7:
+                return uri_port != null ? Arrays.asList(uri_port) : null;
+
+            // LOCATION_PATH
+            case 8:
+                return location_path;
+
+            // URI_PATH
+            case 11:
+                return uri_path;
+
+            // CONTENT_FORMAT
+            case 12:
+                return content_format != null ? Arrays.asList(content_format)
+                        : null;
+
+            // MAX_AGE
+            case 14:
+                return max_age != null ? Arrays.asList(max_age) : null;
+
+            // URI_QUERY
+            case 15:
+                return uri_query;
+
+            // ACCEPT
+            case 17:
+                return accept != null ? Arrays.asList(accept) : null;
+
+            // LOCATION_QUERY
+            case 20:
+                return location_query;
+
+            // PROXY_URI
+            case 35:
+                return proxy_uri != null ? Arrays.asList(proxy_uri) : null;
+
+            // PROXY_SCHEME
+            case 39:
+                return proxy_scheme != null ? Arrays.asList(proxy_scheme)
+                        : null;
+
+            // SIZE1
+            case 60:
+                return size1 != null ? Arrays.asList(size1) : null;
+
+            // OBSERVE
+            case 6:
+                return observe != null ? Arrays.asList(observe) : null;
+        }
+
+        return null;
+    }
+
+    public String getTokenString() {
+        StringBuffer strBuffer = new StringBuffer(token == null ? "null" : "");
+        if (token != null)
+            for (byte b : token)
+                strBuffer.append(String.format("%02x", b & 0xff)); // hexadecimal(16)
+        return strBuffer.toString();
+    }
+
+    public String getContentFormatString() {
+        List<byte[]> contentFormatList = getOption(
+                CoapOption.CONTENT_FORMAT.getvalue());
+        byte[] contentFormat = null;
+        if (contentFormatList != null && !contentFormatList.isEmpty())
+            contentFormat = contentFormatList.get(0);
+        StringBuffer strBuffer = new StringBuffer(
+                contentFormat == null ? "null" : "");
+        if (contentFormat != null)
+            for (byte b : contentFormat)
+                strBuffer.append(String.format("%02d", b & 0xff)); // decimal(10)
+        return strBuffer.toString();
+    }
+
+    public String getPayloadString() {
+        if (payload == null)
+            return "";
+        return new String(payload, Charset.forName("UTF-8"));
+    }
+
+    public String decodeDeviceId() {
+        Cbor<ArrayList<Object>> cbor = new Cbor<ArrayList<Object>>();
+        ArrayList<Object> decodedPayload = null;
+
+        if (payload == null) {
+            throw new IllegalArgumentException("payload is null");
+        }
+
+        else {
+            decodedPayload = cbor.parsePayloadFromCbor(payload,
+                    ArrayList.class);
+            String deviceId = null;
+            if (decodedPayload != null) {
+                HashMap<Object, Object> tags = (HashMap<Object, Object>) decodedPayload
+                        .get(0);
+
+                deviceId = tags.get("di").toString();
+
+                if (deviceId == null) {
+                    throw new IllegalArgumentException("deviceId is null");
+                }
+
+                Logger.i("deviceId : " + deviceId);
+            }
+            return deviceId;
+        }
+    }
+}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapRequest.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapRequest.java
new file mode 100644 (file)
index 0000000..3a1f013
--- /dev/null
@@ -0,0 +1,120 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.base.protocols.coap;
+
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.iotivity.cloud.base.protocols.coap.enums.CoapMethod;
+
+public class CoapRequest extends CoapMessage {
+    public CoapRequest(CoapMethod method) {
+        this.code = method.getCode();
+    }
+
+    public CoapMethod getRequestMethod() {
+        return CoapMethod.valueOf(code);
+    }
+
+    public void setUriPath(String path) {
+        if (uri_path == null) {
+            uri_path = new ArrayList<byte[]>();
+        }
+        clearUriPath();
+
+        String[] pathSegments = path.split("/");
+        for (String pathSegment : pathSegments) {
+            if (pathSegment.length() == 0)
+                continue;
+            uri_path.add(pathSegment.getBytes(StandardCharsets.UTF_8));
+        }
+    }
+
+    public String getUriPath() {
+        if (uri_path == null) {
+            return null;
+        }
+        StringBuilder path = new StringBuilder();
+        int nItem = uri_path.size();
+        for (byte[] pathSegment : uri_path) {
+            path.append(new String(pathSegment, StandardCharsets.UTF_8));
+            if (--nItem > 0) {
+                path.append('/');
+            }
+        }
+        return path.toString();
+    }
+
+    public List<String> getUriPathSegments() {
+        if (uri_path == null) {
+            return null;
+        }
+        List<String> segments = new ArrayList<String>();
+        for (byte[] pathSegment : uri_path) {
+            segments.add(new String(pathSegment, StandardCharsets.UTF_8));
+        }
+        return segments;
+    }
+
+    public void setUriQuery(String query) {
+        if (uri_query == null) {
+            uri_query = new ArrayList<byte[]>();
+        }
+        String[] querySegments = query.split("&");
+        for (String querySegment : querySegments) {
+            uri_query.add(querySegment.getBytes(StandardCharsets.UTF_8));
+        }
+    }
+
+    public String getUriQuery() {
+        if (uri_query == null) {
+            return null;
+        }
+        StringBuilder uriQuery = new StringBuilder();
+        int nItem = uri_query.size();
+        for (byte[] querySegment : uri_query) {
+            uriQuery.append(new String(querySegment, StandardCharsets.UTF_8));
+            if (--nItem > 0) {
+                uriQuery.append('&');
+            }
+        }
+        return uriQuery.toString();
+    }
+
+    public List<String> getUriQuerySegments() {
+        if (uri_query == null) {
+            return null;
+        }
+        List<String> segments = new ArrayList<String>();
+        for (byte[] querySegment : uri_query) {
+            segments.add(new String(querySegment, StandardCharsets.UTF_8));
+        }
+        return segments;
+    }
+
+    public void clearUriPath() {
+        if (uri_path != null) {
+            uri_path.clear();
+        }
+    }
+}
\ No newline at end of file
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapResponse.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapResponse.java
new file mode 100644 (file)
index 0000000..d4b07cb
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.base.protocols.coap;
+
+import org.iotivity.cloud.base.protocols.coap.enums.CoapStatus;
+
+public class CoapResponse extends CoapMessage {
+    public CoapResponse(CoapStatus status) {
+        this.code = status.getCode();
+    }
+
+    public CoapStatus getResponseCode() {
+        return CoapStatus.valueOf(code);
+    }
+}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/enums/CoapMethod.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/enums/CoapMethod.java
new file mode 100644 (file)
index 0000000..90b99da
--- /dev/null
@@ -0,0 +1,33 @@
+package org.iotivity.cloud.base.protocols.coap.enums;
+
+public enum CoapMethod {
+    GET(1), POST(2), PUT(3), DELETE(4);
+
+    public static CoapMethod valueOf(int code) {
+        switch (code) {
+            case 1:
+                return CoapMethod.GET;
+
+            case 2:
+                return CoapMethod.POST;
+
+            case 3:
+                return CoapMethod.PUT;
+
+            case 4:
+                return CoapMethod.DELETE;
+        }
+
+        throw new IllegalArgumentException("Invalid Method value");
+    }
+
+    private final int code;
+
+    private CoapMethod(int code) {
+        this.code = code;
+    }
+
+    public int getCode() {
+        return code;
+    }
+}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/enums/CoapOption.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/enums/CoapOption.java
new file mode 100644 (file)
index 0000000..f8439c8
--- /dev/null
@@ -0,0 +1,73 @@
+package org.iotivity.cloud.base.protocols.coap.enums;
+
+public enum CoapOption {
+    IF_MATCH(1), URI_HOST(3), ETAG(4), IF_NONE_MATCH(5), URI_PORT(
+            7), LOCATION_PATH(8), URI_PATH(11), CONTENT_FORMAT(12), MAX_AGE(
+                    14), URI_QUERY(15), ACCEPT(17), LOCATION_QUERY(
+                            20), PROXY_URI(35), PROXY_SCHEME(39), SIZE1(
+                                    60), OBSERVE(6);
+
+    public static CoapOption valueOf(int option) {
+        switch (option) {
+            case 1:
+                return CoapOption.IF_MATCH;
+
+            case 3:
+                return CoapOption.URI_HOST;
+
+            case 4:
+                return CoapOption.ETAG;
+
+            case 5:
+                return CoapOption.IF_NONE_MATCH;
+
+            case 7:
+                return CoapOption.URI_PORT;
+
+            case 8:
+                return CoapOption.LOCATION_PATH;
+
+            case 11:
+                return CoapOption.URI_PATH;
+
+            case 12:
+                return CoapOption.CONTENT_FORMAT;
+
+            case 14:
+                return CoapOption.MAX_AGE;
+
+            case 15:
+                return CoapOption.URI_QUERY;
+
+            case 17:
+                return CoapOption.ACCEPT;
+
+            case 20:
+                return CoapOption.LOCATION_QUERY;
+
+            case 35:
+                return CoapOption.PROXY_URI;
+
+            case 39:
+                return CoapOption.PROXY_SCHEME;
+
+            case 60:
+                return CoapOption.SIZE1;
+
+            case 6:
+                return CoapOption.OBSERVE;
+        }
+
+        throw new IllegalArgumentException("Invalid option value");
+    }
+
+    private final int value;
+
+    private CoapOption(int value) {
+        this.value = value;
+    }
+
+    public int getvalue() {
+        return value;
+    }
+}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/enums/CoapStatus.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/enums/CoapStatus.java
new file mode 100644 (file)
index 0000000..a687ad3
--- /dev/null
@@ -0,0 +1,97 @@
+package org.iotivity.cloud.base.protocols.coap.enums;
+
+public enum CoapStatus {
+    // Success 2.xx
+    CREATED(65), DELETED(66), VALID(67), CHANGED(68), CONTENT(69),
+    // Client Error 4.xx
+    BAD_REQUEST(128), UNAUTHORIZED(129), BAD_OPTION(130), FORBIDDEN(131),
+    //
+    NOT_FOUND(132), METHOD_NOT_ALLOWED(133), NOT_ACCEPTABLE(134),
+    //
+    PRECONDITION_FAILED(140), REQUEST_ENTITY_TOO_LARGE(141),
+    //
+    UNSUPPORTED_CONTENT_FORMAT(143),
+    // Server Error 5.xx
+    INTERNAL_SERVER_ERROR(160), NOT_IMPLEMENTED(161), BAD_GATEWAY(162),
+    //
+    SERVICE_UNAVAILABLE(163), GATEWAY_TIMEOUT(164), PROXY_NOT_SUPPORTED(165);
+
+    public static CoapStatus valueOf(int code) {
+        switch (code) {
+            case 65:
+                return CoapStatus.CREATED;
+
+            case 66:
+                return CoapStatus.DELETED;
+
+            case 67:
+                return CoapStatus.VALID;
+
+            case 68:
+                return CoapStatus.CHANGED;
+
+            case 69:
+                return CoapStatus.CONTENT;
+
+            case 128:
+                return CoapStatus.BAD_REQUEST;
+
+            case 129:
+                return CoapStatus.UNAUTHORIZED;
+
+            case 130:
+                return CoapStatus.BAD_OPTION;
+
+            case 131:
+                return CoapStatus.FORBIDDEN;
+
+            case 132:
+                return CoapStatus.NOT_FOUND;
+
+            case 133:
+                return CoapStatus.METHOD_NOT_ALLOWED;
+
+            case 134:
+                return CoapStatus.NOT_ACCEPTABLE;
+
+            case 140:
+                return CoapStatus.PRECONDITION_FAILED;
+
+            case 141:
+                return CoapStatus.REQUEST_ENTITY_TOO_LARGE;
+
+            case 143:
+                return CoapStatus.UNSUPPORTED_CONTENT_FORMAT;
+
+            case 160:
+                return CoapStatus.INTERNAL_SERVER_ERROR;
+
+            case 161:
+                return CoapStatus.NOT_IMPLEMENTED;
+
+            case 162:
+                return CoapStatus.BAD_GATEWAY;
+
+            case 163:
+                return CoapStatus.SERVICE_UNAVAILABLE;
+
+            case 164:
+                return CoapStatus.GATEWAY_TIMEOUT;
+
+            case 165:
+                return CoapStatus.PROXY_NOT_SUPPORTED;
+        }
+
+        throw new IllegalArgumentException("Invalid Status value");
+    }
+
+    private final int code;
+
+    private CoapStatus(int code) {
+        this.code = code;
+    }
+
+    public int getCode() {
+        return code;
+    }
+}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/proxy/CoapHttpProxyHandler.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/proxy/CoapHttpProxyHandler.java
new file mode 100644 (file)
index 0000000..2ac4109
--- /dev/null
@@ -0,0 +1,204 @@
+/*
+ * //****************************************************************** // //
+ * 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.cloud.base.protocols.proxy;
+//
+// import java.nio.charset.StandardCharsets;
+// import java.util.HashMap;
+// import java.util.List;
+// import java.util.Map.Entry;
+//
+// import org.iotivity.cloud.base.SessionManager;
+// import org.iotivity.cloud.base.protocols.coap.CoapRequest;
+// import org.iotivity.cloud.base.protocols.coap.CoapResponse;
+// import org.iotivity.cloud.base.protocols.coap.enums.CoapMethod;
+// import org.iotivity.cloud.util.Cbor;
+// import org.iotivity.cloud.util.Logger;
+//
+// import io.netty.buffer.Unpooled;
+// import io.netty.channel.ChannelDuplexHandler;
+// import io.netty.channel.ChannelFutureListener;
+// import io.netty.channel.ChannelHandler.Sharable;
+// import io.netty.channel.ChannelHandlerContext;
+// import io.netty.handler.codec.http.DefaultFullHttpResponse;
+// import io.netty.handler.codec.http.HttpHeaders;
+// import io.netty.handler.codec.http.HttpMethod;
+// import io.netty.handler.codec.http.HttpRequest;
+// import io.netty.handler.codec.http.HttpResponse;
+// import io.netty.handler.codec.http.HttpResponseStatus;
+// import io.netty.handler.codec.http.HttpVersion;
+// import io.netty.handler.codec.http.QueryStringDecoder;
+// import io.netty.util.AttributeKey;
+// import io.netty.util.CharsetUtil;
+//
+// @Sharable
+// public class CoapHttpProxyHandler extends ChannelDuplexHandler {
+//
+// // Proxy converts http request to coaprequest and coapresponse to
+// // httpresponse
+// private SessionManager sessionManager = null;
+//
+// private static final AttributeKey<ChannelHandlerContext> keyHttpCtx =
+// AttributeKey
+// .newInstance("httpCtx");
+//
+// public CoapHttpProxyHandler(SessionManager sessionManager) {
+// this.sessionManager = sessionManager;
+// }
+//
+// @Override
+// public void channelRead(ChannelHandlerContext ctx, Object msg)
+// throws Exception {
+//
+// // in case of Receive Request from http
+// if (msg instanceof HttpRequest) {
+// // Check uri query param that contains coap device uuid
+// // then search those and create coapRequest and send
+// HttpRequest httpRequest = (HttpRequest) msg;
+// QueryStringDecoder queryStringDecoder = new QueryStringDecoder(
+// httpRequest.getUri());
+//
+// List<String> didList = queryStringDecoder.parameters().get("di");
+//
+// if (didList != null) {
+// ChannelHandlerContext coapClient = sessionManager
+// .querySession(didList.get(0));
+//
+// if (coapClient != null) {
+// List<String> uriList = queryStringDecoder.parameters()
+// .get("href");
+// if (uriList != null) {
+// coapClient.channel().attr(keyHttpCtx).set(ctx);
+// coapClient.writeAndFlush(httpRequestToCoAPRequest(
+// uriList.get(0), (HttpRequest) msg));
+//
+// return;
+// }
+// } else {
+// Logger.d("Unable to find session: " + didList.get(0));
+// }
+// }
+//
+// // Prints available sessions to html
+//
+// ctx.writeAndFlush(printsAvailableSessions())
+// .addListener(ChannelFutureListener.CLOSE);
+// return;
+// }
+//
+// if (msg instanceof CoapResponse) {
+// ctx.channel().attr(keyHttpCtx).get()
+// .writeAndFlush(
+// coapResponseToHttpResponse((CoapResponse) msg))
+// .addListener(ChannelFutureListener.CLOSE);
+// return;
+// }
+//
+// // Pass to upper-layer
+// super.channelRead(ctx, msg);
+// }
+//
+// @Override
+// public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
+// cause.printStackTrace();
+// ctx.close();
+// }
+//
+// HttpResponse printsAvailableSessions() {
+//
+// StringBuilder strBuilder = new StringBuilder();
+// List<String> sessions = sessionManager.getSessions();
+//
+// strBuilder.append("<html>");
+// strBuilder.append("<b>Available sessions</b><br>");
+//
+// for (String session : sessions) {
+// strBuilder.append(session);
+// strBuilder.append("<br>");
+// }
+//
+// strBuilder.append("</html>");
+//
+// HttpResponse response = new DefaultFullHttpResponse(
+// HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
+// Unpooled.copiedBuffer(strBuilder.toString(),
+// CharsetUtil.UTF_8));
+// response.headers().set(HttpHeaders.Names.CONTENT_TYPE,
+// "text/html; charset=UTF-8");
+//
+// return response;
+// }
+//
+// HttpResponse httpRequestToSendError() {
+// HttpResponse response = new DefaultFullHttpResponse(
+// HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND,
+// Unpooled.copiedBuffer(
+// "Failure: " + HttpResponseStatus.NOT_FOUND + "\r\n",
+// CharsetUtil.UTF_8));
+// response.headers().set(HttpHeaders.Names.CONTENT_TYPE,
+// "text/html; charset=UTF-8");
+//
+// return response;
+// }
+//
+// CoapRequest httpRequestToCoAPRequest(String uri, HttpRequest httpRequest) {
+// CoapRequest coapRequest;
+//
+// // TODO: coapRequest converter required
+// // coapRequest.getOptions().setUriQuery();
+// if (httpRequest.getMethod() == HttpMethod.GET) {
+// coapRequest = new CoapRequest(CoapMethod.GET);
+// } else if (httpRequest.getMethod() == HttpMethod.PUT) {
+// coapRequest = new CoapRequest(CoapMethod.PUT);
+// } else if (httpRequest.getMethod() == HttpMethod.POST) {
+// coapRequest = new CoapRequest(CoapMethod.POST);
+// } else if (httpRequest.getMethod() == HttpMethod.DELETE) {
+// coapRequest = new CoapRequest(CoapMethod.DELETE);
+// } else {
+// throw new IllegalArgumentException();
+// }
+//
+// coapRequest.setUriPath(uri);
+//
+// return coapRequest;
+// }
+//
+// HttpResponse coapResponseToHttpResponse(CoapResponse coapResponse) {
+//
+// Cbor<HashMap<String, Object>> cbor = new Cbor<HashMap<String, Object>>();
+//
+// HashMap<String, Object> rep = cbor
+// .parsePayloadFromCbor(coapResponse.getPayload(), HashMap.class);
+//
+// StringBuilder strBuilder = new StringBuilder();
+//
+// for (Entry<String, Object> entry : rep.entrySet()) {
+// String key = entry.getKey();
+// String value = entry.getValue().toString();
+// strBuilder.append("Key: " + key + " Value: " + value + "<br>");
+// }
+//
+// HttpResponse httpResponse = new DefaultFullHttpResponse(
+// HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
+// Unpooled.wrappedBuffer(strBuilder.toString()
+// .getBytes(StandardCharsets.UTF_8)));
+//
+// httpResponse.headers().set(HttpHeaders.Names.CONTENT_TYPE,
+// "text/html; charset=UTF-8");
+//
+// // TODO: httpResponse converter required
+//
+// return httpResponse;
+// }
+// }
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/util/Cbor.java b/cloud/stack/src/main/java/org/iotivity/cloud/util/Cbor.java
new file mode 100644 (file)
index 0000000..565cfe9
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.util;
+
+import java.io.IOException;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
+
+public class Cbor<T> {
+    private CBORFactory  f;
+    private ObjectMapper mapper;
+
+    public Cbor() {
+        f = new CBORFactory();
+        mapper = new ObjectMapper(f);
+    }
+
+    @SuppressWarnings("unchecked")
+    public T parsePayloadFromCbor(byte[] cborPayload,
+            Class<? extends Object> class1) {
+        T payload = null;
+        try {
+            payload = (T) mapper.readValue(cborPayload, class1);
+        } catch (IOException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+
+        return payload;
+    }
+
+    public byte[] encodingPayloadToCbor(Object payload) {
+        byte[] cborData = null;
+        try {
+            cborData = mapper.writeValueAsBytes(payload);
+        } catch (JsonProcessingException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+        return cborData;
+    }
+}
\ No newline at end of file
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/util/CoapLogHandler.java b/cloud/stack/src/main/java/org/iotivity/cloud/util/CoapLogHandler.java
new file mode 100644 (file)
index 0000000..f12a807
--- /dev/null
@@ -0,0 +1,179 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.util;
+
+import java.nio.charset.StandardCharsets;
+
+import org.iotivity.cloud.base.protocols.coap.CoapMessage;
+import org.iotivity.cloud.base.protocols.coap.CoapRequest;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelDuplexHandler;
+import io.netty.channel.ChannelHandler.Sharable;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelPromise;
+
+/**
+ *
+ * This class provides a set of APIs to print out logs for CoAP request and
+ * response.
+ *
+ */
+@Sharable
+public class CoapLogHandler extends ChannelDuplexHandler {
+
+    @Override
+    public void write(ChannelHandlerContext ctx, Object msg,
+            ChannelPromise promise) {
+
+        if (msg instanceof CoapMessage) {
+
+            CoapMessage coapMessage = (CoapMessage) msg;
+
+            StringBuilder strBuilder = new StringBuilder();
+            strBuilder.append(getStringCtx(ctx));
+            strBuilder.append(
+                    "\n/******************************************************************************/\n");
+            strBuilder.append(getStringCoapMessage(coapMessage));
+            strBuilder.append(
+                    "\n/******************************************************************************/\n");
+            Logger.d(strBuilder.toString());
+
+        } else if (msg instanceof String) {
+
+            String message = (String) msg;
+
+            StringBuilder strBuilder = new StringBuilder();
+            strBuilder.append(getStringCtx(ctx));
+            strBuilder.append(
+                    "\n/******************************************************************************/\n");
+            strBuilder.append(message);
+            strBuilder.append(
+                    "\n/******************************************************************************/\n");
+            Logger.d(strBuilder.toString());
+
+            ByteBuf outByteBuf = ctx.alloc().buffer();
+            outByteBuf.writeBytes(message.getBytes(StandardCharsets.UTF_8));
+        }
+
+        ctx.write(msg);
+    }
+
+    @Override
+    public void channelRead(ChannelHandlerContext ctx, Object msg)
+            throws Exception {
+
+        if (msg instanceof CoapMessage) {
+
+            CoapMessage coapMessage = (CoapMessage) msg;
+
+            StringBuilder strBuilder = new StringBuilder();
+            strBuilder.append(getStringCtx(ctx));
+            strBuilder.append(
+                    "\n/******************************************************************************/\n");
+            strBuilder.append(getStringCoapMessage(coapMessage));
+            strBuilder.append(
+                    "\n/******************************************************************************/\n");
+            Logger.d(strBuilder.toString());
+
+        } else if (msg instanceof ByteBuf) {
+
+            ByteBuf inByteBuf = (ByteBuf) msg;
+
+            String message = null;
+            StringBuffer strBuffer = new StringBuffer();
+            while (inByteBuf.isReadable()) {
+                strBuffer.append((char) inByteBuf.readByte());
+            }
+            message = strBuffer.toString();
+
+            StringBuilder strBuilder = new StringBuilder();
+            strBuilder.append(getStringCtx(ctx));
+            strBuilder.append(
+                    "\n/******************************************************************************/\n");
+            strBuilder.append(message);
+            strBuilder.append(
+                    "\n/******************************************************************************/\n");
+            Logger.d(strBuilder.toString());
+        }
+
+        ctx.fireChannelRead(msg);
+    }
+
+    private String getStringCtx(ChannelHandlerContext ctx) {
+
+        StringBuilder strBuilder = new StringBuilder();
+
+        strBuilder.append("\n");
+        strBuilder.append("Local Address: ");
+        strBuilder.append(ctx.channel().localAddress().toString());
+
+        strBuilder.append("\n");
+        strBuilder.append("Remote Address: ");
+        strBuilder.append(ctx.channel().remoteAddress().toString());
+
+        return strBuilder.toString();
+    }
+
+    private String getStringCoapMessage(CoapMessage coapMessage) {
+
+        StringBuilder strBuilder = new StringBuilder();
+
+        strBuilder.append("Code: ");
+        strBuilder.append(coapMessage.getCode());
+        strBuilder.append("\n");
+
+        strBuilder.append("Token Length: ");
+        strBuilder.append(coapMessage.getTokenLength());
+        strBuilder.append("\n");
+
+        strBuilder.append("Token Data: ");
+        strBuilder.append(coapMessage.getTokenString());
+        strBuilder.append("\n");
+
+        if (coapMessage instanceof CoapRequest) {
+
+            CoapRequest coapRequest = (CoapRequest) coapMessage;
+
+            strBuilder.append("Option URI_PATH: ");
+            strBuilder.append(coapRequest.getUriPath());
+            strBuilder.append("\n");
+
+            strBuilder.append("Option URI_QUERY: ");
+            strBuilder.append(coapRequest.getUriQuery());
+            strBuilder.append("\n");
+        }
+
+        strBuilder.append("Option CONTENT_FORMAT: ");
+        strBuilder.append(coapMessage.getContentFormatString());
+        strBuilder.append("\n");
+
+        strBuilder.append("Payload Length: ");
+        strBuilder.append(coapMessage.getPayloadSize());
+
+        strBuilder.append("\n");
+        strBuilder.append("Payload Data: ");
+        strBuilder.append(coapMessage.getPayloadString());
+
+        return strBuilder.toString();
+    }
+}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/util/JSONUtil.java b/cloud/stack/src/main/java/org/iotivity/cloud/util/JSONUtil.java
new file mode 100644 (file)
index 0000000..3f7e061
--- /dev/null
@@ -0,0 +1,115 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.util;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+/**
+ * 
+ * This class provides utility for parsing JSON object and converting data to
+ * JSON string.
+ * 
+ */
+public class JSONUtil {
+
+    private static ObjectMapper mapper = new ObjectMapper();
+
+    public static String parseJSON(String jsonString, String key) {
+
+        if (jsonString == null || jsonString.equals(""))
+            return null;
+
+        String value = null;
+
+        try {
+            @SuppressWarnings("unchecked")
+            Map<String, String> jsonMap = mapper.readValue(jsonString,
+                    Map.class);
+            value = jsonMap.get(key);
+        } catch (IOException ioe) {
+            ioe.printStackTrace();
+        }
+
+        return value;
+    }
+    
+    public static ArrayList<String> parseJSON(byte[] payload, String key) {
+
+        if (payload == null)
+            return null;
+
+        ArrayList<String> value = null;
+
+        try {
+            @SuppressWarnings("unchecked")
+            Map<String, ArrayList<String>> jsonMap = mapper.readValue(payload,
+                    Map.class);
+            value = jsonMap.get(key);
+        } catch (IOException ioe) {
+            ioe.printStackTrace();
+        }
+
+        return value;
+    }
+
+    public static Map<String, String> parseJSON(String jsonString)
+            throws JsonParseException, JsonMappingException, IOException {
+
+        Map<String, String> map = null;
+
+        try {
+            @SuppressWarnings("unchecked")
+            Map<String, String> jsonMap = mapper.readValue(jsonString,
+                    Map.class);
+            map = jsonMap;
+        } catch (IOException ioe) {
+            ioe.printStackTrace();
+        }
+
+        return map;
+    }
+
+    public static String writeJSON(HashMap<Object, Object> data) {
+        if (data == null)
+            return null;
+
+        String json = null;
+        try {
+            json = mapper.writeValueAsString(data);
+        } catch (JsonProcessingException e) {
+            e.printStackTrace();
+        }
+
+        if (json == null)
+            json = "{}";
+
+        return json;
+    }
+}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/util/Logger.java b/cloud/stack/src/main/java/org/iotivity/cloud/util/Logger.java
new file mode 100644 (file)
index 0000000..fce3f51
--- /dev/null
@@ -0,0 +1,138 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.util;
+
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+
+public class Logger {
+
+    public static final int VERBOSE = 0;
+    public static final int DEBUG   = 1;
+    public static final int INFO    = 2;
+    public static final int WARNING = 3;
+    public static final int ERROR   = 4;
+
+    private static int logLevel = DEBUG;
+
+    public static void setLogLevel(int level) {
+        logLevel = level;
+    }
+
+    public static void v(String log) {
+        printLog(VERBOSE, log);
+    }
+
+    public static void d(String log) {
+        printLog(DEBUG, log);
+    }
+
+    public static void i(String log) {
+        printLog(INFO, log);
+    }
+
+    public static void w(String log) {
+        printLog(WARNING, log);
+    }
+
+    public static void e(String log) {
+        printLog(ERROR, log);
+    }
+
+    public static void w(String log, Exception ex) {
+        printLog(WARNING, log);
+        ex.printStackTrace();
+    }
+
+    public static void w(String log, Throwable th) {
+        printLog(WARNING, log);
+        th.printStackTrace();
+    }
+
+    public static void e(String log, Exception ex) {
+        printLog(ERROR, log);
+        ex.printStackTrace();
+    }
+
+    public static void e(String log, Throwable th) {
+        printLog(ERROR, log);
+        th.printStackTrace();
+    }
+
+    private static void printLog(int level, String log) {
+
+        if (logLevel > level)
+            return;
+
+        String format = "";
+        format += getTime();
+        format += " [" + getLogLevelString(level) + "]";
+
+        if (level >= ERROR) {
+            format += " [" + getDetailInfo() + "]";
+        }
+
+        format += " " + log;
+
+        System.out.println(format);
+    }
+
+    private static String getDetailInfo() {
+
+        String res = "";
+
+        StackTraceElement ste = Thread.currentThread().getStackTrace()[4];
+        String className = ste.getClassName()
+                .substring(ste.getClassName().lastIndexOf(".") + 1);
+
+        res += ste.getFileName() + ", " + className + "." + ste.getMethodName()
+                + "(), line:" + ste.getLineNumber();
+
+        return res;
+    }
+
+    private static String getTime() {
+        Calendar calendar = Calendar.getInstance();
+        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSS");
+
+        return dateFormat.format(calendar.getTime());
+    }
+
+    private static String getLogLevelString(int level) {
+
+        String res = "";
+
+        if (level == VERBOSE) {
+            res = "V";
+        } else if (level == DEBUG) {
+            res = "D";
+        } else if (level == INFO) {
+            res = "I";
+        } else if (level == WARNING) {
+            res = "W";
+        } else if (level == ERROR) {
+            res = "E";
+        }
+
+        return res;
+    }
+}
diff --git a/cloud/stack/src/test/java/org/iotivity/cloud/base/CoapClientTest.java b/cloud/stack/src/test/java/org/iotivity/cloud/base/CoapClientTest.java
new file mode 100644 (file)
index 0000000..4003cfe
--- /dev/null
@@ -0,0 +1,104 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.base;
+
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+
+import org.iotivity.cloud.base.protocols.coap.CoapRequest;
+import org.iotivity.cloud.base.protocols.coap.enums.CoapMethod;
+import org.iotivity.cloud.util.CoapLogHandler;
+import org.junit.Test;
+
+public class CoapClientTest {
+    @Test
+    public void testAddHandler() throws Exception {
+        CoapServer coapServer = new CoapServer();
+        coapServer.startServer(new InetSocketAddress(5683));
+        CoapClient coapClient = new CoapClient();
+        coapClient.startClient(new InetSocketAddress("127.0.0.1", 5683));
+        coapClient.addHandler(new CoapLogHandler());
+        coapClient.stopClient();
+        coapServer.stopServer();
+    }
+
+    @Test
+    public void testAddHandlerSendRequest() throws Exception {
+        CoapServer coapServer = new CoapServer();
+        coapServer.startServer(new InetSocketAddress(5683));
+
+        CoapClient coapClient = new CoapClient();
+        coapClient.startClient(new InetSocketAddress("127.0.0.1", 5683));
+        coapClient.addHandler(new CoapLogHandler());
+
+        CoapRequest request = new CoapRequest(CoapMethod.GET);
+        coapClient.sendRequest(request);
+
+        CoapRequest request2 = new CoapRequest(CoapMethod.GET);
+        request2.setToken("1234".getBytes(StandardCharsets.UTF_8));
+        coapClient.sendRequest(request2);
+
+        CoapRequest request3 = new CoapRequest(CoapMethod.GET);
+        request3.setPayload("sample1".getBytes(StandardCharsets.UTF_8));
+        coapClient.sendRequest(request3);
+
+        CoapRequest request4 = new CoapRequest(CoapMethod.GET);
+        request4.setToken("5576".getBytes(StandardCharsets.UTF_8));
+        request4.setPayload("sample2".getBytes(StandardCharsets.UTF_8));
+        coapClient.sendRequest(request4);
+
+        CoapRequest request5 = new CoapRequest(CoapMethod.GET);
+        request5.setToken("565761".getBytes(StandardCharsets.UTF_8));
+        coapClient.sendRequest(request5);
+
+        CoapRequest request6 = new CoapRequest(CoapMethod.GET);
+        coapClient.sendRequest(request6);
+
+        CoapRequest request7 = new CoapRequest(CoapMethod.GET);
+        coapClient.sendRequest(request7);
+
+        coapClient.stopClient();
+        coapServer.stopServer();
+    }
+
+    @Test
+    public void testStartStopClient() throws Exception {
+        CoapServer coapServer = new CoapServer();
+        coapServer.startServer(new InetSocketAddress(5683));
+        CoapClient coapClient = new CoapClient();
+        coapClient.startClient(new InetSocketAddress("127.0.0.1", 5683));
+        coapClient.stopClient();
+        coapServer.stopServer();
+    }
+
+    @Test
+    public void testSendRequest() throws Exception {
+        CoapServer coapServer = new CoapServer();
+        coapServer.startServer(new InetSocketAddress(5683));
+        CoapClient coapClient = new CoapClient();
+        coapClient.startClient(new InetSocketAddress("127.0.0.1", 5683));
+        CoapRequest request = new CoapRequest(CoapMethod.GET);
+        coapClient.sendRequest(request);
+        coapClient.stopClient();
+        coapServer.stopServer();
+    }
+}
diff --git a/cloud/stack/src/test/java/org/iotivity/cloud/base/CoapServerTest.java b/cloud/stack/src/test/java/org/iotivity/cloud/base/CoapServerTest.java
new file mode 100644 (file)
index 0000000..f2162ec
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.cloud.base;
+
+import java.net.InetSocketAddress;
+
+import org.iotivity.cloud.util.CoapLogHandler;
+import org.junit.Test;
+
+public class CoapServerTest {
+    @Test
+    public void testAddHandler() throws Exception {
+        CoapServer server = new CoapServer();
+        server.startServer(new InetSocketAddress(5683));
+        server.addHandler(new CoapLogHandler());
+        server.stopServer();
+    }
+
+    @Test
+    public void testStartStopServer() throws Exception {
+        CoapServer server = new CoapServer();
+        server.startServer(new InetSocketAddress(5683));
+        server.stopServer();
+    }
+}
diff --git a/cloud/stack/src/test/java/org/iotivity/cloud/base/ResourceManagerTest.java b/cloud/stack/src/test/java/org/iotivity/cloud/base/ResourceManagerTest.java
new file mode 100644 (file)
index 0000000..c5c6a8c
--- /dev/null
@@ -0,0 +1,66 @@
+package org.iotivity.cloud.base;
+
+import java.net.InetSocketAddress;
+
+import org.iotivity.cloud.base.SessionManagerTest.CoapClientHandler;
+import org.iotivity.cloud.base.protocols.coap.CoapRequest;
+import org.iotivity.cloud.base.protocols.coap.enums.CoapMethod;
+import org.junit.Test;
+
+import io.netty.channel.ChannelHandlerContext;
+
+public class ResourceManagerTest {
+
+    private static class SampleResource extends Resource {
+
+        public SampleResource() {
+            setUri("sampleUri");
+        }
+
+        @Override
+        public void onRequestReceived(ChannelHandlerContext ctx,
+                CoapRequest request) {
+            // TODO Auto-generated method stub
+        }
+    }
+
+    @Test
+    public void testChannelRead0ChannelHandlerContextCoapRequest()
+            throws Exception {
+
+        ResourceManager resourceManager = new ResourceManager();
+
+        resourceManager.registerResource(new SampleResource());
+
+        CoapServer coapServer = new CoapServer();
+        CoapClient coapClient = new CoapClient();
+        CoapClientHandler coapClientHandler = new CoapClientHandler();
+        coapServer.startServer(new InetSocketAddress(5683));
+        coapClient.addHandler(coapClientHandler);
+        coapClient.startClient(new InetSocketAddress("127.0.0.1", 5683));
+
+        CoapRequest request = new CoapRequest(CoapMethod.GET);
+        request.setUriPath("sampleUri");
+
+        resourceManager.channelRead0(coapClientHandler.connectCtx, request);
+
+        coapClient.stopClient();
+        coapServer.stopServer();
+    }
+
+    @Test
+    public void testRegisterResource() {
+        ResourceManager resourceManager = new ResourceManager();
+
+        resourceManager.registerResource(new SampleResource());
+    }
+
+    @Test
+    public void testUnregisterResource() {
+        SampleResource sampleResource = new SampleResource();
+        ResourceManager resourceManager = new ResourceManager();
+
+        resourceManager.registerResource(sampleResource);
+        resourceManager.unregisterResource(sampleResource);
+    }
+}
\ No newline at end of file
diff --git a/cloud/stack/src/test/java/org/iotivity/cloud/base/ResourceTest.java b/cloud/stack/src/test/java/org/iotivity/cloud/base/ResourceTest.java
new file mode 100644 (file)
index 0000000..6e38855
--- /dev/null
@@ -0,0 +1,54 @@
+package org.iotivity.cloud.base;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+import org.iotivity.cloud.base.protocols.coap.CoapRequest;
+import org.junit.Test;
+
+import io.netty.channel.ChannelHandlerContext;
+
+public class ResourceTest {
+
+    private static class SampleResource extends Resource {
+
+        public SampleResource() {
+            setUri("sampleUri");
+        }
+
+        @Override
+        public void onRequestReceived(ChannelHandlerContext ctx,
+                CoapRequest request) {
+            // TODO Auto-generated method stub
+        }
+    }
+
+    @Test
+    public void testGetSetUri() {
+        SampleResource sampleResource = new SampleResource();
+        assertEquals(sampleResource.getUri(), "sampleUri");
+        sampleResource.setUri("sampleUri2");
+        assertEquals(sampleResource.getUri(), "sampleUri2");
+    }
+
+    @Test
+    public void testGetSetType() {
+        SampleResource sampleResource = new SampleResource();
+        assertNull(sampleResource.getType());
+        sampleResource.setType("sampleType");
+        assertEquals(sampleResource.getType(), "sampleType");
+    }
+
+    @Test
+    public void testGetSetRif() {
+        SampleResource sampleResource = new SampleResource();
+        assertNull(sampleResource.getRif());
+        sampleResource.setRif("sampleRif");
+        assertEquals(sampleResource.getRif(), "sampleRif");
+    }
+
+    @Test
+    public void testOnRequestReceived() {
+
+    }
+}
diff --git a/cloud/stack/src/test/java/org/iotivity/cloud/base/SessionManagerTest.java b/cloud/stack/src/test/java/org/iotivity/cloud/base/SessionManagerTest.java
new file mode 100644 (file)
index 0000000..30df055
--- /dev/null
@@ -0,0 +1,99 @@
+package org.iotivity.cloud.base;
+
+import static org.junit.Assert.assertNotNull;
+
+import java.net.InetSocketAddress;
+
+import org.iotivity.cloud.base.protocols.coap.CoapResponse;
+import org.junit.Test;
+
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.SimpleChannelInboundHandler;
+
+public class SessionManagerTest {
+
+    static class CoapClientHandler
+            extends SimpleChannelInboundHandler<CoapResponse> {
+
+        ChannelHandlerContext connectCtx = null;
+
+        @Override
+        public void channelActive(ChannelHandlerContext ctx) throws Exception {
+            connectCtx = ctx;
+        }
+
+        @Override
+        protected void channelRead0(ChannelHandlerContext arg0,
+                CoapResponse arg1) throws Exception {
+            // TODO Auto-generated method stub
+
+        }
+    }
+
+    @Test
+    public void testAddSession() throws Exception {
+        SessionManager sessionManager = new SessionManager();
+        CoapServer coapServer = new CoapServer();
+        CoapClient coapClient = new CoapClient();
+        CoapClientHandler coapClientHandler = new CoapClientHandler();
+        coapServer.startServer(new InetSocketAddress(5683));
+        coapClient.addHandler(coapClientHandler);
+        coapClient.startClient(new InetSocketAddress("127.0.0.1", 5683));
+
+        sessionManager.addSession("sampleDid", coapClientHandler.connectCtx);
+
+        coapClient.stopClient();
+        coapServer.stopServer();
+    }
+
+    @Test
+    public void testRemoveSession() throws Exception {
+        SessionManager sessionManager = new SessionManager();
+        CoapServer coapServer = new CoapServer();
+        CoapClient coapClient = new CoapClient();
+        CoapClientHandler coapClientHandler = new CoapClientHandler();
+        coapServer.startServer(new InetSocketAddress(5683));
+        coapClient.addHandler(coapClientHandler);
+        coapClient.startClient(new InetSocketAddress("127.0.0.1", 5683));
+
+        sessionManager.addSession("sampleDid", coapClientHandler.connectCtx);
+        sessionManager.removeSession("sampleDid");
+
+        coapClient.stopClient();
+        coapServer.stopServer();
+    }
+
+    @Test
+    public void testRemoveSessionByChannel() throws Exception {
+        SessionManager sessionManager = new SessionManager();
+        CoapServer coapServer = new CoapServer();
+        CoapClient coapClient = new CoapClient();
+        CoapClientHandler coapClientHandler = new CoapClientHandler();
+        coapServer.startServer(new InetSocketAddress(5683));
+        coapClient.addHandler(coapClientHandler);
+        coapClient.startClient(new InetSocketAddress("127.0.0.1", 5683));
+
+        sessionManager.addSession("sampleDid", coapClientHandler.connectCtx);
+        sessionManager.removeSessionByChannel(coapClientHandler.connectCtx);
+
+        coapClient.stopClient();
+        coapServer.stopServer();
+    }
+
+    @Test
+    public void testQuerySession() throws Exception {
+        SessionManager sessionManager = new SessionManager();
+        CoapServer coapServer = new CoapServer();
+        CoapClient coapClient = new CoapClient();
+        CoapClientHandler coapClientHandler = new CoapClientHandler();
+        coapServer.startServer(new InetSocketAddress(5683));
+        coapClient.addHandler(coapClientHandler);
+        coapClient.startClient(new InetSocketAddress("127.0.0.1", 5683));
+
+        sessionManager.addSession("sampleDid", coapClientHandler.connectCtx);
+        assertNotNull(sessionManager.querySession("sampleDid"));
+
+        coapClient.stopClient();
+        coapServer.stopServer();
+    }
+}
diff --git a/cloud/stack/src/test/java/org/iotivity/cloud/base/protocols/coap/CoapRequestTest.java b/cloud/stack/src/test/java/org/iotivity/cloud/base/protocols/coap/CoapRequestTest.java
new file mode 100644 (file)
index 0000000..0dbe337
--- /dev/null
@@ -0,0 +1,91 @@
+package org.iotivity.cloud.base.protocols.coap;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+import java.util.List;
+
+import org.iotivity.cloud.base.protocols.coap.enums.CoapMethod;
+import org.junit.Test;
+
+public class CoapRequestTest {
+
+    @Test
+    public void testCoapRequest() {
+        CoapRequest request = new CoapRequest(CoapMethod.GET);
+        assertNotNull(request);
+    }
+
+    @Test
+    public void testGetRequestMethod() {
+        CoapRequest request = new CoapRequest(CoapMethod.GET);
+        assertEquals(request.getRequestMethod(), CoapMethod.GET);
+    }
+
+    @Test
+    public void testSetUriPath() {
+        CoapRequest request = new CoapRequest(CoapMethod.GET);
+        request.setUriPath("sample");
+    }
+
+    @Test
+    public void testGetUriPath() {
+        CoapRequest request = new CoapRequest(CoapMethod.GET);
+        assertNull(request.getUriPath());
+        request.setUriPath("sample");
+        assertEquals(request.getUriPath(), "sample");
+    }
+
+    @Test
+    public void testGetUriPathSegments() {
+        CoapRequest request = new CoapRequest(CoapMethod.GET);
+        assertNull(request.getUriPathSegments());
+        request.setUriPath("parent/child");
+        List<String> list = request.getUriPathSegments();
+        if (list != null) {
+            assertEquals(list.size(), 2);
+        }
+    }
+
+    @Test
+    public void testSetUriQuery() {
+        CoapRequest request = new CoapRequest(CoapMethod.GET);
+        request.setUriQuery("sample=sample");
+    }
+
+    @Test
+    public void testGetUriQuery() {
+        CoapRequest request = new CoapRequest(CoapMethod.GET);
+        assertNull(request.getUriQuery());
+        request.setUriQuery("sample=sample");
+        assertEquals(request.getUriQuery(), "sample=sample");
+    }
+
+    @Test
+    public void testGetUriQuerySegments() {
+        CoapRequest request = new CoapRequest(CoapMethod.GET);
+        assertNull(request.getUriQuerySegments());
+        request.setUriQuery("sample=samplle&sample2=sample2");
+        List<String> list = request.getUriQuerySegments();
+        if (list != null) {
+            assertEquals(list.size(), 2);
+        }
+    }
+
+    @Test
+    public void testClearUriPath() {
+        CoapRequest request = new CoapRequest(CoapMethod.GET);
+        assertNull(request.getUriPathSegments());
+        request.setUriPath("sample");
+        List<String> list = request.getUriPathSegments();
+        if (list != null) {
+            assertEquals(list.size(), 1);
+        }
+        request.clearUriPath();
+        list = request.getUriPathSegments();
+        if (list != null) {
+            assertEquals(list.size(), 0);
+        }
+    }
+}
diff --git a/cloud/stack/src/test/java/org/iotivity/cloud/base/protocols/coap/CoapResponseTest.java b/cloud/stack/src/test/java/org/iotivity/cloud/base/protocols/coap/CoapResponseTest.java
new file mode 100644 (file)
index 0000000..5aaf4d5
--- /dev/null
@@ -0,0 +1,21 @@
+package org.iotivity.cloud.base.protocols.coap;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import org.iotivity.cloud.base.protocols.coap.enums.CoapStatus;
+import org.junit.Test;
+
+public class CoapResponseTest {
+    @Test
+    public void testCoapResponse() throws Exception {
+        CoapResponse response = new CoapResponse(CoapStatus.VALID);
+        assertNotNull(response);
+    }
+
+    @Test
+    public void testGetResponseCode() throws Exception {
+        CoapResponse response = new CoapResponse(CoapStatus.VALID);
+        assertEquals(response.getResponseCode(), CoapStatus.VALID);
+    }
+}
diff --git a/cloud/stack/src/test/java/org/iotivity/cloud/util/UtilTest.java b/cloud/stack/src/test/java/org/iotivity/cloud/util/UtilTest.java
new file mode 100644 (file)
index 0000000..a2f44b1
--- /dev/null
@@ -0,0 +1,55 @@
+package org.iotivity.cloud.util;
+
+import java.net.InetSocketAddress;
+import java.util.HashMap;
+
+import org.iotivity.cloud.base.CoapClient;
+import org.iotivity.cloud.base.CoapServer;
+import org.iotivity.cloud.base.protocols.coap.CoapRequest;
+import org.iotivity.cloud.base.protocols.coap.enums.CoapMethod;
+import org.junit.Test;
+
+public class UtilTest {
+
+    @Test
+    public void testCbor() {
+        HashMap<String, String> setpayloadData = new HashMap<String, String>();
+        setpayloadData.put("test", "test");
+    }
+
+    @Test
+    public void testCoapLogHandler() throws Exception {
+        CoapServer server = new CoapServer();
+        server.startServer(new InetSocketAddress(5683));
+        server.addHandler(new CoapLogHandler());
+
+        CoapClient client = new CoapClient();
+        client.addHandler(new CoapLogHandler());
+        client.startClient(new InetSocketAddress("127.0.0.1", 5683));
+
+        CoapRequest request = new CoapRequest(CoapMethod.PUT);
+        client.sendRequest(request);
+
+        client.stopClient();
+        server.stopServer();
+    }
+
+    @Test
+    public void testJSONUtil() throws Exception {
+        HashMap<Object, Object> setpayloadData = new HashMap<Object, Object>();
+        setpayloadData.put("test", "test");
+
+        String msg = JSONUtil.writeJSON(setpayloadData);
+        JSONUtil.parseJSON(msg, "test");
+        JSONUtil.parseJSON(msg);
+    }
+
+    @Test
+    public void testLogger() throws Exception {
+        Logger.v("VERBOSE test");
+        Logger.d("DEBUG test");
+        Logger.i("INFO test");
+        Logger.e("ERROR test");
+        Logger.w("WARNING test");
+    }
+}
index cf7aaf8..f5bbe31 100644 (file)
@@ -22,9 +22,9 @@
 #define NAMEDEFS_H_
 
 #define EDISON_RESOURCE_INTERFACE "core.edison.resources"
-#define TEMPERATURE_RESOURCE_TYPE "Room.Temperature"
-#define LIGHT_RESOURCE_TYPE "Ambient.Light"
-#define LED_RESOURCE_TYPE "Platform.Led"
+#define TEMPERATURE_RESOURCE_TYPE "room.temperature"
+#define LIGHT_RESOURCE_TYPE "ambient.light"
+#define LED_RESOURCE_TYPE "platform.led"
 #define TEMPERATURE_RESOURCE_ENDPOINT "/temperature"
 #define LIGHT_RESOURCE_ENDPOINT "/ambientlight"
 #define LED_RESOURCE_ENDPOINT "/led"
diff --git a/extlibs/expat/SConscript b/extlibs/expat/SConscript
deleted file mode 100644 (file)
index ece6c2f..0000000
+++ /dev/null
@@ -1,58 +0,0 @@
-##
-# build script for expat library
-#
-# Note:
-#   1) Only a part of source code are required to be built.
-#   2) Download code from https://android.googlesource.com/platform/external/expat.git
-# otherwise, after code is downloaded, it's required to execute './configure' to
-# generate expat_config.h
-#
-##
-
-import os
-
-Import('env')
-
-expat_env = env.Clone()
-SConscript(env.get('SRC_DIR') + '/build_common/tools/UnpackAll.py')
-######################################################################
-# Build flags
-######################################################################
-src_dir = 'expat-2.1.0/'
-
-if not os.path.exists(src_dir):
-       # Prepare source code (download / unpack / run configure)
-       env.Download('expat.tar.gz', 'http://sourceforge.net/projects/expat/files/expat/2.1.0/expat-2.1.0.tar.gz/download')
-       expat_src = env.UnpackAll(src_dir + '/Makefile', 'expat.tar.gz')
-       env.Configure(src_dir, './configure')
-
-expat_env.AppendUnique(CPPPATH = [src_dir, src_dir + 'lib', src_dir + 'vms'])
-
-target_os = env.get('TARGET_OS')
-if target_os not in ['windows', 'winrt']:
-       expat_env.AppendUnique(CCFLAGS = ['-g', '-O2', '-Wall',
-                       '-Wmissing-prototypes', '-Wstrict-prototypes',
-                       '-fexceptions', '-fno-common'])
-       expat_env.AppendUnique(CPPDEFINES = ['HAVE_EXPAT_CONFIG_H'])
-
-if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
-       expat_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
-
-######################################################################
-# Source files and Targets
-######################################################################
-expat_src = [
-       src_dir + 'lib/xmlparse.c',
-       src_dir + 'lib/xmltok.c',
-       src_dir + 'lib/xmlrole.c',
-       ]
-
-libexpat = expat_env.SharedLibrary('expat', expat_src)
-
-######################################################################
-# Install header files and library binary
-######################################################################
-h = expat_env.InstallHeadFile([src_dir + 'lib/expat.h', src_dir + 'lib/expat_external.h'])
-lib = expat_env.InstallLib(libexpat)
-
-expat_env.AppendTarget('libexpat', [h, lib])
diff --git a/extlibs/libstrophe/SConscript b/extlibs/libstrophe/SConscript
new file mode 100644 (file)
index 0000000..f774ecd
--- /dev/null
@@ -0,0 +1,75 @@
+######################################################################
+# ref. raxmpp library build script
+#
+######################################################################
+import os
+import commands
+
+Import('env')
+
+base_dir = env.get('SRC_DIR')
+target_os = env.get('TARGET_OS')
+target_arch = env.get('TARGET_ARCH')
+build_path = Dir('.').abspath
+
+with_ra_ibb = env.get('WITH_RA_IBB')
+PKG_NAME = 'strophe'
+SRC_NAME = 'libstrophe'
+EXT_NAME = 'libstrophe'
+EXT_BASE = 'extlibs/' + EXT_NAME
+EXT_PATH = EXT_BASE + '/' + SRC_NAME
+SRC_PATH = base_dir + '/' + EXT_PATH
+INC_PATH = SRC_PATH
+LIB_PATH = SRC_PATH + '/' + '.libs'
+
+if with_ra_ibb:
+       # check 'libstrophe' library, if it doesn't exits, ask user to download it
+       if not os.path.exists(SRC_NAME):
+               raxmpp_env = Environment(ENV = os.environ)
+               c = raxmpp_env.Action(['git clone https://github.com/strophe/libstrophe.git ' + SRC_NAME,
+                       'cd ' + SRC_NAME + ' && git checkout 527bc0573a52f2af3ecad5b9ef39aeec7b669f77'
+                       ])
+
+               print 'Downloading xmpp library ...'
+               if raxmpp_env.Execute(c):
+                       print '''
+       *********************************** Error: ***********************************************
+       * Please download ra_xmpp as following:
+       *     $ git clone https://github.com/strophe/libstrophe.git extlibs/libstrophe/libstrophe
+       *     $ cd  extlibs/libstrophe/libstrophe
+       *     $ git checkout 527bc0573a52f2af3ecad5b9ef39aeec7b669f77
+       ******************************************************************************************
+       '''
+                       Exit(1)
+               else:
+                       print 'Download xmpp library complete'
+
+       print 'Building with ' + SRC_NAME
+       #print 'base_dir', base_dir
+       #print 'target_os', target_os
+       #print 'target_arch', target_arch
+
+       foo=commands.getoutput('patch -N -p1 -d libstrophe < strophe-xmpp_conn_is_secured.patch')
+       print foo
+
+       os.chdir(SRC_NAME)
+       #sconsflags = ' RELEASE=true' if  env['RELEASE'] else ' RELEASE=false'
+       if not os.path.exists('configure') :
+               foo=commands.getoutput('./bootstrap.sh')
+               print foo
+       if not os.path.exists('config.status') :
+               foo=commands.getoutput('./configure')
+               print foo
+       if not os.path.exists('.libs/libstrophe.a') :
+               foo=commands.getoutput('make libstrophe.la')
+               print foo
+       if not os.path.exists('.libs/libstrophe.a') :
+               print 'Building with ' + SRC_NAME + ' failed.'
+               Exit(2)
+
+       print 'Building with ' + SRC_NAME + ' Completely.'
+       env.AppendUnique(CPPPATH = [INC_PATH], RALIBS = ['strophe', 'ssl', 'crypto', 'resolv'], RALIBPATH = [LIB_PATH], RARPATH = [LIB_PATH])
+
+if env.GetOption('clean') :
+       act = env.Action(['cd ' + SRC_PATH, 'make clean'])
+       env.Execute(act)
diff --git a/extlibs/libstrophe/strophe-xmpp_conn_is_secured.patch b/extlibs/libstrophe/strophe-xmpp_conn_is_secured.patch
new file mode 100644 (file)
index 0000000..958783b
--- /dev/null
@@ -0,0 +1,28 @@
+diff --git a/src/conn.c b/src/conn.c
+index d72386f..e4f0a39 100644
+--- a/src/conn.c
++++ b/src/conn.c
+@@ -742,6 +742,11 @@ void xmpp_conn_disable_tls(xmpp_conn_t * const conn)
+     conn->tls_disabled = 1;
+ }
++int xmpp_conn_is_secured(xmpp_conn_t * const conn)
++{
++    return conn->secured == 1 && conn->tls_failed == 0 ? 1 : 0;
++}
++
+ static void _log_open_tag(xmpp_conn_t *conn, char **attrs)
+ {
+     char buf[4096];
+diff --git a/strophe.h b/strophe.h
+index 80a5390..64b2352 100644
+--- a/strophe.h
++++ b/strophe.h
+@@ -215,6 +215,7 @@ const char *xmpp_conn_get_pass(const xmpp_conn_t * const conn);
+ void xmpp_conn_set_pass(xmpp_conn_t * const conn, const char * const pass);
+ xmpp_ctx_t* xmpp_conn_get_context(xmpp_conn_t * const conn);
+ void xmpp_conn_disable_tls(xmpp_conn_t * const conn);
++int xmpp_conn_is_secured(xmpp_conn_t * const conn);
+ int xmpp_connect_client(xmpp_conn_t * const conn, 
+                         const char * const altdomain,
index 29d5cad..6db32f5 100644 (file)
@@ -31,7 +31,8 @@ src_dir = env.get('SRC_DIR')
 target_os = env.get('TARGET_OS')
 target_arch = env.get('TARGET_ARCH')
 with_ra = env.get('WITH_RA')
-if with_ra:
+with_ra_ibb = env.get('WITH_RA_IBB')
+if with_ra and not with_ra_ibb :
        # check 'raxmppl' library, if it doesn't exits, ask user to download it
        if not os.path.exists('raxmpp'):
                print '''
diff --git a/extlibs/timer/SConscript b/extlibs/timer/SConscript
new file mode 100644 (file)
index 0000000..edcc7ef
--- /dev/null
@@ -0,0 +1,28 @@
+# *****************************************************************
+#
+#  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.
+#
+# *****************************************************************/
+
+Import('env')
+env.AppendUnique(TIMER_SRC = 'timer.c')
+
+libtimer = env.StaticLibrary('libtimer', env.get('TIMER_SRC'), OBJPREFIX='libtimer_')
+env.InstallTarget(libtimer, 'libtimer');
+
+
+
index 29c9ceb..5686d19 100755 (executable)
@@ -104,6 +104,13 @@ long int getRelativeIntervalOfWeek(struct tm* tp)
 
     time(&current_time);
     current = localtime(&current_time);
+
+    if(current == NULL)
+    {
+        printf("ERROR; Getting local time fails\n");
+        return 0;
+    }
+
     midnight = (struct tm* )malloc(sizeof(struct tm));
 
     if(midnight == NULL)
index fc12833..8c6a497 100644 (file)
@@ -37,7 +37,8 @@ if not os.path.exists(cborDir):
 
 cbor_src = [
     os.path.join(cborDir,'src/cborparser.c'),
-    os.path.join(cborDir,'src/cborencoder.c')
+    os.path.join(cborDir,'src/cborencoder.c'),
+    os.path.join(cborDir,'src/cborerrorstrings.c'),
     ]
 
 env['cbor_files'] = cbor_src
diff --git a/extlibs/tinycbor/tinycbor/.tag b/extlibs/tinycbor/tinycbor/.tag
new file mode 100644 (file)
index 0000000..658911e
--- /dev/null
@@ -0,0 +1 @@
+ddd99e434c45f30c186e320a79bb04856d0b0e5a
diff --git a/extlibs/tinycbor/tinycbor/.travis.yml b/extlibs/tinycbor/tinycbor/.travis.yml
new file mode 100644 (file)
index 0000000..f7a5dec
--- /dev/null
@@ -0,0 +1,25 @@
+language: cpp
+os:
+  - linux
+  - osx
+env:
+  - CFLAGS="-O0 -g" QMAKEFLAGS="-config debug" PATH=/opt/qt56/bin:/usr/local/opt/qt5/bin:$PATH
+install:
+  - if [ "${TRAVIS_OS_NAME}" = "linux" ]; then
+        sudo apt-add-repository -y ppa:beineri/opt-qt56;
+        sudo apt-add-repository -y ppa:ubuntu-toolchain-r/test;
+        sudo apt-get update -qq;
+        sudo apt-get install -y qt56base valgrind g++-5;
+    else
+        brew install qt5;
+    fi
+script:
+  - if [ "${TRAVIS_OS_NAME}" = "linux" ]; then
+        sudo ln -sf g++-5 /usr/bin/g++;
+    fi
+  - make -s -f Makefile.configure configure | tee .config
+  - make
+        CFLAGS="$CFLAGS"
+        all tests/Makefile
+  - cd tests && make check -k
+        TESTRUNNER=`which valgrind 2>/dev/null`
diff --git a/extlibs/tinycbor/tinycbor/LICENSE b/extlibs/tinycbor/tinycbor/LICENSE
new file mode 100644 (file)
index 0000000..89de354
--- /dev/null
@@ -0,0 +1,17 @@
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
index bb1798d..256191f 100644 (file)
@@ -6,7 +6,7 @@
 #include <stdlib.h>
 #include <unistd.h>
 
-static char *readfile(const char *fname, size_t *size)
+static uint8_t *readfile(const char *fname, size_t *size)
 {
     struct stat st;
     FILE *f = fopen(fname, "rb");
@@ -14,7 +14,7 @@ static char *readfile(const char *fname, size_t *size)
         return NULL;
     if (fstat(fileno(f), &st) == -1)
         return NULL;
-    char *buf = malloc(st.st_size);
+    uint8_t *buf = malloc(st.st_size);
     *size = fread(buf, st.st_size, 1, f);
     fclose(f);
     return buf;
@@ -26,10 +26,10 @@ static void indent(int nestingLevel)
         puts("  ");
 }
 
-static void dumpbytes(const char *buf, size_t len)
+static void dumpbytes(const uint8_t *buf, size_t len)
 {
     while (len--)
-        printf("%02X ", (unsigned char)*buf++);
+        printf("%02X ", *buf++);
 }
 
 static bool dumprecursive(CborValue *it, int nestingLevel)
@@ -67,19 +67,25 @@ static bool dumprecursive(CborValue *it, int nestingLevel)
             break;
         }
 
-        case CborByteStringType:
+        case CborByteStringType: {
+            uint8_t *buf;
+            size_t n;
+            err = cbor_value_dup_byte_string(it, &buf, &n, it);
+            if (err)
+                return err;     // parse error
+            dumpbytes(buf, n);
+            puts("");
+            free(buf);
+            continue;
+        }
+
         case CborTextStringType: {
             char *buf;
             size_t n;
-            err = cbor_value_dup_string(it, &buf, &n, it);
+            err = cbor_value_dup_text_string(it, &buf, &n, it);
             if (err)
                 return err;     // parse error
-            if (type == CborByteStringType) {
-                dumpbytes(buf, n);
-                puts("");
-            } else {
-                puts(buf);
-            }
+            puts(buf);
             free(buf);
             continue;
         }
@@ -153,7 +159,7 @@ int main(int argc, char **argv)
     }
 
     size_t length;
-    char *buf = readfile(argv[1], &length);
+    uint8_t *buf = readfile(argv[1], &length);
     if (!buf) {
         perror("readfile");
         return 1;
index ab3cae1..61c378a 100644 (file)
@@ -65,8 +65,10 @@ static CborError extract_length(const CborParser *parser, const uint8_t **ptr, s
 {
     uint64_t v;
     CborError err = extract_number(ptr, parser->end, &v);
-    if (err)
+    if (err) {
+        *len = 0;
         return err;
+    }
 
     *len = v;
     if (v != *len)
index d6a430e..a813b76 100644 (file)
@@ -26,6 +26,7 @@
 #include "cbor.h"
 #include "cborconstants_p.h"
 #include "compilersupport_p.h"
+#include <stdlib.h>
 
 static inline uint16_t get16(const uint8_t *ptr)
 {
index 64d5d08..901a94c 100644 (file)
@@ -98,5 +98,4 @@ if not env.get('RELEASE'):
        samples_env.AppendTarget('samples')
 
 env.InstallTarget(libtinydtls, 'libtinydtls');
-env.UserInstallTargetLib(libtinydtls, 'libtinydtls');
 
index 2869aca..6cf26b4 100644 (file)
@@ -4275,7 +4275,6 @@ handle_ccs(dtls_context_t *ctx, dtls_peer_t *peer,
           uint8 *record_header, uint8 *data, size_t data_length)
 {
   int err;
-  dtls_handshake_parameters_t *handshake = peer->handshake_params;
 
   /* A CCS message is handled after a KeyExchange message was
    * received from the client. When security parameters have been
@@ -4291,6 +4290,7 @@ handle_ccs(dtls_context_t *ctx, dtls_peer_t *peer,
   if (data_length < 1 || data[0] != 1)
     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
 
+  dtls_handshake_parameters_t *handshake = peer->handshake_params;
   /* Just change the cipher when we are on the same epoch */
   if (peer->role == DTLS_SERVER) {
     err = calculate_key_block(ctx, handshake, peer,
@@ -4443,6 +4443,10 @@ dtls_handle_message(dtls_context_t *ctx,
           dtls_info("decrypt_verify() failed\n");
          if (peer->state < DTLS_STATE_CONNECTED) {
            dtls_alert_send_from_err(ctx, peer, &peer->session, err);
+
+         (void)CALL(ctx, event, &peer->session,
+           DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_HANDSHAKE_FAILURE);
+
            peer->state = DTLS_STATE_CLOSED;
            /* dtls_stop_retransmission(ctx, peer); */
            dtls_destroy_peer(ctx, peer, 1);
@@ -4479,11 +4483,14 @@ dtls_handle_message(dtls_context_t *ctx,
       if (err < 0) {
        dtls_warn("error while handling ChangeCipherSpec message\n");
        dtls_alert_send_from_err(ctx, peer, session, err);
+        if (peer) {
+         (void)CALL(ctx, event, &peer->session,
+                DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_HANDSHAKE_FAILURE);
 
-       /* invalidate peer */
-       dtls_destroy_peer(ctx, peer, 1);
-       peer = NULL;
-
+         /* invalidate peer */
+         dtls_destroy_peer(ctx, peer, 1);
+         peer = NULL;
+        }
        return err;
       }
       break;
@@ -4535,6 +4542,13 @@ dtls_handle_message(dtls_context_t *ctx,
       if (err < 0) {
        dtls_warn("error while handling handshake packet\n");
        dtls_alert_send_from_err(ctx, peer, session, err);
+
+      if (peer) {
+        (void)CALL(ctx, event, &peer->session,
+              DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_HANDSHAKE_FAILURE);
+        dtls_destroy_peer(ctx, peer, 1);
+      }
+
        return err;
       }
       if (peer && peer->state == DTLS_STATE_CONNECTED) {
@@ -4587,6 +4601,7 @@ dtls_new_context(void *app_data) {
 
   if (fread(buf, 1, sizeof(buf), urandom) != sizeof(buf)) {
     dtls_emerg("cannot initialize PRNG\n");
+    fclose(urandom);
     return NULL;
   }
 
index 048bacd..75877fd 100644 (file)
@@ -71,9 +71,9 @@ typedef unsigned char uint48[6];
 #endif
 
 /** Known cipher suites.*/
-typedef enum { 
+typedef enum {
   TLS_NULL_WITH_NULL_NULL = 0x0000,   /**< NULL cipher  */
-  TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256 = 0xC018, /**< see RFC 4492 */
+  TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256 = 0xFF00, /**< OCF Vendor Specific Ciphersuite */
   TLS_PSK_WITH_AES_128_CCM_8 = 0xC0A8, /**< see RFC 6655 */
   TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256 = 0xC037, /**< see RFC 5489 */
   TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 = 0xC0AE /**< see RFC 7251 */
@@ -112,7 +112,7 @@ typedef enum {
 #define TLS_EXT_SIG_HASH_ALGO_SHA256           4 /* see RFC 5246 */
 #define TLS_EXT_SIG_HASH_ALGO_ECDSA            3 /* see RFC 5246 */
 
-/** 
+/**
  * XORs \p n bytes byte-by-byte starting at \p y to the memory area
  * starting at \p x. */
 static inline void
@@ -145,7 +145,7 @@ equals(unsigned char *a, unsigned char *b, size_t len) {
 #ifdef HAVE_FLS
 #define dtls_fls(i) fls(i)
 #else
-static inline int 
+static inline int
 dtls_fls(unsigned int i) {
   int n;
   for (n = 0; i; n++)
index d9c5e53..afdfaea 100644 (file)
  *  see http://www.aarongifford.com/ */
 #include "sha2/sha2.h"
 
-typedef SHA256_CTX dtls_hash_ctx;
+typedef DTLS_SHA256_CTX dtls_hash_ctx;
 typedef dtls_hash_ctx *dtls_hash_t;
-#define DTLS_HASH_CTX_SIZE sizeof(SHA256_CTX)
+#define DTLS_HASH_CTX_SIZE sizeof(DTLS_SHA256_CTX)
 
 static inline void
 dtls_hash_init(dtls_hash_t ctx) {
-  SHA256_Init((SHA256_CTX *)ctx);
+  DTLS_SHA256_Init((DTLS_SHA256_CTX *)ctx);
 }
 
 static inline void 
 dtls_hash_update(dtls_hash_t ctx, const unsigned char *input, size_t len) {
-  SHA256_Update((SHA256_CTX *)ctx, input, len);
+  DTLS_SHA256_Update((DTLS_SHA256_CTX *)ctx, input, len);
 }
 
 static inline size_t
 dtls_hash_finalize(unsigned char *buf, dtls_hash_t ctx) {
-  SHA256_Final(buf, (SHA256_CTX *)ctx);
-  return SHA256_DIGEST_LENGTH;
+  DTLS_SHA256_Final(buf, (DTLS_SHA256_CTX *)ctx);
+  return DTLS_SHA256_DIGEST_LENGTH;
 }
 #endif /* WITH_SHA256 */
 
index 2578f17..4d729e7 100644 (file)
@@ -146,9 +146,9 @@ typedef u_int64_t sha2_word64;      /* Exactly 8 bytes */
 
 /*** SHA-256/384/512 Various Length Definitions ***********************/
 /* NOTE: Most of these are in sha2.h */
-#define SHA256_SHORT_BLOCK_LENGTH      (SHA256_BLOCK_LENGTH - 8)
-#define SHA384_SHORT_BLOCK_LENGTH      (SHA384_BLOCK_LENGTH - 16)
-#define SHA512_SHORT_BLOCK_LENGTH      (SHA512_BLOCK_LENGTH - 16)
+#define DTLS_SHA256_SHORT_BLOCK_LENGTH (DTLS_SHA256_BLOCK_LENGTH - 8)
+#define DTLS_SHA384_SHORT_BLOCK_LENGTH (DTLS_SHA384_BLOCK_LENGTH - 16)
+#define DTLS_SHA512_SHORT_BLOCK_LENGTH (DTLS_SHA512_BLOCK_LENGTH - 16)
 
 
 /*** ENDIAN REVERSAL MACROS *******************************************/
@@ -245,9 +245,9 @@ typedef u_int64_t sha2_word64;      /* Exactly 8 bytes */
  * library -- they are intended for private internal visibility/use
  * only.
  */
-void SHA512_Last(SHA512_CTX*);
-void SHA256_Transform(SHA256_CTX*, const sha2_word32*);
-void SHA512_Transform(SHA512_CTX*, const sha2_word64*);
+void DTLS_SHA512_Last(DTLS_SHA512_CTX*);
+void DTLS_SHA256_Transform(DTLS_SHA256_CTX*, const sha2_word32*);
+void DTLS_SHA512_Transform(DTLS_SHA512_CTX*, const sha2_word64*);
 
 #ifdef WITH_SHA256
 /*** SHA-XYZ INITIAL HASH VALUES AND CONSTANTS ************************/
@@ -367,12 +367,12 @@ static const char *sha2_hex_digits = "0123456789abcdef";
 
 /*** SHA-256: *********************************************************/
 #ifdef WITH_SHA256
-void SHA256_Init(SHA256_CTX* context) {
-       if (context == (SHA256_CTX*)0) {
+void DTLS_SHA256_Init(DTLS_SHA256_CTX* context) {
+       if (context == (DTLS_SHA256_CTX*)0) {
                return;
        }
-       MEMCPY_BCOPY(context->state, sha256_initial_hash_value, SHA256_DIGEST_LENGTH);
-       MEMSET_BZERO(context->buffer, SHA256_BLOCK_LENGTH);
+       MEMCPY_BCOPY(context->state, sha256_initial_hash_value, DTLS_SHA256_DIGEST_LENGTH);
+       MEMSET_BZERO(context->buffer, DTLS_SHA256_BLOCK_LENGTH);
        context->bitcount = 0;
 }
 
@@ -413,7 +413,7 @@ void SHA256_Init(SHA256_CTX* context) {
        (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \
        j++
 
-void SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) {
+void DTLS_SHA256_Transform(DTLS_SHA256_CTX* context, const sha2_word32* data) {
        sha2_word32     a, b, c, d, e, f, g, h, s0, s1;
        sha2_word32     T1, *W256;
        int             j;
@@ -471,7 +471,7 @@ void SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) {
 
 #else /* SHA2_UNROLL_TRANSFORM */
 
-void SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) {
+void DTLS_SHA256_Transform(DTLS_SHA256_CTX* context, const sha2_word32* data) {
        sha2_word32     a, b, c, d, e, f, g, h, s0, s1;
        sha2_word32     T1, T2, *W256;
        int             j;
@@ -551,7 +551,7 @@ void SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) {
 
 #endif /* SHA2_UNROLL_TRANSFORM */
 
-void SHA256_Update(SHA256_CTX* context, const sha2_byte *data, size_t len) {
+void DTLS_SHA256_Update(DTLS_SHA256_CTX* context, const sha2_byte *data, size_t len) {
        unsigned int    freespace, usedspace;
 
        if (len == 0) {
@@ -560,12 +560,12 @@ void SHA256_Update(SHA256_CTX* context, const sha2_byte *data, size_t len) {
        }
 
        /* Sanity check: */
-       assert(context != (SHA256_CTX*)0 && data != (sha2_byte*)0);
+       assert(context != (DTLS_SHA256_CTX*)0 && data != (sha2_byte*)0);
 
-       usedspace = (context->bitcount >> 3) % SHA256_BLOCK_LENGTH;
+       usedspace = (context->bitcount >> 3) % DTLS_SHA256_BLOCK_LENGTH;
        if (usedspace > 0) {
                /* Calculate how much free space is available in the buffer */
-               freespace = SHA256_BLOCK_LENGTH - usedspace;
+               freespace = DTLS_SHA256_BLOCK_LENGTH - usedspace;
 
                if (len >= freespace) {
                        /* Fill the buffer completely and process it */
@@ -573,7 +573,7 @@ void SHA256_Update(SHA256_CTX* context, const sha2_byte *data, size_t len) {
                        context->bitcount += freespace << 3;
                        len -= freespace;
                        data += freespace;
-                       SHA256_Transform(context, (sha2_word32*)context->buffer);
+                       DTLS_SHA256_Transform(context, (sha2_word32*)context->buffer);
                } else {
                        /* The buffer is not yet full */
                        MEMCPY_BCOPY(&context->buffer[usedspace], data, len);
@@ -583,12 +583,12 @@ void SHA256_Update(SHA256_CTX* context, const sha2_byte *data, size_t len) {
                        return;
                }
        }
-       while (len >= SHA256_BLOCK_LENGTH) {
+       while (len >= DTLS_SHA256_BLOCK_LENGTH) {
                /* Process as many complete blocks as we can */
-               SHA256_Transform(context, (sha2_word32*)data);
-               context->bitcount += SHA256_BLOCK_LENGTH << 3;
-               len -= SHA256_BLOCK_LENGTH;
-               data += SHA256_BLOCK_LENGTH;
+               DTLS_SHA256_Transform(context, (sha2_word32*)data);
+               context->bitcount += DTLS_SHA256_BLOCK_LENGTH << 3;
+               len -= DTLS_SHA256_BLOCK_LENGTH;
+               data += DTLS_SHA256_BLOCK_LENGTH;
        }
        if (len > 0) {
                /* There's left-overs, so save 'em */
@@ -599,16 +599,16 @@ void SHA256_Update(SHA256_CTX* context, const sha2_byte *data, size_t len) {
        usedspace = freespace = 0;
 }
 
-void SHA256_Final(sha2_byte digest[], SHA256_CTX* context) {
+void DTLS_SHA256_Final(sha2_byte digest[], DTLS_SHA256_CTX* context) {
        sha2_word32     *d = (sha2_word32*)digest;
        unsigned int    usedspace;
 
        /* Sanity check: */
-       assert(context != (SHA256_CTX*)0);
+       assert(context != (DTLS_SHA256_CTX*)0);
 
        /* If no digest buffer is passed, we don't bother doing this: */
        if (digest != (sha2_byte*)0) {
-               usedspace = (context->bitcount >> 3) % SHA256_BLOCK_LENGTH;
+               usedspace = (context->bitcount >> 3) % DTLS_SHA256_BLOCK_LENGTH;
 #if BYTE_ORDER == LITTLE_ENDIAN
                /* Convert FROM host byte order */
                REVERSE64(context->bitcount,context->bitcount);
@@ -617,31 +617,31 @@ void SHA256_Final(sha2_byte digest[], SHA256_CTX* context) {
                        /* Begin padding with a 1 bit: */
                        context->buffer[usedspace++] = 0x80;
 
-                       if (usedspace <= SHA256_SHORT_BLOCK_LENGTH) {
+                       if (usedspace <= DTLS_SHA256_SHORT_BLOCK_LENGTH) {
                                /* Set-up for the last transform: */
-                               MEMSET_BZERO(&context->buffer[usedspace], SHA256_SHORT_BLOCK_LENGTH - usedspace);
+                               MEMSET_BZERO(&context->buffer[usedspace], DTLS_SHA256_SHORT_BLOCK_LENGTH - usedspace);
                        } else {
-                               if (usedspace < SHA256_BLOCK_LENGTH) {
-                                       MEMSET_BZERO(&context->buffer[usedspace], SHA256_BLOCK_LENGTH - usedspace);
+                               if (usedspace < DTLS_SHA256_BLOCK_LENGTH) {
+                                       MEMSET_BZERO(&context->buffer[usedspace], DTLS_SHA256_BLOCK_LENGTH - usedspace);
                                }
                                /* Do second-to-last transform: */
-                               SHA256_Transform(context, (sha2_word32*)context->buffer);
+                               DTLS_SHA256_Transform(context, (sha2_word32*)context->buffer);
 
                                /* And set-up for the last transform: */
-                               MEMSET_BZERO(context->buffer, SHA256_SHORT_BLOCK_LENGTH);
+                               MEMSET_BZERO(context->buffer, DTLS_SHA256_SHORT_BLOCK_LENGTH);
                        }
                } else {
                        /* Set-up for the last transform: */
-                       MEMSET_BZERO(context->buffer, SHA256_SHORT_BLOCK_LENGTH);
+                       MEMSET_BZERO(context->buffer, DTLS_SHA256_SHORT_BLOCK_LENGTH);
 
                        /* Begin padding with a 1 bit: */
                        *context->buffer = 0x80;
                }
                /* Set the bit count: */
-               *(sha2_word64*)&context->buffer[SHA256_SHORT_BLOCK_LENGTH] = context->bitcount;
+               *(sha2_word64*)&context->buffer[DTLS_SHA256_SHORT_BLOCK_LENGTH] = context->bitcount;
 
                /* Final transform: */
-               SHA256_Transform(context, (sha2_word32*)context->buffer);
+               DTLS_SHA256_Transform(context, (sha2_word32*)context->buffer);
 
 #if BYTE_ORDER == LITTLE_ENDIAN
                {
@@ -653,7 +653,7 @@ void SHA256_Final(sha2_byte digest[], SHA256_CTX* context) {
                        }
                }
 #else
-               MEMCPY_BCOPY(d, context->state, SHA256_DIGEST_LENGTH);
+               MEMCPY_BCOPY(d, context->state, DTLS_SHA256_DIGEST_LENGTH);
 #endif
        }
 
@@ -662,17 +662,17 @@ void SHA256_Final(sha2_byte digest[], SHA256_CTX* context) {
        usedspace = 0;
 }
 
-char *SHA256_End(SHA256_CTX* context, char buffer[]) {
-       sha2_byte       digest[SHA256_DIGEST_LENGTH], *d = digest;
+char *DTLS_SHA256_End(DTLS_SHA256_CTX* context, char buffer[]) {
+       sha2_byte       digest[DTLS_SHA256_DIGEST_LENGTH], *d = digest;
        int             i;
 
        /* Sanity check: */
-       assert(context != (SHA256_CTX*)0);
+       assert(context != (DTLS_SHA256_CTX*)0);
 
        if (buffer != (char*)0) {
-               SHA256_Final(digest, context);
+               DTLS_SHA256_Final(digest, context);
 
-               for (i = 0; i < SHA256_DIGEST_LENGTH; i++) {
+               for (i = 0; i < DTLS_SHA256_DIGEST_LENGTH; i++) {
                        *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4];
                        *buffer++ = sha2_hex_digits[*d & 0x0f];
                        d++;
@@ -681,27 +681,27 @@ char *SHA256_End(SHA256_CTX* context, char buffer[]) {
        } else {
                MEMSET_BZERO(context, sizeof(*context));
        }
-       MEMSET_BZERO(digest, SHA256_DIGEST_LENGTH);
+       MEMSET_BZERO(digest, DTLS_SHA256_DIGEST_LENGTH);
        return buffer;
 }
 
-char* SHA256_Data(const sha2_byte* data, size_t len, char digest[SHA256_DIGEST_STRING_LENGTH]) {
-       SHA256_CTX      context;
+char* DTLS_SHA256_Data(const sha2_byte* data, size_t len, char digest[DTLS_SHA256_DIGEST_STRING_LENGTH]) {
+       DTLS_SHA256_CTX context;
 
-       SHA256_Init(&context);
-       SHA256_Update(&context, data, len);
-       return SHA256_End(&context, digest);
+       DTLS_SHA256_Init(&context);
+       DTLS_SHA256_Update(&context, data, len);
+       return DTLS_SHA256_End(&context, digest);
 }
 #endif
 
 /*** SHA-512: *********************************************************/
 #ifdef WITH_SHA512
-void SHA512_Init(SHA512_CTX* context) {
-       if (context == (SHA512_CTX*)0) {
+void DTLS_SHA512_Init(DTLS_SHA512_CTX* context) {
+       if (context == (DTLS_SHA512_CTX*)0) {
                return;
        }
-       MEMCPY_BCOPY(context->state, sha512_initial_hash_value, SHA512_DIGEST_LENGTH);
-       MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH);
+       MEMCPY_BCOPY(context->state, sha512_initial_hash_value, DTLS_SHA512_DIGEST_LENGTH);
+       MEMSET_BZERO(context->buffer, DTLS_SHA512_BLOCK_LENGTH);
        context->bitcount[0] = context->bitcount[1] =  0;
 }
 
@@ -741,7 +741,7 @@ void SHA512_Init(SHA512_CTX* context) {
        (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \
        j++
 
-void SHA512_Transform(SHA512_CTX* context, const sha2_word64* data) {
+void DTLS_SHA512_Transform(DTLS_SHA512_CTX* context, const sha2_word64* data) {
        sha2_word64     a, b, c, d, e, f, g, h, s0, s1;
        sha2_word64     T1, *W512 = (sha2_word64*)context->buffer;
        int             j;
@@ -796,7 +796,7 @@ void SHA512_Transform(SHA512_CTX* context, const sha2_word64* data) {
 
 #else /* SHA2_UNROLL_TRANSFORM */
 
-void SHA512_Transform(SHA512_CTX* context, const sha2_word64* data) {
+void DTLS_SHA512_Transform(DTLS_SHA512_CTX* context, const sha2_word64* data) {
        sha2_word64     a, b, c, d, e, f, g, h, s0, s1;
        sha2_word64     T1, T2, *W512 = (sha2_word64*)context->buffer;
        int             j;
@@ -874,7 +874,7 @@ void SHA512_Transform(SHA512_CTX* context, const sha2_word64* data) {
 
 #endif /* SHA2_UNROLL_TRANSFORM */
 
-void SHA512_Update(SHA512_CTX* context, const sha2_byte *data, size_t len) {
+void DTLS_SHA512_Update(DTLS_SHA512_CTX* context, const sha2_byte *data, size_t len) {
        unsigned int    freespace, usedspace;
 
        if (len == 0) {
@@ -883,12 +883,12 @@ void SHA512_Update(SHA512_CTX* context, const sha2_byte *data, size_t len) {
        }
 
        /* Sanity check: */
-       assert(context != (SHA512_CTX*)0 && data != (sha2_byte*)0);
+       assert(context != (DTLS_SHA512_CTX*)0 && data != (sha2_byte*)0);
 
-       usedspace = (context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH;
+       usedspace = (context->bitcount[0] >> 3) % DTLS_SHA512_BLOCK_LENGTH;
        if (usedspace > 0) {
                /* Calculate how much free space is available in the buffer */
-               freespace = SHA512_BLOCK_LENGTH - usedspace;
+               freespace = DTLS_SHA512_BLOCK_LENGTH - usedspace;
 
                if (len >= freespace) {
                        /* Fill the buffer completely and process it */
@@ -896,7 +896,7 @@ void SHA512_Update(SHA512_CTX* context, const sha2_byte *data, size_t len) {
                        ADDINC128(context->bitcount, freespace << 3);
                        len -= freespace;
                        data += freespace;
-                       SHA512_Transform(context, (sha2_word64*)context->buffer);
+                       DTLS_SHA512_Transform(context, (sha2_word64*)context->buffer);
                } else {
                        /* The buffer is not yet full */
                        MEMCPY_BCOPY(&context->buffer[usedspace], data, len);
@@ -906,12 +906,12 @@ void SHA512_Update(SHA512_CTX* context, const sha2_byte *data, size_t len) {
                        return;
                }
        }
-       while (len >= SHA512_BLOCK_LENGTH) {
+       while (len >= DTLS_SHA512_BLOCK_LENGTH) {
                /* Process as many complete blocks as we can */
-               SHA512_Transform(context, (sha2_word64*)data);
-               ADDINC128(context->bitcount, SHA512_BLOCK_LENGTH << 3);
-               len -= SHA512_BLOCK_LENGTH;
-               data += SHA512_BLOCK_LENGTH;
+               DTLS_SHA512_Transform(context, (sha2_word64*)data);
+               ADDINC128(context->bitcount, DTLS_SHA512_BLOCK_LENGTH << 3);
+               len -= DTLS_SHA512_BLOCK_LENGTH;
+               data += DTLS_SHA512_BLOCK_LENGTH;
        }
        if (len > 0) {
                /* There's left-overs, so save 'em */
@@ -922,10 +922,10 @@ void SHA512_Update(SHA512_CTX* context, const sha2_byte *data, size_t len) {
        usedspace = freespace = 0;
 }
 
-void SHA512_Last(SHA512_CTX* context) {
+void DTLS_SHA512_Last(DTLS_SHA512_CTX* context) {
        unsigned int    usedspace;
 
-       usedspace = (context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH;
+       usedspace = (context->bitcount[0] >> 3) % DTLS_SHA512_BLOCK_LENGTH;
 #if BYTE_ORDER == LITTLE_ENDIAN
        /* Convert FROM host byte order */
        REVERSE64(context->bitcount[0],context->bitcount[0]);
@@ -935,43 +935,43 @@ void SHA512_Last(SHA512_CTX* context) {
                /* Begin padding with a 1 bit: */
                context->buffer[usedspace++] = 0x80;
 
-               if (usedspace <= SHA512_SHORT_BLOCK_LENGTH) {
+               if (usedspace <= DTLS_SHA512_SHORT_BLOCK_LENGTH) {
                        /* Set-up for the last transform: */
-                       MEMSET_BZERO(&context->buffer[usedspace], SHA512_SHORT_BLOCK_LENGTH - usedspace);
+                       MEMSET_BZERO(&context->buffer[usedspace], DTLS_SHA512_SHORT_BLOCK_LENGTH - usedspace);
                } else {
-                       if (usedspace < SHA512_BLOCK_LENGTH) {
-                               MEMSET_BZERO(&context->buffer[usedspace], SHA512_BLOCK_LENGTH - usedspace);
+                       if (usedspace < DTLS_SHA512_BLOCK_LENGTH) {
+                               MEMSET_BZERO(&context->buffer[usedspace], DTLS_SHA512_BLOCK_LENGTH - usedspace);
                        }
                        /* Do second-to-last transform: */
-                       SHA512_Transform(context, (sha2_word64*)context->buffer);
+                       DTLS_SHA512_Transform(context, (sha2_word64*)context->buffer);
 
                        /* And set-up for the last transform: */
-                       MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH - 2);
+                       MEMSET_BZERO(context->buffer, DTLS_SHA512_BLOCK_LENGTH - 2);
                }
        } else {
                /* Prepare for final transform: */
-               MEMSET_BZERO(context->buffer, SHA512_SHORT_BLOCK_LENGTH);
+               MEMSET_BZERO(context->buffer, DTLS_SHA512_SHORT_BLOCK_LENGTH);
 
                /* Begin padding with a 1 bit: */
                *context->buffer = 0x80;
        }
        /* Store the length of input data (in bits): */
-       *(sha2_word64*)&context->buffer[SHA512_SHORT_BLOCK_LENGTH] = context->bitcount[1];
-       *(sha2_word64*)&context->buffer[SHA512_SHORT_BLOCK_LENGTH+8] = context->bitcount[0];
+       *(sha2_word64*)&context->buffer[DTLS_SHA512_SHORT_BLOCK_LENGTH] = context->bitcount[1];
+       *(sha2_word64*)&context->buffer[DTLS_SHA512_SHORT_BLOCK_LENGTH+8] = context->bitcount[0];
 
        /* Final transform: */
-       SHA512_Transform(context, (sha2_word64*)context->buffer);
+       DTLS_SHA512_Transform(context, (sha2_word64*)context->buffer);
 }
 
-void SHA512_Final(sha2_byte digest[], SHA512_CTX* context) {
+void DTLS_SHA512_Final(sha2_byte digest[], DTLS_SHA512_CTX* context) {
        sha2_word64     *d = (sha2_word64*)digest;
 
        /* Sanity check: */
-       assert(context != (SHA512_CTX*)0);
+       assert(context != (DTLS_SHA512_CTX*)0);
 
        /* If no digest buffer is passed, we don't bother doing this: */
        if (digest != (sha2_byte*)0) {
-               SHA512_Last(context);
+               DTLS_SHA512_Last(context);
 
                /* Save the hash data for output: */
 #if BYTE_ORDER == LITTLE_ENDIAN
@@ -984,7 +984,7 @@ void SHA512_Final(sha2_byte digest[], SHA512_CTX* context) {
                        }
                }
 #else
-               MEMCPY_BCOPY(d, context->state, SHA512_DIGEST_LENGTH);
+               MEMCPY_BCOPY(d, context->state, DTLS_SHA512_DIGEST_LENGTH);
 #endif
        }
 
@@ -992,17 +992,17 @@ void SHA512_Final(sha2_byte digest[], SHA512_CTX* context) {
        MEMSET_BZERO(context, sizeof(context));
 }
 
-char *SHA512_End(SHA512_CTX* context, char buffer[]) {
-       sha2_byte       digest[SHA512_DIGEST_LENGTH], *d = digest;
+char *DTLS_SHA512_End(DTLS_SHA512_CTX* context, char buffer[]) {
+       sha2_byte       digest[DTLS_SHA512_DIGEST_LENGTH], *d = digest;
        int             i;
 
        /* Sanity check: */
-       assert(context != (SHA512_CTX*)0);
+       assert(context != (DTLS_SHA512_CTX*)0);
 
        if (buffer != (char*)0) {
-               SHA512_Final(digest, context);
+               DTLS_SHA512_Final(digest, context);
 
-               for (i = 0; i < SHA512_DIGEST_LENGTH; i++) {
+               for (i = 0; i < DTLS_SHA512_DIGEST_LENGTH; i++) {
                        *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4];
                        *buffer++ = sha2_hex_digits[*d & 0x0f];
                        d++;
@@ -1011,43 +1011,43 @@ char *SHA512_End(SHA512_CTX* context, char buffer[]) {
        } else {
                MEMSET_BZERO(context, sizeof(context));
        }
-       MEMSET_BZERO(digest, SHA512_DIGEST_LENGTH);
+       MEMSET_BZERO(digest, DTLS_SHA512_DIGEST_LENGTH);
        return buffer;
 }
 
-char* SHA512_Data(const sha2_byte* data, size_t len, char digest[SHA512_DIGEST_STRING_LENGTH]) {
-       SHA512_CTX      context;
+char* DTLS_SHA512_Data(const sha2_byte* data, size_t len, char digest[DTLS_SHA512_DIGEST_STRING_LENGTH]) {
+       DTLS_SHA512_CTX context;
 
-       SHA512_Init(&context);
-       SHA512_Update(&context, data, len);
-       return SHA512_End(&context, digest);
+       DTLS_SHA512_Init(&context);
+       DTLS_SHA512_Update(&context, data, len);
+       return DTLS_SHA512_End(&context, digest);
 }
 #endif
 
 /*** SHA-384: *********************************************************/
 #ifdef WITH_SHA384
-void SHA384_Init(SHA384_CTX* context) {
-       if (context == (SHA384_CTX*)0) {
+void DTLS_SHA384_Init(DTLS_SHA384_CTX* context) {
+       if (context == (DTLS_SHA384_CTX*)0) {
                return;
        }
-       MEMCPY_BCOPY(context->state, sha384_initial_hash_value, SHA512_DIGEST_LENGTH);
-       MEMSET_BZERO(context->buffer, SHA384_BLOCK_LENGTH);
+       MEMCPY_BCOPY(context->state, sha384_initial_hash_value, DTLS_SHA512_DIGEST_LENGTH);
+       MEMSET_BZERO(context->buffer, DTLS_SHA384_BLOCK_LENGTH);
        context->bitcount[0] = context->bitcount[1] = 0;
 }
 
-void SHA384_Update(SHA384_CTX* context, const sha2_byte* data, size_t len) {
-       SHA512_Update((SHA512_CTX*)context, data, len);
+void DTLS_SHA384_Update(DTLS_SHA384_CTX* context, const sha2_byte* data, size_t len) {
+       DTLS_SHA512_Update((DTLS_SHA512_CTX*)context, data, len);
 }
 
-void SHA384_Final(sha2_byte digest[], SHA384_CTX* context) {
+void DTLS_SHA384_Final(sha2_byte digest[], DTLS_SHA384_CTX* context) {
        sha2_word64     *d = (sha2_word64*)digest;
 
        /* Sanity check: */
-       assert(context != (SHA384_CTX*)0);
+       assert(context != (DTLS_SHA384_CTX*)0);
 
        /* If no digest buffer is passed, we don't bother doing this: */
        if (digest != (sha2_byte*)0) {
-               SHA512_Last((SHA512_CTX*)context);
+               DTLS_SHA512_Last((DTLS_SHA512_CTX*)context);
 
                /* Save the hash data for output: */
 #if BYTE_ORDER == LITTLE_ENDIAN
@@ -1060,7 +1060,7 @@ void SHA384_Final(sha2_byte digest[], SHA384_CTX* context) {
                        }
                }
 #else
-               MEMCPY_BCOPY(d, context->state, SHA384_DIGEST_LENGTH);
+               MEMCPY_BCOPY(d, context->state, DTLS_SHA384_DIGEST_LENGTH);
 #endif
        }
 
@@ -1068,17 +1068,17 @@ void SHA384_Final(sha2_byte digest[], SHA384_CTX* context) {
        MEMSET_BZERO(context, sizeof(context));
 }
 
-char *SHA384_End(SHA384_CTX* context, char buffer[]) {
-       sha2_byte       digest[SHA384_DIGEST_LENGTH], *d = digest;
+char *DTLS_SHA384_End(DTLS_SHA384_CTX* context, char buffer[]) {
+       sha2_byte       digest[DTLS_SHA384_DIGEST_LENGTH], *d = digest;
        int             i;
 
        /* Sanity check: */
-       assert(context != (SHA384_CTX*)0);
+       assert(context != (DTLS_SHA384_CTX*)0);
 
        if (buffer != (char*)0) {
-               SHA384_Final(digest, context);
+               DTLS_SHA384_Final(digest, context);
 
-               for (i = 0; i < SHA384_DIGEST_LENGTH; i++) {
+               for (i = 0; i < DTLS_SHA384_DIGEST_LENGTH; i++) {
                        *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4];
                        *buffer++ = sha2_hex_digits[*d & 0x0f];
                        d++;
@@ -1087,15 +1087,15 @@ char *SHA384_End(SHA384_CTX* context, char buffer[]) {
        } else {
                MEMSET_BZERO(context, sizeof(context));
        }
-       MEMSET_BZERO(digest, SHA384_DIGEST_LENGTH);
+       MEMSET_BZERO(digest, DTLS_SHA384_DIGEST_LENGTH);
        return buffer;
 }
 
-char* SHA384_Data(const sha2_byte* data, size_t len, char digest[SHA384_DIGEST_STRING_LENGTH]) {
-       SHA384_CTX      context;
+char* DTLS_SHA384_Data(const sha2_byte* data, size_t len, char digest[DTLS_SHA384_DIGEST_STRING_LENGTH]) {
+       DTLS_SHA384_CTX context;
 
-       SHA384_Init(&context);
-       SHA384_Update(&context, data, len);
-       return SHA384_End(&context, digest);
+       DTLS_SHA384_Init(&context);
+       DTLS_SHA384_Update(&context, data, len);
+       return DTLS_SHA384_End(&context, digest);
 }
 #endif
index 709fc80..e6eecc4 100644 (file)
@@ -55,15 +55,15 @@ extern "C" {
 
 
 /*** SHA-256/384/512 Various Length Definitions ***********************/
-#define SHA256_BLOCK_LENGTH            64
-#define SHA256_DIGEST_LENGTH           32
-#define SHA256_DIGEST_STRING_LENGTH    (SHA256_DIGEST_LENGTH * 2 + 1)
-#define SHA384_BLOCK_LENGTH            128
-#define SHA384_DIGEST_LENGTH           48
-#define SHA384_DIGEST_STRING_LENGTH    (SHA384_DIGEST_LENGTH * 2 + 1)
-#define SHA512_BLOCK_LENGTH            128
-#define SHA512_DIGEST_LENGTH           64
-#define SHA512_DIGEST_STRING_LENGTH    (SHA512_DIGEST_LENGTH * 2 + 1)
+#define DTLS_SHA256_BLOCK_LENGTH               64
+#define DTLS_SHA256_DIGEST_LENGTH              32
+#define DTLS_SHA256_DIGEST_STRING_LENGTH       (DTLS_SHA256_DIGEST_LENGTH * 2 + 1)
+#define DTLS_SHA384_BLOCK_LENGTH               128
+#define DTLS_SHA384_DIGEST_LENGTH              48
+#define DTLS_SHA384_DIGEST_STRING_LENGTH       (DTLS_SHA384_DIGEST_LENGTH * 2 + 1)
+#define DTLS_SHA512_BLOCK_LENGTH               128
+#define DTLS_SHA512_DIGEST_LENGTH              64
+#define DTLS_SHA512_DIGEST_STRING_LENGTH       (DTLS_SHA512_DIGEST_LENGTH * 2 + 1)
 
 
 /*** SHA-256/384/512 Context Structures *******************************/
@@ -94,33 +94,33 @@ typedef unsigned long long u_int64_t;       /* 8-bytes (64-bits) */
  */
 #ifdef SHA2_USE_INTTYPES_H
 
-typedef struct _SHA256_CTX {
+typedef struct _DTLS_SHA256_CTX {
        uint32_t        state[8];
        uint64_t        bitcount;
-       uint8_t buffer[SHA256_BLOCK_LENGTH];
-} SHA256_CTX;
-typedef struct _SHA512_CTX {
+       uint8_t buffer[DTLS_SHA256_BLOCK_LENGTH];
+} DTLS_SHA256_CTX;
+typedef struct _DTLS_SHA512_CTX {
        uint64_t        state[8];
        uint64_t        bitcount[2];
-       uint8_t buffer[SHA512_BLOCK_LENGTH];
-} SHA512_CTX;
+       uint8_t buffer[DTLS_SHA512_BLOCK_LENGTH];
+} DTLS_SHA512_CTX;
 
 #else /* SHA2_USE_INTTYPES_H */
 
-typedef struct _SHA256_CTX {
+typedef struct _DTLS_SHA256_CTX {
        u_int32_t       state[8];
        u_int64_t       bitcount;
-       u_int8_t        buffer[SHA256_BLOCK_LENGTH];
-} SHA256_CTX;
-typedef struct _SHA512_CTX {
+       u_int8_t        buffer[DTLS_SHA256_BLOCK_LENGTH];
+} DTLS_SHA256_CTX;
+typedef struct _DTLS_SHA512_CTX {
        u_int64_t       state[8];
        u_int64_t       bitcount[2];
-       u_int8_t        buffer[SHA512_BLOCK_LENGTH];
-} SHA512_CTX;
+       u_int8_t        buffer[DTLS_SHA512_BLOCK_LENGTH];
+} DTLS_SHA512_CTX;
 
 #endif /* SHA2_USE_INTTYPES_H */
 
-typedef SHA512_CTX SHA384_CTX;
+typedef DTLS_SHA512_CTX DTLS_SHA384_CTX;
 
 
 /*** SHA-256/384/512 Function Prototypes ******************************/
@@ -128,53 +128,53 @@ typedef SHA512_CTX SHA384_CTX;
 #ifdef SHA2_USE_INTTYPES_H
 
 #ifdef WITH_SHA256
-void SHA256_Init(SHA256_CTX *);
-void SHA256_Update(SHA256_CTX*, const uint8_t*, size_t);
-void SHA256_Final(uint8_t[SHA256_DIGEST_LENGTH], SHA256_CTX*);
-char* SHA256_End(SHA256_CTX*, char[SHA256_DIGEST_STRING_LENGTH]);
-char* SHA256_Data(const uint8_t*, size_t, char[SHA256_DIGEST_STRING_LENGTH]);
+void DTLS_SHA256_Init(DTLS_SHA256_CTX *);
+void DTLS_SHA256_Update(DTLS_SHA256_CTX*, const uint8_t*, size_t);
+void DTLS_SHA256_Final(uint8_t[DTLS_SHA256_DIGEST_LENGTH], DTLS_SHA256_CTX*);
+char* DTLS_SHA256_End(DTLS_SHA256_CTX*, char[DTLS_SHA256_DIGEST_STRING_LENGTH]);
+char* DTLS_SHA256_Data(const uint8_t*, size_t, char[DTLS_SHA256_DIGEST_STRING_LENGTH]);
 #endif
 
 #ifdef WITH_SHA384
-void SHA384_Init(SHA384_CTX*);
-void SHA384_Update(SHA384_CTX*, const uint8_t*, size_t);
-void SHA384_Final(uint8_t[SHA384_DIGEST_LENGTH], SHA384_CTX*);
-char* SHA384_End(SHA384_CTX*, char[SHA384_DIGEST_STRING_LENGTH]);
-char* SHA384_Data(const uint8_t*, size_t, char[SHA384_DIGEST_STRING_LENGTH]);
+void DTLS_SHA384_Init(DTLS_SHA384_CTX*);
+void DTLS_SHA384_Update(DTLS_SHA384_CTX*, const uint8_t*, size_t);
+void DTLS_SHA384_Final(uint8_t[DTLS_SHA384_DIGEST_LENGTH], SHA384_CTX*);
+char* DTLS_SHA384_End(DTLS_SHA384_CTX*, char[DTLS_SHA384_DIGEST_STRING_LENGTH]);
+char* DTLS_SHA384_Data(const uint8_t*, size_t, char[DTLS_SHA384_DIGEST_STRING_LENGTH]);
 #endif
 
 #ifdef WITH_SHA512
-void SHA512_Init(SHA512_CTX*);
-void SHA512_Update(SHA512_CTX*, const uint8_t*, size_t);
-void SHA512_Final(uint8_t[SHA512_DIGEST_LENGTH], SHA512_CTX*);
-char* SHA512_End(SHA512_CTX*, char[SHA512_DIGEST_STRING_LENGTH]);
-char* SHA512_Data(const uint8_t*, size_t, char[SHA512_DIGEST_STRING_LENGTH]);
+void DTLS_SHA512_Init(DTLS_SHA512_CTX*);
+void DTLS_SHA512_Update(DTLS_SHA512_CTX*, const uint8_t*, size_t);
+void DTLS_SHA512_Final(uint8_t[DTLS_SHA512_DIGEST_LENGTH], DTLS_SHA512_CTX*);
+char* DTLS_SHA512_End(DTLS_SHA512_CTX*, char[DTLS_SHA512_DIGEST_STRING_LENGTH]);
+char* DTLS_SHA512_Data(const uint8_t*, size_t, char[DTLS_SHA512_DIGEST_STRING_LENGTH]);
 #endif
 
 #else /* SHA2_USE_INTTYPES_H */
 
 #ifdef WITH_SHA256
-void SHA256_Init(SHA256_CTX *);
-void SHA256_Update(SHA256_CTX*, const u_int8_t*, size_t);
-void SHA256_Final(u_int8_t[SHA256_DIGEST_LENGTH], SHA256_CTX*);
-char* SHA256_End(SHA256_CTX*, char[SHA256_DIGEST_STRING_LENGTH]);
-char* SHA256_Data(const u_int8_t*, size_t, char[SHA256_DIGEST_STRING_LENGTH]);
+void DTLS_SHA256_Init(DTLS_SHA256_CTX *);
+void DTLS_SHA256_Update(DTLS_SHA256_CTX*, const u_int8_t*, size_t);
+void DTLS_SHA256_Final(u_int8_t[DTLS_SHA256_DIGEST_LENGTH], DTLS_SHA256_CTX*);
+char* DTLS_SHA256_End(DTLS_SHA256_CTX*, char[DTLS_SHA256_DIGEST_STRING_LENGTH]);
+char* DTLS_SHA256_Data(const u_int8_t*, size_t, char[DTLS_SHA256_DIGEST_STRING_LENGTH]);
 #endif
 
 #ifdef WITH_SHA384
-void SHA384_Init(SHA384_CTX*);
-void SHA384_Update(SHA384_CTX*, const u_int8_t*, size_t);
-void SHA384_Final(u_int8_t[SHA384_DIGEST_LENGTH], SHA384_CTX*);
-char* SHA384_End(SHA384_CTX*, char[SHA384_DIGEST_STRING_LENGTH]);
-char* SHA384_Data(const u_int8_t*, size_t, char[SHA384_DIGEST_STRING_LENGTH]);
+void DTLS_SHA384_Init(DTLS_SHA384_CTX*);
+void DTLS_SHA384_Update(DTLS_SHA384_CTX*, const u_int8_t*, size_t);
+void DTLS_SHA384_Final(u_int8_t[DTLS_SHA384_DIGEST_LENGTH], DTLS_SHA384_CTX*);
+char* DTLS_SHA384_End(DTLS_SHA384_CTX*, char[DTLS_SHA384_DIGEST_STRING_LENGTH]);
+char* DTLS_SHA384_Data(const u_int8_t*, size_t, char[DTLS_SHA384_DIGEST_STRING_LENGTH]);
 #endif
 
 #ifdef WITH_SHA512
-void SHA512_Init(SHA512_CTX*);
-void SHA512_Update(SHA512_CTX*, const u_int8_t*, size_t);
-void SHA512_Final(u_int8_t[SHA512_DIGEST_LENGTH], SHA512_CTX*);
-char* SHA512_End(SHA512_CTX*, char[SHA512_DIGEST_STRING_LENGTH]);
-char* SHA512_Data(const u_int8_t*, size_t, char[SHA512_DIGEST_STRING_LENGTH]);
+void DTLS_SHA512_Init(DTLS_SHA512_CTX*);
+void DTLS_SHA512_Update(DTLS_SHA512_CTX*, const u_int8_t*, size_t);
+void DTLS_SHA512_Final(u_int8_t[DTLS_SHA512_DIGEST_LENGTH], DTLS_SHA512_CTX*);
+char* DTLS_SHA512_End(DTLS_SHA512_CTX*, char[DTLS_SHA512_DIGEST_STRING_LENGTH]);
+char* DTLS_SHA512_Data(const u_int8_t*, size_t, char[DTLS_SHA512_DIGEST_STRING_LENGTH]);
 #endif
 
 #endif /* SHA2_USE_INTTYPES_H */
@@ -182,27 +182,27 @@ char* SHA512_Data(const u_int8_t*, size_t, char[SHA512_DIGEST_STRING_LENGTH]);
 #else /* NOPROTO */
 
 #ifdef WITH_SHA256
-void SHA256_Init();
-void SHA256_Update();
-void SHA256_Final();
-char* SHA256_End();
-char* SHA256_Data();
+void DTLS_SHA256_Init();
+void DTLS_SHA256_Update();
+void DTLS_SHA256_Final();
+char* DTLS_SHA256_End();
+char* DTLS_SHA256_Data();
 #endif
 
 #ifdef WITH_SHA384
-void SHA384_Init();
-void SHA384_Update();
-void SHA384_Final();
-char* SHA384_End();
-char* SHA384_Data();
+void DTLS_SHA384_Init();
+void DTLS_SHA384_Update();
+void DTLS_SHA384_Final();
+char* DTLS_SHA384_End();
+char* DTLS_SHA384_Data();
 #endif
 
 #ifdef WITH_SHA512
-void SHA512_Init();
-void SHA512_Update();
-void SHA512_Final();
-char* SHA512_End();
-char* SHA512_Data();
+void DTLS_SHA512_Init();
+void DTLS_SHA512_Update();
+void DTLS_SHA512_Final();
+char* DTLS_SHA512_End();
+char* DTLS_SHA512_Data();
 #endif
 
 #endif /* NOPROTO */
index 8d9d6ae..b5c485e 100644 (file)
@@ -52,14 +52,14 @@ int main(int argc, char **argv) {
        int             quiet = 0, hash = 0;
        char            *av, *file = (char*)0;
        FILE            *IN = (FILE*)0;
-       SHA256_CTX      ctx256;
-       SHA384_CTX      ctx384;
-       SHA512_CTX      ctx512;
+       DTLS_SHA256_CTX ctx256;
+       DTLS_SHA384_CTX ctx384;
+       DTLS_SHA512_CTX ctx512;
        unsigned char   buf[BUFLEN];
 
-       SHA256_Init(&ctx256);
-       SHA384_Init(&ctx384);
-       SHA512_Init(&ctx512);
+       DTLS_SHA256_Init(&ctx256);
+       DTLS_SHA384_Init(&ctx384);
+       DTLSSHA512_Init(&ctx512);
 
        /* Read data from STDIN by default */
        fd = fileno(stdin);
@@ -100,28 +100,28 @@ int main(int argc, char **argv) {
        kl = 0;
        while ((l = read(fd,buf,BUFLEN)) > 0) {
                kl += l;
-               SHA256_Update(&ctx256, (unsigned char*)buf, l);
-               SHA384_Update(&ctx384, (unsigned char*)buf, l);
-               SHA512_Update(&ctx512, (unsigned char*)buf, l);
+               DTLS_SHA256_Update(&ctx256, (unsigned char*)buf, l);
+               DTLS_SHA384_Update(&ctx384, (unsigned char*)buf, l);
+               DTLS_SHA512_Update(&ctx512, (unsigned char*)buf, l);
        }
        if (file) {
                fclose(IN);
        }
 
        if (hash & 1) {
-               SHA256_End(&ctx256, buf);
+               DTLS_SHA256_End(&ctx256, buf);
                if (!quiet)
                        printf("SHA-256 (%s) = ", file);
                printf("%s\n", buf);
        }
        if (hash & 2) {
-               SHA384_End(&ctx384, buf);
+               DTLS_SHA384_End(&ctx384, buf);
                if (!quiet)
                        printf("SHA-384 (%s) = ", file);
                printf("%s\n", buf);
        }
        if (hash & 4) {
-               SHA512_End(&ctx512, buf);
+               DTLS_SHA512_End(&ctx512, buf);
                if (!quiet)
                        printf("SHA-512 (%s) = ", file);
                printf("%s\n", buf);
index 2e13575..f012f40 100644 (file)
@@ -60,11 +60,11 @@ void printspeed(char *caption, unsigned long bytes, double time) {
 
 
 int main(int argc, char **argv) {
-       SHA256_CTX      c256;
-       SHA384_CTX      c384;
-       SHA512_CTX      c512;
+       DTLS_SHA256_CTX c256;
+       DTLS_SHA384_CTX c384;
+       DTLS_SHA512_CTX c512;
        char            buf[BUFSIZE];
-       char            md[SHA512_DIGEST_STRING_LENGTH];
+       char            md[DTLS_SHA512_DIGEST_STRING_LENGTH];
        int             bytes, blocks, rep, i, j;
        struct timeval  start, end;
        double          t, ave256, ave384, ave512;
@@ -97,18 +97,18 @@ int main(int argc, char **argv) {
        ave256 = ave384 = ave512 = 0;
        best256 = best384 = best512 = 100000;
        for (i = 0; i < rep; i++) {
-               SHA256_Init(&c256);
-               SHA384_Init(&c384);
-               SHA512_Init(&c512);
+               DTLS_SHA256_Init(&c256);
+               DTLS_SHA384_Init(&c384);
+               DTLS_SHA512_Init(&c512);
        
                gettimeofday(&start, (struct timezone*)0);
                for (j = 0; j < blocks; j++) {
-                       SHA256_Update(&c256, (unsigned char*)buf, BUFSIZE);
+                       DTLS_SHA256_Update(&c256, (unsigned char*)buf, BUFSIZE);
                }
                if (bytes % BUFSIZE) {
-                       SHA256_Update(&c256, (unsigned char*)buf, bytes % BUFSIZE);
+                       DTLS_SHA256_Update(&c256, (unsigned char*)buf, bytes % BUFSIZE);
                }
-               SHA256_End(&c256, md);
+               DTLS_SHA256_End(&c256, md);
                gettimeofday(&end, (struct timezone*)0);
                t = ((end.tv_sec - start.tv_sec) * 1000000.0 + (end.tv_usec - start.tv_usec)) / 1000000.0;
                ave256 += t;
@@ -119,12 +119,12 @@ int main(int argc, char **argv) {
 
                gettimeofday(&start, (struct timezone*)0);
                for (j = 0; j < blocks; j++) {
-                       SHA384_Update(&c384, (unsigned char*)buf, BUFSIZE);
+                       DTLS_SHA384_Update(&c384, (unsigned char*)buf, BUFSIZE);
                }
                if (bytes % BUFSIZE) {
-                       SHA384_Update(&c384, (unsigned char*)buf, bytes % BUFSIZE);
+                       DTLS_SHA384_Update(&c384, (unsigned char*)buf, bytes % BUFSIZE);
                }
-               SHA384_End(&c384, md);
+               DTLS_SHA384_End(&c384, md);
                gettimeofday(&end, (struct timezone*)0);
                t = ((end.tv_sec - start.tv_sec) * 1000000.0 + (end.tv_usec - start.tv_usec)) / 1000000.0;
                ave384 += t;
@@ -135,12 +135,12 @@ int main(int argc, char **argv) {
 
                gettimeofday(&start, (struct timezone*)0);
                for (j = 0; j < blocks; j++) {
-                       SHA512_Update(&c512, (unsigned char*)buf, BUFSIZE);
+                       DTLS_SHA512_Update(&c512, (unsigned char*)buf, BUFSIZE);
                }
                if (bytes % BUFSIZE) {
-                       SHA512_Update(&c512, (unsigned char*)buf, bytes % BUFSIZE);
+                       DTLS_SHA512_Update(&c512, (unsigned char*)buf, bytes % BUFSIZE);
                }
-               SHA512_End(&c512, md);
+               DTLS_SHA512_End(&c512, md);
                gettimeofday(&end, (struct timezone*)0);
                t = ((end.tv_sec - start.tv_sec) * 1000000.0 + (end.tv_usec - start.tv_usec)) / 1000000.0;
                ave512 += t;
index 7534c5f..8f72f26 100644 (file)
@@ -44,7 +44,7 @@ finalize_hash(uint8 *buf) {
 #if DTLS_VERSION == 0xfeff
   unsigned char statebuf[sizeof(md5_state_t) + sizeof(SHA_CTX)];
 #elif DTLS_VERSION == 0xfefd
-  unsigned char statebuf[sizeof(SHA256_CTX)];
+  unsigned char statebuf[sizeof(DTLS_SHA256_CTX)];
 #endif
 
   if (!hs_hash[0])
@@ -213,7 +213,7 @@ handle_packet(const u_char *packet, int length) {
 #endif
   uint8 hash_buf[16 + SHA1_DIGEST_LENGTH];
 #elif DTLS_VERSION == 0xfefd
-  uint8 hash_buf[SHA256_DIGEST_LENGTH];
+  uint8 hash_buf[DTLS_SHA256_DIGEST_LENGTH];
 #endif
 #define verify_data_length 12
   int is_client;
diff --git a/extlibs/wksxmppxep/SConscript b/extlibs/wksxmppxep/SConscript
new file mode 100644 (file)
index 0000000..c6bb6ce
--- /dev/null
@@ -0,0 +1,63 @@
+######################################################################
+# Ref. libstrophe library build script
+#
+######################################################################
+import os
+import commands
+
+Import('env')
+
+base_dir = env.get('SRC_DIR')
+target_os = env.get('TARGET_OS')
+target_arch = env.get('TARGET_ARCH')
+
+with_ra_ibb = env.get('WITH_RA_IBB')
+
+SRC_NAME = 'wks_xep0047'
+EXT_NAME = 'wksxmppxep'
+EXT_BASE = 'extlibs/' + EXT_NAME
+EXT_PATH = EXT_BASE + '/' + SRC_NAME
+SRC_PATH = base_dir + '/' + EXT_PATH
+INC_PATH = SRC_PATH + '/include'
+LIB_PATH = SRC_PATH
+
+if with_ra_ibb:
+       env.SConscript(base_dir + '/extlibs/libstrophe/SConscript')
+       if not os.path.exists(SRC_NAME):
+               raxmpp_env = Environment(ENV = os.environ)
+               c = raxmpp_env.Action(['git clone https://github.com/WorksSystems/wks_xep0047.git ' + SRC_NAME,
+                       'cd ' + SRC_NAME + ' && git checkout 8e9f42d02a0f416001065d1cddc1ab07974cef14'
+        ])
+
+               print 'Downloading', SRC_NAME ,'library ...'
+               if raxmpp_env.Execute(c):
+                       print '''
+       *********************************** Error: ***********************************************
+       * Please download ra_xmpp as following:
+       *     $ git clone https://github.com/WorksSystems/wksxmpp_chat.git extlibs/wksxmppxep/wksxmpp_chat
+       *     $ cd extlibs/wksxmppxep/wksxmpp_chat
+       *     $ git checkout 8e9f42d02a0f416001065d1cddc1ab07974cef14
+       ******************************************************************************************
+       '''
+                       Exit(1)
+               else:
+                       print 'Download', SRC_NAME, 'library complete'
+
+       print 'Building with ' + SRC_NAME
+       os.chdir(SRC_NAME)
+       if not os.path.exists('libwksxmppxep.so') :
+               LIBSTROPHE_BASE=base_dir + '/extlibs/libstrophe/libstrophe'
+               foo=commands.getoutput('make LIBSTROPHE_BASE=' + LIBSTROPHE_BASE + ' libraries')
+               print foo
+
+       if not os.path.exists('libwksxmppxep.so') :
+               print 'Building with ' + SRC_NAME + ' failed.'
+               Exit(2)
+
+       print 'Building with ' + SRC_NAME + ' Completely.'
+
+       env.PrependUnique(CPPPATH = [INC_PATH], RALIBS = ['wksxmppxep', 'm', 'crypto'], RALIBPATH = [LIB_PATH], RARPATH = [LIB_PATH])
+
+if env.GetOption('clean') :
+       act = env.Action(['cd ' + SRC_PATH, 'make clean'])
+       env.Execute(act)
index d9ab246..9ba4a72 100755 (executable)
@@ -40,6 +40,7 @@ cp ./extra_options.scons $sourcedir/tmp
 cp ./tools/tizen/*.spec ./tmp/packaging
 cp ./tools/tizen/*.manifest ./tmp/packaging
 cp ./SConstruct ./tmp
+cp ./LICENSE.md ./tmp
 
 # copy dependency RPMs and conf files for tizen build
 cp ./tools/tizen/*.rpm ./tmp
@@ -62,7 +63,7 @@ if [ ! -d .git ]; then
 fi
 
 echo "Calling core gbs build command"
-gbscommand="gbs build -A armv7l -B ~/GBS-ROOT --include-all --repository ./"
+gbscommand="gbs build -A armv7l -B ~/GBS-ROOT-OIC --include-all --repository ./"
 echo $gbscommand
 if eval $gbscommand; then
    echo "Build is successful"
index 66d088b..59bd6b5 100644 (file)
@@ -4,11 +4,18 @@ prefix=@PREFIX@
 exec_prefix=${prefix}
 libdir=@LIB_INSTALL_DIR@
 includedir=${prefix}/include
+svcincludedir=${includedir}/service
 
 Name: iotivity
-Description: IoTivity is an open source reference implementation of the OIC standard specifications.
+Description: IoTivity is an open source reference implementation of the OIC standard specifications. This includes the libs for resource c and c++ sdk apis.
 Version: @VERSION@
 URL: https://www.iotivity.org
 Requires:
 Libs: -L${libdir} -loc -loc_logger -loc_logger_core -loctbstack -lconnectivity_abstraction
-Cflags: -I${includedir}/resource -I${includedir}/iotivity-service -D@ROUTING_DEFINE@
+Cflags: -I${includedir}/resource \
+                       -I${svcincludedir}/resource-encapsulation \
+                       -I${svcincludedir}/resource-container \
+                       -I${svcincludedir}/resource-hosting \
+                       -I${svcincludedir}/resource-directory \
+                       -I${svcincludedir}/things-manager \
+                       -D@ROUTING_DEFINE@
index 6b4e7e1..8002174 100644 (file)
@@ -8,8 +8,7 @@
                        <smack request="device::sys_logging" type="w" />
                        <smack request="device::app_logging" type="w" />
                        <smack request="system::use_internet" type="w" />
-                       <smack request="tizen::vconf::public::r::platform::rw" type="rl" />
-                       <smack request="bluez" type="rw" />
+                       <smack request="connman::get" type="w" />
                </request>
        </define>
        <request>
index ac06cee..c335968 100644 (file)
@@ -1,5 +1,5 @@
 Name: iotivity
-Version: 1.0.1
+Version: 1.1.0
 Release: 0
 Summary: IoT Connectivity sponsored by the OIC
 Group: Network & Connectivity/Other
@@ -20,7 +20,6 @@ BuildRequires:  pkgconfig(dlog)
 BuildRequires:  pkgconfig(uuid)
 BuildRequires:  pkgconfig(capi-network-wifi)
 BuildRequires:  pkgconfig(capi-network-bluetooth)
-BuildRequires:  pkgconfig(capi-appfw-app-common)
 BuildRequires:  pkgconfig(glib-2.0)
 BuildRequires:  pkgconfig(sqlite3)
 Requires(postun): /sbin/ldconfig
@@ -35,10 +34,13 @@ Requires(post): /sbin/ldconfig
 %define RELEASE True
 %endif
 
-%{!?TARGET_TRANSPORT: %define TARGET_TRANSPORT IP,BT}
+%{!?TARGET_TRANSPORT: %define TARGET_TRANSPORT IP}
 %{!?SECURED: %define SECURED 0}
 %{!?LOGGING: %define LOGGING True}
 %{!?ROUTING: %define ROUTING GW}
+%{!?ES_TARGET_ENROLLEE: %define ES_TARGET_ENROLLEE tizen}
+%{!?ES_ROLE: %define ES_ROLE enrollee}
+%{!?ES_SOFTAP_MODE: %define ES_SOFTAP_MODE MEDIATOR_SOFTAP}
 
 %description
 An open source reference implementation of the OIC standard specifications
@@ -108,6 +110,7 @@ cp %{SOURCE1001} ./%{name}-test.manifest
 scons -j2 --prefix=%{_prefix} \
        TARGET_OS=tizen TARGET_ARCH=%{RPM_ARCH} TARGET_TRANSPORT=%{TARGET_TRANSPORT} \
        RELEASE=%{RELEASE} SECURED=%{SECURED} LOGGING=%{LOGGING} ROUTING=%{ROUTING} \
+       ES_TARGET_ENROLLEE=%{ES_TARGET_ENROLLEE} ES_ROLE=%{ES_ROLE} ES_SOFTAP_MODE=%{ES_SOFTAP_MODE} \
        LIB_INSTALL_DIR=%{_libdir}
 
 
@@ -117,6 +120,7 @@ CFLAGS="${CFLAGS:-%optflags}" ; export CFLAGS ;
 scons install --install-sandbox=%{buildroot} --prefix=%{_prefix} \
        TARGET_OS=tizen TARGET_ARCH=%{RPM_ARCH} TARGET_TRANSPORT=%{TARGET_TRANSPORT} \
        RELEASE=%{RELEASE} SECURED=%{SECURED} LOGGING=%{LOGGING} ROUTING=%{ROUTING} \
+       ES_TARGET_ENROLLEE=%{ES_TARGET_ENROLLEE} ES_ROLE=%{ES_ROLE} ES_SOFTAP_MODE=%{ES_SOFTAP_MODE} \
        LIB_INSTALL_DIR=%{_libdir}
 
 
@@ -148,17 +152,20 @@ cp out/tizen/*/%{build_mode}/resource/examples/simpleclientserver %{ex_install_d
 cp out/tizen/*/%{build_mode}/resource/examples/simpleserver %{ex_install_dir}
 cp out/tizen/*/%{build_mode}/resource/examples/simpleserverHQ %{ex_install_dir}
 cp out/tizen/*/%{build_mode}/resource/examples/threadingsample %{ex_install_dir}
-cp out/tizen/*/%{build_mode}/resource/examples/oic_svr_db_server.json %{ex_install_dir}
-cp out/tizen/*/%{build_mode}/resource/examples/oic_svr_db_client.json %{ex_install_dir}
+cp out/tizen/*/%{build_mode}/resource/examples/oic_svr_db_server.dat %{ex_install_dir}
+cp out/tizen/*/%{build_mode}/resource/examples/oic_svr_db_client.dat %{ex_install_dir}
 %if 0%{?SECURED} == 1
 mkdir -p %{ex_install_dir}/provisioning
-cp out/tizen/*/%{build_mode}/resource/provisioning/examples/oic_svr_db_client.json %{ex_install_dir}/provisioning/
-cp out/tizen/*/%{build_mode}/resource/provisioning/examples/provisioningclient %{ex_install_dir}/provisioning/
+mkdir -p %{ex_install_dir}/provision-sample
+
+cp ./resource/csdk/security/include/pinoxmcommon.h %{buildroot}%{_includedir}
+cp ./resource/csdk/security/provisioning/include/oxm/*.h %{buildroot}%{_includedir}
+cp ./resource/csdk/security/provisioning/include/internal/*.h %{buildroot}%{_includedir}
+cp ./resource/csdk/security/provisioning/include/*.h %{buildroot}%{_includedir}
+cp ./resource/csdk/security/provisioning/sample/oic_svr_db_server_justworks.dat %{buildroot}%{_libdir}/oic_svr_db_server.dat
+
 %endif
 
-# For iotcon
-cp resource/csdk/stack/include/ocpayload.h %{buildroot}%{_includedir}/resource
-cp resource/c_common/ocrandom/include/ocrandom.h %{buildroot}%{_includedir}/resource
 
 %if 0%{?tizen_version_major} < 3
 mkdir -p %{buildroot}/%{_datadir}/license
@@ -166,6 +173,13 @@ cp LICENSE.APLv2 %{buildroot}/%{_datadir}/license/%{name}
 cp LICENSE.APLv2 %{buildroot}/%{_datadir}/license/%{name}-service
 cp LICENSE.APLv2 %{buildroot}/%{_datadir}/license/%{name}-test
 %endif
+cp resource/c_common/*.h %{buildroot}%{_includedir}
+cp resource/csdk/stack/include/*.h %{buildroot}%{_includedir}
+
+cp service/things-manager/sdk/inc/*.h %{buildroot}%{_includedir}
+cp service/easy-setup/inc/*.h %{buildroot}%{_includedir}
+cp service/easy-setup/enrollee/inc/*.h %{buildroot}%{_includedir}
+
 
 %post -p /sbin/ldconfig
 
@@ -197,6 +211,12 @@ cp LICENSE.APLv2 %{buildroot}/%{_datadir}/license/%{name}-test
 %{_libdir}/librcs_common.so
 %{_libdir}/librcs_container.so
 %{_libdir}/librcs_server.so
+%{_libdir}/libESEnrolleeSDK.so
+%if 0%{?SECURED} == 1
+%{_libdir}/libocpmapi.so
+%{_libdir}/libocprovision.so
+%{_libdir}/oic_svr_db_server.dat
+%endif
 %if 0%{?tizen_version_major} < 3
 %{_datadir}/license/%{name}-service
 %else
index e4449cc..86c1635 100644 (file)
@@ -29,7 +29,7 @@ target_os = env.get('TARGET_OS')
 build_sample = env.get('BUILD_SAMPLE')
 src_dir = env.get('SRC_DIR')
 
-if target_os not in ['android', 'arduino', 'darwin', 'ios','tizen']:
+if target_os not in ['android', 'arduino', 'darwin', 'ios', 'tizen']:
 
     SConscript(os.path.join('zigbee_wrapper', 'SConscript'))
 
index ea57da0..925e24a 100644 (file)
@@ -42,11 +42,18 @@ OCStackResult DeletePluginList();
 OCStackResult GetResourceFromHandle(PIPluginBase * plugin, PIResource ** piResource,
                                     OCResourceHandle * resourceHandle);
 
-OCStackResult GetResourceFromURI(PIPluginBase * plugin, PIResource ** piResource,
-                                    const char * uri);
+OCStackResult GetResourceFromZigBeeNodeId(PIPluginBase * plugin,
+                                          PIResource_Zigbee ** piResource,
+                                          const char * nodeId,
+                                          const char * endpointId,
+                                          const char * clusterId);
 
 OCStackResult AddResourceToPlugin(PIPluginBase * plugin, PIResourceBase * resource);
 
+OCStackResult UpdateZigbeeResourceNodeId(PIPluginBase * plugin,
+                                         const char * eui,
+                                         const char * nodeId);
+
 OCStackResult DeleteResource(PIPluginBase * plugin, PIResourceBase * resource);
 
 OCStackResult DeleteResourceList(PIPluginBase * plugin);
index 901f343..c5a8580 100644 (file)
@@ -58,7 +58,7 @@ typedef void (* PINewResourceFound)(struct PIPluginBase * plugin,
  *
  */
 typedef void (* PIObserveNotificationUpdate)(struct PIPluginBase * plugin,
-                                            const char * uri);
+                                             OCResourceHandle resourceHandle);
 
 /**
  *
index e66d1d9..ac417d3 100644 (file)
@@ -62,6 +62,16 @@ OCStackResult PIStopAll();
 
 /**
  *
+ * Performs any required work on this specific plugin to initiate it's respective
+ * discovery operation.
+ *
+ * @param[in] plugin The plugin to initiate it's discovery operation on.
+ *
+ */
+OCStackResult PISetup(PIPlugin * plugin);
+
+/**
+ *
  * Called in main loop of application. Gives cycles for Plugin Interface'
  * internal operation.
  *
index 35ea112..c781891 100644 (file)
@@ -31,6 +31,7 @@
 #include <string.h>
 #include <signal.h>
 #include <unistd.h>
+#include <errno.h>
 #include "ocstack.h"
 #include "logger.h"
 #include "ocpayload.h"
 #define MAX_URI_SIZE                (256)
 #define MAX_RESOURCE_TYPE_SIZE      (32)
 #define MAX_RESOURCE_TYPE_LENGTH    (MAX_RESOURCE_TYPE_SIZE - 1)
-#define MAX_RESOURCES_REMEMBERED    (10)
+#define MAX_RESOURCES_REMEMBERED    (100)
+
+#define MAX_USER_INPUT              (100)
 
 #define TAG "oc_zb_client"
 
 static uint32_t countDiscoveredResources = 0;
 static bool promptUser = false;
 
-static const char*      coapServerIP    = "255.255.255.255";
-static       uint32_t   coapServerPort  = 5683;
+static OCDevAddr destinationAddress = {
+    .adapter = OC_ADAPTER_IP
+};
 
 typedef struct
 {
@@ -64,53 +68,54 @@ static DiscoveredResourceInfo g_discoveredResources[MAX_RESOURCES_REMEMBERED];
 static void PrintTestCases()
 {
     printf("\nTest Cases:\n");
-    printf ("\n\t%d : Quit    %d: GET    %d: Build PUT payload %d: OBSERVE\n\n",
+    printf("\n\t%d : Quit    %d: GET    %d: Build PUT payload %d: OBSERVE\n\n",
             TEST_QUIT, TEST_GET, TEST_CUSTOM_PUT, TEST_OBSERVE);
-    printf ("\t%d : Turn binary switch for light ON\n", TEST_TURN_SWITCH_ON);
-    printf ("\t%d : Turn binary switch for light OFF\n", TEST_TURN_SWITCH_OFF);
-    printf ("\t%d : Change light brightness\n", TEST_SET_LIGHT_BRIGHTNESS);
-    printf ("\n\t%d : Check for observation updates.\n", TEST_CYCLE);
+    printf("\t%d : Turn binary switch for light ON\n", TEST_TURN_SWITCH_ON);
+    printf("\t%d : Turn binary switch for light OFF\n", TEST_TURN_SWITCH_OFF);
+    printf("\t%d : Change light brightness\n", TEST_SET_LIGHT_BRIGHTNESS);
+    printf("\t%d : Change light temperature\n", TEST_SET_LIGHT_TEMPERATURE);
+    printf("\n\t%d : Check for observation updates.\n", TEST_CYCLE);
 }
 
-static void PrintResources ()
+static void PrintResources()
 {
     printf("\nResources: \n");
-    for (int i = 0; i < countDiscoveredResources; ++i)
+    for(uint32_t i = 0; i < countDiscoveredResources; ++i)
     {
         printf("\t# : %u \t URI: %s \t Type:%s\n", i, g_discoveredResources[i].uri,
             g_discoveredResources[i].resourceType);
     }
 }
 
-void rememberDiscoveredResources (OCClientResponse *clientResponse)
+void rememberDiscoveredResources(OCClientResponse *clientResponse)
 {
     OCResourcePayload* itr = NULL;
-    if(!(OCDiscoveryPayload*)clientResponse->payload)
+    if (!(OCDiscoveryPayload*)clientResponse->payload)
     {
-        OC_LOG (INFO, TAG, "No resources discovered.");
+        OIC_LOG(INFO, TAG, "No resources discovered.");
         return;
     }
 
     itr = ((OCDiscoveryPayload*)(clientResponse->payload))->resources;
 
-    while(itr && itr != itr->next)
+    while (itr && itr != itr->next)
     {
         if (countDiscoveredResources == MAX_RESOURCES_REMEMBERED)
         {
-            OC_LOG_V (INFO, TAG, "Only remembering %u resources. Ignoring rest.",
+            OIC_LOG_V(INFO, TAG, "Only remembering %u resources. Ignoring rest.",
                 MAX_RESOURCES_REMEMBERED);
             break;
         }
-        strncpy (g_discoveredResources[countDiscoveredResources].uri,
+        strncpy(g_discoveredResources[countDiscoveredResources].uri,
             itr->uri, MAX_URI_SIZE - 1);
-        strncpy (g_discoveredResources[countDiscoveredResources].resourceType,
+        strncpy(g_discoveredResources[countDiscoveredResources].resourceType,
             itr->types->value, MAX_RESOURCE_TYPE_SIZE - 1);
         ++countDiscoveredResources;
         itr = itr->next;
     }
 }
 
-OCStackResult InvokeOCDoResource (char *query,
+OCStackResult InvokeOCDoResource(const char *query,
                                  OCPayload *payload,
                                  OCMethod method,
                                  OCClientResponseHandler cb)
@@ -122,13 +127,13 @@ OCStackResult InvokeOCDoResource (char *query,
 
     OCDoHandle handle = NULL;
 
-    OCStackResult ret = OCDoResource(&handle, method, query, 0, payload,
-                        CT_ADAPTER_IP, OC_LOW_QOS, &cbData, NULL, 0);
+    OCStackResult ret = OCDoResource(&handle, method, query, &destinationAddress,
+                    payload, CT_ADAPTER_IP, OC_LOW_QOS, &cbData, NULL, 0);
 
     if (ret != OC_STACK_OK)
     {
         promptUser = true;
-        OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
+        OIC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
     }
     return ret;
 }
@@ -138,66 +143,81 @@ OCStackApplicationResult responseCallbacks(void* ctx,
                 OCClientResponse * clientResponse)
 {
     (void)handle;
-    if(clientResponse == NULL)
+    (void) ctx;
+    if (clientResponse == NULL)
     {
-        OC_LOG(INFO, TAG, "responseCallbacks received NULL clientResponse");
+        OIC_LOG(INFO, TAG, "responseCallbacks received NULL clientResponse");
         return   OC_STACK_DELETE_TRANSACTION;
     }
 
-    OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+    OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
     promptUser = true;
     return OC_STACK_KEEP_TRANSACTION;
 }
 
-int InitGetRequest (const char *resourceUri)
+int InitGetRequest(const char *resourceUri)
 {
-    char query[MAX_QUERY_SIZE] = {0};
-    snprintf (query, sizeof(query), "coap://%s:%u%s", coapServerIP,
-                                            coapServerPort,resourceUri);
-
-    OC_LOG_V(INFO, TAG, "Executing %s queryString is: %s", __func__, query);
-
-    return (InvokeOCDoResource(query, NULL, OC_REST_GET, responseCallbacks));
+    OIC_LOG_V(INFO, TAG, "Executing %s for resource: %s", __func__, resourceUri);
+    return (InvokeOCDoResource(resourceUri, NULL, OC_REST_GET, responseCallbacks));
 }
 
-int InitPutRequest (const char *resourceUri, OCPayload* payload)
+int InitPutRequest(const char *resourceUri, OCPayload* payload)
 {
-    char query[MAX_QUERY_SIZE] = {0};
-    snprintf (query, sizeof(query), "coap://%s:%u%s", coapServerIP, coapServerPort,
-                                                            resourceUri);
-    OC_LOG_V(INFO, TAG, "Executing %s queryString is: %s", __func__, query);
-
-    return (InvokeOCDoResource(query, payload, OC_REST_PUT, responseCallbacks));
+    OIC_LOG_V(INFO, TAG, "Executing %s for resource: %s", __func__, resourceUri);
+    return (InvokeOCDoResource(resourceUri, payload, OC_REST_PUT, responseCallbacks));
 }
 
 int InitObserveRequest(const char *resourceUri)
 {
-    OC_LOG_V(INFO, TAG, "Executing %s for resource: %s", __func__, resourceUri);
+    OIC_LOG_V(INFO, TAG, "Executing %s for resource: %s", __func__, resourceUri);
     return (InvokeOCDoResource(resourceUri, NULL, OC_REST_OBSERVE, responseCallbacks));
 }
 
-OCPayload * getSwitchStatePayload (bool state)
+OCPayload * getSwitchStatePayload(bool state)
 {
     OCRepPayload* payload = OCRepPayloadCreate();
-    if(!payload)
+    if (!payload)
     {
-       OC_LOG (ERROR, TAG, "Failed to create payload object");
+       OIC_LOG(ERROR, TAG, "Failed to create payload object");
        exit(1);
     }
     OCRepPayloadSetPropBool(payload, "value", state);
     return (OCPayload*) payload;
 }
 
-OCPayload* getChangeLevelPayload(uint32_t level)
+OCPayload* getChangeBulbTempLevelPayload(uint32_t level)
 {
     OCRepPayload* payload = OCRepPayloadCreate();
-    if(!payload)
+    if (!payload)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to create payload object");
+        exit(1);
+    }
+
+    OIC_LOG_V(INFO, TAG, "Setting level to : %u", level);
+    char value[4] = "";
+    errno = 0;
+    size_t sizeValue = sizeof(value);
+    int strRet = snprintf(value, sizeValue, "%d", level);
+    if (strRet < 0 || (size_t)strRet >= sizeValue)
     {
-        OC_LOG (ERROR, TAG, "Failed to create payload object");
+        OIC_LOG_V(ERROR, TAG, "Failed to parse string due to errno: %d", errno);
         exit(1);
     }
+    OCRepPayloadSetPropString(payload, "colourspacevalue", value);
+    return (OCPayload*) payload;
+}
 
-    OC_LOG_V(INFO, TAG, "Setting level to : %u", level);
+OCPayload* getChangeDimLevelPayload(uint32_t level)
+{
+    OCRepPayload* payload = OCRepPayloadCreate();
+    if (!payload)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to create payload object");
+        exit(1);
+    }
+
+    OIC_LOG_V(INFO, TAG, "Setting level to : %u", level);
     OCRepPayloadSetPropInt(payload, "dimmingSetting", level);
     return (OCPayload*) payload;
 }
@@ -206,38 +226,38 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
                             OCClientResponse * clientResponse)
 {
     (void)handle;
+    (void) ctx;
     if (!clientResponse)
     {
-        OC_LOG(INFO, TAG, "Discovery response is NULL");
+        OIC_LOG(INFO, TAG, "Discovery response is NULL");
         return OC_STACK_KEEP_TRANSACTION;
     }
 
-    OC_LOG_PAYLOAD(INFO, clientResponse->payload);
-    OC_LOG_V(INFO, TAG, "Discovered @ %s:%d", clientResponse->devAddr.addr,
+    OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
+    OIC_LOG_V(INFO, TAG, "Discovered @ %s:%d", clientResponse->devAddr.addr,
                                 clientResponse->devAddr.port);
 
-    coapServerIP   = OICStrdup (clientResponse->devAddr.addr);
-    coapServerPort = clientResponse->devAddr.port;
+    destinationAddress = clientResponse->devAddr;
 
-    rememberDiscoveredResources (clientResponse);
+    rememberDiscoveredResources(clientResponse);
 
     promptUser = true;
 
     return OC_STACK_KEEP_TRANSACTION;
 }
 
-OCPayload* getCustomPutPayload ()
+OCPayload* getCustomPutPayload()
 {
     OCRepPayload* payload = OCRepPayloadCreate();
-    if(!payload)
+    if (!payload)
     {
-        OC_LOG (ERROR, TAG, "Failed to create payload object");
+        OIC_LOG(ERROR, TAG, "Failed to create payload object");
         exit(1);
     }
 
-    char key[100] = {0};
-    char input[100] = {0};
-    char valueString[100] = {0};
+    char key[MAX_USER_INPUT] = {0};
+    char input[MAX_USER_INPUT] = {0};
+    char valueString[MAX_USER_INPUT] = {0};
     int value = 0;
     double valueDouble = 0.0;
     int type = -1;
@@ -246,10 +266,10 @@ OCPayload* getCustomPutPayload ()
     printf("\nType: 0:bool \t 1:int \t 2:double\n");
     while (true)
     {
-        printf ("Blank line / press ENTER to finish :");
-        char *ret = fgets (input, sizeof(input), stdin);
+        printf("Blank line / press ENTER to finish :");
+        char *ret = fgets(input, sizeof(input), stdin);
         (void) ret;
-        int inCount = sscanf (input, "%d %s %s", &type, key, valueString);
+        int inCount = sscanf(input, "%d %s %s", &type, key, valueString);
 
         if (inCount <= 0)
         {
@@ -258,7 +278,7 @@ OCPayload* getCustomPutPayload ()
         if (inCount != 3)
         {
             printf("Invalid input\n");
-            OCRepPayloadDestroy (payload);
+            OCRepPayloadDestroy(payload);
             promptUser = true;
             return NULL;
         }
@@ -286,14 +306,14 @@ OCPayload* getCustomPutPayload ()
         }
         else
         {
-            OC_LOG(ERROR, TAG, "Invalid entry. Stopping accepting key-values");
-            OCRepPayloadDestroy (payload);
+            OIC_LOG(ERROR, TAG, "Invalid entry. Stopping accepting key-values");
+            OCRepPayloadDestroy(payload);
             promptUser = true;
             return NULL;
         }
-        memset (input, 0, sizeof (input));
-        memset (key, 0, sizeof (key));
-        memset (valueString, 0, sizeof (valueString));
+        memset(input, 0, sizeof (input));
+        memset(key, 0, sizeof (key));
+        memset(valueString, 0, sizeof (valueString));
     }
 
     if (payload->values)
@@ -302,53 +322,71 @@ OCPayload* getCustomPutPayload ()
     }
     else
     {
-        OCRepPayloadDestroy (payload);
+        OCRepPayloadDestroy(payload);
         return NULL;
     }
 }
 
-void processUserInput (int resourceNo, int testCase)
+void processUserInput(int resourceNo, int testCase)
 {
+    int level = 0;
+    if (!resourceNo && !testCase)
+    {
+        testCase = TEST_QUIT;
+    }
     switch (testCase)
     {
         case TEST_GET:
-            InitGetRequest (g_discoveredResources[resourceNo].uri);
+            InitGetRequest(g_discoveredResources[resourceNo].uri);
             break;
 
         case TEST_CUSTOM_PUT:
         {
-            OCPayload *payload = getCustomPutPayload ();
+            OCPayload *payload = getCustomPutPayload();
             if (payload)
             {
-                InitPutRequest (g_discoveredResources[resourceNo].uri, payload);
+                InitPutRequest(g_discoveredResources[resourceNo].uri, payload);
             }
             else
             {
-                OC_LOG(ERROR, TAG, "Error creating payload. Not sending PUT request");
+                OIC_LOG(ERROR, TAG, "Error creating payload. Not sending PUT request");
                 promptUser = true;
             }
             break;
         }
 
         case TEST_OBSERVE:
-            InitObserveRequest (g_discoveredResources[resourceNo].uri);
+            InitObserveRequest(g_discoveredResources[resourceNo].uri);
             break;
 
         case TEST_TURN_SWITCH_ON:
-            InitPutRequest (g_discoveredResources[resourceNo].uri, getSwitchStatePayload (true));
+            InitPutRequest(g_discoveredResources[resourceNo].uri, getSwitchStatePayload (true));
             break;
 
         case TEST_TURN_SWITCH_OFF:
-            InitPutRequest (g_discoveredResources[resourceNo].uri, getSwitchStatePayload (false));
+            InitPutRequest(g_discoveredResources[resourceNo].uri, getSwitchStatePayload (false));
             break;
 
         case TEST_SET_LIGHT_BRIGHTNESS:
-            printf ("Change bulb level [0-100] to ? :");
-            int level = 0;
-            if (scanf ("%d", &level) > 0)
+            printf("Change bulb level [0-100] to ? :");
+            if (scanf("%d", &level) > 0)
+            {
+                InitPutRequest(g_discoveredResources[resourceNo].uri,
+                    getChangeDimLevelPayload (level));
+            }
+            else
+            {
+                printf("Invalid value\n");
+                promptUser = true;
+            }
+            break;
+
+        case TEST_SET_LIGHT_TEMPERATURE:
+            printf("Change bulb temp level [0-100] to ? :");
+            if (scanf("%d", &level) > 0)
             {
-                InitPutRequest (g_discoveredResources[resourceNo].uri,
-                    getChangeLevelPayload (level));
+                InitPutRequest(g_discoveredResources[resourceNo].uri,
+                    getChangeBulbTempLevelPayload(level));
             }
             else
             {
@@ -363,28 +401,28 @@ void processUserInput (int resourceNo, int testCase)
             break;
 
         case TEST_QUIT:
-            raise (SIGINT);
+            raise(SIGINT);
             break;
 
         default:
             promptUser = true;
-            OC_LOG(INFO, TAG, "Invalid test case");
+            OIC_LOG(INFO, TAG, "Invalid test case");
     }
 }
 
-void getTestCaseFromUser ()
+void getTestCaseFromUser()
 {
-    PrintResources ();
-    PrintTestCases ();
+    PrintResources();
+    PrintTestCases();
     printf("\nUsage:<resource number> <test case> :");
 
     char input[10] = {0};
-    int resourceNo = 0;
+    uint32_t resourceNo = 0;
     int testCase = 0;
 
-    char * ret = fgets (input, sizeof(input), stdin);
+    char * ret = fgets(input, sizeof(input), stdin);
     (void) ret;
-    int inCount = sscanf (input, "%d %d", &resourceNo, &testCase);
+    int inCount = sscanf(input, "%d %d", &resourceNo, &testCase);
 
     if (inCount != 2)
     {
@@ -398,10 +436,10 @@ void getTestCaseFromUser ()
         promptUser = true;
         return;
     }
-    processUserInput (resourceNo, testCase);
+    processUserInput(resourceNo, testCase);
 }
 
-OCStackResult DiscoverResources ()
+OCStackResult DiscoverResources()
 {
     OCCallbackData cbData = {
                                 .context = (void*)DEFAULT_CONTEXT_VALUE,
@@ -413,7 +451,7 @@ OCStackResult DiscoverResources ()
 
     if (ret != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCDoResource error");
+        OIC_LOG(ERROR, TAG, "OCDoResource error");
     }
     return ret;
 }
@@ -430,7 +468,7 @@ bool processSignal(bool set)
 
 void processCancel(int signal)
 {
-    if(signal == SIGINT)
+    if (signal == SIGINT)
     {
         processSignal(true);
     }
@@ -438,48 +476,50 @@ void processCancel(int signal)
 
 int main(int argc, char* argv[])
 {
+    (void) argc;
+    (void) argv;
     OCStackResult result;
-    OC_LOG(INFO, TAG, "Initializing IoTivity...");
+    OIC_LOG(INFO, TAG, "Initializing IoTivity...");
 
     result = OCInit(NULL, 0, OC_CLIENT);
     if (result != OC_STACK_OK)
     {
-        OC_LOG_V(ERROR, TAG, "OCInit Failed %d", result);
+        OIC_LOG_V(ERROR, TAG, "OCInit Failed %d", result);
         return -1;
     }
 
-    DiscoverResources ();
+    DiscoverResources();
 
     if (signal(SIGINT, processCancel) == SIG_ERR)
     {
-        OC_LOG(ERROR, TAG, "Unable to catch SIGINT, terminating...");
+        OIC_LOG(ERROR, TAG, "Unable to catch SIGINT, terminating...");
     }
     else
     {
-        OC_LOG(INFO, TAG, "Press Ctrl-C to terminate");
+        OIC_LOG(INFO, TAG, "Press Ctrl-C to terminate");
         // Loop until sigint
         while (!processSignal(false) && result == OC_STACK_OK)
         {
             result = OCProcess();
             if (result != OC_STACK_OK)
             {
-                OC_LOG_V(ERROR, TAG, "OCProcess Failed: %d", result);
+                OIC_LOG_V(ERROR, TAG, "OCProcess Failed: %d", result);
                 break;
             }
 
             if (promptUser)
             {
                 promptUser = false;
-                getTestCaseFromUser ();
+                getTestCaseFromUser();
             }
         }
     }
 
-    OC_LOG(INFO, TAG, "Stopping IoTivity...");
+    OIC_LOG(INFO, TAG, "Stopping IoTivity...");
     result = OCStop();
     if (result != OC_STACK_OK)
     {
-        OC_LOG_V(ERROR, TAG, "OCStop Failed: %d", result);
+        OIC_LOG_V(ERROR, TAG, "OCStop Failed: %d", result);
     }
 
     return 0;
index d47879c..0f403e8 100644 (file)
@@ -39,6 +39,7 @@ typedef enum
     TEST_TURN_SWITCH_ON,
     TEST_TURN_SWITCH_OFF,
     TEST_SET_LIGHT_BRIGHTNESS,
+    TEST_SET_LIGHT_TEMPERATURE,
     TEST_CYCLE,
     MAX_TESTS
 } CLIENT_TEST;
index be95b5a..dc011aa 100644 (file)
 #include <signal.h>
 #include <ocstack.h>
 #include <logger.h>
+#include "oic_string.h"
+#include "oic_malloc.h"
 
 #define TAG "IoTivityZigbeeServer"
 #define defaultComPort "/dev/ttyUSB0"
 int main()
 {
-    OC_LOG(INFO, TAG, "Initializing IoTivity...");
+    OIC_LOG(INFO, TAG, "Initializing IoTivity...");
     OCStackResult result = OCInit(NULL, 0, OC_SERVER);
     if (result != OC_STACK_OK)
     {
-        OC_LOG_V(ERROR, TAG, "OCInit Failed %d", result);
+        OIC_LOG_V(ERROR, TAG, "OCInit Failed %d", result);
         return -1;
     }
 
     result = SetPlatformInfo();
     if (result != OC_STACK_OK)
     {
-        OC_LOG_V(ERROR, TAG, "SetPlatformInfo Failed %d", result);
+        OIC_LOG_V(ERROR, TAG, "SetPlatformInfo Failed %d", result);
         goto IotivityStop;
     }
 
     result  = SetDeviceInfo();
     if (result != OC_STACK_OK)
     {
-        OC_LOG_V(ERROR, TAG, "SetPlatformInfo Failed: %d", result);
+        OIC_LOG_V(ERROR, TAG, "SetPlatformInfo Failed: %d", result);
         goto IotivityStop;
     }
 
     result  = OCStartPresence(0);
     if (result != OC_STACK_OK)
     {
-        OC_LOG_V(ERROR, TAG, "OCStartPresence Failed: %d", result);
+        OIC_LOG_V(ERROR, TAG, "OCStartPresence Failed: %d", result);
         goto IotivityStop;
     }
 
     // PIStartPlugin
     PIPlugin* plugin = NULL;
-    OC_LOG(INFO, TAG, "IoTivity Initialized properly, Starting Zigbee Plugin...");
+    OIC_LOG(INFO, TAG, "IoTivity Initialized properly, Starting Zigbee Plugin...");
     result = PIStartPlugin(defaultComPort, PLUGIN_ZIGBEE, &plugin);
     if (result != OC_STACK_OK)
     {
-        OC_LOG_V(ERROR, TAG, "Zigbee Plugin Start Failed: %d", result);
+        OIC_LOG_V(ERROR, TAG, "Zigbee Plugin Start Failed: %d", result);
         goto IotivityStop;
     }
 
     if (signal(SIGINT, processCancel) == SIG_ERR)
     {
-        OC_LOG(ERROR, TAG, "Unable to catch SIGINT, terminating...");
+        OIC_LOG(ERROR, TAG, "Unable to catch SIGINT, terminating...");
     }
     else
     {
-        OC_LOG(INFO, TAG, "Zigbee Plugin started correctly, press Ctrl-C to terminate application");
+        OIC_LOG(INFO, TAG, "Zigbee Plugin started correctly, press Ctrl-C to terminate application");
         // Loop until sigint
         while (!processSignal(false) && result == OC_STACK_OK)
         {
             result = OCProcess();
             if (result != OC_STACK_OK)
             {
-                OC_LOG_V(ERROR, TAG, "OCProcess Failed: %d", result);
+                OIC_LOG_V(ERROR, TAG, "OCProcess Failed: %d", result);
                 break;
             }
 
             result = PIProcess(plugin);
             if (result != OC_STACK_OK)
             {
-                OC_LOG_V(ERROR, TAG, "PIProcess Failed: %d", result);
+                OIC_LOG_V(ERROR, TAG, "PIProcess Failed: %d", result);
             }
         }
     }
 
-    OC_LOG(INFO, TAG, "Stopping Zigbee Plugin...");
+    OIC_LOG(INFO, TAG, "Stopping Zigbee Plugin...");
     result = PIStopPlugin(plugin);
     if (result != OC_STACK_OK)
     {
-        OC_LOG_V(ERROR, TAG, "Zigbee Plugin Stop Failed: %d", result);
+        OIC_LOG_V(ERROR, TAG, "Zigbee Plugin Stop Failed: %d", result);
     }
-    OC_LOG(INFO, TAG, "Zigbee Plugin Stopped");
+    OIC_LOG(INFO, TAG, "Zigbee Plugin Stopped");
     // OCStop
 IotivityStop:
-    OC_LOG(INFO, TAG, "Stopping IoTivity...");
+    OIC_LOG(INFO, TAG, "Stopping IoTivity...");
     result = OCStop();
     if (result != OC_STACK_OK)
     {
-        OC_LOG_V(ERROR, TAG, "OCStop Failed: %d", result);
+        OIC_LOG_V(ERROR, TAG, "OCStop Failed: %d", result);
         return 0;
     }
 
-    OC_LOG(INFO, TAG, "Application Completed Successfully");
+    OIC_LOG(INFO, TAG, "Application Completed Successfully");
     return 0;
 }
 
@@ -134,11 +136,14 @@ OCStackResult SetPlatformInfo()
 
 OCStackResult SetDeviceInfo()
 {
-    static const OCDeviceInfo deviceInfo =
+    static OCDeviceInfo deviceInfo =
         {
-            .deviceName = "IoTivity/Zigbee Server Sample"
+            .deviceName = "IoTivity/Zigbee Server Sample",
         };
-
+    char *dup = OICStrdup("oic.wk.d");
+    deviceInfo.types = (OCStringLL *)OICCalloc(1, sizeof(OCStringLL));
+    deviceInfo.types->value = dup;
+    OICFree(dup);
     return OCSetDeviceInfo(deviceInfo);
 }
 
@@ -160,4 +165,3 @@ void processCancel(int signal)
         processSignal(true);
     }
 }
-
index 55f0b7d..939084d 100644 (file)
@@ -37,6 +37,7 @@ print"Reading PI script"
 
 env.PrependUnique(CPPPATH = [ os.path.join(src_dir, 'resource', 'c_common', 'oic_malloc', 'include'),
                               os.path.join(src_dir, 'resource', 'c_common', 'oic_string', 'include'),
+                              os.path.join(src_dir, 'resource', 'c_common', 'oic_time', 'include'),
                               os.path.join(src_dir, 'resource', 'oc_logger', 'include'),
                               os.path.join(src_dir, 'resource', 'csdk', 'logger', 'include'),
                               os.path.join(src_dir, 'resource', 'csdk', 'stack', 'include'),
index 29ce028..483a3a5 100644 (file)
@@ -48,7 +48,7 @@ OCEntityHandlerResult PluginInterfaceEntityHandler(OCEntityHandlerFlag flag,
 {
     if (!entityHandlerRequest)
     {
-        OC_LOG (ERROR, TAG, "Invalid request pointer");
+        OIC_LOG (ERROR, TAG, "Invalid request pointer");
         return OC_EH_ERROR;
     }
 
@@ -88,13 +88,22 @@ OCEntityHandlerResult PluginInterfaceEntityHandler(OCEntityHandlerFlag flag,
         result = OCDoResponse(response);
         if (result != OC_STACK_OK)
         {
-            OC_LOG_V(ERROR, TAG, "Error sending response %u", result);
+            OIC_LOG_V(ERROR, TAG, "Error sending response %u", result);
             ehResult = OC_EH_ERROR;
         }
     }
     else
     {
-        OC_LOG_V(ERROR, TAG, "Error handling request %u", ehResult);
+        OIC_LOG_V(ERROR, TAG, "Error handling request %u", ehResult);
+        PIResource * piResource = NULL;
+        result = GetResourceFromHandle(plugin, &piResource, response->resourceHandle);
+        OIC_LOG_V(ERROR, TAG, "Deleting resource \"%s\" because of failed request.", piResource->uri);
+        result = DeleteResource(plugin, piResource);
+        if(result != OC_STACK_OK)
+        {
+            OIC_LOG_V(ERROR, TAG, "Failed to delete resource after failed request.");
+            ehResult = OC_EH_ERROR;
+        }
     }
 
     OCPayloadDestroy(response->payload);
@@ -123,31 +132,23 @@ void piNewResourceCB(PIPluginBase * p_plugin, PIResourceBase * r_newResource)
         OICFree (r_newResource);
         return;
     }
-    OC_LOG_V(INFO, TAG, "Created resource of type: %s\n",
+    OIC_LOG_V(INFO, TAG, "Created resource of type: %s\n",
         r_newResource->piResource.resourceTypeName);
 
     result = AddResourceToPlugin(p_plugin, r_newResource);
 }
 
-void piObserveNotificationUpdate(PIPluginBase * plugin, const char * uri)
+void piObserveNotificationUpdate(PIPluginBase * plugin, OCResourceHandle resourceHandle)
 {
-    if(!plugin || !uri)
+    if(!plugin)
     {
         return;
     }
-    PIResource * piResource = NULL;
 
-    OCStackResult result = GetResourceFromURI(plugin, &piResource, uri);
-    if(result != OC_STACK_OK)
-    {
-        OC_LOG(ERROR, TAG, "Failed to find a matching URI based on observe notification update.");
-        return;
-    }
-
-    result = OCNotifyAllObservers(piResource->resourceHandle, OC_LOW_QOS);
+    OCStackResult result = OCNotifyAllObservers(resourceHandle, OC_LOW_QOS);
     if(result != OC_STACK_OK && result != OC_STACK_NO_OBSERVERS)
     {
-        OC_LOG_V(ERROR, TAG, "Failed to notify observers of update. Result: %d", result);
+        OIC_LOG_V(ERROR, TAG, "Failed to notify observers of update. Result: %d", result);
     }
 }
 
@@ -172,10 +173,10 @@ OCStackResult PIStartPlugin(const char * comPort, PIPluginType pluginType, PIPlu
         {
             return OC_STACK_ERROR;
         }
-        result = AddPlugin((PIPluginBase *) *plugin);
-        if (result == OC_STACK_OK)
+        result = AddPlugin((PIPluginBase *)*plugin);
+        if(result != OC_STACK_OK)
         {
-            result = ZigbeeDiscover((PIPlugin_Zigbee *) plugin);
+            return result;
         }
     }
     return result;
@@ -196,6 +197,24 @@ OCStackResult PIStopAll()
     return DeletePluginList();
 }
 
+OCStackResult PISetup(PIPlugin * plugin)
+{
+    if (!plugin)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+    OCStackResult result = OC_STACK_ERROR;
+    if (((PIPluginBase *)plugin)->type == PLUGIN_ZIGBEE)
+    {
+        result = ZigbeeDiscover((PIPlugin_Zigbee *) plugin);
+        if( result != OC_STACK_OK)
+        {
+            return result;
+        }
+    }
+    return result;
+}
+
 OCStackResult PIProcess(PIPlugin * p_plugin)
 {
     PIPluginBase * plugin = (PIPluginBase *) p_plugin;
index cf9a331..01c7adc 100644 (file)
@@ -26,6 +26,7 @@
 #include "zigbee_wrapper.h"
 #include "utlist.h"
 #include "oic_malloc.h"
+#include "oic_string.h"
 #include "ocstack.h"
 #include "logger.h"
 
@@ -101,28 +102,72 @@ OCStackResult GetResourceFromHandle(PIPluginBase * plugin, PIResource ** piResou
     return OC_STACK_NO_RESOURCE;
 }
 
-OCStackResult GetResourceFromURI(PIPluginBase * plugin, PIResource ** piResource,
-                                    const char * uri)
+static bool ZigbeeStrEquals(const char * s1, const char * s2, size_t s1_length, size_t s2_length)
 {
-    if (!plugin || !piResource || !uri)
+    if (!s1 || !s2 || s1_length == 0 || s2_length == 0)
     {
+        return false;
+    }
+    if (s1_length == s2_length && memcmp(s1, s2, (s1_length + 1)) == 0)
+    {
+        return true;
+    }
+    return false;
+}
+
+OCStackResult GetResourceFromZigBeeNodeId(PIPluginBase * plugin,
+                                          PIResource_Zigbee ** piResource,
+                                          const char * nodeId,
+                                          const char * endpointId,
+                                          const char * clusterId)
+{
+    OIC_LOG(INFO, TAG, "Entered GetResourceFromZigBeeNodeId().");
+    if(!plugin || !piResource || !nodeId || !clusterId || !endpointId)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid param.");
         return OC_STACK_INVALID_PARAM;
     }
+    if(plugin->type != PLUGIN_ZIGBEE)
+    {
+        OIC_LOG(ERROR, TAG, "Plugin Type is not Zigbee.");
+        return OC_STACK_INVALID_PARAM;
+    }
+
     PIResourceBase * out = NULL;
     PIResourceBase * tmp = NULL;
-    size_t checkUriLength = strlen(uri);
-    size_t indexUriLength = 0;
-    size_t minLength = 0;
+    size_t checkNodeIdLength = strlen(nodeId);
+    size_t checkEndpointIdLength = strlen(endpointId);
+    size_t checkClusterIdLength = strlen(clusterId);
+    size_t indexLength = 0;
     LL_FOREACH_SAFE(plugin->resourceList, out, tmp)
     {
-        indexUriLength = strlen(out->piResource.uri);
-        minLength = indexUriLength > checkUriLength ? checkUriLength : indexUriLength;
-        if ((checkUriLength == indexUriLength) &&
-            memcmp(out->piResource.uri, uri, minLength + 1) == 0)
+        indexLength = strlen(((PIResource_Zigbee *)out)->nodeId);
+        if(ZigbeeStrEquals(nodeId,
+                           ((PIResource_Zigbee *)out)->nodeId,
+                           checkNodeIdLength,
+                           indexLength) == false)
         {
-            *piResource = (PIResource *) out;
-            return OC_STACK_OK;
+            continue;
+        }
+        indexLength = strlen(((PIResource_Zigbee *)out)->endpointId);
+        if(ZigbeeStrEquals(endpointId,
+                           ((PIResource_Zigbee *)out)->endpointId,
+                           checkEndpointIdLength,
+                           indexLength) == false)
+        {
+            continue;
+        }
+        indexLength = strlen(((PIResource_Zigbee *)out)->clusterId);
+        if(ZigbeeStrEquals(clusterId,
+                           ((PIResource_Zigbee *)out)->clusterId,
+                           checkClusterIdLength,
+                           indexLength) == false)
+        {
+            continue;
         }
+        OIC_LOG_V(INFO, TAG, "Found a match! URI = %s", out->piResource.uri);
+        *piResource = (PIResource_Zigbee *) out;
+        return OC_STACK_OK;
     }
     *piResource = NULL;
     return OC_STACK_NO_RESOURCE;
@@ -140,6 +185,33 @@ OCStackResult AddResourceToPlugin (PIPluginBase * plugin, PIResourceBase * resou
     return OC_STACK_NO_MEMORY;
 }
 
+OCStackResult UpdateZigbeeResourceNodeId(PIPluginBase * plugin,
+                                         const char * eui,
+                                         const char * nodeId)
+{
+    if (!plugin || !eui || !nodeId)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+    if(plugin->type != PLUGIN_ZIGBEE)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+    PIResourceBase * out = NULL;
+    PIResourceBase * tmp = NULL;
+    size_t checkLength = strlen(eui);
+    LL_FOREACH_SAFE(plugin->resourceList, out, tmp)
+    {
+        size_t indexLength = strlen(((PIResource_Zigbee *)out)->eui);
+        if(ZigbeeStrEquals(eui, ((PIResource_Zigbee *)out)->eui, checkLength, indexLength) != true)
+        {
+            continue;
+        }
+        OICStrcpy(((PIResource_Zigbee *)out)->nodeId, (strlen(nodeId)+1)*sizeof(char), nodeId);
+    }
+    return OC_STACK_OK;
+}
+
 OCStackResult DeleteResource(PIPluginBase * plugin, PIResourceBase * resource)
 {
     if (!plugin || !resource)
@@ -155,7 +227,7 @@ OCStackResult DeleteResource(PIPluginBase * plugin, PIResourceBase * resource)
     OCStackResult result = OCDeleteResource(resource->piResource.resourceHandle);
     if(result != OC_STACK_OK)
     {
-        OC_LOG_V(ERROR, TAG, "Failed to delete resource with error: %d", result);
+        OIC_LOG_V(ERROR, TAG, "Failed to delete resource with error: %d", result);
         return result;
     }
 
index 929d184..ee17a9b 100644 (file)
 #include <math.h>
 #include <errno.h>
 
+// The following #define must be here under "math.h".
+// This ifdef ensures that "__STDC_IEC_559__" is defined. If it is defined,
+// then we are guaranteed that the 'double' type is 64-bit. Otherwise, the
+// compilation of this file should fail because we are no longer guaranteed.
+#ifndef __STDC_IEC_559__
+#error "Requires IEEE 754 floating point!"
+#endif
+
 #include "zigbee_wrapper.h"
 #include "telegesis_wrapper.h"
 #include "pluginlist.h"
 #define ZB_ON_OFF_CLUSTER                    "0006"
 #define ZB_ON_OFF_ATTRIBUTE_ID               "0000"
 #define ZB_IAS_ZONE_TYPE_ATTRIBUTE_ID        "0001"
+#define ZB_COLOR_CONTROL_CLUSTER             "0300"
+#define ZB_COLOR_TEMPERATURE_ATTRIBUTE_ID    "0007"
 
-#define IAS_ZONE_TYPE_MOTION_SENSOR          "000d"
+#define IAS_ZONE_TYPE_MOTION_SENSOR          "000D"
 #define IAS_ZONE_TYPE_CONTACT_SENSOR         "0015"
-#define IAS_ZONE_TYPE_WATER_SENSOR           "002a"
+#define IAS_ZONE_TYPE_WATER_SENSOR           "002A"
 
 #define ZB_DATA_TYPE_NULL                    "00"
 #define ZB_DATA_TYPE_1_BYTE                  "08"
@@ -100,13 +110,15 @@ static const char* OIC_CONTACT_SENSOR = "oic.r.sensor.contact";
 static const char* OIC_MOTION_SENSOR = "oic.r.sensor.motion";
 static const char* OIC_WATER_SENSOR = "oic.r.sensor.water";
 static const char* OIC_BINARY_SWITCH = "oic.r.switch.binary";
+static const char* OIC_CHROMA_LIGHT = "oic.r.colour.chroma";
 
 static const char* OIC_TEMPERATURE_ATTRIBUTE = "temperature";
 static const char* OIC_DIMMING_ATTRIBUTE = "dimmingSetting";
 static const char* OIC_CONTACT_ATTRIBUTE = "value";
+static const char* OIC_WATER_ATTRIBUTE = "value";
+static const char* OIC_MOTION_ATTRIBUTE = "value";
 static const char* OIC_ON_OFF_ATTRIBUTE = "value";
-
-PIPlugin_Zigbee ** gPlugin = NULL;
+static const char* OIC_COLOUR_TEMPERATURE_ATTRIBUTE = "colourspacevalue";
 
 typedef enum
 {
@@ -185,9 +197,9 @@ bool getZigBeeAttributesIfValid(const char * OICResourceType,
                                     AttributeList *attributeList,
                                     OCRepPayload *payload);
 
-const char * getResourceTypeForIASZoneType(TWDevice *device)
+const char * getResourceTypeForIASZoneType(TWDevice *device, PIPluginBase* plugin)
 {
-    if(!device)
+    if (!device)
     {
         return NULL;
     }
@@ -202,30 +214,31 @@ const char * getResourceTypeForIASZoneType(TWDevice *device)
         ZB_IAS_ZONE_CLUSTER,
         ZB_IAS_ZONE_TYPE_ATTRIBUTE_ID,
         &IASZoneType,
-        &length
+        &length,
+        (PIPlugin_Zigbee*)plugin
     );
 
     if (ret != OC_STACK_OK || !IASZoneType)
     {
-        OC_LOG_V (ERROR, TAG, "Error %u getting IAS Zone Type", ret);
+        OIC_LOG_V(ERROR, TAG, "Error %u getting IAS Zone Type", ret);
         return NULL;
     }
 
-    if (strcmp (IASZoneType, IAS_ZONE_TYPE_CONTACT_SENSOR) == 0)
+    if (strcmp(IASZoneType, IAS_ZONE_TYPE_CONTACT_SENSOR) == 0)
     {
         resourceType = OIC_CONTACT_SENSOR;
     }
-    else if (strcmp (IASZoneType, IAS_ZONE_TYPE_MOTION_SENSOR) == 0)
+    else if (strcmp(IASZoneType, IAS_ZONE_TYPE_MOTION_SENSOR) == 0)
     {
         resourceType = OIC_MOTION_SENSOR;
     }
-    else if (strcmp (IASZoneType, IAS_ZONE_TYPE_WATER_SENSOR) == 0)
+    else if (strcmp(IASZoneType, IAS_ZONE_TYPE_WATER_SENSOR) == 0)
     {
         resourceType = OIC_WATER_SENSOR;
     }
     else
     {
-        OC_LOG_V (ERROR, TAG, "Unsupported Zone Type %s", IASZoneType);
+        OIC_LOG_V(ERROR, TAG, "Unsupported Zone Type %s", IASZoneType);
         resourceType = NULL;
     }
 
@@ -236,18 +249,18 @@ const char * getResourceTypeForIASZoneType(TWDevice *device)
 
 OCStackResult buildURI(char ** output,
                        const char * prefix,
-                       const char * nodeId,
+                       const char * eui,
                        const char * endpointId,
                        const char * clusterId)
 {
-    if(!output || !prefix || !nodeId || !endpointId || !clusterId)
+    if(!output || !prefix || !eui || !endpointId || !clusterId)
     {
         return OC_STACK_INVALID_PARAM;
     }
     const char LEN_SEPARATOR[] = "/";
     size_t lenSeparatorSize = sizeof(LEN_SEPARATOR) - 1;
     size_t newUriSize = strlen(prefix) + lenSeparatorSize +
-                        strlen(nodeId) + lenSeparatorSize +
+                        strlen(eui) + lenSeparatorSize +
                         strlen(endpointId) + lenSeparatorSize +
                         strlen(clusterId)
                         + 1; // NULL Terminator
@@ -255,42 +268,42 @@ OCStackResult buildURI(char ** output,
 
     if (!*output)
     {
-        OC_LOG (ERROR, TAG, "Out of memory");
+        OIC_LOG(ERROR, TAG, "Out of memory");
         return OC_STACK_NO_MEMORY;
     }
 
     char * temp = OICStrcpy(*output, newUriSize, prefix);
-    if(temp != *output)
+    if (temp != *output)
     {
         goto exit;
     }
     temp = OICStrcat(*output, newUriSize, LEN_SEPARATOR);
-    if(temp != *output)
+    if (temp != *output)
     {
         goto exit;
     }
-    temp = OICStrcat(*output, newUriSize, nodeId);
-    if(temp != *output)
+    temp = OICStrcat(*output, newUriSize, eui);
+    if (temp != *output)
     {
         goto exit;
     }
     temp = OICStrcat(*output, newUriSize, LEN_SEPARATOR);
-    if(temp != *output)
+    if (temp != *output)
     {
         goto exit;
     }
     temp = OICStrcat(*output, newUriSize, endpointId);
-    if(temp != *output)
+    if (temp != *output)
     {
         goto exit;
     }
     temp = OICStrcat(*output, newUriSize, LEN_SEPARATOR);
-    if(temp != *output)
+    if (temp != *output)
     {
         goto exit;
     }
     temp = OICStrcat(*output, newUriSize, clusterId);
-    if(temp != *output)
+    if (temp != *output)
     {
         goto exit;
     }
@@ -303,31 +316,31 @@ exit:
     return OC_STACK_NO_MEMORY;
 }
 
-void foundZigbeeCallback(TWDevice *device)
+void foundZigbeeCallback(TWDevice *device, PIPlugin_Zigbee* plugin)
 {
-    if(!device)
+    if (!device)
     {
-        OC_LOG(ERROR, TAG, "foundZigbeeCallback: Invalid parameter.");
+        OIC_LOG(ERROR, TAG, "foundZigbeeCallback: Invalid parameter.");
         return;
     }
     int count = device->endpointOfInterest->clusterList->count;
-    for(int i=0; i < count; i++)
+    for (int i=0; i < count; i++)
     {
         PIResource_Zigbee *piResource = (PIResource_Zigbee *) OICMalloc(sizeof(*piResource));
         if (!piResource)
         {
-            OC_LOG (ERROR, TAG, "Out of memory");
+            OIC_LOG(ERROR, TAG, "Out of memory");
             return;
         }
-        piResource->header.plugin = (PIPluginBase *)gPlugin;
+        piResource->header.plugin = (PIPluginBase *)plugin;
 
         OCStackResult result = buildURI(&piResource->header.piResource.uri,
                                 PI_ZIGBEE_PREFIX,
-                                device->nodeId,
+                                device->eui,
                                 device->endpointOfInterest->endpointId,
                                 device->endpointOfInterest->clusterList->clusterIds[i].clusterId);
 
-        if(result != OC_STACK_OK)
+        if (result != OC_STACK_OK)
         {
             OICFree(piResource);
             return;
@@ -336,19 +349,20 @@ void foundZigbeeCallback(TWDevice *device)
         char * foundClusterID =
             device->endpointOfInterest->clusterList->clusterIds[i].clusterId;
 
-        if (strcmp (foundClusterID, ZB_IAS_ZONE_CLUSTER) == 0)
+        if (strcmp(foundClusterID, ZB_IAS_ZONE_CLUSTER) == 0)
         {
             piResource->header.piResource.resourceTypeName
-                = getResourceTypeForIASZoneType (device);
+                = getResourceTypeForIASZoneType (device, (PIPluginBase *)plugin);
 
-            OCStackResult ret = TWListenForStatusUpdates (device->nodeId,
-                                      device->endpointOfInterest->endpointId);
+            OCStackResult ret = TWListenForStatusUpdates(device->nodeId,
+                                                          device->endpointOfInterest->endpointId,
+                                                          plugin);
 
             if (ret != OC_STACK_OK)
             {
                 // Just log it and move on if this fails?
                 // or not create this resource at all?
-                OC_LOG (ERROR, TAG, "Command to listen for status updates failed");
+                OIC_LOG(ERROR, TAG, "Command to listen for status updates failed");
             }
         }
         else
@@ -357,9 +371,9 @@ void foundZigbeeCallback(TWDevice *device)
                     (char *) ZigBeeClusterIDToOICResourceType(foundClusterID);
         }
 
-        if(piResource->header.piResource.resourceTypeName == NULL)
+        if (piResource->header.piResource.resourceTypeName == NULL)
         {
-            OC_LOG_V (ERROR, TAG, "unsupported clusterId : %s",
+            OIC_LOG_V(ERROR, TAG, "unsupported clusterId : %s",
                 device->endpointOfInterest->clusterList->clusterIds[i].clusterId);
             OICFree(piResource->header.piResource.uri);
             OICFree(piResource);
@@ -375,43 +389,58 @@ void foundZigbeeCallback(TWDevice *device)
         piResource->endpointId = OICStrdup(device->endpointOfInterest->endpointId);
         piResource->clusterId =
             OICStrdup(device->endpointOfInterest->clusterList->clusterIds[i].clusterId);
-        (*gPlugin)->header.NewResourceFoundCB(&(*gPlugin)->header, &piResource->header);
+        plugin->header.NewResourceFoundCB(&(plugin)->header, &piResource->header);
     }
 }
 
-void zigbeeZoneStatusUpdate(TWUpdate * update)
+void zigbeeZoneStatusUpdate(TWUpdate * update, PIPlugin_Zigbee* plugin)
 {
-    if(!update)
+    if (!update)
     {
         return;
     }
 
-    char * uri = NULL;
-    OCStackResult result = buildURI(&uri,
-                                    PI_ZIGBEE_PREFIX,
-                                    update->nodeId,
-                                    update->endpoint,
-                                    ZB_IAS_ZONE_CLUSTER);
-    if(result != OC_STACK_OK || !uri)
+    PIResource_Zigbee * piResource = NULL;
+    OCStackResult result = GetResourceFromZigBeeNodeId((PIPluginBase *)plugin,
+                                                    &piResource,
+                                                    update->nodeId,
+                                                    update->endpoint,
+                                                    ZB_IAS_ZONE_CLUSTER);
+    if (result != OC_STACK_OK || !piResource)
     {
-        OC_LOG_V(ERROR, TAG, "Failed to build URI with result: %d", result);
+        OIC_LOG_V(ERROR, TAG, "Failed to retrieve resource handle with result: %d", result);
         return;
     }
 
-    (*gPlugin)->header.ObserveNotificationUpdate((PIPluginBase *)*gPlugin, uri);
-    OICFree(uri);
+    plugin->header.ObserveNotificationUpdate((PIPluginBase *)plugin,
+                                                 piResource->header.piResource.resourceHandle);
+}
+
+void deviceNodeIdChanged(const char * eui, const char * nodeId, PIPlugin_Zigbee* plugin)
+{
+    if(!eui || !nodeId)
+    {
+        return;
+    }
+    OCStackResult result = UpdateZigbeeResourceNodeId((PIPluginBase *)plugin,
+                                                  eui,
+                                                  nodeId);
+    if(result != OC_STACK_OK)
+    {
+        OIC_LOG_V(ERROR, TAG, "Failed to update Zigbee Resource NodeId due to result: %s", result);
+    }
 }
 
 OCStackResult ZigbeeInit(const char * comPort, PIPlugin_Zigbee ** plugin,
                          PINewResourceFound newResourceCB,
                          PIObserveNotificationUpdate observeNotificationUpdate)
 {
-    if(!plugin)
+    if (!plugin)
     {
         return OC_STACK_INVALID_PARAM;
     }
     *plugin = (PIPlugin_Zigbee *) OICMalloc(sizeof(PIPlugin_Zigbee) + sizeof(PIPluginBase));
-    if(!*plugin)
+    if (!*plugin)
     {
         return OC_STACK_NO_MEMORY;
     }
@@ -423,37 +452,39 @@ OCStackResult ZigbeeInit(const char * comPort, PIPlugin_Zigbee ** plugin,
     ((*plugin)->header).resourceList = NULL;
     ((*plugin)->header).processEHRequest = ProcessEHRequest;
 
-    gPlugin = plugin;
-    OCStackResult result = TWInitialize(comPort);
+    OCStackResult result = TWInitialize(*plugin, comPort);
+    if (result != OC_STACK_OK)
+    {
+        return result;
+    }
+    result = TWSetStatusUpdateCallback(zigbeeZoneStatusUpdate, *plugin);
     if(result != OC_STACK_OK)
     {
         return result;
     }
-
-    return TWSetStatusUpdateCallback(zigbeeZoneStatusUpdate);
+    return TWSetEndDeviceNodeIdChangedCallback(deviceNodeIdChanged, *plugin);
 }
 
 OCStackResult ZigbeeDiscover(PIPlugin_Zigbee * plugin)
 {
     OCStackResult result = OC_STACK_ERROR;
-    (void)plugin;
-    TWSetDiscoveryCallback(foundZigbeeCallback);
-    result = TWDiscover(NULL);
-    OC_LOG_V (DEBUG, TAG, "ZigbeeDiscover : Status = %d\n", result);
+    TWSetDiscoveryCallback(foundZigbeeCallback, plugin);
+    result = TWDiscover(plugin);
+    OIC_LOG_V(DEBUG, TAG, "ZigbeeDiscover : Status = %d\n", result);
 
     return result;
 }
 
 OCStackResult ZigbeeStop(PIPlugin_Zigbee * plugin)
 {
+    OCStackResult ret = TWUninitialize(plugin);
     free(plugin);
-    return TWUninitialize();
+    return ret;
 }
 
 OCStackResult ZigbeeProcess(PIPlugin_Zigbee * plugin)
 {
-    (void)plugin;
-    return TWProcess();
+    return TWProcess(plugin);
 }
 
 // Function returns an OIC Smart Home resource Type
@@ -462,6 +493,10 @@ OCStackResult ZigbeeProcess(PIPlugin_Zigbee * plugin)
 // NOTE: The returned string is NOT malloc'ed.
 const char* ZigBeeClusterIDToOICResourceType(const char * clusterID) //Discovery/CreateResource
 {
+    if (!clusterID)
+    {
+        return NULL;
+    }
     if (strcmp(clusterID, ZB_TEMPERATURE_CLUSTER) == 0)
     {
         return OIC_TEMPERATURE_SENSOR;
@@ -478,6 +513,10 @@ const char* ZigBeeClusterIDToOICResourceType(const char * clusterID) //Discovery
     {
         return OIC_BINARY_SWITCH;
     }
+    else if (strcmp(clusterID, ZB_COLOR_CONTROL_CLUSTER) == 0)
+    {
+        return OIC_CHROMA_LIGHT;
+    }
     else
     {
         return NULL;
@@ -486,6 +525,10 @@ const char* ZigBeeClusterIDToOICResourceType(const char * clusterID) //Discovery
 
 const char* OICResourceToZigBeeClusterID(char *oicResourceType)
 {
+    if (!oicResourceType)
+    {
+        return NULL;
+    }
     if (strcmp(oicResourceType, OIC_TEMPERATURE_SENSOR) == 0)
     {
         return ZB_TEMPERATURE_CLUSTER;
@@ -506,6 +549,10 @@ const char* OICResourceToZigBeeClusterID(char *oicResourceType)
     {
         return ZB_INDICATOR_CLUSTER;
     }
+    else if (strcmp(oicResourceType, OIC_CHROMA_LIGHT) == 0)
+    {
+        return ZB_COLOR_CONTROL_CLUSTER;
+    }
     else
     {
         return NULL;
@@ -515,7 +562,11 @@ const char* OICResourceToZigBeeClusterID(char *oicResourceType)
 OCStackResult getZigBeeAttributesForOICResource(const char * OICResourceType,
                                                     AttributeList *attributeList) // GET
 {
-    if (strcmp (OICResourceType, OIC_TEMPERATURE_SENSOR) == 0)
+    if (!OICResourceType || !attributeList)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+    if (strcmp(OICResourceType, OIC_TEMPERATURE_SENSOR) == 0)
     {
         attributeList->count = 1;
         attributeList->list[0].oicAttribute = OICStrdup(OIC_TEMPERATURE_ATTRIBUTE);
@@ -524,7 +575,7 @@ OCStackResult getZigBeeAttributesForOICResource(const char * OICResourceType,
         attributeList->list[0].zigbeeType = ZB_16_SINT;
         return OC_STACK_OK;
     }
-    else if (strcmp (OICResourceType, OIC_DIMMABLE_LIGHT) == 0)
+    else if (strcmp(OICResourceType, OIC_DIMMABLE_LIGHT) == 0)
     {
         attributeList->count = 1;
         attributeList->list[0].oicAttribute = OICStrdup(OIC_DIMMING_ATTRIBUTE);
@@ -533,7 +584,7 @@ OCStackResult getZigBeeAttributesForOICResource(const char * OICResourceType,
         attributeList->list[0].zigbeeType = ZB_8_UINT;
         return OC_STACK_OK;
     }
-    else if (strcmp (OICResourceType, OIC_CONTACT_SENSOR) == 0)
+    else if (strcmp(OICResourceType, OIC_CONTACT_SENSOR) == 0)
     {
         attributeList->count = 1;
         attributeList->list[0].oicAttribute = OICStrdup(OIC_CONTACT_ATTRIBUTE);
@@ -542,7 +593,25 @@ OCStackResult getZigBeeAttributesForOICResource(const char * OICResourceType,
         attributeList->list[0].zigbeeType = ZB_BOOL;
         return OC_STACK_OK;
     }
-    else if (strcmp (OICResourceType, OIC_BINARY_SWITCH) == 0)
+    else if (strcmp(OICResourceType, OIC_WATER_SENSOR) == 0)
+    {
+        attributeList->count = 1;
+        attributeList->list[0].oicAttribute = OICStrdup(OIC_WATER_ATTRIBUTE);
+        attributeList->list[0].zigBeeAttribute = ZB_IAS_ZONE_STATUS_ATTRIBUTE_ID;
+        attributeList->list[0].oicType = OIC_ATTR_BOOL;
+        attributeList->list[0].zigbeeType = ZB_BOOL;
+        return OC_STACK_OK;
+    }
+    else if (strcmp(OICResourceType, OIC_MOTION_SENSOR) == 0)
+    {
+        attributeList->count = 1;
+        attributeList->list[0].oicAttribute = OICStrdup(OIC_MOTION_ATTRIBUTE);
+        attributeList->list[0].zigBeeAttribute = ZB_IAS_ZONE_STATUS_ATTRIBUTE_ID;
+        attributeList->list[0].oicType = OIC_ATTR_BOOL;
+        attributeList->list[0].zigbeeType = ZB_BOOL;
+        return OC_STACK_OK;
+    }
+    else if (strcmp(OICResourceType, OIC_BINARY_SWITCH) == 0)
     {
         attributeList->count = 1;
         attributeList->list[0].oicAttribute = OICStrdup(OIC_ON_OFF_ATTRIBUTE);
@@ -551,6 +620,15 @@ OCStackResult getZigBeeAttributesForOICResource(const char * OICResourceType,
         attributeList->list[0].zigbeeType = ZB_BOOL;
         return OC_STACK_OK;
     }
+    else if (strcmp(OICResourceType, OIC_CHROMA_LIGHT) == 0)
+    {
+        attributeList->count = 1;
+        attributeList->list[0].oicAttribute = OICStrdup(OIC_COLOUR_TEMPERATURE_ATTRIBUTE);
+        attributeList->list[0].zigBeeAttribute = ZB_COLOR_TEMPERATURE_ATTRIBUTE_ID;
+        attributeList->list[0].oicType = OIC_ATTR_INT;
+        attributeList->list[0].zigbeeType = ZB_16_UINT;
+        return OC_STACK_OK;
+    }
 
     return OC_STACK_ERROR;
 }
@@ -559,18 +637,18 @@ bool getZigBeeAttributesIfValid(const char * OICResourceType,
                                     AttributeList *attributeList,
                                     OCRepPayload *payload) // Put
 {
-    if(!OICResourceType)
+    if (!OICResourceType)
     {
         return false;
     }
-    if(strcmp(OICResourceType, OIC_TEMPERATURE_SENSOR) == 0)
+    if (strcmp(OICResourceType, OIC_TEMPERATURE_SENSOR) == 0)
     {
         // Cant really PUT on the temp sensor, but the code is still there.
         int64_t temperature = 0;
 
         // TODO: This if should only look for attributes it supports and ignore the rest
         // or examine every attribute in the payload and complain about unsupported attributes?
-        if(OCRepPayloadGetPropInt(payload, OIC_TEMPERATURE_ATTRIBUTE, &temperature))
+        if (OCRepPayloadGetPropInt(payload, OIC_TEMPERATURE_ATTRIBUTE, &temperature))
         {
             attributeList->count = 1;
             attributeList->list[0].oicAttribute = OICStrdup(OIC_TEMPERATURE_ATTRIBUTE);
@@ -583,11 +661,11 @@ bool getZigBeeAttributesIfValid(const char * OICResourceType,
             return true;
         }
     }
-    else if (strcmp (OICResourceType, OIC_DIMMABLE_LIGHT) == 0)
+    else if (strcmp(OICResourceType, OIC_DIMMABLE_LIGHT) == 0)
     {
         int64_t onLevel = 0;
 
-        if(OCRepPayloadGetPropInt(payload, OIC_DIMMING_ATTRIBUTE, &onLevel))
+        if (OCRepPayloadGetPropInt(payload, OIC_DIMMING_ATTRIBUTE, &onLevel))
         {
             attributeList->count = 1;
             attributeList->list[0].oicAttribute = OICStrdup(OIC_DIMMING_ATTRIBUTE);
@@ -601,11 +679,11 @@ bool getZigBeeAttributesIfValid(const char * OICResourceType,
             return true;
         }
     }
-    else if (strcmp (OICResourceType, OIC_CONTACT_SENSOR) == 0)
+    else if (strcmp(OICResourceType, OIC_CONTACT_SENSOR) == 0)
     {
         int64_t value = 0;
 
-        if(OCRepPayloadGetPropInt(payload, OIC_CONTACT_ATTRIBUTE, &value))
+        if (OCRepPayloadGetPropInt(payload, OIC_CONTACT_ATTRIBUTE, &value))
         {
             attributeList->count = 1;
             attributeList->list[0].oicAttribute = OICStrdup(OIC_CONTACT_ATTRIBUTE);
@@ -618,11 +696,28 @@ bool getZigBeeAttributesIfValid(const char * OICResourceType,
             return true;
         }
     }
-    else if (strcmp (OICResourceType, OIC_BINARY_SWITCH) == 0)
+    else if (strcmp(OICResourceType, OIC_WATER_SENSOR) == 0)
+    {
+        int64_t value = 0;
+
+        if (OCRepPayloadGetPropInt(payload, OIC_WATER_ATTRIBUTE, &value))
+        {
+            attributeList->count = 1;
+            attributeList->list[0].oicAttribute = OICStrdup(OIC_WATER_ATTRIBUTE);
+            attributeList->list[0].zigBeeAttribute = ZB_IAS_ZONE_STATUS_ATTRIBUTE_ID;
+            attributeList->list[0].oicType = OIC_ATTR_BOOL;
+            attributeList->list[0].val.i = value;
+            attributeList->list[0].zigbeeType = ZB_BOOL;
+            attributeList->CIEMask = (CIECommandMask) 0;
+
+            return true;
+        }
+    }
+    else if (strcmp(OICResourceType, OIC_BINARY_SWITCH) == 0)
     {
         bool value = 0;
 
-        if(OCRepPayloadGetPropBool(payload, OIC_ON_OFF_ATTRIBUTE, &value))
+        if (OCRepPayloadGetPropBool(payload, OIC_ON_OFF_ATTRIBUTE, &value))
         {
             attributeList->count = 1;
             attributeList->list[0].oicAttribute = OICStrdup(OIC_ON_OFF_ATTRIBUTE);
@@ -635,25 +730,45 @@ bool getZigBeeAttributesIfValid(const char * OICResourceType,
             return true;
         }
     }
+    else if (strcmp(OICResourceType, OIC_CHROMA_LIGHT) == 0)
+    {
+        char * value = 0;
+        if (OCRepPayloadGetPropString(payload, OIC_COLOUR_TEMPERATURE_ATTRIBUTE, &value))
+        {
+            attributeList->count = 1;
+            attributeList->list[0].oicAttribute = OICStrdup(OIC_COLOUR_TEMPERATURE_ATTRIBUTE);
+            attributeList->list[0].zigBeeAttribute = ZB_COLOR_TEMPERATURE_ATTRIBUTE_ID;
+            attributeList->list[0].oicType = OIC_ATTR_STRING;
+            attributeList->list[0].val.str = value;
+            attributeList->list[0].zigbeeType = ZB_16_UINT;
+            attributeList->CIEMask = (CIECommandMask) 0;
+
+            return true;
+        }
+    }
     return false;
 }
 
-OCEntityHandlerResult getDoubleValueFromString (const char *str, double *outDouble)
+OCEntityHandlerResult getDoubleValueFromString(const char *str, double *outDouble)
 {
+    if (!str || !outDouble)
+    {
+        return OC_EH_ERROR;
+    }
     size_t hexOutValSize = strlen(HexPrepend) + strlen(str) + 1;
     char * hexOutVal = (char *) OICCalloc(1, hexOutValSize);
-    if(!hexOutVal)
+    if (!hexOutVal)
     {
         return OC_EH_ERROR;
     }
     OICStrcpy(hexOutVal, hexOutValSize, HexPrepend);
     OICStrcat(hexOutVal, hexOutValSize, str);
 
-    char *endPtr;
+    char *endPtr = NULL;
     errno = 0;
     double value = strtod(hexOutVal, &endPtr);
 
-    if(errno != 0 || *endPtr != 0 || value == HUGE_VALF || value == HUGE_VALL)
+    if (errno != 0 || *endPtr != 0 || value == HUGE_VALF || value == HUGE_VALL)
     {
         OICFree(hexOutVal);
         return OC_EH_ERROR;
@@ -665,7 +780,33 @@ OCEntityHandlerResult getDoubleValueFromString (const char *str, double *outDoub
 
 }
 
-OCEntityHandlerResult processGetRequest (PIPluginBase * plugin,
+OCEntityHandlerResult getColourTemperatureFromString(const char* str, int64_t* outVal)
+{
+    if (!str || !outVal)
+    {
+        return OC_EH_ERROR;
+    }
+    // str comes in as "X,Y,T" where "T" is the colour temperature.
+    // Iterate 3 times to retrieve the last value.
+    char * strstr = OICStrdup(str);
+    char * savePtr = NULL;
+    char * temp = NULL;
+    for (int i=0; i<3; i++)
+    {
+        temp = strtok_r(strstr, ",", &savePtr);
+        if (!temp)
+        {
+            *outVal = 0;
+            OICFree(strstr);
+            return OC_EH_ERROR;
+        }
+    }
+    OCStackResult result = getDoubleValueFromString(temp, (double *)outVal);
+    OICFree(strstr);
+    return result;
+}
+
+OCEntityHandlerResult processGetRequest(PIPluginBase * plugin,
         OCEntityHandlerRequest *ehRequest, OCRepPayload **payload)
 {
     if (!plugin || !ehRequest || !payload)
@@ -682,31 +823,31 @@ OCEntityHandlerResult processGetRequest (PIPluginBase * plugin,
                         ehRequest->resource);
     if (stackResult != OC_STACK_OK)
     {
-        OC_LOG (ERROR, TAG, "Failed to get resource from handle");
+        OIC_LOG(ERROR, TAG, "Failed to get resource from handle");
         return OC_EH_ERROR;
     }
-    stackResult = getZigBeeAttributesForOICResource (
+    stackResult = getZigBeeAttributesForOICResource(
         piResource->header.piResource.resourceTypeName, &attributeList);
-    if(stackResult != OC_STACK_OK)
+    if (stackResult != OC_STACK_OK)
     {
-        OC_LOG_V (ERROR, TAG, "Failed to fetch attributes for %s",
+        OIC_LOG_V(ERROR, TAG, "Failed to fetch attributes for %s",
             piResource->header.piResource.resourceTypeName);
         return OC_EH_ERROR;
     }
 
     *payload = OCRepPayloadCreate();
-    if(!payload)
+    if (!payload)
     {
-        OC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
+        OIC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
         return OC_EH_ERROR;
     }
     bool boolRes = OCRepPayloadSetUri(*payload, piResource->header.piResource.uri);
     if (boolRes == false)
     {
-        OCRepPayloadDestroy (*payload);
+        OCRepPayloadDestroy(*payload);
         return OC_EH_ERROR;
     }
-    for(uint32_t i = 0; i<attributeList.count; i++)
+    for (uint32_t i = 0; i<attributeList.count; i++)
     {
         char * outVal = NULL;
         uint8_t outValLength = 0;
@@ -717,21 +858,27 @@ OCEntityHandlerResult processGetRequest (PIPluginBase * plugin,
                                      piResource->clusterId,
                                      attributeList.list[i].zigBeeAttribute,
                                      &outVal,
-                                     &outValLength);
+                                     &outValLength,
+                                     (PIPlugin_Zigbee *)plugin);
 
         if (stackResult != OC_STACK_OK || !outVal)
         {
             stackResult = OC_EH_ERROR;
-            OCRepPayloadDestroy (*payload);
+            OCRepPayloadDestroy(*payload);
             goto exit;
         }
         if (attributeList.list[i].oicType == OIC_ATTR_INT)
         {
             char *endPtr = NULL;
+            errno = 0;
             // Third arg is 16 as outVal is a hex Number
-            uint64_t value = strtol (outVal, &endPtr, 16);
+            uint64_t value = strtol(outVal, &endPtr, 16);
 
-            if (*endPtr != 0)
+            if (*endPtr != 0 || errno != 0)
+            {
+                return OC_EH_ERROR;
+            }
+            if (!attributeList.list[i].oicAttribute)
             {
                 return OC_EH_ERROR;
             }
@@ -748,6 +895,29 @@ OCEntityHandlerResult processGetRequest (PIPluginBase * plugin,
                     value = value / 2.54;
                 }
             }
+            else if (strcmp(attributeList.list[i].oicAttribute, OIC_COLOUR_TEMPERATURE_ATTRIBUTE) == 0)
+            {
+                // OIC Chroma requires: Hue, Saturation, and ColorSpaceValue (color space value is
+                // "chromaX, chromaY, colourTemperature").
+                // ZigBee HA requires: "currentX", "currentY", while we're trying to map a specific
+                // device which goes against the HA spec and ONLY implements "ColorTemperature".
+                // Because of the misalignments between OIC Smart Home and ZigBee HA specs, the
+                // follow assumption is required:
+                // - *X and *Y will be zero, and therefore ignored (or passed as zero where
+                // applicable).
+                // OIC ColorTemperature operates between 0-1000 (degrees Kelvin) in string form,
+                // while ZigBee operates between 0-65279 (bits, with an operating range
+                // 15.32-1,000,000 (degrees Kelvin)).
+                // ZigBee HA states: ColorTemperature(bits) = 1,000,000/ColorTemperature(Kelvin)
+                // Invalid: ColorTemperature==0 || ColorTemperature==65535
+                // However the specific bulb we're mapping only operates between 2700-6500 (Kelvin)
+                // which equates to 0x0099-0x0172 (ie. 153-370; giving a resolution of 217 bits).
+                // Conversion from ZigBee HA specific bulb to OIC temporary mapping:
+                // OIC Value: 0-100  ZigBee Value: (0-217)+153
+                // OICValue = (ZigBeeValue-153)/2.17
+
+                value = (value-153)/2.17;
+            }
             boolRes = OCRepPayloadSetPropInt(*payload,
                                              attributeList.list[i].oicAttribute,
                                              (uint64_t) value);
@@ -756,7 +926,11 @@ OCEntityHandlerResult processGetRequest (PIPluginBase * plugin,
         {
             double value = 0;
 
-            if (getDoubleValueFromString (outVal, &value) != OC_EH_OK)
+            if (getDoubleValueFromString(outVal, &value) != OC_EH_OK)
+            {
+                return OC_EH_ERROR;
+            }
+            if (!piResource->clusterId)
             {
                 return OC_EH_ERROR;
             }
@@ -781,7 +955,7 @@ OCEntityHandlerResult processGetRequest (PIPluginBase * plugin,
             char *endPtr = NULL;
             errno = 0;
             // Third arg is 16 as outVal is a hex Number
-            uint64_t value = strtol (outVal, &endPtr, 16);
+            uint64_t value = strtol(outVal, &endPtr, 16);
 
             if (errno != 0 || *endPtr != 0)
             {
@@ -795,7 +969,7 @@ OCEntityHandlerResult processGetRequest (PIPluginBase * plugin,
                                               value);
         }
 
-        OICFree (outVal);
+        OICFree(outVal);
     }
 
     if (boolRes == false)
@@ -805,7 +979,7 @@ OCEntityHandlerResult processGetRequest (PIPluginBase * plugin,
     }
 
 exit:
-    for(; attributeListIndex < attributeList.count; attributeListIndex++)
+    for (; attributeListIndex < attributeList.count; attributeListIndex++)
     {
         OICFree(attributeList.list[attributeListIndex].oicAttribute);
     }
@@ -832,22 +1006,22 @@ OCEntityHandlerResult processPutRequest(PIPluginBase * plugin,
                                         ehRequest->resource);
     if (stackResult != OC_STACK_OK)
     {
-        OC_LOG (ERROR, TAG, "Failed to get resource from handle");
+        OIC_LOG(ERROR, TAG, "Failed to get resource from handle");
         return OC_EH_ERROR;
     }
 
-    bool boolRes = getZigBeeAttributesIfValid (
+    bool boolRes = getZigBeeAttributesIfValid(
                         piResource->header.piResource.resourceTypeName,
                         &attributeList, *payload);
-    if(boolRes == false)
+    if (boolRes == false)
     {
-        OC_LOG_V (ERROR, TAG, "Failed to fetch attributes for %s",
+        OIC_LOG_V(ERROR, TAG, "Failed to fetch attributes for %s",
             piResource->header.piResource.resourceTypeName);
         return OC_EH_ERROR;
     }
 
     uint32_t i = 0;
-    for(; i<attributeList.count; i++)
+    for (; i<attributeList.count; i++)
     {
         if (attributeList.list[i].oicType == OIC_ATTR_INT)
         {
@@ -868,18 +1042,35 @@ OCEntityHandlerResult processPutRequest(PIPluginBase * plugin,
                 }
                 if (rangeDiff <= 0xFE)
                 {
-                    snprintf(value, sizeof(value), "%02x", (unsigned int) rangeDiff);
+                    errno = 0;
+                    int strRet = snprintf(value, sizeof(value), "%02x", (unsigned int) rangeDiff);
+                    if (strRet <= 0)
+                    {
+                        OIC_LOG_V(ERROR, TAG, "Failed to parse string due to errno: %d", errno);
+                        return OC_EH_ERROR;
+                    }
                 }
                 stackResult = TWMoveToLevel(piResource->nodeId, piResource->endpointId,
-                                    DEFAULT_MOVETOLEVEL_MODE, value, DEFAULT_TRANS_TIME);
+                                    DEFAULT_MOVETOLEVEL_MODE, value, DEFAULT_TRANS_TIME,
+                                    (PIPlugin_Zigbee*)plugin);
             }
             else
             {
-                snprintf(value, sizeof(value), "%"PRId64, attributeList.list[i].val.i);
+                errno = 0;
+                int strRet = snprintf(value,
+                                      sizeof(value),
+                                      "%"PRId64,
+                                      attributeList.list[i].val.i);
+                if (strRet <= 0)
+                {
+                    OIC_LOG_V(ERROR, TAG, "Failed to parse string due to errno: %d", errno);
+                    return OC_EH_ERROR;
+                }
                 stackResult = TWSetAttribute(piResource->eui,
                     piResource->nodeId, piResource->endpointId,
                     piResource->clusterId, attributeList.list[i].zigBeeAttribute,
-                    getZBDataTypeString(attributeList.list[i].zigbeeType), value);
+                    getZBDataTypeString(attributeList.list[i].zigbeeType), value,
+                    (PIPlugin_Zigbee*)plugin);
             }
             if (stackResult != OC_STACK_OK)
             {
@@ -889,19 +1080,48 @@ OCEntityHandlerResult processPutRequest(PIPluginBase * plugin,
         else if (attributeList.list[i].oicType == OIC_ATTR_DOUBLE)
         {
             char value[MAX_STRLEN_DOUBLE] = {};
-            snprintf(value, sizeof(value), "%f", attributeList.list[i].val.d);
+            errno = 0;
+            int strRet = snprintf(value, sizeof(value), "%f", attributeList.list[i].val.d);
+            if (strRet <= 0)
+            {
+                OIC_LOG_V(ERROR, TAG, "Failed to parse string due to errno: %d", errno);
+                return OC_EH_ERROR;
+            }
             stackResult = TWSetAttribute(piResource->eui,
                 piResource->nodeId, piResource->endpointId,
                  piResource->clusterId, attributeList.list[i].zigBeeAttribute,
-                 getZBDataTypeString(attributeList.list[i].zigbeeType), value);
+                 getZBDataTypeString(attributeList.list[i].zigbeeType), value,
+                 (PIPlugin_Zigbee*)plugin);
         }
         else if (attributeList.list[i].oicType == OIC_ATTR_STRING)
         {
-            stackResult = TWSetAttribute(piResource->eui,
-                piResource->nodeId, piResource->endpointId,
-                piResource->clusterId, attributeList.list[i].zigBeeAttribute,
-                getZBDataTypeString(attributeList.list[i].zigbeeType),
-                attributeList.list[i].val.str);
+            if (strcmp(attributeList.list[i].oicAttribute, OIC_COLOUR_TEMPERATURE_ATTRIBUTE) == 0)
+            {
+                char *endPtr = NULL;
+                uint16_t zbVal = (uint16_t)strtod(attributeList.list[i].val.str, &endPtr);
+                zbVal = (zbVal*2.17)+153;
+                char value[5] = {0};
+                errno = 0;
+                int strRet = snprintf(value, sizeof(value), "%04x", zbVal);
+                if (strRet <= 0)
+                {
+                    OIC_LOG_V(ERROR, TAG, "Failed to parse string due to errno: %d", errno);
+                    return OC_EH_ERROR;
+                }
+                stackResult =
+                TWColorMoveToColorTemperature(piResource->nodeId, piResource->endpointId,
+                                              value, DEFAULT_TRANS_TIME,
+                                              (PIPlugin_Zigbee*)plugin);
+            }
+            else
+            {
+                stackResult = TWSetAttribute(piResource->eui,
+                    piResource->nodeId, piResource->endpointId,
+                    piResource->clusterId, attributeList.list[i].zigBeeAttribute,
+                    getZBDataTypeString(attributeList.list[i].zigbeeType),
+                    attributeList.list[i].val.str,
+                    (PIPlugin_Zigbee*)plugin);
+            }
             if (stackResult != OC_STACK_OK)
             {
                 return OC_EH_ERROR;
@@ -912,7 +1132,8 @@ OCEntityHandlerResult processPutRequest(PIPluginBase * plugin,
             char * value = attributeList.list[i].val.b ? "1" : "0";
             if (attributeList.CIEMask || CIE_RON_OFF)
             {
-                stackResult = TWSwitchOnOff(piResource->nodeId, piResource->endpointId, value);
+                stackResult = TWSwitchOnOff(piResource->nodeId, piResource->endpointId, value,
+                                            (PIPlugin_Zigbee*)plugin);
             }
             else
             {
@@ -920,7 +1141,8 @@ OCEntityHandlerResult processPutRequest(PIPluginBase * plugin,
                     piResource->nodeId, piResource->endpointId,
                     piResource->clusterId, attributeList.list[i].zigBeeAttribute,
                     getZBDataTypeString(attributeList.list[i].zigbeeType),
-                    value);
+                    value,
+                    (PIPlugin_Zigbee*)plugin);
             }
             if (stackResult != OC_STACK_OK)
             {
@@ -939,15 +1161,15 @@ OCEntityHandlerResult processPutRequest(PIPluginBase * plugin,
 OCEntityHandlerResult ProcessEHRequest(PIPluginBase * plugin,
     OCEntityHandlerRequest *ehRequest, OCRepPayload **payload)
 {
-    if(!ehRequest || !payload)
+    if (!ehRequest || !payload)
     {
         return OC_EH_ERROR;
     }
-    if(ehRequest->method == OC_REST_GET)
+    if (ehRequest->method == OC_REST_GET)
     {
         return processGetRequest(plugin, ehRequest, payload);
     }
-    else if(ehRequest->method == OC_REST_PUT)
+    else if (ehRequest->method == OC_REST_PUT)
     {
         return processPutRequest(plugin, ehRequest, payload);
     }
index 4ef6489..30feb33 100644 (file)
@@ -36,6 +36,7 @@ extern "C" {
 
 #include "twtypes.h"
 #include "plugininterface.h"
+#include "plugintranslatortypes.h"
 
 typedef enum
 {
@@ -101,7 +102,7 @@ typedef struct TWEntry
  *
  * @param fileLoc The file descriptor location on the file system to start.
  */
-TWResultCode TWStartSock(PIPlugin * plugin, const char * fileLoc);
+TWResultCode TWStartSock(PIPlugin_Zigbee * plugin, const char * fileLoc);
 
 /**
  * Issues command to a specific Telegesis Dongle.
@@ -110,7 +111,7 @@ TWResultCode TWStartSock(PIPlugin * plugin, const char * fileLoc);
  *
  * @param command The command to be issued to the Telegesis Dongle.
  */
-TWResultCode TWIssueATCommand(PIPlugin * plugin, const char * command);
+TWResultCode TWIssueATCommand(PIPlugin_Zigbee * plugin, const char * command);
 
 /**
  * Returns a response/prompt. If NULL, no response or prompts have been issued
@@ -129,7 +130,7 @@ TWResultCode TWIssueATCommand(PIPlugin * plugin, const char * command);
  * function returns NULL. Otherwise, handle the data in TWEntry. Release
  * memory allocated by this function by passing the entry into TWDeleteEntry.
  */
-TWResultCode TWDequeueEntry(PIPlugin * plugin, TWEntry ** entry, TWEntryType type);
+TWResultCode TWDequeueEntry(PIPlugin_Zigbee * plugin, TWEntry ** entry, TWEntryType type);
 
 /**
  * Helper function to deallocate memory of a TWEntry.
@@ -142,7 +143,7 @@ TWResultCode TWDequeueEntry(PIPlugin * plugin, TWEntry ** entry, TWEntryType typ
  *
  * @param entry The entry that was dequeued by calling TWDequeueLine.
  */
-TWResultCode TWDeleteEntry(PIPlugin * plugin, TWEntry * entry);
+TWResultCode TWDeleteEntry(PIPlugin_Zigbee * plugin, TWEntry * entry);
 
 /**
  * Helper function to retrieve the current radio's EUI.
@@ -151,14 +152,14 @@ TWResultCode TWDeleteEntry(PIPlugin * plugin, TWEntry * entry);
  *
  * @param eui The local radio's EUI.
  */
-TWResultCode TWGetEUI(PIPlugin * plugin, char ** eui);
+TWResultCode TWGetEUI(PIPlugin_Zigbee * plugin, char ** eui);
 
 /**
  * Stops socket communication with the Telegesis Dongle within scope of plugin.
  *
  * @param plugin The plugin' scope the socket ops cease to operate within.
  */
-TWResultCode TWStopSock(PIPlugin * plugin);
+TWResultCode TWStopSock(PIPlugin_Zigbee * plugin);
 
 #ifdef __cplusplus
 }
index eea7128..7a42ede 100644 (file)
@@ -129,10 +129,11 @@ typedef struct
     char eui[SIZE_EUI];
 } TWEnrollee;
 
-typedef void (*TWDeviceFoundCallback)(TWDevice* device);
-typedef void (*TWEnrollmentSucceedCallback)(TWEnrollee* enrollee);
-typedef void (*TWDeviceStatusUpdateCallback)(TWUpdate* update);
-typedef void (*TWInitCompleteCallback)(bool status);
+typedef void (*TWDeviceFoundCallback)(TWDevice* device, PIPlugin_Zigbee* plugin);
+typedef void (*TWEnrollmentSucceedCallback)(TWEnrollee* enrollee, PIPlugin_Zigbee* plugin);
+typedef void (*TWDeviceStatusUpdateCallback)(TWUpdate* update, PIPlugin_Zigbee* plugin);
+typedef void (*TWDeviceNodeIdChangedCallback)(const char* eui, const char* nodeId,
+                                              PIPlugin_Zigbee* plugin);
 
 /**
  *
@@ -141,14 +142,15 @@ typedef void (*TWInitCompleteCallback)(bool status);
  * @param[in] deviceDevPath The device path at which this Telegesis module exists.
  *
  */
-OCStackResult TWInitialize(const char* deviceDevPath);
+OCStackResult TWInitialize(PIPlugin_Zigbee* plugin, const char* deviceDevPath);
 
 /**
  *
  * Initiates necessary operations to find ZigBee devices.
+ * @param[in] plugin The plugin instance to operate with.
  *
  */
-OCStackResult TWDiscover();
+OCStackResult TWDiscover(PIPlugin_Zigbee* plugin);
 
 /**
  *
@@ -161,11 +163,13 @@ OCStackResult TWDiscover();
  * @param[in] attributeId The attribute id from which the attribute belongs.
  * @param[out] outValue The value at the specified attribute.
  * @param[out] outValueLength The length of the value.
+ * @param[in] plugin The plugin instance to operate with.
  *
  */
 OCStackResult TWGetAttribute(char* extendedUniqueId, char* nodeId, char* endpointId,
                              char* clusterId, char* attributeId,
-                             char** outValue, uint8_t* outValueLength);
+                             char** outValue, uint8_t* outValueLength,
+                             PIPlugin_Zigbee* plugin);
 
 /**
  *
@@ -178,11 +182,12 @@ OCStackResult TWGetAttribute(char* extendedUniqueId, char* nodeId, char* endpoin
  * @param[in] attributeId The attribute id from which the attribute belongs.
  * @param[in] attributeType The attribute type of the attribute.
  * @param[in] newValue The value to set at the specified attribute.
+ * @param[in] plugin The plugin instance to operate with.
  *
  */
 OCStackResult TWSetAttribute(char* extendedUniqueId, char* nodeId, char* endpointId,
                              char* clusterId, char* attributeId, char* attributeType,
-                             char* newValue);
+                             char* newValue, PIPlugin_Zigbee* plugin);
 
 /**
  *
@@ -191,9 +196,11 @@ OCStackResult TWSetAttribute(char* extendedUniqueId, char* nodeId, char* endpoin
  * @param[in] nodeId The node id of the device.
  * @param[in] endpointId The endpoint id from which the attribute belongs.
  * @param[in] newState Use "0" for OFF, "1" for ON, NULL for toggling.
+ * @param[in] plugin The plugin instance to operate with.
  *
  */
-OCStackResult TWSwitchOnOff(char* nodeId, char* endpointId, char* newState);
+OCStackResult TWSwitchOnOff(char* nodeId, char* endpointId, char* newState,
+                            PIPlugin_Zigbee* plugin);
 
 /**
  *
@@ -210,11 +217,13 @@ OCStackResult TWSwitchOnOff(char* nodeId, char* endpointId, char* newState);
  * @param[in] level The The meaning of â€˜level’ is device dependent
  *                  e.g. for a light it may mean brightness level.
  *
- * @param[in] transTime The time taken to move to the new level
+ * @param[in] transTime The time taken to move to the new level.
+ * @param[in] plugin The plugin instance to operate with.
  *
  */
 OCStackResult TWMoveToLevel(char* nodeId, char* endpointId,
-                            char* onOffState, char* level, char* transTime);
+                            char* onOffState, char* level, char* transTime,
+                            PIPlugin_Zigbee* plugin);
 
 /**
  *
@@ -223,9 +232,11 @@ OCStackResult TWMoveToLevel(char* nodeId, char* endpointId,
  * @param[in] nodeId The node id of the device.
  * @param[in] endpointId The endpoint id from which the attribute belongs.
  * @param[in] newState Use "0" to Unlock, "1" to Lock ON.
+ * @param[in] plugin The plugin instance to operate with.
  *
  */
-OCStackResult TWSwitchDoorLockState(char* nodeId, char* endpointId, char* newState);
+OCStackResult TWSwitchDoorLockState(char* nodeId, char* endpointId, char* newState,
+                                    PIPlugin_Zigbee* plugin);
 
 /**
  *
@@ -235,10 +246,12 @@ OCStackResult TWSwitchDoorLockState(char* nodeId, char* endpointId, char* newSta
  * @param[in] endpointId The endpoint id from which the attribute belongs.
  * @param[in] colorTemperature 16 bit hexadecimal number.
  * @param[in] transTime The time taken to move to the new level.
+ * @param[in] plugin The plugin instance to operate with.
  *
  */
 OCStackResult TWColorMoveToColorTemperature(char* nodeId, char* endpointId,
-                                            char* colorTemperature, char* transTime);
+                                            char* colorTemperature, char* transTime,
+                                            PIPlugin_Zigbee* plugin);
 
 /**
  *
@@ -246,14 +259,26 @@ OCStackResult TWColorMoveToColorTemperature(char* nodeId, char* endpointId,
  * This callback will be called when TWDiscover() discovers ZigBee device(s).
  *
  */
-OCStackResult TWSetDiscoveryCallback(const TWDeviceFoundCallback callback);
+OCStackResult TWSetDiscoveryCallback(const TWDeviceFoundCallback callback,
+                                     PIPlugin_Zigbee* plugin);
+
+/**
+ *
+ * Sets end device's nodeId changed callback.
+ * This callback will be called when there is a NodeId change for a remote ZigBee device.
+ *
+ */
+OCStackResult TWSetEndDeviceNodeIdChangedCallback(TWDeviceNodeIdChangedCallback callback,
+                                                  PIPlugin_Zigbee* plugin);
+
 /**
  *
  * Sets status update callback.
  * This callback will be called when there is an update on remote ZigBee devices.
  *
  */
-OCStackResult TWSetStatusUpdateCallback(TWDeviceStatusUpdateCallback callback);
+OCStackResult TWSetStatusUpdateCallback(TWDeviceStatusUpdateCallback callback,
+                                        PIPlugin_Zigbee* plugin);
 
 /**
  *
@@ -261,24 +286,27 @@ OCStackResult TWSetStatusUpdateCallback(TWDeviceStatusUpdateCallback callback);
  * A callback TWEnrollSucceedCallback will be invoked when this registration is fulfill.
  * @param[in] nodeId The node id of the remote zone device.
  * @param[in] endpointId The node id of the remote zone device.
+ * @param[in] plugin The plugin instance to operate with.
  *
  *
  */
-OCStackResult TWListenForStatusUpdates(char* nodeId, char* endpointId);
+OCStackResult TWListenForStatusUpdates(char* nodeId, char* endpointId, PIPlugin_Zigbee* plugin);
 
 /**
  *
  * Process TWEntry.
+ * @param[in] plugin The plugin instance to operate with.
  *
  */
-OCStackResult TWProcess();
+OCStackResult TWProcess(PIPlugin_Zigbee* plugin);
 
 /**
  *
  * Uninitializes the Telegesis module.
+ * @param[in] plugin The plugin instance to operate with.
  *
  */
-OCStackResult TWUninitialize();
+OCStackResult TWUninitialize(PIPlugin_Zigbee* plugin);
 
 
 #ifdef __cplusplus
index e06d19e..6b4092f 100644 (file)
@@ -44,7 +44,7 @@ extern "C" {
 
 typedef struct TWSock
 {
-    PIPlugin * plugin; // Handle
+    PIPlugin_Zigbee * plugin; // Handle
     char * eui; // The associated Zigbee radio's EUI.
     int fd;
     char * buffer;
@@ -59,15 +59,15 @@ typedef struct TWSock
     struct TWSock * next;
 } TWSock;
 
-TWResultCode TWAddTWSock(TWSock * sock, PIPlugin * plugin, const char * fileLoc);
+TWResultCode TWAddTWSock(TWSock * sock, PIPlugin_Zigbee * plugin, const char * fileLoc);
 
-TWSock * TWGetSock(PIPlugin * plugin);
+TWSock * TWGetSock(PIPlugin_Zigbee * plugin);
 
 TWResultCode TWDeleteTWSock(TWSock * sock);
 
 TWResultCode TWDeleteAllTWSock();
 
-TWResultCode TWFreeQueue(PIPlugin * plugin);
+TWResultCode TWFreeQueue(PIPlugin_Zigbee * plugin);
 
 #ifdef __cplusplus
 }
index 373bed7..8dc20e9 100644 (file)
@@ -50,6 +50,14 @@ extern "C" {
 
 #define SIMPLEDESC_RESPONSE_EXPECTED_LINES (6)
 
+#define ZB_PROFILE_ID_HOME_AUTOMATION       "0104"
+
+#define ZB_CLUSTER_IDENTIFY                 "0003"
+#define ZB_CLUSTER_ON_OFF                   "0006"
+#define ZB_CLUSTER_TEMPERATURE_MEASUREMENT  "0402"
+#define ZB_CLUSTER_IAS_ZONE                 "0500"
+#define ZB_CLUSTER_COLOR_CONTROL            "0300"
+
 #define AT_STR_ERROR_OK             "00"
 #define AT_STR_ERROR_INVALID_OP     "70"
 
@@ -163,14 +171,6 @@ typedef struct
 
 } TWEndControlMap;
 
-typedef TWResultCode (*TWATResultHandler)(int count, char** tokens);
-
-typedef struct
-{
-    const char *resultTxt;
-    TWATResultHandler handler;
-
-} TWATResultHandlerPair;
 
 #ifdef __cplusplus
 }
index d4c592d..877cf06 100644 (file)
@@ -37,7 +37,7 @@
 /**
  * New thread's main() ftn.
  */
-void * readForever(/*PIPlugin */void * plugin);
+void * readForever(/*PIPlugin_Zigbee */void * plugin);
 /**
  * Just grabs the next char in the buffer. Called by readBufferLine() multiple times.
  */
@@ -53,7 +53,7 @@ TWEntry * readEntry(int fd);
 /**
  * Posts the TWEntry to the queue.
  */
-TWResultCode TWEnqueueEntry(PIPlugin * plugin, TWEntry * entry);
+TWResultCode TWEnqueueEntry(PIPlugin_Zigbee * plugin, TWEntry * entry);
 
 /**
  * Defines the mapping relationships between Telegesis AT response/prompt tags and
@@ -90,6 +90,7 @@ static TWEntryTypePair TWEntryTypePairArray[] =
     {"ENROLLED:",       1, TW_ENROLLED},
     {"ZONESTATUS:",     1, TW_ZONESTATUS},
     {"AddrResp:",       1, TW_ADDRESS_RESPONSE},
+    {"REPORTATTR:",     1, TW_NONE},
     {"Unknown:",        0, TW_NONE},
     {"Unknown:",        1, TW_MAX_ENTRY}
 };
@@ -98,17 +99,26 @@ TWEntry * TWEntryList = NULL;
 
 TWEntryTypePair getEntryTypePair(const char * bufferLine)
 {
+    size_t count = sizeof(TWEntryTypePairArray)/sizeof(TWEntryTypePairArray[0]);
+    if (!bufferLine)
+    {
+        return TWEntryTypePairArray[count-1];
+    }
     size_t bufferLength = strlen(bufferLine);
-    for(uint8_t i = 0; i < TW_MAX_ENTRY; i++)
+    for (size_t i = 0; i < count; i++)
     {
+        if (!TWEntryTypePairArray[i].resultTxt)
+        {
+            return TWEntryTypePairArray[count-1];
+        }
         size_t resultTxtLength = strlen(TWEntryTypePairArray[i].resultTxt);
-        if((bufferLength >= resultTxtLength) &&
+        if ((bufferLength >= resultTxtLength) &&
            strncmp(bufferLine, TWEntryTypePairArray[i].resultTxt, resultTxtLength) == 0)
         {
             return TWEntryTypePairArray[i];
         }
     }
-    return TWEntryTypePairArray[TW_MAX_ENTRY];
+    return TWEntryTypePairArray[count-1];
 }
 
 TWResultCode TWWait(pthread_cond_t * cond, pthread_mutex_t * mutex, uint8_t timeout)
@@ -126,13 +136,13 @@ TWResultCode TWWait(pthread_cond_t * cond, pthread_mutex_t * mutex, uint8_t time
         case 0:
             return TW_RESULT_OK;
         case ETIMEDOUT:
-            OC_LOG(INFO, TAG, "Timed out waiting for CV. Non-error. Please try again.");
+            OIC_LOG(INFO, TAG, "Timed out waiting for CV. Non-error. Please try again.");
             return TW_RESULT_OK;
         case EINVAL:
-            OC_LOG(ERROR, TAG, "Cond or Mutex is invalid. OR timeout value for CV is invalid.");
+            OIC_LOG(ERROR, TAG, "Cond or Mutex is invalid. OR timeout value for CV is invalid.");
             break;
         case EPERM:
-            OC_LOG(ERROR, TAG, "Cannot use CV because the current thread does not own the CV.");
+            OIC_LOG(ERROR, TAG, "Cannot use CV because the current thread does not own the CV.");
             break;
     }
 
@@ -148,16 +158,16 @@ TWResultCode TWGrabMutex(pthread_mutex_t * mutex)
         case 0:
             return TW_RESULT_OK;
         case EINVAL:
-            OC_LOG(ERROR, TAG, "Mutex was not initialized.");
+            OIC_LOG(ERROR, TAG, "Mutex was not initialized.");
             break;
         case ETIMEDOUT:
-            OC_LOG(INFO, TAG, "Timed out waiting for mutex. Non-error. Please try again.");
+            OIC_LOG(INFO, TAG, "Timed out waiting for mutex. Non-error. Please try again.");
             return TW_RESULT_OK;
         case EAGAIN:
-            OC_LOG(ERROR, TAG, "Maximum number of locks for mutex have been exceeded.");
+            OIC_LOG(ERROR, TAG, "Maximum number of locks for mutex have been exceeded.");
             break;
         case EDEADLK:
-            OC_LOG(ERROR, TAG, "Deadlock OR this thread already owns the mutex.");
+            OIC_LOG(ERROR, TAG, "Deadlock OR this thread already owns the mutex.");
             break;
     }
     return TW_RESULT_ERROR;
@@ -172,13 +182,13 @@ TWResultCode TWReleaseMutex(pthread_mutex_t * mutex)
         case 0:
             return TW_RESULT_OK;
         case EINVAL:
-            OC_LOG(ERROR, TAG, "Mutex was not initialized.");
+            OIC_LOG(ERROR, TAG, "Mutex was not initialized.");
             break;
         case EAGAIN:
-            OC_LOG(ERROR, TAG, "Maximum number of locks for mutex have been exceeded.");
+            OIC_LOG(ERROR, TAG, "Maximum number of locks for mutex have been exceeded.");
             break;
         case EPERM:
-            OC_LOG(ERROR, TAG, "Cannot unlock because the current thread does not own the mutex.");
+            OIC_LOG(ERROR, TAG, "Cannot unlock because the current thread does not own the mutex.");
             break;
     }
     return TW_RESULT_ERROR;
@@ -197,7 +207,7 @@ char readBufferChar(int fd, ssize_t * readDataBytes)
     *readDataBytes = read(fd, &byte, sizeof(byte));
     if(*readDataBytes < 0)
     {
-        OC_LOG_V(ERROR, TAG, "\tCould not read from port. Errno is: %d\n", errno);
+        OIC_LOG_V(ERROR, TAG, "\tCould not read from port. Errno is: %d\n", errno);
         return '\0';
     }
     return byte;
@@ -272,7 +282,7 @@ const char * readBufferLine(int fd)
             bufferLine = (char *) OICRealloc(bufferLineHold, bufferLineSize);
             if(!bufferLine)
             {
-                OC_LOG(ERROR, TAG, "Ran out of memory.");
+                OIC_LOG(ERROR, TAG, "Ran out of memory.");
                 return NULL;
             }
             bufferLine[bufferLoc] = '\0';
@@ -280,7 +290,7 @@ const char * readBufferLine(int fd)
             bufferLoc++;
             bufferLineHold = bufferLine;
 
-            OC_LOG_V(DEBUG, TAG, "Incoming: %s", bufferLine);
+            OIC_LOG_V(DEBUG, TAG, "Incoming: %s", bufferLine);
         }
         else
         {
@@ -292,7 +302,7 @@ const char * readBufferLine(int fd)
             bufferLine = (char *) OICRealloc(bufferLineHold, bufferLineSize);
             if(!bufferLine)
             {
-                OC_LOG(ERROR, TAG, "Ran out of memory.");
+                OIC_LOG(ERROR, TAG, "Ran out of memory.");
                 return NULL;
             }
             bufferLine[bufferLoc] = '\0';
@@ -320,13 +330,13 @@ TWResultCode TWAddLineToEntry(const char * line, TWEntry * entry)
 {
     if(!line || !entry)
     {
-        OC_LOG(ERROR, TAG, "Invalid/NULL parameter(s) received.");
+        OIC_LOG(ERROR, TAG, "Invalid/NULL parameter(s) received.");
         return TW_RESULT_ERROR_INVALID_PARAMS;
     }
     TWLine * twLine = (TWLine *) OICCalloc(1, sizeof(TWLine));
     if(!twLine)
     {
-        OC_LOG(ERROR, TAG, "Ran out of memory.");
+        OIC_LOG(ERROR, TAG, "Ran out of memory.");
         return TW_RESULT_ERROR_NO_MEMORY;
     }
     size_t lineLength = strlen(line);
@@ -371,7 +381,7 @@ TWEntry * readEntry(int fd)
     TWEntry * entry = (TWEntry *) OICCalloc(1, sizeof(TWEntry));
     if(!entry)
     {
-        OC_LOG(ERROR, TAG, "Ran out of memory.");
+        OIC_LOG(ERROR, TAG, "Ran out of memory.");
         return NULL;
     }
     entry->count = 0;
@@ -391,6 +401,10 @@ TWEntry * readEntry(int fd)
                 goto exit;
             }
             entryTypePair = getEntryTypePair(bufferLine);
+            if(entryTypePair.entryType == TW_NONE)
+            {
+                goto exit;
+            }
         }
         else
         {
@@ -419,13 +433,33 @@ exit:
     return NULL;
 }
 
-TWResultCode TWRetrieveEUI(PIPlugin * plugin, TWSock * twSock)
+TWResultCode TWRetrieveEUI(PIPlugin_Zigbee * plugin, TWSock * twSock)
 {
+    if(!plugin || !twSock)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid param.");
+        return TW_RESULT_ERROR_INVALID_PARAMS;
+    }
     if(twSock->isActive == false)
     {
+        OIC_LOG(ERROR, TAG, "Tried to retrieve Zigbee EUI on an uninitialized socket.");
         return TW_RESULT_ERROR;
     }
 
+    //Empty buffer
+    char hideBuffer[1] = "";
+    int p = 1;
+    while(p != 0)
+    {
+        errno = 0;
+        p = read(twSock->fd, hideBuffer, 1);
+        if(p < 0)
+        {
+            OIC_LOG_V(ERROR, TAG, "\tCould not read from port. Errno is: %d\n", errno);
+            return TW_RESULT_ERROR;
+        }
+    }
+
     TWEntry * entry = NULL;
     TWResultCode deleteResult = TW_RESULT_OK;
     TWResultCode result = TWIssueATCommand(plugin, AT_CMD_GET_LOCAL_EUI);
@@ -450,12 +484,22 @@ TWResultCode TWRetrieveEUI(PIPlugin * plugin, TWSock * twSock)
     twSock->eui = (char *) OICMalloc(strlen(entry->lines[0].line)+1);
     if(!twSock->eui)
     {
+        result = TWReleaseMutex(&twSock->mutex);
+        if(result != TW_RESULT_OK)
+        {
+            goto exit;
+        }
         result = TW_RESULT_ERROR_NO_MEMORY;
         goto exit;
     }
 
     if(SIZE_EUI != (strlen(entry->lines[0].line)+1))
     {
+        result = TWReleaseMutex(&twSock->mutex);
+        if(result != TW_RESULT_OK)
+        {
+            goto exit;
+        }
         OICFree(twSock->eui);
         result = TW_RESULT_ERROR;
         goto exit;
@@ -478,9 +522,9 @@ exit:
     return result;
 }
 
-TWResultCode TWStartSock(PIPlugin * plugin, const char * fileLoc)
+TWResultCode TWStartSock(PIPlugin_Zigbee * plugin, const char * fileLoc)
 {
-    TWSock * sock = TWGetSock((PIPlugin *)plugin);
+    TWSock * sock = TWGetSock((PIPlugin_Zigbee *)plugin);
     if(sock && sock->isActive == true)
     {
         // Ignore requests to start up the same socket.
@@ -500,10 +544,10 @@ TWResultCode TWStartSock(PIPlugin * plugin, const char * fileLoc)
         goto exit;
     }
 
-    ret = TWRetrieveEUI((PIPlugin *)plugin, sock);
+    ret = TWRetrieveEUI((PIPlugin_Zigbee *)plugin, sock);
     if(ret != TW_RESULT_OK)
     {
-        OC_LOG(ERROR, TAG, "Unable to retrieve Zigbee Radio's EUI.");
+        OIC_LOG(ERROR, TAG, "Unable to retrieve Zigbee Radio's EUI.");
         return ret;
     }
 
@@ -513,7 +557,7 @@ TWResultCode TWStartSock(PIPlugin * plugin, const char * fileLoc)
                                 (void *) plugin);
     if(result != 0)
     {
-        OC_LOG_V(ERROR, TAG, "Thread start failed with error %d", result);
+        OIC_LOG_V(ERROR, TAG, "Thread start failed with error %d", result);
         ret = TW_RESULT_ERROR;
         goto exit;
     }
@@ -530,24 +574,24 @@ static void sigHandler(int signal)
     pthread_t tid = pthread_self();
     (void)tid;
     (void)signal;
-    OC_LOG_V(INFO, TAG, "Received signal on thread: %lu\n", tid);
-    OC_LOG_V(INFO, TAG, "Signal is: %d", signal);
+    OIC_LOG_V(INFO, TAG, "Received signal on thread: %lu\n", tid);
+    OIC_LOG_V(INFO, TAG, "Signal is: %d", signal);
 }
 
 void * readForever(/*PIPlugin*/ void * plugin)
 {
     TWResultCode result = TW_RESULT_OK;
     TWEntry * entry = NULL;
-    TWSock * twSock = TWGetSock((PIPlugin *)plugin);
+    TWSock * twSock = TWGetSock((PIPlugin_Zigbee *)plugin);
     if(!twSock)
     {
-        OC_LOG(ERROR, TAG, "Unable to retrieve associated socket.");
+        OIC_LOG(ERROR, TAG, "Unable to retrieve associated socket.");
         return NULL;
     }
 
     pthread_t tid = pthread_self();
     (void)tid;
-    OC_LOG_V(INFO, TAG, "ReadForever Telegesis ThreadId: %lu", tid);
+    OIC_LOG_V(INFO, TAG, "ReadForever Telegesis ThreadId: %lu", tid);
 
     struct sigaction action = { .sa_handler = 0 };
 
@@ -579,13 +623,15 @@ void * readForever(/*PIPlugin*/ void * plugin)
                     continue;
                     // This EINTR signal is not for us. Do not handle it.
                 }
-                OC_LOG(DEBUG, TAG, "Thread has been joined. Exiting thread.");
+                // Notify other threads waiting for a response that the stack is going down.
+                pthread_cond_signal(&twSock->queueCV);
+                OIC_LOG(DEBUG, TAG, "Thread has been joined. Exiting thread.");
                 pthread_exit(PTHREAD_CANCELED);
                 return NULL;
             }
             else
             {
-                OC_LOG_V(ERROR, TAG, "Unaccounted error occurred. Exiting thread."
+                OIC_LOG_V(ERROR, TAG, "Unaccounted error occurred. Exiting thread."
                                      "Errno is: %d", errno);
                 return NULL;
             }
@@ -602,7 +648,7 @@ void * readForever(/*PIPlugin*/ void * plugin)
                     result = TWGrabMutex(&twSock->mutex);
                     if(result != TW_RESULT_OK)
                     {
-                        OC_LOG(ERROR, TAG, "Unable to grab mutex.");
+                        OIC_LOG(ERROR, TAG, "Unable to grab mutex.");
                         return NULL;
                     }
                     haveMutex = true;
@@ -613,7 +659,7 @@ void * readForever(/*PIPlugin*/ void * plugin)
                     result = TWReleaseMutex(&twSock->mutex);
                     if(result != TW_RESULT_OK)
                     {
-                        OC_LOG(ERROR, TAG, "Unable to release mutex.");
+                        OIC_LOG(ERROR, TAG, "Unable to release mutex.");
                         return NULL;
                     }
                     haveMutex = false;
@@ -621,13 +667,13 @@ void * readForever(/*PIPlugin*/ void * plugin)
                     // response. Not necessarily fatal.
                     continue;
                 }
-                result = TWEnqueueEntry((PIPlugin *)plugin, entry);
+                result = TWEnqueueEntry((PIPlugin_Zigbee *)plugin, entry);
                 if(result != TW_RESULT_OK)
                 {
-                    OC_LOG_V(ERROR, TAG, "Could not add TWEntry to queue for"
+                    OIC_LOG_V(ERROR, TAG, "Could not add TWEntry to queue for"
                                           "consumption by the application"
                                           "layer. Error is: %d", result);
-                    TWDeleteEntry((PIPlugin *)plugin, entry);
+                    TWDeleteEntry((PIPlugin_Zigbee *)plugin, entry);
                     // This is most likely a FATAL error, such as out of memory.
                     break;
                 }
@@ -649,13 +695,13 @@ void * readForever(/*PIPlugin*/ void * plugin)
     return NULL;
 }
 
-TWResultCode TWIssueATCommand(PIPlugin * plugin, const char * command)
+TWResultCode TWIssueATCommand(PIPlugin_Zigbee * plugin, const char * command)
 {
     if(!plugin || !command)
     {
         return TW_RESULT_ERROR_INVALID_PARAMS;
     }
-    OC_LOG_V(INFO, TAG, "Attempt to write %s.", command);
+    OIC_LOG_V(INFO, TAG, "Attempt to write %s.", command);
     TWSock * twSock = TWGetSock(plugin);
     if(!twSock)
     {
@@ -697,13 +743,13 @@ TWResultCode TWIssueATCommand(PIPlugin * plugin, const char * command)
     size_t actualWrittenBytes = write(twSock->fd, sendCommand, expectedWrittenBytes);
     if(actualWrittenBytes <= 0)
     {
-        OC_LOG_V(ERROR, TAG, "Could not write to port. Errno is: %d\n", errno);
+        OIC_LOG_V(ERROR, TAG, "Could not write to port. Errno is: %d\n", errno);
         result =  TW_RESULT_ERROR;
         goto exit;
     }
     if(actualWrittenBytes != expectedWrittenBytes)
     {
-        OC_LOG(ERROR, TAG, "Telegesis Adapter did not receive expected command. Unknown state.");
+        OIC_LOG(ERROR, TAG, "Telegesis Adapter did not receive expected command. Unknown state.");
         result = TW_RESULT_ERROR;
     }
 
@@ -717,7 +763,7 @@ exit:
     return result;
 }
 
-TWResultCode TWEnqueueEntry(PIPlugin * plugin, TWEntry * entry)
+TWResultCode TWEnqueueEntry(PIPlugin_Zigbee * plugin, TWEntry * entry)
 {
     if(!plugin || !entry)
     {
@@ -737,7 +783,7 @@ TWResultCode TWEnqueueEntry(PIPlugin * plugin, TWEntry * entry)
     return TW_RESULT_OK;
 }
 
-TWResultCode TWDequeueEntry(PIPlugin * plugin, TWEntry ** entry, TWEntryType type)
+TWResultCode TWDequeueEntry(PIPlugin_Zigbee * plugin, TWEntry ** entry, TWEntryType type)
 {
     if(!plugin || !entry)
     {
@@ -762,31 +808,54 @@ TWResultCode TWDequeueEntry(PIPlugin * plugin, TWEntry ** entry, TWEntryType typ
     {
         return ret;
     }
-
+    *entry = NULL;
     if(type != TW_NONE)
     {
-        // Wait for up to 10 seconds for the entry to put into the queue.
-        ret = TWWait(&twSock->queueCV, &twSock->mutex, TIME_OUT_10_SECONDS);
-        if(ret != TW_RESULT_OK)
-        {
-            return ret;
+        struct timespec abs_time;
+        clock_gettime(CLOCK_REALTIME , &abs_time);
+        abs_time.tv_sec += TIME_OUT_10_SECONDS;
+        while(!*entry)
+         {
+            // Wait for up to 10 seconds for the entry to put into the queue.
+            ret = TWWait(&twSock->queueCV, &twSock->mutex, TIME_OUT_10_SECONDS);
+            if(ret != TW_RESULT_OK)
+            {
+                return ret;
+            }
+            if(twSock->isActive == false)
+            {
+                break;
+            }
+            TWEntry * out = NULL;
+            TWEntry * temp = NULL;
+            LL_FOREACH_SAFE(twSock->queue, out, temp)
+             {
+                if(out->type == type)
+                {
+                    *entry = out;
+                    break;
+                }
+            }
+            struct timespec cur_time;
+            clock_gettime(CLOCK_REALTIME, &cur_time);
+            if(cur_time.tv_sec >= abs_time.tv_sec)
+            {
+                break;
+            }
         }
     }
-
-    *entry = twSock->queue;
-    if(*entry)
+    else
     {
-        LL_DELETE(twSock->queue, *entry);
+        *entry = twSock->queue;
     }
-    ret = TWReleaseMutex(&twSock->mutex);
-    if(ret != TW_RESULT_OK)
+    if(*entry)
     {
-        return ret;
+        LL_DELETE(twSock->queue, *entry);
     }
-    return ret;
+    return TWReleaseMutex(&twSock->mutex);
 }
 
-TWResultCode TWFreeQueue(PIPlugin * plugin)
+TWResultCode TWFreeQueue(PIPlugin_Zigbee * plugin)
 {
     if(!plugin)
     {
@@ -814,7 +883,7 @@ TWResultCode TWFreeQueue(PIPlugin * plugin)
     return ret;
 }
 
-TWResultCode TWDeleteEntry(PIPlugin * plugin, TWEntry * entry)
+TWResultCode TWDeleteEntry(PIPlugin_Zigbee * plugin, TWEntry * entry)
 {
     if(!plugin || !entry)
     {
@@ -843,7 +912,7 @@ TWResultCode TWDeleteEntry(PIPlugin * plugin, TWEntry * entry)
     {
         if(out == entry)
         {
-            OC_LOG(ERROR, TAG, "Tried to delete an entry that is still in the queue. \
+            OIC_LOG(ERROR, TAG, "Tried to delete an entry that is still in the queue. \
                                 Please dequeue the entry first.");
             return TW_RESULT_ERROR;
         }
@@ -855,7 +924,7 @@ TWResultCode TWDeleteEntry(PIPlugin * plugin, TWEntry * entry)
     return TW_RESULT_OK;
 }
 
-TWResultCode TWGetEUI(PIPlugin * plugin, char ** eui)
+TWResultCode TWGetEUI(PIPlugin_Zigbee * plugin, char ** eui)
 {
     if(!plugin || !eui)
     {
@@ -878,7 +947,7 @@ TWResultCode TWGetEUI(PIPlugin * plugin, char ** eui)
 
 }
 
-TWResultCode TWStopSock(PIPlugin * plugin)
+TWResultCode TWStopSock(PIPlugin_Zigbee * plugin)
 {
     if(!plugin)
     {
@@ -916,16 +985,16 @@ TWResultCode TWStopSock(PIPlugin * plugin)
         switch(pthreadRet)
         {
             case EDEADLK:
-                OC_LOG(ERROR, TAG, "A deadlock has occurred.");
+                OIC_LOG(ERROR, TAG, "A deadlock has occurred.");
                 break;
             case EINVAL:
-                OC_LOG(ERROR, TAG, "Thread is not joinable or another thread has already joined.");
+                OIC_LOG(ERROR, TAG, "Thread is not joinable or another thread has already joined.");
                 break;
             case ESRCH:
-                OC_LOG(ERROR, TAG, "No thread with the ID could be found.");
+                OIC_LOG(ERROR, TAG, "No thread with the ID could be found.");
                 break;
             default:
-                OC_LOG_V(ERROR, TAG, "Unknown error occurred when joining thread: %d", pthreadRet);
+                OIC_LOG_V(ERROR, TAG, "Unknown error occurred when joining thread: %d", pthreadRet);
         }
         return TW_RESULT_ERROR;
     }
@@ -941,3 +1010,4 @@ TWResultCode TWStopSock(PIPlugin * plugin)
 
     return ret;
 }
+
index 6a55aeb..08728ef 100644 (file)
@@ -25,6 +25,7 @@
 #include <inttypes.h>
 
 #include <unistd.h>
+#include <sys/stat.h>
 
 #include <termios.h>
 #include <string.h>
@@ -37,6 +38,7 @@
 #include "twtypes.h"
 #include "telegesis_socket.h"
 #include "telegesis_wrapper.h"
+#include "twsocketlist.h"
 
 
 #define TAG PCF("telegesiswrapper")     // Module Name
 #define RESPONSE_PARAMS_COUNT_ZONESTATUS_4                  (4)
 #define RESPONSE_PARAMS_COUNT_ZONESTATUS_6                  (6)
 
+#define IN_CLUSTER_COUNT_STRING    "05"
+#define OUT_CLUSTER_COUNT_STRING   "00"
+
+#define TOKEN_ADDRRESP_STATUS_CODE                  (0)
+#define TOKEN_ADDRRESP_NODEID                       (1)
+#define TOKEN_ADDRRESP_EUI                          (2)
+
+#define TOKEN_PLUS_N_DEVICE_TYPE                    (0)
+#define TOKEN_PLUS_N_PANID                          (3)
+#define TOKEN_PLUS_N_PANID_EXTENDED                 (4)
+
+#define TOKEN_JPAN_PANID                            (1)
+#define TOKEN_JPAN_PANID_EXTENDED                   (2)
+
+#define TOKEN_PJOIN_RESPONSE_IEEE_ADDRESS           (0)
+#define TOKEN_PJOIN_RESPONSE_NODEID                 (1)
+
+#define TOKEN_MATCHDESC_NODEID                      (0)
+#define TOKEN_MATCHDESC_STATUS_CODE                 (1)
+#define TOKEN_MATCHDESC_ENDPOINTID                  (2)
+
+#define TOKEN_SIMPLEDESC_SIMPLEDESC_NODEID          (0)
+#define TOKEN_SIMPLEDESC_SIMPLEDESC_STATUS_CODE     (1)
+#define TOKEN_SIMPLEDESC_INCLUSTER_STRING           (0)
+
+#define TOKEN_WRITEATTR_STATUS_CODE                 (3)
+#define TOKEN_WRITEATTR_STATUS_CODE_ALTERNATIVE     (4)
+
+#define TOKEN_TEMPERATURE_STATUS_CODE               (3)
+#define TOKEN_TEMPERATURE_VALUE                     (4)
+
+#define TOKEN_RESPATTR_STATUS_CODE                  (4)
+#define TOKEN_RESPATTR_ATTRIBUTE_VALUE              (5)
+
+#define TOKEN_DFTREP_NODEID                         (0)
+#define TOKEN_DFTREP_ENDPOINTID                     (1)
+#define TOKEN_DFTREP_CLUSTERID                      (2)
+#define TOKEN_DFTREP_COMMANDID                      (3)
+#define TOKEN_DFTREP_STATUS_CODE                    (4)
+
+#define TOKEN_DRLOCKRSP_NODEID                      (0)
+#define TOKEN_DRLOCKRSP_ENDPOINTID                  (1)
+#define TOKEN_DRLOCKRSP_STATUS_CODE                 (2)
+
+#define TOKEN_ZENROLLREQ_NODEID                     (0)
+#define TOKEN_ZENROLLREQ_ENDPOINTID                 (1)
+#define TOKEN_ZENROLLREQ_ZONETYPE                   (2)
+#define TOKEN_ZENROLLREQ_MANUFACTURE_CODE           (3)
+#define TOKEN_ENROLLED_ZONEID                       (0)
+#define TOKEN_ENROLLED_ZONETYPE                     (1)
+#define TOKEN_ENROLLED_EUI                          (2)
+
+#define TOKEN_ZONESTATUS_NODEID                     (0)
+#define TOKEN_ZONESTATUS_ENDPOINTID                 (1)
+#define TOKEN_ZONESTATUS_ZONESTATUS                 (2)
+#define TOKEN_ZONESTATUS_ZONESTATUS_EXTENDED        (3)
+#define TOKEN_ZONESTATUS_ZONEID                     (4)
+#define TOKEN_ZONESTATUS_DELAY                      (5)
+
+
+typedef struct TWContext{
+    PIPlugin_Zigbee* g_plugin;
+    const char* g_port;
+
+    char g_LocalEUI[SIZE_EUI];
+    char g_WIPRemoteEUI[SIZE_EUI];
+    char g_WIPRemoteNodeId[SIZE_NODEID];
+
+    TWStatus g_ZigBeeStatus;
+    TWDeviceList* g_FoundMatchedDeviceList;
+    TWDevice* g_WIPDevice;
+
+    TWDeviceFoundCallback g_DeviceFoundCallback;
+    TWEnrollmentSucceedCallback g_EnrollmentSucceedCallback;
+    TWDeviceStatusUpdateCallback g_DeviceStatusUpdateCallback;
+    TWDeviceNodeIdChangedCallback g_EndDeviceNodeIdChangedCallback;
+
+    struct TWContext* next;
+} TWContext;
+
+typedef TWResultCode (*TWATResultHandler)(int count, char** tokens, TWContext* ctx);
+
+typedef struct
+{
+    const char *resultTxt;
+    TWATResultHandler handler;
+} TWATResultHandlerPair;
+
+
 //-----------------------------------------------------------------------------
 // Private internal function prototypes
 //-----------------------------------------------------------------------------
 
-static TWResultCode HandleATResponse(TWEntry* entry);
-
-static TWResultCode processEntry(TWEntry* entry);
-static TWResultCode processEntryNETWORK_INFO(TWEntry* entry);
-static TWResultCode processEntryJPAN(TWEntry* entry);
-static TWResultCode processEntryEndDevice(TWEntry* entry);
-static TWResultCode processEntryMatchDesc(TWEntry* entry);
-static TWResultCode processEntrySimpleDesc(TWEntry* entry);
-static TWResultCode processEntryWriteAttr(TWEntry* entry);
-static TWResultCode processEntryReadAttr(TWEntry* entry);
-static TWResultCode processEntryTemperature(TWEntry* entry);
-static TWResultCode processEntrySwitchDoorLockState(TWEntry* entry);
-static TWResultCode processEntryZCLDefaultResponse(TWEntry* entry);
-static TWResultCode processEntryZoneEnrollRequest(TWEntry* entry);
-static TWResultCode processEntryEnrolled(TWEntry* entry);
-static TWResultCode processEntryZoneStatus(TWEntry* entry);
-static TWResultCode processEntryAddressResponse(TWEntry* entry);
-
-static TWResultCode Reset();
-static TWResultCode GetRemoteEUI();
-static TWResultCode CreatePAN();
-static TWResultCode EnableJoin(bool isKeyEncrypted);
-static TWResultCode FindMatchNodes();
-static TWResultCode FindClusters(char nodeId[], char endpoint[]);
-
-static TWResultCode TelNetworkInfoHandler(int count, char* tokens[]);
-static TWResultCode TelJpanHandler(int count, char* tokens[]);
-static TWResultCode TelEndDeviceJoinHandler(int count, char* tokens[]);
-static TWResultCode TelMatchDescHandler(int count, char* tokens[]);
-static TWResultCode TelAddressResponseHandler(int count, char* tokens[]);
-static TWResultCode TelSimpleDescHandler(int count, char* tokens[]);
-static TWResultCode TelSimpleDescInClusterHandler(int count, char* tokens[]);
-static TWResultCode TelWriteAttrHandler(int count, char* tokens[]);
-static TWResultCode TelReadAttrHandler(int count, char* tokens[]);
-static TWResultCode TelReadAttrHandlerTemperature(int count, char* tokens[]);
-static TWResultCode TelZCLDefaultResponseHandler(int count, char* tokens[]);
-static TWResultCode TelSwitchDoorLockStateHandler(int count, char* tokens[]);
-static TWResultCode TelZoneEnrollRequestHandler(int count, char* tokens[]);
-static TWResultCode TelEnrolledHandler(int count, char* tokens[]);
-static TWResultCode TelZoneStatusHandler(int count, char* tokens[]);
+static TWResultCode HandleATResponse(TWEntry* entry, TWContext* ctx);
+
+static TWResultCode processEntry(TWEntry* entry, TWContext* ctx);
+static TWResultCode processEntryNETWORK_INFO(TWEntry* entry, TWContext* ctx);
+static TWResultCode processEntryJPAN(TWEntry* entry, TWContext* ctx);
+static TWResultCode processEntryEndDevice(TWEntry* entry, TWContext* ctx);
+static TWResultCode processEntryMatchDesc(TWEntry* entry, TWContext* ctx);
+static TWResultCode processEntrySimpleDesc(TWEntry* entry, TWContext* ctx);
+static TWResultCode processEntryWriteAttr(TWEntry* entry, TWContext* ctx);
+static TWResultCode processEntryReadAttr(TWEntry* entry, TWContext* ctx);
+static TWResultCode processEntryTemperature(TWEntry* entry, TWContext* ctx);
+static TWResultCode processEntrySwitchDoorLockState(TWEntry* entry, TWContext* ctx);
+static TWResultCode processEntryZCLDefaultResponse(TWEntry* entry, TWContext* ctx);
+static TWResultCode processEntryZoneEnrollRequest(TWEntry* entry, TWContext* ctx);
+static TWResultCode processEntryEnrolled(TWEntry* entry, TWContext* ctx);
+static TWResultCode processEntryZoneStatus(TWEntry* entry, TWContext* ctx);
+static TWResultCode processEntryAddressResponse(TWEntry* entry, TWContext* ctx);
+
+static TWResultCode Reset(TWContext* ctx);
+static TWResultCode GetRemoteEUI(char *nodeId, char* outRemoteEUI, TWContext* ctx);
+static TWResultCode CreatePAN(TWContext* ctx);
+static TWResultCode EnableJoin(bool isKeyEncrypted, TWContext* ctx);
+static TWResultCode FindMatchNodes(TWContext* ctx);
+static TWResultCode FindClusters(char nodeId[], char endpoint[], TWContext* ctx);
+
+static TWResultCode TelNetworkInfoHandler(int count, char* tokens[], TWContext* ctx);
+static TWResultCode TelJpanHandler(int count, char* tokens[], TWContext* ctx);
+static TWResultCode TelEndDeviceJoinHandler(int count, char* tokens[], TWContext* ctx);
+static TWResultCode TelMatchDescHandler(int count, char* tokens[], TWContext* ctx);
+static TWResultCode TelAddressResponseHandler(int count, char* tokens[], TWContext* ctx);
+static TWResultCode TelSimpleDescHandler(int count, char* tokens[], TWContext* ctx);
+static TWResultCode TelSimpleDescInClusterHandler(int count, char* tokens[], TWContext* ctx);
+static TWResultCode TelWriteAttrHandler(int count, char* tokens[], TWContext* ctx);
+static TWResultCode TelReadAttrHandler(int count, char* tokens[], TWContext* ctx);
+static TWResultCode TelReadAttrHandlerTemperature(int count, char* tokens[], TWContext* ctx);
+static TWResultCode TelZCLDefaultResponseHandler(int count, char* tokens[], TWContext* ctx);
+static TWResultCode TelSwitchDoorLockStateHandler(int count, char* tokens[], TWContext* ctx);
+static TWResultCode TelZoneEnrollRequestHandler(int count, char* tokens[], TWContext* ctx);
+static TWResultCode TelEnrolledHandler(int count, char* tokens[], TWContext* ctx);
+static TWResultCode TelZoneStatusHandler(int count, char* tokens[], TWContext* ctx);
 
 static TWResultCode AsciiHexToValue(char* hexString, int length, uint64_t* value);
 static int AsciiToHex(char c);
 static int Tokenize(const char *input, const char* delimiters, char* output[]);
 
-static void DeallocateTWDeviceList();
+static void DeallocateTWDeviceList(TWContext* ctx);
+static TWContext* GetTWContext(PIPlugin_Zigbee * plugin);
 
 //-----------------------------------------------------------------------------
 // Private variables
@@ -141,125 +233,179 @@ static TWATResultHandlerPair g_TWATResultHandlerPairArray[] =
     {"Unknown:",    TelNetworkInfoHandler}
 };
 
-//TODO: Take care of all global variables
-static PIPlugin* g_plugin = (PIPlugin*)1;
-static const char* g_port = NULL;
-
-static char g_LocalEUI[SIZE_EUI] = "";
-static char g_WIPRemoteEUI[SIZE_EUI] = "";
-static char g_WIPRemoteNodeId[SIZE_NODEID] = "";
+static TWContext* g_twContextList = NULL;
 
-static TWStatus g_ZigBeeStatus = {ZB_STATE_UNKNOWN,0,0,NULL,0};
-static TWDeviceList* g_FoundMatchedDeviceList = NULL;
-static TWDevice* g_WIPDevice = NULL;
-
-static TWDeviceFoundCallback g_DeviceFoundCallback = NULL;
-static TWEnrollmentSucceedCallback g_EnrollmentSucceedCallback = NULL;
-static TWDeviceStatusUpdateCallback g_DeviceStatusUpdateCallback = NULL;
+void InitializeContext(TWContext* context)
+{
+    context->g_port = NULL;
+    memset(context->g_LocalEUI, '\0', sizeof(context->g_LocalEUI));
+    memset(context->g_WIPRemoteEUI, '\0', sizeof(context->g_WIPRemoteEUI));
+    memset(context->g_WIPRemoteNodeId, '\0', sizeof(context->g_WIPRemoteNodeId));
+
+    context->g_ZigBeeStatus.state = ZB_STATE_UNKNOWN;
+    context->g_ZigBeeStatus.panId = 0;
+    context->g_ZigBeeStatus.extPanId = 0;
+    context->g_ZigBeeStatus.remoteAttributeValueRead = NULL;
+    context->g_ZigBeeStatus.remoteAtrributeValueReadLength = 0;
+
+    context->g_FoundMatchedDeviceList = NULL;
+    context->g_WIPDevice = NULL;
+
+    context->g_DeviceFoundCallback = NULL;
+    context->g_EnrollmentSucceedCallback = NULL;
+    context->g_DeviceStatusUpdateCallback = NULL;
+    context->g_EndDeviceNodeIdChangedCallback = NULL;
+}
 
 /*****************************************************************************/
 /*                                                                           */
 /* Public functions                                                          */
 /*                                                                           */
 /*****************************************************************************/
-OCStackResult TWInitialize(const char* deviceDevPath)
+OCStackResult TWInitialize(PIPlugin_Zigbee* plugin, const char* deviceDevPath)
 {
-    OC_LOG_V(INFO, TAG, "Enter TWInitialize()");
+    OIC_LOG(INFO, TAG, "Enter TWInitialize()");
 
     TWResultCode twCode = TW_RESULT_ERROR;
 
-    g_port = deviceDevPath;
-    OC_LOG_V(INFO, TAG, "Attempt to open %s", deviceDevPath);
+    if ((plugin == NULL) || (deviceDevPath == NULL))
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
 
-    twCode = TWStartSock(g_plugin, deviceDevPath);  //TODO:
+    if (g_twContextList != NULL)
+    {
+        TWContext* out = NULL;
+        TWContext* temp = NULL;
+        LL_FOREACH_SAFE(g_twContextList, out, temp)
+        {
+            if (out->g_plugin == plugin)
+            {
+                //Ignore because it's already in the list.
+                return TW_RESULT_OK;
+            }
+        }
+    }
+
+    TWContext* ctx = (TWContext*)OICCalloc(1, sizeof(*ctx));
+    if (ctx == NULL)
+    {
+        return OC_STACK_NO_MEMORY;
+    }
+    InitializeContext(ctx);
+    ctx->g_plugin = plugin;
+    ctx->g_port = deviceDevPath;
 
+    OIC_LOG_V(INFO, TAG, "Attempt to open %s", deviceDevPath);
+
+    twCode = TWStartSock(ctx->g_plugin, deviceDevPath);  //TODO:
     if (twCode != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "Failed to open %s because of error: %d", deviceDevPath, twCode);
+        OIC_LOG_V(ERROR, TAG, "Failed to open %s because of error: %d", deviceDevPath, twCode);
+        OICFree(ctx);
         return OC_STACK_ERROR;
     }
 
     char* eui = NULL;
-    twCode = TWGetEUI(g_plugin, &eui);
+    twCode = TWGetEUI(ctx->g_plugin, &eui);
     if (twCode != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "Failed to get EUI because of error: %d", twCode);
+        OIC_LOG_V(ERROR, TAG, "Failed to get EUI because of error: %d", twCode);
+        OICFree(ctx);
         return OC_STACK_ERROR;
     }
-    OICStrcpy(g_LocalEUI, SIZE_EUI, eui);
-    OC_LOG_V(INFO, TAG, "LocalEUI=%s", g_LocalEUI);
+    OICStrcpy(ctx->g_LocalEUI, sizeof(ctx->g_LocalEUI), eui);
+    OIC_LOG_V(INFO, TAG, "LocalEUI=%s", ctx->g_LocalEUI);
     OICFree(eui);
 
     bool wantReset = false;     //TODO:
     if (wantReset)
     {
-        twCode = Reset();
+        twCode = Reset(ctx);
         if (twCode != TW_RESULT_OK)
         {
-            OC_LOG_V(ERROR, TAG, "ZigBee Initialization - Reset");
+            OIC_LOG(ERROR, TAG, "ZigBee Initialization - Reset");
+            OICFree(ctx);
             return OC_STACK_ERROR;
         }
     }
 
-    twCode = CreatePAN();
+    twCode = CreatePAN(ctx);
     if (twCode != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "CreatePan Failed");
-        OC_LOG_V(ERROR, TAG, "TWInitialize() - MUST STOP NOW");
-        g_ZigBeeStatus.state = ZB_STATE_UNKNOWN;
+        OIC_LOG(ERROR, TAG, "CreatePan Failed");
+        OIC_LOG(ERROR, TAG, "TWInitialize() - MUST STOP NOW");
+        ctx->g_ZigBeeStatus.state = ZB_STATE_UNKNOWN;
+        OICFree(ctx);
         return OC_STACK_ERROR;
     }
     else
     {
-        OC_LOG_V(INFO, TAG, "CreatePan Succeed");
-        OC_LOG_V(INFO, TAG, "TWInitialize() Succeed");
+        OIC_LOG(INFO, TAG, "CreatePan Succeed");
+        OIC_LOG(INFO, TAG, "TWInitialize() Succeed");
+        ctx->g_ZigBeeStatus.state = ZB_STATE_INIT;
+        LL_APPEND(g_twContextList, ctx);
         return OC_STACK_OK;
     }
 }
 
-OCStackResult TWDiscover()
+OCStackResult TWDiscover(PIPlugin_Zigbee* plugin)
 {
-    OC_LOG_V(INFO, TAG, "Enter TWDiscover()");
+    OIC_LOG(INFO, TAG, "Enter TWDiscover()");
 
     OCStackResult ret = OC_STACK_ERROR;
     TWResultCode twRet = TW_RESULT_ERROR;
 
-    if (g_DeviceFoundCallback == NULL)
+    TWContext* ctx = GetTWContext(plugin);
+    if (ctx == NULL)
     {
-        OC_LOG_V(INFO, TAG, "Required TWDeviceFoundCallback.");
+        OIC_LOG(ERROR, TAG, "Invalid Param");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    if (ctx->g_DeviceFoundCallback == NULL)
+    {
+        OIC_LOG(INFO, TAG, "Required TWDeviceFoundCallback.");
         return OC_STACK_ERROR;
     }
 
-    twRet = EnableJoin(false);
+    twRet = EnableJoin(false, ctx);
     if (twRet != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "EnableJoin");
+        OIC_LOG(ERROR, TAG, "EnableJoin");
         return OC_STACK_ERROR;
     }
 
-    twRet = FindMatchNodes();
+    twRet = FindMatchNodes(ctx);
     if (twRet == TW_RESULT_OK)
     {
-        OC_LOG_V(INFO, TAG, "FindMatchNodes");
+        OIC_LOG(INFO, TAG, "FindMatchNodes");
         ret = OC_STACK_OK;
     }
     else
     {
-        OC_LOG_V(ERROR, TAG, "FindMatchNodes");
+        OIC_LOG(ERROR, TAG, "FindMatchNodes");
         ret = OC_STACK_ERROR;
     }
 
-    OC_LOG_V(INFO, TAG, "Leave TWDiscover() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave TWDiscover() with ret=%d", ret);
     return ret;
 }
 
 OCStackResult TWSetAttribute(char* extendedUniqueId, char* nodeId, char* endpointId,
                              char* clusterId, char* attributeId, char* attributeType,
-                             char* newValue)
+                             char* newValue, PIPlugin_Zigbee* plugin)
 {
     //Ask:  AT+WRITEATR:5DA7,01,0,0003,0000,21,01
 
-    OC_LOG_V(INFO, TAG, "Enter TWSetAttribute()");
+    OIC_LOG(INFO, TAG, "Enter TWSetAttribute()");
+
+    TWContext* ctx = GetTWContext(plugin);
+    if (ctx == NULL)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid Param");
+        return OC_STACK_INVALID_PARAM;
+    }
 
     (void)extendedUniqueId;
 
@@ -277,7 +423,7 @@ OCStackResult TWSetAttribute(char* extendedUniqueId, char* nodeId, char* endpoin
     char* cmdString = (char*)OICMalloc(size * sizeof(char));
     if (cmdString == NULL)
     {
-        OC_LOG_V(ERROR, TAG, "No Memory");
+        OIC_LOG(ERROR, TAG, "No Memory");
         ret = OC_STACK_ERROR;
         goto exit;
     }
@@ -285,34 +431,40 @@ OCStackResult TWSetAttribute(char* extendedUniqueId, char* nodeId, char* endpoin
              AT_CMD_WRITE_ATR, nodeId, endpointId, SENDMODE,
              clusterId, attributeId, attributeType, newValue);
 
-    twRet = TWIssueATCommand(g_plugin, cmdString);
+    twRet = TWIssueATCommand(ctx->g_plugin, cmdString);
     if (twRet != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "Write %s", cmdString);
+        OIC_LOG_V(ERROR, TAG, "Write %s", cmdString);
         ret = OC_STACK_ERROR;
         goto exit;
     }
-    OC_LOG_V(INFO, TAG, "Write %s", cmdString);
+    OIC_LOG_V(INFO, TAG, "Write %s", cmdString);
 
     TWEntry* entry = NULL;
-    twRet = TWDequeueEntry(g_plugin, &entry, TW_WRITEATTR);
+    twRet = TWDequeueEntry(ctx->g_plugin, &entry, TW_WRITEATTR);
     if (twRet != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "TWDequeueEntry");
+        OIC_LOG(ERROR, TAG, "TWDequeueEntry");
         ret = OC_STACK_ERROR;
         goto exit;
     }
     if (entry == NULL)
     {
-        OC_LOG_V(INFO, TAG, "TWEntry is NULL.");
+        OIC_LOG(INFO, TAG, "TWEntry is NULL.");
         ret = OC_STACK_ERROR;
         goto exit;
     }
 
-    twRet = processEntry(entry);
+    twRet = processEntry(entry, ctx);
+    if (twRet == TW_RESULT_ERROR_INVALID_OP)
+    {
+        OIC_LOG_V(INFO, TAG, "Write %s - Invalid Operation", cmdString);
+        ret = OC_STACK_INVALID_OPTION;
+        goto exit;
+    }
     if (twRet != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "processEntry");
+        OIC_LOG(ERROR, TAG, "processEntry");
         ret = OC_STACK_ERROR;
         goto exit;
     }
@@ -320,19 +472,26 @@ OCStackResult TWSetAttribute(char* extendedUniqueId, char* nodeId, char* endpoin
     ret = OC_STACK_OK;
 
 exit:
-    TWDeleteEntry(g_plugin, entry);
+    TWDeleteEntry(ctx->g_plugin, entry);
     OICFree(cmdString);
-    OC_LOG_V(INFO, TAG, "Leave TWSetAttribute() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave TWSetAttribute() with ret=%d", ret);
     return ret;
 }
 
 OCStackResult TWGetAttribute(char* extendedUniqueId, char* nodeId, char* endpointId,
                              char* clusterId, char* attributeId,
-                             char** outValue, uint8_t* outValueLength)
+                             char** outValue, uint8_t* outValueLength,
+                             PIPlugin_Zigbee* plugin)
 {
     //Ask:  AT+READATR:FE5A,01,0,0402,0002
 
-    OC_LOG_V(INFO, TAG, "Enter TWGetAttribute()");
+    OIC_LOG(INFO, TAG, "Enter TWGetAttribute()");
+
+    TWContext* ctx = GetTWContext(plugin);
+    if (ctx == NULL)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
 
     (void)extendedUniqueId;
 
@@ -348,7 +507,7 @@ OCStackResult TWGetAttribute(char* extendedUniqueId, char* nodeId, char* endpoin
     char* cmdString = (char*)OICMalloc(size * sizeof(char));
     if (cmdString == NULL)
     {
-        OC_LOG_V(ERROR, TAG, "No Memory");
+        OIC_LOG(ERROR, TAG, "No Memory");
         ret = OC_STACK_NO_MEMORY;
         goto exit;
     }
@@ -360,74 +519,82 @@ OCStackResult TWGetAttribute(char* extendedUniqueId, char* nodeId, char* endpoin
                              SEPARATOR, attributeId);
     if(stringRet <= 0)
     {
-        OC_LOG_V(ERROR, TAG, "Build command error.");
+        OIC_LOG(ERROR, TAG, "Build command error.");
         ret = OC_STACK_ERROR;
         goto exit;
     }
-    twRet = TWIssueATCommand(g_plugin, cmdString);
+    twRet = TWIssueATCommand(ctx->g_plugin, cmdString);
     if (twRet != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "Write %s", cmdString);
+        OIC_LOG_V(ERROR, TAG, "Write %s", cmdString);
         ret = OC_STACK_ERROR;
         goto exit;
     }
-    OC_LOG_V(INFO, TAG, "Write %s", cmdString);
+    OIC_LOG_V(INFO, TAG, "Write %s", cmdString);
 
     TWEntry* entry = NULL;
-    twRet = TWDequeueEntry(g_plugin, &entry, TW_RESPATTR);
+    twRet = TWDequeueEntry(ctx->g_plugin, &entry, TW_RESPATTR);
     if (twRet != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "TWDequeueEntry");
+        OIC_LOG(ERROR, TAG, "TWDequeueEntry");
         ret = OC_STACK_ERROR;
         goto exit;
     }
     if (entry == NULL)
     {
-        OC_LOG_V(INFO, TAG, "TWEntry is NULL");
+        OIC_LOG(INFO, TAG, "TWEntry is NULL");
         ret = OC_STACK_ERROR;
         goto exit;
     }
 
-    twRet = processEntry(entry);
+    twRet = processEntry(entry, ctx);
     if (twRet != TW_RESULT_REMOTE_ATTR_HAS_VALUE)
     {
-        OC_LOG_V(ERROR, TAG, "processEntry.");
+        OIC_LOG(ERROR, TAG, "processEntry.");
         ret = OC_STACK_ERROR;
         goto exit;
     }
 
-    size = strlen(g_ZigBeeStatus.remoteAttributeValueRead) + 1;
+    size = strlen(ctx->g_ZigBeeStatus.remoteAttributeValueRead) + 1;
     *outValue = (char*)OICMalloc(sizeof(char) * size);
     if (*outValue == NULL)
     {
-        OC_LOG_V(ERROR, TAG, "No Memory");
+        OIC_LOG(ERROR, TAG, "No Memory");
         ret = OC_STACK_NO_MEMORY;
         goto exit;
     }
 
-    OICStrcpy(*outValue, size, g_ZigBeeStatus.remoteAttributeValueRead);
-    *outValueLength = g_ZigBeeStatus.remoteAtrributeValueReadLength;
-    OICFree(g_ZigBeeStatus.remoteAttributeValueRead);
-    g_ZigBeeStatus.remoteAttributeValueRead = NULL;
-    g_ZigBeeStatus.remoteAtrributeValueReadLength = 0;
-    OC_LOG_V(INFO, TAG, "TWGetAttribute() gets an attribute value.");
+    OICStrcpy(*outValue, size, ctx->g_ZigBeeStatus.remoteAttributeValueRead);
+    *outValueLength = ctx->g_ZigBeeStatus.remoteAtrributeValueReadLength;
+    OICFree(ctx->g_ZigBeeStatus.remoteAttributeValueRead);
+    ctx->g_ZigBeeStatus.remoteAttributeValueRead = NULL;
+    ctx->g_ZigBeeStatus.remoteAtrributeValueReadLength = 0;
+    OIC_LOG(INFO, TAG, "TWGetAttribute() gets an attribute value.");
     ret = OC_STACK_OK;
 
 exit:
-    TWDeleteEntry(g_plugin, entry);
+    TWDeleteEntry(ctx->g_plugin, entry);
     OICFree(cmdString);
-    OC_LOG_V(INFO, TAG, "Leave TWGetAttribute() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave TWGetAttribute() with ret=%d", ret);
     return ret;
 }
 
-OCStackResult TWSwitchOnOff(char* nodeId, char* endpointId, char* newState)
+OCStackResult TWSwitchOnOff(char* nodeId, char* endpointId, char* newState,
+                            PIPlugin_Zigbee* plugin)
 {
     //AT+RONOFF:<Address>,<EP>,<SendMode>[,<ON/OFF>]
     //AT+RONOFF:9E2B,01,0,1
     //      OK
     //      DFTREP:9E2B,01,0006,01,00
 
-    OC_LOG_V(INFO, TAG, "Enter TWSwitchOnOff()");
+    OIC_LOG(INFO, TAG, "Enter TWSwitchOnOff()");
+
+    TWContext* ctx = GetTWContext(plugin);
+    if (ctx == NULL)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid Param");
+        return OC_STACK_INVALID_PARAM;
+    }
 
     OCStackResult ret = OC_STACK_ERROR;
     TWResultCode twRet = TW_RESULT_UNKNOWN;
@@ -450,7 +617,7 @@ OCStackResult TWSwitchOnOff(char* nodeId, char* endpointId, char* newState)
     char* cmdString = (char*)OICMalloc(size * sizeof(char));
     if (cmdString == NULL)
     {
-        OC_LOG_V(ERROR, TAG, "No Memory");
+        OIC_LOG(ERROR, TAG, "No Memory");
         ret = OC_STACK_NO_MEMORY;
         goto exit;
     }
@@ -460,7 +627,7 @@ OCStackResult TWSwitchOnOff(char* nodeId, char* endpointId, char* newState)
                              endpointId, SEPARATOR, SENDMODE);
     if(stringRet <= 0)
     {
-        OC_LOG_V(ERROR, TAG, "Build command error.");
+        OIC_LOG(ERROR, TAG, "Build command error.");
         ret = OC_STACK_ERROR;
         goto exit;
     }
@@ -470,34 +637,34 @@ OCStackResult TWSwitchOnOff(char* nodeId, char* endpointId, char* newState)
         OICStrcat(cmdString, size, newState);
     }
 
-    twRet = TWIssueATCommand(g_plugin, cmdString);
+    twRet = TWIssueATCommand(ctx->g_plugin, cmdString);
     if (twRet != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "Write %s", cmdString);
+        OIC_LOG_V(ERROR, TAG, "Write %s", cmdString);
         ret = OC_STACK_ERROR;
         goto exit;
     }
-    OC_LOG_V(INFO, TAG, "Write %s", cmdString);
+    OIC_LOG_V(INFO, TAG, "Write %s", cmdString);
 
     TWEntry* entry = NULL;
-    twRet = TWDequeueEntry(g_plugin, &entry, TW_DFTREP);
+    twRet = TWDequeueEntry(ctx->g_plugin, &entry, TW_DFTREP);
     if (twRet != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "TWDequeueEntry");
+        OIC_LOG(ERROR, TAG, "TWDequeueEntry");
         ret = OC_STACK_ERROR;
         goto exit;
     }
     if (entry == NULL)
     {
-        OC_LOG_V(ERROR, TAG, "TWEntry is NULL");
+        OIC_LOG(ERROR, TAG, "TWEntry is NULL");
         ret = OC_STACK_ERROR;
         goto exit;
     }
 
-    twRet = processEntry(entry);
+    twRet = processEntry(entry, ctx);
     if (twRet != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "processEntry - %s", cmdString);
+        OIC_LOG_V(ERROR, TAG, "processEntry - %s", cmdString);
         ret = OC_STACK_ERROR;
         goto exit;
     }
@@ -505,18 +672,26 @@ OCStackResult TWSwitchOnOff(char* nodeId, char* endpointId, char* newState)
     ret = OC_STACK_OK;
 
 exit:
-    TWDeleteEntry(g_plugin, entry);
+    TWDeleteEntry(ctx->g_plugin, entry);
     OICFree(cmdString);
-    OC_LOG_V(INFO, TAG, "Leave TWSwitchOnOff() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave TWSwitchOnOff() with ret=%d", ret);
     return ret;
 }
 
 OCStackResult TWMoveToLevel(char* nodeId, char* endpointId,
-                            char* onOffState, char* level, char* transTime)
+                            char* onOffState, char* level, char* transTime,
+                            PIPlugin_Zigbee* plugin)
 {
     //AT+LCMVTOLEV:<Address>,<EP>,<SendMode>,<ON/OFF>,<LevelValue>,<TransTime>
 
-    OC_LOG_V(INFO, TAG, "Enter TWMoveToLevel()");
+    OIC_LOG(INFO, TAG, "Enter TWMoveToLevel()");
+
+    TWContext* ctx = GetTWContext(plugin);
+    if (ctx == NULL)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid Param");
+        return OC_STACK_INVALID_PARAM;
+    }
 
     OCStackResult ret = OC_STACK_ERROR;
     TWResultCode twRet = TW_RESULT_UNKNOWN;
@@ -532,7 +707,7 @@ OCStackResult TWMoveToLevel(char* nodeId, char* endpointId,
     char* cmdString = (char*)OICMalloc(size * sizeof(char));
     if (cmdString == NULL)
     {
-        OC_LOG_V(ERROR, TAG, "No Memory");
+        OIC_LOG(ERROR, TAG, "No Memory");
         ret = OC_STACK_NO_MEMORY;
         goto exit;
     }
@@ -546,40 +721,40 @@ OCStackResult TWMoveToLevel(char* nodeId, char* endpointId,
                              SEPARATOR, transTime);
     if(stringRet <= 0)
     {
-        OC_LOG_V(ERROR, TAG, "Build command error.");
+        OIC_LOG(ERROR, TAG, "Build command error.");
         ret = OC_STACK_ERROR;
         goto exit;
     }
 
-    twRet = TWIssueATCommand(g_plugin, cmdString);
+    twRet = TWIssueATCommand(ctx->g_plugin, cmdString);
     if (twRet != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "Write %s", cmdString);
+        OIC_LOG_V(ERROR, TAG, "Write %s", cmdString);
         ret = OC_STACK_ERROR;
         goto exit;
     }
 
-    OC_LOG_V(INFO, TAG, "Write %s", cmdString);
+    OIC_LOG_V(INFO, TAG, "Write %s", cmdString);
 
     TWEntry* entry = NULL;
-    twRet = TWDequeueEntry(g_plugin, &entry, TW_DFTREP);
+    twRet = TWDequeueEntry(ctx->g_plugin, &entry, TW_DFTREP);
     if (twRet != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "TWDequeueEntry");
+        OIC_LOG(ERROR, TAG, "TWDequeueEntry");
         ret = OC_STACK_ERROR;
         goto exit;
     }
     if (entry == NULL)
     {
-        OC_LOG_V(ERROR, TAG, "TWEntry is NULL");
+        OIC_LOG(ERROR, TAG, "TWEntry is NULL");
         ret = OC_STACK_ERROR;
         goto exit;
     }
 
-    twRet = processEntry(entry);
+    twRet = processEntry(entry, ctx);
     if (twRet != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "processEntry - %s", cmdString);
+        OIC_LOG_V(ERROR, TAG, "processEntry - %s", cmdString);
         ret = OC_STACK_ERROR;
         goto exit;
     }
@@ -587,17 +762,25 @@ OCStackResult TWMoveToLevel(char* nodeId, char* endpointId,
     ret = OC_STACK_OK;
 
 exit:
-    TWDeleteEntry(g_plugin, entry);
+    TWDeleteEntry(ctx->g_plugin, entry);
     OICFree(cmdString);
-    OC_LOG_V(INFO, TAG, "Leave TWMoveToLevel() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave TWMoveToLevel() with ret=%d", ret);
     return ret;
 }
 
-OCStackResult TWSwitchDoorLockState(char* nodeId, char* endpointId, char* newState)
+OCStackResult TWSwitchDoorLockState(char* nodeId, char* endpointId, char* newState,
+                                    PIPlugin_Zigbee* plugin)
 {
     //AT+DRLOCK:<Address>,<EP>,<SendMode>,<Lock/Unlock>
 
-    OC_LOG_V(INFO, TAG, "Enter TWSwitchDoorLockState()");
+    OIC_LOG(INFO, TAG, "Enter TWSwitchDoorLockState()");
+
+    TWContext* ctx = GetTWContext(plugin);
+    if (ctx == NULL)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid Param");
+        return OC_STACK_INVALID_PARAM;
+    }
 
     OCStackResult ret = OC_STACK_ERROR;
     TWResultCode twRet = TW_RESULT_UNKNOWN;
@@ -611,7 +794,7 @@ OCStackResult TWSwitchDoorLockState(char* nodeId, char* endpointId, char* newSta
     char* cmdString = (char*)OICMalloc(size * sizeof(char));
     if (cmdString == NULL)
     {
-        OC_LOG_V(ERROR, TAG, "No Memory");
+        OIC_LOG(ERROR, TAG, "No Memory");
         ret = OC_STACK_NO_MEMORY;
         goto exit;
     }
@@ -623,41 +806,41 @@ OCStackResult TWSwitchDoorLockState(char* nodeId, char* endpointId, char* newSta
                              SEPARATOR, newState);
     if(stringRet <= 0)
     {
-        OC_LOG_V(ERROR, TAG, "Build command error.");
+        OIC_LOG(ERROR, TAG, "Build command error.");
         ret = OC_STACK_ERROR;
         goto exit;
     }
 
-    twRet = TWIssueATCommand(g_plugin, cmdString);
+    twRet = TWIssueATCommand(ctx->g_plugin, cmdString);
     if (twRet != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "Write %s", cmdString);
+        OIC_LOG_V(ERROR, TAG, "Write %s", cmdString);
         ret = OC_STACK_ERROR;
         goto exit;
     }
 
-    OC_LOG_V(INFO, TAG, "Write %s", cmdString);
+    OIC_LOG_V(INFO, TAG, "Write %s", cmdString);
 
     TWEntry* entry = NULL;
-    twRet = TWDequeueEntry(g_plugin, &entry, TW_DFTREP);
+    twRet = TWDequeueEntry(ctx->g_plugin, &entry, TW_DFTREP);
     if (twRet != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "TWDequeueEntry");
+        OIC_LOG(ERROR, TAG, "TWDequeueEntry");
         ret = OC_STACK_ERROR;
         goto exit;
     }
 
     if (entry == NULL)
     {
-        OC_LOG_V(ERROR, TAG, "TWEntry is NULL");
+        OIC_LOG(ERROR, TAG, "TWEntry is NULL");
         ret = OC_STACK_ERROR;
         goto exit;
     }
 
-    twRet = processEntry(entry);
+    twRet = processEntry(entry, ctx);
     if (twRet != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "processEntry - %s", cmdString);
+        OIC_LOG_V(ERROR, TAG, "processEntry - %s", cmdString);
         ret = OC_STACK_ERROR;
         goto exit;
     }
@@ -665,21 +848,29 @@ OCStackResult TWSwitchDoorLockState(char* nodeId, char* endpointId, char* newSta
     ret = OC_STACK_OK;
 
 exit:
-    TWDeleteEntry(g_plugin, entry);
+    TWDeleteEntry(ctx->g_plugin, entry);
     OICFree(cmdString);
-    OC_LOG_V(INFO, TAG, "Leave TWSwitchDoorLockState() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave TWSwitchDoorLockState() with ret=%d", ret);
     return ret;
 }
 
 OCStackResult TWColorMoveToColorTemperature(char* nodeId, char* endpointId,
-                                            char* colorTemperature, char* transTime)
+                                            char* colorTemperature, char* transTime,
+                                            PIPlugin_Zigbee* plugin)
 {
 
     //AT+CCMVTOCT:<Address>,<EP>,<SendMode>,<ColorTemperature>,<TransTime>
     //  OK
     //  ERROR:<errorcode>
 
-    OC_LOG_V(INFO, TAG, "Enter TWColorMoveToColorTemperature()");
+    OIC_LOG(INFO, TAG, "Enter TWColorMoveToColorTemperature()");
+
+    TWContext* ctx = GetTWContext(plugin);
+    if (ctx == NULL)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid Param");
+        return OC_STACK_INVALID_PARAM;
+    }
 
     OCStackResult ret = OC_STACK_ERROR;
     TWResultCode twRet = TW_RESULT_UNKNOWN;
@@ -694,7 +885,7 @@ OCStackResult TWColorMoveToColorTemperature(char* nodeId, char* endpointId,
     char* cmdString = (char*)OICMalloc(size * sizeof(char));
     if (cmdString == NULL)
     {
-        OC_LOG_V(ERROR, TAG, "No Memory");
+        OIC_LOG(ERROR, TAG, "No Memory");
         ret = OC_STACK_NO_MEMORY;
         goto exit;
     }
@@ -707,38 +898,38 @@ OCStackResult TWColorMoveToColorTemperature(char* nodeId, char* endpointId,
                              SEPARATOR, transTime);
     if(stringRet <= 0)
     {
-        OC_LOG_V(ERROR, TAG, "Build command error.");
+        OIC_LOG(ERROR, TAG, "Build command error.");
         ret = OC_STACK_ERROR;
         goto exit;
     }
-    twRet = TWIssueATCommand(g_plugin, cmdString);
+    twRet = TWIssueATCommand(ctx->g_plugin, cmdString);
     if (twRet != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "Write %s", cmdString);
+        OIC_LOG_V(ERROR, TAG, "Write %s", cmdString);
         ret = OC_STACK_ERROR;
         goto exit;
     }
-    OC_LOG_V(INFO, TAG, "Write %s", cmdString);
+    OIC_LOG_V(INFO, TAG, "Write %s", cmdString);
 
     TWEntry* entry = NULL;
-    twRet = TWDequeueEntry(g_plugin, &entry, TW_DFTREP);
+    twRet = TWDequeueEntry(ctx->g_plugin, &entry, TW_DFTREP);
     if (twRet != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "TWDequeueEntry - %s", cmdString);
+        OIC_LOG_V(ERROR, TAG, "TWDequeueEntry - %s", cmdString);
         ret = OC_STACK_ERROR;
         goto exit;
     }
     if (entry == NULL)
     {
-        OC_LOG_V(ERROR, TAG, "TWEntry is NULL - %s", cmdString);
+        OIC_LOG_V(ERROR, TAG, "TWEntry is NULL - %s", cmdString);
         ret = OC_STACK_ERROR;
         goto exit;
     }
 
-    twRet = processEntry(entry);
+    twRet = processEntry(entry, ctx);
     if (twRet != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "processEntry - %s", cmdString);
+        OIC_LOG_V(ERROR, TAG, "processEntry - %s", cmdString);
         ret = OC_STACK_ERROR;
         goto exit;
     }
@@ -746,72 +937,146 @@ OCStackResult TWColorMoveToColorTemperature(char* nodeId, char* endpointId,
     ret = OC_STACK_OK;
 
 exit:
-    TWDeleteEntry(g_plugin, entry);
+    TWDeleteEntry(ctx->g_plugin, entry);
     OICFree(cmdString);
-    OC_LOG_V(INFO, TAG, "Leave TWColorMoveToColorTemperature() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave TWColorMoveToColorTemperature() with ret=%d", ret);
     return ret;
 }
 
-OCStackResult TWSetDiscoveryCallback(const TWDeviceFoundCallback callback)
+OCStackResult TWSetDiscoveryCallback(const TWDeviceFoundCallback callback, PIPlugin_Zigbee* plugin)
 {
-    OC_LOG_V(INFO, TAG, "Enter TWSetDiscoveryCallback()");
-    if (callback != NULL)
+    OIC_LOG(INFO, TAG, "Enter TWSetDiscoveryCallback()");
+
+    OCStackResult ret = OC_STACK_OK;
+
+    TWContext* ctx = GetTWContext(plugin);
+    if (ctx == NULL)
     {
-        g_DeviceFoundCallback= callback;
+        ret = OC_STACK_INVALID_PARAM;
     }
     else
     {
-        g_DeviceFoundCallback = NULL;
+        if (callback != NULL)
+        {
+            ctx->g_DeviceFoundCallback= callback;
+        }
+        else
+        {
+            ctx->g_DeviceFoundCallback = NULL;
+        }
     }
 
-    OC_LOG_V(INFO, TAG, "Leave TWSetDiscoveryCallback() with ret=%d", OC_STACK_OK);
-    return OC_STACK_OK;
+    OIC_LOG_V(INFO, TAG, "Leave TWSetDiscoveryCallback() with ret=%d", ret);
+    return ret;
 }
 
-OCStackResult TWSetStatusUpdateCallback(TWDeviceStatusUpdateCallback callback)
+OCStackResult TWSetEndDeviceNodeIdChangedCallback(TWDeviceNodeIdChangedCallback callback,
+                                                  PIPlugin_Zigbee* plugin)
 {
-    OC_LOG_V(INFO, TAG, "Enter TWSetStatusUpdateCallback()");
-    if (callback != NULL)
+    OIC_LOG(INFO, TAG, "Enter TWSetEndDeviceNodeIdChangedCallback()");
+
+    OCStackResult ret = OC_STACK_OK;
+
+    TWContext* ctx = GetTWContext(plugin);
+    if (ctx == NULL)
     {
-        g_DeviceStatusUpdateCallback= callback;
+        ret = OC_STACK_INVALID_PARAM;
     }
     else
     {
-        g_DeviceStatusUpdateCallback = NULL;
+        if (callback != NULL)
+        {
+            ctx->g_EndDeviceNodeIdChangedCallback= callback;
+        }
+        else
+        {
+            ctx->g_EndDeviceNodeIdChangedCallback = NULL;
+        }
     }
+    OIC_LOG_V(INFO, TAG, "Leave TWSetEndDeviceNodeIdChangedCallback() with ret=%d", ret);
+    return ret;
+}
+
+OCStackResult TWSetStatusUpdateCallback(TWDeviceStatusUpdateCallback callback,
+                                        PIPlugin_Zigbee* plugin)
+{
+    OIC_LOG(INFO, TAG, "Enter TWSetStatusUpdateCallback()");
+
+    OCStackResult ret = OC_STACK_OK;
 
-    OC_LOG_V(INFO, TAG, "Leave TWSetStatusUpdateCallback() with ret=%d", OC_STACK_OK);
-    return OC_STACK_OK;
+    TWContext* ctx = GetTWContext(plugin);
+    if (ctx == NULL)
+    {
+        ret = OC_STACK_INVALID_PARAM;
+    }
+    else
+    {
+        if (callback != NULL)
+        {
+            ctx->g_DeviceStatusUpdateCallback= callback;
+        }
+        else
+        {
+            ctx->g_DeviceStatusUpdateCallback = NULL;
+        }
+    }
+
+    OIC_LOG_V(INFO, TAG, "Leave TWSetStatusUpdateCallback() with ret=%d", ret);
+    return ret;
 }
 
-OCStackResult TWListenForStatusUpdates(char* nodeId, char* endpointId)
+OCStackResult TWListenForStatusUpdates(char* nodeId, char* endpointId, PIPlugin_Zigbee* plugin)
 {
-    OC_LOG_V(INFO, TAG, "Enter TWListenForStatusUpdates()");
+    OIC_LOG(INFO, TAG, "Enter TWListenForStatusUpdates()");
 
-    char* zoneClusterID = "0500";
-    char* zoneAttributeID = "0010";
-    char* attributeDateType = "F0";
+    OCStackResult ret = OC_STACK_OK;
 
-    OCStackResult ret = TWSetAttribute(NULL, nodeId, endpointId,
-                                       zoneClusterID, zoneAttributeID, attributeDateType,
-                                       g_LocalEUI);
+    TWContext* ctx = GetTWContext(plugin);
+    if (ctx == NULL)
+    {
+        ret = OC_STACK_INVALID_PARAM;
+    }
+    else
+    {
+        char* zoneClusterID = "0500";
+        char* zoneAttributeID = "0010";
+        char* attributeDateType = "F0";
+
+        ret = TWSetAttribute(NULL, nodeId, endpointId,
+                             zoneClusterID, zoneAttributeID, attributeDateType,
+                             ctx->g_LocalEUI, ctx->g_plugin);
 
-    OC_LOG_V(INFO, TAG, "Leave TWListenForStatusUpdates() with ret=%d", ret);
+        if (ret == OC_STACK_INVALID_OPTION)
+        {
+            OIC_LOG(INFO, TAG, "Already registered for ZoneStatusUpdate");
+            ret = OC_STACK_OK;
+        }
+    }
+    OIC_LOG_V(INFO, TAG, "Leave TWListenForStatusUpdates() with ret=%d", ret);
     return ret;
 }
 
-OCStackResult TWProcess()
+OCStackResult TWProcess(PIPlugin_Zigbee* plugin)
 {
+    if (plugin == NULL)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+    TWContext* ctx = GetTWContext(plugin);
+    if (ctx == NULL)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
 
     TWResultCode ret = TW_RESULT_UNKNOWN;
 
     while (true)
     {
         TWEntry* entry = NULL;
-        ret = TWDequeueEntry(g_plugin, &entry, TW_NONE);
+        ret = TWDequeueEntry(ctx->g_plugin, &entry, TW_NONE);
         if (ret != TW_RESULT_OK)
         {
-            OC_LOG_V(ERROR, TAG, "TWDequeueEntry");
+            OIC_LOG(ERROR, TAG, "TWDequeueEntry");
             ret = OC_STACK_ERROR;
             break;
         }
@@ -821,25 +1086,25 @@ OCStackResult TWProcess()
             break;
         }
 
-        ret = processEntry(entry);
+        ret = processEntry(entry, ctx);
         if (ret != TW_RESULT_OK)
         {
-            OC_LOG_V(ERROR, TAG, "processEntry");
-            ret = TWDeleteEntry(g_plugin, entry);
+            OIC_LOG(ERROR, TAG, "processEntry");
+            ret = TWDeleteEntry(ctx->g_plugin, entry);
             if(ret != TW_RESULT_OK)
             {
-                OC_LOG_V(ERROR, TAG, "Failed to delete entry.");
+                OIC_LOG(ERROR, TAG, "Failed to delete entry.");
                 ret = OC_STACK_ERROR;
                 break;
             }
         }
         else
         {
-            OC_LOG_V(INFO, TAG, "processEntry");
-            ret = TWDeleteEntry(g_plugin, entry);
+            OIC_LOG(INFO, TAG, "processEntry");
+            ret = TWDeleteEntry(ctx->g_plugin, entry);
             if(ret != TW_RESULT_OK)
             {
-                OC_LOG_V(ERROR, TAG, "Failed to delete entry.");
+                OIC_LOG(ERROR, TAG, "Failed to delete entry.");
                 ret = OC_STACK_ERROR;
                 break;
             }
@@ -849,26 +1114,36 @@ OCStackResult TWProcess()
     return ret;
 }
 
-OCStackResult TWUninitialize()
+OCStackResult TWUninitialize(PIPlugin_Zigbee* plugin)
 {
-    OC_LOG_V(INFO, TAG, "Enter TWUninitializeZigBee()");
+    OIC_LOG(INFO, TAG, "Enter TWUninitializeZigBee()");
     OCStackResult ret = OC_STACK_ERROR;
 
-    TWResultCode twRet = TWStopSock(g_plugin);
-    if (twRet == TW_RESULT_OK)
+    TWContext* ctx = GetTWContext(plugin);
+    if (ctx == NULL)
     {
-        OC_LOG_V(INFO, TAG, "TWStopSock");
-        ret = OC_STACK_OK;
+        ret = OC_STACK_INVALID_PARAM;
     }
     else
     {
-        OC_LOG_V(ERROR, TAG, "TWStopSock");
-        ret = OC_STACK_ERROR;
-    }
+        TWResultCode twRet = TWStopSock(ctx->g_plugin);
+        if (twRet == TW_RESULT_OK)
+        {
+            OIC_LOG(INFO, TAG, "TWStopSock");
+            ret = OC_STACK_OK;
+        }
+        else
+        {
+            OIC_LOG(ERROR, TAG, "TWStopSock");
+            ret = OC_STACK_ERROR;
+        }
+        DeallocateTWDeviceList(ctx);
 
-    DeallocateTWDeviceList();
+        LL_DELETE(g_twContextList, ctx);
+        OICFree(ctx);
+    }
 
-    OC_LOG_V(INFO, TAG, "Leave TWUninitializeZigBee() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave TWUninitializeZigBee() with ret=%d", ret);
     return ret;
 }
 
@@ -876,173 +1151,155 @@ OCStackResult TWUninitialize()
 // Internal functions
 //-----------------------------------------------------------------------------
 
-TWResultCode processEntry(TWEntry *entry)
+TWResultCode processEntry(TWEntry *entry, TWContext* ctx)
 {
-    OC_LOG_V(INFO, TAG, "Enter processEntry()");
+    OIC_LOG(INFO, TAG, "Enter processEntry()");
 
     TWResultCode ret = TW_RESULT_UNKNOWN;
     switch(entry->type)
     {
-        /*
-        TW_OK,              TODO: Joey to return an TWEntry for OK
-        TW_ERROR,           TODO: Joey to return an TWEntry for ERROR
-
-        TW_INCLUSTER,
-
-        TW_ACK,
-        TW_NACK,
-        TW_SEQ,
-        TW_MAX_ENTRY
-         */
-
-        /*
-        TODO: Joey?
-        //Ask:          AT+PJOIN
-        //Response:     OK
-
-        //Ask:          AT+PJOIN
-        //Response:     ERROR:70
-
-         */
-
         case TW_NETWORK_INFO:
-            ret = processEntryNETWORK_INFO(entry);
+            ret = processEntryNETWORK_INFO(entry, ctx);
             if ((ret != TW_RESULT_NO_LOCAL_PAN) &&
                 (ret != TW_RESULT_HAS_LOCAL_PAN))
             {
-                OC_LOG_V(ERROR, TAG, "processEntryNETWORK_INFO.");
+                OIC_LOG(ERROR, TAG, "processEntryNETWORK_INFO.");
             }
             break;
         case TW_JPAN:
-            ret = processEntryJPAN(entry);
+            ret = processEntryJPAN(entry, ctx);
             if (ret != TW_RESULT_OK)
             {
-                OC_LOG_V(ERROR, TAG, "processEntryJPAN.");
+                OIC_LOG(ERROR, TAG, "processEntryJPAN.");
             }
             break;
         case TW_SED:
-            ret = processEntryEndDevice(entry);
+            ret = processEntryEndDevice(entry, ctx);
             if (ret != TW_RESULT_OK)
             {
-                OC_LOG_V(ERROR, TAG, "processEntrySED.");
+                OIC_LOG(ERROR, TAG, "processEntrySED.");
             }
             break;
         case TW_RFD:
-            ret = processEntryEndDevice(entry);
+            ret = processEntryEndDevice(entry, ctx);
             if (ret != TW_RESULT_OK)
             {
-                OC_LOG_V(ERROR, TAG, "processEntryRFD.");
+                OIC_LOG(ERROR, TAG, "processEntryRFD.");
             }
             break;
         case TW_FFD:
-            ret = processEntryEndDevice(entry);
+            ret = processEntryEndDevice(entry, ctx);
             if (ret != TW_RESULT_OK)
             {
-                OC_LOG_V(ERROR, TAG, "processEntryFFD.");
+                OIC_LOG(ERROR, TAG, "processEntryFFD.");
             }
             break;
         case TW_ZED:
-            ret = processEntryEndDevice(entry);
+            ret = processEntryEndDevice(entry, ctx);
             if (ret != TW_RESULT_OK)
             {
-                OC_LOG_V(ERROR, TAG, "processEntryZED.");
+                OIC_LOG(ERROR, TAG, "processEntryZED.");
             }
             break;
         case TW_MATCHDESC:
-            ret = processEntryMatchDesc(entry);
+            ret = processEntryMatchDesc(entry, ctx);
             if (ret != TW_RESULT_OK)
             {
-                OC_LOG_V(ERROR, TAG, "processEntryMatchDesc.");
+                OIC_LOG(ERROR, TAG, "processEntryMatchDesc.");
             }
             break;
         case TW_SIMPLEDESC:
-            ret = processEntrySimpleDesc(entry);
+            ret = processEntrySimpleDesc(entry, ctx);
             if (ret != TW_RESULT_OK)
             {
-                OC_LOG_V(ERROR, TAG, "processEntrySimpleDesc.");
+                OIC_LOG(ERROR, TAG, "processEntrySimpleDesc.");
             }
             break;
         case TW_WRITEATTR:
-            ret = processEntryWriteAttr(entry);
-            if (ret != TW_RESULT_OK)
+            ret = processEntryWriteAttr(entry, ctx);
+            if (ret == TW_RESULT_ERROR_INVALID_OP)
+            {
+               OIC_LOG_V(INFO, TAG, "processEntryWriteAttr - ret=%d", TW_RESULT_ERROR_INVALID_OP);
+            }
+            else if (ret != TW_RESULT_OK)
             {
-                OC_LOG_V(ERROR, TAG, "processEntryWriteAttr.");
+                OIC_LOG(ERROR, TAG, "processEntryWriteAttr.");
             }
             break;
         case TW_RESPATTR:
-            ret = processEntryReadAttr(entry);
+            ret = processEntryReadAttr(entry, ctx);
             if (ret != TW_RESULT_REMOTE_ATTR_HAS_VALUE)
             {
-                OC_LOG_V(ERROR, TAG, "processEntryReadAttr.");
+                OIC_LOG(ERROR, TAG, "processEntryReadAttr.");
             }
             break;
         case TW_TEMPERATURE:
-            ret = processEntryTemperature(entry);
+            ret = processEntryTemperature(entry, ctx);
             if (ret != TW_RESULT_REMOTE_ATTR_HAS_VALUE)
             {
-                OC_LOG_V(ERROR, TAG, "processEntryTemperature.");
+                OIC_LOG(ERROR, TAG, "processEntryTemperature.");
             }
             break;
         case TW_DRLOCRSP:
-            ret = processEntrySwitchDoorLockState(entry);
+            ret = processEntrySwitchDoorLockState(entry, ctx);
             if (ret != TW_RESULT_OK)
             {
-                OC_LOG_V(ERROR, TAG, "processEntrySwitchDoorLockState.");
+                OIC_LOG(ERROR, TAG, "processEntrySwitchDoorLockState.");
             }
             break;
         case TW_DRUNLOCKRSP:
-            ret = processEntrySwitchDoorLockState(entry);
+            ret = processEntrySwitchDoorLockState(entry, ctx);
             if (ret != TW_RESULT_OK)
             {
-                OC_LOG_V(ERROR, TAG, "processEntrySwitchDoorLockState.");
+                OIC_LOG(ERROR, TAG, "processEntrySwitchDoorLockState.");
             }
             break;
         case TW_DFTREP:
-            ret = processEntryZCLDefaultResponse(entry);
+            ret = processEntryZCLDefaultResponse(entry, ctx);
             if (ret != TW_RESULT_OK)
             {
-                OC_LOG_V(ERROR, TAG, "processEntryZCLDefaultResponse.");
+                OIC_LOG(ERROR, TAG, "processEntryZCLDefaultResponse.");
             }
             break;
         case TW_ZENROLLREQ:
-            ret = processEntryZoneEnrollRequest(entry);
+            ret = processEntryZoneEnrollRequest(entry, ctx);
             if (ret != TW_RESULT_OK)
             {
-                OC_LOG_V(ERROR, TAG, "processEntryZoneEnrollRequest.");
+                OIC_LOG(ERROR, TAG, "processEntryZoneEnrollRequest.");
             }
             break;
         case TW_ENROLLED:
-            ret = processEntryEnrolled(entry);
+            ret = processEntryEnrolled(entry, ctx);
             if (ret != TW_RESULT_OK)
             {
-                OC_LOG_V(ERROR, TAG, "processEntryEnrolled.");
+                OIC_LOG(ERROR, TAG, "processEntryEnrolled.");
             }
             break;
         case TW_ZONESTATUS:
-            ret = processEntryZoneStatus(entry);
+            ret = processEntryZoneStatus(entry, ctx);
             if (ret != TW_RESULT_OK)
             {
-                OC_LOG_V(ERROR, TAG, "processEntryZoneStatus.");
+                OIC_LOG(ERROR, TAG, "processEntryZoneStatus.");
             }
             break;
         case TW_ADDRESS_RESPONSE:
-            ret = processEntryAddressResponse(entry);
+            ret = processEntryAddressResponse(entry, ctx);
             if (ret != TW_RESULT_OK)
             {
-                OC_LOG_V(ERROR, TAG, "processEntryAddressResponse.");
+                OIC_LOG(ERROR, TAG, "processEntryAddressResponse.");
             }
             break;
         default:
-            OC_LOG_V(ERROR, TAG, "processEntry() doesn't receive an valid entry.");
+            OIC_LOG(ERROR, TAG, "processEntry() doesn't receive an valid entry.");
             ret = TW_RESULT_ERROR;
             break;
     }
 
-    OC_LOG_V(INFO, TAG, "Leave processEntry() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave processEntry() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode processEntryNETWORK_INFO(TWEntry* entry)
+TWResultCode processEntryNETWORK_INFO(TWEntry* entry, TWContext* ctx)
 {
     /*
     //at+n
@@ -1054,25 +1311,25 @@ TWResultCode processEntryNETWORK_INFO(TWEntry* entry)
     //      OK
     */
 
-    OC_LOG_V(INFO, TAG, "Enter processEntryNETWORK_INFO()");
+    OIC_LOG(INFO, TAG, "Enter processEntryNETWORK_INFO()");
 
     TWResultCode ret = TW_RESULT_UNKNOWN;
 
     if (strcmp(entry->atErrorCode, AT_STR_ERROR_EVERYTHING_OK) != 0)
     {
-        OC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR: %s", entry->atErrorCode);
+        OIC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR: %s", entry->atErrorCode);
         ret = TW_RESULT_ERROR;
         goto exit;
     }
 
-    ret = HandleATResponse(entry);
+    ret = HandleATResponse(entry,ctx);
 
 exit:
-    OC_LOG_V(INFO, TAG, "Leave processEntryNETWORK_INFO() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave processEntryNETWORK_INFO() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode processEntryJPAN(TWEntry* entry)
+TWResultCode processEntryJPAN(TWEntry* entry, TWContext* ctx)
 {
     /*
     //at+en
@@ -1083,15 +1340,15 @@ TWResultCode processEntryJPAN(TWEntry* entry)
     //      ERROR:28
     */
 
-    OC_LOG_V(INFO, TAG, "Enter processEntryJPAN()");
+    OIC_LOG(INFO, TAG, "Enter processEntryJPAN()");
 
     TWResultCode ret = TW_RESULT_UNKNOWN;
     if (strcmp(entry->atErrorCode, AT_STR_ERROR_EVERYTHING_OK) == 0)
     {
-        ret = HandleATResponse(entry);
+        ret = HandleATResponse(entry,ctx);
         if (ret == TW_RESULT_NEW_LOCAL_PAN_ESTABLISHED)
         {
-            OC_LOG_V(INFO, TAG, "New Local PAN established.");
+            OIC_LOG(INFO, TAG, "New Local PAN established.");
             ret =  TW_RESULT_OK;
         }
         else
@@ -1101,84 +1358,85 @@ TWResultCode processEntryJPAN(TWEntry* entry)
     }
     else if (strcmp(entry->atErrorCode, AT_STR_ERROR_NODE_IS_PART_OF_PAN) == 0)
     {
-        OC_LOG_V(INFO, TAG, "Already Established PAN.");
+        OIC_LOG(INFO, TAG, "Already Established PAN.");
         ret = TW_RESULT_OK;
     }
     else
     {
-        OC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR: %s", entry->atErrorCode);
+        OIC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR: %s", entry->atErrorCode);
         ret = TW_RESULT_ERROR;
     }
 
-    OC_LOG_V(INFO, TAG, "Leave processEntryJPAN() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave processEntryJPAN() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode processEntryEndDevice(TWEntry* entry)
+TWResultCode processEntryEndDevice(TWEntry* entry, TWContext* ctx)
 {
-    OC_LOG_V(INFO, TAG, "Enter processEntryEndDevice()");
+    OIC_LOG(INFO, TAG, "Enter processEntryEndDevice()");
 
     TWResultCode ret = TW_RESULT_UNKNOWN;
-    ret = HandleATResponse(entry);
+    ret = HandleATResponse(entry,ctx);
     if (ret != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "HandleATResponse");
+        OIC_LOG(ERROR, TAG, "HandleATResponse");
     }
 
-    OC_LOG_V(INFO, TAG, "Leave processEntryEndDevice() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave processEntryEndDevice() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode processEntryMatchDesc(TWEntry* entry)
+TWResultCode processEntryMatchDesc(TWEntry* entry, TWContext* ctx)
 {
     //MatchDesc:0B4A,00,01
 
-    OC_LOG_V(INFO, TAG, "Enter processEntryMatchDesc()");
+    OIC_LOG(INFO, TAG, "Enter processEntryMatchDesc()");
     TWResultCode ret = TW_RESULT_UNKNOWN;
 
     if (strcmp(entry->atErrorCode, AT_STR_ERROR_EVERYTHING_OK) != 0)
     {
-        OC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR = %s", entry->atErrorCode);
+        OIC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR = %s", entry->atErrorCode);
         ret = TW_RESULT_ERROR;
     }
     else
     {
-        ret = HandleATResponse(entry);
+        ret = HandleATResponse(entry,ctx);
         if (ret == TW_RESULT_OK)
         {
-            OC_LOG_V(INFO, TAG, "HandleATResponse");
-            ret = FindClusters(g_WIPDevice->nodeId,
-                               g_WIPDevice->endpointOfInterest->endpointId);
+            OIC_LOG(INFO, TAG, "HandleATResponse");
+            ret = FindClusters(ctx->g_WIPDevice->nodeId,
+                               ctx->g_WIPDevice->endpointOfInterest->endpointId,
+                               ctx);
             if (ret == TW_RESULT_OK)
             {
-                OC_LOG_V(INFO, TAG, "FindClusters - Found a match node");
-                if (g_DeviceFoundCallback != NULL)
+                OIC_LOG(INFO, TAG, "FindClusters - Found a match node");
+                if (ctx->g_DeviceFoundCallback != NULL)
                 {
-                    OC_LOG_V(INFO, TAG, "Found a match node -- invoke callback");
-                    g_DeviceFoundCallback(g_WIPDevice);
+                    OIC_LOG(INFO, TAG, "Found a match node -- invoke callback");
+                    ctx->g_DeviceFoundCallback(ctx->g_WIPDevice, ctx->g_plugin);
                 }
                 ret =  TW_RESULT_OK;
             }
             else
             {
-                OC_LOG_V(ERROR, TAG, "FindClusters");
+                OIC_LOG(ERROR, TAG, "FindClusters");
                 ret = TW_RESULT_ERROR;
             }
         }
         else
         {
-            OC_LOG_V(ERROR, TAG, "HandleATResponse");
+            OIC_LOG(ERROR, TAG, "HandleATResponse");
             ret = TW_RESULT_ERROR;
         }
 
-        g_WIPDevice = NULL; //reset and do not deallocate it
+        ctx->g_WIPDevice = NULL; //reset and do not deallocate it
     }
 
-    OC_LOG_V(INFO, TAG, "Leave processEntryMatchDesc() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave processEntryMatchDesc() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode processEntrySimpleDesc(TWEntry* entry)
+TWResultCode processEntrySimpleDesc(TWEntry* entry, TWContext* ctx)
 {
     /*
     //AT+SIMPLEDESC:3746,3746,01
@@ -1194,124 +1452,124 @@ TWResultCode processEntrySimpleDesc(TWEntry* entry)
     //
     //      ACK:97
     */
-    OC_LOG_V(INFO, TAG, "Enter processEntrySimpleDesc()");
+    OIC_LOG(INFO, TAG, "Enter processEntrySimpleDesc()");
 
     TWResultCode ret = TW_RESULT_UNKNOWN;
 
     if (strcmp((entry->atErrorCode), AT_STR_ERROR_EVERYTHING_OK) != 0)
     {
-        OC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR = %s", (entry->atErrorCode));
+        OIC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR = %s", (entry->atErrorCode));
         ret = TW_RESULT_ERROR;
     }
     else
     {
         if (entry->count == 6)   //must be 6 as it is the number of lines to expect
         {
-            ret = HandleATResponse(entry);
+            ret = HandleATResponse(entry,ctx);
             if (ret == TW_RESULT_HAS_CLUSTERS)
             {
-                OC_LOG_V(INFO, TAG, "has clusters.");
+                OIC_LOG(INFO, TAG, "has clusters.");
                 ret = TW_RESULT_OK;
             }
         }
         else
         {
-            OC_LOG_V(INFO, TAG, "Received an invalid Simple Descriptor.");
+            OIC_LOG(INFO, TAG, "Received an invalid Simple Descriptor.");
             ret = TW_RESULT_ERROR;
         }
     }
 
-    OC_LOG_V(INFO, TAG, "Leave processEntrySimpleDesc() returns with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave processEntrySimpleDesc() returns with ret=%d", ret);
     return ret;
 }
 
-TWResultCode processEntryWriteAttr(TWEntry* entry)
+TWResultCode processEntryWriteAttr(TWEntry* entry, TWContext* ctx)
 {
     //AT+WRITEATR:3A3D,01,0,0003,0000,21,00
     //      OK
     //      WRITEATTR:3A3D,01,0003,,00
 
-    OC_LOG_V(INFO, TAG, "Enter processEntryWriteAttr()");
+    OIC_LOG(INFO, TAG, "Enter processEntryWriteAttr()");
 
     TWResultCode ret = TW_RESULT_UNKNOWN;
 
     if (strcmp((entry->atErrorCode), AT_STR_ERROR_EVERYTHING_OK) != 0)
     {
-        OC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR = %s", entry->atErrorCode);
+        OIC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR = %s", entry->atErrorCode);
         ret = TW_RESULT_ERROR;
     }
     else
     {
-        ret = HandleATResponse(entry);
+        ret = HandleATResponse(entry,ctx);
     }
 
-    OC_LOG_V(INFO, TAG, "Leave processEntryWriteAttr() returns with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave processEntryWriteAttr() returns with ret=%d", ret);
     return ret;
 }
 
-TWResultCode processEntryReadAttr(TWEntry* entry)
+TWResultCode processEntryReadAttr(TWEntry* entry, TWContext* ctx)
 {
-    OC_LOG_V(INFO, TAG, "Enter processEntryWriteAttr()");
+    OIC_LOG(INFO, TAG, "Enter processEntryReadAttr()");
 
     TWResultCode ret = TW_RESULT_UNKNOWN;
 
     if (strcmp((entry->atErrorCode), AT_STR_ERROR_EVERYTHING_OK) != 0)
     {
-        OC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR = %s", entry->atErrorCode);
+        OIC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR = %s", entry->atErrorCode);
         ret = TW_RESULT_ERROR;
     }
     else
     {
-        ret = HandleATResponse(entry);
+        ret = HandleATResponse(entry,ctx);
     }
 
-    OC_LOG_V(INFO, TAG, "Leave processEntryWriteAttr() returns with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave processEntryReadAttr() returns with ret=%d", ret);
     return ret;
 }
 
-TWResultCode processEntryTemperature(TWEntry* entry)
+TWResultCode processEntryTemperature(TWEntry* entry, TWContext* ctx)
 {
-    OC_LOG_V(INFO, TAG, "Enter processEntryTemperature()");
+    OIC_LOG(INFO, TAG, "Enter processEntryTemperature()");
 
     TWResultCode ret = TW_RESULT_UNKNOWN;
 
     if (strcmp((entry->atErrorCode), AT_STR_ERROR_EVERYTHING_OK) != 0)
     {
-        OC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR = %s", entry->atErrorCode);
+        OIC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR = %s", entry->atErrorCode);
         ret = TW_RESULT_ERROR;
     }
     else
     {
-        ret = HandleATResponse(entry);
+        ret = HandleATResponse(entry,ctx);
     }
 
-    OC_LOG_V(INFO, TAG, "Leave processEntryTemperature() returns with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave processEntryTemperature() returns with ret=%d", ret);
     return ret;
 }
 
-TWResultCode processEntrySwitchDoorLockState(TWEntry* entry)
+TWResultCode processEntrySwitchDoorLockState(TWEntry* entry, TWContext* ctx)
 {
-    OC_LOG_V(INFO, TAG, "Enter processEntrySwitchDoorLockState()");
+    OIC_LOG(INFO, TAG, "Enter processEntrySwitchDoorLockState()");
 
     TWResultCode ret = TW_RESULT_UNKNOWN;
 
     if (strcmp((entry->atErrorCode), AT_STR_ERROR_EVERYTHING_OK) != 0)
     {
-        OC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR = %s", entry->atErrorCode);
+        OIC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR = %s", entry->atErrorCode);
         ret = TW_RESULT_ERROR;
     }
     else
     {
-        ret = HandleATResponse(entry);
+        ret = HandleATResponse(entry,ctx);
     }
 
-    OC_LOG_V(INFO, TAG, "Leave processEntrySwitchDoorLockState() returns with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave processEntrySwitchDoorLockState() returns with ret=%d", ret);
     return ret;
 }
 
-TWResultCode processEntryZCLDefaultResponse(TWEntry* entry)
+TWResultCode processEntryZCLDefaultResponse(TWEntry* entry, TWContext* ctx)
 {
-    OC_LOG_V(INFO, TAG, "Enter processEntryZCLDefaultResponse()");
+    OIC_LOG(INFO, TAG, "Enter processEntryZCLDefaultResponse()");
 
     TWResultCode ret = TW_RESULT_UNKNOWN;
 
@@ -1319,119 +1577,119 @@ TWResultCode processEntryZCLDefaultResponse(TWEntry* entry)
     {
         if (strcmp(entry->atErrorCode, AT_STR_ERROR_MESSAGE_NOT_SENT_TO_TARGET_SUCCESSFULLY) == 0)
         {
-            OC_LOG_V(ERROR, TAG, "Send to the target not succeed.");
+            OIC_LOG(ERROR, TAG, "Send to the target not succeed.");
             ret = TW_RESULT_ERROR;
         }
         else
         {
-            OC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR = %s", entry->atErrorCode);
+            OIC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR = %s", entry->atErrorCode);
             ret = TW_RESULT_ERROR;
         }
     }
     else
     {
-        ret = HandleATResponse(entry);
+        ret = HandleATResponse(entry,ctx);
     }
 
-    OC_LOG_V(INFO, TAG, "Leave processEntryZCLDefaultResponse() returns with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave processEntryZCLDefaultResponse() returns with ret=%d", ret);
     return ret;
 }
 
-TWResultCode processEntryZoneEnrollRequest(TWEntry* entry)
+TWResultCode processEntryZoneEnrollRequest(TWEntry* entry, TWContext* ctx)
 {
-    OC_LOG_V(INFO, TAG, "Enter processEntryZoneEnrollRequest()");
+    OIC_LOG(INFO, TAG, "Enter processEntryZoneEnrollRequest()");
 
     TWResultCode ret = TW_RESULT_UNKNOWN;
     if (strcmp(entry->atErrorCode, AT_STR_ERROR_EVERYTHING_OK) != 0)
     {
-        OC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR: %s", entry->atErrorCode);
+        OIC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR: %s", entry->atErrorCode);
         ret = TW_RESULT_ERROR;
     }
     else
     {
-        ret = HandleATResponse(entry);
+        ret = HandleATResponse(entry,ctx);
     }
 
-    OC_LOG_V(INFO, TAG, "Leave processEntryZoneEnrollRequest() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave processEntryZoneEnrollRequest() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode processEntryEnrolled(TWEntry* entry)
+TWResultCode processEntryEnrolled(TWEntry* entry, TWContext* ctx)
 {
-    OC_LOG_V(INFO, TAG, "Enter processEntryEnrolled()");
+    OIC_LOG(INFO, TAG, "Enter processEntryEnrolled()");
 
     TWResultCode ret = TW_RESULT_UNKNOWN;
     if (strcmp(entry->atErrorCode, AT_STR_ERROR_EVERYTHING_OK) != 0)
     {
-        OC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR: %s", entry->atErrorCode);
+        OIC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR: %s", entry->atErrorCode);
         ret = TW_RESULT_ERROR;
     }
     else
     {
-        ret = HandleATResponse(entry);
+        ret = HandleATResponse(entry,ctx);
     }
 
-    OC_LOG_V(INFO, TAG, "Leave processEntryEnrolled() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave processEntryEnrolled() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode processEntryZoneStatus(TWEntry* entry)
+TWResultCode processEntryZoneStatus(TWEntry* entry, TWContext* ctx)
 {
-    OC_LOG_V(INFO, TAG, "Enter processEntryZoneStatus()");
+    OIC_LOG(INFO, TAG, "Enter processEntryZoneStatus()");
 
     TWResultCode ret = TW_RESULT_UNKNOWN;
     if (strcmp(entry->atErrorCode, AT_STR_ERROR_EVERYTHING_OK) != 0)
     {
-        OC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR: %s", entry->atErrorCode);
+        OIC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR: %s", entry->atErrorCode);
         ret = TW_RESULT_ERROR;
     }
     else
     {
-        ret = HandleATResponse(entry);
+        ret = HandleATResponse(entry,ctx);
     }
 
-    OC_LOG_V(INFO, TAG, "Leave processEntryZoneStatus() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave processEntryZoneStatus() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode processEntryAddressResponse(TWEntry* entry)
+TWResultCode processEntryAddressResponse(TWEntry* entry, TWContext* ctx)
 {
-    OC_LOG_V(INFO, TAG, "Enter processEntryAddressResponse()");
+    OIC_LOG(INFO, TAG, "Enter processEntryAddressResponse()");
 
     TWResultCode ret = TW_RESULT_UNKNOWN;
     if (strcmp(entry->atErrorCode, AT_STR_ERROR_EVERYTHING_OK) != 0)
     {
-        OC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR: %s", entry->atErrorCode);
+        OIC_LOG_V(ERROR, TAG, "TWEntry contains AT_ERROR: %s", entry->atErrorCode);
         ret = TW_RESULT_ERROR;
     }
     else
     {
-        ret = HandleATResponse(entry);
+        ret = HandleATResponse(entry,ctx);
     }
 
-    OC_LOG_V(INFO, TAG, "Leave processEntryAddressResponse() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave processEntryAddressResponse() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode Reset()
+TWResultCode Reset(TWContext* ctx)
 {
-    OC_LOG_V(INFO, TAG, "Enter Reset()");
+    OIC_LOG(INFO, TAG, "Enter Reset()");
 
     TWResultCode ret = TW_RESULT_ERROR;
-    ret = TWIssueATCommand(g_plugin, AT_CMD_RESET);
+    ret = TWIssueATCommand(ctx->g_plugin, AT_CMD_RESET);
     if (ret == TW_RESULT_OK)
     {
-        OC_LOG_V(INFO, TAG, "Write %s", AT_CMD_RESET);
+        OIC_LOG_V(INFO, TAG, "Write %s", AT_CMD_RESET);
     }
     else
     {
-        OC_LOG_V(ERROR, TAG, "Write %s", AT_CMD_RESET);
+        OIC_LOG_V(ERROR, TAG, "Write %s", AT_CMD_RESET);
     }
-    OC_LOG_V(INFO, TAG, "Leave Reset() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave Reset() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode CreatePAN()
+TWResultCode CreatePAN(TWContext* ctx)
 {
     /*
     //at+n
@@ -1450,103 +1708,120 @@ TWResultCode CreatePAN()
     //      ERROR:28
     */
 
-    OC_LOG_V(INFO, TAG, "Enter CreatePAN()");
+    OIC_LOG(INFO, TAG, "Enter CreatePAN()");
 
     TWResultCode twRet1 = TW_RESULT_UNKNOWN;
     TWResultCode twRet2 = TW_RESULT_UNKNOWN;
     TWResultCode ret = TW_RESULT_UNKNOWN;
-    ret = TWIssueATCommand(g_plugin, AT_CMD_GET_NETWORK_INFO);
+    ret = TWIssueATCommand(ctx->g_plugin, AT_CMD_GET_NETWORK_INFO);
     if (ret != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "Write %s", AT_CMD_GET_NETWORK_INFO);
+        OIC_LOG_V(ERROR, TAG, "Write %s", AT_CMD_GET_NETWORK_INFO);
         goto exit;
     }
-    OC_LOG_V(INFO, TAG, "Write %s", AT_CMD_GET_NETWORK_INFO);
+    OIC_LOG_V(INFO, TAG, "Write %s", AT_CMD_GET_NETWORK_INFO);
     TWEntry* entry = NULL;
     TWEntry* entry2 = NULL;
-    ret = TWDequeueEntry(g_plugin, &entry, TW_NETWORK_INFO);
+    ret = TWDequeueEntry(ctx->g_plugin, &entry, TW_NETWORK_INFO);
     if (ret != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "TWDequeueEntry - %s", AT_CMD_GET_NETWORK_INFO);
+        OIC_LOG_V(ERROR, TAG, "TWDequeueEntry - %s", AT_CMD_GET_NETWORK_INFO);
         goto exit;
     }
     if (entry == NULL)
     {
-        OC_LOG_V(ERROR, TAG, "TWEntry is NULL - %s", AT_CMD_GET_NETWORK_INFO);
+        OIC_LOG_V(ERROR, TAG, "TWEntry is NULL - %s", AT_CMD_GET_NETWORK_INFO);
         ret = TW_RESULT_ERROR;
         goto exit;
     }
-    ret = processEntry(entry);
+    ret = processEntry(entry, ctx);
     if (ret == TW_RESULT_HAS_LOCAL_PAN)
     {
-        OC_LOG_V(INFO, TAG, "Has local PAN.");
+        OIC_LOG(INFO, TAG, "Has local PAN.");
         ret = TW_RESULT_OK;
     }
     else if (ret == TW_RESULT_NO_LOCAL_PAN)
     {
-        OC_LOG_V(INFO, TAG, "Has no local PAN.");
-        ret = TWIssueATCommand(g_plugin, AT_CMD_ESTABLISH_NETWORK);
+        OIC_LOG(INFO, TAG, "Has no local PAN.");
+        ret = TWIssueATCommand(ctx->g_plugin, AT_CMD_ESTABLISH_NETWORK);
         if (ret != TW_RESULT_OK)
         {
-            OC_LOG_V(ERROR, TAG, "Write %s", AT_CMD_ESTABLISH_NETWORK);
+            OIC_LOG_V(ERROR, TAG, "Write %s", AT_CMD_ESTABLISH_NETWORK);
             goto exit;
         }
-        OC_LOG_V(INFO, TAG, "Write %s", AT_CMD_ESTABLISH_NETWORK);
+        OIC_LOG_V(INFO, TAG, "Write %s", AT_CMD_ESTABLISH_NETWORK);
 
-        ret = TWDequeueEntry(g_plugin, &entry2, TW_JPAN);
+        ret = TWDequeueEntry(ctx->g_plugin, &entry2, TW_JPAN);
         if (ret != TW_RESULT_OK)
         {
-            OC_LOG_V(ERROR, TAG, "TWDequeueEntry - %s", AT_CMD_ESTABLISH_NETWORK);
+            OIC_LOG_V(ERROR, TAG, "TWDequeueEntry - %s", AT_CMD_ESTABLISH_NETWORK);
             goto exit;
         }
         if (entry2 == NULL)
         {
-            OC_LOG_V(ERROR, TAG, "TWEntry is NULL - %s", AT_CMD_ESTABLISH_NETWORK);
+            OIC_LOG_V(ERROR, TAG, "TWEntry is NULL - %s", AT_CMD_ESTABLISH_NETWORK);
             ret = TW_RESULT_ERROR;
             goto exit;
         }
-        ret = processEntry(entry2);
+        ret = processEntry(entry2, ctx);
         if (ret == TW_RESULT_OK)
         {
-            OC_LOG_V(INFO, TAG, "processEntry - %s", AT_CMD_ESTABLISH_NETWORK);
-            g_ZigBeeStatus.state = ZB_STATE_INIT;
+            OIC_LOG_V(INFO, TAG, "processEntry - %s", AT_CMD_ESTABLISH_NETWORK);
             ret = TW_RESULT_OK;
         }
         else
         {
-            OC_LOG_V(ERROR, TAG, "processEntry - %s", AT_CMD_ESTABLISH_NETWORK);
+            OIC_LOG_V(ERROR, TAG, "processEntry - %s", AT_CMD_ESTABLISH_NETWORK);
             ret = TW_RESULT_ERROR;
         }
     }
     else
     {
-        OC_LOG_V(ERROR, TAG, "processEntry - unexpected return code: %d", ret);
+        OIC_LOG_V(ERROR, TAG, "processEntry - unexpected return code: %d", ret);
         ret = TW_RESULT_ERROR;
     }
 
 exit:
     if (entry)
     {
-        twRet1 = TWDeleteEntry(g_plugin, entry);
+        twRet1 = TWDeleteEntry(ctx->g_plugin, entry);
         if(twRet1 != TW_RESULT_OK)
         {
-            OC_LOG_V(ERROR, TAG, "TWDeleteEntry 1 - ret=%d", twRet1);
+            OIC_LOG_V(ERROR, TAG, "TWDeleteEntry 1 - ret=%d", twRet1);
         }
     }
     if (entry2)
     {
-        twRet2 = TWDeleteEntry(g_plugin, entry2);
+        twRet2 = TWDeleteEntry(ctx->g_plugin, entry2);
         if(twRet2 != TW_RESULT_OK)
         {
-            OC_LOG_V(ERROR, TAG, "TWDeleteEntry 2 - ret=%d", twRet2);
+            OIC_LOG_V(ERROR, TAG, "TWDeleteEntry 2 - ret=%d", twRet2);
         }
     }
 
-    OC_LOG_V(INFO, TAG, "Leave CreatePan with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave CreatePan with ret=%d", ret);
     return ret;
 }
 
-TWResultCode EnableJoin(bool isKeyEncrypted)
+TWContext * GetTWContext(PIPlugin_Zigbee* plugin)
+{
+    if(!plugin)
+    {
+        return NULL;
+    }
+    TWContext * out = NULL;
+    TWContext * tmp = NULL;
+    LL_FOREACH_SAFE(g_twContextList, out, tmp)
+    {
+        if(out->g_plugin == plugin)
+        {
+            return out;
+        }
+    }
+    return NULL;
+}
+
+TWResultCode EnableJoin(bool isKeyEncrypted, TWContext* ctx)
 {
     //Ask:          AT+PJOIN
     //Response:     OK
@@ -1566,30 +1841,30 @@ TWResultCode EnableJoin(bool isKeyEncrypted)
     char* cmdString = (char*)OICMalloc(size * sizeof(char));
     if (cmdString == NULL)
     {
-        OC_LOG_V(ERROR, TAG, "No Memory");
+        OIC_LOG(ERROR, TAG, "No Memory");
         ret = TW_RESULT_ERROR_NO_MEMORY;
         goto exit;
     }
     snprintf(cmdString, size, "%s%s%s%s",
              AT_CMD_PERMIT_JOIN, joinTimeHex, SEPARATOR, broadcast);
-    ret = TWIssueATCommand(g_plugin, cmdString);
+    ret = TWIssueATCommand(ctx->g_plugin, cmdString);
     if (ret != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "Write %s", cmdString);
+        OIC_LOG_V(ERROR, TAG, "Write %s", cmdString);
         ret = TW_RESULT_ERROR;
         goto exit;
     }
-    OC_LOG_V(INFO, TAG, "Write %s", cmdString);
+    OIC_LOG_V(INFO, TAG, "Write %s", cmdString);
 
     sleep(15);  //must sleep here to permit joining for 15 seconds
 
 exit:
     OICFree(cmdString);
-    OC_LOG_V(INFO, TAG, "Leave EnableJoin() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave EnableJoin() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode FindMatchNodes()
+TWResultCode FindMatchNodes(TWContext* ctx)
 {
     //AT+MATCHREQ:0104,03,0003,0006,0402,00
     //      OK
@@ -1598,65 +1873,59 @@ TWResultCode FindMatchNodes()
     //AT+MATCHREQ:0104,03,0999,0999,0999,00
     //      OK
 
-    OC_LOG_V(INFO, TAG, "Enter FindMatchNodes()");
+    OIC_LOG(INFO, TAG, "Enter FindMatchNodes()");
 
     TWResultCode ret = TW_RESULT_UNKNOWN;
 
-    char* profileHomeAutomation = "0104";
-    char* inClusterCount = "04";
-    char* outClusterCount = "00";
+    //TODO: add more clusters if needed
 
-    //TODO: add more clusters
-    char* clusterIdentify = "0003";
-    char* clusterOnOff = "0006";
-    char* clusterTemperatureMeasurement = "0402";
-    char* clusterIASZone = "0500";
-
-    int size = strlen(AT_CMD_MATCH_REQUEST) + strlen(profileHomeAutomation) +
-               SEPARATOR_LENGTH + strlen(inClusterCount) +
-               SEPARATOR_LENGTH + strlen(clusterIdentify) +
-               SEPARATOR_LENGTH + strlen(clusterOnOff) +
-               SEPARATOR_LENGTH + strlen(clusterTemperatureMeasurement) +
-               SEPARATOR_LENGTH + strlen(clusterIASZone) +
-               SEPARATOR_LENGTH + strlen(outClusterCount) + 1;
+    int size = strlen(AT_CMD_MATCH_REQUEST) + strlen(ZB_PROFILE_ID_HOME_AUTOMATION) +
+               SEPARATOR_LENGTH + strlen(IN_CLUSTER_COUNT_STRING) +
+               SEPARATOR_LENGTH + strlen(ZB_CLUSTER_IDENTIFY) +
+               SEPARATOR_LENGTH + strlen(ZB_CLUSTER_ON_OFF) +
+               SEPARATOR_LENGTH + strlen(ZB_CLUSTER_TEMPERATURE_MEASUREMENT) +
+               SEPARATOR_LENGTH + strlen(ZB_CLUSTER_IAS_ZONE) +
+               SEPARATOR_LENGTH + strlen(ZB_CLUSTER_COLOR_CONTROL) +
+               SEPARATOR_LENGTH + strlen(OUT_CLUSTER_COUNT_STRING) + 1;
 
     char* cmdString = (char*)OICMalloc(size * sizeof(char));
     if (cmdString == NULL)
     {
-        OC_LOG_V(INFO, TAG, "No Memory");
+        OIC_LOG(ERROR, TAG, "No Memory");
         ret = TW_RESULT_ERROR_NO_MEMORY;
         goto exit;
     }
 
-    int stringRet = snprintf(cmdString, size, "%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
-                             AT_CMD_MATCH_REQUEST, profileHomeAutomation,
-                             SEPARATOR, inClusterCount,
-                             SEPARATOR, clusterIdentify,
-                             SEPARATOR, clusterOnOff,
-                             SEPARATOR, clusterTemperatureMeasurement,
-                             SEPARATOR, clusterIASZone,
-                             SEPARATOR, outClusterCount);
+    int stringRet = snprintf(cmdString, size, "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
+                             AT_CMD_MATCH_REQUEST, ZB_PROFILE_ID_HOME_AUTOMATION,
+                             SEPARATOR, IN_CLUSTER_COUNT_STRING,
+                             SEPARATOR, ZB_CLUSTER_IDENTIFY,
+                             SEPARATOR, ZB_CLUSTER_ON_OFF,
+                             SEPARATOR, ZB_CLUSTER_TEMPERATURE_MEASUREMENT,
+                             SEPARATOR, ZB_CLUSTER_IAS_ZONE,
+                             SEPARATOR, ZB_CLUSTER_COLOR_CONTROL,
+                             SEPARATOR, OUT_CLUSTER_COUNT_STRING);
     if(stringRet <= 0)
     {
-        OC_LOG_V(ERROR, TAG, "Build command error.");
+        OIC_LOG(ERROR, TAG, "Build command error.");
         ret = OC_STACK_ERROR;
         goto exit;
     }
-    ret = TWIssueATCommand(g_plugin, cmdString);
+    ret = TWIssueATCommand(ctx->g_plugin, cmdString);
     if (ret != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "Write %s.", cmdString);
+        OIC_LOG_V(ERROR, TAG, "Write %s.", cmdString);
         goto exit;
     }
-    OC_LOG_V(INFO, TAG, "Write %s.", cmdString);
+    OIC_LOG_V(INFO, TAG, "Write %s.", cmdString);
 
 exit:
     OICFree(cmdString);
-    OC_LOG_V(INFO, TAG, "Leave FindMatchNodes() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave FindMatchNodes() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode FindClusters(char nodeId[], char endpoint[])
+TWResultCode FindClusters(char nodeId[], char endpoint[], TWContext* ctx)
 {
     /*
     //AT+SIMPLEDESC:3746,3746,01
@@ -1673,7 +1942,7 @@ TWResultCode FindClusters(char nodeId[], char endpoint[])
     //      ACK:97
     */
 
-    OC_LOG_V(INFO, TAG, "Enter FindClusters()");
+    OIC_LOG(INFO, TAG, "Enter FindClusters()");
 
     TWResultCode ret = TW_RESULT_UNKNOWN;
 
@@ -1684,7 +1953,7 @@ TWResultCode FindClusters(char nodeId[], char endpoint[])
     char* cmdString = (char*)OICMalloc(size * sizeof(char));
     if (cmdString == NULL)
     {
-        OC_LOG_V(ERROR, TAG, "No Memory");
+        OIC_LOG(ERROR, TAG, "No Memory");
         ret = TW_RESULT_ERROR_NO_MEMORY;
         goto exit;
     }
@@ -1695,57 +1964,57 @@ TWResultCode FindClusters(char nodeId[], char endpoint[])
                              SEPARATOR, endpoint);
     if(stringRet <= 0)
     {
-        OC_LOG_V(ERROR, TAG, "Build command error.");
+        OIC_LOG(ERROR, TAG, "Build command error.");
         ret = OC_STACK_ERROR;
         goto exit;
     }
-    ret = TWIssueATCommand(g_plugin, cmdString);
+    ret = TWIssueATCommand(ctx->g_plugin, cmdString);
     if (ret != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "Write %s", cmdString);
+        OIC_LOG_V(ERROR, TAG, "Write %s", cmdString);
         ret = TW_RESULT_ERROR;
         goto exit;
     }
-    OC_LOG_V(INFO, TAG, "Write %s", cmdString);
+    OIC_LOG_V(INFO, TAG, "Write %s", cmdString);
 
     TWEntry* entry = NULL;
-    ret = TWDequeueEntry(g_plugin, &entry, TW_SIMPLEDESC);
+    ret = TWDequeueEntry(ctx->g_plugin, &entry, TW_SIMPLEDESC);
     if (ret != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "TWDequeueEntry - %s", cmdString);
+        OIC_LOG_V(ERROR, TAG, "TWDequeueEntry - %s", cmdString);
         goto exit;
     }
     if (entry == NULL)
     {
-        OC_LOG_V(ERROR, TAG, "TWEntry is NULL - %s", cmdString);
+        OIC_LOG_V(ERROR, TAG, "TWEntry is NULL - %s", cmdString);
         ret = TW_RESULT_ERROR;
         goto exit;
     }
 
-    ret = processEntry(entry);
+    ret = processEntry(entry, ctx);
     if (ret == TW_RESULT_OK)
     {
-        OC_LOG_V(INFO, TAG, "processEntry - %s", cmdString);
+        OIC_LOG_V(INFO, TAG, "processEntry - %s", cmdString);
     }
     else
     {
-        OC_LOG_V(ERROR, TAG, "processEntry - %s", cmdString);
+        OIC_LOG_V(ERROR, TAG, "processEntry - %s", cmdString);
     }
 
 exit:
-    TWDeleteEntry(g_plugin, entry);
+    TWDeleteEntry(ctx->g_plugin, entry);
     OICFree(cmdString);
-    OC_LOG_V(INFO, TAG, "Leave FindClusters() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave FindClusters() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode GetRemoteEUI(char *nodeId, char* outRemoteEUI)
+TWResultCode GetRemoteEUI(char *nodeId, char* outRemoteEUI, TWContext* ctx)
 {
     //AT+EUIREQ:< Address>,<NodeID>[,XX]
     //  AddrResp:<errorcode>[,<NodeID>,<EUI64>]
     //  AddrResp:00,15ED,000D6F00040574B8
 
-    OC_LOG_V(INFO, TAG, "Enter GetRemoteEUI()");
+    OIC_LOG(INFO, TAG, "Enter GetRemoteEUI()");
     TWResultCode ret = TW_RESULT_UNKNOWN;
 
     int size = strlen(AT_CMD_REMOTE_EUI_REQUEST) + strlen(nodeId) +
@@ -1753,7 +2022,7 @@ TWResultCode GetRemoteEUI(char *nodeId, char* outRemoteEUI)
     char* cmdString = (char*)OICMalloc(size * sizeof(char));
     if (cmdString == NULL)
     {
-        OC_LOG_V(ERROR, TAG, "No Memory");
+        OIC_LOG(ERROR, TAG, "No Memory");
         ret = TW_RESULT_ERROR_NO_MEMORY;
         goto exit;
     }
@@ -1763,68 +2032,68 @@ TWResultCode GetRemoteEUI(char *nodeId, char* outRemoteEUI)
                          SEPARATOR, nodeId);
     if(stringRet <= 0)
     {
-        OC_LOG_V(ERROR, TAG, "Build command error.");
+        OIC_LOG(ERROR, TAG, "Build command error.");
         ret = OC_STACK_ERROR;
         goto exit;
     }
-    ret = TWIssueATCommand(g_plugin, cmdString);
+    ret = TWIssueATCommand(ctx->g_plugin, cmdString);
     if (ret != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "Write %s", cmdString);
+        OIC_LOG_V(ERROR, TAG, "Write %s", cmdString);
         ret = TW_RESULT_ERROR;
         goto exit;
     }
-    OC_LOG_V(INFO, TAG, "Write %s", cmdString);
+    OIC_LOG_V(INFO, TAG, "Write %s", cmdString);
 
     TWEntry* entry = NULL;
-    ret = TWDequeueEntry(g_plugin, &entry, TW_ADDRESS_RESPONSE);
+    ret = TWDequeueEntry(ctx->g_plugin, &entry, TW_ADDRESS_RESPONSE);
     if (ret != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "TWDequeueEntry - %s", cmdString);
+        OIC_LOG_V(ERROR, TAG, "TWDequeueEntry - %s", cmdString);
         ret = TW_RESULT_ERROR;
         goto exit;
     }
     if (entry == NULL)
     {
-        OC_LOG_V(ERROR, TAG, "TWEntry is NULL - %s", cmdString);
+        OIC_LOG_V(ERROR, TAG, "TWEntry is NULL - %s", cmdString);
         ret = TW_RESULT_ERROR;
         goto exit;
     }
 
-    ret = processEntry(entry);
+    ret = processEntry(entry, ctx);
     if (ret != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "processEntry - %s", cmdString);
+        OIC_LOG_V(ERROR, TAG, "processEntry - %s", cmdString);
         ret = TW_RESULT_ERROR;
         goto exit;
     }
-    OC_LOG_V(INFO, TAG, "Wanted   eui of NodeID=%s ", nodeId);
-    OC_LOG_V(INFO, TAG, "Received eui of g_WIPRemoteNodeId=%s ", g_WIPRemoteNodeId);
-    if (strcmp(nodeId, g_WIPRemoteNodeId) != 0)
+    OIC_LOG_V(INFO, TAG, "Wanted   eui of NodeID=%s ", nodeId);
+    OIC_LOG_V(INFO, TAG, "Received eui of g_WIPRemoteNodeId=%s ", ctx->g_WIPRemoteNodeId);
+    if (strcmp(nodeId, ctx->g_WIPRemoteNodeId) != 0)
     {
-        OC_LOG_V(ERROR, TAG, "Received eui for an unexpected remote node id.");
+        OIC_LOG(ERROR, TAG, "Received eui for an unexpected remote node id.");
         ret = TW_RESULT_ERROR;
         goto exit;
     }
 
-    OC_LOG_V(INFO, TAG, "Remote NodeId:%s has EUI: %s \n",
-                        g_WIPRemoteNodeId, g_WIPRemoteEUI);
-    OICStrcpy(outRemoteEUI, SIZE_EUI, g_WIPRemoteEUI);
+    OIC_LOG_V(INFO, TAG, "Remote NodeId:%s has EUI: %s \n",
+                        ctx->g_WIPRemoteNodeId, ctx->g_WIPRemoteEUI);
+    OICStrcpy(outRemoteEUI, sizeof(ctx->g_WIPRemoteEUI), ctx->g_WIPRemoteEUI);
 
     ret = TW_RESULT_OK;
 
 exit:
-    memset(g_WIPRemoteEUI, '\0', SIZE_EUI);
-    memset(g_WIPRemoteNodeId, '\0', SIZE_NODEID);
-    TWDeleteEntry(g_plugin, entry);
+    memset(ctx->g_WIPRemoteEUI, '\0', sizeof(ctx->g_WIPRemoteEUI));
+    memset(ctx->g_WIPRemoteNodeId, '\0', sizeof(ctx->g_WIPRemoteNodeId));
+    TWDeleteEntry(ctx->g_plugin, entry);
     OICFree(cmdString);
-    OC_LOG_V(INFO, TAG, "Leave GetRemoteEUI() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave GetRemoteEUI() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode HandleATResponse(TWEntry* entry)
+TWResultCode HandleATResponse(TWEntry* entry, TWContext* ctx)
 {
-    OC_LOG_V(INFO, TAG, "Enter HandleATResponse()");
+    OIC_LOG(INFO, TAG, "Enter HandleATResponse()");
 
     TWResultCode ret = TW_RESULT_ERROR;
 
@@ -1847,7 +2116,7 @@ TWResultCode HandleATResponse(TWEntry* entry)
                                            delimiters, tokens);
                 if (paramCount > 0)
                 {
-                    ret = g_TWATResultHandlerPairArray[k].handler(paramCount, tokens);
+                    ret = g_TWATResultHandlerPairArray[k].handler(paramCount, tokens, ctx);
                 }
 
                 int n = 0;
@@ -1861,7 +2130,7 @@ TWResultCode HandleATResponse(TWEntry* entry)
         }
     }
 
-    OC_LOG_V(INFO, TAG, "Leave HandleATResponse() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave HandleATResponse() with ret=%d", ret);
     return ret;
 }
 
@@ -1869,13 +2138,13 @@ TWResultCode HandleATResponse(TWEntry* entry)
 // Internal functions - AT Response/Prompt Handlers
 //-----------------------------------------------------------------------------
 
-TWResultCode TelAddressResponseHandler(int count, char* tokens[])
+TWResultCode TelAddressResponseHandler(int count, char* tokens[], TWContext* ctx)
 {
     //AT+EUIREQ:< Address>,<NodeID>[,XX]
     //  AddrResp:<errorcode>[,<NodeID>,<EUI64>]
     //  AddrResp:00,15ED,000D6F00040574B8
 
-    OC_LOG_V(INFO, TAG, "Enter TelAddressResponseHandler()");
+    OIC_LOG(INFO, TAG, "Enter TelAddressResponseHandler()");
 
     TWResultCode ret = TW_RESULT_UNKNOWN;
 
@@ -1885,27 +2154,27 @@ TWResultCode TelAddressResponseHandler(int count, char* tokens[])
     }
     else
     {
-        if (strcmp(tokens[0], AT_STR_ERROR_OK) != 0)
+        if (strcmp(tokens[TOKEN_ADDRRESP_STATUS_CODE], AT_STR_ERROR_OK) != 0)
         {
-            OC_LOG_V(ERROR, TAG, "AddrResp prompt contained error status.");
+            OIC_LOG(ERROR, TAG, "AddrResp prompt contained error status.");
             ret = TW_RESULT_ERROR;
         }
         else
         {
-            OICStrcpy(g_WIPRemoteNodeId, SIZE_NODEID, tokens[1]);
-            OICStrcpy(g_WIPRemoteEUI, SIZE_EUI, tokens[2]);
-            OC_LOG_V(INFO, TAG, "Received eui %s for g_WIPRemoteNodeId=%s ",
-                     g_WIPRemoteEUI,
-                     g_WIPRemoteNodeId);
+            OICStrcpy(ctx->g_WIPRemoteNodeId, SIZE_NODEID, tokens[TOKEN_ADDRRESP_NODEID]);
+            OICStrcpy(ctx->g_WIPRemoteEUI, SIZE_EUI, tokens[TOKEN_ADDRRESP_EUI]);
+            OIC_LOG_V(INFO, TAG, "Received eui %s for g_WIPRemoteNodeId=%s ",
+                     ctx->g_WIPRemoteEUI,
+                     ctx->g_WIPRemoteNodeId);
             ret = TW_RESULT_OK;
         }
     }
 
-    OC_LOG_V(INFO, TAG, "Leave TelAddressResponseHandler() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave TelAddressResponseHandler() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode TelNetworkInfoHandler(int count, char* tokens[])
+TWResultCode TelNetworkInfoHandler(int count, char* tokens[], TWContext* ctx)
 {
     // Ask:         AT+N
     // Response:    +N=COO,24,-6,9726,12BB200F073AB573
@@ -1914,7 +2183,7 @@ TWResultCode TelNetworkInfoHandler(int count, char* tokens[])
     //
     //              +N=<devicetype>,<channel>,<power>,<PANID>,<EPANID>
 
-    OC_LOG_V(INFO, TAG, "Enter TelNetworkInfoHandler()");
+    OIC_LOG(INFO, TAG, "Enter TelNetworkInfoHandler()");
 
     TWResultCode ret = TW_RESULT_UNKNOWN;
 
@@ -1931,53 +2200,58 @@ TWResultCode TelNetworkInfoHandler(int count, char* tokens[])
     {
         if (tokens[i] != NULL)
         {
-            OC_LOG_V(INFO, TAG, "Token[%d] = %s", i, tokens[i]);
+            OIC_LOG_V(INFO, TAG, "Token[%d] = %s", i, tokens[i]);
         }
     }
 
-    char* temp = tokens[0];
+    char* temp = tokens[TOKEN_PLUS_N_DEVICE_TYPE];
     if (strcmp(temp, "NoPAN") == 0)
     {
-        OC_LOG_V(INFO, TAG, "It is NoPan.");
+        OIC_LOG(INFO, TAG, "It is NoPan.");
         ret = TW_RESULT_NO_LOCAL_PAN;
         goto exit;
     }
 
-    OC_LOG_V(INFO, TAG, "Already have an established network.");
-    ret = AsciiHexToValue(tokens[3], strlen(tokens[3]), &g_ZigBeeStatus.panId);
+    OIC_LOG(INFO, TAG, "Already have an established network.");
+    ret = AsciiHexToValue(tokens[TOKEN_PLUS_N_PANID],
+                          strlen(tokens[TOKEN_PLUS_N_PANID]),
+                          &(ctx->g_ZigBeeStatus.panId));
     if(ret != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "AsciiHexToValue - panId");
+        OIC_LOG(ERROR, TAG, "AsciiHexToValue - panId");
         goto exit;
     }
-    ret = AsciiHexToValue(tokens[4], strlen(tokens[4]), &g_ZigBeeStatus.extPanId);
+
+    ret = AsciiHexToValue(tokens[TOKEN_PLUS_N_PANID_EXTENDED],
+                          strlen(tokens[TOKEN_PLUS_N_PANID_EXTENDED]),
+                          &(ctx->g_ZigBeeStatus.extPanId));
     if(ret != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "AsciiHexToValue - extPanId");
+        OIC_LOG(ERROR, TAG, "AsciiHexToValue - extPanId");
         goto exit;
     }
-    OC_LOG_V(INFO, TAG, "PanId=%" PRId64 , g_ZigBeeStatus.panId);
-    OC_LOG_V(INFO, TAG, "ExtPanId=%" PRId64 , g_ZigBeeStatus.extPanId);
-    OC_LOG_V(INFO, TAG, "PanId=%s", tokens[3]);
-    OC_LOG_V(INFO, TAG, "ExtPanId=%s", tokens[4]);
+    OIC_LOG_V(INFO, TAG, "PanId=%" PRId64 , ctx->g_ZigBeeStatus.panId);
+    OIC_LOG_V(INFO, TAG, "ExtPanId=%" PRId64 , ctx->g_ZigBeeStatus.extPanId);
+    OIC_LOG_V(INFO, TAG, "PanId=%s", tokens[TOKEN_PLUS_N_PANID]);
+    OIC_LOG_V(INFO, TAG, "ExtPanId=%s", tokens[TOKEN_PLUS_N_PANID_EXTENDED]);
 
-    OC_LOG_V(INFO, TAG, "TelNetworkInfoHandler set ExtPanId to %08X%08X",
-             (unsigned int)(g_ZigBeeStatus.extPanId >> 32),
-             (unsigned int)(g_ZigBeeStatus.extPanId & 0xFFFFFFFF));
+    OIC_LOG_V(INFO, TAG, "TelNetworkInfoHandler set ExtPanId to %08X%08X",
+             (unsigned int)(ctx->g_ZigBeeStatus.extPanId >> 32),
+             (unsigned int)(ctx->g_ZigBeeStatus.extPanId & 0xFFFFFFFF));
 
     ret = TW_RESULT_HAS_LOCAL_PAN;
 
 exit:
-    OC_LOG_V(INFO, TAG, "Leave TelNetworkInfoHandler() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave TelNetworkInfoHandler() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode TelJpanHandler(int count, char* tokens[])
+TWResultCode TelJpanHandler(int count, char* tokens[], TWContext* ctx)
 {
     //Ask:        AT+EN:[<channel>],[<POWER>],[<PANID>]
     //Response:   JPAN:<channel>,<PANID>,<EPANID>
 
-    OC_LOG_V(INFO, TAG, "Enter TelJpanHandler()");
+    OIC_LOG(INFO, TAG, "Enter TelJpanHandler()");
 
     TWResultCode ret = TW_RESULT_UNKNOWN;
 
@@ -1987,28 +2261,34 @@ TWResultCode TelJpanHandler(int count, char* tokens[])
         goto exit;
     }
 
-    ret = AsciiHexToValue(tokens[1], strlen(tokens[1]), &g_ZigBeeStatus.panId);
+    ret = AsciiHexToValue(tokens[TOKEN_JPAN_PANID],
+                          strlen(tokens[TOKEN_JPAN_PANID]),
+                          &(ctx->g_ZigBeeStatus.panId));
+
     if(ret != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "AsciiHexToValue - panId");
+        OIC_LOG(ERROR, TAG, "AsciiHexToValue - panId");
         goto exit;
     }
-    ret = AsciiHexToValue(tokens[2], strlen(tokens[2]), &g_ZigBeeStatus.extPanId);
+
+    ret = AsciiHexToValue(tokens[TOKEN_JPAN_PANID_EXTENDED],
+                          strlen(tokens[TOKEN_JPAN_PANID_EXTENDED]),
+                          &(ctx->g_ZigBeeStatus.extPanId));
     if(ret != TW_RESULT_OK)
     {
-        OC_LOG_V(ERROR, TAG, "AsciiHexToValue - extPanId");
+        OIC_LOG(ERROR, TAG, "AsciiHexToValue - extPanId");
         goto exit;
     }
-    OC_LOG_V(INFO, TAG, "PanId = %" PRId64 "\n", g_ZigBeeStatus.panId);
-    OC_LOG_V(INFO, TAG, "ExtPanId = %" PRId64 "\n", g_ZigBeeStatus.extPanId);
+    OIC_LOG_V(INFO, TAG, "PanId = %" PRId64 "\n", ctx->g_ZigBeeStatus.panId);
+    OIC_LOG_V(INFO, TAG, "ExtPanId = %" PRId64 "\n", ctx->g_ZigBeeStatus.extPanId);
     ret = TW_RESULT_NEW_LOCAL_PAN_ESTABLISHED;
 
 exit:
-    OC_LOG_V(INFO, TAG, "Leave TelJpanHandler() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave TelJpanHandler() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode TelEndDeviceJoinHandler(int count, char* tokens[])
+TWResultCode TelEndDeviceJoinHandler(int count, char* tokens[], TWContext* ctx)
 {
     //Ask:      AT+PJOIN
     //
@@ -2017,7 +2297,7 @@ TWResultCode TelEndDeviceJoinHandler(int count, char* tokens[])
     //Prompt:   SED:<IEEE Address>,<NodeID>
     //Prompt:   ZED:<IEEE Address>,<NodeID>
 
-    OC_LOG_V(INFO, TAG, "Enter TelEndDeviceJoinHandler()");
+    OIC_LOG(INFO, TAG, "Enter TelEndDeviceJoinHandler()");
     TWResultCode ret = TW_RESULT_UNKNOWN;
 
     if(!tokens || count != RESPONSE_PARAMS_COUNT_DEVICE_JOINED)
@@ -2027,19 +2307,29 @@ TWResultCode TelEndDeviceJoinHandler(int count, char* tokens[])
     }
 
     //TODO: Might need to add into the list if needed - log it for now.
-    OC_LOG_V(INFO, TAG, "Just Joined - EUI:%s; NodeID:%s.\n", tokens[0], tokens[1]);
+    OIC_LOG_V(INFO, TAG, "Received RFD/FFD/SED/ZED - EUI:%s; NodeID:%s.\n",
+            tokens[TOKEN_PJOIN_RESPONSE_IEEE_ADDRESS],
+            tokens[TOKEN_PJOIN_RESPONSE_NODEID]);
+
+    if (ctx->g_EndDeviceNodeIdChangedCallback != NULL)
+    {
+        ctx->g_EndDeviceNodeIdChangedCallback(tokens[TOKEN_PJOIN_RESPONSE_IEEE_ADDRESS],
+                                              tokens[TOKEN_PJOIN_RESPONSE_NODEID],
+                                              ctx->g_plugin);
+    }
+
     ret = TW_RESULT_OK;
 
 exit:
-    OC_LOG_V(INFO, TAG, "Leave TelEndDeviceJoinHandler() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave TelEndDeviceJoinHandler() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode TelMatchDescHandler(int count, char* tokens[])
+TWResultCode TelMatchDescHandler(int count, char* tokens[], TWContext* ctx)
 {
     //Prompt:       MatchDesc:0B4A,00,01
 
-    OC_LOG_V(INFO, TAG, "Enter TelMatchDescHandler()");
+    OIC_LOG(INFO, TAG, "Enter TelMatchDescHandler()");
     TWResultCode ret = TW_RESULT_ERROR;
 
     if(!tokens || count != RESPONSE_PARAMS_COUNT_MATCH_DESC)
@@ -2048,19 +2338,19 @@ TWResultCode TelMatchDescHandler(int count, char* tokens[])
         goto exit;
     }
 
-    if (strcmp(tokens[1], AT_STR_ERROR_OK) != 0)
+    if (strcmp(tokens[TOKEN_MATCHDESC_STATUS_CODE], AT_STR_ERROR_OK) != 0)
     {
-        OC_LOG_V(INFO, TAG, "MatchDesc prompt contained error status.");
+        OIC_LOG(INFO, TAG, "MatchDesc prompt contained error status.");
         ret = TW_RESULT_ERROR;
         goto exit;
     }
     else
     {
         char remoteEUI[SIZE_EUI];
-        ret = GetRemoteEUI(tokens[0], remoteEUI);
+        ret = GetRemoteEUI(tokens[TOKEN_MATCHDESC_NODEID], remoteEUI, ctx);
         if (ret != TW_RESULT_OK)
         {
-            OC_LOG_V(ERROR, TAG, "GetRemoteEUI()");
+            OIC_LOG(ERROR, TAG, "GetRemoteEUI()");
             goto exit;
         }
         else
@@ -2083,16 +2373,19 @@ TWResultCode TelMatchDescHandler(int count, char* tokens[])
                 else
                 {
                     OICStrcpy(device->eui, SIZE_EUI, remoteEUI);
-                    OICStrcpy(device->nodeId, SIZE_NODEID, tokens[0]);
-                    OICStrcpy(device->endpointOfInterest->endpointId, SIZE_ENDPOINTID, tokens[2]);
-                    g_WIPDevice = device;
+                    OICStrcpy(device->nodeId, SIZE_NODEID, tokens[TOKEN_MATCHDESC_NODEID]);
+                    OICStrcpy(device->endpointOfInterest->endpointId,
+                              SIZE_ENDPOINTID,
+                              tokens[TOKEN_MATCHDESC_ENDPOINTID]);
+                    ctx->g_WIPDevice = device;
 
                     //Step 2: Add to list
-                    if (g_FoundMatchedDeviceList == NULL)
+                    if (ctx->g_FoundMatchedDeviceList == NULL)
                     {
                         //Create a list of promptCount entries
-                        g_FoundMatchedDeviceList = (TWDeviceList*)OICMalloc(sizeof(TWDeviceList));
-                        if (g_FoundMatchedDeviceList == NULL)
+                        ctx->g_FoundMatchedDeviceList =
+                                (TWDeviceList*)OICMalloc(sizeof(TWDeviceList));
+                        if (ctx->g_FoundMatchedDeviceList == NULL)
                         {
                             OICFree(device->endpointOfInterest);
                             OICFree(device);
@@ -2100,10 +2393,10 @@ TWResultCode TelMatchDescHandler(int count, char* tokens[])
                         }
                         else
                         {
-                            g_FoundMatchedDeviceList->count = 1;
-                            g_FoundMatchedDeviceList->deviceList =
+                            ctx->g_FoundMatchedDeviceList->count = 1;
+                            ctx->g_FoundMatchedDeviceList->deviceList =
                                     (TWDevice*)OICMalloc(sizeof(TWDevice));
-                            if (g_FoundMatchedDeviceList->deviceList == NULL)
+                            if (ctx->g_FoundMatchedDeviceList->deviceList == NULL)
                             {
                                 OICFree(device->endpointOfInterest);
                                 OICFree(device);
@@ -2111,7 +2404,7 @@ TWResultCode TelMatchDescHandler(int count, char* tokens[])
                             }
                             else
                             {
-                                memcpy(g_FoundMatchedDeviceList->deviceList,
+                                memcpy(ctx->g_FoundMatchedDeviceList->deviceList,
                                        device,
                                        sizeof(TWDevice));
                                 ret = TW_RESULT_OK;
@@ -2121,9 +2414,10 @@ TWResultCode TelMatchDescHandler(int count, char* tokens[])
                     else
                     {
                         //Expand the list
-                        int newSize = sizeof(TWDevice) * (g_FoundMatchedDeviceList->count + 1);
-                        TWDevice* temp = (TWDevice*)realloc(g_FoundMatchedDeviceList->deviceList,
-                                                            newSize);
+                        int newSize = sizeof(TWDevice)*(ctx->g_FoundMatchedDeviceList->count + 1);
+                        TWDevice* temp =
+                                (TWDevice*)realloc(ctx->g_FoundMatchedDeviceList->deviceList,
+                                                   newSize);
                         if (temp == NULL)
                         {
                             OICFree(device->endpointOfInterest);
@@ -2132,16 +2426,16 @@ TWResultCode TelMatchDescHandler(int count, char* tokens[])
                         }
                         else
                         {
-                            g_FoundMatchedDeviceList->deviceList = temp;
+                            ctx->g_FoundMatchedDeviceList->deviceList = temp;
 
                             //Add to the end of list
-                            int count = g_FoundMatchedDeviceList->count;
-                            memcpy(&g_FoundMatchedDeviceList->deviceList[count],
+                            int count = ctx->g_FoundMatchedDeviceList->count;
+                            memcpy(&(ctx->g_FoundMatchedDeviceList->deviceList[count]),
                                    device,
                                    sizeof(TWDevice));
 
                             //Increase the count
-                            g_FoundMatchedDeviceList->count++;
+                            ctx->g_FoundMatchedDeviceList->count++;
 
                             ret = TW_RESULT_OK;
                         }
@@ -2152,11 +2446,11 @@ TWResultCode TelMatchDescHandler(int count, char* tokens[])
     }
 
 exit:
-    OC_LOG_V(INFO, TAG, "Leave TelMatchDescHandler() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave TelMatchDescHandler() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode TelSimpleDescHandler(int count, char* tokens[])
+TWResultCode TelSimpleDescHandler(int count, char* tokens[], TWContext* ctx)
 {
     //AT+SIMPLEDESC:3746,3746,01
     //      SEQ:97
@@ -2170,7 +2464,7 @@ TWResultCode TelSimpleDescHandler(int count, char* tokens[])
     //      OutCluster:0019
     //      ACK:97
 
-    OC_LOG_V(INFO, TAG, "Enter TelSimpleDescHandler().");
+    OIC_LOG(INFO, TAG, "Enter TelSimpleDescHandler().");
     TWResultCode ret = TW_RESULT_UNKNOWN;
 
     if(!tokens || count != RESPONSE_PARAMS_COUNT_SIMPLE_DESC)
@@ -2179,40 +2473,50 @@ TWResultCode TelSimpleDescHandler(int count, char* tokens[])
         goto exit;
     }
 
-    if (g_WIPDevice == NULL)
+    if (ctx->g_WIPDevice == NULL)
     {
-        OC_LOG_V(ERROR, TAG,
-                 "Receive simple descriptor unexpectedly - %s", tokens[0]);
+        OIC_LOG_V(ERROR, TAG,
+                 "Receive simple descriptor unexpectedly - %s",
+                 tokens[TOKEN_SIMPLEDESC_SIMPLEDESC_NODEID]);
         ret = TW_RESULT_ERROR;
         goto exit;
     }
 
-    if (strcmp(tokens[1], AT_STR_ERROR_OK) != 0)
+    if (strcmp(tokens[TOKEN_SIMPLEDESC_SIMPLEDESC_STATUS_CODE], AT_STR_ERROR_OK) != 0)
     {
-        OC_LOG_V(ERROR, TAG, "SimpleDesc: prompt contained error status %s.", tokens[1]);
+        OIC_LOG_V(ERROR,
+                 TAG,
+                 "SimpleDesc: prompt contained error status %s.",
+                 tokens[TOKEN_SIMPLEDESC_SIMPLEDESC_STATUS_CODE]);
         ret = TW_RESULT_ERROR;
     }
     else
     {
-        if (strcmp(tokens[0], g_WIPDevice->nodeId) == 0)
+        if (strcmp(tokens[TOKEN_SIMPLEDESC_SIMPLEDESC_NODEID],
+                   ctx->g_WIPDevice->nodeId) == 0)
         {
-            OC_LOG_V(INFO, TAG, "Got simple descriptor for nodeid %s", tokens[0]);
+            OIC_LOG_V(INFO,
+                     TAG,
+                     "Got simple descriptor for nodeid %s",
+                     tokens[TOKEN_SIMPLEDESC_SIMPLEDESC_NODEID]);
             ret = TW_RESULT_OK;
         }
         else
         {
-            OC_LOG_V(ERROR, TAG,
-                     "Finding simple descriptor for non existing nodeid %s.", tokens[0]);
+            OIC_LOG_V(ERROR,
+                     TAG,
+                     "Finding simple descriptor for non existing nodeid %s.",
+                     tokens[TOKEN_SIMPLEDESC_SIMPLEDESC_NODEID]);
             ret = TW_RESULT_ERROR;
         }
     }
 
 exit:
-    OC_LOG_V(INFO, TAG, "Leave TelSimpleDescHandler() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave TelSimpleDescHandler() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode TelSimpleDescInClusterHandler(int count, char* tokens[])
+TWResultCode TelSimpleDescInClusterHandler(int count, char* tokens[], TWContext* ctx)
 {
     //AT+SIMPLEDESC:3746,3746,01
     //      SEQ:97
@@ -2226,47 +2530,48 @@ TWResultCode TelSimpleDescInClusterHandler(int count, char* tokens[])
     //      OutCluster:0019
     //      ACK:97
 
-    OC_LOG_V(INFO, TAG, "Enter TelSimpleDescInClusterHandler()");
+    OIC_LOG(INFO, TAG, "Enter TelSimpleDescInClusterHandler()");
     TWResultCode ret = TW_RESULT_ERROR;
 
     if (!tokens || count < RESPONSE_PARAMS_COUNT_SIMPLE_DESC_IN_CLUSTER_MIN )
     {
-        OC_LOG_V(ERROR, TAG, "Invalid Params");
+        OIC_LOG(ERROR, TAG, "Invalid Params");
         ret = TW_RESULT_ERROR_INVALID_PARAMS;
                goto exit;
     }
 
-    if (g_WIPDevice == NULL)
+    if (ctx->g_WIPDevice == NULL)
     {
-        OC_LOG_V(ERROR, TAG,
-                 "Receive simple descriptor unexpectedly - %s", tokens[0]);
+        OIC_LOG_V(ERROR, TAG,
+                 "Receive simple descriptor unexpectedly - %s",
+                 tokens[TOKEN_SIMPLEDESC_INCLUSTER_STRING]);
         ret = TW_RESULT_ERROR;
         goto exit;
     }
 
-    if (g_WIPDevice->endpointOfInterest->clusterList != NULL)
+    if (ctx->g_WIPDevice->endpointOfInterest->clusterList != NULL)
     {
-        OC_LOG_V(ERROR, TAG, "Expected an empty cluster list.");
+        OIC_LOG(ERROR, TAG, "Expected an empty cluster list.");
         ret = TW_RESULT_ERROR;
         goto exit;
     }
 
     //Add found clusters for the node.
-    g_WIPDevice->endpointOfInterest->clusterList =
+    ctx->g_WIPDevice->endpointOfInterest->clusterList =
             (TWClusterList*)OICMalloc(sizeof(TWClusterList));
-    if (g_WIPDevice->endpointOfInterest->clusterList == NULL)
+    if (ctx->g_WIPDevice->endpointOfInterest->clusterList == NULL)
     {
-        OC_LOG_V(ERROR, TAG, "No Memory - clusterList");
+        OIC_LOG(ERROR, TAG, "No Memory - clusterList");
         ret = TW_RESULT_ERROR_NO_MEMORY;
         goto exit;
     }
 
-    g_WIPDevice->endpointOfInterest->clusterList->clusterIds =
+    ctx->g_WIPDevice->endpointOfInterest->clusterList->clusterIds =
             (TWClusterId*)OICMalloc(sizeof(TWClusterId) * count);
-    if (g_WIPDevice->endpointOfInterest->clusterList->clusterIds == NULL)
+    if (ctx->g_WIPDevice->endpointOfInterest->clusterList->clusterIds == NULL)
     {
-        OICFree(g_WIPDevice->endpointOfInterest->clusterList);
-        OC_LOG_V(ERROR, TAG, "No Memory - clusterIds");
+        OICFree(ctx->g_WIPDevice->endpointOfInterest->clusterList);
+        OIC_LOG(ERROR, TAG, "No Memory - clusterIds");
         ret = TW_RESULT_ERROR_NO_MEMORY;
         goto exit;
     }
@@ -2274,25 +2579,23 @@ TWResultCode TelSimpleDescInClusterHandler(int count, char* tokens[])
     int i = 0;
     for (; i < count; i++)
     {
-        OICStrcpy(g_WIPDevice->endpointOfInterest->clusterList->
-                    clusterIds[i].clusterId,
-                    SIZE_CLUSTERID,
-                    tokens[i]);
+        OICStrcpy(ctx->g_WIPDevice->endpointOfInterest->clusterList->clusterIds[i].clusterId,
+                  SIZE_CLUSTERID,
+                  tokens[i]);
 
-        OC_LOG_V(INFO, TAG, "ClusterIds[%d]=%s",
+        OIC_LOG_V(INFO, TAG, "ClusterIds[%d]=%s",
                  i,
-                 g_WIPDevice->endpointOfInterest->
-                 clusterList->clusterIds[i].clusterId);
+                 ctx->g_WIPDevice->endpointOfInterest->clusterList->clusterIds[i].clusterId);
     }
-    g_WIPDevice->endpointOfInterest->clusterList->count = count;
+    ctx->g_WIPDevice->endpointOfInterest->clusterList->count = count;
     ret = TW_RESULT_HAS_CLUSTERS;
 
 exit:
-    OC_LOG_V(INFO, TAG, "Leave TelSimpleDescInClusterHandler() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave TelSimpleDescInClusterHandler() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode TelWriteAttrHandler(int count, char* tokens[])
+TWResultCode TelWriteAttrHandler(int count, char* tokens[], TWContext* ctx)
 {
     //AT+WRITEATR:3A3D,01,0,0003,0000,21,00
     //      OK
@@ -2302,7 +2605,8 @@ TWResultCode TelWriteAttrHandler(int count, char* tokens[])
     //      OK
     //      WRITEATTR:B826,01,0500,0010,70
 
-    OC_LOG_V(INFO, TAG, "Enter TelWriteAttrHandler()");
+    OIC_LOG(INFO, TAG, "Enter TelWriteAttrHandler()");
+    (void)ctx;
 
     TWResultCode ret = TW_RESULT_ERROR;
 
@@ -2316,25 +2620,34 @@ TWResultCode TelWriteAttrHandler(int count, char* tokens[])
 
     if (count == RESPONSE_PARAMS_COUNT_WRITE_ATTR_4)
     {
-        if (strcmp(tokens[3], AT_STR_ERROR_OK) == 0)
+        if (strcmp(tokens[TOKEN_WRITEATTR_STATUS_CODE], AT_STR_ERROR_OK) == 0)
         {
             ret = TW_RESULT_OK;
         }
+        else if (strcmp(tokens[TOKEN_WRITEATTR_STATUS_CODE], AT_STR_ERROR_INVALID_OP) == 0)
+        {
+            ret = TW_RESULT_ERROR_INVALID_OP;
+        }
     }
     else if (count == RESPONSE_PARAMS_COUNT_WRITE_ATTR_5)
     {
-        if (strcmp(tokens[4], AT_STR_ERROR_INVALID_OP) == 0)
+        if (strcmp(tokens[TOKEN_WRITEATTR_STATUS_CODE_ALTERNATIVE], AT_STR_ERROR_OK) == 0)
+        {
+            ret = TW_RESULT_OK;
+        }
+        else if (strcmp(tokens[TOKEN_WRITEATTR_STATUS_CODE_ALTERNATIVE],
+                        AT_STR_ERROR_INVALID_OP) == 0)
         {
             ret = TW_RESULT_ERROR_INVALID_OP;
         }
     }
 
 exit:
-    OC_LOG_V(INFO, TAG, "Leave TelWriteAttrHandler() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave TelWriteAttrHandler() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode TelReadAttrHandlerTemperature(int count, char* tokens[])
+TWResultCode TelReadAttrHandlerTemperature(int count, char* tokens[], TWContext* ctx)
 {
     //AT+READATR:F2D7,01,0,0402,0002
     //      OK
@@ -2344,51 +2657,53 @@ TWResultCode TelReadAttrHandlerTemperature(int count, char* tokens[])
     //      OK
     //      ERROR:66
 
-    OC_LOG_V(INFO, TAG, "Enter TelReadAttrHandlerTemperature().");
+    OIC_LOG(INFO, TAG, "Enter TelReadAttrHandlerTemperature().");
     TWResultCode ret = TW_RESULT_UNKNOWN;
 
     if(!tokens || count != RESPONSE_PARAMS_COUNT_TEMPERATURE)
     {
-        OC_LOG_V(ERROR, TAG, "Invalid Params");
+        OIC_LOG(ERROR, TAG, "Invalid Params");
         ret = TW_RESULT_ERROR_INVALID_PARAMS;
         goto exit;
     }
 
-    if (strcmp(tokens[3], AT_STR_ERROR_OK) != 0)
+    if (strcmp(tokens[TOKEN_TEMPERATURE_STATUS_CODE], AT_STR_ERROR_OK) != 0)
     {
-        OC_LOG_V(ERROR, TAG, "TEMPERATURE prompt contained error status.");
+        OIC_LOG(ERROR, TAG, "TEMPERATURE prompt contained error status.");
         ret = TW_RESULT_ERROR;
         goto exit;
     }
 
     // AttrInfo is 16-bit value representing (100 * Degrees Celsius)
     // so 0x812 = 20.66 C = 69.188 F
-    if (g_ZigBeeStatus.remoteAttributeValueRead != NULL)
+    if (ctx->g_ZigBeeStatus.remoteAttributeValueRead != NULL)
     {
-        OICFree(g_ZigBeeStatus.remoteAttributeValueRead);
-        g_ZigBeeStatus.remoteAttributeValueRead = NULL;
+        OICFree(ctx->g_ZigBeeStatus.remoteAttributeValueRead);
+        ctx->g_ZigBeeStatus.remoteAttributeValueRead = NULL;
     }
-    OC_LOG_V(INFO, TAG, "Read Attribute Value: %s", tokens[4]);
-    g_ZigBeeStatus.remoteAttributeValueRead =
-            (char*)OICMalloc(sizeof(char) * strlen(tokens[4]));
-    if (g_ZigBeeStatus.remoteAttributeValueRead == NULL)
+    OIC_LOG_V(INFO, TAG, "Read Attribute Value: %s", tokens[TOKEN_TEMPERATURE_VALUE]);
+    ctx->g_ZigBeeStatus.remoteAttributeValueRead =
+            (char*)OICMalloc(sizeof(char) * strlen(tokens[TOKEN_TEMPERATURE_VALUE]));
+    if (ctx->g_ZigBeeStatus.remoteAttributeValueRead == NULL)
     {
-        OC_LOG_V(ERROR, TAG, "No Memory");
+        OIC_LOG_V(ERROR, TAG, "No Memory");
         ret = TW_RESULT_ERROR_NO_MEMORY;
     }
     else
     {
-        strcpy(g_ZigBeeStatus.remoteAttributeValueRead, tokens[4]);
-        g_ZigBeeStatus.remoteAtrributeValueReadLength = strlen(tokens[4]);
+        strcpy(ctx->g_ZigBeeStatus.remoteAttributeValueRead,
+               tokens[TOKEN_TEMPERATURE_VALUE]);
+        ctx->g_ZigBeeStatus.remoteAtrributeValueReadLength =
+                     strlen(tokens[TOKEN_TEMPERATURE_VALUE]);
         ret = TW_RESULT_REMOTE_ATTR_HAS_VALUE;
     }
 
 exit:
-    OC_LOG_V(INFO, TAG, "Leave TelReadAttrHandlerTemperature() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave TelReadAttrHandlerTemperature() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode TelReadAttrHandler(int count, char* tokens[])
+TWResultCode TelReadAttrHandler(int count, char* tokens[], TWContext* ctx)
 {
     //AT+READATR:F2D7,01,0,0402,0002
     //      OK
@@ -2398,48 +2713,50 @@ TWResultCode TelReadAttrHandler(int count, char* tokens[])
     //      OK
     //      ERROR:66
 
-    OC_LOG_V(INFO, TAG, "Enter TelReadAttrHandler()");
+    OIC_LOG(INFO, TAG, "Enter TelReadAttrHandler()");
     TWResultCode ret = TW_RESULT_UNKNOWN;
 
     if(!tokens || count != RESPONSE_PARAMS_COUNT_RESPATTR)
     {
-        OC_LOG_V(ERROR, TAG, "Invalid Params");
+        OIC_LOG(ERROR, TAG, "Invalid Params");
         ret = TW_RESULT_ERROR_INVALID_PARAMS;
         goto exit;
     }
 
-    if (strcmp(tokens[4], AT_STR_ERROR_OK) != 0)
+    if (strcmp(tokens[TOKEN_RESPATTR_STATUS_CODE], AT_STR_ERROR_OK) != 0)
     {
-        OC_LOG_V(INFO, TAG, "READATTR prompt contained error status.");
+        OIC_LOG(INFO, TAG, "READATTR prompt contained error status.");
         ret = TW_RESULT_ERROR;
         goto exit;
     }
 
-    if (g_ZigBeeStatus.remoteAttributeValueRead != NULL)
+    if (ctx->g_ZigBeeStatus.remoteAttributeValueRead != NULL)
     {
-        OICFree(g_ZigBeeStatus.remoteAttributeValueRead);
+        OICFree(ctx->g_ZigBeeStatus.remoteAttributeValueRead);
     }
-    OC_LOG_V(INFO, TAG, "Read Attribute Value: %s.", tokens[5]);
-    g_ZigBeeStatus.remoteAttributeValueRead =
-            (char*)OICMalloc(sizeof(char) * strlen(tokens[5]));
-    if (g_ZigBeeStatus.remoteAttributeValueRead != NULL)
+    OIC_LOG_V(INFO, TAG, "Read Attribute Value: %s.", tokens[TOKEN_RESPATTR_ATTRIBUTE_VALUE]);
+    ctx->g_ZigBeeStatus.remoteAttributeValueRead =
+            (char*)OICMalloc(sizeof(char) * strlen(tokens[TOKEN_RESPATTR_ATTRIBUTE_VALUE]));
+    if (ctx->g_ZigBeeStatus.remoteAttributeValueRead != NULL)
     {
-        strcpy(g_ZigBeeStatus.remoteAttributeValueRead, tokens[5]);
-        g_ZigBeeStatus.remoteAtrributeValueReadLength = strlen(tokens[5]);
+        strcpy(ctx->g_ZigBeeStatus.remoteAttributeValueRead,
+               tokens[TOKEN_RESPATTR_ATTRIBUTE_VALUE]);
+        ctx->g_ZigBeeStatus.remoteAtrributeValueReadLength =
+                     strlen(tokens[TOKEN_RESPATTR_ATTRIBUTE_VALUE]);
         ret = TW_RESULT_REMOTE_ATTR_HAS_VALUE;
     }
     else
     {
-        OC_LOG_V(ERROR, TAG, "No Memory");
+        OIC_LOG(ERROR, TAG, "No Memory");
         ret = TW_RESULT_ERROR_NO_MEMORY;
     }
 
 exit:
-    OC_LOG_V(INFO, TAG, "Leave TelReadAttrHandler().\n");
+    OIC_LOG(INFO, TAG, "Leave TelReadAttrHandler()");
     return ret;
 }
 
-TWResultCode TelZCLDefaultResponseHandler(int count, char* tokens[])
+TWResultCode TelZCLDefaultResponseHandler(int count, char* tokens[], TWContext* ctx)
 {
     //AT+RONOFF:<Address>,<EP>,<SendMode>[,<ON/OFF>]
     //      DFTREP:<NodeID>,<EP>,<ClusterID>,<CMD>,<Status>
@@ -2450,21 +2767,25 @@ TWResultCode TelZCLDefaultResponseHandler(int count, char* tokens[])
     //AT+LCMVTOLEV:<Address>,<EP>,<SendMode>,<ON/OFF>,<LevelValue>,<TransTime>
     //      DFTREP:<NodeID>,<EP>,<ClusterID>,<CMD>,<Status>
 
-    OC_LOG_V(INFO, TAG, "Enter TelZCLDefaultResponseHandler()");
+    OIC_LOG(INFO, TAG, "Enter TelZCLDefaultResponseHandler()");
+    (void)ctx;
     TWResultCode ret = TW_RESULT_UNKNOWN;
 
     if(!tokens || count != RESPONSE_PARAMS_COUNT_DFTREP)
     {
-        OC_LOG_V(ERROR, TAG, "Invalid Params");
+        OIC_LOG(ERROR, TAG, "Invalid Params");
         ret = TW_RESULT_ERROR_INVALID_PARAMS;
         goto exit;
     }
 
-    OC_LOG_V(INFO, TAG,
+    OIC_LOG_V(INFO, TAG,
              "DFTREP prompt succeed for NodeId:%s, EP:%s, ClusterId:%s, CMD:%s.\n",
-             tokens[0], tokens[1], tokens[2], tokens[3]);
+             tokens[TOKEN_DFTREP_NODEID],
+             tokens[TOKEN_DFTREP_ENDPOINTID],
+             tokens[TOKEN_DFTREP_CLUSTERID],
+             tokens[TOKEN_DFTREP_COMMANDID]);
 
-    if (strcmp(tokens[4], AT_STR_ERROR_OK) != 0)
+    if (strcmp(tokens[TOKEN_DFTREP_STATUS_CODE], AT_STR_ERROR_OK) != 0)
     {
         ret = TW_RESULT_ERROR;
     }
@@ -2474,144 +2795,150 @@ TWResultCode TelZCLDefaultResponseHandler(int count, char* tokens[])
     }
 
 exit:
-    OC_LOG_V(INFO, TAG, "Leave TelZCLDefaultResponseHandler()");
+    OIC_LOG(INFO, TAG, "Leave TelZCLDefaultResponseHandler()");
     return ret;
 }
 
-TWResultCode TelSwitchDoorLockStateHandler(int count, char* tokens[])
+TWResultCode TelSwitchDoorLockStateHandler(int count, char* tokens[], TWContext* ctx)
 {
     //AT+DRLOCK:<Address>,<EP>,<SendMode>,<Lock/Unlock>
     //      DRLOCRSP:<nodeID>,<ep>,<status>
     //      or
     //      DRUNLOCKRSP:<nodeID>,<ep>,<status>
 
-    OC_LOG_V(INFO, TAG, "Enter TelSwitchDoorLockStateHandler()");
+    OIC_LOG(INFO, TAG, "Enter TelSwitchDoorLockStateHandler()");
+    (void)ctx;
     TWResultCode ret = TW_RESULT_UNKNOWN;
 
     if(!tokens || count != RESPONSE_PARAMS_COUNT_DRLOCKUNLOCKRSP)
     {
-        OC_LOG_V(ERROR, TAG, "Invalid Params");
+        OIC_LOG(ERROR, TAG, "Invalid Params");
         ret = TW_RESULT_ERROR_INVALID_PARAMS;
         goto exit;
     }
 
-    if (strcmp(tokens[2], AT_STR_ERROR_OK) != 0)
+    if (strcmp(tokens[TOKEN_DRLOCKRSP_STATUS_CODE], AT_STR_ERROR_OK) != 0)
     {
-        OC_LOG_V(INFO, TAG,
-                 "DRLOCRSP/DRUNLOCKRSP prompt contained error status %s.", tokens[4]);
+        OIC_LOG_V(INFO,
+                 TAG,
+                 "DRLOCRSP/DRUNLOCKRSP prompt contained error status %s.",
+                 tokens[TOKEN_DRLOCKRSP_STATUS_CODE]);
         ret = TW_RESULT_ERROR;
     }
     else
     {
-        OC_LOG_V(INFO, TAG, "DRLOCRSP/DRUNLOCKRSP prompt succeed for nodeId:%s, ep:%s.",
-                 tokens[0], tokens[1]);
+        OIC_LOG_V(INFO, TAG, "DRLOCRSP/DRUNLOCKRSP prompt succeed for nodeId:%s, ep:%s.",
+                 tokens[TOKEN_DRLOCKRSP_NODEID],
+                 tokens[TOKEN_DRLOCKRSP_ENDPOINTID]);
         ret = TW_RESULT_OK;
     }
 
 exit:
-    OC_LOG_V(INFO, TAG, "Leave TelSwitchDoorLockStateHandler() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave TelSwitchDoorLockStateHandler() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode TelZoneEnrollRequestHandler(int count, char* tokens[])
+TWResultCode TelZoneEnrollRequestHandler(int count, char* tokens[], TWContext* ctx)
 {
     //ZENROLLREQ:<NodeID>,<EndPoint>,<ZoneType>,<ManufactureCode>
 
-    OC_LOG_V(INFO, TAG, "Enter TelZoneEnrollRequestHandler()");
+    OIC_LOG(INFO, TAG, "Enter TelZoneEnrollRequestHandler()");
+    (void)ctx;
     TWResultCode ret = TW_RESULT_UNKNOWN;
 
     if(!tokens || count != RESPONSE_PARAMS_COUNT_ZENROLLREQ)
     {
-        OC_LOG_V(ERROR, TAG, "Invalid Params");
+        OIC_LOG(ERROR, TAG, "Invalid Params");
         ret = TW_RESULT_ERROR_INVALID_PARAMS;
         goto exit;
     }
 
-    OC_LOG_V(INFO, TAG, "Received zone request from:");
-    OC_LOG_V(INFO, TAG, "Node:%s", tokens[0]);
-    OC_LOG_V(INFO, TAG, "EP:%s", tokens[1]);
-    OC_LOG_V(INFO, TAG, "ZoneType:%s", tokens[2]);
-    OC_LOG_V(INFO, TAG, "ManufactureCode:%s", tokens[3]);
+    OIC_LOG(INFO, TAG, "Received zone request from:");
+    OIC_LOG_V(INFO, TAG, "Node:%s", tokens[TOKEN_ZENROLLREQ_NODEID]);
+    OIC_LOG_V(INFO, TAG, "EP:%s", tokens[TOKEN_ZENROLLREQ_ENDPOINTID]);
+    OIC_LOG_V(INFO, TAG, "ZoneType:%s", tokens[TOKEN_ZENROLLREQ_ZONETYPE]);
+    OIC_LOG_V(INFO, TAG, "ManufactureCode:%s", tokens[TOKEN_ZENROLLREQ_MANUFACTURE_CODE]);
     ret = TW_RESULT_OK;
 
 exit:
-    OC_LOG_V(INFO, TAG, "Leave TelZoneEnrollRequestHandler() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave TelZoneEnrollRequestHandler() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode TelEnrolledHandler(int count, char* tokens[])
+TWResultCode TelEnrolledHandler(int count, char* tokens[], TWContext* ctx)
 {
     //ENROLLED:<ZID>,<ZoneType>,<EUI>
 
-    OC_LOG_V(INFO, TAG, "Enter TelEnrolledHandler()");
+    OIC_LOG(INFO, TAG, "Enter TelEnrolledHandler()");
     TWResultCode ret = TW_RESULT_OK;
 
     if(!tokens || count != RESPONSE_PARAMS_COUNT_ENROLLED)
     {
-        OC_LOG_V(ERROR, TAG, "Invalid Params");
+        OIC_LOG(ERROR, TAG, "Invalid Params");
         ret = TW_RESULT_ERROR_INVALID_PARAMS;
         goto exit;
     }
 
-    OC_LOG_V(INFO, TAG, "Received zone enrollment for:");
-    OC_LOG_V(INFO, TAG, "ZID:%s", tokens[0]);
-    OC_LOG_V(INFO, TAG, "ZoneType:%s", tokens[1]);
-    OC_LOG_V(INFO, TAG, "EUI:%s", tokens[2]);
+    OIC_LOG(INFO, TAG, "Received zone enrollment for:");
+    OIC_LOG_V(INFO, TAG, "ZID:%s", tokens[TOKEN_ENROLLED_ZONEID]);
+    OIC_LOG_V(INFO, TAG, "ZoneType:%s", tokens[TOKEN_ENROLLED_ZONETYPE]);
+    OIC_LOG_V(INFO, TAG, "EUI:%s", tokens[TOKEN_ENROLLED_EUI]);
 
     TWEnrollee enrollee;
-    OICStrcpy(enrollee.zoneId, SIZE_ZONEID, tokens[0]);
-    OICStrcpy(enrollee.zoneType, SIZE_ZONETYPE, tokens[1]);
-    OICStrcpy(enrollee.eui, SIZE_EUI, tokens[2]);
+    OICStrcpy(enrollee.zoneId, SIZE_ZONEID, tokens[TOKEN_ENROLLED_ZONEID]);
+    OICStrcpy(enrollee.zoneType, SIZE_ZONETYPE, tokens[TOKEN_ENROLLED_ZONETYPE]);
+    OICStrcpy(enrollee.eui, SIZE_EUI, tokens[TOKEN_ENROLLED_EUI]);
 
-    if (g_EnrollmentSucceedCallback != NULL)
+    if (ctx->g_EnrollmentSucceedCallback != NULL)
     {
-        OC_LOG_V(INFO, TAG, "Enrolled - Invoke callback");
-        g_EnrollmentSucceedCallback(&enrollee);
+        OIC_LOG_V(INFO, TAG, "Enrolled - Invoke callback");
+        ctx->g_EnrollmentSucceedCallback(&enrollee, ctx->g_plugin);
     }
     ret = TW_RESULT_OK;
 
 exit:
-    OC_LOG_V(INFO, TAG, "Leave TelEnrolledHandler() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave TelEnrolledHandler() with ret=%d", ret);
     return ret;
 }
 
-TWResultCode TelZoneStatusHandler(int count, char* tokens[])
+TWResultCode TelZoneStatusHandler(int count, char* tokens[], TWContext* ctx)
 {
     //ZONESTATUS:<NodeID>,<EP>,<ZoneStatus>,<ExtendStatus>[,<ZoneID>,<Delay>]
     //ZONESTATUS:5FBA,01,0021,00,01,00AF
 
-    OC_LOG_V(INFO, TAG, "Enter TelZoneStatusHandler()");
+    OIC_LOG(INFO, TAG, "Enter TelZoneStatusHandler()");
     TWResultCode ret = TW_RESULT_UNKNOWN;
     if(!tokens ||
        ((count != RESPONSE_PARAMS_COUNT_ZONESTATUS_4) &&
         (count != RESPONSE_PARAMS_COUNT_ZONESTATUS_6)))
     {
-        OC_LOG_V(ERROR, TAG, "Invalid Params");
+        OIC_LOG(ERROR, TAG, "Invalid Params");
         ret = TW_RESULT_ERROR_INVALID_PARAMS;
         goto exit;
     }
 
     TWUpdate update;
-    OICStrcpy(update.nodeId, SIZE_NODEID, tokens[0]);
-    OICStrcpy(update.endpoint, SIZE_NODEID, tokens[1]);
-    OICStrcpy(update.status, SIZE_NODEID, tokens[2]);
-    OICStrcpy(update.extendedStatus, SIZE_NODEID, tokens[3]);
+    OICStrcpy(update.nodeId, SIZE_NODEID, tokens[TOKEN_ZONESTATUS_NODEID]);
+    OICStrcpy(update.endpoint, SIZE_NODEID, tokens[TOKEN_ZONESTATUS_ENDPOINTID]);
+    OICStrcpy(update.status, SIZE_NODEID, tokens[TOKEN_ZONESTATUS_ZONESTATUS]);
+    OICStrcpy(update.extendedStatus, SIZE_NODEID, tokens[TOKEN_ZONESTATUS_ZONESTATUS_EXTENDED]);
 
     if (count == RESPONSE_PARAMS_COUNT_ZONESTATUS_6)
     {
-        OICStrcpy(update.zoneId, SIZE_NODEID, tokens[4]);
-        OICStrcpy(update.delay, SIZE_NODEID, tokens[5]);
+        OICStrcpy(update.zoneId, SIZE_NODEID, tokens[TOKEN_ZONESTATUS_ZONEID]);
+        OICStrcpy(update.delay, SIZE_NODEID, tokens[TOKEN_ZONESTATUS_DELAY]);
     }
 
-    if (g_DeviceStatusUpdateCallback != NULL)
+    if (ctx->g_DeviceStatusUpdateCallback != NULL)
     {
-        OC_LOG_V(INFO, TAG, "device status update - invoke callback");
-        g_DeviceStatusUpdateCallback(&update);
+        OIC_LOG(INFO, TAG, "device status update - invoke callback");
+        ctx->g_DeviceStatusUpdateCallback(&update, ctx->g_plugin);
+        OIC_LOG(INFO, TAG, "device status update - callback done");
     }
     ret = TW_RESULT_OK;
 
 exit:
-    OC_LOG_V(INFO, TAG, "Leave TelZoneStatusHandler() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave TelZoneStatusHandler() with ret=%d", ret);
     return ret;
 }
 
@@ -2626,11 +2953,11 @@ exit:
  */
 int Tokenize(const char *input, const char* delimiters, char* output[])
 {
-    OC_LOG_V(INFO, TAG, "Enter Tokenize() - %s", input);
+    OIC_LOG_V(INFO, TAG, "Enter Tokenize() - %s", input);
 
     if (output == NULL)
     {
-        OC_LOG_V(INFO, TAG, "Invalid parameter.");
+        OIC_LOG(INFO, TAG, "Invalid parameter.");
         return -1;
     }
 
@@ -2646,13 +2973,13 @@ int Tokenize(const char *input, const char* delimiters, char* output[])
         int size = strlen(p) + 1;   //for null char
         output[index] = (char*)OICCalloc(size, sizeof(char));
         OICStrcpy(output[index], size, p);
-        OC_LOG_V(INFO, TAG, "Token[%d]=%s", index, output[index]);
+        OIC_LOG_V(INFO, TAG, "Token[%d]=%s", index, output[index]);
         p = strtok_r (NULL, delimiters, &savePtr);
         index++;
     }
 
     OICFree(str);
-    OC_LOG_V(INFO, TAG, "Leave Tokenize()");
+    OIC_LOG(INFO, TAG, "Leave Tokenize()");
     return index;
 }
 
@@ -2680,7 +3007,7 @@ TWResultCode AsciiHexToValue(char* hexString, int length, uint64_t* value)
     int retVal = AsciiToHex(hexString[0]);
     if(retVal == -1)
     {
-        OC_LOG(ERROR, TAG, "Bad conversion from ASCII To Hex.");
+        OIC_LOG(ERROR, TAG, "Bad conversion from ASCII To Hex.");
         return TW_RESULT_ERROR;
     }
     *value = (uint64_t)retVal;
@@ -2692,7 +3019,7 @@ TWResultCode AsciiHexToValue(char* hexString, int length, uint64_t* value)
             retVal = AsciiToHex(hexString[i]);
             if(retVal == -1)
             {
-                OC_LOG(ERROR, TAG, "Bad conversion from ASCII To Hex.");
+                OIC_LOG(ERROR, TAG, "Bad conversion from ASCII To Hex.");
                 return TW_RESULT_ERROR;
             }
             *value |= (uint64_t)retVal;
@@ -2706,71 +3033,73 @@ TWResultCode AsciiHexToValue(char* hexString, int length, uint64_t* value)
  * Deallocate device list.
  *
  */
-void DeallocateTWDeviceList()
+void DeallocateTWDeviceList(TWContext* ctx)
 {
-    if (g_FoundMatchedDeviceList == NULL)
+    if (ctx->g_FoundMatchedDeviceList == NULL)
     {
         return;
     }
 
-    if (g_FoundMatchedDeviceList->deviceList == NULL)
+    if (ctx->g_FoundMatchedDeviceList->deviceList == NULL)
     {
-        OICFree(g_FoundMatchedDeviceList);
-        g_FoundMatchedDeviceList = NULL;
+        OICFree(ctx->g_FoundMatchedDeviceList);
+        ctx->g_FoundMatchedDeviceList = NULL;
         return;
     }
 
-    if (g_FoundMatchedDeviceList->deviceList->endpointOfInterest == NULL)
+    if (ctx->g_FoundMatchedDeviceList->deviceList->endpointOfInterest == NULL)
     {
-        OICFree(g_FoundMatchedDeviceList->deviceList);
-        g_FoundMatchedDeviceList->deviceList = NULL;
+        OICFree(ctx->g_FoundMatchedDeviceList->deviceList);
+        ctx->g_FoundMatchedDeviceList->deviceList = NULL;
 
-        OICFree(g_FoundMatchedDeviceList);
-        g_FoundMatchedDeviceList = NULL;
+        OICFree(ctx->g_FoundMatchedDeviceList);
+        ctx->g_FoundMatchedDeviceList = NULL;
         return;
     }
 
-    if (g_FoundMatchedDeviceList->deviceList->endpointOfInterest->clusterList == NULL)
+    if (ctx->g_FoundMatchedDeviceList->deviceList->endpointOfInterest->clusterList == NULL)
     {
-        OICFree(g_FoundMatchedDeviceList->deviceList->endpointOfInterest);
-        g_FoundMatchedDeviceList->deviceList->endpointOfInterest = NULL;
+        OICFree(ctx->g_FoundMatchedDeviceList->deviceList->endpointOfInterest);
+        ctx->g_FoundMatchedDeviceList->deviceList->endpointOfInterest = NULL;
 
-        OICFree(g_FoundMatchedDeviceList->deviceList);
-        g_FoundMatchedDeviceList->deviceList = NULL;
+        OICFree(ctx->g_FoundMatchedDeviceList->deviceList);
+        ctx->g_FoundMatchedDeviceList->deviceList = NULL;
 
-        OICFree(g_FoundMatchedDeviceList);
-        g_FoundMatchedDeviceList = NULL;
+        OICFree(ctx->g_FoundMatchedDeviceList);
+        ctx->g_FoundMatchedDeviceList = NULL;
         return;
     }
 
-    if (g_FoundMatchedDeviceList->deviceList->endpointOfInterest-> clusterList->clusterIds == NULL)
+    if (ctx->g_FoundMatchedDeviceList->deviceList->endpointOfInterest->clusterList->clusterIds
+            == NULL)
     {
-        OICFree(g_FoundMatchedDeviceList->deviceList->endpointOfInterest->clusterList);
-        g_FoundMatchedDeviceList->deviceList->endpointOfInterest->clusterList = NULL;
+        OICFree(ctx->g_FoundMatchedDeviceList->deviceList->endpointOfInterest->clusterList);
+        ctx->g_FoundMatchedDeviceList->deviceList->endpointOfInterest->clusterList = NULL;
 
-        OICFree(g_FoundMatchedDeviceList->deviceList->endpointOfInterest);
-        g_FoundMatchedDeviceList->deviceList->endpointOfInterest = NULL;
+        OICFree(ctx->g_FoundMatchedDeviceList->deviceList->endpointOfInterest);
+        ctx->g_FoundMatchedDeviceList->deviceList->endpointOfInterest = NULL;
 
-        OICFree(g_FoundMatchedDeviceList->deviceList);
-        g_FoundMatchedDeviceList->deviceList = NULL;
+        OICFree(ctx->g_FoundMatchedDeviceList->deviceList);
+        ctx->g_FoundMatchedDeviceList->deviceList = NULL;
 
-        OICFree(g_FoundMatchedDeviceList);
-        g_FoundMatchedDeviceList = NULL;
+        OICFree(ctx->g_FoundMatchedDeviceList);
+        ctx->g_FoundMatchedDeviceList = NULL;
         return;
     }
 
-    OICFree(g_FoundMatchedDeviceList->deviceList->endpointOfInterest-> clusterList->clusterIds);
-    g_FoundMatchedDeviceList->deviceList->endpointOfInterest->clusterList->clusterIds = NULL;
+    OICFree(ctx->g_FoundMatchedDeviceList->deviceList->
+            endpointOfInterest->clusterList->clusterIds);
+    ctx->g_FoundMatchedDeviceList->deviceList->endpointOfInterest->clusterList->clusterIds = NULL;
 
-    OICFree(g_FoundMatchedDeviceList->deviceList->endpointOfInterest->clusterList);
-    g_FoundMatchedDeviceList->deviceList->endpointOfInterest->clusterList = NULL;
+    OICFree(ctx->g_FoundMatchedDeviceList->deviceList->endpointOfInterest->clusterList);
+    ctx->g_FoundMatchedDeviceList->deviceList->endpointOfInterest->clusterList = NULL;
 
-    OICFree(g_FoundMatchedDeviceList->deviceList->endpointOfInterest);
-    g_FoundMatchedDeviceList->deviceList->endpointOfInterest = NULL;
+    OICFree(ctx->g_FoundMatchedDeviceList->deviceList->endpointOfInterest);
+    ctx->g_FoundMatchedDeviceList->deviceList->endpointOfInterest = NULL;
 
-    OICFree(g_FoundMatchedDeviceList->deviceList);
-    g_FoundMatchedDeviceList->deviceList = NULL;
+    OICFree(ctx->g_FoundMatchedDeviceList->deviceList);
+    ctx->g_FoundMatchedDeviceList->deviceList = NULL;
 
-    OICFree(g_FoundMatchedDeviceList);
-    g_FoundMatchedDeviceList = NULL;
+    OICFree(ctx->g_FoundMatchedDeviceList);
+    ctx->g_FoundMatchedDeviceList = NULL;
 }
index aeee38d..0bfa9a8 100644 (file)
@@ -58,7 +58,7 @@ TWResultCode TWCloseTWSock(TWSock * sock);
 
 static TWSock * g_twSockList = NULL;
 
-TWResultCode TWAddTWSock(TWSock * sock, PIPlugin * plugin, const char * fileLoc)
+TWResultCode TWAddTWSock(TWSock * sock, PIPlugin_Zigbee * plugin, const char * fileLoc)
 {
     if(!sock || !plugin || !fileLoc)
     {
@@ -80,7 +80,7 @@ TWResultCode TWAddTWSock(TWSock * sock, PIPlugin * plugin, const char * fileLoc)
     sock->fd = open(fileLoc, O_RDWR | O_NOCTTY | O_SYNC);
     if(sock->fd <= 0)
     {
-        OC_LOG_V(INFO, TAG, "Could not open port. Errno is: %d\n", errno);
+        OIC_LOG_V(INFO, TAG, "Could not open port. Errno is: %d\n", errno);
         return TW_RESULT_ERROR;
     }
 
@@ -110,7 +110,7 @@ TWResultCode TWAddTWSock(TWSock * sock, PIPlugin * plugin, const char * fileLoc)
     return TW_RESULT_OK;
 }
 
-TWSock * TWGetSock(PIPlugin * plugin)
+TWSock * TWGetSock(PIPlugin_Zigbee * plugin)
 {
     if(!plugin)
     {
@@ -137,7 +137,7 @@ TWResultCode TWCloseTWSock(TWSock * sock)
     int ret = close(sock->fd);
     if(ret != 0)
     {
-        OC_LOG_V(ERROR, TAG, "Could not close port. Errno is: %d", errno);
+        OIC_LOG_V(ERROR, TAG, "Could not close port. Errno is: %d", errno);
         return TW_RESULT_ERROR;
     }
     return TW_RESULT_OK;
@@ -166,7 +166,7 @@ TWResultCode TWDeleteTWSock(TWSock * sock)
     int mutexRet = pthread_mutex_destroy(&(sock->mutex));
     if(mutexRet != 0)
     {
-        OC_LOG_V(ERROR, TAG, "Failed to destroy mutex. Error: %d", mutexRet);
+        OIC_LOG_V(ERROR, TAG, "Failed to destroy mutex. Error: %d", mutexRet);
         return TW_RESULT_ERROR;
     }
     TWResultCode result = TWCloseTWSock(sock);
@@ -192,7 +192,7 @@ TWResultCode TWDeleteAllTWSock()
  */
 int SetTerminalInfo(int fd, int speed, int parity, int shouldBlock)
 {
-    OC_LOG(INFO, TAG, "Enter SetTerminalInfo()");
+    OIC_LOG(INFO, TAG, "Enter SetTerminalInfo()");
 
     int ret = 0;
     struct termios terminalInfo = {
@@ -203,7 +203,7 @@ int SetTerminalInfo(int fd, int speed, int parity, int shouldBlock)
     ret = tcgetattr(fd, &terminalInfo);
     if (ret != 0)
     {
-        OC_LOG_V(ERROR, TAG, "tcgetattr() - ret=%d errno=%d", ret, errno);
+        OIC_LOG_V(ERROR, TAG, "tcgetattr() - ret=%d errno=%d", ret, errno);
         ret = -1;
         goto exit;
     }
@@ -212,7 +212,7 @@ int SetTerminalInfo(int fd, int speed, int parity, int shouldBlock)
     ret = cfsetispeed (&terminalInfo, speed);
     if (ret != 0)
     {
-        OC_LOG_V(ERROR, TAG, "cfsetispeed() - ret=%d errno=%d", ret, errno);
+        OIC_LOG_V(ERROR, TAG, "cfsetispeed() - ret=%d errno=%d", ret, errno);
         ret = -1;
         goto exit;
     }
@@ -221,7 +221,7 @@ int SetTerminalInfo(int fd, int speed, int parity, int shouldBlock)
     ret = cfsetospeed (&terminalInfo, speed);
     if (ret != 0)
     {
-        OC_LOG_V(ERROR, TAG, "cfsetospeed() - ret=%d errno=%d", ret, errno);
+        OIC_LOG_V(ERROR, TAG, "cfsetospeed() - ret=%d errno=%d", ret, errno);
         ret = -1;
         goto exit;
     }
@@ -253,11 +253,11 @@ int SetTerminalInfo(int fd, int speed, int parity, int shouldBlock)
     ret = tcsetattr (fd, TCSANOW, &terminalInfo);
     if (ret != 0)
     {
-        OC_LOG_V(ERROR, TAG, "tcsetattr - ret=%d errno=%d", ret, errno);
+        OIC_LOG_V(ERROR, TAG, "tcsetattr - ret=%d errno=%d", ret, errno);
         ret = -1;
     }
 
 exit:
-    OC_LOG_V(INFO, TAG, "Leave SetTerminalInfo() with ret=%d", ret);
+    OIC_LOG_V(INFO, TAG, "Leave SetTerminalInfo() with ret=%d", ret);
     return ret;
 }
index 1bea369..3637717 100644 (file)
@@ -30,6 +30,10 @@ Import('env')
 target_os = env.get('TARGET_OS')
 src_dir = env.get('SRC_DIR')
 
+if target_os not in ['tizen']:
+       # Build liblogger
+       SConscript('csdk/logger/SConscript')
+
 if target_os not in ['arduino', 'darwin', 'ios', 'android']:
        env.AppendUnique(LIBS=['rt'])
 
index 4ce7309..d7bce9f 100644 (file)
@@ -23,4 +23,3 @@ compatibilitylib_src = ['OCAndroid.cpp']
 if target_os == 'android':
        static_compatibilitylib = compatibilitylib_env.StaticLibrary('compatibility', compatibilitylib_src)
        compatibilitylib_env.InstallTarget(static_compatibilitylib, 'libcompatibility')
-       compatibilitylib_env.UserInstallTargetLib(static_compatibilitylib, 'libcompatibility')
index a9682b9..a9285ae 100644 (file)
@@ -28,6 +28,7 @@ env.AppendUnique(CPPPATH = [
             os.path.join(Dir('.').abspath),
             os.path.join(Dir('.').abspath, 'oic_malloc/include'),
             os.path.join(Dir('.').abspath, 'oic_string/include'),
+            os.path.join(Dir('.').abspath, 'oic_time/include'),
             os.path.join(Dir('.').abspath, 'ocrandom/include')
         ])
 
@@ -53,6 +54,7 @@ common_env = env.Clone()
 common_src = [
        'oic_string/src/oic_string.c',
        'oic_malloc/src/oic_malloc.c',
+       'oic_time/src/oic_time.c',
        'ocrandom/src/ocrandom.c',
        ]
 
index ff09112..95472b6 100644 (file)
@@ -37,6 +37,7 @@
 #include <sys/time.h>
 #include <time.h>
 #if defined(__ANDROID__)
+#include <ctype.h>
 #include <linux/time.h>
 #endif
 #endif
 #include <uuid/uuid.h>
 #endif
 
+#if !defined(__ANDROID__) || defined(__linux__) || defined(__APPLE__) || defined(__TIZEN__)
+#define NANO_SEC 1000000000
+#endif
+
 #ifdef ARDUINO
 #include "Arduino.h"
 
@@ -105,15 +110,15 @@ int8_t OCSeedRandom()
 #ifdef __ANDROID__
     struct timespec getTs;
     clock_gettime(CLOCK_MONOTONIC, &getTs);
-    currentTime = (getTs.tv_sec * (uint64_t)1000000000 + getTs.tv_nsec)/1000;
+    currentTime = (getTs.tv_sec * (uint64_t)NANO_SEC + getTs.tv_nsec)/1000;
 #elif  _POSIX_TIMERS > 0
     struct timespec ts;
     clock_gettime(CLOCK_MONOTONIC, &ts);
-    currentTime = ts.tv_sec * 1000000 + ts.tv_nsec / 1000;
+    currentTime = (ts.tv_sec * (uint64_t)NANO_SEC + ts.tv_nsec)/ 1000;
 #else
     struct timeval tv;
     gettimeofday(&tv, NULL);
-    currentTime = tv.tv_sec * 1000000 + tv.tv_usec;
+    currentTime = tv.tv_sec * (uint64_t)1000000 + tv.tv_usec;
 #endif
 
     int32_t fd = open("/dev/urandom", O_RDONLY);
index 2c83059..7175f40 100644 (file)
@@ -27,7 +27,7 @@
 // Enable extra debug logging for malloc.  Comment out to disable
 #ifdef ENABLE_MALLOC_DEBUG
 #include "logger.h"
-#define TAG "OICMalloc"
+#define TAG "OIC_MALLOC"
 #endif
 
 //-----------------------------------------------------------------------------
diff --git a/resource/c_common/oic_time/include/oic_time.h b/resource/c_common/oic_time/include/oic_time.h
new file mode 100644 (file)
index 0000000..3ecdd8a
--- /dev/null
@@ -0,0 +1,70 @@
+//******************************************************************
+//
+// Copyright 2015 Intel Mobile Communications GmbH 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef OIC_TIME_H_
+#define OIC_TIME_H_
+
+#include <stdint.h>
+
+#define MS_PER_SEC  (1000)
+#define US_PER_SEC  (1000000)
+#define US_PER_MS   (1000)
+#define NS_PER_US   (1000)
+#define NS_PER_MS   (1000000)
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif // __cplusplus
+
+typedef enum
+{
+    TIME_IN_MS = 0,
+    TIME_IN_US,
+}OICTimePrecision;
+
+/*
+ * If monotonic coarse/monotonic clock supported then gets current time as monotonic time
+ * in milliseconds or microseconds as the elapsed time since some unspecified starting point
+ * else gets current time in milliseconds or microseconds as the elapsed time since the epoch.
+ *
+ * For Arduino gets current time in milliseconds or microseconds since Arduino board begin
+ * running this program.
+ *
+ * @param     precision   based on this parameter, current time is returned in milliseconds or
+ *                        microseconds
+ *
+ * @note
+ *            On Arduino platform:
+ *            if the time precision is in milliseconds then the function will overflow
+ *            (go back to 0) after approximately 50 days.
+ *            if the time precision is in microseconds then the function will overflow
+ *            (go back to 0) after approximately 70minutes.
+ *
+ * @return
+ *         returns current time in milliseconds or microseconds.
+ */
+uint64_t OICGetCurrentTime(OICTimePrecision precision);
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+#endif // OIC_TIME_H_
diff --git a/resource/c_common/oic_time/src/oic_time.c b/resource/c_common/oic_time/src/oic_time.c
new file mode 100644 (file)
index 0000000..2415d42
--- /dev/null
@@ -0,0 +1,93 @@
+//******************************************************************
+//
+// Copyright 2015 Intel Mobile Communications GmbH 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+// Defining _POSIX_C_SOURCE macro with 199309L (or greater) as value
+// causes header files to expose definitions
+// corresponding to the POSIX.1b, Real-time extensions
+// (IEEE Std 1003.1b-1993) specification
+//
+// For this specific file, see use of clock_gettime,
+// Refer to http://pubs.opengroup.org/stage7tc1/functions/clock_gettime.html
+// and to http://man7.org/linux/man-pages/man2/clock_gettime.2.html
+#ifndef _POSIX_C_SOURCE
+#define _POSIX_C_SOURCE 200809L
+#endif
+
+#include "oic_time.h"
+
+#include <stddef.h>        // For NULL
+
+#ifndef WITH_ARDUINO
+# if _POSIX_TIMERS > 0
+#  include <time.h>        // For clock_gettime()
+# else
+#  include <sys/time.h>    // For gettimeofday()
+# endif  // _POSIX_TIMERS > 0
+#endif
+
+#define TAG "OIC_TIME"
+
+uint64_t OICGetCurrentTime(OICTimePrecision precision)
+{
+    uint64_t currentTime = 0;
+
+#ifdef WITH_ARDUINO
+    currentTime = (TIME_IN_MS == precision) ? millis() : micros();
+#else
+# if _POSIX_TIMERS > 0
+#   if defined(CLOCK_MONOTONIC_COARSE)
+    static const clockid_t clockId = CLOCK_MONOTONIC_COARSE;
+#   elif _POSIX_MONOTONIC_CLOCK >= 0
+    // Option _POSIX_MONOTONIC_CLOCK == 0 indicates that the option is
+    // available at compile time but may not be supported at run
+    // time.  Check if option _POSIX_MONOTONIC_CLOCK is supported at
+    // run time.
+#     if _POSIX_MONOTONIC_CLOCK == 0
+    static const clockid_t clockId =
+        sysconf(_SC_MONOTONIC_CLOCK) > 0 ? CLOCK_MONOTONIC : CLOCK_REALTIME;
+#     else
+    static const clockid_t clockId = CLOCK_MONOTONIC;
+#     endif  // _POSIX_MONOTONIC_CLOCK == 0
+#   else
+    static const clockid_t clockId = CLOCK_REALTIME;
+#   endif  // CLOCK_MONOTONIC_COARSE
+
+    struct timespec current = { .tv_sec = 0, .tv_nsec = 0 };
+    if (clock_gettime(clockId, &current) == 0)
+    {
+        currentTime =
+            (TIME_IN_MS == precision)
+            ? (((uint64_t) current.tv_sec * MS_PER_SEC) + (current.tv_nsec / NS_PER_MS))
+            : (((uint64_t) current.tv_sec * US_PER_SEC) + (current.tv_nsec / NS_PER_US));
+    }
+# else
+    struct timeval current = { .tv_sec = 0, .tv_usec = 0 };
+    if (gettimeofday(&current, NULL) == 0)
+    {
+        currentTime =
+            (TIME_IN_MS == precision)
+            ? (((uint64_t) current.tv_sec * MS_PER_SEC) + (current.tv_usec / US_PER_MS))
+            : (((uint64_t) current.tv_sec * US_PER_SEC) + (current.tv_usec));
+    }
+# endif  // _POSIX_TIMERS > 0
+#endif  // WITH_ARDUINO
+
+    return currentTime;
+}
diff --git a/resource/c_common/oic_time/test/SConscript b/resource/c_common/oic_time/test/SConscript
new file mode 100644 (file)
index 0000000..222b9e8
--- /dev/null
@@ -0,0 +1,58 @@
+#******************************************************************
+#
+# Copyright 2015 Intel Mobile Communications GmbH 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+
+Import('env')
+import os
+
+
+timetest_env = env.Clone()
+src_dir = timetest_env.get('SRC_DIR')
+
+######################################################################
+# Build flags
+######################################################################
+timetest_env.PrependUnique(CPPPATH = [
+        '../include',
+        '#extlibs/gtest/gtest-1.7.0/include' ])
+
+timetest_env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource/c_common')])
+timetest_env.AppendUnique(LIBPATH = [src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs'])
+timetest_env.PrependUnique(LIBS = ['c_common', 'gtest', 'gtest_main', 'pthread'])
+timetest_env.Append(LIBS = ['rt']);
+
+if env.get('LOGGING'):
+    timetest_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+#
+######################################################################
+# Source files and Targets
+######################################################################
+timetests = timetest_env.Program('timetests', ['linux/oic_time_tests.cpp'])
+
+Alias("test", [timetests])
+
+env.AppendTarget('test')
+if env.get('TEST') == '1':
+    target_os = env.get('TARGET_OS')
+    if target_os == 'linux':
+                from tools.scons.RunTest import *
+                run_test(timetest_env,
+                         'resource_ccommon_time_test.memcheck',
+                         'resource/c_common/oic_time/test/timetests')
diff --git a/resource/c_common/oic_time/test/linux/oic_time_tests.cpp b/resource/c_common/oic_time/test/linux/oic_time_tests.cpp
new file mode 100644 (file)
index 0000000..4e98ef2
--- /dev/null
@@ -0,0 +1,37 @@
+//******************************************************************
+//
+// Copyright 2015 Intel Mobile Communications GmbH 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 "oic_time.h"
+#include "gtest/gtest.h"
+#include <stdint.h>
+
+// Tests to get current time in milli seconds
+TEST(TimeTests, GetCurrentTimeInMilliSec)
+{
+    uint64_t  currentMilliSecTime = OICGetCurrentTime(TIME_IN_MS);
+    EXPECT_TRUE(0 != currentMilliSecTime);
+}
+
+//Test to get current time in micro seconds
+TEST(TimeTests, GetCurrentTimeInMicroSec)
+{
+    uint64_t currentMicroSecTime = OICGetCurrentTime(TIME_IN_US);
+    EXPECT_TRUE(0 != currentMicroSecTime);
+}
index de89c45..37dc29b 100644 (file)
@@ -30,6 +30,8 @@ liboctbstack_env = lib_env.Clone()
 
 target_os = env.get('TARGET_OS')
 with_ra = env.get('WITH_RA')
+with_ra_ibb = env.get('WITH_RA_IBB')
+with_tcp = env.get('WITH_TCP')
 # As in the source code, it includes arduino Time library (C++)
 # It requires compile the .c with g++
 if target_os == 'arduino':
@@ -47,15 +49,15 @@ liboctbstack_env.PrependUnique(CPPPATH = [
                'stack/include/internal',
                '../oc_logger/include',
                'connectivity/lib/libcoap-4.1.1',
+               'connectivity/common/inc',
                'connectivity/inc',
                'connectivity/api',
                'connectivity/external/inc',
                'security/include',
                'security/include/internal',
+               'security/provisioning/include',
                ])
 
-liboctbstack_env.AppendUnique(LIBS = ['ocsrm'])
-
 if target_os not in ['arduino', 'windows', 'winrt']:
        liboctbstack_env.AppendUnique(CPPDEFINES  = ['WITH_POSIX'])
        liboctbstack_env.AppendUnique(CFLAGS = ['-std=c99'])
@@ -73,10 +75,14 @@ liboctbstack_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 if target_os in ['android', 'linux', 'tizen']:
        liboctbstack_env.PrependUnique(LIBS = ['connectivity_abstraction'])
 
-       if with_ra:
-               liboctbstack_env.AppendUnique(LIBS = ['ra_xmpp'])
+       if with_ra_ibb:
+               liboctbstack_env.AppendUnique(LIBS = liboctbstack_env['RALIBS'], LIBPATH = liboctbstack_env['RALIBPATH'], RPATH = liboctbstack_env['RARPATH'])
+       else :
+               if with_ra:
+                       liboctbstack_env.AppendUnique(LIBS = ['ra_xmpp'])
 
 liboctbstack_env.AppendUnique(LIBS = ['coap', 'm'])
+liboctbstack_env.PrependUnique(LIBS = ['ocsrm'])
 
 if target_os in ['tizen', 'linux']:
        liboctbstack_env.ParseConfig("pkg-config --cflags --libs uuid")
@@ -104,6 +110,11 @@ if env.get('LOGGING'):
 if env.get('DTLS_WITH_X509') == '1':
        liboctbstack_env.AppendUnique(CPPDEFINES = ['__WITH_X509__'])
 
+if env.get('WITH_RD') == '1':
+       liboctbstack_env.PrependUnique(CPPPATH = ['../../service/resource-directory/include'])
+       liboctbstack_env.AppendUnique(CPPDEFINES = ['-DWITH_RD'])
+       liboctbstack_env.AppendUnique(LIBS = ['resource_directory'])
+
 liboctbstack_env.Append(LIBS = ['c_common'])
 
 if liboctbstack_env.get('ROUTING') in ['GW', 'EP']:
@@ -126,10 +137,12 @@ liboctbstack_src = [
        OCTBSTACK_SRC + 'ocserverrequest.c',
        OCTBSTACK_SRC + 'occollection.c',
        OCTBSTACK_SRC + 'oicgroup.c',
-       'logger/src/logger.c',
        OCTBSTACK_SRC + "rdpayload.c"
        ]
 
+if with_tcp == True:
+       liboctbstack_src.append(OCTBSTACK_SRC + 'oickeepalive.c')
+
 liboctbstack_src.extend(env['cbor_files'])
 
 if target_os in ['arduino','darwin','ios'] :
@@ -147,4 +160,3 @@ else:
        liboctbstack_env.UserInstallTargetHeader('stack/include/octypes.h', 'resource', 'octypes.h')
        liboctbstack_env.UserInstallTargetHeader('stack/include/ocstack.h', 'resource', 'ocstack.h')
        liboctbstack_env.UserInstallTargetHeader('stack/include/ocpresence.h', 'resource', 'ocpresence.h')
-
index 5de9342..893dc5c 100644 (file)
@@ -31,6 +31,8 @@ if 'ALL' in transport:
                env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','NO_EDR_ADAPTER','LE_ADAPTER'])
        elif target_os == 'tizen':
                env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','EDR_ADAPTER','LE_ADAPTER'])
+       elif target_os == 'android':
+               env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','EDR_ADAPTER','LE_ADAPTER', 'NFC_ADAPTER'])
        elif target_os in['darwin','ios']:
                env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','NO_EDR_ADAPTER','NO_LE_ADAPTER'])
        else:
@@ -60,8 +62,8 @@ else:
                env.AppendUnique(CPPDEFINES = ['NO_IP_ADAPTER'])
 
        if with_tcp == True:
-               if target_os in ['linux', 'tizen']:
-                       env.AppendUnique(CPPDEFINES = ['TCP_ADAPTER'])
+               if target_os in ['linux', 'tizen', 'android']:
+                       env.AppendUnique(CPPDEFINES = ['TCP_ADAPTER', 'WITH_TCP'])
                        print "CA Transport is TCP"
                else:
                        print "CA Transport TCP is not supported "
@@ -69,6 +71,16 @@ else:
        else:
                env.AppendUnique(CPPDEFINES = ['NO_TCP_ADAPTER'])
 
+       if 'NFC' in transport:
+               if target_os in['android']:
+                       env.AppendUnique(CPPDEFINES = ['NFC_ADAPTER'])
+                       print "CA Transport is NFC"
+               else:
+                       print "CA Transport NFC is not supported "
+                       Exit(1)
+       else:
+               env.AppendUnique(CPPDEFINES = ['NO_NFC_ADAPTER'])
+
 env.SConscript('./src/SConscript')
 
 if build_sample == 'ON':
index b85364c..464f24b 100644 (file)
 #ifndef CA_COMMON_H_
 #define CA_COMMON_H_
 
+#ifdef TCP_ADAPTER
+#define HAVE_SYS_POLL_H
+#endif
+
 #include <stdint.h>
 #include <stdlib.h>
 #include <stdbool.h>
 
+#ifdef HAVE_SYS_POLL_H
+#include <sys/poll.h>
+#endif
 
 #ifdef __cplusplus
 extern "C"
@@ -141,7 +148,9 @@ typedef enum
     CA_ADAPTER_REMOTE_ACCESS = (1 << 3),   // Remote Access over XMPP.
 #endif
 
-    CA_ADAPTER_TCP = (1 << 4),   // CoAP over TCP
+    CA_ADAPTER_TCP           = (1 << 4),   // CoAP over TCP
+    CA_ADAPTER_NFC           = (1 << 5),   // NFC Adapter
+
     CA_ALL_ADAPTERS          = 0xffffffff
 } CATransportAdapter_t;
 
@@ -276,6 +285,7 @@ typedef enum
     CA_DESTINATION_DISCONNECTED,    /**< Destination is disconnected */
     CA_NOT_SUPPORTED,               /**< Not supported */
     CA_STATUS_NOT_INITIALIZED,      /**< Not Initialized*/
+    CA_DTLS_AUTHENTICATION_FAILURE, /**< Decryption error in DTLS */
     CA_STATUS_FAILED =255           /**< Failure */
     /* Result code - END HERE */
 } CAResult_t;
@@ -424,22 +434,6 @@ typedef struct
 } CAErrorInfo_t;
 
 /**
- * CA Remote Access information for XMPP Client
- *
- */
-typedef struct
-{
-    char *hostname;     /**< XMPP server hostname */
-    uint16_t port;      /**< XMPP server serivce port */
-    char *xmpp_domain;  /**< XMPP login domain */
-    char *username;     /**< login username */
-    char *password;     /**< login password */
-    char *resource;     /**< specific resource for login */
-    char *user_jid;     /**< specific JID for login */
-} CARAInfo_t;
-
-
-/**
  * Hold global variables for CA layer (also used by RI layer)
  */
 typedef struct
@@ -511,9 +505,6 @@ typedef struct
     struct calayer
     {
         CAHistory_t requestHistory;  /**< filter IP family in requests */
-        CAHistory_t responseHistory; /**< filter IP family in responses */
-        CATransportFlags_t previousRequestFlags;/**< address family filtering */
-        uint16_t previousRequestMessageId;      /**< address family filtering */
     } ca;
 
 #ifdef TCP_ADAPTER
@@ -526,6 +517,8 @@ typedef struct
         void *svrlist;          /**< unicast IPv4 TCP server information*/
         int selectTimeout;      /**< in seconds */
         int listenBacklog;      /**< backlog counts*/
+        int shutdownFds[2];     /**< shutdown pipe */
+        int connectionFds[2];   /**< connection pipe */
         int maxfd;              /**< highest fd (for select) */
         bool started;           /**< the TCP adapter has started */
         bool terminate;         /**< the TCP adapter needs to stop */
@@ -536,6 +529,38 @@ typedef struct
 
 extern CAGlobals_t caglobals;
 
+/**
+ * Callback function type for request delivery.
+ * @param[out]   object       Endpoint object from which the request is received.
+ *                            It contains endpoint address based on the connectivity type.
+ * @param[out]   requestInfo  Info for resource model to understand about the request.
+ */
+typedef void (*CARequestCallback)(const CAEndpoint_t *object,
+                                  const CARequestInfo_t *requestInfo);
+
+/**
+ * Callback function type for response delivery.
+ * @param[out]   object           Endpoint object from which the response is received.
+ * @param[out]   responseInfo     Identifier which needs to be mapped with response.
+ */
+typedef void (*CAResponseCallback)(const CAEndpoint_t *object,
+                                   const CAResponseInfo_t *responseInfo);
+/**
+ * Callback function type for error.
+ * @param[out]   object           remote device information.
+ * @param[out]   errorInfo        CA Error information.
+ */
+typedef void (*CAErrorCallback)(const CAEndpoint_t *object,
+                                const CAErrorInfo_t *errorInfo);
+
+/**
+ * Callback function type for network status changes delivery from CA common logic.
+ * @param[out]   info       Endpoint object from which the network status is changed.
+ *                          It contains endpoint address based on the connectivity type.
+ * @param[out]   status     Current network status info.
+ */
+typedef void (*CANetworkMonitorCallback)(const CAEndpoint_t *info, CANetworkStatus_t status);
+
 #ifdef __cplusplus
 } /* extern "C" */
 #endif
index d82b67b..a253846 100644 (file)
@@ -38,31 +38,55 @@ extern "C"
 {
 #endif
 
+#ifdef RA_ADAPTER
+
 /**
- * Callback function type for request delivery.
- * @param[out]   object       Endpoint object from which the request is received.
- *                            It contains endpoint address based on the connectivity type.
- * @param[out]   requestInfo  Info for resource model to understand about the request.
+ * Callback for bound JID
+ * @param[out]   jid           Boud Jabber Identifier.
  */
-typedef void (*CARequestCallback)(const CAEndpoint_t *object,
-                                  const CARequestInfo_t *requestInfo);
+typedef void (*CAJidBoundCallback)(char *jid);
+
+/**
+ * CA Remote Access information for XMPP Client
+ *
+ */
+typedef struct
+{
+    char *hostName;     /**< XMPP server hostname */
+    uint16_t port;      /**< XMPP server serivce port */
+    char *xmppDomain;  /**< XMPP login domain */
+    char *userName;     /**< login username */
+    char *password;     /**< login password */
+    char *resource;     /**< specific resource for login */
+    char *userJid;     /**< specific JID for login */
+    CAJidBoundCallback jidBoundCallback;  /**< callback when JID bound */
+} CARAInfo_t;
 
+#endif //RA_ADAPTER
+
+#ifdef TCP_ADAPTER
 /**
- * Callback function type for response delivery.
- * @param[out]   object           Endpoint object from which the response is received.
- * @param[out]   responseInfo     Identifier which needs to be mapped with response.
+ * Callback function to pass the connection information from CA to RI.
+ * @param[out]   object           remote device information.
  */
-typedef void (*CAResponseCallback)(const CAEndpoint_t *object,
-                                   const CAResponseInfo_t *responseInfo);
+typedef void (*CAKeepAliveConnectedCallback)(const CAEndpoint_t *object);
+
 /**
- * Callback function type for error.
+ * Callback function to pass the disconnection information from CA to RI.
  * @param[out]   object           remote device information.
- * @param[out]   errorInfo        CA Error information.
  */
-typedef void (*CAErrorCallback)(const CAEndpoint_t *object,
-                                const CAErrorInfo_t *errorInfo);
+typedef void (*CAKeepAliveDisconnectedCallback)(const CAEndpoint_t *object);
 
 /**
+ * Register connected callback and disconnected callback to process KeepAlive.
+ * connection informations are delivered these callbacks.
+ * @param[in]   ConnHandler     Connected callback.
+ * @param[in]   DisconnHandler  Disconnected Callback.
+ */
+void CARegisterKeepAliveHandler(CAKeepAliveConnectedCallback ConnHandler,
+                                CAKeepAliveDisconnectedCallback DisconnHandler);
+#endif
+/**
  * Initialize the connectivity abstraction module.
  * It will initialize adapters, thread pool and other modules based on the platform
  * compilation options.
@@ -81,14 +105,14 @@ void CATerminate();
  * Starts listening servers.
  * This API is used by resource hosting server for listening multicast requests.
  * Based on the adapters configurations, different kinds of servers are started.
- * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED
+ * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED or ::CA_STATUS_NOT_INITIALIZED
  */
 CAResult_t CAStartListeningServer();
 
 /**
  * Stops the server from receiving the multicast traffic. This is used by sleeping
  * device to not receives the multicast traffic.
- * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED
+ * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED or ::CA_STATUS_NOT_INITIALIZED
  */
 CAResult_t CAStopListeningServer();
 
@@ -96,7 +120,7 @@ CAResult_t CAStopListeningServer();
  * Starts discovery servers.
  * This API is used by resource required clients for listening multicast requests.
  * Based on the adapters configurations, different kinds of servers are started.
- * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED
+ * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED or ::CA_STATUS_NOT_INITIALIZED
  */
 CAResult_t CAStartDiscoveryServer();
 
@@ -105,6 +129,7 @@ CAResult_t CAStartDiscoveryServer();
  *          Requests and responses are delivered these callbacks.
  * @param[in]   ReqHandler    Request callback ( for GET,PUT ..etc).
  * @param[in]   RespHandler   Response Handler Callback.
+ * @param[in]   ErrorHandler  Error Handler Callback.
  * @see     CARequestCallback
  * @see     CAResponseCallback
  * @see     CAErrorCallback
@@ -118,8 +143,8 @@ void CARegisterHandler(CARequestCallback ReqHandler, CAResponseCallback RespHand
  * @param[in]   adapter               which adapter to use.
  * @param[in]   addr                  string representation of address.
  * @param[in]   port                  port (for IP_ADAPTER).
- * @param[in]   endpoint              Endpoint which contains the above.
- * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED
+ * @param[out]  object                Endpoint which contains the above.
+ * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED or ::CA_STATUS_INVALID_PARAM
  * @remark  The created Remote endpoint can be freed using CADestroyEndpoint().
  * @see     CADestroyEndpoint
  */
@@ -137,10 +162,10 @@ void CADestroyEndpoint(CAEndpoint_t *object);
 
 /**
  * Generating the token for matching the request and response.
- * @param[in]   token            Token for the request.
+ * @param[out]  token            Token for the request.
  * @param[in]   tokenLength      length of the token.
  * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED or
- *          ::CA_MEMORY_ALLOC_FAILED or ::CA_STATUS_NOT_INITIALIZED
+ *          ::CA_MEMORY_ALLOC_FAILED or ::CA_STATUS_INVALID_PARAM
  * @remark  Token memory is destroyed by the caller using CADestroyToken().
  * @see     CADestroyToken
  */
@@ -157,7 +182,8 @@ void CADestroyToken(CAToken_t token);
  * @param[in]   object       Endpoint where the payload need to be sent.
  *                           This endpoint is delivered with Request or response callback.
  * @param[in]   requestInfo  Information for the request.
- * @return  ::CA_STATUS_OK ::CA_STATUS_FAILED ::CA_MEMORY_ALLOC_FAILED
+ * @return ::CA_STATUS_OK or ::CA_STATUS_FAILED or ::CA_STATUS_NOT_INITIALIZED or
+           ::CA_SEND_FAILED or ::CA_STATUS_INVALID_PARAM or ::CA_MEMORY_ALLOC_FAILED
  */
 CAResult_t CASendRequest(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo);
 
@@ -166,22 +192,24 @@ CAResult_t CASendRequest(const CAEndpoint_t *object, const CARequestInfo_t *requ
  * @param[in]   object           Endpoint where the payload need to be sent.
  *                               This endpoint is delivered with Request or response callback.
  * @param[in]   responseInfo     Information for the response.
- * @return  ::CA_STATUS_OK or  ::CA_STATUS_FAILED or ::CA_MEMORY_ALLOC_FAILED
+ * @return ::CA_STATUS_OK or ::CA_STATUS_FAILED or ::CA_STATUS_NOT_INITIALIZED or
+           ::CA_SEND_FAILED or ::CA_STATUS_INVALID_PARAM or ::CA_MEMORY_ALLOC_FAILED
  */
 CAResult_t CASendResponse(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo);
 
 /**
  * Select network to use.
  * @param[in]   interestedNetwork    Connectivity Type enum.
- * @return  ::CA_STATUS_OK or ::CA_NOT_SUPPORTED or
- *          ::CA_STATUS_FAILED or ::CA_NOT_SUPPORTED
+ * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED or ::CA_STATUS_NOT_INITIALIZED or
+ *          ::CA_NOT_SUPPORTED or ::CA_ADAPTER_NOT_ENABLED or ::CA_MEMORY_ALLOC_FAILED
  */
 CAResult_t CASelectNetwork(CATransportAdapter_t interestedNetwork);
 
 /**
  * Select network to unuse.
  * @param[in]   nonInterestedNetwork     Connectivity Type enum.
- * @return  ::CA_STATUS_OK or ::CA_NOT_SUPPORTED or ::CA_STATUS_FAILED
+ * @return  ::CA_STATUS_OK or ::CA_NOT_SUPPORTED or ::CA_STATUS_FAILED or
+            ::CA_STATUS_NOT_INITIALIZED
  */
 CAResult_t CAUnSelectNetwork(CATransportAdapter_t nonInterestedNetwork);
 
@@ -190,14 +218,14 @@ CAResult_t CAUnSelectNetwork(CATransportAdapter_t nonInterestedNetwork);
  * It should be destroyed by the caller as it Get Information.
  * @param[out]   info     LocalConnectivity objects
  * @param[out]   size     No Of Array objects
- * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED or
+ * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED or ::CA_STATUS_NOT_INITIALIZED or
  *          ::CA_STATUS_INVALID_PARAM or ::CA_MEMORY_ALLOC_FAILED
  */
 CAResult_t CAGetNetworkInformation(CAEndpoint_t **info, uint32_t *size);
 
 /**
  * To Handle the Request or Response.
- * @return   ::CA_STATUS_OK
+ * @return   ::CA_STATUS_OK or ::CA_STATUS_NOT_INITIALIZED
  */
 CAResult_t CAHandleRequestResponse();
 
@@ -206,7 +234,7 @@ CAResult_t CAHandleRequestResponse();
  * Set Remote Access information for XMPP Client.
  * @param[in]   caraInfo          remote access info.
  *
- * @return  ::CA_STATUS_OK
+ * @return  ::CA_STATUS_OK or ::CA_STATUS_INVALID_PARAM
  */
 CAResult_t CASetRAInfo(const CARAInfo_t *caraInfo);
 #endif
index fb8afdb..3d12870 100644 (file)
@@ -31,6 +31,7 @@
 #include "pki.h"
 #endif //__WITH_X509__
 
+#include "cacommon.h"
 
 #ifdef __cplusplus
 extern "C"
@@ -65,9 +66,16 @@ typedef enum
  * @return The number of bytes written to @p result or a value
  *         less than zero on error.
  */
-typedef int (*CAGetDTLSPskCredentialsHandler)( CADtlsPskCredType_t type,
-                     const unsigned char *desc, size_t desc_len,
-                     unsigned char *result, size_t result_length);
+typedef int (*CAGetDTLSPskCredentialsHandler)(CADtlsPskCredType_t type,
+                     const uint8_t *desc, size_t desc_len,
+                     uint8_t *result, size_t result_length);
+
+/**
+ * Register callback to receive the result of DTLS handshake.
+ * @param[in] dtlsHandshakeCallback callback for get dtls handshake result
+ * @return ::CA_STATUS_OK
+ */
+CAResult_t CARegisterDTLSHandshakeCallback(CAErrorCallback dtlsHandshakeCallback);
 
 /**
  * Register callback to get DTLS PSK credentials.
diff --git a/resource/csdk/connectivity/api/cautilinterface.h b/resource/csdk/connectivity/api/cautilinterface.h
new file mode 100644 (file)
index 0000000..cdd377b
--- /dev/null
@@ -0,0 +1,125 @@
+/* ****************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef CA_UTILS_INTERFACE_H_
+#define CA_UTILS_INTERFACE_H_
+
+#include "cacommon.h"
+#ifdef __ANDROID__
+#include "jni.h"
+#endif
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * Callback function type for connection status changes delivery.
+ */
+typedef void (*CAConnectionStateChangedCB)(CATransportAdapter_t adapter,
+        const char *remote_address, bool connected);
+
+/**
+ * Callback function type for adapter status changes delivery.
+ * @param[out]   adapter    Transport type information.
+ * @param[out]   enabled    Current adapter status info.
+ */
+typedef void (*CAAdapterStateChangedCB)(CATransportAdapter_t adapter, bool enabled);
+
+/**
+ * Register network monitoring callback.
+ * Network status changes are delivered these callback.
+ * @param[in]   adapterStateCB  Adapter state monitoring callback.
+ * @param[in]   connStateCB     Connection state monitoring callback.
+ *
+ * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED or ::CA_MEMORY_ALLOC_FAILED
+ */
+CAResult_t CARegisterNetworkMonitorHandler(CAAdapterStateChangedCB adapterStateCB,
+                                           CAConnectionStateChangedCB connStateCB);
+
+/**
+ * Set device to handle for auto connection.
+ * @param[in]   address         LE address to set.
+ *
+ * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED.
+ */
+CAResult_t CASetAutoConnectionDeviceInfo(const char* address);
+
+/**
+ * Unset device to handle for auto connection.
+ * @param[in]   address         LE address to unset.
+ *
+ * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED.
+ */
+CAResult_t CAUnsetAutoConnectionDeviceInfo(const char* address);
+
+#ifdef __ANDROID__
+/**
+ * initialize util client for android
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   jvm                   invocation inferface for JAVA virtual machine.
+ * @param[in]   context               application context.
+ *
+ * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED or ::CA_MEMORY_ALLOC_FAILED
+ */
+CAResult_t CAUtilClientInitialize(JNIEnv *env, JavaVM *jvm, jobject context);
+
+/**
+ * terminate util client for android
+ * @param[in]   env                   JNI interface pointer.
+ *
+ * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED or ::CA_MEMORY_ALLOC_FAILED
+ */
+CAResult_t CAUtilClientTerminate(JNIEnv *env);
+
+// BT pairing
+/**
+ * start discovery for BT device which has iotivity UUID.
+ * @param[in]  env              JNI interface pointer.
+ */
+CAResult_t CAUtilStartScan(JNIEnv *env);
+
+/**
+ * stop discovery
+ * @param[in]  env              JNI interface pointer.
+ */
+CAResult_t CAUtilStopScan(JNIEnv *env);
+
+/**
+ * bonding between devices.
+ * @param[in]  env              JNI interface pointer.
+ * @param[in]  device           bluetooth device object.
+ */
+CAResult_t CAUtilCreateBond(JNIEnv *env, jobject device);
+
+
+/**
+ * set callback listener of found device.
+ * @param[in]  listener         callback listener
+ */
+void CAUtilSetFoundDeviceListener(jobject listener);
+#endif
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* CA_UTILS_INTERFACE_H_ */
+
index 953f3f3..e829d4b 100644 (file)
@@ -175,17 +175,13 @@ def __installlib(ienv, targets, name):
        user_prefix = env.get('PREFIX')
        if user_prefix:
                i_n = ienv.Install(user_prefix + '/lib', targets)
-       else:
-               i_n = ienv.Install(env.get('BUILD_DIR'), targets)
-       ienv.Alias("install", i_n)
+               ienv.Alias("install", i_n)
 
 def __installbin(ienv, targets, name):
        user_prefix = env.get('PREFIX')
        if user_prefix:
                i_n = ienv.Install(user_prefix + '/bin', targets)
-       else:
-               i_n = ienv.Install(env.get('BUILD_DIR'), targets)
-       ienv.Alias("install", i_n)
+               ienv.Alias("install", i_n)
 
 def __append_target(ienv, target):
        env.AppendUnique(TS = [target])
index ed86105..efbf64f 100644 (file)
@@ -32,11 +32,12 @@ OIC_C_COMMON_PATH           = $(ROOT_DIR_PATH)/resource/c_common
 EDR             = EDR_ADAPTER
 IP              = IP_ADAPTER
 LE              = LE_ADAPTER
+NFC             = NFC_ADAPTER
 
 #Add Pre processor definitions
 DEFINE_FLAG =  -DWITH_POSIX -D__ANDROID__
 DEFINE_FLAG +=  -D__WITH_DTLS__
-DEFINE_FLAG += -D$(EDR) -D$(LE) -D$(IP)
+DEFINE_FLAG += -D$(EDR) -D$(LE) -D$(IP) -D$(NFC)
 
 #Add Debug flags here
 DEBUG_FLAG      = -DTB_LOG
@@ -46,30 +47,6 @@ BUILD_FLAG.release      =       $(DEFINE_FLAG)
 BUILD_FLAG = $(BUILD_FLAG.$(BUILD))
 
 #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-#include glib
-
-#include $(CLEAR_VARS)
-#LOCAL_PATH = $(PROJECT_LIB_PATH)/android
-#LOCAL_MODULE = Glib
-#LOCAL_SRC_FILES := libglib-2.40.2.so
-#LOCAL_EXPORT_C_INCLUDES = $(GLIB_PATH) \
-#                          $(GLIB_PATH)/glib
-#
-#include $(PREBUILT_SHARED_LIBRARY)
-
-#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-#include glibthread
-
-#include $(CLEAR_VARS)
-#LOCAL_PATH = $(PROJECT_LIB_PATH)/android
-#LOCAL_MODULE = GLibThread
-#LOCAL_SRC_FILES := libgthread-2.40.2.so
-#LOCAL_EXPORT_C_INCLUDES = $(GLIB_PATH) \
-#                          $(GLIB_PATH)/glib
-#
-#include $(PREBUILT_SHARED_LIBRARY)
-
-#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 #Build TinyDtls
 
 include $(CLEAR_VARS)
@@ -174,7 +151,6 @@ LOCAL_SRC_FILES = \
                 camessagehandler.c canetworkconfigurator.c caprotocolmessage.c \
                 caretransmission.c caqueueingthread.c cablockwisetransfer.c \
                 $(ADAPTER_UTILS)/caadapternetdtls.c $(ADAPTER_UTILS)/caadapterutils.c \
-                $(ADAPTER_UTILS)/cafragmentation.c \
                 bt_le_adapter/caleadapter.c $(LE_ADAPTER_PATH)/caleclient.c \
                 $(LE_ADAPTER_PATH)/caleserver.c $(LE_ADAPTER_PATH)/caleutils.c \
                 $(LE_ADAPTER_PATH)/calenwmonitor.c \
@@ -183,5 +159,6 @@ LOCAL_SRC_FILES = \
                 $(EDR_ADAPTER_PATH)/caedrnwmonitor.c \
                 $(IP_ADAPTER_PATH)/caipadapter.c $(IP_ADAPTER_PATH)/caipserver.c \
                 $(IP_ADAPTER_PATH)/android/caipnwmonitor.c \
+                nfc_adapter/canfcadapter.c nfc_adapter/android/canfcserver.c
 
 include $(BUILD_STATIC_LIBRARY)
index 7227798..e1786e8 100755 (executable)
@@ -95,7 +95,7 @@ CORE_CPPOBJ = CDC.cpp.o HardwareSerial.cpp.o HardwareSerial0.cpp.o HardwareSeria
               main.cpp.o new.cpp.o Print.cpp.o Stream.cpp.o Tone.cpp.o USBCore.cpp.o WMath.cpp.o WString.cpp.o
 SPI_OBJ = SPI.cpp.o
 LOGGER_OBJ = logger.c.o oic_logger.c.o oic_console_logger.c.o oic_malloc.c.o oic_string.c.o uarraylist.c.o
-UTIL_OBJ = caadapterutils.c.o cafragmentation.c.o
+UTIL_OBJ = caadapterutils.c.o
 CACOMMON_OBJ = caconnectivitymanager_singlethread.c.o cainterfacecontroller_singlethread.c.o camessagehandler_singlethread.c.o canetworkconfigurator_singlethread.c.o caprotocolmessage_singlethread.c.o \
                           caremotehandler.c.o caretransmission_singlethread.c.o
 
index 6ab0e87..14c6f90 100755 (executable)
@@ -50,14 +50,14 @@ cp -R $cur_dir/src/bt_edr_adapter/SConscript $sourcedir/tmp/con/src/bt_edr_adapt
 cp -R $cur_dir/common/SConscript $sourcedir/tmp/con/common/
 cp -R $cur_dir/lib/libcoap-4.1.1/SConscript $sourcedir/tmp/con/lib/libcoap-4.1.1/
 cp -R $cur_dir/samples/tizen/ $sourcedir/tmp/con/sample/
-mkdir -p $sourcedir/tmp/con/sample/lib/tizen/ble/libs
-cp -R $cur_dir/lib/tizen/ble/libs/* $sourcedir/tmp/con/sample/lib/tizen/ble/libs/
 mkdir -p $sourcedir/tmp/con/sample/external/inc
 cp -R $cur_dir/external/inc/* $sourcedir/tmp/con/sample/external/inc/
 mkdir -p $sourcedir/tmp/con/extlibs/
 cp -R ./extlibs/tinydtls/ $sourcedir/tmp/con/extlibs/
+cp -R ./extlibs/timer/ $sourcedir/tmp/con/extlibs/
 mkdir -p $sourcedir/tmp/con/c_common
 cp -R ./resource/c_common/* $sourcedir/tmp/con/c_common/
+cp -R ./resource/csdk/logger/include/* $sourcedir/tmp/con/common/inc/
 
 # copy dependency RPMs and conf files for tizen build
 cp ./tools/tizen/*.rpm $sourcedir/tmp
@@ -94,7 +94,7 @@ if [ ! -d .git ]; then
 fi
 
 echo "Calling core gbs build command"
-gbscommand="gbs build -A armv7l --include-all  --repository ./ --define 'TARGET_TRANSPORT $1' --define 'SECURED $2' --define 'RELEASE $4' --define 'LOGGING $5' --define 'WITH_TCP $6'"
+gbscommand="gbs build -A armv7l -B ~/GBS-ROOT-OIC --include-all  --repository ./ --define 'TARGET_TRANSPORT $1' --define 'SECURED $2' --define 'RELEASE $4' --define 'LOGGING $5' --define 'WITH_TCP $6'"
 echo $gbscommand
 if eval $gbscommand; then
    echo "Core build is successful"
@@ -117,7 +117,7 @@ if echo $BUILD_SAMPLE|grep -qi '^ON$'; then
       git commit -m "Initial commit"
    fi
    echo "Calling sample gbs build command"
-   gbscommand="gbs build -A armv7l --include-all --define 'TARGET_TRANSPORT $1' --define 'SECURED $2' --define 'RELEASE $4' --define 'LOGGING $5' --repository ./"
+   gbscommand="gbs build -A armv7l -B ~/GBS-ROOT-OIC --include-all --define 'TARGET_TRANSPORT $1' --define 'SECURED $2' --define 'RELEASE $4' --define 'LOGGING $5' --repository ./"
    echo $gbscommand
    if eval $gbscommand; then
       echo "Sample build is successful"
index 8c3a25b..1346ff9 100644 (file)
@@ -49,11 +49,13 @@ fi
 cp -rf %{ROOTDIR}/con/api/cacommon.h* %{DEST_INC_DIR}/
 cp -rf %{ROOTDIR}/con/inc/caadapterinterface.h* %{DEST_INC_DIR}/
 cp -rf %{ROOTDIR}/con/common/inc/cathreadpool.h* %{DEST_INC_DIR}/
+cp -rf %{ROOTDIR}/con/util/inc/camanagerleinterface.h* %{DEST_INC_DIR}/
 cp -rf %{ROOTDIR}/con/inc/caipadapter.h* %{DEST_INC_DIR}/
 cp -rf %{ROOTDIR}/con/inc/caedradapter.h* %{DEST_INC_DIR}/
 cp -rf %{ROOTDIR}/con/inc/caleadapter.h* %{DEST_INC_DIR}/
 cp -rf %{ROOTDIR}/con/api/cainterface.h* %{DEST_INC_DIR}/
 cp -rf %{ROOTDIR}/con/api/casecurityinterface.h* %{DEST_INC_DIR}/
+cp -rf %{ROOTDIR}/con/api/cautilinterface.h* %{DEST_INC_DIR}/
 cp -rf %{ROOTDIR}/com.oic.ca.pc %{DEST_LIB_DIR}/pkgconfig/
 
 
index d07c625..79326e5 100644 (file)
@@ -7,7 +7,7 @@ Import('env')
 print "Reading common folder script"
 
 ca_os = env.get('TARGET_OS')
-
+src_dir = env.get('SRC_DIR')
 root_dir = './../'
 
 
@@ -16,13 +16,9 @@ ca_common_src_path = ca_common_path + 'src/'
 
 env.AppendUnique(CPPPATH = [
        'common/inc/',
+       src_dir + '/resource/csdk/logger/include/',
        ])
 
-temp = env['CPPPATH']
-header = ' '
-for item in temp:
-       header = header + ' -I' + item
-
 ######################################################################
 # Source files and Target(s)
 ######################################################################
@@ -33,18 +29,6 @@ ca_common_src = [
                ca_common_src_path + 'caremotehandler.c'
        ]
 
-if ca_os == 'arduino':
-       env.Command(env.get('BUILD_DIR') + 'logger.c.o', None, '$CXX -o ' + env.get('BUILD_DIR') + 'logger.c.o' + ' $LINKFLAGS  $CCFLAGS  $CXXFLAGS ' + '-I' + Dir('.').srcnode().path + '/inc' + header + ' ' + Dir('.').srcnode().path + '/src/logger.c')
-       logger_src = [
-               env.get('BUILD_DIR') + 'logger.c.o',
-       ]
-else:
-       logger_src = [
-               ca_common_src_path + 'logger.c',
-               ca_common_src_path + 'oic_logger.c',
-               ca_common_src_path + 'oic_console_logger.c'
-               ]
-
 if env['POSIX_SUPPORTED']:
        platform_src = [
                ca_common_src_path + 'cathreadpool_pthreads.c',
@@ -57,5 +41,4 @@ else:
 
 
 env.AppendUnique(CA_SRC = ca_common_src)
-env.AppendUnique(CA_SRC = logger_src)
 env.AppendUnique(CA_SRC = platform_src)
diff --git a/resource/csdk/connectivity/common/inc/cacommonutil.h b/resource/csdk/connectivity/common/inc/cacommonutil.h
new file mode 100644 (file)
index 0000000..eced7d9
--- /dev/null
@@ -0,0 +1,73 @@
+/* ****************************************************************
+ *
+ * Copyright 2014 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.
+ *
+ ******************************************************************/
+
+#ifndef CA_COMMON_UTIL_H_
+#define CA_COMMON_UTIL_H_
+
+#include "cacommon.h"
+#include "logger.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+/**
+ * Macro to verify the validity of input argument.
+ *
+ * @param  arg  log level
+ * @param  log_tag  log tag
+ * @param  log_message  log message
+ * @param  ret  return value
+ */
+#define VERIFY_NON_NULL_RET(arg, log_tag, log_message, ret) \
+    if (NULL == (arg)) { \
+        OIC_LOG_V(ERROR, (log_tag), "Invalid input:%s", (log_message)); \
+        return (ret); \
+    } \
+
+/**
+ * Macro to verify the validity of input argument.
+ *
+ * @param  arg  log level
+ * @param  log_tag  log tag
+ * @param  log_message  log message
+ */
+#define VERIFY_NON_NULL(arg, log_tag, log_message) \
+    VERIFY_NON_NULL_RET((arg), (log_tag), (log_message), CA_STATUS_INVALID_PARAM)
+
+/**
+ * Macro to verify the validity of input argument.
+ *
+ * @param  arg  log level
+ * @param  log_tag  log tag
+ * @param  log_message  log message
+ */
+#define VERIFY_NON_NULL_VOID(arg, log_tag, log_message) \
+    if (NULL == (arg)) { \
+        OIC_LOG_V(ERROR, (log_tag), "Invalid input:%s", (log_message)); \
+        return; \
+    } \
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* CA_COMMON_UTIL_H_ */
diff --git a/resource/csdk/connectivity/common/inc/logger.h b/resource/csdk/connectivity/common/inc/logger.h
deleted file mode 100644 (file)
index 558b1c5..0000000
+++ /dev/null
@@ -1,216 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#ifndef U_LOGGER_H_
-#define U_LOGGER_H_
-
-#include <stdint.h>
-#include <stdio.h>
-#include <stdarg.h>
-#include "oic_logger.h"
-#include "oic_console_logger.h"
-
-#ifdef __ANDROID__
-#include <android/log.h>
-#elif defined(__TIZEN__)
-#include <dlog.h>
-#elif defined ARDUINO
-#include "Arduino.h"
-#include "avr/pgmspace.h"
-#endif
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
-// Use the PCF macro to wrap strings stored in FLASH on the Arduino
-// Example:  OC_LOG(INFO, TAG, PCF("Entering function"));
-#ifdef ARDUINO
-
-#ifdef __cplusplus
-#define PCF(str)  ((PROGMEM const char *)(F(str)))
-#else
-#define PCF(str)  ((PROGMEM const char *)(PSTR(str)))
-#endif //__cplusplus
-
-#else
-#define PCF(str) str
-#endif //ARDUINO
-
-// Max buffer size used in variable argument log function
-#define MAX_LOG_V_BUFFER_SIZE (256)
-
-// Log levels
-#ifdef __TIZEN__
-typedef enum {
-    DEBUG = DLOG_DEBUG,
-    INFO = DLOG_INFO,
-    WARNING = DLOG_WARN,
-    ERROR = DLOG_ERROR,
-    FATAL = DLOG_ERROR
-} LogLevel;
-#else
-typedef enum
-{
-    DEBUG = 0, INFO, WARNING, ERROR, FATAL
-} LogLevel;
-#endif
-
-#ifdef __TIZEN__
-#define OC_LOG(level,tag,mes) LOG_(LOG_ID_MAIN, level, tag, mes)
-#define OC_LOG_V(level,tag,fmt,args...) LOG_(LOG_ID_MAIN, level, tag, fmt,##args)
-#define OC_LOG_BUFFER(level, tag, buffer, bufferSize)
-#endif
-
-#ifdef __TIZEN__
-#define OICLog(level,tag,mes) LOG(level,tag,mes)
-#define OICLogv(level,tag,fmt,args...) LOG(level,tag,fmt,##args)
-#elif defined(ANDROID) || defined(__linux__) || defined(__APPLE__)
-/**
- * Configure logger to use a context that defines a custom logger function
- *
- * @param ctx - pointer to oc_log_ctx_t struct that defines custom logging functions
- */
-void OICLogConfig(oic_log_ctx_t *ctx);
-
-/**
- * Initialize the logger.  Optional on Android and Linux.  Configures serial port on Arduino
- */
-void OICLogInit();
-
-/**
- * Called to Free dyamically allocated resources used with custom logging.
- * Not necessary if default logging is used
- *
- */
-void OICLogShutdown();
-
-/**
- * Output a log string with the specified priority level.
- * Only defined for Linux and Android
- *
- * @param level  - DEBUG, INFO, WARNING, ERROR, FATAL
- * @param tag    - Module name
- * @param logStr - log string
- */
-void OICLog(LogLevel level, const char *tag, const char *logStr);
-
-/**
- * Output a variable argument list log string with the specified priority level.
- * Only defined for Linux and Android
- *
- * @param level  - DEBUG, INFO, WARNING, ERROR, FATAL
- * @param tag    - Module name
- * @param format - variadic log string
- */
-void OICLogv(LogLevel level, const char *tag, const char *format, ...);
-
-/**
- * Output the contents of the specified buffer (in hex) with the specified priority level.
- *
- * @param level      - DEBUG, INFO, WARNING, ERROR, FATAL
- * @param tag        - Module name
- * @param buffer     - pointer to buffer of bytes
- * @param bufferSize - max number of byte in buffer
- */
-void OICLogBuffer(LogLevel level, const char *tag, const uint8_t *buffer, uint16_t bufferSize);
-#else  // For arduino platforms
-/**
- * Initialize the serial logger for Arduino
- * Only defined for Arduino
- */
-void OICLogInit();
-
-/**
- * Output a log string with the specified priority level.
- * Only defined for Arduino.  Uses PROGMEM strings
- *
- * @param level  - DEBUG, INFO, WARNING, ERROR, FATAL
- * @param tag    - Module name
- * @param logStr - log string
- */
-void OICLog(LogLevel level, PROGMEM const char *tag, const int16_t lineNum,
-              PROGMEM const char *logStr);
-
-/**
- * Output the contents of the specified buffer (in hex) with the specified priority level.
- *
- * @param level      - DEBUG, INFO, WARNING, ERROR, FATAL
- * @param tag        - Module name
- * @param buffer     - pointer to buffer of bytes
- * @param bufferSize - max number of byte in buffer
- */
-void OICLogBuffer(LogLevel level, const char *tag, const uint8_t *buffer, uint16_t bufferSize);
-
-/**
- * Output a variable argument list log string with the specified priority level.
- *
- * @param level  - DEBUG, INFO, WARNING, ERROR, FATAL
- * @param tag    - Module name
- * @param format - variadic log string
- */
-void OICLogv(LogLevel level, PROGMEM const char *tag, const int16_t lineNum,
-               PROGMEM const char *format, ...);
-#endif
-
-#ifdef TB_LOG
-
-#ifdef __TIZEN__
-#define OIC_LOG(level,tag,mes) LOG_(LOG_ID_MAIN, level, tag, mes)
-#define OIC_LOG_V(level,tag,fmt,args...) LOG_(LOG_ID_MAIN, level, tag, fmt,##args)
-#define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)
-#else // These macros are defined for Linux, Android, and Arduino
-#define OIC_LOG_INIT()    OICLogInit()
-
-#ifdef ARDUINO
-#define OIC_LOG_CONFIG(ctx)
-#define OIC_LOG_SHUTDOWN()
-#define OIC_LOG(level, tag, logStr) OICLog((level), PCF(tag), __LINE__, PCF(logStr))
-#define OIC_LOG_V(level, tag, ...)
-// To enable OIC_LOG_V, uncomment the below
-//#define OIC_LOG_V(level, tag, format, ...)  OICLogv((level), PCF(tag), __LINE__, PCF(format), __VA_ARGS__)
-#define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)\
-    OICLogBuffer((level), PCF(tag), (buffer), (bufferSize))
-#else
-#define OIC_LOG_CONFIG(ctx)    OICLogConfig((ctx))
-#define OIC_LOG_SHUTDOWN()     OICLogShutdown()
-#define OIC_LOG(level, tag, logStr)  OICLog((level), (tag), (logStr))
-#define OIC_LOG_V(level, tag, ...) OICLogv((level), (tag), __VA_ARGS__)
-#define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)\
-    OICLogBuffer((level), tag, (buffer), (bufferSize))
-#endif //ARDUINO
-#endif //__TIZEN__
-#else //TB_LOG
-
-#define OIC_LOG_CONFIG(ctx)
-#define OIC_LOG_SHUTDOWN()
-#define OIC_LOG(level, tag, logStr)
-#define OIC_LOG_V(level, tag, ...)
-#define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)
-#define OIC_LOG_INIT()
-
-#endif // TB_LOG
-
-
-#ifdef __cplusplus
-}
-#endif // __cplusplus
-#endif /* U_LOGGER_H_ */
diff --git a/resource/csdk/connectivity/common/inc/oic_console_logger.h b/resource/csdk/connectivity/common/inc/oic_console_logger.h
deleted file mode 100644 (file)
index bb09eb0..0000000
+++ /dev/null
@@ -1,45 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#ifndef OIC_CONSOLE_LOGGER_
-#define OIC_CONSOLE_LOGGER_
-
-#include "oic_logger_types.h"
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
-oic_log_ctx_t *oic_make_console_logger();
-
-int oic_console_logger_init(oic_log_ctx_t *ctx, void *world);
-void oic_console_logger_destroy(oic_log_ctx_t *ctx);
-void oic_console_logger_flush(oic_log_ctx_t *ctx);
-void oic_console_logger_set_level(oic_log_ctx_t *ctx, const int level);
-size_t oic_console_logger_write(oic_log_ctx_t *ctx, const int level, const char *msg);
-int oic_console_logger_set_module(oic_log_ctx_t *ctx, const char *module_name);
-
-#ifdef __cplusplus
-} // extern "C"
-#endif
-
-#endif /* OIC_CONSOLE_LOGGER_ */
-
diff --git a/resource/csdk/connectivity/common/inc/oic_logger.h b/resource/csdk/connectivity/common/inc/oic_logger.h
deleted file mode 100644 (file)
index d1a5b8d..0000000
+++ /dev/null
@@ -1,50 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#ifndef OIC_LOGGER_H_
-#define OIC_LOGGER_H_
-
-#include "oic_logger_types.h"
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
-/* Basic interface: */
-oic_log_ctx_t *oic_log_make_ctx(void *world, const oic_log_level level, oic_log_init_t init,
-                                    oic_log_destroy_t destroy, oic_log_flush_t flush,
-                                    oic_log_set_level_t set_level,oic_log_write_level_t write_level,
-                                    oic_log_set_module_t set_module);
-
-void oic_log_destroy(oic_log_ctx_t *ctx);
-
-void oic_log_flush(oic_log_ctx_t *ctx);
-void oic_log_set_level(oic_log_ctx_t *ctx, const oic_log_level ll);
-size_t oic_log_write(oic_log_ctx_t *ctx, const char *msg);
-size_t oic_log_write_level(oic_log_ctx_t *ctx, const oic_log_level ll, const char *msg);
-int oic_log_set_module(oic_log_ctx_t *ctx, const char *module_name);
-
-#ifdef __cplusplus
-} // extern "C"
-#endif
-
-#endif /* OIC_LOGGER_H_ */
-
diff --git a/resource/csdk/connectivity/common/inc/oic_logger_types.h b/resource/csdk/connectivity/common/inc/oic_logger_types.h
deleted file mode 100644 (file)
index 121270b..0000000
+++ /dev/null
@@ -1,87 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#ifndef OIC_LOGGER_TYPES_H_
-#define OIC_LOGGER_TYPES_H_
-
-#include <stddef.h>
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
-typedef enum
-{
-    __OIC_LOG_MIN__ = -1,
-    OIC_LOG_ALL = 0,
-    OIC_LOG_FATAL,
-    OIC_LOG_ERROR,
-    OIC_LOG_WARNING,
-    OIC_LOG_INFO,
-    OIC_LOG_DEBUG,
-    OIC_LOG_DISABLED,
-    __OIC_LOG_MAX__
-} oic_log_level;
-
-typedef struct _oic_log_ctx
-{
-    void *ctx;
-
-    oic_log_level log_level;
-
-    char *module_name;
-
-    /* Required interface: */
-    int (*init)(struct _oic_log_ctx *, void *);
-    void (*destroy)(struct _oic_log_ctx *);
-    void (*flush)(struct _oic_log_ctx *);
-    void (*set_level)(struct _oic_log_ctx *, const int);
-    size_t (*write_level)(struct _oic_log_ctx *, const int, const char *);
-    int (*set_module)(struct _oic_log_ctx *, const char *);
-
-    /* Optional interface (if one is implemented, all must be implemented): */
-    int (*lock)(struct _oic_log_ctx *);
-    int (*unlock)(struct _oic_log_ctx *);
-    int (*try_lock)(struct _oic_log_ctx *);
-    int (*locked_destroy)(struct _oic_log_ctx *);
-
-} oic_log_ctx_t;
-
-/* Notice that these are all passed the /top level/ ctx-- it's "public" with respect to
- these functions, they have full access to fiddle with the structure all they want (but,
- generally should avoid doing that); I could certainly be convinced to go the other direction,
- and have most functions only take the inner context: */
-typedef int (*oic_log_init_t)(oic_log_ctx_t *, void *);
-typedef void (*oic_log_destroy_t)(oic_log_ctx_t *);
-typedef void (*oic_log_flush_t)(oic_log_ctx_t *);
-typedef void (*oic_log_set_level_t)(oic_log_ctx_t *, const int);
-typedef size_t (*oic_log_write_level_t)(oic_log_ctx_t *, const int, const char *);
-typedef int (*oic_log_set_module_t)(oic_log_ctx_t *, const char *);
-typedef int (*oic_log_lock_t)(oic_log_ctx_t *);
-typedef int (*oic_log_unlock_t)(oic_log_ctx_t *);
-typedef int (*oic_log_try_lock_t)(oic_log_ctx_t *);
-
-#ifdef __cplusplus
-} // extern "C"
-#endif
-
-#endif /* OIC_LOGGER_TYPES_H_ */
-
index 7132f42..bc0dc28 100644 (file)
@@ -139,7 +139,6 @@ void ca_mutex_lock(ca_mutex mutex)
     if (mutexInfo)
     {
         int ret = pthread_mutex_lock(&mutexInfo->mutex);
-        assert(0 == ret);
         if(ret != 0)
         {
             OIC_LOG_V(ERROR, TAG, "Pthread Mutex lock failed: %d", ret);
@@ -190,8 +189,6 @@ void ca_mutex_unlock(ca_mutex mutex)
     if (mutexInfo)
     {
         int ret = pthread_mutex_unlock(&mutexInfo->mutex);
-
-        assert ( 0 == ret);
         if(ret != 0)
         {
             OIC_LOG_V(ERROR, TAG, "Pthread Mutex unlock failed: %d", ret);
index 1315dae..61a2509 100644 (file)
@@ -281,6 +281,8 @@ CAResult_t CACloneInfo(const CAInfo_t *info, CAInfo_t *clone)
         clone->numOptions = info->numOptions;
     }
 
+    memcpy(&(clone->identity), &(info->identity), sizeof(info->identity));
+
     if ((info->payload) && (0 < info->payloadSize))
     {
         // allocate payload field
index 751bafc..636036e 100644 (file)
@@ -24,7 +24,9 @@
  * This file provides APIs related to thread pool.
  */
 
+#ifndef _GNU_SOURCE
 #define _GNU_SOURCE
+#endif
 #include <errno.h>
 #include <pthread.h>
 #include "cathreadpool.h"
diff --git a/resource/csdk/connectivity/common/src/logger.c b/resource/csdk/connectivity/common/src/logger.c
deleted file mode 100644 (file)
index 19b01e2..0000000
+++ /dev/null
@@ -1,460 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-// Defining _POSIX_C_SOURCE macro with 199309L (or greater) as value
-// causes header files to expose definitions
-// corresponding to the POSIX.1b, Real-time extensions
-// (IEEE Std 1003.1b-1993) specification
-//
-// For this specific file, see use of clock_gettime,
-// Refer to http://pubs.opengroup.org/stage7tc1/functions/clock_gettime.html
-// and to http://man7.org/linux/man-pages/man2/clock_gettime.2.html
-#ifndef _POSIX_C_SOURCE
-#define _POSIX_C_SOURCE 200809L
-#endif
-
-// Platform check can be extended to check and/or define more, or could be
-// moved into a config.h
-#if !defined(__ARDUINO__) && !defined(ARDUINO)
-#define HAVE_UNISTD_H 1
-#endif
-
-// Pull in _POSIX_TIMERS feature test macro to check for
-// clock_gettime() support.
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-
-// if we have unistd.h, we're a Unix system
-#include <time.h>
-#include <sys/time.h>
-#endif
-
-#include "logger.h"
-#include "string.h"
-#include "oic_logger.h"
-#include "oic_console_logger.h"
-
-#ifndef __TIZEN__
-static oic_log_ctx_t *logCtx = 0;
-
-#ifndef __ANDROID__
-static oic_log_level LEVEL_XTABLE[] =
-{ OIC_LOG_DEBUG, OIC_LOG_INFO, OIC_LOG_WARNING, OIC_LOG_ERROR, OIC_LOG_FATAL };
-#endif
-
-#endif
-
-static const uint16_t LINE_BUFFER_SIZE = (16 * 2) + 16 +
-        1; // Show 16 bytes, 2 chars/byte, spaces between bytes, null termination
-
-// Convert LogLevel to platform-specific severity level.  Store in PROGMEM on Arduino
-#ifdef __ANDROID__
-#ifdef ADB_SHELL
-static const char *LEVEL[] =
-{   "DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
-
-#else
-static android_LogPriority LEVEL[] =
-{   ANDROID_LOG_DEBUG, ANDROID_LOG_INFO, ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL};
-#endif
-#elif defined (__linux__) || defined (__APPLE__)
-static const char *LEVEL[] __attribute__ ((unused)) =
-{   "DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
-#elif defined ARDUINO
-#include <stdarg.h>
-#include "Arduino.h"
-
-PROGMEM const char level0[] = "DEBUG";
-PROGMEM const char level1[] = "INFO";
-PROGMEM const char level2[] = "WARNING";
-PROGMEM const char level3[] = "ERROR";
-PROGMEM const char level4[] = "FATAL";
-
-PROGMEM const char *const LEVEL[] =
-{   level0, level1, level2, level3, level4};
-
-static void OICLogString(LogLevel level, PROGMEM const char *tag, PROGMEM const char *logStr);
-#ifdef ARDUINO_ARCH_AVR
-//Mega2560 and other 8-bit AVR microcontrollers
-#define GET_PROGMEM_BUFFER(buffer, addr) { strcpy_P(buffer, (char*)pgm_read_word(addr));}
-#elif defined ARDUINO_ARCH_SAM
-//Arduino Due and other 32-bit ARM micro-controllers
-#define GET_PROGMEM_BUFFER(buffer, addr) { strcpy_P(buffer, (char*)pgm_read_dword(addr));}
-#else
-#define GET_PROGMEM_BUFFER(buffer, addr) { buffer[0] = '\0';}
-#endif
-#endif // __ANDROID__
-
-#ifndef ARDUINO
-#ifndef __TIZEN__
-void OICLogConfig(oic_log_ctx_t *ctx)
-{
-    logCtx = ctx;
-}
-
-void OICLogInit()
-{
-
-}
-
-void OICLogShutdown()
-{
-#if defined(__linux__) || defined(__APPLE__)
-    if (logCtx && logCtx->destroy)
-    {
-        logCtx->destroy(logCtx);
-    }
-#endif
-}
-
-/**
- * Output a log string with the specified priority level.
- * Only defined for Linux and Android
- *
- * @param level  - DEBUG, INFO, WARNING, ERROR, FATAL
- * @param tag    - Module name
- * @param logStr - log string
- */
-void OICLog(LogLevel level, const char *tag, const char *logStr)
-{
-    if (!logStr || !tag)
-    {
-        return;
-    }
-
-#ifdef __ANDROID__
-
-#ifdef ADB_SHELL
-    printf("%s: %s: %s\n", LEVEL[level], tag, logStr);
-#else
-    __android_log_write(LEVEL[level], tag, logStr);
-#endif
-
-#elif defined __linux__ || defined __APPLE__
-    if (logCtx && logCtx->write_level)
-    {
-        logCtx->write_level(logCtx, LEVEL_XTABLE[level], logStr);
-
-    }
-    else
-    {
-        int min = 0;
-        int sec = 0;
-        int ms = 0;
-#if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
-        struct timespec when = { 0, 0 };
-        clockid_t clk = CLOCK_REALTIME;
-#ifdef CLOCK_REALTIME_COARSE
-        clk = CLOCK_REALTIME_COARSE;
-#endif
-        if (!clock_gettime(clk, &when))
-        {
-            min = (when.tv_sec / 60) % 60;
-            sec = when.tv_sec % 60;
-            ms = when.tv_nsec / 1000000;
-        }
-#else
-        struct timeval now;
-        if (!gettimeofday(&now, NULL))
-        {
-            min = (now.tv_sec / 60) % 60;
-            sec = now.tv_sec % 60;
-            ms = now.tv_usec * 1000;
-        }
-#endif
-        printf("%02d:%02d.%03d %s: %s: %s\n", min, sec, ms, LEVEL[level], tag, logStr);
-    }
-#endif
-}
-
-/**
- * Output a variable argument list log string with the specified priority level.
- * Only defined for Linux and Android
- *
- * @param level  - DEBUG, INFO, WARNING, ERROR, FATAL
- * @param tag    - Module name
- * @param format - variadic log string
- */
-void OICLogv(LogLevel level, const char *tag, const char *format, ...)
-{
-    if (!format || !tag)
-    {
-        return;
-    }
-    char buffer[MAX_LOG_V_BUFFER_SIZE] = {};
-    va_list args;
-    va_start(args, format);
-    vsnprintf(buffer, sizeof buffer - 1, format, args);
-    va_end(args);
-    OICLog(level, tag, buffer);
-}
-
-/**
- * Output the contents of the specified buffer (in hex) with the specified priority level.
- *
- * @param level      - DEBUG, INFO, WARNING, ERROR, FATAL
- * @param tag        - Module name
- * @param buffer     - pointer to buffer of bytes
- * @param bufferSize - max number of byte in buffer
- */
-void OICLogBuffer(LogLevel level, const char *tag, const uint8_t *buffer, uint16_t bufferSize)
-{
-    if (!buffer || !tag || (bufferSize == 0))
-    {
-        return;
-    }
-
-    // I've got no idea why static initialization doesn't work here.  It seems that the compiler
-    // seems to think that this is a variable-sized object
-    char lineBuffer[LINE_BUFFER_SIZE];
-    memset(lineBuffer, 0, sizeof lineBuffer);
-    int lineIndex = 0;
-    int i;
-    for (i = 0; i < bufferSize; i++)
-    {
-        // Format the buffer data into a line
-        snprintf(&lineBuffer[lineIndex*3], sizeof(lineBuffer)-lineIndex*3, "%02X ", buffer[i]);
-        lineIndex++;
-        // Output 16 values per line
-        if (((i + 1) % 16) == 0)
-        {
-            OICLog(level, tag, lineBuffer);
-            memset(lineBuffer, 0, sizeof lineBuffer);
-            lineIndex = 0;
-        }
-    }
-    // Output last values in the line, if any
-    if (bufferSize % 16)
-    {
-        OICLog(level, tag, lineBuffer);
-    }
-}
-#endif //__TIZEN__
-#endif //ARDUINO
-#ifdef ARDUINO
-/**
- * Initialize the serial logger for Arduino
- * Only defined for Arduino
- */
-void OICLogInit()
-{
-    Serial.begin(115200);
-}
-
-/**
- * Output a log string with the specified priority level.
- * Only defined for Arduino.  Only uses PROGMEM strings
- * for the tag parameter
- *
- * @param level  - DEBUG, INFO, WARNING, ERROR, FATAL
- * @param tag    - Module name
- * @param logStr - log string
- */
- void OICLogString(LogLevel level, PROGMEM const char * tag,
-         const char * logStr)
- {
-     if (!logStr || !tag)
-     {
-         return;
-     }
-
-     char buffer[LINE_BUFFER_SIZE] = {};
-     strcpy_P(buffer, (char*)pgm_read_word(&(LEVEL[level])));
-     Serial.print(buffer);
-
-     char c = NULL;
-     Serial.print(F(": "));
-     while ((c = pgm_read_byte(tag)))
-     {
-         Serial.write(c);
-         tag++;
-     }
-     Serial.print(F(": "));
-
-     Serial.println(logStr);
- }
-
-/**
- * Output the contents of the specified buffer (in hex) with the specified
- * priority level.
- *
- * @param level      - DEBUG, INFO, WARNING, ERROR, FATAL
- * @param tag        - Module name
- * @param buffer     - pointer to buffer of bytes
- * @param bufferSize - max number of byte in buffer
- */
- void OICLogBuffer(LogLevel level, PROGMEM const char * tag,
-         const uint8_t * buffer, uint16_t bufferSize)
- {
-     if (!buffer || !tag || (bufferSize == 0))
-     {
-         return;
-     }
-
-     char lineBuffer[LINE_BUFFER_SIZE] = {0};
-     uint8_t lineIndex = 0;
-     for (uint8_t i = 0; i < bufferSize; i++)
-     {
-        // Format the buffer data into a line
-        snprintf(&lineBuffer[lineIndex*3], sizeof(lineBuffer)-lineIndex*3, "%02X ", buffer[i]);
-        lineIndex++;
-         // Output 16 values per line
-         if (((i+1)%16) == 0)
-         {
-             OICLogString(level, tag, lineBuffer);
-             memset(lineBuffer, 0, sizeof lineBuffer);
-             lineIndex = 0;
-         }
-     }
-     // Output last values in the line, if any
-     if (bufferSize % 16)
-     {
-         OICLogString(level, tag, lineBuffer);
-     }
- }
-
-/**
- * Output a log string with the specified priority level.
- * Only defined for Arduino.  Uses PROGMEM strings
- *
- * @param level  - DEBUG, INFO, WARNING, ERROR, FATAL
- * @param tag    - Module name
- * @param logStr - log string
- */
-void OICLog(LogLevel level, PROGMEM const char *tag, const int16_t lineNum,
-              PROGMEM const char *logStr)
-{
-    if (!logStr || !tag)
-    {
-        return;
-    }
-    char buffer[LINE_BUFFER_SIZE] = {0};
-    GET_PROGMEM_BUFFER(buffer, &(LEVEL[level]));
-    Serial.print(buffer);
-    char c;
-    Serial.print(F(": "));
-    while ((c = pgm_read_byte(tag)))
-    {
-        Serial.write(c);
-        tag++;
-    }
-    Serial.print(F(": "));
-    Serial.print(lineNum);
-    Serial.print(F(": "));
-    while ((c = pgm_read_byte(logStr)))
-    {
-        Serial.write(c);
-        logStr++;
-    }
-    Serial.println();
-}
-
-/**
- * Output a variable argument list log string with the specified priority level.
- * Only defined for Arduino as depicted below.
- *
- * @param level  - DEBUG, INFO, WARNING, ERROR, FATAL
- * @param tag    - Module name
- * @param format - variadic log string
- */
-void OICLogv(LogLevel level, PROGMEM const char *tag, const int16_t lineNum,
-                PROGMEM const char *format, ...)
-{
-    char buffer[LINE_BUFFER_SIZE];
-    va_list ap;
-    va_start(ap, format);
-    GET_PROGMEM_BUFFER(buffer, &(LEVEL[level]));
-    Serial.print(buffer);
-
-    char c;
-    Serial.print(F(": "));
-    while ((c = pgm_read_byte(tag))) {
-     Serial.write(c);
-     tag++;
-     }
-    Serial.print(F(": "));
-    Serial.print(lineNum);
-    Serial.print(F(": "));
-
-#ifdef __AVR__
-    vsnprintf_P(buffer, sizeof(buffer), format, ap);
-#else
-    vsnprintf(buffer, sizeof(buffer), format, ap);
-#endif
-    for (char *p = &buffer[0]; *p; p++)
-    {
-        // emulate cooked mode for newlines
-        if (*p == '\n')
-        {
-            Serial.write('\r');
-        }
-        Serial.write(*p);
-    }
-    Serial.println();
-    va_end(ap);
-}
-/**
- * Output a variable argument list log string with the specified priority level.
- * Only defined for Arduino as depicted below.
- *
- * @param level  - DEBUG, INFO, WARNING, ERROR, FATAL
- * @param tag    - Module name
- * @param format - variadic log string
- */
-void OICLogv(LogLevel level, const char *tag, const __FlashStringHelper *format, ...)
-{
-    char buffer[LINE_BUFFER_SIZE];
-    va_list ap;
-    va_start(ap, format);
-    // strcpy_P(buffer, (char*)pgm_read_word(&(LEVEL[level])));
-    // Serial.print(buffer);
-
-    Serial.print(LEVEL[level]);
-    // char c;
-    Serial.print(F(": "));
-
-    /*while ((c = pgm_read_byte(tag))) {
-     Serial.write(c);
-     tag++;
-     }*/
-    Serial.print(tag);
-    Serial.print(F(": "));
-
-#ifdef __AVR__
-    vsnprintf_P(buffer, sizeof(buffer), (const char *)format, ap); // progmem for AVR
-#else
-    vsnprintf(buffer, sizeof(buffer), (const char *)format, ap); // for the rest of the world
-#endif
-    for (char *p = &buffer[0]; *p; p++)
-    {
-        // emulate cooked mode for newlines
-        if (*p == '\n')
-        {
-            // Serial.write('\r');
-            Serial.print('\r');
-        }
-        //Serial.write(*p);
-        Serial.print(p);
-    }
-    Serial.println();
-    va_end(ap);
-}
-
-#endif //ARDUINO
\ No newline at end of file
diff --git a/resource/csdk/connectivity/common/src/oic_console_logger.c b/resource/csdk/connectivity/common/src/oic_console_logger.c
deleted file mode 100644 (file)
index aa13b00..0000000
+++ /dev/null
@@ -1,97 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH 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 "oic_logger.h"
-#include "oic_console_logger.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-
-typedef struct
-{
-    FILE *out;
-} oic_console_logger_ctx;
-
-oic_log_ctx_t *oic_make_console_logger()
-{
-    return oic_log_make_ctx(NULL, OIC_LOG_ALL, oic_console_logger_init, oic_console_logger_destroy,
-                            oic_console_logger_flush, oic_console_logger_set_level,
-                            oic_console_logger_write,oic_console_logger_set_module);
-}
-
-int oic_console_logger_init(oic_log_ctx_t *ctx, void *world)
-{
-    (void)world;
-    oic_console_logger_ctx *my_ctx =
-        (oic_console_logger_ctx *) malloc(sizeof(oic_console_logger_ctx));
-
-    if (0 == my_ctx)
-        return 0;
-
-    my_ctx->out = stderr;
-
-    ctx->ctx = (void *) my_ctx;
-
-    return 1;
-}
-
-void oic_console_logger_destroy(oic_log_ctx_t *ctx)
-{
-    oic_console_logger_ctx *lctx = (oic_console_logger_ctx *) ctx->ctx;
-
-    fflush(lctx->out);
-
-    free(lctx);
-}
-
-void oic_console_logger_flush(oic_log_ctx_t *ctx)
-{
-    oic_console_logger_ctx *lctx = (oic_console_logger_ctx *) ctx->ctx;
-
-    fflush(lctx->out);
-}
-
-void oic_console_logger_set_level(oic_log_ctx_t *ctx, const int level)
-{
-    (void)ctx;
-    (void)level;
-    /* We don't have any special thing we need to do when a log level changes. */
-    return;
-}
-
-size_t oic_console_logger_write(oic_log_ctx_t *ctx, const int level, const char *msg)
-{
-    oic_console_logger_ctx *lctx = (oic_console_logger_ctx *) ctx->ctx;
-
-    /* A "real" implementation might want to replace the loglevel with a mnemonic: */
-
-    if (0 == ctx->module_name)
-        return 1 + fprintf(lctx->out, "%d: %s\n", level, msg);
-
-    return 1 + fprintf(lctx->out, "%d: [%s]: %s\n", level, ctx->module_name, msg);
-}
-
-int oic_console_logger_set_module(oic_log_ctx_t *ctx, const char *module_name)
-{
-    (void)ctx;
-    (void)module_name;
-    /* We don't do anything special when the module name changes: */
-    return 1;
-}
diff --git a/resource/csdk/connectivity/common/src/oic_logger.c b/resource/csdk/connectivity/common/src/oic_logger.c
deleted file mode 100644 (file)
index 9347c27..0000000
+++ /dev/null
@@ -1,149 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH 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 "oic_logger.h"
-#include "oic_string.h"
-
-#include <string.h>
-#include <stdlib.h>
-
-oic_log_ctx_t *oic_log_make_ctx(void *world, const oic_log_level level, oic_log_init_t init,
-                                oic_log_destroy_t destroy, oic_log_flush_t flush,
-                                oic_log_set_level_t set_level,oic_log_write_level_t write_level,
-                                oic_log_set_module_t set_module)
-{
-    oic_log_ctx_t *log_ctx;
-
-    if (0 == init || 0 == destroy || 0 == flush || 0 == set_level || 0 == write_level
-        || 0 == set_module)
-        return 0;
-
-    if (__OIC_LOG_MIN__ > level || __OIC_LOG_MAX__ < level)
-        return 0;
-
-    log_ctx = (oic_log_ctx_t *) malloc(sizeof(oic_log_ctx_t));
-
-    if (0 == log_ctx)
-        return 0;
-
-    log_ctx->ctx = 0; /* we'll get to this in a sec... */
-    log_ctx->log_level = level;
-    log_ctx->module_name = 0;
-    log_ctx->init = init;
-    log_ctx->destroy = destroy;
-    log_ctx->flush = flush;
-    log_ctx->set_level = set_level;
-    log_ctx->set_module = set_module;
-
-    log_ctx->write_level = write_level;
-
-    if (0 == log_ctx->init(log_ctx, world))
-    {
-        free(log_ctx);
-        return 0;
-    }
-
-    return log_ctx;
-}
-
-void oic_log_destroy(oic_log_ctx_t *ctx)
-{
-    if (0 == ctx)
-        return;
-
-    ctx->destroy(ctx);
-
-    if (0 != ctx->module_name)
-        free(ctx->module_name);
-
-    free(ctx);
-}
-
-int oic_log_init(oic_log_ctx_t *ctx, void *world)
-{
-    if (0 == ctx)
-        return 0;
-
-    return ctx->init(ctx, world);
-}
-
-void oic_log_flush(oic_log_ctx_t *ctx)
-{
-    if (0 == ctx)
-    {
-        return;
-    }
-    ctx->flush(ctx);
-}
-
-void oic_log_set_level(oic_log_ctx_t *ctx, const oic_log_level ll)
-{
-    if (0 == ctx)
-    {
-        return;
-    }
-    ctx->set_level(ctx, ll);
-}
-
-size_t oic_log_write(oic_log_ctx_t *ctx, const char *msg)
-{
-    if (0 == ctx)
-        return 0;
-
-    return oic_log_write_level(ctx, ctx->log_level, msg);
-}
-
-size_t oic_log_write_level(oic_log_ctx_t *ctx, const oic_log_level ll, const char *msg)
-{
-    if (0 == ctx)
-        return 0;
-
-    ctx->log_level = ll;
-
-    /* Notify: */
-    return ctx->write_level(ctx, ll, msg);
-}
-
-int oic_log_set_module(oic_log_ctx_t *ctx, const char *module_name)
-{
-    char *mn;
-
-    if (0 == ctx)
-        return 0;
-
-    /* Swap pointers so that module data's not erased in the event of failure: */
-    mn = OICStrdup(module_name);
-    if (0 == mn)
-    {
-        if (0 != ctx->module_name)
-            free(ctx->module_name);
-        return 0;
-    }
-
-    if (0 != ctx->module_name)
-        free(ctx->module_name);
-
-    ctx->module_name = mn;
-
-    /* Notify: */
-    return ctx->set_module(ctx, ctx->module_name);
-}
-
-
index e796f4b..5dedb6b 100644 (file)
@@ -113,15 +113,17 @@ CAResult_t u_linklist_free(u_linklist_t **linklist)
     u_linklist_data_t *free_node=NULL;
     while((*linklist)->size)
     {
-        free_node = (*linklist)->list;
-        (*linklist)->list = (*linklist)->list->next;
-
-        if(free_node != NULL)
+        //Size is more but no node in linked list
+        if(!(*linklist)->list)
         {
-            OICFree(free_node);
-            free_node=NULL;
+            OIC_LOG(ERROR, TAG, "Trying to free Empty List!!");
+            return CA_STATUS_FAILED;
         }
 
+        free_node = (*linklist)->list;
+        (*linklist)->list = (*linklist)->list->next;
+        OICFree(free_node);
+        free_node=NULL;
         (*linklist)->size -= 1;
     }
 
index 50df459..8e029ad 100644 (file)
@@ -169,14 +169,15 @@ typedef struct
     /** Terminate function address stored in this pointer. **/
     CAAdapterTerminate terminate;
 
+    /** Type of transport adapter. **/
+    CATransportAdapter_t cType;
 } CAConnectivityHandler_t;
 
 /**
  * This will be used during the registration of adapters call backs to the common logic.
- * @see ::CAConnectivityHandler_t , ::CATransportAdapter_t
+ * @see ::CAConnectivityHandler_t
  */
-typedef void (*CARegisterConnectivityCallback)(CAConnectivityHandler_t handler,
-        CATransportAdapter_t cType);
+typedef void (*CARegisterConnectivityCallback)(CAConnectivityHandler_t handler);
 
 /**
  * This will be used during the receive of network requests and response.
index 1ef7fb6..d9f6e81 100644 (file)
@@ -123,6 +123,12 @@ void CADTLSSetAdapterCallbacks(CAPacketReceivedCallback recvCallback,
                                CATransportAdapter_t type);
 
 /**
+ * Register callback to deliver the result of DTLS handshake
+ * @param[in] dtlsHandshakeCallback Callback to receive the result of DTLS handshake.
+ */
+void CADTLSSetHandshakeCallback(CAErrorCallback dtlsHandshakeCallback);
+
+/**
  * Register callback to get DTLS PSK credentials.
  * @param[in]  credCallback    callback to get DTLS PSK credentials.
  */
index d146678..aec4ea7 100644 (file)
@@ -40,6 +40,7 @@
 #include "logger.h"
 #include "pdu.h"
 #include "uarraylist.h"
+#include "cacommonutil.h"
 
 #ifdef __cplusplus
 extern "C"
@@ -47,30 +48,6 @@ extern "C"
 #endif
 
 /**
- * Macro to verify the validity of input argument.
- */
-#define VERIFY_NON_NULL_RET(arg, log_tag, log_message,ret) \
-    if (NULL == arg) { \
-        OIC_LOG_V(ERROR, log_tag, "Invalid input:%s", log_message); \
-        return ret; \
-    } \
-
-/**
- * Macro to verify the validity of input argument.
- */
-#define VERIFY_NON_NULL(arg, log_tag, log_message) \
-    VERIFY_NON_NULL_RET((arg), (log_tag), (log_message), CA_STATUS_INVALID_PARAM)
-
-/**
- * Macro to verify the validity of input argument.
- */
-#define VERIFY_NON_NULL_VOID(arg, log_tag, log_message) \
-    if (NULL == arg) { \
-        OIC_LOG_V(ERROR, log_tag, "Invalid input:%s", log_message); \
-        return; \
-    } \
-
-/**
  * Length of network interface name.
  */
 #define CA_INTERFACE_NAME_SIZE 16
@@ -261,6 +238,28 @@ jobject CANativeJNIGetContext();
  * @return  JVM object.
  */
 JavaVM *CANativeJNIGetJavaVM();
+
+/**
+ * To set Activity to JNI.
+ * This must be called by the Android API before CA Initialization.
+ * @param[in]   env         JNI Environment pointer.
+ * @param[in]   activity    Activity object.
+ */
+void CANativeSetActivity(JNIEnv *env, jobject activity);
+
+/**
+ * To get Activity.
+ * Called from adapters to get Activity.
+ * @return  Activity object.
+ */
+jobject *CANativeGetActivity();
+
+/**
+ * To Delete other Global References
+ * Called during CATerminate to remove global references
+ */
+void CADeleteGlobalReferences();
+
 #endif
 
 #ifdef __cplusplus
index 3b2878b..b9ee8a7 100644 (file)
@@ -98,15 +98,13 @@ typedef struct
 typedef enum
 {
     CA_BLOCK_UNKNOWN = 0,
-    CA_OPTION1_ACK,
-    CA_OPTION1_NO_ACK_LAST_BLOCK,
-    CA_OPTION1_NO_ACK_BLOCK,
+    CA_OPTION1_RESPONSE,
+    CA_OPTION1_REQUEST_LAST_BLOCK,
+    CA_OPTION1_REQUEST_BLOCK,
     CA_OPTION2_FIRST_BLOCK,
     CA_OPTION2_LAST_BLOCK,
-    CA_OPTION2_ACK,
-    CA_OPTION2_NON,
-    CA_OPTION2_CON,
-    CA_SENT_PREVIOUS_NON_MSG,
+    CA_OPTION2_RESPONSE,
+    CA_OPTION2_REQUEST,
     CA_BLOCK_INCOMPLETE,
     CA_BLOCK_TOO_LARGE,
     CA_BLOCK_RECEIVED_ALREADY
@@ -193,12 +191,11 @@ CAResult_t CAProcessNextStep(const coap_pdu_t *pdu, const CAData_t *receivedData
  * send block message to remote device.
  * @param[in]   pdu    received pdu binary data.
  * @param[in]   msgType    the message type of the block.
- * @param[in]   status    block-wise state to move next step.
  * @param[in]   blockID     ID set of CABlockData.
  * @return ::CASTATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
  */
 CAResult_t CASendBlockMessage(const coap_pdu_t *pdu, CAMessageType_t msgType,
-                              uint8_t status, const CABlockDataID_t *blockID);
+                              const CABlockDataID_t *blockID);
 
 /**
  * send error message to remote device.
@@ -256,7 +253,7 @@ CAResult_t CASetNextBlockOption2(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
  * @return ::CASTATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
  */
 CAResult_t CANegotiateBlockSize(CABlockData_t *currData, coap_block_t *block,
-                                CAMessageType_t msgType, uint16_t blockType);
+                                coap_pdu_t *pdu, uint16_t blockType);
 
 /**
  * Update the block option in block-wise transfer list.
@@ -294,7 +291,7 @@ CAResult_t CAUpdateBlockOptionItems(CABlockData_t *currData, const coap_pdu_t *p
  * @param[out]  block   block option.
  * @return ::CASTATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
  */
-CAResult_t CAGetMoreBitFromBlock(size_t payloadLen, coap_block_t *block);
+CAResult_t CASetMoreBitFromBlock(size_t payloadLen, coap_block_t *block);
 
 /**
  * check the block option what kind of option have to set.
index 6944270..92de500 100644 (file)
@@ -45,11 +45,14 @@ typedef enum
     STATE_CONNECTED     /**< State is Connected. */
 } CAConnectedState_t;
 
-typedef struct connected_state
+typedef struct connected_device
 {
     uint8_t address[CA_MACADDR_SIZE];
     CAConnectedState_t state;
-} state_t;
+    uint8_t *recvData;
+    size_t recvDataLen;
+    size_t totalDataLen;
+} CAConnectedDeviceInfo_t;
 
 /**
  * Enum for defining different server types.
@@ -160,8 +163,9 @@ void CAEDRClientUnsetCallbacks();
 
 /**
  * Used to initialize the EDR client module where mutex is initialized.
+ * @return ::CA_STATUS_OK or Appropriate error code.
  */
-void CAEDRInitializeClient(ca_thread_pool_t handle);
+CAResult_t CAEDRClientInitialize();
 
 /**
  * Destroys the Device list and mutex.
@@ -217,15 +221,13 @@ CAResult_t CAEDRGetInterfaceInformation(CAEndpoint_t **info);
 /**
  * Start RFCOMM server for given service UUID
  *
- * @param[in]  handle       Threadpool Handle.
- *
  * @return ::CA_STATUS_OK or Appropriate error code.
  * @retval ::CA_STATUS_OK  Successful.
  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
  * @retval ::CA_STATUS_FAILED Operation failed.
  *
  */
-CAResult_t CAEDRServerStart(ca_thread_pool_t handle);
+CAResult_t CAEDRServerStart();
 
 /**
  * Stop RFCOMM server
@@ -237,6 +239,13 @@ CAResult_t CAEDRServerStart(ca_thread_pool_t handle);
 CAResult_t CAEDRServerStop();
 
 /**
+ * Used to initialize the EDR server module where mutex is initialized.
+ * @param[in]  threadPool   Threadpool Handle.
+ * @return ::CA_STATUS_OK or Appropriate error code.
+ */
+CAResult_t CAEDRServerInitialize(ca_thread_pool_t handle);
+
+/**
  * Terminate server for EDR.
  */
 void CAEDRServerTerminate();
@@ -284,6 +293,13 @@ CAResult_t CAEDRClientSendMulticastData(const uint8_t *data,
  */
 CAResult_t CAEDRGetBondedDeviceList();
 
+#ifdef __TIZEN__
+/**
+ * This function starts device discovery.
+ */
+CAResult_t CAEDRStartDeviceDiscovery(void);
+#endif
+
 #ifdef __cplusplus
 } /* extern "C" */
 #endif
diff --git a/resource/csdk/connectivity/inc/cafragmentation.h b/resource/csdk/connectivity/inc/cafragmentation.h
deleted file mode 100644 (file)
index 253fbd4..0000000
+++ /dev/null
@@ -1,169 +0,0 @@
-/* ****************************************************************
- *
- * Copyright 2014 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.
- *
- ******************************************************************/
-
-/**
- * @file
- *
- * This file contains common utility functions to manage the CA msg
- * fragmentation and reassemebly.
- */
-
-#ifndef CA_FRAGMENTATION_H_
-#define CA_FRAGMENTATION_H_
-
-#include "cacommon.h"
-#include "logger.h"
-
-/**
- * From the adapter level, this is the maximum data length is supported
- * for the data transmission.
- */
-#define MAX_DATA_LENGTH_SUPPORTED 4095
-
-/**
- * The number of bits allocated to represent data length in header.
- */
-#define NUMBER_OF_BITS_TO_IDENTIFY_DATA 12
-
-/**
- * The length of the header in bits.
- */
-#define NUMBER_OF_BITS_IN_CA_HEADER 15
-
-/**
- * The length of the header in bytes.
- */
-#define CA_HEADER_LENGTH 2
-
-/**
- * The MTU supported for BLE adapter
- */
-#define CA_SUPPORTED_BLE_MTU_SIZE  20
-
-#ifdef __TIZEN__
-/**
- * Reserved bit to differentiating the platform. Currently not in use.
- */
-#define PLATFORM_IDENTIFIER_BIT 1
-
-/**
- * The MTU supported from Tizen platform for EDR adapter.
- */
-#define CA_SUPPORTED_EDR_MTU_SIZE  512
-
-#elif __ANDROID__
-/**
- * Reserved bit to differentiating the platform. Currently not in use.
- */
-#define PLATFORM_IDENTIFIER_BIT 0
-
-/**
- * The MTU supported from Android platform for EDR adapter.
- */
-#define CA_SUPPORTED_EDR_MTU_SIZE  200
-
-#elif __ARDUINO__
-/**
- * Reserved bit to differentiating the platform. Currently not in use.
- */
-#define PLATFORM_IDENTIFIER_BIT 0
-
-/**
- * The MTU supported from Arduino platform for EDR adapter.
- */
-#define CA_SUPPORTED_EDR_MTU_SIZE  200
-
-#else //Other Platforms
-/**
- * Reserved bit to differentiating the platform. Currently not in use.
- */
-#define PLATFORM_IDENTIFIER_BIT 0
-
-/**
- * The MTU supported for EDR adapter
- */
-#define CA_SUPPORTED_EDR_MTU_SIZE  200
-
-#endif
-
-/**
- * Current Header version.
- */
-#define HEADER_VERSION 1
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
-/*****************************************************************
- * @file The CA Header format
- * CA Header will be defined by 2 bytes of Header.
- * First two bits : Header version(Currently Its not being used)
- * Third bit and fourth bit: Reserved bits for future use.
- * 5th to 16th bit : 12 bits to provide the length of the data.
- *****************************************************************/
-
-/**
- * This function is used to generate the CA specific header to
- * maintain the fragmentation logic. The header structure explained
- * above will be formed and returned to the caller.
- *
- * @param[in,out] header       Pointer to the octet array that will
- *                             contain the generated header.
- * @param[in]     headerLength Length of the @a header octet array.
- * @param[in]     dataLength   The total length of the data.  The
- *                             length will be embedded in bits 5-16 of
- *                             the header, meaning the maximum overall
- *                             length of the data to be fragmented can
- *                             be no more than 4096 (2^12).
- *
- * @return @c CA_STATUS_OK on success. One of the @c CA_STATUS_FAILED
- *         or other error values on error.
- * @retval @c CA_STATUS_OK             Successful
- * @retval @c CA_STATUS_INVALID_PARAM  Invalid input arguments
- * @retval @c CA_STATUS_FAILED         Operation failed
- */
-CAResult_t CAGenerateHeader(uint8_t *header,
-                            size_t headerLength,
-                            size_t datalength);
-
-/**
- * This function is used to parse the header in the receiver end. This
- * function will provide the information of the total length of the
- * data which has been fragmented.
- *
- * @param[in] header Pointer to the octet array data which contains
- *                   the header information.  Note that pointer should
- *                   point to two bytes of data header which needs to
- *                   be parsed.
- * @param[in] length Length of the @a octet array containing the
- *                   header.
- *
- * @return Overall length of the data to be reassembled, or 0 on
- *         failure.
- */
-uint32_t CAParseHeader(const uint8_t *header, size_t length);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif  /* CA_FRAGMENTATION_H_ */
index 5240935..477674f 100644 (file)
@@ -28,6 +28,7 @@
 #define CA_INTERFACE_CONTROLLER_H_
 
 #include "caadapterinterface.h"
+#include "cainterface.h"
 
 #ifndef SINGLE_THREAD
 #include "cathreadpool.h" /* for thread pool */
index ff344f0..2caf5b1 100644 (file)
@@ -94,6 +94,11 @@ CAResult_t CAIPStartServer(const ca_thread_pool_t threadPool);
 #endif
 
 /**
+ * Close IP socket.
+ */
+void CADeInitializeIPGlobals();
+
+/**
  * Stop IP server.
  */
 void CAIPStopServer();
index 5436b33..0ac0028 100644 (file)
@@ -31,6 +31,7 @@
 
 #include "cacommon.h"
 #include "cathreadpool.h"
+#include "uarraylist.h"
 
 #ifdef __cplusplus
 extern "C"
@@ -50,12 +51,42 @@ typedef enum
 } CALETransferType_t;
 
 /**
+ * Stores the information of the Data to be sent from the queues.
+ *
+ * This structure will be pushed to the sender/receiver queue for
+ * processing.
+ */
+typedef struct
+{
+    /// Remote endpoint contains the information of remote device.
+    CAEndpoint_t *remoteEndpoint;
+
+    /// Data to be transmitted over LE transport.
+    uint8_t *data;
+
+    /// Length of the data being transmitted.
+    uint32_t dataLen;
+
+    /// Sender information list
+    u_arraylist_t * senderInfo;
+} CALEData_t;
+
+/**
  * This will be used to notify device status changes to the LE adapter layer.
  * @param[in]  adapter_state State of the adapter.
  */
 typedef void (*CALEDeviceStateChangedCallback)(CAAdapterState_t adapter_state);
 
 /**
+ * This will be used to notify device connection state changes to the LE adapter layer.
+ * @param[in]   adapter        Transport type information.
+ * @param[in]   remoteAddress  Endpoint object from which the connection status is changed.
+ * @param[in]   connected      State of connection.
+ */
+typedef void (*CALEConnectionStateChangedCallback)(CATransportAdapter_t adapter,
+                                                   const char *remoteAddress, bool connected);
+
+/**
  * Notify the adapter layer that a packet was received from the GATT
  * peer.
  *
@@ -78,12 +109,13 @@ typedef CAResult_t (*CABLEDataReceivedCallback)(const char *remoteAddress,
  * Initialize the LE adapter layer. This will be invoked from the CA
  * layer.
  *
+ * @param[in] threadPool Thread pool handle
  * @return ::CA_STATUS_OK or Appropriate error code
  * @retval ::CA_STATUS_OK  Successful
  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments
  * @retval ::CA_STATUS_FAILED Operation failed
  */
-CAResult_t CAInitializeLEAdapter();
+CAResult_t CAInitializeLEAdapter(const ca_thread_pool_t threadPool);
 
 /**
  * Start the LE adapter layer.
@@ -99,6 +131,19 @@ CAResult_t CAInitializeLEAdapter();
 CAResult_t CAStartLEAdapter();
 
 /**
+ * Stop the LE adapter layer.
+ *
+ * This function will be invoked from the CA layer when the LE
+ * "network" is unselected via @c CAUnselectNetwork().  It gives an
+ * opportunity for LE adapter implementations to perform operations
+ * after stopping a GATT client or server.  Most LE adapter
+ * implementations will simply implement this function as no-op.
+ *
+ * @return ::CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAStopLEAdapter();
+
+/**
  * Used to get the current state of the LE adapter.
  *
  * @return ::CA_STATUS_OK or Appropriate error code
@@ -141,21 +186,17 @@ void CATerminateLENetworkMonitor();
 CAResult_t CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCallback callback);
 
 /**
- * Initialize all the mutex variables required to operate the LE
- * network monitor layer.
+ * Set the callback for the device connection state changes.
+ *
+ * @param[in] callback Callback to notify the Device connection state change to
+ *            the CA Layer
  *
  * @return ::CA_STATUS_OK or Appropriate error code
  * @retval ::CA_STATUS_OK  Successful
  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments
  * @retval ::CA_STATUS_FAILED Operation failed
  */
-CAResult_t CAInitLENetworkMonitorMutexVariables();
-
-/**
- * Used to terminate all the mutex variables required to operate the LE
- * network monitor layer.
- */
-void CATerminateLENetworkMonitorMutexVariables();
+CAResult_t CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCallback callback);
 
 /**
  * Provides the MAC address of the local Bluetooth adapter.
@@ -192,6 +233,15 @@ CAResult_t CAStartLEGattServer();
 CAResult_t CAStopLEGattServer();
 
 /**
+ * initialize gatt server
+ *
+ * @return ::CA_STATUS_OK or Appropriate error code
+ * @retval ::CA_STATUS_OK  Successful
+ * @retval ::CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAInitializeLEGattServer();
+
+/**
  * Stop Gatt Server thread and remove service registration, stop
  * advertising.
  */
@@ -259,6 +309,15 @@ CAResult_t CAStartLEGattClient();
 void CAStopLEGattClient();
 
 /**
+ * initialize Client
+ *
+ * @return ::CA_STATUS_OK or Appropriate error code
+ * @retval ::CA_STATUS_OK  Successful
+ * @retval ::CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAInitializeLEGattClient();
+
+/**
  * Unset all the callbacks and stop service discovery
  */
 void CATerminateLEGattClient();
@@ -337,7 +396,7 @@ void CASetLEServerThreadPoolHandle(ca_thread_pool_t handle);
 void CASetLEClientThreadPoolHandle(ca_thread_pool_t handle);
 
 /**
- * Unset the callback of adapter connection state change.
+ * Unset the callback of adapter state change.
  *
  * @return ::CA_STATUS_OK or Appropriate error code.
  * @retval ::CA_STATUS_OK  Successful.
@@ -347,6 +406,16 @@ void CASetLEClientThreadPoolHandle(ca_thread_pool_t handle);
 CAResult_t CAUnSetLEAdapterStateChangedCb();
 
 /**
+ * Unset the callback of adapter connection state change.
+ *
+ * @return ::CA_STATUS_OK or Appropriate error code.
+ * @retval ::CA_STATUS_OK  Successful.
+ * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
+ * @retval ::CA_STATUS_FAILED Operation failed.
+ */
+CAResult_t CAUnSetLENWConnectionStateChangedCb();
+
+/**
  * This will be used to notify errors in BLE adapter.
  *
  * @param[in] remoteAddress Remote endpoint Address
@@ -374,7 +443,6 @@ void CASetBLEClientErrorHandleCallback(CABLEErrorHandleCallback callback);
  *                     adapter.
  */
 void CASetBLEServerErrorHandleCallback(CABLEErrorHandleCallback callback);
-
 #ifdef __cplusplus
 }
 #endif
index c84836c..3f2fa6c 100644 (file)
@@ -61,44 +61,15 @@ extern "C"
 #endif
 
 /**
- * Detaches control from the caller for sending unicast request.
+ * Detaches control from the caller for sending message.
  * @param[in] endpoint    endpoint information where the data has to be sent.
- * @param[in] request     request that needs to be sent.
+ * @param[in] sendMsg     message that needs to be sent.
+ * @param[in] dataType    type of the message(request/response).
  * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
  */
-CAResult_t CADetachRequestMessage(const CAEndpoint_t *endpoint,
-                                  const CARequestInfo_t *request);
-
-/**
- * Detaches control from the caller for sending multicast request.
- * @param[in] object     Group endpoint information where the data has to be sent.
- * @param[in] request    request that needs to be sent.
- * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
- */
-CAResult_t CADetachRequestToAllMessage(const CAEndpoint_t *object,
-                                       const CARequestInfo_t *request);
-
-/**
- * Detaches control from the caller for sending response.
- * @param[in] endpoint    endpoint information where the data has to be sent.
- * @param[in] response    response that needs to be sent.
- * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
- */
-CAResult_t CADetachResponseMessage(const CAEndpoint_t *endpoint,
-                                   const CAResponseInfo_t *response);
-
-/**
- * Detaches control from the caller for sending request.
- * @param[in] resourceUri    resource uri that needs to  be sent in the request.
- * @param[in] token          token information of the request.
- * @param[in] tokenLength    length of the token.
- * @param[in] options        header options that need to be append in the request.
- * @param[in] numOptions     number of options be appended.
- * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
- */
-CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t token,
-                                      uint8_t tokenLength, const CAHeaderOption_t *options,
-                                      uint8_t numOptions);
+CAResult_t CADetachSendMessage(const CAEndpoint_t *endpoint,
+                               const void *sendMsg,
+                               CADataType_t dataType);
 
 /**
  * Setting the request and response callbacks for network packets.
@@ -127,6 +98,12 @@ void CATerminateMessageHandler();
 void CAHandleRequestResponseCallbacks();
 
 /**
+ * Setting the Callback funtion for network state change callback.
+ * @param[in] nwMonitorHandler    callback for network state change.
+ */
+void CASetNetworkMonitorCallback(CANetworkMonitorCallback nwMonitorHandler);
+
+/**
  * To log the PDU data.
  * @param[in] pdu    pdu data.
  * @param[in] endpoint  endpoint
diff --git a/resource/csdk/connectivity/inc/canfcadapter.h b/resource/csdk/connectivity/inc/canfcadapter.h
new file mode 100644 (file)
index 0000000..3e8fb48
--- /dev/null
@@ -0,0 +1,132 @@
+/* *****************************************************************\r
+ *\r
+ * Copyright 2015 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
+ * @file\r
+ * This file contains the APIs for NFC Adapter.\r
+ */\r
+#ifndef CA_NFC_ADAPTER_H_\r
+#define CA_NFC_ADAPTER_H_\r
+\r
+#include "cacommon.h"\r
+#include "caadapterinterface.h"\r
+#include "cathreadpool.h"\r
+\r
+#ifdef __cplusplus\r
+extern "C"\r
+{\r
+#endif\r
+\r
+/**\r
+ * API to initialize NFC Interface.\r
+ * @param[in] registerCallback      Callback to register NFC interfaces to Connectivity\r
+ *                                  Abstraction Layer\r
+ * @param[in] networkPacketCallback Callback to notify request and response messages from server(s)\r
+ *                                  started at Connectivity Abstraction Layer.\r
+ * @param[in] netCallback           Callback to notify the network additions to Connectivity\r
+ *                                  Abstraction Layer.\r
+ * @param[in] errorCallback         Callback to notify the network errors to Connectivity\r
+ *                                  Abstraction Layer\r
+ * @param[in] handle                Threadpool Handle\r
+ * @return  ::CA_STATUS_OK, if success or Appropriate error code\r
+ */\r
+CAResult_t CAInitializeNFC(CARegisterConnectivityCallback registerCallback,\r
+                          CANetworkPacketReceivedCallback networkPacketCallback,\r
+                          CANetworkChangeCallback netCallback,\r
+                          CAErrorHandleCallback errorCallback, ca_thread_pool_t handle);\r
+\r
+/**\r
+ * Start NFC Interface adapter.\r
+ * @return  ::CA_STATUS_OK, if success or Appropriate error code\r
+ */\r
+CAResult_t CAStartNFC();\r
+\r
+/**\r
+ * Start listening server for receiving multicast search requests.\r
+ * @return  ::CA_STATUS_OK, if success or Appropriate error code\r
+ */\r
+CAResult_t CAStartNFCListeningServer();\r
+\r
+/**\r
+ * Start listening server for receiving multicast search requests.\r
+ * @return  ::CA_STATUS_OK, if success or Appropriate error code\r
+ */\r
+CAResult_t CAStopNFCListeningServer();\r
+\r
+/**\r
+ * Start discovery servers for receiving multicast advertisements.\r
+ * @return  ::CA_STATUS_OK, if success or Appropriate error code.\r
+ */\r
+CAResult_t CAStartNFCDiscoveryServer();\r
+\r
+/**\r
+ * Sends data to the endpoint using the adapter connectivity.\r
+ * @param[in]   endpoint    Remote Endpoint information.\r
+ * @param[in]   data        data to be sent.\r
+ * @param[in]   dataLen     Size of data to be sent.\r
+ * @return  number of bytes sent on the network. Return value equal to -1 indicates error.\r
+ * @remark  dataLen must be > 0.\r
+ */\r
+int32_t CASendNFCUnicastData(const CAEndpoint_t *endpoint, const void *data,\r
+                             uint32_t dataLen);\r
+\r
+/**\r
+ * Send Multicast data to the endpoint using the NFC connectivity.\r
+ * @param[in]   endpoint    Remote Endpoint information.\r
+ * @param[in]   data        Data which is required to be sent.\r
+ * @param[in]   dataLen     Size of data to be sent.\r
+ * @return  number of bytes sent on the network. Return value equal to -1 indicates error.\r
+ * @remark  dataLen must be > 0.\r
+ */\r
+int32_t CASendNFCMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLen);\r
+\r
+/**\r
+ * Get NFC Connectivity network information\r
+ * @param[out]   info        Local connectivity information structures.\r
+ * @param[out]   size        Number of local connectivity structures.\r
+ * @return  ::CA_STATUS_OK, if success or Appropriate error code.\r
+ * @remarks info is allocated in this API and must be freed by the caller.\r
+ */\r
+CAResult_t CAGetNFCInterfaceInformation(CAEndpoint_t **info, uint32_t *size);\r
+\r
+/**\r
+ * Read Synchronous API callback.\r
+ * @return  ::CA_STATUS_OK, if success or Appropriate error code.\r
+ */\r
+CAResult_t CAReadNFCData();\r
+\r
+/**\r
+ * Stops stop servers and close the sockets.\r
+ * @return  ::CA_STATUS_OK, if success or Appropriate error code.\r
+ */\r
+CAResult_t CAStopNFC();\r
+\r
+/**\r
+ * Terminate the NFC connectivity adapter.\r
+ * Configuration information will be deleted from further use\r
+ */\r
+void CATerminateNFC();\r
+\r
+#ifdef __cplusplus\r
+} /* extern "C" */\r
+#endif\r
+\r
+#endif  /* CA_NFC_ADAPTER_H_ */\r
+\r
diff --git a/resource/csdk/connectivity/inc/canfcinterface.h b/resource/csdk/connectivity/inc/canfcinterface.h
new file mode 100644 (file)
index 0000000..8cbd642
--- /dev/null
@@ -0,0 +1,136 @@
+/* *****************************************************************\r
+ *\r
+ * Copyright 2015 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
+ * @file\r
+ * This file provides APIs NFC client/server/network monitor modules.\r
+ */\r
+\r
+#ifndef CA_NFC_INTERFACE_H_\r
+#define CA_NFC_INTERFACE_H_\r
+\r
+#include <stdbool.h>\r
+\r
+#include "cacommon.h"\r
+#include "cathreadpool.h"\r
+#include "uarraylist.h"\r
+\r
+#ifdef __cplusplus\r
+extern "C"\r
+{\r
+#endif\r
+\r
+/**\r
+ * CAAdapterServerType_t.\r
+ * Enum for defining different server types.\r
+ */\r
+typedef enum\r
+{\r
+    CA_NFC_SERVER = 0, /**< Listening Server */\r
+} CAAdapterServerType_t;\r
+\r
+/**\r
+ * Callback to be notified on reception of any data from remote OIC devices.\r
+ *\r
+ * @param[in]  endpoint    network endpoint description\r
+ * @param[in]  data        Data received from remote OIC device.\r
+ * @param[in]  dataLength  Length of data in bytes.\r
+ */\r
+typedef void (*CANFCPacketReceivedCallback)(const CASecureEndpoint_t *endpoint, const void *data,\r
+                                            uint32_t dataLength);\r
+\r
+/**\r
+  * Callback to notify error in the NFC adapter.\r
+  *\r
+  * @param[in]  endpoint     network endpoint description.\r
+  * @param[in]  data         Data sent/received.\r
+  * @param[in]  dataLength   Length of data in bytes.\r
+  * @param[in]  result       result of request.\r
+  */\r
+typedef void (*CANFCErrorHandleCallback)(const CAEndpoint_t *endpoint, const void *data,\r
+                                         uint32_t dataLength, CAResult_t result);\r
+\r
+/**\r
+ * Callback to be notified when exception occures on multicast/unicast server.\r
+ * @param[in]  type    Type of server(::CAAdapterServerType_t).\r
+ */\r
+typedef void (*CANFCExceptionCallback)(CAAdapterServerType_t type);\r
+\r
+/**\r
+ * Initialize Nfc server.\r
+ *\r
+ * @return  ::CA_STATUS_OK, if success or Appropriate error code.\r
+ */\r
+CAResult_t CAInitializeNfcServer();\r
+\r
+/**\r
+ * Starts Nfc server.\r
+ *\r
+ * @return  ::CA_STATUS_OK, if success or Appropriate error code.\r
+ */\r
+CAResult_t CANFCStartServer();\r
+\r
+/**\r
+ * Stop Nfc server.\r
+ */\r
+void CANFCStopServer();\r
+\r
+/**\r
+ * Set this callback for receiving data packets from peer devices.\r
+ *\r
+ * @param[in]  callback   Callback to be notified when data received.\r
+ */\r
+void CANFCSetPacketReceiveCallback(CANFCPacketReceivedCallback callback);\r
+\r
+/**\r
+ * Set this callback for receiving exception notifications.\r
+ *\r
+ * @param[in]  callback    Callback to be notified in case of exception.\r
+ */\r
+void CANFCSetExceptionCallback(CANFCExceptionCallback callback);\r
+\r
+/**\r
+ * API to send Data.\r
+ *\r
+ * @param[in]  endpoint    Remote End point.\r
+ * @param[in]  data        Data to be send.\r
+ * @param[in]  dataLength  Length of data in bytes.\r
+ */\r
+void CANFCSendData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLength);\r
+\r
+/**\r
+ * Get a list of CAInterface_t items.\r
+ * @param[in] desiredIndex    Get interface information for the given index.\r
+ * @return  List of CAInterface_t items if success, NULL pointer if failed.\r
+ */\r
+u_arraylist_t *CANFCGetInterfaceInformation(int desiredIndex);\r
+\r
+/**\r
+ * Set callback for error handling.\r
+ *\r
+ * @param[in] nfcErrorCallback    callback to notify error to the nfcadapter.\r
+ */\r
+void CANFCSetErrorHandleCallback(CANFCErrorHandleCallback nfcErrorCallback);\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+#endif /* CA_NFC_INTERFACE_H_ */\r
index 29b5478..b752a4d 100644 (file)
@@ -217,12 +217,6 @@ CAResult_t CAGenerateTokenInternal(CAToken_t *token, uint8_t tokenLength);
 void CADestroyTokenInternal(CAToken_t token);
 
 /**
- * destroy the ca info structure.
- * @param[in]   info            info structure  created from received  packet.
- */
-void CADestroyInfo(CAInfo_t *info);
-
-/**
  * gets message type from PDU binary data.
  * @param[in]   pdu                 pdu data.
  * @param[in]   size                size of pdu data.
@@ -253,6 +247,24 @@ CAResponseResult_t CAGetCodeFromPduBinaryData(const void *pdu, uint32_t size);
  */
 CAPayloadFormat_t CAConvertFormat(uint8_t format);
 
+#ifdef WITH_TCP
+/**
+ * check whether CoAP over TCP is supported or not.
+ * @param[in]   adapter             transport adapter type.
+ * @return true or false.
+ */
+bool CAIsSupportedCoAPOverTCP(CATransportAdapter_t adapter);
+#endif
+
+#ifdef WITH_BWT
+/**
+ * check whether blockwise transfer is supported or not.
+ * @param[in]   adapter             transport adapter type.
+ * @return true or false.
+ */
+bool CAIsSupportedBlockwiseTransfer(CATransportAdapter_t adapter);
+#endif
+
 #ifdef __cplusplus
 } /* extern "C" */
 #endif
index 5b9c04c..7dd0940 100644 (file)
@@ -27,6 +27,7 @@
 
 #include "cacommon.h"
 #include "caadapterinterface.h"
+#include "cainterface.h"
 #include "cathreadpool.h"
 
 #ifdef __cplusplus
index 14b2c8e..2528df1 100644 (file)
@@ -28,6 +28,7 @@
 #include "cacommon.h"
 #include "caadapterinterface.h"
 #include "cathreadpool.h"
+#include "cainterface.h"
 
 #ifdef __cplusplus
 extern "C"
@@ -35,13 +36,16 @@ extern "C"
 #endif
 
 /**
- * TCP Server Information for IPv4 TCP transport
+ * TCP Session Information for IPv4 TCP transport
  */
 typedef struct
 {
-    char addr[MAX_ADDR_STR_SIZE_CA];    /**< TCP Server address */
-    CASocket_t u4tcp;                   /**< TCP Server port */
-} CATCPServerInfo_t;
+    CASecureEndpoint_t sep;             /**< secure endpoint information */
+    int fd;                             /**< file descriptor info */
+    void *recvData;                     /**< received data from remote device*/
+    size_t recvDataLen;                 /**< received data length */
+    size_t totalDataLen;                /**< total data length */
+} CATCPSessionInfo_t;
 
 /**
  * API to initialize TCP Interface.
@@ -147,6 +151,15 @@ CAResult_t CAStopTCP();
  */
 void CATerminateTCP();
 
+/**
+ * Set connected callback and disconnected callback to process KeepAlive.
+ * connection informations are delivered these callbacks.
+ * @param[in]   ConnHandler     Connected callback.
+ * @param[in]   DisconnHandler  Disconnected Callback.
+ */
+void CATCPSetKeepAliveCallbacks(CAKeepAliveConnectedCallback ConnHandler,
+                                CAKeepAliveDisconnectedCallback DisconnHandler);
+
 #ifdef __cplusplus
 } /* extern "C" */
 #endif
index 0519263..38efb00 100644 (file)
@@ -46,9 +46,9 @@ extern "C"
  * @param[in]  dataLength    Length of data in bytes.
  * @pre  Callback must be registered using CAIPSetPacketReceiveCallback().
  */
-typedef void (*CATCPPacketReceivedCallback)(const CAEndpoint_t *endpoint,
-                                           const void *data,
-                                           uint32_t dataLength);
+typedef void (*CATCPPacketReceivedCallback)(const CASecureEndpoint_t *endpoint,
+                                            const void *data,
+                                            uint32_t dataLength);
 
 /**
   * Callback to notify error in the TCP adapter.
@@ -60,7 +60,17 @@ typedef void (*CATCPPacketReceivedCallback)(const CAEndpoint_t *endpoint,
   * @pre  Callback must be registered using CAIPSetPacketReceiveCallback().
  */
 typedef void (*CATCPErrorHandleCallback)(const CAEndpoint_t *endpoint, const void *data,
-                                        uint32_t dataLength, CAResult_t result);
+                                         uint32_t dataLength, CAResult_t result);
+
+/**
+  * Callback to notify connection information in the TCP adapter.
+  *
+  * @param[in]  addr    connected device address.
+  * @param[in]  port    connected port info.
+  * @param[in]  isConnected    Whether keepalive message needs to be sent.
+  * @see  Callback must be registered using CATCPSetKeepAliveCallback().
+ */
+typedef void (*CATCPKeepAliveHandleCallback)(const char *addr, uint16_t port, bool isConnected);
 
 /**
  * set error callback to notify error in TCP adapter.
@@ -71,6 +81,14 @@ typedef void (*CATCPErrorHandleCallback)(const CAEndpoint_t *endpoint, const voi
 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback);
 
 /**
+ * set keepalive callback to notify connection information in TCP adapter.
+ *
+ * @param[in]  keepaliveHandler Callback function to notify the connection information.
+ * in the TCP adapter.
+ */
+void CATCPSetKeepAliveCallback(CATCPKeepAliveHandleCallback keepaliveHandler);
+
+/**
  * Start TCP server.
  *
  * @param   threadPool   Thread pool for managing Unicast server threads.
@@ -113,27 +131,52 @@ u_arraylist_t *CATCPGetInterfaceInformation(int desiredIndex);
 
 /**
  * Connect to TCP Server.
- * @param[in]   TCPServerInfo   TCP Server information.
- * @return  TCP Server Information structure.
+ *
+ * @param[in]   endpoint    remote endpoint information.
+ * @return  TCP Session Information structure.
  */
-CATCPServerInfo_t *CAConnectToTCPServer(const CAEndpoint_t *TCPServerInfo);
+CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint);
 
 /**
  * Disconnect from TCP Server.
- * @param[in]   TCPServerInfo   TCP Server information.
+ *
+ * @param[in]   svritem     TCP session information.
+ * @param[in]   index       current session index in list.
  * @return  ::CA_STATUS_OK or Appropriate error code.
  */
-CAResult_t CADisconnectFromTCPServer(const CAEndpoint_t *TCPServerInfo);
+CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index);
 
 /**
- * Get TCP Connection Information from list.
- * @param[in]   addr    TCP Server address.
- * @param[in]   port    TCP Server port.
+ * Disconnect all connection from TCP Server.
+ */
+void CATCPDisconnectAll();
+
+/**
+ * Get TCP connection information from list.
+ *
+ * @param[in]   endpoint    remote endpoint information.
  * @param[out]  index   index of array list.
+ * @return  TCP Session Information structure.
+ */
+CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint,
+                                                    size_t *index);
+
+/**
+ * Get total length from CoAP over TCP header.
+ *
+ * @param[in]   recvBuffer    received header data.
+ * @return  total data length
+ */
+size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer);
+
+/**
+ * Get session information from file descriptor index.
+ *
+ * @param[in]   fd      file descriptor.
+ * @param[out]  index   index of array list
  * @return  TCP Server Information structure.
  */
-CATCPServerInfo_t *CAGetTCPServerInfoFromList(const char *addr, const uint16_t port,
-                                            uint32_t *index);
+CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index);
 
 #ifdef __cplusplus
 }
index dd50893..22892cd 100644 (file)
@@ -19,6 +19,7 @@
 
  ******************************************************************/
 
+
 #ifndef _BYTE_ARRAY_H_
 #define _BYTE_ARRAY_H_
 
@@ -45,14 +46,14 @@ typedef struct
 } ByteArray;
 
 
-/**
+/**@def BYTE_ARRAY_INITIALIZER
  *
  * Initializes of existing byte array pointer to \a NULL.
  */
 #undef BYTE_ARRAY_INITIALIZER
 #define BYTE_ARRAY_INITIALIZER {NULL, 0}
 
-/**
+/**@def INIT_BYTE_ARRAY(array)
  *
  * Initializes of existing byte array \a array.
  *
@@ -64,7 +65,7 @@ typedef struct
         (array).len = 0;            \
     }while(0)
 
-/**
+/**@def PRINT_BYTE_ARRAY(msg, array)
  *
  * Prints out byte array \a array in hex representation with message \a msg.
  *
@@ -82,7 +83,7 @@ typedef struct
         putchar('\n');                                  \
     }while(0)
 
-/**
+/**@def INC_BYTE_ARRAY_PTR(array, size)
  *
  * Increments byte array pointer \a array by \a size.
  *
@@ -95,7 +96,7 @@ typedef struct
         (array)->len -= size;                    \
     }while(0)
 
-/**
+/**@def INC_BYTE_ARRAY(array, size)
  *
  * Increments byte array \a array by \a size.
  *
@@ -108,20 +109,6 @@ typedef struct
         (array).len -= size;                 \
     }while(0)
 
-/**
- *
- * Initializes of existing byte array.
- *
- * @param array of uint8_t
- *
- * @note Array must  be statically allocated.
- */
-#ifdef __cplusplus
-#define BYTE_ARRAY_CONSTRUCTOR(array) {array, sizeof(array)}
-#else
-#define BYTE_ARRAY_CONSTRUCTOR(array) {.data = array, .len = sizeof(array)}
-#endif
-
 #ifdef __cplusplus
 }
 #endif //__cplusplus
index 1c6a39f..03c6f7c 100644 (file)
@@ -54,23 +54,6 @@ typedef struct
 } CertificateX509;
 
 /**
- *
- *
- * Initializes of certificate structure.
- *
- */
-#define CERTIFICATE_X509_INITIALIZER {\
-    BYTE_ARRAY_INITIALIZER,                                            \
-    BYTE_ARRAY_INITIALIZER,                                            \
-    BYTE_ARRAY_INITIALIZER,                                            \
-    BYTE_ARRAY_INITIALIZER,                                            \
-    BYTE_ARRAY_INITIALIZER,                                            \
-    BYTE_ARRAY_INITIALIZER,                                            \
-    BYTE_ARRAY_INITIALIZER,                                            \
-    BYTE_ARRAY_INITIALIZER,                                            \
-    BYTE_ARRAY_INITIALIZER}
-
-/**
  * Reads certificate from byte array and write it into certificate structure.
  *
  * @param[in] code  Byte array with DER encoded certificate
index 3fda0cf..3f2b93c 100644 (file)
@@ -52,10 +52,10 @@ extern "C" {
  */
 #undef GET_SHA_256
 #define GET_SHA_256(tbs, sha256) do{                     \
-        SHA256_CTX ctx256;                               \
-        SHA256_Init(&ctx256);                            \
-        SHA256_Update(&ctx256, tbs.data, tbs.len);       \
-        SHA256_Final(sha256, &ctx256);                   \
+        DTLS_SHA256_CTX ctx256;                          \
+        DTLS_SHA256_Init(&ctx256);                       \
+        DTLS_SHA256_Update(&ctx256, tbs.data, tbs.len);  \
+        DTLS_SHA256_Final(sha256, &ctx256);              \
     }while(0)
 
 /**@def CHECK_SIGN(structure, caPubKey)
index 876bc03..0683773 100644 (file)
@@ -37,12 +37,14 @@ if target_os not in ['windows', 'winrt']:
        libcoap_env.AppendUnique(CFLAGS = ['-Wall', '-ffunction-sections',
                        '-fdata-sections', '-fno-exceptions'])
 
-if target_os in ['linux', 'tizen']:
+if target_os in ['linux', 'tizen', 'android', 'ios']:
        if with_tcp == True:
                libcoap_env.AppendUnique(CPPDEFINES = ['WITH_TCP'])
 
-if target_os == 'android':
+if target_os in ['linux', 'tizen', 'android', 'arduino']:
        libcoap_env.AppendUnique(LIBS = ['log'])
+       if (('BLE' in ca_transport) or ('BT' in ca_transport) or ('ALL' in ca_transport)):
+               libcoap_env.AppendUnique(CPPDEFINES = ['WITH_TCP'])
 
 if target_os == 'arduino':
        libcoap_env.AppendUnique(CPPDEFINES = ['NDEBUG', 'WITH_ARDUINO'])
index e4f40d6..1da4034 100644 (file)
@@ -15,6 +15,7 @@
 #include <stdlib.h>
 #include <stdio.h>
 #include <string.h>
+#include <limits.h>
 #ifdef HAVE_ARPA_INET_H
 #include <arpa/inet.h>
 #endif
@@ -243,24 +244,43 @@ void coap_delete_pdu(coap_pdu_t *pdu)
 }
 
 #ifdef WITH_TCP
+size_t coap_get_total_message_length(const unsigned char *data, size_t size)
+{
+    if (!data || !size)
+    {
+        debug("received data length is null\n");
+        return 0;
+    }
+
+    coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
+            ((unsigned char *)data)[0] >> 4);
+    size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)data,
+                                                        transport);
+    size_t headerLen = coap_get_tcp_header_length((unsigned char *)data);
+
+    return headerLen + optPaylaodLen;
+}
+
 coap_transport_type coap_get_tcp_header_type_from_size(unsigned int size)
 {
-    if (COAP_TCP_LENGTH_LIMIT_8_BIT < size && COAP_TCP_LENGTH_LIMIT_16_BIT >= size)
+    if (size < COAP_TCP_LENGTH_FIELD_8_BIT)
+    {
+        return coap_tcp;
+    }
+    else if (size < COAP_TCP_LENGTH_FIELD_16_BIT)
     {
         return coap_tcp_8bit;
     }
-    else if (COAP_TCP_LENGTH_LIMIT_16_BIT < size && COAP_TCP_LENGTH_LIMIT_32_BIT >= size)
+    else if (size < COAP_TCP_LENGTH_FIELD_32_BIT)
     {
         return coap_tcp_16bit;
     }
-    else if (COAP_TCP_LENGTH_LIMIT_32_BIT < size)
+    else if (size < ULONG_MAX + COAP_TCP_LENGTH_FIELD_32_BIT)
     {
         return coap_tcp_32bit;
     }
-    else
-    {
-        return coap_tcp;
-    }
+
+    return -1;
 }
 
 coap_transport_type coap_get_tcp_header_type_from_initbyte(unsigned int length)
@@ -436,14 +456,9 @@ size_t coap_get_opt_header_length(unsigned short key, size_t length)
     {
         optDeltaLength = 1;
     }
-    else if (COAP_OPTION_FIELD_16_BIT < key && COAP_OPTION_FIELD_32_BIT >= key)
-    {
-        optDeltaLength = 2;
-    }
     else
     {
-        printf("Error : Reserved for the Payload marker for Delta");
-        return 0;
+        optDeltaLength = 2;
     }
 
     size_t optLength = 0;
index 1e19c85..d461913 100644 (file)
@@ -316,7 +316,10 @@ typedef struct
 
 /** Options in coap_pdu_t are accessed with the macro COAP_OPTION. */
 #define COAP_OPTION(node) ((coap_option *)(node)->options)
-
+#ifdef __cplusplus
+extern "C"
+{
+#endif
 #ifdef WITH_LWIP
 /**
  * Creates a CoAP PDU from an lwIP @p pbuf, whose reference is passed on to
@@ -395,6 +398,15 @@ int coap_pdu_parse(unsigned char *data, size_t length, coap_pdu_t *pdu,
 
 #ifdef WITH_TCP
 /**
+ * Get total message length from header.
+ *
+ * @param data   The raw data to parse as CoAP PDU.
+ * @param size   payload size of pdu.
+ * @return Total message length.
+ */
+size_t coap_get_total_message_length(const unsigned char *data, size_t size);
+
+/**
  * Get transport type of coap header for coap over tcp through payload size.
  *
  * @param size   payload size of pdu.
@@ -541,5 +553,7 @@ int coap_add_data(coap_pdu_t *pdu, unsigned int len, const unsigned char *data);
  * destroyed with the pdu.
  */
 int coap_get_data(const coap_pdu_t *pdu, size_t *len, unsigned char **data);
-
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
 #endif /* _PDU_H_ */
diff --git a/resource/csdk/connectivity/lib/tizen/ble/inc/bluetooth.h b/resource/csdk/connectivity/lib/tizen/ble/inc/bluetooth.h
deleted file mode 100644 (file)
index a6574c7..0000000
+++ /dev/null
@@ -1,4474 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd 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.
- */
-
-
-#ifndef __TIZEN_NETWORK_BLUETOOTH_H__
-#define __TIZEN_NETWORK_BLUETOOTH_H__
-
-#include <stdlib.h>
-#include <unistd.h>
-#include <stdbool.h>
-#include <tizen_error.h>
-
-#include "bluetooth_type.h"
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif /* __cplusplus */
-
-/**
- * @file        bluetooth.h
- * @brief       API to control the Bluetooth adapter and devices and communications.
- * @ingroup     CAPI_NETWORK_BLUETOOTH_MODULE
- */
-
-
-/**
- * @addtogroup CAPI_NETWORK_BLUETOOTH_MODULE
- * @{
- */
-
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_MODULE
- * @brief Initializes the Bluetooth API.
- * @since_tizen 2.3
- *
- * @remarks This function must be called before Bluetooth API starts. \n
- * You must free all resources of the Bluetooth service by calling bt_deinitialize() if Bluetooth service is no longer needed.
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- *
- * @see  bt_deinitialize()
- */
-int bt_initialize(void);
-
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_MODULE
- * @brief Releases all resources of the Bluetooth API.
- * @since_tizen 2.3
- *
- * @remarks This function must be called if Bluetooth API is no longer needed.
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- *
- * @pre Bluetooth API must be initialized with bt_initialize().
- *
- * @see bt_initialize()
- */
-int bt_deinitialize(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief Enables the local Bluetooth adapter, asynchronously.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- *
- * @details This function enables Bluetooth protocol stack and hardware.
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_ALREADY_DONE  Already enabled
- * @retval #BT_ERROR_NOW_IN_PROGRESS  Operation now in progress
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre Bluetooth service must be initialized with bt_initialize().
- * @pre The state of local Bluetooth must be #BT_ADAPTER_DISABLED
- * @post This function invokes bt_adapter_state_changed_cb().
- *
- * @see bt_initialize()
- * @see bt_adapter_get_state()
- * @see bt_adapter_set_state_changed_cb()
- * @see bt_adapter_unset_state_changed_cb()
- * @see bt_adapter_state_changed_cb()
- *
- */
-int bt_adapter_enable(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief Disables the local Bluetooth adapter, asynchronously.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- *
- * @details This function disables Bluetooth protocol stack and hardware.
- *
- * @remarks You should disable Bluetooth adapter, which is helpful for saving power.
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_NOW_IN_PROGRESS  Operation now in progress
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED
- * @post This function invokes bt_adapter_state_changed_cb().
- *
- * @see bt_adapter_get_state()
- * @see bt_adapter_state_changed_cb()
- * @see bt_adapter_set_state_changed_cb()
- * @see bt_adapter_unset_state_changed_cb ()
- *
- */
-int bt_adapter_disable(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief Recover the local Bluetooth adapter, asynchronously.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- *
- * @details This function does recovery logic, disables Bluetooth protocol stack and hardware, then enables after a few seconds.
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_NOW_IN_PROGRESS  Operation now in progress
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED
- * @post This function invokes bt_adapter_state_changed_cb().
- *
- * @see bt_adapter_get_state()
- * @see bt_adapter_state_changed_cb()
- * @see bt_adapter_set_state_changed_cb()
- * @see bt_adapter_unset_state_changed_cb ()
- *
- */
-int bt_adapter_recover(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief Reset the local Bluetooth adapter, synchronously.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- *
- * @details This function resets Bluetooth protocol and values.
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_OPERATION_FAILED Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre Bluetooth service must be initialized with bt_initialize().
- * @post bt_adapter_state_changed_cb() will be invoked if The state of local Bluetooth was #BT_ADAPTER_ENABLED.
- *
- * @see bt_initialize()
- * @see bt_adapter_get_state()
- * @see bt_adapter_set_state_changed_cb()
- * @see bt_adapter_unset_state_changed_cb()
- * @see bt_adapter_state_changed_cb()
- *
- */
-int bt_adapter_reset(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief Gets the current state of local Bluetooth adapter.
- * @since_tizen 2.3
- *
- * @param[out] adapter_state The current adapter state
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- *
- * @pre Bluetooth service must be initialized with bt_initialize().
- *
- * @see bt_initialize()
- */
-int bt_adapter_get_state(bt_adapter_state_e *adapter_state);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief Gets the address of local Bluetooth adapter.
- * @since_tizen 2.3
- *
- * @remarks The @a local_address must be released with free() by you.
- *
- * @param[out] local_address The device address of local Bluetooth adapter
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
- * @retval #BT_ERROR_OPERATION_FAILED Operation failed
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @see bt_adapter_get_name()
- */
-int bt_adapter_get_address(char **local_address);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief Gets the version of local Bluetooth adapter.
- * @since_tizen 2.3
- * @remarks The @a local_version must be released with free() by you.
- *
- * @param[out] local_version The version of local Bluetooth adapter
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
- * @retval #BT_ERROR_OPERATION_FAILED Operation failed
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- */
-int bt_adapter_get_version(char **local_version);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief Gets the information regarding local Bluetooth adapter.
- * @since_tizen 2.3
- * @remarks The @a all parameters must be released with free() by you.
- *
- * @param[out] chipset Chipset name of local Bluetooth adapter
- * @param[out] firmware Firmware info. of local Bluetooth adapter
- * @param[out] stack_version Bluetooth stack version
- * @param[out] profiles The profile list of local Bluetooth adapter
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
- * @retval #BT_ERROR_OPERATION_FAILED Operation failed
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- */
-int bt_adapter_get_local_info(char **chipset, char **firmware, char **stack_version, char **profiles);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief Gets the name of local Bluetooth adapter.
- * @since_tizen 2.3
- *
- * @details Use this function to get the friendly name associated with Bluetooth
- * device, retrieved by the remote Bluetooth devices.
- *
- * @remarks The @a local_name must be released with free() by you.
- *
- * @param[out] local_name  The local device name
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- *
- * @see bt_adapter_set_name()
- */
-int bt_adapter_get_name(char **local_name);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief Sets the name of local Bluetooth adapter.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- *
- * @param[in] local_name The name of the Bluetooth device. \n
- *                             The maximum length is 248 characters.
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @post bt_adapter_name_changed_cb() will be invoked if this function returns #BT_ERROR_NONE.
- *
- * @see bt_adapter_get_name()
- * @see bt_adapter_name_changed_cb()
- * @see bt_adapter_set_name_changed_cb()
- * @see bt_adapter_unset_name_changed_cb()
- */
-int bt_adapter_set_name(const char *local_name);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief  Gets the visibility mode of local Bluetooth adapter.
- * @since_tizen 2.3
- * @param[out] mode  The visibility mode of the Bluetooth device
- * @param[out] duration  The duration until the visibility mode is changed to #BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE (in seconds).
- * @a duration is valid only if @a mode is #BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE. This value can be NULL.
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- */
-int bt_adapter_get_visibility(bt_adapter_visibility_mode_e *mode, int *duration);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief Sets the visibility mode.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- *
- * @remarks #BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE will change to #BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE
- * after the given @a duration goes.
- *
- * @param[in] discoverable_mode The Bluetooth visibility mode to set
- * @param[in] duration The duration until the visibility mode is changed to #BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE (in seconds).
- * @a duration is used only for #BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE mode.
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @post bt_adapter_visibility_mode_changed_cb() will be invoked if this function returns #BT_ERROR_NONE.
- *
- * @see bt_adapter_get_visibility()
- * @see bt_adapter_visibility_mode_changed_cb()
- * @see bt_adapter_set_visibility_mode_changed_cb()
- * @see bt_adapter_unset_visibility_mode_changed_cb()
- */
-int bt_adapter_set_visibility(bt_adapter_visibility_mode_e discoverable_mode, int duration);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief Starts the device discovery, asynchronously.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- *
- * @details If a device is discovered, bt_adapter_device_discovery_state_changed_cb() will be invoked
- * with #BT_ADAPTER_DEVICE_DISCOVERY_FOUND, and then bt_adapter_device_discovery_state_changed_cb()
- * will be called with #BT_ADAPTER_DEVICE_DISCOVERY_FINISHED in case of the completion or cancellation of the discovery.
- *
- * @remarks To connect to peer Bluetooth device, you need to know its Bluetooth address. \n
- * The device discovery can be stopped by bt_adapter_stop_device_discovery().
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_NOW_IN_PROGRESS  Operation is now in progress
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @post This function invokes bt_adapter_device_discovery_state_changed_cb().
- *
- * @see bt_adapter_is_discovering()
- * @see bt_adapter_stop_device_discovery()
- * @see bt_adapter_device_discovery_state_changed_cb()
- * @see bt_adapter_set_device_discovery_state_changed_cb()
- * @see bt_adapter_unset_device_discovery_state_changed_cb()
- */
-int bt_adapter_start_device_discovery(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief Stops the device discovery, asynchronously.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @remarks The device discovery process will take 10 ~ 20 seconds to get all the devices in vicinity.
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_NOT_IN_PROGRESS  Operation is not in progress
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The device discovery must be in progress with bt_adapter_start_device_discovery().
- * @post This function invokes bt_adapter_device_discovery_state_changed_cb().
- *
- * @see bt_adapter_is_discovering()
- * @see bt_adapter_start_device_discovery()
- * @see bt_adapter_set_device_discovery_state_changed_cb()
- * @see bt_adapter_unset_device_discovery_state_changed_cb()
- * @see bt_adapter_device_discovery_state_changed_cb()
- */
-int bt_adapter_stop_device_discovery(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief Checks for the device discovery is in progress or not.
- * @since_tizen 2.3
- *
- * @remarks If Bluetooth discovery is in progress, other operations are not allowed and
- * you have to either stop the discovery operation, or wait for it to be finished,
- * before performing other operations.
-
- * @param[out] is_discovering The discovering status: (@c true = in progress , @c  false = not in progress )
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- *
- * @see bt_adapter_start_device_discovery()
- * @see bt_adapter_stop_device_discovery()
- */
-int bt_adapter_is_discovering(bool *is_discovering);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Get the service mask from the uuid list.
- * @since_tizen 2.3
- *
- * @param[in] uuids The UUID list of the device.
- * @param[in] no_of_service The number of the UUID list count.
- * @param[out] service_mask_list Service mask list converted from the given UUID list.
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- *
- * @see bt_service_class_t
- */
-int bt_device_get_service_mask_from_uuid_list(char **uuids,
-                                     int no_of_service,
-                                     bt_service_class_t *service_mask_list);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief Retrieves the device information of all bonded devices.
- * @since_tizen 2.3
- *
- * @param [in] callback The callback function to invoke
- * @param [in] user_data The user data passed from the foreach function
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @post This function invokes bt_adapter_bonded_device_cb().
- *
- * @see bt_adapter_bonded_device_cb()
- */
-int bt_adapter_foreach_bonded_device(bt_adapter_bonded_device_cb callback, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief Gets the device information of a bonded device.
- * @since_tizen 2.3
- * @remarks The @a device_info must be released with bt_adapter_free_device_info() by you .
- *
- * @param [in] remote_address The address of remote device
- * @param [out] device_info The bonded device information
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device not bonded
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @post This function invokes bt_adapter_bonded_device_cb().
- *
- * @see bt_adapter_bonded_device_cb()
- */
-int bt_adapter_get_bonded_device_info(const char *remote_address, bt_device_info_s **device_info);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief Frees device info.
- * @since_tizen 2.3
- *
- * @param [in] device_info The bonded device information
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- *
- * @see bt_adapter_get_bonded_device_info()
- */
-int bt_adapter_free_device_info(bt_device_info_s *device_info);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief Checks whether the UUID of service is used or not
- * @since_tizen 2.3
- * @param[in] service_uuid The UUID of service
- * @param[out] used Indicates whether the service is used or not
- * @return true on success, otherwise false.
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- */
-int bt_adapter_is_service_used(const char *service_uuid, bool *used);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief  Registers a callback function to be invoked when the Bluetooth adapter state changes.
- * @since_tizen 2.3
- *
- * @param[in] callback The callback function to invoke
- * @param[in] user_data        The user data to be passed to the callback function
- *
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- *
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @post bt_adapter_state_changed_cb() will be invoked.
- *
- * @see bt_initialize()
- * @see bt_adapter_state_changed_cb()
- * @see bt_adapter_set_state_changed_cb()
- * @see bt_adapter_unset_state_changed_cb()
- */
-int bt_adapter_set_state_changed_cb(bt_adapter_state_changed_cb callback, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief      Unregisters the callback function.
- * @since_tizen 2.3
- *
- * @return     0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- *
- * @pre The Bluetooth service must be initialized with bt_initialize().
- *
- * @see bt_initialize()
- * @see bt_adapter_set_state_changed_cb()
- */
-int bt_adapter_unset_state_changed_cb(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief  Registers a callback function to be invoked when the name of Bluetooth adapter changes.
- * @since_tizen 2.3
- *
- * @param[in] callback The callback function to invoke
- * @param[in] user_data The user data to be passed to the callback function
- *
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- *
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @post  bt_adapter_name_changed_cb() will be invoked.
- *
- * @see bt_initialize()
- * @see bt_adapter_name_changed_cb()
- * @see bt_adapter_unset_name_changed_cb()
- */
-int bt_adapter_set_name_changed_cb(bt_adapter_name_changed_cb callback, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief      Unregisters the callback function.
- * @since_tizen 2.3
- *
- * @return     0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- *
- * @pre The Bluetooth service must be initialized with bt_initialize().
- *
- * @see bt_initialize()
- * @see bt_adapter_set_name_changed_cb()
- */
-int bt_adapter_unset_name_changed_cb(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief  Registers a callback function to be invoked when the visibility mode changes.
- * @since_tizen 2.3
- *
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- *
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- *
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @post bt_adapter_visibility_mode_changed_cb() will be invoked.
- *
- * @see bt_initialize()
- * @see bt_adapter_visibility_mode_changed_cb()
- * @see bt_adapter_unset_visibility_mode_changed_cb()
- */
-int bt_adapter_set_visibility_mode_changed_cb(bt_adapter_visibility_mode_changed_cb callback, void *user_data);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief  Unregisters the callback function.
- * @since_tizen 2.3
- *
- * @return  0 on success, otherwise a negative error value.
- * @retval  #BT_ERROR_NONE  Successful
- * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
- *
- * @pre  The Bluetooth service must be initialized with bt_initialize().
- *
- * @see  bt_initialize()
- * @see  bt_adapter_set_visibility_mode_changed_cb()
- */
-int bt_adapter_unset_visibility_mode_changed_cb(void);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief  Registers a callback function to be invoked every second
- * @since_tizen 2.3
- * until the visibility mode is changed from #BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE
- * to #BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE.
- * @details  When you set visibility mode as #BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE,
- * @a callback will be called every second until visibility mode is changed to #BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE.
- * @param[in]  callback  The callback function to register
- * @param[in]  user_data  The user data to be passed to the callback function
- * @return  0 on success, otherwise a negative error value.
- * @retval  #BT_ERROR_NONE  Successful
- * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @pre  The Bluetooth service must be initialized by bt_initialize().
- * @post  bt_adapter_visibility_duration_changed_cb() will be invoked.
- * @see  bt_initialize()
- * @see  bt_adapter_visibility_duration_changed_cb()
- * @see  bt_adapter_unset_visibility_duration_changed_cb()
- */
-int bt_adapter_set_visibility_duration_changed_cb(bt_adapter_visibility_duration_changed_cb callback, void *user_data);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief       Unregisters the callback function.
- * @since_tizen 2.3
- * @return  0 on success, otherwise a negative error value.
- * @retval  #BT_ERROR_NONE  Successful
- * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @pre  The Bluetooth service must be initialized with bt_initialize().
- * @see  bt_initialize()
- * @see  bt_adapter_set_visibility_duration_changed_cb()
- */
-int bt_adapter_unset_visibility_duration_changed_cb(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief  Registers a callback function to be invoked when the device discovery state changes.
- * @since_tizen 2.3
- *
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- *
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- *
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @post bt_adapter_device_discovery_state_changed_cb() will be invoked.
- *
- * @see bt_initialize()
- * @see bt_adapter_device_discovery_state_changed_cb()
- * @see bt_adapter_set_device_discovery_state_changed_cb()
- * @see bt_adapter_unset_device_discovery_state_changed_cb()
- */
-int bt_adapter_set_device_discovery_state_changed_cb(bt_adapter_device_discovery_state_changed_cb callback, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief      Unregisters the callback function.
- * @since_tizen 2.3
- *
- * @return     0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- *
- * @pre The Bluetooth service must be initialized with bt_initialize().
- *
- * @see bt_initialize()
- * @see bt_adapter_set_device_discovery_state_changed_cb()
- */
-int bt_adapter_unset_device_discovery_state_changed_cb(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief Get the Hash and Randmoizer value, synchronously.
- * @since_tizen 2.3
- *
- * @param[out] hash The hash value recieved from the controller
- * @param[out] randomizer The hash value recieved from the controller
- * @param[out] hash_len The length of the hash value
- * @param[out] randomizer_len The length of the randomizer value
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @see bt_initialize()
- */
-int bt_adapter_get_local_oob_data(unsigned char **hash, unsigned char **randomizer,
-                                       int *hash_len, int *randomizer_len);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief Sets the Hash and Randmoizer value, synchronously.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- *
- * @param[in] remote_address Remote device address
- * @param[in] hash The hash value recieved from the controller
- * @param[in] randomizer The hash value recieved from the controller
- * @param[in] hash_len The length of the hash value. Allowed value is 16
- * @param[in] randomizer_len The length of the randomizer value. Allowed value is 16
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @see bt_initialize()
- */
-int bt_adapter_set_remote_oob_data(const char *remote_address,
-                               unsigned char *hash, unsigned char *randomizer,
-                               int hash_len, int randomizer_len);
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief Deletes the Hash and Randomizer value, synchronously.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- *
- * @param[in] remote_address Remote device address
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @see bt_initialize()
- */
-int bt_adapter_remove_remote_oob_data(const char *remote_address);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief  Registers a callback function to be invoked when the connectable state changes.
- * @since_tizen 2.3
- *
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- *
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- *
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @post bt_adapter_connectable_changed_cb() will be invoked.
- *
- * @see bt_initialize()
- * @see bt_adapter_connectable_changed_cb()
- * @see bt_adapter_unset_connectable_changed_cb()
- */
-int bt_adapter_set_connectable_changed_cb(bt_adapter_connectable_changed_cb callback, void *user_data);
-
-/**
- * @internal
- * @ingroup  CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief  Unregisters the callback function.
- * @since_tizen 2.3
- *
- * @return  0 on success, otherwise a negative error value.
- * @retval  #BT_ERROR_NONE  Successful
- * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
- *
- * @pre  The Bluetooth service must be initialized with bt_initialize().
- *
- * @see  bt_initialize()
- * @see  bt_adapter_set_connectable_changed_cb()
- */
-int bt_adapter_unset_connectable_changed_cb(void);
-
-/**
- * @internal
- * @ingroup  CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief  Gets the connectable state of local Bluetooth adapter.
- * @since_tizen 2.3
- *
- * @remarks When connectable state is false, no device can connect to this device and visibility mode cannot be changed.
- *
- * @param[out] connectable The connectable state of local Bluetooth adapter
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- *
- * @see bt_adapter_set_connectable()
- */
-int bt_adapter_get_connectable(bool *connectable);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief  Sets the connectable state of local Bluetooth adapter.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- *
- * @remarks When connectable state is false, no device can connect to this device and visibility mode cannot be changed.
- *
- * @param[in] connectable The connectable state to set
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @post bt_adapter_connectable_changed_cb() will be invoked if this function returns #BT_ERROR_NONE.
- *
- * @see bt_adapter_get_connectable()
- * @see bt_adapter_connectable_changed_cb()
- * @see bt_adapter_set_connectable_changed_cb()
- * @see bt_adapter_unset_connectable_changed_cb()
- */
-int bt_adapter_set_connectable(bool connectable);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief Enables the local Bluetooth le adapter, asynchronously.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- *
- * @details This function enables Bluetooth protocol stack and hardware.
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_ALREADY_DONE  Already enabled
- * @retval #BT_ERROR_NOW_IN_PROGRESS  Operation now in progress
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre Bluetooth service must be initialized with bt_initialize().
- * @post This function invokes bt_adapter_le_state_changed_cb().
- *
- * @see bt_initialize()
- * @see bt_adapter_le_get_state()
- * @see bt_adapter_le_set_state_changed_cb()
- * @see bt_adapter_le_unset_state_changed_cb()
- * @see bt_adapter_le_state_changed_cb()
- *
- */
-int bt_adapter_le_enable(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief Disables the local Bluetooth le adapter, asynchronously.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- *
- * @details This function disables Bluetooth le protocol stack and hardware.
- *
- * @remarks
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_NOW_IN_PROGRESS  Operation now in progress
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_LE_ENABLED
- * @post This function invokes bt_adapter_le_state_changed_cb().
- *
- * @see bt_adapter_le_get_state()
- * @see bt_adapter_le_state_changed_cb()
- * @see bt_adapter_le_set_state_changed_cb()
- * @see bt_adapter_le_unset_state_changed_cb ()
- *
- */
-int bt_adapter_le_disable(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief Gets the current state of local Bluetooth adapter.
- * @since_tizen 2.3
- *
- * @param[out] adapter_le_state The current adapter le state
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- *
- * @pre Bluetooth service must be initialized with bt_initialize().
- *
- * @see bt_initialize()
- */
-int bt_adapter_le_get_state(bt_adapter_le_state_e *adapter_le_state);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief Starts the LE device discovery for a BT_ADAPTER_DEVICE_DISCOVERY_LE type.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- *
- * @details If a LE device is discovered, bt_adapter_le_device_discovery_state_changed_cb()
-*  will be invoked with #BT_ADAPTER_LE_DEVICE_DISCOVERY_FOUND, and then bt_adapter_le_device_discovery_state_changed_cb()
- * will be called with #BT_ADAPTER_LE_DEVICE_DISCOVERY_FINISHED in case of the completion or cancellation of the discovery.
- *
- * @remarks To connect to peer Bluetooth device, you need to know its Bluetooth address. \n
- * The device discovery can be stopped by bt_adapter_le_stop_device_discovery().
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_NOW_IN_PROGRESS  Operation is now in progress
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * or must be #BT_ADAPTER_LE_ENABLED.
- * @post This function invokes bt_adapter_le_device_discovery_state_changed_cb().
- *
- * @see bt_adapter_le_is_discovering()
- * @see bt_adapter_le_device_discovery_state_changed_cb()
- * @see bt_adapter_le_set_device_discovery_state_changed_cb()
- * @see bt_adapter_le_unset_device_discovery_state_changed_cb()
- */
-int bt_adapter_le_start_device_discovery(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief Stops the LE device discovery, asynchronously.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_NOT_IN_PROGRESS  Operation is not in progress
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The device discovery must be in progress with bt_adapter_le_start_device_discovery().
- * @post This function invokes bt_adapter_le_device_discovery_state_changed_cb().
- *
- * @see bt_adapter_le_is_discovering()
- * @see bt_adapter_le_start_device_discovery()
- * @see bt_adapter_le_set_device_discovery_state_changed_cb()
- * @see bt_adapter_le_unset_device_discovery_state_changed_cb()
- * @see bt_adapter_le_device_discovery_state_changed_cb()
- */
-int bt_adapter_le_stop_device_discovery(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief Checks for the LE device discovery is in progress or not.
- * @since_tizen 2.3
- *
- * @remarks If Bluetooth LE discovery is in progress, other operations are not allowed and
- * you have to either stop the LE discovery operation, or wait for it to be finished,
- * before performing other operations.
-
- * @param[out] is_discovering The discovering status: (@c true = in progress , @c  false = not in progress )
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * or must be #BT_ADAPTER_LE_ENABLED.
- *
- * @see bt_adapter_le_start_device_discovery()
- * @see bt_adapter_le_stop_device_discovery()
- */
-int bt_adapter_le_is_discovering(bool *is_discovering);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief  Registers a callback function to be invoked when the LE device discovery state changes.
- * @since_tizen 2.3
- *
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- *
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- *
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @post bt_adapter_le_device_discovery_state_changed_cb() will be invoked.
- *
- * @see bt_initialize()
- * @see bt_adapter_le_device_discovery_state_changed_cb()
- * @see bt_adapter_le_unset_device_discovery_state_changed_cb()
- */
-int bt_adapter_le_set_device_discovery_state_changed_cb(bt_adapter_le_device_discovery_state_changed_cb callback, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief      Unregisters the callback function.
- * @since_tizen 2.3
- *
- * @return     0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- *
- * @pre The Bluetooth service must be initialized with bt_initialize().
- *
- * @see bt_initialize()
- * @see bt_adapter_le_set_device_discovery_state_changed_cb()
- */
-int bt_adapter_le_unset_device_discovery_state_changed_cb(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief  Registers a callback function to be invoked when the Bluetooth adapter le state changes.
- * @since_tizen 2.3
- *
- * @param[in] callback The callback function to invoke
- * @param[in] user_data        The user data to be passed to the callback function
- *
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- *
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @post bt_adapter_le_state_changed_cb() will be invoked.
- *
- * @see bt_initialize()
- * @see bt_adapter_le_state_changed_cb()
- * @see bt_adapter_le_unset_state_changed_cb()
- */
-int bt_adapter_le_set_state_changed_cb(bt_adapter_le_state_changed_cb callback, void *user_data);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief      Unregisters the callback function.
- * @since_tizen 2.3
- *
- * @return     0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- *
- * @pre The Bluetooth service must be initialized with bt_initialize().
- *
- * @see bt_initialize()
- * @see bt_adapter_le_set_state_changed_cb()
- */
-int bt_adapter_le_unset_state_changed_cb(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief add address to whitelist for accepting scanning request.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- *
- * @remarks If the adress is in the whitelist then other LE devices are able to
- * search this device. Before calling this API, make sure that the adapter is
- * enabled. There is no callback event for this API.
-
- * @param[in] address The other device's address
- * @param[in] address_type The other device's address type
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Adapter is not enabled
- * @retval #BT_ERROR_RESOURCE_BUSY  Device or resource busy
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- *
- * @see bt_adapter_le_start_advertising()
- * @see bt_adapter_le_stop_advertising()
- */
-int bt_adapter_le_add_white_list(const char *address, bt_device_address_type_e address_type);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief remove address from the whitelist for not accepting scanning request.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- *
- * @remarks If the adress is in the whitelist then other LE devices are able to
- * search this device. Before calling this API, make sure that the adapter is
- * enabled. There is no callback event for this API.
- *
- * @param[in] address The other device's address
- * @param[in] address_type The other device's address type
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Adapter is not enabled
- * @retval #BT_ERROR_RESOURCE_BUSY  Device or resource busy
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- *
- * @see bt_adapter_le_start_advertising()
- * @see bt_adapter_le_stop_advertising()
- */
-int bt_adapter_le_remove_white_list(const char *address, bt_device_address_type_e address_type);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief clear address from the whitelist for not accepting scanning request.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- *
- * @remarks If the adress is in the whitelist then other LE devices are able to
- * search this device. Before calling this API, make sure that the adapter is
- * enabled. There is no callback event for this API.
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Adapter is not enabled
- * @retval #BT_ERROR_RESOURCE_BUSY  Device or resource busy
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- *
- * @see bt_adapter_le_start_advertising()
- * @see bt_adapter_le_stop_advertising()
- */
-int bt_adapter_le_clear_white_list(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief Create advertiser to advertise device's existence or respond to LE scanning reqeust.
- * @since_tizen 2.3
- *
- * @param[out] advertiser The handle of advertiser
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
- *
- * @pre The Bluetooth service must be initialized with bt_initialize().
- *
- * @see bt_adapter_le_destroy_advertiser()
- */
-int bt_adapter_le_create_advertiser(bt_advertiser_h *advertiser);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief Destroy advertiser.
- * @since_tizen 2.3
- *
- * @param[out] advertiser The handle of advertiser
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- *
- * @pre The Bluetooth service must be initialized with bt_initialize().
- *
- * @see bt_adapter_le_create_advertiser()
- */
-int bt_adapter_le_destroy_advertiser(bt_advertiser_h advertiser);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief Set the data to be advertised or responded to scan request from LE scanning device.
- *        The maximum advertised or responded data size is 31 bytes
- *        including data type and system wide data.
- * @since_tizen 2.3
- *
- * @param[in] advertiser The handle of advertiser
- * @param[in] pkt_type The packet type
- * @param[in] data_type The data type that is included in packet
- * @param[in] data The data to be advertised or be responded to scan request from LE scanning device
- * @param[in] data_size The size of data to be set.
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_QUOTA_EXCEEDED  Quota exceeded
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- *
- * @pre The Bluetooth service must be initialized with bt_initialize().
- *
- * @see bt_adapter_le_remove_advertising_data()
- * @see bt_adapter_le_clear_advertising_data()
- */
-int bt_adapter_le_add_advertising_data(bt_advertiser_h advertiser,
-               bt_adapter_le_packet_type_e pkt_type, bt_adapter_le_packet_data_type_e data_type,
-               void *data, unsigned int data_size);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief Unset the data to be advertised or responded to scan request from LE scanning device.
- * @since_tizen 2.3
- *
- * @param[in] advertiser The handle of advertiser
- * @param[in] pkt_type The packet type
- * @param[in] data_type The data type to be removed from selected packet
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- *
- * @pre The Bluetooth service must be initialized with bt_initialize().
- *
- * @see bt_adapter_le_add_advertising_data()
- * @see bt_adapter_le_clear_advertising_data()
- */
-int bt_adapter_le_remove_advertising_data(bt_advertiser_h advertiser,
-               bt_adapter_le_packet_type_e pkt_type, bt_adapter_le_packet_data_type_e data_type);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief Clear all data to be advertised or responded to scan request from LE scanning device.
- * @since_tizen 2.3
- *
- * @param[in] advertiser The handle of advertiser
- * @param[in] pkt_type The packet type to be cleared
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- *
- * @pre The Bluetooth service must be initialized with bt_initialize().
- *
- * @see bt_adapter_le_add_advertising_data()
- * @see bt_adapter_le_remove_advertising_data()
- */
-int bt_adapter_le_clear_advertising_data(bt_advertiser_h advertiser, bt_adapter_le_packet_type_e pkt_type);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief Start advertising with passed advertiser and advertising parameters.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- *
- * @details Once Bluetooth advertising is started, nearby Bluetooth LE(Low Energy) supported
- * devices can know this device's existence. And one of them can make a connection reqeust,
- * if it is allowed.
- *
- * @param[in] advertiser The handle of advertiser
- * @param[in] adv_params The parameters of advertising \n
- * If NULL is passed, default values which are defined in driver / controller are used.
- * @param[in] cb The callback to report the result of this function
- * @param[in] user_data The user data to be passed when callback is called
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_NOW_IN_PROGRESS  Operation is now in progress
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @post This function invokes bt_adapter_le_advertising_state_changed_cb().
- *
- * @see bt_adapter_le_stop_advertising()
- * @see bt_adapter_le_advertising_state_changed_cb()
- */
-int bt_adapter_le_start_advertising(bt_advertiser_h advertiser, bt_adapter_le_advertising_params_s *adv_params,
-               bt_adapter_le_advertising_state_changed_cb cb, void *user_data);
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief Stops the advertising.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- *
- * @param[in] advertiser The handle of advertiser
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_NOT_IN_PROGRESS  Operation is not in progress
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The advertising must be going on with bt_adapter_le_start_advertising().
- * @post This function invokes bt_adapter_le_advertising_state_changed_cb().
- *
- * @see bt_adapter_le_start_advertising()
- * @see bt_adapter_le_advertising_state_changed_cb()
- */
-int bt_adapter_le_stop_advertising(bt_advertiser_h advertiser);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief  Sets the Privacy feature state of local Bluetooth adapter.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- *
- * @param[in] enable_privacy The privacy feature to set/unset.
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @pre The state of local Bluetooth must be #BT_ADAPTER_LE_ENABLED.
- *
- */
-int bt_adapter_le_enable_privacy(bool enable_privacy);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Creates a bond with a remote Bluetooth device, asynchronously.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- *
- * @remarks A bond can be destroyed by bt_device_destroy_bond().\n
- * The bonding request can be cancelled by bt_device_cancel_bonding().
- *
- * @param[in] remote_address The address of the remote Bluetooth device with which the bond should be created
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_RESOURCE_BUSY  Device or resource busy
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @pre The remote device must be discoverable with bt_adapter_start_device_discovery().
- * @post This function invokes bt_device_bond_created_cb().
- *
- * @see bt_adapter_start_device_discovery()
- * @see bt_device_bond_created_cb()
- * @see bt_device_cancel_bonding()
- * @see bt_device_destroy_bond()
- * @see bt_device_set_bond_created_cb()
- * @see bt_device_unset_bond_created_cb()
- */
-int bt_device_create_bond(const char *remote_address);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Creates a bond with a remote Bluetooth device, asynchronously.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- *
- * @remarks A bond can be destroyed by bt_device_destroy_bond().\n
- * The bonding request can be cancelled by bt_device_cancel_bonding().
- *
- * @param[in] remote_address The address of the remote Bluetooth device with which the bond should be created
- * @param[in] conn_type The connection type(LE or BREDR) to create bond with remote device
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_RESOURCE_BUSY     Device or resource busy
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @pre The remote device must be discoverable with bt_adapter_start_device_discovery().
- * @post This function invokes bt_device_bond_created_cb().
- *
- * @see bt_adapter_start_device_discovery()
- * @see bt_device_create_bond()
- * @see bt_device_bond_created_cb()
- * @see bt_device_cancel_bonding()
- * @see bt_device_destroy_bond()
- * @see bt_device_set_bond_created_cb()
- * @see bt_device_unset_bond_created_cb()
- */
-int bt_device_create_bond_by_type(const char *remote_address,
-                                 bt_device_connection_link_type_e conn_type);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Cancels the bonding process.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- *
- * @remarks Use this function when the remote Bluetooth device is not responding to the
- * bond request or you wish to cancel the bonding request.
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_NOT_IN_PROGRESS  Operation not in progress
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The creating a bond must be in progress by bt_device_create_bond().
- *
- * @see bt_device_create_bond()
- * @see bt_device_bond_created_cb()
- * @see bt_device_set_bond_created_cb()
- * @see bt_device_unset_bond_created_cb()
- */
-int bt_device_cancel_bonding(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Destroys the bond, asynchronously.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- *
- * @param[in] remote_address The address of the remote Bluetooth device to remove bonding
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_RESOURCE_BUSY  Device or resource busy
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device not bonded
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @pre The bond with the remote device must be created with bt_device_create_bond().
- * @post This function invokes bt_device_bond_destroyed_cb().
- *
- * @see bt_device_create_bond()
- * @see bt_device_bond_destroyed_cb()
- * @see bt_device_set_bond_destroyed_cb()
- * @see bt_device_unset_bond_destroyed_cb()
- */
-int bt_device_destroy_bond(const char *remote_address);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Sets an alias for the bonded device.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- *
- * @param[in] remote_address The address of the remote Bluetooth device
- * @param[in] alias The alias of the remote Bluetooth device
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device not bonded
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @pre The bond with the remote device must be created with bt_device_create_bond().
- *
- * @see bt_device_create_bond()
- */
-int bt_device_set_alias(const char *remote_address, const char *alias);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Sets the authorization of a bonded device, asynchronously.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- *
- * @remarks Once a device is authorized, you don't need to receive a confirmation.
- *
- * @param[in] remote_address The address of the remote Bluetooth device to authorize
- * @param[in] authorization_state The Bluetooth authorization state
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device not bonded
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @pre The bond with the remote device must be created with bt_device_create_bond().
- * @post bt_device_authorization_changed_cb() will be invoked.
- *
- * @see bt_device_create_bond()
- * @see bt_device_authorization_changed_cb()
- * @see bt_device_set_authorization_changed_cb()
- * @see bt_device_unset_authorization_changed_cb()
- */
-int bt_device_set_authorization(const char *remote_address, bt_device_authorization_e authorization_state);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Starts the search for services supported by the specified device, asynchronously.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- *
- * @remarks If creating a bond succeeds, which means bt_device_bond_created_cb() is called with result #BT_ERROR_NONE,
- * then you don't need to run this function.\n
- * The service search takes a couple of seconds to complete normally. \n
- * The service search can be canceled by bt_device_cancel_service_search().
- *
- * @param[in] remote_address The address of the remote Bluetooth device whose services need to be checked
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device not bonded
- * @retval #BT_ERROR_SERVICE_SEARCH_FAILED  Service search failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @pre The remote device must be discoverable with bt_adapter_start_device_discovery().
- * @pre The bond with the remote device must be created with bt_device_create_bond().
- * @post This function invokes bt_device_service_searched_cb().
- *
- * @see bt_adapter_start_device_discovery()
- * @see bt_device_create_bond()
- * @see bt_device_bond_created_cb()
- * @see bt_device_service_searched_cb()
- * @see bt_device_cancel_service_search()
- * @see bt_device_set_service_searched_cb()
- * @see bt_device_unset_service_searched_cb()
- */
-int bt_device_start_service_search(const char *remote_address);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Cancels service search process.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device not bonded
- * @retval #BT_ERROR_NOT_IN_PROGRESS  Operation not in progress
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The service search must be in progress by bt_device_start_service_search().
- *
- * @see bt_device_start_service_search()
- * @see bt_device_service_searched_cb()
- * @see bt_device_set_service_searched_cb()
- * @see bt_device_unset_service_searched_cb()
- */
-int bt_device_cancel_service_search(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Gets the connected profiles.
- * @since_tizen 2.3
- * @param[in] remote_address The address of the remote device
- * @param[in] callback The callback function to invoke
- * @param[in] user_data The user data to be passed to the callback function
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @post bt_device_connected_profile() will be invoked.
- * @see bt_device_connected_profile()
- */
-int bt_device_foreach_connected_profiles(const char *remote_address, bt_device_connected_profile callback, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Gets the profile connected status.
- * @since_tizen 2.3
- * @param[in] remote_address The address of the remote device
- * @param[in] bt_profile wish to know bt_profile
- * @param[out] connected_status the connected status
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device not bonded
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- */
-int bt_device_is_profile_connected(const char *remote_address, bt_profile_e bt_profile,
-                                       bool *connected_status);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief  Registers a callback function to be invoked when the bond creates.
- * @since_tizen 2.3
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @post  bt_device_bond_created_cb() will be invoked.
- * @see bt_initialize()
- * @see bt_device_bond_created_cb()
- * @see bt_device_unset_bond_created_cb()
- */
-int bt_device_set_bond_created_cb(bt_device_bond_created_cb callback, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief      Unregisters the callback function.
- * @since_tizen 2.3
- * @return     0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @see bt_initialize()
- * @see bt_device_set_bond_created_cb()
- */
-int bt_device_unset_bond_created_cb(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief  Registers a callback function to be invoked when the bond destroys.
- * @since_tizen 2.3
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @post  bt_device_bond_destroyed_cb() will be invoked.
- * @see bt_initialize()
- * @see bt_device_bond_destroyed_cb()
- * @see bt_device_unset_bond_destroyed_cb()
- */
-int bt_device_set_bond_destroyed_cb(bt_device_bond_destroyed_cb callback, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief      Unregisters the callback function.
- * @since_tizen 2.3
- * @return     0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @see bt_initialize()
- * @see bt_device_set_bond_destroyed_cb()
- */
-int bt_device_unset_bond_destroyed_cb(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief  Registers a callback function to be invoked when the authorization of device changes.
- * @since_tizen 2.3
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @post  bt_device_authorization_changed_cb() will be invoked.
- * @see bt_initialize()
- * @see bt_device_authorization_changed_cb()
- * @see bt_device_set_authorization_changed_cb()
- * @see bt_device_unset_authorization_changed_cb()
- */
-int bt_device_set_authorization_changed_cb(bt_device_authorization_changed_cb callback, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief      Unregisters the callback function.
- * @since_tizen 2.3
- * @return     0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @see bt_initialize()
- * @see bt_device_set_authorization_changed_cb()
- */
-int bt_device_unset_authorization_changed_cb(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief  Registers a callback function to be invoked when the process of service search finishes.
- * @since_tizen 2.3
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @post  bt_device_service_searched_cb() will be invoked.
- * @see bt_initialize()
- * @see bt_device_service_searched_cb()
- * @see bt_device_unset_service_searched_cb()
- */
-int bt_device_set_service_searched_cb(bt_device_service_searched_cb callback, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief      Unregisters the callback function.
- * @since_tizen 2.3
- * @return     0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @see bt_initialize()
- * @see bt_device_set_service_searched_cb()
- */
-int bt_device_unset_service_searched_cb(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief  Registers a callback function to be invoked when the connection state is changed.
- * @since_tizen 2.3
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @post bt_device_connection_state_changed_cb() will be invoked.
- * @see bt_initialize()
- * @see bt_device_connection_state_changed_cb()
- * @see bt_device_unset_connection_state_changed_cb()
- */
-int bt_device_set_connection_state_changed_cb(bt_device_connection_state_changed_cb callback, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief      Unregisters the callback function to be invoked when the connection state is changed.
- * @since_tizen 2.3
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @see bt_initialize()
- * @see bt_device_set_connection_state_changed_cb()
- */
-int bt_device_unset_connection_state_changed_cb(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
- * @brief Registers a rfcomm server socket with a specific UUID.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- *
- * @remarks A socket can be destroyed by bt_socket_destroy_rfcomm().
- *
- * @param[in] service_uuid The UUID of service to provide
- * @param[out] socket_fd The file descriptor of socket to listen
- * @return 0 on success, otherwise a negative error value.
- *
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- *
- * @see bt_socket_listen_and_accept_rfcomm()
- * @see bt_socket_destroy_rfcomm()
- */
-int bt_socket_create_rfcomm(const char *service_uuid, int *socket_fd);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
- * @brief Removes the rfcomm server socket which was created using bt_socket_create_rfcomm().
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @remarks If callback function bt_socket_connection_state_changed_cb() is set and the remote Bluetooth device is connected,
- * then bt_socket_connection_state_changed_cb() will be called when this function is finished successfully.
- *
- * @param[in] socket_fd The file descriptor of socket (which was created using bt_socket_create_rfcomm()) to destroy
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The socket must be created with bt_socket_create_rfcomm().
- * @post If callback function bt_socket_connection_state_changed_cb() is set and the remote Bluetooth device is connected,
- * then bt_socket_connection_state_changed_cb() will be called.
- * @see bt_socket_create_rfcomm()
- * @see bt_socket_connection_state_changed_cb()
- * @see bt_socket_set_connection_state_changed_cb()
- * @see bt_socket_unset_connection_state_changed_cb()
- */
-int bt_socket_destroy_rfcomm(int socket_fd);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
- * @brief Starts listening on passed rfcomm socket and accepts connection requests.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @details Pop-up is shown automatically when a RFCOMM connection is requested.
- * bt_socket_connection_state_changed_cb() will be called with
- * #BT_SOCKET_CONNECTED if you click "yes" and connection is finished successfully.
- * @param[in] socket_fd The file descriptor of socket on which start to listen
- * @param[in] max_pending_connections The maximum number of pending connections
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The socket must be created with bt_socket_create_rfcomm().
- * @post If callback function bt_socket_connection_state_changed_cb() is set,
- * then bt_socket_connection_state_changed_cb() will be called when the remote Bluetooth device is connected.
- * @see bt_socket_create_rfcomm()
- * @see bt_socket_connection_state_changed_cb()
- * @see bt_socket_set_connection_state_changed_cb()
- * @see bt_socket_unset_connection_state_changed_cb()
- */
-int bt_socket_listen_and_accept_rfcomm(int socket_fd, int max_pending_connections);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
- * @brief Starts listening on passed rfcomm socket.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @details bt_socket_connection_requested_cb() will be called when a RFCOMM connection is requested.
- *
- * @param[in] socket_fd  The file descriptor socket on which start to listen
- * @param[in] max_pending_connections  The number of pending connections
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The socket must be created with bt_socket_create_rfcomm().
- * @post This function invokes bt_socket_connection_state_changed_cb().
- *
- * @see bt_socket_create_rfcomm()
- * @see bt_socket_set_connection_requested_cb()
- * @see bt_socket_unset_connection_requested_cb()
- * @see bt_socket_connection_requested_cb()
- */
-int bt_socket_listen(int socket_fd, int max_pending_connections);
-
-/**
- * @internal
- * @ingroup  CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
- * @brief  Accepts a connection request.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @param[in] requested_socket_fd  The file descriptor of socket on which a connection is requested
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The connection is requested by bt_socket_connection_requested_cb().
- * @see bt_socket_create_rfcomm()
- * @see bt_socket_connection_requested_cb()
- * @see bt_socket_listen()
- * @see bt_socket_reject()
-*/
-int bt_socket_accept(int requested_socket_fd);
-
-/**
- * @internal
- * @ingroup  CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
- * @brief  Rejects a connection request.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @param[in] socket_fd  The file descriptor of socket on which a connection is requested
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The connection is requested by bt_socket_connection_requested_cb().
- * @see bt_socket_create_rfcomm()
- * @see bt_socket_connection_requested_cb()
- * @see bt_socket_listen()
- * @see bt_socket_accept()
- */
-int bt_socket_reject(int socket_fd);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
- * @brief Connects to a specific RFCOMM based service on a remote Bluetooth device UUID, asynchronously.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- *
- * @remarks A connection can be disconnected by bt_socket_disconnect_rfcomm().
- *
- * @param[in] remote_address The address of the remote Bluetooth device
- * @param[in] service_uuid The UUID of service provided by the remote Bluetooth device
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device not bonded
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @pre The remote device must be discoverable with bt_adapter_start_device_discovery().
- * @pre The bond with the remote device must be created with bt_device_create_bond().
- * @post This function invokes bt_socket_connection_state_changed_cb().
- *
- * @see bt_device_create_bond()
- * @see bt_adapter_start_device_discovery()
- * @see bt_device_start_service_search()
- * @see bt_socket_disconnect_rfcomm()
- * @see bt_socket_connection_state_changed_cb()
- * @see bt_socket_set_connection_state_changed_cb()
- * @see bt_socket_unset_connection_state_changed_cb()
- */
-int bt_socket_connect_rfcomm(const char *remote_address, const char *service_uuid);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
- * @brief Disconnects the RFCOMM connection with the given file descriptor of conneted socket.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @param[in] socket_fd  The file descriptor of socket to close which was received using bt_socket_connection_state_changed_cb().
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The connection must be established.
- *
- * @see bt_socket_connection_state_changed_cb()
- * @see bt_socket_set_connection_state_changed_cb()
- * @see bt_socket_unset_connection_state_changed_cb()
- */
-int bt_socket_disconnect_rfcomm(int socket_fd);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
- * @brief Sends data to the connected device.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @remark The specific error code can be obtained using the get_last_result() method. Error codes are described in Exception section.
- *
- * @param[in] socket_fd The file descriptor of connected socket which was received using bt_socket_connection_state_changed_cb()
- * @param[in] data The data to be sent
- * @param[in] length The length of data to be sent
- *
- * @return the number of bytes written (zero indicates nothing was written).
- * @retval On error, -1 is returned, and errno is set appropriately. See write 2 man page.
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @exception BT_ERROR_NOT_INITIALIZED  Not initialized
- * @exception BT_ERROR_PERMISSION_DENIED  Permission denied
- * @exception BT_ERROR_AGAIN  Resource temporarily unavailable
- *
- * @pre The connection must be established.
- *
- * @see bt_socket_connection_state_changed_cb()
- * @see bt_socket_set_connection_state_changed_cb()
- * @see bt_socket_unset_connection_state_changed_cb()
- */
-int bt_socket_send_data(int socket_fd, const char *data, int length);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
- * @brief  Register a callback function that will be invoked when you receive data.
- * @since_tizen 2.3
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @post  bt_socket_data_received_cb() will be invoked.
- * @see bt_initialize()
- * @see bt_socket_data_received_cb()
- * @see bt_socket_set_data_received_cb()
- * @see bt_socket_unset_data_received_cb()
- */
-int bt_socket_set_data_received_cb(bt_socket_data_received_cb callback, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
- * @brief      Unregisters the callback function.
- * @since_tizen 2.3
- * @return     0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @see bt_initialize()
- * @see bt_socket_data_received_cb()
- * @see bt_socket_set_data_received_cb()
- */
-int bt_socket_unset_data_received_cb(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
- * @brief  Register a callback function that will be invoked when a RFCOMM connection is requested.
- * @since_tizen 2.3
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @post If you listen a socket by bt_socket_listen(), bt_socket_connection_requested_cb() will be invoked.
- * @see bt_initialize()
- * @see bt_socket_unset_connection_requested_cb()
- */
-int bt_socket_set_connection_requested_cb(bt_socket_connection_requested_cb callback, void *user_data);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
- * @brief  Unregisters the callback function.
- * @since_tizen 2.3
- * @return  0 on success, otherwise a negative error value.
- * @retval  #BT_ERROR_NONE  Successful
- * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @pre  The Bluetooth service must be initialized with bt_initialize().
- * @see  bt_initialize()
- * @see  bt_socket_set_connection_requested_cb()
- * @see  bt_socket_connection_requested_cb()
- */
-int bt_socket_unset_connection_requested_cb(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
- * @brief  Register a callback function that will be invoked when the connection state changes.
- * @since_tizen 2.3
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @post bt_socket_connection_state_changed_cb() will be invoked.
- * @see bt_initialize()
- * @see bt_socket_connection_state_changed_cb()
- * @see bt_socket_unset_connection_state_changed_cb()
- */
-int bt_socket_set_connection_state_changed_cb(bt_socket_connection_state_changed_cb callback, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
- * @brief      Unregisters the callback function.
- * @since_tizen 2.3
- * @return     0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @see bt_initialize()
- * @see bt_socket_connection_state_changed_cb()
- * @see bt_socket_set_connection_state_changed_cb()
- */
-int bt_socket_unset_connection_state_changed_cb(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
- * @brief Initializes the Bluetooth OPP server requested by bt_opp_server_push_requested_cb().
- * @since_tizen 2.3
- * @details The popup appears when an OPP connection is requested from a remote device.
- * If you accept the request, then connection will be established and bt_opp_server_push_requested_cb() will be called.
- * At that time, you can call either bt_opp_server_accept() or bt_opp_server_reject().
- * @remarks This function must be called to start Bluetooth OPP server. You must free all resources of the Bluetooth service
- * by calling bt_opp_server_deinitialize() if Bluetooth OPP service is no longer needed.
- * @param[in] destination  The destination path
- * @param[in] push_requested_cb  The callback called when a push is requested
- * @param[in] user_data The user data to be passed to the callback function
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_RESOURCE_BUSY  Device or resource busy
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @see  bt_opp_server_push_requested_cb()
- * @see  bt_opp_server_deinitialize()
- * @see  bt_opp_server_accept()
- * @see  bt_opp_server_reject()
- */
-int bt_opp_server_initialize(const char *destination, bt_opp_server_push_requested_cb push_requested_cb, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
- * @brief Initializes the Bluetooth OPP server requested by bt_opp_server_connection_requested_cb().
- * @since_tizen 2.3
- * @details No popup appears when an OPP connection is requested from a remote device.
- * Instead, @a connection_requested_cb() will be called.
- * At that time, you can call either bt_opp_server_accept() or bt_opp_server_reject().
- * @remarks This function must be called to start Bluetooth OPP server. \n
- * You must free all resources of the Bluetooth service by calling bt_opp_server_deinitialize() if Bluetooth OPP service is no longer needed.
- * @param[in] destination  The destination path
- * @param[in] connection_requested_cb  The callback called when an OPP connection is requested
- * @param[in] user_data The user data to be passed to the callback function
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_RESOURCE_BUSY  Device or resource busy
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @see  bt_opp_server_connection_requested_cb()
- * @see  bt_opp_server_deinitialize()
- * @see  bt_opp_server_accept_connection()
- * @see  bt_opp_server_reject_connection()
- */
-int bt_opp_server_initialize_by_connection_request(const char *destination, bt_opp_server_connection_requested_cb connection_requested_cb, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
- * @brief Denitializes the Bluetooth OPP server.
- * @since_tizen 2.3
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @see  bt_opp_server_initialize()
- * @see  bt_opp_server_deinitialize()
- */
-int bt_opp_server_deinitialize(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
- * @brief Accepts the push request from the remote device.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @remarks If you initialize OPP server by bt_opp_server_initialize_by_connection_request(), then name is ignored.
- * You can cancel the pushes by bt_opp_server_cancel_transfer() with transfer_id.
- * @param[in] progress_cb  The callback called when a file is being transfered
- * @param[in] finished_cb  The callback called when a transfer is finished
- * @param[in] name  The name to store. This can be NULL if you initialize OPP server by bt_opp_server_initialize_by_connection_request().
- * @param[in] user_data The user data to be passed to the callback function
- * @param[out]  transfer_id  The ID of transfer
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_NOW_IN_PROGRESS  Operation now in progress
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @see  bt_opp_server_reject()
- */
-int bt_opp_server_accept(bt_opp_server_transfer_progress_cb progress_cb, bt_opp_server_transfer_finished_cb finished_cb, const char *name,
- void *user_data, int *transfer_id);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
- * @brief Rejects the push request from the remote device.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @see  bt_opp_server_accept()
- */
-int bt_opp_server_reject(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
- * @brief Cancels the transfer.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @param[in] transfer_id  The ID of transfer
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @see  bt_opp_server_accept_connection()
- * @see  bt_opp_server_accept()
- */
-int bt_opp_server_cancel_transfer(int transfer_id);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
- * @brief Sets the destination path of file to be pushed.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @param[in] destination  The destination path of file to be pushed
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @see  bt_opp_server_initialize()
- */
-int bt_opp_server_set_destination(const char *destination);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
- * @brief Initializes the Bluetooth OPP client.
- * @since_tizen 2.3
- * @remarks This function must be called before Bluetooth OPP client starts. \n
- * You must free all resources of the Bluetooth service by calling bt_opp_client_deinitialize()
- * if Bluetooth OPP service is no longer needed.
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_RESOURCE_BUSY  Device or resource busy
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @see  bt_opp_client_deinitialize()
- */
-int bt_opp_client_initialize(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
- * @brief Denitializes the Bluetooth OPP client.
- * @since_tizen 2.3
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @see  bt_opp_client_initialize()
- */
-int bt_opp_client_deinitialize(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
- * @brief Adds file to be pushed.
- * @since_tizen 2.3
- * @param[in] file  The path of file to be pushed
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @see  bt_opp_client_clear_files()
- * @see  bt_opp_client_push_files()
- */
-int bt_opp_client_add_file(const char *file);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
- * @brief Adds file to be pushed.
- * @since_tizen 2.3
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @see  bt_opp_client_add_file()
- * @see  bt_opp_client_push_files()
- */
-int bt_opp_client_clear_files(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
- * @brief Pushes the file to the remote device, asynchronously.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @details At first, bt_opp_client_push_responded_cb() will be called when OPP server responds to the push request.
- * After connection is established, bt_opp_client_push_progress_cb() will be called repeatedly until a file is tranfered completely.
- * If you send several files, then bt_opp_client_push_progress_cb() with another file will be called repeatedly until the file is tranfered completely.
- * bt_opp_client_push_finished_cb() will be called when the push request is finished.
- * @param[in] remote_address The remote address
- * @param[in] responded_cb  The callback called when OPP server responds to the push request
- * @param[in] progress_cb  The callback called when each file is being transfered
- * @param[in] finished_cb  The callback called when the push request is finished
- * @param[in] user_data The user data to be passed to the callback function
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_NOW_IN_PROGRESS  Operation now in progress
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @see bt_opp_client_initialize()
- * @see bt_opp_client_cancel_push
- */
-int bt_opp_client_push_files(const char *remote_address, bt_opp_client_push_responded_cb responded_cb,
- bt_opp_client_push_progress_cb progress_cb, bt_opp_client_push_finished_cb finished_cb, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
- * @brief Cancels the push request in progress, asynchronously.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre bt_opp_client_push_files() must be called.
- * @post bt_opp_client_push_finished_cb() will be invoked with result #BT_ERROR_CANCELLED,
- * which is a parameter of bt_opp_client_push_files().
- * @see bt_opp_client_initialize()
- * @see bt_opp_client_push_files()
- */
-int bt_opp_client_cancel_push(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_HID_MODULE
- * @brief Initializes the Bluetooth HID(Human Interface Device) Host.
- * @since_tizen 2.3
- * @remarks This function must be called before Bluetooth HID Host starts. \n
- * You must free all resources of the Bluetooth service by calling bt_hid_host_deinitialize()
- * if Bluetooth HID Host service is no longer needed.
- * @param[in] connection_cb  The callback called when the connection state is changed
- * @param[in] user_data The user data to be passed to the callback function
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @see bt_initialize()
- * @see  bt_hid_host_deinitialize()
- */
-int bt_hid_host_initialize(bt_hid_host_connection_state_changed_cb connection_cb, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_HID_MODULE
- * @brief Deinitializes the Bluetooth HID(Human Interface Device) Host.
- * @since_tizen 2.3
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @pre The Bluetooth HID service must be initialized with bt_hid_host_initialize().
- * @see  bt_hid_host_initialize()
- */
-int bt_hid_host_deinitialize(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_HID_MODULE
- * @brief Connects the remote device with the HID(Human Interface Device) service, asynchronously.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @param[in] remote_address  The remote address
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device is not bonded
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre The local device must be bonded with the remote device by bt_device_create_bond().
- * @pre The Bluetooth HID service must be initialized with bt_hid_host_initialize().
- * @post bt_hid_host_connection_state_changed_cb() will be invoked.
- * @see bt_hid_host_disconnect()
- * @see bt_hid_host_connection_state_changed_cb()
- */
-int bt_hid_host_connect(const char *remote_address);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_HID_MODULE
- * @brief Disconnects the remote device with the HID(Human Interface Device) service, asynchronously.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @param[in] remote_address  The remote address
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre The remote device must be connected by bt_hid_host_connect().
- * @post bt_hid_host_connection_state_changed_cb() will be invoked.
- * @see bt_hid_host_connect()
- * @see bt_hid_host_connection_state_changed_cb()
- */
-int bt_hid_host_disconnect(const char *remote_address);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_MODULE
- * @brief Initializes the Bluetooth profiles related with audio.
- * @since_tizen 2.3
- * @remarks This function must be called before Bluetooth profiles related with audio starts. \n
- * You must free all resources of the this service by calling bt_audio_deinitialize()
- * if Bluetooth profiles related with audio service is no longer needed.
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @see bt_initialize()
- * @see bt_audio_deinitialize()
- */
-int bt_audio_initialize(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_MODULE
- * @brief Deinitializes the Bluetooth profiles related with audio.
- * @since_tizen 2.3
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
- * @see bt_audio_initialize()
- */
-int bt_audio_deinitialize(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_MODULE
- * @brief Connects the remote device with the given audio profile, asynchronously.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @details If you input type as #BT_AUDIO_PROFILE_TYPE_ALL and connection request succeeds, then bt_audio_connection_state_changed_cb() will be called twice
- * when #BT_AUDIO_PROFILE_TYPE_HSP_HFP is connected and #BT_AUDIO_PROFILE_TYPE_A2DP is connected.
- * @param[in] remote_address  The remote address
- * @param[in] type  The type of audio profile
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device is not bonded
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
- * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
- * @pre The local device must be bonded with the remote device by bt_device_create_bond().
- * @post bt_audio_connection_state_changed_cb() will be invoked.
- * @see bt_audio_disconnect()
- * @see bt_audio_connection_state_changed_cb()
- */
-int bt_audio_connect(const char *remote_address, bt_audio_profile_type_e type);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_MODULE
- * @brief Disconnects the remote device with the given audio profile, asynchronously.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @details If you input type as #BT_AUDIO_PROFILE_TYPE_ALL and disconnection request succeeds, then bt_audio_connection_state_changed_cb() will be called twice
- * when #BT_AUDIO_PROFILE_TYPE_HSP_HFP is disconnected and #BT_AUDIO_PROFILE_TYPE_A2DP is disconnected.
- * @param[in] remote_address  The remote address
- * @param[in] type  The type of audio profile
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
- * @pre The remote device must be connected by bt_audio_connect().
- * @post bt_audio_connection_state_changed_cb() will be invoked.
- * @see bt_audio_connect()
- * @see bt_audio_connection_state_changed_cb()
- */
-int bt_audio_disconnect(const char *remote_address, bt_audio_profile_type_e type);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_MODULE
- * @brief  Registers a callback function that will be invoked when the connection state is changed.
- * @since_tizen 2.3
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
- * @see bt_audio_initialize()
- * @see bt_audio_connection_state_changed_cb()
- * @see bt_panu_unset_connection_state_changed_cb()
- */
-int bt_audio_set_connection_state_changed_cb(bt_audio_connection_state_changed_cb callback, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_MODULE
- * @brief  Unregisters a callback function that will be invoked when the connection state is changed.
- * @since_tizen 2.3
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
- * @see bt_audio_initialize()
- * @see bt_audio_connection_state_changed_cb()
- * @see bt_audio_set_connection_state_changed_cb()
- */
-int bt_audio_unset_connection_state_changed_cb(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief Opens a SCO(Synchronous Connection Oriented link) to connected remote device, asynchronously.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device is not bonded
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
- * @retval #BT_ERROR_ALREADY_DONE  Operation is already done
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
- * @pre The Bluetooth audio device must be connected with bt_audio_connect().
- * @post bt_ag_sco_state_changed_cb() will be invoked.
- * @see bt_ag_close_sco()
- * @see bt_ag_sco_state_changed_cb()
- * @see bt_audio_connect()
- */
-int bt_ag_open_sco(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief Closes an opened SCO(Synchronous Connection Oriented link), asynchronously.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device is not bonded
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
- * @pre The SCO must be opened with bt_ag_open_sco().
- * @post bt_ag_sco_state_changed_cb() will be invoked.
- * @see bt_ag_open_sco()
- * @see bt_ag_sco_state_changed_cb()
- */
-int bt_ag_close_sco(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief Checks whether an opened SCO(Synchronous Connection Oriented link) exists or not.
- * @since_tizen 2.3
- * @param[out] opened The SCO status: (@c true = opened, @c  false = not opened)
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
- * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
- * @see bt_ag_open_sco()
- * @see bt_ag_close_sco()
- */
-int bt_ag_is_sco_opened(bool *opened);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Registers a callback function that will be invoked when the SCO(Synchronous Connection Oriented link) state is changed.
- * @since_tizen 2.3
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
- * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
- * @see bt_audio_initialize()
- * @see bt_ag_sco_state_changed_cb()
- * @see bt_ag_unset_sco_state_changed_cb()
- */
-int bt_ag_set_sco_state_changed_cb(bt_ag_sco_state_changed_cb callback, void *user_data);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Unregisters a callback function that will be invoked when the SCO(Synchronous Connection Oriented link) state is changed.
- * @since_tizen 2.3
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
- * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
- * @see bt_audio_initialize()
- * @see bt_ag_sco_state_changed_cb()
- * @see bt_ag_set_sco_state_changed_cb()
- */
-int bt_ag_unset_sco_state_changed_cb(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief Notifies the call event to the remote bluetooth device.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @remarks Before notifying #BT_AG_CALL_EVENT_ANSWERED or #BT_AG_CALL_EVENT_DIALING, you should open SCO(Synchronous Connection Oriented link)
- * if Bluetooth Hands-Free need SCO connection.
- * @param[in] event  The call event
- * @param[in] call_id  The call ID
- * @param[in] phone_number  The phone number. You must set this value in case of #BT_AG_CALL_EVENT_DIALING and #BT_AG_CALL_EVENT_INCOMING.
- * In other cases, this value can be NULL.
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device is not bonded
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
- * @pre The Bluetooth audio device must be connected with bt_audio_connect().
- * @see bt_audio_connect()
- */
-int bt_ag_notify_call_event(bt_ag_call_event_e event, unsigned int call_id, const char *phone_number);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief Notifies the call list to the remote bluetooth device.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @param[in] list  The call list
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device is not bonded
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
- * @pre The Bluetooth audio device must be connected with bt_audio_connect().
- * @see bt_audio_connect()
- */
-int bt_ag_notify_call_list(bt_call_list_h list);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief Notifies the state of voice recognition.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @param[in] state  The state of voice recognition: (@c true = enabled, @c  false = disabled)
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device is not bonded
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
- * @pre The Bluetooth audio device must be connected with bt_audio_connect().
- * @see bt_audio_connect()
- */
-int bt_ag_notify_voice_recognition_state(bool state);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Registers a callback function that will be invoked when a call handling event happened from Hands-Free.
- * @since_tizen 2.3
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
- * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
- * @see bt_audio_initialize()
- * @see bt_ag_call_handling_event_cb()
- * @see bt_ag_unset_call_handling_event_cb()
- */
-int bt_ag_set_call_handling_event_cb(bt_ag_call_handling_event_cb callback, void *user_data);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Unregisters a callback function that will be invoked when a call handling event happened from Hands-Free.
- * @since_tizen 2.3
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
- * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
- * @see bt_audio_initialize()
- * @see bt_ag_call_handling_event_cb()
- * @see bt_ag_set_call_handling_event_cb()
- */
-int bt_ag_unset_call_handling_event_cb(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Registers a callback function that will be invoked when a multi call handling event happened from Hands-Free.
- * @since_tizen 2.3
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
- * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
- * @see bt_audio_initialize()
- * @see bt_ag_multi_call_handling_event_cb()
- * @see bt_ag_unset_multi_call_handling_event_cb()
- */
-int bt_ag_set_multi_call_handling_event_cb(bt_ag_multi_call_handling_event_cb callback, void *user_data);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Unregisters a callback function that will be invoked when a multi call handling event happened from Hands-Free.
- * @since_tizen 2.3
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
- * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
- * @see bt_audio_initialize()
- * @see bt_ag_multi_call_handling_event_cb()
- * @see bt_ag_set_multi_call_handling_event_cb()
- */
-int bt_ag_unset_multi_call_handling_event_cb(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Registers a callback function that will be invoked when a DTMF(Dual Tone Multi Frequency) is transmitted from Hands-Free.
- * @since_tizen 2.3
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
- * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
- * @see bt_audio_initialize()
- * @see bt_ag_dtmf_transmitted_cb()
- * @see bt_ag_unset_dtmf_transmitted_cb()
- */
-int bt_ag_set_dtmf_transmitted_cb(bt_ag_dtmf_transmitted_cb callback, void *user_data);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Unregisters a callback function that will be invoked when a DTMF(Dual Tone Multi Frequency) is transmitted from Hands-Free.
- * @since_tizen 2.3
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
- * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
- * @see bt_audio_initialize()
- * @see bt_ag_dtmf_transmitted_cb()
- * @see bt_ag_set_dtmf_transmitted_cb()
- */
-int bt_ag_unset_dtmf_transmitted_cb(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Notifies the speaker gain to the remote device.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @details This function sends a signal to the remote device. This signal has the gain value.
- * @a gain is represented on a scale from 0 to 15. This value is absolute value relating to a particular volume level.
- * When the speaker gain of remote device is changed to the requested gain, bt_audio_speaker_gain_changed_cb() will be called.
- * @param[in] gain The gain of speaker (0 ~ 15)
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
- * @pre The remote device is connected by bt_audio_connect() with #BT_AUDIO_PROFILE_TYPE_HSP_HFP service.
- * @see bt_ag_get_speaker_gain()
- * @see bt_ag_set_speaker_gain_changed_cb()
- * @see bt_ag_unset_speaker_gain_changed_cb()
- */
-int bt_ag_notify_speaker_gain(int gain);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Gets the current speaker gain of the remote device.
- * @since_tizen 2.3
- * @details This function gets the value of speaker gain of the remote device.
- * @a gain is represented on a scale from 0 to 15. This value is absolute value relating to a particular volume level.
- * @param[out] gain The gain of speaker (0 ~ 15)
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
- * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
- * @pre The remote device is connected by bt_audio_connect() with #BT_AUDIO_PROFILE_TYPE_HSP_HFP service.
- * @see bt_ag_notify_speaker_gain()
- * @see bt_ag_set_speaker_gain_changed_cb()
- * @see bt_ag_unset_speaker_gain_changed_cb()
- */
-int bt_ag_get_speaker_gain(int *gain);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief Checks whether the remoted device enables NREC(Noise Reduction and Echo Canceling) or not.
- * @since_tizen 2.3
- * @param[out] enabled The NREC status: (@c true = enabled, @c  false = not enabled)
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
- * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
- * @pre The remote device is connected by bt_audio_connect() with #BT_AUDIO_PROFILE_TYPE_HSP_HFP service.
- * @see bt_audio_connect()
- */
-int bt_ag_is_nrec_enabled(bool *enabled);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Registers a callback function that will be invoked when the speaker gain of the remote device is changed.
- * @since_tizen 2.3
- * @details This function let you know the change of the speaker gain of the remote device.
- * @a gain is represented on a scale from 0 to 15. This value is absolute value relating to a particular volume level.
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
- * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
- * @see bt_audio_initialize()
- * @see bt_ag_unset_speaker_gain_changed_cb()
- */
-int bt_ag_set_speaker_gain_changed_cb(bt_ag_speaker_gain_changed_cb callback, void *user_data);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Unregisters a callback function that will be invoked when the speaker gain of the remote device is changed.
- * @since_tizen 2.3
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
- * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
- * @see bt_audio_initialize()
- * @see bt_ag_set_speaker_gain_changed_cb()
- */
-int bt_ag_unset_speaker_gain_changed_cb(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Registers a callback function that will be invoked when the microphone gain of the remote device is changed.
- * @since_tizen 2.3
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
- * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
- * @see bt_audio_initialize()
- * @see bt_ag_unset_microphone_gain_changed_cb()
- */
-int bt_ag_set_microphone_gain_changed_cb(bt_ag_microphone_gain_changed_cb callback, void *user_data);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Unregisters a callback function that will be invoked when the microphone gain of the remote device is changed.
- * @since_tizen 2.3
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
- * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
- * @see bt_audio_initialize()
- * @see bt_ag_set_microphone_gain_changed_cb()
- */
-int bt_ag_unset_microphone_gain_changed_cb(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_CALL_MODULE
- * @brief Creates a handle of call list.
- * @since_tizen 2.3
- * @param[out] list  The handle of call list
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @see bt_call_list_destroy()
- */
-int bt_call_list_create(bt_call_list_h *list);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_CALL_MODULE
- * @brief Destroys the handle of call list.
- * @since_tizen 2.3
- * @param[in] list  The handle of call list
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @see bt_call_list_create()
- */
-int bt_call_list_destroy(bt_call_list_h list);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_CALL_MODULE
- * @brief Resets the handle of call list.
- * @since_tizen 2.3
- * @param[in] list  The handle of call list
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @see bt_call_list_create()
- */
-int bt_call_list_reset(bt_call_list_h list);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_CALL_MODULE
- * @brief Adds a call to the handle of call list.
- * @since_tizen 2.3
- * @param[in] list  The handle of call list
- * @param[in] call_id  The call ID
- * @param[in] state  The state of audio gate call
- * @param[in] phone_number The phone number. You must set this value in case of #BT_AG_CALL_EVENT_DIALING and      #BT_AG_CALL_EVENT_INCOMING.
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
- * @see bt_call_list_create()
- */
-int bt_call_list_add(bt_call_list_h list, unsigned int call_id, bt_ag_call_state_e state, const char *phone_number);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief Initializes the Bluetooth AVRCP(Audio/Video Remote Control Profile) service.
- * @since_tizen 2.3
- * @remarks This function must be called before Bluetooth AVRCP service. \n
- * You must free all resources of the this service by calling bt_avrcp_target_deinitialize()
- * if Bluetooth AVRCP service is no longer needed.
- * @param[in] callback The callback function called when the connection state is changed
- * @param[in] user_data The user data to be passed to the callback function
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @see bt_initialize()
- * @see bt_avrcp_target_deinitialize()
- */
-int bt_avrcp_target_initialize(bt_avrcp_target_connection_state_changed_cb callback, void *user_data);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief Deinitializes the Bluetooth AVRCP(Audio/Video Remote Control Profile) service.
- * @since_tizen 2.3
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @pre The Bluetooth audio service must be initialized with bt_avrcp_target_initialize().
- * @see bt_avrcp_target_initialize()
- */
-int bt_avrcp_target_deinitialize(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief  Notifies the equalize state to the remote device.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @param[in] state The state of equalizer
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre The remote device must be connected.
- * @see bt_avrcp_target_connection_state_changed_cb()
- * @see bt_avrcp_target_initialize()
- */
-int bt_avrcp_target_notify_equalizer_state(bt_avrcp_equalizer_state_e state);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief  Notifies the repeat mode to the remote device.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @param[in] mode The repeat mode
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre The remote device must be connected.
- * @see bt_avrcp_target_connection_state_changed_cb()
- * @see bt_avrcp_target_initialize()
- */
-int bt_avrcp_target_notify_repeat_mode(bt_avrcp_repeat_mode_e mode);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief  Notifies the shuffle mode to the remote device.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @param[in] mode The repeat mode
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre The remote device must be connected.
- * @see bt_avrcp_target_connection_state_changed_cb()
- * @see bt_avrcp_target_initialize()
- */
-int bt_avrcp_target_notify_shuffle_mode(bt_avrcp_shuffle_mode_e mode);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief  Notifies the scan mode to the remote device.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @param[in] mode The scan mode
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre The remote device must be connected.
- * @see bt_avrcp_target_connection_state_changed_cb()
- * @see bt_avrcp_target_initialize()
- */
-int bt_avrcp_target_notify_scan_mode(bt_avrcp_scan_mode_e mode);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief  Notifies the player state to the remote device.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @param[in] state The player state
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre The remote device must be connected.
- * @see bt_avrcp_target_connection_state_changed_cb()
- * @see bt_avrcp_target_initialize()
- */
-int bt_avrcp_target_notify_player_state(bt_avrcp_player_state_e state);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief  Notifies the current position of song to the remote device.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @param[in] position The current position in milliseconds
- * @return  0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre The remote device must be connected.
- * @see bt_avrcp_target_connection_state_changed_cb()
- * @see bt_avrcp_target_initialize()
- */
-int bt_avrcp_target_notify_position(unsigned int position);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief  Notifies the track to the remote device.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @param[in] title The title of track
- * @param[in] artist The artist of track
- * @param[in] album The album of track
- * @param[in] genre The genre of track
- * @param[in] track_num The track number
- * @param[in] total_tracks The number of all tracks
- * @param[in] duration The duration of track in milliseconds
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre The remote device must be connected.
- * @see bt_avrcp_target_connection_state_changed_cb()
- * @see bt_avrcp_target_initialize()
- */
-int bt_avrcp_target_notify_track(const char *title, const char *artist, const char *album, const char *genre, unsigned int track_num, unsigned int total_tracks, unsigned int duration);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief  Registers a callback function that will be invoked when the equalizer state is changed by the remote control device.
- * @since_tizen 2.3
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @pre The Bluetooth service must be initialized by bt_initialize().
- * @see bt_initialize()
- * @see bt_avrcp_unset_equalizer_state_changed_cb()
- */
-int bt_avrcp_set_equalizer_state_changed_cb(bt_avrcp_equalizer_state_changed_cb callback, void *user_data);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief  Unregisters a callback function that will be invoked when the equalizer state is changed by the remote control device.
- * @since_tizen 2.3
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @pre The Bluetooth service must be initialized by bt_initialize().
- * @see bt_initialize()
- * @see bt_avrcp_set_equalizer_state_changed_cb()
- */
-int bt_avrcp_unset_equalizer_state_changed_cb(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief  Registers a callback function that will be invoked when the repeat mode is changed by the remote control device.
- * @since_tizen 2.3
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @pre The Bluetooth service must be initialized by bt_initialize().
- * @see bt_initialize()
- * @see bt_avrcp_unset_repeat_mode_changed_cb()
- */
-int bt_avrcp_set_repeat_mode_changed_cb(bt_avrcp_repeat_mode_changed_cb callback, void *user_data);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief  Unregisters a callback function that will be invoked when the repeat mode is changed by the remote control device.
- * @since_tizen 2.3
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @pre The Bluetooth service must be initialized by bt_initialize().
- * @see bt_initialize()
- * @see bt_avrcp_set_repeat_mode_changed_cb()
- */
-int bt_avrcp_unset_repeat_mode_changed_cb(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief  Registers a callback function that will be invoked when the shuffle mode is changed by the remote control device.
- * @since_tizen 2.3
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @pre The Bluetooth service must be initialized by bt_initialize().
- * @see bt_initialize()
- * @see bt_avrcp_unset_shuffle_mode_changed_cb()
- */
-int bt_avrcp_set_shuffle_mode_changed_cb(bt_avrcp_shuffle_mode_changed_cb callback, void *user_data);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief  Unregisters a callback function that will be invoked when the shuffle mode is changed by the remote control device.
- * @since_tizen 2.3
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @pre The Bluetooth service must be initialized by bt_initialize().
- * @see bt_initialize()
- * @see bt_avrcp_set_shuffle_mode_changed_cb()
- */
-int bt_avrcp_unset_shuffle_mode_changed_cb(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief  Registers a callback function that will be invoked when the scan mode is changed by the remote control device.
- * @since_tizen 2.3
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @pre The Bluetooth service must be initialized by bt_initialize().
- * @see bt_initialize()
- * @see bt_avrcp_unset_scan_mode_changed_cb()
- */
-int bt_avrcp_set_scan_mode_changed_cb(bt_avrcp_scan_mode_changed_cb callback, void *user_data);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief  Unregisters a callback function that will be invoked when the scan mode is changed by the remote control device.
- * @since_tizen 2.3
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @pre The Bluetooth service must be initialized by bt_initialize().
- * @see bt_initialize()
- * @see bt_avrcp_set_scan_mode_changed_cb()
- */
-int bt_avrcp_unset_scan_mode_changed_cb(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
- * @brief Registers an application that acts as the @a Sink role of HDP(Health Device Profile).
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @remarks The @a app_id must be released with free() by you.
- * @param[in] data_type  The data type of MDEP. This value is defined in ISO/IEEE 11073-20601 spec.
- * For example, pulse oximeter is 0x1004 and blood pressure monitor is 0x1007.
- * @param[out] app_id  The ID of application
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @see bt_hdp_deactivate_sink()
- */
-int bt_hdp_register_sink_app(unsigned short data_type, char **app_id);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
- * @brief Unregisters the given application that acts as the @a Sink role of HDP(Health Device Profile).
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @param[in] app_id  The ID of application
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @see bt_hdp_register_sink_app()
- */
-int bt_hdp_unregister_sink_app(const char *app_id);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
- * @brief Connects the remote device which acts as @a Source role, asynchronously.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @param[in] remote_address  The remote address
- * @param[in] app_id  The ID of application
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device is not bonded
- * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre The Sink role of HDP must be registered with bt_hdp_register_sink_app().
- * @pre The local device must be bonded with the remote device by bt_device_create_bond().
- * @post bt_hdp_connected_cb() will be invoked.
- * @see bt_hdp_disconnect()
- * @see bt_hdp_set_connection_state_changed_cb()
- * @see bt_hdp_unset_connection_state_changed_cb()
- */
-int bt_hdp_connect_to_source(const char *remote_address, const char *app_id);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
- * @brief Disconnects the remote device, asynchronously.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @param[in] remote_address  The remote address
- * @param[in] channel  The connected data channel
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
- * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre The remote device must be connected.
- * @post bt_hdp_disconnected_cb() will be invoked.
- * @see bt_hdp_set_connection_state_changed_cb()
- * @see bt_hdp_unset_connection_state_changed_cb()
- */
-int bt_hdp_disconnect(const char *remote_address, unsigned int channel);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
- * @brief Sends the data to the remote device.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @param[in] channel  The connected data channel
- * @param[in] data  The data to send
- * @param[in] size  The size of data to send (byte)
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre The remote device must be connected.
- * @see bt_hdp_data_received_cb()
- * @see bt_hdp_set_data_received_cb()
- * @see bt_hdp_unset_data_received_cb()
- */
-int bt_hdp_send_data(unsigned int channel, const char *data, unsigned int size);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
- * @brief  Registers a callback function that will be invoked when the connection state is changed.
- * @since_tizen 2.3
- * @param[in] connected_cb The callback function called when a connection is established
- * @param[in] disconnected_cb The callback function called when a connection is disconnected
- * @param[in] user_data The user data to be passed to the callback function
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @see bt_hdp_unset_connection_state_changed_cb()
- */
-int bt_hdp_set_connection_state_changed_cb(bt_hdp_connected_cb connected_cb, bt_hdp_disconnected_cb disconnected_cb, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
- * @brief  Unregisters a callback function that will be invoked when the connection state is changed.
- * @since_tizen 2.3
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @see bt_hdp_set_connection_state_changed_cb()
- */
-int bt_hdp_unset_connection_state_changed_cb(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
- * @brief  Registers a callback function that will be invoked when you receive the data.
- * @since_tizen 2.3
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @see bt_hdp_unset_data_received_cb()
- */
-int bt_hdp_set_data_received_cb(bt_hdp_data_received_cb callback, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
- * @brief  Unregisters a callback function that will be invoked when you receive the data.
- * @since_tizen 2.3
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @see bt_hdp_set_data_received_cb()
- */
-int bt_hdp_unset_data_received_cb(void);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Gets the primary services of GATT(Generic Attribute Profile).
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @param[in]  remote_address  The address of the remote device
- * @param[in]  callback  The callback function to invoke
- * @param[in]  user_data  The user data to be passed to the callback function
- * @return  0 on success, otherwise a negative error value.
- * @retval  #BT_ERROR_NONE  Successful
- * @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval  #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval  #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @post  @a callback will be called if there are primary services.
- * @see  bt_gatt_primary_service_cb()
- */
-int bt_gatt_foreach_primary_services(const char *remote_address, bt_gatt_primary_service_cb callback, void *user_data);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Discovers the characteristics in service, asynchronously.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @param[in]  service  The attribute handle of service
- * @param[in]  callback  The result callback
- * @param[in]  user_data  The user data to be passed to the callback function
- * @return  0 on success, otherwise a negative error value.
- * @retval  #BT_ERROR_NONE  Successful
- * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval  #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @post  @a callback will be called.
- * @see  bt_gatt_characteristics_discovered_cb()
- */
-int bt_gatt_discover_characteristics(bt_gatt_attribute_h service, bt_gatt_characteristics_discovered_cb callback, void *user_data);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Gets the UUID of service.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @remarks  @a uuid must be released with free() by you.
- * @param[in]  service  The attribute handle of service
- * @param[out]  uuid  The UUID of service
- * @return  0 on success, otherwise a negative error value.
- * @retval  #BT_ERROR_NONE  Successful
- * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval  #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval  #BT_ERROR_OUT_OF_MEMORY  Out of memory
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- */
-int bt_gatt_get_service_uuid(bt_gatt_attribute_h service, char **uuid);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Gets the included services in service.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @param[in]  service  The attribute handle of service
- * @param[in]  callback  The callback function to invoke
- * @param[in]  user_data  The user data to be passed to the callback function
- * @return  0 on success, otherwise a negative error value.
- * @retval  #BT_ERROR_NONE  Successful
- * @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval  #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval  #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @post  @a callback will be called if there are included services.
- * @see  bt_gatt_included_service_cb()
- */
-int bt_gatt_foreach_included_services(bt_gatt_attribute_h service, bt_gatt_included_service_cb callback, void *user_data);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Registers a callback function that will be invoked when a characteristic value is changed.
- * @since_tizen 2.3
- * @param[in]  callback  The callback function to register
- * @param[in]  user_data  The user data to be passed to the callback function
- * @return  0 on success, otherwise a negative error value.
- * @retval  #BT_ERROR_NONE  Successful
- * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @pre  The Bluetooth service must be initialized with bt_initialize().
- * @see  bt_gatt_unset_characteristic_changed_cb()
- */
-int bt_gatt_set_characteristic_changed_cb(bt_gatt_characteristic_changed_cb callback, void *user_data);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Unregisters a callback function that will be invoked when a characteristic is changed.
- * @since_tizen 2.3
- * @return  0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @see bt_gatt_set_characteristic_changed_cb()
- */
-int bt_gatt_unset_characteristic_changed_cb(void);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Watches all the characteristic value changes of the service
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @param[in]  service  The attribute handle of service
- * @return  0 on success, otherwise a negative error value.
- * @retval  #BT_ERROR_NONE  Successful
- * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre  The Bluetooth service must be initialized with bt_initialize().
- * @see  bt_gatt_unset_characteristic_changed_cb()
- */
-int bt_gatt_watch_characteristic_changes(bt_gatt_attribute_h service);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Remove watching of all the characteristic value changes of the service
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @param[in]  service  The attribute handle of service
- * @return  0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @see bt_gatt_set_characteristic_changed_cb()
- */
-int bt_gatt_unwatch_characteristic_changes(bt_gatt_attribute_h service);
-
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Gets the characteristic declaration.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @remarks  @a uuid and @a value must be released with free() by you.
- * @param[in]  characteristic  The attribute handle of characteristic
- * @param[out]  uuid  The UUID of service
- * @param[out]  value  The value of characteristic (byte array)
- * @param[out]  value_length  The length of value
- * @return  0 on success, otherwise a negative error value.
- * @retval  #BT_ERROR_NONE  Successful
- * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval  #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval  #BT_ERROR_OUT_OF_MEMORY  Out of memory
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @see  bt_gatt_set_characteristic_value()
- */
-int bt_gatt_get_characteristic_declaration(bt_gatt_attribute_h characteristic, char **uuid, unsigned char **value, int *value_length);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Sets the value of characteristic.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @param[in]  characteristic  The attribute handle of characteristic
- * @param[in]  value  The value of characteristic (byte array)
- * @param[in]  value_length  The length of value
- * @return  0 on success, otherwise a negative error value.
- * @retval  #BT_ERROR_NONE  Successful
- * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval  #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @see  bt_gatt_get_characteristic_declaration()
- */
-int bt_gatt_set_characteristic_value(bt_gatt_attribute_h characteristic, const unsigned char *value, int value_length);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Sets the value of characteristic request.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @param[in]  characteristic  The attribute handle of characteristic
- * @param[in]  value  The value of characteristic (byte array)
- * @param[in]  value_length  The length of value
-  * @param[in]  callback  The result callback
- * @return  0 on success, otherwise a negative error value.
- * @retval  #BT_ERROR_NONE  Successful
- * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval  #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @see  bt_gatt_get_characteristic_declaration()
- */
-int bt_gatt_set_characteristic_value_request(bt_gatt_attribute_h characteristic, const unsigned char *value,
-                               int value_length, bt_gatt_characteristic_write_cb callback);
-
-/**
-* @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
-* @brief  Clones the attribute handle.
-* @since_tizen 2.3
-* @remarks  @a clone must be released with bt_gatt_destroy_attribute_handle().
-* @param[out]  clone  The cloned attribute handle
-* @param[in]  origin  The origin attribute handle
-* @return  0 on success, otherwise negative error value.
-* @retval  #BT_ERROR_NONE  Successful
-* @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
-* @retval  #BT_ERROR_OUT_OF_MEMORY  Out of memory
-* @see  bt_gatt_destroy_attribute_handle()
-*/
-int bt_gatt_clone_attribute_handle(bt_gatt_attribute_h* clone, bt_gatt_attribute_h origin);
-
-/**
-* @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
-* @brief  Destroys the attribute handle.
-* @since_tizen 2.3
-* @param[in]  handle  The attribute handle
-* @return  0 on success, otherwise negative error value.
-* @retval  #BT_ERROR_NONE  Successful
-* @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
-* @see  bt_gatt_clone_attribute_handle()
-*/
-int bt_gatt_destroy_attribute_handle(bt_gatt_attribute_h handle);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Reads the value of characteristic from remote device
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @param[in]  char_handle  The attribute handle of characteristic
- * @param[in]  callback  The result callback
- * @return     0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE      Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @see  bt_gatt_get_characteristic_declaration()
- */
-int bt_gatt_read_characteristic_value(bt_gatt_attribute_h char_handle,
-               bt_gatt_characteristic_read_cb callback);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Discovers the characteristic descriptors of a characteristic within its definition, asynchronously.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @param[in]  characteristic_handle  The attribute handle of characteristic
- * @param[in]  callback  The result callback
- * @param[in]  user_data  The user data to be passed to the callback function
- * @return  0 on success, otherwise a negative error value.
- * @retval  #BT_ERROR_NONE  Successful
- * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval  #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval  #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @post  @a callback will be called.
- * @see  bt_gatt_characteristic_descriptor_discovered_cb()
- */
-int bt_gatt_discover_characteristic_descriptor(bt_gatt_attribute_h characteristic_handle,
-               bt_gatt_characteristic_descriptor_discovered_cb callback,
-               void *user_data);
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Sets the value of characteristic descriptor request.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- * @param[in]  characteristic  The attribute handle of characteristic
- * @param[in]  value  The value of characteristic (byte array), desc handle, desc value
- * @param[in]  value_length  The length of value
-  * @param[in] callback  The result callback
- * @return     0 on success, otherwise a negative error value.
- * @retval     #BT_ERROR_NONE  Successful
- * @retval     #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval     #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval     #BT_ERROR_OPERATION_FAILED      Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
- * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @see  bt_gatt_get_characteristic_declaration()
- */
-int bt_gatt_set_characteristic_desc_value_request(bt_gatt_attribute_h characteristic,
-                               const unsigned char *value, int value_length,
-                               bt_gatt_characteristic_write_cb callback);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief Connect to a specific LE based service on a remote bluetooth dievice address, asynchronously.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- *
- * @remarks A connection can be disconnected by bt_gatt_disconnect().
- *
- * @param[in] address The address of the remote Bluetooth device.
- * @param[in] auto_connect The flag of the auto connection.
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED Not enabled
- * @retval #BT_ERROR_INVALID_PARAMETER Invalid paramater
- * @retval #BT_ERROR_OPERATION_FAILED Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @pre The remote device must support le connection.
- * @post This function invokes bt_gatt_connection_state_changed_cb().
- *
- * @see bt_initialize()
- * @see bt_gatt_disconnect()
- * @see bt_gatt_set_connection_state_changed_cb()
- * @see bt_gatt_unset_connection_state_changed_cb()
- * @see bt_gatt_connection_state_changed_cb()
- */
-int bt_gatt_connect(const char *address, bool auto_connect);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief Disconnect to LE connection with the given remote Bluetooth dievice address, asynchronously.
- * @since_tizen 2.3
- * @privlevel public
- * @privilege %http://tizen.org/privilege/bluetooth
- *
- * @param[in] address The address of the remote Bluetooth device
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED Not enabled
- * @retval #BT_ERROR_INVALID_PARAMETER Invalid paramater
- * @retval #BT_ERROR_OPERATION_FAILED Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre The connection must be established.
- * @post This function invokes bt_gatt_connection_state_changed_cb().
- *
- * @see bt_initialize()
- * @see bt_gatt_connect()
- * @see bt_gatt_set_connection_state_changed_cb()
- * @see bt_gatt_unset_connection_state_changed_cb()
- * @see bt_gatt_connection_state_changed_cb()
- */
-int bt_gatt_disconnect(const char *address);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief Registers a callback function that will be invoked when the connection state is changed.
- * @since_tizen 2.3
- *
- * @param[in] callback The callback function to register.
- * @param[in] user_data The user data to be passed  to the callback function.
- *
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER Invalid paramater
- *
- * @see bt_gatt_connect()
- * @see bt_gatt_disconnect()
- * @see bt_gatt_unset_connection_state_changed_cb()
- */
-int bt_gatt_set_connection_state_changed_cb(bt_gatt_connection_state_changed_cb callback, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief Unregisters a callback function that will be invoked when the connection state is changed.
- * @since_tizen 2.3
- *
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- *
- * @see bt_gatt_connect()
- * @see bt_gatt_disconnect()
- * @see bt_gatt_connection_state_changed_cb()
- */
-int bt_gatt_unset_connection_state_changed_cb(void);
-
-/**
- * @internal
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Initializes the Gatt Service.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege http://tizen.org/privilege/bluetooth.admin
- *
- * @return     0 on success, otherwise a negative error value.
- * @retval     #BT_ERROR_NONE  Successful
- * @retval     #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval     #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval     #BT_ERROR_OPERATION_FAILED      Operation failed
- * @retval     #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @see  bt_adapter_enable()
- */
-int _bt_gatt_init_service(void);
-
-
-/**
- * @internal
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  DeInitializes the Gatt Service.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege http://tizen.org/privilege/bluetooth.admin
- *
- * @return     0 on success, otherwise a negative error value.
- * @retval     #BT_ERROR_NONE  Successful
- * @retval     #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval     #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval     #BT_ERROR_OPERATION_FAILED      Operation failed
- * @retval     #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @see  bt_adapter_enable()
- * @see _bt_gatt_init_service(void)
- */
-int _bt_gatt_deinit_service(void);
-
-
-/**
- * @internal
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Adds Gatt Service to the service interface.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege http://tizen.org/privilege/bluetooth.admin
- *
- * @param[in]  svc_uuid                Gatt service uuid.
- * @param[out] svc_path        Object path of the GATT service.
- * @remarks svc_path must be released with free() by you.
- *
- * @return     0 on success, otherwise a negative error value.
- * @retval     #BT_ERROR_NONE  Successful
- * @retval     #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval     #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval     #BT_ERROR_OPERATION_FAILED      Operation failed
- * @retval     #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @see  bt_adapter_enable()
- */
-int bt_gatt_add_service(const char *svc_uuid,
-                               char **svc_path);
-
-/**
- * @internal
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Deletes a Gatt Service from the Gatt Server Database.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege http://tizen.org/privilege/bluetooth.admin
- *
- * @param[in]  svc_path  Service path of the gatt service to remove.
- * @return     0 on success, otherwise a negative error value.
- * @retval     #BT_ERROR_NONE  Successful
- * @retval     #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval     #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval     #BT_ERROR_OPERATION_FAILED      Operation failed
- * @retval     #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @see  bt_adapter_enable()
- */
-int bt_gatt_remove_service(const char *svc_path);
-
-/**
- * @internal
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Adds Gatt characteristic to the Characteristics interface.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege http://tizen.org/privilege/bluetooth.admin
- *
- * @param[in]  char_uuid Gatt characteristic uuid.
- * @param[in]  char_value      Gatt characteristic value.
- * @param[in]  value_length Caracteristic value length.
- * @param[in]  char_flags    Characteristic flags.
- * @param[in]  flags_length Caracteristic flags length.
- * @param[in]  svc_path        service path to which this characteristic belongs to.
- * @param[out]  char_path      characteristic path registered on the interface.
- * @remarks char_path must be released with free() by you.
- *
- * @return     0 on success, otherwise a negative error value.
- * @retval     #BT_ERROR_NONE  Successful
- * @retval     #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval     #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval     #BT_ERROR_OPERATION_FAILED      Operation failed
- * @retval     #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @see  bt_adapter_enable()
- */
-int bt_gatt_add_characteristic(const char *char_uuid,
-                       const char *char_value, int value_length,
-                       const char *char_flags[], int flags_length,
-                       const char *svc_path, char **char_path);
-
-/**
- * @internal
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Adds Gatt descriptor to the descriptor interface.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege http://tizen.org/privilege/bluetooth.admin
- *
- * @param[in]  desc_uuid Gatt descriptor uuid.
- * @param[in]  desc_value      Gatt descriptor value.
- * @param[in]  desc_length     Gatt descriptor value.
- * @param[in]  permissions     Permissions for the descriptor.
- * @param[in]  char_path       Characteristic path to which this descriptor should belong to.
- * @return     0 on success, otherwise a negative error value.
- * @retval     #BT_ERROR_NONE  Successful
- * @retval     #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval     #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval     #BT_ERROR_OPERATION_FAILED      Operation failed
- * @retval     #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @see  bt_adapter_enable()
- */
-int bt_gatt_add_descriptor(const char *desc_uuid,
-                       const char *desc_value, int value_length,
-                       const char *permissions, const char *char_path,
-                       char **desc_path);
-
-/**
- * @internal
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Registers the given service path (including characteristics and descriptor) with the Bluez.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege http://tizen.org/privilege/bluetooth.admin
- *
- * @param[in]  svc_path Gatt service path obtained from the add_service.
- * @return     0 on success, otherwise a negative error value.
- * @retval     #BT_ERROR_NONE  Successful
- * @retval     #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval     #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval     #BT_ERROR_OPERATION_FAILED      Operation failed
- * @retval     #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @pre  bt_gatt_add_service, bt_gatt_add_characteristic and bt_gatt_add_descriptor
- *          must be called before calling bt_gatt_register_service
- *
- * @see  bt_adapter_enable()
- * @see  bt_gatt_add_service()
- * @see  bt_gatt_add_characteristic()
- * @see  bt_gatt_add_descriptor()
- */
-int bt_gatt_register_service(const char *svc_path,
-               bt_gatt_remote_characteristic_write_cb callback,
-               void *user_data);
-
-/**
- * @internal
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Updates the existing characteristic value.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege http://tizen.org/privilege/bluetooth.admin
- *
- * @param[in]  char_path       characteristic path registered on the interface.
- * @param[in]  char_value      Gatt characteristic value.
- * @param[in]  value_length    Characteristic value length.
- * @param[in]  address Remote device address, for which
- *                       Notification/Indication need to be sent.
- *
- * @return     0 on success, otherwise a negative error value.
- * @retval     #BT_ERROR_NONE  Successful
- * @retval     #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval     #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval     #BT_ERROR_OPERATION_FAILED      Operation failed
- * @retval     #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @see  bt_adapter_enable()
- */
-int bt_gatt_update_characteristic(const char *char_path,
-                       const char *char_value, int value_length,
-                       const char *address);
-/**
- * @internal
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Delete Gatt Services from the Gatt Server Database.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege http://tizen.org/privilege/bluetooth.admin
- *
- * @return     0 on success, otherwise a negative error value.
- * @retval     #BT_ERROR_NONE  Successful
- * @retval     #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval     #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval     #BT_ERROR_OPERATION_FAILED      Operation failed
- * @retval     #BT_ERROR_PERMISSION_DENIED  Permission denied
- *
- * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @post  @a callback will be called.
- * @see  bt_adapter_enable()
- */
-int bt_gatt_delete_services(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_NAP_MODULE
- * @brief Activates the NAP(Network Access Point).
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_ALREADY_DONE  Operation is already done
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED
- * @see bt_nap_deactivate()
- */
-int bt_nap_activate(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_NAP_MODULE
- * @brief Deactivates the NAP(Network Access Point).
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_ALREADY_DONE  Operation is already done
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre The Bluetooth NAP service must be activated with bt_nap_activate().
- * @see bt_nap_activate()
- */
-int bt_nap_deactivate(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_NAP_MODULE
- * @brief Disconnects the all PANUs(Personal Area Networking User) which are connected to you.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre The Bluetooth NAP service must be activated with bt_nap_activate().
- * @see bt_nap_activate()
- */
-int bt_nap_disconnect_all(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_NAP_MODULE
- * @brief Disconnects the specified PANU(Personal Area Networking User) which is connected to you.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @param[in] remote_address  The remote address
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre The Bluetooth NAP service must be activated with bt_nap_activate().
- * @see bt_nap_activate()
- */
-int bt_nap_disconnect(const char *remote_address);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_NAP_MODULE
- * @brief  Registers a callback function that will be invoked when the connection state changes.
- * @since_tizen 2.3
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @post bt_nap_connection_state_changed_cb() will be invoked.
- * @see bt_initialize()
- * @see bt_nap_connection_state_changed_cb()
- * @see bt_nap_unset_connection_state_changed_cb()
- */
-int bt_nap_set_connection_state_changed_cb(bt_nap_connection_state_changed_cb callback, void *user_data);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_NAP_MODULE
- * @brief  Unregisters a callback function that will be invoked when the connection state changes.
- * @since_tizen 2.3
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @post bt_nap_connection_state_changed_cb() will be invoked.
- * @see bt_initialize()
- * @see bt_nap_connection_state_changed_cb()
- * @see bt_nap_set_connection_state_changed_cb()
- */
-int bt_nap_unset_connection_state_changed_cb(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_PANU_MODULE
- * @brief  Registers a callback function that will be invoked when the connection state changes.
- * @since_tizen 2.3
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @post bt_nap_connection_state_changed_cb() will be invoked.
- * @see bt_initialize()
- * @see bt_panu_connection_state_changed_cb()
- * @see bt_panu_unset_connection_state_changed_cb()
- */
-int bt_panu_set_connection_state_changed_cb(bt_panu_connection_state_changed_cb callback, void *user_data);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_PANU_MODULE
- * @brief  Unregisters a callback function that will be invoked when the connection state changes.
- * @since_tizen 2.3
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @post bt_nap_connection_state_changed_cb() will be invoked.
- * @see bt_initialize()
- * @see bt_panu_connection_state_changed_cb()
- * @see bt_panu_set_connection_state_changed_cb()
- */
-int bt_panu_unset_connection_state_changed_cb(void);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_PANU_MODULE
- * @brief Connects the remote device with the PAN(Personal Area Networking) service, asynchronously.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @param[in] remote_address  The remote address
- * @param[in] type  The type of PAN service
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device is not bonded
- * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre The local device must be bonded with the remote device by bt_device_create_bond().
- * @post bt_panu_connection_state_changed_cb() will be invoked.
- * @see bt_panu_disconnect()
- * @see bt_panu_connection_state_changed_cb()
- */
-int bt_panu_connect(const char *remote_address, bt_panu_service_type_e type);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_PANU_MODULE
- * @brief Disconnects the remote device with the PAN(Personal Area Networking) service, asynchronously.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @param[in] remote_address  The remote address
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
- * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre The remote device must be connected by bt_panu_connect().
- * @post bt_panu_connection_state_changed_cb() will be invoked.
- * @see bt_panu_connect()
- * @see bt_panu_connection_state_changed_cb()
- */
-int bt_panu_disconnect(const char *remote_address);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief   update LE connection.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
- * @pre The Bluetooth service must be initialized by bt_initialize().
- * @pre The remote device must be connected with bt_gatt_connect().
- */
-int bt_device_le_conn_update(const char *device_address,
-                            const bt_le_conn_update_s *parameters);
-
-
-/**
- * @}
- */
-
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif // __TIZEN_NETWORK_BLUETOOTH_H__
diff --git a/resource/csdk/connectivity/lib/tizen/ble/inc/bluetooth_private.h b/resource/csdk/connectivity/lib/tizen/ble/inc/bluetooth_private.h
deleted file mode 100644 (file)
index dbb8e44..0000000
+++ /dev/null
@@ -1,284 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd 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.
- */
-
-
-#ifndef __TIZEN_NETWORK_BLUETOOTH_PRIVATE_H__
-#define __TIZEN_NETWORK_BLUETOOTH_PRIVATE_H__
-
-#include <dlog.h>
-#include <stdbool.h>
-#include <bluetooth-api.h>
-#include <bluetooth-audio-api.h>
-#include <bluetooth-telephony-api.h>
-#include <bluetooth-media-control.h>
-#include <bluetooth-hid-api.h>
-
-#include "bluetooth.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#undef LOG_TAG
-#define LOG_TAG "CAPI_NETWORK_BLUETOOTH"
-
-#define BT_INFO(fmt, args...) SLOGI(fmt, ##args)
-#define BT_DBG(fmt, args...) SLOGD(fmt, ##args)
-#define BT_ERR(fmt, args...) SLOGE(fmt, ##args)
-
-#define OPP_UUID "00001105-0000-1000-8000-00805f9b34fb"
-
-/**
- * @internal
- * @brief Bluetooth callback.
- */
-typedef enum
-{
-       BT_EVENT_STATE_CHANGED = 0x00, /**< Adapter state is changed */
-       BT_EVENT_LE_STATE_CHANGED, /**< Adapter le state is changed */
-       BT_EVENT_NAME_CHANGED, /**< Adapter name is changed */
-       BT_EVENT_VISIBILITY_MODE_CHANGED, /**< Adapter visibility mode is changed */
-       BT_EVENT_VISIBILITY_DURATION_CHANGED, /**< Adapter visibility duration is changed */
-       BT_EVENT_DEVICE_DISCOVERY_STATE_CHANGED, /**< Device discovery state is changed */
-       BT_EVENT_LE_DEVICE_DISCOVERY_STATE_CHANGED, /**< LE Device discovery state is changed */
-       BT_EVENT_BOND_CREATED, /**< A bond is created */
-       BT_EVENT_BOND_DESTROYED, /**< A bond is destroyed */
-       BT_EVENT_AUTHORIZATION_CHANGED, /**< Authorization is changed */
-       BT_EVENT_SERVICE_SEARCHED, /**< Service search finish */
-       BT_EVENT_DATA_RECEIVED, /**< Data is received */
-       BT_EVENT_CONNECTION_STATE_CHANGED, /**< Connection state is changed */
-       BT_EVENT_RFCOMM_CONNECTION_REQUESTED, /**< RFCOMM connection is requested */
-       BT_EVENT_OPP_CONNECTION_REQUESTED, /**< OPP connection is requested */
-       BT_EVENT_OPP_PUSH_REQUESTED, /**< OPP push is requested */
-       BT_EVENT_OPP_SERVER_TRANSFER_PROGRESS, /**< OPP transfer progress */
-       BT_EVENT_OPP_SERVER_TRANSFER_FINISHED, /**< OPP transfer is completed */
-       BT_EVENT_OPP_CLIENT_PUSH_RESPONSED, /**< OPP client connection is reponsed */
-       BT_EVENT_OPP_CLIENT_PUSH_PROGRESS, /**< OPP client push progress */
-       BT_EVENT_OPP_CLIENT_PUSH_FINISHED, /**< OPP client push is finished */
-       BT_EVENT_PAN_CONNECTION_STATE_CHANGED, /**< PAN connection change */
-       BT_EVENT_NAP_CONNECTION_STATE_CHANGED, /**< NAP connection change */
-       BT_EVENT_HDP_CONNECTED, /**< HDP connection change */
-       BT_EVENT_HDP_DISCONNECTED, /**< HDP disconnection change */
-       BT_EVENT_HDP_DATA_RECEIVED, /**< HDP Data receive Callabck */
-       BT_EVENT_AUDIO_CONNECTION_STATUS, /**< Audio Connection change callback */
-       BT_EVENT_AG_SCO_CONNECTION_STATUS, /**< Audio - AG SCO Connection state change callback */
-       BT_EVENT_AG_CALL_HANDLING_EVENT, /**< Audio - AG call event callback */
-       BT_EVENT_AG_MULTI_CALL_HANDLING_EVENT, /**< Audio - AG 3-way call event callback */
-       BT_EVENT_AG_DTMF_TRANSMITTED, /**< Audio - DTMF tone sending request */
-       BT_EVENT_AG_MICROPHONE_GAIN_CHANGE, /**< Audio Microphone change callback */
-       BT_EVENT_AG_SPEAKER_GAIN_CHANGE, /**< Audio Speaker gain change callback */
-       BT_EVENT_AG_VENDOR_CMD, /**< Audio - XSAT Vendor cmd */
-       BT_EVENT_AVRCP_CONNECTION_STATUS, /**< AVRCP connection change callback */
-       BT_EVENT_AVRCP_EQUALIZER_STATE_CHANGED, /**< AVRCP equalizer state change callback */
-       BT_EVENT_AVRCP_REPEAT_MODE_CHANGED, /**< AVRCP repeat mode change callback */
-       BT_EVENT_AVRCP_SHUFFLE_MODE_CHANGED, /**< AVRCP equalizer mode change callback */
-       BT_EVENT_AVRCP_SCAN_MODE_CHANGED, /**< AVRCP scan mode change callback */
-       BT_EVENT_HID_CONNECTION_STATUS, /**< HID connection status callback */
-       BT_EVENT_DEVICE_CONNECTION_STATUS, /**< Device connection status callback */
-       BT_EVENT_GATT_CONNECTION_STATUS, /** < GATT connection status callback */
-       BT_EVENT_GATT_PRIM_SVC_DISCOVERED, /**< GATT Primary Service discovered callback */
-       BT_EVENT_GATT_CHARACTERISTIC_DISCOVERED, /**< GATT characteristic discovered callback */
-       BT_EVENT_GATT_CHARACTERISTIC_DESCRIPTOR_DISCOVERED, /**< GATT characteristic descriptor discovered callback */
-       BT_EVENT_GATT_VALUE_CHANGED, /**< GATT characteristic value changed callback */
-       BT_EVENT_GATT_READ_CHARACTERISTIC, /**< GATT characteristic value read callback */
-       BT_EVENT_GATT_WRITE_CHARACTERISTIC, /**< GATT characteristic value write callback */
-       BT_EVENT_GATT_SERVER_ON_WRITE_CHAR, /**< GATT characteristic value write callback */
-       BT_EVENT_ADVERTISING_STATE_CHANGED, /**< Advertising state changed callback */
-       BT_EVENT_MANUFACTURER_DATA_CHANGED, /**< Manufacturer data changed callback */
-       BT_EVENT_CONNECTABLE_CHANGED_EVENT, /**< Adapter connectable changed callback */
-       BT_EVENT_RSSI_ENABLED_EVENT, /**< RSSI Enabled callback */
-       BT_EVENT_RSSI_ALERT_EVENT, /**< RSSI Alert callback */
-       BT_EVENT_GET_RSSI_EVENT, /**< Get RSSI Strength callback */
-#ifdef TIZEN_WEARABLE
-       BT_EVENT_PBAP_CONNECTION_STATUS, /**< PBAP connection status callback */
-       BT_EVENT_PBAP_PHONEBOOK_SIZE, /**< PBAP Phonebook Size status callback */
-       BT_EVENT_PBAP_PHONEBOOK_PULL, /**< PBAP Phonebook Pull status callback */
-       BT_EVENT_PBAP_VCARD_LIST, /**< PBAP vCard List status callback */
-       BT_EVENT_PBAP_VCARD_PULL, /**< PBAP vCard Pull status callback */
-       BT_EVENT_PBAP_PHONEBOOK_SEARCH, /**< PBAP Phonebook Search status callback */
-       BT_EVENT_HF_SCO_CONNECTION_STATUS, /**< Audio - HF SCO Connection state change callback */
-       BT_EVENT_HF_SPEAKER_GAIN_CHANGE, /**< Audio - HF Speaker gain change callback */
-       BT_EVENT_HF_CALL_HANDLING_EVENT, /**< Audio - HF call event callback */
-       BT_EVENT_HF_VENDOR_DEP_CMD_EVENT, /**< Audio - HF Vendor Command callback */
-       BT_EVENT_HF_MULTI_CALL_HANDLING_EVENT, /**< Audio - HF 3-way call event callback */
-#endif
-} bt_event_e;
-
-/**
- * @internal
- */
-typedef struct {
-       int handle;
-
-       bt_adapter_le_advertising_state_changed_cb cb;
-       void *cb_data;
-
-       bt_adapter_le_advertising_params_s adv_params;
-
-       unsigned int adv_data_len;
-       char *adv_data;
-
-       unsigned int scan_rsp_data_len;
-       char *scan_rsp_data;
-
-       void *user_data;
-} bt_advertiser_s;
-
-/**
- * @internal
- */
-typedef struct bt_event_sig_event_slot_s
-{
-    int event_type;
-    const void *callback;
-    void *user_data;
-} bt_event_sig_event_slot_s;
-
-
-#define BT_CHECK_INPUT_PARAMETER(arg) \
-       if (arg == NULL) \
-       { \
-               LOGE("[%s] INVALID_PARAMETER(0x%08x)", __FUNCTION__, BT_ERROR_INVALID_PARAMETER); \
-               return BT_ERROR_INVALID_PARAMETER; \
-       }
-
-/**
- * @internal
- * @brief Check the initialzating status
- */
-int _bt_check_init_status(void);
-
-#define BT_CHECK_INIT_STATUS() \
-       if (_bt_check_init_status() == BT_ERROR_NOT_INITIALIZED) \
-       { \
-               LOGE("[%s] NOT_INITIALIZED(0x%08x)", __FUNCTION__, BT_ERROR_NOT_INITIALIZED); \
-               return BT_ERROR_NOT_INITIALIZED; \
-       }
-
-/**
- * @internal
- * @brief Initialize Bluetooth LE adapter
- */
-int _bt_le_adapter_init(void);
-
-/**
- * @internal
- * @brief Deinitialize Bluetooth LE adapter
- */
-int _bt_le_adapter_deinit(void);
-
-/**
- * @internal
- * @brief Set the event callback.
- */
-void _bt_set_cb(int events, void *callback, void *user_data);
-
-/**
- * @internal
- * @brief Unset the event callback.
- */
-void _bt_unset_cb(int events);
-
-/**
- * @internal
- * @brief Check if the event callback exist or not.
- */
-bool _bt_check_cb(int events);
-
-/**
- * @internal
- * @brief Convert Bluetooth F/W error codes to capi Bluetooth error codes.
- */
-int _bt_get_error_code(int origin_error);
-
-
-/**
- * @internal
- * @brief Convert Bluetooth F/W bluetooth_device_info_t to capi bt_device_info_s.
- */
-int _bt_get_bt_device_info_s(bt_device_info_s **dest_dev, bluetooth_device_info_t *source_dev);
-
-
-/**
- * @internal
- * @brief Free bt_device_info_s.
- */
-void _bt_free_bt_device_info_s(bt_device_info_s *device_info);
-
-/**
- * @internal
- * @brief Convert Bluetooth F/W bluetooth_device_address_t to string.
- */
-int _bt_convert_address_to_string(char **addr_str, bluetooth_device_address_t *addr_hex);
-
-
-/**
- * @internal
- * @brief Convert string to Bluetooth F/W bluetooth_device_address_t.
- */
-void _bt_convert_address_to_hex(bluetooth_device_address_t *addr_hex, const char *addr_str);
-
-
-/**
- * @internal
- * @brief Convert error code to string.
- */
-char* _bt_convert_error_to_string(int error);
-
-/**
- * @internal
- * @brief Convert the visibility mode
- */
-bt_adapter_visibility_mode_e _bt_get_bt_visibility_mode_e(bluetooth_discoverable_mode_t mode);
-
-/**
- * @internal
- * @brief Since the Audio call back and event proxy call backs have different prototype it is wrapper function.
- */
-void _bt_audio_event_proxy(int event, bt_audio_event_param_t *param, void *user_data);
-
-#ifdef TIZEN_WEARABLE
-/**
- * @internal
- * @brief Since the HF call back and event proxy call backs have different prototype it is wrapper function.
- */
-void _bt_hf_event_proxy(int event, bt_hf_event_param_t *param, void *user_data);
-#endif
-
-/**
- * @internal
- * @brief Since the Telephony call back and event proxy call backs have different prototype it is wrapper function.
- */
-void _bt_telephony_event_proxy(int event, telephony_event_param_t *param, void *user_data);
-
-/**
- * @internal
- * @brief Since the AVRCP call back and event proxy call backs have different prototype it is wrapper function.
- */
-void _bt_avrcp_event_proxy(int event, media_event_param_t *param, void *user_data);
-
-/**
- * @internal
- * @brief Since the HID call back and event proxy call backs have different prototype it is wrapper function.
- */
-void _bt_hid_event_proxy(int event, hid_event_param_t *param, void *user_data);
-
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* __TIZEN_NETWORK_BLUETOOTH_PRIVATE_H__ */
diff --git a/resource/csdk/connectivity/lib/tizen/ble/inc/bluetooth_type.h b/resource/csdk/connectivity/lib/tizen/ble/inc/bluetooth_type.h
deleted file mode 100644 (file)
index 95d195d..0000000
+++ /dev/null
@@ -1,1495 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd 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.
- */
-
-
-#ifndef __TIZEN_NETWORK_BLUETOOTH_TYPE_H__
-#define __TIZEN_NETWORK_BLUETOOTH_TYPE_H__
-
- #ifdef __cplusplus
-extern "C"
-{
-#endif /* __cplusplus */
-
-/**
- * @file bluetooth_type.h
- * @brief API to control the Bluetooth adapter, devices and communications.
- * @ingroup     CAPI_NETWORK_BLUETOOTH_TYPE_MODULE
- */
-
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_MODULE
- * @brief Enumerations of Bluetooth error codes.
- */
-typedef enum
-{
-       BT_ERROR_NONE = TIZEN_ERROR_NONE, /**< Successful*/
-       BT_ERROR_CANCELLED = TIZEN_ERROR_CANCELED, /**< Operation cancelled */
-       BT_ERROR_INVALID_PARAMETER = TIZEN_ERROR_INVALID_PARAMETER, /**< Invalid parameter */
-       BT_ERROR_OUT_OF_MEMORY = TIZEN_ERROR_OUT_OF_MEMORY, /**< Out of memory */
-       BT_ERROR_RESOURCE_BUSY = TIZEN_ERROR_RESOURCE_BUSY, /**< Device or resource busy */
-       BT_ERROR_TIMED_OUT = TIZEN_ERROR_TIMED_OUT, /**< Timeout error */
-       BT_ERROR_NOW_IN_PROGRESS = TIZEN_ERROR_NOW_IN_PROGRESS, /**< Operation now in progress */
-       BT_ERROR_NOT_SUPPORTED = TIZEN_ERROR_NOT_SUPPORTED,
-       BT_ERROR_PERMISSION_DENIED = TIZEN_ERROR_PERMISSION_DENIED, /**< Permission denied */
-       BT_ERROR_QUOTA_EXCEEDED = TIZEN_ERROR_QUOTA_EXCEEDED, /**< Quota exceeded */
-       BT_ERROR_NOT_INITIALIZED = TIZEN_ERROR_BLUETOOTH|0x0101, /**< Local adapter not initialized */
-       BT_ERROR_NOT_ENABLED = TIZEN_ERROR_BLUETOOTH|0x0102, /**< Local adapter not enabled */
-       BT_ERROR_ALREADY_DONE = TIZEN_ERROR_BLUETOOTH|0x0103, /**< Operation already done  */
-       BT_ERROR_OPERATION_FAILED = TIZEN_ERROR_BLUETOOTH|0x0104, /**< Operation failed */
-       BT_ERROR_NOT_IN_PROGRESS = TIZEN_ERROR_BLUETOOTH|0x0105, /**< Operation not in progress */
-       BT_ERROR_REMOTE_DEVICE_NOT_BONDED = TIZEN_ERROR_BLUETOOTH|0x0106, /**< Remote device not bonded */
-       BT_ERROR_AUTH_REJECTED = TIZEN_ERROR_BLUETOOTH|0x0107, /**< Authentication rejected */
-       BT_ERROR_AUTH_FAILED = TIZEN_ERROR_BLUETOOTH|0x0108, /**< Authentication failed */
-       BT_ERROR_REMOTE_DEVICE_NOT_FOUND = TIZEN_ERROR_BLUETOOTH|0x0109, /**< Remote device not found */
-       BT_ERROR_SERVICE_SEARCH_FAILED = TIZEN_ERROR_BLUETOOTH|0x010A, /**< Service search failed */
-       BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED = TIZEN_ERROR_BLUETOOTH|0x010B, /**< Remote device is not connected */
-       BT_ERROR_AGAIN = TIZEN_ERROR_BLUETOOTH|0x010C, /**< Resource temporarily unavailable */
-       BT_ERROR_SERVICE_NOT_FOUND = TIZEN_ERROR_BLUETOOTH|0x010D, /**< Service Not Found */
-} bt_error_e;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief  Enumerations of the Bluetooth adapter state.
- */
-typedef enum
-{
-       BT_ADAPTER_DISABLED = 0x00, /**< Bluetooth adapter is disabled */
-       BT_ADAPTER_ENABLED, /**< Bluetooth adapter is enabled */
-} bt_adapter_state_e;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief  Enumerations of the Bluetooth adapter le state.
- */
-typedef enum
-{
-       BT_ADAPTER_LE_DISABLED = 0x00, /**< Bluetooth le is disabled */
-       BT_ADAPTER_LE_ENABLED, /**< Bluetooth le is enabled */
-} bt_adapter_le_state_e;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief Enumerations of the Bluetooth visibility mode.
- */
-typedef enum
-{
-       BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE = 0x00,  /**< Other devices cannot find your device via discovery */
-       BT_ADAPTER_VISIBILITY_MODE_GENERAL_DISCOVERABLE,  /**< Discoverable mode */
-       BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE,  /**< Discoverable mode with time limit. After specific period,
-                                                           it is changed to #BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE.*/
-} bt_adapter_visibility_mode_e;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief Enumerations of the discovery state of Bluetooth device.
- *
- */
-typedef enum
-{
-       BT_ADAPTER_DEVICE_DISCOVERY_STARTED, /**< Device discovery is started */
-       BT_ADAPTER_DEVICE_DISCOVERY_FINISHED, /**< Device discovery is finished */
-       BT_ADAPTER_DEVICE_DISCOVERY_FOUND, /**< The remote Bluetooth device is found */
-} bt_adapter_device_discovery_state_e;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief Enumerations of the discovery state of Bluetooth LE device.
- *
- */
-typedef enum
-{
-       BT_ADAPTER_LE_DEVICE_DISCOVERY_STARTED, /**< LE device discovery is started */
-       BT_ADAPTER_LE_DEVICE_DISCOVERY_FINISHED, /**< LE device discovery is finished */
-       BT_ADAPTER_LE_DEVICE_DISCOVERY_FOUND, /**< The remote Bluetooth LE device is found */
-} bt_adapter_le_device_discovery_state_e;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief  Enumerations of the Bluetooth advertising state.
- */
-typedef enum {
-       BT_ADAPTER_LE_ADVERTISING_STOPPED = 0x00, /**< Bluetooth advertising is stopped */
-       BT_ADAPTER_LE_ADVERTISING_STARTED, /**< Bluetooth advertising is started */
-} bt_adapter_le_advertising_state_e;
-
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief  Enumerations of the Bluetooth advertising filter policy.
- */
-typedef enum {
-       BT_ADAPTER_LE_ADVERTISING_FILTER_DEFAULT = 0x00, /**< White list is not in use */
-       BT_ADAPTER_LE_ADVERTISING_FILTER_ALLOW_SCAN_WL = 0x01, /**< Allow the scan
-                                       request that in the White list */
-       BT_ADAPTER_LE_ADVERTISING_FILTER_ALLOW_CONN_WL = 0x02, /**< Allow the connectoin
-                                       request that in the White list */
-       BT_ADAPTER_LE_ADVERTISING_FILTER_ALLOW_SCAN_CONN_WL = 0x03, /**< Allow the
-                                       scan and connectoin request that in the White list */
-} bt_adapter_le_advertising_filter_policy_e;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief  Enumerations of the Bluetooth advertising type.
- */
-typedef enum {
-       BT_ADAPTER_LE_ADVERTISING_CONNECTABLE = 0x00, /**< Connectable undirected advertising (ADV_IND) */
-       BT_ADAPTER_LE_ADVERTISING_CONNECTABLE_DIRECT_HIGH = 0x01, /**< Connectable high duty cycle directed advertising (ADV_DIRECT_IND) */
-       BT_ADAPTER_LE_ADVERTISING_SCANNABLE = 0x02, /**< Scannable undirected advertising (ADV_SCAN_IND) */
-       BT_ADAPTER_LE_ADVERTISING_NON_CONNECTABLE = 0x03, /**< Non connectable undirected advertising (ADV_NONCOND_IND) */
-       BT_ADAPTER_LE_ADVERTISING_CONNECTABLE_DIRECT_LOW = 0x04, /**< Connectable low duty cycle directed advertising (ADV_DIRECT_IND) */
-} bt_adapter_le_advertising_type_e;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief  Enumerations of the Bluetooth LE packet type.
- */
-typedef enum {
-       BT_ADAPTER_LE_PACKET_ADVERTISING, /**< Advertising packet */
-       BT_ADAPTER_LE_PACKET_SCAN_RESPONSE, /**< Sacn response packet */
-} bt_adapter_le_packet_type_e;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief  Enumerations of the Bluetooth LE data type
- *         that can be included in LE packets.
- */
-typedef enum {
-       BT_ADAPTER_LE_PACKET_DATA_COMP_LIST_16_BIT_SERVICE_CLASS_UUIDS = 0x03, /**< 16 bit UUID */
-       BT_ADAPTER_LE_PACKET_DATA_MANUFACTURER_SPECIFIC_DATA = 0xff, /**< Manufacturer data */
-} bt_adapter_le_packet_data_type_e;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Enumerations of device disconnect reason.
- */
-typedef enum
-{
-       BT_DEVICE_DISCONNECT_REASON_UNKNOWN, /**< Disconnected by unknown reason */
-       BT_DEVICE_DISCONNECT_REASON_TIMEOUT, /**< Disconnected by timeout */
-       BT_DEVICE_DISCONNECT_REASON_LOCAL_HOST, /**< Disconnected by local host */
-       BT_DEVICE_DISCONNECT_REASON_REMOTE, /**< Disconnected by remote */
-} bt_device_disconnect_reason_e;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Enumerations of connection link type.
- */
-typedef enum
-{
-       BT_DEVICE_CONNECTION_LINK_BREDR, /**< BR/EDR link */
-       BT_DEVICE_CONNECTION_LINK_LE, /**< LE link */
-       BT_DEVICE_CONNECTION_LINK_DEFAULT = 0xFF, /**< The connection type defualt */
-} bt_device_connection_link_type_e;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Enumerations of device authorization state.
- */
-typedef enum
-{
-       BT_DEVICE_AUTHORIZED, /**< The remote Bluetooth device is authorized */
-       BT_DEVICE_UNAUTHORIZED, /**< The remote Bluetooth device is unauthorized */
-} bt_device_authorization_e;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Enumerations of Bluetooth profile.
- */
-typedef enum
-{
-    BT_PROFILE_RFCOMM = 0x01, /**< RFCOMM Profile */
-    BT_PROFILE_A2DP = 0x02, /**< Advanced Audio Distribution Profile */
-    BT_PROFILE_HSP = 0x04, /**< Headset Profile */
-    BT_PROFILE_HID = 0x08, /**< Human Interface Device Profile */
-    BT_PROFILE_NAP = 0x10, /**< Network Access Point Profile */
-    BT_PROFILE_AG = 0x20, /**< Audio Gateway Profile */
-    BT_PROFILE_GATT = 0x40, /**< Generic Attribute Profile */
-    BT_PROFILE_NAP_SERVER = 0x80, /**< NAP server Profile */
-} bt_profile_e;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Enumerations of device address type.
- */
-typedef enum
-{
-       BT_DEVICE_PUBLIC_ADDRESS = 0x00, /**< Public address */
-       BT_DEVICE_RANDOM_ADDRESS, /**< Random address */
-} bt_device_address_type_e;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief  Enumerations of service class.
- */
-typedef enum {
-       BT_SC_NONE = 0, /**< No service class */
-       BT_SC_RES_SERVICE_MASK = 0x00000001, /**< RES service class */
-       BT_SC_SPP_SERVICE_MASK = 0x00000002, /**< SPP service class */
-       BT_SC_DUN_SERVICE_MASK = 0x00000004, /**< DUN service class */
-       BT_SC_FAX_SERVICE_MASK = 0x00000008, /**< FAX service class */
-       BT_SC_LAP_SERVICE_MASK = 0x00000010, /**< LAP service class */
-       BT_SC_HSP_SERVICE_MASK = 0x00000020, /**< HSP service class */
-       BT_SC_HFP_SERVICE_MASK = 0x00000040, /**< HFP service class */
-       BT_SC_OPP_SERVICE_MASK = 0x00000080, /**< OPP service class */
-       BT_SC_FTP_SERVICE_MASK = 0x00000100, /**< FTP service class */
-       BT_SC_CTP_SERVICE_MASK = 0x00000200, /**< CTP service class */
-       BT_SC_ICP_SERVICE_MASK = 0x00000400, /**< ICP service class */
-       BT_SC_SYNC_SERVICE_MASK = 0x00000800, /**< SYNC service class */
-       BT_SC_BPP_SERVICE_MASK = 0x00001000, /**< BPP service class */
-       BT_SC_BIP_SERVICE_MASK = 0x00002000, /**< BIP service class */
-       BT_SC_PANU_SERVICE_MASK = 0x00004000, /**< PANU service class */
-       BT_SC_NAP_SERVICE_MASK = 0x00008000, /**< NAP service class */
-       BT_SC_GN_SERVICE_MASK = 0x00010000, /**< GN service class */
-       BT_SC_SAP_SERVICE_MASK = 0x00020000, /**< SAP service class */
-       BT_SC_A2DP_SERVICE_MASK = 0x00040000, /**< A2DP service class */
-       BT_SC_AVRCP_SERVICE_MASK = 0x00080000, /**< AVRCP service class */
-       BT_SC_PBAP_SERVICE_MASK = 0x00100000, /**< PBAP service class */
-       BT_SC_HID_SERVICE_MASK = 0x00200000, /**< HID service class */
-       BT_SC_ALL_SERVICE_MASK = 0x00FFFFFF, /**< ALL service class */
-       BT_SC_MAX /**< MAX service class */
-} bt_service_class_t;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief  Enumerations of major service class.
- */
-typedef enum
-{
-       BT_MAJOR_SERVICE_CLASS_LIMITED_DISCOVERABLE_MODE  = 0x002000, /**< Limited discoverable mode */
-       BT_MAJOR_SERVICE_CLASS_POSITIONING                = 0x010000, /**< Positioning class */
-       BT_MAJOR_SERVICE_CLASS_NETWORKING                 = 0x020000, /**< Networking class */
-       BT_MAJOR_SERVICE_CLASS_RENDERING                  = 0x040000, /**< Rendering class */
-       BT_MAJOR_SERVICE_CLASS_CAPTURING                  = 0x080000, /**< Capturing class */
-       BT_MAJOR_SERVICE_CLASS_OBJECT_TRANSFER            = 0x100000, /**< Object transferring class */
-       BT_MAJOR_SERVICE_CLASS_AUDIO                      = 0x200000, /**< Audio class*/
-       BT_MAJOR_SERVICE_CLASS_TELEPHONY                  = 0x400000, /**< Telephony class */
-       BT_MAJOR_SERVICE_CLASS_INFORMATION                = 0x800000, /**< Information class */
-} bt_major_service_class_e;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief  Enumerations of major device class.
- */
-typedef enum
-{
-       BT_MAJOR_DEVICE_CLASS_MISC = 0x00, /**< Miscellaneous major device class*/
-       BT_MAJOR_DEVICE_CLASS_COMPUTER = 0x01, /**< Computer major device class */
-       BT_MAJOR_DEVICE_CLASS_PHONE = 0x02, /**< Phone major device class */
-       BT_MAJOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT = 0x03, /**< LAN/Network access point major device class */
-       BT_MAJOR_DEVICE_CLASS_AUDIO_VIDEO = 0x04, /**< Audio/Video major device class */
-       BT_MAJOR_DEVICE_CLASS_PERIPHERAL = 0x05, /**< Peripheral major device class */
-       BT_MAJOR_DEVICE_CLASS_IMAGING = 0x06, /**< Imaging major device class */
-       BT_MAJOR_DEVICE_CLASS_WEARABLE = 0x07, /**< Wearable device class */
-       BT_MAJOR_DEVICE_CLASS_TOY = 0x08, /**< Toy device class */
-       BT_MAJOR_DEVICE_CLASS_HEALTH = 0x09, /**< Health device class */
-       BT_MAJOR_DEVICE_CLASS_UNCATEGORIZED = 0x1F, /**< Uncategorized major device class */
-} bt_major_device_class_e;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief  Enumerations of minor device class.
- */
-typedef enum
-{
-       BT_MINOR_DEVICE_CLASS_COMPUTER_UNCATEGORIZED = 0x00, /**< Uncategorized minor device class of computer */
-       BT_MINOR_DEVICE_CLASS_COMPUTER_DESKTOP_WORKSTATION = 0x04, /**< Desktop workstation minor device class of computer */
-       BT_MINOR_DEVICE_CLASS_COMPUTER_SERVER_CLASS = 0x08, /**< Server minor device class of computer */
-       BT_MINOR_DEVICE_CLASS_COMPUTER_LAPTOP = 0x0C, /**< Laptop minor device class of computer */
-       BT_MINOR_DEVICE_CLASS_COMPUTER_HANDHELD_PC_OR_PDA = 0x10, /**< Handheld PC/PDA minor device class of computer */
-       BT_MINOR_DEVICE_CLASS_COMPUTER_PALM_SIZED_PC_OR_PDA = 0x14, /**< Palm sized PC/PDA minor device class of computer */
-       BT_MINOR_DEVICE_CLASS_COMPUTER_WEARABLE_COMPUTER = 0x18, /**< Wearable(watch sized) minor device class of computer */
-
-       BT_MINOR_DEVICE_CLASS_PHONE_UNCATEGORIZED = 0x00, /**< Uncategorized minor device class of phone */
-       BT_MINOR_DEVICE_CLASS_PHONE_CELLULAR = 0x04, /**< Cellular minor device class of phone */
-       BT_MINOR_DEVICE_CLASS_PHONE_CORDLESS = 0x08, /**< Cordless minor device class of phone */
-       BT_MINOR_DEVICE_CLASS_PHONE_SMART_PHONE = 0x0C, /**< Smart phone minor device class of phone */
-       BT_MINOR_DEVICE_CLASS_PHONE_WIRED_MODEM_OR_VOICE_GATEWAY = 0x10, /**< Wired modem or voice gateway minor device class of phone */
-       BT_MINOR_DEVICE_CLASS_PHONE_COMMON_ISDN_ACCESS = 0x14, /**< Common ISDN minor device class of phone */
-
-       BT_MINOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT_FULLY_AVAILABLE = 0x04, /**< Fully available minor device class of LAN/Network access point */
-       BT_MINOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT_1_TO_17_PERCENT_UTILIZED = 0x20, /**< 1-17% utilized minor device class of LAN/Network access point */
-       BT_MINOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT_17_TO_33_PERCENT_UTILIZED = 0x40, /**< 17-33% utilized minor device class of LAN/Network access point */
-       BT_MINOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT_33_TO_50_PERCENT_UTILIZED = 0x60, /**< 33-50% utilized minor device class of LAN/Network access point */
-       BT_MINOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT_50_to_67_PERCENT_UTILIZED = 0x80, /**< 50-67% utilized minor device class of LAN/Network access point */
-       BT_MINOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT_67_TO_83_PERCENT_UTILIZED = 0xA0, /**< 67-83% utilized minor device class of LAN/Network access point */
-       BT_MINOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT_83_TO_99_PERCENT_UTILIZED = 0xC0, /**< 83-99% utilized minor device class of LAN/Network access point */
-       BT_MINOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT_NO_SERVICE_AVAILABLE = 0xE0, /**< No service available minor device class of LAN/Network access point */
-
-       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_UNCATEGORIZED = 0x00, /**< Uncategorized minor device class of audio/video */
-       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_WEARABLE_HEADSET = 0x04, /**< Wearable headset minor device class of audio/video */
-       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_HANDS_FREE = 0x08, /**< Hands-free minor device class of audio/video */
-       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_MICROPHONE = 0x10, /**< Microphone minor device class of audio/video */
-       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_LOUDSPEAKER = 0x14, /**< Loudspeaker minor device class of audio/video */
-       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_HEADPHONES = 0x18, /**< Headphones minor device class of audio/video */
-       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_PORTABLE_AUDIO = 0x1C, /**< Portable audio minor device class of audio/video */
-       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_CAR_AUDIO = 0x20, /**< Car audio minor device class of audio/video */
-       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_SET_TOP_BOX = 0x24, /**< Set-top box minor device class of audio/video */
-       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_HIFI_AUDIO_DEVICE = 0x28, /**< Hifi audio minor device class of audio/video */
-       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_VCR = 0x2C, /**< VCR minor device class of audio/video */
-       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_VIDEO_CAMERA = 0x30, /**< Video camera minor device class of audio/video */
-       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_CAMCORDER = 0x34, /**< Camcorder minor device class of audio/video */
-       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_VIDEO_MONITOR = 0x38, /**< Video monitor minor device class of audio/video */
-       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_VIDEO_DISPLAY_LOUDSPEAKER = 0x3C, /**< Video display and loudspeaker minor device class of audio/video */
-       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_VIDEO_CONFERENCING = 0x40, /**< Video conferencing minor device class of audio/video */
-       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_GAMING_TOY = 0x48, /**< Gaming/toy minor device class of audio/video */
-
-       BT_MINOR_DEVICE_CLASS_PERIPHERA_UNCATEGORIZED = 0x00, /**< Uncategorized minor device class of peripheral */
-       BT_MINOR_DEVICE_CLASS_PERIPHERAL_KEY_BOARD = 0x40, /**< Key board minor device class of peripheral */
-       BT_MINOR_DEVICE_CLASS_PERIPHERAL_POINTING_DEVICE = 0x80, /**< Pointing device minor device class of peripheral */
-       BT_MINOR_DEVICE_CLASS_PERIPHERAL_COMBO_KEYBOARD_POINTING_DEVICE = 0xC0, /**< Combo keyboard or pointing device minor device class of peripheral */
-       BT_MINOR_DEVICE_CLASS_PERIPHERAL_JOYSTICK = 0x04, /**< Joystick minor device class of peripheral */
-       BT_MINOR_DEVICE_CLASS_PERIPHERAL_GAME_PAD = 0x08, /**< Game pad minor device class of peripheral */
-       BT_MINOR_DEVICE_CLASS_PERIPHERAL_REMOTE_CONTROL = 0x0C, /**< Remote control minor device class of peripheral */
-       BT_MINOR_DEVICE_CLASS_PERIPHERAL_SENSING_DEVICE = 0x10, /**< Sensing device minor device class of peripheral */
-       BT_MINOR_DEVICE_CLASS_PERIPHERAL_DIGITIZER_TABLET = 0x14, /**< Digitizer minor device class of peripheral */
-       BT_MINOR_DEVICE_CLASS_PERIPHERAL_CARD_READER = 0x18, /**< Card reader minor device class of peripheral */
-       BT_MINOR_DEVICE_CLASS_PERIPHERAL_DIGITAL_PEN = 0x1C, /**< Digital pen minor device class of peripheral */
-       BT_MINOR_DEVICE_CLASS_PERIPHERAL_HANDHELD_SCANNER = 0x20, /**< Handheld scanner minor device class of peripheral */
-       BT_MINOR_DEVICE_CLASS_PERIPHERAL_HANDHELD_GESTURAL_INPUT_DEVICE = 0x24, /**< Handheld gestural input device minor device class of peripheral */
-
-       BT_MINOR_DEVICE_CLASS_IMAGING_DISPLAY = 0x10, /**< Display minor device class of imaging */
-       BT_MINOR_DEVICE_CLASS_IMAGING_CAMERA = 0x20, /**< Camera minor device class of imaging */
-       BT_MINOR_DEVICE_CLASS_IMAGING_SCANNER = 0x40, /**< Scanner minor device class of imaging */
-       BT_MINOR_DEVICE_CLASS_IMAGING_PRINTER = 0x80, /**< Printer minor device class of imaging */
-
-       BT_MINOR_DEVICE_CLASS_WEARABLE_WRIST_WATCH = 0x04, /**< Wrist watch minor device class of wearable */
-       BT_MINOR_DEVICE_CLASS_WEARABLE_PAGER = 0x08, /**< Pager minor device class of wearable */
-       BT_MINOR_DEVICE_CLASS_WEARABLE_JACKET = 0x0C, /**< Jacket minor device class of wearable */
-       BT_MINOR_DEVICE_CLASS_WEARABLE_HELMET = 0x10, /**< Helmet minor device class of wearable */
-       BT_MINOR_DEVICE_CLASS_WEARABLE_GLASSES = 0x14, /**< Glasses minor device class of wearable */
-
-       BT_MINOR_DEVICE_CLASS_TOY_ROBOT = 0x04, /**< Robot minor device class of toy */
-       BT_MINOR_DEVICE_CLASS_TOY_VEHICLE = 0x08, /**< Vehicle minor device class of toy */
-       BT_MINOR_DEVICE_CLASS_TOY_DOLL_ACTION = 0x0C, /**< Doll/Action minor device class of toy */
-       BT_MINOR_DEVICE_CLASS_TOY_CONTROLLER = 0x10, /**< Controller minor device class of toy */
-       BT_MINOR_DEVICE_CLASS_TOY_GAME = 0x14, /**< Game minor device class of toy */
-
-       BT_MINOR_DEVICE_CLASS_HEALTH_UNCATEGORIZED = 0x00, /**< Uncategorized minor device class of health */
-       BT_MINOR_DEVICE_CLASS_HEALTH_BLOOD_PRESSURE_MONITOR = 0x04, /**< Blood pressure monitor minor device class of health */
-       BT_MINOR_DEVICE_CLASS_HEALTH_THERMOMETER = 0x08, /**< Thermometer minor device class of health */
-       BT_MINOR_DEVICE_CLASS_HEALTH_WEIGHING_SCALE = 0x0C, /**< Weighing scale minor device class of health */
-       BT_MINOR_DEVICE_CLASS_HEALTH_GLUCOSE_METER = 0x10, /**< Glucose minor device class of health */
-       BT_MINOR_DEVICE_CLASS_HEALTH_PULSE_OXIMETER = 0x14, /**< Pulse oximeter minor device class of health */
-       BT_MINOR_DEVICE_CLASS_HEALTH_HEART_PULSE_RATE_MONITOR = 0x18, /**< Heart/Pulse rate monitor minor device class of health */
-       BT_MINOR_DEVICE_CLASS_HEALTH_DATA_DISPLAY = 0x1C, /**< Health data display minor device class of health */
-       BT_MINOR_DEVICE_CLASS_HEALTH_STEP_COUNTER = 0x20, /**< Step counter minor device class of health */
-       BT_MINOR_DEVICE_CLASS_HEALTH_BODY_COMPOSITION_ANALYZER = 0x24, /**< Body composition analyzer minor device class of health */
-       BT_MINOR_DEVICE_CLASS_HEALTH_PEAK_FLOW_MONITOR = 0x28, /**< Peak flow monitor minor device class of health */
-       BT_MINOR_DEVICE_CLASS_HEALTH_MEDICATION_MONITOR = 0x2C, /**< Medication monitor minor device class of health */
-       BT_MINOR_DEVICE_CLASS_HEALTH_KNEE_PROSTHESIS = 0x30, /**< Knee prosthesis minor device class of health */
-       BT_MINOR_DEVICE_CLASS_HEALTH_ANKLE_PROSTHESIS = 0x34, /**< Ankle prosthesis minor device class of health */
-} bt_minor_device_class_e;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief  Enumerations of gap appearance type.
- */
-typedef enum
-{
-       BT_APPEARANCE_TYPE_UNKNOWN = 0x00, /**< Unknown appearance type */
-       BT_APPEARANCE_TYPE_GENERIC_PHONE = 0x40, /**< Generic Phone type - Generic category */
-       BT_APPEARANCE_TYPE_GENERIC_COMPUTER = 0x80, /**< Generic Computer type - Generic category */
-       BT_APPEARANCE_TYPE_GENERIC_WATCH = 0xC0, /**< Generic Watch type - Generic category */
-} bt_appearance_type_e;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
- * @brief  Enumerations of connected Bluetooth device event role.
- */
-typedef enum
-{
-       BT_SOCKET_UNKNOWN = 0x00, /**< Unknown role*/
-       BT_SOCKET_SERVER , /**< Server role*/
-       BT_SOCKET_CLIENT, /**< Client role*/
-} bt_socket_role_e;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
- * @brief  Enumerations of Bluetooth socket connection state.
- */
-typedef enum
-{
-       BT_SOCKET_CONNECTED, /**< RFCOMM is connected */
-       BT_SOCKET_DISCONNECTED, /**< RFCOMM is disconnected */
-} bt_socket_connection_state_e;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_MODULE
- * @brief  Enumerations for the types of profiles related with audio
- */
-typedef enum {
-    BT_AUDIO_PROFILE_TYPE_ALL = 0,  /**< All supported profiles related with audio */
-    BT_AUDIO_PROFILE_TYPE_HSP_HFP,  /**< HSP(Headset Profile) and HFP(Hands-Free Profile) */
-    BT_AUDIO_PROFILE_TYPE_A2DP,  /**< A2DP(Advanced Audio Distribution Profile) */
-    BT_AUDIO_PROFILE_TYPE_AG,  /**< AG(Audio Gateway) */
-} bt_audio_profile_type_e;
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Enumerations for the call handling event
- */
-typedef enum {
-    BT_AG_CALL_HANDLING_EVENT_ANSWER = 0x00,  /**< Request to answer an incoming call */
-    BT_AG_CALL_HANDLING_EVENT_RELEASE,  /**< Request to release a call */
-    BT_AG_CALL_HANDLING_EVENT_REJECT,  /**< Request to reject an incoming call */
-} bt_ag_call_handling_event_e;
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Enumerations for the multi call handling event
- */
-typedef enum {
-    BT_AG_MULTI_CALL_HANDLING_EVENT_RELEASE_HELD_CALLS = 0x00,  /**< Request to release held calls */
-    BT_AG_MULTI_CALL_HANDLING_EVENT_RELEASE_ACTIVE_CALLS,  /**< Request to release active calls */
-    BT_AG_MULTI_CALL_HANDLING_EVENT_ACTIVATE_HELD_CALL,  /**< Request to put active calls into hold state and activate another (held or waiting) call */
-    BT_AG_MULTI_CALL_HANDLING_EVENT_MERGE_CALLS,  /**< Request to add a held call to the conversation */
-    BT_AG_MULTI_CALL_HANDLING_EVENT_EXPLICIT_CALL_TRANSFER,  /**< Request to let a user who has two calls to connect these two calls together and release its connections to both other parties */
-} bt_ag_multi_call_handling_event_e;
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Enumerations for the call state
- */
-typedef enum {
-    BT_AG_CALL_EVENT_IDLE = 0x00,  /**< Idle */
-    BT_AG_CALL_EVENT_ANSWERED,  /**< Answered */
-    BT_AG_CALL_EVENT_HELD,  /**< Held */
-    BT_AG_CALL_EVENT_RETRIEVED,  /**< Retrieved */
-    BT_AG_CALL_EVENT_DIALING,  /**< Dialing */
-    BT_AG_CALL_EVENT_ALERTING,  /**< Alerting */
-    BT_AG_CALL_EVENT_INCOMING,  /**< Incoming */
-} bt_ag_call_event_e;
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Enumerations for the call state
- */
-typedef enum {
-    BT_AG_CALL_STATE_IDLE = 0x00,  /**< Idle state */
-    BT_AG_CALL_STATE_ACTIVE,  /**< Active state */
-    BT_AG_CALL_STATE_HELD,  /**< Held state */
-    BT_AG_CALL_STATE_DIALING,  /**< Dialing state */
-    BT_AG_CALL_STATE_ALERTING,  /**< Alerting state */
-    BT_AG_CALL_STATE_INCOMING,  /**< Incoming state */
-    BT_AG_CALL_STATE_WAITING,  /**< Waiting for connected indication event after answering an incoming call*/
-} bt_ag_call_state_e;
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief  Enumerations for the equalizer state
- */
-typedef enum {
-    BT_AVRCP_EQUALIZER_STATE_OFF = 0x01,  /**< Equalizer Off */
-    BT_AVRCP_EQUALIZER_STATE_ON,  /**< Equalizer On */
-} bt_avrcp_equalizer_state_e;
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief  Enumerations for the repeat mode
- */
-typedef enum {
-    BT_AVRCP_REPEAT_MODE_OFF = 0x01,  /**< Repeat Off */
-    BT_AVRCP_REPEAT_MODE_SINGLE_TRACK,  /**< Single track repeat */
-    BT_AVRCP_REPEAT_MODE_ALL_TRACK,  /**< All track repeat */
-    BT_AVRCP_REPEAT_MODE_GROUP,  /**< Group repeat */
-} bt_avrcp_repeat_mode_e;
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief  Enumerations for the shuffle mode
- */
-typedef enum {
-    BT_AVRCP_SHUFFLE_MODE_OFF = 0x01,  /**< Shuffle Off */
-    BT_AVRCP_SHUFFLE_MODE_ALL_TRACK,  /**< All tracks shuffle */
-    BT_AVRCP_SHUFFLE_MODE_GROUP,  /**< Group shuffle */
-} bt_avrcp_shuffle_mode_e;
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief  Enumerations for the scan mode
- */
-typedef enum {
-    BT_AVRCP_SCAN_MODE_OFF = 0x01,  /**< Scan Off */
-    BT_AVRCP_SCAN_MODE_ALL_TRACK,  /**< All tracks scan */
-    BT_AVRCP_SCAN_MODE_GROUP,  /**< Group scan */
-} bt_avrcp_scan_mode_e;
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief  Enumerations for the player state
- */
-typedef enum {
-    BT_AVRCP_PLAYER_STATE_STOPPED = 0x00,  /**< Stopped */
-    BT_AVRCP_PLAYER_STATE_PLAYING,  /**< Playing */
-    BT_AVRCP_PLAYER_STATE_PAUSED,  /**< Paused */
-    BT_AVRCP_PLAYER_STATE_FORWARD_SEEK,  /**< Seek Forward */
-    BT_AVRCP_PLAYER_STATE_REWIND_SEEK,  /**< Seek Rewind */
-} bt_avrcp_player_state_e;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
- * @brief  Enumerations for the data channel type
- */
-typedef enum {
-    BT_HDP_CHANNEL_TYPE_RELIABLE  = 0x01,  /**< Reliable Data Channel */
-    BT_HDP_CHANNEL_TYPE_STREAMING,  /**< Streaming Data Channel */
-} bt_hdp_channel_type_e;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_PANU_MODULE
- * @brief  Enumerations for the types of PAN(Personal Area Networking) service
- */
-typedef enum {
-    BT_PANU_SERVICE_TYPE_NAP = 0,  /**< Network Access Point */
-} bt_panu_service_type_e;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief The handle to control Bluetooth LE advertising
- */
-typedef void* bt_advertiser_h;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  The attribute handle of GATT(Generic Attribute Profile)
- */
-typedef void* bt_gatt_attribute_h;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  The handle of calls state
- */
-typedef void* bt_call_list_h;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Class structure of device and service.
- *
- * @see #bt_device_info_s
- * @see #bt_adapter_device_discovery_info_s
- * @see bt_device_bond_created_cb()
- * @see bt_adapter_device_discovery_state_changed_cb()
- */
-typedef struct
-{
-       bt_major_device_class_e major_device_class;     /**< Major device class. */
-       bt_minor_device_class_e minor_device_class;     /**< Minor device class. */
-       int major_service_class_mask;   /**< Major service class mask.
-       This value can be a combination of #bt_major_service_class_e like #BT_MAJOR_SERVICE_CLASS_RENDERING | #BT_MAJOR_SERVICE_CLASS_AUDIO */
-} bt_class_s;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief Structure of device discovery information.
- *
- * @see #bt_class_s
- * @see bt_adapter_device_discovery_state_changed_cb()
- */
-typedef struct
-{
-       char *remote_address;   /**< The address of remote device */
-       char *remote_name;      /**< The name of remote device */
-       bt_class_s bt_class;    /**< The Bluetooth classes */
-       int rssi;       /**< The strength indicator of received signal  */
-       bool is_bonded; /**< The bonding state */
-       char **service_uuid;  /**< The UUID list of service */
-       int service_count;      /**< The number of services */
-       bt_appearance_type_e appearance;        /**< The Bluetooth appearance */
-       int manufacturer_data_len;      /**< manufacturer specific data length */
-       char *manufacturer_data;                /**< manufacturer specific data */
-} bt_adapter_device_discovery_info_s;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief Structure of le device discovery information.
- *
- * @see #bt_class_s
- * @see bt_adapter_le_device_discovery_state_changed_cb()
- */
-typedef struct
-{
-       char *remote_address;   /**< The address of remote device */
-       int address_type;       /**< The address type of remote device */
-       int rssi;       /**< The strength indicator of received signal  */
-       char **service_uuid;  /**< The UUID list of service */
-       int service_count;      /**< The number of services */
-       int adv_data_len;               /**< advertising indication data length */
-       char *adv_data;                 /**< advertising indication data */
-       int scan_data_len;              /**< scan response data length */
-       char *scan_data;                /**< scan response data */
-} bt_adapter_le_device_discovery_info_s;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief Structure of advertising parameters
- *
- * @see #bt_class_s
- * @see bt_adapter_le_advertising_state_changed_cb()
- * @see bt_adapter_le_start_advertising()
- */
-typedef struct {
-       float interval_min; /**< Minimum advertising interval for non-directed advertising.
-                             A multiple of 0.625ms is only allowed (Time range : 20ms to 10.24sec). */
-       float interval_max; /**< Maximum advertising interval for non-directed advertising.
-                             A multiple of 0.625ms is only allowed (Time range : 20ms to 10.24sec). */
-       char filter_policy; /* Advertising filter policy */
-       char type; /* Advertising type */
-} bt_adapter_le_advertising_params_s;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Device information structure used for identifying pear device.
- *
- * @see #bt_class_s
- * @see bt_device_bond_created_cb()
- */
-typedef struct
-{
-       char *remote_address;   /**< The address of remote device */
-       char *remote_name;      /**< The name of remote device */
-       bt_class_s bt_class;    /**< The Bluetooth classes */
-       char **service_uuid;  /**< The UUID list of service */
-       int service_count;      /**< The number of services */
-       bool is_bonded; /**< The bonding state */
-       bool is_connected;      /**< The connection state */
-       bool is_authorized;     /**< The authorization state */
-       int manufacturer_data_len;      /**< manufacturer specific data length */
-       char *manufacturer_data;                /**< manufacturer specific data */
-} bt_device_info_s;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Service Discovery Protocol (SDP) data structure.
- *
- * @details This protocol is used for discovering available services or pear device,
- * and finding one to connect with.
- *
- * @see bt_device_service_searched_cb()
- */
-typedef struct
-{
-       char *remote_address;   /**< The address of remote device */
-       char **service_uuid;  /**< The UUID list of service */
-       int service_count;    /**< The number of services. */
-} bt_device_sdp_info_s;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Device connection information structure.
- *
- * @see bt_device_connection_state_changed_cb()
- */
-typedef struct
-{
-       char *remote_address;   /**< The address of remote device */
-       bt_device_connection_link_type_e link;  /**< Link type */
-       bt_device_disconnect_reason_e disconn_reason;  /**< Disconnection reason */
-} bt_device_connection_info_s;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Device LE connection update structure.
- *
- * @see bt_device_le_conn_update()
- */
-typedef struct
-{
-       unsigned int interval_min;   /**< Minimum value for the connection event interval (msec) */
-       unsigned int interval_max;   /**< Maximum value for the connection event interval (msec) */
-       unsigned int latency;   /**< Slave latency (msec) */
-       unsigned int time_out;   /**< Supervision timeout (msec) */
-} bt_le_conn_update_s;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
- *
- * @brief Rfcomm connection data used for exchanging data between Bluetooth devices.
- *
- * @see bt_socket_connection_state_changed_cb()
- */
-typedef struct
-{
-       int socket_fd;  /**< The file descriptor of connected socket */
-       int server_fd;  /**< The file descriptor of the server socket or -1 for client connection */
-       bt_socket_role_e local_role;    /**< The local device role in this connection */
-       char *remote_address;   /**< The remote device address */
-       char *service_uuid;     /**< The service UUId */
-} bt_socket_connection_s;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
- *
- * @brief Structure of RFCOMM received data.
- *
- * @remarks User can use standard linux functions for reading/writing
- * data from/to sockets.
- *
- * @see bt_socket_data_received_cb()
- */
-typedef struct
-{
-       int socket_fd;  /**< The socket fd */
-       int data_size;  /**< The length of the received data */
-       char *data;     /**< The received data */
-} bt_socket_received_data_s;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief  Called when the Bluetooth adapter state changes.
- * @param[in]   result  The result of the adapter state changing
- * @param[in]   adapter_state  The adapter state to be changed
- * @param[in]   user_data  The user data passed from the callback registration function
- * @see bt_adapter_set_state_changed_cb()
- * @see bt_adapter_unset_state_changed_cb()
- */
-typedef void (*bt_adapter_state_changed_cb)(int result, bt_adapter_state_e adapter_state, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief  Called when adapter name changes.
- * @param[in]   device_name    The name of the Bluetooth device to be changed
- * @param[in]   user_data      The user data passed from the callback registration function
- * @pre This function will be invoked when the name of Bluetooth adapter changes
- * if you register this callback using bt_adapter_set_name_changed_cb().
- * @see bt_adapter_set_name()
- * @see bt_adapter_set_name_changed_cb()
- * @see bt_adapter_unset_name_changed_cb()
- */
-typedef void (*bt_adapter_name_changed_cb)(char *device_name, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief  Called when the visibility mode changes.
- * @param[in] result The result of the visibility mode changing
- * @param[in] visibility_mode The visibility mode to be changed
- * @param[in] user_data The user data passed from the callback registration function
- *
- * @pre This function will be invoked when the visibility of Bluetooth adapter changes
- * if you register this callback using bt_adapter_set_visibility_mode_changed_cb().
- *
- * @see bt_adapter_set_visibility_mode_changed_cb()
- * @see bt_adapter_unset_visibility_mode_changed_cb()
- */
-typedef void (*bt_adapter_visibility_mode_changed_cb)
-       (int result, bt_adapter_visibility_mode_e visibility_mode, void *user_data);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief  Called every second until the visibility mode is changed to #BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE.
- * @remarks  This callback function is called only if visibility mode is #BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE.
- * @param[in]  duration  The duration until the visibility mode is changed to #BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE (in seconds)
- * @param[in]  user_data  The user data passed from the callback registration function
- * @pre  This function will be invoked if you register this callback using bt_adapter_set_visibility_duration_changed_cb().
- * @see  bt_adapter_set_visibility_duration_changed_cb()
- * @see  bt_adapter_unset_visibility_duration_changed_cb()
- */
-typedef void (*bt_adapter_visibility_duration_changed_cb)(int duration, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief  Called when the state of device discovery changes.
- *
- * @remarks If \a discovery_state is #BT_ADAPTER_DEVICE_DISCOVERY_FOUND,
- * then you can get some information, such as remote device address, remote device name, rssi, and bonding state.
- *
- * @param[in] result The result of the device discovery
- * @param[in] discovery_state The discovery state to be changed
- * @param[in] discovery_info The information of the discovered device \n
- *                                     If \a discovery_state is #BT_ADAPTER_DEVICE_DISCOVERY_STARTED or
- * #BT_ADAPTER_DEVICE_DISCOVERY_FINISHED, then \a discovery_info is NULL.
- * @param[in] user_data The user data passed from the callback registration function
- *
- * @pre Either bt_adapter_start_device_discovery() or bt_adapter_stop_device_discovery() will invoke this function
- * if you register this callback using bt_adapter_set_device_discovery_state_changed_cb().
- *
- * @see bt_adapter_start_device_discovery()
- * @see bt_adapter_stop_device_discovery()
- * @see bt_adapter_set_device_discovery_state_changed_cb()
- * @see bt_adapter_unset_device_discovery_state_changed_cb()
- *
- */
-typedef void (*bt_adapter_device_discovery_state_changed_cb)
-       (int result, bt_adapter_device_discovery_state_e discovery_state, bt_adapter_device_discovery_info_s *discovery_info, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief  Called when you get bonded devices repeatedly.
- *
- * @param[in] device_info The bonded device information
- * @param[in] user_data The user data passed from the foreach function
- * @return @c true to continue with the next iteration of the loop,
- * \n @c false to break out of the loop.
- * @pre bt_adapter_foreach_bonded_device() will invoke this function.
- *
- * @see bt_adapter_foreach_bonded_device()
- *
- */
-typedef bool (*bt_adapter_bonded_device_cb)(bt_device_info_s *device_info, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief  Called when the connectable state changes.
- * @param[in] result The result of the connectable state changing
- * @param[in] connectable The connectable to be changed
- * @param[in] user_data The user data passed from the callback registration function
- *
- * @pre This function will be invoked when the connectable state of local Bluetooth adapter changes
- * if you register this callback using bt_adapter_set_connectable_changed_cb().
- *
- * @see bt_adapter_set_connectable()
- * @see bt_adapter_set_connectable_changed_cb()
- * @see bt_adapter_unset_connectable_changed_cb()
- */
-typedef void (*bt_adapter_connectable_changed_cb)
-       (int result, bool connectable, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief  Called when the state of LE device discovery changes.
- *
- * @remarks If \a discovery_state is #BT_ADAPTER_LE_DEVICE_DISCOVERY_FOUND,
- * then you can get some information, such as remote LE device address, remote device name, rssi, and bonding state.
- *
- * @param[in] result The result of the LE device discovery
- * @param[in] discovery_state The discovery state to be changed
- * @param[in] discovery_info The information of the discovered LE device \n
- *                                     If \a discovery_state is #BT_ADAPTER_LE_DEVICE_DISCOVERY_STARTED or
- * #BT_ADAPTER_LE_DEVICE_DISCOVERY_FINISHED, then \a discovery_info is NULL.
- * @param[in] user_data The user data passed from the callback registration function
- *
- * @pre Either bt_adapter_start_device_discovery() or bt_adapter_stop_device_discovery() will invoke this function
- * if you register this callback using bt_adapter_set_device_discovery_state_changed_cb().
- *
- * @see bt_adapter_le_start_device_discovery()
- * @see bt_adapter_le_stop_device_discovery()
- * @see bt_adapter_le_set_device_discovery_state_changed_cb()
- * @see bt_adapter_le_unset_device_discovery_state_changed_cb()
- *
- */
-typedef void (*bt_adapter_le_device_discovery_state_changed_cb)
-       (int result, bt_adapter_le_device_discovery_state_e discovery_state, bt_adapter_le_device_discovery_info_s *discovery_info, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief  Called when the state of advertiser changes.
- *
- * @param[out] result The result of the requested state change of advertiser
- * @param[out] advertiser The handle of the state changed advertiser
- * @param[out] adv_state The advertiser state to be changed
- * @param[out] user_data The user data passed from the start function
- *
- * @see bt_adapter_le_start_advertiser()
- * @see bt_adapter_le_stop_advertiser()
- */
-typedef void (*bt_adapter_le_advertising_state_changed_cb)(int result,
-               bt_advertiser_h advertiser, bt_adapter_le_advertising_state_e adv_state, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief  Called when the Bluetooth adapter le state changes.
- * @param[in]   result  The result of the adapter state changing
- * @param[in]   adapter_le_state  The adapter le state to be changed
- * @param[in]   user_data  The user data passed from the callback registration function
- * @pre Either bt_adapter_le_enable() or bt_adapter_le_disable() will invoke this callback if you register this callback using bt_adapter_le_set_state_changed_cb().
- * @see bt_adapter_le_enable()
- * @see bt_adapter_le_disable()
- * @see bt_adapter_le_set_state_changed_cb()
- * @see bt_adapter_le_unset_state_changed_cb()
- */
-typedef void (*bt_adapter_le_state_changed_cb)(int result, bt_adapter_le_state_e adapter_le_state, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Called when the process of creating bond finishes.
- * @remarks If the remote user does not respond within 60 seconds, a time out will happen with #BT_ERROR_TIMED_OUT result code.\n
- * If bt_device_cancel_bonding() is called and it returns #BT_ERROR_NONE, then this callback function will be called
- * with #BT_ERROR_CANCELLED result. \n
- * If creating a bond succeeds but service search fails, then this callback will be called with #BT_ERROR_SERVICE_SEARCH_FAILED.
- * In this case, you should try service search again by bt_device_start_service_search() to get the supported service list.
- *
- * @param[in] result The result of the bonding device
- * @param[in] device_info The device information which you creates bond with
- * @param[in] user_data The user data passed from the callback registration function
- *
- * @pre Either bt_device_create_bond() will invoke this function
- * if you register this callback using bt_device_set_bond_created_cb().
- *
- * @see bt_device_create_bond()
- * @see bt_device_cancel_bonding()
- * @see bt_device_set_bond_created_cb()
- * @see bt_device_unset_bond_created_cb()
- */
-typedef void (*bt_device_bond_created_cb)(int result, bt_device_info_s *device_info, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief  Called when you get connected profiles repeatedly.
- * @param[in] profile The connected Bluetooth profile
- * @param[in] user_data The user data passed from the foreach function
- * @return @c true to continue with the next iteration of the loop,
- * \n @c false to break out of the loop.
- * @pre bt_device_foreach_connected_profiles() will invoke this function.
- * @see bt_device_foreach_connected_profiles()
- */
-typedef bool (*bt_device_connected_profile)(bt_profile_e profile, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief  Called when the bond destroys.
- * @param[in] result The result that a bond is destroyed
- * @param[in] remote_address The address of the remote Bluetooth device to destroy bond with
- * @param[in] user_data The user data passed from the callback registration function
- * @pre bt_device_destroy_bond() will invoke this function
- * if you register this callback using bt_device_set_bond_destroyed_cb().
- *
- * @see bt_device_destroy_bond()
- * @see bt_device_set_bond_destroyed_cb()
- * @see bt_device_unset_bond_destroyed_cb()
- */
-typedef void (*bt_device_bond_destroyed_cb)(int result, char *remote_address, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief  Called when the authorization of device changes.
- * @param[in] authorization The authorization of device
- * @param[in] remote_address The address of the remote Bluetooth device which is (un)authorized
- * @param[in] user_data The user data passed from the callback registration function
- * @pre bt_device_set_authorization() will invoke this function if you register this callback using bt_device_set_authorization_changed_cb().
- *
- * @see bt_device_set_authorization()
- * @see #bt_device_set_authorization_changed_cb()
- * @see #bt_device_unset_authorization_changed_cb()
- */
-typedef void (*bt_device_authorization_changed_cb)
-       (bt_device_authorization_e authorization, char *remote_address, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief  Called when the process of service search finishes.
- * @remark If bt_device_cancel_service_search() is called and it returns #BT_ERROR_NONE,
- * then this callback function will be called with #BT_ERROR_CANCELLED result.
- *
- * @param[in] result The result of the service searching
- * @param[in] sdp_info The structure of service lists found on a device
- * @param[in] user_data The user data passed from the callback registration function
- * @pre Either bt_device_start_service_search() will invoke this function
- * if you register this callback using  bt_device_set_service_searched_cb().
- *
- * @see bt_device_start_service_search()
- * @see bt_device_cancel_service_search()
- * @see bt_device_set_service_searched_cb()
- * @see bt_device_unset_service_searched_cb()
- *
- */
-typedef void (*bt_device_service_searched_cb)(int result, bt_device_sdp_info_s *sdp_info, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief  Called when the connection state is changed.
- * @param[in] connected The connection status: (@c true = connected, @c false = disconnected)
- * @param[in] conn_info The connection information
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_device_set_connection_state_changed_cb()
- * @see bt_device_unset_connection_state_changed_cb()
- */
-typedef void (*bt_device_connection_state_changed_cb)(bool connected, bt_device_connection_info_s *conn_info, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
- * @brief Called when you receive data.
- *
- * @param[in] data The received data from the remote device
- * @param[in] user_data The user data passed from the callback registration function
- *
- * @pre When the connected remote Bluetooth device invokes bt_socket_send_data(),
- *             this function will be invoked if you register this function using bt_socket_set_data_received_cb().
- *
- * @see bt_socket_set_data_received_cb()
- * @see bt_socket_unset_data_received_cb()
- * @see bt_socket_send_data()
- */
-typedef void (*bt_socket_data_received_cb)(bt_socket_received_data_s *data, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
- * @brief  Called when the socket connection state changes.
- * @param[in] result The result of connection state changing
- * @param[in] connection_state The connection state
- * @param[in] connection The connection information which is established or disconnected
- * @param[in] user_data The user data passed from the callback registration function
- * @pre Either bt_socket_connect_rfcomm() will invoke this function.
- * In addtion, bt_socket_connection_state_changed_cb() will be invoked when the socket connection state is changed.
- * @see bt_socket_listen_and_accept_rfcomm()
- * @see bt_socket_connect_rfcomm()
- * @see bt_socket_set_connection_state_changed_cb()
- * @see bt_socket_unset_connection_state_changed_cb()
- */
-typedef void (*bt_socket_connection_state_changed_cb)
-       (int result, bt_socket_connection_state_e connection_state, bt_socket_connection_s *connection, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
- * @brief  Called when a RFCOMM connection is requested.
- * @details You must call bt_socket_accept() if you want to accept. Otherwise, you must call bt_socket_reject().
- * @param[in] socket_fd  The file descriptor of socket on which a connection is requested
- * @param[in] remote_address  The address of remote device
- * @param[in] user_data The user data passed from the callback registration function
- * @pre If you register this callback function by bt_socket_set_connection_requested_cb() and listen a socket by bt_socket_listen(),
- * bt_socket_connection_requested_cb() will be invoked.
- * @see bt_socket_listen()
- * @see bt_socket_accept()
- * @see bt_socket_reject()
- */
-typedef void (*bt_socket_connection_requested_cb) (int socket_fd, const char *remote_address, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
- * @brief  Called when the push is requested.
- * @details You must call bt_opp_server_accept() if you want to accept.
- * Otherwise, you must call bt_opp_server_reject().
- * @param[in] file  The path of file to be pushed
- * @param[in] size The file size (bytes)
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_opp_server_initialize()
- */
-typedef void (*bt_opp_server_push_requested_cb)(const char *file, int size, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
- * @brief  Called when an OPP connection is requested.
- * @details You must call bt_opp_server_accept_connection() if you want to accept.
- * Otherwise, you must call bt_opp_server_reject_connection().
- * @param[in] remote_address  The address of remote device
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_opp_server_initialize()
- * @see bt_opp_server_accept_connection()
- * @see bt_opp_server_reject_connection()
- */
-typedef void (*bt_opp_server_connection_requested_cb)(const char *remote_address, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
- * @brief  Called when a file is being transfered.
- * @param[in] file  The path of file to be pushed
- * @param[in] size The file size (bytes)
- * @param[in] percent The progress in percentage (1 ~ 100)
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_opp_server_accept()
- * @see bt_opp_server_accept_connection()
- */
-typedef void (*bt_opp_server_transfer_progress_cb) (const char *file, long long size, int percent, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
- * @brief  Called when a transfer is finished.
- * @param[in] error_code  The result of push
- * @param[in] file  The path of file to be pushed
- * @param[in] size The file size (bytes)
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_opp_server_accept()
- * @see bt_opp_server_accept_connection()
- */
-typedef void (*bt_opp_server_transfer_finished_cb) (int result, const char *file, long long size, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
- * @brief  Called when OPP server responds to the push request.
- * @param[in] result  The result of OPP server response
- * @param[in] remote_address  The remote address
- * @param[in] user_data  The user data passed from the callback registration function
- * @pre bt_opp_client_push_files() will invoke this function.
- * @see bt_opp_client_push_files()
- */
-typedef void (*bt_opp_client_push_responded_cb)(int result, const char *remote_address, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
- * @brief  Called when each file is being transfered.
- * @param[in] file  The path of file to be pushed
- * @param[in] size The file size (bytes)
- * @param[in] percent The progress in percentage (1 ~ 100). 100 means that a file is transfered completely.
- * @param[in] user_data The user data passed from the callback registration function
- * @pre bt_opp_client_push_files() will invoke this function.
- * @see bt_opp_client_push_files()
- */
-typedef void (*bt_opp_client_push_progress_cb)(const char *file, long long size, int percent, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
- * @brief  Called when the push request is finished.
- * @param[in] result  The result of the push request
- * @param[in] remote_address  The remote address
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_opp_client_push_files()
- */
-typedef void (*bt_opp_client_push_finished_cb)(int result, const char *remote_address, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_MODULE
- * @brief  Called when the connection state is changed.
- * @details  This callback is called when the connection state is changed.
- * When you call bt_audio_connect() or bt_audio_disconnect(), this callback is also called with error result even though these functions fail.
- * @param[in] result  The result of changing the connection state
- * @param[in] connected  The state to be changed. @a true means connected state, Otherwise, @a false.
- * @param[in] remote_address  The remote address
- * @param[in] type  The type of audio profile except #BT_AUDIO_PROFILE_TYPE_ALL
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_audio_set_connection_state_changed_cb()
- * @see bt_audio_unset_connection_state_changed_cb()
- */
-typedef void (*bt_audio_connection_state_changed_cb) (int result, bool connected, const char *remote_address, bt_audio_profile_type_e type, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Called when the SCO(Synchronous Connection Oriented link) state is changed.
- * @details  This callback is called when the SCO state is changed.
- * When you call bt_ag_open_sco() or bt_ag_close_sco(), this callback is also called with error result even though these functions failed.
- * @param[in] result  The result of changing the connection state
- * @param[in] opened  The state to be changed: (@c true = opened, @c  false = not opened)
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_ag_set_sco_state_changed_cb()
- * @see bt_ag_unset_sco_state_changed_cb()
- * @see bt_ag_open_sco()
- * @see bt_ag_close_sco()
- */
-typedef void (*bt_ag_sco_state_changed_cb) (int result, bool opened, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Called when a call handling event happened from Hands-Free.
- * @param[in] event  The call handling event happened from Hands-Free
- * @param[in] call_id  The call ID
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_ag_set_call_handling_event_cb()
- * @see bt_ag_unset_call_handling_event_cb()
- */
-typedef void (*bt_ag_call_handling_event_cb) (bt_ag_call_handling_event_e event, unsigned int call_id, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Called when a multi call handling event happened from Hands-Free.
- * @param[in] event  The call handling event happened from Hands-Free
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_ag_set_multi_call_handling_event_cb()
- * @see bt_ag_unset_multi_call_handling_event_cb()
- */
-typedef void (*bt_ag_multi_call_handling_event_cb) (bt_ag_multi_call_handling_event_e event, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Called when a DTMF(Dual Tone Multi Frequency) is transmitted from Hands-Free.
- * @param[in] dtmf  The DTMF transmitted from Hands-Free
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_ag_set_dtmf_transmitted_cb()
- * @see bt_ag_unset_dtmf_transmitted_cb()
- */
-typedef void (*bt_ag_dtmf_transmitted_cb) (const char *dtmf, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Called when the speaker gain of the remote device is changed.
- * @param[in] gain The gain of speaker (0 ~ 15)
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_ag_set_speaker_gain_changed_cb()
- * @see bt_ag_unset_speaker_gain_changed_cb()
- */
-typedef void (*bt_ag_speaker_gain_changed_cb) (int gain, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Called when the microphone gain of the remote device is changed.
- * @param[in] gain The gain of microphone (0 ~ 15)
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_ag_set_microphone_gain_changed_cb()
- * @see bt_ag_unset_microphone_gain_changed_cb()
- */
-typedef void (*bt_ag_microphone_gain_changed_cb) (int gain, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief  Called when the connection state is changed.
- * @param[in] connected  The state to be changed. @a true means connected state, Otherwise, @a false.
- * @param[in] remote_address  The remote address
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_avrcp_target_initialize()
- * @see bt_avrcp_target_deinitialize()
- */
-typedef void (*bt_avrcp_target_connection_state_changed_cb) (bool connected, const char *remote_address, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief  Called when the equalizer state is changed by the remote control device.
- * @param[in] equalizer The equalizer state
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_avrcp_set_equalizer_state_changed_cb()
- * @see bt_avrcp_unset_equalizer_state_changed_cb()
- */
-typedef void (*bt_avrcp_equalizer_state_changed_cb) (bt_avrcp_equalizer_state_e equalizer, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief  Called when the repeat mode is changed by the remote control device.
- * @param[in] repeat The repeat mode
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_avrcp_set_repeat_mode_changed_cb()
- * @see bt_avrcp_unset_repeat_mode_changed_cb()
- */
-typedef void (*bt_avrcp_repeat_mode_changed_cb) (bt_avrcp_repeat_mode_e repeat, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief  Called when the shuffle mode is changed by the remote control device.
- * @param[in] shuffle The shuffle mode
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_avrcp_set_shuffle_mode_changed_cb()
- * @see bt_avrcp_unset_shuffle_mode_changed_cb()
- */
-typedef void (*bt_avrcp_shuffle_mode_changed_cb) (bt_avrcp_shuffle_mode_e shuffle, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
- * @brief  Called when the scan mode is changed by the remote control device.
- * @param[in] shuffle The shuffle mode
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_avrcp_set_scan_mode_changed_cb()
- * @see bt_avrcp_unset_scan_mode_changed_cb()
- */
-typedef void (*bt_avrcp_scan_mode_changed_cb) (bt_avrcp_scan_mode_e scan, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_HID_MODULE
- * @brief  Called when the connection state is changed.
- * @details  This callback is called when the connection state is changed.
- * When you call bt_hid_host_connect() or bt_hid_host_disconnect(), this callback is also called with error result even though these functions fail.
- * @param[in] result  The result of changing the connection state
- * @param[in] connected  The state to be changed. @a true means connected state, Otherwise, @a false.
- * @param[in] remote_address  The remote address
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_hid_host_connect()
- * @see bt_hid_host_disconnect()
- */
-typedef void (*bt_hid_host_connection_state_changed_cb) (int result, bool connected, const char *remote_address, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
- * @brief  Called when the connection is established.
- * @param[in] result  The result of connecting to the remote device
- * @param[in] remote_address  The address of connected remote device
- * @param[in] app_id  The ID of application
- * @param[in] type  The type of HDP(Health Device Profile) channel
- * @param[in] channel  The connected data channel
- * @param[in] user_data The user data passed from the callback registration function
- * @see  bt_hdp_disconnected_cb
- * @see bt_hdp_set_connection_state_changed_cb()
- * @see bt_hdp_unset_connection_state_changed_cb()
- */
-typedef void (*bt_hdp_connected_cb) (int result, const char *remote_address, const char *app_id,
-    bt_hdp_channel_type_e type, unsigned int channel, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
- * @brief  Called when the connection is disconnected.
- * @param[in] result  The result of disconnecting from the remote device
- * @param[in] remote_address  The address of disconnected remote device
- * @param[in] channel  The connected data channel
- * @param[in] user_data The user data passed from the callback registration function
- * @see  bt_hdp_connected_cb
- * @see bt_hdp_set_connection_state_changed_cb()
- * @see bt_hdp_unset_connection_state_changed_cb()
- */
-typedef void (*bt_hdp_disconnected_cb) (int result, const char *remote_address, unsigned int channel, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
- * @brief  Called when the you receive the data.
- * @param[in] channel  The connected data channel
- * @param[in] data  The received data
- * @param[in] size  The size of received data (byte)
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_hdp_set_data_received_cb()
- * @see bt_hdp_unset_data_received_cb()
- */
-typedef void (*bt_hdp_data_received_cb) (unsigned int channel, const char *data, unsigned int size, void *user_data);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Called when you get the primary services repeatedly.
- * @param[in]  service  The attribute handle of service
- * @param[in]  index  The index of a service, starts from 0
- * @param[in]  total  The total number of services
- * @param[in]  user_data  The user data passed from the foreach function
- * @return  @c true to continue with the next iteration of the loop,
- * \n @c false to break out of the loop.
- * @pre  bt_gatt_foreach_primary_services() will invoke this function.
- * @see  bt_gatt_foreach_primary_services()
- */
-typedef bool (*bt_gatt_primary_service_cb) (bt_gatt_attribute_h service, int index, int total, void *user_data);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Called after the characteristics are discovered by bt_gatt_discover_characteristics().
- * @remarks  If bt_gatt_discover_characteristics() failed, then this callback function is called only once with 0 totla and NULL characteristic_handle.
- * @param[in]  result  The result of discovering
- * @param[in]  index  The index of characteristics in a service, starts from 0
- * @param[in]  total  The total number of characteristics in a service
- * @param[in]  characteristic  The attribute handle of characteristic
- * @param[in]  user_data  The user data passed from the request function
- * @return  @c true to continue with the next iteration of the loop,
- * \n @c false to break out of the loop.
- * @pre  bt_gatt_discover_characteristics() will invoke this callback.
- * @see  bt_gatt_discover_characteristics()
- */
-typedef bool (*bt_gatt_characteristics_discovered_cb) (int result, int index, int total, bt_gatt_attribute_h characteristic, void *user_data);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Called when you get the included services repeatedly.
- * @param[in]  service  The attribute handle of service
- * @param[in]  user_data  The user data passed from the foreach function
- * @return  @c true to continue with the next iteration of the loop,
- * \n @c false to break out of the loop.
- * @pre  bt_gatt_foreach_included_services() will invoke this function.
- * @see  bt_gatt_foreach_included_services()
- */
-typedef bool (*bt_gatt_included_service_cb) (bt_gatt_attribute_h service, void *user_data);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Called when a characteristic in service is changed.
- * @param[in]  characteristic  The attribute handle of characteristic
- * @param[in]  value  The value of characteristic (byte array)
- * @param[in]  value_length  The length of value
- * @param[in]  user_data  The user data passed from the callback registration function
- * @see bt_gatt_set_characteristic_changed_cb()
- * @see bt_gatt_unset_characteristic_changed_cb()
- */
-typedef void (*bt_gatt_characteristic_changed_cb) (bt_gatt_attribute_h characteristic, unsigned char *value, int value_length, void *user_data);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Called when a characteristic value is written.
- * @see bt_gatt_set_characteristic_value()
- */
-typedef void (*bt_gatt_characteristic_write_cb) (int result, void *user_data);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Called when a characteristic value is read.
- * @param[in]  value  The value of characteristic (byte array)
- * @param[in]  value_length  The length of value
- * @param[in]  user_data  The user data passed from the foreach function
- * @see bt_gatt_read_characteristic_value()
- */
-typedef void (*bt_gatt_characteristic_read_cb) (unsigned char *value,
-                       int value_length, void *user_data);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief  Called after the characteristics descriptors are discovered by bt_gatt_discover_characteristic_descriptor().
- * @param[in]  result  The result of discovering
- * @param[in]  characteristic_format  The format of the information data.
- *                        characteristic_format = 0x01 indicates UUIDs are 16-bits
- *                        characteristic_format = 0x02 indicates UUIDs are 128-bits
- * @param[in]  total  The total number of elements in characteristic_descriptor
- * @param[in]  characteristic descriptor  The attribute handle and the UUID of characteristic descriptor
- * @param[in]  characteristic  The attribute handle and the UUID of characteristic
- * @param[in]  user_data  The user data passed from the request function
- * @see  bt_gatt_discover_characteristic_descriptor()
- */
-typedef void (*bt_gatt_characteristic_descriptor_discovered_cb) (int result,
-               unsigned char characteristic_format, int total,
-               bt_gatt_attribute_h characteristic_descriptor,
-               bt_gatt_attribute_h characteristic, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief Called when the connection state is changed.
- * @details This callback is called when the connection state is changed.
- * When you called bt_gatt_connect() or bt_gatt_disconnect(), this callback is also called with error result even though these functions fail.
- *
- * @param[in] result The result of changing the connection state.
- * @param[in] connected The state to be changed, @a true means connected state, Otherwise, @a false.
- * @param[in] remote_address The remote_address
- * @param[in] user_data The user data passed from the callback registration function.
- *
- * @see bt_gatt_connect()
- * @see bt_gatt_disconnect()
- * @see bt_gatt_set_connection_state_changed_cb()
- * @see bt_gatt_unset_connection_state_changed_cb()
- */
-typedef void (*bt_gatt_connection_state_changed_cb)(int result, bool connected, const char *remote_address, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
- * @brief Called when the remote devices writes a characteristic to the server db.
- * @details This callback is called when the remote client device writes a characteristics
- *                     to the server attribute database.
- *
- * @param[in] char_path Characteristic path for which the value is writtten.
- * @param[in] char_value The characteristic value
- * @param[in] value_length The length of the characteristic value written.
- * @param[in] remote_address remote client device bd address.
- *
- * @see bt_gatt_connect()
- */
-typedef void (*bt_gatt_remote_characteristic_write_cb) (char *char_path,
-                                       unsigned char* char_value, int value_length,
-                                       const char *remote_address,
-                                       void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_NAP_MODULE
- * @brief  Called when the connection state is changed.
- * @param[in] connected  Indicates whether a client is connected or disconnected
- * @param[in] remote_address  The remote address
- * @param[in] interface_name  The interface name. For example, bnep0, bnep1.
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_nap_set_connection_state_changed_cb()
- * @see bt_nap_unset_connection_state_changed_cb()
- */
-typedef void (*bt_nap_connection_state_changed_cb) (bool connected, const char *remote_address, const char *interface_name, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_PANU_MODULE
- * @brief  Called when the connection state is changed.
- * @details  This callback is called when the connection state is changed.
- * When you call bt_panu_connect() or bt_panu_disconnect(), this callback is also called with error result even though these functions fail.
- * @param[in] result  The result of changing the connection state
- * @param[in] connected  The state to be changed. @a true means connected state, Otherwise, @a false.
- * @param[in] remote_address  The remote address
- * @param[in] type  The type of PAN service
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_nap_set_connection_state_changed_cb()
- * @see bt_nap_unset_connection_state_changed_cb()
- */
-typedef void (*bt_panu_connection_state_changed_cb) (int result, bool connected, const char *remote_address, bt_panu_service_type_e type, void *user_data);
-
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif // __TIZEN_NETWORK_BLUETOOTH_TYPE_H__
diff --git a/resource/csdk/connectivity/lib/tizen/ble/inc/mobile/bluetooth_product.h b/resource/csdk/connectivity/lib/tizen/ble/inc/mobile/bluetooth_product.h
deleted file mode 100644 (file)
index 74f2b55..0000000
+++ /dev/null
@@ -1,315 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd 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.
- */
-
-/**
- * @file
- *
- *
- */
-
-#ifndef __TIZEN_NETWORK_BLUETOOTH_PRODUCT_H__
-#define __TIZEN_NETWORK_BLUETOOTH_PRODUCT_H__
-
-#include "bluetooth_type.h"
-#include "bluetooth_type_product.h"
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif /* __cplusplus */
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief Sets the manufacturer data of local Bluetooth adapter.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- *
- * @param[in]   data   The manufacturer specific data of the Bluetooth device.
- * @param[in]   len    The length of @a data.Maximaum length is 240 bytes.
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_OPERATION_FAILED Operation failed
- *
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @post bt_adapter_manufacturer_data_changed_cb() will be invoked
- * if this function returns #BT_ERROR_NONE.
- *
- * @see bt_adapter_manufacturer_data_changed_cb
- * @see bt_adapter_set_manufacturer_data_changed_cb()
- * @see bt_adapter_unset_manufacturer_data_changed_cb()
- */
-int bt_adapter_set_manufacturer_data(char *data, int len);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief  Registers a callback function to be invoked
- * when the manufacturer data of Bluetooth adapter changes.
- * @since_tizen 2.3
- *
- * @param[in]   callback       The callback function to invoke
- * @param[in]   user_data      The user data to be passed to the callback function
- *
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- *
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @post  bt_adapter_manufacturer_data_changed_cb() will be invoked.
- *
- * @see bt_initialize()
- * @see bt_adapter_unset_manufacturer_data_changed_cb()
- */
-int bt_adapter_set_manufacturer_data_changed_cb(
-               bt_adapter_manufacturer_data_changed_cb callback,
-               void *user_data);
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief      Unregisters the callback function.
- * @since_tizen 2.3
- *
- * @return     0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- *
- * @pre The Bluetooth service must be initialized with bt_initialize().
- *
- * @see bt_initialize()
- * @see bt_adapter_set_manufacturer_data_changed_cb()
- */
-int bt_adapter_unset_manufacturer_data_changed_cb(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief Sets the scan interval and widow, synchronously.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @param[in]  scan_params  The parameters of le scanning \n
- *                             If NULL is passed, default values which are defined in driver / controller are used.
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE Successful
- * @retval #BT_ERROR_NOT_ENABLED Adapter is not enabled
- * @retval #BT_ERROR_INVALID_PARAM Parameter is invalid
- * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
- * @pre The Bluetooth service must be initialized with bt_initialize().
- * @see bt_initialize()
- */
-int bt_adapter_le_set_scan_parameter(bt_adapter_le_scan_params_s *scan_params);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Enables RSSI monitoring and sets threshold for LE/ACL link present with the remote device.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- *
- * @param[in] remote_address The address of the remote Bluetooth device for which RSSI is to be monitored
- * @param[in] link_type Link type for the connection (@c 0 = BR/EDR link, @c 1 = LE link).
- * @param[in] low_threshold Lower threshold value for the LE Link in dBm.
- * @param[in] in_range_threshold In-Range threshold value for the LE Link in dBm.
- * @param[in] cb_enable Callback to be called when RSSI monitoring is enabled.
- * @param[in] user_data_enable Data to be passed to RSSI enable callback.
- * @param[in] cb_alert Callback to receive RSSI Alert values.
- * @param[in] user_data_alert Data to be passed to RSSI Alert callback.
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_RESOURCE_BUSY  Device or resource busy
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- *
- * @remarks High Threshold value is set to 127.
- *
- * @see bt_device_unset_rssi_alert_cb()
- * @see bt_device_disable_rssi_monitor()
- */
-int bt_device_enable_rssi_monitor(const char *remote_address,
-               bt_device_connection_link_type_e link_type,
-               int low_threshold, int in_range_threshold,
-               bt_rssi_monitor_enabled_cb cb_enable, void *user_data_enable,
-               bt_rssi_alert_cb cb_alert, void *user_data_alert);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Disables RSSI monitoring for LE/ACL link present with the remote device.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- *
- * @param[in] remote_address The address of the remote Bluetooth device for which RSSI monitoring is to be disabled
- * @param[in] link_type Link type for the connection (@c 0 = BR/EDR link, @c 1 = LE link).
- * @param[in] cb_disable Callback to be called when RSSI monitoring is disabled.
- * @param[in] user_data_enable Data to be passed to RSSI enable callback.
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_RESOURCE_BUSY  Device or resource busy
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- *
- * @remarks Low Threshold, In-range Threshold and High Threshold value are set to 0 to disable RSSI monitoring.
- * @remarks This also calls bt_device_unset_rssi_alert_cb()
- *
- * @see bt_device_unset_rssi_alert_cb()
- * @see bt_device_enable_rssi_monitor()
- */
-int bt_device_disable_rssi_monitor(const char *remote_address,
-               bt_device_connection_link_type_e link_type,
-               bt_rssi_monitor_enabled_cb cb_disable, void *user_data_disable);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Get Raw RSSI for LE link present with the remote device.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- *
- * @param[in] remote_address The address of the remote Bluetooth device for which RSSI is to be monitored
- * @param[in] link_type Link type for the connection (@c 0 = BR/EDR link, @c 1 = LE link).
- * @param[in] callback Callback to receive Raw RSSI values.
- * @param[in] user_data Data to be passed to Raw RSSI callback.
- *
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_RESOURCE_BUSY  Device or resource busy
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- *
- * @see bt_device_le_unset_rssi_strength_cb()
- */
-int bt_device_get_rssi_strength(const char *remote_address,
-               bt_device_connection_link_type_e link_type,
-               bt_rssi_strength_cb callback, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief Unset the callback to receive RSSI Alert values.
- * @since_tizen 2.3
- *
- * @return 0 on success, otherwise a negative error value.
- *
- * @see bt_device_le_enable_rssi()
- */
-int bt_device_unset_rssi_alert_cb(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief Notifies the XSAT vendor command to the remote.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @param[in] state  The XSAT vendor dependent command string. Ex: "AT+SAT= 00,TY,WA"
- * @return 0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device is not bonded
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
- * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
- * @pre The Bluetooth audio device must be connected with bt_audio_connect().
- * @see bt_audio_connect()
- */
-int bt_ag_notify_vendor_cmd(const char *command);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Registers a callback function that will be invoked when a XSATvendor AT command is transmitted from Hands-Free.
- * @since_tizen 2.3
- * @param[in] callback The callback function to register
- * @param[in] user_data The user data to be passed to the callback function
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
- * @see bt_audio_initialize()
- * @see bt_ag_vendor_cmd_cb()
- * @see bt_ag_unset_vendor_cmd_cb()
- */
-int bt_ag_set_vendor_cmd_cb(bt_ag_vendor_cmd_cb callback, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Unregisters a callback function that will be invoked when a XSATvendor AT command is transmitted from Hands-Free
- * @since_tizen 2.3
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
- * @see bt_audio_initialize()
- * @see bt_ag_vendor_cmd_cb()
- * @see bt_ag_set_vendor_cmd_cb()
- */
-int bt_ag_unset_vendor_cmd_cb(void);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief Checks whether the remoted device is wbs (Wide Band Speech) mode or not.
- * @since_tizen 2.3
- * @param[out] wbs_mode The wbs status: (@c true = wide band speech, @c  false = narrow band speech)
- * @return   0 on success, otherwise a negative error value.
- * @retval #BT_ERROR_NONE  Successful
- * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
- * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
- * @retval #BT_ERROR_NOT_ENABLED  Not enabled
- * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
- * @pre The remote device is connected by bt_audio_connect() with #BT_AUDIO_PROFILE_TYPE_HSP_HFP service.
- * @see bt_audio_connect()
- */
-int bt_ag_is_wbs_mode(bool *wbs_mode);
-
-/**
- * @ingroup  CAPI_NETWORK_BLUETOOTH_AUDIO_A2DP_MODULE
- * @brief  Sets copy protection. streaming application that needs to have the copy protection for the streaming data, shall invoke this API.
- * @since_tizen 2.3
- * @privlevel platform
- * @privilege %http://tizen.org/privilege/bluetooth.admin
- * @param[in] status - TRUE/FALSE
- * @return  0 on success, otherwise negative error value.
- * @retval  #BT_ERROR_NONE  Successful
- * @retval  #BT_ERROR_OPERATION_FAILED  on failure
- */
-int bt_a2dp_set_content_protection(bool status);
-
-
-/**
- * @}
- */
-
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif // __TIZEN_NETWORK_BLUETOOTH_PRODUCT_H__
diff --git a/resource/csdk/connectivity/lib/tizen/ble/inc/mobile/bluetooth_type_product.h b/resource/csdk/connectivity/lib/tizen/ble/inc/mobile/bluetooth_type_product.h
deleted file mode 100644 (file)
index 999b847..0000000
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd 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.
- */
-
-/**
- * @file
- *
- *
- */
-
-#ifndef __TIZEN_NETWORK_BLUETOOTH_TYPE_PRODUCT_H__
-#define __TIZEN_NETWORK_BLUETOOTH_TYPE_PRODUCT_H__
-
- #ifdef __cplusplus
-extern "C"
-{
-#endif /* __cplusplus */
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief  Enumerations of the Bluetooth adapter le scan type.
- */
-typedef enum
-{
-       BT_ADAPTER_LE_PASSIVE_SCAN = 0x00,
-       BT_ADAPTER_LE_ACTIVE_SCAN
-} bt_adapter_le_scan_type_e;
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
- * @brief Structure of le scan parameters
- *
- * @see bt_adapter_le_set_scan_parameter()
- * @see bt_adapter_le_start_device_discovery()
- */
-typedef struct {
-       bt_adapter_le_scan_type_e type;  /**< LE scan type */
-       float interval;  /**< LE scan interval */
-       float window;  /**< LE scan window */
-} bt_adapter_le_scan_params_s;
-
-/**
- * @internal
- * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
- * @brief  Called when the manufacturer dat changes.
- * @param[in]   data           The manufacurer data of the Bluetooth device to be changed
- * @param[in]   len                    The length of @a data
- * @param[in]   user_data      The user data passed from the callback registration function
- * @pre This function will be invoked when the manufacturer data of Bluetooth adapter changes
- * if callback is registered using bt_adapter_set_manufacturer_data_changed_cb().
- * @see bt_adapter_set_manufacturer_data()
- * @see bt_adapter_set_manufacturer_data_changed_cb()
- * @see bt_adapter_unset_manufacturer_data_changed_cb()
- */
-typedef void (*bt_adapter_manufacturer_data_changed_cb) (char *data,
-               int len, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief  Called when RSSI monitoring is enabled.
- * @param[in] remote_address Remote Device address
- * @param[in] link_type Link type for the connection (@c 0 = BR/EDR link, @c 1 = LE link).
- * @param[in] rssi_enabled RSSI monitoring status (@c 1 = enabled, @c 0 = disabled)
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_device_enable_rssi_monitor()
- * @see bt_device_disable_rssi_monitor()
- */
-typedef void (*bt_rssi_monitor_enabled_cb)(const char *remote_address,
-               bt_device_connection_link_type_e link_type,
-               int rssi_enabled, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief  Called when RSSI Alert is received.
- * @param[in] remote_address Remote Device address
- * @param[in] link_type Link type for the connection (@c 0 = BR/EDR link, @c 1 = LE link).
- * @param[in] rssi_alert_type RSSI Alert type (@c 1 = High Alert (In-Range Alert), @c 2 = Low Alert)
- * @param[in] rssi_alert_dbm RSSI Alert signal strength value
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_device_enable_rssi_monitor()
- * @see bt_device_disable_rssi_monitor()
- */
-typedef void (*bt_rssi_alert_cb)(char *bt_address,
-               bt_device_connection_link_type_e link_type,
-               int rssi_alert_type, int rssi_alert_dbm, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
- * @brief  Called when Raw RSSI signal strength is received.
- * @param[in] remote_address Remote Device address
- * @param[in] link_type Link type for the connection (@c 0 = BR/EDR link, @c 1 = LE link).
- * @param[in] rssi_dbm Raw RSSI signal strength value
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_device_get_rssi_strength()
- */
-typedef void (*bt_rssi_strength_cb)(char *bt_address,
-               bt_device_connection_link_type_e link_type,
-               int rssi_dbm, void *user_data);
-
-/**
- * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
- * @brief  Called when a XSAT vendor command is transmitted from Hands-Free.
- * @param[in] command  The XSAT vendor command transmitted from Hands-Free
- * @param[in] user_data The user data passed from the callback registration function
- * @see bt_ag_set_vendor_cmd_cb()
- * @see bt_ag_unset_vendor_cmd_cb()
- */
-typedef void (*bt_ag_vendor_cmd_cb) (char *command, void *user_data);
-
-
-/**
- * @}
- */
-
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif // __TIZEN_NETWORK_BLUETOOTH_TYPE_PRODUCT_H__
diff --git a/resource/csdk/connectivity/samples/android/SConscript b/resource/csdk/connectivity/samples/android/SConscript
deleted file mode 100644 (file)
index 9487cba..0000000
+++ /dev/null
@@ -1,56 +0,0 @@
-##
-# Building sample application
-##
-
-Import('env')
-
-app_env = env.Clone()
-
-ca_os = app_env.get('TARGET_OS')
-ca_transport = app_env.get('TARGET_TRANSPORT')
-secured = app_env.get('SECURED')
-
-root_dir = './../../'
-main_dir  = Dir('.').srcnode().abspath
-jni_dir = main_dir + '/sample_serivce/android/jni'
-env.PrependUnique(CPPPATH = ['jni_dir'])
-app_env.PrependUnique(CPPDEFINES = ['__ANDROID__'])
-
-#####################################################################
-# Source files and Target(s)
-######################################################################
-
-print"Reading ca script %s"%ca_transport
-
-app_env.AppendUnique(CPPPATH = [root_dir + '/api/'])
-app_env.AppendUnique(CPPPATH = [root_dir + '/inc/'])
-app_env.AppendUnique(CPPPATH = [root_dir + '/common/inc/'])
-app_env.AppendUnique(CPPPATH = [root_dir + 'lib/libcoap-4.1.1'])
-
-print "Reading sample application build script"
-
-build_dir = app_env.get('BUILD_DIR')
-secured = app_env.get('SECURED')
-
-print "Sample secured flag is %s" % secured
-
-sample_dir = 'casample/sampleService/src/main/jni/'
-sample_src = [sample_dir + 'ResourceModel.c',]
-
-print " sample src %s" % sample_src
-
-app_env.AppendUnique(LIBPATH = [app_env.get('BUILD_DIR'), '.',])
-app_env.AppendUnique(CPPPATH = ['lib/android'])
-app_env.PrependUnique(LIBS = ['connectivity_abstraction'])
-app_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
-
-
-if secured == '1':
-       app_env.AppendUnique(CPPPATH = [root_dir + 'external/inc/'])
-       app_env.PrependUnique(CPPDEFINES = ['__WITH_DTLS__'])
-
-libRMInterface = app_env.SharedLibrary('RMInterface', sample_src, OBJPREFIX='libRMInterface_')
-app_env.InstallTarget(libRMInterface, 'RMInterface')
-app_env.UserInstallTargetLib(libRMInterface, 'RMInterface')
-
-
diff --git a/resource/csdk/connectivity/samples/android/casample/.gitignore b/resource/csdk/connectivity/samples/android/casample/.gitignore
deleted file mode 100644 (file)
index 6f9b76a..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-local.properties
-import-summary.txt
-/.idea/
-/.gradle/
-/build/
diff --git a/resource/csdk/connectivity/samples/android/casample/SConscript b/resource/csdk/connectivity/samples/android/casample/SConscript
deleted file mode 100644 (file)
index e285068..0000000
+++ /dev/null
@@ -1,28 +0,0 @@
-import os
-import platform
-Import('env')
-
-ANDROID_TARGET_ARCH = env.get('TARGET_ARCH')
-if env.get('RELEASE'):
-       ANDROID_RELEASE="release"
-else:
-       ANDROID_RELEASE="debug"
-
-print '''
-***************************************** Info ********************************
-* NOTE: If you have a problem in downloading the gradle-core-1.1.0.jar file   *
-*       please do one time setup as below                                     *
-*                                                                             *
-* Edit resource/csdk/connectivity/samples/android/casample/gradle.properties  *
-* Add the proxy information as below :                                        *
-*    systemProp.http.proxyPort=<YOUR_PORT_NUMBER>                             *
-*    systemProp.http.proxyHost=<YOUR_HTTP_PROXY_ADDRESS>                      *
-*    systemProp.https.proxyPort=<YOUR_PORT_NUMBER>                            *
-*    systemProp.https.proxyHost=<YOUR_HTTP_PROXY_ADDRESS>                     *
-*                                                                             *
-*******************************************************************************
-'''
-jdk_env = Environment(ENV=os.environ)
-jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') + ' build -b' + Dir('.').srcnode().abspath + '/build.gradle -PTARGET_ARCH=%s -PRELEASE=%s' %(ANDROID_TARGET_ARCH, ANDROID_RELEASE))
-jdk_env.Gradle(target="base/objs", source="sampleService/src/main/java/org/iotivity/ca/service/MainActivity.java")
-
diff --git a/resource/csdk/connectivity/samples/android/casample/build.gradle b/resource/csdk/connectivity/samples/android/casample/build.gradle
deleted file mode 100755 (executable)
index 2712137..0000000
+++ /dev/null
@@ -1,21 +0,0 @@
-// Top-level build file where you can add configuration options common to all sub-projects/modules.
-buildscript {
-    repositories {
-        jcenter()
-               {
-                       url "http://jcenter.bintray.com"
-               }
-    }
-    dependencies {
-        classpath 'com.android.tools.build:gradle:1.3.0'
-    }
-}
-
-allprojects {
-    repositories {
-        jcenter()
-               {
-                       url "http://jcenter.bintray.com"
-               }
-    }
-}
diff --git a/resource/csdk/connectivity/samples/android/casample/cAInterface/.gitignore b/resource/csdk/connectivity/samples/android/casample/cAInterface/.gitignore
deleted file mode 100644 (file)
index 84c048a..0000000
+++ /dev/null
@@ -1 +0,0 @@
-/build/
diff --git a/resource/csdk/connectivity/samples/android/casample/cAInterface/build.gradle b/resource/csdk/connectivity/samples/android/casample/cAInterface/build.gradle
deleted file mode 100755 (executable)
index 6ca1fe0..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-apply plugin: 'com.android.library'
-
-android {
-    compileSdkVersion 21
-    buildToolsVersion "20.0.0"
-
-    defaultConfig {
-        minSdkVersion 21
-        targetSdkVersion 21
-    }
-
-    buildTypes {
-        release {
-            minifyEnabled false
-            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
-        }
-    }
-
-    lintOptions {
-       abortOnError false
-    }
-}
-
-dependencies {
-//    compile 'com.android.support:support-v4:21.0.3'
-}
diff --git a/resource/csdk/connectivity/samples/android/casample/cAInterface/cAInterface.iml b/resource/csdk/connectivity/samples/android/casample/cAInterface/cAInterface.iml
deleted file mode 100755 (executable)
index 217b60e..0000000
+++ /dev/null
@@ -1,93 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="MainActivity" 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=":cAInterface" />
-      </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="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
-        <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugAndroidTestSources" />
-        <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" />
-        <option name="LIBRARY_PROJECT" value="true" />
-      </configuration>
-    </facet>
-  </component>
-  <component name="NewModuleRootManager" 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/generated/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/generated/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/tmp" />
-    </content>
-    <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
-    <orderEntry type="sourceFolder" forTests="false" />
-    <orderEntry type="library" exported="" name="support-v4-21.0.3" level="project" />
-    <orderEntry type="library" exported="" name="support-annotations-21.0.3" level="project" />
-  </component>
-</module>
-
diff --git a/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/.gitignore b/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/.gitignore
deleted file mode 100644 (file)
index 7cf58ac..0000000
+++ /dev/null
@@ -1 +0,0 @@
-/assets/
diff --git a/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/AndroidManifest.xml b/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/AndroidManifest.xml
deleted file mode 100755 (executable)
index 4bc64f6..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="org.iotivity.ca"
-    android:versionCode="1"
-    android:versionName="1.0" >
-
-    <uses-sdk
-        android:minSdkVersion="21"
-        android:targetSdkVersion="21" />
-
-    <application
-        android:allowBackup="true"
-        android:icon="@drawable/ic_launcher"
-        android:label="@string/app_name"
-        android:theme="@style/AppTheme" >
-    </application>
-
-</manifest>
diff --git a/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/java/org/iotivity/ca/CaEdrInterface.java b/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/java/org/iotivity/ca/CaEdrInterface.java
deleted file mode 100755 (executable)
index 1e4d47c..0000000
+++ /dev/null
@@ -1,87 +0,0 @@
-/******************************************************************
- *
- * Copyright 2014 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.ca;
-
-import android.bluetooth.BluetoothAdapter;
-import android.bluetooth.BluetoothDevice;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-
-public class CaEdrInterface {
-
-    private CaEdrInterface(Context context) {
-
-        registerIntentFilter(context);
-    }
-
-    private static IntentFilter registerIntentFilter(Context context) {
-        IntentFilter filter = new IntentFilter();
-        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
-        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
-        context.registerReceiver(mReceiver, filter);
-        return filter;
-    }
-
-    // Network Monitor
-    private native static void caEdrStateChangedCallback(int state);
-
-    private native static void caEdrBondStateChangedCallback(String addr);
-
-    private static final BroadcastReceiver mReceiver = new BroadcastReceiver() {
-
-        @Override
-        public void onReceive(Context context, Intent intent) {
-
-            String action = intent.getAction();
-
-            if (action != null && action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
-
-                int state =
-                        intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
-
-                // STATE_ON:12, STATE_OFF:10
-                if (state == BluetoothAdapter.STATE_ON || state == BluetoothAdapter.STATE_OFF)
-                {
-                    caEdrStateChangedCallback(state);
-                }
-            }
-
-            if (action != null && action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
-
-                int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE,
-                                                   BluetoothDevice.ERROR);
-
-                if (bondState == BluetoothDevice.BOND_NONE) {
-                    if ((intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE,
-                                            BluetoothDevice.ERROR)
-                                                == BluetoothDevice.BOND_BONDED)) {
-                        BluetoothDevice device
-                            = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
-
-                        caEdrBondStateChangedCallback(device.getAddress());
-                    }
-                }
-            }
-        }
-    };
-}
diff --git a/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/java/org/iotivity/ca/CaIpInterface.java b/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/java/org/iotivity/ca/CaIpInterface.java
deleted file mode 100755 (executable)
index cbe0ec0..0000000
+++ /dev/null
@@ -1,68 +0,0 @@
-/******************************************************************
- *
- * Copyright 2014 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.ca;
-
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.net.ConnectivityManager;
-import android.net.NetworkInfo;
-import android.net.wifi.WifiManager;
-
-public class CaIpInterface {
-    private static Context mContext;
-
-    private CaIpInterface(Context context) {
-        mContext = context;
-        registerIpStateReceiver();
-    }
-
-    private void registerIpStateReceiver() {
-        IntentFilter intentFilter = new IntentFilter();
-        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
-        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
-
-        mContext.registerReceiver(mReceiver, intentFilter);
-    }
-
-    private static BroadcastReceiver mReceiver = new BroadcastReceiver() {
-        @Override
-        public void onReceive(Context context, Intent intent) {
-            if (intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
-                WifiManager.WIFI_STATE_UNKNOWN) == WifiManager.WIFI_STATE_DISABLED) {
-                caIpStateDisabled();
-            } else if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
-                ConnectivityManager manager = (ConnectivityManager)
-                        mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
-                NetworkInfo nwInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
-
-                if(nwInfo.isConnected()) {
-                    caIpStateEnabled();
-                }
-            }
-        }
-    };
-
-    private native static void caIpStateEnabled();
-
-    private native static void caIpStateDisabled();
-}
\ No newline at end of file
diff --git a/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/java/org/iotivity/ca/CaLeClientInterface.java b/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/java/org/iotivity/ca/CaLeClientInterface.java
deleted file mode 100755 (executable)
index 5a21786..0000000
+++ /dev/null
@@ -1,272 +0,0 @@
-/******************************************************************
- *
- * Copyright 2014 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.ca;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.UUID;
-
-import android.bluetooth.BluetoothAdapter;
-import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothGatt;
-import android.bluetooth.BluetoothGattCallback;
-import android.bluetooth.BluetoothGattCharacteristic;
-import android.bluetooth.BluetoothGattDescriptor;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.util.Log;
-
-public class CaLeClientInterface {
-
-    private static String SERVICE_UUID = "ADE3D529-C784-4F63-A987-EB69F70EE816";
-    private static String TAG          = "Sample_Service : CaLeClientInterface";
-
-    private CaLeClientInterface(Context context) {
-
-        caLeRegisterLeScanCallback(mLeScanCallback);
-        caLeRegisterGattCallback(mGattCallback);
-
-        registerIntentFilter(context);
-    }
-
-    public static void getLeScanCallback() {
-        caLeRegisterLeScanCallback(mLeScanCallback);
-    }
-
-    public static void getLeGattCallback() {
-        caLeRegisterGattCallback(mGattCallback);
-    }
-
-    private static IntentFilter registerIntentFilter(Context context) {
-        IntentFilter filter = new IntentFilter();
-        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
-        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
-        context.registerReceiver(mReceiver, filter);
-        return filter;
-    }
-
-    private native static void caLeRegisterLeScanCallback(BluetoothAdapter.LeScanCallback callback);
-
-    private native static void caLeRegisterGattCallback(BluetoothGattCallback callback);
-
-    // BluetoothAdapter.LeScanCallback
-    private native static void caLeScanCallback(BluetoothDevice device);
-
-    // BluetoothGattCallback
-    private native static void caLeGattConnectionStateChangeCallback(
-            BluetoothGatt gatt, int status, int newState);
-
-    private native static void caLeGattServicesDiscoveredCallback(BluetoothGatt gatt, int status);
-
-    private native static void caLeGattCharacteristicWriteCallback(
-            BluetoothGatt gatt, byte[] data, int status);
-
-    private native static void caLeGattCharacteristicChangedCallback(
-            BluetoothGatt gatt, byte[] data);
-
-    private native static void caLeGattDescriptorWriteCallback(BluetoothGatt gatt, int status);
-
-    private native static void caLeGattReliableWriteCompletedCallback(BluetoothGatt gatt,
-                                                                     int status);
-
-    private native static void caLeGattReadRemoteRssiCallback(BluetoothGatt gatt, int rssi,
-                                                             int status);
-
-    // Network Monitor
-    private native static void caLeStateChangedCallback(int state);
-
-    // bond state
-    private native static void caLeBondStateChangedCallback(String address);
-
-    // Callback
-    private static BluetoothAdapter.LeScanCallback mLeScanCallback =
-                   new BluetoothAdapter.LeScanCallback() {
-
-        @Override
-        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
-
-            try {
-                List<UUID> uuids = getUuids(scanRecord);
-                for (UUID uuid : uuids) {
-                    Log.d(TAG, "UUID : " + uuid.toString());
-                    if(uuid.toString().contains(SERVICE_UUID.toLowerCase())) {
-                        Log.d(TAG, "we found that has the Device");
-                        caLeScanCallback(device);
-                    }
-                }
-            } catch(UnsatisfiedLinkError e) {
-
-            }
-        }
-    };
-
-    private static List<UUID> getUuids(final byte[] scanRecord) {
-        List<UUID> uuids = new ArrayList<UUID>();
-
-        int offset = 0;
-        while (offset < (scanRecord.length - 2)) {
-            int len = scanRecord[offset++];
-            if (len == 0)
-                break;
-
-            int type = scanRecord[offset++];
-
-            switch (type) {
-            case 0x02:
-            case 0x03:
-                while (len > 1) {
-                    int uuid16 = scanRecord[offset++];
-                    uuid16 += (scanRecord[offset++] << 8);
-                    len -= 2;
-                    uuids.add(UUID.fromString(String.format(
-                            "%08x-0000-1000-8000-00805f9b34fb", uuid16)));
-                }
-                break;
-            case 0x06:
-            case 0x07:
-                while (len >= 16) {
-                    try {
-                        ByteBuffer buffer = ByteBuffer.wrap(scanRecord, offset++, 16).
-                                                            order(ByteOrder.LITTLE_ENDIAN);
-                        long mostSigBits = buffer.getLong();
-                        long leastSigBits = buffer.getLong();
-                        uuids.add(new UUID(leastSigBits, mostSigBits));
-                    } catch (IndexOutOfBoundsException e) {
-                        Log.e(TAG, e.toString());
-                        continue;
-                    } finally {
-                        offset += 15;
-                        len -= 16;
-                    }
-                }
-                break;
-            default:
-                offset += (len - 1);
-                break;
-            }
-        }
-        return uuids;
-    }
-
-    private static final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
-
-        @Override
-        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
-            super.onConnectionStateChange(gatt, status, newState);
-
-            caLeGattConnectionStateChangeCallback(gatt, status, newState);
-        }
-
-        @Override
-        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
-            super.onServicesDiscovered(gatt, status);
-
-            caLeGattServicesDiscoveredCallback(gatt, status);
-        }
-
-        @Override
-        public void onCharacteristicRead(BluetoothGatt gatt,
-                BluetoothGattCharacteristic characteristic, int status) {
-            super.onCharacteristicRead(gatt, characteristic, status);
-        }
-
-        @Override
-        public void onCharacteristicWrite(BluetoothGatt gatt,
-                BluetoothGattCharacteristic characteristic, int status) {
-            super.onCharacteristicWrite(gatt, characteristic, status);
-
-            caLeGattCharacteristicWriteCallback(gatt, characteristic.getValue(), status);
-        }
-
-        @Override
-        public void onCharacteristicChanged(BluetoothGatt gatt,
-                BluetoothGattCharacteristic characteristic) {
-            super.onCharacteristicChanged(gatt, characteristic);
-
-            caLeGattCharacteristicChangedCallback(gatt, characteristic.getValue());
-        }
-
-        @Override
-        public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor,
-                int status) {
-            super.onDescriptorRead(gatt, descriptor, status);
-        }
-
-        @Override
-        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor,
-                int status) {
-            super.onDescriptorWrite(gatt, descriptor, status);
-
-            caLeGattDescriptorWriteCallback(gatt, status);
-        }
-
-        @Override
-        public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
-            super.onReliableWriteCompleted(gatt, status);
-        }
-
-        @Override
-        public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
-            super.onReadRemoteRssi(gatt, rssi, status);
-        }
-    };
-
-    private static final BroadcastReceiver mReceiver = new BroadcastReceiver() {
-
-        @Override
-        public void onReceive(Context context, Intent intent) {
-
-            String action = intent.getAction();
-
-            if (action != null && action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
-
-                int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
-                                               BluetoothAdapter.ERROR);
-
-                if (state == BluetoothAdapter.STATE_ON || state == BluetoothAdapter.STATE_OFF)
-                {
-                    caLeStateChangedCallback(state);
-                }
-            }
-
-            if (action != null && action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
-
-                int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE,
-                                                   BluetoothDevice.ERROR);
-
-                if (bondState == BluetoothDevice.BOND_NONE) {
-                    if ((intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE,
-                            BluetoothDevice.ERROR) == BluetoothDevice.BOND_BONDED)) {
-                            BluetoothDevice device = intent
-                                .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
-
-                        caLeBondStateChangedCallback(device.getAddress());
-                    }
-                }
-            }
-        }
-    };
-}
-
diff --git a/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/java/org/iotivity/ca/CaLeServerInterface.java b/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/java/org/iotivity/ca/CaLeServerInterface.java
deleted file mode 100755 (executable)
index b2ed163..0000000
+++ /dev/null
@@ -1,155 +0,0 @@
-/******************************************************************
- *
- * Copyright 2014 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.ca;
-
-import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothGattCharacteristic;
-import android.bluetooth.BluetoothGattDescriptor;
-import android.bluetooth.BluetoothGattServerCallback;
-import android.bluetooth.BluetoothGattService;
-import android.bluetooth.le.AdvertiseCallback;
-import android.bluetooth.le.AdvertiseSettings;
-
-public class CaLeServerInterface {
-
-    private CaLeServerInterface() {
-
-        caLeRegisterGattServerCallback(mGattServerCallback);
-        caLeRegisterBluetoothLeAdvertiseCallback(mAdvertiseCallback);
-    }
-
-    public static void getLeGattServerCallback() {
-        caLeRegisterGattServerCallback(mGattServerCallback);
-    }
-
-    public static void getBluetoothLeAdvertiseCallback() {
-        caLeRegisterBluetoothLeAdvertiseCallback(mAdvertiseCallback);
-    }
-
-    private native static void caLeRegisterGattServerCallback(BluetoothGattServerCallback callback);
-
-    private native static void caLeRegisterBluetoothLeAdvertiseCallback(AdvertiseCallback callback);
-
-    // BluetoothGattServerCallback
-    private native static void caLeGattServerConnectionStateChangeCallback(
-            BluetoothDevice device, int status, int newState);
-
-    private native static void caLeGattServerServiceAddedCallback(int status,
-                                                                  BluetoothGattService service);
-
-    private native static void caLeGattServerCharacteristicReadRequestCallback(
-            BluetoothDevice device, byte[] data);
-
-    private native static void caLeGattServerCharacteristicWriteRequestCallback(
-            BluetoothDevice device, byte[] data);
-
-    private native static void caLeGattServerNotificationSentCallback(BluetoothDevice device,
-                                                                     int status);
-
-    // AdvertiseCallback
-    private native static void caLeAdvertiseStartSuccessCallback(
-            AdvertiseSettings settingsInEffect);
-
-    private native static void caLeAdvertiseStartFailureCallback(int errorCode);
-
-    private static final BluetoothGattServerCallback mGattServerCallback =
-                         new BluetoothGattServerCallback() {
-
-        @Override
-        public void onConnectionStateChange(BluetoothDevice device, int status,
-                int newState) {
-            super.onConnectionStateChange(device, status, newState);
-
-            caLeGattServerConnectionStateChangeCallback(device, status, newState);
-        }
-
-        @Override
-        public void onServiceAdded(int status, BluetoothGattService service) {
-            super.onServiceAdded(status, service);
-
-            caLeGattServerServiceAddedCallback(status, service);
-        }
-
-        @Override
-        public void onCharacteristicReadRequest(
-                BluetoothDevice device, int requestId, int offset,
-                BluetoothGattCharacteristic characteristic) {
-            super.onCharacteristicReadRequest(device, requestId, offset, characteristic);
-
-            caLeGattServerCharacteristicReadRequestCallback(device, characteristic.getValue());
-        }
-
-        @Override
-        public void onCharacteristicWriteRequest(
-                BluetoothDevice device, int requestId, BluetoothGattCharacteristic characteristic,
-                boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
-            super.onCharacteristicWriteRequest(device, requestId, characteristic,
-                    preparedWrite, responseNeeded, offset, value);
-
-            caLeGattServerCharacteristicWriteRequestCallback(device, value);
-        }
-
-        @Override
-        public void onDescriptorReadRequest(
-                BluetoothDevice device,
-                int requestId, int offset, BluetoothGattDescriptor descriptor) {
-            super.onDescriptorReadRequest(device, requestId, offset, descriptor);
-        }
-
-        @Override
-        public void onDescriptorWriteRequest(
-                BluetoothDevice device, int requestId, BluetoothGattDescriptor descriptor,
-                boolean preparedWrite, boolean responseNeeded, int offset,
-                byte[] value) {
-            super.onDescriptorWriteRequest(device, requestId, descriptor, preparedWrite,
-                                           responseNeeded, offset, value);
-        }
-
-        @Override
-        public void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute) {
-            super.onExecuteWrite(device, requestId, execute);
-        }
-
-        @Override
-        public void onNotificationSent(BluetoothDevice device, int status) {
-            super.onNotificationSent(device, status);
-
-            caLeGattServerNotificationSentCallback(device, status);
-        }
-    };
-
-    private static final AdvertiseCallback mAdvertiseCallback = new AdvertiseCallback() {
-
-        @Override
-        public void onStartSuccess(AdvertiseSettings settingsInEffect) {
-            super.onStartSuccess(settingsInEffect);
-
-            caLeAdvertiseStartSuccessCallback(settingsInEffect);
-        }
-
-        @Override
-        public void onStartFailure(int errorCode) {
-            super.onStartFailure(errorCode);
-
-            caLeAdvertiseStartFailureCallback(errorCode);
-        }
-    };
-}
diff --git a/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/res/drawable-hdpi/ic_launcher.png b/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/res/drawable-hdpi/ic_launcher.png
deleted file mode 100755 (executable)
index 96a442e..0000000
Binary files a/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/res/drawable-hdpi/ic_launcher.png and /dev/null differ
diff --git a/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/res/drawable-mdpi/ic_launcher.png b/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/res/drawable-mdpi/ic_launcher.png
deleted file mode 100755 (executable)
index 359047d..0000000
Binary files a/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/res/drawable-mdpi/ic_launcher.png and /dev/null differ
diff --git a/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/res/drawable-xhdpi/ic_launcher.png b/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/res/drawable-xhdpi/ic_launcher.png
deleted file mode 100755 (executable)
index 71c6d76..0000000
Binary files a/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/res/drawable-xhdpi/ic_launcher.png and /dev/null differ
diff --git a/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/res/values-v11/styles.xml b/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/res/values-v11/styles.xml
deleted file mode 100755 (executable)
index 3c02242..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-<resources>
-
-    <!--
-        Base application theme for API 11+. This theme completely replaces
-        AppBaseTheme from res/values/styles.xml on API 11+ devices.
-    -->
-    <style name="AppBaseTheme" parent="android:Theme.Holo.Light">
-        <!-- API 11 theme customizations can go here. -->
-    </style>
-
-</resources>
diff --git a/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/res/values-v14/styles.xml b/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/res/values-v14/styles.xml
deleted file mode 100755 (executable)
index a91fd03..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-<resources>
-
-    <!--
-        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.
-    -->
-    <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
-        <!-- API 14 theme customizations can go here. -->
-    </style>
-
-</resources>
diff --git a/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/res/values/strings.xml b/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/res/values/strings.xml
deleted file mode 100755 (executable)
index 0e63d00..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-<resources>
-
-    <string name="app_name">CAInterface</string>
-
-</resources>
diff --git a/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/res/values/styles.xml b/resource/csdk/connectivity/samples/android/casample/cAInterface/src/main/res/values/styles.xml
deleted file mode 100755 (executable)
index 6ce89c7..0000000
+++ /dev/null
@@ -1,20 +0,0 @@
-<resources>
-
-    <!--
-        Base application theme, dependent on API level. This theme is replaced
-        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-    -->
-    <style name="AppBaseTheme" parent="android:Theme.Light">
-        <!--
-            Theme customizations available in newer API levels can go in
-            res/values-vXX/styles.xml, while customizations related to
-            backward-compatibility can go here.
-        -->
-    </style>
-
-    <!-- Application theme. -->
-    <style name="AppTheme" parent="AppBaseTheme">
-        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
-    </style>
-
-</resources>
diff --git a/resource/csdk/connectivity/samples/android/casample/casample.iml b/resource/csdk/connectivity/samples/android/casample/casample.iml
deleted file mode 100755 (executable)
index ed92464..0000000
+++ /dev/null
@@ -1,29 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
-  <component name="FacetManager">
-    <facet type="java-gradle" name="Java-Gradle">
-      <configuration>
-        <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/../MainActivity/build" />
-      </configuration>
-    </facet>
-    <facet type="android-gradle" name="Android-Gradle">
-      <configuration>
-        <option name="GRADLE_PROJECT_PATH" value=":" />
-      </configuration>
-    </facet>
-    <facet type="android" name="Android">
-      <configuration>
-        <option name="ALLOW_USER_CONFIGURATION" value="false" />
-      </configuration>
-    </facet>
-  </component>
-  <component name="NewModuleRootManager" inherit-compiler-output="true">
-    <exclude-output />
-    <content url="file://$MODULE_DIR$">
-      <excludeFolder url="file://$MODULE_DIR$/.gradle" />
-    </content>
-    <orderEntry type="inheritedJdk" />
-    <orderEntry type="sourceFolder" forTests="false" />
-  </component>
-</module>
-
diff --git a/resource/csdk/connectivity/samples/android/casample/gradle.properties b/resource/csdk/connectivity/samples/android/casample/gradle.properties
deleted file mode 100755 (executable)
index b0f079c..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
-#
-# //******************************************************************
-# //
-# // Copyright 2015 Intel Corporation.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-
-# Project-wide Gradle settings.
-
-# IDE (e.g. Android Studio) users:
-# Gradle settings configured through the IDE *will override*
-# any settings specified in this file.
-
-# For more details on how to configure your build environment visit
-# http://www.gradle.org/docs/current/userguide/build_environment.html
-
-# Specifies the JVM arguments used for the daemon process.
-# The setting is particularly useful for tweaking memory settings.
-# Default value: -Xmx10248m -XX:MaxPermSize=256m
-# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
-
-# When configured, Gradle will run in incubating parallel mode.
-# This option should only be used with decoupled projects. More details, visit
-# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
-# org.gradle.parallel=true
-
diff --git a/resource/csdk/connectivity/samples/android/casample/gradle/wrapper/gradle-wrapper.properties b/resource/csdk/connectivity/samples/android/casample/gradle/wrapper/gradle-wrapper.properties
deleted file mode 100755 (executable)
index 0c71e76..0000000
+++ /dev/null
@@ -1,6 +0,0 @@
-#Wed Apr 10 15:27:10 PDT 2013
-distributionBase=GRADLE_USER_HOME
-distributionPath=wrapper/dists
-zipStoreBase=GRADLE_USER_HOME
-zipStorePath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip
diff --git a/resource/csdk/connectivity/samples/android/casample/sampleService/.gitignore b/resource/csdk/connectivity/samples/android/casample/sampleService/.gitignore
deleted file mode 100644 (file)
index 84c048a..0000000
+++ /dev/null
@@ -1 +0,0 @@
-/build/
diff --git a/resource/csdk/connectivity/samples/android/casample/sampleService/build.gradle b/resource/csdk/connectivity/samples/android/casample/sampleService/build.gradle
deleted file mode 100755 (executable)
index 1e31192..0000000
+++ /dev/null
@@ -1,70 +0,0 @@
-apply plugin: 'com.android.application'
-
-android {
-    compileSdkVersion 21
-    buildToolsVersion "20.0.0"
-
-    defaultConfig {
-        applicationId "org.iotivity.ca.sample_service"
-        minSdkVersion 21
-        targetSdkVersion 21
-
-        ndk {
-            moduleName "RMInterface"
-        }
-    }
-
-    buildTypes {
-        release {
-            minifyEnabled false
-            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
-        }
-    }
-
-    lintOptions {
-       abortOnError false
-    }
-
-    sourceSets {
-        main {
-            manifest.srcFile 'src/main/AndroidManifest.xml'
-            jniLibs.srcDir 'libs'
-            jni.srcDirs = [] //disable automatic ndk-build call
-        }
-    }
-}
-
-dependencies {
-    compile fileTree(dir: 'libs', include: ['*.jar'])
-    compile project(':cAInterface')
-}
-
-task copyNativeLibs(type: Copy, dependsOn: 'buildNative') {
-    dependsOn 'buildNative'
-    from(new File('src/main/libs')) { include '**/*.so' }
-    into new File(buildDir, 'native-libs')
-}
-
-tasks.withType(JavaCompile) { compileTask -> compileTask.dependsOn copyNativeLibs }
-
-clean.dependsOn 'cleanCopyNativeLibs'
-
-tasks.withType(com.android.build.gradle.tasks.PackageApplication) { pkgTask ->
-    pkgTask.jniFolders = new HashSet<File>()
-    pkgTask.jniFolders.add(new File(buildDir, 'native-libs'))
-}
-
-task buildNative(type: Exec) {
-    if (System.env.ANDROID_NDK_HOME != null) {
-        //for windows use 'ndk-build.cmd'
-        //def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build.cmd')
-        def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build')
-        commandLine ndkBuild, "-C", file("src/main"), "-B", "-j", Runtime.runtime.availableProcessors(),
-                              "APP_ABI=$TARGET_ARCH", "APP_OPTIM=$RELEASE"
-    } else {
-        println '##################'
-        println 'Skipping NDK build'
-        println 'Reason: ANDROID_NDK_HOME not set.'
-        println '##################'
-    }
-}
diff --git a/resource/csdk/connectivity/samples/android/casample/sampleService/sampleService.iml b/resource/csdk/connectivity/samples/android/casample/sampleService/sampleService.iml
deleted file mode 100755 (executable)
index 145e474..0000000
+++ /dev/null
@@ -1,91 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="casample" 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=":sampleService" />
-      </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="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
-        <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugAndroidTestSources" />
-        <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" 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/generated/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/generated/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" />
-    </content>
-    <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
-    <orderEntry type="sourceFolder" forTests="false" />
-    <orderEntry type="library" exported="" name="support-annotations-21.0.3" level="project" />
-    <orderEntry type="module" module-name="cAInterface" exported="" />
-  </component>
-</module>
-
diff --git a/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/.gitignore b/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/.gitignore
deleted file mode 100644 (file)
index 89a3c7d..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-/libs/
-/obj/
-/assets/
diff --git a/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/AndroidManifest.xml b/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/AndroidManifest.xml
deleted file mode 100755 (executable)
index 40963c5..0000000
+++ /dev/null
@@ -1,37 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="org.iotivity.ca.sample_service"
-    android:versionCode="1"
-    android:versionName="1.0" >
-
-    <uses-sdk
-        android:minSdkVersion="21"
-        android:targetSdkVersion="21" />
-
-    <application
-        android:allowBackup="true"
-        android:label="@string/app_name"
-        android:theme="@style/AppTheme" >
-        <activity
-            android:name="org.iotivity.ca.service.MainActivity"
-            android:label="@string/app_name"
-            android:windowSoftInputMode="stateHidden" >
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-
-                <category android:name="android.intent.category.LAUNCHER" />
-            </intent-filter>
-        </activity>
-    </application>
-
-    <uses-permission android:name="android.permission.BLUETOOTH" />
-    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
-    <uses-permission android:name="android.permission.INTERNET" />
-    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
-    <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
-    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
-    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
-    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
-    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
-    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
-</manifest>
diff --git a/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/java/org/iotivity/ca/service/DLog.java b/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/java/org/iotivity/ca/service/DLog.java
deleted file mode 100755 (executable)
index 9fe8422..0000000
+++ /dev/null
@@ -1,90 +0,0 @@
-
-package org.iotivity.ca.service;
-
-import android.os.Handler;
-import android.widget.TextView;
-
-public final class DLog {
-
-    private final static String MAIN_TAG = "Sample_Service : DLog";
-
-    private static TextView mLogView = null;
-
-    private static Handler mHandler = null;
-
-    public static void setTextView(Handler handler, TextView logView) {
-        mHandler = handler;
-        mLogView = logView;
-    }
-
-    private static void addLogText(final String msg) {
-
-        mHandler.post(new Runnable() {
-
-            @Override
-            public void run() {
-
-                if (mLogView == null)
-                    return;
-
-                StringBuilder builder = new StringBuilder(mLogView.getText());
-                // add front
-                builder.append(msg + "\n");
-
-                mLogView.setText(builder.toString());
-            }
-
-        });
-
-    }
-
-    public static final void v(String className, String msg) {
-        android.util.Log.v(MAIN_TAG, className + "." + msg);
-
-        if (mLogView != null) {
-            addLogText(msg);
-        }
-    }
-
-    public static final void d(String className, String msg) {
-        android.util.Log.d(MAIN_TAG, className + "." + msg);
-
-        if (mLogView != null) {
-            addLogText(msg);
-        }
-    }
-
-    public static final void i(String className, String msg) {
-        android.util.Log.i(MAIN_TAG, className + "." + msg);
-
-        if (mLogView != null) {
-            addLogText(msg);
-        }
-    }
-
-    public static final void w(String className, String msg) {
-        android.util.Log.w(MAIN_TAG, className + "." + msg);
-
-        if (mLogView != null) {
-            addLogText(msg);
-        }
-    }
-
-    public static final void w(String className, String msg, Exception ex) {
-        android.util.Log.w(MAIN_TAG, className + "." + msg + ":" + ex.getMessage());
-
-        if (mLogView != null) {
-            addLogText(msg);
-        }
-    }
-
-    public static final void w(String className, String msg, Error e) {
-        android.util.Log.w(MAIN_TAG, className + "." + msg + ":" + e.getMessage());
-
-        if (mLogView != null) {
-            addLogText(msg);
-        }
-    }
-
-}
-
diff --git a/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/java/org/iotivity/ca/service/FileChooser.java b/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/java/org/iotivity/ca/service/FileChooser.java
deleted file mode 100644 (file)
index d2e50d8..0000000
+++ /dev/null
@@ -1,135 +0,0 @@
-package org.iotivity.ca.service;
-
-import android.app.Activity;
-import android.app.Dialog;
-import android.os.Environment;
-import android.view.View;
-import android.view.ViewGroup;
-import android.view.WindowManager.LayoutParams;
-import android.widget.AdapterView;
-import android.widget.ArrayAdapter;
-import android.widget.ListView;
-import android.widget.TextView;
-import java.io.File;
-import java.io.FileFilter;
-import java.util.Arrays;
-
-public class FileChooser {
-    private static final String PARENT_DIR = "..";
-
-    private final Activity activity;
-    private ListView list;
-    private Dialog dialog;
-    private File currentPath;
-
-    // filter on file extension
-    private String extension = null;
-    public void setExtension(String extension) {
-        this.extension = (extension == null) ? null :
-                extension.toLowerCase();
-    }
-
-    // file selection event handling
-    public interface FileSelectedListener {
-        void fileSelected(File file);
-    }
-    public FileChooser setFileListener(FileSelectedListener fileListener) {
-        this.fileListener = fileListener;
-        return this;
-    }
-    private FileSelectedListener fileListener;
-
-    public FileChooser(Activity activity) {
-        this.activity = activity;
-        dialog = new Dialog(activity);
-        list = new ListView(activity);
-        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
-            @Override public void onItemClick(AdapterView<?> parent, View view, int which, long id) {
-                String fileChosen = (String) list.getItemAtPosition(which);
-                File chosenFile = getChosenFile(fileChosen);
-                if (chosenFile.isDirectory()) {
-                    refresh(chosenFile);
-                } else {
-                    if (fileListener != null) {
-                        fileListener.fileSelected(chosenFile);
-                    }
-                    dialog.dismiss();
-                }
-            }
-        });
-        dialog.setContentView(list);
-        dialog.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
-        refresh(Environment.getExternalStorageDirectory());
-    }
-
-    public void showDialog() {
-        dialog.show();
-    }
-
-
-    /**
-     * Sort, filter and display the files for the given path.
-     */
-    private void refresh(File path) {
-        this.currentPath = path;
-        if (path.exists()) {
-            File[] dirs = path.listFiles(new FileFilter() {
-                @Override public boolean accept(File file) {
-                    return (file.isDirectory() && file.canRead());
-                }
-            });
-            File[] files = path.listFiles(new FileFilter() {
-                @Override public boolean accept(File file) {
-                    if (!file.isDirectory()) {
-                        if (!file.canRead()) {
-                            return false;
-                        } else if (extension == null) {
-                            return true;
-                        } else {
-                            return file.getName().toLowerCase().endsWith(extension);
-                        }
-                    } else {
-                        return false;
-                    }
-                }
-            });
-
-            // convert to an array
-            int i = 0;
-            String[] fileList;
-            if (path.getParentFile() == null) {
-                fileList = new String[dirs.length + files.length];
-            } else {
-                fileList = new String[dirs.length + files.length + 1];
-                fileList[i++] = PARENT_DIR;
-            }
-            Arrays.sort(dirs);
-            Arrays.sort(files);
-            for (File dir : dirs) { fileList[i++] = dir.getName(); }
-            for (File file : files ) { fileList[i++] = file.getName(); }
-
-            // refresh the user interface
-            dialog.setTitle(currentPath.getPath());
-            list.setAdapter(new ArrayAdapter(activity,
-                   android.R.layout.simple_list_item_1, fileList) {
-                       @Override public View getView(int pos, View view, ViewGroup parent) {
-                           view = super.getView(pos, view, parent);
-                           ((TextView) view).setSingleLine(true);
-                           return view;
-                       }
-                   });
-        }
-    }
-
-
-    /**
-     * Convert a relative filename into an actual File object.
-     */
-    private File getChosenFile(String fileChosen) {
-        if (fileChosen.equals(PARENT_DIR)) {
-            return currentPath.getParentFile();
-        } else {
-            return new File(currentPath, fileChosen);
-        }
-    }
-}
diff --git a/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/java/org/iotivity/ca/service/MainActivity.java b/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/java/org/iotivity/ca/service/MainActivity.java
deleted file mode 100755 (executable)
index cdc82bd..0000000
+++ /dev/null
@@ -1,755 +0,0 @@
-package org.iotivity.ca.service;
-
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.content.DialogInterface;
-import android.os.Bundle;
-import android.os.Handler;
-import android.util.Log;
-import android.view.Menu;
-import android.view.MenuItem;
-import android.view.View;
-import android.view.View.OnClickListener;
-import android.widget.Button;
-import android.widget.EditText;
-import android.widget.RelativeLayout;
-import android.widget.TextView;
-import android.widget.Toast;
-import java.io.File;
-
-import org.iotivity.ca.sample_service.R;
-import org.iotivity.ca.service.FileChooser;
-import org.iotivity.ca.service.FileChooser.FileSelectedListener;
-
-public class MainActivity extends Activity {
-
-    static RMInterface RM = new RMInterface();
-
-    private final static String TAG = "Sample_Service : MainActivity";
-
-    private final CharSequence[] mNetworkCheckBoxItems = { Network.IP.name(),
-            Network.LE.name(), Network.EDR.name()};
-
-    private final CharSequence[] mDTLSCheckBoxItems = { DTLS.UNSECURED.name(),
-            DTLS.SECURED.name() };
-
-    private final CharSequence[] mMsgTyleCheckBoxItems = { MsgType.CON.name(),
-            MsgType.NON.name(), MsgType.ACK.name(), MsgType.RESET.name() };
-
-    private final CharSequence[] mResponseResultCheckBoxItems = {
-            ResponseResult.CA_CREATED.name(), ResponseResult.CA_DELETED.name(),
-            ResponseResult.CA_VALID.name(), ResponseResult.CA_CHANGED.name(),
-            ResponseResult.CA_CONTENT.name(), ResponseResult.CA_EMPTY.name(),
-            ResponseResult.CA_BAD_REQ.name(), ResponseResult.CA_BAD_OPT.name(),
-            ResponseResult.CA_NOT_FOUND.name(), ResponseResult.CA_INTERNAL_SERVER_ERROR.name(),
-            ResponseResult.CA_RETRANSMIT_TIMEOUT.name() };
-
-    private enum Mode {
-        SERVER, CLIENT, BOTH, UNKNOWN
-    };
-
-    private enum Network {
-        IP, LE, EDR
-    };
-
-    private enum DTLS {
-        UNSECURED, SECURED
-    };
-
-    private enum MsgType {
-        CON, NON, ACK, RESET
-    };
-
-    private enum ResponseResult {
-        CA_CREATED, CA_DELETED, CA_VALID, CA_CHANGED, CA_CONTENT, CA_EMPTY,
-        CA_BAD_REQ, CA_BAD_OPT, CA_NOT_FOUND, CA_INTERNAL_SERVER_ERROR, CA_RETRANSMIT_TIMEOUT
-    }
-
-    private boolean mCheckedItems[] = {
-            false, false, false, false
-    };
-
-    private int mSelectedItems[] = { 0, 0, 0 };
-
-    private int mUnSelectedItems[] = { 0, 0, 0 };
-
-    private Mode mCurrentMode = Mode.UNKNOWN;
-
-    private RelativeLayout mSendNotificationLayout = null;
-
-    private RelativeLayout mSendRequestLayout = null;
-
-    private RelativeLayout mSendRequestToAllLayout = null;
-
-    private RelativeLayout mSendRequestSettingLayout = null;
-
-    private RelativeLayout mSendRequestToAllSettingLayout = null;
-
-    private RelativeLayout mSendResponseNotiSettingLayout = null;
-
-    private RelativeLayout mReceiveLayout = null;
-
-    private RelativeLayout mRequestTitleLayout = null;
-
-    private RelativeLayout mRequestToAllTitleLayout = null;
-
-    private RelativeLayout mResponseNotificationTitleLayout = null;
-
-    private RelativeLayout mHandleTitleLayout = null;
-
-    private TextView mMode_tv = null;
-
-    private TextView mNetwork_tv = null;
-
-    private EditText mNotification_ed = null;
-
-    private EditText mReqData_ed = null;
-
-    private EditText mReqToAllData_ed = null;
-
-    private Button mNotify_btn = null;
-
-    private Button mReqeust_btn = null;
-
-    private Button mReqeust_setting_btn = null;
-
-    private Button mReqeustToAll_btn = null;
-
-    private Button mReqeustToAll_setting_btn = null;
-
-    private Button mResponse_Notify_setting_btn = null;
-
-    private Button mResponse_btn = null;
-
-    private Button mGetNetworkInfo_btn = null;
-
-    private Button mRecv_btn = null;
-
-    private Button mBig_btn = null;
-
-    private Handler mLogHandler = null;
-
-    /**
-     * Defined ConnectivityType in cacommon.c
-     *
-     * CA_IP = (1 << 0) CA_LE = (1 << 2) CA_EDR = (1 << 3)
-     */
-    private int CA_IP = (1 << 0);
-    private int CA_LE = (1 << 1);
-    private int CA_EDR = (1 << 2);
-    private int isSecured = 0;
-    private int msgType = 1;
-    private int responseValue = 0;
-    private int selectedNetworkType = -1;
-    private int selectedMsgType = 1;
-    private int selectedMsgSecured = 0;
-    private int selectedResponseValue = 0;
-    int selectedNetwork = -1;
-    int interestedNetwork = 0;
-    int uninterestedNetwork = 0;
-    private boolean isSendResponseSetting = false;
-    private boolean isSendRequestToAllSetting = false;
-    private boolean isBigData = false;
-
-    @Override
-    protected void onCreate(Bundle savedInstanceState) {
-        super.onCreate(savedInstanceState);
-        setContentView(R.layout.activity_main);
-
-        RM.setResponseListener(this);
-
-        mLogHandler = new Handler();
-        TextView logView = (TextView) findViewById(R.id.tv_result);
-        DLog.setTextView(mLogHandler, logView);
-
-        // Initialize UI
-        // common
-        mReceiveLayout = (RelativeLayout) findViewById(R.id.layout_receive);
-
-        // client
-        mSendRequestLayout = (RelativeLayout) findViewById(R.id.layout_request);
-        mSendRequestToAllLayout = (RelativeLayout) findViewById(R.id.layout_request_to_all);
-        mSendRequestSettingLayout = (RelativeLayout)
-                findViewById(R.id.layout_request_setting_for_client);
-        mSendRequestToAllSettingLayout = (RelativeLayout)
-                findViewById(R.id.layout_request_to_all_setting_for_client);
-        mRequestTitleLayout = (RelativeLayout) findViewById(R.id.layout_request_title);
-        mRequestToAllTitleLayout = (RelativeLayout) findViewById(R.id.layout_request_to_all_title);
-        mHandleTitleLayout = (RelativeLayout) findViewById(R.id.layout_handle_title);
-
-        // server
-        mSendNotificationLayout = (RelativeLayout) findViewById(R.id.layout_notify);
-        mSendResponseNotiSettingLayout = (RelativeLayout)
-                findViewById(R.id.layout_request_setting_for_server);
-        mResponseNotificationTitleLayout = (RelativeLayout)
-                findViewById(R.id.layout_Response_Noti_title);
-
-        mMode_tv = (TextView) findViewById(R.id.tv_mode);
-        mNetwork_tv = (TextView) findViewById(R.id.tv_network);
-
-        mNotification_ed = (EditText) findViewById(R.id.et_notification);
-        mReqData_ed = (EditText) findViewById(R.id.et_req_data);
-        mReqToAllData_ed = (EditText) findViewById(R.id.et_req_to_all_data);
-
-        mResponse_btn = (Button) findViewById(R.id.btn_sendresponse);
-        mNotify_btn = (Button) findViewById(R.id.btn_notify);
-        mReqeust_btn = (Button) findViewById(R.id.btn_Request);
-        mReqeust_setting_btn = (Button) findViewById(R.id.btn_Request_setting_for_client);
-        mReqeustToAll_btn = (Button) findViewById(R.id.btn_request_to_all);
-        mReqeustToAll_setting_btn = (Button)
-                findViewById(R.id.btn_request_to_all_setting_for_client);
-        mResponse_Notify_setting_btn = (Button) findViewById(R.id.btn_Request_setting_for_server);
-        mGetNetworkInfo_btn = (Button) findViewById(R.id.btn_get_network_info);
-        mRecv_btn = (Button) findViewById(R.id.btn_receive);
-        mBig_btn = (Button) findViewById(R.id.btn_big_data);
-        mBig_btn.setOnClickListener(mSelectLargeDataButtonHandler);
-
-        mResponse_btn.setOnClickListener(mSendResponseHandler);
-        mNotify_btn.setOnClickListener(mNotifyHandler);
-        mReqeust_btn.setOnClickListener(mSendRequestHandler);
-        mReqeust_setting_btn.setOnClickListener(mSendRequestSettingHandler);
-        mReqeustToAll_btn.setOnClickListener(mSendRequestToAllHandler);
-        mReqeustToAll_setting_btn.setOnClickListener(mSendRequestToAllSettingHandler);
-        mResponse_Notify_setting_btn
-                .setOnClickListener(mSendResponseNotiSettingHandler);
-        mRecv_btn.setOnClickListener(mResponseHandler);
-        mGetNetworkInfo_btn.setOnClickListener(mGetNetworkInfoHandler);
-
-        showSelectModeView();
-
-        // Initialize Connectivity Abstraction
-        RM.RMInitialize(getApplicationContext());
-
-        // set handler
-        RM.RMRegisterHandler();
-    }
-
-    private void showSelectModeView() {
-
-        mSendNotificationLayout.setVisibility(View.INVISIBLE);
-        mSendRequestLayout.setVisibility(View.INVISIBLE);
-        mSendRequestToAllLayout.setVisibility(View.INVISIBLE);
-        mSendRequestSettingLayout.setVisibility(View.INVISIBLE);
-        mSendRequestToAllSettingLayout.setVisibility(View.INVISIBLE);
-        mReceiveLayout.setVisibility(View.INVISIBLE);
-        mRequestTitleLayout.setVisibility(View.INVISIBLE);
-        mRequestToAllTitleLayout.setVisibility(View.INVISIBLE);
-        mHandleTitleLayout.setVisibility(View.INVISIBLE);
-        mResponseNotificationTitleLayout.setVisibility(View.INVISIBLE);
-        mSendResponseNotiSettingLayout.setVisibility(View.INVISIBLE);
-
-        mMode_tv.setText("Select Mode (Server or Client)");
-        Log.i(TAG, "Select Mode (Server or Client)");
-    }
-
-    private void showNetworkView() {
-
-        mNetwork_tv.setText("Select Network Type");
-        Log.i(TAG, "Select Network Type");
-    }
-
-    private void showModeView() {
-
-        if (mCurrentMode == Mode.SERVER) {
-
-            mSendNotificationLayout.setVisibility(View.VISIBLE);
-            mSendRequestLayout.setVisibility(View.INVISIBLE);
-            mSendRequestToAllLayout.setVisibility(View.VISIBLE);
-            mSendRequestSettingLayout.setVisibility(View.INVISIBLE);
-            mSendRequestToAllSettingLayout.setVisibility(View.VISIBLE);
-            mReceiveLayout.setVisibility(View.VISIBLE);
-
-            mRequestTitleLayout.setVisibility(View.INVISIBLE);
-            mRequestToAllTitleLayout.setVisibility(View.VISIBLE);
-            mHandleTitleLayout.setVisibility(View.VISIBLE);
-
-            mResponseNotificationTitleLayout.setVisibility(View.VISIBLE);
-            mSendResponseNotiSettingLayout.setVisibility(View.VISIBLE);
-
-            mNetwork_tv.setText("");
-
-        } else if (mCurrentMode == Mode.CLIENT) {
-
-            mSendNotificationLayout.setVisibility(View.INVISIBLE);
-            mSendRequestLayout.setVisibility(View.VISIBLE);
-            mSendRequestToAllLayout.setVisibility(View.VISIBLE);
-            mSendRequestSettingLayout.setVisibility(View.VISIBLE);
-            mSendRequestToAllSettingLayout.setVisibility(View.VISIBLE);
-            mReceiveLayout.setVisibility(View.VISIBLE);
-
-            mRequestTitleLayout.setVisibility(View.VISIBLE);
-            mRequestToAllTitleLayout.setVisibility(View.VISIBLE);
-            mHandleTitleLayout.setVisibility(View.VISIBLE);
-
-            mResponseNotificationTitleLayout.setVisibility(View.INVISIBLE);
-            mSendResponseNotiSettingLayout.setVisibility(View.INVISIBLE);
-
-            mNetwork_tv.setText("");
-        }
-    }
-
-    @Override
-    protected void onDestroy() {
-        super.onDestroy();
-
-        // Terminate Connectivity Abstraction
-        RM.RMTerminate();
-        android.os.Process.killProcess(android.os.Process.myPid());
-    }
-
-    @Override
-    public boolean onCreateOptionsMenu(Menu menu) {
-
-        menu.add(0, 1, Menu.NONE, "Start Server");
-        menu.add(0, 2, Menu.NONE, "Start Client");
-        menu.add(0, 3, Menu.NONE, "Select Network");
-
-        return true;
-    }
-
-    @Override
-    public boolean onOptionsItemSelected(MenuItem item) {
-
-        switch (item.getItemId()) {
-
-        case 1:
-
-            RM.RMStartListeningServer();
-
-            if (interestedNetwork == 0) {
-                mCurrentMode = Mode.SERVER;
-                mMode_tv.setText("MODE: " + mCurrentMode.toString());
-                Log.i(TAG, "MODE: " + mCurrentMode.toString());
-                showNetworkView();
-
-            } else {
-                mCurrentMode = Mode.SERVER;
-                mMode_tv.setText("MODE: " + mCurrentMode.toString());
-                Log.i(TAG, "MODE: " + mCurrentMode.toString());
-                showModeView();
-            }
-
-            break;
-
-        case 2:
-
-            RM.RMStartDiscoveryServer();
-
-            if (interestedNetwork == 0) {
-                mCurrentMode = Mode.CLIENT;
-                mMode_tv.setText("MODE: " + mCurrentMode.toString());
-                Log.i(TAG, "MODE: " + mCurrentMode.toString());
-                showNetworkView();
-
-            } else {
-                mCurrentMode = Mode.CLIENT;
-                mMode_tv.setText("MODE: " + mCurrentMode.toString());
-                Log.i(TAG, "MODE: " + mCurrentMode.toString());
-                showModeView();
-            }
-
-            break;
-
-        case 3:
-
-            checkInterestedNetwork("Select Network");
-
-            break;
-        }
-
-        return super.onOptionsItemSelected(item);
-    }
-
-    private OnClickListener mSendResponseHandler = new OnClickListener() {
-
-        @Override
-        public void onClick(View v) {
-
-            DLog.v(TAG, "SendResponse click");
-            if ( selectedNetwork != -1) {
-                RM.RMSendResponse(selectedNetwork, isSecured, msgType, responseValue);
-            }
-            else {
-                DLog.v(TAG, "Please Select Network Type");
-            }
-        }
-    };
-
-    private OnClickListener mNotifyHandler = new OnClickListener() {
-
-        @Override
-        public void onClick(View v) {
-
-            DLog.v(TAG, "SendNotification click");
-            if ( selectedNetwork != -1) {
-                RM.RMSendNotification(mNotification_ed.getText().toString(),
-                    null, selectedNetwork, isSecured, msgType);
-            }
-            else {
-                DLog.v(TAG, "Please Select Network Type");
-            }
-        }
-    };
-
-    private OnClickListener mSendRequestHandler = new OnClickListener() {
-
-        @Override
-        public void onClick(View v) {
-
-            DLog.v(TAG, "SendRequest click");
-            if ( selectedNetwork != -1) {
-                RM.RMSendRequest(mReqData_ed.getText().toString(), null,
-                    selectedNetwork, isSecured, msgType, false);
-            }
-            else {
-                DLog.v(TAG, "Please Select Network Type");
-            }
-        }
-    };
-
-    private OnClickListener mSendRequestSettingHandler = new OnClickListener() {
-
-        @Override
-        public void onClick(View v) {
-            checkSendNetworkType("Select Send Network Type");
-        }
-    };
-
-    private OnClickListener mSendRequestToAllHandler = new OnClickListener() {
-
-        @Override
-        public void onClick(View v) {
-
-            DLog.v(TAG, "SendRequestToAll click");
-            if ( selectedNetwork != -1) {
-                RM.RMSendReqestToAll(mReqToAllData_ed.getText().toString(), selectedNetwork);
-            }
-            else {
-                DLog.v(TAG, "Please Select Network Type");
-            }
-        }
-    };
-
-    private OnClickListener mSendRequestToAllSettingHandler = new OnClickListener() {
-
-        @Override
-        public void onClick(View v) {
-            isSendRequestToAllSetting = true;
-            checkSendNetworkType("Select Send Network Type");
-        }
-    };
-
-    private OnClickListener mSendResponseNotiSettingHandler = new OnClickListener() {
-
-        @Override
-        public void onClick(View v) {
-            isSendResponseSetting = true;
-            checkSendNetworkType("Select Send Network Type");
-        }
-    };
-
-    private OnClickListener mGetNetworkInfoHandler = new OnClickListener() {
-        @Override
-        public void onClick(View v) {
-
-            RM.RMGetNetworkInfomation();
-        }
-    };
-
-    private OnClickListener mResponseHandler = new OnClickListener() {
-
-        @Override
-        public void onClick(View v) {
-
-            RM.RMHandleRequestResponse();
-        }
-    };
-
-    private OnClickListener mSelectLargeDataButtonHandler = new OnClickListener() {
-        @Override
-        public void onClick(View v) {
-
-            isBigData = true;
-            checkSendNetworkType("Select Send Network Type");
-        }
-    };
-
-    private void checkInterestedNetwork(String title) {
-
-        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
-        builder.setTitle(title)
-                .setMultiChoiceItems(mNetworkCheckBoxItems, mCheckedItems,
-                        new DialogInterface.OnMultiChoiceClickListener() {
-
-                            @Override
-                            public void onClick(DialogInterface dialog,
-                                    int which, boolean isChecked) {
-
-                                if (isChecked) {
-
-                                    mSelectedItems[which] = 1;
-                                    mUnSelectedItems[which] = 0;
-
-                                } else if (mSelectedItems[which] == 1) {
-
-                                    mSelectedItems[which] = 0;
-                                    mUnSelectedItems[which] = 1;
-                                }
-                            }
-                        })
-                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
-
-                    @Override
-                    public void onClick(DialogInterface dialog, int which) {
-
-                        interestedNetwork = 0;
-
-                        for (int i = 0; i < mSelectedItems.length; i++) {
-                            if (mSelectedItems[i] == 1) {
-                                interestedNetwork |= (1 << i);
-                            }
-                        }
-                        if(0 != interestedNetwork)
-                            RM.RMSelectNetwork(interestedNetwork);
-
-                        uninterestedNetwork = 0;
-
-                        for (int i = 0; i < mUnSelectedItems.length; i++) {
-                            if (mUnSelectedItems[i] == 1) {
-                                uninterestedNetwork |= (1 << i);
-                            }
-                        }
-                        if(0 != uninterestedNetwork)
-                            RM.RMUnSelectNetwork(uninterestedNetwork);
-
-                    }
-                }).show();
-    }
-
-    private void checkMsgSecured(String title) {
-
-        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
-
-        builder.setTitle(title)
-                .setSingleChoiceItems(mDTLSCheckBoxItems, selectedMsgSecured,
-                        new DialogInterface.OnClickListener() {
-
-                            @Override
-                            public void onClick(DialogInterface dialog,
-                                    int which) {
-                                selectedMsgSecured = which;
-                            }
-                        })
-                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
-
-                    @Override
-                    public void onClick(DialogInterface dialog, int which) {
-
-                        if (selectedMsgSecured == DTLS.SECURED.ordinal()) {
-                            isSecured = 1;
-                            DLog.v(TAG, "Send secured message");
-
-                        } else if (selectedMsgSecured == DTLS.UNSECURED.ordinal()) {
-                            isSecured = 0;
-                            DLog.v(TAG, "Send unsecured message");
-                        }
-                        checkMsgType("Select Msg Type");
-                    }
-
-                }).show();
-    }
-
-    private void checkMsgType(String title) {
-
-        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
-        builder.setTitle(title)
-                .setSingleChoiceItems(mMsgTyleCheckBoxItems, selectedMsgType,
-                        new DialogInterface.OnClickListener() {
-
-                            @Override
-                            public void onClick(DialogInterface dialog,
-                                    int which) {
-                                selectedMsgType = which;
-                            }
-                        })
-                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
-
-                    @Override
-                    public void onClick(DialogInterface dialog, int which) {
-
-                        if (selectedMsgType == MsgType.CON.ordinal()) {
-                            msgType = 0;
-                            DLog.v(TAG, "Message Type is CON");
-
-                        } else if (selectedMsgType == MsgType.NON.ordinal()) {
-                            msgType = 1;
-                            DLog.v(TAG, "Message Type is NON");
-                        } else if (selectedMsgType == MsgType.ACK.ordinal()) {
-                            msgType = 2;
-                            DLog.v(TAG, "Message Type is ACK");
-                        } else if (selectedMsgType == MsgType.RESET.ordinal()) {
-                            msgType = 3;
-                            DLog.v(TAG, "Message Type is RESET");
-                            }
-
-                        if (isSendResponseSetting == true && msgType != 3) {
-                            checkResponseResult("Select Value of Response Result");
-                            isSendResponseSetting = false;
-                        }
-                    }
-                }).show();
-    }
-
-    private void checkResponseResult(String title) {
-
-        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
-        builder.setTitle(title)
-                .setSingleChoiceItems(mResponseResultCheckBoxItems, selectedResponseValue,
-                        new DialogInterface.OnClickListener() {
-
-                            @Override
-                            public void onClick(DialogInterface dialog,
-                                    int which) {
-                                selectedResponseValue = which;
-                            }
-                        })
-                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
-
-                    @Override
-                    public void onClick(DialogInterface dialog, int which) {
-
-                        if (selectedResponseValue == ResponseResult.CA_CREATED.ordinal()) {
-                            responseValue = 201;
-                            DLog.v(TAG, "Response Value is CA_CREATED");
-                        } else if (selectedResponseValue == ResponseResult.CA_DELETED
-                                .ordinal()) {
-                            responseValue = 202;
-                            DLog.v(TAG, "Response Value is CA_DELETED");
-                        } else if (selectedResponseValue == ResponseResult.CA_VALID
-                                .ordinal()) {
-                            responseValue = 203;
-                            DLog.v(TAG, "Response Value is CA_VALID");
-                        } else if (selectedResponseValue == ResponseResult.CA_CHANGED
-                                .ordinal()) {
-                            responseValue = 204;
-                            DLog.v(TAG, "Response Value is CA_CHANGED");
-                        } else if (selectedResponseValue == ResponseResult.CA_CONTENT
-                                .ordinal()) {
-                            responseValue = 205;
-                            DLog.v(TAG, "Response Value is CA_CONTENT");
-                        } else if (selectedResponseValue == ResponseResult.CA_EMPTY
-                                .ordinal()) {
-                            responseValue = 0;
-                            DLog.v(TAG, "Response Value is CA_EMPTY");
-                        } else if (selectedResponseValue == ResponseResult.CA_BAD_REQ
-                                .ordinal()) {
-                            responseValue = 400;
-                            DLog.v(TAG, "Response Value is CA_BAD_REQ");
-                        } else if (selectedResponseValue == ResponseResult.CA_BAD_OPT
-                                .ordinal()) {
-                            responseValue = 402;
-                            DLog.v(TAG, "Response Value is CA_BAD_OPT");
-                        } else if (selectedResponseValue == ResponseResult.CA_NOT_FOUND
-                                .ordinal()) {
-                            responseValue = 404;
-                            DLog.v(TAG, "Response Value is CA_NOT_FOUND");
-                        } else if (selectedResponseValue ==
-                                ResponseResult.CA_INTERNAL_SERVER_ERROR
-                                .ordinal()) {
-                            responseValue = 500;
-                            DLog.v(TAG, "Response Value is CA_INTERNAL_SERVER_ERROR");
-                        } else if (selectedResponseValue == ResponseResult.CA_RETRANSMIT_TIMEOUT
-                                .ordinal()) {
-                            responseValue = 504;
-                            DLog.v(TAG, "Response Value is CA_RETRANSMIT_TIMEOUT");
-                        }
-                    }
-                }).show();
-    }
-
-    private void checkSendNetworkType(String title) {
-        selectedNetworkType = -1;
-        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
-
-        builder.setTitle(title)
-                .setSingleChoiceItems(mNetworkCheckBoxItems, -1,
-                        new DialogInterface.OnClickListener() {
-
-                            @Override
-                            public void onClick(DialogInterface dialog,
-                                    int which) {
-                                selectedNetworkType = which;
-                            }
-                        })
-                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
-
-                    @Override
-                    public void onClick(DialogInterface dialog, int which) {
-
-                        if (selectedNetworkType == Network.IP.ordinal()) {
-                            selectedNetwork = CA_IP;
-                            DLog.v(TAG, "Selected Network is IP");
-                        } else if (selectedNetworkType == Network.LE.ordinal()) {
-                            selectedNetwork = CA_LE;
-                            DLog.v(TAG, "Selected Network is LE");
-                        } else if (selectedNetworkType == Network.EDR.ordinal()) {
-                            selectedNetwork = CA_EDR;
-                            DLog.v(TAG, "Selected Network is EDR");
-                        } else {
-                            DLog.v(TAG, "Selected Network is NULL");
-                            selectedNetwork = -1;
-                        }
-
-                        if (isBigData)
-                        {
-                            new FileChooser(MainActivity.this).setFileListener(new FileSelectedListener() {
-                                public void fileSelected(final File file) {
-                                    if (selectedNetwork != -1) {
-
-                                        String path = file.getAbsolutePath();
-                                        Log.d(TAG, "File Path: " + path);
-
-                                        RM.RMSendRequest(mReqData_ed.getText().toString(), path,
-                                                         selectedNetwork, isSecured, msgType, true);
-                                    } else {
-                                        Toast.makeText(getApplicationContext(),
-                                                       "Request Setting Fisrt!!", Toast.LENGTH_LONG).show();
-                                    }
-                                }
-                            } ).showDialog();
-                            isBigData = false;
-                        } else {
-                            if (isSendRequestToAllSetting != true) {
-                                checkMsgSecured("Select DTLS Type");
-                            }
-                        }
-
-                        isSendRequestToAllSetting = false;
-                        isBigData = false;
-                    }
-                }).show();
-    }
-
-    public void OnResponseReceived(String subject, String receivedData) {
-        String callbackData = subject + receivedData;
-        DLog.v(TAG, callbackData);
-
-        if (subject.equals(getString(R.string.remote_address))) {
-            StringBuilder sb = new StringBuilder();
-            sb.append(getString(R.string.coap_prefix)).append(receivedData);
-            mReqData_ed.setText(sb.toString());
-            mNotification_ed.setText(sb.toString());
-        } else if (subject.equals(getString(R.string.remote_port))) {
-            StringBuilder sb = new StringBuilder();
-            String uri = mReqData_ed.getText().toString();
-            sb.append(uri);
-            if (null != receivedData && uri.contains("."))
-            {
-                sb.append(":").append(receivedData);
-            }
-            sb.append(getString(R.string.uri));
-            mReqData_ed.setText(sb.toString());
-            mNotification_ed.setText(sb.toString());
-        }
-    }
-}
\ No newline at end of file
diff --git a/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/java/org/iotivity/ca/service/RMInterface.java b/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/java/org/iotivity/ca/service/RMInterface.java
deleted file mode 100755 (executable)
index 9b6a6dc..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-package org.iotivity.ca.service;
-
-import android.content.Context;
-
-public class RMInterface {
-
-    static {
-        // Load RI JNI interface
-        System.loadLibrary("RMInterface");
-    }
-
-    private org.iotivity.ca.service.MainActivity mResponseListener = null;
-
-    public native void setNativeResponseListener(Object listener);
-
-    public native void RMInitialize(Context context);
-
-    public native void RMTerminate();
-
-    public native void RMStartListeningServer();
-
-    public native void RMStartDiscoveryServer();
-
-    public native void RMRegisterHandler();
-
-    public native void RMFindResource(String uri);
-
-    public native void RMSendRequest(String uri, String payload,
-            int selectedNetwork, int isSecured, int msgType, boolean isBigData);
-
-    public native void RMSendReqestToAll(String uri, int selectedNetwork);
-
-    public native void RMSendResponse(int selectedNetwork, int isSecured,
-            int msgType, int responseValue);
-
-    public native void RMAdvertiseResource(String advertiseResource);
-
-    public native void RMSendNotification(String uri, String payload,
-            int selectedNetwork, int isSecured, int msgType);
-
-    public native void RMSelectNetwork(int interestedNetwork);
-
-    public native void RMUnSelectNetwork(int uninterestedNetwork);
-
-    public native void RMGetNetworkInfomation();
-
-    public native void RMHandleRequestResponse();
-
-    public void setResponseListener(org.iotivity.ca.service.MainActivity listener) {
-        mResponseListener = listener;
-        setNativeResponseListener(this);
-    }
-
-    private void OnResponseReceived(String subject, String receivedData) {
-        if (null != mResponseListener) {
-            mResponseListener.OnResponseReceived(subject, receivedData);
-        }
-    }
-
-}
diff --git a/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/jni/Android.mk b/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/jni/Android.mk
deleted file mode 100755 (executable)
index be764d8..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-APP_PATH := $(call my-dir)
-#specify project root path here wrt make file directory
-PROJECT_ROOT_PATH      = ../../../../../../
-include $(CLEAR_VARS)
-LOCAL_PATH= $(PROJECT_ROOT_PATH)/../../../out/android/$(APP_ABI)/$(APP_OPTIM)/resource/csdk/connectivity/src
-LOCAL_SRC_FILES = libconnectivity_abstraction.so
-LOCAL_MODULE = CA
-include $(PREBUILT_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_PATH= $(PROJECT_ROOT_PATH)/../../../out/android/$(APP_ABI)/$(APP_OPTIM)/resource/csdk/connectivity/samples/android
-LOCAL_SRC_FILES = libRMInterface.so
-LOCAL_MODULE = CASAMPLE
-include $(PREBUILT_SHARED_LIBRARY)
diff --git a/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/jni/Application.mk b/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/jni/Application.mk
deleted file mode 100755 (executable)
index ed9b8b6..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-
-APP_PROJECT_PATH = ./
-APP_STL := gnustl_shared
-
-APP_PLATFORM = android-21
-APP_CPPFLAGS += -fexceptions
-APP_CPPFLAGS += -frtti
-APP_CFLAGS = -Wno-error=format-security
diff --git a/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/jni/ResourceModel.c b/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/jni/ResourceModel.c
deleted file mode 100644 (file)
index 5e08bb4..0000000
+++ /dev/null
@@ -1,1738 +0,0 @@
-#include <jni.h>
-#include <android/log.h>
-#include <stdio.h>
-#include <dlfcn.h>
-#include <stdlib.h>
-#include <string.h>
-#include <time.h>
-
-#include "cainterface.h"
-#include "cacommon.h"
-#include "caadapterutils.h"
-#include "oic_string.h"
-
-#include "org_iotivity_ca_service_RMInterface.h"
-
-#define  LOG_TAG   "JNI_INTERFACE_SAMPLE"
-#define  LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
-#define  LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
-
-// Iotivity Device Identity.
-const unsigned char IDENTITY[] = ("1111111111111111");
-
-// PSK between this device and peer device.
-const unsigned char RS_CLIENT_PSK[] = ("AAAAAAAAAAAAAAAA");
-
-#define PORT_LENGTH 5
-#define SECURE_DEFAULT_PORT 5684
-#define RESOURCE_URI_LENGTH 14
-#define OPTION_INFO_LENGTH 1024
-#define NETWORK_INFO_LENGTH 1024
-#define BIG_PAYLOAD_LENGTH 1024
-#define RECEIVED_FILE_NAME_PREFIX_LENGTH 7
-#define RECEIVED_FILE_NAME_LENGTH 14
-
-typedef struct
-{
-    char ipAddress[CA_IPADDR_SIZE];
-    uint16_t port;
-} addressSet_t;
-
-static void request_handler(const CAEndpoint_t* object, const CARequestInfo_t* requestInfo);
-static void response_handler(const CAEndpoint_t* object, const CAResponseInfo_t* responseInfo);
-static void error_handler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
-static void get_resource_uri(const char *URI, char *resourceURI, int32_t length);
-static uint32_t get_secure_information(CAPayload_t payLoad);
-static CAResult_t get_network_type(uint32_t selectedNetwork);
-static void callback(char *subject, char *receivedData);
-static CAResult_t get_remote_address(const char *address);
-static void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags);
-static void delete_global_references(JNIEnv *env, jobject obj);
-static int get_address_set(const char *pAddress, addressSet_t* outAddress);
-bool read_file(const char* name, char** bytes, size_t* length);
-uint32_t gettodaydate();
-void saveFile(const char *payload, size_t payloadSize);
-
-uint16_t g_localSecurePort = SECURE_DEFAULT_PORT;
-CATransportAdapter_t g_selectedNwType = CA_ADAPTER_IP;
-static CAToken_t g_lastRequestToken = NULL;
-static uint8_t g_lastRequestTokenLength = 0;
-
-static const char COAP_PREFIX[] =  "coap://";
-static const char COAPS_PREFIX[] = "coaps://";
-static const uint16_t COAP_PREFIX_LEN = sizeof(COAP_PREFIX) - 1;
-static const uint16_t COAPS_PREFIX_LEN = sizeof(COAPS_PREFIX) - 1;
-
-static const char RECEIVED_FILE_PATH[] = "/storage/emulated/0/Download/%d%s.txt";
-
-static const char SECURE_INFO_DATA[]
-                                   = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
-                                     "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":"
-                                     "%d}}]}";
-static const char NORMAL_INFO_DATA[]
-                                   = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
-                                     "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
-
-static jobject g_responseListenerObject = NULL;
-static JavaVM *g_jvm;
-
-static CAEndpoint_t *g_clientEndpoint = NULL;
-static char *g_resourceUri = NULL;
-static CAToken_t g_clientToken = NULL;
-static uint8_t g_clientTokenLength = 0;
-
-static uint16_t g_clientMsgId = 0;
-static char *g_remoteAddress = NULL;
-
-// init
-JNIEXPORT void JNICALL
-Java_org_iotivity_ca_service_RMInterface_setNativeResponseListener(JNIEnv *env, jobject obj,
-                                                                   jobject listener)
-{
-    LOGI("setNativeResponseListener");
-    if (!env || !obj || !listener)
-    {
-        LOGI("Invalid input parameter");
-        return;
-    }
-
-    g_responseListenerObject = (*env)->NewGlobalRef(env, listener);
-}
-
-#ifdef __WITH_DTLS__
-// Internal API. Invoked by OC stack to retrieve credentials from this module
-int32_t CAGetDtlsPskCredentials( CADtlsPskCredType_t type,
-              const unsigned char *desc, size_t desc_len,
-              unsigned char *result, size_t result_length)
-{
-    LOGI("CAGetDtlsPskCredentials IN");
-
-    int32_t ret = -1;
-
-    if (NULL == result)
-    {
-        return ret;
-    }
-
-    switch (type)
-    {
-        case CA_DTLS_PSK_HINT:
-        case CA_DTLS_PSK_IDENTITY:
-
-            if (result_length < sizeof(IDENTITY))
-            {
-                LOGE("ERROR : Wrong value for result for storing IDENTITY");
-                return ret;
-            }
-
-            memcpy(result, IDENTITY, sizeof(IDENTITY));
-            ret = sizeof(IDENTITY);
-            break;
-
-        case CA_DTLS_PSK_KEY:
-
-            if ((desc_len == sizeof(IDENTITY)) &&
-                memcmp(desc, IDENTITY, sizeof(IDENTITY)) == 0)
-            {
-                if (result_length < sizeof(RS_CLIENT_PSK))
-                {
-                    LOGE("ERROR : Wrong value for result for storing RS_CLIENT_PSK");
-                    return ret;
-                }
-
-                memcpy(result, RS_CLIENT_PSK, sizeof(RS_CLIENT_PSK));
-                ret = sizeof(RS_CLIENT_PSK);
-            }
-            break;
-
-        default:
-
-            LOGE("Wrong value passed for PSK_CRED_TYPE.");
-            ret = -1;
-    }
-
-    LOGI("CAGetDtlsPskCredentials OUT\n");
-    return ret;
-}
-
-#endif
-
-JNIEXPORT jint JNI_OnLoad(JavaVM *jvm, void *reserved)
-{
-    LOGI("JNI_OnLoad");
-    (void)reserved;
-
-    JNIEnv* env;
-    if (JNI_OK != (*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6))
-    {
-        return -1;
-    }
-    g_jvm = jvm; /* cache the JavaVM pointer */
-
-    CANativeJNISetJavaVM(g_jvm);
-
-    return JNI_VERSION_1_6;
-}
-
-void JNI_OnUnload(JavaVM *jvm, void *reserved)
-{
-    LOGI("JNI_OnUnload");
-    (void)reserved;
-
-    JNIEnv* env;
-    if (JNI_OK != (*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6))
-    {
-        return;
-    }
-    g_jvm = 0;
-    return;
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_ca_service_RMInterface_RMInitialize(JNIEnv *env, jobject obj, jobject context)
-{
-    LOGI("RMInitialize");
-    if (!env || !obj || !context)
-    {
-        LOGI("Invalid input parameter");
-        return;
-    }
-
-    //Currently set context for Android Platform
-    CANativeJNISetContext(env, context);
-
-    CAResult_t res = CAInitialize();
-
-    if (CA_STATUS_OK != res)
-    {
-        LOGE("Could not Initialize");
-    }
-
-#ifdef __WITH_DTLS__
-    res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
-    if(CA_STATUS_OK != res)
-    {
-        LOGE("Set credential handler fail");
-        return;
-    }
-#endif
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_ca_service_RMInterface_RMTerminate(JNIEnv *env, jobject obj)
-{
-    LOGI("RMTerminate");
-    if (!env || !obj)
-    {
-        LOGI("Invalid input parameter");
-        return;
-    }
-
-    CADestroyToken(g_lastRequestToken);
-    CATerminate();
-    delete_global_references(env, obj);
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_ca_service_RMInterface_RMStartListeningServer(JNIEnv *env, jobject obj)
-{
-    LOGI("RMStartListeningServer");
-    if (!env || !obj)
-    {
-        LOGI("Invalid input parameter");
-        return;
-    }
-
-    if (CA_STATUS_OK != CAStartListeningServer())
-    {
-        LOGE("Could not start Listening server");
-    }
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_ca_service_RMInterface_RMStartDiscoveryServer(JNIEnv *env, jobject obj)
-{
-    LOGI("RMStartDiscoveryServer");
-    if (!env || !obj)
-    {
-        LOGI("Invalid input parameter");
-        return;
-    }
-
-    if (CA_STATUS_OK != CAStartDiscoveryServer())
-    {
-        LOGE("Could not start discovery server");
-    }
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_ca_service_RMInterface_RMRegisterHandler(JNIEnv *env, jobject obj)
-{
-    LOGI("RMRegisterHandler");
-    if(!env || !obj)
-    {
-        LOGI("Invalid input parameter");
-        return;
-    }
-
-    CARegisterHandler(request_handler, response_handler, error_handler);
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_ca_service_RMInterface_RMSendRequest(JNIEnv *env, jobject obj, jstring uri,
-                                                       jstring payload, jint selectedNetwork,
-                                                       jint isSecured, jint msgType,
-                                                       jboolean isBigData)
-{
-    LOGI("selectedNetwork - %d", selectedNetwork);
-    if (!env || !obj)
-    {
-        LOGI("Invalid input parameter");
-        return;
-    }
-
-    if (!uri)
-    {
-        LOGE("Invalid input parameter : uri");
-        return;
-    }
-
-    CAResult_t res = get_network_type(selectedNetwork);
-    if (CA_STATUS_OK != res)
-    {
-        return;
-    }
-
-    const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
-    LOGI("RMSendRequest - %s", strUri);
-
-    CATransportFlags_t flags;
-    addressSet_t address = {{0}, 0};
-    parsing_coap_uri(strUri, &address, &flags);
-
-    //create remote endpoint
-    CAEndpoint_t* endpoint = NULL;
-    res = CACreateEndpoint(flags, g_selectedNwType, (const char*)(address.ipAddress),
-                           address.port, &endpoint);
-    if (CA_STATUS_OK != res)
-    {
-        LOGE("Could not create remote end point");
-        (*env)->ReleaseStringUTFChars(env, uri, strUri);
-        return;
-    }
-
-    CAMessageType_t messageType = msgType;
-
-    // create token
-    CAToken_t token = NULL;
-    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
-
-    res = CAGenerateToken(&token, tokenLength);
-    if ((CA_STATUS_OK != res) || (!token))
-    {
-        LOGE("token generate error!!");
-        // destroy remote endpoint
-        CADestroyEndpoint(endpoint);
-        (*env)->ReleaseStringUTFChars(env, uri, strUri);
-        return;
-    }
-
-    char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
-
-    get_resource_uri((const CAURI_t) strUri, resourceURI, RESOURCE_URI_LENGTH);
-    (*env)->ReleaseStringUTFChars(env, uri, strUri);
-
-    CAInfo_t requestData = { 0 };
-    requestData.token = token;
-    requestData.tokenLength = tokenLength;
-
-    size_t payloadLength = 0;
-    if (isBigData)
-    {
-        const char* path = NULL;
-        if (payload)
-        {
-            path = (*env)->GetStringUTFChars(env, payload, NULL);
-            if(path)
-            {
-                char* bigData = NULL;
-                bool result = read_file(path, &bigData, &payloadLength);
-                if (!result)
-                {
-                    LOGE("read has failed");
-                    (*env)->ReleaseStringUTFChars(env, payload, path);
-                    CADestroyToken(token);
-                    CADestroyEndpoint(endpoint);
-                    return;
-                }
-                (*env)->ReleaseStringUTFChars(env, payload, path);
-
-                requestData.payload = (CAPayload_t) malloc(payloadLength);
-                if (NULL == requestData.payload)
-                {
-                    LOGE("Memory allocation failed!");
-                    // destroy token
-                    CADestroyToken(token);
-                    // destroy remote endpoint
-                    CADestroyEndpoint(endpoint);
-                    return;
-                }
-                memcpy(requestData.payload, bigData, payloadLength);
-                requestData.payloadSize = payloadLength;
-            }
-        }
-    }
-    else
-    {
-        if (isSecured)
-        {
-            payloadLength = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
-            requestData.payload = (CAPayload_t) malloc(payloadLength);
-            if (NULL == requestData.payload)
-            {
-                LOGE("Memory allocation failed!");
-                // destroy token
-                CADestroyToken(token);
-                // destroy remote endpoint
-                CADestroyEndpoint(endpoint);
-                return;
-            }
-            snprintf((char *) requestData.payload, payloadLength, SECURE_INFO_DATA,
-                     resourceURI, g_localSecurePort);
-            requestData.payloadSize = payloadLength;
-        }
-        else
-        {
-            payloadLength = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
-            requestData.payload = (CAPayload_t) malloc(payloadLength);
-            if (NULL == requestData.payload)
-            {
-                LOGE("Memory allocation failed!");
-                // destroy token
-                CADestroyToken(token);
-                // destroy remote endpoint
-                CADestroyEndpoint(endpoint);
-                return;
-            }
-            snprintf((char *) requestData.payload, payloadLength, NORMAL_INFO_DATA, resourceURI);
-            requestData.payloadSize = payloadLength;
-        }
-    }
-
-    requestData.type = messageType;
-    requestData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
-    if (NULL == requestData.resourceUri)
-    {
-        LOGE("Memory allocation failed!");
-        // destroy token
-        CADestroyToken(token);
-        // destroy remote endpoint
-        CADestroyEndpoint(endpoint);
-        free(requestData.payload);
-        return;
-    }
-    memcpy(requestData.resourceUri, resourceURI, sizeof(resourceURI));
-
-    CARequestInfo_t requestInfo = { 0 };
-    requestInfo.method = CA_GET;
-    requestInfo.isMulticast = false;
-    requestInfo.info = requestData;
-
-    // send request
-    if (CA_STATUS_OK != CASendRequest(endpoint, &requestInfo))
-    {
-        LOGE("Could not send request");
-    }
-
-    // destroy token
-    CADestroyToken(token);
-
-    // destroy remote endpoint
-    CADestroyEndpoint(endpoint);
-
-    free(requestData.payload);
-    free(requestData.resourceUri);
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_ca_service_RMInterface_RMSendReqestToAll(JNIEnv *env, jobject obj, jstring uri,
-                                                           jint selectedNetwork)
-{
-    LOGI("selectedNetwork - %d", selectedNetwork);
-    if (!env || !obj)
-    {
-        LOGI("Invalid input parameter");
-        return;
-    }
-
-    CAResult_t res = get_network_type(selectedNetwork);
-    if (CA_STATUS_OK != res)
-    {
-        return;
-    }
-
-    // create remote endpoint
-    CAEndpoint_t *endpoint = NULL;
-    res = CACreateEndpoint(CA_IPV4, g_selectedNwType, NULL, 0, &endpoint);
-
-    if (CA_STATUS_OK != res)
-    {
-        LOGE("create remote endpoint error, error code: %d", res);
-        return;
-    }
-
-    // create token
-    CAToken_t token = NULL;
-    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
-
-    res = CAGenerateToken(&token, tokenLength);
-    if ((CA_STATUS_OK != res) || (!token))
-    {
-        LOGE("token generate error!!");
-        // destroy remote endpoint
-        CADestroyEndpoint(endpoint);
-        return;
-    }
-
-    LOGI("generated token %s", token);
-
-    CAInfo_t requestData = { 0 };
-    requestData.token = token;
-    requestData.tokenLength = tokenLength;
-    requestData.payload = (CAPayload_t) "TempJsonPayload";
-    requestData.payloadSize = strlen((const char *) requestData.payload);
-    requestData.type = CA_MSG_NONCONFIRM;
-
-    const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
-    LOGI("resourceUri - %s", strUri);
-    requestData.resourceUri = (CAURI_t)strUri;
-
-    uint8_t optionNum = 2;
-    CAHeaderOption_t *headerOpt = (CAHeaderOption_t*) calloc(1,
-                                                             sizeof(CAHeaderOption_t) * optionNum);
-    if (NULL == headerOpt)
-    {
-        LOGE("Memory allocation failed");
-        // destroy remote endpoint
-        CADestroyEndpoint(endpoint);
-        return;
-    }
-
-    char* FirstOptionData = "Hello";
-    headerOpt[0].optionID = 3000;
-    memcpy(headerOpt[0].optionData, FirstOptionData, strlen(FirstOptionData));
-    headerOpt[0].optionLength = (uint16_t) strlen(FirstOptionData);
-
-    char* SecondOptionData2 = "World";
-    headerOpt[1].optionID = 3001;
-    memcpy(headerOpt[1].optionData, SecondOptionData2, strlen(SecondOptionData2));
-    headerOpt[1].optionLength = (uint16_t) strlen(SecondOptionData2);
-
-    requestData.numOptions = optionNum;
-    requestData.options = headerOpt;
-
-    CARequestInfo_t requestInfo = { 0 };
-    requestInfo.method = CA_GET;
-    requestInfo.isMulticast = true;
-    requestInfo.info = requestData;
-
-    // send request to all
-    res = CASendRequest(endpoint, &requestInfo);
-    if (CA_STATUS_OK != res)
-    {
-        LOGE("Could not send request to all");
-        //destroy token
-        CADestroyToken(token);
-    }
-    else
-    {
-        CADestroyToken(g_lastRequestToken);
-        g_lastRequestToken = token;
-        g_lastRequestTokenLength = tokenLength;
-    }
-
-    //ReleaseStringUTFChars for strUri
-    (*env)->ReleaseStringUTFChars(env, uri, strUri);
-
-    free(headerOpt);
-
-    // destroy remote endpoint
-    CADestroyEndpoint(endpoint);
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_ca_service_RMInterface_RMSendResponse(JNIEnv *env, jobject obj,
-                                                        jint selectedNetwork,
-                                                        jint isSecured, jint msgType,
-                                                        jint responseValue)
-{
-    LOGI("RMSendResponse");
-    if (!env || !obj)
-    {
-        LOGI("Invalid input parameter");
-        return;
-    }
-
-    LOGI("selectedNetwork - %d", selectedNetwork);
-
-    CAResult_t res = get_network_type(selectedNetwork);
-    if (CA_STATUS_OK != res)
-    {
-        LOGE("Not supported network type");
-        return;
-    }
-
-    if (NULL == g_clientEndpoint)
-    {
-        LOGE("No Request received");
-        return;
-    }
-
-    CAMessageType_t messageType = msgType;
-
-    CAInfo_t responseData = { 0 };
-    responseData.type = messageType;
-    responseData.messageId = g_clientMsgId;
-    responseData.resourceUri = (CAURI_t)g_resourceUri;
-
-    CAResponseInfo_t responseInfo = { 0 };
-
-    if (CA_MSG_RESET == msgType ||
-        (CA_MSG_ACKNOWLEDGE == msgType && CA_EMPTY == responseValue))
-    {
-        printf("RESET or ACK/EMPTY. there will be not payload/option\n");
-        responseInfo.result = CA_EMPTY;
-    }
-    else
-    {
-        responseData.token = g_clientToken;
-        responseData.tokenLength = g_clientTokenLength;
-        responseInfo.result = responseValue;
-
-        if (1 == isSecured)
-        {
-            uint32_t length = strlen(SECURE_INFO_DATA) + strlen(g_resourceUri) + 1;
-            responseData.payload = (CAPayload_t) malloc(length);
-            snprintf((char *) responseData.payload, length, SECURE_INFO_DATA,
-                     g_resourceUri, g_localSecurePort);
-            responseData.payloadSize = length;
-        }
-        else
-        {
-            uint32_t length = strlen(NORMAL_INFO_DATA) + strlen(g_resourceUri) + 1;
-            responseData.payload = (CAPayload_t) malloc(length);
-            snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA, g_resourceUri);
-            responseData.payloadSize = length;
-        }
-    }
-
-    responseInfo.info = responseData;
-
-    // send response
-    res = CASendResponse(g_clientEndpoint, &responseInfo);
-    if (CA_STATUS_OK != res)
-    {
-        LOGE("Could not send response");
-    }
-
-    // destroy token
-    CADestroyToken(g_clientToken);
-    g_clientToken = NULL;
-    g_clientTokenLength = 0;
-
-    // destroy remote endpoint
-    CADestroyEndpoint(g_clientEndpoint);
-    g_clientEndpoint = NULL;
-    free(responseData.payload);
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_ca_service_RMInterface_RMSendNotification(JNIEnv *env, jobject obj, jstring uri,
-                                                            jstring payload, jint selectedNetwork,
-                                                            jint isSecured, jint msgType)
-{
-    LOGI("selectedNetwork - %d", selectedNetwork);
-    if (!env || !obj)
-    {
-        LOGI("Invalid input parameter");
-        return;
-    }
-
-    if (!payload)
-    {
-        LOGE("payload is NULL");
-    }
-
-    if (!uri)
-    {
-        LOGE("Invalid input parameter : uri");
-        return;
-    }
-
-    CAResult_t res = get_network_type(selectedNetwork);
-    if (CA_STATUS_OK != res)
-    {
-        LOGE("Not supported network type");
-        return;
-    }
-
-    const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
-    LOGI("RMSendNotification - %s", strUri);
-
-    CATransportFlags_t flags;
-    addressSet_t address = {{0}, 0};
-    parsing_coap_uri(strUri, &address, &flags);
-
-    //create remote endpoint
-    CAEndpoint_t* endpoint = NULL;
-    if (CA_STATUS_OK != CACreateEndpoint(flags, g_selectedNwType,
-                                         (const char*)address.ipAddress,
-                                         address.port, &endpoint))
-    {
-        //ReleaseStringUTFChars for strUri
-        (*env)->ReleaseStringUTFChars(env, uri, strUri);
-        LOGE("Could not create remote end point");
-        return;
-    }
-
-    char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
-    get_resource_uri(strUri, resourceURI, RESOURCE_URI_LENGTH);
-
-    //ReleaseStringUTFChars for strUri
-    (*env)->ReleaseStringUTFChars(env, uri, strUri);
-
-    CAMessageType_t messageType = msgType;
-
-    // create token
-    CAToken_t token = NULL;
-    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
-
-    res = CAGenerateToken(&token, tokenLength);
-    if ((CA_STATUS_OK != res) || (!token))
-    {
-        LOGE("token generate error!");
-        CADestroyEndpoint(endpoint);
-        return;
-    }
-
-    CAInfo_t requestData = { 0 };
-    requestData.token = token;
-    requestData.tokenLength = tokenLength;
-    requestData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
-    if (NULL == requestData.resourceUri)
-    {
-        LOGE("Memory allocation failed!");
-        // destroy token
-        CADestroyToken(token);
-        // destroy remote endpoint
-        CADestroyEndpoint(endpoint);
-        return;
-    }
-    memcpy(requestData.resourceUri, resourceURI, sizeof(resourceURI));
-
-    if (1 == isSecured)
-    {
-        uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
-        requestData.payload = (CAPayload_t) malloc(length);
-        if (NULL == requestData.payload)
-        {
-            LOGE("Memory allocation failed!");
-            // destroy token
-            CADestroyToken(token);
-            // destroy remote endpoint
-            CADestroyEndpoint(endpoint);
-
-            free(requestData.resourceUri);
-            return;
-        }
-        snprintf((char *) requestData.payload, length, SECURE_INFO_DATA,
-                 resourceURI, g_localSecurePort);
-        requestData.payloadSize = length;
-    }
-    else
-    {
-        uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
-        requestData.payload = (CAPayload_t) malloc(length);
-        if (NULL == requestData.payload)
-        {
-            LOGE("Memory allocation failed!");
-            // destroy token
-            CADestroyToken(token);
-            // destroy remote endpoint
-            CADestroyEndpoint(endpoint);
-
-            free(requestData.resourceUri);
-            return;
-        }
-        snprintf((char *) requestData.payload, length, NORMAL_INFO_DATA, resourceURI);
-        requestData.payloadSize = length;
-    }
-
-    requestData.type = messageType;
-
-    CARequestInfo_t requestInfo = { 0 };
-    requestInfo.method = CA_GET;
-    requestInfo.info = requestData;
-
-    // send notification
-    if (CA_STATUS_OK != CASendRequest(endpoint, &requestInfo))
-    {
-        LOGE("Could not send notification");
-    }
-
-    LOGI("Send Notification");
-
-    // destroy token
-    CADestroyToken(token);
-
-    // destroy remote endpoint
-    CADestroyEndpoint(endpoint);
-
-    free(requestData.payload);
-    free(requestData.resourceUri);
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_ca_service_RMInterface_RMSelectNetwork(JNIEnv *env, jobject obj,
-                                                         jint networkType)
-{
-    LOGI("RMSelectNetwork Type : %d", networkType);
-    if (!env || !obj)
-    {
-        LOGI("Invalid input parameter");
-        return;
-    }
-
-    if (CA_STATUS_OK != CASelectNetwork(networkType))
-    {
-        LOGE("Could not select network");
-    }
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_ca_service_RMInterface_RMUnSelectNetwork(JNIEnv *env, jobject obj,
-                                                           jint networkType)
-{
-    LOGI("RMUnSelectNetwork Type : %d", networkType);
-    if (!env || !obj)
-    {
-        LOGI("Invalid input parameter");
-        return;
-    }
-
-    if (CA_STATUS_OK != CAUnSelectNetwork(networkType))
-    {
-        LOGE("Could not unselect network");
-    }
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_ca_service_RMInterface_RMGetNetworkInfomation(JNIEnv *env, jobject obj)
-{
-    LOGI("RMGetNetworkInfomation");
-    if (!env || !obj)
-    {
-        LOGI("Invalid input parameter");
-        return;
-    }
-
-    CAEndpoint_t *tempInfo = NULL;
-    uint32_t tempSize = 0;
-
-    CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
-    if (CA_STATUS_OK != res)
-    {
-        LOGE("Could not start get network information");
-        free(tempInfo);
-        return;
-    }
-
-    LOGI("################## Network Information #######################");
-    callback("######## Network Information", "#######");
-    LOGI("Network info total size is %d", tempSize);
-
-    uint32_t index;
-    for (index = 0; index < tempSize; index++)
-    {
-        res = get_remote_address(tempInfo[index].addr);
-        if (CA_STATUS_OK != res)
-        {
-            free(tempInfo);
-            return;
-        }
-        if (NULL != g_responseListenerObject)
-        {
-            char networkInfo[NETWORK_INFO_LENGTH];
-            LOGI("Type: %d", tempInfo[index].adapter);
-            snprintf(networkInfo, NETWORK_INFO_LENGTH, "%d",tempInfo[index].adapter);
-            callback("Type :", networkInfo);
-            if (CA_ADAPTER_IP == tempInfo[index].adapter)
-            {
-                LOGI("Port: %d", tempInfo[index].port);
-                snprintf(networkInfo, NETWORK_INFO_LENGTH, "%d",tempInfo[index].port);
-                callback("Port: ", networkInfo);
-            }
-            LOGI("Secured: %d", (tempInfo[index].flags & CA_SECURE));
-            LOGI("Address: %s", g_remoteAddress);
-            callback("Address: ", g_remoteAddress);
-            free(g_remoteAddress);
-        }
-        if (tempInfo[index].flags & CA_SECURE)
-        {
-            g_localSecurePort = tempInfo[index].port;
-        }
-    }
-
-    // free
-    free(tempInfo);
-
-    LOGI("##############################################################");
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_ca_service_RMInterface_RMHandleRequestResponse(JNIEnv *env, jobject obj)
-{
-    LOGI("RMHandleRequestResponse");
-    if(!env || !obj)
-    {
-        LOGI("Invalid input parameter");
-        return;
-    }
-
-    if (CA_STATUS_OK != CAHandleRequestResponse())
-    {
-        LOGE("Could not handle request and response");
-    }
-}
-
-void request_handler(const CAEndpoint_t* object, const CARequestInfo_t* requestInfo)
-{
-
-    if (!object)
-    {
-        LOGE("Remote endpoint is NULL!");
-        return;
-    }
-
-    if (!requestInfo)
-    {
-        LOGE("Request info is NULL!");
-        return;
-    }
-
-    if ((NULL != g_lastRequestToken) && (NULL != requestInfo->info.token) &&
-            (strncmp(g_lastRequestToken, requestInfo->info.token,
-                     requestInfo->info.tokenLength) == 0))
-    {
-        LOGI("token is same. received request of it's own. skip.. ");
-        return;
-    }
-
-    CAResult_t res = get_remote_address(object->addr);
-    if (CA_STATUS_OK != res)
-    {
-        return;
-    }
-
-    LOGI("##########received request from remote device #############");
-    LOGI("Remote Address: %s", g_remoteAddress);
-    LOGI("Remote Port: %d", object->port);
-    LOGI("Uri: %s", requestInfo->info.resourceUri);
-    LOGI("Data: %s", requestInfo->info.payload);
-    LOGI("Token: %s", requestInfo->info.token);
-    LOGI("Code: %d", requestInfo->method);
-    LOGI("MessageType: %d", requestInfo->info.type);
-
-    if (NULL != g_responseListenerObject)
-    {
-        char *cloneUri = NULL;
-        uint32_t len = 0;
-
-        if (NULL != requestInfo->info.resourceUri)
-        {
-            len = strlen(requestInfo->info.resourceUri);
-            cloneUri = (char *)malloc(sizeof(char) * (len + 1));
-
-            if (NULL == cloneUri)
-            {
-                LOGE("cloneUri Out of memory");
-                free(g_remoteAddress);
-                return;
-            }
-
-            memcpy(cloneUri, requestInfo->info.resourceUri, len + 1);
-            callback("Uri: ", cloneUri);
-        }
-
-        len = strlen(g_remoteAddress);
-        char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
-
-        if (NULL == cloneRemoteAddress)
-        {
-            LOGE("cloneRemoteAddress Out of memory");
-            free(g_remoteAddress);
-            free(cloneUri);
-            return;
-        }
-
-        memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
-
-        callback("Remote Address: ", cloneRemoteAddress);
-        free(cloneRemoteAddress);
-        free(g_remoteAddress);
-
-        char portInfo[PORT_LENGTH] = { 0, };
-        snprintf(portInfo, PORT_LENGTH, "%d", object->port);
-        callback("Remote Port: ", portInfo);
-
-        //clone g_clientEndpoint
-        g_clientEndpoint = (CAEndpoint_t *) malloc(sizeof(CAEndpoint_t));
-        if (NULL == g_clientEndpoint)
-        {
-            LOGE("g_clientEndpoint Out of memory");
-            free(cloneUri);
-            return;
-        }
-        memcpy(g_clientEndpoint, object, sizeof(CAEndpoint_t));
-
-        if (NULL != cloneUri)
-        {
-            len = strlen(cloneUri);
-            g_resourceUri = (char *) malloc(sizeof(char) * (len + 1));
-            if (NULL == g_resourceUri)
-            {
-                LOGE("g_clientEndpoint->resourceUri Out of memory");
-                free(g_clientEndpoint);
-                free(cloneUri);
-                return;
-            }
-            memcpy(g_resourceUri, cloneUri, len + 1);
-            free(cloneUri);
-        }
-        //clone g_clientToken
-        len = requestInfo->info.tokenLength;
-
-        g_clientToken = (char *) malloc(sizeof(char) * len);
-        if (NULL == g_clientToken)
-        {
-            LOGE("g_clientToken Out of memory");
-            free(g_clientEndpoint);
-            return;
-        }
-
-        if (NULL != requestInfo->info.token)
-        {
-            memcpy(g_clientToken, requestInfo->info.token, len);
-            g_clientTokenLength = len;
-
-        }
-
-        //clone g_clientMsgId
-        g_clientMsgId = requestInfo->info.messageId;
-
-        if (NULL != requestInfo->info.payload && requestInfo->info.payloadSize > 0)
-        {
-            len = requestInfo->info.payloadSize;
-            char *clonePayload = (char *) malloc(len + 1);
-            if (NULL == clonePayload)
-            {
-                LOGE("clonePayload Out of memory");
-                free(g_clientEndpoint);
-                return;
-            }
-
-            memcpy(clonePayload, requestInfo->info.payload, len);
-            clonePayload[len] = '\0';
-
-            if (len > BIG_PAYLOAD_LENGTH)
-            {
-                saveFile(clonePayload, len);
-            }
-            else
-            {
-                callback("Data: ", clonePayload);
-            }
-            free(clonePayload);
-        }
-    }
-
-    if (requestInfo->info.options)
-    {
-        uint32_t len = requestInfo->info.numOptions;
-        uint32_t i;
-
-        LOGI("Option count: %d", requestInfo->info.numOptions);
-
-        for (i = 0; i < len; i++)
-        {
-            LOGI("Option %d", i + 1);
-            LOGI("ID : %d", requestInfo->info.options[i].optionID);
-            LOGI("Data[%d]: %s", requestInfo->info.options[i].optionLength,
-                 requestInfo->info.options[i].optionData);
-
-            if (NULL != g_responseListenerObject)
-            {
-                char optionInfo[OPTION_INFO_LENGTH] = { 0, };
-                snprintf(optionInfo, OPTION_INFO_LENGTH,
-                         "Num[%d] - ID : %d, Option Length : %d", i + 1,
-                         requestInfo->info.options[i].optionID,
-                         requestInfo->info.options[i].optionLength);
-
-                callback("Option info: ", optionInfo);
-
-                size_t optionDataLen = strlen(requestInfo->info.options[i].optionData);
-                char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
-                if (NULL == cloneOptionData)
-                {
-                    LOGE("cloneOptionData Out of memory");
-                    free(g_clientEndpoint);
-                    return;
-                }
-
-                memcpy(cloneOptionData, requestInfo->info.options[i].optionData,
-                       optionDataLen + 1);
-
-                callback("Option Data: ", cloneOptionData);
-                free(cloneOptionData);
-            }
-        }
-    }
-    LOGI("############################################################");
-
-    //Check if this has secure communication information
-    if (requestInfo->info.payload && CA_ADAPTER_IP == object->adapter)
-    {
-        uint32_t securePort = get_secure_information(requestInfo->info.payload);
-        if (0 < securePort) //Set the remote endpoint secure details and send response
-        {
-            LOGI("This is secure resource...");
-
-            CAEndpoint_t *endpoint = NULL;
-            if (CA_STATUS_OK != CACreateEndpoint(CA_SECURE,
-                        object->adapter, object->addr, securePort, &endpoint))
-            {
-                LOGE("Failed to create duplicate of remote endpoint!");
-                return;
-            }
-            object = endpoint;
-        }
-    }
-}
-
-void response_handler(const CAEndpoint_t* object, const CAResponseInfo_t* responseInfo)
-{
-    if (!object || !responseInfo)
-    {
-        LOGE("Invalid input parameter");
-        return;
-    }
-
-    CAResult_t res = get_remote_address(object->addr);
-    if (CA_STATUS_OK != res)
-    {
-        return;
-    }
-
-    LOGI("##########Received response from remote device #############");
-    LOGI("Uri: %s", responseInfo->info.resourceUri);
-    LOGI("Remote Address: %s", g_remoteAddress);
-    LOGI("Remote Port: %d", object->port);
-    LOGI("response result: %d", responseInfo->result);
-    LOGI("Data: %s", responseInfo->info.payload);
-    LOGI("Token: %s", responseInfo->info.token);
-    LOGI("MessageType: %d", responseInfo->info.type);
-
-    if (NULL != g_responseListenerObject)
-    {
-        uint32_t len = 0;
-
-        if (NULL != responseInfo->info.resourceUri)
-        {
-            len = strlen(responseInfo->info.resourceUri);
-            char *cloneUri = (char *) malloc(sizeof(char) * (len + 1));
-
-            if (NULL == cloneUri)
-            {
-                LOGE("cloneUri Out of memory");
-                free(g_remoteAddress);
-                return;
-            }
-
-            memcpy(cloneUri, responseInfo->info.resourceUri, len + 1);
-
-            callback("Uri: ", cloneUri);
-            free(cloneUri);
-        }
-
-        len = strlen(g_remoteAddress);
-        char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
-
-        if (NULL == cloneRemoteAddress)
-        {
-            LOGE("cloneRemoteAddress Out of memory");
-            free(g_remoteAddress);
-            return;
-        }
-
-        memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
-
-        callback("Remote Address: ", cloneRemoteAddress);
-        free(cloneRemoteAddress);
-        free(g_remoteAddress);
-
-        char portInfo[PORT_LENGTH] = { 0, };
-        snprintf(portInfo, PORT_LENGTH, "%d", object->port);
-        callback("Remote Port: ", portInfo);
-
-        if (NULL != responseInfo->info.payload && responseInfo->info.payloadSize)
-        {
-            len = responseInfo->info.payloadSize;
-            char *clonePayload = (char *) malloc(len + 1);
-            if (NULL == clonePayload)
-            {
-                LOGE("clonePayload Out of memory");
-                return;
-            }
-
-            memcpy(clonePayload, responseInfo->info.payload, len);
-            clonePayload[len] = '\0';
-
-            if (len > BIG_PAYLOAD_LENGTH)
-            {
-                saveFile(clonePayload, len);
-            }
-            else
-            {
-                callback("Data: ", clonePayload);
-            }
-            free(clonePayload);
-        }
-    }
-
-    if (responseInfo->info.options)
-    {
-        uint32_t len = responseInfo->info.numOptions;
-        uint32_t i;
-        for (i = 0; i < len; i++)
-        {
-            LOGI("Option %d", i + 1);
-            LOGI("ID : %d", responseInfo->info.options[i].optionID);
-            LOGI("Data[%d]: %s", responseInfo->info.options[i].optionLength,
-                 responseInfo->info.options[i].optionData);
-
-            if (NULL != g_responseListenerObject)
-            {
-                char optionInfo[OPTION_INFO_LENGTH] = { 0, };
-                snprintf(optionInfo, OPTION_INFO_LENGTH,
-                         "Num[%d] - ID : %d, Option Length : %d", i + 1,
-                         responseInfo->info.options[i].optionID,
-                         responseInfo->info.options[i].optionLength);
-
-                callback("Option info: ", optionInfo);
-
-                size_t optionDataLen = strlen(responseInfo->info.options[i].optionData);
-                char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
-                if (NULL == cloneOptionData)
-                {
-                    LOGE("cloneOptionData Out of memory");
-                    return;
-                }
-                memcpy(cloneOptionData, responseInfo->info.options[i].optionData,
-                       optionDataLen + 1);
-                callback("Option Data: ", cloneOptionData);
-                free(cloneOptionData);
-            }
-        }
-    }
-    LOGI("############################################################");
-
-    //Check if this has secure communication information
-    if (responseInfo->info.payload && CA_ADAPTER_IP == object->adapter)
-    {
-        uint32_t securePort = get_secure_information(responseInfo->info.payload);
-        if (0 < securePort) //Set the remote endpoint secure details and send response
-        {
-            LOGI("This is secure resource...");
-        }
-    }
-}
-
-void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
-{
-    LOGI("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++");
-
-    if (rep)
-    {
-        LOGI("Error Handler, Adapter Type : %d", rep->adapter);
-        LOGI("Error Handler, Adapter Type : %s", rep->addr);
-    }
-
-    if (errorInfo)
-    {
-        const CAInfo_t *info = &errorInfo->info;
-        LOGI("Error Handler, ErrorInfo :");
-        LOGI("Error Handler result    : %d", errorInfo->result);
-        LOGI("Error Handler token     : %s", info->token);
-        LOGI("Error Handler messageId : %d", (uint16_t) info->messageId);
-        LOGI("Error Handler resourceUri : %s", info->resourceUri);
-        LOGI("Error Handler type      : %d", info->type);
-        LOGI("Error Handler payload   : %s", info->payload);
-
-        if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
-        {
-            LOGE("CA_ADAPTER_NOT_ENABLED, enable the adapter");
-        }
-        else if(CA_SEND_FAILED == errorInfo->result)
-        {
-            LOGE("CA_SEND_FAILED, unable to send the message, check parameters");
-        }
-        else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
-        {
-            LOGE("CA_MEMORY_ALLOC_FAILED, insufficient memory");
-        }
-        else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
-        {
-            LOGE("CA_SOCKET_OPERATION_FAILED, socket operation failed");
-        }
-        else if(CA_STATUS_FAILED == errorInfo->result)
-        {
-            LOGE("CA_STATUS_FAILED, message could not be delivered, internal error");
-        }
-    }
-    LOGI("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++");
-
-    return;
-}
-
-void get_resource_uri(const char *URI, char *resourceURI, int32_t length)
-{
-    const char *startPos = URI;
-    const char *temp = strstr(URI, "://");
-    if (NULL != temp)
-    {
-        startPos = strchr(temp + 3, '/');
-        if (!startPos)
-        {
-            LOGE("Resource URI is missing");
-            return;
-        }
-    }
-
-    const char *endPos = strchr(startPos, '?');
-    if (!endPos)
-    {
-        endPos = URI + strlen(URI);
-    }
-    --endPos;
-
-    if (endPos - startPos <= length)
-    {
-        memcpy(resourceURI, startPos + 1, endPos - startPos);
-    }
-
-    LOGI("URI: %s, ResourceURI: %s", URI, resourceURI);
-}
-
-uint32_t get_secure_information(CAPayload_t payLoad)
-{
-    LOGI("entering get_secure_information");
-
-    if (!payLoad)
-    {
-        LOGE("Payload is NULL");
-        return -1;
-    }
-
-    const char *subString = NULL;
-    if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1")))
-    {
-        LOGE("This is not secure resource");
-        return -1;
-    }
-
-    if (NULL == (subString = strstr((const char *) payLoad, "\"port\":")))
-    {
-        LOGE("This secure resource does not have port information");
-        return -1;
-    }
-
-    const char *startPos = strstr(subString, ":");
-    if (!startPos)
-    {
-        LOGE("Parsing failed !");
-        return -1;
-    }
-
-    const char *endPos = strstr(startPos, "}");
-    if (!endPos)
-    {
-        LOGE("Parsing failed !");
-        return -1;
-    }
-
-    char portStr[6] = { 0 };
-    memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
-
-    LOGI("secured port is: %s", portStr);
-    return atoi(portStr);
-}
-
-CAResult_t get_network_type(uint32_t selectedNetwork)
-{
-
-    uint32_t number = selectedNetwork;
-
-    if (!(number & 0xf))
-    {
-        return CA_NOT_SUPPORTED;
-    }
-    if (number & CA_ADAPTER_IP)
-    {
-        g_selectedNwType = CA_ADAPTER_IP;
-        return CA_STATUS_OK;
-    }
-    if (number & CA_ADAPTER_RFCOMM_BTEDR)
-    {
-        g_selectedNwType = CA_ADAPTER_RFCOMM_BTEDR;
-        return CA_STATUS_OK;
-    }
-    if (number & CA_ADAPTER_GATT_BTLE)
-    {
-        g_selectedNwType = CA_ADAPTER_GATT_BTLE;
-        return CA_STATUS_OK;
-    }
-
-    return CA_NOT_SUPPORTED;
-}
-
-void callback(char *subject, char *receivedData)
-{
-    bool isAttached = false;
-    JNIEnv* env;
-
-    if (!g_responseListenerObject)
-    {
-        LOGE("g_responseListenerObject is NULL, cannot have callback");
-        return;
-    }
-
-    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
-    if (JNI_OK != res)
-    {
-        LOGI("Could not get JNIEnv pointer");
-        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
-
-        if (JNI_OK != res)
-        {
-            LOGE("AttachCurrentThread has failed");
-            return;
-        }
-        isAttached = true;
-    }
-
-    jclass cls = (*env)->GetObjectClass(env, g_responseListenerObject);
-    if (!cls)
-    {
-        LOGE("could not get class");
-        goto detach_thread;
-    }
-
-    jmethodID mid = (*env)->GetMethodID(env, cls, "OnResponseReceived",
-                                        "(Ljava/lang/String;Ljava/lang/String;)V");
-    if (!mid)
-    {
-        LOGE("could not get Method ID");
-        goto detach_thread;
-    }
-
-    jstring jsubject = (*env)->NewStringUTF(env, (char*) subject);
-    if (!jsubject)
-    {
-        LOGE("NewStringUTF failed");
-        goto detach_thread;
-    }
-
-    jstring jreceivedData = (*env)->NewStringUTF(env, (char*) receivedData);
-    if (!jreceivedData)
-    {
-        LOGE("NewStringUTF failed");
-        goto detach_thread;
-    }
-
-    (*env)->CallVoidMethod(env, g_responseListenerObject, mid, jsubject, jreceivedData);
-
-detach_thread :
-    if (isAttached)
-    {
-        (*g_jvm)->DetachCurrentThread(g_jvm);
-        LOGI("DetachCurrentThread");
-    }
-}
-
-CAResult_t get_remote_address(const char *address)
-{
-    uint32_t len = strlen(address);
-
-    g_remoteAddress = (char *)malloc(sizeof (char) * (len + 1));
-    if (NULL == g_remoteAddress)
-    {
-        LOGE("g_remoteAddress Out of memory");
-        return CA_MEMORY_ALLOC_FAILED;
-    }
-
-    memcpy(g_remoteAddress, address, len + 1);
-
-    return CA_STATUS_OK;
-}
-
-
-void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
-{
-    if (NULL == uri || NULL == address)
-    {
-        LOGE("parameter is null");
-        return;
-    }
-
-    // parse uri
-    // #1. check prefix
-    uint8_t startIndex = 0;
-    if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
-    {
-        LOGI("uri has '%s' prefix", COAPS_PREFIX);
-        startIndex = COAPS_PREFIX_LEN;
-        *flags = CA_SECURE;
-    }
-    else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
-    {
-        LOGI("uri has '%s' prefix", COAP_PREFIX);
-        startIndex = COAP_PREFIX_LEN;
-        *flags = CA_IPV4;
-    }
-
-    // #2. copy uri for parse
-    size_t len = strlen(uri) - startIndex;
-
-    if (len <= 0)
-    {
-        LOGE("uri length is 0!");
-        return;
-    }
-
-    char *cloneUri = (char *) calloc(len + 1, sizeof(char));
-    if (NULL == cloneUri)
-    {
-        LOGE("Out of memory");
-        return;
-    }
-
-    OICStrcpy(cloneUri, len+1, &uri[startIndex]);
-
-    char *pstr = NULL;
-    //filter out the resource uri
-    char *pUrl = strtok_r(cloneUri, "/", &pstr);
-
-    if (pUrl)
-    {
-        LOGI("pAddress : %s", pUrl);
-        int res = get_address_set(pUrl, address);
-        if (res == -1)
-        {
-            LOGE("address parse error");
-
-            return;
-        }
-    }
-    else
-    {
-        LOGE("strtok_r error, could not get the address");
-    }
-
-    return;
-}
-
-int get_address_set(const char *pAddress, addressSet_t* outAddress)
-{
-    if (NULL == pAddress || NULL == outAddress)
-    {
-        LOGE("parameter is null");
-        return -1;
-    }
-
-    size_t len = strlen(pAddress);
-    int isIp = 0;
-    size_t ipLen = 0;
-
-    for (size_t i = 0; i < len; i++)
-    {
-        if (pAddress[i] == '.')
-        {
-            isIp = 1;
-        }
-
-        // found port number start index
-        if (isIp && pAddress[i] == ':')
-        {
-            ipLen = i;
-            break;
-        }
-    }
-
-    if (isIp)
-    {
-        if(ipLen && (ipLen <  sizeof(outAddress->ipAddress)))
-        {
-            strncpy(outAddress->ipAddress, pAddress, ipLen);
-            outAddress->ipAddress[ipLen] = '\0';
-        }
-        else if (!ipLen && (len <  sizeof(outAddress->ipAddress)))
-        {
-            strncpy(outAddress->ipAddress, pAddress, len);
-            outAddress->ipAddress[len] = '\0';
-        }
-        else
-        {
-            LOGE("IP Address too long: %d", ipLen==0 ? len : ipLen);
-            return -1;
-        }
-
-        if (ipLen > 0)
-        {
-            outAddress->port = atoi(pAddress + ipLen + 1);
-        }
-    }
-    else
-    {
-        strncpy(outAddress->ipAddress, pAddress, len);
-        outAddress->ipAddress[len] = '\0';
-    }
-
-    return isIp;
-}
-
-void delete_global_references(JNIEnv *env, jobject obj)
-{
-    LOGI("delete_global_references");
-    if (!env || !obj )
-    {
-        LOGI("Invalid input parameter");
-        return;
-    }
-
-    (*env)->DeleteGlobalRef(env, g_responseListenerObject);
-}
-
-
-bool read_file(const char* name, char** bytes, size_t* length)
-{
-    if (NULL == name)
-    {
-        LOGE("parameter is null");
-        return false;
-    }
-
-    FILE* file;
-    char* buffer;
-    size_t fileLen;
-
-    // Open file
-    file = fopen(name, "rt");
-    if (!file)
-    {
-        fprintf(stderr, "Unable to open file %s", name);
-        return false;
-    }
-
-    // Get file length
-    fseek(file, 0, SEEK_END);
-    fileLen = ftell(file);
-    if (-1 == fileLen)
-    {
-        fprintf(stderr, "Failed to read file length");
-        fclose(file);
-        return false;
-    }
-    fseek(file, 0, SEEK_SET);
-
-    LOGI("file size: %d", fileLen);
-
-    // Allocate memory
-    buffer = calloc(1, sizeof(char) * fileLen + 1);
-    if (!buffer)
-    {
-        fprintf(stderr, "Memory error!");
-        fclose(file);
-        return false;
-    }
-
-    // Read file contents into buffer
-    size_t ret = fread(buffer, fileLen, 1, file);
-    if (ret != 1)
-    {
-        printf("Failed to read data from file, %s\n", name);
-        fclose(file);
-        free(buffer);
-        return false;
-    }
-
-    fclose(file);
-
-    LOGI("file bytes: %s", buffer);
-
-    *bytes = buffer;
-    *length = fileLen;
-
-    return true;
-}
-
-void saveFile(const char *payload, size_t payloadSize)
-{
-    // 1. get day
-    uint32_t day = gettodaydate();
-
-    // 2. get time
-    time_t current_time;
-    struct tm * time_info;
-    char timeString[RECEIVED_FILE_NAME_PREFIX_LENGTH];
-
-    time(&current_time);
-    time_info = localtime(&current_time);
-
-    strftime(timeString, sizeof(timeString), "%H%M%S", time_info);
-
-    uint32_t path_length = strlen(RECEIVED_FILE_PATH) + RECEIVED_FILE_NAME_LENGTH + 1;
-    char* path = calloc(1, sizeof(char) * path_length);
-    if (path != NULL)
-    {
-        snprintf(path, path_length, RECEIVED_FILE_PATH, day, timeString);
-        LOGI("received file path: %s", path);
-
-        FILE *fp = fopen(path, "wt");
-        fwrite(payload, 1, payloadSize, fp);
-        fclose(fp);
-
-        callback("File Path: ", path);
-    }
-    else
-    {
-        LOGE("path Out of memory");
-    }
-}
-
-uint32_t gettodaydate()
-{
-    uint32_t ldate;
-    time_t clock;
-    struct tm *date;
-
-    clock = time(0);
-    date = localtime(&clock);
-    ldate = date->tm_year * 100000;
-    ldate += (date->tm_mon + 1) * 1000;
-    ldate += date->tm_mday * 10;
-    ldate += date->tm_wday;
-    ldate += 190000000;
-    ldate /= 10;
-
-    return(ldate);
-}
diff --git a/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/jni/org_iotivity_ca_service_RMInterface.h b/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/jni/org_iotivity_ca_service_RMInterface.h
deleted file mode 100644 (file)
index 48f82f8..0000000
+++ /dev/null
@@ -1,118 +0,0 @@
-#include <jni.h>
-/* Header for class org_iotivity_ca_service_RMInterface */
-
-#ifndef _Included_org_iotivity_ca_service_RMInterface
-#define _Included_org_iotivity_ca_service_RMInterface
-#ifdef __cplusplus
-extern "C" {
-#endif
-JNIEXPORT void JNICALL Java_org_iotivity_ca_service_RMInterface_setNativeResponseListener
-  (JNIEnv *, jobject, jobject);
-/*
- * Class:     org_iotivity_ca_service_RMInterface
- * Method:    RMInitialize
- * Signature: (Landroid/content/Context;)V
- */
-JNIEXPORT void JNICALL Java_org_iotivity_ca_service_RMInterface_RMInitialize
-  (JNIEnv *, jobject, jobject);
-
-/*
- * Class:     org_iotivity_ca_service_RMInterface
- * Method:    RMTerminate
- * Signature: ()V
- */
-JNIEXPORT void JNICALL Java_org_iotivity_ca_service_RMInterface_RMTerminate
-  (JNIEnv *, jobject);
-
-/*
- * Class:     org_iotivity_ca_service_RMInterface
- * Method:    RMStartListeningServer
- * Signature: ()V
- */
-JNIEXPORT void JNICALL Java_org_iotivity_ca_service_RMInterface_RMStartListeningServer
-  (JNIEnv *, jobject);
-
-/*
- * Class:     org_iotivity_ca_service_RMInterface
- * Method:    RMStartDiscoveryServer
- * Signature: ()V
- */
-JNIEXPORT void JNICALL Java_org_iotivity_ca_service_RMInterface_RMStartDiscoveryServer
-  (JNIEnv *, jobject);
-
-/*
- * Class:     org_iotivity_ca_service_RMInterface
- * Method:    RMRegisterHandler
- * Signature: ()V
- */
-JNIEXPORT void JNICALL Java_org_iotivity_ca_service_RMInterface_RMRegisterHandler
-  (JNIEnv *, jobject);
-
-/*
- * Class:     org_iotivity_ca_service_RMInterface
- * Method:    RMSendRequest
- * Signature: (Ljava/lang/String;Ljava/lang/String;III)V
- */
-JNIEXPORT void JNICALL Java_org_iotivity_ca_service_RMInterface_RMSendRequest
-  (JNIEnv *, jobject, jstring, jstring, jint, jint, jint, jboolean);
-
-/*
- * Class:     org_iotivity_ca_service_RMInterface
- * Method:    RMSendReqestToAll
- * Signature: (Ljava/lang/String;I)V
- */
-JNIEXPORT void JNICALL Java_org_iotivity_ca_service_RMInterface_RMSendReqestToAll
-  (JNIEnv *, jobject, jstring, jint);
-
-/*
- * Class:     org_iotivity_ca_service_RMInterface
- * Method:    RMSendResponse
- * Signature: (IIII)V
- */
-JNIEXPORT void JNICALL Java_org_iotivity_ca_service_RMInterface_RMSendResponse
-  (JNIEnv *, jobject, jint, jint, jint, jint);
-
-/*
- * Class:     org_iotivity_ca_service_RMInterface
- * Method:    RMSendNotification
- * Signature: (Ljava/lang/String;Ljava/lang/String;IIII)V
- */
-JNIEXPORT void JNICALL Java_org_iotivity_ca_service_RMInterface_RMSendNotification
-  (JNIEnv *, jobject, jstring, jstring, jint, jint, jint);
-
-/*
- * Class:     org_iotivity_ca_service_RMInterface
- * Method:    RMSelectNetwork
- * Signature: (I)V
- */
-JNIEXPORT void JNICALL Java_org_iotivity_ca_service_RMInterface_RMSelectNetwork
-  (JNIEnv *, jobject, jint);
-
-/*
- * Class:     org_iotivity_ca_service_RMInterface
- * Method:    RMUnSelectNetwork
- * Signature: (I)V
- */
-JNIEXPORT void JNICALL Java_org_iotivity_ca_service_RMInterface_RMUnSelectNetwork
-  (JNIEnv *, jobject, jint);
-
-/*
- * Class:     org_iotivity_ca_service_RMInterface
- * Method:    RMGetNetworkInfomation
- * Signature: ()V
- */
-JNIEXPORT void JNICALL Java_org_iotivity_ca_service_RMInterface_RMGetNetworkInfomation
-  (JNIEnv *, jobject);
-
-/*
- * Class:     org_iotivity_ca_service_RMInterface
- * Method:    RMHandleRequestResponse
- * Signature: ()V
- */
-JNIEXPORT void JNICALL Java_org_iotivity_ca_service_RMInterface_RMHandleRequestResponse
-  (JNIEnv *, jobject);
-
-#ifdef __cplusplus
-}
-#endif
-#endif
diff --git a/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/res/layout/activity_main.xml b/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/res/layout/activity_main.xml
deleted file mode 100755 (executable)
index 69642b6..0000000
+++ /dev/null
@@ -1,265 +0,0 @@
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:tools="http://schemas.android.com/tools"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent"
-    android:paddingBottom="@dimen/activity_vertical_margin"
-    android:paddingLeft="@dimen/activity_horizontal_margin"
-    android:paddingRight="@dimen/activity_horizontal_margin"
-    android:paddingTop="@dimen/activity_vertical_margin"
-    tools:context="org.iotivity.ca.service.MainActivity" >
-
-    <RelativeLayout
-        android:id="@+id/sample_service_layout"
-        android:layout_width="fill_parent"
-        android:layout_height="wrap_content"
-        android:layout_alignParentTop="true"
-        android:background="#cccccc" >
-
-        <LinearLayout
-            android:id="@+id/layout_mode"
-            android:layout_width="fill_parent"
-            android:layout_height="wrap_content"
-            android:layout_alignParentTop="true"
-            android:orientation="horizontal" >
-
-            <TextView
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content" />
-
-            <TextView
-                android:id="@+id/tv_mode"
-                android:layout_width="fill_parent"
-                android:layout_height="wrap_content" />
-        </LinearLayout>
-
-        <RelativeLayout
-            android:id="@+id/layout_network"
-            android:layout_width="fill_parent"
-            android:layout_height="wrap_content"
-            android:layout_below="@id/layout_mode"
-            android:orientation="horizontal" >
-
-            <TextView
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content" />
-
-            <TextView
-                android:id="@+id/tv_network"
-                android:layout_width="fill_parent"
-                android:layout_height="wrap_content" />
-        </RelativeLayout>
-
-        <RelativeLayout
-            android:id="@+id/layout_Response_Noti_title"
-            android:layout_width="fill_parent"
-            android:layout_height="wrap_content"
-            android:layout_below="@id/layout_mode" >
-
-            <TextView
-                android:id="@+id/tv_Response_Noti"
-                android:layout_width="fill_parent"
-                android:layout_height="wrap_content"
-                android:text="[Send Response / Send Notification]"
-                />
-
-        </RelativeLayout>
-
-        <RelativeLayout
-            android:id="@+id/layout_notify"
-            android:layout_width="fill_parent"
-            android:layout_height="wrap_content"
-            android:layout_below="@id/layout_Response_Noti_title" >
-
-            <EditText
-                android:id="@+id/et_notification"
-                android:layout_width="fill_parent"
-                android:layout_height="wrap_content"
-                android:layout_alignParentRight="true"
-                android:text="@string/notification" />
-        </RelativeLayout>
-
-        <RelativeLayout
-            android:id="@+id/layout_request_setting_for_server"
-            android:layout_width="fill_parent"
-            android:layout_height="wrap_content"
-            android:layout_below="@id/layout_notify" >
-
-            <Button
-                android:id="@+id/btn_Request_setting_for_server"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_alignParentLeft="true"
-                android:text="@string/request_setting" />
-
-            <Button
-                android:id="@+id/btn_notify"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_toRightOf="@id/btn_Request_setting_for_server"
-                android:text="@string/notify" />
-
-            <Button
-                android:id="@+id/btn_sendresponse"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_toRightOf="@id/btn_notify"
-                android:text="@string/sendresponse" />
-        </RelativeLayout>
-
-        <RelativeLayout
-            android:id="@+id/layout_request_title"
-            android:layout_width="fill_parent"
-            android:layout_height="wrap_content"
-            android:layout_below="@id/layout_mode" >
-
-            <TextView
-                android:id="@+id/tv_request"
-                android:layout_width="fill_parent"
-                android:layout_height="wrap_content"
-                android:text="[Send Request]" />
-
-        </RelativeLayout>
-
-        <RelativeLayout
-            android:id="@+id/layout_request"
-            android:layout_width="fill_parent"
-            android:layout_height="wrap_content"
-            android:layout_below="@id/layout_request_title" >
-
-            <EditText
-                android:id="@+id/et_req_data"
-                android:layout_width="fill_parent"
-                android:layout_height="wrap_content"
-                android:layout_centerVertical="true"
-                android:text="@string/req_data" />
-        </RelativeLayout>
-
-        <RelativeLayout
-            android:id="@+id/layout_request_setting_for_client"
-            android:layout_width="fill_parent"
-            android:layout_height="wrap_content"
-            android:layout_below="@id/layout_request" >
-
-            <Button
-                android:id="@+id/btn_Request_setting_for_client"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_alignParentLeft="true"
-                android:text="@string/request_setting" />
-
-            <Button
-                android:id="@+id/btn_Request"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_toRightOf="@id/btn_Request_setting_for_client"
-                android:text="@string/request" />
-
-        </RelativeLayout>
-
-        <RelativeLayout
-            android:id="@+id/layout_request_to_all_title"
-            android:layout_width="fill_parent"
-            android:layout_height="wrap_content"
-            android:layout_below="@id/layout_request_setting_for_client" >
-
-            <TextView
-                android:id="@+id/tv_request_to_all"
-                android:layout_width="fill_parent"
-                android:layout_height="wrap_content" 
-                android:text="[Send Request to All]"
-                />
-
-         </RelativeLayout>
-
-        <RelativeLayout
-            android:id="@+id/layout_request_to_all"
-            android:layout_width="fill_parent"
-            android:layout_height="wrap_content"
-            android:layout_below="@id/layout_request_to_all_title" >
-
-            <EditText
-                android:id="@+id/et_req_to_all_data"
-                android:layout_width="fill_parent"
-                android:layout_height="wrap_content"
-                android:layout_centerVertical="true"
-                android:text="@string/uri" />
-        </RelativeLayout>
-
-        <RelativeLayout
-            android:id="@+id/layout_request_to_all_setting_for_client"
-            android:layout_width="fill_parent"
-            android:layout_height="wrap_content"
-            android:layout_below="@id/layout_request_to_all" >
-
-            <Button
-                android:id="@+id/btn_request_to_all_setting_for_client"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_alignParentLeft="true"
-                android:text="@string/request_setting" />
-
-            <Button
-                android:id="@+id/btn_request_to_all"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_toRightOf="@id/btn_request_to_all_setting_for_client"
-                android:text="@string/request_to_all" />
-        </RelativeLayout>
-
-        <RelativeLayout
-            android:id="@+id/layout_handle_title"
-            android:layout_width="fill_parent"
-            android:layout_height="wrap_content"
-            android:layout_below="@id/layout_request_to_all_setting_for_client" >
-
-            <TextView
-                android:id="@+id/tv_handle"
-                android:layout_width="fill_parent"
-                android:layout_height="wrap_content"
-                android:text="[Handle Reqeust,Response data / Get NetworkInfo]"/>
-        </RelativeLayout>
-
-        <RelativeLayout
-            android:id="@+id/layout_receive"
-            android:layout_width="fill_parent"
-            android:layout_height="wrap_content"
-            android:layout_below="@id/layout_handle_title" >
-
-            <Button
-                android:id="@+id/btn_receive"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_alignParentLeft="true"
-                android:text="@string/receive" />
-
-            <Button
-                android:id="@+id/btn_get_network_info"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_toRightOf="@id/btn_receive"
-                android:text="@string/get_network_info" />
-
-            <Button
-                android:id="@+id/btn_big_data"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_toRightOf="@id/btn_get_network_info"
-                android:text="big data" />
-
-        </RelativeLayout>
-    </RelativeLayout>
-
-    <ScrollView
-        android:id="@+id/sv_result_scoll"
-        android:layout_width="fill_parent"
-        android:layout_height="fill_parent"
-        android:layout_below="@id/sample_service_layout"
-        android:layout_marginTop="10pt" >
-
-        <TextView
-            android:id="@+id/tv_result"
-            android:layout_width="fill_parent"
-            android:layout_height="wrap_content" />
-    </ScrollView>
-
-</RelativeLayout>
\ No newline at end of file
diff --git a/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/res/menu/main.xml b/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/res/menu/main.xml
deleted file mode 100755 (executable)
index e0d03f4..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-<menu xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:tools="http://schemas.android.com/tools"
-    tools:context="org.iotivity.ca.sample_service.MainActivity" >
-
-    <item
-        android:id="@+id/action_settings"
-        android:orderInCategory="100"
-        android:showAsAction="never"
-        android:title="@string/action_settings"/>
-
-</menu>
-
diff --git a/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/res/values-v11/styles.xml b/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/res/values-v11/styles.xml
deleted file mode 100755 (executable)
index 3df0c14..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-<resources>
-
-    <!--
-        Base application theme for API 11+. This theme completely replaces
-        AppBaseTheme from res/values/styles.xml on API 11+ devices.
-    -->
-    <style name="AppBaseTheme" parent="android:Theme.Holo.Light">
-        <!-- API 11 theme customizations can go here. -->
-    </style>
-
-</resources>
-
diff --git a/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/res/values-v14/styles.xml b/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/res/values-v14/styles.xml
deleted file mode 100755 (executable)
index 13d7045..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-<resources>
-
-    <!--
-        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.
-    -->
-    <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
-        <!-- API 14 theme customizations can go here. -->
-    </style>
-
-</resources>
-
diff --git a/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/res/values-w820dp/dimens.xml b/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/res/values-w820dp/dimens.xml
deleted file mode 100755 (executable)
index efaa062..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-<resources>
-
-    <!--
-         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).
-    -->
-    <dimen name="activity_horizontal_margin">64dp</dimen>
-
-</resources>
-
diff --git a/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/res/values/dimens.xml b/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/res/values/dimens.xml
deleted file mode 100755 (executable)
index 6ed10f5..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-<resources>
-
-    <!-- Default screen margins, per the Android Design guidelines. -->
-    <dimen name="activity_horizontal_margin">16dp</dimen>
-    <dimen name="activity_vertical_margin">16dp</dimen>
-
-</resources>
-
diff --git a/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/res/values/strings.xml b/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/res/values/strings.xml
deleted file mode 100755 (executable)
index 1dcde2c..0000000
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
-
-    <string name="app_name">CA Android Sample</string>
-    <string name="sendresponse">Response</string>
-    <string name="notify">Notification</string>
-    <string name="request_setting">Setting</string>
-    <string name="request">Request</string>
-    <string name="request_to_all">Request to All</string>
-    <string name="response">Response</string>
-    <string name="uri">/a/light</string>
-    <string name="coap_prefix">coap://</string>
-    <string name="notification"></string>
-    <string name="req_data"></string>
-    <string name="resp_data">resourceUri/response</string>
-    <string name="get_network_info">Network Info</string>
-    <string name="receive">Receive</string>
-    <string name="received">Received Message</string>
-    <string name="remote_address">"Remote Address: "</string>
-    <string name="remote_port">"Remote Port: "</string>
-    <string name="action_settings">Settings</string>
-</resources>
\ No newline at end of file
diff --git a/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/res/values/styles.xml b/resource/csdk/connectivity/samples/android/casample/sampleService/src/main/res/values/styles.xml
deleted file mode 100755 (executable)
index d77df4e..0000000
+++ /dev/null
@@ -1,21 +0,0 @@
-<resources>
-
-    <!--
-        Base application theme, dependent on API level. This theme is replaced
-        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-    -->
-    <style name="AppBaseTheme" parent="android:Theme.Light">
-        <!--
-            Theme customizations available in newer API levels can go in
-            res/values-vXX/styles.xml, while customizations related to
-            backward-compatibility can go here.
-        -->
-    </style>
-
-    <!-- Application theme. -->
-    <style name="AppTheme" parent="AppBaseTheme">
-        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
-    </style>
-
-</resources>
-
diff --git a/resource/csdk/connectivity/samples/android/casample/settings.gradle b/resource/csdk/connectivity/samples/android/casample/settings.gradle
deleted file mode 100644 (file)
index 97b651e..0000000
+++ /dev/null
@@ -1,2 +0,0 @@
-include ':cAInterface'
-include ':sampleService'
diff --git a/resource/csdk/connectivity/samples/arduino/SConscript b/resource/csdk/connectivity/samples/arduino/SConscript
deleted file mode 100644 (file)
index 0722421..0000000
+++ /dev/null
@@ -1,30 +0,0 @@
-Import('env')
-
-sample_env= env.Clone()
-root_dir = './../../'
-
-sample_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-sample_env.PrependUnique(LIBS = ['connectivity_abstraction', 'coap'])
-
-sample_env.PrependUnique(CPPPATH = [root_dir + '/api/'])
-sample_env.AppendUnique(CPPPATH = [root_dir + '/inc/'])
-sample_env.AppendUnique(CPPPATH = [root_dir + '/lib/libcoap-4.1.1/'])
-sample_env.AppendUnique(CPPPATH = [root_dir + 'common/inc/'])
-
-if env.get('SHIELD') == 'WIFI':
-       sample_env.AppendUnique(CPPDEFINES = ['ARDUINOWIFI'])
-elif env.get('SHIELD') == 'ETH':
-       sample_env.AppendUnique(CPPDEFINES = ['ARDUINOETH'])
-
-sample_dir = './samples/arduino/'
-arduino_simplecs = sample_env.Program('CASample', 'casample.cpp')
-env.CreateBin('CASample')
-
-i_arduino_simplecs = sample_env.Install(env.get('BUILD_DIR'), arduino_simplecs)
-
-Alias('arduino_simplecs', i_arduino_simplecs)
-sample_env.Default('CASample.hex')
-
-if(sample_env['UPLOAD'] == True):
-       sample_env.Upload(env.get('BUILD_DIR') + 'resource/csdk/connectivity/samples/arduino/' + 'CASample.hex')
-
diff --git a/resource/csdk/connectivity/samples/arduino/casample.cpp b/resource/csdk/connectivity/samples/arduino/casample.cpp
deleted file mode 100644 (file)
index 273ed08..0000000
+++ /dev/null
@@ -1,874 +0,0 @@
-/******************************************************************
- *
- * Copyright 2014 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 <ctype.h>
-#include <errno.h>
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "cacommon.h"
-#include "cainterface.h"
-#include "Arduino.h"
-
-#ifdef ARDUINOWIFI
-#include "WiFi.h"
-#elif defined ARDUINOETH
-#include "Ethernet.h"
-#endif
-
-#include "oic_malloc.h"
-
-#define MAX_BUF_LEN 100 //1024
-#define MAX_OPT_LEN 16
-#define PORT_LENGTH 5
-
-static bool g_isLeSelected = false;
-
-static void PrintMenu();
-static void Process();
-static void Initialize();
-static void StartListeningServer();
-static void StartDiscoveryServer();
-static void SendRequest();
-static void SendRequestAll();
-static void SendResponse(CAEndpoint_t *endpoint, const CAInfo_t* info);
-static void SendNotification();
-static void SelectNetwork();
-static void UnselectNetwork();
-static void HandleRequestResponse();
-static void GetNetworkInfo();
-
-static void RequestHandler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo);
-static void ResponseHandler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo);
-static void ErrorHandler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
-static void Terminate();
-
-void GetData(char *readInput, size_t bufferLength, size_t *dataLength)
-{
-    if (!readInput || bufferLength == 0 || !dataLength)
-    {
-        Serial.println("Invalid buffer");
-        return;
-    }
-
-    while (!Serial.available())
-    {
-        delay(500);
-    }
-    int len = 0;
-    while (Serial.available())
-    {
-        delay(100);
-        char c = Serial.read();
-        if ('\n' != c && '\r' != c && len < bufferLength - 1)
-        {
-            readInput[len++] = c;
-        }
-        else
-        {
-            break;
-        }
-    }
-
-    readInput[len] = '\0';
-    Serial.flush();
-    Serial.print("PD: ");
-    Serial.println(readInput);
-    (*dataLength) = len;
-}
-
-bool ParseData(char *buf, char *url, char *port, char *resourceUri)
-{
-    char *slash = strchr(buf, '/');
-    if (!slash)
-    {
-        return false;
-    }
-
-    strcpy(resourceUri, slash);
-
-    char *dot = strchr(buf, '.');
-    if (dot && dot < slash)
-    {
-        char *colon = strchr(buf, ':');
-
-        if (colon)
-        {
-            strncpy(port, colon, slash - colon);
-            memmove(port, port+1, strlen(port));
-        }
-        if (colon && colon < slash)
-        {
-            strncpy(url, buf, colon - buf);
-            return true;
-        }
-    }
-
-    strncpy(url, buf, slash - buf);
-    return true;
-}
-
-CATransportAdapter_t GetConnectivityType()
-{
-    char type[2] = {0};
-    Serial.println("Select network");
-    Serial.println("IP: 0");
-    Serial.println("GATT (BLE): 1");
-    Serial.println("RFCOMM (EDR): 2");
-
-    size_t typeLen = 0;
-    GetData(type, sizeof(type), &typeLen);
-    if (0 >= typeLen)
-    {
-        Serial.println("i/p err,default ethernet");
-        return CA_ADAPTER_IP;
-    }
-    switch (type[0])
-    {
-        case '0':
-            return CA_ADAPTER_IP;
-        case '1':
-            return CA_ADAPTER_GATT_BTLE;
-        case '2':
-            return CA_ADAPTER_RFCOMM_BTEDR;
-    }
-    return CA_ADAPTER_IP;
-}
-
-void setup()
-{
-    Serial.begin (115200);
-
-    Serial.println("============");
-    Serial.println("CA SAMPLE");
-    Serial.println("============");
-    PrintMenu();
-}
-
-void loop()
-{
-    char buffer[5] = {0};
-    size_t len;
-    if (Serial.available() > 0)
-    {
-        GetData(buffer, sizeof(buffer), &len);
-        if (0 >= len)
-        {
-            Serial.println("i/p err");
-            return;
-        }
-        switch (toupper(buffer[0]))
-        {
-            case 'M': // menu
-                PrintMenu();
-                break;
-
-            case 'Q': // quit
-                Serial.println("quit");
-                return;
-
-            case 'I': // Initialize interface
-                Initialize();
-                break;
-
-            case 'S': // start listening server
-                StartListeningServer();
-                break;
-
-            case 'D': // start discovery server
-                StartDiscoveryServer();
-                break;
-
-            case 'R': // send request
-                SendRequest();
-                break;
-
-            case 'E': //send request to all
-                SendRequestAll();
-                break;
-            case 'B': // send notification
-                SendNotification();
-                break;
-            case 'G': // Get network info
-                GetNetworkInfo();
-                break;
-
-            case 'N': // select network
-                SelectNetwork();
-                break;
-
-            case 'X': // unselect network
-                UnselectNetwork();
-                break;
-
-            case 'H': // handle request response
-                HandleRequestResponse();
-                break;
-
-            case 'T': // handle request response
-                Terminate();
-                break;
-
-            default:
-                Serial.println("wrong menu");
-                break;
-        }
-    }
-    //1:Add check for startserver before calling below api
-    if (g_isLeSelected)
-    {
-        HandleRequestResponse();
-    }
-    delay(1000);
-}
-
-void Initialize()
-{
-    if(CAInitialize() != CA_STATUS_OK)
-    {
-        Serial.println("Initialize failed");
-        return;
-    }
-    SelectNetwork();
-    // set handler.
-    CARegisterHandler(RequestHandler, ResponseHandler, ErrorHandler);
-}
-
-void StartListeningServer()
-{
-    Serial.println("listening server");
-    CAResult_t ret = CAStartListeningServer();
-    if(ret != CA_STATUS_OK)
-    {
-        Serial.print("listening failed: ");
-        Serial.println(ret);
-        return;
-    }
-}
-
-void StartDiscoveryServer()
-{
-    Serial.println("discovery server");
-    CAResult_t ret = CAStartDiscoveryServer();
-    if(ret != CA_STATUS_OK)
-    {
-        Serial.print("discovery failed: ");
-        Serial.println(ret);
-        return;
-    }
-}
-
-void SendRequest()
-{
-    char buf[MAX_BUF_LEN] = {0};
-    char address[MAX_BUF_LEN] = {0};
-    char resourceUri[MAX_BUF_LEN] = {0};
-    char port[PORT_LENGTH] = {0};
-    CATransportAdapter_t selectedNetwork;
-    selectedNetwork = GetConnectivityType();
-
-    Serial.println("============");
-    Serial.println("10.11.12.13:4545/res_uri (for IP)");
-    Serial.println("10:11:12:13:45:45/res_uri (for BT)");
-    Serial.println("uri: ");
-
-    size_t len = 0;
-    GetData(buf, sizeof(buf), &len);
-    if (0 >= len)
-    {
-        Serial.println("i/p err");
-        return;
-    }
-
-    if (!ParseData(buf, address, port, resourceUri))
-    {
-        Serial.println("bad uri");
-        return;
-    }
-
-    // create remote endpoint
-    CAEndpoint_t *endpoint = NULL;
-    CAResult_t res = CACreateEndpoint(CA_DEFAULT_FLAGS, selectedNetwork, address, atoi(port),
-                                      &endpoint);
-    if (res != CA_STATUS_OK)
-    {
-        Serial.println("Out of memory");
-        CADestroyEndpoint(endpoint);
-        return;
-    }
-
-    memset(buf, 0, sizeof(buf));
-
-    Serial.println("\n=============================================\n");
-    Serial.println("0:CON, 1:NON\n");
-    Serial.println("select message type : ");
-    GetData(buf, sizeof(buf), &len);
-    CAMessageType_t msgType = CA_MSG_CONFIRM;
-
-    if (0 >= len)
-    {
-        Serial.println("i/p err,default: 0");
-    }
-    else if(buf[0] == '1')
-    {
-        msgType = CA_MSG_NONCONFIRM;
-    }
-
-    // create token
-    CAToken_t token = NULL;
-    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
-
-    res = CAGenerateToken(&token, tokenLength);
-    if (res != CA_STATUS_OK || (!token))
-    {
-        Serial.println("token error");
-        CADestroyEndpoint(endpoint);
-        return;
-    }
-
-    Serial.println(token);
-    CAInfo_t requestData = {CA_MSG_RESET};
-    requestData.token = token;
-    requestData.tokenLength = tokenLength;
-    requestData.payload = (CAPayload_t)"Json Payload";
-    requestData.payloadSize = strlen((const char *) requestData.payload);
-
-    requestData.type = msgType;
-    requestData.resourceUri = (char *)OICMalloc(strlen(resourceUri) + 1);
-    strcpy(requestData.resourceUri, resourceUri);
-
-    CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
-    requestInfo.method = CA_GET;
-    requestInfo.isMulticast = false;
-    requestInfo.info = requestData;
-    requestInfo.isMulticast = false;
-
-    // send request
-    CASendRequest(endpoint, &requestInfo);
-    if (NULL != token)
-    {
-        CADestroyToken(token);
-    }
-
-    // destroy remote endpoint
-    if (endpoint != NULL)
-    {
-        CADestroyEndpoint(endpoint);
-    }
-
-    Serial.println("============");
-}
-
-void SendRequestAll()
-{
-    char buf[MAX_BUF_LEN] = {0};
-    char address[MAX_BUF_LEN] = {0};
-    char resourceUri[MAX_BUF_LEN] = {0};
-    char port[PORT_LENGTH] = {0};
-
-    CATransportAdapter_t selectedNetwork;
-    selectedNetwork = GetConnectivityType();
-
-    Serial.println("\n=============================================\n");
-    Serial.println("ex) /a/light\n");
-    Serial.println("resource uri : ");
-
-    size_t len = 0;
-    GetData(buf, sizeof(buf), &len);
-    if (0 >= len)
-    {
-        Serial.println("i/p err");
-        return;
-    }
-
-    if (!ParseData(buf, address, port, resourceUri))
-    {
-        Serial.println("bad uri");
-        return;
-    }
-
-    // create remote endpoint
-    CAEndpoint_t *endpoint = NULL;
-    CAResult_t res = CACreateEndpoint(CA_IPV4, selectedNetwork, address, atoi(port),
-                                        &endpoint);
-
-    if (res != CA_STATUS_OK)
-    {
-        Serial.println("create remote endpoint error");
-        CADestroyEndpoint(endpoint);
-        return;
-    }
-
-    // create token
-    CAToken_t token = NULL;
-    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
-
-    res = CAGenerateToken(&token, tokenLength);
-    if (res != CA_STATUS_OK || (!token))
-    {
-        Serial.println("token error");
-        CADestroyEndpoint(endpoint);
-        return;
-    }
-
-    Serial.println(token);
-
-    CAInfo_t requestData = {CA_MSG_RESET};
-    requestData.token = token;
-    requestData.tokenLength = tokenLength;
-    requestData.payload = (CAPayload_t)"Temp Json Payload";
-    requestData.payloadSize = strlen((const char *) requestData.payload);
-    requestData.type = CA_MSG_NONCONFIRM;
-    requestData.resourceUri = (char *)OICMalloc(strlen(resourceUri) + 1);
-    strcpy(requestData.resourceUri, resourceUri);
-
-    CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
-    requestInfo.method = CA_GET;
-    requestInfo.isMulticast = true;
-    requestInfo.info = requestData;
-
-    // send request
-    CASendRequest(endpoint, &requestInfo);
-
-    if (NULL != token)
-    {
-        CADestroyToken(token);
-    }
-
-    // destroy remote endpoint
-    if (endpoint != NULL)
-    {
-        CADestroyEndpoint(endpoint);
-    }
-
-    Serial.println("==========");
-}
-
-void SendNotification()
-{
-    char buf[MAX_BUF_LEN] = {0};
-    char address[MAX_BUF_LEN] = {0};
-    char resourceUri[MAX_BUF_LEN] = {0};
-    char port[PORT_LENGTH] = {0};
-    CATransportAdapter_t selectedNetwork;
-    selectedNetwork = GetConnectivityType();
-
-    Serial.println("============");
-    Serial.println("10.11.12.13:4545/res_uri (for IP)");
-    Serial.println("10:11:12:13:45:45/res_uri (for BT)");
-    Serial.println("uri: ");
-
-    size_t len = 0;
-    GetData(buf, sizeof(buf), &len);
-    if (0 >= len)
-    {
-        Serial.println("i/p err");
-        return;
-    }
-
-    if (!ParseData(buf, address, port, resourceUri))
-    {
-        Serial.println("bad uri");
-        return;
-    }
-
-    // create remote endpoint
-    CAEndpoint_t *endpoint = NULL;
-    CAResult_t res = CACreateEndpoint(CA_DEFAULT_FLAGS, selectedNetwork, address, atoi(port),
-                                      &endpoint);
-    if (CA_STATUS_OK != res)
-    {
-        Serial.println("Out of memory");
-        CADestroyEndpoint(endpoint);
-        return;
-    }
-
-    // create token
-    CAToken_t token = NULL;
-    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
-
-    res = CAGenerateToken(&token, tokenLength);
-    if (res != CA_STATUS_OK || (!token))
-    {
-        Serial.println("token error");
-        CADestroyEndpoint(endpoint);
-        return;
-    }
-
-    CAInfo_t requestData = {CA_MSG_NONCONFIRM};
-    requestData.token = token;
-    requestData.tokenLength = tokenLength;
-    requestData.payload = (CAPayload_t)"Notification Data";
-    requestData.payloadSize = strlen((const char *) requestData.payload);
-    requestData.resourceUri = (char *)OICMalloc(strlen(resourceUri) + 1);
-    strcpy(requestData.resourceUri, resourceUri);
-
-    CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
-    requestInfo.method = CA_GET;
-    requestInfo.info = requestData;
-
-    // send request
-    CASendRequest(endpoint, &requestInfo);
-    // destroy remote endpoint
-    if (NULL != endpoint)
-    {
-        CADestroyEndpoint(endpoint);
-    }
-
-    CADestroyToken(token);
-    Serial.println("============");
-}
-
-void SelectNetwork()
-{
-    char buf[MAX_BUF_LEN] = {0};
-
-    Serial.println("============");
-    Serial.println("Select network");
-    Serial.println("IP: 0");
-    Serial.println("LE: 1");
-    Serial.println("EDR: 2\n");
-
-    size_t len = 0;
-    GetData(buf, sizeof(buf), &len);
-    int number = buf[0] - '0';
-    if (0 >= len || number < 0 || number > 3)
-    {
-        Serial.println("Wrong i/p. WIFI selected");
-        number = 1;
-    }
-
-    switch (number)
-    {
-        case 0:
-            {
-#ifdef ARDUINOWIFI
-                const char ssid[] = "SSID";              // your network SSID (name)
-                const char pass[] = "SSID_Password";     // your network password
-                int16_t status = WL_IDLE_STATUS;         // the Wifi radio's status
-
-                if (WiFi.status() == WL_NO_SHIELD)
-                {
-                    Serial.println("ERROR:No Shield");
-                    return;
-                }
-
-                while (status != WL_CONNECTED)
-                {
-                    Serial.print("connecting: ");
-                    Serial.println(ssid);
-                    // WiFi.begin api is weird. ssid should also be taken as const char *
-                    // Connect to WPA/WPA2 network:
-                    status = WiFi.begin((char *)ssid, pass);
-                }
-#elif defined ARDUINOETH
-                // Note: ****Update the MAC address here with your shield's MAC address****
-                uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0E, 0xC4, 0x05};
-                uint8_t error = Ethernet.begin(ETHERNET_MAC);
-                if (error  == 0)
-                {
-                    Serial.print("Failed: ");
-                    Serial.println(error);
-                    return;
-                }
-#endif
-            }
-            break;
-        case 1:
-            g_isLeSelected = true;
-            break;
-        case 2:
-            // Nothing TBD here
-            break;
-    }
-
-    CASelectNetwork(CATransportAdapter_t(1<<number));
-    Serial.println("============");
-}
-
-void UnselectNetwork()
-{
-    char buf[MAX_BUF_LEN] = {0};
-
-    Serial.println("============");
-    Serial.println("Unselect network");
-    Serial.println("IPv4: 0");
-    Serial.println("LE: 1");
-    Serial.println("EDR: 2\n");
-
-    size_t len = 0;
-    GetData(buf, sizeof(buf), &len);
-    int number = buf[0] - '0';
-    Serial.println(number);
-    if (0 >= len || number < 0 || number > 3)
-    {
-        Serial.println("Wrong i/p. WIFI selected");
-        number = 1;
-    }
-    if (number == 3)
-    {
-        g_isLeSelected = false;
-    }
-    CAUnSelectNetwork((CATransportAdapter_t)(1 << number));
-    Serial.println("Terminate");
-    CATerminate();
-    Serial.println("============");
-}
-
-void GetNetworkInfo()
-{
-    CAEndpoint_t *tempInfo = NULL;
-    uint32_t tempSize = 0;
-    CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
-    if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize)
-    {
-        Serial.println("Network not connected");
-        free(tempInfo);
-        return;
-    }
-    Serial.println("=========");
-    Serial.print("Network info total size is ");
-    Serial.println(tempSize);
-    int index;
-    for (index = 0; index < tempSize; index++)
-    {
-        Serial.print("Type: ");
-        Serial.println(tempInfo[index].adapter);
-        if (CA_ADAPTER_IP == tempInfo[index].adapter)
-        {
-            Serial.print("Address: ");
-            Serial.println(tempInfo[index].addr);
-            Serial.print("Port: ");
-            Serial.println(tempInfo[index].port);
-        }
-    }
-    free(tempInfo);
-    Serial.println("=======");
-}
-
-void PrintMenu()
-{
-
-    Serial.println("============");
-    Serial.println("i: Initialize");
-    Serial.println("s: start listening server");
-    Serial.println("d: start discovery server");
-    Serial.println("r: send request");
-    Serial.println("e: send request to all");
-    Serial.println("b: send notification");
-    Serial.println("g: get network info");
-    Serial.println("n: select network");
-    Serial.println("x: unselect network");
-    Serial.println("h: handle request response");
-    Serial.println("t: terminate");
-    Serial.println("q: quit");
-    Serial.println("============");
-}
-
-void HandleRequestResponse()
-{
-    CAHandleRequestResponse();
-}
-
-void RequestHandler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo)
-{
-    if (!object)
-    {
-        Serial.println("endpoint is NULL!");
-        return;
-    }
-
-    if (!requestInfo)
-    {
-        Serial.println("Request info is NULL!");
-        return;
-    }
-
-    Serial.print("RAddr: ");
-    Serial.println(object->addr);
-    Serial.print("Port: ");
-    Serial.println(object->port);
-    Serial.print("uri: ");
-    Serial.println(requestInfo->info.resourceUri);
-    Serial.print("data: ");
-    Serial.println((char*)requestInfo->info.payload);
-    Serial.print("data size: ");
-    Serial.println(requestInfo->info.payloadSize);
-    Serial.print("Type: ");
-    Serial.println(requestInfo->info.type);
-
-    if (requestInfo->info.options)
-    {
-        uint32_t len = requestInfo->info.numOptions;
-        uint32_t i;
-        for (i = 0; i < len; i++)
-        {
-            Serial.print("Option: ");
-            Serial.println(i+1);
-            Serial.print("ID: ");
-            Serial.println(requestInfo->info.options[i].optionID);
-            Serial.print("Data: ");
-            Serial.println((char*)requestInfo->info.options[i].optionData);
-        }
-    }
-    Serial.println("send response");
-    SendResponse((CAEndpoint_t *)object, (requestInfo != NULL) ? &requestInfo->info : NULL);
-}
-
-void ResponseHandler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
-{
-    if (object)
-    {
-        Serial.print("uri: ");
-        Serial.println(object->addr);
-    }
-
-    if (responseInfo)
-    {
-        Serial.print("uri: ");
-        Serial.println(responseInfo->info.resourceUri);
-        Serial.print("data: ");
-        Serial.println((char*)responseInfo->info.payload);
-        Serial.print("data size: ");
-        Serial.println(responseInfo->info.payloadSize);
-        Serial.print("Type: ");
-        Serial.println(responseInfo->info.type);
-        Serial.print("res result=");
-        Serial.println(responseInfo->result);
-    }
-}
-
-void ErrorHandler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
-{
-    Serial.println("ErrorInfo");
-
-    if(errorInfo)
-    {
-        const CAInfo_t *info = &errorInfo->info;
-        Serial.print("result: ");
-        Serial.println(errorInfo->result);
-        Serial.print("token: ");
-        Serial.println(info->token);
-        Serial.print("messageId: ");
-        Serial.println(info->messageId);
-        Serial.print("type: ");
-        Serial.println(info->type);
-        Serial.print("resourceUri: ");
-        Serial.println(info->resourceUri);
-        Serial.print("payload: ");
-        Serial.println((char*)info->payload);
-    }
-
-    return;
-}
-
-void SendResponse(CAEndpoint_t *endpoint, const CAInfo_t* info)
-{
-    char buf[MAX_BUF_LEN] = {0};
-
-    Serial.println("============");
-    Serial.println("Select Message Type");
-    Serial.println("CON: 0");
-    Serial.println("NON: 1");
-    Serial.println("ACK: 2");
-    Serial.println("RESET: 3");
-
-    size_t len = 0;
-    int messageType = 0;
-    while(1)
-    {
-        GetData(buf, sizeof(buf), &len);
-        if(len >= 1)
-        {
-            messageType = buf[0] - '0';
-            if (messageType >= 0 && messageType <= 3)
-            {
-                break;
-            }
-        }
-        Serial.println("Invalid type");
-    }
-
-    int respCode = 0;
-    if(messageType != 3)
-    {
-        Serial.println("============");
-        Serial.println("Enter Resp Code:");
-        Serial.println("For Ex: Empty  : 0");
-        Serial.println("Created: 201");
-        Serial.println("Deleted: 202");
-        Serial.println("Valid  : 203");
-        Serial.println("Changed: 204");
-        Serial.println("Content: 205");
-        Serial.println("BadReq : 400");
-        Serial.println("BadOpt : 402");
-        Serial.println("NotFnd : 404");
-        Serial.println("Internal Srv Err:500");
-        Serial.println("Timeout: 504");
-        while(1)
-        {
-            GetData(buf, sizeof(buf), &len);
-            if(len >= 1)
-            {
-                respCode = atoi(buf);
-                if (respCode >= 0 && respCode <= 504)
-                {
-                    break;
-                }
-            }
-            Serial.println("Invalid response");
-        }
-    }
-
-    CAInfo_t responseData = {CA_MSG_RESET};
-    responseData.type = static_cast<CAMessageType_t>(messageType);
-    responseData.messageId = (info != NULL) ? info->messageId : 0;
-    responseData.resourceUri = (info != NULL) ? info->resourceUri : 0;
-    if(messageType != 3)
-    {
-        responseData.token = (info != NULL) ? info->token : NULL;
-        responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
-        responseData.payload = reinterpret_cast<CAPayload_t>(const_cast<char*>("response payload"));
-        responseData.payloadSize = strlen((const char *) responseData.payload);
-    }
-    CAResponseInfo_t responseInfo = {CA_BAD_REQ, {CA_MSG_RESET}};
-    responseInfo.result = static_cast<CAResponseResult_t>(respCode);
-    responseInfo.info = responseData;
-    // send request (transportType from remoteEndpoint of request Info)
-    CAResult_t res = CASendResponse(endpoint, &responseInfo);
-    if(res != CA_STATUS_OK)
-    {
-        Serial.println("Snd Resp error");
-    }
-    else
-    {
-        Serial.println("Snd Resp success");
-    }
-
-    Serial.println("============");
-}
-
-void Terminate()
-{
-    UnselectNetwork();
-}
-
diff --git a/resource/csdk/connectivity/samples/linux/README b/resource/csdk/connectivity/samples/linux/README
deleted file mode 100644 (file)
index bc122b4..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-The build steps used in continuous integration can be found
-in auto_build.sh which is also in the the repository root directory.
-
-Go to the top directory of 'iotivity' project(Note: should always run 'scons'
-command in this directory)
-
-#1. build "connectivity" project (for release mode)
-       - execute 'scons resource/csdk/connectivity/' command
-
-#2. build "example" for linux
-       - execute 'scons resource/csdk/connectivity/samples/linux/' command
-
-#3. execute sample program
-       - you should link the "connectivity_abstraction" library.
-       ex. cd out/linux/x86/release/resource/csdk/connectivity/samples/linux
-           ./casample
-
diff --git a/resource/csdk/connectivity/samples/linux/SConscript b/resource/csdk/connectivity/samples/linux/SConscript
deleted file mode 100644 (file)
index 9bcc7e2..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-##
-# Building sample application
-##
-
-Import('env')
-
-sample_env = env.Clone()
-
-ca_os = sample_env.get('TARGET_OS')
-ca_transport = sample_env.get('TARGET_TRANSPORT')
-secured = sample_env.get('SECURED')
-with_ra = sample_env.get('WITH_RA')
-root_dir = './../../'
-
-#####################################################################
-# Source files and Target(s)
-######################################################################
-
-print"Reading ca script %s"%ca_transport
-
-sample_env.PrependUnique(CPPPATH = [root_dir + '/api/'])
-sample_env.AppendUnique(CPPPATH = [root_dir + '/inc/'])
-sample_env.AppendUnique(CPPPATH = [root_dir + '/lib/libcoap-4.1.1/'])
-sample_env.AppendUnique(CPPPATH = [root_dir + 'common/inc/'])
-
-print "Reading sample application build script"
-
-build_dir = sample_env.get('BUILD_DIR')
-sample_dir = './samples/linux/'
-
-secured = sample_env.get('SECURED')
-
-print "Sample secured flag is %s" % secured
-
-sample_src = ['./sample_main.c',]
-print " sample src %s" % sample_src
-#env.StaticLibrary('casample', sample_src)
-
-sample_env.PrependUnique(LIBPATH = [sample_env.get('BUILD_DIR'), '.'])
-sample_env.PrependUnique(RPATH = [sample_env.get('BUILD_DIR'), '.',])
-sample_env.PrependUnique(LIBS = ['connectivity_abstraction'])
-if with_ra:
-       sample_env.AppendUnique(LIBS = ['ra_xmpp'])
-sample_env.AppendUnique(LIBS = ['coap', 'pthread'])
-
-if ca_os not in ['darwin']:
-       sample_env.PrependUnique(LIBS = ['rt'])
-
-if secured == '1':
-       current_dir=env.get('SRC_DIR')
-       sample_env.AppendUnique(CPPPATH = [root_dir + 'external/inc/'])
-       sample_env.AppendUnique(LIBS = ['tinydtls'])
-       casample =sample_env.Program('casample', [sample_src])
-else:
-       casample =sample_env.Program('casample', [sample_src])
-env.InstallTarget(casample, 'casample')
-env.UserInstallTargetBin(casample, 'casample')
-
-
-
-
diff --git a/resource/csdk/connectivity/samples/linux/sample_main.c b/resource/csdk/connectivity/samples/linux/sample_main.c
deleted file mode 100644 (file)
index 8332183..0000000
+++ /dev/null
@@ -1,1683 +0,0 @@
-/* ****************************************************************
- *
- * Copyright 2014 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 <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <unistd.h>
-#include <stdbool.h>
-
-#include "cacommon.h"
-#include "cainterface.h"
-#include "oic_string.h"
-
-#define MAX_BUF_LEN 1024
-#define MAX_OPT_LEN 16
-
-#define PORT_LENGTH 5
-
-#define SECURE_DEFAULT_PORT 5684
-
-#define RESOURCE_URI_LENGTH 14
-
-#define SYSTEM_INVOKE_ERROR 127
-#define SYSTEM_ERROR -1
-
-#ifdef WITH_BWT
-#define BLOCK_SIZE(arg) (1 << ((arg) + 4))
-#endif
-
-// Iotivity Device Identity.
-const unsigned char IDENTITY[] = ("1111111111111111");
-
-// PSK between this device and peer device.
-const unsigned char RS_CLIENT_PSK[] = ("AAAAAAAAAAAAAAAA");
-
-int g_received;
-uint16_t g_local_secure_port = SECURE_DEFAULT_PORT;
-CATransportAdapter_t g_selected_nw_type = CA_ADAPTER_IP;
-const char *MESSAGE_TYPE[] = {"CON", "NON", "ACK", "RESET"};
-
-typedef struct
-{
-    char ipAddress[CA_IPADDR_SIZE];
-    uint16_t port;
-} addressSet_t;
-
-char get_menu();
-void process();
-CAResult_t get_network_type();
-CAResult_t get_input_data(char *buf, int32_t length);
-
-bool select_payload_type();
-CAPayload_t get_binary_payload(size_t *payloadLength);
-bool read_file(const char* name, CAPayload_t* bytes, size_t* length);
-void create_file(CAPayload_t bytes, size_t length);
-
-void start_listening_server();
-void start_discovery_server();
-void send_request();
-void send_request_all();
-void send_notification();
-void select_network();
-void unselect_network();
-void handle_request_response();
-void get_network_info();
-void send_secure_request();
-
-void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo);
-void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo);
-void error_handler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
-void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info);
-void get_resource_uri(char *URI, char *resourceURI, int length);
-int get_secure_information(CAPayload_t payLoad);
-bool get_address_set(const char *pAddress, addressSet_t* outAddress);
-void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags);
-CAHeaderOption_t* get_option_data(CAInfo_t* requestData);
-
-static CAToken_t g_last_request_token = NULL;
-
-static const char COAP_PREFIX[] =  "coap://";
-static const char COAPS_PREFIX[] = "coaps://";
-static const char COAP_TCP_PREFIX[] =  "coap+tcp://";
-
-static const uint16_t COAP_PREFIX_LEN = sizeof(COAP_PREFIX) - 1;
-static const uint16_t COAPS_PREFIX_LEN = sizeof(COAPS_PREFIX) - 1;
-static const uint16_t COAP_TCP_PREFIX_LEN = sizeof(COAP_TCP_PREFIX) - 1;
-
-static const char SECURE_INFO_DATA[] =
-                                    "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
-                                     "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":"
-                                     "%d}}]}";
-static const char NORMAL_INFO_DATA[] =
-                                    "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
-                                     "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
-
-#ifdef __WITH_DTLS__
-#ifdef __WITH_X509__
-int GetDtlsX509Credentials(CADtlsX509Creds_t *credInfo)
-{
-    (void) credInfo;
-    return -1;
-}
-int * GetCRLResource()
-{
-    return (int*) NULL;
-}
-#endif //__WITH_X509__
-
-// Internal API. Invoked by CA stack to retrieve credentials from this module
-int32_t CAGetDtlsPskCredentials( CADtlsPskCredType_t type,
-              const unsigned char *desc, size_t desc_len,
-              unsigned char *result, size_t result_length)
-{
-    printf("CAGetDtlsPskCredentials IN\n");
-
-    int32_t ret = -1;
-
-    if (NULL == result)
-    {
-        return ret;
-    }
-
-    switch (type)
-    {
-        case CA_DTLS_PSK_HINT:
-        case CA_DTLS_PSK_IDENTITY:
-
-            if (result_length < sizeof(IDENTITY))
-            {
-                printf("ERROR : Wrong value for result for storing IDENTITY");
-                return ret;
-            }
-
-            memcpy(result, IDENTITY, sizeof(IDENTITY));
-            ret = sizeof(IDENTITY);
-            break;
-
-        case CA_DTLS_PSK_KEY:
-
-            if ((desc_len == sizeof(IDENTITY)) &&
-                memcmp(desc, IDENTITY, sizeof(IDENTITY)) == 0)
-            {
-                if (result_length < sizeof(RS_CLIENT_PSK))
-                {
-                    printf("ERROR : Wrong value for result for storing RS_CLIENT_PSK");
-                    return ret;
-                }
-
-                memcpy(result, RS_CLIENT_PSK, sizeof(RS_CLIENT_PSK));
-                ret = sizeof(RS_CLIENT_PSK);
-            }
-            break;
-
-        default:
-
-            printf("Wrong value passed for PSK_CRED_TYPE.");
-            ret = -1;
-    }
-
-    printf("CAGetDtlsPskCredentials OUT\n");
-    return ret;
-}
-
-#endif //__WITH_DTLS__
-
-int main()
-{
-    int ret = system("clear");
-    // shell invoke error: 127, others: -1
-    if (SYSTEM_INVOKE_ERROR == ret || SYSTEM_ERROR == ret)
-    {
-        printf("Terminal Clear Error: %d\n", ret);
-        return -1;
-    }
-
-    printf("=============================================\n");
-    printf("\t\tsample main\n");
-    printf("=============================================\n");
-
-    CAResult_t res = CAInitialize();
-    if (CA_STATUS_OK != res)
-    {
-        printf("CAInitialize fail\n");
-        return -1;
-    }
-
-    // Set the PSK Credentials callback handler.
-#ifdef __WITH_DTLS__
-    res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
-    if (CA_STATUS_OK != res)
-    {
-        printf("Register credential handler fail\n");
-        return -1;
-    }
-#endif
-
-    // set handler.
-    CARegisterHandler(request_handler, response_handler, error_handler);
-
-    process();
-
-    CADestroyToken(g_last_request_token);
-
-    g_last_request_token = NULL;
-
-    CATerminate();
-    return 0;
-}
-
-void process()
-{
-    while (1)
-    {
-        char menu = get_menu();
-
-        switch (menu)
-        {
-            case 'm': // menu
-            case 'M':
-                break;
-
-            case 'q': // quit
-            case 'Q':
-                printf("quit..!!\n");
-                return;
-
-            case 's': // start server
-            case 'S':
-                start_listening_server();
-                break;
-
-            case 't': // send request
-            case 'T':
-                send_request_all();
-                break;
-
-            case 'c': // start client
-            case 'C':
-                start_discovery_server();
-                break;
-
-            case 'r': // send request
-            case 'R':
-                send_request();
-                break;
-
-            case 'b': // send notification
-            case 'B':
-                send_notification();
-                break;
-
-            case 'n': // select network
-            case 'N':
-                select_network();
-                break;
-
-            case 'x': // unselect network
-            case 'X':
-                unselect_network();
-                break;
-
-            case 'h': // handle request response
-            case 'H':
-                handle_request_response();
-                break;
-
-            case 'w':
-            case 'W':
-                g_received = 0;
-                start_discovery_server();
-                send_secure_request();
-                while (g_received == 0)
-                {
-                    sleep(1);
-                    handle_request_response();
-                }
-                break;
-
-            case 'z':
-            case 'Z':
-                start_listening_server();
-                while (1)
-                {
-                    sleep(1);
-                    handle_request_response();
-                }
-                break;
-
-            case 'g': // get network information
-            case 'G':
-                get_network_info();
-                break;
-
-            default:
-                printf("not supported menu!!\n");
-                break;
-        }
-    }
-}
-
-void start_listening_server()
-{
-    printf("start listening server!!\n");
-
-    CAResult_t res = CAStartListeningServer();
-    if (CA_STATUS_OK != res)
-    {
-        printf("start listening server fail, error code : %d\n", res);
-    }
-    else
-    {
-        printf("start listening server success\n");
-    }
-}
-
-void start_discovery_server()
-{
-    printf("start discovery client!!\n");
-
-    CAResult_t res = CAStartDiscoveryServer();
-    if (CA_STATUS_OK != res)
-    {
-        printf("start discovery client fail, error code : %d\n", res);
-    }
-    else
-    {
-        printf("start discovery client success\n");
-    }
-}
-
-bool select_payload_type()
-{
-    char buf[MAX_BUF_LEN]={0};
-    printf("\n=============================================\n");
-    printf("Normal Payload  : 0\nBig Payload   : 1\n");
-    printf("select Payload type : ");
-
-    CAResult_t res = get_input_data(buf, sizeof(buf));
-    if (CA_STATUS_OK != res)
-    {
-        printf("Payload type selection error\n");
-        printf("Default: Using normal Payload\n");
-        return false;
-    }
-
-    return (buf[0] == '1') ? true : false;
-}
-
-CAPayload_t get_binary_payload(size_t *payloadLength)
-{
-    CAPayload_t binaryPayload = NULL;
-    bool result = read_file("sample_input.txt", &binaryPayload, payloadLength);
-    if (false == result)
-    {
-        return NULL;
-    }
-
-    return binaryPayload;
-}
-
-void send_request()
-{
-    CAResult_t res = get_network_type();
-    if (CA_STATUS_OK != res)
-    {
-        return;
-    }
-
-    printf("Do you want to send secure request ?.... enter (0/1): ");
-
-    char secureRequest[MAX_BUF_LEN] = {0};
-    if (CA_STATUS_OK != get_input_data(secureRequest, MAX_BUF_LEN))
-    {
-        return;
-    }
-
-    if (strcmp(secureRequest, "1") == 0)
-    {
-        printf("Enter the URI like below....\n");
-        printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
-    }
-    else if (strcmp(secureRequest, "0") == 0)
-    {
-        printf("Enter the URI like below....\n");
-        printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
-        printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
-        printf("coap+tcp://10:11:12:13:45:45/resource_uri ( for TCP )\n");
-    }
-    else
-    {
-        printf("Input data is wrong value\n");
-        return;
-    }
-
-    char uri[MAX_BUF_LEN] = {'\0'};
-    if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
-    {
-        return;
-    }
-
-    // create remote endpoint
-    CAEndpoint_t *endpoint = NULL;
-    CATransportFlags_t flags;
-
-    printf("URI : %s\n", uri);
-    addressSet_t address = {{}, 0};
-    parsing_coap_uri(uri, &address, &flags);
-
-    res = CACreateEndpoint(flags, g_selected_nw_type,
-                           (const char*)address.ipAddress, address.port, &endpoint);
-    if (CA_STATUS_OK != res || !endpoint)
-    {
-        printf("Failed to create remote endpoint, error code : %d\n", res);
-        return;
-    }
-
-    printf("\n=============================================\n");
-    printf("0:CON, 1:NON\n");
-    printf("select message type : ");
-
-    char buf[MAX_BUF_LEN] = { 0 };
-    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
-    {
-        CADestroyEndpoint(endpoint);
-        return;
-    }
-
-    CAMessageType_t msgType = (buf[0] == '1') ? 1 : 0;
-
-    // create token
-    CAToken_t token = NULL;
-    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
-
-    res = CAGenerateToken(&token, tokenLength);
-    if ((CA_STATUS_OK != res) || (!token))
-    {
-        printf("Token generate error, error code : %d\n", res);
-        CADestroyEndpoint(endpoint);
-        return;
-    }
-
-    printf("Generated token %s\n", token);
-
-    // extract relative resourceuri from give uri
-    char resourceURI[RESOURCE_URI_LENGTH + 1] = {0};
-    get_resource_uri(uri, resourceURI, RESOURCE_URI_LENGTH);
-    printf("resourceURI : %s\n", resourceURI);
-
-    // create request data
-    CAInfo_t requestData = { .type = msgType,
-                             .messageId = 0,
-                             .token = token,
-                             .tokenLength = tokenLength,
-                             .options = NULL,
-                             .numOptions = 0,
-                             .payload = NULL,
-                             .payloadSize = 0,
-                             .resourceUri = (CAURI_t)resourceURI };
-
-    if (strcmp(secureRequest, "1") == 0)
-    {
-        size_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
-        requestData.payload = (CAPayload_t) calloc(length,  sizeof(char));
-        if (NULL == requestData.payload)
-        {
-            printf("Memory allocation fail\n");
-            CADestroyEndpoint(endpoint);
-            CADestroyToken(token);
-            return;
-        }
-        snprintf((char *) requestData.payload, length, SECURE_INFO_DATA,
-                 (const char *) resourceURI, g_local_secure_port);
-        requestData.payloadSize = length;
-    }
-    else
-    {
-        bool useBigPayload = select_payload_type();
-        if (useBigPayload)
-        {
-            size_t payloadLength = 0;
-            CAPayload_t binaryPayload = get_binary_payload(&payloadLength);
-            if (!binaryPayload)
-            {
-                free(binaryPayload);
-                CADestroyToken(token);
-                CADestroyEndpoint(endpoint);
-                return;
-            }
-
-            requestData.payload = (CAPayload_t) malloc(payloadLength);
-            if (NULL == requestData.payload)
-            {
-                printf("Memory allocation failed!");
-                free(binaryPayload);
-                CADestroyToken(token);
-                CADestroyEndpoint(endpoint);
-                return;
-            }
-            memcpy(requestData.payload, binaryPayload, payloadLength);
-            requestData.payloadSize = payloadLength;
-
-            // memory free
-            free(binaryPayload);
-        }
-        else
-        {
-            size_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
-            requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
-            if (NULL == requestData.payload)
-            {
-                printf("Memory allocation fail\n");
-                CADestroyEndpoint(endpoint);
-                CADestroyToken(token);
-                return;
-            }
-            snprintf((char *) requestData.payload, length, NORMAL_INFO_DATA,
-                     (const char *) resourceURI);
-            requestData.payloadSize = length;
-        }
-    }
-
-    CAHeaderOption_t* headerOpt = get_option_data(&requestData);
-
-    CARequestInfo_t requestInfo = { .method = CA_GET,
-                                    .info = requestData,
-                                    .isMulticast = false };
-
-    // send request
-    res = CASendRequest(endpoint, &requestInfo);
-    if (CA_STATUS_OK != res)
-    {
-        printf("Could not send request : %d\n", res);
-    }
-
-    if (headerOpt)
-    {
-        free(headerOpt);
-    }
-
-    //destroy token
-    CADestroyToken(token);
-    // destroy remote endpoint
-    CADestroyEndpoint(endpoint);
-    free(requestData.payload);
-
-    printf("=============================================\n");
-}
-
-void send_secure_request()
-{
-    char uri[MAX_BUF_LEN];
-    char ipv4addr[CA_IPADDR_SIZE];
-
-    printf("\n=============================================\n");
-    printf("Enter IPv4 address of the source hosting secure resource (Ex: 11.12.13.14)\n");
-
-    if (CA_STATUS_OK != get_input_data(ipv4addr, CA_IPADDR_SIZE))
-    {
-        return;
-    }
-    snprintf(uri, MAX_BUF_LEN, "%s%s:5684/a/light", COAPS_PREFIX, ipv4addr);
-
-    // create remote endpoint
-    CAEndpoint_t *endpoint = NULL;
-    CAResult_t res = CACreateEndpoint(0, CA_ADAPTER_IP, ipv4addr, SECURE_DEFAULT_PORT, &endpoint);
-    if (CA_STATUS_OK != res)
-    {
-        printf("Failed to create remote endpoint, error code: %d\n", res);
-        goto exit;
-    }
-
-    // create token
-    CAToken_t token = NULL;
-    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
-
-    res = CAGenerateToken(&token, tokenLength);
-    if (CA_STATUS_OK != res)
-    {
-        printf("Token generate error, error code : %d\n", res);
-        goto exit;
-    }
-
-    printf("Generated token %s\n", token);
-
-    // create request data
-    CAInfo_t requestData = { .type = CA_MSG_NONCONFIRM,
-                             .messageId = 0,
-                             .token = token,
-                             .tokenLength = tokenLength,
-                             .options = NULL,
-                             .numOptions = 0,
-                             .payload = NULL,
-                             .payloadSize = 0,
-                             .resourceUri = NULL };
-
-    CARequestInfo_t requestInfo = { .method = CA_GET,
-                                    .info = requestData,
-                                    .isMulticast = false };
-
-    // send request
-    CASendRequest(endpoint, &requestInfo);
-
-exit:
-    // cleanup
-    CADestroyToken(token);
-    CADestroyEndpoint(endpoint);
-    printf("=============================================\n");
-}
-
-
-void send_request_all()
-{
-    CAResult_t res = get_network_type();
-    if (CA_STATUS_OK != res)
-    {
-        return;
-    }
-
-    printf("\n=============================================\n");
-    printf("ex) /a/light\n");
-    printf("resource uri : ");
-
-    char resourceURI[MAX_BUF_LEN] = { 0 };
-    if (CA_STATUS_OK != get_input_data(resourceURI, MAX_BUF_LEN))
-    {
-        return;
-    }
-
-    // create remote endpoint
-    CAEndpoint_t *group = NULL;
-    res = CACreateEndpoint(CA_IPV4, g_selected_nw_type, NULL, 0, &group);
-    if (CA_STATUS_OK != res)
-    {
-        printf("Create remote endpoint error, error code: %d\n", res);
-        return;
-    }
-
-    // create token
-    CAToken_t token = NULL;
-    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
-
-    res = CAGenerateToken(&token, tokenLength);
-    if ((CA_STATUS_OK != res) || (!token))
-    {
-        printf("Token generate error!!\n");
-        CADestroyEndpoint(group);
-        return;
-    }
-
-    printf("generated token %s\n", token);
-
-    // create request data
-    CAPayload_t payload = (CAPayload_t) "TempJsonPayload";
-    size_t payloadSize = strlen((const char *) payload);
-
-    CAInfo_t requestData = { .type = CA_MSG_NONCONFIRM,
-                             .messageId = 0,
-                             .token = token,
-                             .tokenLength = tokenLength,
-                             .options = NULL,
-                             .numOptions = 0,
-                             .payload = payload,
-                             .payloadSize = payloadSize,
-                             .resourceUri = (CAURI_t) resourceURI };
-
-    CARequestInfo_t requestInfo = { .method = CA_GET,
-                                    .info = requestData,
-                                    .isMulticast = true };
-
-    CAHeaderOption_t* headerOpt = get_option_data(&requestData);
-
-    // send request
-    res = CASendRequest(group, &requestInfo);
-    if (CA_STATUS_OK != res)
-    {
-        printf("Could not send request to all\n");
-        CADestroyToken(token);
-    }
-    else
-    {
-        CADestroyToken(g_last_request_token);
-        g_last_request_token = token;
-    }
-
-    if (headerOpt)
-    {
-        free(headerOpt);
-    }
-
-    // destroy remote endpoint
-    CADestroyEndpoint(group);
-
-    printf("=============================================\n");
-}
-
-void send_notification()
-{
-    CAResult_t res = get_network_type();
-    if (CA_STATUS_OK != res)
-    {
-        return;
-    }
-
-    printf("\n=============================================\n");
-    printf("Enter the URI like below....\n");
-    printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
-    printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
-    printf("coap+tcp://10:11:12:13:45:45/resource_uri ( for TCP )\n");
-    printf("uri : ");
-
-    char uri[MAX_BUF_LEN] = { 0 };
-    if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
-    {
-        return;
-    }
-
-    printf("\n=============================================\n");
-    printf("\tselect message type\n");
-    printf("CON     : 0\n");
-    printf("NON     : 1\n");
-    printf("ACK     : 2\n");
-    printf("RESET   : 3\n");
-    printf("select : ");
-
-    char messageTypeBuf[MAX_BUF_LEN] = { 0 };
-    if (CA_STATUS_OK != get_input_data(messageTypeBuf, MAX_BUF_LEN))
-    {
-        return;
-    }
-
-    int messageType = messageTypeBuf[0] - '0';
-
-    CATransportFlags_t flags;
-    addressSet_t address = {{}, 0};
-    parsing_coap_uri(uri, &address, &flags);
-
-    // create remote endpoint
-    CAEndpoint_t *endpoint = NULL;
-    res = CACreateEndpoint(flags, g_selected_nw_type, address.ipAddress, address.port, &endpoint);
-    if (CA_STATUS_OK != res)
-    {
-        printf("Create remote endpoint error, error code: %d\n", res);
-        return;
-    }
-
-    // create token
-    CAToken_t token = NULL;
-    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
-
-    res = CAGenerateToken(&token, tokenLength);
-    if ((CA_STATUS_OK != res) || (!token))
-    {
-        printf("Token generate error!!\n");
-        CADestroyEndpoint(endpoint);
-        return;
-    }
-
-    printf("Generated token %s\n", token);
-
-    // create response data
-    CAPayload_t payload = (CAPayload_t) "TempNotificationData";
-    size_t payloadSize = strlen((const char *) payload);
-
-    CAInfo_t requestData = { .type = messageType,
-                             .messageId = 0,
-                             .token = token,
-                             .tokenLength = tokenLength,
-                             .options = NULL,
-                             .numOptions = 0,
-                             .payload = payload,
-                             .payloadSize = payloadSize,
-                             .resourceUri = (CAURI_t) uri };
-
-    CARequestInfo_t requestInfo = { .method = CA_GET,
-                                    .info = requestData };
-
-    // send request
-    res = CASendRequest(endpoint, &requestInfo);
-    if (CA_STATUS_OK != res)
-    {
-        printf("Send notification error, error code: %d\n", res);
-    }
-    else
-    {
-        printf("Send notification success\n");
-    }
-
-    // destroy token
-    CADestroyToken(token);
-    // destroy remote endpoint
-    CADestroyEndpoint(endpoint);
-
-    printf("\n=============================================\n");
-}
-
-void select_network()
-{
-    printf("\n=============================================\n");
-    printf("\tselect network\n");
-    printf("IP     : 0\n");
-    printf("GATT   : 1\n");
-    printf("RFCOMM : 2\n");
-    printf("TCP    : 4\n");
-    printf("select : ");
-
-    char buf[MAX_BUF_LEN] = { 0 };
-    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
-    {
-        return;
-    }
-
-    int number = buf[0] - '0';
-
-    if (number < 0 || number > 4)
-    {
-        printf("Invalid network type\n");
-        return;
-    }
-
-    CAResult_t res = CASelectNetwork(1 << number);
-    if (CA_STATUS_OK != res)
-    {
-        printf("Select network error\n");
-    }
-    else
-    {
-        printf("Select network success\n");
-    }
-
-    printf("=============================================\n");
-}
-
-void unselect_network()
-{
-    printf("\n=============================================\n");
-    printf("\tunselect enabled network\n");
-    printf("IP     : 0\n");
-    printf("GATT   : 1\n");
-    printf("RFCOMM : 2\n");
-    printf("TCP    : 4\n");
-    printf("select : ");
-
-    char buf[MAX_BUF_LEN] = { 0 };
-    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
-    {
-        return;
-    }
-
-    int number = buf[0] - '0';
-
-    if (number < 0 || number > 4)
-    {
-        printf("Invalid network type\n");
-        return;
-    }
-
-    CAResult_t res = CAUnSelectNetwork(1 << number);
-    if (CA_STATUS_OK != res)
-    {
-        printf("Unselect network error\n");
-    }
-    else
-    {
-        printf("Unselect network success\n");
-    }
-
-    printf("=============================================\n");
-}
-
-char get_menu()
-{
-    printf("\n=============================================\n");
-    printf("\t\tMenu\n");
-    printf("\ts : start server\n");
-    printf("\tc : start client\n");
-    printf("\tr : send request\n");
-    printf("\tt : send request to all\n");
-    printf("\tb : send notification\n");
-    printf("\tn : select network\n");
-    printf("\tx : unselect network\n");
-    printf("\tg : get network information\n");
-    printf("\th : handle request response\n");
-    printf("\tz : run static server\n");
-    printf("\tw : send secure request\n");
-    printf("\tq : quit\n");
-    printf("=============================================\n");
-    printf("select : ");
-
-    char buf[MAX_BUF_LEN] = { 0 };
-    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
-    {
-        printf("Failed to get input data\n");
-    }
-
-    return buf[0];
-}
-
-void handle_request_response()
-{
-    printf("Handle_request_response\n");
-
-    CAResult_t res = CAHandleRequestResponse();
-    if (CA_STATUS_OK != res)
-    {
-        printf("Handle request error, error code: %d\n", res);
-    }
-    else
-    {
-        printf("Handle request success\n");
-    }
-}
-
-void get_network_info()
-{
-    CAEndpoint_t *tempInfo = NULL;
-    uint32_t tempSize = 0;
-
-    CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
-    if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize)
-    {
-        printf("Network not connected\n");
-        free(tempInfo);
-        return;
-    }
-
-    printf("################## Network Information #######################\n");
-    printf("Network info total size is %d\n\n", tempSize);
-
-    for (uint32_t index = 0; index  < tempSize; index++)
-    {
-        printf("Type: %d\n", tempInfo[index].adapter);
-        printf("Address: %s\n", tempInfo[index].addr);
-        if (CA_ADAPTER_IP == tempInfo[index].adapter)
-        {
-            printf("Port: %d\n", tempInfo[index].port);
-            printf("Secured: %s flag : %x\n\n", (tempInfo[index].flags & CA_SECURE) ? "true" :
-                   "false", tempInfo[index].flags);
-
-            if (tempInfo[index].flags & CA_SECURE)
-            {
-                g_local_secure_port = tempInfo[index].port;
-                printf("Secured: in global %d\n\n", g_local_secure_port);
-            }
-        }
-    }
-
-    free(tempInfo);
-    printf("##############################################################");
-}
-
-void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo)
-{
-    if (NULL == object || NULL == requestInfo)
-    {
-        printf("Input parameter is NULL\n");
-        return;
-    }
-
-    if ((NULL != g_last_request_token) && (NULL != requestInfo->info.token)
-        && (memcmp(g_last_request_token, requestInfo->info.token,
-                   CA_MAX_TOKEN_LEN) == 0))
-    {
-        printf("token is same. received request of it's own. skip.. \n");
-        return;
-    }
-
-    printf("##########received request from remote device #############\n");
-    if (CA_ADAPTER_IP == object->adapter)
-    {
-        printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
-               object->port, object->flags & CA_SECURE);
-    }
-    else
-    {
-        printf("Remote Address: %s \n", object->addr);
-    }
-    printf("Data: %s\n", requestInfo->info.payload);
-    printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]);
-    printf("Resource URI: %s \n", requestInfo->info.resourceUri);
-
-    if (requestInfo->info.options)
-    {
-        uint32_t len = requestInfo->info.numOptions;
-        uint32_t i;
-        for (i = 0; i < len; i++)
-        {
-            printf("Option %d\n", i + 1);
-            printf("ID : %d\n", requestInfo->info.options[i].optionID);
-            printf("Data[%d]: %s\n", requestInfo->info.options[i].optionLength,
-                   requestInfo->info.options[i].optionData);
-        }
-    }
-    printf("############################################################\n");
-
-    //Check if this has secure communication information
-    if (requestInfo->info.payload &&
-            (CA_ADAPTER_IP == object->adapter))
-    {
-        int securePort = get_secure_information(requestInfo->info.payload);
-        if (0 < securePort) //Set the remote endpoint secure details and send response
-        {
-            printf("This is secure resource...\n");
-
-            CAEndpoint_t *endpoint = NULL;
-            if (CA_STATUS_OK != CACreateEndpoint(0, object->adapter, object->addr,
-                                                 object->port, &endpoint))
-            {
-                printf("Failed to create duplicate of remote endpoint!\n");
-                return;
-            }
-            endpoint->flags = CA_SECURE;
-            object = endpoint;
-        }
-    }
-
-#ifdef WITH_BWT
-    // if received message is bulk data, create output file
-    if ((requestInfo->info.payload) &&
-            (requestInfo->info.payloadSize > BLOCK_SIZE(CA_DEFAULT_BLOCK_SIZE)))
-    {
-        create_file(requestInfo->info.payload, requestInfo->info.payloadSize);
-    }
-#endif
-
-    printf("Send response with URI\n");
-    send_response(object, &requestInfo->info);
-
-    g_received = 1;
-}
-
-void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
-{
-    printf("##########Received response from remote device #############\n");
-    if (CA_ADAPTER_IP == object->adapter)
-    {
-        printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
-               object->port, object->flags & CA_SECURE);
-    }
-    else
-    {
-        printf("Remote Address: %s \n", object->addr);
-    }
-    printf("response result : %d\n", responseInfo->result);
-    printf("Data: %s\n", responseInfo->info.payload);
-    printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]);
-    printf("Token: %s\n", responseInfo->info.token);
-    printf("Resource URI: %s \n", responseInfo->info.resourceUri);
-
-    if (responseInfo->info.options)
-    {
-        uint32_t len = responseInfo->info.numOptions;
-        uint32_t i;
-        for (i = 0; i < len; i++)
-        {
-            printf("Option %d\n", i + 1);
-            printf("ID : %d\n", responseInfo->info.options[i].optionID);
-            printf("Data[%d]: %s\n", responseInfo->info.options[i].optionLength,
-                   responseInfo->info.options[i].optionData);
-        }
-    }
-    printf("############################################################\n");
-    g_received = 1;
-
-    //Check if this has secure communication information
-    if (responseInfo->info.payload)
-    {
-        int securePort = get_secure_information(responseInfo->info.payload);
-        if (0 < securePort) //Set the remote endpoint secure details and send response
-        {
-            printf("This is secure resource...\n");
-        }
-    }
-
-#ifdef WITH_BWT
-    // if received message is bulk data, create output file
-    if ((responseInfo->info.payload) &&
-            (responseInfo->info.payloadSize > BLOCK_SIZE(CA_DEFAULT_BLOCK_SIZE)))
-    {
-        create_file(responseInfo->info.payload, responseInfo->info.payloadSize);
-    }
-#endif
-}
-
-void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
-{
-    (void)rep;
-    printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++\n");
-
-    if(errorInfo)
-    {
-        const CAInfo_t *info = &errorInfo->info;
-        printf("Error Handler, ErrorInfo :\n");
-        printf("Error Handler result    : %d\n", errorInfo->result);
-        printf("Error Handler token     : %s\n", info->token);
-        printf("Error Handler messageId : %d\n", (uint16_t) info->messageId);
-        printf("Error Handler type      : %d\n", info->type);
-        printf("Error Handler resourceUri : %s\n", info->resourceUri);
-        printf("Error Handler payload   : %s\n", info->payload);
-
-        if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
-        {
-            printf("CA_ADAPTER_NOT_ENABLED, enable the adapter\n");
-        }
-        else if(CA_SEND_FAILED == errorInfo->result)
-        {
-            printf("CA_SEND_FAILED, unable to send the message, check parameters\n");
-        }
-        else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
-        {
-            printf("CA_MEMORY_ALLOC_FAILED, insufficient memory\n");
-        }
-        else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
-        {
-            printf("CA_SOCKET_OPERATION_FAILED, socket operation failed\n");
-        }
-        else if(CA_STATUS_FAILED == errorInfo->result)
-        {
-            printf("CA_STATUS_FAILED, message could not be delivered, internal error\n");
-        }
-    }
-    printf("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++\n");
-
-    return;
-}
-
-void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info)
-{
-    printf("entering send_response\n");
-
-    printf("\n=============================================\n");
-    printf("\tselect message type\n");
-    printf("CON     : 0\n");
-    printf("NON     : 1\n");
-    printf("ACK     : 2\n");
-    printf("RESET   : 3\n");
-    printf("select : ");
-
-    char buf[MAX_BUF_LEN] = { 0 };
-    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
-    {
-        return;
-    }
-
-    int messageType = buf[0] - '0';
-    if (0 > messageType || 3 < messageType)
-    {
-        printf("Invalid message type\n");
-        return;
-    }
-
-    int responseCode = 0 ;
-    char responseCodeBuf[MAX_BUF_LEN] = { 0 };
-    if (CA_MSG_RESET != messageType)
-    {
-        printf("\n=============================================\n");
-        printf("\tselect response code\n");
-        printf("EMPTY                    :   0\n");
-        printf("CREATED                  : 201\n");
-        printf("DELETED                  : 202\n");
-        printf("VALID                    : 203\n");
-        printf("CHANGED                  : 204\n");
-        printf("CONTENT                  : 205\n");
-        printf("BAD_REQ                  : 400\n");
-        printf("BAD_OPT                  : 402\n");
-        printf("NOT_FOUND                : 404\n");
-        printf("INTERNAL_SERVER_ERROR    : 500\n");
-        printf("RETRANSMIT_TIMEOUT       : 504\n");
-        printf("select : ");
-
-        if (CA_STATUS_OK != get_input_data(responseCodeBuf, MAX_BUF_LEN))
-        {
-            return;
-        }
-        responseCode = atoi(responseCodeBuf);
-    }
-
-    // create response data
-    uint16_t messageId = (info != NULL) ? info->messageId : 0;
-    CAURI_t resourceUri = (info != NULL) ? info->resourceUri : 0;
-
-    CAInfo_t responseData = { .type = messageType,
-                              .messageId = messageId,
-                              .token = NULL,
-                              .tokenLength = 0,
-                              .options = NULL,
-                              .numOptions = 0,
-                              .payload = NULL,
-                              .payloadSize = 0,
-                              .resourceUri = resourceUri };
-
-    if (CA_MSG_RESET == messageType ||
-        (CA_MSG_ACKNOWLEDGE == messageType && CA_EMPTY == responseCode))
-    {
-        printf("RESET or ACK/EMPTY. there will be not payload/option\n");
-
-    }
-    else
-    {
-        responseData.token = (info != NULL) ? info->token : NULL;
-        responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
-
-        if (endpoint->flags & CA_SECURE)
-        {
-            if(!responseData.resourceUri)
-            {
-               printf("resourceUri not available in SECURE\n");
-               return;
-            }
-            printf("Sending response on secure communication\n");
-
-            uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(responseData.resourceUri);
-            responseData.payload = (CAPayload_t) calloc(length,  sizeof(char));
-            if (NULL == responseData.payload)
-            {
-                printf("Memory allocation fail\n");
-                return;
-            }
-            snprintf((char *) responseData.payload, length, SECURE_INFO_DATA,
-                     (const char *) responseData.resourceUri, g_local_secure_port);
-            responseData.payloadSize = length;
-        }
-        else
-        {
-            printf("Sending response on non-secure communication\n");
-
-            bool useBigPayload = select_payload_type();
-            if (useBigPayload)
-            {
-                size_t payloadLength = 0;
-                CAPayload_t binaryPayload = get_binary_payload(&payloadLength);
-                if (NULL == binaryPayload)
-                {
-                    free(binaryPayload);
-                    return;
-                }
-
-                responseData.payload = (CAPayload_t) malloc(payloadLength);
-                if (NULL == responseData.payload)
-                {
-                    printf("Memory allocation failed!");
-                    free(binaryPayload);
-                    return;
-                }
-                memcpy(responseData.payload, binaryPayload, payloadLength);
-                responseData.payloadSize = payloadLength;
-
-                // memory free
-                free(binaryPayload);
-            }
-            else
-            {
-                if(!responseData.resourceUri)
-                {
-                   printf("resourceUri not available in NON-SECURE\n");
-                   return;
-                }
-                uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(responseData.resourceUri);
-                responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
-                if (NULL == responseData.payload)
-                {
-                    printf("Memory allocation fail\n");
-                    return;
-                }
-                snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA,
-                         (const char *) responseData.resourceUri);
-                responseData.payloadSize = length;
-            }
-        }
-    }
-
-    CAResponseInfo_t responseInfo = { .result = responseCode,
-                                      .info = responseData };
-
-    // send response (transportType from remoteEndpoint of request Info)
-    CAResult_t res = CASendResponse(endpoint, &responseInfo);
-    if (CA_STATUS_OK != res)
-    {
-        printf("Send response error\n");
-    }
-    else
-    {
-        printf("Send response success\n");
-    }
-
-    if (responseData.payload)
-    {
-        free(responseData.payload);
-    }
-
-    printf("=============================================\n");
-}
-
-int get_secure_information(CAPayload_t payLoad)
-{
-    printf("Entering get_secure_information\n");
-
-    if (!payLoad)
-    {
-        printf("Payload is NULL\n");
-        return -1;
-    }
-
-    char *subString = NULL;
-    if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1")))
-    {
-        printf("This is not secure resource\n");
-        return -1;
-    }
-
-    if (NULL == (subString = strstr((const char *) payLoad, "\"port\":")))
-    {
-        printf("This secure resource does not have port information\n");
-        return -1;
-    }
-
-    char *startPos = strstr(subString, ":");
-    if (!startPos)
-    {
-        printf("Parsing failed !\n");
-        return -1;
-    }
-
-    char *endPos = strstr(startPos, "}");
-    if (!endPos)
-    {
-        printf("Parsing failed !\n");
-        return -1;
-    }
-
-    char portStr[6] = {0};
-    OICStrcpyPartial(portStr, sizeof(portStr), startPos + 1, (endPos - 1) - startPos);
-    printf("secured port is: %s\n", portStr);
-    return atoi(portStr);
-}
-
-void get_resource_uri(char *URI, char *resourceURI, int length)
-{
-    char *startPos = URI;
-    char *temp = NULL;
-    if (NULL != (temp = strstr(URI, "://")))
-    {
-        startPos = strchr(temp + 3, '/');
-        if (!startPos)
-        {
-            printf("Resource URI is missing\n");
-            return;
-        }
-    }
-
-    char *endPos = strchr(startPos, '?');
-    if (!endPos)
-    {
-        endPos = URI + strlen(URI);
-    }
-    endPos -= 1;
-
-    if (endPos - startPos <= length)
-    {
-        OICStrcpyPartial(resourceURI, length, startPos + 1, endPos - startPos);
-    }
-
-    printf("URI: %s, ResourceURI:%s\n", URI, resourceURI);
-}
-
-CAResult_t get_network_type()
-{
-    char buf[MAX_BUF_LEN] = { 0 };
-
-    printf("\n=============================================\n");
-    printf("\tselect network type\n");
-    printf("IP     : 0\n");
-    printf("GATT   : 1\n");
-    printf("RFCOMM : 2\n");
-    printf("TCP    : 4\n");
-    printf("select : ");
-
-    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
-    {
-        return CA_NOT_SUPPORTED ;
-    }
-
-    int number = buf[0] - '0';
-
-    number = (number < 0 || number > 4) ? 0 : 1 << number;
-
-    switch (number)
-    {
-        case CA_ADAPTER_IP:
-        case CA_ADAPTER_GATT_BTLE:
-        case CA_ADAPTER_RFCOMM_BTEDR:
-        case CA_ADAPTER_TCP:
-            g_selected_nw_type = number;
-            return CA_STATUS_OK;
-        default:
-            return CA_NOT_SUPPORTED;
-    }
-}
-
-CAResult_t get_input_data(char *buf, int32_t length)
-{
-    if (!fgets(buf, length, stdin))
-    {
-        printf("fgets error\n");
-        return CA_STATUS_FAILED;
-    }
-
-    char *p = NULL;
-    if ( (p = strchr(buf, '\n')) != NULL )
-    {
-        *p = '\0';
-    }
-
-    return CA_STATUS_OK;
-}
-
-CAHeaderOption_t* get_option_data(CAInfo_t* requestData)
-{
-    char optionNumBuf[MAX_BUF_LEN] = { 0 };
-    char optionData[MAX_OPT_LEN] = { 0 } ;
-
-    printf("Option Num : ");
-    if (CA_STATUS_OK != get_input_data(optionNumBuf, MAX_BUF_LEN))
-    {
-        return NULL;
-    }
-    int optionNum = atoi(optionNumBuf);
-
-    CAHeaderOption_t * headerOpt = NULL;
-    if (0 >= optionNum)
-    {
-        printf("there is no headerOption!\n");
-        return NULL;
-    }
-    else if (optionNum > MAX_OPT_LEN)
-    {
-        printf("Too many header options!\n");
-        return NULL;
-    }
-    else
-    {
-        headerOpt = (CAHeaderOption_t *)calloc(optionNum, sizeof(CAHeaderOption_t));
-        if (NULL == headerOpt)
-        {
-            printf("Memory allocation failed!\n");
-            return NULL;
-        }
-
-        int i;
-        for (i = 0; i < optionNum; i++)
-        {
-            char getOptionID[MAX_BUF_LEN] = { 0 } ;
-
-            printf("[%d] Option ID : ", i + 1);
-            if (CA_STATUS_OK != get_input_data(getOptionID, MAX_BUF_LEN))
-            {
-                free(headerOpt);
-                return NULL;
-            }
-            int optionID = atoi(getOptionID);
-            headerOpt[i].optionID = optionID;
-
-            printf("[%d] Option Data : ", i + 1);
-            if (CA_STATUS_OK != get_input_data(optionData, MAX_OPT_LEN))
-            {
-                free(headerOpt);
-                return NULL;
-            }
-
-            OICStrcpy(headerOpt[i].optionData, sizeof(headerOpt[i].optionData), optionData);
-
-            headerOpt[i].optionLength = (uint16_t) strlen(optionData);
-        }
-        requestData->numOptions = optionNum;
-        requestData->options = headerOpt;
-    }
-    return headerOpt;
-}
-
-void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
-{
-    if (NULL == uri)
-    {
-        printf("parameter is null\n");
-        return;
-    }
-
-    // parse uri
-    // #1. check prefix
-    uint8_t startIndex = 0;
-    if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
-    {
-        printf("uri has '%s' prefix\n", COAPS_PREFIX);
-        startIndex = COAPS_PREFIX_LEN;
-        *flags = CA_SECURE;
-    }
-    else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
-    {
-        printf("uri has '%s' prefix\n", COAP_PREFIX);
-        startIndex = COAP_PREFIX_LEN;
-        *flags = CA_IPV4;
-    }
-    else if (strncmp(COAP_TCP_PREFIX, uri, COAP_TCP_PREFIX_LEN) == 0)
-    {
-        printf("uri has '%s' prefix\n", COAP_TCP_PREFIX);
-        startIndex = COAP_TCP_PREFIX_LEN;
-        *flags = CA_IPV4;
-    }
-
-    // #2. copy uri for parse
-    int32_t len = strlen(uri) - startIndex;
-
-    if (len <= 0)
-    {
-        printf("uri length is 0!\n");
-        return;
-    }
-
-    char *cloneUri = (char *) calloc(len + 1, sizeof(char));
-    if (NULL == cloneUri)
-    {
-        printf("Out of memory\n");
-        return;
-    }
-
-    memcpy(cloneUri, &uri[startIndex], sizeof(char) * len);
-    cloneUri[len] = '\0';
-
-    char *pAddress = cloneUri;
-    printf("pAddress : %s\n", pAddress);
-
-    if (!get_address_set(pAddress, address))
-    {
-        printf("address parse error\n");
-
-        free(cloneUri);
-        return;
-    }
-    free(cloneUri);
-    return;
-}
-
-bool get_address_set(const char *pAddress, addressSet_t* outAddress)
-{
-    if (NULL == pAddress)
-    {
-        printf("parameter is null !\n");
-        return false;
-    }
-
-    size_t len = strlen(pAddress);
-    bool isIp = false;
-    size_t ipLen = 0;
-
-    for (size_t i = 0; i < len; i++)
-    {
-        if (pAddress[i] == '.')
-        {
-            isIp = true;
-        }
-
-        // found port number start index
-        if (isIp && pAddress[i] == ':')
-        {
-            ipLen = i;
-            break;
-        }
-    }
-
-    if (isIp)
-    {
-        if(ipLen && ipLen < sizeof(outAddress->ipAddress))
-        {
-            OICStrcpyPartial(outAddress->ipAddress, sizeof(outAddress->ipAddress),
-                             pAddress, ipLen);
-        }
-        else if (!ipLen && len < sizeof(outAddress->ipAddress))
-        {
-            OICStrcpyPartial(outAddress->ipAddress, sizeof(outAddress->ipAddress),
-                             pAddress, len);
-        }
-        else
-        {
-            printf("IP Address too long: %zu\n", (ipLen == 0) ? len : ipLen);
-            return false;
-        }
-
-        if (ipLen > 0)
-        {
-            outAddress->port = atoi(pAddress + ipLen + 1);
-        }
-        return true;
-    }
-    else
-    {
-        return false;
-    }
-}
-
-void create_file(CAPayload_t bytes, size_t length)
-{
-    FILE *fp = fopen("sample_output.txt", "wb");
-    if (fp)
-    {
-        fwrite(bytes, 1, length, fp);
-        fclose(fp);
-    }
-}
-
-bool read_file(const char* name, CAPayload_t* bytes, size_t* length)
-{
-    if (NULL == name)
-    {
-        printf("parameter is null\n");
-        return false;
-    }
-
-    FILE* file = NULL;
-    CAPayload_t buffer = NULL;
-    unsigned long fileLen = 0;
-
-    // Open file
-    file = fopen(name, "rb");
-    if (!file)
-    {
-        fprintf(stderr, "Unable to open file, %s\n", name);
-        return false;
-    }
-
-    // Get file length
-    fseek(file, 0, SEEK_END);
-    fileLen = ftell(file);
-    if (-1 == fileLen)
-    {
-        fprintf(stderr, "Failed to get file length\n");
-        fclose(file);
-        return false;
-    }
-    fseek(file, 0, SEEK_SET);
-
-    // Allocate memory
-    buffer = calloc(1, sizeof(uint8_t) * fileLen + 1);
-    if (!buffer)
-    {
-        fprintf(stderr, "Memory error\n");
-        fclose(file);
-        return false;
-    }
-
-    // Read file contents into buffer
-    size_t ret = fread(buffer, fileLen, 1, file);
-    if (ret != 1)
-    {
-        printf("Failed to read data from file, %s\n", name);
-        fclose(file);
-        free(buffer);
-        return false;
-    }
-
-    fclose(file);
-
-    *bytes = buffer;
-    *length = fileLen;
-
-    return true;
-}
diff --git a/resource/csdk/connectivity/samples/linux/threadpool/main.c b/resource/csdk/connectivity/samples/linux/threadpool/main.c
deleted file mode 100644 (file)
index 2e90d8c..0000000
+++ /dev/null
@@ -1,166 +0,0 @@
-/******************************************************************
- *
- * Copyright 2014 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 <stdio.h>
-#include <stdlib.h>
-
-#include "cathreadpool.h"
-#include "camutex.h"
-
-ca_thread_pool_t g_threadPoolHandle = NULL;
-
-ca_mutex g_mutex = NULL;
-ca_cond g_cond = NULL;
-bool g_condFlag = false;
-
-void task(void *data)
-{
-    printf("[TASK] Task is executing: data: %s\n", (char *) data);
-
-    //Signal the condition that task has been completed
-    printf("[TASK] Signaling the condition\n");
-    ca_mutex_lock(g_mutex);
-    g_condFlag = true;
-    ca_cond_signal(g_cond);
-    ca_mutex_unlock(g_mutex);
-}
-
-void testThreadPool(void)
-{
-    char *string = "Test thread pool";
-
-    //Initialize the mutex
-    printf("[testThreadPool] Initializing mutex\n");
-
-    //Initialize the thread pool
-    printf("[testThreadPool] Initializing thread pool\n");
-    if (CA_STATUS_OK != ca_thread_pool_init(2, &g_threadPoolHandle))
-    {
-        printf("thread_pool_init failed!\n");
-        return;
-    }
-
-    //Create the mutex
-    printf("[testThreadPool] Creating mutex\n");
-    g_mutex = ca_mutex_new();
-    if (NULL == g_mutex)
-    {
-        printf("[testThreadPool] Failed to create mutex!\n");
-        ca_thread_pool_free(g_threadPoolHandle);
-        return;
-    }
-
-    //Create the condition
-    printf("[testThreadPool] Creating Condition\n");
-    g_cond = ca_cond_new();
-    if (NULL == g_cond)
-    {
-        printf("[testThreadPool] Failed to create condition!\n");
-        ca_mutex_free(g_mutex);
-        ca_thread_pool_free(g_threadPoolHandle);
-        return;
-    }
-
-    //Lock the mutex
-    printf("[testThreadPool] Locking the mutex\n");
-    ca_mutex_lock(g_mutex);
-
-    g_condFlag = false;
-    //Add task to thread pool
-    printf("[testThreadPool] Adding the task to thread pool\n");
-    if (CA_STATUS_OK != ca_thread_pool_add_task(g_threadPoolHandle, task, (void *) string))
-    {
-        printf("[testThreadPool] thread_pool_add_task failed!\n");
-        ca_thread_pool_free(g_threadPoolHandle);
-        ca_mutex_unlock(g_mutex);
-        ca_mutex_free(g_mutex);
-        ca_cond_free(g_cond);
-        return;
-    }
-
-    //Wait for the task to be executed
-    printf("[testThreadPool] Waiting for the task to be completed\n");
-
-    while (!g_condFlag)
-    {
-        ca_cond_wait(g_cond, g_mutex);
-    }
-
-    //Unlock the mutex
-    printf("[testThreadPool] Got the signal and unlock the mutex\n");
-    ca_mutex_unlock(g_mutex);
-
-    printf("[testThreadPool] Task is completed and terminating threadpool\n");
-    ca_cond_free(g_cond);
-    ca_mutex_free(g_mutex);
-    ca_thread_pool_free(g_threadPoolHandle);
-
-    printf("Exiting from testThreadPool\n");
-}
-
-static void menu()
-{
-    printf(" =====================================================================\n");
-    printf("|                 Welcome to Theadpool testing                        |\n");
-    printf("|---------------------------------------------------------------------|\n");
-    printf("|                           ** Options **                             |\n");
-    printf("|  1 - Test Threadpool functionality                                  |\n");
-    printf("|  0 - Terminate test                                                 |\n");
-}
-
-static void startTesting(void)
-{
-    while (1)
-    {
-        int choice = -1;
-        if(scanf("%d", &choice) == 1)
-        {
-            switch (choice)
-            {
-                case 0:
-                    printf("Terminating test.\n");
-                    return;
-                case 1:
-                    testThreadPool();
-                    break;
-                default:
-                    printf("Invalid input.\n");
-                    menu();
-                    break;
-            }
-        }
-        else
-        {
-            printf("Invalid input.\n");
-            menu();
-        }
-
-        // clear input buffer
-        while (getchar() != '\n');
-    }
-}
-
-int main()
-{
-    menu();
-    startTesting();
-    return 0;
-}
-
diff --git a/resource/csdk/connectivity/samples/tizen/README.txt b/resource/csdk/connectivity/samples/tizen/README.txt
deleted file mode 100644 (file)
index a5e4283..0000000
+++ /dev/null
@@ -1,53 +0,0 @@
-Procedure to Execute Sample App:
-================================
-    1) Copy the generated rpm(com-oic-ca-sample-0.1-1.armv7l.rpm) to Tizen Device
-       (say /opt/usr/media/xxx/)
-    2) sdb shell
-    3) su
-    4) cd  /opt/usr/media/xxx/
-
-    5) change-booting-mode.sh --update
-
-    6) Install casample(console app). It contains Interface API libs and OIC-CORE Libs
-        i) rpm -Uvh com-oic-ca-sample-0.1-1.armv7l.rpm --force --nodeps
-
-    7) RPM will be installed in "/usr/apps/"
-       Execute the sample app by below commands
-        i) cd /usr/apps/com.oic.ca.sample/bin
-        ii) ./ca_sample (for CA Sample)
-
-Apply smack rule[ONLY for WIFI]
-===============================
-
-    1) After installing the RPMs, apply the following smack rule
-        a) chsmack -a "net-config" /usr/apps/com.oic.ca.sample/bin/ca_sample
-        b) chsmack -e "net-config" /usr/apps/com.oic.ca.sample/bin/ca_sample
-
-    Note: EDR adapter will give permission issues if these rules are applied.
-          So to test EDR adapter, delete the "/usr/apps/com.oic.ca.sample" folder
-          and again install the RPMs.
-
-Install Dependent RPMS(Only for EDR Adapter Testing)
-====================================================
-
-    1) In su(super user) mode, install Bluetooth related RPMs present in
-    "connectivity/lib/tizen/edr/rpms" on Tizen v2.3 mobile device
-    (Currently only SM Z910F Device is supported).
-    2) Install the Sample as given above in "Procedure to Execute Sample App"
-
-Install Dependent RPMS(Only for BLE Adapter Testing)
-====================================================
-
-    1) Flash the system image present in connectivity/lib/tizen/ble/image/ folder on SM Z910F Tizen v2.3
-    2) In su(super user) mode, Install Bluetooth related rpms Present in connectivity/lib/tizen/ble/rpms on
-    Tizen v2.3 mobile device (Currently only SM Z910F Device is supported)
-    3) Install the Sample as given above in "Procedure to Execute Sample App" [ Till Step 6 ]
-    4) Open another sdb shell, in su (super user) mode follow the below steps:
-            (i)   cd /var/lib/bluetooth
-            (ii)  Turn off Bluetooth in the device
-            (iii) rm -rf *
-            (iv)  Run the command ./usr/lib/bluetooth/bluetoothd -ndE &. for OIC Server device and
-            run the command ./usr/lib/bluetooth/bluetoothd -nd &. for OIC Client device.
-            (v)   Turn on the Bluetooth.
-    5) Run the sample as given in Step 8 of "Procedure to Execute Sample App"
-
diff --git a/resource/csdk/connectivity/samples/tizen/SConscript b/resource/csdk/connectivity/samples/tizen/SConscript
deleted file mode 100644 (file)
index 7013cf4..0000000
+++ /dev/null
@@ -1,267 +0,0 @@
-##
-# This script includes generic build options:
-#    release/debug, target os, target arch, cross toolchain, build environment etc
-##
-import os
-import platform
-
-# Map of host os and allowed target os (host: allowed target os)
-host_target_map = {
-               'linux': ['linux', 'android', 'arduino', 'yocto', 'tizen'],
-               'windows': ['windows', 'winrt', 'android', 'arduino', 'tizen'],
-               'darwin': ['darwin', 'ios', 'android', 'arduino'],
-               }
-
-# Map of os and allowed archs (os: allowed archs)
-os_arch_map = {
-               'linux': ['x86', 'x86_64', 'arm', 'arm64'],
-               'android': ['x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'armeabi-v7a-hard', 'arm64-v8a'],
-               'windows': ['x86', 'amd64', 'arm'],
-               'winrt': ['arm'],
-               'darwin': ['i386', 'x86_64'],
-               'ios': ['i386', 'x86_64', 'armv7', 'armv7s', 'arm64'],
-               'arduino': ['avr', 'arm'],
-                'yocto': ['x86', 'x86_64'],
-               'tizen': ['armv7'],
-               }
-
-host = platform.system().lower()
-
-if not host_target_map.has_key(host):
-       print "\nError: Current system (%s) isn't supported\n" % host
-       Exit(1)
-
-######################################################################
-# Get build options (the optins from command line)
-######################################################################
-target_os = ARGUMENTS.get('TARGET_OS', host).lower() # target os
-
-if target_os not in host_target_map[host]:
-       print "\nError: Unknown target os: %s (Allow values: %s)\n" % (target_os, host_target_map[host])
-       Exit(1)
-
-default_arch = platform.machine()
-if default_arch not in os_arch_map[target_os]:
-       default_arch = os_arch_map[target_os][0].lower()
-
-target_arch = ARGUMENTS.get('TARGET_ARCH', default_arch) # target arch
-
-######################################################################
-# Common build options (release, target os, target arch)
-######################################################################
-help_vars = Variables()
-help_vars.Add(BoolVariable('RELEASE', 'Build for release?', True)) # set to 'no', 'false' or 0 for debug
-help_vars.Add(EnumVariable('TARGET_OS', 'Target platform', host, host_target_map[host]))
-help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'IP', 'BT', 'BLE']))
-help_vars.Add(EnumVariable('TARGET_ARCH', 'Target architecture', default_arch, os_arch_map[target_os]))
-help_vars.Add(EnumVariable('SECURED', 'Build with DTLS', '0', allowed_values=('0', '1')))
-
-
-AddOption('--prefix',
-                  dest='prefix',
-                  type='string',
-                  nargs=1,
-                  action='store',
-                  metavar='DIR',
-                  help='installation prefix')
-
-######################################################################
-# Platform(build target) specific options: SDK/NDK & toolchain
-######################################################################
-targets_support_cc = ['linux', 'arduino', 'tizen']
-
-if target_os in targets_support_cc:
-       # Set cross compile toolchain
-       help_vars.Add('TC_PREFIX', "Toolchain prefix (Generally only be required for cross-compiling)", os.environ.get('TC_PREFIX'))
-       help_vars.Add(PathVariable('TC_PATH',
-                       'Toolchain path (Generally only be required for cross-compiling)',
-                       os.environ.get('TC_PATH')))
-
-if target_os in ['android', 'arduino']: # Android/Arduino always uses GNU compiler regardless of the host
-       env = Environment(variables = help_vars,
-                       tools = ['gnulink', 'gcc', 'g++', 'ar', 'as']
-                       )
-else:
-       env = Environment(variables = help_vars, TARGET_ARCH = target_arch, TARGET_OS = target_os, PREFIX = GetOption('prefix'))
-
-Help(help_vars.GenerateHelpText(env))
-
-tc_set_msg = '''
-************************************ Warning **********************************
-*   Enviornment variable TC_PREFIX/TC_PATH is set. It will change the default *
-* toolchain, if it isn't what you expect you should unset it, otherwise it may*
-* cause inexplicable errors.                                                  *
-*******************************************************************************
-'''
-
-if target_os in targets_support_cc:
-       prefix = env.get('TC_PREFIX')
-       tc_path = env.get('TC_PATH')
-       if prefix:
-               env.Replace(CC = prefix + 'gcc')
-               env.Replace(CXX = prefix + 'g++')
-               env.Replace(AR = prefix + 'ar')
-               env.Replace(AS = prefix + 'as')
-               env.Replace(LINK = prefix + 'ld')
-               env.Replace(RANLIB = prefix + 'ranlib')
-
-       if tc_path:
-               env.PrependENVPath('PATH', tc_path)
-               sys_root = os.path.abspath(tc_path + '/../')
-               env.AppendUnique(CCFLAGS = ['--sysroot=' + sys_root])
-               env.AppendUnique(LINKFLAGS = ['--sysroot=' + sys_root])
-
-       if prefix or tc_path:
-               print tc_set_msg
-
-# Ensure scons be able to change its working directory
-env.SConscriptChdir(1)
-
-# Set the source directory and build directory
-#   Source directory: 'dir'
-#   Build directory: 'dir'/out/<target_os>/<target_arch>/<release or debug>/
-#
-# You can get the directory as following:
-#   env.get('SRC_DIR')
-#   env.get('BUILD_DIR')
-
-def __set_dir(env, dir):
-       if not os.path.exists(dir + '/SConstruct'):
-               print '''
-*************************************** Error *********************************
-* The directory(%s) seems isn't a source code directory, no SConstruct file is
-* found. *
-*******************************************************************************
-''' % dir
-               Exit(1)
-
-       if env.get('RELEASE'):
-               build_dir = dir + '/out/' + target_os + '/' + target_arch + '/release/'
-       else:
-               build_dir = dir + '/out/' + target_os + '/' + target_arch + '/debug/'
-       env.VariantDir(build_dir, dir, duplicate=0)
-
-       env.Replace(BUILD_DIR = build_dir)
-       env.Replace(SRC_DIR = dir)
-
-def __src_to_obj(env, src, home = ''):
-       obj = env.get('BUILD_DIR') + src.replace(home, '')
-       if env.get('OBJSUFFIX'):
-               obj += env.get('OBJSUFFIX')
-       return env.Object(obj, src)
-
-def __install(ienv, targets, name):
-       i_n = ienv.Install(env.get('BUILD_DIR'), targets)
-       Alias(name, i_n)
-       env.AppendUnique(TS = [name])
-
-def __append_target(ienv, target):
-       env.AppendUnique(TS = [target])
-
-def __installlib(ienv, targets, name):
-       user_prefix = env.get('PREFIX')
-       if user_prefix:
-               i_n = ienv.Install(user_prefix + '/lib', targets)
-       else:
-               i_n = ienv.Install(env.get('BUILD_DIR'), targets)
-       ienv.Alias("install", i_n)
-
-def __installbin(ienv, targets, name):
-       user_prefix = env.get('PREFIX')
-       if user_prefix:
-               i_n = ienv.Install(user_prefix + '/bin', targets)
-       else:
-               i_n = ienv.Install(env.get('BUILD_DIR'), targets)
-       ienv.Alias("install", i_n)
-
-def __print_targets(env):
-       Help('''
-===============================================================================
-Targets:\n    ''')
-       for t in env.get('TS'):
-               Help(t + ' ')
-       Help('''
-\nDefault all targets will be built. You can specify the target to build:
-
-    $ scons [options] [target]
-===============================================================================
-''')
-
-env.AddMethod(__set_dir, 'SetDir')
-env.AddMethod(__print_targets, 'PrintTargets')
-env.AddMethod(__src_to_obj, 'SrcToObj')
-env.AddMethod(__append_target, 'AppendTarget')
-env.AddMethod(__install, 'InstallTarget')
-env.AddMethod(__installlib, 'UserInstallTargetLib')
-env.AddMethod(__installbin, 'UserInstallTargetBin')
-env.SetDir(env.GetLaunchDir())
-env['ROOT_DIR']=env.GetLaunchDir()
-
-Export('env')
-
-######################################################################
-# Link scons to Yocto cross-toolchain ONLY when target_os is yocto
-######################################################################
-if target_os == "yocto":
-    '''
-    This code injects Yocto cross-compilation tools+flags into scons'
-    build environment in order to invoke the relevant tools while
-    performing a build.
-    '''
-    import os.path
-    try:
-        CC = os.environ['CC']
-        target_prefix = CC.split()[0]
-        target_prefix = target_prefix[:len(target_prefix)-3]
-        tools = {"CC" : target_prefix+"gcc",
-                "CXX" : target_prefix+"g++",
-                "AS" : target_prefix+"as",
-                "LD" : target_prefix+"ld",
-                "GDB" : target_prefix+"gdb",
-                "STRIP" : target_prefix+"strip",
-                "RANLIB" : target_prefix+"ranlib",
-                "OBJCOPY" : target_prefix+"objcopy",
-                "OBJDUMP" : target_prefix+"objdump",
-                "AR" : target_prefix+"ar",
-                "NM" : target_prefix+"nm",
-                "M4" : "m4",
-                "STRINGS": target_prefix+"strings"}
-        PATH = os.environ['PATH'].split(os.pathsep)
-        for tool in tools:
-            if tool in os.environ:
-                for path in PATH:
-                    if os.path.isfile(os.path.join(path, tools[tool])):
-                        env[tool] = os.path.join(path, os.environ[tool])
-                        break
-    except:
-        print "ERROR in Yocto cross-toolchain environment"
-        Exit(1)
-    '''
-    Now reset TARGET_OS to linux so that all linux specific build configurations
-    hereupon apply for the entirety of the build process.
-    '''
-    env['TARGET_OS'] = 'linux'
-    '''
-    We want to preserve debug symbols to allow BitBake to generate both DEBUG and
-    RELEASE packages for OIC.
-    '''
-    env['CCFLAGS'].append('-g')
-    Export('env')
-else:
-    '''
-    If target_os is not Yocto, continue with the regular build process
-    '''
-    # Load config of target os
-    env.SConscript(target_os + '/SConscript')
-
-# Delete the temp files of configuration
-if env.GetOption('clean'):
-       dir = env.get('SRC_DIR')
-
-       if os.path.exists(dir + '/config.log'):
-               Execute(Delete(dir + '/config.log'))
-               Execute(Delete(dir + '/.sconsign.dblite'))
-               Execute(Delete(dir + '/.sconf_temp'))
-
-Return('env')
-
diff --git a/resource/csdk/connectivity/samples/tizen/casample.c b/resource/csdk/connectivity/samples/tizen/casample.c
deleted file mode 100644 (file)
index 7e0810f..0000000
+++ /dev/null
@@ -1,1449 +0,0 @@
-/******************************************************************
- *
- * Copyright 2014 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 <glib.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <stdbool.h>
-#include <pthread.h>
-#include "cacommon.h"
-#include "cainterface.h"
-
-/**
- * @def MAX_BUF_LEN
- * @brief maximum buffer length
- */
-#define MAX_BUF_LEN 1024
-
-/**
- * @def MAX_OPT_LEN
- * @brief maximum option length
- */
-#define MAX_OPT_LEN 16
-
-/**
- * @def PORT_LENGTH
- * @brief maximum port length
- */
-#define PORT_LENGTH 5
-
-/**
- * @def SECURE_DEFAULT_PORT
- * @brief default secured port
- */
-#define SECURE_DEFAULT_PORT 5684
-
-#define RESOURCE_URI_LENGTH 14
-
-#define COAP_PREFIX          "coap://"
-#define COAP_PREFIX_LEN      7
-#define COAPS_PREFIX         "coaps://"
-#define COAPS_PREFIX_LEN     8
-
-#define COAP_TCP_PREFIX      "coap+tcp://"
-#define COAP_TCP_PREFIX_LEN  11
-
-// Iotivity Device Identity.
-const unsigned char IDENTITY[] = ("1111111111111111");
-
-// PSK between this device and peer device.
-const unsigned char RS_CLIENT_PSK[] = ("AAAAAAAAAAAAAAAA");
-
-/**
- * Max size for big payload.
- */
-#define BIG_PAYLOAD_SIZE 15000
-
-static GMainLoop *g_mainloop = NULL;
-pthread_t thread;
-
-int g_received;
-uint16_t g_local_secure_port = SECURE_DEFAULT_PORT;
-CATransportAdapter_t g_selected_nw_type = CA_ADAPTER_IP;
-const char *MESSAGE_TYPE[] = {"CON", "NON", "ACK", "RESET"};
-
-typedef struct
-{
-    char ipAddress[CA_IPADDR_SIZE];
-    uint16_t port;
-} addressSet_t;
-
-char get_menu();
-void process();
-CAResult_t get_network_type();
-CAResult_t get_input_data(char *buf, int32_t length);
-
-bool select_payload();
-void populate_binary_payload(uint8_t *bigBuffer, size_t bigBufferLen);
-
-void start_listening_server();
-void start_discovery_server();
-void send_request();
-void send_request_all();
-void send_notification();
-void select_network();
-void unselect_network();
-void handle_request_response();
-void get_network_info();
-void send_secure_request();
-
-void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo);
-void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo);
-void error_handler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
-void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info);
-void get_resource_uri(char *URI, char *resourceURI, int length);
-int get_secure_information(CAPayload_t payLoad);
-int get_address_set(const char *uri, addressSet_t* outAddress);
-void parse_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags);
-
-static CAToken_t g_last_request_token = NULL;
-static const char SECURE_COAPS_PREFIX[] = "coaps://";
-static const char SECURE_INFO_DATA[] =
-    "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
-    "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
-static const char NORMAL_INFO_DATA[] =
-    "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
-    "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
-
-#ifdef __WITH_DTLS__
-// Internal API. Invoked by CA stack to retrieve credentials from this module.
-int32_t CAGetDtlsPskCredentials( CADtlsPskCredType_t type,
-              const unsigned char *desc, size_t desc_len,
-              unsigned char *result, size_t result_length)
-{
-    printf("CAGetDtlsPskCredentials IN\n");
-
-    int32_t ret = -1;
-
-    if (NULL == result)
-    {
-        return ret;
-    }
-
-    switch (type)
-    {
-        case CA_DTLS_PSK_HINT:
-        case CA_DTLS_PSK_IDENTITY:
-
-            if (result_length < sizeof(IDENTITY))
-            {
-                printf("ERROR : Wrong value for result for storing IDENTITY");
-                return ret;
-            }
-
-            memcpy(result, IDENTITY, sizeof(IDENTITY));
-            ret = sizeof(IDENTITY);
-            break;
-
-        case CA_DTLS_PSK_KEY:
-
-            if ((desc_len == sizeof(IDENTITY)) &&
-                memcmp(desc, IDENTITY, sizeof(IDENTITY)) == 0)
-            {
-                if (result_length < sizeof(RS_CLIENT_PSK))
-                {
-                    printf("ERROR : Wrong value for result for storing RS_CLIENT_PSK");
-                    return ret;
-                }
-
-                memcpy(result, RS_CLIENT_PSK, sizeof(RS_CLIENT_PSK));
-                ret = sizeof(RS_CLIENT_PSK);
-            }
-            break;
-
-        default:
-
-            printf("Wrong value passed for PSK_CRED_TYPE.");
-            ret = -1;
-    }
-
-    printf("CAGetDtlsPskCredentials OUT\n");
-    return ret;
-}
-#endif
-
-void GMainLoopThread()
-{
-    g_main_loop_run(g_mainloop);
-}
-
-CAResult_t Initialize()
-{
-    g_mainloop = g_main_loop_new(NULL, FALSE);
-    if(!g_mainloop)
-    {
-        printf("g_main_loop_new failed\n");
-        return CA_STATUS_FAILED;
-    }
-
-    int result = pthread_create(&thread, NULL, (void *) &GMainLoopThread, NULL);
-    if (result < 0)
-    {
-        printf("pthread_create failed in initialize\n");
-        return CA_STATUS_FAILED;
-    }
-
-    CAResult_t res = CAInitialize();
-    if (res != CA_STATUS_OK)
-    {
-        printf("CAInitialize fail\n");
-    }
-    return res;
-}
-
-int main()
-{
-    int ret = system("clear");
-    // shell invoke error: 127, others: -1
-    if (127 == ret || -1 == ret)
-    {
-        printf("Terminal Clear Error: %d\n", ret);
-    }
-
-    printf("=============================================\n");
-    printf("\t\tsample main\n");
-    printf("=============================================\n");
-
-    CAResult_t res = Initialize();
-    if (CA_STATUS_OK != res)
-    {
-        printf("Initialization is  failed\n");
-        return -1;
-    }
-
-    // Set the PSK Credentials callback handler.
-#ifdef __WITH_DTLS__
-    res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
-    if (CA_STATUS_OK != res)
-    {
-        printf("Set credential handler fail\n");
-        return -1;
-    }
-#endif
-
-    // set handler.
-    CARegisterHandler(request_handler, response_handler, error_handler);
-
-    process();
-
-    CADestroyToken(g_last_request_token);
-
-    CATerminate();
-    return 0;
-}
-
-void process()
-{
-    while (1)
-    {
-        char menu = get_menu();
-
-        switch (menu)
-        {
-            case 'm': // menu
-            case 'M':
-                break;
-
-            case 'q': // quit
-            case 'Q':
-                printf("quit..!!\n");
-                return;
-
-            case 's': // start server
-            case 'S':
-                start_listening_server();
-                break;
-
-            case 't': // send request
-            case 'T':
-                send_request_all();
-                break;
-
-            case 'c': // start client
-            case 'C':
-                start_discovery_server();
-                break;
-
-            case 'r': // send request
-            case 'R':
-                send_request();
-                break;
-
-            case 'b': // send notification
-            case 'B':
-                send_notification();
-                break;
-
-            case 'n': // select network
-            case 'N':
-                select_network();
-                break;
-
-            case 'x': // unselect network
-            case 'X':
-                unselect_network();
-                break;
-
-            case 'h': // handle request response
-            case 'H':
-                handle_request_response();
-                break;
-
-            case 'w':
-            case 'W':
-                g_received = 0;
-                start_discovery_server();
-                send_secure_request();
-                while (g_received == 0)
-                {
-                    sleep(1);
-                    handle_request_response();
-                }
-                break;
-
-            case 'z':
-            case 'Z':
-                start_listening_server();
-                while (1)
-                {
-                    sleep(1);
-                    handle_request_response();
-                }
-                break;
-
-            case 'g': // get network information
-            case 'G':
-                get_network_info();
-                break;
-
-            default:
-                printf("Not supported menu!!\n");
-                break;
-        }
-    }
-
-}
-
-void start_listening_server()
-{
-    printf("Start listening server!!\n");
-
-    CAResult_t res = CAStartListeningServer();
-    if (CA_STATUS_OK != res)
-    {
-        printf("Start listening server fail, error code : %d\n", res);
-    }
-    else
-    {
-        printf("Start listening server success\n");
-    }
-}
-
-void start_discovery_server()
-{
-    printf("Start discovery client!!\n");
-
-    CAResult_t res = CAStartDiscoveryServer();
-    if (CA_STATUS_OK != res)
-    {
-        printf("Start discovery client fail, error code : %d\n", res);
-    }
-    else
-    {
-        printf("Start discovery client success\n");
-    }
-}
-
-bool select_payload()
-{
-    char buf[MAX_BUF_LEN]={0};
-    printf("\n=============================================\n");
-    printf("0:Normal Payload\n1:Big Payload(~15KB)\n");
-    printf("select Payload type : ");
-
-    CAResult_t res = get_input_data(buf, sizeof(buf));
-    if (CA_STATUS_OK != res)
-    {
-        printf("Payload type selection error\n");
-        printf("Default: Using normal Payload\n");
-        return false;
-    }
-
-    return (buf[0] == '1') ? true : false;
-}
-
-void populate_binary_payload(uint8_t *bigBuffer, size_t bigBufferLen)
-{
-/**
- * bigBuffer to be filled with binary data. For our sample application to verify, we may fill with
- * any arbitrary value. Hence filling with '1' here.
- */
-    memset(bigBuffer, '1', bigBufferLen-1);
-    //Last byte making NULL
-    bigBuffer[bigBufferLen-1] = '\0';
-}
-
-void send_request()
-{
-    CAResult_t res = get_network_type();
-    if (CA_STATUS_OK != res)
-    {
-        return;
-    }
-
-    printf("Do you want to send secure request ?.... enter (0/1): ");
-
-    char secureRequest[MAX_BUF_LEN] = {0};
-    if (CA_STATUS_OK != get_input_data(secureRequest, MAX_BUF_LEN))
-    {
-        return;
-    }
-
-    if (strcmp(secureRequest, "1") == 0)
-    {
-        printf("Enter the URI like below....\n");
-        printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
-    }
-    else if (strcmp(secureRequest, "0") == 0)
-    {
-        printf("Enter the URI like below....\n");
-        printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
-        printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
-        printf("coap+tcp://10:11:12:13:45:45/resource_uri ( for TCP )\n");
-    }
-    else
-    {
-        printf("Input data is wrong value\n");
-        return;
-    }
-
-    char uri[MAX_BUF_LEN] = {'\0'};
-    if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
-    {
-        return;
-    }
-
-    // create remote endpoint
-    CAEndpoint_t *endpoint = NULL;
-    CATransportFlags_t flags;
-
-    printf("URI : %s\n", uri);
-    addressSet_t address = {};
-    parse_coap_uri(uri, &address, &flags);
-
-    res = CACreateEndpoint(flags, g_selected_nw_type,
-                           (const char*)address.ipAddress, address.port, &endpoint);
-    if (CA_STATUS_OK != res || !endpoint)
-    {
-        printf("Failed to create remote endpoint, error code : %d\n", res);
-        return;
-    }
-
-    printf("\n=============================================\n");
-    printf("0:CON, 1:NON\n");
-    printf("select message type : ");
-
-    char buf[MAX_BUF_LEN] = { 0 };
-    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
-    {
-        CADestroyEndpoint(endpoint);
-        return;
-    }
-
-    CAMessageType_t msgType = (buf[0] == '1') ? 1 : 0;
-
-    // create token
-    CAToken_t token = NULL;
-    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
-
-    res = CAGenerateToken(&token, tokenLength);
-    if ((CA_STATUS_OK != res) || (!token))
-    {
-        printf("Token generate error, error code : %d\n", res);
-        CADestroyEndpoint(endpoint);
-        return;
-    }
-
-    printf("Generated token %s\n", token);
-
-    // extract relative resourceuri from give uri
-    char resourceURI[RESOURCE_URI_LENGTH + 1] = {0};
-    get_resource_uri(uri, resourceURI, RESOURCE_URI_LENGTH);
-    printf("resourceURI : %s\n", resourceURI);
-
-    // create request data
-    CAInfo_t requestData = { 0 };
-    requestData.token = token;
-    requestData.tokenLength = tokenLength;
-    requestData.resourceUri = (CAURI_t)resourceURI;
-
-    if (strcmp(secureRequest, "1") == 0)
-    {
-        size_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
-        requestData.payload = (CAPayload_t) calloc(length,  sizeof(char));
-        if (NULL == requestData.payload)
-        {
-            printf("Memory allocation fail\n");
-            CADestroyEndpoint(endpoint);
-            CADestroyToken(token);
-            return;
-        }
-        snprintf((char *) requestData.payload, length, SECURE_INFO_DATA,
-                 (const char *) resourceURI, g_local_secure_port);
-    }
-    else
-    {
-        bool useBigPayload = select_payload();
-        if (useBigPayload)
-        {
-            requestData.payload = (CAPayload_t) calloc(BIG_PAYLOAD_SIZE, sizeof(char));
-            if (NULL == requestData.payload)
-            {
-                printf("Memory allocation fail\n");
-                CADestroyEndpoint(endpoint);
-                CADestroyToken(token);
-                return;
-            }
-            populate_binary_payload(requestData.payload, BIG_PAYLOAD_SIZE);
-        }
-        else
-        {
-            size_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
-            requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
-            if (NULL == requestData.payload)
-            {
-                printf("Memory allocation fail\n");
-                CADestroyEndpoint(endpoint);
-                CADestroyToken(token);
-                return;
-            }
-            snprintf((char *) requestData.payload, length, NORMAL_INFO_DATA,
-                     (const char *) resourceURI);
-        }
-    }
-    requestData.payloadSize = strlen((char *)requestData.payload)+1;
-    requestData.type = msgType;
-
-    CARequestInfo_t requestInfo = { 0 };
-    requestInfo.method = CA_GET;
-    requestInfo.info = requestData;
-    requestInfo.isMulticast = false;
-
-    // send request
-    res = CASendRequest(endpoint, &requestInfo);
-    if (CA_STATUS_OK != res)
-    {
-        printf("Could not send request : %d\n", res);
-    }
-
-    //destroy token
-    CADestroyToken(token);
-    // destroy remote endpoint
-    CADestroyEndpoint(endpoint);
-    free(requestData.payload);
-
-
-    printf("=============================================\n");
-}
-
-void send_secure_request()
-{
-    char ipv4addr[CA_IPADDR_SIZE];
-
-    printf("\n=============================================\n");
-    printf("Enter IPv4 address of the source hosting secure resource (Ex: 11.12.13.14)\n");
-
-    if (CA_STATUS_OK != get_input_data(ipv4addr, CA_IPADDR_SIZE))
-    {
-        return;
-    }
-    printf("%s%s:5684/a/light", SECURE_COAPS_PREFIX, ipv4addr);
-
-    // create remote endpoint
-    CAEndpoint_t *endpoint = NULL;
-    CAResult_t res = CACreateEndpoint(0, CA_ADAPTER_IP, ipv4addr, SECURE_DEFAULT_PORT, &endpoint);
-    if (CA_STATUS_OK != res)
-    {
-        printf("Failed to create remote endpoint, error code: %d\n", res);
-        goto exit;
-    }
-
-    // create token
-    CAToken_t token = NULL;
-    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
-
-    res = CAGenerateToken(&token, tokenLength);
-    if ((CA_STATUS_OK != res) || (!token))
-    {
-        printf("Token generate error, error code : %d\n", res);
-        goto exit;
-    }
-
-    printf("Generated token %s\n", token);
-
-    // create request data
-    CAMessageType_t msgType = CA_MSG_NONCONFIRM;
-    CAInfo_t requestData = { 0 };
-    requestData.token = token;
-    requestData.tokenLength = tokenLength;
-    requestData.type = msgType;
-    requestData.payload = "Temp Json Payload";
-    requestData.payloadSize = strlen(requestData.payload)+1;
-
-    CARequestInfo_t requestInfo = { 0 };
-    requestInfo.method = CA_GET;
-    requestInfo.info = requestData;
-    requestInfo.isMulticast = false;
-
-    // send request
-    CASendRequest(endpoint, &requestInfo);
-
-exit:
-    // cleanup
-    CADestroyToken(token);
-    CADestroyEndpoint(endpoint);
-    printf("=============================================\n");
-}
-
-
-void send_request_all()
-{
-    CAResult_t res = get_network_type();
-    if (CA_STATUS_OK != res)
-    {
-        return;
-    }
-
-    printf("\n=============================================\n");
-    printf("ex) /a/light\n");
-    printf("resource uri : ");
-
-    char resourceURI[MAX_BUF_LEN] = { 0 };
-    if (CA_STATUS_OK != get_input_data(resourceURI, MAX_BUF_LEN))
-    {
-        return;
-    }
-
-    // create remote endpoint
-    CAEndpoint_t *endpoint = NULL;
-    res = CACreateEndpoint(CA_IPV4, g_selected_nw_type, NULL, 0, &endpoint);
-    if (CA_STATUS_OK != res)
-    {
-        printf("Create remote endpoint error, error code: %d\n", res);
-        return;
-    }
-
-    // create token
-    CAToken_t token = NULL;
-    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
-
-    res = CAGenerateToken(&token, tokenLength);
-    if ((CA_STATUS_OK != res) || (!token))
-    {
-        printf("Token generate error!!\n");
-        CADestroyEndpoint(endpoint);
-        return;
-    }
-
-    printf("generated token %s\n", token);
-
-    CAInfo_t requestData = { 0 };
-    requestData.token = token;
-    requestData.tokenLength = tokenLength;
-    requestData.payload = (CAPayload_t) "TempJsonPayload";
-    requestData.payloadSize = strlen((const char *) requestData.payload);
-    requestData.type = CA_MSG_NONCONFIRM;
-    requestData.resourceUri = (CAURI_t)resourceURI;
-
-    CARequestInfo_t requestInfo = { 0 };
-    requestInfo.method = CA_GET;
-    requestInfo.info = requestData;
-    requestInfo.isMulticast = true;
-
-    // send request
-    res = CASendRequest(endpoint, &requestInfo);
-    if (CA_STATUS_OK != res)
-    {
-        printf("Could not send request to all\n");
-    }
-    else
-    {
-        CADestroyToken(g_last_request_token);
-        g_last_request_token = token;
-    }
-
-    // destroy remote endpoint
-    CADestroyEndpoint(endpoint);
-
-    printf("=============================================\n");
-}
-
-void send_notification()
-{
-    CAResult_t res = get_network_type();
-    if (CA_STATUS_OK != res)
-    {
-        return;
-    }
-
-    printf("\n=============================================\n");
-    printf("Enter the URI like below....\n");
-    printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
-    printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
-    printf("uri : ");
-
-    char uri[MAX_BUF_LEN] = { 0 };
-    if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
-    {
-        return;
-    }
-
-    printf("\n=============================================\n");
-    printf("\tselect message type\n");
-    printf("CON     : 0\n");
-    printf("NON     : 1\n");
-    printf("ACK     : 2\n");
-    printf("RESET   : 3\n");
-
-    printf("select : ");
-
-    char messageTypeBuf[MAX_BUF_LEN] = { 0 };
-    if (CA_STATUS_OK != get_input_data(messageTypeBuf, MAX_BUF_LEN))
-    {
-        return;
-    }
-
-    int messageType = messageTypeBuf[0] - '0';
-
-    switch(messageType)
-    {
-        case 0:
-                printf("CONFIRM messagetype is selected\n");
-                break;
-        case 1:
-                printf("NONCONFIRM messagetype is selected\n");
-                break;
-        default:
-                printf("Invalid Selection\n");
-                return;
-    }
-
-    CATransportFlags_t flags;
-    addressSet_t address = {};
-    parse_coap_uri(uri, &address, &flags);
-
-    // create remote endpoint
-    CAEndpoint_t *endpoint = NULL;
-    res = CACreateEndpoint(flags, g_selected_nw_type, address.ipAddress, address.port, &endpoint);
-    if (CA_STATUS_OK != res)
-    {
-        printf("Create remote endpoint error, error code: %d\n", res);
-        return;
-    }
-
-    // create token
-    CAToken_t token = NULL;
-    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
-
-    res = CAGenerateToken(&token, tokenLength);
-    if ((CA_STATUS_OK != res) || (!token))
-    {
-        printf("Token generate error!!\n");
-        CADestroyEndpoint(endpoint);
-        return;
-    }
-
-    printf("Generated token %s\n", token);
-
-    CAInfo_t requestData = { 0 };
-    requestData.token = token;
-    requestData.tokenLength = tokenLength;
-    requestData.payload = (CAPayload_t) "TempNotificationData";
-    requestData.payloadSize = strlen((const char *) requestData.payload);
-    requestData.type = messageType;
-    requestData.resourceUri = (CAURI_t)uri;
-
-    CARequestInfo_t requestInfo = { 0 };
-    requestInfo.method = CA_GET;
-    requestInfo.info = requestData;
-
-    // send notification
-    res = CASendRequest(endpoint, &requestInfo);
-    if (CA_STATUS_OK != res)
-    {
-        printf("Send notification error, error code: %d\n", res);
-    }
-    else
-    {
-        printf("Send notification success\n");
-    }
-
-    // destroy token
-    CADestroyToken(token);
-    // destroy remote endpoint
-    CADestroyEndpoint(endpoint);
-
-    printf("\n=============================================\n");
-}
-
-void select_network()
-{
-    printf("\n=============================================\n");
-    printf("\tselect network\n");
-    printf("IP     : 0\n");
-    printf("GATT   : 1\n");
-    printf("RFCOMM : 2\n");
-    printf("TCP    : 4\n");
-    printf("select : ");
-
-    char buf[MAX_BUF_LEN] = { 0 };
-    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
-    {
-        return;
-    }
-
-    int number = buf[0] - '0';
-
-    if (number < 0 || number > 4)
-    {
-        printf("Invalid network type\n");
-        return;
-    }
-
-    CAResult_t res = CASelectNetwork(1 << number);
-    if (CA_STATUS_OK != res)
-    {
-        printf("Select network error\n");
-        g_selected_nw_type = 1 << number;
-    }
-    else
-    {
-        printf("Select network success\n");
-    }
-    printf("=============================================\n");
-}
-
-void unselect_network()
-{
-    printf("\n=============================================\n");
-    printf("\tunselect enabled network\n");
-    printf("IP     : 0\n");
-    printf("GATT   : 1\n");
-    printf("RFCOMM : 2\n");
-    printf("TCP    : 4\n");
-    printf("select : ");
-
-    char buf[MAX_BUF_LEN] = { 0 };
-    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
-    {
-        return;
-    }
-
-    int number = buf[0] - '0';
-
-    if (number < 0 || number > 4)
-    {
-        printf("Invalid network type\n");
-        return;
-    }
-
-    CAResult_t res = CAUnSelectNetwork(1 << number);
-    if (CA_STATUS_OK != res)
-    {
-        printf("Unselect network error\n");
-    }
-    else
-    {
-        printf("Unselect network success\n");
-    }
-
-    printf("=============================================\n");
-}
-
-char get_menu()
-{
-    printf("\n=============================================\n");
-    printf("\t\tMenu\n");
-    printf("\ts : start server\n");
-    printf("\tc : start client\n");
-    printf("\tr : send request\n");
-    printf("\tt : send request to all\n");
-    printf("\tb : send notification\n");
-    printf("\tn : select network\n");
-    printf("\tx : unselect network\n");
-    printf("\tg : get network information\n");
-    printf("\th : handle request response\n");
-    printf("\tz : run static server\n");
-    printf("\tw : send secure request\n");
-    printf("\tq : quit\n");
-    printf("=============================================\n");
-    printf("select : ");
-
-    char buf[MAX_BUF_LEN] = { 0 };
-    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
-    {
-        printf("Failed to get input data\n");
-    }
-
-    return buf[0];
-}
-
-void handle_request_response()
-{
-    printf("Handle_request_response\n");
-
-    CAResult_t res = CAHandleRequestResponse();
-    if (CA_STATUS_OK != res)
-    {
-        printf("Handle request error, error code: %d\n", res);
-    }
-    else
-    {
-        printf("Handle request success\n");
-    }
-}
-
-void get_network_info()
-{
-    CAEndpoint_t *tempInfo = NULL;
-    uint32_t tempSize = 0;
-
-    CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
-    if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize)
-    {
-        printf("Network not connected\n");
-        free(tempInfo);
-        return;
-    }
-
-    printf("################## Network Information #######################\n");
-    printf("Network info total size is %d\n\n", tempSize);
-
-    int index;
-    for (index = 0; index < tempSize; index++)
-    {
-        printf("Type: %d\n", tempInfo[index].adapter);
-        if (CA_ADAPTER_IP == tempInfo[index].adapter)
-        {
-            printf("Address: %s\n", tempInfo[index].addr);
-            printf("Port: %d\n", tempInfo[index].port);
-        }
-        else
-        {
-            printf("Address: %s\n", tempInfo[index].addr);
-        }
-
-        printf("Secured: %s\n\n", (tempInfo[index].flags & CA_SECURE) ? "true" : "false");
-
-        if (tempInfo[index].flags & CA_SECURE)
-        {
-            g_local_secure_port = tempInfo[index].port;
-            printf("Secured: in global %d\n\n", g_local_secure_port);
-        }
-    }
-
-    free(tempInfo);
-    printf("##############################################################");
-}
-
-void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo)
-{
-    if (NULL == object || NULL == requestInfo)
-    {
-        printf("Input parameter is NULL\n");
-        return;
-    }
-
-    if ((NULL != g_last_request_token) && (NULL != requestInfo->info.token)
-        && (strncmp(g_last_request_token, requestInfo->info.token,
-                    requestInfo->info.tokenLength) == 0))
-    {
-        printf("Token is same. received request of it's own. skip.. \n");
-        return;
-    }
-
-    printf("##########received request from remote device #############\n");
-    if (CA_ADAPTER_IP == object->adapter)
-    {
-        printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
-               object->port, object->flags & CA_SECURE);
-    }
-    else
-    {
-        printf("Remote Address: %s \n", object->addr);
-    }
-    printf("Data: %s\n", requestInfo->info.payload);
-    printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]);
-
-    if (requestInfo->info.options)
-    {
-        uint32_t len = requestInfo->info.numOptions;
-        uint32_t i;
-        for (i = 0; i < len; i++)
-        {
-            printf("Option %d\n", i + 1);
-            printf("ID : %d\n", requestInfo->info.options[i].optionID);
-            printf("Data[%d]: %s\n", requestInfo->info.options[i].optionLength,
-                   requestInfo->info.options[i].optionData);
-        }
-    }
-    printf("############################################################\n");
-
-    //Check if this has secure communication information
-    if (requestInfo->info.payload &&
-            (CA_ADAPTER_IP == object->adapter))
-    {
-        int securePort = get_secure_information(requestInfo->info.payload);
-        if (0 < securePort) //Set the remote endpoint secure details and send response
-        {
-            printf("This is secure resource...\n");
-
-            CAEndpoint_t *endpoint = NULL;
-            if (CA_STATUS_OK != CACreateEndpoint(0, object->adapter, object->addr,
-                                                 object->port, &endpoint))
-            {
-                printf("Failed to create duplicate of remote endpoint!\n");
-                return;
-            }
-            endpoint->flags = CA_SECURE;
-            object = endpoint;
-        }
-    }
-
-    printf("Send response with URI\n");
-    send_response(object, &requestInfo->info);
-
-    g_received = 1;
-}
-
-void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
-{
-    printf("##########Received response from remote device #############\n");
-    if (CA_ADAPTER_IP == object->adapter)
-    {
-        printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
-               object->port, object->flags & CA_SECURE);
-    }
-    else
-    {
-        printf("Remote Address: %s \n", object->addr);
-    }
-
-    printf("resource uri : %s\n", responseInfo->info.resourceUri);
-    printf("response result : %d\n", responseInfo->result);
-    printf("Data: %s\n", responseInfo->info.payload);
-    printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]);
-    printf("Token: %s\n", responseInfo->info.token);
-    if (responseInfo->info.options)
-    {
-        uint32_t len = responseInfo->info.numOptions;
-        uint32_t i;
-        for (i = 0; i < len; i++)
-        {
-            printf("Option %d\n", i + 1);
-            printf("ID : %d\n", responseInfo->info.options[i].optionID);
-            printf("Data[%d]: %s\n", responseInfo->info.options[i].optionLength,
-                   responseInfo->info.options[i].optionData);
-        }
-    }
-    printf("############################################################\n");
-    g_received = 1;
-
-    //Check if this has secure communication information
-    if (responseInfo->info.payload)
-    {
-        int securePort = get_secure_information(responseInfo->info.payload);
-        if (0 < securePort) //Set the remote endpoint secure details and send response
-        {
-            printf("This is secure resource...\n");
-        }
-    }
-}
-
-void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
-{
-    printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++\n");
-
-    if(errorInfo)
-    {
-        const CAInfo_t *info = &errorInfo->info;
-        printf("Error Handler, ErrorInfo :\n");
-        printf("Error Handler result    : %d\n", errorInfo->result);
-        printf("Error Handler token     : %s\n", info->token);
-        printf("Error Handler messageId : %d\n", (uint16_t) info->messageId);
-        printf("Error Handler type      : %d\n", info->type);
-        printf("Error Handler resourceUri : %s\n", info->resourceUri);
-        printf("Error Handler payload   : %s\n", info->payload);
-
-        if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
-        {
-            printf("CA_ADAPTER_NOT_ENABLED, enable the adapter\n");
-        }
-        else if(CA_SEND_FAILED == errorInfo->result)
-        {
-            printf("CA_SEND_FAILED, unable to send the message, check parameters\n");
-        }
-        else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
-        {
-            printf("CA_MEMORY_ALLOC_FAILED, insufficient memory\n");
-        }
-        else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
-        {
-            printf("CA_SOCKET_OPERATION_FAILED, socket operation failed\n");
-        }
-        else if(CA_STATUS_FAILED == errorInfo->result)
-        {
-            printf("CA_STATUS_FAILED, message could not be delivered, internal error\n");
-        }
-    }
-    printf("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++\n");
-
-    return;
-}
-
-void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info)
-{
-    printf("entering send_response\n");
-
-    printf("\n=============================================\n");
-    printf("\tselect message type\n");
-    printf("CON     : 0\n");
-    printf("NON     : 1\n");
-    printf("ACK     : 2\n");
-    printf("RESET   : 3\n");
-    printf("select : ");
-
-    char buf[MAX_BUF_LEN] = { 0 };
-    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
-    {
-        return;
-    }
-
-    int messageType = buf[0] - '0';
-    int responseCode = 0 ;
-    char responseCodeBuf[MAX_BUF_LEN] = { 0 };
-    if (CA_MSG_RESET != messageType)
-    {
-        printf("\n=============================================\n");
-        printf("\tselect response code\n");
-        printf("EMPTY                    :   0\n");
-        printf("CREATED                  : 201\n");
-        printf("DELETED                  : 202\n");
-        printf("VALID                    : 203\n");
-        printf("CHANGED                  : 204\n");
-        printf("CONTENT                  : 205\n");
-        printf("BAD_REQ                  : 400\n");
-        printf("BAD_OPT                  : 402\n");
-        printf("NOT_FOUND                : 404\n");
-        printf("INTERNAL_SERVER_ERROR    : 500\n");
-        printf("RETRANSMIT_TIMEOUT       : 504\n");
-        printf("select : ");
-
-        if (CA_STATUS_OK != get_input_data(responseCodeBuf, MAX_BUF_LEN))
-        {
-            return;
-        }
-        responseCode = atoi(responseCodeBuf);
-    }
-    CAInfo_t responseData = { 0 };
-    responseData.type = messageType;
-    responseData.messageId = (info != NULL) ? info->messageId : 0;
-    responseData.resourceUri = (info != NULL) ? info->resourceUri : 0;
-
-    if(CA_MSG_RESET != messageType)
-    {
-        responseData.token = (info != NULL) ? info->token : NULL;
-        responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
-
-        if (endpoint->flags & CA_SECURE)
-        {
-            printf("Sending response on secure communication\n");
-
-            uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(responseData.resourceUri)
-                              + sizeof(g_local_secure_port);
-            responseData.payload = (CAPayload_t) calloc(length,  sizeof(char));
-            if (NULL == responseData.payload)
-            {
-                printf("Memory allocation fail\n");
-                return;
-            }
-            snprintf((char *) responseData.payload, length, SECURE_INFO_DATA,
-                     (const char *) responseData.resourceUri, g_local_secure_port);
-        }
-        else
-        {
-            printf("Sending response on non-secure communication\n");
-
-            bool useBigPayload = select_payload();
-            if (useBigPayload)
-            {
-                responseData.payload = (CAPayload_t) calloc(BIG_PAYLOAD_SIZE, sizeof(char));
-                if (NULL == responseData.payload)
-                {
-                    printf("Memory allocation fail\n");
-                    return;
-                }
-                populate_binary_payload(responseData.payload, BIG_PAYLOAD_SIZE);
-            }
-            else
-            {
-                size_t length = sizeof(NORMAL_INFO_DATA) + strlen(responseData.resourceUri);
-                responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
-                if (NULL == responseData.payload)
-                {
-                    printf("Memory allocation fail\n");
-                    return;
-                }
-                snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA,
-                         (const char *) responseData.resourceUri);
-            }
-        }
-    }
-    responseData.payloadSize = strlen((char *)responseData.payload)+1;
-    CAResponseInfo_t responseInfo = { 0 };
-    responseInfo.result = responseCode;
-    responseInfo.info = responseData;
-
-    // send response (transportType from remoteEndpoint of request Info)
-    CAResult_t res = CASendResponse(endpoint, &responseInfo);
-    if (CA_STATUS_OK != res)
-    {
-        printf("Send response error\n");
-    }
-    else
-    {
-        printf("Send response success\n");
-    }
-
-    printf("=============================================\n");
-}
-
-int get_secure_information(CAPayload_t payLoad)
-{
-    printf("Entering get_secure_information\n");
-
-    if (!payLoad)
-    {
-        printf("Payload is NULL\n");
-        return -1;
-    }
-
-    char *subString = NULL;
-    if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1")))
-    {
-        printf("This is not secure resource\n");
-        return -1;
-    }
-
-    if (NULL == (subString = strstr((const char *) payLoad, "\"port\":")))
-    {
-        printf("This secure resource does not have port information\n");
-        return -1;
-    }
-
-    char *startPos = strstr(subString, ":");
-    if (!startPos)
-    {
-        printf("Parsing failed !\n");
-        return -1;
-    }
-
-    char *endPos = strstr(startPos, "}");
-    if (!endPos)
-    {
-        printf("Parsing failed !\n");
-        return -1;
-    }
-
-    char portStr[6] = {0};
-    memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
-
-    printf("secured port is: %s\n", portStr);
-    return atoi(portStr);
-}
-
-void get_resource_uri(char *URI, char *resourceURI, int length)
-{
-    char *startPos = URI;
-    char *temp = NULL;
-    if (NULL != (temp = strstr(URI, "://")))
-    {
-        startPos = strchr(temp + 3, '/');
-        if (!startPos)
-        {
-            printf("Resource URI is missing\n");
-            return;
-        }
-    }
-
-    char *endPos = strchr(startPos, '?');
-    if (!endPos)
-    {
-        endPos = URI + strlen(URI);
-    }
-    endPos -= 1;
-
-    if (endPos - startPos <= length)
-    {
-        memcpy(resourceURI, startPos + 1, endPos - startPos);
-    }
-
-    printf("URI: %s, ResourceURI:%s\n", URI, resourceURI);
-}
-
-CAResult_t get_network_type()
-{
-    printf("\n=============================================\n");
-    printf("\tselect network type\n");
-    printf("IP     : 0\n");
-    printf("GATT   : 1\n");
-    printf("RFCOMM : 2\n");
-    printf("TCP    : 4\n");
-    printf("select : ");
-
-    char buf[MAX_BUF_LEN] = { 0 };
-    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
-    {
-        return CA_NOT_SUPPORTED ;
-    }
-
-    int number = buf[0] - '0';
-    if (0 > number || 4 < number)
-    {
-        printf("\nInvalid Network type");
-        return CA_NOT_SUPPORTED;
-    }
-
-    g_selected_nw_type = 1 << number;
-
-    return CA_STATUS_OK;
-}
-
-CAResult_t get_input_data(char *buf, int32_t length)
-{
-    if (!fgets(buf, length, stdin))
-    {
-        printf("fgets error\n");
-        return CA_STATUS_FAILED;
-    }
-
-    char *p = NULL;
-    if ((p = strchr(buf, '\n')) != NULL)
-    {
-        *p = '\0';
-    }
-
-    return CA_STATUS_OK;
-}
-
-
-void parse_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
-{
-    if (NULL == uri)
-    {
-        printf("parameter is null\n");
-        return;
-    }
-
-    // parse uri
-    // #1. check prefix
-    uint8_t startIndex = 0;
-    if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
-    {
-        printf("uri has '%s' prefix\n", COAPS_PREFIX);
-        startIndex = COAPS_PREFIX_LEN;
-        *flags = CA_SECURE;
-    }
-    else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
-    {
-        printf("uri has '%s' prefix\n", COAP_PREFIX);
-        startIndex = COAP_PREFIX_LEN;
-        *flags = CA_IPV4;
-    }
-    else if (strncmp(COAP_TCP_PREFIX, uri, COAP_TCP_PREFIX_LEN) == 0)
-    {
-        printf("uri has '%s' prefix\n", COAP_TCP_PREFIX);
-        startIndex = COAP_TCP_PREFIX_LEN;
-        *flags = CA_IPV4;
-    }
-
-    // #2. copy uri for parse
-    int32_t len = strlen(uri) - startIndex;
-
-    if (len <= 0)
-    {
-        printf("uri length is 0!\n");
-        return;
-    }
-
-    int res = get_address_set(uri + startIndex, address);
-    if (res == -1)
-    {
-        printf("address parse error\n");
-        return;
-    }
-
-    return;
-}
-
-int get_address_set(const char *uri, addressSet_t* outAddress)
-{
-    if (NULL == uri || NULL == outAddress)
-    {
-        printf("parameter is null !\n");
-        return -1;
-    }
-
-    int32_t len = strlen(uri);
-    if (len <= 0)
-    {
-        printf("uri length is 0!\n");
-        return -1;
-    }
-
-    int32_t isIp = 0;
-    int32_t ipLen = 0;
-    for (int i = 0; i < len; i++)
-    {
-        if (uri[i] == '.')
-        {
-            isIp = 1;
-        }
-
-        // found port number start index
-        if (isIp && uri[i] == ':')
-        {
-            ipLen = i;
-            outAddress->port = atoi(uri + ipLen + 1);
-            break;
-        }
-
-        if (uri[i] == '/')
-        {
-            break;
-        }
-
-        outAddress->ipAddress[i] = uri[i];
-    }
-
-    return isIp;
-}
diff --git a/resource/csdk/connectivity/samples/tizen/com.oic.ca.sample.manifest b/resource/csdk/connectivity/samples/tizen/com.oic.ca.sample.manifest
deleted file mode 100644 (file)
index 50868ad..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-<manifest>
-       <define>
-         <domain name="casample" />
-         <permit>
-               <smack permit="system::use_internet" type="rwx"/>
-         </permit>
-         <request>
-                <smack request="system::use_internet" type="rwx"/>
-                <smack request="bt-service" type="rwx"/>
-               <smack request="sap" type="rwx"/>
-                <smack request="bt-service::spp" type="rwx"/>
-                <smack request="bt-service::gap" type="rwx"/>
-                <smack request="bt-service::admin" type="rwx"/>
-                <smack request="bt-service::manager" type="rwx"/>
-                <smack request="bt-service::public" type="rwx"/>
-                 <smack request="bt-service::platform" type="rwx"/>
-         </request>
-       </define>
-       <assign>
-               <filesystem path="/opt/apps/com.oic.ca.sample/bin/sample" exec_label="sample" />
-       </assign>
-       <request>
-               <domain name="casample" />
-       </request>
-</manifest>
-
diff --git a/resource/csdk/connectivity/samples/tizen/com.oic.ca.sample.xml b/resource/csdk/connectivity/samples/tizen/com.oic.ca.sample.xml
deleted file mode 100644 (file)
index 7ee7fbb..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns="http://tizen.org/ns/packages" package="com.oic.ca.sample" version="0.1.12" install-location="internal-only">
-       <label>casample</label>
-       <author email="oic" href="www.iotivity.org">OIC</author>
-       <description>casample</description>
-       <ui-application appid="com.oic.ca.sample" exec="/usr/apps/com.oic.ca.sample/bin/sample" nodisplay="false" multiple="false" type="capp" taskmanage="true">
-               <icon>com.oic.ca.sample.png</icon>
-               <label>casample</label>
-               <label xml:lang="en-us">casample</label>
-               <label xml:lang="nl-nl">casample</label>
-       </ui-application>
-       <privileges>
-               <privilege>http://tizen.org/privilege/socket</privilege>
-       </privileges>
-
-</manifest>
-
diff --git a/resource/csdk/connectivity/samples/tizen/gbsbuild.sh b/resource/csdk/connectivity/samples/tizen/gbsbuild.sh
deleted file mode 100644 (file)
index 6c60044..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/bin/sh
-
-git init
-gbs build -A armv7l --include-all -B ~/GBS-ROOT-NEW
-
-
-
diff --git a/resource/csdk/connectivity/samples/tizen/packaging/com.oic.ca.sample.spec b/resource/csdk/connectivity/samples/tizen/packaging/com.oic.ca.sample.spec
deleted file mode 100644 (file)
index 6954f53..0000000
+++ /dev/null
@@ -1,51 +0,0 @@
-%define PREFIX /usr/apps/com.oic.ca.sample
-%define ROOTDIR  %{_builddir}/%{name}-%{version}
-
-Name: com-oic-ca-sample
-Version:    0.1
-Release:    1
-Summary: Tizen adapter interfacesample application
-URL: http://slp-source.sec.samsung.net
-Source: %{name}-%{version}.tar.gz
-License: Apache-2.0
-Group: Applications/OICSample
-BuildRequires: pkgconfig(dlog)
-BuildRequires: pkgconfig(glib-2.0)
-BuildRequires: boost-devel
-BuildRequires: boost-thread
-BuildRequires: boost-system
-BuildRequires: boost-filesystem
-BuildRequires: pkgconfig(capi-network-wifi)
-BuildRequires: pkgconfig(capi-network-bluetooth)
-BuildRequires: scons
-BuildRequires: com-oic-ca
-
-
-%description
-OIC interfacesample application
-
-%prep
-%setup -q
-
-%build
-
-scons TARGET_OS=tizen -c
-scons TARGET_OS=tizen TARGET_TRANSPORT=%{TARGET_TRANSPORT} SECURED=%{SECURED} RELEASE=%{RELEASE}
-
-%install
-
-mkdir -p %{buildroot}%{_datadir}/packages
-mkdir -p %{buildroot}/%{_sysconfdir}/smack/accesses2.d
-mkdir -p %{buildroot}/usr/apps/com.oic.ca.sample/bin/
-mkdir -p %{buildroot}/usr/apps/com.oic.ca.sample/bin/internal
-
-cp -rf %{ROOTDIR}/com.oic.ca.sample.xml %{buildroot}/%{_datadir}/packages
-cp -rf %{ROOTDIR}/scons/ca_sample %{buildroot}/usr/apps/com.oic.ca.sample/bin/
-
-%files
-%manifest com.oic.ca.sample.manifest
-%defattr(-,root,root,-)
-/usr/apps/com.oic.ca.sample/bin/ca_sample
-/%{_datadir}/packages/com.oic.ca.sample.xml
-
-
diff --git a/resource/csdk/connectivity/samples/tizen/scons/SConscript b/resource/csdk/connectivity/samples/tizen/scons/SConscript
deleted file mode 100644 (file)
index 8cdf053..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-##
-# 'resource' sub-project main build script
-#
-##
-
-Import('env')
-
-target_os = env.get('TARGET_OS')
-transport = env.get('TARGET_TRANSPORT')
-secured = env.get('SECURED')
-
-OIC_LIB = 'oic'
-root_dir = env.get('ROOT_DIR')
-build_dir = env.get('BUILD_DIR')
-sample_dir = build_dir
-
-env.AppendUnique(CFLAGS = ['-std=c99', '-fPIC', '-D__TIZEN__','-DWITH_POSIX', '-Wall', '-DSLP_SDK_LOG', '-g','-D_GNU_SOURCE','-DTIZEN_DEBUG_ENABLE', '-DTB_LOG','`pkg-config', '--cflags', '--libs','dlog', 'com.oic.ca', 'capi-network-wifi',
-                               'gobject-2.0','glib-2.0`'])
-
-env.Append(LIBPATH=[root_dir +'/lib/tizen/ble/libs/',])
-env.Append(LIBS=[
-  '-lm', '-lpthread', '-lrt', '-ldl', '-lstdc++', '-lgobject-2.0', '-lgio-2.0', '-lglib-2.0', '-lcapi-network-wifi', '-ldlog', '-lcapi-network-bluetooth', '-lconnectivity_abstraction', 'coap',
-])
-
-if secured == '1':
-       env.PrependUnique(CPPPATH = [root_dir + '/external/inc/'])
-       env.AppendUnique(CPPDEFINES = ['__WITH_DTLS__'])
-       env.Append(LIBS=['-ltinydtls'])
-
-env.Prepend(RPATH=[root_dir +'/lib/tizen/ble/libs/',])
-if 'ALL' in transport:
-               env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','EDR_ADAPTER','LE_ADAPTER','BT_ADAPTER_TEST','BLE_ADAPTER_TEST'])
-               print "CA Transport is ALL"
-else:
-       if 'BT' in transport:
-               env.AppendUnique(CPPDEFINES = ['EDR_ADAPTER','BT_ADAPTER_TEST'])
-               print "CA Transport is BT"
-       else:
-               env.AppendUnique(CPPDEFINES = ['NO_EDR_ADAPTER'])
-
-       if 'BLE' in transport:
-               env.AppendUnique(CPPDEFINES = ['LE_ADAPTER','BLE_ADAPTER_TEST'])
-               print "CA Transport is BLE"
-       else:
-               env.AppendUnique(CPPDEFINES = ['NO_LE_ADAPTER'])
-
-       if 'IP' in transport:
-               env.AppendUnique(CPPDEFINES = ['IP_ADAPTER'])
-               print "CA Transport is IP"
-       else:
-               env.AppendUnique(CPPDEFINES = ['NO_IP_ADAPTER'])
-
-
-ca_sample_src = [sample_dir + '/casample.c']
-
-print " ca sample src %s" % ca_sample_src
-
-env.Program('ca_sample', [ca_sample_src,])
-
-
-
index 367590a..897e390 100644 (file)
@@ -11,6 +11,7 @@ ca_transport = env.get('TARGET_TRANSPORT')
 secured = env.get('SECURED')
 with_ra = env.get ('WITH_RA')
 with_tcp = env.get('WITH_TCP')
+src_dir = env.get('SRC_DIR')
 root_dir = os.pardir
 ca_path = os.curdir
 
@@ -23,7 +24,9 @@ print"Reading ca script %s"%ca_transport
 env.PrependUnique(CPPPATH = [ os.path.join(root_dir, 'api') ])
 env.AppendUnique(CPPPATH = [ os.path.join(root_dir, 'inc'),
                              os.path.join(root_dir, 'lib/libcoap-4.1.1'),
-                             os.path.join(root_dir, 'common/inc') ])
+                             os.path.join(src_dir, '/resource/csdk/logger/include/'),
+                             os.path.join(root_dir, 'common/inc'),
+                             os.path.join(root_dir, 'util/inc') ])
 
 if ca_os not in ['arduino', 'windows', 'winrt']:
        env.AppendUnique(CPPDEFINES = ['WITH_POSIX'])
@@ -37,6 +40,9 @@ if ca_os in ['darwin','ios']:
 # Getting common source files
 env.SConscript('./../common/SConscript')
 
+# Getting util source files
+env.SConscript(root_dir + '/util/SConscript')
+
 # The tinydtls library is found in '#extlibs/tinydtls', where the '#'
 # is interpreted by SCons as the top-level iotivity directory where
 # the SConscruct file is found.
@@ -45,18 +51,22 @@ if env.get('SECURED') == '1':
                env.SConscript(os.path.join(root_dir, 'extlibs/tinydtls/SConscript'))
        else:
                env.SConscript('#extlibs/tinydtls/SConscript')
+       if ca_os == 'tizen' and os.path.exists(root_dir + '/extlibs/timer'):
+               env.SConscript(os.path.join(root_dir, 'extlibs/timer/SConscript'))
+               env.AppendUnique(CPPPATH = [os.path.join(root_dir, 'extlibs/timer')])
+       else:
+               env.SConscript('#extlibs/timer/SConscript')
+               env.AppendUnique(CPPPATH = ['#extlibs/timer'])
 
 env.AppendUnique(CA_SRC = [os.path.join(ca_path,
                                         'adapter_util/caadapterutils.c')])
-env.AppendUnique(CA_SRC = [os.path.join(ca_path,
-                                        'adapter_util/cafragmentation.c')])
+
 if env.get('SECURED') == '1':
        env.AppendUnique(CA_SRC = [os.path.join(ca_path,
                                                 'adapter_util/caadapternetdtls.c')])
        env.AppendUnique(CPPPATH = [os.path.join(root_dir,
                                                  'external/inc')])
 if env.get('DTLS_WITH_X509') == '1':
-       src_dir = env.get('SRC_DIR')
        env.AppendUnique(CPPPATH = [src_dir + '/resource/csdk/connectivity/inc/pkix'])
        env.AppendUnique(CPPPATH = [src_dir + '/extlibs/tinydtls/ecc/'])
        env.AppendUnique(CPPPATH = [src_dir + '/extlibs/tinydtls/sha2/'])
@@ -95,7 +105,7 @@ else:
                'caqueueingthread.c',
                'caretransmission.c',
                ]
-       if (('BT' in ca_transport) or ('IP' in ca_transport) or ('ALL' in ca_transport)):
+       if (('IP' in ca_transport) or ('ALL' in ca_transport)):
                env.AppendUnique(CA_SRC = [os.path.join(ca_path, 'cablockwisetransfer.c') ])
                env.AppendUnique(CPPDEFINES = ['WITH_BWT'])
        if secured == '1':
@@ -114,6 +124,8 @@ if 'ALL' in ca_transport:
                transports = [ 'ip_adapter', 'bt_edr_adapter', 'bt_le_adapter']
                if with_ra:
                                transports.append ('ra_adapter')
+               if ca_os in ['android']:
+                               transports.append ('nfc_adapter')
                env.SConscript(dirs = [
                                os.path.join(ca_path, d) for d in transports ])
 
@@ -126,9 +138,17 @@ if 'BT' in ca_transport:
 if 'BLE' in ca_transport:
        env.SConscript(os.path.join(ca_path, 'bt_le_adapter/SConscript'))
 
-if ca_os in ['linux', 'tizen']:
+if 'NFC' in ca_transport:
+       env.SConscript(os.path.join(ca_path, 'nfc_adapter/SConscript'))
+
+if ca_os in ['linux', 'tizen', 'android']:
        if with_tcp == True:
                env.SConscript(os.path.join(ca_path, 'tcp_adapter/SConscript'))
+               env.AppendUnique(CPPDEFINES = ['WITH_TCP'])
+
+if ca_os in ['linux', 'tizen', 'android', 'arduino', 'ios']:
+       if (('BLE' in ca_transport) or ('BT' in ca_transport) or ('ALL' in ca_transport)):
+               env.AppendUnique(CPPDEFINES = ['WITH_TCP'])
 
 print "Include path is %s" % env.get('CPPPATH')
 print "Files path is %s" % env.get('CA_SRC')
@@ -136,6 +156,7 @@ if ca_os in ['android', 'tizen']:
        env.AppendUnique(LIBS = ['coap'])
        if env.get('SECURED') == '1':
                env.AppendUnique(LIBS = ['tinydtls'])
+               env.AppendUnique(LIBS = ['timer'])
        if ca_os != 'android':
                env.AppendUnique(LIBS = ['rt'])
        calib = env.SharedLibrary('connectivity_abstraction', env.get('CA_SRC'))
@@ -143,4 +164,3 @@ else:
        calib = env.StaticLibrary('connectivity_abstraction', env.get('CA_SRC'))
 env.InstallTarget(calib, 'libconnectivity_abstraction')
 env.UserInstallTargetLib(calib, 'libconnectivity_abstraction')
-
index 7d7eba2..8caf45f 100644 (file)
 #include "oic_malloc.h"
 #include "oic_string.h"
 #include "global.h"
+#include "timer.h"
 #include <netdb.h>
 
+/* tinyDTLS library error code */
+#define TINY_DTLS_ERROR (-1)
+/* tinyDTLS library success code */
+#define TINY_DTLS_SUCCESS (0)
+
 #ifdef __WITH_X509__
 #include "pki.h"
 #include "crl.h"
@@ -44,7 +50,7 @@
  * @def NET_DTLS_TAG
  * @brief Logging tag for module name
  */
-#define NET_DTLS_TAG "NET_DTLS"
+#define NET_DTLS_TAG "OIC_CA_NET_DTLS"
 
 /**
  * @var g_caDtlsContext
@@ -64,6 +70,18 @@ static ca_mutex g_dtlsContextMutex = NULL;
  */
 static CAGetDTLSPskCredentialsHandler g_getCredentialsCallback = NULL;
 
+/**
+ * @var MAX_RETRANSMISSION_TIME
+ * @brief Maximum timeout value (in seconds) to start DTLS retransmission.
+ */
+#define MAX_RETRANSMISSION_TIME 1
+
+/**
+ * @var g_dtlsHandshakeCallback
+ * @brief callback to deliver the DTLS handshake result
+ */
+static CAErrorCallback g_dtlsHandshakeCallback = NULL;
+
 #ifdef __WITH_X509__
 /**
  * @var g_getX509CredentialsCallback
@@ -77,6 +95,7 @@ static CAGetDTLSX509CredentialsHandler g_getX509CredentialsCallback = NULL;
 static CAGetDTLSCrlHandler g_getCrlCallback = NULL;
 #endif //__WITH_X509__
 
+
 static CASecureEndpoint_t *GetPeerInfo(const CAEndpoint_t *peer)
 {
     uint32_t list_index = 0;
@@ -407,7 +426,7 @@ static int32_t CAReadDecryptedPayload(dtls_context_t *context,
     OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
 
     VERIFY_NON_NULL_RET(session, NET_DTLS_TAG, "Param Session is NULL", 0);
-    OIC_LOG_V(DEBUG, NET_DTLS_TAG, "Decrypted buf len [%d]", bufLen);
+    OIC_LOG_V(DEBUG, NET_DTLS_TAG, "Decrypted buf len [%zu]", bufLen);
 
     stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)session;
 
@@ -422,7 +441,7 @@ static int32_t CAReadDecryptedPayload(dtls_context_t *context,
     if (NULL == g_caDtlsContext)
     {
         OIC_LOG(ERROR, NET_DTLS_TAG, "Context is NULL");
-        return 0;
+        return TINY_DTLS_ERROR;
     }
 
     int type = 0;
@@ -444,7 +463,7 @@ static int32_t CAReadDecryptedPayload(dtls_context_t *context,
     }
 
     OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
-    return 0;
+    return TINY_DTLS_SUCCESS;
 }
 
 static int32_t CASendSecureData(dtls_context_t *context,
@@ -500,27 +519,54 @@ static int32_t CAHandleSecureEvent(dtls_context_t *context,
 
     VERIFY_NON_NULL_RET(session, NET_DTLS_TAG, "Param Session is NULL", 0);
 
-    OIC_LOG_V(DEBUG, NET_DTLS_TAG, "level [%d] code [%u]", level, code);
+    OIC_LOG_V(DEBUG, NET_DTLS_TAG, "level [%d] code [%u]\n", level, code);
+
+    CAEndpoint_t endpoint = {.adapter=CA_DEFAULT_ADAPTER};
+    CAErrorInfo_t errorInfo = {.result=CA_STATUS_OK};
+
+    stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)session;
+    char peerAddr[MAX_ADDR_STR_SIZE_CA] = { 0 };
+    uint16_t port = 0;
+    CAConvertAddrToName(&(addrInfo->addr.st), addrInfo->size, peerAddr, &port);
 
-    if (!level && (code == DTLS_EVENT_CONNECTED))
+    if (!level && (DTLS_EVENT_CONNECTED == code))
     {
         OIC_LOG(DEBUG, NET_DTLS_TAG, "Received DTLS_EVENT_CONNECTED. Sending Cached data");
+
+        if(g_dtlsHandshakeCallback)
+        {
+            OICStrcpy(endpoint.addr, MAX_ADDR_STR_SIZE_CA, peerAddr);
+            endpoint.port = port;
+            errorInfo.result = CA_STATUS_OK;
+            g_dtlsHandshakeCallback(&endpoint, &errorInfo);
+        }
+
         CASendCachedMsg((stCADtlsAddrInfo_t *)session);
     }
-
-    if(DTLS_ALERT_LEVEL_FATAL == level && DTLS_ALERT_CLOSE_NOTIFY == code)
+    else if(DTLS_ALERT_LEVEL_FATAL == level && DTLS_ALERT_DECRYPT_ERROR == code)
+    {
+        if(g_dtlsHandshakeCallback)
+        {
+            OICStrcpy(endpoint.addr, MAX_ADDR_STR_SIZE_CA, peerAddr);
+            endpoint.addr[MAX_ADDR_STR_SIZE_CA - 1] = '\0';
+            endpoint.port = port;
+            errorInfo.result = CA_DTLS_AUTHENTICATION_FAILURE;
+            g_dtlsHandshakeCallback(&endpoint, &errorInfo);
+        }
+    }
+    else if(DTLS_ALERT_LEVEL_FATAL == level && DTLS_ALERT_CLOSE_NOTIFY == code)
     {
         OIC_LOG(INFO, NET_DTLS_TAG, "Peer closing connection");
-
-        stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)session;
-        char peerAddr[MAX_ADDR_STR_SIZE_CA] = { 0 };
-        uint16_t port = 0;
-        CAConvertAddrToName(&(addrInfo->addr.st), addrInfo->size, peerAddr, &port);
+        CARemovePeerFromPeerInfoList(peerAddr, port);
+    }
+    else if(DTLS_ALERT_LEVEL_FATAL == level && DTLS_ALERT_HANDSHAKE_FAILURE == code)
+    {
+        OIC_LOG(INFO, NET_DTLS_TAG, "Failed to DTLS handshake, the peer will be removed.");
         CARemovePeerFromPeerInfoList(peerAddr, port);
     }
 
     OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
-    return 0;
+    return TINY_DTLS_SUCCESS;
 }
 
 
@@ -532,7 +578,7 @@ static int32_t CAGetPskCredentials(dtls_context_t *ctx,
 {
     OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
 
-    int32_t ret  = -1;
+    int32_t ret = TINY_DTLS_ERROR;
     if(NULL == ctx || NULL == session || NULL == result)
     {
         OIC_LOG(ERROR, NET_DTLS_TAG, "CAGetPskCredentials invalid parameters");
@@ -589,6 +635,13 @@ void CADTLSSetAdapterCallbacks(CAPacketReceivedCallback recvCallback,
     OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
 }
 
+void CADTLSSetHandshakeCallback(CAErrorCallback dtlsHandshakeCallback)
+{
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
+    g_dtlsHandshakeCallback = dtlsHandshakeCallback;
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
+}
+
 void CADTLSSetCredentialsCallback(CAGetDTLSPskCredentialsHandler credCallback)
 {
     // TODO Does this method needs protection of DtlsContextMutex ?
@@ -812,7 +865,7 @@ int CAInitX509()
 static int CAIsX509Active(struct dtls_context_t *ctx)
 {
     (void)ctx;
-    return 0;
+    return TINY_DTLS_SUCCESS;
 }
 
 static int CAGetDeviceKey(struct dtls_context_t *ctx,
@@ -822,13 +875,13 @@ static int CAGetDeviceKey(struct dtls_context_t *ctx,
     OIC_LOG(DEBUG, NET_DTLS_TAG, "CAGetDeviceKey");
     static dtls_ecc_key_t ecdsa_key = {DTLS_ECDH_CURVE_SECP256R1, NULL, NULL, NULL};
 
-    int ret = 1;
+    int ret = TINY_DTLS_ERROR;
     VERIFY_SUCCESS(CAInitX509(), 0);
 
     ecdsa_key.priv_key = g_X509Cred.devicePrivateKey;
     *result = &ecdsa_key;
 
-    ret = 0;
+    ret = TINY_DTLS_SUCCESS;
 exit:
     return ret;
 }
@@ -840,7 +893,7 @@ CAGetDeviceCertificate(struct dtls_context_t *ctx,
                     size_t *cert_size)
 {
     OIC_LOG(DEBUG, NET_DTLS_TAG, "CAGetDeviceCertificate");
-    int ret = 1;
+    int ret = TINY_DTLS_ERROR;
 
     VERIFY_SUCCESS(CAInitX509(), 0);
 
@@ -851,7 +904,7 @@ CAGetDeviceCertificate(struct dtls_context_t *ctx,
     PRINT_BYTE_ARRAY("OWN CERT: \n", ownCert);
 #endif
 
-    ret = 0;
+    ret = TINY_DTLS_SUCCESS;
 exit:
     return ret;
 }
@@ -890,7 +943,7 @@ static int CAVerifyCertificate(struct dtls_context_t *ctx, const session_t *sess
 
     uint8_t chainLength;
 
-    int ret;
+    int ret = TINY_DTLS_ERROR;
     const unsigned char *ca_pub_x;
     const unsigned char *ca_pub_y;
     ByteArray certDerCode = BYTE_ARRAY_INITIALIZER;
@@ -899,7 +952,7 @@ static int CAVerifyCertificate(struct dtls_context_t *ctx, const session_t *sess
 
     if ( !ctx ||  !session ||  !cert || !x || !y)
     {
-        return -PKI_NULL_PASSED;
+        return TINY_DTLS_ERROR;
     }
 
     CAGetRootKey (&ca_pub_x, &ca_pub_y);
@@ -945,17 +998,60 @@ static int CAVerifyCertificate(struct dtls_context_t *ctx, const session_t *sess
 exit:
     if (ret != 0)
     {
-        OIC_LOG(DEBUG, NET_DTLS_TAG, "Certificate verification FAILED\n");
+        OIC_LOG(ERROR, NET_DTLS_TAG, "Certificate verification FAILED\n");
+        return TINY_DTLS_ERROR;
     }
     else
     {
         OIC_LOG(DEBUG, NET_DTLS_TAG, "Certificate verification SUCCESS\n");
+        return TINY_DTLS_SUCCESS;
     }
-    return -ret;
 }
 
 #endif
 
+static void CAStartRetransmit()
+{
+    static int timerId = -1;
+    clock_time_t nextSchedule = MAX_RETRANSMISSION_TIME;
+
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "CAStartRetransmit IN");
+
+    if (timerId != -1)
+    {
+        //clear previous timer
+        unregisterTimer(timerId);
+
+        ca_mutex_lock(g_dtlsContextMutex);
+
+        //stop retransmission if context is invalid
+        if(NULL == g_caDtlsContext)
+        {
+            OIC_LOG(ERROR, NET_DTLS_TAG, "Context is NULL. Stop retransmission");
+            ca_mutex_unlock(g_dtlsContextMutex);
+            return;
+        }
+
+        OIC_LOG(DEBUG, NET_DTLS_TAG, "Check retransmission");
+        dtls_check_retransmit(g_caDtlsContext->dtlsContext, &nextSchedule);
+        ca_mutex_unlock(g_dtlsContextMutex);
+
+        //re-transmission timeout should not be greater then max one
+        //this will cover case when several clients start dtls sessions
+        nextSchedule /= CLOCKS_PER_SEC;
+        if (nextSchedule > MAX_RETRANSMISSION_TIME)
+        {
+            nextSchedule = MAX_RETRANSMISSION_TIME;
+        }
+    }
+
+    //start new timer
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "Start new timer");
+    registerTimer(nextSchedule, &timerId, CAStartRetransmit);
+
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "CAStartRetransmit OUT");
+}
+
 CAResult_t CAAdapterNetDtlsInit()
 {
     OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
@@ -1030,6 +1126,9 @@ CAResult_t CAAdapterNetDtlsInit()
 #endif //__WITH_X509__*
     dtls_set_handler(g_caDtlsContext->dtlsContext, &(g_caDtlsContext->callbacks));
     ca_mutex_unlock(g_dtlsContextMutex);
+
+    CAStartRetransmit();
+
     OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
     return CA_STATUS_OK;
 }
index 3022e99..bb79375 100644 (file)
@@ -36,7 +36,7 @@
 #include <jni.h>
 #endif
 
-#define CA_ADAPTER_UTILS_TAG "CA_ADAPTER_UTILS"
+#define CA_ADAPTER_UTILS_TAG "OIC_CA_ADAP_UTILS"
 
 #ifdef __ANDROID__
 /**
@@ -50,6 +50,7 @@ static JavaVM *g_jvm = NULL;
  * @brief pointer to store context for android callback interface
  */
 static jobject g_Context = NULL;
+static jobject g_Activity = NULL;
 #endif
 
 #ifdef WITH_ARDUINO
@@ -199,11 +200,18 @@ void CANativeJNISetContext(JNIEnv *env, jobject context)
 
     if (!context)
     {
-        OIC_LOG(DEBUG, CA_ADAPTER_UTILS_TAG, "context is null");
-
+        OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "context is null");
+        return;
     }
 
-    g_Context = (*env)->NewGlobalRef(env, context);
+    if (!g_Context)
+    {
+        g_Context = (*env)->NewGlobalRef(env, context);
+    }
+    else
+    {
+        OIC_LOG(INFO, CA_ADAPTER_UTILS_TAG, "context is already set");
+    }
 }
 
 void CANativeJNISetJavaVM(JavaVM *jvm)
@@ -221,4 +229,44 @@ JavaVM *CANativeJNIGetJavaVM()
 {
     return g_jvm;
 }
+
+void CANativeSetActivity(JNIEnv *env, jobject activity)
+{
+    OIC_LOG_V(DEBUG, CA_ADAPTER_UTILS_TAG, "CANativeSetActivity");
+
+    if (!activity)
+    {
+        OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "activity is null");
+        return;
+    }
+
+    if (!g_Activity)
+    {
+        g_Activity = (*env)->NewGlobalRef(env, activity);
+    }
+    else
+    {
+        OIC_LOG(INFO, CA_ADAPTER_UTILS_TAG, "activity is already set");
+    }
+}
+
+jobject *CANativeGetActivity()
+{
+    return g_Activity;
+}
+
+void CADeleteGlobalReferences(JNIEnv *env)
+{
+    if (g_Context)
+    {
+        (*env)->DeleteGlobalRef(env, g_Context);
+        g_Context = NULL;
+    }
+
+    if (g_Activity)
+    {
+        (*env)->DeleteGlobalRef(env, g_Activity);
+        g_Activity = NULL;
+    }
+}
 #endif
diff --git a/resource/csdk/connectivity/src/adapter_util/cafragmentation.c b/resource/csdk/connectivity/src/adapter_util/cafragmentation.c
deleted file mode 100644 (file)
index 6831046..0000000
+++ /dev/null
@@ -1,86 +0,0 @@
-/******************************************************************
- *
- * Copyright 2014 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 <string.h>
-#include <math.h>
-
-#include "cacommon.h"
-#include "caadapterutils.h"
-#include "cafragmentation.h"
-
-/**
- * Debugging tag for fragmentation module.
- */
-#define CA_FRAGMENTATION_TAG "CA_FRAGMENTATION"
-
-CAResult_t CAGenerateHeader(uint8_t *header,
-                            size_t headerLength,
-                            size_t dataLength)
-{
-    OIC_LOG(DEBUG, CA_FRAGMENTATION_TAG, "IN");
-
-    VERIFY_NON_NULL(header, CA_FRAGMENTATION_TAG, "header is NULL");
-
-    if (headerLength < CA_HEADER_LENGTH)
-    {
-        return CA_STATUS_FAILED;
-    }
-
-    if (dataLength > MAX_DATA_LENGTH_SUPPORTED)
-    {
-        OIC_LOG_V(WARNING,
-                  CA_FRAGMENTATION_TAG,
-                  "Given length is more than %d.  It will be truncated.",
-                  MAX_DATA_LENGTH_SUPPORTED);
-    }
-
-    // Only bother initializing the header section of the buffer.  It
-    // is up to the caller to handle the data section.
-    memset(header, 0, CA_HEADER_LENGTH);
-
-    // If length is more than 4095 then it will be truncated.
-    header[1] = dataLength & 0xFF;
-    dataLength >>= 8;
-    header[0] = dataLength & 0x0F;
-    header[0] = header[0] | 0x40; // Adding version 0100.
-                                  // (Not used. Future use)
-
-    OIC_LOG(DEBUG, CA_FRAGMENTATION_TAG, "OUT");
-
-    return CA_STATUS_OK;
-}
-
-uint32_t CAParseHeader(const uint8_t *header, size_t length)
-{
-    OIC_LOG(DEBUG, CA_FRAGMENTATION_TAG, "IN");
-
-    VERIFY_NON_NULL_RET(header, CA_FRAGMENTATION_TAG, "header is NULL", 0);
-
-    uint32_t dataLen = 0;
-
-    if (length >= CA_HEADER_LENGTH)
-    {
-        dataLen = ((header[0] & 0x0F) << 8) | (header[1] & 0xFF);
-    }
-
-    OIC_LOG(DEBUG, CA_FRAGMENTATION_TAG, "OUT");
-
-    return dataLen;
-}
index a1c5bba..06e46b9 100644 (file)
@@ -46,7 +46,7 @@ PKIError DecodeLength(ByteArray *code, size_t *length)
 
         for (i = 0; i < blocksNum; ++i)
         {
-            *length |= *(code->data) << ((blocksNum - i - 1) * SIZE_OF_BYTE);
+            *length |= (size_t) (((size_t) *(code->data)) << ((blocksNum - i - 1) * SIZE_OF_BYTE));
             CHECK_INC_BYTE_ARRAY_PTR(code, 1);
         }
     }
index b393fbb..f3db429 100644 (file)
@@ -58,8 +58,8 @@ void FreeSNStore(void)
 PKIError StoreSerialNumber(const ByteArray sn)
 {
     FUNCTION_INIT(
-        CHECK_NULL(sn.data, PKI_NULL_PASSED);
         uint8_t *temp = NULL;
+        CHECK_NULL(sn.data, PKI_NULL_PASSED);
     );
     if (Store.array.len == 0 || Store.array.len + sn.len + 1 > CRL_BLOCK_LEN * Store.blockNumber)
     {
@@ -82,7 +82,8 @@ PKIError StoreSerialNumber(const ByteArray sn)
 PKIError CheckSerialNumber(const ByteArray sn)
 {
     FUNCTION_INIT(
-        int i, res;
+        unsigned long int i;
+        int res;
         CHECK_NULL(sn.data, PKI_NULL_PASSED);
     );
     CHECK_NULL(Store.array.data, PKI_SUCCESS);
index b41dfb2..16e588a 100644 (file)
@@ -34,8 +34,7 @@
 #include "caadapterutils.h"
 #include "caremotehandler.h"
 
-//#define DEBUG_MODE
-#define TAG PCF("CA_EDR_CLIENT")
+#define TAG PCF("OIC_CA_EDR_CLIENT")
 
 static const char METHODID_CONTEXTNONPARAM[] = "()Landroid/content/Context;";
 static const char METHODID_OBJECTNONPARAM[] = "()Landroid/bluetooth/BluetoothAdapter;";
@@ -51,8 +50,6 @@ static const char CLASSPATH_BT_UUID[] = "java/util/UUID";
 static const char CLASSPATH_CONTEXT[] = "android/content/Context";
 static const char CLASSPATH_OUTPUT[] = "java/io/OutputStream";
 
-static ca_thread_pool_t g_threadPoolHandle = NULL;
-
 static JavaVM *g_jvm;
 static jobject g_context;
 
@@ -204,20 +201,16 @@ CAResult_t CAEDRClientSendUnicastData(const char *remoteAddress, const uint8_t *
 {
     VERIFY_NON_NULL(remoteAddress, TAG, "remoteAddress is null");
     VERIFY_NON_NULL(data, TAG, "data is null");
-    OIC_LOG(DEBUG, TAG, "IN");
 
     CAResult_t result = CAEDRSendUnicastMessage(remoteAddress, data, dataLength);
-    OIC_LOG(DEBUG, TAG, "OUT");
     return result;
 }
 
 CAResult_t CAEDRClientSendMulticastData(const uint8_t *data, uint32_t dataLength)
 {
     VERIFY_NON_NULL(data, TAG, "data is null");
-    OIC_LOG(DEBUG, TAG, "IN");
 
     CAResult_t result = CAEDRSendMulticastMessage(data, dataLength);
-    OIC_LOG(DEBUG, TAG, "OUT");
     return result;
 }
 
@@ -239,7 +232,8 @@ void CAEDRClientDisconnectAll()
 
 CAResult_t CAEDRGetAdapterEnableState(bool *state)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL(state, TAG, "state is null");
+
     if (!g_jvm)
     {
         OIC_LOG(ERROR, TAG, "g_jvm is null");
@@ -260,22 +254,19 @@ CAResult_t CAEDRGetAdapterEnableState(bool *state)
         }
         isAttached = true;
     }
+
+    *state = false;
     jboolean ret = CAEDRNativeIsEnableBTAdapter(env);
     if (ret)
     {
         *state = true;
     }
-    else
-    {
-        *state = false;
-    }
 
     if (isAttached)
     {
         (*g_jvm)->DetachCurrentThread(g_jvm);
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
 
@@ -289,11 +280,11 @@ void CAEDRJniInitContext()
 CAResult_t CAEDRCreateJNIInterfaceObject(jobject context)
 {
     JNIEnv* env;
-    OIC_LOG(DEBUG, TAG, "[EDRCore] CAEDRCreateJNIInterfaceObject");
+    OIC_LOG(DEBUG, TAG, "CAEDRCreateJNIInterfaceObject");
 
     if ((*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6) != JNI_OK)
     {
-        OIC_LOG(ERROR, TAG, "[EDRCore] Could not get JNIEnv pointer");
+        OIC_LOG(ERROR, TAG, "Could not get JNIEnv pointer");
         return CA_STATUS_FAILED;
     }
 
@@ -301,7 +292,7 @@ CAResult_t CAEDRCreateJNIInterfaceObject(jobject context)
     jclass contextClass = (*env)->FindClass(env, CLASSPATH_CONTEXT);
     if (!contextClass)
     {
-        OIC_LOG(ERROR, TAG, "[EDRCore] Could not get context object class");
+        OIC_LOG(ERROR, TAG, "Could not get context object class");
         return CA_STATUS_FAILED;
     }
 
@@ -310,7 +301,7 @@ CAResult_t CAEDRCreateJNIInterfaceObject(jobject context)
                                                                 METHODID_CONTEXTNONPARAM);
     if (!getApplicationContextMethod)
     {
-        OIC_LOG(ERROR, TAG, "[EDRCore] Could not get getApplicationContext method");
+        OIC_LOG(ERROR, TAG, "Could not get getApplicationContext method");
         return CA_STATUS_FAILED;
     }
 
@@ -318,7 +309,7 @@ CAResult_t CAEDRCreateJNIInterfaceObject(jobject context)
     jclass EDRJniInterface = (*env)->FindClass(env, CLASSPATH_BT_INTERFACE);
     if (!EDRJniInterface)
     {
-        OIC_LOG(ERROR, TAG, "[EDRCore] Could not get CaEdrInterface class");
+        OIC_LOG(ERROR, TAG, "Could not get CaEdrInterface class");
         return CA_STATUS_FAILED;
     }
 
@@ -326,21 +317,18 @@ CAResult_t CAEDRCreateJNIInterfaceObject(jobject context)
                                                                   "(Landroid/content/Context;)V");
     if (!EDRInterfaceConstructorMethod)
     {
-        OIC_LOG(ERROR, TAG, "[EDRCore] Could not get CaEdrInterface constructor method");
+        OIC_LOG(ERROR, TAG, "Could not get CaEdrInterface constructor method");
         return CA_STATUS_FAILED;
     }
 
     (*env)->NewObject(env, EDRJniInterface, EDRInterfaceConstructorMethod, context);
-    OIC_LOG(DEBUG, TAG, "[EDRCore] NewObject Success");
+    OIC_LOG(DEBUG, TAG, "NewObject Success");
 
     return CA_STATUS_OK;
-
 }
 
 static void CAEDRDestroyMutex()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     if (g_mutexUnicastServer)
     {
         ca_mutex_free(g_mutexUnicastServer);
@@ -364,13 +352,10 @@ static void CAEDRDestroyMutex()
         ca_mutex_free(g_mutexObjectList);
         g_mutexObjectList = NULL;
     }
-    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 static CAResult_t CAEDRCreateMutex()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     g_mutexUnicastServer = ca_mutex_new();
     if (!g_mutexUnicastServer)
     {
@@ -405,22 +390,24 @@ static CAResult_t CAEDRCreateMutex()
         return CA_STATUS_FAILED;
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
 
-void CAEDRInitialize(ca_thread_pool_t handle)
+CAResult_t CAEDRInitialize()
 {
     OIC_LOG(DEBUG, TAG, "CAEDRInitialize");
 
-    g_threadPoolHandle = handle;
-
     CAEDRCoreJniInit();
 
     CAEDRJniInitContext();
 
     // init mutex
-    CAEDRCreateMutex();
+    CAResult_t result = CAEDRCreateMutex();
+    if(CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, TAG, "CAEDRInitialize - Could not create mutex");
+        return result;
+    }
 
     bool isAttached = false;
     JNIEnv* env;
@@ -433,7 +420,7 @@ void CAEDRInitialize(ca_thread_pool_t handle)
         if (JNI_OK != res)
         {
             OIC_LOG(ERROR, TAG, "AttachCurrentThread failed");
-            return;
+            return CA_STATUS_NOT_INITIALIZED;
         }
         isAttached = true;
     }
@@ -444,6 +431,7 @@ void CAEDRInitialize(ca_thread_pool_t handle)
         OIC_LOG_V(DEBUG, TAG, "My BT Address is %s", localAddress);
         (*env)->ReleaseStringUTFChars(env, jni_address, localAddress);
     }
+    (*env)->DeleteLocalRef(env, jni_address);
 
     ca_mutex_lock(g_mutexStateList);
     CAEDRNativeCreateDeviceStateList();
@@ -464,6 +452,8 @@ void CAEDRInitialize(ca_thread_pool_t handle)
     }
 
     OIC_LOG(DEBUG, TAG, "OUT");
+
+    return result;
 }
 
 void CAEDRTerminate()
@@ -507,6 +497,78 @@ void CAEDRTerminate()
 
     CAEDRNativeRemoveAllDeviceState();
     CAEDRNativeRemoveAllDeviceSocket(env);
+    CAEDRDestroyJniInterface();
+}
+
+CAResult_t CAEDRDestroyJniInterface()
+{
+    OIC_LOG(DEBUG, TAG, "CAEDRDestroyJniInterface");
+
+    if (!g_jvm)
+    {
+        OIC_LOG(ERROR, TAG, "g_jvm is null");
+        return CA_STATUS_FAILED;
+    }
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return CA_STATUS_FAILED;
+        }
+        isAttached = true;
+    }
+
+    jclass jni_EDRJniInterface = (*env)->FindClass(env, CLASSPATH_BT_INTERFACE);
+    if (!jni_EDRJniInterface)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get CaEdrInterface class");
+        goto error_exit;
+    }
+
+    jmethodID jni_EDRInterfaceDestroyMethod = (*env)->GetStaticMethodID(env, jni_EDRJniInterface,
+                                                                        "destroyEdrInterface",
+                                                                        "()V");
+    if (!jni_EDRInterfaceDestroyMethod)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get CaEdrInterface destroy method");
+        goto error_exit;
+    }
+
+    (*env)->CallStaticVoidMethod(env, jni_EDRJniInterface, jni_EDRInterfaceDestroyMethod);
+
+    if ((*env)->ExceptionCheck(env))
+    {
+        OIC_LOG(ERROR, TAG, "destroyEdrInterface has failed");
+        (*env)->ExceptionDescribe(env);
+        (*env)->ExceptionClear(env);
+        goto error_exit;
+    }
+
+    OIC_LOG(DEBUG, TAG, "Destroy instance for CaEdrInterface");
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    return CA_STATUS_OK;
+
+error_exit:
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    return CA_STATUS_FAILED;
 }
 
 void CAEDRCoreJniInit()
@@ -527,7 +589,6 @@ CAResult_t CAEDRSendUnicastMessage(const char* address, const uint8_t* data, uin
 CAResult_t CAEDRSendMulticastMessage(const uint8_t* data, uint32_t dataLen)
 {
     VERIFY_NON_NULL(data, TAG, "data is null");
-    OIC_LOG_V(DEBUG, TAG, "CAEDRSendMulticastMessage(%s)", data);
 
     bool isAttached = false;
     JNIEnv* env;
@@ -618,7 +679,6 @@ CAResult_t CAEDRSendUnicastMessageImpl(const char* address, const uint8_t* data,
 {
     VERIFY_NON_NULL(address, TAG, "address is null");
     VERIFY_NON_NULL(data, TAG, "data is null");
-    OIC_LOG_V(DEBUG, TAG, "CAEDRSendUnicastMessageImpl, address: %s, data: %s", address, data);
 
     bool isAttached = false;
     JNIEnv* env;
@@ -635,13 +695,13 @@ CAResult_t CAEDRSendUnicastMessageImpl(const char* address, const uint8_t* data,
         isAttached = true;
     }
 
-    OIC_LOG(DEBUG, TAG, "[EDR][Native] set byteArray for data");
+    OIC_LOG(DEBUG, TAG, "set byteArray for data");
 
     // get bonded device list
     jobjectArray jni_arrayPairedDevices = CAEDRNativeGetBondedDevices(env);
     if (!jni_arrayPairedDevices)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] jni_arrayPairedDevices is empty");
+        OIC_LOG(ERROR, TAG, "jni_arrayPairedDevices is empty");
         if (isAttached)
         {
             (*g_jvm)->DetachCurrentThread(g_jvm);
@@ -658,7 +718,7 @@ CAResult_t CAEDRSendUnicastMessageImpl(const char* address, const uint8_t* data,
     jsize length = (*env)->GetArrayLength(env, jni_arrayPairedDevices);
     for (jsize i = 0; i < length; i++)
     {
-        OIC_LOG(DEBUG, TAG, "[EDR][Native] start to check device");
+        OIC_LOG(DEBUG, TAG, "start to check device");
         // get name, address from BT device
         jobject j_obj_device = (*env)->GetObjectArrayElement(env, jni_arrayPairedDevices, i);
         jstring j_str_name = (*env)->CallObjectMethod(env, j_obj_device, j_mid_getName);
@@ -666,7 +726,7 @@ CAResult_t CAEDRSendUnicastMessageImpl(const char* address, const uint8_t* data,
         if (j_str_name)
         {
             const char * name = (*env)->GetStringUTFChars(env, j_str_name, NULL);
-            OIC_LOG_V(DEBUG, TAG, "[EDR][Native] getBondedDevices: ~~device name is %s", name);
+            OIC_LOG_V(DEBUG, TAG, "device name is %s", name);
             (*env)->ReleaseStringUTFChars(env, j_str_name, name);
             (*env)->DeleteLocalRef(env, j_str_name);
         }
@@ -676,7 +736,7 @@ CAResult_t CAEDRSendUnicastMessageImpl(const char* address, const uint8_t* data,
         (*env)->DeleteLocalRef(env, j_obj_device);
         if (!remoteAddress)
         {
-            OIC_LOG(ERROR, TAG, "[EDR][Native] remoteAddress is null");
+            OIC_LOG(ERROR, TAG, "remoteAddress is null");
             if (isAttached)
             {
                 (*g_jvm)->DetachCurrentThread(g_jvm);
@@ -687,8 +747,7 @@ CAResult_t CAEDRSendUnicastMessageImpl(const char* address, const uint8_t* data,
             (*env)->DeleteLocalRef(env, jni_cid_BTDevice);
             return CA_STATUS_INVALID_PARAM;
         }
-        OIC_LOG_V(DEBUG, TAG,
-                  "[EDR][Native] getBondedDevices: ~~device address is %s", remoteAddress);
+        OIC_LOG_V(DEBUG, TAG, "device address is %s", remoteAddress);
 
         // find address
         if (!strcmp(remoteAddress, address))
@@ -721,14 +780,14 @@ CAResult_t CAEDRSendUnicastMessageImpl(const char* address, const uint8_t* data,
 
 CAResult_t CAEDRSendMulticastMessageImpl(JNIEnv *env, const uint8_t* data, uint32_t dataLen)
 {
+    VERIFY_NON_NULL(env, TAG, "env is null");
     VERIFY_NON_NULL(data, TAG, "data is null");
-    OIC_LOG_V(DEBUG, TAG, "CASendMulticastMessageImpl, send to, data: %s, %d", data, dataLen);
 
     // get bonded device list
     jobjectArray jni_arrayPairedDevices = CAEDRNativeGetBondedDevices(env);
     if (!jni_arrayPairedDevices)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] jni_arrayPairedDevices is empty");
+        OIC_LOG(ERROR, TAG, "jni_arrayPairedDevices is empty");
         return CA_STATUS_INVALID_PARAM;
     }
     // Get information from array of devices
@@ -744,32 +803,31 @@ CAResult_t CAEDRSendMulticastMessageImpl(JNIEnv *env, const uint8_t* data, uint3
         // get name, address from BT device
         jobject j_obj_device = (*env)->GetObjectArrayElement(env, jni_arrayPairedDevices, i);
         jstring j_str_name = (*env)->CallObjectMethod(env, j_obj_device, j_mid_getName);
+        jstring j_str_address = (*env)->CallObjectMethod(env, j_obj_device, j_mid_getAddress);
 
-        if (j_str_name)
+        if (j_str_name && j_str_address)
         {
             const char * name = (*env)->GetStringUTFChars(env, j_str_name, NULL);
-            OIC_LOG_V(DEBUG, TAG, "[EDR][Native] getBondedDevices: ~~device name is %s", name);
+            const char * remoteAddress = (*env)->GetStringUTFChars(env, j_str_address, NULL);
+            if (name && remoteAddress)
+            {
+                OIC_LOG_V(DEBUG, TAG, "device name is %s, address is %s", name, remoteAddress);
+
+                CAResult_t res = CAEDRNativeSendData(env, remoteAddress, data, dataLen);
+                if (CA_STATUS_OK != res)
+                {
+                    OIC_LOG_V(ERROR, TAG, "Failed to send multicast message to : %s",
+                              remoteAddress);
+                    g_edrErrorHandler(remoteAddress, data, dataLen, res);
+                }
+            }
             (*env)->ReleaseStringUTFChars(env, j_str_name, name);
-            (*env)->DeleteLocalRef(env, j_str_name);
+            (*env)->ReleaseStringUTFChars(env, j_str_address, remoteAddress);
         }
 
-        jstring j_str_address = (*env)->CallObjectMethod(env, j_obj_device, j_mid_getAddress);
-        const char * remoteAddress = (*env)->GetStringUTFChars(env, j_str_address, NULL);
         (*env)->DeleteLocalRef(env, j_obj_device);
-        OIC_LOG_V(DEBUG, TAG,
-                  "[EDR][Native] getBondedDevices: ~~device address is %s", remoteAddress);
-
-        // find address
-        CAResult_t res = CAEDRNativeSendData(env, remoteAddress, data, dataLen);
-        (*env)->ReleaseStringUTFChars(env, j_str_address, remoteAddress);
+        (*env)->DeleteLocalRef(env, j_str_name);
         (*env)->DeleteLocalRef(env, j_str_address);
-        if (CA_STATUS_OK != res)
-        {
-            OIC_LOG_V(ERROR, TAG, "CASendMulticastMessageImpl, failed to send message to : %s",
-                      remoteAddress);
-            g_edrErrorHandler(remoteAddress, data, dataLen, res);
-            continue;
-        }
     }
 
     (*env)->DeleteLocalRef(env, jni_arrayPairedDevices);
@@ -778,26 +836,23 @@ CAResult_t CAEDRSendMulticastMessageImpl(JNIEnv *env, const uint8_t* data, uint3
     return CA_STATUS_OK;
 }
 
-/**
- * EDR Method
- */
 CAResult_t CAEDRNativeSendData(JNIEnv *env, const char *address, const uint8_t *data,
                                uint32_t dataLength)
 {
+    VERIFY_NON_NULL(env, TAG, "env is null");
     VERIFY_NON_NULL(address, TAG, "address is null");
     VERIFY_NON_NULL(data, TAG, "data is null");
-    OIC_LOG_V(DEBUG, TAG, "[EDR][Native] btSendData logic start : %s, %d", data, dataLength);
 
     if (!CAEDRNativeIsEnableBTAdapter(env))
     {
-        OIC_LOG(ERROR, TAG, "BT adpater is not enable");
-        return CA_STATUS_INVALID_PARAM;
+        OIC_LOG(INFO, TAG, "BT adapter is not enabled");
+        return CA_ADAPTER_NOT_ENABLED;
     }
 
     if (STATE_DISCONNECTED == CAEDRIsConnectedDevice(address))
     {
         // connect before send data
-        OIC_LOG(DEBUG, TAG, "[EDR][Native] connect before send data");
+        OIC_LOG(DEBUG, TAG, "connect before send data");
 
         CAResult_t res = CAEDRNativeConnect(env, address);
         if (CA_STATUS_OK != res)
@@ -813,7 +868,7 @@ CAResult_t CAEDRNativeSendData(JNIEnv *env, const char *address, const uint8_t *
             jclass jni_cid_BTsocket = (*env)->FindClass(env, CLASSPATH_BT_SOCKET);
             if (!jni_cid_BTsocket)
             {
-                OIC_LOG(ERROR, TAG, "[EDR][Native] btSendData: jni_cid_BTsocket is null");
+                OIC_LOG(ERROR, TAG, "jni_cid_BTsocket is null");
                 return CA_STATUS_FAILED;
             }
 
@@ -822,17 +877,17 @@ CAResult_t CAEDRNativeSendData(JNIEnv *env, const char *address, const uint8_t *
                                                                     METHODID_OUTPUTNONPARAM);
             if (!jni_mid_getOutputStream)
             {
-                OIC_LOG(ERROR, TAG, "[EDR][Native] btSendData: jni_mid_getOutputStream is null");
+                OIC_LOG(ERROR, TAG, "jni_mid_getOutputStream is null");
                 (*env)->DeleteLocalRef(env, jni_cid_BTsocket);
                 return CA_STATUS_FAILED;
             }
 
-            OIC_LOG(DEBUG, TAG, "[EDR][Native] btSendData: Get MethodID for i/o stream");
+            OIC_LOG(DEBUG, TAG, "Get MethodID for i/o stream");
 
             jobject jni_obj_socket = CAEDRNativeGetDeviceSocketBaseAddr(env, address);
             if (!jni_obj_socket)
             {
-                OIC_LOG(ERROR, TAG, "[EDR][Native] btSendData: jni_socket is not available");
+                OIC_LOG(ERROR, TAG, "jni_socket is not available");
                 (*env)->DeleteLocalRef(env, jni_cid_BTsocket);
                 return CA_STATUS_FAILED;
             }
@@ -841,17 +896,17 @@ CAResult_t CAEDRNativeSendData(JNIEnv *env, const char *address, const uint8_t *
                                                                     jni_mid_getOutputStream);
             if (!jni_obj_outputStream)
             {
-                OIC_LOG(ERROR, TAG, "[EDR][Native] btSendData: jni_obj_outputStream is null");
+                OIC_LOG(ERROR, TAG, "jni_obj_outputStream is null");
                 (*env)->DeleteLocalRef(env, jni_cid_BTsocket);
                 return CA_STATUS_FAILED;
             }
 
-            OIC_LOG(DEBUG, TAG, "[EDR][Native] btSendData: ready outputStream..");
+            OIC_LOG(DEBUG, TAG, "ready outputStream..");
 
             jclass jni_cid_OutputStream = (*env)->FindClass(env, CLASSPATH_OUTPUT);
             if (!jni_cid_OutputStream)
             {
-                OIC_LOG(ERROR, TAG, "[EDR][Native] btSendData: jni_cid_OutputStream is null");
+                OIC_LOG(ERROR, TAG, "jni_cid_OutputStream is null");
                 (*env)->DeleteLocalRef(env, jni_cid_BTsocket);
                 (*env)->DeleteLocalRef(env, jni_obj_outputStream);
                 return CA_STATUS_FAILED;
@@ -861,7 +916,7 @@ CAResult_t CAEDRNativeSendData(JNIEnv *env, const char *address, const uint8_t *
                                                           "([BII)V");
             if (!jni_mid_write)
             {
-                OIC_LOG(ERROR, TAG, "[EDR][Native] btSendData: jni_mid_write is null");
+                OIC_LOG(ERROR, TAG, "jni_mid_write is null");
                 (*env)->DeleteLocalRef(env, jni_cid_BTsocket);
                 (*env)->DeleteLocalRef(env, jni_obj_outputStream);
                 (*env)->DeleteLocalRef(env, jni_cid_OutputStream);
@@ -881,25 +936,26 @@ CAResult_t CAEDRNativeSendData(JNIEnv *env, const char *address, const uint8_t *
 
             if ((*env)->ExceptionCheck(env))
             {
-                OIC_LOG(ERROR, TAG, "[EDR][Native] btSendData: Write Error!!!");
+                OIC_LOG(ERROR, TAG, "Failed to write data in outputStram");
                 (*env)->ExceptionDescribe(env);
                 (*env)->ExceptionClear(env);
                 return CA_STATUS_FAILED;
             }
 
-            OIC_LOG(DEBUG, TAG, "[EDR][Native] btSendData: Write Success");
+            OIC_LOG_V(INFO, TAG, "EDR sendTo is successful: %u bytes, to %s",
+                      dataLength, address);
         }
         else
         {
             (*env)->ExceptionDescribe(env);
             (*env)->ExceptionClear(env);
-            OIC_LOG(ERROR, TAG, "[EDR][Native] btSendData: error!!");
+            OIC_LOG(ERROR, TAG, "error!!");
             return CA_STATUS_FAILED;
         }
     }
     else
     {
-        OIC_LOG(DEBUG, TAG, "[EDR][Native] btSendData: BT connection is not completed!!");
+        OIC_LOG(DEBUG, TAG, "BT connection is not completed!!");
     }
 
     return CA_STATUS_OK;
@@ -908,18 +964,18 @@ CAResult_t CAEDRNativeSendData(JNIEnv *env, const char *address, const uint8_t *
 CAResult_t CAEDRNativeConnect(JNIEnv *env, const char *address)
 {
     VERIFY_NON_NULL(address, TAG, "address is null");
-    OIC_LOG(DEBUG, TAG, "[EDR][Native] btConnect..");
+    OIC_LOG(DEBUG, TAG, "btConnect..");
 
     if (!CAEDRNativeIsEnableBTAdapter(env))
     {
-        OIC_LOG(ERROR, TAG, "BT adpater is not enable");
-        return CA_STATUS_INVALID_PARAM;
+        OIC_LOG(INFO, TAG, "BT adapter is not enabled");
+        return CA_ADAPTER_NOT_ENABLED;
     }
 
     jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
     if (!jni_cid_BTAdapter)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_cid_BTAdapter is null");
+        OIC_LOG(ERROR, TAG, "jni_cid_BTAdapter is null");
         return CA_STATUS_FAILED;
     }
 
@@ -929,7 +985,7 @@ CAResult_t CAEDRNativeConnect(JNIEnv *env, const char *address)
                                                                     METHODID_OBJECTNONPARAM);
     if (!jni_mid_getDefaultAdapter)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_mid_getDefaultAdapter is null");
+        OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null");
         (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
         return CA_STATUS_FAILED;
     }
@@ -938,7 +994,7 @@ CAResult_t CAEDRNativeConnect(JNIEnv *env, const char *address)
                                                                jni_mid_getDefaultAdapter);
     if (!jni_obj_BTAdapter)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_obj_BTAdapter is null");
+        OIC_LOG(ERROR, TAG, "jni_obj_BTAdapter is null");
         (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
         return CA_STATUS_FAILED;
     }
@@ -950,7 +1006,7 @@ CAResult_t CAEDRNativeConnect(JNIEnv *env, const char *address)
     (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
     if (!jni_mid_getRemoteDevice)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_mid_getRemoteDevice is null");
+        OIC_LOG(ERROR, TAG, "jni_mid_getRemoteDevice is null");
         (*env)->DeleteLocalRef(env, jni_obj_BTAdapter);
         return CA_STATUS_FAILED;
     }
@@ -962,7 +1018,7 @@ CAResult_t CAEDRNativeConnect(JNIEnv *env, const char *address)
     (*env)->DeleteLocalRef(env, jni_obj_BTAdapter);
     if (!jni_obj_remoteBTDevice)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_obj_remoteBTDevice is null");
+        OIC_LOG(ERROR, TAG, "jni_obj_remoteBTDevice is null");
         return CA_STATUS_FAILED;
     }
 
@@ -970,7 +1026,7 @@ CAResult_t CAEDRNativeConnect(JNIEnv *env, const char *address)
     jclass jni_cid_BluetoothDevice = (*env)->FindClass(env, CLASSPATH_BT_DEVICE);
     if (!jni_cid_BluetoothDevice)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_cid_BluetoothDevice is null");
+        OIC_LOG(ERROR, TAG, "jni_cid_BluetoothDevice is null");
         (*env)->DeleteLocalRef(env, jni_obj_remoteBTDevice);
         return CA_STATUS_FAILED;
     }
@@ -981,7 +1037,7 @@ CAResult_t CAEDRNativeConnect(JNIEnv *env, const char *address)
     (*env)->DeleteLocalRef(env, jni_cid_BluetoothDevice);
     if (!jni_mid_createSocket)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_mid_createSocket is null");
+        OIC_LOG(ERROR, TAG, "jni_mid_createSocket is null");
         (*env)->DeleteLocalRef(env, jni_obj_remoteBTDevice);
         return CA_STATUS_FAILED;
     }
@@ -990,7 +1046,7 @@ CAResult_t CAEDRNativeConnect(JNIEnv *env, const char *address)
     jclass jni_cid_uuid = (*env)->FindClass(env, CLASSPATH_BT_UUID);
     if (!jni_cid_uuid)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_cid_uuid is null");
+        OIC_LOG(ERROR, TAG, "jni_cid_uuid is null");
         (*env)->DeleteLocalRef(env, jni_obj_remoteBTDevice);
         return CA_STATUS_FAILED;
     }
@@ -999,7 +1055,7 @@ CAResult_t CAEDRNativeConnect(JNIEnv *env, const char *address)
             env, jni_cid_uuid, "fromString", "(Ljava/lang/String;)Ljava/util/UUID;");
     if (!jni_mid_fromString)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_mid_fromString is null");
+        OIC_LOG(ERROR, TAG, "jni_mid_fromString is null");
         (*env)->DeleteLocalRef(env, jni_cid_uuid);
         (*env)->DeleteLocalRef(env, jni_obj_remoteBTDevice);
         return CA_STATUS_FAILED;
@@ -1008,7 +1064,7 @@ CAResult_t CAEDRNativeConnect(JNIEnv *env, const char *address)
     jstring jni_uuid = (*env)->NewStringUTF(env, OIC_EDR_SERVICE_ID);
     if (!jni_uuid)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_uuid is null");
+        OIC_LOG(ERROR, TAG, "jni_uuid is null");
         (*env)->DeleteLocalRef(env, jni_cid_uuid);
         (*env)->DeleteLocalRef(env, jni_obj_remoteBTDevice);
         return CA_STATUS_FAILED;
@@ -1019,7 +1075,7 @@ CAResult_t CAEDRNativeConnect(JNIEnv *env, const char *address)
     (*env)->DeleteLocalRef(env, jni_uuid);
     if (!jni_obj_uuid)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_obj_uuid is null");
+        OIC_LOG(ERROR, TAG, "jni_obj_uuid is null");
         (*env)->DeleteLocalRef(env, jni_obj_remoteBTDevice);
         return CA_STATUS_FAILED;
     }
@@ -1030,7 +1086,7 @@ CAResult_t CAEDRNativeConnect(JNIEnv *env, const char *address)
     (*env)->DeleteLocalRef(env, jni_obj_remoteBTDevice);
     if (!jni_obj_BTSocket)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_obj_BTSocket is null");
+        OIC_LOG(ERROR, TAG, "jni_obj_BTSocket is null");
         return CA_STATUS_FAILED;
     }
 
@@ -1038,7 +1094,7 @@ CAResult_t CAEDRNativeConnect(JNIEnv *env, const char *address)
     jclass jni_cid_BTSocket = (*env)->FindClass(env, CLASSPATH_BT_SOCKET);
     if (!jni_cid_BTSocket)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_cid_BTSocket is null");
+        OIC_LOG(ERROR, TAG, "jni_cid_BTSocket is null");
         (*env)->DeleteLocalRef(env, jni_obj_BTSocket);
         return CA_STATUS_FAILED;
     }
@@ -1047,17 +1103,17 @@ CAResult_t CAEDRNativeConnect(JNIEnv *env, const char *address)
     (*env)->DeleteLocalRef(env, jni_cid_BTSocket);
     if (!jni_mid_connect)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_mid_connect is null");
+        OIC_LOG(ERROR, TAG, "jni_mid_connect is null");
         (*env)->DeleteLocalRef(env, jni_obj_BTSocket);
         return CA_STATUS_FAILED;
     }
 
-    OIC_LOG(DEBUG, TAG, "[EDR][Native] btConnect: initiating connection...");
+    OIC_LOG(DEBUG, TAG, "initiating connection...");
     (*env)->CallVoidMethod(env, jni_obj_BTSocket, jni_mid_connect);
 
     if ((*env)->ExceptionCheck(env))
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: Connect is Failed!!!");
+        OIC_LOG(ERROR, TAG, "Connect is Failed!!!");
         (*env)->ExceptionDescribe(env);
         (*env)->ExceptionClear(env);
         return CA_STATUS_FAILED;
@@ -1067,7 +1123,7 @@ CAResult_t CAEDRNativeConnect(JNIEnv *env, const char *address)
     jobject jni_socket = (*env)->NewGlobalRef(env, jni_obj_BTSocket);
     if (!jni_socket)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_socket is null");
+        OIC_LOG(ERROR, TAG, "jni_socket is null");
         (*env)->DeleteLocalRef(env, jni_obj_BTSocket);
         return CA_STATUS_FAILED;
     }
@@ -1082,7 +1138,7 @@ CAResult_t CAEDRNativeConnect(JNIEnv *env, const char *address)
     CAEDRUpdateDeviceState(STATE_CONNECTED, address);
     ca_mutex_unlock(g_mutexStateList);
 
-    OIC_LOG(DEBUG, TAG, "[EDR][Native] btConnect: connected");
+    OIC_LOG(DEBUG, TAG, "connected");
 
     return CA_STATUS_OK;
 }
@@ -1094,21 +1150,21 @@ void CAEDRNativeSocketClose(JNIEnv *env, const char *address)
     jclass jni_cid_BTSocket = (*env)->FindClass(env, "android/bluetooth/BluetoothSocket");
     if (!jni_cid_BTSocket)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] close: jni_cid_BTSocket is null");
+        OIC_LOG(ERROR, TAG, "jni_cid_BTSocket is null");
         return;
     }
 
     jmethodID jni_mid_close = (*env)->GetMethodID(env, jni_cid_BTSocket, "close", "()V");
     if (!jni_mid_close)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] close: jni_mid_close is null");
+        OIC_LOG(ERROR, TAG, "jni_mid_close is null");
         return;
     }
 
     jobject jni_obj_socket = CAEDRNativeGetDeviceSocketBaseAddr(env, address);
     if (!jni_obj_socket)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] close: jni_obj_socket is not available");
+        OIC_LOG(ERROR, TAG, "jni_obj_socket is not available");
         return;
     }
 
@@ -1116,7 +1172,7 @@ void CAEDRNativeSocketClose(JNIEnv *env, const char *address)
 
     if ((*env)->ExceptionCheck(env))
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] close: close is Failed!!!");
+        OIC_LOG(ERROR, TAG, "close is Failed!!!");
         (*env)->ExceptionDescribe(env);
         (*env)->ExceptionClear(env);
         return;
@@ -1130,14 +1186,13 @@ void CAEDRNativeSocketClose(JNIEnv *env, const char *address)
     CAEDRUpdateDeviceState(STATE_DISCONNECTED, address);
     ca_mutex_unlock(g_mutexStateList);
 
-    OIC_LOG(DEBUG, TAG, "[EDR][Native] close: disconnected");
+    OIC_LOG(DEBUG, TAG, "disconnected");
 }
 
-void CAEDRInitializeClient(ca_thread_pool_t handle)
+CAResult_t CAEDRClientInitialize()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-    CAEDRInitialize(handle);
-    OIC_LOG(DEBUG, TAG, "OUT");
+    CAResult_t result = CAEDRInitialize();
+    return result;
 }
 
 void CAEDRSetErrorHandler(CAEDRErrorHandleCallback errorHandleCallback)
index 98e2cc8..c8c0bb6 100644 (file)
@@ -50,9 +50,9 @@ CAResult_t CAEDRCreateJNIInterfaceObject(jobject context);
 
 /**
  * Initialize client for EDR.
- * @param[in]  handle           thread pool handle object.
+ * @return  ::CA_STATUS_OK or Appropriate error code.
  */
-void CAEDRInitialize(ca_thread_pool_t handle);
+CAResult_t CAEDRInitialize();
 
 /**
  * Terminate server for EDR.
@@ -60,6 +60,12 @@ void CAEDRInitialize(ca_thread_pool_t handle);
 void CAEDRTerminate();
 
 /**
+ * destroy interface object and terminate the interface.
+ * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
+ */
+CAResult_t CAEDRDestroyJniInterface();
+
+/**
  * Initialize JNI object.
  */
 void CAEDRCoreJniInit();
index 14fca1e..de187d8 100644 (file)
@@ -36,7 +36,7 @@
 #include "org_iotivity_ca_CaEdrInterface.h"
 
 //#define DEBUG_MODE
-#define TAG PCF("CA_EDR_MONITOR")
+#define TAG PCF("OIC_CA_EDR_MONITOR")
 
 static JavaVM *g_jvm;
 static jobject g_context;
@@ -127,7 +127,7 @@ Java_org_iotivity_ca_CaEdrInterface_caEdrStateChangedCallback(JNIEnv *env, jobje
 
     if (NULL == g_networkChangeCb)
     {
-        OIC_LOG_V(DEBUG, TAG, "gNetworkChangeCb is null", status);
+        OIC_LOG(DEBUG, TAG, "g_networkChangeCb is null");
         return;
     }
 
@@ -158,14 +158,23 @@ Java_org_iotivity_ca_CaEdrInterface_caEdrStateChangedCallback(JNIEnv *env, jobje
     if (state_on == status)
     {
         CANetworkStatus_t newStatus = CA_INTERFACE_UP;
+
+        CAResult_t res = CAEDRStartUnicastServer(false);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "CAEDRStartUnicastServer failed");
+            return;
+        }
         CAEDRServerStartAcceptThread();
         g_networkChangeCb(newStatus);
     }
     else if (state_off == status)
     {
         CANetworkStatus_t newStatus = CA_INTERFACE_DOWN;
+        CAEDRServerStop();
+        CAEDRNativeSocketCloseToAll(env);
+        CAEDRNativeRemoveAllDeviceState();
         CAEDRNativeRemoveAllDeviceSocket(env);
-        CAEDRNativeRemoveAllDeviceState(env);
         g_networkChangeCb(newStatus);
     }
 }
index de09553..66decf1 100644 (file)
@@ -34,9 +34,7 @@
 #include "org_iotivity_ca_CaEdrInterface.h"
 #include "oic_string.h"
 
-//#define DEBUG_MODE
-#define TAG PCF("CA_EDR_SERVER")
-#define MAX_PDU_BUFFER (1024)
+#define TAG PCF("OIC_CA_EDR_SERVER")
 
 static const char METHODID_OBJECTNONPARAM[] = "()Landroid/bluetooth/BluetoothAdapter;";
 static const char CLASSPATH_BT_ADPATER[] = "android/bluetooth/BluetoothAdapter";
@@ -47,9 +45,10 @@ static ca_thread_pool_t g_threadPoolHandle = NULL;
 static JavaVM *g_jvm;
 
 /**
- * Mutex to synchronize socket list update.
+ * Maximum CoAP over TCP header length
+ * to know the total data length.
  */
-static ca_mutex g_mutexSocketListManager;
+#define EDR_MAX_HEADER_LEN  6
 
 /**
  * server socket instance.
@@ -86,8 +85,6 @@ static ca_mutex g_mutexAcceptServer = NULL;
  */
 static bool g_stopAccept = false;
 
-static jobject g_inputStream = NULL;
-
 /**
  * Mutex to synchronize server socket.
  */
@@ -106,18 +103,6 @@ static ca_mutex g_mutexStateList = NULL;
 static ca_mutex g_mutexObjectList = NULL;
 
 /**
- * Mutex to synchronize input stream.
- */
-static ca_mutex g_mutexInputStream = NULL;
-
-typedef struct send_data
-{
-    char* address;
-    char* data;
-    uint32_t id;
-} data_t;
-
-/**
  * Thread context information for unicast, multicast and secured unicast server.
  */
 typedef struct
@@ -163,6 +148,12 @@ static void CAReceiveHandler(void *data)
 
     while (true != *(ctx->stopFlag))
     {
+        if (!CAEDRNativeIsEnableBTAdapter(env))
+        {
+            OIC_LOG(INFO, TAG, "BT adapter is not enabled");
+            break;
+        }
+
         // if new socket object is added in socket list after below logic is ran.
         // new socket will be started to read after next while loop
         uint32_t length = CAEDRGetSocketListLength();
@@ -170,8 +161,7 @@ static void CAReceiveHandler(void *data)
         {
             for (uint32_t idx = 0; idx < length; idx++)
             {
-                OIC_LOG(DEBUG, TAG, "start CAEDRNativeReadData");
-                CAEDRNativeReadData(env, idx, ctx->type);
+                CAEDRNativeReadData(env, idx);
             }
         }
     }
@@ -188,13 +178,9 @@ static void CAReceiveHandler(void *data)
 
 static void CAAcceptHandler(void *data)
 {
-    if (!data)
-    {
-        OIC_LOG(ERROR, TAG, "[EDR] CAAcceptHandler: data is null");
-        return;
-    }
+    OIC_LOG(DEBUG, TAG, "AcceptThread start");
 
-    OIC_LOG(DEBUG, TAG, "[EDR] AcceptThread start");
+    VERIFY_NON_NULL_VOID(data, TAG, "CAAcceptHandler: data is null");
 
     bool isAttached = false;
     JNIEnv* env;
@@ -215,7 +201,7 @@ static void CAAcceptHandler(void *data)
     jobject jni_obj_BTServerSocket = CAEDRNativeListen(env);
     if (!jni_obj_BTServerSocket)
     {
-        OIC_LOG(ERROR, TAG, "[EDR] AcceptThread: jni_obj_BTServerSocket is null");
+        OIC_LOG(ERROR, TAG, "AcceptThread: jni_obj_BTServerSocket is null");
 
         if (isAttached)
         {
@@ -238,12 +224,12 @@ static void CAAcceptHandler(void *data)
 
     while (true != *(ctx->stopFlag))
     {
-        OIC_LOG(DEBUG, TAG, "[EDR] AcceptThread running");
+        OIC_LOG(DEBUG, TAG, "AcceptThread running");
 
         // when BT state is changed with Off. its thread will be stopped
         if (!CAEDRNativeIsEnableBTAdapter(env))
         {
-            OIC_LOG(DEBUG, TAG, "BT adpater is not enable");
+            OIC_LOG(INFO, TAG, "BT adapter is not enabled");
             ca_mutex_lock(g_mutexAcceptServer);
             g_stopAccept = true;
             ca_mutex_unlock(g_mutexAcceptServer);
@@ -264,7 +250,7 @@ static void CAAcceptHandler(void *data)
 
     OICFree(ctx);
 
-    OIC_LOG(DEBUG, TAG, "[EDR] AcceptThread finish");
+    OIC_LOG(DEBUG, TAG, "AcceptThread finish");
 
     return;
 }
@@ -272,24 +258,27 @@ static void CAAcceptHandler(void *data)
 /**
  * implement for adapter common method.
  */
-CAResult_t CAEDRServerStart(ca_thread_pool_t handle)
+CAResult_t CAEDRServerStart()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-    CAEDRServerInitialize(handle);
+    if (!g_threadPoolHandle)
+    {
+        return CA_STATUS_NOT_INITIALIZED;
+    }
+
+    CAEDRServerStartAcceptThread();
     CAResult_t res = CAEDRStartUnicastServer(false);
     if (CA_STATUS_OK != res)
     {
         OIC_LOG(ERROR, TAG, "CAEDRStartUnicastServer failed");
+        CAEDRServerStop();
         return CA_STATUS_FAILED;
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT");
-    return CA_STATUS_OK;
+    return res;
 }
 
 CAResult_t CAEDRServerStop()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
     CAEDRStopUnicastServer();
     CAEDRStopMulticastServer();
 
@@ -299,7 +288,7 @@ CAResult_t CAEDRServerStop()
 
     if (!g_jvm)
     {
-        OIC_LOG(DEBUG, TAG, "CAEDRServerStop - g_jvm is null");
+        OIC_LOG(DEBUG, TAG, "g_jvm is null");
         return CA_STATUS_FAILED;
     }
 
@@ -308,7 +297,7 @@ CAResult_t CAEDRServerStop()
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
-        OIC_LOG(DEBUG, TAG, "CAEDRServerStop - Could not get JNIEnv pointer");
+        OIC_LOG(DEBUG, TAG, "Could not get JNIEnv pointer");
         res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
 
         if (JNI_OK != res)
@@ -326,7 +315,6 @@ CAResult_t CAEDRServerStop()
         (*g_jvm)->DetachCurrentThread(g_jvm);
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
 
@@ -335,13 +323,8 @@ void CAEDRSetPacketReceivedCallback(CAEDRDataReceivedCallback packetReceivedCall
     g_edrPacketReceivedCallback = packetReceivedCallback;
 }
 
-/**
- * Destroy Mutex.
- */
 static void CAEDRServerDestroyMutex()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     if (g_mutexUnicastServer)
     {
         ca_mutex_free(g_mutexUnicastServer);
@@ -354,12 +337,6 @@ static void CAEDRServerDestroyMutex()
         g_mutexMulticastServer = NULL;
     }
 
-    if (g_mutexSocketListManager)
-    {
-        ca_mutex_free(g_mutexSocketListManager);
-        g_mutexSocketListManager = NULL;
-    }
-
     if (g_mutexAcceptServer)
     {
         ca_mutex_free(g_mutexAcceptServer);
@@ -383,23 +360,10 @@ static void CAEDRServerDestroyMutex()
         ca_mutex_free(g_mutexObjectList);
         g_mutexObjectList = NULL;
     }
-
-    if (g_mutexInputStream)
-    {
-        ca_mutex_free(g_mutexInputStream);
-        g_mutexInputStream = NULL;
-    }
-
-    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
-/*
- * Create Mutex
- */
 static CAResult_t CAEDRServerCreateMutex()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     g_mutexUnicastServer = ca_mutex_new();
     if (!g_mutexUnicastServer)
     {
@@ -416,15 +380,6 @@ static CAResult_t CAEDRServerCreateMutex()
         return CA_STATUS_FAILED;
     }
 
-    g_mutexSocketListManager = ca_mutex_new();
-    if (!g_mutexSocketListManager)
-    {
-        OIC_LOG(ERROR, TAG, "Failed to created mutex!");
-
-        CAEDRServerDestroyMutex();
-        return CA_STATUS_FAILED;
-    }
-
     g_mutexAcceptServer = ca_mutex_new();
     if (!g_mutexAcceptServer)
     {
@@ -461,16 +416,6 @@ static CAResult_t CAEDRServerCreateMutex()
         return CA_STATUS_FAILED;
     }
 
-    g_mutexInputStream = ca_mutex_new();
-    if (!g_mutexInputStream)
-    {
-        OIC_LOG(ERROR, TAG, "Failed to created g_mutexInputStream.");
-
-        CAEDRServerDestroyMutex();
-        return CA_STATUS_FAILED;
-    }
-
-    OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
 
@@ -480,36 +425,32 @@ void CAEDRServerJniInit()
     g_jvm = CANativeJNIGetJavaVM();
 }
 
-void CAEDRServerInitialize(ca_thread_pool_t handle)
+CAResult_t CAEDRServerInitialize(ca_thread_pool_t handle)
 {
     OIC_LOG(DEBUG, TAG, "CAEDRServerInitialize");
-
+    VERIFY_NON_NULL(handle, TAG, "handle is NULL");
     g_threadPoolHandle = handle;
-
-    CAEDRServerStartAcceptThread();
-
-    OIC_LOG(DEBUG, TAG, "OUT");
-}
-
-void CAEDRServerStartAcceptThread()
-{
     CAEDRServerJniInit();
 
     // init mutex
-    CAEDRServerCreateMutex();
+    CAResult_t result = CAEDRServerCreateMutex();
+    return result;
+}
 
+CAResult_t CAEDRServerStartAcceptThread()
+{
     bool isAttached = false;
     JNIEnv* env;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
-        OIC_LOG(DEBUG, TAG, "CAEDRServerInitialize - Could not get JNIEnv pointer");
+        OIC_LOG(DEBUG, TAG, "Could not get JNIEnv pointer");
         res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
 
         if (JNI_OK != res)
         {
             OIC_LOG(ERROR, TAG, "AttachCurrentThread failed");
-            return;
+            return CA_STATUS_FAILED;
         }
         isAttached = true;
     }
@@ -540,7 +481,7 @@ void CAEDRServerStartAcceptThread()
     if (!ctx)
     {
         OIC_LOG(ERROR, TAG, "Out of memory!");
-        return;
+        return CA_MEMORY_ALLOC_FAILED;
     }
 
     ctx->stopFlag = &g_stopAccept;
@@ -548,10 +489,10 @@ void CAEDRServerStartAcceptThread()
     {
         OIC_LOG(ERROR, TAG, "Failed to create read thread!");
         OICFree((void *) ctx);
-        return;
+        return CA_STATUS_FAILED;
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
 }
 
 void CAEDRServerTerminate()
@@ -567,7 +508,7 @@ void CAEDRServerTerminate()
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
-        OIC_LOG(DEBUG, TAG, "CAEDRServerTerminate - Could not get JNIEnv pointer");
+        OIC_LOG(DEBUG, TAG, "Could not get JNIEnv pointer");
         res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
 
         if (JNI_OK != res)
@@ -696,218 +637,252 @@ CAResult_t CAEDRStopMulticastServer()
     return CA_STATUS_OK;
 }
 
-CAResult_t CAEDRNativeReadData(JNIEnv *env, uint32_t id, CAAdapterServerType_t type)
+CAResult_t CAEDRNativeReadData(JNIEnv *env, uint32_t id)
 {
-    if (!CAEDRNativeIsEnableBTAdapter(env))
+    if ((*env)->ExceptionCheck(env))
+    {
+        (*env)->ExceptionDescribe(env);
+        (*env)->ExceptionClear(env);
+        OIC_LOG(ERROR, TAG, "env error!!");
+        return CA_STATUS_FAILED;
+    }
+
+    // check whether this socket object is connected or not.
+    jobject jni_obj_socket = CAEDRNativeGetDeviceSocket(id);
+    if (!jni_obj_socket)
     {
-        OIC_LOG(ERROR, TAG, "BT adpater is not enable");
         return CA_STATUS_INVALID_PARAM;
     }
 
-    if (!((*env)->ExceptionCheck(env)))
+    // check it whether is still connected or not through google api
+    jboolean ret = CAEDRIsConnectedForSocket(env, jni_obj_socket);
+    if (!ret)
     {
-        // check whether this socket object is connected or not.
-        jobject jni_obj_socket = CAEDRNativeGetDeviceSocket(id);
-        if (!jni_obj_socket)
-        {
-            return CA_STATUS_INVALID_PARAM;
-        }
+        OIC_LOG(ERROR, TAG, "it is not connected yet.");
 
-        jstring jni_str_address = CAEDRNativeGetAddressFromDeviceSocket(env, jni_obj_socket);
-        if (!jni_str_address)
-        {
-            OIC_LOG(ERROR, TAG, "[EDR][Native] btReadData: jni_str_address is null");
-            return CA_STATUS_FAILED;
-        }
-        const char* address = (*env)->GetStringUTFChars(env, jni_str_address, NULL);
+        // remove socket to list
+        CAEDRNativeRemoveDeviceSocket(env, jni_obj_socket);
+        return CA_STATUS_FAILED;
+    }
 
-        // check it whether is still connected or not through google api
-        jboolean ret = CAEDRIsConnectedForSocket(env, jni_obj_socket);
-        if (!ret)
-        {
-            OIC_LOG(DEBUG, TAG, "[EDR][Native] this device is not connected now.let close socket");
-        }
+    // start to read through InputStream
+    jclass jni_cid_BTsocket = (*env)->FindClass(env, "android/bluetooth/BluetoothSocket");
+    if (!jni_cid_BTsocket)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BTsocket is null");
+        return CA_STATUS_FAILED;
+    }
+    jmethodID jni_mid_getInputStream = (*env)->GetMethodID(env, jni_cid_BTsocket,
+                                                           "getInputStream",
+                                                           "()Ljava/io/InputStream;");
 
-        // check it whether is still connected or not through socket state list
-        if (STATE_DISCONNECTED == CAEDRIsConnectedDevice(address))
-        {
-            OIC_LOG(ERROR, TAG, "[EDR][Native] btReadData: it is not connected yet..");
+    jobject jni_obj_inputStream = (*env)->CallObjectMethod(env, jni_obj_socket,
+                                                           jni_mid_getInputStream);
+    if (!jni_obj_inputStream)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_inputStream is null");
+        (*env)->DeleteLocalRef(env, jni_cid_BTsocket);
+        return CA_STATUS_FAILED;
+    }
 
-            // remove socket to list
-            // this code is related to below read fail exception code
-            CAEDRNativeRemoveDeviceSocket(env, jni_obj_socket);
-            (*env)->ReleaseStringUTFChars(env, jni_str_address, address);
+    jclass jni_cid_InputStream = (*env)->FindClass(env, "java/io/InputStream");
+    if (!jni_cid_InputStream)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_InputStream is null");
+        (*env)->DeleteLocalRef(env, jni_obj_inputStream);
+        (*env)->DeleteLocalRef(env, jni_cid_BTsocket);
+        return CA_STATUS_FAILED;
+    }
 
-            (*env)->DeleteLocalRef(env, jni_str_address);
+    jmethodID jni_mid_available = (*env)->GetMethodID(env, jni_cid_InputStream,
+                                                      "available", "()I");
+    if (!jni_mid_available)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_available is null");
+        goto exit;
+    }
 
-            return CA_STATUS_FAILED;
+    jint available = (*env)->CallIntMethod(env, jni_obj_inputStream, jni_mid_available);
+
+    CAConnectedDeviceInfo_t *deviceInfo = NULL;
+    if (0 < available)
+    {
+        jstring jni_str_address = CAEDRNativeGetAddressFromDeviceSocket(env, jni_obj_socket);
+        if (!jni_str_address)
+        {
+            OIC_LOG(ERROR, TAG, "jni_str_address is null");
+            goto exit;
         }
 
-        // start to read through InputStream
-        jclass jni_cid_BTsocket = (*env)->FindClass(env, "android/bluetooth/BluetoothSocket");
-        if (!jni_cid_BTsocket)
+        const char* address = (*env)->GetStringUTFChars(env, jni_str_address, NULL);
+        if (!address)
         {
+            OIC_LOG(ERROR, TAG, "address is null");
             (*env)->DeleteLocalRef(env, jni_str_address);
-
-            OIC_LOG(ERROR, TAG, "[EDR][Native] btReadData: jni_cid_BTsocket is null");
-            return CA_STATUS_FAILED;
+            goto exit;
         }
-        jmethodID jni_mid_getInputStream = (*env)->GetMethodID(env, jni_cid_BTsocket,
-                                                               "getInputStream",
-                                                               "()Ljava/io/InputStream;");
-        OIC_LOG_V(DEBUG, TAG, "[EDR][Native] btReadData:  get InputStream..%d, %s", id, address);
-
-        jobject jni_obj_inputStream = (*env)->CallObjectMethod(env, jni_obj_socket,
-                                                               jni_mid_getInputStream);
-        if (!jni_obj_inputStream)
+
+        OIC_LOG_V(DEBUG, TAG, "get InputStream..%d, %s", id, address);
+        jmethodID jni_mid_read = (*env)->GetMethodID(env, jni_cid_InputStream,
+                                                     "read", "([BII)I");
+        if (!jni_mid_read)
         {
-            (*env)->DeleteLocalRef(env, jni_cid_BTsocket);
+            OIC_LOG(ERROR, TAG, "jni_mid_read is null");
+            (*env)->ReleaseStringUTFChars(env, jni_str_address, address);
             (*env)->DeleteLocalRef(env, jni_str_address);
-
-            OIC_LOG(ERROR, TAG, "[EDR] btReadData: jni_obj_inputStream is null");
-            return CA_STATUS_FAILED;
+            goto exit;
         }
 
-        OIC_LOG(DEBUG, TAG, "[EDR][Native] btReadData:  ready inputStream..");
-
-        jclass jni_cid_InputStream = (*env)->FindClass(env, "java/io/InputStream");
-        if (!jni_cid_InputStream)
+        deviceInfo = (CAConnectedDeviceInfo_t *) CAEDRGetDeviceInfoFromAddress(address);
+        if (!deviceInfo)
         {
-            (*env)->DeleteLocalRef(env, jni_obj_inputStream);
-            (*env)->DeleteLocalRef(env, jni_cid_BTsocket);
+            OIC_LOG(ERROR, TAG, "failed to get device info from list");
+            (*env)->ReleaseStringUTFChars(env, jni_str_address, address);
             (*env)->DeleteLocalRef(env, jni_str_address);
-
-            OIC_LOG(ERROR, TAG, "[EDR][Native] btReadData: jni_cid_InputStream is null");
-            return CA_STATUS_FAILED;
+            goto exit;
         }
-        jmethodID jni_mid_read = (*env)->GetMethodID(env, jni_cid_InputStream, "read", "([BII)I");
-
-        jbyteArray jbuf = (*env)->NewByteArray(env, MAX_PDU_BUFFER);
 
-        ca_mutex_lock(g_mutexInputStream);
-        if (!g_inputStream)
+        jint bufSize = (deviceInfo->totalDataLen == 0) ?
+                EDR_MAX_HEADER_LEN : deviceInfo->totalDataLen;
+        if (!deviceInfo->recvData)
         {
-            g_inputStream = (*env)->NewGlobalRef(env, jni_obj_inputStream);
+            deviceInfo->recvData = OICCalloc(1, bufSize);
+            if (!deviceInfo->recvData)
+            {
+                OIC_LOG(ERROR, TAG, "out of memory");
+                (*env)->ReleaseStringUTFChars(env, jni_str_address, address);
+                (*env)->DeleteLocalRef(env, jni_str_address);
+                goto exit;
+            }
         }
 
-        jint length = (*env)->CallIntMethod(env, g_inputStream, jni_mid_read, jbuf, (jint) 0,
-                                            MAX_PDU_BUFFER);
-        ca_mutex_unlock(g_mutexInputStream);
-
-        OIC_LOG(DEBUG, TAG, "[EDR][Native] read something from InputStream");
-
-        if (-1 == length)
+        jbyteArray jbuf = (*env)->NewByteArray(env, (jint) bufSize - deviceInfo->recvDataLen);
+        if (!jbuf)
         {
-            (*env)->DeleteLocalRef(env, jni_cid_InputStream);
-            (*env)->DeleteLocalRef(env, jbuf);
-            (*env)->DeleteLocalRef(env, jni_obj_inputStream);
-            (*env)->DeleteLocalRef(env, jni_cid_BTsocket);
+            OIC_LOG(ERROR, TAG, "jbuf is null");
+            (*env)->ReleaseStringUTFChars(env, jni_str_address, address);
             (*env)->DeleteLocalRef(env, jni_str_address);
-
-            OIC_LOG(ERROR, TAG, "[EDR][Native] read buffer is empty...");
-            return CA_STATUS_FAILED;
+            goto exit;
         }
 
-        if ((*env)->ExceptionCheck(env))
+        jint recvLen = (*env)->CallIntMethod(env, jni_obj_inputStream, jni_mid_read,
+                                             jbuf, (jint) 0,
+                                             (jint) bufSize - deviceInfo->recvDataLen);
+        if (-1 == recvLen)
         {
-            OIC_LOG(ERROR, TAG, "[EDR][Native] btReadData: read Error!!!");
-            (*env)->ExceptionDescribe(env);
-            (*env)->ExceptionClear(env);
-
-            // update state to disconnect
-            // the socket will be close next read thread routine
-            ca_mutex_lock(g_mutexStateList);
-            CAEDRUpdateDeviceState(STATE_DISCONNECTED, address);
-            ca_mutex_unlock(g_mutexStateList);
-            (*env)->ReleaseStringUTFChars(env, jni_str_address, address);
-
+            OIC_LOG(ERROR, TAG, "recvLen is -1");
             (*env)->DeleteLocalRef(env, jbuf);
-            (*env)->DeleteLocalRef(env, jni_cid_InputStream);
-            (*env)->DeleteLocalRef(env, jni_obj_inputStream);
-            (*env)->DeleteLocalRef(env, jni_cid_BTsocket);
+            (*env)->ReleaseStringUTFChars(env, jni_str_address, address);
             (*env)->DeleteLocalRef(env, jni_str_address);
-
-            return CA_STATUS_FAILED;
+            goto exit;
         }
 
-        OIC_LOG(DEBUG, TAG, "[EDR][Native] btReadData: reading");
         jbyte* buf = (*env)->GetByteArrayElements(env, jbuf, NULL);
-        if (NULL == buf)
+        if (!buf)
         {
-            (*env)->DeleteLocalRef(env, jni_cid_InputStream);
+            OIC_LOG(ERROR, TAG, "buf is null");
             (*env)->DeleteLocalRef(env, jbuf);
-            (*env)->DeleteLocalRef(env, jni_obj_inputStream);
-            (*env)->DeleteLocalRef(env, jni_cid_BTsocket);
+            (*env)->ReleaseStringUTFChars(env, jni_str_address, address);
             (*env)->DeleteLocalRef(env, jni_str_address);
-
-            OIC_LOG(ERROR, TAG, "[EDR][Native] btReadData: buf is null");
-            return CA_STATUS_FAILED;
+            goto exit;
         }
+        memcpy(deviceInfo->recvData + deviceInfo->recvDataLen, (const char*) buf, recvLen);
+        deviceInfo->recvDataLen += recvLen;
 
-        OIC_LOG_V(DEBUG, TAG, "[EDR][Native] btReadData: read %s, %d", buf, length);
+        OIC_LOG(DEBUG, TAG, "read something from InputStream");
 
-        char responseData[MAX_PDU_BUFFER] = { 0 };
-        memcpy(responseData, (const char*) buf, length);
-
-        switch (type)
+        if (!deviceInfo->totalDataLen)
         {
-            case CA_UNICAST_SERVER:
-            case CA_MULTICAST_SERVER:
-                // Notify data to upper layer
-                if (g_edrPacketReceivedCallback)
+            coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
+                    ((unsigned char *) deviceInfo->recvData)[0] >> 4);
+            size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
+            if (deviceInfo->recvData && deviceInfo->recvDataLen >= headerLen)
+            {
+                deviceInfo->totalDataLen = coap_get_total_message_length(deviceInfo->recvData,
+                                                                         deviceInfo->recvDataLen);
+                OIC_LOG_V(DEBUG, TAG, "total data length [%d] bytes", deviceInfo->totalDataLen);
+
+                uint8_t *newBuf = OICRealloc(deviceInfo->recvData, deviceInfo->totalDataLen);
+                if (!newBuf)
                 {
-                    uint32_t sentLength = 0;
-                    OIC_LOG_V(DEBUG, TAG,"[EDR][Native] data will be sent to callback routine: \
-                              %s, %d", responseData, length);
-                    g_edrPacketReceivedCallback(address, (void*) responseData, length, &sentLength);
+                    OIC_LOG(ERROR, TAG, "out of memory");
+                    (*env)->ReleaseByteArrayElements(env, jbuf, buf, 0);
+                    (*env)->DeleteLocalRef(env, jbuf);
+                    (*env)->ReleaseStringUTFChars(env, jni_str_address, address);
+                    (*env)->DeleteLocalRef(env, jni_str_address);
+                    goto exit;
                 }
-                break;
+                deviceInfo->recvData = newBuf;
+            }
+        }
+
+        if (deviceInfo->totalDataLen == deviceInfo->recvDataLen)
+        {
+            if ((*env)->ExceptionCheck(env))
+            {
+                OIC_LOG(ERROR, TAG, "read Error!!!");
+                (*env)->ExceptionDescribe(env);
+                (*env)->ExceptionClear(env);
 
-            default:
-                // Should never occur
-                OIC_LOG(ERROR, TAG, "Invalid server type");
-                return CA_STATUS_FAILED;
+                // update state to disconnect
+                // the socket will be close next read thread routine
+                ca_mutex_lock(g_mutexStateList);
+                CAEDRUpdateDeviceState(STATE_DISCONNECTED, address);
+                ca_mutex_unlock(g_mutexStateList);
+
+                (*env)->ReleaseByteArrayElements(env, jbuf, buf, 0);
+                (*env)->DeleteLocalRef(env, jbuf);
+                (*env)->ReleaseStringUTFChars(env, jni_str_address, address);
+                (*env)->DeleteLocalRef(env, jni_str_address);
+                goto exit;
+            }
+
+            if (g_edrPacketReceivedCallback)
+            {
+                OIC_LOG_V(DEBUG, TAG,"data will be sent to callback routine: \
+                          %s, %d", deviceInfo->recvData, deviceInfo->recvDataLen);
+
+                uint32_t sentLength = 0;
+                g_edrPacketReceivedCallback(address, (void*) deviceInfo->recvData,
+                                            deviceInfo->recvDataLen, &sentLength);
+
+                OICFree(deviceInfo->recvData);
+                deviceInfo->recvData = NULL;
+                deviceInfo->recvDataLen = 0;
+                deviceInfo->totalDataLen = 0;
+            }
         }
         (*env)->ReleaseByteArrayElements(env, jbuf, buf, 0);
-        (*env)->ReleaseStringUTFChars(env, jni_str_address, address);
-
-        (*env)->DeleteLocalRef(env, jni_cid_InputStream);
         (*env)->DeleteLocalRef(env, jbuf);
-        (*env)->DeleteLocalRef(env, jni_obj_inputStream);
-        (*env)->DeleteLocalRef(env, jni_cid_BTsocket);
+        (*env)->ReleaseStringUTFChars(env, jni_str_address, address);
         (*env)->DeleteLocalRef(env, jni_str_address);
     }
-    else
-    {
-        (*env)->ExceptionDescribe(env);
-        (*env)->ExceptionClear(env);
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btReadData: env error!!");
-        return CA_STATUS_FAILED;
-    }
+    (*env)->DeleteLocalRef(env, jni_cid_InputStream);
+    (*env)->DeleteLocalRef(env, jni_obj_inputStream);
+    (*env)->DeleteLocalRef(env, jni_cid_BTsocket);
 
     return CA_STATUS_OK;
+
+exit:
+    (*env)->DeleteLocalRef(env, jni_cid_InputStream);
+    (*env)->DeleteLocalRef(env, jni_obj_inputStream);
+    (*env)->DeleteLocalRef(env, jni_cid_BTsocket);
+
+    return CA_STATUS_FAILED;
 }
 
 jboolean CAEDRIsConnectedForSocket(JNIEnv *env, jobject socket)
 {
-    OIC_LOG(DEBUG, TAG, "[EDR][Native] CAEDRIsConnectedForSocket...");
-
-    if (!CAEDRNativeIsEnableBTAdapter(env))
-    {
-        OIC_LOG(ERROR, TAG, "BT adpater is not enable");
-        return JNI_FALSE;
-    }
-
     if (!socket)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] CAEDRIsConnectedForSocket - socket is null");
+        OIC_LOG(ERROR, TAG, "socket is null");
         return JNI_FALSE;
     }
 
     jclass jni_cid_BTsocket = (*env)->FindClass(env, "android/bluetooth/BluetoothSocket");
     if (!jni_cid_BTsocket)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] CAEDRIsConnectedForSocket - jni_cid_BTsocket is null");
+        OIC_LOG(ERROR, TAG, "jni_cid_BTsocket is null");
         return JNI_FALSE;
     }
 
@@ -915,10 +890,8 @@ jboolean CAEDRIsConnectedForSocket(JNIEnv *env, jobject socket)
                                                         "()Z");
     if (!jni_mid_isConnected)
     {
+        OIC_LOG(ERROR, TAG, "jni_mid_isConnected is null.");
         (*env)->DeleteLocalRef(env, jni_cid_BTsocket);
-
-        OIC_LOG(ERROR, TAG, "[EDR][Native] CAEDRIsConnectedForSocket \
-                - jni_mid_isConnected is null.");
         return JNI_FALSE;
     }
 
@@ -934,7 +907,7 @@ void CANativeStartListenTask(JNIEnv *env)
     jobject jni_obj_BTServerSocket = CAEDRNativeListen(env);
     if (!jni_obj_BTServerSocket)
     {
-        OIC_LOG(ERROR, TAG, "[EDR] AcceptThread: jni_obj_BTServerSocket is null");
+        OIC_LOG(ERROR, TAG, "jni_obj_BTServerSocket is null");
         return;
     }
 
@@ -945,18 +918,18 @@ void CANativeStartListenTask(JNIEnv *env)
 
 jobject CAEDRNativeListen(JNIEnv *env)
 {
+    OIC_LOG(DEBUG, TAG, "CAEDRNativeListen - IN");
+
     if (!CAEDRNativeIsEnableBTAdapter(env))
     {
-        OIC_LOG(ERROR, TAG, "BT adpater is not enable");
+        OIC_LOG(INFO, TAG, "BT adapter is not enabled");
         return NULL;
     }
 
-    OIC_LOG(DEBUG, TAG, "[EDR][Native] btListen");
-
     jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
     if (!jni_cid_BTAdapter)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_cid_BTAdapter is null");
+        OIC_LOG(ERROR, TAG, "jni_cid_BTAdapter is null");
         return NULL;
     }
 
@@ -966,7 +939,7 @@ jobject CAEDRNativeListen(JNIEnv *env)
                                                                     METHODID_OBJECTNONPARAM);
     if (!jni_mid_getDefaultAdapter)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_mid_getDefaultAdapter is null");
+        OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null");
         return NULL;
     }
 
@@ -974,7 +947,7 @@ jobject CAEDRNativeListen(JNIEnv *env)
                                                                jni_mid_getDefaultAdapter);
     if (!jni_obj_BTAdapter)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_obj_BTAdapter is null");
+        OIC_LOG(ERROR, TAG, "jni_obj_BTAdapter is null");
         return NULL;
     }
 
@@ -984,7 +957,7 @@ jobject CAEDRNativeListen(JNIEnv *env)
             "(Ljava/lang/String;Ljava/util/UUID;)Landroid/bluetooth/BluetoothServerSocket;");
     if (!jni_mid_listen)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_mid_listen is null");
+        OIC_LOG(ERROR, TAG, "jni_mid_listen is null");
         return NULL;
     }
     // listenUsingInsecureRfcommWithServiceRecord  / listenUsingRfcommWithServiceRecord
@@ -992,7 +965,7 @@ jobject CAEDRNativeListen(JNIEnv *env)
     jclass jni_cid_uuid = (*env)->FindClass(env, CLASSPATH_BT_UUID);
     if (!jni_cid_uuid)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_mid_listen is null");
+        OIC_LOG(ERROR, TAG, "jni_mid_listen is null");
         return NULL;
     }
 
@@ -1000,21 +973,21 @@ jobject CAEDRNativeListen(JNIEnv *env)
             env, jni_cid_uuid, "fromString", "(Ljava/lang/String;)Ljava/util/UUID;");
     if (!jni_mid_fromString)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_mid_fromString is null");
+        OIC_LOG(ERROR, TAG, "jni_mid_fromString is null");
         return NULL;
     }
 
     jstring jni_uuid = (*env)->NewStringUTF(env, OIC_EDR_SERVICE_ID);
     if (!jni_uuid)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_uuid is null");
+        OIC_LOG(ERROR, TAG, "jni_uuid is null");
         return NULL;
     }
     jobject jni_obj_uuid = (*env)->CallStaticObjectMethod(env, jni_cid_uuid, jni_mid_fromString,
                                                           jni_uuid);
     if (!jni_obj_uuid)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_obj_uuid is null");
+        OIC_LOG(ERROR, TAG, "jni_obj_uuid is null");
         return NULL;
     }
 
@@ -1022,31 +995,35 @@ jobject CAEDRNativeListen(JNIEnv *env)
     jstring jni_name = (*env)->NewStringUTF(env, "BluetoothTestSecure");
     if (!jni_name)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_name is null");
+        OIC_LOG(ERROR, TAG, "jni_name is null");
         return NULL;
     }
     jobject jni_obj_BTServerSocket = (*env)->CallObjectMethod(env, jni_obj_BTAdapter, jni_mid_listen,
                                                              jni_name, jni_obj_uuid);
     if (!jni_obj_BTServerSocket)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_obj_BTServerSocket is null");
+        OIC_LOG(ERROR, TAG, "jni_obj_BTServerSocket is null");
         return NULL;
     }
 
     g_serverSocketObject = (*env)->NewGlobalRef(env, jni_obj_BTServerSocket);
 
+    OIC_LOG(DEBUG, TAG, "CAEDRNativeListen - OUT");
+
     return jni_obj_BTServerSocket;
 }
 
 void CAEDRNativeAccept(JNIEnv *env, jobject serverSocketObject)
 {
+    OIC_LOG(DEBUG, TAG, "CAEDRNativeAccept - IN");
+
     if (NULL != serverSocketObject)
     {
         jclass jni_cid_BTServerSocket = (*env)->FindClass(
                 env, "android/bluetooth/BluetoothServerSocket");
         if (!jni_cid_BTServerSocket)
         {
-            OIC_LOG(ERROR, TAG, "[EDR][Native] btAccept: jni_cid_BTServerSocket is null");
+            OIC_LOG(ERROR, TAG, "jni_cid_BTServerSocket is null");
             return;
         }
 
@@ -1054,21 +1031,21 @@ void CAEDRNativeAccept(JNIEnv *env, jobject serverSocketObject)
                                                        "()Landroid/bluetooth/BluetoothSocket;");
         if (!jni_mid_accept)
         {
-            OIC_LOG(ERROR, TAG, "[EDR][Native] btAccept: jni_mid_accept is null");
+            OIC_LOG(ERROR, TAG, "jni_mid_accept is null");
             return;
         }
 
-        OIC_LOG(DEBUG, TAG, "[EDR][Native] btAccept: initiating accept...");
+        OIC_LOG(DEBUG, TAG, "initiating accept...");
 
         jobject jni_obj_BTSocket = (*env)->CallObjectMethod(env, serverSocketObject,
                                                             jni_mid_accept);
         if (!jni_obj_BTSocket)
         {
-            OIC_LOG(ERROR, TAG, "[EDR][Native] btAccept: jni_obj_BTSocket is null");
+            OIC_LOG(ERROR, TAG, "jni_obj_BTSocket is null");
 
             if ((*env)->ExceptionCheck(env))
             {
-                OIC_LOG(ERROR, TAG, "[EDR][Native] btAccept: socket might closed or timeout!!!");
+                OIC_LOG(ERROR, TAG, "socket might closed or timeout!!!");
                 (*env)->ExceptionDescribe(env);
                 (*env)->ExceptionClear(env);
                 return;
@@ -1079,12 +1056,12 @@ void CAEDRNativeAccept(JNIEnv *env, jobject serverSocketObject)
         jstring j_str_address = CAEDRNativeGetAddressFromDeviceSocket(env, jni_obj_BTSocket);
         if (!j_str_address)
         {
-            OIC_LOG(ERROR, TAG, "[EDR][Native] btAccept: j_str_address is null");
+            OIC_LOG(ERROR, TAG, "j_str_address is null");
             return;
         }
 
         const char* address = (*env)->GetStringUTFChars(env, j_str_address, NULL);
-        OIC_LOG_V(DEBUG, TAG, "[EDR][Native] btAccept: address is %s", address);
+        OIC_LOG_V(DEBUG, TAG, "address is %s", address);
 
         // set socket to list
         jobject jni_socket = (*env)->NewGlobalRef(env, jni_obj_BTSocket);
@@ -1092,18 +1069,22 @@ void CAEDRNativeAccept(JNIEnv *env, jobject serverSocketObject)
         CAEDRNativeAddDeviceSocketToList(env, jni_socket);
         ca_mutex_unlock(g_mutexObjectList);
 
-        OIC_LOG(DEBUG, TAG, "[EDR][Native] btAccept: Accepted!!");
+        OIC_LOG(DEBUG, TAG, "Accepted!!");
 
         // update state
         ca_mutex_lock(g_mutexStateList);
         CAEDRUpdateDeviceState(STATE_CONNECTED, address);
         ca_mutex_unlock(g_mutexStateList);
+
         (*env)->ReleaseStringUTFChars(env, j_str_address, address);
+        (*env)->DeleteLocalRef(env, j_str_address);
     }
     else
     {
-        OIC_LOG(DEBUG, TAG, "[EDR][Native] btAccept: serverSocket is close previously");
+        OIC_LOG(DEBUG, TAG, "serverSocket is close previously");
     }
+
+    OIC_LOG(DEBUG, TAG, "CAEDRNativeAccept - OUT");
 }
 
 /**
@@ -1111,38 +1092,28 @@ void CAEDRNativeAccept(JNIEnv *env, jobject serverSocketObject)
  */
 void CAEDRNatvieCloseServerTask(JNIEnv* env)
 {
-    if (g_inputStream)
-    {
-        OIC_LOG(DEBUG, TAG, "InputStream will be close");
-        jclass jni_cid_InputStream = (*env)->FindClass(env, "java/io/InputStream");
-        jmethodID jni_mid_close = (*env)->GetMethodID(env, jni_cid_InputStream, "close", "()V");
-        (*env)->CallVoidMethod(env, g_inputStream, jni_mid_close);
-        (*env)->DeleteGlobalRef(env, g_inputStream);
-        g_inputStream = NULL;
-    }
-
     if (g_serverSocket)
     {
-        OIC_LOG(DEBUG, TAG, "[EDR][Native] Accept Resource will be close");
+        OIC_LOG(DEBUG, TAG, "Accept Resource will be close");
 
         jclass jni_cid_BTServerSocket = (*env)->FindClass(
                 env, "android/bluetooth/BluetoothServerSocket");
         if (!jni_cid_BTServerSocket)
         {
-            OIC_LOG(ERROR, TAG, "[EDR][Native] jni_cid_BTServerSocket is null");
+            OIC_LOG(ERROR, TAG, "jni_cid_BTServerSocket is null");
             return;
         }
 
         jmethodID jni_mid_accept = (*env)->GetMethodID(env, jni_cid_BTServerSocket, "close", "()V");
         if (!jni_mid_accept)
         {
-            OIC_LOG(ERROR, TAG, "[EDR][Native] jni_mid_accept is null");
+            OIC_LOG(ERROR, TAG, "jni_mid_accept is null");
             return;
         }
         (*env)->CallVoidMethod(env, g_serverSocket, jni_mid_accept);
         (*env)->DeleteGlobalRef(env, g_serverSocket);
         g_serverSocket = NULL;
 
-        OIC_LOG(DEBUG, TAG, "[EDR][Native] close accept obj");
+        OIC_LOG(DEBUG, TAG, "close accept obj");
     }
 }
index 5324d80..43edafa 100644 (file)
@@ -44,15 +44,10 @@ typedef void (*CAPacketReceiveCallback)(const char *address, const char *data);
 void CAEDRServerJniInit();
 
 /**
- * Initialize server for EDR.
- * @param[in]   handle           thread pool handle object.
- */
-void CAEDRServerInitialize(ca_thread_pool_t handle);
-
-/**
  * Start Accept Thread.
+ * @return ::CA_STATUS_OK or Appropriate error code.
  */
-void CAEDRServerStartAcceptThread();
+CAResult_t CAEDRServerStartAcceptThread();
 
 /**
  * Start unicast server.
@@ -83,10 +78,9 @@ CAResult_t CAEDRStopMulticastServer();
  * This function will read the data from remote device.
  * @param[in]  env              JNI interface pointer.
  * @param[in]  id               index of remote address.
- * @param[in]  type             EDR server type.
  * @return ::CA_STATUS_OK or Appropriate error code.
  */
-CAResult_t CAEDRNativeReadData(JNIEnv *env, uint32_t id, CAAdapterServerType_t type);
+CAResult_t CAEDRNativeReadData(JNIEnv *env, uint32_t id);
 
 /**
  * Start Listen Task.
index 154ef47..5b682c7 100644 (file)
@@ -29,7 +29,7 @@
 #include "uarraylist.h"
 
 #define ERROR_CODE (-1)
-#define TAG PCF("CA_EDR_UTILS")
+#define TAG PCF("OIC_CA_EDR_UTILS")
 
 static const char METHODID_OBJECTNONPARAM[] = "()Landroid/bluetooth/BluetoothAdapter;";
 static const char METHODID_STRINGNONPARAM[] = "()Ljava/lang/String;";
@@ -45,14 +45,14 @@ jstring CAEDRNativeGetAddressFromDeviceSocket(JNIEnv *env, jobject bluetoothSock
 {
     if (!bluetoothSocketObj)
     {
-        OIC_LOG(ERROR, TAG, "[EDR] getRemoteAddress: bluetoothSocketObj is null");
+        OIC_LOG(ERROR, TAG, "bluetoothSocketObj is null");
         return NULL;
     }
 
     jclass jni_cid_BTSocket = (*env)->FindClass(env, CLASSPATH_BT_SOCKET);
     if (!jni_cid_BTSocket)
     {
-        OIC_LOG(ERROR, TAG, "[EDR] getRemoteAddress: jni_cid_BTSocket is null");
+        OIC_LOG(ERROR, TAG, "jni_cid_BTSocket is null");
         return NULL;
     }
 
@@ -60,9 +60,8 @@ jstring CAEDRNativeGetAddressFromDeviceSocket(JNIEnv *env, jobject bluetoothSock
             env, jni_cid_BTSocket, "getRemoteDevice", "()Landroid/bluetooth/BluetoothDevice;");
     if (!jni_mid_getRemoteDevice)
     {
+        OIC_LOG(ERROR, TAG, "jni_mid_getRemoteDevice is null");
         (*env)->DeleteLocalRef(env, jni_cid_BTSocket);
-
-        OIC_LOG(ERROR, TAG, "[EDR] getRemoteAddress: jni_mid_getRemoteDevice is null");
         return NULL;
     }
 
@@ -70,41 +69,37 @@ jstring CAEDRNativeGetAddressFromDeviceSocket(JNIEnv *env, jobject bluetoothSock
                                                               jni_mid_getRemoteDevice);
     if (!jni_obj_remoteBTDevice)
     {
+        OIC_LOG(ERROR, TAG, "jni_obj_remoteBTDevice is null");
         (*env)->DeleteLocalRef(env, jni_cid_BTSocket);
-
-        OIC_LOG(ERROR, TAG, "[EDR] getRemoteAddress: jni_obj_remoteBTDevice is null");
         return NULL;
     }
 
     jclass jni_cid_BTDevice = (*env)->FindClass(env, CLASSPATH_BT_DEVICE);
     if (!jni_cid_BTDevice)
     {
+        OIC_LOG(ERROR, TAG, "jni_cid_BTDevice is null");
         (*env)->DeleteLocalRef(env, jni_obj_remoteBTDevice);
         (*env)->DeleteLocalRef(env, jni_cid_BTSocket);
-
-        OIC_LOG(ERROR, TAG, "[EDR] getRemoteAddress: jni_cid_BTDevice is null");
         return NULL;
     }
     jmethodID j_mid_getAddress = (*env)->GetMethodID(env, jni_cid_BTDevice, "getAddress",
                                                      METHODID_STRINGNONPARAM);
     if (!j_mid_getAddress)
     {
+        OIC_LOG(ERROR, TAG, "j_mid_getAddress is null");
         (*env)->DeleteLocalRef(env, jni_obj_remoteBTDevice);
         (*env)->DeleteLocalRef(env, jni_cid_BTDevice);
         (*env)->DeleteLocalRef(env, jni_cid_BTSocket);
-
-        OIC_LOG(ERROR, TAG, "[EDR] getRemoteAddress: j_mid_getAddress is null");
         return NULL;
     }
 
     jstring j_str_address = (*env)->CallObjectMethod(env, jni_obj_remoteBTDevice, j_mid_getAddress);
     if (!j_str_address)
     {
+        OIC_LOG(ERROR, TAG, "j_str_address is null");
         (*env)->DeleteLocalRef(env, jni_obj_remoteBTDevice);
         (*env)->DeleteLocalRef(env, jni_cid_BTDevice);
         (*env)->DeleteLocalRef(env, jni_cid_BTSocket);
-
-        OIC_LOG(ERROR, TAG, "[EDR] getRemoteAddress: j_str_address is null");
         return NULL;
     }
 
@@ -120,7 +115,7 @@ jstring CAEDRNativeGetLocalDeviceAddress(JNIEnv* env)
     jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
     if (!jni_cid_BTAdapter)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] getAddress: jni_cid_BTAdapter is null");
+        OIC_LOG(ERROR, TAG, "jni_cid_BTAdapter is null");
         return NULL;
     }
 
@@ -129,9 +124,8 @@ jstring CAEDRNativeGetLocalDeviceAddress(JNIEnv* env)
                                                                     METHODID_OBJECTNONPARAM);
     if (!jni_mid_getDefaultAdapter)
     {
+        OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null");
         (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
-
-        OIC_LOG(ERROR, TAG, "[EDR][Native] getAddress: jni_mid_getDefaultAdapter is null");
         return NULL;
     }
 
@@ -139,9 +133,8 @@ jstring CAEDRNativeGetLocalDeviceAddress(JNIEnv* env)
                                                        METHODID_STRINGNONPARAM);
     if (!jni_mid_getAddress)
     {
+        OIC_LOG(ERROR, TAG, "jni_mid_getAddress is null");
         (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
-
-        OIC_LOG(ERROR, TAG, "[EDR][Native] getAddress: jni_mid_getAddress is null");
         return NULL;
     }
 
@@ -149,9 +142,8 @@ jstring CAEDRNativeGetLocalDeviceAddress(JNIEnv* env)
                                                                jni_mid_getDefaultAdapter);
     if (!jni_obj_BTAdapter)
     {
+        OIC_LOG(ERROR, TAG, "jni_obj_BTAdapter is null");
         (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
-
-        OIC_LOG(ERROR, TAG, "[EDR][Native] getAddress: jni_obj_BTAdapter is null");
         return NULL;
     }
 
@@ -159,10 +151,9 @@ jstring CAEDRNativeGetLocalDeviceAddress(JNIEnv* env)
                                                                 jni_mid_getAddress);
     if (!jni_str_address)
     {
+        OIC_LOG(ERROR, TAG, "jni_str_address is null");
         (*env)->DeleteLocalRef(env, jni_obj_BTAdapter);
         (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
-
-        OIC_LOG(ERROR, TAG, "[EDR][Native] getAddress: jni_str_address is null");
         return NULL;
     }
 
@@ -177,7 +168,7 @@ jobjectArray CAEDRNativeGetBondedDevices(JNIEnv *env)
     jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
     if (!jni_cid_BTAdapter)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] getBondedDevices: jni_cid_BTAdapter is null");
+        OIC_LOG(ERROR, TAG, "jni_cid_BTAdapter is null");
         return NULL;
     }
 
@@ -186,9 +177,8 @@ jobjectArray CAEDRNativeGetBondedDevices(JNIEnv *env)
                                                                     METHODID_OBJECTNONPARAM);
     if (!jni_mid_getDefaultAdapter)
     {
+        OIC_LOG(ERROR, TAG, "default adapter is null");
         (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
-
-        OIC_LOG(ERROR, TAG, "[EDR][Native] getBondedDevices: default adapter is null");
         return NULL;
     }
 
@@ -196,9 +186,8 @@ jobjectArray CAEDRNativeGetBondedDevices(JNIEnv *env)
                                                                jni_mid_getDefaultAdapter);
     if (!jni_obj_BTAdapter)
     {
+        OIC_LOG(ERROR, TAG, "bluetooth adapter is null");
         (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
-
-        OIC_LOG(ERROR, TAG, "[EDR][Native] getBondedDevices: bluetooth adapter is null");
         return NULL;
     }
 
@@ -208,10 +197,9 @@ jobjectArray CAEDRNativeGetBondedDevices(JNIEnv *env)
                                                              "()Ljava/util/Set;");
     if (!jni_mid_getBondedDevices)
     {
+        OIC_LOG(ERROR, TAG, "jni_mid_getBondedDevicesr is null");
         (*env)->DeleteLocalRef(env, jni_obj_BTAdapter);
         (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
-
-        OIC_LOG(ERROR, TAG, "[EDR][Native] getBondedDevices: jni_mid_getBondedDevicesr is null");
         return NULL;
     }
 
@@ -219,10 +207,9 @@ jobjectArray CAEDRNativeGetBondedDevices(JNIEnv *env)
                                                                 jni_mid_getBondedDevices);
     if (!jni_obj_setPairedDevices)
     {
+        OIC_LOG(ERROR, TAG, "ni_obj_setPairedDevices is null");
         (*env)->DeleteLocalRef(env, jni_obj_BTAdapter);
         (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
-
-        OIC_LOG(ERROR, TAG, "[EDR][Native] getBondedDevices: jni_obj_setPairedDevices is null");
         return NULL;
     }
 
@@ -231,36 +218,24 @@ jobjectArray CAEDRNativeGetBondedDevices(JNIEnv *env)
     jclass jni_cid_Set = (*env)->FindClass(env, "java/util/Set");
     if (!jni_cid_Set)
     {
-        (*env)->DeleteLocalRef(env, jni_obj_BTAdapter);
-        (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
-        (*env)->DeleteLocalRef(env, jni_obj_setPairedDevices);
-
-        OIC_LOG(ERROR, TAG, "[EDR][Native] getBondedDevices: jni_cid_Set is null");
-        return NULL;
+        OIC_LOG(ERROR, TAG, "jni_cid_Set is null");
+        goto exit;
     }
     jmethodID jni_mid_toArray = (*env)->GetMethodID(env, jni_cid_Set, "toArray",
                                                     "()[Ljava/lang/Object;");
 
     if (!jni_mid_toArray)
     {
-        (*env)->DeleteLocalRef(env, jni_obj_BTAdapter);
-        (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
-        (*env)->DeleteLocalRef(env, jni_obj_setPairedDevices);
-
-        OIC_LOG(ERROR, TAG, "[EDR][Native] getBondedDevices: jni_mid_toArray is null");
-        return NULL;
+        OIC_LOG(ERROR, TAG, "jni_mid_toArray is null");
+        goto exit;
     }
 
     jobjectArray jni_arrayPairedDevices = (jobjectArray)(
             (*env)->CallObjectMethod(env, jni_obj_setPairedDevices, jni_mid_toArray));
     if (!jni_arrayPairedDevices)
     {
-        (*env)->DeleteLocalRef(env, jni_obj_BTAdapter);
-        (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
-        (*env)->DeleteLocalRef(env, jni_obj_setPairedDevices);
-
-        OIC_LOG(ERROR, TAG, "[EDR][Native] getBondedDevices: jni_arrayPairedDevices is null");
-        return NULL;
+        OIC_LOG(ERROR, TAG, "jni_arrayPairedDevices is null");
+        goto exit;
     }
 
     (*env)->DeleteLocalRef(env, jni_obj_BTAdapter);
@@ -268,6 +243,12 @@ jobjectArray CAEDRNativeGetBondedDevices(JNIEnv *env)
     (*env)->DeleteLocalRef(env, jni_obj_setPairedDevices);
 
     return jni_arrayPairedDevices;
+
+exit:
+    (*env)->DeleteLocalRef(env, jni_obj_BTAdapter);
+    (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
+    (*env)->DeleteLocalRef(env, jni_obj_setPairedDevices);
+    return NULL;
 }
 
 jint CAEDRNativeGetBTStateOnInfo(JNIEnv *env)
@@ -275,7 +256,7 @@ jint CAEDRNativeGetBTStateOnInfo(JNIEnv *env)
     jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
     if (!jni_cid_BTAdapter)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] getBTStateOnInfo: jni_cid_BTAdapter is null");
+        OIC_LOG(ERROR, TAG, "jni_cid_BTAdapter is null");
         return ERROR_CODE;
     }
 
@@ -284,12 +265,12 @@ jint CAEDRNativeGetBTStateOnInfo(JNIEnv *env)
     {
         (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
 
-        OIC_LOG(ERROR, TAG, "[EDR][Native] get_field_state is 0");
+        OIC_LOG(ERROR, TAG, "get_field_state is 0");
         return ERROR_CODE;
     }
     jint jni_int_val = (*env)->GetStaticIntField(env, jni_cid_BTAdapter, jni_fid_stateon);
 
-    OIC_LOG_V(DEBUG, TAG, "[EDR][Native] bluetooth state integer value : %d", jni_int_val);
+    OIC_LOG_V(DEBUG, TAG, "bluetooth state integer value : %d", jni_int_val);
 
     (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
 
@@ -301,7 +282,7 @@ jboolean CAEDRNativeIsEnableBTAdapter(JNIEnv *env)
     jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
     if (!jni_cid_BTAdapter)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] jni_cid_BTAdapter: jni_cid_BTAdapter is null");
+        OIC_LOG(ERROR, TAG, "jni_cid_BTAdapter: jni_cid_BTAdapter is null");
         return JNI_FALSE;
     }
 
@@ -310,9 +291,8 @@ jboolean CAEDRNativeIsEnableBTAdapter(JNIEnv *env)
                                                                     METHODID_OBJECTNONPARAM);
     if (!jni_mid_getDefaultAdapter)
     {
+        OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null");
         (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
-
-        OIC_LOG(ERROR, TAG, "[EDR][Native] jni_mid_getDefaultAdapter is null");
         return JNI_FALSE;
     }
 
@@ -320,9 +300,8 @@ jboolean CAEDRNativeIsEnableBTAdapter(JNIEnv *env)
                                                                jni_mid_getDefaultAdapter);
     if (!jni_obj_BTAdapter)
     {
+        OIC_LOG(ERROR, TAG, "jni_obj_BTAdapter is null");
         (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
-
-        OIC_LOG(ERROR, TAG, "[EDR][Native] jni_obj_BTAdapter is null");
         return JNI_FALSE;
     }
 
@@ -330,15 +309,13 @@ jboolean CAEDRNativeIsEnableBTAdapter(JNIEnv *env)
     jmethodID jni_mid_isEnable = (*env)->GetMethodID(env, jni_cid_BTAdapter, "isEnabled", "()Z");
     if (!jni_mid_isEnable)
     {
+        OIC_LOG(ERROR, TAG, "jni_mid_isEnable is null");
         (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
         (*env)->DeleteLocalRef(env, jni_obj_BTAdapter);
-
-        OIC_LOG(ERROR, TAG, "[EDR][Native] jni_mid_isEnable is null");
         return JNI_FALSE;
     }
 
     jboolean jni_isEnable = (*env)->CallBooleanMethod(env, jni_obj_BTAdapter, jni_mid_isEnable);
-    OIC_LOG_V(DEBUG, TAG, "[EDR][Native] adapter state is %d", jni_isEnable);
 
     (*env)->DeleteLocalRef(env, jni_obj_BTAdapter);
     (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
@@ -350,13 +327,13 @@ jstring CAEDRNativeGetAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice)
 {
     if (!bluetoothDevice)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] bluetoothDevice is null");
+        OIC_LOG(ERROR, TAG, "bluetoothDevice is null");
         return NULL;
     }
     jclass jni_cid_device_list = (*env)->FindClass(env, "android/bluetooth/BluetoothDevice");
     if (!jni_cid_device_list)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] jni_cid_device_list is null");
+        OIC_LOG(ERROR, TAG, "jni_cid_device_list is null");
         return NULL;
     }
 
@@ -364,7 +341,7 @@ jstring CAEDRNativeGetAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice)
                                                        METHODID_STRINGNONPARAM);
     if (!jni_mid_getAddress)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] jni_mid_getAddress is null");
+        OIC_LOG(ERROR, TAG, "jni_mid_getAddress is null");
         return NULL;
     }
 
@@ -372,7 +349,7 @@ jstring CAEDRNativeGetAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice)
                                                             jni_mid_getAddress);
     if (!jni_address)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] jni_address is null");
+        OIC_LOG(ERROR, TAG, "jni_address is null");
         return NULL;
     }
     return jni_address;
@@ -383,7 +360,7 @@ jstring CAEDRNativeGetAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice)
  */
 void CAEDRNativeCreateDeviceStateList()
 {
-    OIC_LOG(DEBUG, TAG, "[EDR][Native] CAEDRNativeCreateDeviceStateList");
+    OIC_LOG(DEBUG, TAG, "CAEDRNativeCreateDeviceStateList");
 
     // create new object array
     if (NULL == g_deviceStateList)
@@ -398,72 +375,69 @@ void CAEDRUpdateDeviceState(CAConnectedState_t state, const char *address)
 {
     if (!address)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] address is null");
+        OIC_LOG(ERROR, TAG, "address is null");
         return;
     }
-    state_t *newstate = (state_t*) OICCalloc(1, sizeof(state_t));
-    if (!newstate)
+    CAConnectedDeviceInfo_t *deviceInfo =
+            (CAConnectedDeviceInfo_t *) OICCalloc(1, sizeof(CAConnectedDeviceInfo_t));
+    if (!deviceInfo)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] newstate is null");
+        OIC_LOG(ERROR, TAG, "deviceInfo is null");
         return;
     }
-    OICStrcpy((char*) newstate->address, sizeof(newstate->address), address);
-    newstate->state = state;
+    OICStrcpy((char*) deviceInfo->address, sizeof(deviceInfo->address), address);
+    deviceInfo->state = state;
 
-    CAEDRNativeAddDeviceStateToList(newstate);
+    CAEDRNativeAddDeviceStateToList(deviceInfo);
 }
 
-void CAEDRNativeAddDeviceStateToList(state_t *state)
+void CAEDRNativeAddDeviceStateToList(CAConnectedDeviceInfo_t *deviceInfo)
 {
-    if (!state)
+    if (!deviceInfo)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] device is null");
+        OIC_LOG(ERROR, TAG, "device is null");
         return;
     }
 
     if (!g_deviceStateList)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] gdevice_list is null");
+        OIC_LOG(ERROR, TAG, "gdevice_list is null");
         return;
     }
 
-    if (CAEDRNativeIsDeviceInList((const char*) state->address))
+    if (CAEDRNativeIsDeviceInList((const char*) deviceInfo->address))
     {
         // delete previous state for update new state
-        CAEDRNativeRemoveDevice((const char*) state->address);
+        CAEDRNativeRemoveDevice((const char*) deviceInfo->address);
     }
-    u_arraylist_add(g_deviceStateList, state); // update new state
-    OIC_LOG_V(DEBUG, TAG, "Set State Info to List : %d", state->state);
+    u_arraylist_add(g_deviceStateList, deviceInfo); // update new state
+    OIC_LOG_V(DEBUG, TAG, "Set State Info to List : %d", deviceInfo->state);
 }
 
 bool CAEDRNativeIsDeviceInList(const char* remoteAddress)
 {
-
     if (!remoteAddress)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] remoteAddress is null");
+        OIC_LOG(ERROR, TAG, "remoteAddress is null");
         return false;
     }
-    jint index;
+
     jint length = u_arraylist_length(g_deviceStateList);
-    for (index = 0; index < length; index++)
+    for (jint index = 0; index < length; index++)
     {
-        state_t* state = (state_t*) u_arraylist_get(g_deviceStateList, index);
-        if (!state)
+        CAConnectedDeviceInfo_t* deviceInfo =
+                (CAConnectedDeviceInfo_t*) u_arraylist_get(g_deviceStateList, index);
+        if (!deviceInfo)
         {
-            OIC_LOG(ERROR, TAG, "[EDR][Native] state_t object is null");
+            OIC_LOG(ERROR, TAG, "deviceInfo object is null");
             return false;
         }
 
-        if (!strcmp(remoteAddress, (const char*) state->address))
+        if (!strcmp(remoteAddress, (const char*) deviceInfo->address))
         {
             OIC_LOG(DEBUG, TAG, "the device is already set");
             return true;
         }
-        else
-        {
-            continue;
-        }
     }
 
     OIC_LOG(DEBUG, TAG, "there are no the device in list.");
@@ -476,7 +450,7 @@ void CAEDRNativeRemoveAllDeviceState()
 
     if (!g_deviceStateList)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceStateList is null");
+        OIC_LOG(ERROR, TAG, "gdeviceStateList is null");
         return;
     }
 
@@ -484,13 +458,14 @@ void CAEDRNativeRemoveAllDeviceState()
     jint length = u_arraylist_length(g_deviceStateList);
     for (index = 0; index < length; index++)
     {
-        state_t* state = (state_t*) u_arraylist_get(g_deviceStateList, index);
-        if (!state)
+        CAConnectedDeviceInfo_t* deviceInfo =
+                (CAConnectedDeviceInfo_t*) u_arraylist_get(g_deviceStateList, index);
+        if (!deviceInfo)
         {
-            OIC_LOG(DEBUG, TAG, "[EDR][Native] jarrayObj is null");
+            OIC_LOG(DEBUG, TAG, "jarrayObj is null");
             continue;
         }
-        OICFree(state);
+        OICFree(deviceInfo);
     }
 
     OICFree(g_deviceStateList);
@@ -504,30 +479,30 @@ void CAEDRNativeRemoveDevice(const char *remoteAddress)
 
     if (!g_deviceStateList)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceStateList is null");
+        OIC_LOG(ERROR, TAG, "gdeviceStateList is null");
         return;
     }
     if (!remoteAddress)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] remoteAddress is null");
+        OIC_LOG(ERROR, TAG, "remoteAddress is null");
         return;
     }
 
-    jint index;
     jint length = u_arraylist_length(g_deviceStateList);
-    for (index = 0; index < length; index++)
+    for (jint index = 0; index < length; index++)
     {
-        state_t* state = (state_t*) u_arraylist_get(g_deviceStateList, index);
-        if (!state)
+        CAConnectedDeviceInfo_t* deviceInfo =
+                (CAConnectedDeviceInfo_t*) u_arraylist_get(g_deviceStateList, index);
+        if (!deviceInfo)
         {
-            OIC_LOG(DEBUG, TAG, "[EDR][Native] state_t object is null");
+            OIC_LOG(DEBUG, TAG, "deviceInfo object is null");
             continue;
         }
 
-        if (!strcmp((const char*) state->address, remoteAddress))
+        if (!strcmp((const char*) deviceInfo->address, remoteAddress))
         {
-            OIC_LOG_V(DEBUG, TAG, "[EDR][Native] remove state : %s", remoteAddress);
-            OICFree(state);
+            OIC_LOG_V(DEBUG, TAG, "remove state : %s", remoteAddress);
+            OICFree(deviceInfo);
 
             u_arraylist_remove(g_deviceStateList, index);
             break;
@@ -542,32 +517,30 @@ CAConnectedState_t CAEDRIsConnectedDevice(const char *remoteAddress)
 
     if (!remoteAddress)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] remoteAddress is null");
+        OIC_LOG(ERROR, TAG, "remoteAddress is null");
         return STATE_DISCONNECTED;
     }
 
     if (!g_deviceStateList)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceStateList is null");
+        OIC_LOG(ERROR, TAG, "gdeviceStateList is null");
         return STATE_DISCONNECTED;
     }
 
-    jint index;
     jint length = u_arraylist_length(g_deviceStateList);
-    for (index = 0; index < length; index++)
+    for (jint index = 0; index < length; index++)
     {
-        state_t* state = (state_t*) u_arraylist_get(g_deviceStateList, index);
-        if (!state)
+        CAConnectedDeviceInfo_t* deviceInfo =
+                (CAConnectedDeviceInfo_t*) u_arraylist_get(g_deviceStateList, index);
+        if (!deviceInfo)
         {
-            OIC_LOG(DEBUG, TAG, "[EDR][Native] state_t object is null");
+            OIC_LOG(DEBUG, TAG, "deviceInfo object is null");
             continue;
         }
 
-        if (!strcmp((const char*) state->address, remoteAddress))
+        if (!strcmp((const char*) deviceInfo->address, remoteAddress))
         {
-            OIC_LOG(DEBUG, TAG, "[EDR][Native] check whether it is connected or not");
-
-            return state->state;
+            return deviceInfo->state;
         }
     }
     return STATE_DISCONNECTED;
@@ -578,7 +551,7 @@ CAConnectedState_t CAEDRIsConnectedDevice(const char *remoteAddress)
  */
 void CAEDRNativeCreateDeviceSocketList()
 {
-    OIC_LOG(DEBUG, TAG, "[EDR][Native] CAEDRNativeCreateDeviceSocketList");
+    OIC_LOG(DEBUG, TAG, "CAEDRNativeCreateDeviceSocketList");
 
     // create new object array
     if (NULL == g_deviceObjectList)
@@ -591,24 +564,24 @@ void CAEDRNativeCreateDeviceSocketList()
 
 void CAEDRNativeAddDeviceSocketToList(JNIEnv *env, jobject deviceSocket)
 {
-    OIC_LOG(DEBUG, TAG, "[EDR][Native] CANativeAddDeviceobjToList");
+    OIC_LOG(DEBUG, TAG, "CANativeAddDeviceobjToList");
 
     if (!deviceSocket)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] Device is null");
+        OIC_LOG(ERROR, TAG, "Device is null");
         return;
     }
 
     if (!g_deviceObjectList)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceObjectList is null");
+        OIC_LOG(ERROR, TAG, "gdeviceObjectList is null");
         return;
     }
 
     jstring jni_remoteAddress = CAEDRNativeGetAddressFromDeviceSocket(env, deviceSocket);
     if (!jni_remoteAddress)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] jni_remoteAddress is null");
+        OIC_LOG(ERROR, TAG, "jni_remoteAddress is null");
         return;
     }
 
@@ -626,37 +599,36 @@ void CAEDRNativeAddDeviceSocketToList(JNIEnv *env, jobject deviceSocket)
 
 bool CAEDRNativeIsDeviceSocketInList(JNIEnv *env, const char* remoteAddress)
 {
-    OIC_LOG(DEBUG, TAG, "[EDR][Native] CANativeIsDeviceObjInList");
+    OIC_LOG(DEBUG, TAG, "CANativeIsDeviceObjInList");
 
     if (!remoteAddress)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] remoteAddress is null");
+        OIC_LOG(ERROR, TAG, "remoteAddress is null");
         return false;
     }
-    jint index;
+
     jint length = u_arraylist_length(g_deviceStateList);
-    for (index = 0; index < length; index++)
+    for (jint index = 0; index < length; index++)
     {
 
         jobject jarrayObj = (jobject) u_arraylist_get(g_deviceObjectList, index);
         if (!jarrayObj)
         {
-            OIC_LOG(DEBUG, TAG, "[EDR][Native] jarrayObj is null");
+            OIC_LOG(DEBUG, TAG, "jarrayObj is null");
             return false;
         }
 
         jstring jni_setAddress = CAEDRNativeGetAddressFromDeviceSocket(env, jarrayObj);
-        (*env)->DeleteLocalRef(env, jarrayObj);
         if (!jni_setAddress)
         {
-            OIC_LOG(DEBUG, TAG, "[EDR][Native] jni_setAddress is null");
+            OIC_LOG(DEBUG, TAG, "jni_setAddress is null");
             return false;
         }
 
         const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
         if (!setAddress)
         {
-            OIC_LOG(DEBUG, TAG, "[EDR][Native] setAddress is null");
+            OIC_LOG(DEBUG, TAG, "setAddress is null");
             return false;
         }
 
@@ -679,36 +651,35 @@ bool CAEDRNativeIsDeviceSocketInList(JNIEnv *env, const char* remoteAddress)
 
 void CAEDRNativeSocketCloseToAll(JNIEnv *env)
 {
-    OIC_LOG(DEBUG, TAG, "[EDR][Native] CAEDRNativeSocketCloseToAll");
+    OIC_LOG(DEBUG, TAG, "CAEDRNativeSocketCloseToAll");
 
     if (!g_deviceObjectList)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceObjectList is null");
+        OIC_LOG(ERROR, TAG, "gdeviceObjectList is null");
         return;
     }
 
     jclass jni_cid_BTSocket = (*env)->FindClass(env, CLASSPATH_BT_SOCKET);
     if (!jni_cid_BTSocket)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] close: jni_cid_BTSocket is null");
+        OIC_LOG(ERROR, TAG, "jni_cid_BTSocket is null");
         return;
     }
 
     jmethodID jni_mid_close = (*env)->GetMethodID(env, jni_cid_BTSocket, "close", "()V");
     if (!jni_mid_close)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] close: jni_mid_close is null");
+        OIC_LOG(ERROR, TAG, "jni_mid_close is null");
         return;
     }
 
-    jint index;
     jint length = u_arraylist_length(g_deviceStateList);
-    for (index = 0; index < length; index++)
+    for (jint index = 0; index < length; index++)
     {
         jobject jni_obj_socket = (jobject) u_arraylist_get(g_deviceObjectList, index);
         if (!jni_obj_socket)
         {
-            OIC_LOG(ERROR, TAG, "[EDR][Native] socket obj is null");
+            OIC_LOG(ERROR, TAG, "socket obj is null");
             return;
         }
 
@@ -716,7 +687,7 @@ void CAEDRNativeSocketCloseToAll(JNIEnv *env)
 
         if ((*env)->ExceptionCheck(env))
         {
-            OIC_LOG(ERROR, TAG, "[EDR][Native] close: close is Failed!!!");
+            OIC_LOG(ERROR, TAG, "close is Failed!!!");
             (*env)->ExceptionDescribe(env);
             (*env)->ExceptionClear(env);
             return;
@@ -730,18 +701,17 @@ void CAEDRNativeRemoveAllDeviceSocket(JNIEnv *env)
 
     if (!g_deviceObjectList)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceObjectList is null");
+        OIC_LOG(ERROR, TAG, "gdeviceObjectList is null");
         return;
     }
 
-    jint index;
     jint length = u_arraylist_length(g_deviceStateList);
-    for (index = 0; index < length; index++)
+    for (jint index = 0; index < length; index++)
     {
         jobject jarrayObj = (jobject) u_arraylist_get(g_deviceObjectList, index);
         if (!jarrayObj)
         {
-            OIC_LOG(ERROR, TAG, "[EDR][Native] jarrayObj is null");
+            OIC_LOG(ERROR, TAG, "jarrayObj is null");
             return;
         }
         (*env)->DeleteGlobalRef(env, jarrayObj);
@@ -758,32 +728,31 @@ void CAEDRNativeRemoveDeviceSocket(JNIEnv *env, jobject deviceSocket)
 
     if (!g_deviceObjectList)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceObjectList is null");
+        OIC_LOG(ERROR, TAG, "gdeviceObjectList is null");
         return;
     }
 
-    jint index;
     jint length = u_arraylist_length(g_deviceStateList);
-    for (index = 0; index < length; index++)
+    for (jint index = 0; index < length; index++)
     {
         jobject jarrayObj = (jobject) u_arraylist_get(g_deviceObjectList, index);
         if (!jarrayObj)
         {
-            OIC_LOG(DEBUG, TAG, "[EDR][Native] jarrayObj is null");
+            OIC_LOG(DEBUG, TAG, "jarrayObj is null");
             continue;
         }
 
         jstring jni_setAddress = CAEDRNativeGetAddressFromDeviceSocket(env, jarrayObj);
         if (!jni_setAddress)
         {
-            OIC_LOG(DEBUG, TAG, "[EDR][Native] jni_setAddress is null");
+            OIC_LOG(DEBUG, TAG, "jni_setAddress is null");
             continue;
         }
 
         jstring jni_remoteAddress = CAEDRNativeGetAddressFromDeviceSocket(env, deviceSocket);
         if (!jni_remoteAddress)
         {
-            OIC_LOG(DEBUG, TAG, "[EDR][Native] jni_remoteAddress is null");
+            OIC_LOG(DEBUG, TAG, "jni_remoteAddress is null");
             continue;
         }
 
@@ -792,7 +761,7 @@ void CAEDRNativeRemoveDeviceSocket(JNIEnv *env, jobject deviceSocket)
 
         if (!strcmp(setAddress, remoteAddress))
         {
-            OIC_LOG_V(DEBUG, TAG, "[EDR][Native] remove object : %s", remoteAddress);
+            OIC_LOG_V(DEBUG, TAG, "remove object : %s", remoteAddress);
             (*env)->DeleteGlobalRef(env, jarrayObj);
             (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
             (*env)->ReleaseStringUTFChars(env, jni_remoteAddress, remoteAddress);
@@ -804,7 +773,7 @@ void CAEDRNativeRemoveDeviceSocket(JNIEnv *env, jobject deviceSocket)
         (*env)->ReleaseStringUTFChars(env, jni_remoteAddress, remoteAddress);
     }
 
-    OIC_LOG(DEBUG, TAG, "[EDR][Native] there are no target object");
+    OIC_LOG(DEBUG, TAG, "there are no target object");
     return;
 }
 
@@ -814,25 +783,24 @@ void CAEDRNativeRemoveDeviceSocketBaseAddr(JNIEnv *env, jstring address)
 
     if (!g_deviceObjectList)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceObjectList is null");
+        OIC_LOG(ERROR, TAG, "gdeviceObjectList is null");
         return;
     }
 
-    jint index;
     jint length = u_arraylist_length(g_deviceStateList);
-    for (index = 0; index < length; index++)
+    for (jint index = 0; index < length; index++)
     {
         jobject jarrayObj = (jobject) u_arraylist_get(g_deviceObjectList, index);
         if (!jarrayObj)
         {
-            OIC_LOG(DEBUG, TAG, "[EDR][Native] jarrayObj is null");
+            OIC_LOG(DEBUG, TAG, "jarrayObj is null");
             continue;
         }
 
         jstring jni_setAddress = CAEDRNativeGetAddressFromDeviceSocket(env, jarrayObj);
         if (!jni_setAddress)
         {
-            OIC_LOG(ERROR, TAG, "[EDR][Native] jni_setAddress is null");
+            OIC_LOG(ERROR, TAG, "jni_setAddress is null");
             continue;
         }
         const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
@@ -840,7 +808,7 @@ void CAEDRNativeRemoveDeviceSocketBaseAddr(JNIEnv *env, jstring address)
 
         if (!strcmp(setAddress, remoteAddress))
         {
-            OIC_LOG_V(ERROR, TAG, "[EDR][Native] remove object : %s", remoteAddress);
+            OIC_LOG_V(ERROR, TAG, "remove object : %s", remoteAddress);
             (*env)->DeleteGlobalRef(env, jarrayObj);
             (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
             (*env)->ReleaseStringUTFChars(env, address, remoteAddress);
@@ -852,24 +820,22 @@ void CAEDRNativeRemoveDeviceSocketBaseAddr(JNIEnv *env, jstring address)
         (*env)->ReleaseStringUTFChars(env, address, remoteAddress);
     }
 
-    OIC_LOG(DEBUG, TAG, "[EDR][Native] there are no target object");
+    OIC_LOG(DEBUG, TAG, "there are no target object");
     return;
 }
 
 jobject CAEDRNativeGetDeviceSocket(uint32_t idx)
 {
-    OIC_LOG(DEBUG, TAG, "CAEDRNativeGetDeviceSocket");
-
     if (!g_deviceObjectList)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceObjectList is null");
+        OIC_LOG(ERROR, TAG, "gdeviceObjectList is null");
         return NULL;
     }
 
     jobject jarrayObj = (jobject) u_arraylist_get(g_deviceObjectList, idx);
     if (!jarrayObj)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] jarrayObj is not available");
+        OIC_LOG(ERROR, TAG, "jarrayObj is not available");
         return NULL;
     }
     return jarrayObj;
@@ -881,32 +847,31 @@ jobject CAEDRNativeGetDeviceSocketBaseAddr(JNIEnv *env, const char* remoteAddres
 
     if (!g_deviceObjectList)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceObjectList is null");
+        OIC_LOG(ERROR, TAG, "gdeviceObjectList is null");
         return NULL;
     }
 
-    jint index;
     jint length = u_arraylist_length(g_deviceStateList);
-    for (index = 0; index < length; index++)
+    for (jint index = 0; index < length; index++)
     {
         jobject jarrayObj = (jobject) u_arraylist_get(g_deviceObjectList, index);
         if (!jarrayObj)
         {
-            OIC_LOG(ERROR, TAG, "[EDR][Native] jarrayObj is null");
+            OIC_LOG(ERROR, TAG, "jarrayObj is null");
             continue;
         }
 
         jstring jni_setAddress = CAEDRNativeGetAddressFromDeviceSocket(env, jarrayObj);
         if (!jni_setAddress)
         {
-            OIC_LOG(ERROR, TAG, "[EDR][Native] jni_setAddress is null");
+            OIC_LOG(ERROR, TAG, "jni_setAddress is null");
             continue;
         }
         const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
 
         if (!strcmp(setAddress, remoteAddress))
         {
-            OIC_LOG_V(ERROR, TAG, "[EDR][Native] remove object : %s", remoteAddress);
+            OIC_LOG_V(ERROR, TAG, "remove object : %s", remoteAddress);
             (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
             (*env)->DeleteLocalRef(env, jni_setAddress);
             return jarrayObj;
@@ -922,7 +887,7 @@ uint32_t CAEDRGetSocketListLength()
 {
     if (!g_deviceObjectList)
     {
-        OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceObjectList is null");
+        OIC_LOG(ERROR, TAG, "gdeviceObjectList is null");
         return 0;
     }
 
@@ -930,3 +895,37 @@ uint32_t CAEDRGetSocketListLength()
 
     return length;
 }
+
+CAConnectedDeviceInfo_t *CAEDRGetDeviceInfoFromAddress(const char *remoteAddress)
+{
+    OIC_LOG(DEBUG, TAG, "CAEDRGetDeviceInfoFromAddress");
+
+    if (!g_deviceStateList)
+    {
+        OIC_LOG(ERROR, TAG, "gdeviceStateList is null");
+        return NULL;
+    }
+    if (!remoteAddress)
+    {
+        OIC_LOG(ERROR, TAG, "remoteAddress is null");
+        return NULL;
+    }
+
+    jint length = u_arraylist_length(g_deviceStateList);
+    for (jint index = 0; index < length; index++)
+    {
+        CAConnectedDeviceInfo_t* deviceInfo =
+                (CAConnectedDeviceInfo_t*) u_arraylist_get(g_deviceStateList, index);
+        if (!deviceInfo)
+        {
+            OIC_LOG(DEBUG, TAG, "deviceInfo object is null");
+            continue;
+        }
+
+        if (!strcmp((const char*) deviceInfo->address, remoteAddress))
+        {
+            return deviceInfo;
+        }
+    }
+    return NULL;
+}
index ec12615..7d1601e 100644 (file)
@@ -27,7 +27,6 @@
 
 #include "cacommon.h"
 #include "cathreadpool.h"
-#include "uarraylist.h"
 #include "caedrinterface.h"
 #include "jni.h"
 
@@ -96,7 +95,7 @@ void CAEDRUpdateDeviceState(CAConnectedState_t state, const char *address);
  * Add device object to the list.
  * @param[in]  state            connection state object.
  */
-void CAEDRNativeAddDeviceStateToList(state_t *state);
+void CAEDRNativeAddDeviceStateToList(CAConnectedDeviceInfo_t *state);
 
 /**
  * Check whether the device exist in the list or not.
@@ -190,6 +189,13 @@ jobject CAEDRNativeGetDeviceSocketBaseAddr(JNIEnv *env, const char* remoteAddres
  */
 uint32_t CAEDRGetSocketListLength();
 
+/**
+ * Get device information from list.
+ * @param[in]   remoteAddress   remote address.
+ * @return  Device information object or NULL.
+ */
+CAConnectedDeviceInfo_t *CAEDRGetDeviceInfoFromAddress(const char *remoteAddress);
+
 #ifdef __cplusplus
 } /* extern "C" */
 #endif
index cf90302..9a1c018 100644 (file)
 #include "caedrinterface.h"
 #include "caadapterutils.h"
 #include "logger.h"
-#include "cafragmentation.h"
 #include "caqueueingthread.h"
 #include "oic_malloc.h"
 #include "caremotehandler.h"
+#include "pdu.h"
 
 /**
  * @var EDR_ADAPTER_TAG
  * @brief Logging tag for module name.
  */
-#define EDR_ADAPTER_TAG "CA_EDR_ADAPTER"
+#define EDR_ADAPTER_TAG "OIC_CA_EDR_ADAP"
 
 /**
  * @var g_edrThreadPool
@@ -95,25 +95,6 @@ static CAEndpoint_t *g_localConnectivity = NULL;
  */
 static bool g_serverState = false;
 
-/**
- * Stores information of all the senders.
- *
- * This structure will be used to track and defragment all incoming
- * data packet.
- */
-typedef struct
-{
-    uint32_t recvDataLen;
-    uint32_t totalDataLen;
-    uint8_t *defragData;
-    CAEndpoint_t *remoteEndpoint;
-} CAEDRSenderInfo_t;
-
-/**
- * Sender information.
- */
-static u_arraylist_t *g_senderInfo = NULL;
-
 static CAResult_t CAStartServer();
 static CAResult_t CAEDRInitializeQueueHandlers();
 CAResult_t CAEDRInitializeSendHandler();
@@ -126,13 +107,10 @@ void CAAdapterRecvData(const char *remoteAddress, const uint8_t *data, uint32_t
                        uint32_t *sentLength);
 void CAEDRNotifyNetworkStatus(CANetworkStatus_t status);
 void CAEDROnNetworkStatusChanged(void *context);
-CAResult_t CAAdapterSendData(const char *remoteAddress, const char *serviceUUID, const uint8_t *data,
-                             uint32_t dataLength, uint32_t *sentLength);
-CAEDRNetworkEvent *CAEDRCreateNetworkEvent(CAEndpoint_t *connectivity,
-                                           CANetworkStatus_t status);
-
-CAResult_t CAEDRClientSendData(const char *remoteAddress,
-                               const uint8_t *data,
+CAResult_t CAAdapterSendData(const char *remoteAddress, const char *serviceUUID,
+                             const uint8_t *data, uint32_t dataLength, uint32_t *sentLength);
+CAEDRNetworkEvent *CAEDRCreateNetworkEvent(CAEndpoint_t *connectivity, CANetworkStatus_t status);
+CAResult_t CAEDRClientSendData(const char *remoteAddress, const uint8_t *data,
                                uint32_t dataLength);
 
 /**
@@ -159,15 +137,11 @@ static void CAEDRDataDestroyer(void *data, uint32_t size);
 static void CAEDRErrorHandler(const char *remoteAddress, const uint8_t *data,
                               uint32_t dataLength, CAResult_t result);
 
-static void CAEDRClearSenderInfo();
-
 CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback,
                            CANetworkPacketReceivedCallback packetReceivedCallback,
                            CANetworkChangeCallback networkStateChangeCallback,
                            CAErrorHandleCallback errorCallback, ca_thread_pool_t handle)
 {
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
-
     // Input validation
     VERIFY_NON_NULL(registerCallback, EDR_ADAPTER_TAG, "register callback is NULL");
     VERIFY_NON_NULL(packetReceivedCallback, EDR_ADAPTER_TAG, "data receive callback is NULL");
@@ -183,48 +157,53 @@ CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback,
     g_errorCallback = errorCallback;
 
     // Initialize EDR Network Monitor
-    CAResult_t err = CAEDRInitializeNetworkMonitor(handle);
-    if (CA_STATUS_OK != err)
+    CAResult_t res = CAEDRInitializeNetworkMonitor(handle);
+    if (CA_STATUS_OK != res)
     {
         OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "EDR N/w Monitor Initialize failed!, error number [%d]",
-                  err);
-        return err;
+                  res);
+        return res;
     }
 
     CAEDRSetNetworkChangeCallback(CAEDRNotifyNetworkStatus);
     CAEDRSetPacketReceivedCallback(CAAdapterRecvData);
     CAEDRSetErrorHandler(CAEDRErrorHandler);
-    CAEDRInitializeClient(handle);
-
-    CAConnectivityHandler_t handler;
-    handler.startAdapter = CAStartEDR;
-    handler.startListenServer = CAStartEDRListeningServer;
-    handler.stopListenServer = CAStopEDRListeningServer;
-    handler.startDiscoveryServer = CAStartEDRDiscoveryServer;
-    handler.sendData = CASendEDRUnicastData;
-    handler.sendDataToAll = CASendEDRMulticastData;
-    handler.GetnetInfo = CAGetEDRInterfaceInformation;
-    handler.readData = CAReadEDRData;
-    handler.stopAdapter = CAStopEDR;
-    handler.terminate = CATerminateEDR;
-    registerCallback(handler, CA_ADAPTER_RFCOMM_BTEDR);
+    res = CAEDRClientInitialize();
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "EDR Client Initialize failed, error number [%d]", res);
+        return res;
+    }
 
-    // Initialize Send/Receive data message queues
-    if (CA_STATUS_OK != CAEDRInitializeQueueHandlers())
+    res = CAEDRServerInitialize(handle);
+    if (CA_STATUS_OK != res)
     {
-        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "CAAdapterInitializeQueues API failed");
-        CATerminateEDR();
-        return CA_STATUS_FAILED;
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "EDR Server Initialize failed, error number [%d]", res);
+        return res;
     }
 
+    static const CAConnectivityHandler_t handler =
+        {
+            .startAdapter = CAStartEDR,
+            .stopAdapter = CAStopEDR,
+            .startListenServer = CAStartEDRListeningServer,
+            .stopListenServer = CAStopEDRListeningServer,
+            .startDiscoveryServer = CAStartEDRDiscoveryServer,
+            .sendData = CASendEDRUnicastData,
+            .sendDataToAll = CASendEDRMulticastData,
+            .GetnetInfo = CAGetEDRInterfaceInformation,
+            .readData = CAReadEDRData,
+            .terminate = CATerminateEDR,
+            .cType = CA_ADAPTER_RFCOMM_BTEDR
+        };
+    registerCallback(handler);
+
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
     return CA_STATUS_OK;
 }
 
 CAResult_t CAStartEDR()
 {
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
-
     //Start Monitoring EDR Network
     CAResult_t ret = CAEDRStartNetworkMonitor();
     if (CA_STATUS_OK != ret)
@@ -253,32 +232,44 @@ CAResult_t CAStartEDR()
                   ret);
     }
 
+    // Initialize Send/Receive data message queues
+    if (CA_STATUS_OK != (ret = CAEDRInitializeQueueHandlers()))
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG,
+                  "CAAdapterInitializeQueues failed!, error number [%d] ", ret);
+        CATerminateEDR();
+        return CA_STATUS_FAILED;
+    }
+
+    // Start Send/Receive data message queues
     if (CA_STATUS_OK != (ret = CAAdapterStartQueue()))
     {
         OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "CAAdapterStartQueue failed!, error number [%d] ", ret);
     }
 
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
     return ret;
 }
 
 CAResult_t CAStartEDRListeningServer()
 {
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
-
     return CAStartServer();
 }
 
 CAResult_t CAStopEDRListeningServer()
 {
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
-
     return CAEDRServerStop();
 }
 
 CAResult_t CAStartEDRDiscoveryServer()
 {
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+#ifdef __TIZEN__
+    // Start device discovery
+    CAResult_t result = CAEDRStartDeviceDiscovery();
+    if(CA_STATUS_OK != result)
+    {
+        OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Failed to Start Device discovery");
+    }
+#endif
 
     return CAStartServer();
 }
@@ -286,8 +277,6 @@ CAResult_t CAStartEDRDiscoveryServer()
 int32_t CASendEDRUnicastData(const CAEndpoint_t *remoteEndpoint, const void *data,
                              uint32_t dataLength)
 {
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
-
     // Input validation
     VERIFY_NON_NULL_RET(remoteEndpoint, EDR_ADAPTER_TAG, "Remote endpoint is null", -1);
     VERIFY_NON_NULL_RET(data, EDR_ADAPTER_TAG, "Data is null", -1);
@@ -315,7 +304,6 @@ int32_t CASendEDRUnicastData(const CAEndpoint_t *remoteEndpoint, const void *dat
         return -1;
     }
 
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
     return sentLength;
 }
 
@@ -348,8 +336,6 @@ int32_t CASendEDRMulticastData(const CAEndpoint_t *endpoint, const void *data, u
 
 CAResult_t CAGetEDRInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
 {
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
-
     VERIFY_NON_NULL(info, EDR_ADAPTER_TAG, "LocalConnectivity info is null");
 
     CAResult_t err = CA_STATUS_OK;
@@ -362,21 +348,16 @@ CAResult_t CAGetEDRInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
     }
 
     *size = 1;
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
     return err;
 }
 
 CAResult_t CAReadEDRData()
 {
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
-
     return CAEDRManagerReadData();
 }
 
 CAResult_t CAStopEDR()
 {
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
-
     // Stop RFComm server if it is running
     CAEDRServerStop();
 
@@ -392,14 +373,11 @@ CAResult_t CAStopEDR()
     // Stop Send and receive Queue
     CAAdapterStopQueue();
 
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
     return CA_STATUS_OK;
 }
 
 void CATerminateEDR()
 {
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
-
     // Terminate EDR Network Monitor
     CAEDRTerminateNetworkMonitor();
 
@@ -421,16 +399,10 @@ void CATerminateEDR()
     // Free LocalConnectivity information
     CAFreeEndpoint(g_localConnectivity);
     g_localConnectivity = NULL;
-
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
 }
 
 CAResult_t CAStartServer()
 {
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
-
-    CAResult_t err = CA_STATUS_OK;
-
     if (false == g_adapterState)
     {
         OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Bluetooth adapter is disabled!");
@@ -439,21 +411,19 @@ CAResult_t CAStartServer()
         return CA_STATUS_OK;
     }
 
-    if (CA_STATUS_OK != (err = CAEDRServerStart(g_edrThreadPool)))
+    CAResult_t err = CA_STATUS_OK;
+    if (CA_STATUS_OK != (err = CAEDRServerStart()))
     {
         OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to start RFCOMM server!, error num [%d]",
                   err);
         return err;
     }
 
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
     return err;
 }
 
 CAResult_t CAEDRInitializeQueueHandlers()
 {
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
-
     if (CA_STATUS_OK == CAEDRInitializeSendHandler()
         && CA_STATUS_OK == CAEDRInitializeReceiveHandler())
     {
@@ -461,13 +431,11 @@ CAResult_t CAEDRInitializeQueueHandlers()
         return CA_STATUS_OK;
     }
 
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
     return CA_STATUS_FAILED;
 }
 
 CAResult_t CAEDRInitializeSendHandler()
 {
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
     // Check if the message queue is already initialized
     if (g_sendQueueHandle)
     {
@@ -493,7 +461,6 @@ CAResult_t CAEDRInitializeSendHandler()
 
 CAResult_t CAEDRInitializeReceiveHandler()
 {
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
     // Check if the message queue is already initialized
     if (g_recvQueueHandle)
     {
@@ -508,34 +475,22 @@ CAResult_t CAEDRInitializeReceiveHandler()
         return CA_MEMORY_ALLOC_FAILED;
     }
 
-    g_senderInfo = u_arraylist_create();
-    if (!g_senderInfo)
-    {
-        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "ClientInfo memory allcation failed!");
-        OICFree(g_recvQueueHandle);
-        g_recvQueueHandle = NULL;
-        return CA_MEMORY_ALLOC_FAILED;
-    }
 
     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_recvQueueHandle, g_edrThreadPool,
                                                    CAAdapterDataReceiverHandler,
                                                    CAEDRDataDestroyer))
     {
         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to Initialize send queue thread");
-        u_arraylist_free(&g_senderInfo);
         OICFree(g_recvQueueHandle);
         g_recvQueueHandle = NULL;
         return CA_STATUS_FAILED;
     }
 
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
     return CA_STATUS_OK;
 }
 
 void CAAdapterTerminateQueues()
 {
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
-
     if (g_sendQueueHandle)
     {
         CAQueueingThreadDestroy(g_sendQueueHandle);
@@ -546,10 +501,6 @@ void CAAdapterTerminateQueues()
         CAQueueingThreadDestroy(g_recvQueueHandle);
         g_recvQueueHandle = NULL;
     }
-
-    CAEDRClearSenderInfo();
-
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
 }
 
 void CAAdapterDataSendHandler(void *context)
@@ -557,24 +508,19 @@ void CAAdapterDataSendHandler(void *context)
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN - CAAdapterDataSendHandler");
 
     CAEDRData *message = (CAEDRData *) context;
-    if (NULL == message)
+    if (!message)
     {
         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to get message!");
         return;
     }
 
-    const char *remoteAddress = NULL;
-
-    if (NULL == message->remoteEndpoint)
+    if (!message->remoteEndpoint)
     {
         OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "remoteEndpoint is not available");
         return;
     }
-    else
-    {
-        remoteAddress = message->remoteEndpoint->addr;
-    }
 
+    const char *remoteAddress = message->remoteEndpoint->addr;
     if(!remoteAddress)
     {
         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "EDR Send Message error");
@@ -582,38 +528,8 @@ void CAAdapterDataSendHandler(void *context)
         return;
     }
 
-    uint32_t dataSegmentLength = message->dataLen + CA_HEADER_LENGTH;
-
-    uint8_t *header = (uint8_t *) OICCalloc(CA_HEADER_LENGTH, sizeof(uint8_t));
-    VERIFY_NON_NULL_VOID(header, EDR_ADAPTER_TAG, "Memory allocation failed");
-
-    uint8_t* dataSegment = (uint8_t *) OICCalloc(dataSegmentLength, sizeof(uint8_t));
-    if (NULL == dataSegment)
-    {
-        CAEDRErrorHandler(remoteAddress, message->data, message->dataLen, CA_SEND_FAILED);
-        OICFree(header);
-        return;
-    }
-
-    CAResult_t result = CAGenerateHeader(header, CA_HEADER_LENGTH, message->dataLen);
-    if (CA_STATUS_OK != result)
-    {
-        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Generate header failed");
-        OICFree(header);
-        OICFree(dataSegment);
-        CAEDRErrorHandler(remoteAddress, message->data, message->dataLen, result);
-        return;
-    }
-
-    memcpy(dataSegment, header, CA_HEADER_LENGTH);
-    OICFree(header);
-
-    memcpy(dataSegment + CA_HEADER_LENGTH, message->data, message->dataLen);
-
-    result = CAEDRClientSendData(remoteAddress, dataSegment, dataSegmentLength);
-    OICFree(dataSegment);
-
-    if (CA_STATUS_OK != result)
+    CAResult_t result = CAEDRClientSendData(remoteAddress, message->data, message->dataLen);
+    if(CA_STATUS_OK != result)
     {
         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "CAEDRClientSendData API failed");
         CAEDRErrorHandler(remoteAddress, message->data, message->dataLen, result);
@@ -623,11 +539,9 @@ void CAAdapterDataSendHandler(void *context)
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
 }
 
-CAResult_t CAEDRClientSendData(const char *remoteAddress,
-                               const uint8_t *data,
+CAResult_t CAEDRClientSendData(const char *remoteAddress, const uint8_t *data,
                                uint32_t dataLength)
 {
-
     CAResult_t result = CA_SEND_FAILED;
 
     // Send the first segment with the header.
@@ -654,65 +568,6 @@ CAResult_t CAEDRClientSendData(const char *remoteAddress,
     return result;
 }
 
-static void CAEDRClearSenderInfo()
-{
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
-
-    uint32_t listIndex = 0;
-    uint32_t listLength = u_arraylist_length(g_senderInfo);
-    for (listIndex = 0; listIndex < listLength; listIndex++)
-    {
-        CAEDRSenderInfo_t *info = (CAEDRSenderInfo_t *) u_arraylist_get(g_senderInfo, listIndex);
-        if (!info)
-        {
-            continue;
-        }
-
-        OICFree(info->defragData);
-        CAFreeEndpoint(info->remoteEndpoint);
-        OICFree(info);
-    }
-    u_arraylist_free(&g_senderInfo);
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
-}
-
-static CAResult_t CAEDRGetSenderInfo(const char *edrAddress,
-                                     CAEDRSenderInfo_t **senderInfo,
-                                     uint32_t *senderIndex)
-{
-    VERIFY_NON_NULL_RET(edrAddress,
-                        EDR_ADAPTER_TAG,
-                        "NULL edr address argument",
-                        CA_STATUS_INVALID_PARAM);
-    VERIFY_NON_NULL_RET(senderIndex,
-                        EDR_ADAPTER_TAG,
-                        "NULL index argument",
-                        CA_STATUS_INVALID_PARAM);
-
-    const uint32_t listLength = u_arraylist_length(g_senderInfo);
-    const uint32_t addrLength = strlen(edrAddress);
-    for (uint32_t index = 0; index < listLength; index++)
-    {
-        CAEDRSenderInfo_t *info = (CAEDRSenderInfo_t *) u_arraylist_get(g_senderInfo, index);
-        if (!info || !(info->remoteEndpoint))
-        {
-            continue;
-        }
-
-        if (!strncmp(info->remoteEndpoint->addr, edrAddress, addrLength))
-        {
-            *senderIndex = index;
-            if (senderInfo)
-            {
-                *senderInfo = info;
-            }
-            return CA_STATUS_OK;
-        }
-    }
-
-    return CA_STATUS_FAILED;
-}
-
 void CAAdapterDataReceiverHandler(void *context)
 {
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN_CAAdapterDataReceiverHandler");
@@ -729,138 +584,31 @@ void CAAdapterDataReceiverHandler(void *context)
         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to get message!");
         return;
     }
-    uint32_t dataLen = 0;
 
-    CAEDRSenderInfo_t *senderInfo = NULL;
-    uint32_t senderIndex = 0;
+    CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
+                                                          CA_ADAPTER_RFCOMM_BTEDR,
+                                                          message->remoteEndpoint->addr,
+                                                          0);
 
-    while (dataLen < message->dataLen)
+    if (!remoteEndpoint)
     {
-        if(CA_STATUS_OK != CAEDRGetSenderInfo(message->remoteEndpoint->addr,
-                                              &senderInfo, &senderIndex))
-        {
-            OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "This is a new client [%s]",
-                                                message->remoteEndpoint->addr);
-        }
-
-        if (!senderInfo)
-        {
-            CAEDRSenderInfo_t *newSender = OICMalloc(sizeof(CAEDRSenderInfo_t));
-            if (!newSender)
-            {
-                return;
-            }
-            newSender->recvDataLen = 0;
-            newSender->totalDataLen = 0;
-            newSender->defragData = NULL;
-            newSender->remoteEndpoint = NULL;
-
-            OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Parsing the header");
-            newSender->totalDataLen = CAParseHeader(message->data + dataLen,
-                                                    message->dataLen - dataLen);
-            if(!(newSender->totalDataLen))
-            {
-                OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Total Data Length is parsed as 0!!!");
-                OICFree(newSender);
-                return;
-            }
-
-            OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "Total data to be accumulated [%u] bytes",
-                                                newSender->totalDataLen);
-            OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "data received in the first packet [%u] bytes",
-                                                message->dataLen);
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "remoteEndpoint is NULL");
+        return;
+    }
 
-            newSender->defragData = OICCalloc(newSender->totalDataLen,
-                                              sizeof(*newSender->defragData));
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Sending data up !");
 
-            if (NULL == newSender->defragData)
-            {
-                OICFree(newSender);
-                return;
-            }
+    const CASecureEndpoint_t sep = { .endpoint = *remoteEndpoint };
 
-            newSender->remoteEndpoint = CACloneEndpoint(message->remoteEndpoint);
-            if (NULL == newSender->remoteEndpoint)
-            {
-                OIC_LOG(ERROR, EDR_ADAPTER_TAG, "remoteEndpoint is NULL!");
-                OICFree(newSender->defragData);
-                OICFree(newSender);
-                return;
-            }
+    g_networkPacketReceivedCallback(&sep, message->data, message->dataLen);
 
-            if (message->dataLen - CA_HEADER_LENGTH - dataLen <= newSender->totalDataLen)
-            {
-                memcpy(newSender->defragData, message->data + dataLen + CA_HEADER_LENGTH,
-                       message->dataLen - dataLen - CA_HEADER_LENGTH);
-                newSender->recvDataLen += message->dataLen - dataLen - CA_HEADER_LENGTH;
-                u_arraylist_add(g_senderInfo,(void *)newSender);
-                dataLen = message->dataLen;
-            }
-            else
-            {
-                memcpy(newSender->defragData, message->data + dataLen + CA_HEADER_LENGTH,
-                       newSender->totalDataLen);
-                newSender->recvDataLen = newSender->totalDataLen;
-                u_arraylist_add(g_senderInfo,(void *)newSender);
-                dataLen += newSender->totalDataLen + CA_HEADER_LENGTH;
-            }
-            //Getting newSender index position in g_senderInfo array list
-            if (CA_STATUS_OK !=
-                CAEDRGetSenderInfo(newSender->remoteEndpoint->addr, NULL, &senderIndex))
-            {
-                OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Existing sender index not found!!");
-                OICFree(newSender->defragData);
-                CAFreeEndpoint(newSender->remoteEndpoint);
-                OICFree(newSender);
-                return;
-            }
-            senderInfo = newSender;
-        }
-        else
-        {
-            if (senderInfo->recvDataLen + message->dataLen - dataLen <= senderInfo->totalDataLen)
-            {
-                OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "Copying the data of length [%d]",
-                          message->dataLen - dataLen);
-                memcpy(senderInfo->defragData + senderInfo->recvDataLen, message->data + dataLen,
-                       message->dataLen - dataLen);
-                senderInfo->recvDataLen += message->dataLen - dataLen;
-                OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "totalDatalength  [%d] recveived Datalen [%d]",
-                          senderInfo->totalDataLen, senderInfo->recvDataLen);
-                dataLen = message->dataLen;
-            }
-            else
-            {
-                OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "Copying the data of length [%d]",
-                          senderInfo->totalDataLen - senderInfo->recvDataLen);
-                memcpy(senderInfo->defragData + senderInfo->recvDataLen, message->data + dataLen,
-                       senderInfo->totalDataLen - senderInfo->recvDataLen);
-                dataLen += senderInfo->totalDataLen - senderInfo->recvDataLen;
-                senderInfo->recvDataLen = senderInfo->totalDataLen;
-                OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "totalDatalength  [%d] recveived Datalen [%d]",
-                          senderInfo->totalDataLen, senderInfo->recvDataLen);
-            }
-        }
+    CAFreeEndpoint(remoteEndpoint);
 
-        if (senderInfo->totalDataLen == senderInfo->recvDataLen)
-        {
-            OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Sending data up !");
-
-            CASecureEndpoint_t sep = {.endpoint = *(senderInfo->remoteEndpoint)};
-            g_networkPacketReceivedCallback(&sep, senderInfo->defragData, senderInfo->recvDataLen);
-            u_arraylist_remove(g_senderInfo, senderIndex);
-            senderInfo->remoteEndpoint = NULL;
-            senderInfo->defragData = NULL;
-            OICFree(senderInfo);
-            senderInfo = NULL;
-        }
-    }
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT_CAAdapterDataReceiverHandler");
 }
 
 CAResult_t CAAdapterStartQueue()
 {
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
     // Start send queue thread
     if (CA_STATUS_OK != CAQueueingThreadStart(g_sendQueueHandle))
     {
@@ -880,27 +628,24 @@ CAResult_t CAAdapterStartQueue()
         CAEDRClientDisconnectAll();
         return CA_STATUS_FAILED;
     }
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+
     return CA_STATUS_OK;
 }
 
 CAResult_t CAAdapterStopQueue()
 {
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
     //Stop send queue thread
     CAQueueingThreadStop(g_sendQueueHandle);
 
     //Stop receive queue thread
     CAQueueingThreadStop(g_recvQueueHandle);
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+
     return CA_STATUS_OK;
 }
 
 void CAAdapterRecvData(const char *remoteAddress, const uint8_t *data, uint32_t dataLength,
                        uint32_t *sentLength)
 {
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
-
     if (false == g_adapterState)
     {
         OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Bluetooth adapter is disabled!");
@@ -929,15 +674,11 @@ void CAAdapterRecvData(const char *remoteAddress, const uint8_t *data, uint32_t
 
     // Free remote endpoint
     CAFreeEndpoint(remoteEndpoint);
-
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
 }
 
 void CAEDRErrorHandler(const char *remoteAddress, const uint8_t *data,
                        uint32_t dataLength, CAResult_t result)
 {
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
-
     // Input validation
     VERIFY_NON_NULL_VOID(data, EDR_ADAPTER_TAG, "Data is null");
 
@@ -954,8 +695,6 @@ void CAEDRErrorHandler(const char *remoteAddress, const uint8_t *data,
 
     // Free remote endpoint
     CAFreeEndpoint(remoteEndpoint);
-
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
 }
 
 CAResult_t CAAdapterSendData(const char *remoteAddress, const char *serviceUUID, const uint8_t *data,
@@ -998,8 +737,6 @@ CAResult_t CAAdapterSendData(const char *remoteAddress, const char *serviceUUID,
 
 void CAEDRNotifyNetworkStatus(CANetworkStatus_t status)
 {
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
-
     // Create localconnectivity
     if (NULL == g_localConnectivity)
     {
@@ -1018,7 +755,7 @@ void CAEDRNotifyNetworkStatus(CANetworkStatus_t status)
                 return;
             }
 
-            if (false== adapterState)
+            if (false == adapterState)
             {
                 OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Bluetooth adapter is disabled!");
                 g_adapterState = false;
@@ -1055,14 +792,10 @@ void CAEDRNotifyNetworkStatus(CANetworkStatus_t status)
             }
         }
     }
-
-    OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
 }
 
 void CAEDROnNetworkStatusChanged(void *context)
 {
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
-
     if (NULL == context)
     {
         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "context is NULL!");
@@ -1079,8 +812,6 @@ void CAEDROnNetworkStatusChanged(void *context)
 
     // Free the created Network event
     CAEDRFreeNetworkEvent(networkEvent);
-
-    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
 }
 
 CAEDRNetworkEvent *CAEDRCreateNetworkEvent(CAEndpoint_t *connectivity,
@@ -1112,9 +843,9 @@ void CAEDRFreeNetworkEvent(CAEDRNetworkEvent *event)
 }
 
 CAEDRData *CACreateEDRData(const CAEndpoint_t *remoteEndpoint,
-                                        const uint8_t *data, uint32_t dataLength)
+                           const uint8_t *data, uint32_t dataLength)
 {
-    CAEDRData *edrData = (CAEDRData *)OICMalloc(sizeof (CAEDRData));
+    CAEDRData *edrData = (CAEDRData *) OICCalloc(1, sizeof(*edrData));
     if (!edrData)
     {
         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Memory allocation failed!");
@@ -1149,8 +880,7 @@ void CAEDRDataDestroyer(void *data, uint32_t size)
 {
     if ((size_t)size < sizeof(CAEDRData))
     {
-        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Destroy data too small %p %d",
-                  data, size);
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Destroy data too small %p %d", data, size);
     }
     CAEDRData *edrdata = (CAEDRData *) data;
 
index 4ed9085..4863861 100644 (file)
@@ -25,7 +25,7 @@
 #include "caedradapter.h"
 #include "logger.h"
 
-#define TAG PCF("CA")
+#define TAG PCF("OIC_CA")
 
 static CANetworkPacketReceivedCallback g_edrReceivedCallback = NULL;
 static ca_thread_pool_t g_threadPoolHandle = NULL;
@@ -53,10 +53,11 @@ CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback,
         .GetnetInfo = CAGetEDRInterfaceInformation,
         .readData = CAReadEDRData,
         .stopAdapter = CAStopEDR,
-        .terminate = CATerminateEDR
+        .terminate = CATerminateEDR,
+        .cType = CA_ADAPTER_RFCOMM_BTEDR
     };
 
-    registerCallback(handler, CA_ADAPTER_RFCOMM_BTEDR);
+    registerCallback(handler);
 
     return CA_STATUS_OK;
 }
index 0b145b6..cb7c711 100644 (file)
@@ -9,7 +9,7 @@ env.PrependUnique(CPPPATH = [ os.path.join(src_dir, 'tizen'),
                               './con/lib/tizen/ble/inc',
                               './con/lib/tizen/ble/inc/mobile' ])
 
-env.ParseConfig("pkg-config --cflags --libs capi-network-bluetooth glib-2.0")
+env.ParseConfig("pkg-config --cflags --libs capi-network-bluetooth")
 
 src_files = [ 'caedrclient.c',
               'caedrdevicelist.c',
index a0106eb..e24e2ae 100644 (file)
@@ -27,6 +27,7 @@
 
 #include <string.h>
 #include <bluetooth.h>
+#include <bluetooth_internal.h>
 
 #include "caedrinterface.h"
 #include "camutex.h"
 #define MICROSECS_PER_SEC 1000000
 
 /**
- * Condition to check if OIC supported device is found.
+ * Maximum CoAP over TCP header length
+ * to know the total data length.
  */
-static ca_cond g_deviceDescCond = NULL;
-
-/**
- * Flag that will be set when EDR adapter is stopped.
- */
-static bool g_isStopping = false;
+#define EDR_MAX_HEADER_LEN  6
 
 /**
  * Mutex to synchronize the access to Bluetooth device information list.
@@ -71,9 +68,24 @@ static CAEDRDataReceivedCallback g_edrPacketReceivedCallback = NULL;
 static CAEDRErrorHandleCallback g_edrErrorHandler = NULL;
 
 /**
+ * Pending multicast data list to be sent.
+ */
+static u_arraylist_t *g_multicastDataList = NULL;
+
+/**
+ * Mutex to synchronize the access to Pending multicast data list.
+ */
+static ca_mutex g_multicastDataListMutex = NULL;
+
+/**
+ * To Store Adapter Mode information
+ */
+static bool g_isDiscoveryServer = false;
+
+/**
  * This function creates mutex.
  */
-static void CAEDRManagerInitializeMutex(void);
+static CAResult_t CAEDRManagerInitializeMutex(void);
 
 /**
  * This function frees mutex.
@@ -86,11 +98,6 @@ static void CAEDRManagerTerminateMutex(void);
 static void CAEDRDataRecvCallback(bt_socket_received_data_s *data, void *userData);
 
 /**
- * This function starts device discovery.
- */
-static CAResult_t CAEDRStartDeviceDiscovery(void);
-
-/**
  * This function stops any ongoing service sevice search.
  */
 static CAResult_t CAEDRStopServiceSearch(void);
@@ -261,6 +268,10 @@ void CAEDRDeviceDiscoveryCallback(int result, bt_adapter_device_discovery_state_
         case BT_ADAPTER_DEVICE_DISCOVERY_FINISHED:
             {
                 OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Discovery finished!");
+                ca_mutex_lock(g_multicastDataListMutex);
+                u_arraylist_destroy(g_multicastDataList);
+                g_multicastDataList = NULL;
+                ca_mutex_unlock(g_multicastDataListMutex);
             }
             break;
 
@@ -304,9 +315,40 @@ void CAEDRDeviceDiscoveryCallback(int result, bt_adapter_device_discovery_state_
                         ca_mutex_unlock(g_edrDeviceListMutex);
                         return;
                     }
+
+                    int lengthData = u_arraylist_length(g_multicastDataList);
+                    for(int len = 0; len < lengthData; len++)
+                    {
+                        // Adding to pending list
+                        EDRData *multicastData =
+                            (EDRData *)u_arraylist_get(g_multicastDataList, len);
+                        if (NULL == multicastData)
+                        {
+                            OIC_LOG(ERROR, EDR_ADAPTER_TAG, "multicastData is NULL");
+                            continue;
+                        }
+                        result = CAAddEDRDataToList(&device->pendingDataList, multicastData->data,
+                                                    multicastData->dataLength);
+                        if (CA_STATUS_OK != result)
+                        {
+                            OIC_LOG_V(ERROR, EDR_ADAPTER_TAG,
+                                      "Failed to add data to pending list[%d]", result);
+                            continue;
+                        }
+                    }
+                    if (lengthData)
+                    {
+                        result = CAEDRClientConnect(device->remoteAddress, device->serviceUUID);
+                        if (CA_STATUS_OK != result)
+                        {
+                            OIC_LOG_V(ERROR, EDR_ADAPTER_TAG,
+                                      "Failed to make RFCOMM connection[%d]", result);
+
+                            //Remove the data which added to pending list
+                            CARemoveEDRDataFromList(&device->pendingDataList);
+                        }
+                    }
                     device->serviceSearched = true;
-                    // Signal the wait to send the data.
-                    ca_cond_signal(g_deviceDescCond);
                     ca_mutex_unlock(g_edrDeviceListMutex);
                 }
                 else
@@ -375,7 +417,6 @@ CAResult_t CAEDRStartDeviceDiscovery(void)
 {
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
 
-
     bool isDiscoveryStarted = false;
 
     // Check the device discovery state
@@ -399,6 +440,8 @@ CAResult_t CAEDRStartDeviceDiscovery(void)
         }
     }
 
+    g_isDiscoveryServer = true;
+
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
     return CA_STATUS_OK;
 }
@@ -478,21 +521,12 @@ CAResult_t CAEDRClientSetCallbacks(void)
 {
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
 
-    g_isStopping = false;
     // Register for discovery and rfcomm socket connection callbacks
     bt_adapter_set_device_discovery_state_changed_cb(CAEDRDeviceDiscoveryCallback, NULL);
     bt_device_set_service_searched_cb(CAEDRServiceSearchedCallback, NULL);
     bt_socket_set_connection_state_changed_cb(CAEDRSocketConnectionStateCallback, NULL);
     bt_socket_set_data_received_cb(CAEDRDataRecvCallback, NULL);
 
-    // Start device discovery
-    CAResult_t result = CAEDRStartDeviceDiscovery();
-    if(CA_STATUS_OK != result)
-    {
-        OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Failed to Start Device discovery");
-        return CA_STATUS_FAILED;
-    }
-
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
     return CA_STATUS_OK;
 }
@@ -508,10 +542,6 @@ void CAEDRClientUnsetCallbacks(void)
     // Stop the device discovery process
     CAEDRStopDeviceDiscovery();
 
-    // Signal the conditional wait for discovery of devices.
-    g_isStopping = true;
-    ca_cond_signal(g_deviceDescCond);
-
     // reset bluetooth adapter callbacks
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Resetting the callbacks");
     bt_adapter_unset_device_discovery_state_changed_cb();
@@ -522,8 +552,9 @@ void CAEDRClientUnsetCallbacks(void)
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
 }
 
-void CAEDRManagerInitializeMutex(void)
+CAResult_t CAEDRManagerInitializeMutex(void)
 {
+    CAResult_t result = CA_STATUS_OK;
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
 
     if (!g_edrDeviceListMutex)
@@ -531,12 +562,19 @@ void CAEDRManagerInitializeMutex(void)
         g_edrDeviceListMutex = ca_mutex_new();
     }
 
-    if (!g_deviceDescCond)
+    if (!g_multicastDataListMutex)
+    {
+        g_multicastDataListMutex = ca_mutex_new();
+    }
+
+    if (!g_edrDeviceListMutex || !g_multicastDataListMutex)
     {
-        g_deviceDescCond = ca_cond_new();
+        result = CA_STATUS_NOT_INITIALIZED;
     }
 
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+
+    return result;
 }
 
 void CAEDRManagerTerminateMutex(void)
@@ -549,19 +587,21 @@ void CAEDRManagerTerminateMutex(void)
         g_edrDeviceListMutex = NULL;
     }
 
-    if (g_deviceDescCond)
+    if (g_multicastDataListMutex)
     {
-        ca_cond_free(g_deviceDescCond);
-        g_deviceDescCond = NULL;
+        ca_mutex_free(g_multicastDataListMutex);
+        g_multicastDataListMutex = NULL;
     }
+
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
 }
 
-void CAEDRInitializeClient(ca_thread_pool_t handle)
+CAResult_t CAEDRClientInitialize()
 {
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
-    CAEDRManagerInitializeMutex();
+    CAResult_t result = CAEDRManagerInitializeMutex();
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return result;
 }
 
 void CAEDRClientTerminate()
@@ -576,6 +616,14 @@ void CAEDRClientTerminate()
         ca_mutex_unlock(g_edrDeviceListMutex);
     }
 
+    if (g_multicastDataListMutex)
+    {
+        ca_mutex_lock(g_multicastDataListMutex);
+        u_arraylist_destroy(g_multicastDataList);
+        g_multicastDataList = NULL;
+        ca_mutex_unlock(g_multicastDataListMutex);
+    }
+
     // Free the mutex
     CAEDRManagerTerminateMutex();
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
@@ -728,32 +776,6 @@ CAResult_t CAEDRClientSendMulticastData(const uint8_t *data,
     // Send the packet to all OIC devices
     ca_mutex_lock(g_edrDeviceListMutex);
 
-    // Check if any device is discovered.
-    if (NULL == g_edrDeviceList)
-    {
-        // Wait for BT devices to be discovered.
-
-        // Number of times to wait for discovery to complete.
-        int const RETRIES = 5;
-
-        uint64_t const TIMEOUT = 2 * MICROSECS_PER_SEC;  // Microseconds
-
-        bool devicesDiscovered = false;
-        for (size_t i = 0; NULL == g_edrDeviceList && i < RETRIES && !g_isStopping;
-             ++i)
-        {
-            if (ca_cond_wait_for(g_deviceDescCond, g_edrDeviceListMutex,
-                                 TIMEOUT) == 0)
-            {
-                devicesDiscovered = true;
-            }
-        }
-        if (!devicesDiscovered || g_isStopping)
-        {
-            goto exit;
-        }
-    }
-
     EDRDeviceList *curList = g_edrDeviceList;
     CAResult_t result = CA_STATUS_FAILED;
     while (curList != NULL)
@@ -806,9 +828,44 @@ CAResult_t CAEDRClientSendMulticastData(const uint8_t *data,
             }
         }
     }
-exit:
+
     ca_mutex_unlock(g_edrDeviceListMutex);
 
+    if(g_isDiscoveryServer)
+    {
+        // Start the device Discovery.
+        result = CAEDRStartDeviceDiscovery();
+        if (CA_STATUS_OK == result)
+        {
+            OIC_LOG(INFO, EDR_ADAPTER_TAG, "Add the data to the multicast data list");
+
+            EDRData *multicastData = (EDRData *)OICCalloc(1, sizeof(EDRData));
+            if (NULL == multicastData)
+            {
+                OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Malloc failed");
+                goto exit;
+            }
+            multicastData->data = OICCalloc(1, dataLength);
+            if (NULL == multicastData->data)
+            {
+                OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Malloc failed");
+                goto exit;
+            }
+            memcpy(multicastData->data, data, dataLength);
+            multicastData->dataLength = dataLength;
+
+            // Add the data to pending multicast data list.
+            ca_mutex_lock(g_multicastDataListMutex);
+            if (NULL == g_multicastDataList)
+            {
+                g_multicastDataList = u_arraylist_create();
+            }
+            u_arraylist_add(g_multicastDataList, (void *)multicastData);
+            ca_mutex_unlock(g_multicastDataListMutex);
+        }
+    }
+
+exit:
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
     return CA_STATUS_OK;
 }
@@ -893,18 +950,95 @@ void CAEDRDataRecvCallback(bt_socket_received_data_s *data, void *userData)
     }
     ca_mutex_unlock(g_edrDeviceListMutex);
 
+    //: TODO Need to check if 'check required for socket still connected or not'
     if (!device)
     {
         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "There is no device!");
         return;
     }
 
-    uint32_t sentLength = 0;
+    CAConnectedDeviceInfo_t *deviceInfo =
+        (CAConnectedDeviceInfo_t *) CAEDRGetDeviceInfoFromAddress(device->remoteAddress);
 
-    g_edrPacketReceivedCallback(device->remoteAddress,
-                                (uint8_t *) data->data,
-                                (uint32_t) data->data_size,
-                                &sentLength);
+    if (!deviceInfo)
+    {
+        OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Received Data from new device");
+        deviceInfo = (CAConnectedDeviceInfo_t *) OICCalloc(1, sizeof(*deviceInfo));
+        if (!deviceInfo)
+        {
+            OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Out of memory");
+            return;
+        }
+
+        deviceInfo->state = STATE_CONNECTED;
+        deviceInfo->recvData = NULL;
+        deviceInfo->recvDataLen = 0;
+        deviceInfo->totalDataLen = 0;
+        result = CAEDRAddDeviceInfoToList(device->remoteAddress, deviceInfo);
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Could not add device info to list!");
+            OICFree(deviceInfo);
+            return;
+        }
+    }
+
+    if (!deviceInfo->recvData)
+    {
+        OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Callocing deviceInfo->recvData");
+        deviceInfo->recvData = OICCalloc(data->data_size, sizeof(uint8_t));
+        if (!deviceInfo->recvData)
+        {
+            OIC_LOG(ERROR, EDR_ADAPTER_TAG, "out of memory");
+            return;
+        }
+    }
+
+    memcpy(deviceInfo->recvData + deviceInfo->recvDataLen, (const char*)data->data,
+           data->data_size);
+    deviceInfo->recvDataLen += data->data_size;
+
+    if (!deviceInfo->totalDataLen)
+    {
+        coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
+                ((unsigned char *)deviceInfo->recvData)[0] >> 4);
+        size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
+
+        if (deviceInfo->recvDataLen >= headerLen)
+        {
+            // get actual data length from coap over tcp header
+            deviceInfo->totalDataLen = coap_get_total_message_length(deviceInfo->recvData,
+                                                                     deviceInfo->recvDataLen);
+            OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "total data length [%d] bytes", deviceInfo->totalDataLen);
+
+            uint8_t *newBuf = OICRealloc(deviceInfo->recvData, deviceInfo->totalDataLen);
+            if (!newBuf)
+            {
+                OIC_LOG(ERROR, EDR_ADAPTER_TAG, "out of memory");
+                //Memory free
+                return;
+            }
+            deviceInfo->recvData = newBuf;
+        }
+    }
+
+    if (deviceInfo->totalDataLen == deviceInfo->recvDataLen)
+    {
+        if (g_edrPacketReceivedCallback)
+        {
+            OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG,"data will be sent to callback routine: %s, %d",
+                      deviceInfo->recvData, deviceInfo->recvDataLen);
+
+            uint32_t sentLength = 0;
+            g_edrPacketReceivedCallback(device->remoteAddress, (void*) deviceInfo->recvData,
+                                        deviceInfo->recvDataLen, &sentLength);
+
+            OICFree(deviceInfo->recvData);
+            deviceInfo->recvData = NULL;
+            deviceInfo->recvDataLen = 0;
+            deviceInfo->totalDataLen = 0;
+        }
+    }
 
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
 }
index c7156e6..78af3ff 100644 (file)
@@ -47,6 +47,11 @@ CAResult_t CAEDRSendData(int serverFD, const void *data, uint32_t dataLength)
         OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "sending data failed!, soketid [%d]", serverFD);
         return CA_SOCKET_OPERATION_FAILED;
     }
+    else if (dataLen == 0)
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "soketid [%d] may be disconnected?", serverFD);
+        return CA_SOCKET_OPERATION_FAILED;
+    }
 
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
     return CA_STATUS_OK;
index dd3e11d..4958b43 100644 (file)
@@ -51,10 +51,9 @@ static CAEDRNetworkStatusCallback g_edrNetworkChangeCallback = NULL;
 static void CAEDRAdapterStateChangeCallback(int result, bt_adapter_state_e adapterState,
                                             void *userData);
 
-void *GMainLoopThread (void *param)
+void CAEDRMainLoopThread(void *param)
 {
     g_main_loop_run(g_mainloop);
-    return NULL;
 }
 
 CAResult_t CAEDRInitializeNetworkMonitor(const ca_thread_pool_t threadPool)
@@ -88,7 +87,7 @@ CAResult_t CAEDRStartNetworkMonitor()
         return CA_STATUS_FAILED;
     }
 
-    if (CA_STATUS_OK != ca_thread_pool_add_task(g_threadPoolHandle, GMainLoopThread, (void *) NULL))
+    if (CA_STATUS_OK != ca_thread_pool_add_task(g_threadPoolHandle, CAEDRMainLoopThread, (void *) NULL))
     {
         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to create thread!");
         return CA_STATUS_FAILED;
index b2a5371..9ef15fa 100644 (file)
@@ -42,7 +42,7 @@ static int32_t g_maxPendingConnections = 10;
  */
 static int g_serverFD = -1;
 
-CAResult_t CAEDRServerStart(ca_thread_pool_t handle)
+CAResult_t CAEDRServerStart()
 {
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
 
@@ -106,6 +106,12 @@ CAResult_t CAEDRServerStop()
     return CA_STATUS_OK;
 }
 
+CAResult_t CAEDRServerInitialize(ca_thread_pool_t handle)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "CAEDRServerInitialize");
+    return CA_STATUS_OK;
+}
+
 void CAEDRServerTerminate()
 {
     // This is just a dummy
index 70073ae..72df325 100644 (file)
 #include <bluetooth.h>
 
 #include "logger.h"
+#include "uarraylist.h"
+
+/**
+ * Pending devices list for data transfer.
+ */
+static u_arraylist_t *g_deviceStateList = NULL;
 
 bool CAEDRIsServiceSupported(const char **serviceUUID, int32_t serviceCount,
                                  const char *matchService)
@@ -54,5 +60,69 @@ bool CAEDRIsServiceSupported(const char **serviceUUID, int32_t serviceCount,
     return false;
 }
 
+CAConnectedDeviceInfo_t *CAEDRGetDeviceInfoFromAddress(const char *remoteAddress)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "CAEDRGetDeviceInfoFromAddress");
 
+    if (!remoteAddress)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "remoteAddress is null");
+        return NULL;
+    }
+
+    uint32_t length = u_arraylist_length(g_deviceStateList);
+    for (uint32_t index = 0; index < length; index++)
+    {
+        CAConnectedDeviceInfo_t* deviceInfo =
+                (CAConnectedDeviceInfo_t*) u_arraylist_get(g_deviceStateList, index);
+        if (!deviceInfo)
+        {
+            OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "deviceInfo object is null");
+            continue;
+        }
+
+        if (!strcmp((const char*) deviceInfo->address, remoteAddress))
+        {
+            return deviceInfo;
+        }
+    }
+    return NULL;
+}
+
+CAResult_t CAEDRAddDeviceInfoToList(const char *remoteAddress, CAConnectedDeviceInfo_t *deviceInfo)
+{
+    if (!remoteAddress)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "remoteAddress is null");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    if (!deviceInfo)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "deviceInfo is null");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    for (int i = 0; i < CA_MACADDR_SIZE; i++)
+    {
+        deviceInfo->address[i] = (uint8_t) remoteAddress[i];
+    }
+
+    if (!g_deviceStateList)
+    {
+        g_deviceStateList = u_arraylist_create();
+        if (!g_deviceStateList)
+        {
+            OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to create Device list");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (!u_arraylist_add(g_deviceStateList, (void *) deviceInfo))
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to Add Device to list");
+        return CA_STATUS_FAILED;
+    }
 
+    return CA_STATUS_OK;
+}
\ No newline at end of file
index 6a7d706..c3afe31 100644 (file)
@@ -32,6 +32,7 @@
 
 #include "cacommon.h"
 #include "oic_malloc.h"
+#include "caedrinterface.h"
 
 /**
  * Logging tag for module name.
@@ -58,6 +59,21 @@ extern "C"
 bool CAEDRIsServiceSupported(const char **serviceUUID, int32_t serviceCount,
                             const char *matchService);
 
+/**
+ * Get device information from list.
+ * @param[in]   remoteAddress   remote address.
+ * @return  Device information object or NULL.
+ */
+CAConnectedDeviceInfo_t *CAEDRGetDeviceInfoFromAddress(const char *remoteAddress);
+
+/**
+ * Add device information to list.
+ * @param[in]   remoteAddress   remote address.
+ * @param[in]   deviceInfo      device information.
+ * @return ::CA_STATUS_OK or Appropriate error code.
+ */
+CAResult_t CAEDRAddDeviceInfoToList(const char *remoteAddress, CAConnectedDeviceInfo_t *deviceInfo);
+
 #ifdef __cplusplus
 } /* extern "C" */
 #endif
index bb622ed..dd953de 100644 (file)
 #include "uarraylist.h"
 #include "org_iotivity_ca_CaLeClientInterface.h"
 
-#define TAG PCF("CA_LE_CLIENT")
+#define TAG PCF("OIC_CA_LE_CLIENT")
 
 #define MICROSECS_PER_SEC 1000000
+#define WAIT_TIME_WRITE_CHARACTERISTIC 10 * MICROSECS_PER_SEC
+
+#define GATT_CONNECTION_PRIORITY_BALANCED   0
+#define GATT_FAILURE                        257
+#define GATT_INSUFFICIENT_AUTHENTICATION    5
+#define GATT_INSUFFICIENT_ENCRYPTION        15
+#define GATT_INVALID_ATTRIBUTE_LENGTH       13
+#define GATT_INVALID_OFFSET                 7
+#define GATT_READ_NOT_PERMITTED             2
+#define GATT_REQUEST_NOT_SUPPORTED          6
+#define GATT_WRITE_NOT_PERMITTED            3
 
-static const char METHODID_OBJECTNONPARAM[] = "()Landroid/bluetooth/BluetoothAdapter;";
-static const char CLASSPATH_BT_ADAPTER[] = "android/bluetooth/BluetoothAdapter";
-static const char CLASSPATH_BT_UUID[] = "java/util/UUID";
-static const char CLASSPATH_BT_GATT[] = "android/bluetooth/BluetoothGatt";
+static ca_thread_pool_t g_threadPoolHandle = NULL;
 
 JavaVM *g_jvm;
 static u_arraylist_t *g_deviceList = NULL; // device list to have same UUID
@@ -53,7 +61,6 @@ static u_arraylist_t *g_deviceStateList = NULL;
 
 static CAPacketReceiveCallback g_packetReceiveCallback = NULL;
 static CABLEErrorHandleCallback g_clientErrorCallback;
-static ca_thread_pool_t g_threadPoolHandle = NULL;
 static jobject g_leScanCallback = NULL;
 static jobject g_leGattCallback = NULL;
 static jobject g_context = NULL;
@@ -61,7 +68,6 @@ static jobjectArray g_uuidList = NULL;
 
 // it will be prevent to start send logic when adapter has stopped.
 static bool g_isStartedLEClient = false;
-static bool g_isStartedMulticastServer = false;
 static bool g_isStartedScan = false;
 
 static jbyteArray g_sendBuffer = NULL;
@@ -74,6 +80,9 @@ static ca_cond g_threadCond = NULL;
 static ca_cond g_deviceDescCond = NULL;
 
 static ca_mutex g_threadSendMutex = NULL;
+static ca_mutex g_threadWriteCharacteristicMutex = NULL;
+static ca_cond g_threadWriteCharacteristicCond = NULL;
+static bool g_isSignalSetFlag = false;
 
 static ca_mutex g_bleReqRespClientCbMutex = NULL;
 static ca_mutex g_bleServerBDAddressMutex = NULL;
@@ -82,10 +91,39 @@ static ca_mutex g_deviceListMutex = NULL;
 static ca_mutex g_gattObjectMutex = NULL;
 static ca_mutex g_deviceStateListMutex = NULL;
 
+static ca_mutex g_deviceScanRetryDelayMutex = NULL;
+static ca_cond g_deviceScanRetryDelayCond = NULL;
+
 static ca_mutex g_scanMutex = NULL;
 
 static CABLEDataReceivedCallback g_CABLEClientDataReceivedCallback = NULL;
 
+/**
+ * check if retry logic for connection routine has to be stopped or not.
+ * in case of error value including this method, connection routine has to be stopped.
+ * since there is no retry logic for this error reason in this client.
+ * @param state constant value of bluetoothgatt.
+ * @return true - waiting for background connection in BT platform.
+ *         false - connection routine has to be stopped.
+ */
+static bool CALECheckConnectionStateValue(jint state)
+{
+    switch(state)
+    {
+        case GATT_CONNECTION_PRIORITY_BALANCED:
+        case GATT_FAILURE:
+        case GATT_INSUFFICIENT_AUTHENTICATION:
+        case GATT_INSUFFICIENT_ENCRYPTION:
+        case GATT_INVALID_ATTRIBUTE_LENGTH:
+        case GATT_INVALID_OFFSET:
+        case GATT_READ_NOT_PERMITTED:
+        case GATT_REQUEST_NOT_SUPPORTED:
+        case GATT_WRITE_NOT_PERMITTED:
+            return true;
+    }
+    return false;
+}
+
 //getting jvm
 void CALEClientJniInit()
 {
@@ -166,7 +204,7 @@ error_exit:
     return CA_STATUS_FAILED;
 }
 
-CAResult_t CALEClientInitialize(ca_thread_pool_t handle)
+CAResult_t CALEClientInitialize()
 {
     OIC_LOG(DEBUG, TAG, "CALEClientInitialize");
 
@@ -207,8 +245,6 @@ CAResult_t CALEClientInitialize(ca_thread_pool_t handle)
         return ret;
     }
 
-    g_threadPoolHandle = handle;
-
     ret = CALEClientInitGattMutexVaraibles();
     if (CA_STATUS_OK != ret)
     {
@@ -227,6 +263,8 @@ CAResult_t CALEClientInitialize(ca_thread_pool_t handle)
 
     // init mutex for send logic
     g_threadCond = ca_cond_new();
+    g_threadWriteCharacteristicCond = ca_cond_new();
+    g_deviceScanRetryDelayCond = ca_cond_new();
 
     CALEClientCreateDeviceList();
     CALEClientJNISetContext();
@@ -295,21 +333,25 @@ void CALEClientTerminate()
     if (g_leScanCallback)
     {
         (*env)->DeleteGlobalRef(env, g_leScanCallback);
+        g_leScanCallback = NULL;
     }
 
     if (g_leGattCallback)
     {
         (*env)->DeleteGlobalRef(env, g_leGattCallback);
+        g_leGattCallback = NULL;
     }
 
     if (g_sendBuffer)
     {
         (*env)->DeleteGlobalRef(env, g_sendBuffer);
+        g_sendBuffer = NULL;
     }
 
     if (g_uuidList)
     {
         (*env)->DeleteGlobalRef(env, g_uuidList);
+        g_uuidList = NULL;
     }
 
     CAResult_t ret = CALEClientRemoveAllDeviceState();
@@ -330,17 +372,23 @@ void CALEClientTerminate()
         OIC_LOG(ERROR, TAG, "CALEClientRemoveAllGattObjs has failed");
     }
 
-    g_isStartedMulticastServer = false;
     CALEClientSetScanFlag(false);
-    CALEClientSetSendFinishFlag(false);
+    CALEClientSetSendFinishFlag(true);
 
     CALEClientTerminateGattMutexVariables();
+    CALEClientDestroyJniInterface();
 
     ca_cond_free(g_deviceDescCond);
     ca_cond_free(g_threadCond);
+    ca_cond_free(g_threadWriteCharacteristicCond);
+    ca_cond_free(g_deviceScanRetryDelayCond);
 
     g_deviceDescCond = NULL;
     g_threadCond = NULL;
+    g_threadWriteCharacteristicCond = NULL;
+    g_deviceScanRetryDelayCond = NULL;
+
+    g_isSignalSetFlag = false;
 
     if (isAttached)
     {
@@ -348,6 +396,77 @@ void CALEClientTerminate()
     }
 }
 
+CAResult_t CALEClientDestroyJniInterface()
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientDestroyJniInterface");
+
+    if (!g_jvm)
+    {
+        OIC_LOG(ERROR, TAG, "g_jvm is null");
+        return CA_STATUS_FAILED;
+    }
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return CA_STATUS_FAILED;
+        }
+        isAttached = true;
+    }
+
+    jclass jni_LeInterface = (*env)->FindClass(env, "org/iotivity/ca/CaLeClientInterface");
+    if (!jni_LeInterface)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get CaLeClientInterface class");
+        goto error_exit;
+    }
+
+    jmethodID jni_InterfaceDestroyMethod = (*env)->GetStaticMethodID(env, jni_LeInterface,
+                                                                     "destroyLeInterface",
+                                                                     "()V");
+    if (!jni_InterfaceDestroyMethod)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get CaLeClientInterface destroy method");
+        goto error_exit;
+    }
+
+    (*env)->CallStaticVoidMethod(env, jni_LeInterface, jni_InterfaceDestroyMethod);
+
+    if ((*env)->ExceptionCheck(env))
+    {
+        OIC_LOG(ERROR, TAG, "destroyLeInterface has failed");
+        (*env)->ExceptionDescribe(env);
+        (*env)->ExceptionClear(env);
+        goto error_exit;
+    }
+
+    OIC_LOG(DEBUG, TAG, "Destroy instance for CaLeClientInterface");
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    return CA_STATUS_OK;
+
+error_exit:
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    return CA_STATUS_FAILED;
+}
+
 void CALEClientSendFinish(JNIEnv *env, jobject gatt)
 {
     OIC_LOG(DEBUG, TAG, "CALEClientSendFinish");
@@ -426,49 +545,9 @@ CAResult_t CALEClientStartUnicastServer(const char* address)
 
 CAResult_t CALEClientStartMulticastServer()
 {
-    OIC_LOG(DEBUG, TAG, "CALEClientStartMulticastServer");
-
-    if (g_isStartedMulticastServer)
-    {
-        OIC_LOG(ERROR, TAG, "server is already started..it will be skipped");
-        return CA_STATUS_FAILED;
-    }
-
-    if (!g_jvm)
-    {
-        OIC_LOG(ERROR, TAG, "g_jvm is null");
-        return CA_STATUS_FAILED;
-    }
-
-    bool isAttached = false;
-    JNIEnv* env;
-    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
-    if (JNI_OK != res)
-    {
-        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
-        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
-
-        if (JNI_OK != res)
-        {
-            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
-            return CA_STATUS_FAILED;
-        }
-        isAttached = true;
-    }
-
-    g_isStartedMulticastServer = true;
-    CAResult_t ret = CALEClientStartScan();
-    if (CA_STATUS_OK != ret)
-    {
-        OIC_LOG(ERROR, TAG, "CALEClientStartScan has failed");
-    }
-
-    if (isAttached)
-    {
-        (*g_jvm)->DetachCurrentThread(g_jvm);
-    }
+    OIC_LOG(DEBUG, TAG, "it is not needed in this platform");
 
-    return ret;
+    return CA_NOT_SUPPORTED;
 }
 
 void CALEClientStopUnicastServer()
@@ -479,13 +558,6 @@ void CALEClientStopUnicastServer()
 void CALEClientStopMulticastServer()
 {
     OIC_LOG(DEBUG, TAG, "CALEClientStopMulticastServer");
-    g_isStartedMulticastServer = false;
-    CAResult_t res = CALEClientStopScan();
-    if (CA_STATUS_OK != res)
-    {
-        OIC_LOG(ERROR, TAG, "CALEClientStartScan has failed");
-        return;
-    }
 }
 
 void CALEClientSetCallback(CAPacketReceiveCallback callback)
@@ -498,6 +570,87 @@ void CASetBLEClientErrorHandleCallback(CABLEErrorHandleCallback callback)
     g_clientErrorCallback = callback;
 }
 
+CAResult_t CALEClientIsThereScannedDevices(JNIEnv *env, const char* address)
+{
+    VERIFY_NON_NULL(env, TAG, "env");
+
+    if (!g_deviceList)
+    {
+        return CA_STATUS_FAILED;
+    }
+
+    if (0 == u_arraylist_length(g_deviceList) // multicast
+            || (address && !CALEClientIsDeviceInScanDeviceList(env, address))) // unicast
+    {
+        // Wait for LE peripherals to be discovered.
+
+        // Number of times to wait for discovery to complete.
+        static size_t const RETRIES = 5;
+
+        static uint64_t const TIMEOUT =
+            2 * MICROSECS_PER_SEC;  // Microseconds
+
+        bool devicesDiscovered = false;
+        for (size_t i = 0; i < RETRIES; ++i)
+        {
+            OIC_LOG(DEBUG, TAG, "waiting for target device");
+            if (ca_cond_wait_for(g_deviceDescCond,
+                                 g_threadSendMutex,
+                                 TIMEOUT) == CA_WAIT_SUCCESS)
+            {
+                ca_mutex_lock(g_deviceListMutex);
+                size_t scannedDeviceLen = u_arraylist_length(g_deviceList);
+                ca_mutex_unlock(g_deviceListMutex);
+
+                if (0 < scannedDeviceLen)
+                {
+                    if (!address  // multicast
+                        || (address && CALEClientIsDeviceInScanDeviceList(env, address))) // unicast
+                    {
+                      devicesDiscovered = true;
+                      break;
+                    }
+                    else
+                    {
+                        if (address)
+                        {
+                            OIC_LOG(INFO, TAG, "waiting..");
+
+                            ca_mutex_lock(g_deviceScanRetryDelayMutex);
+                            if (ca_cond_wait_for(g_deviceScanRetryDelayCond,
+                                                 g_deviceScanRetryDelayMutex,
+                                                 MICROSECS_PER_SEC) == CA_WAIT_SUCCESS)
+                            {
+                                OIC_LOG(INFO, TAG, "finish to waiting for target device");
+                                ca_mutex_unlock(g_deviceScanRetryDelayMutex);
+                                break;
+                            }
+                            ca_mutex_unlock(g_deviceScanRetryDelayMutex);
+                            // time out
+
+                            // checking whether a target device is found while waiting for time-out.
+                            if (CALEClientIsDeviceInScanDeviceList(env, address))
+                            {
+                                devicesDiscovered = true;
+                                break;
+                            }
+                        }
+                    }
+                }
+            }
+        }
+
+        // time out for scanning devices
+        if (!devicesDiscovered)
+        {
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    return CA_STATUS_OK;
+}
+
+
 CAResult_t CALEClientSendUnicastMessageImpl(const char* address, const uint8_t* data,
                                       const uint32_t dataLen)
 {
@@ -529,7 +682,15 @@ CAResult_t CALEClientSendUnicastMessageImpl(const char* address, const uint8_t*
 
     ca_mutex_lock(g_threadSendMutex);
 
-    CAResult_t ret = CA_STATUS_OK;
+    CALEClientSetSendFinishFlag(false);
+
+    CAResult_t ret = CALEClientIsThereScannedDevices(env, address);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(INFO, TAG, "there is no scanned device");
+        goto error_exit;
+    }
+
     if (g_context && g_deviceList)
     {
         uint32_t length = u_arraylist_length(g_deviceList);
@@ -573,11 +734,15 @@ CAResult_t CALEClientSendUnicastMessageImpl(const char* address, const uint8_t*
                 if (g_sendBuffer)
                 {
                     (*env)->DeleteGlobalRef(env, g_sendBuffer);
+                    g_sendBuffer = NULL;
                 }
                 jbyteArray jni_arr = (*env)->NewByteArray(env, dataLen);
                 (*env)->SetByteArrayRegion(env, jni_arr, 0, dataLen, (jbyte*) data);
                 g_sendBuffer = (jbyteArray)(*env)->NewGlobalRef(env, jni_arr);
 
+                // Target device to send message is just one.
+                g_targetCnt = 1;
+
                 ret = CALEClientSendData(env, jarrayObj);
                 if (CA_STATUS_OK != ret)
                 {
@@ -592,6 +757,19 @@ CAResult_t CALEClientSendUnicastMessageImpl(const char* address, const uint8_t*
         }
     }
 
+    OIC_LOG(DEBUG, TAG, "connection routine is finished for unicast");
+
+    // wait for finish to send data through "CALeGattServicesDiscoveredCallback"
+    // if there is no connection state.
+    ca_mutex_lock(g_threadMutex);
+    if (!g_isFinishedSendData)
+    {
+        OIC_LOG(DEBUG, TAG, "waiting send finish signal");
+        ca_cond_wait(g_threadCond, g_threadMutex);
+        OIC_LOG(DEBUG, TAG, "the data was sent");
+    }
+    ca_mutex_unlock(g_threadMutex);
+
     if (isAttached)
     {
         (*g_jvm)->DetachCurrentThread(g_jvm);
@@ -607,8 +785,8 @@ CAResult_t CALEClientSendUnicastMessageImpl(const char* address, const uint8_t*
     }
 
     ca_mutex_unlock(g_threadSendMutex);
-    OIC_LOG(INFO, TAG, "unicast - send success");
-    return CA_STATUS_OK;
+    OIC_LOG(INFO, TAG, "unicast - send logic has finished");
+    return CALECheckSendState(address);
 
     // error label.
 error_exit:
@@ -660,39 +838,18 @@ CAResult_t CALEClientSendMulticastMessageImpl(JNIEnv *env, const uint8_t* data,
     if (g_sendBuffer)
     {
         (*env)->DeleteGlobalRef(env, g_sendBuffer);
+        g_sendBuffer = NULL;
     }
 
-    if (0 == u_arraylist_length(g_deviceList))
+    CAResult_t res = CALEClientIsThereScannedDevices(env, NULL);
+    if (CA_STATUS_OK != res)
     {
-        // Wait for LE peripherals to be discovered.
-
-        // Number of times to wait for discovery to complete.
-        static size_t const RETRIES = 5;
-
-        static uint64_t const TIMEOUT =
-            2 * MICROSECS_PER_SEC;  // Microseconds
-
-        bool devicesDiscovered = false;
-        for (size_t i = 0;
-             0 == u_arraylist_length(g_deviceList) && i < RETRIES;
-             ++i)
-        {
-            if (ca_cond_wait_for(g_deviceDescCond,
-                                 g_threadSendMutex,
-                                 TIMEOUT) == 0)
-            {
-                devicesDiscovered = true;
-            }
-        }
-
-        if (!devicesDiscovered)
-        {
-            goto error_exit;
-        }
+        OIC_LOG(INFO, TAG, "there is no scanned device");
+        goto error_exit;
     }
 
     // connect to gatt server
-    CAResult_t res = CALEClientStopScan();
+    res = CALEClientStopScan();
     if (CA_STATUS_OK != res)
     {
         OIC_LOG(ERROR, TAG, "CALEClientStopScan has failed");
@@ -738,16 +895,17 @@ CAResult_t CALEClientSendMulticastMessageImpl(JNIEnv *env, const uint8_t* data,
         (*env)->ReleaseStringUTFChars(env, jni_address, address);
     }
 
-    OIC_LOG(DEBUG, TAG, "connection routine is finished");
+    OIC_LOG(DEBUG, TAG, "connection routine is finished for multicast");
 
     // wait for finish to send data through "CALeGattServicesDiscoveredCallback"
+    ca_mutex_lock(g_threadMutex);
     if (!g_isFinishedSendData)
     {
-        ca_mutex_lock(g_threadMutex);
+        OIC_LOG(DEBUG, TAG, "waiting send finish signal");
         ca_cond_wait(g_threadCond, g_threadMutex);
-        OIC_LOG(DEBUG, TAG, "the data was sent for All devices");
-        ca_mutex_unlock(g_threadMutex);
+        OIC_LOG(DEBUG, TAG, "the data was sent");
     }
+    ca_mutex_unlock(g_threadMutex);
 
     // start LE Scan again
     res = CALEClientStartScan();
@@ -795,6 +953,8 @@ CAResult_t CALECheckSendState(const char* address)
         ca_mutex_unlock(g_deviceStateListMutex);
         return CA_SEND_FAILED;
     }
+
+    OIC_LOG(INFO, TAG, "sendstate is STATE_SEND_SUCCESS");
     ca_mutex_unlock(g_deviceStateListMutex);
     return CA_STATUS_OK;
 }
@@ -805,32 +965,59 @@ CAResult_t CALEClientSendData(JNIEnv *env, jobject device)
     VERIFY_NON_NULL(device, TAG, "device is null");
     VERIFY_NON_NULL(env, TAG, "env is null");
 
-    jstring jni_address = CALEGetAddressFromBTDevice(env, device);
-    if (!jni_address)
-    {
-        OIC_LOG(ERROR, TAG, "CALEGetAddressFromBTDevice has failed");
-        return CA_STATUS_FAILED;
-    }
-
-    const char* address = (*env)->GetStringUTFChars(env, jni_address, NULL);
-    if (!address)
+    // get BLE address from bluetooth device object.
+    char* address = NULL;
+    CALEState_t* state = NULL;
+    jstring jni_address = CALEClientGetLEAddressFromBTDevice(env, device);
+    if (jni_address)
     {
-        OIC_LOG(ERROR, TAG, "address is not available");
-        return CA_STATUS_FAILED;
+        OIC_LOG(INFO, TAG, "there is gatt object..it's not first connection");
+        address = (char*)(*env)->GetStringUTFChars(env, jni_address, NULL);
+        if (!address)
+        {
+            OIC_LOG(ERROR, TAG, "address is not available");
+            return CA_STATUS_FAILED;
+        }
+        ca_mutex_lock(g_deviceStateListMutex);
+        state = CALEClientGetStateInfo(address);
+        ca_mutex_unlock(g_deviceStateListMutex);
+        (*env)->ReleaseStringUTFChars(env, jni_address, address);
     }
 
-    ca_mutex_lock(g_deviceStateListMutex);
-    CALEState_t* state = CALEClientGetStateInfo(address);
-    ca_mutex_unlock(g_deviceStateListMutex);
     if (!state)
     {
         OIC_LOG(DEBUG, TAG, "state is empty..start to connect LE");
-        CAResult_t ret = CALEClientConnect(env, device, JNI_FALSE, g_leGattCallback);
-        if (CA_STATUS_OK != ret)
+
+        // cancel previous connection request before connection
+        // if there is gatt object in g_gattObjectList.
+        if (jni_address)
         {
-            OIC_LOG(ERROR, TAG, "CALEClientConnect has failed");
+            address = (char*)(*env)->GetStringUTFChars(env, jni_address, NULL);
+            if (!address)
+            {
+                OIC_LOG(ERROR, TAG, "address is not available");
+                return CA_STATUS_FAILED;
+            }
+
+            jobject gatt = CALEClientGetGattObjInList(env, address);
+            if (gatt)
+            {
+                CAResult_t res = CALEClientDisconnect(env, gatt);
+                if (CA_STATUS_OK != res)
+                {
+                    OIC_LOG(INFO, TAG, "there is no gatt object");
+                }
+            }
             (*env)->ReleaseStringUTFChars(env, jni_address, address);
-            return ret;
+        }
+
+        // connection request
+        jobject newGatt = CALEClientConnect(env, device,
+                                            JNI_FALSE);
+        if (NULL == newGatt)
+        {
+            OIC_LOG(ERROR, TAG, "CALEClientConnect has failed");
+            return CA_STATUS_FAILED;
         }
     }
     else
@@ -838,6 +1025,19 @@ CAResult_t CALEClientSendData(JNIEnv *env, jobject device)
         if (STATE_CONNECTED == state->connectedState)
         {
             OIC_LOG(INFO, TAG, "GATT has already connected");
+            if (!jni_address)
+            {
+                OIC_LOG(ERROR, TAG, "jni_address is not available");
+                return CA_STATUS_FAILED;
+            }
+
+            address = (char*)(*env)->GetStringUTFChars(env, jni_address, NULL);
+            if (!address)
+            {
+                OIC_LOG(ERROR, TAG, "address is not available");
+                return CA_STATUS_FAILED;
+            }
+
             jobject gatt = CALEClientGetGattObjInList(env, address);
             if (!gatt)
             {
@@ -846,28 +1046,53 @@ CAResult_t CALEClientSendData(JNIEnv *env, jobject device)
                 return CA_STATUS_FAILED;
             }
 
-            CAResult_t ret = CALEClientWriteCharacteristic(env, gatt);
+            CAResult_t ret = CALESetValueAndWriteCharacteristic(env, gatt);
             if (CA_STATUS_OK != ret)
             {
-                OIC_LOG(ERROR, TAG, "CALEClientWriteCharacteristic has failed");
+                OIC_LOG(ERROR, TAG, "CALESetValueAndWriteCharacteristic has failed");
                 (*env)->ReleaseStringUTFChars(env, jni_address, address);
                 return ret;
             }
+            (*env)->ReleaseStringUTFChars(env, jni_address, address);
         }
         else
         {
+            OIC_LOG(INFO, TAG, "STATE_DISCONNECTED - start to connect LE");
+
+            // cancel previous connection request before connection
+            // if there is gatt object in g_gattObjectList.
+            if (jni_address)
+            {
+                address = (char*)(*env)->GetStringUTFChars(env, jni_address, NULL);
+                if (!address)
+                {
+                    OIC_LOG(ERROR, TAG, "address is not available");
+                    return CA_STATUS_FAILED;
+                }
+
+                jobject gatt = CALEClientGetGattObjInList(env, address);
+                if (gatt)
+                {
+                    CAResult_t res = CALEClientDisconnect(env, gatt);
+                    if (CA_STATUS_OK != res)
+                    {
+                        OIC_LOG(INFO, TAG, "there is no gatt object");
+                    }
+                }
+                (*env)->ReleaseStringUTFChars(env, jni_address, address);
+            }
+
             OIC_LOG(DEBUG, TAG, "start to connect LE");
-            CAResult_t ret = CALEClientConnect(env, device, JNI_FALSE, g_leGattCallback);
-            if (CA_STATUS_OK != ret)
+            jobject gatt = CALEClientConnect(env, device,
+                                             CALEClientGetAutoConnectFlag(env, jni_address));
+            if (NULL == gatt)
             {
                 OIC_LOG(ERROR, TAG, "CALEClientConnect has failed");
-                (*env)->ReleaseStringUTFChars(env, jni_address, address);
-                return ret;
+                return CA_STATUS_FAILED;
             }
         }
     }
 
-    (*env)->ReleaseStringUTFChars(env, jni_address, address);
     return CA_STATUS_OK;
 }
 
@@ -876,15 +1101,8 @@ jstring CALEClientGetAddressFromGattObj(JNIEnv *env, jobject gatt)
     VERIFY_NON_NULL_RET(gatt, TAG, "gatt is null", NULL);
     VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
 
-    jclass jni_cid_gattdevice_list = (*env)->FindClass(env, CLASSPATH_BT_GATT);
-    if (!jni_cid_gattdevice_list)
-    {
-        OIC_LOG(ERROR, TAG, "jni_cid_gattdevice_list is null");
-        return NULL;
-    }
-
-    jmethodID jni_mid_getDevice = (*env)->GetMethodID(env, jni_cid_gattdevice_list, "getDevice",
-                                                      "()Landroid/bluetooth/BluetoothDevice;");
+    jmethodID jni_mid_getDevice = CALEGetJNIMethodID(env, CLASSPATH_BT_GATT, "getDevice",
+                                                     "()Landroid/bluetooth/BluetoothDevice;");
     if (!jni_mid_getDevice)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_getDevice is null");
@@ -918,16 +1136,9 @@ CAResult_t CALEClientGattClose(JNIEnv *env, jobject bluetoothGatt)
     VERIFY_NON_NULL(bluetoothGatt, TAG, "bluetoothGatt is null");
     VERIFY_NON_NULL(env, TAG, "env is null");
 
-    // get BluetoothGatt class
-    OIC_LOG(DEBUG, TAG, "get BluetoothGatt class");
-    jclass jni_cid_BluetoothGatt = (*env)->FindClass(env, CLASSPATH_BT_GATT);
-    if (!jni_cid_BluetoothGatt)
-    {
-        OIC_LOG(ERROR, TAG, "jni_cid_BluetoothGatt is null");
-        return CA_STATUS_FAILED;
-    }
-
-    jmethodID jni_mid_closeGatt = (*env)->GetMethodID(env, jni_cid_BluetoothGatt, "close", "()V");
+    // get BluetoothGatt method
+    OIC_LOG(DEBUG, TAG, "get BluetoothGatt method");
+    jmethodID jni_mid_closeGatt = CALEGetJNIMethodID(env, CLASSPATH_BT_GATT, "close", "()V");
     if (!jni_mid_closeGatt)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_closeGatt is null");
@@ -951,12 +1162,6 @@ CAResult_t CALEClientGattClose(JNIEnv *env, jobject bluetoothGatt)
 
 CAResult_t CALEClientStartScan()
 {
-    if (!g_isStartedMulticastServer)
-    {
-        OIC_LOG(ERROR, TAG, "server is not started yet..scan will be passed");
-        return CA_STATUS_FAILED;
-    }
-
     if (!g_isStartedLEClient)
     {
         OIC_LOG(ERROR, TAG, "LE client is not started");
@@ -999,17 +1204,20 @@ CAResult_t CALEClientStartScan()
     {
 #ifdef UUID_SCAN
         ret = CALEClientStartScanWithUUIDImpl(env, g_uuidList, g_leScanCallback);
-        if(CA_STATUS_OK != ret)
-        {
-            OIC_LOG(ERROR, TAG, "CALEClientStartScanWithUUIDImpl has failed");
-        }
 #else
         ret = CALEClientStartScanImpl(env, g_leScanCallback);
+#endif
         if (CA_STATUS_OK != ret)
         {
-            OIC_LOG(ERROR, TAG, "CALEClientStartScanImpl has failed");
+            if (CA_ADAPTER_NOT_ENABLED == ret)
+            {
+                OIC_LOG(DEBUG, TAG, "Adapter is disabled");
+            }
+            else
+            {
+                OIC_LOG(ERROR, TAG, "start scan has failed");
+            }
         }
-#endif
     }
 
     if (isAttached)
@@ -1027,7 +1235,7 @@ CAResult_t CALEClientStartScanImpl(JNIEnv *env, jobject callback)
 
     if (!CALEIsEnableBTAdapter(env))
     {
-        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        OIC_LOG(INFO, TAG, "BT adapter is not enabled");
         return CA_ADAPTER_NOT_ENABLED;
     }
 
@@ -1073,8 +1281,7 @@ CAResult_t CALEClientStartScanImpl(JNIEnv *env, jobject callback)
                                                              jni_mid_startLeScan, callback);
     if (!jni_obj_startLeScan)
     {
-        OIC_LOG(ERROR, TAG, "startLeScan is failed");
-        return CA_STATUS_FAILED;
+        OIC_LOG(INFO, TAG, "startLeScan is failed");
     }
     else
     {
@@ -1093,7 +1300,7 @@ CAResult_t CALEClientStartScanWithUUIDImpl(JNIEnv *env, jobjectArray uuids, jobj
 
     if (!CALEIsEnableBTAdapter(env))
     {
-        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        OIC_LOG(INFO, TAG, "BT adapter is not enabled");
         return CA_ADAPTER_NOT_ENABLED;
     }
 
@@ -1138,8 +1345,7 @@ CAResult_t CALEClientStartScanWithUUIDImpl(JNIEnv *env, jobjectArray uuids, jobj
                                                              jni_mid_startLeScan, uuids, callback);
     if (!jni_obj_startLeScan)
     {
-        OIC_LOG(ERROR, TAG, "startLeScan With UUID is failed");
-        return CA_STATUS_FAILED;
+        OIC_LOG(INFO, TAG, "startLeScan With UUID is failed");
     }
     else
     {
@@ -1216,7 +1422,14 @@ CAResult_t CALEClientStopScan()
     CAResult_t ret = CALEClientStopScanImpl(env, g_leScanCallback);
     if (CA_STATUS_OK != ret)
     {
-        OIC_LOG(ERROR, TAG, "CALEClientStopScanImpl has failed");
+        if (CA_ADAPTER_NOT_ENABLED == ret)
+        {
+            OIC_LOG(DEBUG, TAG, "Adapter is disabled");
+        }
+        else
+        {
+            OIC_LOG(ERROR, TAG, "CALEClientStopScanImpl has failed");
+        }
     }
     else
     {
@@ -1246,7 +1459,7 @@ CAResult_t CALEClientStopScanImpl(JNIEnv *env, jobject callback)
 
     if (!CALEIsEnableBTAdapter(env))
     {
-        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        OIC_LOG(INFO, TAG, "BT adapter is not enabled");
         return CA_ADAPTER_NOT_ENABLED;
     }
 
@@ -1301,89 +1514,276 @@ CAResult_t CALEClientStopScanImpl(JNIEnv *env, jobject callback)
     return CA_STATUS_OK;
 }
 
-CAResult_t CALEClientConnect(JNIEnv *env, jobject bluetoothDevice, jboolean autoconnect,
-                             jobject callback)
+CAResult_t CALEClientSetAutoConnectFlag(JNIEnv *env, jstring jni_address, jboolean flag)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEClientSetAutoConnectFlag");
+    VERIFY_NON_NULL(env, TAG, "env");
+    VERIFY_NON_NULL(jni_address, TAG, "jni_address");
+
+    ca_mutex_lock(g_deviceStateListMutex);
+
+    char* address = (char*)(*env)->GetStringUTFChars(env, jni_address, NULL);
+    if (!address)
+    {
+        OIC_LOG(ERROR, TAG, "address is not available");
+        return CA_STATUS_FAILED;
+    }
+
+    if (CALEClientIsDeviceInList(address))
+    {
+        CALEState_t* curState = CALEClientGetStateInfo(address);
+        if(!curState)
+        {
+            OIC_LOG(ERROR, TAG, "curState is null");
+            (*env)->ReleaseStringUTFChars(env, jni_address, address);
+            ca_mutex_unlock(g_deviceStateListMutex);
+            return CA_STATUS_FAILED;
+        }
+        OIC_LOG_V(INFO, TAG, "auto connect flag is set %d", flag);
+
+        curState->autoConnectFlag = flag;
+    }
+
+    (*env)->ReleaseStringUTFChars(env, jni_address, address);
+    ca_mutex_unlock(g_deviceStateListMutex);
+    OIC_LOG(DEBUG, TAG, "OUT - CALEClientSetAutoConnectFlag");
+    return CA_STATUS_OK;
+}
+
+jboolean CALEClientGetAutoConnectFlag(JNIEnv *env, jstring jni_address)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEClientGetAutoConnectFlag");
+    VERIFY_NON_NULL_RET(env, TAG, "env", false);
+    VERIFY_NON_NULL_RET(jni_address, TAG, "jni_address", false);
+
+    ca_mutex_lock(g_deviceStateListMutex);
+
+    char* address = (char*)(*env)->GetStringUTFChars(env, jni_address, NULL);
+    if (!address)
+    {
+        OIC_LOG(ERROR, TAG, "address is not available");
+        return JNI_FALSE;
+    }
+
+    CALEState_t* curState = CALEClientGetStateInfo(address);
+    if(!curState)
+    {
+        OIC_LOG(INFO, TAG, "there is no information. auto connect flag is false");
+        (*env)->ReleaseStringUTFChars(env, jni_address, address);
+        ca_mutex_unlock(g_deviceStateListMutex);
+        return JNI_FALSE;
+    }
+    OIC_LOG_V(INFO, TAG, "auto connect flag is %d", curState->autoConnectFlag);
+
+    (*env)->ReleaseStringUTFChars(env, jni_address, address);
+    ca_mutex_unlock(g_deviceStateListMutex);
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEClientGetAutoConnectFlag");
+    return curState->autoConnectFlag;
+}
+
+jobject CALEClientConnect(JNIEnv *env, jobject bluetoothDevice, jboolean autoconnect)
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientConnect");
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
+    VERIFY_NON_NULL_RET(bluetoothDevice, TAG, "bluetoothDevice is null", NULL);
+
+    // get gatt object from Bluetooth Device object for closeProfileProxy(..)
+    jstring jni_address = CALEClientGetLEAddressFromBTDevice(env, bluetoothDevice);
+    if (jni_address)
+    {
+        const char* address = (*env)->GetStringUTFChars(env, jni_address, NULL);
+        if (!address)
+        {
+            OIC_LOG(ERROR, TAG, "address is not available");
+            return NULL;
+        }
+
+        // close the gatt service
+        jobject gatt = CALEClientGetGattObjInList(env, address);
+        if (gatt)
+        {
+            CAResult_t res = CALEClientCloseProfileProxy(env, gatt);
+            if (CA_STATUS_OK != res)
+            {
+                OIC_LOG(ERROR, TAG, "CALEClientCloseProfileProxy has failed");
+                (*env)->ReleaseStringUTFChars(env, jni_address, address);
+                return NULL;
+            }
+
+            // clean previous gatt object after close profile service
+            res = CALEClientRemoveGattObjForAddr(env, jni_address);
+            if (CA_STATUS_OK != res)
+            {
+                OIC_LOG(ERROR, TAG, "CALEClientRemoveGattObjForAddr has failed");
+                (*env)->ReleaseStringUTFChars(env, jni_address, address);
+                return NULL;
+            }
+        }
+        (*env)->ReleaseStringUTFChars(env, jni_address, address);
+    }
+
+    jobject newGatt = CALEClientGattConnect(env, bluetoothDevice, autoconnect);
+    if (!newGatt)
+    {
+        OIC_LOG(DEBUG, TAG, "re-connection will be started");
+        return NULL;
+    }
+
+    // add new gatt object into g_gattObjectList
+    CAResult_t res = CALEClientAddGattobjToList(env, newGatt);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "CALEClientAddGattobjToList has failed");
+        return NULL;
+    }
+
+    return newGatt;
+}
+
+jobject CALEClientGattConnect(JNIEnv *env, jobject bluetoothDevice, jboolean autoconnect)
 {
     OIC_LOG(DEBUG, TAG, "GATT CONNECT");
-    VERIFY_NON_NULL(env, TAG, "env is null");
-    VERIFY_NON_NULL(bluetoothDevice, TAG, "bluetoothDevice is null");
-    VERIFY_NON_NULL(callback, TAG, "callback is null");
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
+    VERIFY_NON_NULL_RET(bluetoothDevice, TAG, "bluetoothDevice is null", NULL);
+
+    if (!g_leGattCallback)
+    {
+        OIC_LOG(INFO, TAG, "g_leGattCallback is null");
+        return NULL;
+    }
 
     if (!CALEIsEnableBTAdapter(env))
     {
-        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
-        return CA_ADAPTER_NOT_ENABLED;
+        OIC_LOG(INFO, TAG, "BT adapter is not enabled");
+        return NULL;
     }
 
     jstring jni_address = CALEGetAddressFromBTDevice(env, bluetoothDevice);
     if (!jni_address)
     {
         OIC_LOG(ERROR, TAG, "bleConnect: CALEGetAddressFromBTDevice is null");
-        return CA_STATUS_FAILED;
-    }
-
-    // get BluetoothDevice class
-    OIC_LOG(DEBUG, TAG, "get BluetoothDevice class");
-    jclass jni_cid_BluetoothDevice = (*env)->FindClass(env, "android/bluetooth/BluetoothDevice");
-    if (!jni_cid_BluetoothDevice)
-    {
-        OIC_LOG(ERROR, TAG, "bleConnect: jni_cid_BluetoothDevice is null");
-        return CA_STATUS_FAILED;
+        return NULL;
     }
 
-    // get connectGatt method
-    OIC_LOG(DEBUG, TAG, "get connectGatt method");
-    jmethodID jni_mid_connectGatt = (*env)->GetMethodID(env, jni_cid_BluetoothDevice, "connectGatt",
-                                                        "(Landroid/content/Context;ZLandroid/"
-                                                        "bluetooth/BluetoothGattCallback;)"
-                                                        "Landroid/bluetooth/BluetoothGatt;");
+    // get BluetoothDevice method
+    OIC_LOG(DEBUG, TAG, "get BluetoothDevice method");
+    jmethodID jni_mid_connectGatt = CALEGetJNIMethodID(env, "android/bluetooth/BluetoothDevice",
+                                                       "connectGatt",
+                                                       "(Landroid/content/Context;ZLandroid/"
+                                                       "bluetooth/BluetoothGattCallback;)"
+                                                       "Landroid/bluetooth/BluetoothGatt;");
     if (!jni_mid_connectGatt)
     {
         OIC_LOG(ERROR, TAG, "bleConnect: jni_mid_connectGatt is null");
-        return CA_STATUS_FAILED;
+        return NULL;
     }
 
-    OIC_LOG(DEBUG, TAG, "Call object method - connectGatt");
+    OIC_LOG(INFO, TAG, "CALL API - connectGatt");
     jobject jni_obj_connectGatt = (*env)->CallObjectMethod(env, bluetoothDevice,
                                                            jni_mid_connectGatt,
                                                            NULL,
-                                                           autoconnect, callback);
+                                                           autoconnect, g_leGattCallback);
     if (!jni_obj_connectGatt)
     {
-        OIC_LOG(ERROR, TAG, "CALL API - connectGatt was failed..it will be removed");
+        OIC_LOG(ERROR, TAG, "connectGatt was failed..it will be removed");
         CALEClientRemoveDeviceInScanDeviceList(env, jni_address);
         CALEClientUpdateSendCnt(env);
-        return CA_STATUS_FAILED;
+        return NULL;
     }
     else
     {
         OIC_LOG(DEBUG, TAG, "le connecting..please wait..");
     }
-    return CA_STATUS_OK;
+    return jni_obj_connectGatt;
 }
 
-CAResult_t CALEClientDisconnect(JNIEnv *env, jobject bluetoothGatt)
+CAResult_t CALEClientCloseProfileProxy(JNIEnv *env, jobject gatt)
 {
-    OIC_LOG(DEBUG, TAG, "GATT DISCONNECT");
+    OIC_LOG(DEBUG, TAG, "IN - CALEClientCloseProfileProxy");
+
     VERIFY_NON_NULL(env, TAG, "env is null");
-    VERIFY_NON_NULL(bluetoothGatt, TAG, "bluetoothGatt is null");
+    VERIFY_NON_NULL(gatt, TAG, "gatt is null");
 
-    if (!CALEIsEnableBTAdapter(env))
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADAPTER);
+    if (!jni_cid_BTAdapter)
     {
-        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
-        return CA_ADAPTER_NOT_ENABLED;
+        OIC_LOG(ERROR, TAG, "jni_cid_BTAdapter is null");
+        return CA_STATUS_FAILED;
     }
 
-    // get BluetoothGatt class
-    jclass jni_cid_BluetoothGatt = (*env)->FindClass(env, CLASSPATH_BT_GATT);
-    if (!jni_cid_BluetoothGatt)
+    // get remote bt adapter method
+    jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
+                                                                    "getDefaultAdapter",
+                                                                    METHODID_OBJECTNONPARAM);
+    if (!jni_mid_getDefaultAdapter)
     {
-        OIC_LOG(ERROR, TAG, "jni_cid_BluetoothGatt is null");
+        OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null");
         return CA_STATUS_FAILED;
     }
 
+    // gat bt adapter object
+    jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+                                                               jni_mid_getDefaultAdapter);
+    if (!jni_obj_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_BTAdapter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // get closeProfileProxy method
+    jmethodID jni_mid_closeProfileProxy = (*env)->GetMethodID(env, jni_cid_BTAdapter,
+                                                              "closeProfileProxy",
+                                                              "(ILandroid/bluetooth/"
+                                                              "BluetoothProfile;)V");
+    if (!jni_mid_closeProfileProxy)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_closeProfileProxy is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jclass jni_cid_BTProfile = (*env)->FindClass(env, CLASSPATH_BT_PROFILE);
+    if (!jni_cid_BTProfile)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BTProfile is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // GATT - Constant value : 7 (0x00000007)
+    jfieldID id_gatt = (*env)->GetStaticFieldID(env, jni_cid_BTProfile,
+                                                "GATT", "I");
+    if (!id_gatt)
+    {
+        OIC_LOG(ERROR, TAG, "id_gatt is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jint jni_gatt = (*env)->GetStaticIntField(env, jni_cid_BTProfile, id_gatt);
+
+    OIC_LOG(DEBUG, TAG, "CALL API - close the connection of the profile proxy to the Service");
+    (*env)->CallVoidMethod(env, jni_obj_BTAdapter, jni_mid_closeProfileProxy, jni_gatt, gatt);
+    if ((*env)->ExceptionCheck(env))
+    {
+        OIC_LOG(ERROR, TAG, "closeProfileProxy has failed");
+        (*env)->ExceptionDescribe(env);
+        (*env)->ExceptionClear(env);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEClientCloseProfileProxy");
+    return CA_STATUS_OK;
+}
+
+
+CAResult_t CALEClientDisconnect(JNIEnv *env, jobject bluetoothGatt)
+{
+    OIC_LOG(DEBUG, TAG, "GATT DISCONNECT");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(bluetoothGatt, TAG, "bluetoothGatt is null");
+
+    // get BluetoothGatt method
     OIC_LOG(DEBUG, TAG, "get gatt disconnect method");
-    jmethodID jni_mid_disconnectGatt = (*env)->GetMethodID(env, jni_cid_BluetoothGatt,
+    jmethodID jni_mid_disconnectGatt  = CALEGetJNIMethodID(env, CLASSPATH_BT_GATT,
                                                            "disconnect", "()V");
     if (!jni_mid_disconnectGatt)
     {
@@ -1392,6 +1792,7 @@ CAResult_t CALEClientDisconnect(JNIEnv *env, jobject bluetoothGatt)
     }
 
     // call disconnect gatt method
+    OIC_LOG(DEBUG, TAG, "CALL API - request disconnect gatt");
     (*env)->CallVoidMethod(env, bluetoothGatt, jni_mid_disconnectGatt);
     if ((*env)->ExceptionCheck(env))
     {
@@ -1413,13 +1814,15 @@ CAResult_t CALEClientDisconnectAll(JNIEnv *env)
 
     if (!g_gattObjectList)
     {
-        OIC_LOG(ERROR, TAG, "g_gattObjectList is null");
-        return CA_STATUS_FAILED;
+        OIC_LOG(DEBUG, TAG, "already removed for g_gattObjectList");
+        return CA_STATUS_OK;
     }
 
     uint32_t length = u_arraylist_length(g_gattObjectList);
+    OIC_LOG_V(DEBUG, TAG, "list length : %d", length);
     for (uint32_t index = 0; index < length; index++)
     {
+        OIC_LOG(DEBUG, TAG, "start CALEClientDisconnectAll");
         jobject jarrayObj = (jobject) u_arraylist_get(g_gattObjectList, index);
         if (!jarrayObj)
         {
@@ -1434,9 +1837,73 @@ CAResult_t CALEClientDisconnectAll(JNIEnv *env)
         }
     }
 
-    OICFree(g_gattObjectList);
-    g_gattObjectList = NULL;
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEClientDisconnectforAddress(JNIEnv *env, jstring remote_address)
+{
+    OIC_LOG(DEBUG, TAG, "IN-CALEClientDisconnectforAddress");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+
+    if (!g_gattObjectList)
+    {
+        OIC_LOG(DEBUG, TAG, "already removed for g_gattObjectList");
+        return CA_STATUS_OK;
+    }
+
+    char* address = (char*)(*env)->GetStringUTFChars(env, remote_address, NULL);
+    if (!address)
+    {
+        OIC_LOG(ERROR, TAG, "address is null");
+        return CA_STATUS_FAILED;
+    }
+
+    uint32_t length = u_arraylist_length(g_gattObjectList);
+    for (uint32_t index = 0; index < length; index++)
+    {
+        jobject jarrayObj = (jobject) u_arraylist_get(g_gattObjectList, index);
+        if (!jarrayObj)
+        {
+            OIC_LOG(ERROR, TAG, "jarrayObj is null");
+            continue;
+        }
+
+        jstring jni_setAddress = CALEClientGetAddressFromGattObj(env, jarrayObj);
+        if (!jni_setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "jni_setAddress is null");
+            (*env)->ReleaseStringUTFChars(env, remote_address, address);
+            return CA_STATUS_FAILED;
+        }
+
+        const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
+        if (!setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "setAddress is null");
+            (*env)->ReleaseStringUTFChars(env, remote_address, address);
+            return CA_STATUS_FAILED;
+        }
+
+        OIC_LOG_V(DEBUG, TAG, "target address : %s, set address : %s", address, setAddress);
+        if (!strcmp(address, setAddress))
+        {
+            CAResult_t res = CALEClientDisconnect(env, jarrayObj);
+            if (CA_STATUS_OK != res)
+            {
+                OIC_LOG(ERROR, TAG, "CALEClientDisconnect has failed");
+                (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+                (*env)->ReleaseStringUTFChars(env, remote_address, address);
+                return CA_STATUS_FAILED;
+            }
+            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+            (*env)->ReleaseStringUTFChars(env, remote_address, address);
+            return CA_STATUS_OK;
+        }
+        (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+    }
+    (*env)->ReleaseStringUTFChars(env, remote_address, address);
 
+    OIC_LOG(DEBUG, TAG, "OUT-CALEClientDisconnectforAddress");
     return CA_STATUS_OK;
 }
 
@@ -1447,27 +1914,20 @@ CAResult_t CALEClientDiscoverServices(JNIEnv *env, jobject bluetoothGatt)
 
     if (!CALEIsEnableBTAdapter(env))
     {
-        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        OIC_LOG(INFO, TAG, "BT adapter is not enabled");
         return CA_ADAPTER_NOT_ENABLED;
     }
 
-    // get BluetoothGatt class
-    OIC_LOG(DEBUG, TAG, "get BluetoothGatt class");
-    jclass jni_cid_BluetoothGatt = (*env)->FindClass(env, CLASSPATH_BT_GATT);
-    if (!jni_cid_BluetoothGatt)
-    {
-        OIC_LOG(ERROR, TAG, "jni_cid_BluetoothGatt is null");
-        return CA_STATUS_FAILED;
-    }
-
-    OIC_LOG(DEBUG, TAG, "discovery gatt services method");
-    jmethodID jni_mid_discoverServices = (*env)->GetMethodID(env, jni_cid_BluetoothGatt,
-                                                             "discoverServices", "()Z");
+    // get BluetoothGatt.discoverServices method
+    OIC_LOG(DEBUG, TAG, "get BluetoothGatt.discoverServices method");
+    jmethodID jni_mid_discoverServices = CALEGetJNIMethodID(env, CLASSPATH_BT_GATT,
+                                                            "discoverServices", "()Z");
     if (!jni_mid_discoverServices)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_discoverServices is null");
         return CA_STATUS_FAILED;
     }
+
     // call disconnect gatt method
     OIC_LOG(DEBUG, TAG, "CALL API - request discovery gatt services");
     jboolean ret = (*env)->CallBooleanMethod(env, bluetoothGatt, jni_mid_discoverServices);
@@ -1480,10 +1940,43 @@ CAResult_t CALEClientDiscoverServices(JNIEnv *env, jobject bluetoothGatt)
     return CA_STATUS_OK;
 }
 
-CAResult_t CALEClientWriteCharacteristic(JNIEnv *env, jobject gatt)
+static void CALEWriteCharacteristicThread(void* object)
+{
+    VERIFY_NON_NULL_VOID(object, TAG, "object is null");
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return;
+        }
+        isAttached = true;
+    }
+
+    jobject gatt = (jobject)object;
+    CAResult_t ret = CALESetValueAndWriteCharacteristic(env, gatt);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALESetValueAndWriteCharacteristic has failed");
+    }
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+}
+
+CAResult_t CALESetValueAndWriteCharacteristic(JNIEnv* env, jobject gatt)
 {
-    VERIFY_NON_NULL(env, TAG, "env is null");
     VERIFY_NON_NULL(gatt, TAG, "gatt is null");
+    VERIFY_NON_NULL(env, TAG, "env is null");
 
     // send data
     jobject jni_obj_character = CALEClientCreateGattCharacteristic(env, gatt, g_sendBuffer);
@@ -1497,14 +1990,53 @@ CAResult_t CALEClientWriteCharacteristic(JNIEnv *env, jobject gatt)
     if (CA_STATUS_OK != ret)
     {
         CALEClientSendFinish(env, gatt);
-        return ret;
+        return CA_STATUS_FAILED;
+    }
+
+    // wait for callback for write Characteristic with success to sent data
+    OIC_LOG_V(DEBUG, TAG, "callback flag is %d", g_isSignalSetFlag);
+    ca_mutex_lock(g_threadWriteCharacteristicMutex);
+    if (!g_isSignalSetFlag)
+    {
+        OIC_LOG(DEBUG, TAG, "wait for callback to notify writeCharacteristic is success");
+        if (CA_WAIT_SUCCESS != ca_cond_wait_for(g_threadWriteCharacteristicCond,
+                                  g_threadWriteCharacteristicMutex,
+                                  WAIT_TIME_WRITE_CHARACTERISTIC))
+        {
+            OIC_LOG(ERROR, TAG, "there is no response. write has failed");
+            g_isSignalSetFlag = false;
+            ca_mutex_unlock(g_threadWriteCharacteristicMutex);
+            return CA_STATUS_FAILED;
+        }
+    }
+    // reset flag set by writeCharacteristic Callback
+    g_isSignalSetFlag = false;
+    ca_mutex_unlock(g_threadWriteCharacteristicMutex);
+
+    OIC_LOG(INFO, TAG, "writeCharacteristic success!!");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEClientWriteCharacteristic(JNIEnv *env, jobject gatt)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEClientWriteCharacteristic");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(gatt, TAG, "gatt is null");
+
+    jobject gattParam = (*env)->NewGlobalRef(env, gatt);
+    if (CA_STATUS_OK != ca_thread_pool_add_task(g_threadPoolHandle,
+                                                CALEWriteCharacteristicThread, (void*)gattParam))
+    {
+        OIC_LOG(ERROR, TAG, "Failed to create read thread!");
+        return CA_STATUS_FAILED;
     }
 
+    OIC_LOG(DEBUG, TAG, "OUT - CALEClientWriteCharacteristic");
     return CA_STATUS_OK;
 }
 
 CAResult_t CALEClientWriteCharacteristicImpl(JNIEnv *env, jobject bluetoothGatt,
-                                           jobject gattCharacteristic)
+                                             jobject gattCharacteristic)
 {
     OIC_LOG(DEBUG, TAG, "WRITE GATT CHARACTERISTIC");
     VERIFY_NON_NULL(env, TAG, "env is null");
@@ -1513,24 +2045,16 @@ CAResult_t CALEClientWriteCharacteristicImpl(JNIEnv *env, jobject bluetoothGatt,
 
     if (!CALEIsEnableBTAdapter(env))
     {
-        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
-        return CA_STATUS_FAILED;
-    }
-
-    // get BluetoothGatt class
-    OIC_LOG(DEBUG, TAG, "get BluetoothGatt class");
-    jclass jni_cid_BluetoothGatt = (*env)->FindClass(env, CLASSPATH_BT_GATT);
-    if (!jni_cid_BluetoothGatt)
-    {
-        OIC_LOG(ERROR, TAG, "jni_cid_BluetoothGatt is null");
+        OIC_LOG(INFO, TAG, "BT adapter is not enabled");
         return CA_STATUS_FAILED;
     }
 
+    // get BluetoothGatt.write characteristic method
     OIC_LOG(DEBUG, TAG, "write characteristic method");
-    jmethodID jni_mid_writeCharacteristic = (*env)->GetMethodID(env, jni_cid_BluetoothGatt,
-                                                                "writeCharacteristic",
-                                                                "(Landroid/bluetooth/"
-                                                                "BluetoothGattCharacteristic;)Z");
+    jmethodID jni_mid_writeCharacteristic = CALEGetJNIMethodID(env, CLASSPATH_BT_GATT,
+                                                               "writeCharacteristic",
+                                                               "(Landroid/bluetooth/"
+                                                               "BluetoothGattCharacteristic;)Z");
     if (!jni_mid_writeCharacteristic)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_writeCharacteristic is null");
@@ -1544,7 +2068,7 @@ CAResult_t CALEClientWriteCharacteristicImpl(JNIEnv *env, jobject bluetoothGatt,
                                                        gattCharacteristic);
     if (ret)
     {
-        OIC_LOG(DEBUG, TAG, "writeCharacteristic success");
+        OIC_LOG(DEBUG, TAG, "writeCharacteristic is called successfully");
     }
     else
     {
@@ -1562,14 +2086,7 @@ CAResult_t CALEClientReadCharacteristic(JNIEnv *env, jobject bluetoothGatt)
 
     if (!CALEIsEnableBTAdapter(env))
     {
-        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
-        return CA_STATUS_FAILED;
-    }
-
-    jclass jni_cid_BluetoothGatt = (*env)->FindClass(env, CLASSPATH_BT_GATT);
-    if (!jni_cid_BluetoothGatt)
-    {
-        OIC_LOG(ERROR, TAG, "jni_cid_BluetoothGatt is null");
+        OIC_LOG(INFO, TAG, "BT adapter is not enabled");
         return CA_STATUS_FAILED;
     }
 
@@ -1588,10 +2105,10 @@ CAResult_t CALEClientReadCharacteristic(JNIEnv *env, jobject bluetoothGatt)
     }
 
     OIC_LOG(DEBUG, TAG, "read characteristic method");
-    jmethodID jni_mid_readCharacteristic = (*env)->GetMethodID(env, jni_cid_BluetoothGatt,
-                                                               "readCharacteristic",
-                                                               "(Landroid/bluetooth/"
-                                                               "BluetoothGattCharacteristic;)Z");
+    jmethodID jni_mid_readCharacteristic = CALEGetJNIMethodID(env, CLASSPATH_BT_GATT,
+                                                              "readCharacteristic",
+                                                              "(Landroid/bluetooth/"
+                                                              "BluetoothGattCharacteristic;)Z");
     if (!jni_mid_readCharacteristic)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_readCharacteristic is null");
@@ -1624,24 +2141,16 @@ CAResult_t CALEClientSetCharacteristicNotification(JNIEnv *env, jobject bluetoot
 
     if (!CALEIsEnableBTAdapter(env))
     {
-        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        OIC_LOG(INFO, TAG, "BT adapter is not enabled");
         return CA_ADAPTER_NOT_ENABLED;
     }
 
-    // get BluetoothGatt class
+    // get BluetoothGatt.setCharacteristicNotification method
     OIC_LOG(DEBUG, TAG, "CALEClientSetCharacteristicNotification");
-    jclass jni_cid_BluetoothGatt = (*env)->FindClass(env, CLASSPATH_BT_GATT);
-    if (!jni_cid_BluetoothGatt)
-    {
-        OIC_LOG(ERROR, TAG, "jni_cid_BluetoothGatt is null");
-        return CA_STATUS_FAILED;
-    }
-
-    // set Characteristic Notification
-    jmethodID jni_mid_setNotification = (*env)->GetMethodID(env, jni_cid_BluetoothGatt,
-                                                            "setCharacteristicNotification",
-                                                            "(Landroid/bluetooth/"
-                                                            "BluetoothGattCharacteristic;Z)Z");
+    jmethodID jni_mid_setNotification = CALEGetJNIMethodID(env, CLASSPATH_BT_GATT,
+                                                              "setCharacteristicNotification",
+                                                              "(Landroid/bluetooth/"
+                                                              "BluetoothGattCharacteristic;Z)Z");
     if (!jni_mid_setNotification)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_getService is null");
@@ -1671,22 +2180,16 @@ jobject CALEClientGetGattService(JNIEnv *env, jobject bluetoothGatt, jstring cha
 
     if (!CALEIsEnableBTAdapter(env))
     {
-        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        OIC_LOG(INFO, TAG, "BT adapter is not enabled");
         return NULL;
     }
 
-    // get BluetoothGatt class
-    OIC_LOG(DEBUG, TAG, "CALEClientGetGattService");
-    jclass jni_cid_BluetoothGatt = (*env)->FindClass(env, CLASSPATH_BT_GATT);
-    if (!jni_cid_BluetoothGatt)
-    {
-        OIC_LOG(ERROR, TAG, "jni_cid_BluetoothGatt is null");
-        return NULL;
-    }
-
-    jmethodID jni_mid_getService = (*env)->GetMethodID(
-            env, jni_cid_BluetoothGatt, "getService",
-            "(Ljava/util/UUID;)Landroid/bluetooth/BluetoothGattService;");
+    // get BluetoothGatt.getService method
+    OIC_LOG(DEBUG, TAG, "BluetoothGatt.getService");
+    jmethodID jni_mid_getService = CALEGetJNIMethodID(env, CLASSPATH_BT_GATT,
+                                                      "getService",
+                                                      "(Ljava/util/UUID;)Landroid/bluetooth/"
+                                                      "BluetoothGattService;");
     if (!jni_mid_getService)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_getService is null");
@@ -1710,21 +2213,13 @@ jobject CALEClientGetGattService(JNIEnv *env, jobject bluetoothGatt, jstring cha
         return NULL;
     }
 
-    // get bluetooth gatt service class
-    jclass jni_cid_BluetoothGattService = (*env)->FindClass(
-            env, "android/bluetooth/BluetoothGattService");
-    if (!jni_cid_BluetoothGattService)
-    {
-        OIC_LOG(ERROR, TAG, "jni_cid_BluetoothGattService is null");
-        return NULL;
-    }
-
-    OIC_LOG(DEBUG, TAG, "get gatt getCharacteristic method");
-    jmethodID jni_mid_getCharacteristic = (*env)->GetMethodID(env, jni_cid_BluetoothGattService,
-                                                              "getCharacteristic",
-                                                              "(Ljava/util/UUID;)"
-                                                              "Landroid/bluetooth/"
-                                                              "BluetoothGattCharacteristic;");
+    // get bluetooth gatt service method
+    jmethodID jni_mid_getCharacteristic = CALEGetJNIMethodID(env, "android/bluetooth/"
+                                                      "BluetoothGattService",
+                                                      "getCharacteristic",
+                                                      "(Ljava/util/UUID;)"
+                                                      "Landroid/bluetooth/"
+                                                      "BluetoothGattCharacteristic;");
     if (!jni_mid_getCharacteristic)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_getCharacteristic is null");
@@ -1764,7 +2259,7 @@ jobject CALEClientCreateGattCharacteristic(JNIEnv *env, jobject bluetoothGatt, j
 
     if (!CALEIsEnableBTAdapter(env))
     {
-        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        OIC_LOG(INFO, TAG, "BT adapter is not enabled");
         return NULL;
     }
 
@@ -1843,21 +2338,13 @@ jbyteArray CALEClientGetValueFromCharacteristic(JNIEnv *env, jobject characteris
 
     if (!CALEIsEnableBTAdapter(env))
     {
-        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        OIC_LOG(INFO, TAG, "BT adapter is not enabled");
         return NULL;
     }
 
-    jclass jni_cid_BTGattCharacteristic = (*env)->FindClass(env, "android/bluetooth/"
-                                                            "BluetoothGattCharacteristic");
-    if (!jni_cid_BTGattCharacteristic)
-    {
-        OIC_LOG(ERROR, TAG, "jni_cid_BTGattCharacteristic is null");
-        return NULL;
-    }
-
-    OIC_LOG(DEBUG, TAG, "get value in Characteristic");
-    jmethodID jni_mid_getValue = (*env)->GetMethodID(env, jni_cid_BTGattCharacteristic, "getValue",
-                                                     "()[B");
+    jmethodID jni_mid_getValue  = CALEGetJNIMethodID(env, "android/bluetooth/"
+                                                     "BluetoothGattCharacteristic",
+                                                     "getValue", "()[B");
     if (!jni_mid_getValue)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_getValue is null");
@@ -1946,21 +2433,13 @@ CAResult_t CALEClientSetUUIDToDescriptor(JNIEnv *env, jobject bluetoothGatt,
 
     if (!CALEIsEnableBTAdapter(env))
     {
-        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        OIC_LOG(INFO, TAG, "BT adapter is not enabled");
         return CA_ADAPTER_NOT_ENABLED;
     }
 
     OIC_LOG(DEBUG, TAG, "CALEClientSetUUIDToDescriptor");
-    jclass jni_cid_BTGattCharacteristic = (*env)->FindClass(env, "android/bluetooth/"
-                                                            "BluetoothGattCharacteristic");
-    if (!jni_cid_BTGattCharacteristic)
-    {
-        OIC_LOG(ERROR, TAG, "jni_cid_BTGattCharacteristic is null");
-        return CA_STATUS_FAILED;
-    }
-
-    OIC_LOG(DEBUG, TAG, "set value in Characteristic");
-    jmethodID jni_mid_getDescriptor = (*env)->GetMethodID(env, jni_cid_BTGattCharacteristic,
+    jmethodID jni_mid_getDescriptor  = CALEGetJNIMethodID(env, "android/bluetooth/"
+                                                          "BluetoothGattCharacteristic",
                                                           "getDescriptor",
                                                           "(Ljava/util/UUID;)Landroid/bluetooth/"
                                                           "BluetoothGattDescriptor;");
@@ -1982,8 +2461,8 @@ CAResult_t CALEClientSetUUIDToDescriptor(JNIEnv *env, jobject bluetoothGatt,
                                                           jni_mid_getDescriptor, jni_obj_cc_uuid);
     if (!jni_obj_descriptor)
     {
-        OIC_LOG(ERROR, TAG, "jni_obj_descriptor is null");
-        return CA_STATUS_FAILED;
+        OIC_LOG(INFO, TAG, "jni_obj_descriptor is null");
+        return CA_NOT_SUPPORTED;
     }
 
     OIC_LOG(DEBUG, TAG, "set value in descriptor");
@@ -2025,15 +2504,8 @@ CAResult_t CALEClientSetUUIDToDescriptor(JNIEnv *env, jobject bluetoothGatt,
         return CA_STATUS_FAILED;
     }
 
-    jclass jni_cid_gatt = (*env)->FindClass(env, "android/bluetooth/BluetoothGatt");
-    if (!jni_cid_gatt)
-    {
-        OIC_LOG(ERROR, TAG, "jni_cid_gatt is null");
-        return CA_STATUS_FAILED;
-    }
-
-    OIC_LOG(DEBUG, TAG, "write Descriptor in gatt object");
-    jmethodID jni_mid_writeDescriptor = (*env)->GetMethodID(env, jni_cid_gatt, "writeDescriptor",
+    jmethodID jni_mid_writeDescriptor  = CALEGetJNIMethodID(env, "android/bluetooth/BluetoothGatt",
+                                                            "writeDescriptor",
                                                             "(Landroid/bluetooth/"
                                                             "BluetoothGattDescriptor;)Z");
     if (!jni_mid_writeDescriptor)
@@ -2076,7 +2548,6 @@ void CALEClientCreateScanDeviceList(JNIEnv *env)
 
 CAResult_t CALEClientAddScanDeviceToList(JNIEnv *env, jobject device)
 {
-    OIC_LOG(DEBUG, TAG, "IN - CALEClientAddScanDeviceToList");
     VERIFY_NON_NULL(device, TAG, "device is null");
     VERIFY_NON_NULL(env, TAG, "env is null");
 
@@ -2085,6 +2556,13 @@ CAResult_t CALEClientAddScanDeviceToList(JNIEnv *env, jobject device)
     if (!g_deviceList)
     {
         OIC_LOG(ERROR, TAG, "gdevice_list is null");
+
+        CALEClientSetScanFlag(false);
+        if(CA_STATUS_OK != CALEClientStopScan())
+        {
+            OIC_LOG(ERROR, TAG, "CALEClientStopScan has failed");
+        }
+
         ca_mutex_unlock(g_deviceListMutex);
         return CA_STATUS_FAILED;
     }
@@ -2110,20 +2588,18 @@ CAResult_t CALEClientAddScanDeviceToList(JNIEnv *env, jobject device)
         jobject gdevice = (*env)->NewGlobalRef(env, device);
         u_arraylist_add(g_deviceList, gdevice);
         ca_cond_signal(g_deviceDescCond);
-        OIC_LOG(DEBUG, TAG, "Set Object to Array as Element");
+        OIC_LOG_V(DEBUG, TAG, "Added this BT Device[%s] in the List", remoteAddress);
     }
     (*env)->ReleaseStringUTFChars(env, jni_remoteAddress, remoteAddress);
 
     ca_mutex_unlock(g_deviceListMutex);
 
-    OIC_LOG(DEBUG, TAG, "OUT - CALEClientAddScanDeviceToList");
     return CA_STATUS_OK;
 }
 
 bool CALEClientIsDeviceInScanDeviceList(JNIEnv *env, const char* remoteAddress)
 {
-    OIC_LOG(DEBUG, TAG, "IN - CALEClientIsDeviceInScanDeviceList");
-    VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", true);
     VERIFY_NON_NULL_RET(remoteAddress, TAG, "remoteAddress is null", true);
 
     if (!g_deviceList)
@@ -2158,7 +2634,6 @@ bool CALEClientIsDeviceInScanDeviceList(JNIEnv *env, const char* remoteAddress)
 
         if (!strcmp(remoteAddress, setAddress))
         {
-            OIC_LOG(DEBUG, TAG, "the device is already set");
             (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
             return true;
         }
@@ -2166,7 +2641,6 @@ bool CALEClientIsDeviceInScanDeviceList(JNIEnv *env, const char* remoteAddress)
         (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT - CALEClientIsDeviceInScanDeviceList");
     OIC_LOG(DEBUG, TAG, "there are no the device in list. we can add");
 
     return false;
@@ -2196,6 +2670,7 @@ CAResult_t CALEClientRemoveAllScanDevices(JNIEnv *env)
             continue;
         }
         (*env)->DeleteGlobalRef(env, jarrayObj);
+        jarrayObj = NULL;
     }
 
     OICFree(g_deviceList);
@@ -2260,6 +2735,7 @@ CAResult_t CALEClientRemoveDeviceInScanDeviceList(JNIEnv *env, jstring address)
         {
             OIC_LOG_V(DEBUG, TAG, "remove object : %s", remoteAddress);
             (*env)->DeleteGlobalRef(env, jarrayObj);
+            jarrayObj = NULL;
             (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
             (*env)->ReleaseStringUTFChars(env, address, remoteAddress);
 
@@ -2288,12 +2764,19 @@ CAResult_t CALEClientRemoveDeviceInScanDeviceList(JNIEnv *env, jstring address)
 
 CAResult_t CALEClientAddGattobjToList(JNIEnv *env, jobject gatt)
 {
-    OIC_LOG(DEBUG, TAG, "CALEClientAddGattobjToList");
+    OIC_LOG(INFO, TAG, "CALEClientAddGattobjToList");
     VERIFY_NON_NULL(env, TAG, "env is null");
     VERIFY_NON_NULL(gatt, TAG, "gatt is null");
 
     ca_mutex_lock(g_gattObjectMutex);
 
+    if (!g_gattObjectList)
+    {
+        OIC_LOG(ERROR, TAG, "g_gattObjectList is not available");
+        ca_mutex_unlock(g_gattObjectMutex);
+        return CA_STATUS_FAILED;
+    }
+
     jstring jni_remoteAddress = CALEClientGetAddressFromGattObj(env, gatt);
     if (!jni_remoteAddress)
     {
@@ -2310,11 +2793,12 @@ CAResult_t CALEClientAddGattobjToList(JNIEnv *env, jobject gatt)
         return CA_STATUS_FAILED;
     }
 
+    OIC_LOG_V(INFO, TAG, "remote address : %s", remoteAddress);
     if (!CALEClientIsGattObjInList(env, remoteAddress))
     {
         jobject newGatt = (*env)->NewGlobalRef(env, gatt);
         u_arraylist_add(g_gattObjectList, newGatt);
-        OIC_LOG(DEBUG, TAG, "Set GATT Object to Array as Element");
+        OIC_LOG(INFO, TAG, "Set GATT Object to Array as Element");
     }
 
     (*env)->ReleaseStringUTFChars(env, jni_remoteAddress, remoteAddress);
@@ -2427,9 +2911,9 @@ CAResult_t CALEClientRemoveAllGattObjs(JNIEnv *env)
     ca_mutex_lock(g_gattObjectMutex);
     if (!g_gattObjectList)
     {
-        OIC_LOG(ERROR, TAG, "g_gattObjectList is null");
+        OIC_LOG(DEBUG, TAG, "already removed for g_gattObjectList");
         ca_mutex_unlock(g_gattObjectMutex);
-        return CA_STATUS_FAILED;
+        return CA_STATUS_OK;
     }
 
     uint32_t length = u_arraylist_length(g_gattObjectList);
@@ -2442,10 +2926,12 @@ CAResult_t CALEClientRemoveAllGattObjs(JNIEnv *env)
             continue;
         }
         (*env)->DeleteGlobalRef(env, jarrayObj);
+        jarrayObj = NULL;
     }
 
     OICFree(g_gattObjectList);
     g_gattObjectList = NULL;
+    OIC_LOG(INFO, TAG, "g_gattObjectList is removed");
     ca_mutex_unlock(g_gattObjectMutex);
     return CA_STATUS_OK;
 }
@@ -2459,9 +2945,9 @@ CAResult_t CALEClientRemoveGattObj(JNIEnv *env, jobject gatt)
     ca_mutex_lock(g_gattObjectMutex);
     if (!g_gattObjectList)
     {
-        OIC_LOG(ERROR, TAG, "g_gattObjectList is null");
+        OIC_LOG(DEBUG, TAG, "already removed for g_gattObjectList");
         ca_mutex_unlock(g_gattObjectMutex);
-        return CA_STATUS_FAILED;
+        return CA_STATUS_OK;
     }
 
     uint32_t length = u_arraylist_length(g_gattObjectList);
@@ -2513,6 +2999,7 @@ CAResult_t CALEClientRemoveGattObj(JNIEnv *env, jobject gatt)
         {
             OIC_LOG_V(DEBUG, TAG, "remove object : %s", remoteAddress);
             (*env)->DeleteGlobalRef(env, jarrayObj);
+            jarrayObj = NULL;
             (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
             (*env)->ReleaseStringUTFChars(env, jni_remoteAddress, remoteAddress);
 
@@ -2543,70 +3030,165 @@ CAResult_t CALEClientRemoveGattObjForAddr(JNIEnv *env, jstring addr)
     ca_mutex_lock(g_gattObjectMutex);
     if (!g_gattObjectList)
     {
-        OIC_LOG(ERROR, TAG, "g_gattObjectList is null");
-        ca_mutex_unlock(g_gattObjectMutex);
-        return CA_STATUS_FAILED;
+        OIC_LOG(DEBUG, TAG, "already removed for g_gattObjectList");
+        ca_mutex_unlock(g_gattObjectMutex);
+        return CA_STATUS_OK;
+    }
+
+    uint32_t length = u_arraylist_length(g_gattObjectList);
+    for (uint32_t index = 0; index < length; index++)
+    {
+        jobject jarrayObj = (jobject) u_arraylist_get(g_gattObjectList, index);
+        if (!jarrayObj)
+        {
+            OIC_LOG(ERROR, TAG, "jarrayObj is null");
+            ca_mutex_unlock(g_gattObjectMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        jstring jni_setAddress = CALEClientGetAddressFromGattObj(env, jarrayObj);
+        if (!jni_setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "jni_setAddress is null");
+            ca_mutex_unlock(g_gattObjectMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
+        if (!setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "setAddress is null");
+            ca_mutex_unlock(g_gattObjectMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        const char* remoteAddress = (*env)->GetStringUTFChars(env, addr, NULL);
+        if (!remoteAddress)
+        {
+            OIC_LOG(ERROR, TAG, "remoteAddress is null");
+            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+            ca_mutex_unlock(g_gattObjectMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        if (!strcmp(setAddress, remoteAddress))
+        {
+            OIC_LOG_V(DEBUG, TAG, "remove object : %s", remoteAddress);
+            (*env)->DeleteGlobalRef(env, jarrayObj);
+            jarrayObj = NULL;
+            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+            (*env)->ReleaseStringUTFChars(env, addr, remoteAddress);
+            if (NULL == u_arraylist_remove(g_gattObjectList, index))
+            {
+                OIC_LOG(ERROR, TAG, "List removal failed.");
+                ca_mutex_unlock(g_gattObjectMutex);
+                return CA_STATUS_FAILED;
+            }
+            ca_mutex_unlock(g_gattObjectMutex);
+            return CA_STATUS_OK;
+        }
+        (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+        (*env)->ReleaseStringUTFChars(env, addr, remoteAddress);
+    }
+
+    ca_mutex_unlock(g_gattObjectMutex);
+    OIC_LOG(DEBUG, TAG, "there are no target object");
+    return CA_STATUS_FAILED;
+}
+
+jstring CALEClientGetLEAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEClientGetLEAddressFromBTDevice");
+
+    VERIFY_NON_NULL_RET(env, TAG, "env", NULL);
+    VERIFY_NON_NULL_RET(bluetoothDevice, TAG, "bluetoothDevice", NULL);
+
+    // get Bluetooth Address
+    jstring jni_btTargetAddress = CALEGetAddressFromBTDevice(env, bluetoothDevice);
+    if (!jni_btTargetAddress)
+    {
+        OIC_LOG(ERROR, TAG, "CALEGetAddressFromBTDevice has failed");
+        return NULL;
+    }
+
+    const char* targetAddress = (*env)->GetStringUTFChars(env, jni_btTargetAddress, NULL);
+    if (!targetAddress)
+    {
+        OIC_LOG(ERROR, TAG, "targetAddress is not available");
+        return NULL;
+    }
+
+    // get method ID of getDevice()
+    jmethodID jni_mid_getDevice = CALEGetJNIMethodID(env, CLASSPATH_BT_GATT,
+                                                     "getDevice", METHODID_BT_DEVICE);
+    if (!jni_mid_getDevice)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getDevice is null");
+        (*env)->ReleaseStringUTFChars(env, jni_btTargetAddress, targetAddress);
+        return NULL;
     }
 
-    uint32_t length = u_arraylist_length(g_gattObjectList);
-    for (uint32_t index = 0; index < length; index++)
+    size_t length = u_arraylist_length(g_gattObjectList);
+    for (size_t index = 0; index < length; index++)
     {
         jobject jarrayObj = (jobject) u_arraylist_get(g_gattObjectList, index);
         if (!jarrayObj)
         {
             OIC_LOG(ERROR, TAG, "jarrayObj is null");
-            ca_mutex_unlock(g_gattObjectMutex);
-            return CA_STATUS_FAILED;
+            (*env)->ReleaseStringUTFChars(env, jni_btTargetAddress, targetAddress);
+            return NULL;
         }
 
-        jstring jni_setAddress = CALEClientGetAddressFromGattObj(env, jarrayObj);
-        if (!jni_setAddress)
+        OIC_LOG(DEBUG, TAG, "CALL API - bluetoothGatt.getDevice()");
+        jobject jni_obj_device = (*env)->CallObjectMethod(env, jarrayObj, jni_mid_getDevice);
+        if (!jni_obj_device)
         {
-            OIC_LOG(ERROR, TAG, "jni_setAddress is null");
-            ca_mutex_unlock(g_gattObjectMutex);
-            return CA_STATUS_FAILED;
+            OIC_LOG(ERROR, TAG, "jni_obj_device is null");
+            (*env)->ReleaseStringUTFChars(env, jni_btTargetAddress, targetAddress);
+            return NULL;
         }
 
-        const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
-        if (!setAddress)
+        jstring jni_btAddress = CALEGetAddressFromBTDevice(env, jni_obj_device);
+        if (!jni_btAddress)
         {
-            OIC_LOG(ERROR, TAG, "setAddress is null");
-            ca_mutex_unlock(g_gattObjectMutex);
-            return CA_STATUS_FAILED;
+            OIC_LOG(ERROR, TAG, "CALEGetAddressFromBTDevice has failed");
+            (*env)->ReleaseStringUTFChars(env, jni_btTargetAddress, targetAddress);
+            return NULL;
         }
 
-        const char* remoteAddress = (*env)->GetStringUTFChars(env, addr, NULL);
-        if (!remoteAddress)
+        const char* btAddress = (*env)->GetStringUTFChars(env, jni_btAddress, NULL);
+        if (!btAddress)
         {
-            OIC_LOG(ERROR, TAG, "remoteAddress is null");
-            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
-            ca_mutex_unlock(g_gattObjectMutex);
-            return CA_STATUS_FAILED;
+            OIC_LOG(ERROR, TAG, "btAddress is not available");
+            (*env)->ReleaseStringUTFChars(env, jni_btTargetAddress, targetAddress);
+            return NULL;
         }
 
-        if (!strcmp(setAddress, remoteAddress))
+        OIC_LOG_V(DEBUG, TAG, "targetAddress : %s", targetAddress);
+        OIC_LOG_V(DEBUG, TAG, "btAddress : %s", btAddress);
+        if (!strcmp(targetAddress, btAddress))
         {
-            OIC_LOG_V(DEBUG, TAG, "remove object : %s", remoteAddress);
-            (*env)->DeleteGlobalRef(env, jarrayObj);
+            OIC_LOG(DEBUG, TAG, "Found Gatt object from BT device");
 
-            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
-            (*env)->ReleaseStringUTFChars(env, addr, remoteAddress);
-            if (NULL == u_arraylist_remove(g_gattObjectList, index))
+            // get LE address
+            jstring jni_LEAddress = CALEClientGetAddressFromGattObj(env, jarrayObj);
+            if (!jni_LEAddress)
             {
-                OIC_LOG(ERROR, TAG, "List removal failed.");
-                ca_mutex_unlock(g_gattObjectMutex);
-                return CA_STATUS_FAILED;
+                OIC_LOG(ERROR, TAG, "jni_LEAddress is null");
             }
-            ca_mutex_unlock(g_gattObjectMutex);
-            return CA_STATUS_OK;
+            (*env)->ReleaseStringUTFChars(env, jni_btTargetAddress, targetAddress);
+            (*env)->ReleaseStringUTFChars(env, jni_btAddress, btAddress);
+            (*env)->DeleteLocalRef(env, jni_btAddress);
+            (*env)->DeleteLocalRef(env, jni_obj_device);
+            return jni_LEAddress;
         }
-        (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
-        (*env)->ReleaseStringUTFChars(env, addr, remoteAddress);
+        (*env)->ReleaseStringUTFChars(env, jni_btAddress, btAddress);
+        (*env)->DeleteLocalRef(env, jni_btAddress);
+        (*env)->DeleteLocalRef(env, jni_obj_device);
     }
 
-    ca_mutex_unlock(g_gattObjectMutex);
-    OIC_LOG(DEBUG, TAG, "there are no target object");
-    return CA_STATUS_FAILED;
+    OIC_LOG(DEBUG, TAG, "OUT - CALEClientGetLEAddressFromBTDevice");
+    return NULL;
 }
 
 /**
@@ -2618,7 +3200,7 @@ CAResult_t CALEClientUpdateDeviceState(const char* address, uint32_t connectedSt
 {
     VERIFY_NON_NULL(address, TAG, "address is null");
 
-    CALEState_t *newstate = (CALEState_t*) OICMalloc(sizeof(CALEState_t));
+    CALEState_t *newstate = (CALEState_t*) OICCalloc(1, sizeof(*newstate));
     if (!newstate)
     {
         OIC_LOG(ERROR, TAG, "out of memory");
@@ -2666,6 +3248,7 @@ CAResult_t CALEClientAddDeviceStateToList(CALEState_t* state)
         {
             state->notificationState = curState->notificationState;
         }
+        state->autoConnectFlag = curState->autoConnectFlag;
 
         // delete previous state for update new state
         CAResult_t res = CALEClientRemoveDeviceState(state->address);
@@ -2677,8 +3260,9 @@ CAResult_t CALEClientAddDeviceStateToList(CALEState_t* state)
         }
     }
     u_arraylist_add(g_deviceStateList, state); // update new state
-    OIC_LOG_V(DEBUG, TAG, "Set State Info to List : %d, %d",
-              state->connectedState, state->notificationState);
+    OIC_LOG_V(INFO, TAG, "Set State Info to List : %d, %d, %s, %d",
+              state->connectedState, state->notificationState,
+              state->address, state->autoConnectFlag);
 
     ca_mutex_unlock(g_deviceStateListMutex);
     return CA_STATUS_OK;
@@ -2721,7 +3305,7 @@ bool CALEClientIsDeviceInList(const char* remoteAddress)
 
 CAResult_t CALEClientRemoveAllDeviceState()
 {
-    OIC_LOG(DEBUG, TAG, "CALENativeRemoveAllDevices");
+    OIC_LOG(DEBUG, TAG, "CALEClientRemoveAllDeviceState");
 
     ca_mutex_lock(g_deviceStateListMutex);
     if (!g_deviceStateList)
@@ -2750,6 +3334,39 @@ CAResult_t CALEClientRemoveAllDeviceState()
     return CA_STATUS_OK;
 }
 
+CAResult_t CALEClientResetDeviceStateForAll()
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientResetDeviceStateForAll");
+
+    ca_mutex_lock(g_deviceStateListMutex);
+    if (!g_deviceStateList)
+    {
+        OIC_LOG(ERROR, TAG, "g_deviceStateList is null");
+        ca_mutex_unlock(g_deviceStateListMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    size_t length = u_arraylist_length(g_deviceStateList);
+    for (size_t index = 0; index < length; index++)
+    {
+        CALEState_t* state = (CALEState_t*) u_arraylist_get(g_deviceStateList, index);
+        if (!state)
+        {
+            OIC_LOG(ERROR, TAG, "jarrayObj is null");
+            continue;
+        }
+
+        // autoConnectFlag value will be not changed,
+        // since it has reset only termination case.
+        state->connectedState = STATE_DISCONNECTED;
+        state->notificationState = STATE_CHARACTER_UNSET;
+        state->sendState = STATE_SEND_NONE;
+    }
+    ca_mutex_unlock(g_deviceStateListMutex);
+
+    return CA_STATUS_OK;
+}
+
 CAResult_t CALEClientRemoveDeviceState(const char* remoteAddress)
 {
     OIC_LOG(DEBUG, TAG, "CALEClientRemoveDeviceState");
@@ -2773,20 +3390,22 @@ CAResult_t CALEClientRemoveDeviceState(const char* remoteAddress)
 
         if (!strcmp(state->address, remoteAddress))
         {
-            OIC_LOG_V(DEBUG, TAG, "remove state : %s", remoteAddress);
-            OICFree(state);
+            OIC_LOG_V(DEBUG, TAG, "remove state : %s", state->address);
 
-            if (NULL == u_arraylist_remove(g_deviceStateList, index))
+            CALEState_t* targetState  = (CALEState_t*)u_arraylist_remove(g_deviceStateList,
+                                                                         index);
+            if (NULL == targetState)
             {
                 OIC_LOG(ERROR, TAG, "List removal failed.");
                 return CA_STATUS_FAILED;
             }
 
+            OICFree(targetState);
             return CA_STATUS_OK;
         }
     }
 
-    return CA_STATUS_FAILED;
+    return CA_STATUS_OK;
 }
 
 CALEState_t* CALEClientGetStateInfo(const char* remoteAddress)
@@ -2801,6 +3420,8 @@ CALEState_t* CALEClientGetStateInfo(const char* remoteAddress)
     }
 
     uint32_t length = u_arraylist_length(g_deviceStateList);
+    OIC_LOG_V(DEBUG, TAG, "CALEClientGetStateInfo : %d", length);
+
     for (uint32_t index = 0; index < length; index++)
     {
         CALEState_t* state = (CALEState_t*) u_arraylist_get(g_deviceStateList, index);
@@ -2810,6 +3431,9 @@ CALEState_t* CALEClientGetStateInfo(const char* remoteAddress)
             continue;
         }
 
+        OIC_LOG_V(DEBUG, TAG, "target address : %s", remoteAddress);
+        OIC_LOG_V(DEBUG, TAG, "state address : %s", state->address);
+
         if (!strcmp(state->address, remoteAddress))
         {
             OIC_LOG_V(DEBUG, TAG, "get state : %s", remoteAddress);
@@ -2938,6 +3562,8 @@ void CALEClientCreateDeviceList()
  */
 void CALEClientUpdateSendCnt(JNIEnv *env)
 {
+    OIC_LOG(DEBUG, TAG, "CALEClientUpdateSendCnt");
+
     VERIFY_NON_NULL_VOID(env, TAG, "env is null");
     // mutex lock
     ca_mutex_lock(g_threadMutex);
@@ -2956,6 +3582,7 @@ void CALEClientUpdateSendCnt(JNIEnv *env)
         }
         // notity the thread
         ca_cond_signal(g_threadCond);
+
         CALEClientSetSendFinishFlag(true);
         OIC_LOG(DEBUG, TAG, "set signal for send data");
     }
@@ -2965,8 +3592,6 @@ void CALEClientUpdateSendCnt(JNIEnv *env)
 
 CAResult_t CALEClientInitGattMutexVaraibles()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     if (NULL == g_bleReqRespClientCbMutex)
     {
         g_bleReqRespClientCbMutex = ca_mutex_new();
@@ -3057,14 +3682,31 @@ CAResult_t CALEClientInitGattMutexVaraibles()
         }
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT");
+    if (NULL == g_threadWriteCharacteristicMutex)
+    {
+        g_threadWriteCharacteristicMutex = ca_mutex_new();
+        if (NULL == g_threadWriteCharacteristicMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_deviceScanRetryDelayMutex)
+    {
+        g_deviceScanRetryDelayMutex = ca_mutex_new();
+        if (NULL == g_deviceScanRetryDelayMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
     return CA_STATUS_OK;
 }
 
 void CALEClientTerminateGattMutexVariables()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     ca_mutex_free(g_bleReqRespClientCbMutex);
     g_bleReqRespClientCbMutex = NULL;
 
@@ -3086,7 +3728,11 @@ void CALEClientTerminateGattMutexVariables()
     ca_mutex_free(g_scanMutex);
     g_scanMutex = NULL;
 
-    OIC_LOG(DEBUG, TAG, "OUT");
+    ca_mutex_free(g_threadWriteCharacteristicMutex);
+    g_threadWriteCharacteristicMutex = NULL;
+
+    ca_mutex_free(g_deviceScanRetryDelayMutex);
+    g_deviceScanRetryDelayMutex = NULL;
 }
 
 void CALEClientSetSendFinishFlag(bool flag)
@@ -3104,17 +3750,31 @@ void CALEClientSetSendFinishFlag(bool flag)
 
 CAResult_t CAStartLEGattClient()
 {
-    CAResult_t res = CALEClientStartMulticastServer();
-    if (CA_STATUS_OK != res)
+    // init mutex for send logic
+    if (!g_deviceDescCond)
     {
-        OIC_LOG(ERROR, TAG, "CALEClientStartMulticastServer has failed");
+        g_deviceDescCond = ca_cond_new();
     }
-    else
+
+    if (!g_threadCond)
+    {
+        g_threadCond = ca_cond_new();
+    }
+
+    if (!g_threadWriteCharacteristicCond)
+    {
+        g_threadWriteCharacteristicCond = ca_cond_new();
+    }
+
+    CAResult_t ret = CALEClientStartScan();
+    if (CA_STATUS_OK != ret)
     {
-        g_isStartedLEClient = true;
+        OIC_LOG(ERROR, TAG, "CALEClientStartScan has failed");
+        return ret;
     }
 
-    return res;
+    g_isStartedLEClient = true;
+    return CA_STATUS_OK;
 }
 
 void CAStopLEGattClient()
@@ -3155,7 +3815,31 @@ void CAStopLEGattClient()
         OIC_LOG(ERROR, TAG, "CALEClientStopScan has failed");
     }
 
+    ca_mutex_lock(g_threadMutex);
+    OIC_LOG(DEBUG, TAG, "signal - connection cond");
     ca_cond_signal(g_threadCond);
+    CALEClientSetSendFinishFlag(true);
+    ca_mutex_unlock(g_threadMutex);
+
+    ca_mutex_lock(g_threadWriteCharacteristicMutex);
+    OIC_LOG(DEBUG, TAG, "signal - WriteCharacteristic cond");
+    ca_cond_signal(g_threadWriteCharacteristicCond);
+    ca_mutex_unlock(g_threadWriteCharacteristicMutex);
+
+    ca_mutex_lock(g_deviceScanRetryDelayMutex);
+    OIC_LOG(DEBUG, TAG, "signal - delay cond");
+    ca_cond_signal(g_deviceScanRetryDelayCond);
+    ca_mutex_unlock(g_deviceScanRetryDelayMutex);
+
+    ca_cond_free(g_deviceDescCond);
+    ca_cond_free(g_threadCond);
+    ca_cond_free(g_threadWriteCharacteristicCond);
+    ca_cond_free(g_deviceScanRetryDelayCond);
+
+    g_deviceDescCond = NULL;
+    g_threadCond = NULL;
+    g_threadWriteCharacteristicCond = NULL;
+    g_deviceScanRetryDelayCond = NULL;
 
     if (isAttached)
     {
@@ -3164,9 +3848,17 @@ void CAStopLEGattClient()
 
 }
 
+CAResult_t CAInitializeLEGattClient()
+{
+    OIC_LOG(DEBUG, TAG, "Initialize GATT Client");
+    CALEClientInitialize();
+    return CA_STATUS_OK;
+}
+
 void CATerminateLEGattClient()
 {
     OIC_LOG(DEBUG, TAG, "Terminate GATT Client");
+    CAStopLEGattClient();
     CALEClientTerminate();
 }
 
@@ -3197,22 +3889,14 @@ CAResult_t CAUpdateCharacteristicsToAllGattServers(const uint8_t *data, uint32_t
 
 void CASetLEReqRespClientCallback(CABLEDataReceivedCallback callback)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     ca_mutex_lock(g_bleReqRespClientCbMutex);
     g_CABLEClientDataReceivedCallback = callback;
     ca_mutex_unlock(g_bleReqRespClientCbMutex);
-
-    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 void CASetLEClientThreadPoolHandle(ca_thread_pool_t handle)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
-    CALEClientInitialize(handle);
-
-    OIC_LOG(DEBUG, TAG, "OUT");
+    g_threadPoolHandle = handle;
 }
 
 CAResult_t CAGetLEAddress(char **local_address)
@@ -3261,6 +3945,39 @@ 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 = CALEGetJNIMethodID(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
@@ -3279,7 +3996,11 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeGattConnectionStateChangeCallback(J
     VERIFY_NON_NULL_VOID(obj, TAG, "obj is null");
     VERIFY_NON_NULL_VOID(gatt, TAG, "gatt is null");
 
-    if (GATT_SUCCESS == status && STATE_CONNECTED == newstate) // le connected
+    jint state_connected = CALEGetConstantsValue(env, CLASSPATH_BT_PROFILE, "STATE_CONNECTED");
+    jint state_disconnected = CALEGetConstantsValue(env, CLASSPATH_BT_PROFILE, "STATE_DISCONNECTED");
+    jint gatt_success = CALEGetConstantsValue(env, CLASSPATH_BT_GATT, "GATT_SUCCESS");
+
+    if (gatt_success == status && state_connected == newstate) // le connected
     {
         jstring jni_address = CALEClientGetAddressFromGattObj(env, gatt);
         if (!jni_address)
@@ -3299,6 +4020,8 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeGattConnectionStateChangeCallback(J
                 (*env)->ReleaseStringUTFChars(env, jni_address, address);
                 goto error_exit;
             }
+            OIC_LOG_V(INFO, TAG, "ConnectionStateCB - remote address : %s", address);
+
             (*env)->ReleaseStringUTFChars(env, jni_address, address);
         }
 
@@ -3316,15 +4039,8 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeGattConnectionStateChangeCallback(J
             goto error_exit;
         }
     }
-    else // le disconnected
+    else if (state_disconnected == newstate) // le disconnected
     {
-        CAResult_t res = CALEClientStartScan();
-        if (CA_STATUS_OK != res)
-        {
-            OIC_LOG(ERROR, TAG, "CALEClientStartScan has failed");
-            goto error_exit;
-        }
-
         jstring jni_address = CALEClientGetAddressFromGattObj(env, gatt);
         if (!jni_address)
         {
@@ -3335,27 +4051,77 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeGattConnectionStateChangeCallback(J
         const char* address = (*env)->GetStringUTFChars(env, jni_address, NULL);
         if (address)
         {
-            res = CALEClientRemoveDeviceState(address);
+            CAResult_t res = CALEClientUpdateDeviceState(address, STATE_DISCONNECTED,
+                                                                  STATE_CHARACTER_UNSET,
+                                                                  STATE_SEND_NONE);
             if (CA_STATUS_OK != res)
             {
-                OIC_LOG(ERROR, TAG, "CALEClientRemoveDeviceState has failed");
+                OIC_LOG(ERROR, TAG, "CALEClientUpdateDeviceState has failed");
+                (*env)->ReleaseStringUTFChars(env, jni_address, address);
                 goto error_exit;
             }
+            OIC_LOG_V(INFO, TAG, "ConnectionStateCB - remote address : %s", address);
 
-            res = CALEClientRemoveGattObjForAddr(env, jni_address);
-            if (CA_STATUS_OK != res)
+            (*env)->ReleaseStringUTFChars(env, jni_address, address);
+        }
+
+        CAResult_t res = CALEClientGattClose(env, gatt);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "CALEClientGattClose has failed");
+        }
+
+        if (GATT_ERROR == status)
+        {
+            // when we get GATT ERROR(0x85), gatt connection can be called again.
+            OIC_LOG(INFO, TAG, "retry gatt connect");
+
+            jstring leAddress = CALEClientGetAddressFromGatt(env, gatt);
+            if (!leAddress)
             {
-                OIC_LOG(ERROR, TAG, "CALEClientRemoveGattObjForAddr has failed");
+                OIC_LOG(ERROR, TAG, "CALEClientGetAddressFromGatt has failed");
                 goto error_exit;
             }
 
-            (*env)->ReleaseStringUTFChars(env, jni_address, address);
+            jobject btObject = CALEGetRemoteDevice(env, leAddress);
+            if (!btObject)
+            {
+                OIC_LOG(ERROR, TAG, "CALEGetRemoteDevice has failed");
+                goto error_exit;
+            }
+
+            jobject newGatt = CALEClientConnect(env, btObject, JNI_TRUE);
+            if (!newGatt)
+            {
+                OIC_LOG(ERROR, TAG, "CALEClientConnect has failed");
+                goto error_exit;
+            }
+
+            return;
+        }
+        else
+        {
+            if (CALECheckConnectionStateValue(status))
+            {
+                // this state is unexpected reason to disconnect
+                // if the reason is suitable, connection logic of the device will be destroyed.
+                OIC_LOG(INFO, TAG, "connection logic destroy");
+                goto error_exit;
+            }
+            else
+            {
+                // other reason except for gatt_success is expected to running
+                // background connection in BT platform.
+                OIC_LOG(INFO, TAG, "unknown state or manual disconnected state");
+                CALEClientUpdateSendCnt(env);
+                return;
+            }
         }
 
-        res = CALEClientGattClose(env, gatt);
-        if (CA_STATUS_OK != res)
+        if (g_sendBuffer)
         {
-            OIC_LOG(ERROR, TAG, "CALEClientGattClose has failed");
+            (*env)->DeleteGlobalRef(env, g_sendBuffer);
+            g_sendBuffer = NULL;
         }
     }
     return;
@@ -3430,12 +4196,15 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeGattServicesDiscoveredCallback(JNIE
         res = CALEClientSetUUIDToDescriptor(env, gatt, jni_obj_GattCharacteristic);
         if (CA_STATUS_OK != res)
         {
-            OIC_LOG(INFO, TAG, "Descriptor of the uuid is not found");
-            CAResult_t res = CALEClientWriteCharacteristic(env, gatt);
-            if (CA_STATUS_OK != res)
+            OIC_LOG_V(INFO, TAG, "Descriptor is not found : %d", res);
+            if (g_sendBuffer)
             {
-                OIC_LOG(ERROR, TAG, "CALEClientWriteCharacteristic has failed");
-                goto error_exit;
+                CAResult_t res = CALEClientWriteCharacteristic(env, gatt);
+                if (CA_STATUS_OK != res)
+                {
+                    OIC_LOG(ERROR, TAG, "CALEClientWriteCharacteristic has failed");
+                    goto error_exit;
+                }
             }
         }
 
@@ -3449,18 +4218,23 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeGattServicesDiscoveredCallback(JNIE
     }
     else
     {
-        CAResult_t res = CALEClientWriteCharacteristic(env, gatt);
-        if (CA_STATUS_OK != res)
+        if (g_sendBuffer)
         {
-            OIC_LOG(ERROR, TAG, "CALEClientWriteCharacteristic has failed");
-            goto error_exit;
+            CAResult_t res = CALEClientWriteCharacteristic(env, gatt);
+            if (CA_STATUS_OK != res)
+            {
+                OIC_LOG(ERROR, TAG, "CALEClientWriteCharacteristic has failed");
+                goto error_exit;
+            }
         }
     }
+    OIC_LOG(INFO, TAG, "ServicesDiscovery is successful");
     (*env)->ReleaseStringUTFChars(env, jni_address, address);
     return;
 
     // error label.
 error_exit:
+    OIC_LOG(ERROR, TAG, "ServicesDiscovery has failed");
     (*env)->ReleaseStringUTFChars(env, jni_address, address);
     CALEClientSendFinish(env, gatt);
     return;
@@ -3481,11 +4255,6 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeGattCharacteristicWriteCallback(
     VERIFY_NON_NULL_VOID(obj, TAG, "obj is null");
     VERIFY_NON_NULL_VOID(gatt, TAG, "gatt is null");
 
-    jboolean isCopy;
-    char* wroteData = (char*) (*env)->GetByteArrayElements(env, data, &isCopy);
-
-    OIC_LOG_V(DEBUG, TAG, "CALeGattCharacteristicWriteCallback - write data : %s", wroteData);
-
     // send success & signal
     jstring jni_address = CALEClientGetAddressFromGattObj(env, gatt);
     if (!jni_address)
@@ -3499,23 +4268,38 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeGattCharacteristicWriteCallback(
         goto error_exit;
     }
 
-    if (GATT_SUCCESS != status) // error case
+    jint gatt_success = CALEGetConstantsValue(env, CLASSPATH_BT_GATT, "GATT_SUCCESS");
+    if (gatt_success != status) // error case
     {
         OIC_LOG(ERROR, TAG, "send failure");
-        CAResult_t res = CALEClientUpdateDeviceState(address, STATE_CONNECTED, STATE_CHARACTER_SET,
-                                                     STATE_SEND_FAILED);
+
+        // retry to write
+        CAResult_t res = CALEClientWriteCharacteristic(env, gatt);
         if (CA_STATUS_OK != res)
         {
-            OIC_LOG(ERROR, TAG, "CALEClientUpdateDeviceState has failed");
-        }
+            OIC_LOG(ERROR, TAG, "WriteCharacteristic has failed");
+            ca_mutex_lock(g_threadWriteCharacteristicMutex);
+            g_isSignalSetFlag = true;
+            ca_cond_signal(g_threadWriteCharacteristicCond);
+            ca_mutex_unlock(g_threadWriteCharacteristicMutex);
 
-        if (g_clientErrorCallback)
-        {
-            jint length = (*env)->GetArrayLength(env, data);
-            g_clientErrorCallback(address, data, length, CA_SEND_FAILED);
-        }
+            CAResult_t res = CALEClientUpdateDeviceState(address, STATE_CONNECTED,
+                                                         STATE_CHARACTER_SET,
+                                                         STATE_SEND_FAILED);
+            if (CA_STATUS_OK != res)
+            {
+                OIC_LOG(ERROR, TAG, "CALEClientUpdateDeviceState has failed");
+            }
 
-        CALEClientSendFinish(env, gatt);
+            if (g_clientErrorCallback)
+            {
+                jint length = (*env)->GetArrayLength(env, data);
+                g_clientErrorCallback(address, data, length, CA_SEND_FAILED);
+            }
+
+            CALEClientSendFinish(env, gatt);
+            goto error_exit;
+        }
     }
     else
     {
@@ -3526,6 +4310,13 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeGattCharacteristicWriteCallback(
         {
             OIC_LOG(ERROR, TAG, "CALEClientUpdateDeviceState has failed");
         }
+
+        ca_mutex_lock(g_threadWriteCharacteristicMutex);
+        OIC_LOG(DEBUG, TAG, "g_isSignalSetFlag is set true and signal");
+        g_isSignalSetFlag = true;
+        ca_cond_signal(g_threadWriteCharacteristicCond);
+        ca_mutex_unlock(g_threadWriteCharacteristicMutex);
+
         CALEClientUpdateSendCnt(env);
     }
 
@@ -3616,12 +4407,21 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeGattDescriptorWriteCallback(JNIEnv
     VERIFY_NON_NULL_VOID(obj, TAG, "obj is null");
     VERIFY_NON_NULL_VOID(gatt, TAG, "gatt is null");
 
-    CAResult_t res = CALEClientWriteCharacteristic(env, gatt);
-    if (CA_STATUS_OK != res)
+    jint gatt_success = CALEGetConstantsValue(env, CLASSPATH_BT_GATT, "GATT_SUCCESS");
+    if (gatt_success != status) // error
     {
-        OIC_LOG(ERROR, TAG, "CALEClientWriteCharacteristic has failed");
         goto error_exit;
     }
+
+    if (g_sendBuffer)
+    {
+        CAResult_t res = CALEClientWriteCharacteristic(env, gatt);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "CALEClientWriteCharacteristic has failed");
+            goto error_exit;
+        }
+    }
     return;
 
 // error label.
index df53c3d..10066e1 100644 (file)
@@ -35,6 +35,8 @@ extern "C"
 {
 #endif
 
+static const uint16_t GATT_ERROR = 133;
+
 static const uint16_t STATE_CHARACTER_SET = 2;
 static const uint16_t STATE_CHARACTER_UNSET = 1;
 static const uint16_t STATE_CHARACTER_NO_CHANGE = 0;
@@ -43,15 +45,13 @@ static const uint16_t STATE_SEND_NONE = 0;
 static const uint16_t STATE_SEND_SUCCESS = 1;
 static const uint16_t STATE_SEND_FAILED = 2;
 
-static const jint STATE_CONNECTED = 2;
-static const jint STATE_DISCONNECTED = 0;
-
 typedef struct le_state_info
 {
     char address[CA_MACADDR_SIZE];
     jint connectedState;
     uint16_t notificationState;
     uint16_t sendState;
+    jboolean autoConnectFlag;
 } CALEState_t;
 
 /**
@@ -80,10 +80,9 @@ CAResult_t CALEClientCreateJniInterfaceObject();
 
 /**
  * initialize client for BLE.
- * @param[in]   handle                thread pool handle object.
  * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
  */
-CAResult_t CALEClientInitialize(ca_thread_pool_t handle);
+CAResult_t CALEClientInitialize();
 
 /**
  * terminate client for BLE.
@@ -91,6 +90,12 @@ CAResult_t CALEClientInitialize(ca_thread_pool_t handle);
 void CALEClientTerminate();
 
 /**
+ * destroy interface object and terminate the interface.
+ * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
+ */
+CAResult_t CALEClientDestroyJniInterface();
+
+/**
  * for destroy sending routine.
  * @param[in]   env                   JNI interface pointer.
  * @param[in]   gatt                  Gatt profile object.
@@ -146,6 +151,15 @@ void CALEClientStopMulticastServer();
 void CALEClientSetCallback(CAPacketReceiveCallback callback);
 
 /**
+ * waiting to get scanned device from BT Platform.
+ * if there is no scanned device in the list.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   address               LE address.
+ * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
+ */
+CAResult_t CALEClientIsThereScannedDevices(JNIEnv *env, const char* address);
+
+/**
  * send data for unicast (implement).
  * @param[in]   address               remote address.
  * @param[in]   data                  data for transmission.
@@ -258,17 +272,31 @@ void CALEClientSetScanFlag(bool flag);
 CAResult_t CALEClientStopScanImpl(JNIEnv *env, jobject callback);
 
 /**
+ * set auto connect flag for connectGatt API.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   jni_address           remote address.
+ * @param[in]   flag                  auto connect flag.
+ */
+CAResult_t CALEClientSetAutoConnectFlag(JNIEnv *env, jstring jni_address, jboolean flag);
+
+/**
+ * get auto connect flag.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   jni_address           remote address.
+ * @return  current auto connect flag;
+ */
+jboolean CALEClientGetAutoConnectFlag(JNIEnv *env, jstring jni_address);
+
+/**
  * connect to gatt server hosted.
  * @param[in]   env                   JNI interface pointer.
  * @param[in]   bluetoothDevice       bluetooth Device object.
  * @param[in]   autoconnect           whether to directly connect to the remote device(false) or
  *                                     to automatically connect as soon as the remote device
  *                                     becomes available.
- * @param[in]   callback              callback for connection state change.
- * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
+ * @return  gatt object
  */
-CAResult_t CALEClientConnect(JNIEnv *env, jobject bluetoothDevice, jboolean autoconnect,
-                             jobject callback);
+jobject CALEClientConnect(JNIEnv *env, jobject bluetoothDevice, jboolean autoconnect);
 
 /**
  * disconnect to gatt server by a target device.
@@ -286,6 +314,14 @@ CAResult_t CALEClientDisconnect(JNIEnv *env, jobject bluetoothGatt);
 CAResult_t CALEClientDisconnectAll(JNIEnv *env);
 
 /**
+ * disconnect to gatt server by selected address.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   remoteAddress         remote address.
+ * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
+ */
+CAResult_t CALEClientDisconnectforAddress(JNIEnv *env, jstring remoteAddress);
+
+/**
  * start discovery server.
  * @param[in]   env                   JNI interface pointer.
  * @param[in]   bluetoothGatt         Gatt profile object.
@@ -294,13 +330,21 @@ CAResult_t CALEClientDisconnectAll(JNIEnv *env);
 CAResult_t CALEClientDiscoverServices(JNIEnv *env, jobject bluetoothGatt);
 
 /**
+ * call CALESetValueAndWriteCharacteristic when connection is successful.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   gatt                  Gatt profile object.
+ * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
+ */
+CAResult_t CALEClientWriteCharacteristic(JNIEnv *env, jobject gatt);
+
+/**
  * create GattCharacteristic and call CALEClientWriteCharacteristicImpl
  * for request to write gatt characteristic.
  * @param[in]   env                   JNI interface pointer.
  * @param[in]   gatt                  Gatt profile object.
  * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
  */
-CAResult_t CALEClientWriteCharacteristic(JNIEnv *env, jobject gatt);
+CAResult_t CALESetValueAndWriteCharacteristic(JNIEnv *env, jobject gatt);
 
 /**
  * request to write gatt characteristic.
@@ -451,6 +495,14 @@ CAResult_t CALEClientRemoveGattObj(JNIEnv *env, jobject gatt);
 CAResult_t CALEClientRemoveGattObjForAddr(JNIEnv *env, jstring addr);
 
 /**
+ * get ble address from Bluetooth device.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   bluetoothDevice       Bluetooth device.
+ * @return  ble address.
+ */
+jstring CALEClientGetLEAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice);
+
+/**
  * update new state information.
  * @param[in]   address               remote address.
  * @param[in]   connectedState        connection state.
@@ -482,6 +534,13 @@ bool CALEClientIsDeviceInList(const char *remoteAddress);
 CAResult_t CALEClientRemoveAllDeviceState();
 
 /**
+ * Reset values of device state for all of devices.
+ * this method has to be invoked when BT adapter is disabled.
+ * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
+ */
+CAResult_t CALEClientResetDeviceStateForAll();
+
+/**
  * remove the device state for a remote device.
  * @param[in]   remoteAddress         remote address.
  * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
@@ -537,6 +596,23 @@ void CALEClientTerminateGattMutexVariables();
  */
 void CALEClientSetSendFinishFlag(bool flag);
 
+/**
+ * close the connection of the profile proxy to the Service.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   gatt                  gatt profile object.
+ * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
+ */
+CAResult_t CALEClientCloseProfileProxy(JNIEnv *env, jobject gatt);
+
+/**
+ * connect to GATT Server hosted by this device.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   bluetoothDevice       bluetooth device object.
+ * @param[in]   autoconnect           connect as soon as the device becomes avaiable(true).
+ * @return  gatt profile object
+ */
+jobject CALEClientGattConnect(JNIEnv *env, jobject bluetoothDevice, jboolean autoconnect);
+
 #ifdef __cplusplus
 } /* extern "C" */
 #endif
index 83dfd70..758243e 100644 (file)
 #include "camutex.h"
 
 #include "org_iotivity_ca_CaLeClientInterface.h"
+#include "org_iotivity_ca_CaLeServerInterface.h"
 
-#define TAG PCF("CA_LE_MONITOR")
-
-#define BT_STATE_ON (12)
-#define BT_STATE_OFF (10)
+#define TAG PCF("OIC_CA_LE_MONITOR")
 
 static JavaVM *g_jvm;
 
 /**
- * @var gCALEDeviceStateChangedCallback
+ * @var g_bleDeviceStateChangedCallback
  * @brief Maintains the callback to be notified on device state changed.
  */
-static CALEDeviceStateChangedCallback gCALEDeviceStateChangedCallback = NULL;
+static CALEDeviceStateChangedCallback g_bleDeviceStateChangedCallback = NULL;
 
 /**
- * @var gCALEDeviceStateChangedCbMutex
+ * @var g_bleConnectionStateChangedCallback
+ * @brief Maintains the callback to be notified on device state changed.
+ */
+static CALEConnectionStateChangedCallback g_bleConnectionStateChangedCallback = NULL;
+
+/**
+ * @var g_bleDeviceStateChangedCbMutex
  * @brief Mutex to synchronize access to the deviceStateChanged Callback when the state
  *           of the LE adapter gets change.
  */
-static ca_mutex gCALEDeviceStateChangedCbMutex = NULL;
+static ca_mutex g_bleDeviceStateChangedCbMutex = NULL;
+
+/**
+ * @var g_bleConnectionStateChangedCbMutex
+ * @brief Mutex to synchronize access to the LE ConnectionStateChanged Callback when the state
+ *           of the LE adapter gets change.
+ */
+static ca_mutex g_bleConnectionStateChangedCbMutex = NULL;
 
 //getting context
 void CALENetworkMonitorJNISetContext()
@@ -66,19 +77,16 @@ void CALENetworkMonitorJniInit()
     g_jvm = CANativeJNIGetJavaVM();
 }
 
-void CALESetNetStateCallback(CALEDeviceStateChangedCallback callback)
+void CALESetAdapterStateCallback(CALEDeviceStateChangedCallback callback)
 {
-    OIC_LOG(DEBUG, TAG, "CALESetNetStateCallback");
-    gCALEDeviceStateChangedCallback = callback;
+    OIC_LOG(DEBUG, TAG, "CALESetAdapterStateCallback");
+    g_bleDeviceStateChangedCallback = callback;
 }
 
-CAResult_t CAInitializeLEAdapter()
+CAResult_t CAInitializeLEAdapter(const ca_thread_pool_t threadPool)
 {
     OIC_LOG(DEBUG, TAG, "IN");
-
-    CALENetworkMonitorJNISetContext();
-    CALENetworkMonitorJniInit();
-
+    (void)threadPool;
     OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
@@ -90,30 +98,50 @@ CAResult_t CAStartLEAdapter()
     return CA_STATUS_OK;
 }
 
+CAResult_t CAStopLEAdapter()
+{
+    // Nothing to do.
+
+    return CA_STATUS_OK;
+}
+
 CAResult_t CAInitLENwkMonitorMutexVaraibles()
 {
     OIC_LOG(DEBUG, TAG, "IN");
-    if (NULL == gCALEDeviceStateChangedCbMutex)
+    if (NULL == g_bleDeviceStateChangedCbMutex)
     {
-        gCALEDeviceStateChangedCbMutex = ca_mutex_new();
-        if (NULL == gCALEDeviceStateChangedCbMutex)
+        g_bleDeviceStateChangedCbMutex = ca_mutex_new();
+        if (NULL == g_bleDeviceStateChangedCbMutex)
         {
             OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
             return CA_STATUS_FAILED;
         }
     }
 
+    if (NULL == g_bleConnectionStateChangedCbMutex)
+    {
+       g_bleConnectionStateChangedCbMutex = ca_mutex_new();
+        if (NULL == g_bleConnectionStateChangedCbMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            ca_mutex_free(g_bleDeviceStateChangedCbMutex);
+            return CA_STATUS_FAILED;
+        }
+    }
+
     OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
-
 }
 
 void CATerminateLENwkMonitorMutexVaraibles()
 {
     OIC_LOG(DEBUG, TAG, "IN");
 
-    ca_mutex_free(gCALEDeviceStateChangedCbMutex);
-    gCALEDeviceStateChangedCbMutex = NULL;
+    ca_mutex_free(g_bleDeviceStateChangedCbMutex);
+    g_bleDeviceStateChangedCbMutex = NULL;
+
+    ca_mutex_free(g_bleConnectionStateChangedCbMutex);
+    g_bleConnectionStateChangedCbMutex = NULL;
 
     OIC_LOG(DEBUG, TAG, "OUT");
 }
@@ -174,6 +202,9 @@ CAResult_t CAInitializeLENetworkMonitor()
         return CA_STATUS_FAILED;
     }
 
+    CALENetworkMonitorJNISetContext();
+    CALENetworkMonitorJniInit();
+
     OIC_LOG(DEBUG, TAG, "OUT");
 
     return CA_STATUS_OK;
@@ -195,9 +226,9 @@ CAResult_t CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCallback callback)
 
     OIC_LOG(DEBUG, TAG, "Setting CALEDeviceStateChangedCallback");
 
-    ca_mutex_lock(gCALEDeviceStateChangedCbMutex);
-    CALESetNetStateCallback(callback);
-    ca_mutex_unlock(gCALEDeviceStateChangedCbMutex);
+    ca_mutex_lock(g_bleDeviceStateChangedCbMutex);
+    CALESetAdapterStateCallback(callback);
+    ca_mutex_unlock(g_bleDeviceStateChangedCbMutex);
 
     OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
@@ -209,6 +240,26 @@ CAResult_t CAUnSetLEAdapterStateChangedCb()
     return CA_STATUS_OK;
 }
 
+CAResult_t CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCallback callback)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    ca_mutex_lock(g_bleConnectionStateChangedCbMutex);
+    g_bleConnectionStateChangedCallback = callback;
+    ca_mutex_unlock(g_bleConnectionStateChangedCbMutex);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAUnsetLENWConnectionStateChangedCb()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    ca_mutex_lock(g_bleConnectionStateChangedCbMutex);
+    g_bleConnectionStateChangedCallback = NULL;
+    ca_mutex_unlock(g_bleConnectionStateChangedCbMutex);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
 JNIEXPORT void JNICALL
 Java_org_iotivity_ca_CaLeClientInterface_caLeStateChangedCallback(JNIEnv *env, jobject obj,
                                                                    jint status)
@@ -216,35 +267,33 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeStateChangedCallback(JNIEnv *env, j
     VERIFY_NON_NULL_VOID(env, TAG, "env is null");
     VERIFY_NON_NULL_VOID(obj, TAG, "obj is null");
 
-    OIC_LOG(DEBUG, TAG, "CaLeClientInterface - Network State Changed");
+    OIC_LOG_V(DEBUG, TAG, "CaLeClientInterface - Network State Changed : status(%d)", status);
 
-    if (!gCALEDeviceStateChangedCallback)
+    if (!g_bleDeviceStateChangedCallback)
     {
-        OIC_LOG_V(ERROR, TAG, "gNetworkChangeCb is null", status);
+        OIC_LOG(ERROR, TAG, "gNetworkChangeCb is null");
         return;
     }
 
-    if (BT_STATE_ON == status) // STATE_ON:12
+    jint state_on = CALEGetConstantsValue(env, CLASSPATH_BT_ADAPTER, "STATE_ON");
+    jint state_off = CALEGetConstantsValue(env, CLASSPATH_BT_ADAPTER, "STATE_OFF");
+    jint state_turning_off = CALEGetConstantsValue(env, CLASSPATH_BT_ADAPTER, "STATE_TURNING_OFF");
+
+    if (state_on == status) // STATE_ON:12
     {
         CANetworkStatus_t newStatus = CA_INTERFACE_UP;
         CALEClientCreateDeviceList();
         CALEServerCreateCachedDeviceList();
 
-        CAResult_t res = CALEClientStartScan();
-        if (CA_STATUS_OK != res)
-        {
-            OIC_LOG(ERROR, TAG, "CALEClientStartScan has failed");
-        }
-
-        res = CALEStartAdvertise();
-        if (CA_STATUS_OK != res)
-        {
-            OIC_LOG(ERROR, TAG, "CALEStartAdvertise has failed");
-        }
-
-        gCALEDeviceStateChangedCallback(newStatus);
+        g_bleDeviceStateChangedCallback(newStatus);
     }
-    else if (BT_STATE_OFF == status) // STATE_OFF:10
+    else if (state_turning_off == status) // BT_STATE_TURNING_OFF:13
+    {
+        // gatt Device list will be removed.
+        // so it is need to create list again when adapter is enabled.
+        CAStopLEGattClient();
+    }
+    else if (state_off == status) // STATE_OFF:10
     {
         // remove obj for client
         CAResult_t res = CALEClientRemoveAllGattObjs(env);
@@ -253,19 +302,13 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeStateChangedCallback(JNIEnv *env, j
             OIC_LOG(ERROR, TAG, "CALEClientRemoveAllGattObjs has failed");
         }
 
-        res = CALEClientRemoveAllScanDevices(env);
+        res = CALEClientResetDeviceStateForAll();
         if (CA_STATUS_OK != res)
         {
-            OIC_LOG(ERROR, TAG, "CALEClientRemoveAllScanDevices has failed");
+            OIC_LOG(ERROR, TAG, "CALEClientResetDeviceStateForAll has failed");
         }
 
-        res = CALEClientRemoveAllDeviceState();
-        if (CA_STATUS_OK != res)
-        {
-            OIC_LOG(ERROR, TAG, "CALEClientRemoveAllDeviceState has failed");
-        }
-
-        // remove obej for server
+        // remove obj for server
         res = CALEServerRemoveAllDevices(env);
         if (CA_STATUS_OK != res)
         {
@@ -275,37 +318,125 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeStateChangedCallback(JNIEnv *env, j
         CALEClientSetScanFlag(false);
 
         CANetworkStatus_t newStatus = CA_INTERFACE_DOWN;
-        gCALEDeviceStateChangedCallback(newStatus);
+        g_bleDeviceStateChangedCallback(newStatus);
     }
 }
 
 JNIEXPORT void JNICALL
 Java_org_iotivity_ca_CaLeClientInterface_caLeBondStateChangedCallback(JNIEnv *env, jobject obj,
-                                                                       jstring addr)
+                                                                      jstring jaddr)
 {
     OIC_LOG(DEBUG, TAG, "CaLeClientInterface - Bond State Changed");
     VERIFY_NON_NULL_VOID(env, TAG, "env is null");
     VERIFY_NON_NULL_VOID(obj, TAG, "obj is null");
-    VERIFY_NON_NULL_VOID(addr, TAG, "addr is null");
+    VERIFY_NON_NULL_VOID(jaddr, TAG, "jaddr is null");
+
+    // geneally 'addr' parameter will be not ble address, if you didn't bond for BLE.
+    // below logics will be needed when ble pairing is set.
+
+    CAResult_t res = CALEClientDisconnectforAddress(env, jaddr);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "CALEClientDisconnectforAddress has failed");
+    }
 
     // remove obj for client
-    CAResult_t res = CALEClientRemoveGattObjForAddr(env, addr);
+    res = CALEClientRemoveGattObjForAddr(env, jaddr);
     if (CA_STATUS_OK != res)
     {
         OIC_LOG(ERROR, TAG, "CANativeRemoveGattObjForAddr has failed");
     }
 
-    res = CALEClientRemoveDeviceInScanDeviceList(env, addr);
+    res = CALEClientRemoveDeviceInScanDeviceList(env, jaddr);
     if (CA_STATUS_OK != res)
     {
         OIC_LOG(ERROR, TAG, "CALEClientRemoveDeviceInScanDeviceList has failed");
     }
 
     // remove obej for server
-    res = CALEServerRemoveDevice(env, addr);
+    res = CALEServerRemoveDevice(env, jaddr);
     if (CA_STATUS_OK != res)
     {
         OIC_LOG(ERROR, TAG, "CALEServerRemoveDevice has failed");
     }
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaLeClientInterface_caLeGattNWConnectionStateChangeCallback(JNIEnv *env,
+                                                                                 jobject obj,
+                                                                                 jobject gatt,
+                                                                                 jint status,
+                                                                                 jint newstate)
+{
+    VERIFY_NON_NULL_VOID(env, TAG, "env is null");
+    VERIFY_NON_NULL_VOID(obj, TAG, "obj is null");
+    VERIFY_NON_NULL_VOID(gatt, TAG, "gatt is null");
+
+    OIC_LOG_V(DEBUG, TAG, "CALeGattNWConnectionStateChangeCallback - status %d, newstate %d",
+              status, newstate);
+
+    jint state_disconnected = CALEGetConstantsValue(env, CLASSPATH_BT_PROFILE,
+                                                    "STATE_DISCONNECTED");
+    if (state_disconnected == newstate)
+    {
+        jstring jni_address = CALEClientGetAddressFromGattObj(env, gatt);
+        if (!jni_address)
+        {
+            OIC_LOG(ERROR, TAG, "jni_address is null");
+            return;
+        }
 
+        const char* address = (*env)->GetStringUTFChars(env, jni_address, NULL);
+        if (!address)
+        {
+            OIC_LOG(ERROR, TAG, "address is null");
+            return;
+        }
+
+        if (g_bleConnectionStateChangedCallback)
+        {
+            g_bleConnectionStateChangedCallback(CA_ADAPTER_GATT_BTLE, address, false);
+        }
+
+        (*env)->ReleaseStringUTFChars(env, jni_address, address);
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaLeServerInterface_caLeGattServerNWConnectionStateChangeCallback(
+        JNIEnv *env, jobject obj, jobject device, jint status, jint newState)
+{
+    OIC_LOG(DEBUG, TAG, " Gatt Server NWConnectionStateChange Callback");
+
+    VERIFY_NON_NULL_VOID(env, TAG, "env");
+    VERIFY_NON_NULL_VOID(obj, TAG, "obj");
+    VERIFY_NON_NULL_VOID(device, TAG, "device");
+    (void)status;
+
+    // STATE_DISCONNECTED
+    jint state_disconnected = CALEGetConstantsValue(env, CLASSPATH_BT_PROFILE,
+                                                    "STATE_DISCONNECTED");
+    if (state_disconnected == newState)
+    {
+        jstring jni_remoteAddress = CALEGetAddressFromBTDevice(env, device);
+        if (!jni_remoteAddress)
+        {
+            OIC_LOG(ERROR, TAG, "jni_remoteAddress is null");
+            return;
+        }
+
+        const char* address = (*env)->GetStringUTFChars(env, jni_remoteAddress, NULL);
+        if (!address)
+        {
+            OIC_LOG(ERROR, TAG, "address is null");
+            return;
+        }
+
+        if (g_bleConnectionStateChangedCallback)
+        {
+            g_bleConnectionStateChangedCallback(CA_ADAPTER_GATT_BTLE, address, false);
+        }
+
+        (*env)->ReleaseStringUTFChars(env, jni_remoteAddress, address);
+    }
 }
index 25f20d9..50fc1a0 100644 (file)
@@ -51,7 +51,7 @@ void CALENetworkMonitorJniInit();
  * @param[in]  callback    Callback to be notified on reception of BT state information.
 
  */
-void CALESetNetStateCallback(CALEDeviceStateChangedCallback callback);
+void CALESetAdapterStateCallback(CALEDeviceStateChangedCallback callback);
 
 #ifdef __cplusplus
 } /* extern "C" */
index 687cadf..6237bac 100644 (file)
 #include "uarraylist.h"
 #include "org_iotivity_ca_CaLeServerInterface.h"
 
-#define TAG PCF("CA_LE_SERVER")
+#define TAG PCF("OIC_CA_LE_SERVER")
+
+#define WAIT_TIME_WRITE_CHARACTERISTIC 10000000
 
 static JavaVM *g_jvm = NULL;
 static jobject g_context = NULL;
 static jobject g_bluetoothGattServer = NULL;
 static jobject g_bluetoothGattServerCallback = NULL;
 static jobject g_leAdvertiseCallback = NULL;
+static jobject g_bluetoothManager = NULL;
 
 static CAPacketReceiveCallback g_packetReceiveCallback = NULL;
 static CABLEErrorHandleCallback g_serverErrorCallback;
 
 static u_arraylist_t *g_connectedDeviceList = NULL;
-static ca_thread_pool_t g_threadPoolHandle = NULL;
 
 static bool g_isStartServer = false;
 static bool g_isInitializedServer = false;
 
+static jbyteArray g_sendBuffer = NULL;
+static jobject g_obj_bluetoothDevice = NULL;
+
 static CABLEDataReceivedCallback g_CABLEServerDataReceivedCallback = NULL;
 static ca_mutex g_bleReqRespCbMutex = NULL;
 static ca_mutex g_bleClientBDAddressMutex = NULL;
 static ca_mutex g_connectedDeviceListMutex = NULL;
 
+static ca_mutex g_threadSendMutex = NULL;
+static ca_mutex g_threadSendNotifyMutex = NULL;
+static ca_cond g_threadSendNotifyCond = NULL;
+static bool g_isSignalSetFlag = false;
+
+static const char CLASSPATH_BT_ADVERTISE_CB[] = "android/bluetooth/le/AdvertiseCallback";
+static const char CLASSPATH_BT_GATTSERVER[] = "android/bluetooth/BluetoothGattServer";
+
 void CALEServerJNISetContext()
 {
     OIC_LOG(DEBUG, TAG, "CALEServerJNISetContext");
@@ -136,6 +149,42 @@ CAResult_t CALEServerCreateJniInterfaceObject()
     return CA_STATUS_FAILED;
 }
 
+/**
+ * get the current connection state of the gatt profile to the remote device.
+ * @param[in]   env              JNI interface pointer.
+ * @param[in]   device           bluetooth device object
+ * @return  state of the profile connection.
+ */
+static jint CALEServerGetConnectionState(JNIEnv *env, jobject device)
+{
+    OIC_LOG(DEBUG, TAG, "CALEServerGetConnectionState");
+
+    VERIFY_NON_NULL_RET(env, TAG, "env", -1);
+    VERIFY_NON_NULL_RET(device, TAG, "device", -1);
+
+    jmethodID jni_mid_getConnectionState = CALEGetJNIMethodID(env, "android/bluetooth/BluetoothManager",
+                                                              "getConnectionState",
+                                                              "(Landroid/bluetooth/BluetoothDevice"
+                                                              ";I)I");
+    if (!jni_mid_getConnectionState)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getConnectionState is null");
+        return -1;
+    }
+
+    if (!g_bluetoothManager)
+    {
+        OIC_LOG(ERROR, TAG, "g_bluetoothManager is null");
+        return -1;
+    }
+
+    jint jni_state = (jint)(*env)->CallIntMethod(env, g_bluetoothManager,
+                                                 jni_mid_getConnectionState,
+                                                 device, GATT_PROFILE);
+    OIC_LOG_V(INFO, TAG, "connection state is %d", jni_state);
+    return jni_state;
+}
+
 jobject CALEServerSetResponseData(JNIEnv *env, jbyteArray responseData)
 {
     OIC_LOG(DEBUG, TAG, "IN - CALEServerSetResponseData");
@@ -155,35 +204,10 @@ jobject CALEServerSetResponseData(JNIEnv *env, jbyteArray responseData)
     }
 
     OIC_LOG(DEBUG, TAG, "CALEServerSetResponseData");
-
-    jclass jni_cid_bluetoothGattServer = (*env)->FindClass(env,
-                                                           "android/bluetooth/BluetoothGattServer");
-    if (!jni_cid_bluetoothGattServer)
-    {
-        OIC_LOG(ERROR, TAG, "jni_cid_bluetoothGattServer is null");
-        return NULL;
-    }
-
-    jclass jni_cid_bluetoothGattService = (*env)->FindClass(env, "android/bluetooth/"
-                                                            "BluetoothGattService");
-    if (!jni_cid_bluetoothGattService)
-    {
-        OIC_LOG(ERROR, TAG, "jni_cid_bluetoothGattService is null");
-        return NULL;
-    }
-
-    jclass jni_cid_bluetoothGattCharacteristic = (*env)->FindClass(env, "android/bluetooth/"
-                                                                   "BluetoothGattCharacteristic");
-    if (!jni_cid_bluetoothGattCharacteristic)
-    {
-        OIC_LOG(ERROR, TAG, "jni_cid_bluetoothGattCharacteristic is null");
-        return NULL;
-    }
-
-    jmethodID jni_mid_getService = (*env)->GetMethodID(env, jni_cid_bluetoothGattServer,
-                                                       "getService",
-                                                       "(Ljava/util/UUID;)Landroid/bluetooth/"
-                                                       "BluetoothGattService;");
+    jmethodID jni_mid_getService = CALEGetJNIMethodID(env, CLASSPATH_BT_GATTSERVER,
+                                                      "getService",
+                                                      "(Ljava/util/UUID;)Landroid/bluetooth/"
+                                                      "BluetoothGattService;");
     if (!jni_mid_getService)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_getService is null");
@@ -206,11 +230,12 @@ jobject CALEServerSetResponseData(JNIEnv *env, jbyteArray responseData)
         return NULL;
     }
 
-    jmethodID jni_mid_getCharacteristic = (*env)->GetMethodID(env, jni_cid_bluetoothGattService,
-                                                              "getCharacteristic",
-                                                              "(Ljava/util/UUID;)"
-                                                              "Landroid/bluetooth/"
-                                                              "BluetoothGattCharacteristic;");
+    jmethodID jni_mid_getCharacteristic = CALEGetJNIMethodID(env, "android/bluetooth/"
+                                                             "BluetoothGattService",
+                                                             "getCharacteristic",
+                                                             "(Ljava/util/UUID;)"
+                                                             "Landroid/bluetooth/"
+                                                             "BluetoothGattCharacteristic;");
     if (!jni_mid_getCharacteristic)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_getCharacteristic is null");
@@ -233,8 +258,9 @@ jobject CALEServerSetResponseData(JNIEnv *env, jbyteArray responseData)
         return NULL;
     }
 
-    jmethodID jni_mid_setValue = (*env)->GetMethodID(env, jni_cid_bluetoothGattCharacteristic,
-                                                     "setValue", "([B)Z");
+    jmethodID jni_mid_setValue = CALEGetJNIMethodID(env, "android/bluetooth/"
+                                                    "BluetoothGattCharacteristic",
+                                                    "setValue", "([B)Z");
     if (!jni_mid_setValue)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_setValue is null");
@@ -255,7 +281,7 @@ jobject CALEServerSetResponseData(JNIEnv *env, jbyteArray responseData)
 
 CAResult_t CALEServerSendResponseData(JNIEnv *env, jobject device, jobject responseData)
 {
-    OIC_LOG(DEBUG, TAG, "IN - CALEServerSendResponseData");
+    OIC_LOG(DEBUG, TAG, "CALEServerSendResponseData");
     VERIFY_NON_NULL(responseData, TAG, "responseData is null");
     VERIFY_NON_NULL(device, TAG, "device is null");
     VERIFY_NON_NULL(env, TAG, "env is null");
@@ -266,24 +292,26 @@ CAResult_t CALEServerSendResponseData(JNIEnv *env, jobject device, jobject respo
         return CA_ADAPTER_NOT_ENABLED;
     }
 
-    jclass jni_cid_bluetoothGattServer = (*env)->FindClass(env,
-                                                           "android/bluetooth/BluetoothGattServer");
-    if (!jni_cid_bluetoothGattServer)
+    if (STATE_CONNECTED != CALEServerGetConnectionState(env, device))
     {
-        OIC_LOG(ERROR, TAG, "jni_cid_bluetoothGattServer is null");
+        OIC_LOG(ERROR, TAG, "it is not connected state");
         return CA_STATUS_FAILED;
     }
 
-    jmethodID jni_mid_notifyCharacteristicChanged = (*env)->GetMethodID(
-            env, jni_cid_bluetoothGattServer, "notifyCharacteristicChanged",
-            "(Landroid/bluetooth/BluetoothDevice;"
-            "Landroid/bluetooth/BluetoothGattCharacteristic;Z)Z");
+    jmethodID jni_mid_notifyCharacteristicChanged = CALEGetJNIMethodID(env,
+                                                      CLASSPATH_BT_GATTSERVER,
+                                                      "notifyCharacteristicChanged",
+                                                      "(Landroid/bluetooth/BluetoothDevice;"
+                                                      "Landroid/bluetooth/"
+                                                      "BluetoothGattCharacteristic;Z)Z");
     if (!jni_mid_notifyCharacteristicChanged)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_notifyCharacteristicChanged is null");
         return CA_STATUS_FAILED;
     }
 
+    OIC_LOG(DEBUG, TAG, "CALL API - notifyCharacteristicChanged");
+
     jboolean jni_boolean_notifyCharacteristicChanged = (*env)->CallBooleanMethod(
             env, g_bluetoothGattServer, jni_mid_notifyCharacteristicChanged, device, responseData,
             JNI_FALSE);
@@ -293,7 +321,23 @@ CAResult_t CALEServerSendResponseData(JNIEnv *env, jobject device, jobject respo
         return CA_SEND_FAILED;
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT - CALEServerSendResponseData");
+    OIC_LOG_V(DEBUG, TAG, "callback flag is %d", g_isSignalSetFlag);
+    ca_mutex_lock(g_threadSendNotifyMutex);
+    if (!g_isSignalSetFlag)
+    {
+        OIC_LOG(DEBUG, TAG, "wait for callback to notify notifyCharacteristic is success");
+        if (0 != ca_cond_wait_for(g_threadSendNotifyCond, g_threadSendNotifyMutex,
+                                  WAIT_TIME_WRITE_CHARACTERISTIC))
+        {
+            OIC_LOG(ERROR, TAG, "there is no response. notifyCharacteristic has failed");
+            ca_mutex_unlock(g_threadSendNotifyMutex);
+            return CA_STATUS_FAILED;
+        }
+    }
+    // reset flag set by writeCharacteristic Callback
+    g_isSignalSetFlag = false;
+    ca_mutex_unlock(g_threadSendNotifyMutex);
+    OIC_LOG(INFO, TAG, "notifyCharacteristic success");
     return CA_STATUS_OK;
 }
 
@@ -313,18 +357,10 @@ CAResult_t CALEServerSendResponse(JNIEnv *env, jobject device, jint requestId, j
         return CA_ADAPTER_NOT_ENABLED;
     }
 
-    jclass jni_cid_bluetoothGattServer = (*env)->FindClass(env,
-                                                           "android/bluetooth/BluetoothGattServer");
-    if (!jni_cid_bluetoothGattServer)
-    {
-        OIC_LOG(ERROR, TAG, "jni_cid_bluetoothGattServer is null");
-        return CA_STATUS_FAILED;
-    }
-
-    jmethodID jni_mid_sendResponse = (*env)->GetMethodID(env, jni_cid_bluetoothGattServer,
-                                                         "sendResponse",
-                                                         "(Landroid/bluetooth/BluetoothDevice;"
-                                                         "III[B)Z");
+    jmethodID jni_mid_sendResponse = CALEGetJNIMethodID(env, CLASSPATH_BT_GATTSERVER,
+                                                        "sendResponse",
+                                                        "(Landroid/bluetooth/BluetoothDevice;"
+                                                        "III[B)Z");
     if (!jni_mid_sendResponse)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_sendResponse is null");
@@ -358,7 +394,7 @@ CAResult_t CALEStartAdvertise()
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
-        OIC_LOG(ERROR, TAG, "Could not get JNIEnv pointer");
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
         res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
 
         if (JNI_OK != res)
@@ -500,6 +536,15 @@ CAResult_t CALEServerStartAdvertise(JNIEnv *env, jobject advertiseCallback)
         return CA_STATUS_FAILED;
     }
 
+    jobject jni_AdvertiseDataBuilderForScanRsp = (*env)->NewObject(env,
+                                                                   jni_cid_AdvertiseDataBuilder,
+                                                                   jni_mid_AdvertiseDataBuilder);
+    if (!jni_AdvertiseDataBuilderForScanRsp)
+    {
+        OIC_LOG(ERROR, TAG, "jni_AdvertiseDataBuilderForScanRsp is null");
+        return CA_STATUS_FAILED;
+    }
+
     jobject jni_obj_serviceUUID = CALEGetUuidFromString(env, OIC_GATT_SERVICE_UUID);
     if (!jni_obj_serviceUUID)
     {
@@ -533,6 +578,29 @@ CAResult_t CALEServerStartAdvertise(JNIEnv *env, jobject advertiseCallback)
         return CA_STATUS_FAILED;
     }
 
+    // Device name has to be included in advertise packet after Android API 23
+    OIC_LOG(DEBUG, TAG, "device name will be added into advertise packet");
+    jmethodID jni_mid_setIncludeDeviceName = (*env)->GetMethodID(env, jni_cid_AdvertiseDataBuilder,
+                                                                 "setIncludeDeviceName",
+                                                                 "(Z)Landroid/"
+                                                                 "bluetooth/le/"
+                                                                 "AdvertiseData$Builder;");
+    if (!jni_mid_setIncludeDeviceName)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_setIncludeDeviceName is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jobject jni_obj_setIncludeDeviceName  = (*env)->CallObjectMethod(env,
+                                                               jni_AdvertiseDataBuilderForScanRsp,
+                                                               jni_mid_setIncludeDeviceName,
+                                                               JNI_TRUE);
+    if (!jni_obj_setIncludeDeviceName)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_setIncludeDeviceName is null");
+        return CA_STATUS_FAILED;
+    }
+
     jclass jni_cid_BTAdapter = (*env)->FindClass(env, "android/bluetooth/BluetoothAdapter");
     if (!jni_cid_BTAdapter)
     {
@@ -613,20 +681,23 @@ CAResult_t CALEServerStartAdvertise(JNIEnv *env, jobject advertiseCallback)
         return CA_STATUS_FAILED;
     }
 
-    jclass jni_cid_leAdvertiser = (*env)->FindClass(env,
-                                                    "android/bluetooth/le/BluetoothLeAdvertiser");
-    if (!jni_cid_leAdvertiser)
+    jobject jni_obj_build_LeAdvertiseDataForScanRsp = (*env)->CallObjectMethod(env,
+                                                                jni_AdvertiseDataBuilderForScanRsp,
+                                                                jni_mid_build_LeAdvertiseData);
+    if (!jni_obj_build_LeAdvertiseDataForScanRsp)
     {
-        OIC_LOG(ERROR, TAG, "jni_cid_leAdvertiser is null");
+        OIC_LOG(ERROR, TAG, "jni_obj_build_LeAdvertiseDataForScanRsp is null");
         return CA_STATUS_FAILED;
     }
 
-    jmethodID jni_mid_startAdvertising = (*env)->GetMethodID(env, jni_cid_leAdvertiser,
-                                                             "startAdvertising",
-                                                             "(Landroid/bluetooth/le/"
-                                                             "AdvertiseSettings;Landroid/bluetooth/"
-                                                             "le/AdvertiseData;Landroid/bluetooth/"
-                                                             "le/AdvertiseCallback;)V");
+    jmethodID jni_mid_startAdvertising = CALEGetJNIMethodID(env, "android/bluetooth/le/"
+                                                            "BluetoothLeAdvertiser",
+                                                            "startAdvertising",
+                                                            "(Landroid/bluetooth/le/"
+                                                            "AdvertiseSettings;Landroid/bluetooth/"
+                                                            "le/AdvertiseData;Landroid/bluetooth/"
+                                                            "le/AdvertiseData;Landroid/bluetooth/"
+                                                            "le/AdvertiseCallback;)V");
     if (!jni_mid_startAdvertising)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_startAdvertising is null");
@@ -635,7 +706,7 @@ CAResult_t CALEServerStartAdvertise(JNIEnv *env, jobject advertiseCallback)
 
     (*env)->CallVoidMethod(env, jni_obj_getBluetoothLeAdvertiser, jni_mid_startAdvertising,
                            jni_obj_build_LeAdvertiseSettings, jni_obj_build_LeAdvertiseData,
-                           advertiseCallback);
+                           jni_obj_build_LeAdvertiseDataForScanRsp, advertiseCallback);
 
     if ((*env)->ExceptionCheck(env))
     {
@@ -653,7 +724,7 @@ CAResult_t CALEServerStartAdvertise(JNIEnv *env, jobject advertiseCallback)
 
 CAResult_t CALEServerStopAdvertise(JNIEnv *env, jobject advertiseCallback)
 {
-    OIC_LOG(DEBUG, TAG, "IN - LEServerStopAdvertise");
+    OIC_LOG(DEBUG, TAG, "LEServerStopAdvertise");
     VERIFY_NON_NULL(env, TAG, "env is null");
     VERIFY_NON_NULL(advertiseCallback, TAG, "advertiseCallback is null");
 
@@ -670,14 +741,6 @@ CAResult_t CALEServerStopAdvertise(JNIEnv *env, jobject advertiseCallback)
         return CA_STATUS_FAILED;
     }
 
-    jclass jni_cid_leAdvertiser = (*env)->FindClass(env,
-                                                    "android/bluetooth/le/BluetoothLeAdvertiser");
-    if (!jni_cid_leAdvertiser)
-    {
-        OIC_LOG(ERROR, TAG, "jni_cid_leAdvertiser is null");
-        return CA_STATUS_FAILED;
-    }
-
     jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
                                                                     "getDefaultAdapter",
                                                                     "()Landroid/bluetooth/"
@@ -698,10 +761,11 @@ CAResult_t CALEServerStopAdvertise(JNIEnv *env, jobject advertiseCallback)
         return CA_STATUS_FAILED;
     }
 
-    jmethodID jni_mid_stopAdvertising = (*env)->GetMethodID(env, jni_cid_leAdvertiser,
-                                                            "stopAdvertising",
-                                                            "(Landroid/bluetooth/le/"
-                                                            "AdvertiseCallback;)V");
+    jmethodID jni_mid_stopAdvertising = CALEGetJNIMethodID(env, "android/bluetooth/le/"
+                                                           "BluetoothLeAdvertiser",
+                                                          "stopAdvertising",
+                                                          "(Landroid/bluetooth/le/"
+                                                          "AdvertiseCallback;)V");
     if (!jni_mid_stopAdvertising)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_stopAdvertising is null");
@@ -735,8 +799,6 @@ CAResult_t CALEServerStopAdvertise(JNIEnv *env, jobject advertiseCallback)
     }
 
     OIC_LOG(DEBUG, TAG, "Advertising stopped!!");
-
-    OIC_LOG(DEBUG, TAG, "OUT - LEServerStopAdvertise");
     return CA_STATUS_OK;
 }
 
@@ -810,13 +872,6 @@ jobject CALEServerOpenGattServer(JNIEnv *env)
         return NULL;
     }
 
-    jclass jni_cid_bluetoothManager = (*env)->FindClass(env, "android/bluetooth/BluetoothManager");
-    if (!jni_cid_bluetoothManager)
-    {
-        OIC_LOG(ERROR, TAG, "jni_cid_bluetoothManager is null");
-        return NULL;
-    }
-
     jfieldID jni_fid_bluetoothService = (*env)->GetStaticFieldID(env, jni_cid_context,
                                                                  "BLUETOOTH_SERVICE",
                                                                  "Ljava/lang/String;");
@@ -836,13 +891,14 @@ jobject CALEServerOpenGattServer(JNIEnv *env)
         return NULL;
     }
 
-    jmethodID jni_mid_openGattServer = (*env)->GetMethodID(env, jni_cid_bluetoothManager,
-                                                           "openGattServer",
-                                                           "(Landroid/content/Context;"
-                                                           "Landroid/bluetooth/"
-                                                           "BluetoothGattServerCallback;)"
-                                                           "Landroid/bluetooth/"
-                                                           "BluetoothGattServer;");
+    jmethodID jni_mid_openGattServer = CALEGetJNIMethodID(env, "android/bluetooth/"
+                                                          "BluetoothManager",
+                                                          "openGattServer",
+                                                          "(Landroid/content/Context;"
+                                                          "Landroid/bluetooth/"
+                                                          "BluetoothGattServerCallback;)"
+                                                          "Landroid/bluetooth/"
+                                                          "BluetoothGattServer;");
     if (!jni_mid_openGattServer)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_openGattServer is null");
@@ -866,6 +922,12 @@ jobject CALEServerOpenGattServer(JNIEnv *env)
         return NULL;
     }
 
+    if (g_bluetoothManager)
+    {
+        (*env)->DeleteGlobalRef(env, g_bluetoothManager);
+    }
+    g_bluetoothManager = (*env)->NewGlobalRef(env, jni_obj_bluetoothManager);
+
     jobject jni_obj_bluetoothGattServer = (*env)->CallObjectMethod(env, jni_obj_bluetoothManager,
                                                                    jni_mid_openGattServer,
                                                                    g_context,
@@ -1067,7 +1129,7 @@ jobject CALEServerCreateGattService(JNIEnv *env)
 
 CAResult_t CALEServerAddDescriptor(JNIEnv *env, jobject characteristic)
 {
-    OIC_LOG(DEBUG, TAG, "IN - CALEServerAddDescriptor");
+    OIC_LOG(DEBUG, TAG, "CALEServerAddDescriptor");
     VERIFY_NON_NULL(env, TAG, "env is null");
     VERIFY_NON_NULL(characteristic, TAG, "characteristic is null");
 
@@ -1150,8 +1212,6 @@ CAResult_t CALEServerAddDescriptor(JNIEnv *env, jobject characteristic)
     {
         OIC_LOG(DEBUG, TAG, "addDescriptor success");
     }
-
-    OIC_LOG(DEBUG, TAG, "OUT - CALEServerAddDescriptor");
     return CA_STATUS_OK;
 }
 
@@ -1169,23 +1229,15 @@ CAResult_t CALEServerAddGattService(JNIEnv *env, jobject bluetoothGattServer,
         return CA_ADAPTER_NOT_ENABLED;
     }
 
-    jclass jni_cid_bluetoothGattServer = (*env)->FindClass(env,
-                                                           "android/bluetooth/BluetoothGattServer");
-    if (!jni_cid_bluetoothGattServer)
-    {
-        OIC_LOG(ERROR, TAG, "jni_cid_bluetoothGattServer is null");
-        return CA_STATUS_FAILED;
-    }
-
-    jmethodID jni_mid_addService = (*env)->GetMethodID(env, jni_cid_bluetoothGattServer,
-                                                       "addService",
-                                                       "(Landroid/bluetooth/BluetoothGattService;)"
-                                                       "Z");
-    if (!jni_mid_addService)
-    {
-        OIC_LOG(ERROR, TAG, "jni_mid_addService is null");
-        return CA_STATUS_FAILED;
-    }
+    jmethodID jni_mid_addService = CALEGetJNIMethodID(env, CLASSPATH_BT_GATTSERVER,
+                                                      "addService",
+                                                      "(Landroid/bluetooth/BluetoothGattService;)"
+                                                      "Z");
+     if (!jni_mid_addService)
+     {
+         OIC_LOG(ERROR, TAG, "jni_mid_addService is null");
+         return CA_STATUS_FAILED;
+     }
 
     jboolean jni_boolean_addService = (*env)->CallBooleanMethod(env, bluetoothGattServer,
                                                                 jni_mid_addService,
@@ -1213,16 +1265,9 @@ CAResult_t CALEServerConnect(JNIEnv *env, jobject bluetoothDevice)
         return CA_ADAPTER_NOT_ENABLED;
     }
 
-    jclass jni_cid_bluetoothGattServer = (*env)->FindClass(env,
-                                                           "android/bluetooth/BluetoothGattServer");
-    if (!jni_cid_bluetoothGattServer)
-    {
-        OIC_LOG(ERROR, TAG, "jni_cid_bluetoothGattServer is null");
-        return CA_STATUS_FAILED;
-    }
-
-    jmethodID jni_mid_connect = (*env)->GetMethodID(env, jni_cid_bluetoothGattServer, "connect",
-                                                    "(Landroid/bluetooth/BluetoothDevice;Z)Z");
+    jmethodID jni_mid_connect = CALEGetJNIMethodID(env, CLASSPATH_BT_GATTSERVER,
+                                                   "connect",
+                                                   "(Landroid/bluetooth/BluetoothDevice;Z)Z");
     if (!jni_mid_connect)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_connect is null");
@@ -1291,18 +1336,10 @@ CAResult_t CALEServerDisconnect(JNIEnv *env, jobject bluetoothDevice)
         return CA_ADAPTER_NOT_ENABLED;
     }
 
-    jclass jni_cid_bluetoothGattServer = (*env)->FindClass(env,
-                                                           "android/bluetooth/BluetoothGattServer");
-    if (!jni_cid_bluetoothGattServer)
-    {
-        OIC_LOG(ERROR, TAG, "jni_cid_bluetoothGattServer is null");
-        return CA_STATUS_FAILED;
-    }
-
-    jmethodID jni_mid_cancelConnection = (*env)->GetMethodID(env, jni_cid_bluetoothGattServer,
-                                                             "cancelConnection",
-                                                             "(Landroid/bluetooth/BluetoothDevice;)"
-                                                             "V");
+    jmethodID jni_mid_cancelConnection = CALEGetJNIMethodID(env, CLASSPATH_BT_GATTSERVER,
+                                                            "cancelConnection",
+                                                            "(Landroid/bluetooth/BluetoothDevice;)"
+                                                            "V");
     if (!jni_mid_cancelConnection)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_cancelConnection is null");
@@ -1332,14 +1369,8 @@ CAResult_t CALEServerGattClose(JNIEnv *env, jobject bluetoothGattServer)
 
     // get BluetoothGatt class
     OIC_LOG(DEBUG, TAG, "get BluetoothGatt class");
-    jclass jni_cid_BluetoothGatt = (*env)->FindClass(env, "android/bluetooth/BluetoothGattServer");
-    if (!jni_cid_BluetoothGatt)
-    {
-        OIC_LOG(ERROR, TAG, "jni_cid_BluetoothGatt is null");
-        return CA_STATUS_FAILED;
-    }
-
-    jmethodID jni_mid_closeGatt = (*env)->GetMethodID(env, jni_cid_BluetoothGatt, "close", "()V");
+    jmethodID jni_mid_closeGatt = CALEGetJNIMethodID(env, CLASSPATH_BT_GATTSERVER,
+                                                     "close", "()V");
     if (!jni_mid_closeGatt)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_closeGatt is null");
@@ -1392,7 +1423,7 @@ CAResult_t CALEServerSend(JNIEnv *env, jobject bluetoothDevice, jbyteArray respo
     return result;
 }
 
-CAResult_t CALEServerInitialize(ca_thread_pool_t handle)
+CAResult_t CALEServerInitialize()
 {
     OIC_LOG(DEBUG, TAG, "IN - CALEServerInitialize");
 
@@ -1432,7 +1463,7 @@ CAResult_t CALEServerInitialize(ca_thread_pool_t handle)
         return ret;
     }
 
-    g_threadPoolHandle = handle;
+    g_threadSendNotifyCond = ca_cond_new();
 
     ret = CALEServerInitMutexVaraibles();
     if (CA_STATUS_OK != ret)
@@ -1486,7 +1517,7 @@ void CALEServerTerminate()
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
-        OIC_LOG(ERROR, TAG, "Could not get JNIEnv pointer");
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
         res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
 
         if (JNI_OK != res)
@@ -1497,49 +1528,24 @@ void CALEServerTerminate()
         isAttached = true;
     }
 
-    CAResult_t ret = CALEServerGattClose(env, g_bluetoothGattServer);
-    if (CA_STATUS_OK != ret)
+    if (g_sendBuffer)
     {
-        OIC_LOG(ERROR, TAG, "CALEServerGattClose has failed");
+        (*env)->DeleteGlobalRef(env, g_sendBuffer);
+        g_sendBuffer = NULL;
     }
 
-    ret = CALEServerStopMulticastServer(0);
-    if (CA_STATUS_OK != ret)
+    if (g_bluetoothManager)
     {
-        OIC_LOG(ERROR, TAG, "CALEServerStopMulticastServer has failed");
-    }
-
-    ret = CALEServerDisconnectAllDevices(env);
-    if (CA_STATUS_OK != ret)
-    {
-        OIC_LOG(ERROR, TAG, "CALEServerDisconnectAllDevices has failed");
-    }
-
-    ret = CALEServerRemoveAllDevices(env);
-    if (CA_STATUS_OK != ret)
-    {
-        OIC_LOG(ERROR, TAG, "CALEServerRemoveAllDevices has failed");
-    }
-
-    if (g_leAdvertiseCallback)
-    {
-        (*env)->DeleteGlobalRef(env, g_leAdvertiseCallback);
-    }
-
-    if (g_bluetoothGattServer)
-    {
-        (*env)->DeleteGlobalRef(env, g_bluetoothGattServer);
+        (*env)->DeleteGlobalRef(env, g_bluetoothManager);
+        g_bluetoothManager = NULL;
     }
 
-    if (g_bluetoothGattServerCallback)
-    {
-        (*env)->DeleteGlobalRef(env, g_bluetoothGattServerCallback);
-    }
+    ca_cond_free(g_threadSendNotifyCond);
+    g_threadSendNotifyCond = NULL;
 
     CALEServerTerminateMutexVaraibles();
     CALEServerTerminateConditionVaraibles();
 
-    g_isStartServer = false;
     g_isInitializedServer = false;
 
     if (isAttached)
@@ -1552,7 +1558,7 @@ void CALEServerTerminate()
 
 CAResult_t CALEServerSendUnicastMessage(const char* address, const uint8_t* data, uint32_t dataLen)
 {
-    OIC_LOG_V(DEBUG, TAG, "IN - CALEServerSendUnicastMessage(%s, %p)", address, data);
+    OIC_LOG_V(DEBUG, TAG, "CALEServerSendUnicastMessage(%s, %p)", address, data);
     VERIFY_NON_NULL(address, TAG, "address is null");
     VERIFY_NON_NULL(data, TAG, "data is null");
 
@@ -1567,7 +1573,7 @@ CAResult_t CALEServerSendUnicastMessage(const char* address, const uint8_t* data
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
-        OIC_LOG(ERROR, TAG, "Could not get JNIEnv pointer");
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
         res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
 
         if (JNI_OK != res)
@@ -1589,13 +1595,12 @@ CAResult_t CALEServerSendUnicastMessage(const char* address, const uint8_t* data
         (*g_jvm)->DetachCurrentThread(g_jvm);
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT - CALEServerSendUnicastMessage");
     return ret;
 }
 
 CAResult_t CALEServerSendMulticastMessage(const uint8_t* data, uint32_t dataLen)
 {
-    OIC_LOG_V(DEBUG, TAG, "IN - CALEServerSendMulticastMessage(%p)", data);
+    OIC_LOG_V(DEBUG, TAG, "CALEServerSendMulticastMessage(%p)", data);
     VERIFY_NON_NULL(data, TAG, "data is null");
 
     if (!g_jvm)
@@ -1609,7 +1614,7 @@ CAResult_t CALEServerSendMulticastMessage(const uint8_t* data, uint32_t dataLen)
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
-        OIC_LOG(ERROR, TAG, "Could not get JNIEnv pointer");
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
         res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
 
         if (JNI_OK != res)
@@ -1631,7 +1636,6 @@ CAResult_t CALEServerSendMulticastMessage(const uint8_t* data, uint32_t dataLen)
         (*g_jvm)->DetachCurrentThread(g_jvm);
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT - CALEServerSendMulticastMessage");
     return ret;
 }
 
@@ -1662,7 +1666,7 @@ CAResult_t CALEServerStartMulticastServer()
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
-        OIC_LOG(ERROR, TAG, "Could not get JNIEnv pointer");
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
         res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
 
         if (JNI_OK != res)
@@ -1720,7 +1724,7 @@ CAResult_t CALEServerStopMulticastServer()
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
-        OIC_LOG(ERROR, TAG, "Could not get JNIEnv pointer");
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
         res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
 
         if (JNI_OK != res)
@@ -1757,7 +1761,7 @@ void CALEServerSetCallback(CAPacketReceiveCallback callback)
 CAResult_t CALEServerSendUnicastMessageImpl(JNIEnv *env, const char* address, const uint8_t* data,
                                             uint32_t dataLen)
 {
-    OIC_LOG_V(DEBUG, TAG, "IN - CALEServerSendUnicastMessageImpl, address: %s, data: %p",
+    OIC_LOG_V(DEBUG, TAG, "CALEServerSendUnicastMessageImpl, address: %s, data: %p",
             address, data);
     VERIFY_NON_NULL(env, TAG, "env is null");
     VERIFY_NON_NULL(address, TAG, "address is null");
@@ -1769,7 +1773,8 @@ CAResult_t CALEServerSendUnicastMessageImpl(JNIEnv *env, const char* address, co
         return CA_STATUS_FAILED;
     }
 
-    jobject jni_obj_bluetoothDevice = NULL;
+    ca_mutex_lock(g_threadSendMutex);
+
     uint32_t length = u_arraylist_length(g_connectedDeviceList);
     for (uint32_t index = 0; index < length; index++)
     {
@@ -1778,20 +1783,20 @@ CAResult_t CALEServerSendUnicastMessageImpl(JNIEnv *env, const char* address, co
         if (!jarrayObj)
         {
             OIC_LOG(ERROR, TAG, "jarrayObj is null");
-            return CA_STATUS_FAILED;
+            goto error_exit;
         }
 
         jstring jni_setAddress = CALEGetAddressFromBTDevice(env, jarrayObj);
         if (!jni_setAddress)
         {
             OIC_LOG(ERROR, TAG, "jni_setAddress is null");
-            return CA_STATUS_FAILED;
+            goto error_exit;
         }
         const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
         if (!setAddress)
         {
             OIC_LOG(ERROR, TAG, "setAddress is null");
-            return CA_STATUS_FAILED;
+            goto error_exit;
         }
 
         OIC_LOG_V(DEBUG, TAG, "setAddress : %s", setAddress);
@@ -1800,38 +1805,72 @@ CAResult_t CALEServerSendUnicastMessageImpl(JNIEnv *env, const char* address, co
         if (!strcmp(setAddress, address))
         {
             OIC_LOG(DEBUG, TAG, "found the device");
-            jni_obj_bluetoothDevice = jarrayObj;
+
+            if (g_obj_bluetoothDevice)
+            {
+                (*env)->DeleteGlobalRef(env, g_obj_bluetoothDevice);
+                g_obj_bluetoothDevice = NULL;
+            }
+
+            if (jarrayObj)
+            {
+                g_obj_bluetoothDevice = (*env)->NewGlobalRef(env, jarrayObj);
+            }
             (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
             break;
         }
         (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
     }
 
-    if (jni_obj_bluetoothDevice)
+    if (g_obj_bluetoothDevice)
     {
-        jbyteArray jni_bytearr_data = (*env)->NewByteArray(env, dataLen);
-        (*env)->SetByteArrayRegion(env, jni_bytearr_data, 0, dataLen, (jbyte*) data);
+        jbyteArray jni_arr = (*env)->NewByteArray(env, dataLen);
+        (*env)->SetByteArrayRegion(env, jni_arr, 0, dataLen, (jbyte*) data);
+        g_sendBuffer = (jbyteArray)(*env)->NewGlobalRef(env, jni_arr);
 
-        CAResult_t res = CALEServerSend(env, jni_obj_bluetoothDevice, jni_bytearr_data);
+        CAResult_t res = CALEServerSend(env, g_obj_bluetoothDevice, g_sendBuffer);
         if (CA_STATUS_OK != res)
         {
             OIC_LOG(ERROR, TAG, "send has failed");
-            return CA_SEND_FAILED;
+            goto error_exit;
         }
     }
     else
     {
         OIC_LOG(ERROR, TAG, "There are no device to send in the list");
-        return CA_STATUS_FAILED;
+        goto error_exit;
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT - CALEServerSendUnicastMessageImpl");
+    if (g_sendBuffer)
+    {
+        (*env)->DeleteGlobalRef(env, g_sendBuffer);
+        g_sendBuffer = NULL;
+    }
+
+    ca_mutex_unlock(g_threadSendMutex);
+    OIC_LOG(INFO, TAG, "unicast - send request is successful");
     return CA_STATUS_OK;
+
+error_exit:
+    if (g_sendBuffer)
+    {
+        (*env)->DeleteGlobalRef(env, g_sendBuffer);
+        g_sendBuffer = NULL;
+    }
+
+    if (g_obj_bluetoothDevice)
+    {
+        (*env)->DeleteGlobalRef(env, g_obj_bluetoothDevice);
+        g_obj_bluetoothDevice = NULL;
+    }
+
+    ca_mutex_unlock(g_threadSendMutex);
+    return CA_SEND_FAILED;
 }
 
 CAResult_t CALEServerSendMulticastMessageImpl(JNIEnv *env, const uint8_t *data, uint32_t dataLen)
 {
-    OIC_LOG_V(DEBUG, TAG, "IN - CALEServerSendMulticastMessageImpl, send to, data: %s", data);
+    OIC_LOG_V(DEBUG, TAG, "CALEServerSendMulticastMessageImpl, send to, data: %s", data);
     VERIFY_NON_NULL(env, TAG, "env is null");
     VERIFY_NON_NULL(data, TAG, "data is null");
 
@@ -1841,6 +1880,18 @@ CAResult_t CALEServerSendMulticastMessageImpl(JNIEnv *env, const uint8_t *data,
         return CA_STATUS_FAILED;
     }
 
+    ca_mutex_lock(g_threadSendMutex);
+
+    OIC_LOG(DEBUG, TAG, "set data into g_sendBuffer for notify");
+    if (g_sendBuffer)
+    {
+        (*env)->DeleteGlobalRef(env, g_sendBuffer);
+        g_sendBuffer = NULL;
+    }
+    jbyteArray jni_arr = (*env)->NewByteArray(env, dataLen);
+    (*env)->SetByteArrayRegion(env, jni_arr, 0, dataLen, (jbyte*) data);
+    g_sendBuffer = (jbyteArray)(*env)->NewGlobalRef(env, jni_arr);
+
     uint32_t length = u_arraylist_length(g_connectedDeviceList);
     for (uint32_t index = 0; index < length; index++)
     {
@@ -1848,28 +1899,67 @@ CAResult_t CALEServerSendMulticastMessageImpl(JNIEnv *env, const uint8_t *data,
         if (!jarrayObj)
         {
             OIC_LOG(ERROR, TAG, "jarrayObj is null");
-            return CA_STATUS_FAILED;
+            continue;
         }
 
         // send data for all device
         jbyteArray jni_bytearr_data = (*env)->NewByteArray(env, dataLen);
         (*env)->SetByteArrayRegion(env, jni_bytearr_data, 0, dataLen, (jbyte*) data);
-        CAResult_t res = CALEServerSend(env, jarrayObj, jni_bytearr_data);
+
+        jstring jni_address = CALEGetAddressFromBTDevice(env, jarrayObj);
+        if (!jni_address)
+        {
+            OIC_LOG(ERROR, TAG, "CALEGetAddressFromBTDevice has failed");
+            continue;
+        }
+
+        const char* address = (*env)->GetStringUTFChars(env, jni_address, NULL);
+        if (!address)
+        {
+            OIC_LOG(ERROR, TAG, "address is not available");
+            continue;
+        }
+
+        if (g_obj_bluetoothDevice)
+        {
+            (*env)->DeleteGlobalRef(env, g_obj_bluetoothDevice);
+            g_obj_bluetoothDevice = NULL;
+        }
+
+        if (jarrayObj)
+        {
+            g_obj_bluetoothDevice = (*env)->NewGlobalRef(env, jarrayObj);
+        }
+
+        CAResult_t res = CALEServerSend(env, g_obj_bluetoothDevice, jni_bytearr_data);
         if (CA_STATUS_OK != res)
         {
-            OIC_LOG(ERROR, TAG, "send has failed");
-            return CA_SEND_FAILED;
+            OIC_LOG_V(ERROR, TAG, "send has failed for the device[%s]", address);
+            (*env)->ReleaseStringUTFChars(env, jni_address, address);
+            if (g_obj_bluetoothDevice)
+            {
+                (*env)->DeleteGlobalRef(env, g_obj_bluetoothDevice);
+                g_obj_bluetoothDevice = NULL;
+            }
+            continue;
         }
+
+        OIC_LOG_V(INFO, TAG, "unicast - send request is successful for a device[%s]", address);
+        (*env)->ReleaseStringUTFChars(env, jni_address, address);
+    }
+
+    if (g_sendBuffer)
+    {
+        (*env)->DeleteGlobalRef(env, g_sendBuffer);
+        g_sendBuffer = NULL;
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT - CALEServerSendMulticastMessageImpl");
+    ca_mutex_unlock(g_threadSendMutex);
     return CA_STATUS_OK;
 }
 
 void CALEServerCreateCachedDeviceList()
 {
-    OIC_LOG(DEBUG, TAG, "IN - CALEServerCreateCachedDeviceList");
-
     ca_mutex_lock(g_connectedDeviceListMutex);
     // create new object array
     if (!g_connectedDeviceList)
@@ -1878,13 +1968,10 @@ void CALEServerCreateCachedDeviceList()
         g_connectedDeviceList = u_arraylist_create();
     }
     ca_mutex_unlock(g_connectedDeviceListMutex);
-
-    OIC_LOG(DEBUG, TAG, "OUT - CALEServerCreateCachedDeviceList");
 }
 
 bool CALEServerIsDeviceInList(JNIEnv *env, const char* remoteAddress)
 {
-    OIC_LOG(DEBUG, TAG, "IN - CALEServerIsDeviceInList");
     VERIFY_NON_NULL_RET(env, TAG, "env is null", false);
     VERIFY_NON_NULL_RET(remoteAddress, TAG, "remoteAddress is null", false);
 
@@ -1933,7 +2020,6 @@ bool CALEServerIsDeviceInList(JNIEnv *env, const char* remoteAddress)
     }
 
     OIC_LOG(DEBUG, TAG, "there are no device in the list");
-    OIC_LOG(DEBUG, TAG, "OUT - CALEServerCreateCachedDeviceList");
     return false;
 }
 
@@ -2061,6 +2147,7 @@ CAResult_t CALEServerRemoveDevice(JNIEnv *env, jstring address)
                 (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
                 (*env)->ReleaseStringUTFChars(env, address, remoteAddress);
                 (*env)->DeleteGlobalRef(env, jarrayObj);
+                jarrayObj = NULL;
 
                 if (NULL == u_arraylist_remove(g_connectedDeviceList, index))
                 {
@@ -2120,38 +2207,13 @@ Java_org_iotivity_ca_CaLeServerInterface_caLeGattServerConnectionStateChangeCall
     VERIFY_NON_NULL_VOID(obj, TAG, "obj");
     VERIFY_NON_NULL_VOID(device, TAG, "device");
 
-    jclass jni_cid_bluetoothProfile = (*env)->FindClass(env, "android/bluetooth/BluetoothProfile");
-    if (!jni_cid_bluetoothProfile)
-    {
-        OIC_LOG(ERROR, TAG, "jni_cid_bluetoothProfile is null");
-        return;
-    }
-
-    jfieldID jni_fid_state_connected = (*env)->GetStaticFieldID(env, jni_cid_bluetoothProfile,
-                                                                "STATE_CONNECTED", "I");
-    if(!jni_fid_state_connected)
-    {
-        OIC_LOG(ERROR, TAG, "jni_fid_state_connected is null");
-        return;
-    }
-
-    jfieldID jni_fid_state_disconnected = (*env)->GetStaticFieldID(env, jni_cid_bluetoothProfile,
-                                                                   "STATE_DISCONNECTED", "I");
-    if(!jni_fid_state_disconnected)
-    {
-        OIC_LOG(ERROR, TAG, "jni_fid_state_disconnected is null");
-        return;
-    }
-
     // STATE_CONNECTED
-    jint jni_int_state_connected = (*env)->GetStaticIntField(env, jni_cid_bluetoothProfile,
-                                                             jni_fid_state_connected);
+    jint state_connected = CALEGetConstantsValue(env, CLASSPATH_BT_PROFILE, "STATE_CONNECTED");
 
     // STATE_DISCONNECTED
-    jint jni_int_state_disconnected = (*env)->GetStaticIntField(env, jni_cid_bluetoothProfile,
-                                                                jni_fid_state_disconnected);
+    jint state_disconnected = CALEGetConstantsValue(env, CLASSPATH_BT_PROFILE, "STATE_DISCONNECTED");
 
-    if (newState == jni_int_state_connected)
+    if (newState == state_connected)
     {
 
         OIC_LOG(DEBUG, TAG, "LE CONNECTED");
@@ -2177,7 +2239,7 @@ Java_org_iotivity_ca_CaLeServerInterface_caLeGattServerConnectionStateChangeCall
         }
         (*env)->ReleaseStringUTFChars(env, jni_remoteAddress, remoteAddress);
     }
-    else if (newState == jni_int_state_disconnected)
+    else if (newState == state_disconnected)
     {
         OIC_LOG(DEBUG, TAG, "LE DISCONNECTED");
 
@@ -2290,8 +2352,50 @@ Java_org_iotivity_ca_CaLeServerInterface_caLeGattServerNotificationSentCallback(
     VERIFY_NON_NULL_VOID(obj, TAG, "obj");
     VERIFY_NON_NULL_VOID(device, TAG, "device");
 
-    OIC_LOG_V(DEBUG, TAG, "Gatt Server Notification Sent Callback(%d)",
+    OIC_LOG_V(DEBUG, TAG, "Gatt Server Notification Sent Callback (status : %d)",
               status);
+
+    jint gatt_success = CALEGetConstantsValue(env, CLASSPATH_BT_GATT, "GATT_SUCCESS");
+    if (gatt_success != status) // error case
+    {
+        OIC_LOG(ERROR, TAG, "it will be sent again.");
+
+        CAResult_t res = CALEServerSend(env, device, g_sendBuffer);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "send has failed");
+
+            if (g_obj_bluetoothDevice)
+            {
+                (*env)->DeleteGlobalRef(env, g_obj_bluetoothDevice);
+                g_obj_bluetoothDevice = NULL;
+            }
+
+            ca_mutex_lock(g_threadSendNotifyMutex);
+            g_isSignalSetFlag = true;
+            ca_cond_signal(g_threadSendNotifyCond);
+            ca_mutex_unlock(g_threadSendNotifyMutex);
+            return;
+        }
+    }
+    else
+    {
+        OIC_LOG(DEBUG, TAG, "notify success");
+
+        if (g_obj_bluetoothDevice)
+        {
+            (*env)->DeleteGlobalRef(env, g_obj_bluetoothDevice);
+            g_obj_bluetoothDevice = NULL;
+        }
+
+        // next data can be sent
+        ca_mutex_lock(g_threadSendNotifyMutex);
+        OIC_LOG(DEBUG, TAG, "g_isSignalSetFlag is set true and signal");
+        g_isSignalSetFlag = true;
+        ca_cond_signal(g_threadSendNotifyCond);
+        ca_mutex_unlock(g_threadSendNotifyMutex);
+    }
+
 }
 
 JNIEXPORT void JNICALL
@@ -2315,6 +2419,13 @@ Java_org_iotivity_ca_CaLeServerInterface_caLeAdvertiseStartFailureCallback(JNIEn
     VERIFY_NON_NULL_VOID(obj, TAG, "obj");
 
     OIC_LOG_V(INFO, TAG, "LE Advertise Start Failure Callback(%d)", errorCode);
+
+    jint data_too_large = CALEGetConstantsValue(env, CLASSPATH_BT_ADVERTISE_CB,
+                                                "ADVERTISE_FAILED_DATA_TOO_LARGE");
+    if (data_too_large == errorCode)
+    {
+        OIC_LOG_V(ERROR, TAG, "advertise data too large. please check length of device name");
+    }
 }
 
 /**
@@ -2323,58 +2434,118 @@ Java_org_iotivity_ca_CaLeServerInterface_caLeAdvertiseStartFailureCallback(JNIEn
 
 CAResult_t CAStartLEGattServer()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
+    // start gatt service
+    CALEServerStartMulticastServer();
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStopLEGattServer()
+{
+    OIC_LOG(DEBUG, TAG, "CAStopLEGattServer");
+
+    if (!g_jvm)
+    {
+        OIC_LOG(ERROR, TAG, "g_jvm is null");
+        return CA_STATUS_FAILED;
+    }
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return CA_STATUS_FAILED;
+        }
+        isAttached = true;
+    }
 
-    CAResult_t ret = CALEServerInitMutexVaraibles();
+    CAResult_t ret = CALEServerGattClose(env, g_bluetoothGattServer);
     if (CA_STATUS_OK != ret)
     {
-        OIC_LOG(ERROR, TAG, "CALEServerInitMutexVaraibles has failed!");
-        CALEServerTerminateMutexVaraibles();
-        return CA_SERVER_NOT_STARTED;
+        OIC_LOG(ERROR, TAG, "CALEServerGattClose has failed");
+        return CA_STATUS_FAILED;
     }
 
-    ret = CALEServerInitConditionVaraibles();
+    ret = CALEServerStopMulticastServer();
     if (CA_STATUS_OK != ret)
     {
-        OIC_LOG(ERROR, TAG, "CALEServerInitConditionVaraibles has failed!");
-        CALEServerTerminateConditionVaraibles();
-        return CA_SERVER_NOT_STARTED;
+        OIC_LOG(ERROR, TAG, "CALEServerStopMulticastServer has failed");
+        return CA_STATUS_FAILED;
     }
 
-    // start gatt service
-    CALEServerStartMulticastServer();
+    ret = CALEServerDisconnectAllDevices(env);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEServerDisconnectAllDevices has failed");
+        return CA_STATUS_FAILED;
+    }
+
+    ret = CALEServerRemoveAllDevices(env);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEServerRemoveAllDevices has failed");
+        return CA_STATUS_FAILED;
+    }
+
+    if (g_leAdvertiseCallback)
+    {
+        (*env)->DeleteGlobalRef(env, g_leAdvertiseCallback);
+    }
+
+    if (g_bluetoothGattServer)
+    {
+        (*env)->DeleteGlobalRef(env, g_bluetoothGattServer);
+    }
+
+    if (g_bluetoothGattServerCallback)
+    {
+        (*env)->DeleteGlobalRef(env, g_bluetoothGattServerCallback);
+    }
+
+    if (g_obj_bluetoothDevice)
+    {
+        (*env)->DeleteGlobalRef(env, g_obj_bluetoothDevice);
+        g_obj_bluetoothDevice = NULL;
+    }
+
+    ca_mutex_lock(g_threadSendNotifyMutex);
+    ca_cond_signal(g_threadSendNotifyCond);
+    ca_mutex_unlock(g_threadSendNotifyMutex);
+
+    g_isStartServer = false;
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
 
-    OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
 
-CAResult_t CAStopLEGattServer()
+CAResult_t CAInitializeLEGattServer()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
-    OIC_LOG(DEBUG, TAG, "OUT");
-    return CA_STATUS_OK;
+    OIC_LOG(DEBUG, TAG, "Initialize Gatt Server");
+    return CALEServerInitialize();
 }
 
 void CATerminateLEGattServer()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
-    OIC_LOG(DEBUG, TAG, "Terminat Gatt Server");
+    OIC_LOG(DEBUG, TAG, "Terminate Gatt Server");
     CALEServerTerminate();
-
-    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 void CASetLEReqRespServerCallback(CABLEDataReceivedCallback callback)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     ca_mutex_lock(g_bleReqRespCbMutex);
     g_CABLEServerDataReceivedCallback = callback;
     ca_mutex_unlock(g_bleReqRespCbMutex);
-
-    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 void CASetBLEServerErrorHandleCallback(CABLEErrorHandleCallback callback)
@@ -2387,46 +2558,35 @@ CAResult_t CAUpdateCharacteristicsToGattClient(const char *address,
                                                uint32_t charValueLen)
 {
     CAResult_t result = CA_SEND_FAILED;
-    OIC_LOG(DEBUG, TAG, "IN");
     VERIFY_NON_NULL(address, TAG, "env is null");
     VERIFY_NON_NULL(charValue, TAG, "device is null");
 
     if (address)
     {
-        OIC_LOG(DEBUG, TAG, "CALEServerSendUnicastData");
         result = CALEServerSendUnicastMessage(address, charValue, charValueLen);
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT");
-
     return result;
 }
 
 CAResult_t CAUpdateCharacteristicsToAllGattClients(const uint8_t *charValue,
                                                    uint32_t charValueLen)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
     VERIFY_NON_NULL(charValue, TAG, "device is null");
 
-    OIC_LOG(DEBUG, TAG, "CALEServerSendMulticastMessage");
     CAResult_t result = CALEServerSendMulticastMessage(charValue, charValueLen);
 
-    OIC_LOG(DEBUG, TAG, "OUT");
     return result;
 }
 
 void CASetLEServerThreadPoolHandle(ca_thread_pool_t handle)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
-    CALEServerInitialize(handle);
-
-    OIC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(INFO, TAG, "CASetLEServerThreadPoolHandle is not support");
+    (void)handle;
 }
 
 CAResult_t CALEServerInitMutexVaraibles()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
     if (NULL == g_bleReqRespCbMutex)
     {
         g_bleReqRespCbMutex = ca_mutex_new();
@@ -2457,20 +2617,31 @@ CAResult_t CALEServerInitMutexVaraibles()
         }
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT");
-    return CA_STATUS_OK;
-}
+    if (NULL == g_threadSendMutex)
+    {
+        g_threadSendMutex = ca_mutex_new();
+        if (NULL == g_threadSendMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_threadSendNotifyMutex)
+    {
+        g_threadSendNotifyMutex = ca_mutex_new();
+        if (NULL == g_threadSendNotifyMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
 
-CAResult_t CALEServerInitConditionVaraibles()
-{
-    OIC_LOG(DEBUG, TAG, "this method is not supported");
     return CA_STATUS_OK;
 }
 
 void CALEServerTerminateMutexVaraibles()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     ca_mutex_free(g_bleReqRespCbMutex);
     g_bleReqRespCbMutex = NULL;
 
@@ -2480,7 +2651,11 @@ void CALEServerTerminateMutexVaraibles()
     ca_mutex_free(g_connectedDeviceListMutex);
     g_connectedDeviceListMutex = NULL;
 
-    OIC_LOG(DEBUG, TAG, "OUT");
+    ca_mutex_free(g_threadSendMutex);
+    g_threadSendMutex = NULL;
+
+    ca_mutex_free(g_threadSendNotifyMutex);
+    g_threadSendNotifyMutex = NULL;
 }
 
 void CALEServerTerminateConditionVaraibles()
index 46d6b51..83943b6 100644 (file)
@@ -45,10 +45,9 @@ typedef void (*CAPacketReceiveCallback)(const char *address, const uint8_t *data
 
 /**
  * initialize server for BLE.
- * @param[in]   handle           thread pool handle object.
  * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
  */
-CAResult_t CALEServerInitialize(ca_thread_pool_t handle);
+CAResult_t CALEServerInitialize();
 
 /**
  * terminate client for BLE.
index c7f597f..2905742 100644 (file)
 
 #include "caleutils.h"
 #include "logger.h"
-#include "oic_malloc.h"
 #include "cathreadpool.h"
 #include "uarraylist.h"
 #include "caadapterutils.h"
 
-#define TAG PCF("CA_LE_UTILS")
+#define TAG PCF("OIC_CA_LE_UTILS")
 
-#define METHODID_OBJECTNONPARAM   "()Landroid/bluetooth/BluetoothAdapter;"
-#define METHODID_STRINGNONPARAM   "()Ljava/lang/String;"
-#define CLASSPATH_BT_ADPATER "android/bluetooth/BluetoothAdapter"
+jmethodID CALEGetJNIMethodID(JNIEnv *env, const char* className,
+                             const char* methodName,
+                             const char* methodFormat)
+{
+    VERIFY_NON_NULL_RET(env, TAG, "env", NULL);
+    VERIFY_NON_NULL_RET(className, TAG, "className", NULL);
+    VERIFY_NON_NULL_RET(methodName, TAG, "methodName", NULL);
+    VERIFY_NON_NULL_RET(methodFormat, TAG, "methodFormat", NULL);
+
+    jclass jni_cid = (*env)->FindClass(env, className);
+    if (!jni_cid)
+    {
+        OIC_LOG_V(ERROR, TAG, "jni_cid [%s] is null", className);
+        return NULL;
+    }
+
+    jmethodID jni_midID = (*env)->GetMethodID(env, jni_cid, methodName, methodFormat);
+    if (!jni_midID)
+    {
+        OIC_LOG_V(ERROR, TAG, "jni_midID [%s] is null", methodName);
+        return NULL;
+    }
+
+    return jni_midID;
+}
 
 jobject CALEGetUuidFromString(JNIEnv *env, const char* uuid)
 {
     VERIFY_NON_NULL_RET(uuid, TAG, "uuid is null", NULL);
     VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
 
-    OIC_LOG(DEBUG, TAG, "CALEGetUuidFromString");
-
     jclass jni_cid_UUID = (*env)->FindClass(env, "java/util/UUID");
     if (!jni_cid_UUID)
     {
@@ -78,7 +97,6 @@ jobject CALEGetUuidFromString(JNIEnv *env, const char* uuid)
 
 jobject CALEGetParcelUuid(JNIEnv *env, jobject uuid)
 {
-    OIC_LOG(DEBUG, TAG, "CALEGetParcelUuid");
     VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
     VERIFY_NON_NULL_RET(uuid, TAG, "uuid is null", NULL);
 
@@ -112,15 +130,9 @@ bool CALEIsBondedDevice(JNIEnv *env, jobject bluetoothDevice)
     VERIFY_NON_NULL_RET(env, TAG, "env is null", false);
     VERIFY_NON_NULL_RET(bluetoothDevice, TAG, "bluetoothDevice is null", false);
 
-    jclass jni_cid_device_list = (*env)->FindClass(env, "android/bluetooth/BluetoothDevice");
-    if (!jni_cid_device_list)
-    {
-        OIC_LOG(ERROR, TAG, "jni_cid_device_list is null");
-        return false;
-    }
-
-    jmethodID jni_mid_getBondState = (*env)->GetMethodID(env, jni_cid_device_list, "getBondState",
-                                                         "()I");
+    jmethodID jni_mid_getBondState = CALEGetJNIMethodID(env, "android/bluetooth/BluetoothDevice",
+                                                        "getBondState",
+                                                        "()I");
     if (!jni_mid_getBondState)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_getBondState is null");
@@ -149,7 +161,7 @@ jobjectArray CALEGetBondedDevices(JNIEnv *env)
 {
     VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
 
-    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADAPTER);
     if (!jni_cid_BTAdapter)
     {
         OIC_LOG(ERROR, TAG, "getBondedDevices: jni_cid_BTAdapter is null");
@@ -186,15 +198,8 @@ jobjectArray CALEGetBondedDevices(JNIEnv *env)
         return NULL;
     }
 
-    jclass jni_cid_Set = (*env)->FindClass(env, "java/util/Set");
-    if (!jni_cid_Set)
-    {
-        OIC_LOG(ERROR, TAG, "getBondedDevices : jni_cid_Set is null");
-        return NULL;
-    }
-
-    jmethodID jni_mid_toArray = (*env)->GetMethodID(env, jni_cid_Set, "toArray",
-                                                    "()[Ljava/lang/Object;");
+    jmethodID jni_mid_toArray = CALEGetJNIMethodID(env, "java/util/Set", "toArray",
+                                                   "()[Ljava/lang/Object;");
     if (!jni_mid_toArray)
     {
         OIC_LOG(ERROR, TAG, "getBondedDevices: jni_mid_toArray is null");
@@ -216,7 +221,7 @@ jint CALEGetBTStateOnInfo(JNIEnv *env)
 {
     VERIFY_NON_NULL_RET(env, TAG, "env is null", -1);
 
-    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADAPTER);
     if (!jni_cid_BTAdapter)
     {
         OIC_LOG(ERROR, TAG, "getBTStateOnInfo: jni_cid_BTAdapter is null");
@@ -303,7 +308,7 @@ jboolean CALEIsEnableBTAdapter(JNIEnv *env)
 {
     VERIFY_NON_NULL_RET(env, TAG, "env is null", JNI_FALSE);
 
-    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADAPTER);
     if (!jni_cid_BTAdapter)
     {
         OIC_LOG(ERROR, TAG, "jni_cid_BTAdapter: jni_cid_BTAdapter is null");
@@ -343,19 +348,12 @@ jboolean CALEIsEnableBTAdapter(JNIEnv *env)
 
 jstring CALEGetAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice)
 {
-    OIC_LOG(DEBUG, TAG, "IN - CALEGetAddressFromBTDevice");
     VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
     VERIFY_NON_NULL_RET(bluetoothDevice, TAG, "bluetoothDevice is null", NULL);
 
-    jclass jni_cid_device_list = (*env)->FindClass(env, "android/bluetooth/BluetoothDevice");
-    if (!jni_cid_device_list)
-    {
-        OIC_LOG(ERROR, TAG, "jni_cid_device_list is null");
-        return NULL;
-    }
-
-    jmethodID jni_mid_getAddress = (*env)->GetMethodID(env, jni_cid_device_list, "getAddress",
-                                                       "()Ljava/lang/String;");
+    jmethodID jni_mid_getAddress = CALEGetJNIMethodID(env, "android/bluetooth/BluetoothDevice",
+                                                      "getAddress",
+                                                      "()Ljava/lang/String;");
     if (!jni_mid_getAddress)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_getAddress is null");
@@ -370,6 +368,86 @@ jstring CALEGetAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice)
         return NULL;
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT - CALEGetAddressFromBTDevice");
     return jni_address;
 }
+
+jint CALEGetConstantsValue(JNIEnv *env, const char* classType, const char* name)
+{
+    OIC_LOG(DEBUG, TAG, "CALEGetConstantsValue");
+
+    VERIFY_NON_NULL_RET(env, TAG, "env", -1);
+    VERIFY_NON_NULL_RET(classType, TAG, "classType", -1);
+    VERIFY_NON_NULL_RET(name, TAG, "name", -1);
+
+    jclass jni_cid = (*env)->FindClass(env, classType);
+    if (!jni_cid)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid is null");
+        return -1;
+    }
+
+    jfieldID jni_fieldID = (*env)->GetStaticFieldID(env, jni_cid,
+                                                    name, "I");
+    if (!jni_fieldID)
+    {
+        OIC_LOG(ERROR, TAG, "jni_fieldID is null");
+        return -1;
+    }
+
+    return (*env)->GetStaticIntField(env, jni_cid, jni_fieldID);
+}
+
+jobject CALEGetRemoteDevice(JNIEnv *env, jstring address)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEGetRemoteDevice");
+
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
+    VERIFY_NON_NULL_RET(address, TAG, "address is null", NULL);
+
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADAPTER);
+    if (!jni_cid_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BTAdapter is null");
+        return NULL;
+    }
+
+    // get remote bt adapter method
+    jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
+                                                                    "getDefaultAdapter",
+                                                                    METHODID_OBJECTNONPARAM);
+    if (!jni_mid_getDefaultAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null");
+        return NULL;
+    }
+
+    // gat bt adapter object
+    jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+                                                               jni_mid_getDefaultAdapter);
+    if (!jni_obj_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_BTAdapter is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_getRemoteDevice = (*env)->GetMethodID(env, jni_cid_BTAdapter,
+                                                            "getRemoteDevice",
+                                                            METHODID_BT_REMOTE_DEVICE);
+    if (!jni_mid_getRemoteDevice)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getRemoteDevice is null");
+        return NULL;
+    }
+
+    jobject jni_obj_device = (*env)->CallObjectMethod(env, jni_obj_BTAdapter,
+                                                      jni_mid_getRemoteDevice,
+                                                      address);
+    if (!jni_obj_device)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_device is null");
+        return NULL;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEGetRemoteDevice");
+    return jni_obj_device;
+}
index 520c80a..dcb1b04 100644 (file)
@@ -42,12 +42,39 @@ static const char OIC_GATT_CHARACTERISTIC_REQUEST_UUID[] = CA_GATT_REQUEST_CHRC_
 static const char OIC_GATT_CHARACTERISTIC_RESPONSE_UUID[] = CA_GATT_RESPONSE_CHRC_UUID;
 static const char OIC_GATT_CHARACTERISTIC_CONFIG_UUID[] = "00002902-0000-1000-8000-00805f9b34fb";
 
+static const char CLASSPATH_BT_PROFILE[] = "android/bluetooth/BluetoothProfile";
+static const char CLASSPATH_BT_GATT[] = "android/bluetooth/BluetoothGatt";
+static const char CLASSPATH_BT_ADAPTER[] = "android/bluetooth/BluetoothAdapter";
+static const char CLASSPATH_BT_DEVICE[] = "android/bluetooth/BluetoothDevice";
+static const char CLASSPATH_BT_UUID[] = "java/util/UUID";
+
+
+static const char METHODID_OBJECTNONPARAM[] = "()Landroid/bluetooth/BluetoothAdapter;";
+static const char METHODID_BT_DEVICE[] = "()Landroid/bluetooth/BluetoothDevice;";
+static const char METHODID_BT_REMOTE_DEVICE[] = "(Ljava/lang/String;)Landroid/bluetooth/BluetoothDevice;";
+
+static const jint GATT_PROFILE = 7;
 static const jint GATT_SUCCESS = 0;
 
 static const jint BOND_BONDED = 12;
 static const jint BOND_BONDING = 11;
 static const jint BOND_NONE = 10;
 
+static const jint STATE_CONNECTED = 2;
+static const jint STATE_DISCONNECTED = 0;
+
+/**
+ * get method ID for method Name and class
+ * @param[in]   env              JNI interface pointer.
+ * @param[in]   className        android class.
+ * @param[in]   methodName       android method name.
+ * @param[in]   methodFormat     method type of methodName.
+ * @return  jmethodID of the method.
+ */
+jmethodID CALEGetJNIMethodID(JNIEnv *env, const char* className,
+                             const char* methodName,
+                             const char* methodFormat);
+
 /**
  * get uuid(jni object) from uuid(character).
  * @param[in]   env              JNI interface pointer.
@@ -123,6 +150,23 @@ jboolean CALEIsEnableBTAdapter(JNIEnv *env);
  */
 jstring CALEGetAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice);
 
+/**
+ * get value from selected constants.
+ * @param[in]   env              JNI interface pointer.
+ * @param[in]   classType        class type
+ * @param[in]   name             constants name to get.
+ * @return  remote address.
+ */
+jint CALEGetConstantsValue(JNIEnv *env, const char* classType, const char* name);
+
+/**
+ * get bluetooth device object from bluetooth adapter.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   address               bluetooth address.
+ * @return  bluetooth device object.
+ */
+jobject CALEGetRemoteDevice(JNIEnv *env, jstring address);
+
 #ifdef __cplusplus
 } /* extern "C" */
 #endif
index a210c6d..fd351f2 100644 (file)
@@ -66,6 +66,15 @@ Java_org_iotivity_ca_caLeClientInterface_caLeGattConnectionStateChangeCallback
 
 /*
  * Class:     org_iotivity_ca_caLeClientInterface
+ * Method:    caLeGattNWConnectionStateChangeCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;II)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_caLeClientInterface_caLeGattNWConnectionStateChangeCallback
+(JNIEnv *, jobject, jobject, jint, jint);
+
+/*
+ * Class:     org_iotivity_ca_caLeClientInterface
  * Method:    caLeGattServicesDiscoveredCallback
  * Signature: (Landroid/bluetooth/BluetoothGatt;I)V
  */
@@ -112,12 +121,57 @@ Java_org_iotivity_ca_caLeClientInterface_caLeStateChangedCallback
 /*
  * Class:     org_iotivity_ca_caLeClientInterface
  * Method:    caLeBondStateChangedCallback
- * Signature: (I)V
+ * Signature: (Ljava/lang/String;)V
  */
 JNIEXPORT void JNICALL
 Java_org_iotivity_ca_caLeClientInterface_caLeBondStateChangedCallback
 (JNIEnv *, jobject, jstring);
 
+/*
+ * Class:     org_iotivity_ca_caLeClientInterface
+ * Method:    caManagerLeGattConnectionStateChangeCB
+ * Signature: (Landroid/bluetooth/BluetoothGatt;II)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaLeClientInterface_caManagerLeGattConnectionStateChangeCB
+(JNIEnv *, jobject, jobject, jint, jint);
+
+/*
+ * Class:     org_iotivity_ca_caLeClientInterface
+ * Method:    caManagerAdapterStateChangedCallback
+ * Signature: (I)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaLeClientInterface_caManagerAdapterStateChangedCallback
+(JNIEnv *, jobject, jint);
+
+/*
+ * Class:     org_iotivity_ca_caLeClientInterface
+ * Method:    caManagerBondStateChangedCallback
+ * Signature: (Landroid/bluetooth/BluetoothDevice;)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaLeClientInterface_caManagerBondStateChangedCallback
+(JNIEnv *, jobject, jobject);
+
+/*
+ * Class:     org_iotivity_ca_jar_caleinterface
+ * Method:    caManagerLeServicesDiscoveredCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;I)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaLeClientInterface_caManagerLeServicesDiscoveredCallback
+(JNIEnv *, jobject, jobject, jint);
+
+/*
+ * Class:     org_iotivity_ca_jar_caleinterface
+ * Method:    caManagerLeRemoteRssiCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;I)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaLeClientInterface_caManagerLeRemoteRssiCallback
+(JNIEnv *, jobject, jobject, jint, jint);
+
 #ifdef __cplusplus
 }
 #endif
index f8b4810..fd4f813 100644 (file)
@@ -58,6 +58,15 @@ Java_org_iotivity_ca_caLeServerInterface_caLeGattServerConnectionStateChangeCall
 
 /*
  * Class:     org_iotivity_ca_caLeServerInterface
+ * Method:    caLeGattServerNWConnectionStateChangeCallback
+ * Signature: (Landroid/bluetooth/BluetoothDevice;II)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_caLeServerInterface_caLeGattServerNWConnectionStateChangeCallback
+(JNIEnv *, jobject, jobject, jint, jint);
+
+/*
+ * Class:     org_iotivity_ca_caLeServerInterface
  * Method:    caLeGattServerServiceAddedCallback
  * Signature: (ILandroid/bluetooth/BluetoothGattService;)V
  */
index ad99a59..cf392be 100644 (file)
@@ -59,3 +59,10 @@ void CATerminateLEGattClient()
     OIC_LOG(DEBUG, TAG, "IN");
     OIC_LOG(DEBUG, TAG, "OUT");
 }
+
+CAResult_t CAInitializeLEGattClient()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
index 0466261..f543bb4 100644 (file)
@@ -63,7 +63,7 @@ void CATerminateLENetworkMonitor()
     OIC_LOG(DEBUG, TAG, "OUT");
 }
 
-CAResult_t CAInitializeLEAdapter()
+CAResult_t CAInitializeLEAdapter(const ca_thread_pool_t threadPool)
 {
     OIC_LOG(DEBUG, TAG, "IN");
     OIC_LOG(DEBUG, TAG, "OUT");
@@ -77,6 +77,13 @@ CAResult_t CAStartLEAdapter()
     return CA_STATUS_OK;
 }
 
+CAResult_t CAStopLEAdapter()
+{
+    // Nothing to do.
+
+    return CA_STATUS_OK;
+}
+
 CAResult_t CAGetLEAdapterState()
 {
     OIC_LOG(DEBUG, TAG, "IN");
@@ -125,3 +132,8 @@ CAResult_t CAUnSetLEAdapterStateChangedCb()
 }
 
 
+CAResult_t CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCallback callback)
+{
+    //TODO
+    return CA_STATUS_OK;
+}
index 9e80c02..6e2c639 100644 (file)
 #include <boards.h>
 #include <RBL_nRF8001.h>
 
+#include "pdu.h"
 #include "caleinterface.h"
 #include "oic_malloc.h"
 #include "caadapterutils.h"
-#include "cafragmentation.h"
 
 #define TAG "LES"
+/**
+ * Maximum TCP header length.
+ */
+#define TCP_MAX_HEADER_LENGTH 6
 
 /**
- * @var    g_bleServerDataReceivedCallback
- * @brief  Maintains the callback to be notified on receival of network packets from other
- *           BLE devices
+ * Maintains the callback to be notified on receival of network packets from other
+ * BLE devices
  */
 static CABLEDataReceivedCallback g_bleServerDataReceivedCallback = NULL;
 
 /**
- * @def MAX_EVENT_COUNT
- * @brief Maximum number of tries to get the event on BLE Shield address.
+ * Maximum number of tries to get the event on BLE Shield address.
  */
 #define MAX_EVENT_COUNT 20
 
@@ -53,16 +55,21 @@ static bool g_serverRunning = false;
 static uint8_t *g_coapBuffer = NULL;
 
 /**
- * @var g_receivedDataLen
- * @brief Actual length of data received.
+ * Actual length of data received.
  */
-static uint32_t g_receivedDataLen = 0;
+static size_t g_receivedDataLen = 0;
 
 /**
- * @var g_packetDataLen
- * @brief Total Length of data that is being fragmented.
+ * Total Length of data that is being fragmented.
  */
-static uint32_t g_packetDataLen = 0;
+static size_t g_packetDataLen = 0;
+
+void CAGetTCPHeaderDetails(unsigned char* recvBuffer, size_t *headerlen)
+{
+    coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
+        ((unsigned char *)recvBuffer)[0] >> 4);
+    *headerlen = coap_get_tcp_header_length_for_transport(transport);
+}
 
 void CACheckLEDataInternal()
 {
@@ -74,32 +81,43 @@ void CACheckLEDataInternal()
         if (NULL == g_coapBuffer)
         {
             OIC_LOG(DEBUG, TAG, "IN");
-            uint8_t headerArray[CA_HEADER_LENGTH];
-            while (CAIsLEDataAvailable() && g_receivedDataLen < CA_HEADER_LENGTH)
+            size_t bufSize = TCP_MAX_HEADER_LENGTH;
+            g_coapBuffer = (uint8_t *)OICCalloc(bufSize, 1);
+            if (NULL == g_coapBuffer)
             {
-                headerArray[g_receivedDataLen++] = CALEReadData();
+                OIC_LOG(ERROR, TAG, "malloc");
+                return;
             }
 
-            g_packetDataLen = CAParseHeader(headerArray, CA_HEADER_LENGTH);
+            g_coapBuffer[g_receivedDataLen++] = CALEReadData();
+            size_t headerLen;
+            CAGetTCPHeaderDetails(g_coapBuffer, &headerLen);
+            OIC_LOG_V(INFO, TAG, "hdr len %d", headerLen);
+            while (CAIsLEDataAvailable() && g_receivedDataLen < headerLen)
+            {
+                g_coapBuffer[g_receivedDataLen++] = CALEReadData();
+            }
 
+            g_packetDataLen = coap_get_total_message_length(g_coapBuffer, g_receivedDataLen);
+            OIC_LOG_V(INFO, TAG, "pkt len %d", g_packetDataLen);
             if (g_packetDataLen > COAP_MAX_PDU_SIZE)
             {
                 OIC_LOG(ERROR, TAG, "len > pdu_size");
                 return;
             }
 
-            g_coapBuffer = (uint8_t *)OICCalloc((size_t)g_packetDataLen, 1);
-            if (NULL == g_coapBuffer)
+            bufSize = g_packetDataLen;
+            uint8_t *newBuf = (uint8_t *)OICRealloc(g_coapBuffer, bufSize);
+            if (NULL == newBuf)
             {
                 OIC_LOG(ERROR, TAG, "malloc");
+                OICFree(g_coapBuffer);
+                g_coapBuffer = NULL;
                 return;
             }
-
-            OIC_LOG(DEBUG, TAG, "OUT");
-            g_receivedDataLen = 0;
+            g_coapBuffer = newBuf;
         }
 
-        OIC_LOG(DEBUG, TAG, "IN");
         while (CAIsLEDataAvailable())
         {
             OIC_LOG(DEBUG, TAG, "In While loop");
@@ -117,6 +135,7 @@ void CACheckLEDataInternal()
                 }
 
                 g_receivedDataLen = 0;
+                OICFree(g_coapBuffer);
                 g_coapBuffer = NULL;
                 break;
             }
@@ -221,16 +240,25 @@ CAResult_t CAStartLEGattServer()
 CAResult_t CAStopLEGattServer()
 {
     OIC_LOG(DEBUG, TAG, "IN");
-    // There is no server running to stop.
+    CATerminateLEGattServer();
     OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
 
+CAResult_t CAInitializeLEGattServer()
+{
+    OIC_LOG(DEBUG, TAG, "Initialize GATT Server");
+    return CA_STATUS_OK;
+}
+
 void CATerminateLEGattServer()
 {
     OIC_LOG(DEBUG, TAG, "IN");
-    ble_radio_reset();
-    g_serverRunning = false;
+    if (true == g_serverRunning)
+    {
+        ble_radio_reset();
+        g_serverRunning = false;
+    }
     OIC_LOG(DEBUG, TAG, "OUT");
     return;
 }
index 571a890..63705b8 100644 (file)
 #ifndef SINGLE_THREAD
 #include "caqueueingthread.h"
 #endif
-#include "cafragmentation.h"
+#if defined(__TIZEN__) || defined(__ANDROID__)
+#include "caleserver.h"
+#include "caleclient.h"
+#endif
 #include "oic_malloc.h"
 #include "oic_string.h"
 #include "caremotehandler.h"
+#include "pdu.h"
 
 /**
  * Logging tag for module name.
  */
-#define CALEADAPTER_TAG "LAD"
-
+#define CALEADAPTER_TAG "OIC_CA_LE_ADAP"
 
 /**
- * Stores the information of the Data to be sent from the queues.
- *
- * This structure will be pushed to the sender/receiver queue for
- * processing.
+ * The MTU supported for BLE adapter
  */
-typedef struct
-{
-    /// Remote endpoint contains the information of remote device.
-    CAEndpoint_t *remoteEndpoint;
-
-    /// Data to be transmitted over LE transport.
-    uint8_t *data;
-
-    /// Length of the data being transmitted.
-    uint32_t dataLen;
-} CALEData_t;
+#define CA_SUPPORTED_BLE_MTU_SIZE  20
 
 /**
  * Stores information of all the senders.
@@ -72,6 +62,14 @@ typedef struct
     CAEndpoint_t *remoteEndpoint;
  } CABLESenderInfo_t;
 
+typedef enum
+{
+    ADAPTER_EMPTY = 1,
+    ADAPTER_BOTH_CLIENT_SERVER,
+    ADAPTER_CLIENT,
+    ADAPTER_SERVER
+} CABLEAdapter_t;
+
 /**
  * Callback to provide the status of the network change to CA layer.
  */
@@ -86,7 +84,7 @@ static char g_localBLEAddress[18] = { 0 };
 /**
  * Variable to differentiate btw GattServer and GattClient.
  */
-static bool g_isServer = false;
+static CABLEAdapter_t g_adapterType = ADAPTER_EMPTY;
 
 /**
  * Mutex to synchronize the task to be executed on the GattServer
@@ -126,7 +124,6 @@ static ca_mutex g_bleClientSendDataMutex = NULL;
  */
 static ca_mutex g_bleReceiveDataMutex = NULL;
 
-
 /**
  * Mutex to synchronize the queing of the data from SenderQueue.
  */
@@ -150,28 +147,6 @@ static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
 static CAErrorHandleCallback g_errorHandler = NULL;
 
 /**
- * Storing Adapter state information.
- */
-static CAAdapterState_t g_bleAdapterState = CA_ADAPTER_DISABLED;
-
-/**
- * BLE Server Status.
- *
- * This enumeration provides information of LE Adapter Server status.
- */
-typedef enum
-{
-    CA_SERVER_NOTSTARTED = 0,
-    CA_LISTENING_SERVER,
-    CA_DISCOVERY_SERVER
-} CALeServerStatus;
-
-/**
- * Structure to maintain the status of the server.
- */
-static CALeServerStatus gLeServerStatus = CA_SERVER_NOTSTARTED;
-
-/**
  * Register network change notification callback.
  *
  * @param[in]  netCallback CANetworkChangeCallback callback which will
@@ -196,7 +171,7 @@ static CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCa
 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle);
 
 /**
- * Call the callback to the upper layer when the device state gets
+ * Call the callback to the upper layer when the adapter state gets
  * changed.
  *
  * @param[in] adapter_state New state of the adapter to be notified to
@@ -205,6 +180,16 @@ static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle);
 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state);
 
 /**
+ * Call the callback to the upper layer when the device connection state gets
+ * changed.
+ *
+ * @param[in] address      LE address of the device to be notified to the upper layer.
+ * @param[in] isConnected  whether connection state is connected or not.
+ */
+static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
+                                         bool isConnected);
+
+/**
  * Used to initialize all required mutex variable for LE Adapter
  * implementation.
  *
@@ -234,12 +219,14 @@ static void CALEErrorHandler(const char *remoteAddress,
 /**
  * Stop condition of recvhandler.
  */
-static bool g_dataReceiverHandlerState = false;
+static bool g_dataBleReceiverHandlerState = false;
 
 /**
  * Sender information.
  */
-static u_arraylist_t *g_senderInfo = NULL;
+static u_arraylist_t *g_bleServerSenderInfo = NULL;
+
+static u_arraylist_t *g_bleClientSenderInfo = NULL;
 
 /**
  * Queue to process the outgoing packets from GATTClient.
@@ -247,7 +234,7 @@ static u_arraylist_t *g_senderInfo = NULL;
 static CAQueueingThread_t *g_bleClientSendQueueHandle = NULL;
 
 /**
- * Queue to process the incoming packets to GATT Client.
+ * Queue to process the incoming packets.
  */
 static CAQueueingThread_t *g_bleReceiverQueue = NULL;
 
@@ -391,7 +378,8 @@ static CAResult_t CAInitLEReceiverQueue();
  */
 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
                                   const uint8_t *data,
-                                  uint32_t dataLength);
+                                  uint32_t dataLength,
+                                  u_arraylist_t *senderInfo);
 
 /**
  * Used to free the BLE information stored in the sender/receiver
@@ -406,6 +394,28 @@ static void CAFreeLEData(CALEData_t *bleData);
  */
 static void CALEDataDestroyer(void *data, uint32_t size);
 
+#ifndef SINGLE_THREAD
+/**
+ * remove request or response data of send queue.
+ *
+ * @param[in] queueHandle    queue to process the outgoing packets.
+ * @param[in] mutex          mutex related to sender for client / server.
+ * @param[in] address        target address to remove data in queue.
+ */
+static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle,
+                                    ca_mutex mutex,
+                                    const char* address);
+
+/**
+ * remove all received data of data list from receive queue.
+ *
+ * @param[in] dataInfoList   received data list to remove for client / server.
+ * @param[in] address        target address to remove data in queue.
+ */
+static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList,
+                                       const char* address);
+#endif
+
 static CAResult_t CAInitLEServerQueues()
 {
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
@@ -420,15 +430,24 @@ static CAResult_t CAInitLEServerQueues()
         return CA_STATUS_FAILED;
     }
 
+    g_bleServerSenderInfo = u_arraylist_create();
+    if (!g_bleServerSenderInfo)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
+        ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
     result = CAInitLEReceiverQueue();
     if (CA_STATUS_OK != result)
     {
-        OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerReceiverQueue failed");
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEReceiverQueue failed");
+        u_arraylist_free(&g_bleServerSenderInfo);
         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
         return CA_STATUS_FAILED;
     }
 
-    g_dataReceiverHandlerState = true;
+    g_dataBleReceiverHandlerState = true;
 
     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
 
@@ -450,15 +469,24 @@ static CAResult_t CAInitLEClientQueues()
         return CA_STATUS_FAILED;
     }
 
+    g_bleClientSenderInfo = u_arraylist_create();
+    if (!g_bleClientSenderInfo)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
+        ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
     result = CAInitLEReceiverQueue();
     if (CA_STATUS_OK != result)
     {
-        OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientReceiverQueue failed");
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEReceiverQueue failed");
+        u_arraylist_free(&g_bleClientSenderInfo);
         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
         return CA_STATUS_FAILED;
     }
 
-    g_dataReceiverHandlerState = true;
+    g_dataBleReceiverHandlerState = true;
 
     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
 
@@ -468,7 +496,7 @@ static CAResult_t CAInitLEClientQueues()
 
 static CAResult_t CAInitLEReceiverQueue()
 {
-    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAInitLEReceiverQueue");
     // Check if the message queue is already initialized
     if (g_bleReceiverQueue)
     {
@@ -484,22 +512,14 @@ static CAResult_t CAInitLEReceiverQueue()
         return CA_MEMORY_ALLOC_FAILED;
     }
 
-    g_senderInfo = u_arraylist_create();
-    if (!g_senderInfo)
-    {
-        OIC_LOG(ERROR, CALEADAPTER_TAG, "ClientInfo memory allcation failed!");
-        OICFree(g_bleReceiverQueue);
-        g_bleReceiverQueue = NULL;
-        return CA_MEMORY_ALLOC_FAILED;
-    }
-
-    if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleReceiverQueue, g_bleAdapterThreadPool,
-            CALEDataReceiverHandler, CALEDataDestroyer))
+    if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleReceiverQueue,
+                                                   g_bleAdapterThreadPool,
+                                                   CALEDataReceiverHandler,
+                                                   CALEDataDestroyer))
     {
         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
         OICFree(g_bleReceiverQueue);
         g_bleReceiverQueue = NULL;
-        u_arraylist_free(&g_senderInfo);
         return CA_STATUS_FAILED;
     }
 
@@ -508,7 +528,6 @@ static CAResult_t CAInitLEReceiverQueue()
         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
         OICFree(g_bleReceiverQueue);
         g_bleReceiverQueue = NULL;
-        u_arraylist_free(&g_senderInfo);
         return CA_STATUS_FAILED;
     }
 
@@ -518,7 +537,7 @@ static CAResult_t CAInitLEReceiverQueue()
 
 static CAResult_t CAInitLEServerSenderQueue()
 {
-    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAInitLEServerSenderQueue");
     // Check if the message queue is already initialized
     if (g_bleServerSendQueueHandle)
     {
@@ -536,7 +555,8 @@ static CAResult_t CAInitLEServerSenderQueue()
 
     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerSendQueueHandle,
                                                    g_bleAdapterThreadPool,
-                                                   CALEServerSendDataThread, CALEDataDestroyer))
+                                                   CALEServerSendDataThread,
+                                                   CALEDataDestroyer))
     {
         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
         OICFree(g_bleServerSendQueueHandle);
@@ -544,43 +564,36 @@ static CAResult_t CAInitLEServerSenderQueue()
         return CA_STATUS_FAILED;
     }
 
-    if (CA_STATUS_OK != CAQueueingThreadStart(g_bleServerSendQueueHandle))
-    {
-        OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
-        OICFree(g_bleServerSendQueueHandle);
-        g_bleServerSendQueueHandle = NULL;
-        return CA_STATUS_FAILED;
-    }
-
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
     return CA_STATUS_OK;
 }
 
-static void CALEClearSenderInfo()
+static void CALEClearSenderInfoImpl(u_arraylist_t ** list)
 {
-    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
-
-    uint32_t listIndex = 0;
-    uint32_t listLength = u_arraylist_length(g_senderInfo);
-    for (listIndex = 0; listIndex < listLength; listIndex++)
-    {
-        CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(g_senderInfo, listIndex);
-        if(!info)
-        {
-            continue;
-        }
+    const size_t length = u_arraylist_length(*list);
+    for (size_t i = 0; i < length; ++i)
+    {
+        CABLESenderInfo_t * const info =
+                (CABLESenderInfo_t *) u_arraylist_get(*list, i);
+        if (info)
+         {
+             OICFree(info->defragData);
+             CAFreeEndpoint(info->remoteEndpoint);
+             OICFree(info);
+         }
+    }
+    u_arraylist_free(list);
+}
 
-        OICFree(info->defragData);
-        CAFreeEndpoint(info->remoteEndpoint);
-        OICFree(info);
-    }
-    u_arraylist_free(&g_senderInfo);
-    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+static void CALEClearSenderInfo()
+{
+    CALEClearSenderInfoImpl(&g_bleServerSenderInfo);
+    CALEClearSenderInfoImpl(&g_bleClientSenderInfo);
 }
 
 static CAResult_t CAInitLEClientSenderQueue()
 {
-    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAInitLEClientSenderQueue");
 
     if (g_bleClientSendQueueHandle)
     {
@@ -606,35 +619,13 @@ static CAResult_t CAInitLEClientSenderQueue()
         return CA_STATUS_FAILED;
     }
 
-    if (CA_STATUS_OK != CAQueueingThreadStart(g_bleClientSendQueueHandle))
-    {
-        OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
-        OICFree(g_bleClientSendQueueHandle);
-        g_bleClientSendQueueHandle = NULL;
-        return CA_STATUS_FAILED;
-    }
-
-    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CAInitLEClientSenderQueue");
     return CA_STATUS_OK;
 }
 
 static void CAStopLEQueues()
 {
-    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
-
-    ca_mutex_lock(g_bleClientSendDataMutex);
-    if (NULL != g_bleClientSendQueueHandle)
-    {
-        CAQueueingThreadStop(g_bleClientSendQueueHandle);
-    }
-    ca_mutex_unlock(g_bleClientSendDataMutex);
-
-    ca_mutex_lock(g_bleServerSendDataMutex);
-    if (NULL != g_bleServerSendQueueHandle)
-    {
-        CAQueueingThreadStop(g_bleServerSendQueueHandle);
-    }
-    ca_mutex_unlock(g_bleServerSendDataMutex);
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAStopLEQueues");
 
     ca_mutex_lock(g_bleReceiveDataMutex);
     if (NULL != g_bleReceiverQueue)
@@ -643,7 +634,7 @@ static void CAStopLEQueues()
     }
     ca_mutex_unlock(g_bleReceiveDataMutex);
 
-    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CAStopLEQueues");
 }
 
 static void CATerminateLEQueues()
@@ -668,6 +659,7 @@ static void CATerminateLEQueues()
 }
 
 static CAResult_t CALEGetSenderInfo(const char *leAddress,
+                                    u_arraylist_t *senderInfoList,
                                     CABLESenderInfo_t **senderInfo,
                                     uint32_t *senderIndex)
 {
@@ -680,11 +672,11 @@ static CAResult_t CALEGetSenderInfo(const char *leAddress,
                         "NULL index argument",
                         CA_STATUS_INVALID_PARAM);
 
-    const uint32_t listLength = u_arraylist_length(g_senderInfo);
+    const uint32_t listLength = u_arraylist_length(senderInfoList);
     const uint32_t addrLength = strlen(leAddress);
     for (uint32_t index = 0; index < listLength; index++)
     {
-        CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(g_senderInfo, index);
+        CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(senderInfoList, index);
         if(!info || !(info->remoteEndpoint))
         {
             continue;
@@ -706,11 +698,11 @@ static CAResult_t CALEGetSenderInfo(const char *leAddress,
 
 static void CALEDataReceiverHandler(void *threadData)
 {
-    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEDataReceiverHandler");
 
     ca_mutex_lock(g_bleReceiveDataMutex);
 
-    if (g_dataReceiverHandlerState)
+    if (g_dataBleReceiverHandlerState)
     {
         OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
 
@@ -722,7 +714,14 @@ static void CALEDataReceiverHandler(void *threadData)
             return;
         }
 
-        if(!(bleData->remoteEndpoint))
+        if (!(bleData->senderInfo))
+        {
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "sender info is not available");
+            ca_mutex_unlock(g_bleReceiveDataMutex);
+            return;
+        }
+
+        if (!(bleData->remoteEndpoint))
         {
             OIC_LOG(ERROR, CALEADAPTER_TAG, "Client RemoteEndPoint NULL!!");
             ca_mutex_unlock(g_bleReceiveDataMutex);
@@ -733,10 +732,11 @@ static void CALEDataReceiverHandler(void *threadData)
         uint32_t senderIndex = 0;
 
         if(CA_STATUS_OK != CALEGetSenderInfo(bleData->remoteEndpoint->addr,
-                                                &senderInfo, &senderIndex))
+                                             bleData->senderInfo,
+                                             &senderInfo, &senderIndex))
         {
             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This is a new client [%s]",
-                                                bleData->remoteEndpoint->addr);
+                      bleData->remoteEndpoint->addr);
         }
 
         if(!senderInfo)
@@ -754,8 +754,9 @@ static void CALEDataReceiverHandler(void *threadData)
             newSender->remoteEndpoint = NULL;
 
             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
-            newSender->totalDataLen = CAParseHeader(bleData->data,
-                                                    bleData->dataLen);
+
+            newSender->totalDataLen = coap_get_total_message_length(bleData->data, bleData->dataLen);
+
             if(!(newSender->totalDataLen))
             {
                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
@@ -765,9 +766,9 @@ static void CALEDataReceiverHandler(void *threadData)
             }
 
             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
-                                                newSender->totalDataLen);
+                      newSender->totalDataLen);
             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "data received in the first packet [%u] bytes",
-                                                bleData->dataLen);
+                      bleData->dataLen);
 
             newSender->defragData = OICCalloc(newSender->totalDataLen + 1,
                                               sizeof(*newSender->defragData));
@@ -782,7 +783,9 @@ static void CALEDataReceiverHandler(void *threadData)
 
             const char *remoteAddress = bleData->remoteEndpoint->addr;
             newSender->remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
-                                                            CA_ADAPTER_GATT_BTLE, remoteAddress, 0);
+                                                               CA_ADAPTER_GATT_BTLE,
+                                                               remoteAddress,
+                                                               0);
             if (NULL == newSender->remoteEndpoint)
             {
                 OIC_LOG(ERROR, CALEADAPTER_TAG, "remoteEndpoint is NULL!");
@@ -791,14 +794,25 @@ static void CALEDataReceiverHandler(void *threadData)
                 ca_mutex_unlock(g_bleReceiveDataMutex);
                 return;
             }
-            memcpy(newSender->defragData, bleData->data + CA_HEADER_LENGTH,
-                    bleData->dataLen - CA_HEADER_LENGTH);
-            newSender->recvDataLen += bleData->dataLen - CA_HEADER_LENGTH;
-            u_arraylist_add(g_senderInfo,(void *)newSender);
 
-            //Getting newSender index position in g_senderInfo array list
+            if (newSender->recvDataLen + bleData->dataLen > newSender->totalDataLen)
+            {
+                OIC_LOG(ERROR, CALEADAPTER_TAG, "buffer is smaller than received data");
+                OICFree(newSender->defragData);
+                CAFreeEndpoint(newSender->remoteEndpoint);
+                OICFree(newSender);
+                ca_mutex_unlock(g_bleReceiveDataMutex);
+                return;
+            }
+            memcpy(newSender->defragData, bleData->data, bleData->dataLen);
+            newSender->recvDataLen += bleData->dataLen;
+
+            u_arraylist_add(bleData->senderInfo,(void *)newSender);
+
+            //Getting newSender index position in bleSenderInfo array list
             if(CA_STATUS_OK !=
-                CALEGetSenderInfo(newSender->remoteEndpoint->addr, NULL, &senderIndex))
+                CALEGetSenderInfo(newSender->remoteEndpoint->addr, bleData->senderInfo,
+                                  NULL, &senderIndex))
             {
                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Existing sender index not found!!");
                 OICFree(newSender->defragData);
@@ -814,19 +828,20 @@ static void CALEDataReceiverHandler(void *threadData)
             if(senderInfo->recvDataLen + bleData->dataLen > senderInfo->totalDataLen)
             {
                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
-                            "Data Length exceeding error!! Receiving [%d] total length [%d]",
-                            senderInfo->recvDataLen + bleData->dataLen, senderInfo->totalDataLen);
-                u_arraylist_remove(g_senderInfo, senderIndex);
+                          "Data Length exceeding error!! Receiving [%d] total length [%d]",
+                          senderInfo->recvDataLen + bleData->dataLen, senderInfo->totalDataLen);
+                u_arraylist_remove(bleData->senderInfo, senderIndex);
                 OICFree(senderInfo->defragData);
                 OICFree(senderInfo);
                 ca_mutex_unlock(g_bleReceiveDataMutex);
                 return;
             }
-            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%d]", bleData->dataLen);
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%d]",
+                      bleData->dataLen);
             memcpy(senderInfo->defragData + senderInfo->recvDataLen, bleData->data,
-                    bleData->dataLen);
+                   bleData->dataLen);
             senderInfo->recvDataLen += bleData->dataLen ;
-            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "totalDatalength  [%d] recveived Datalen [%d]",
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "totalDatalength  [%d] received Datalen [%d]",
                                                 senderInfo->totalDataLen, senderInfo->recvDataLen);
         }
 
@@ -837,7 +852,7 @@ static void CALEDataReceiverHandler(void *threadData)
             {
                 OIC_LOG(ERROR, CALEADAPTER_TAG, "gReqRespCallback is NULL!");
 
-                u_arraylist_remove(g_senderInfo, senderIndex);
+                u_arraylist_remove(bleData->senderInfo, senderIndex);
                 OICFree(senderInfo->defragData);
                 OICFree(senderInfo);
                 ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
@@ -845,7 +860,7 @@ static void CALEDataReceiverHandler(void *threadData)
                 return;
             }
 
-            OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending data up !");
+            OIC_LOG(DEBUG, CALEADAPTER_TAG, "[CALEDataReceiverHandler] Sending data up !");
 
             const CASecureEndpoint_t tmp =
                 {
@@ -856,7 +871,7 @@ static void CALEDataReceiverHandler(void *threadData)
                                             senderInfo->defragData,
                                             senderInfo->recvDataLen);
             ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
-            u_arraylist_remove(g_senderInfo, senderIndex);
+            u_arraylist_remove(bleData->senderInfo, senderIndex);
             senderInfo->remoteEndpoint = NULL;
             senderInfo->defragData = NULL;
             OICFree(senderInfo);
@@ -868,7 +883,7 @@ static void CALEDataReceiverHandler(void *threadData)
 
 static void CALEServerSendDataThread(void *threadData)
 {
-    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEServerSendDataThread");
 
     CALEData_t * const bleData = (CALEData_t *) threadData;
     if (!bleData)
@@ -877,10 +892,7 @@ static void CALEServerSendDataThread(void *threadData)
         return;
     }
 
-    uint8_t * const header = OICCalloc(CA_HEADER_LENGTH, 1);
-    VERIFY_NON_NULL_VOID(header, CALEADAPTER_TAG, "Malloc failed");
-
-    const uint32_t totalLength = bleData->dataLen + CA_HEADER_LENGTH;
+    const uint32_t totalLength = bleData->dataLen;
 
     OIC_LOG_V(DEBUG,
               CALEADAPTER_TAG,
@@ -892,39 +904,24 @@ static void CALEServerSendDataThread(void *threadData)
     if (NULL == dataSegment)
     {
         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failed");
-        OICFree(header);
-        return;
-    }
-
-    CAResult_t result = CAGenerateHeader(header,
-                                         CA_HEADER_LENGTH,
-                                         bleData->dataLen);
-    if (CA_STATUS_OK != result )
-    {
-        OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
-        OICFree(header);
-        OICFree(dataSegment);
         return;
     }
 
-    memcpy(dataSegment, header, CA_HEADER_LENGTH);
-    OICFree(header);
-
     uint32_t length = 0;
     if (CA_SUPPORTED_BLE_MTU_SIZE > totalLength)
     {
         length = totalLength;
-        memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data, bleData->dataLen);
+        memcpy(dataSegment, bleData->data, bleData->dataLen);
     }
     else
     {
         length =  CA_SUPPORTED_BLE_MTU_SIZE;
-        memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data,
-               CA_SUPPORTED_BLE_MTU_SIZE - CA_HEADER_LENGTH);
+        memcpy(dataSegment, bleData->data, CA_SUPPORTED_BLE_MTU_SIZE);
     }
 
     uint32_t iter = totalLength / CA_SUPPORTED_BLE_MTU_SIZE;
     uint32_t index = 0;
+    CAResult_t result = CA_STATUS_FAILED;
 
     // Send the first segment with the header.
     if (NULL != bleData->remoteEndpoint) // Sending Unicast Data
@@ -964,8 +961,9 @@ static void CALEServerSendDataThread(void *threadData)
             result =
                 CAUpdateCharacteristicsToGattClient(
                     bleData->remoteEndpoint->addr,
-                    bleData->data + ((index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH),
+                    bleData->data + ((index * CA_SUPPORTED_BLE_MTU_SIZE)),
                     CA_SUPPORTED_BLE_MTU_SIZE);
+
             if (CA_STATUS_OK != result)
             {
                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
@@ -986,10 +984,12 @@ static void CALEServerSendDataThread(void *threadData)
             // send the last segment of the data (Ex: 22 bytes of 622
             // bytes of data when MTU is 200)
             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
+
             result = CAUpdateCharacteristicsToGattClient(
                          bleData->remoteEndpoint->addr,
-                         bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
+                         bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE),
                          remainingLen);
+
             if (CA_STATUS_OK != result)
             {
                 OIC_LOG_V(ERROR,
@@ -1023,9 +1023,11 @@ static void CALEServerSendDataThread(void *threadData)
         {
             // Send the remaining header.
             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Sending the chunk number [%d]", index);
+
             result = CAUpdateCharacteristicsToAllGattClients(
-                         bleData->data + ((index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH),
+                         bleData->data + ((index * CA_SUPPORTED_BLE_MTU_SIZE)),
                          CA_SUPPORTED_BLE_MTU_SIZE);
+
             if (CA_STATUS_OK != result)
             {
                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
@@ -1034,17 +1036,20 @@ static void CALEServerSendDataThread(void *threadData)
                 OICFree(dataSegment);
                 return;
             }
-            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%u]", CA_SUPPORTED_BLE_MTU_SIZE);
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%u]",
+                      CA_SUPPORTED_BLE_MTU_SIZE);
         }
 
         const uint32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
         {
-            // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
+            // send the last segment of the data
             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
+
             result = CAUpdateCharacteristicsToAllGattClients(
-                         bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
+                         bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE),
                          remainingLen);
+
             if (CA_STATUS_OK != result)
             {
                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
@@ -1058,12 +1063,12 @@ static void CALEServerSendDataThread(void *threadData)
     }
     OICFree(dataSegment);
 
-    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CALEServerSendDataThread");
 }
 
 static void CALEClientSendDataThread(void *threadData)
 {
-    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEClientSendDataThread");
 
     CALEData_t *bleData = (CALEData_t *) threadData;
     if (!bleData)
@@ -1072,47 +1077,32 @@ static void CALEClientSendDataThread(void *threadData)
         return;
     }
 
-    uint8_t * const header = OICCalloc(CA_HEADER_LENGTH, 1);
-    VERIFY_NON_NULL_VOID(header, CALEADAPTER_TAG, "Malloc failed");
+    const uint32_t totalLength = bleData->dataLen;
 
-    const uint32_t totalLength = bleData->dataLen + CA_HEADER_LENGTH;
     uint8_t *dataSegment = OICCalloc(totalLength, 1);
     if (NULL == dataSegment)
     {
         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failed");
-        OICFree(header);
         return;
     }
 
-    CAResult_t result = CAGenerateHeader(header,
-                                         CA_HEADER_LENGTH,
-                                         bleData->dataLen);
-    if (CA_STATUS_OK != result )
-    {
-        OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
-        OICFree(header);
-        OICFree(dataSegment);
-        return ;
-    }
-    memcpy(dataSegment, header, CA_HEADER_LENGTH);
-    OICFree(header);
-
     uint32_t length = 0;
     if (CA_SUPPORTED_BLE_MTU_SIZE > totalLength)
     {
         length = totalLength;
-        memcpy(dataSegment + CA_HEADER_LENGTH,
+        memcpy(dataSegment,
                bleData->data,
                bleData->dataLen);
     }
     else
     {
         length = CA_SUPPORTED_BLE_MTU_SIZE;
-        memcpy(dataSegment + CA_HEADER_LENGTH,
+        memcpy(dataSegment,
                bleData->data,
-               CA_SUPPORTED_BLE_MTU_SIZE - CA_HEADER_LENGTH);
+               CA_SUPPORTED_BLE_MTU_SIZE);
     }
 
+    CAResult_t result = CA_STATUS_FAILED;
     const uint32_t iter = totalLength / CA_SUPPORTED_BLE_MTU_SIZE;
     uint32_t index = 0;
     if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
@@ -1151,9 +1141,10 @@ static void CALEClientSendDataThread(void *threadData)
             // Send the remaining header.
             result = CAUpdateCharacteristicsToGattServer(
                      bleData->remoteEndpoint->addr,
-                     bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
+                     bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE),
                      CA_SUPPORTED_BLE_MTU_SIZE,
                      LE_UNICAST, 0);
+
             if (CA_STATUS_OK != result)
             {
                 OIC_LOG_V(ERROR,
@@ -1174,9 +1165,10 @@ static void CALEClientSendDataThread(void *threadData)
             // send the last segment of the data (Ex: 22 bytes of 622
             // bytes of data when MTU is 200)
             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
+
             result = CAUpdateCharacteristicsToGattServer(
                      bleData->remoteEndpoint->addr,
-                     bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
+                     bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE),
                      remainingLen,
                      LE_UNICAST, 0);
 
@@ -1210,11 +1202,12 @@ static void CALEClientSendDataThread(void *threadData)
         for (index = 1; index < iter; index++)
         {
             result = CAUpdateCharacteristicsToAllGattServers(
-                         bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
+                         bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE),
                          CA_SUPPORTED_BLE_MTU_SIZE);
+
             if (CA_STATUS_OK != result)
             {
-                OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics (all) failed, result [%d]",
+                OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
                           result);
                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
                 OICFree(dataSegment);
@@ -1232,8 +1225,9 @@ static void CALEClientSendDataThread(void *threadData)
             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
             result =
                 CAUpdateCharacteristicsToAllGattServers(
-                    bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
+                    bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE),
                     remainingLen);
+
             if (CA_STATUS_OK != result)
             {
                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
@@ -1254,7 +1248,8 @@ static void CALEClientSendDataThread(void *threadData)
 
 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
                                   const uint8_t *data,
-                                  uint32_t dataLength)
+                                  uint32_t dataLength,
+                                  u_arraylist_t *senderInfo)
 {
     CALEData_t * const bleData = OICMalloc(sizeof(CALEData_t));
 
@@ -1276,6 +1271,10 @@ static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
 
     memcpy(bleData->data, data, dataLength);
     bleData->dataLen = dataLength;
+    if (senderInfo)
+    {
+        bleData->senderInfo = senderInfo;
+    }
 
     return bleData;
 }
@@ -1304,7 +1303,7 @@ static void CALEDataDestroyer(void *data, uint32_t size)
 
 static CAResult_t CAInitLEAdapterMutex()
 {
-    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAInitLEAdapterMutex");
 
     if (NULL == g_bleIsServerMutex)
     {
@@ -1398,7 +1397,7 @@ static CAResult_t CAInitLEAdapterMutex()
 
 static void CATerminateLEAdapterMutex()
 {
-    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CATerminateLEAdapterMutex");
 
     ca_mutex_free(g_bleIsServerMutex);
     g_bleIsServerMutex = NULL;
@@ -1541,7 +1540,7 @@ static void CATerminateLE();
  *
  * @param[in] remoteAddress Remote address of the device from where
  *                          data is received.
- * @param[in] data          Actual data recevied from the remote
+ * @param[in] data          Actual data received from the remote
  *                          device.
  * @param[in] dataLength    Length of the data received from the
  *                          remote device.
@@ -1624,6 +1623,102 @@ static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
                                             const uint8_t *data,
                                             uint32_t dataLen);
 
+static CAResult_t CALEAdapterGattServerStart()
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartLEGattServer");
+
+    CAResult_t result = CAStartLEGattServer();
+
+#ifndef SINGLE_THREAD
+    /*
+      Don't start the server side sending queue thread until the
+      server itself has actually started.
+    */
+    if (CA_STATUS_OK == result)
+    {
+        ca_mutex_lock(g_bleServerSendDataMutex);
+        result = CAQueueingThreadStart(g_bleServerSendQueueHandle);
+        ca_mutex_unlock(g_bleServerSendDataMutex);
+
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG_V(ERROR,
+                      CALEADAPTER_TAG,
+                      "Unable to start server queuing thread (%d)",
+                      result);
+        }
+    }
+#endif
+
+    return result;
+}
+
+static CAResult_t CALEAdapterGattServerStop()
+{
+#ifndef SINGLE_THREAD
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEAdapterGattServerStop");
+
+    CAResult_t result = CAStopLEGattServer();
+    ca_mutex_lock(g_bleServerSendDataMutex);
+    if (CA_STATUS_OK == result)
+    {
+        result = CAQueueingThreadStop(g_bleServerSendQueueHandle);
+    }
+    ca_mutex_unlock(g_bleServerSendDataMutex);
+
+    return result;
+#else
+    return CAStopLEGattServer();
+#endif
+}
+
+static CAResult_t CALEAdapterGattClientStart()
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartLEGattClient");
+
+    CAResult_t result = CAStartLEGattClient();
+
+#ifndef SINGLE_THREAD
+    /*
+      Don't start the client side sending queue thread until the
+      client itself has actually started.
+    */
+    if (CA_STATUS_OK == result)
+    {
+        ca_mutex_lock(g_bleClientSendDataMutex);
+        result = CAQueueingThreadStart(g_bleClientSendQueueHandle);
+        ca_mutex_unlock(g_bleClientSendDataMutex);
+
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG(ERROR,
+                    CALEADAPTER_TAG,
+                    "Unable to start client queuing thread");
+        }
+    }
+#endif
+
+    return result;
+}
+
+static CAResult_t CALEAdapterGattClientStop()
+{
+#ifndef SINGLE_THREAD
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEAdapterGattClientStop");
+    CAStopLEGattClient();
+
+    ca_mutex_lock(g_bleClientSendDataMutex);
+    CAResult_t result = CAQueueingThreadStop(g_bleClientSendQueueHandle);
+    ca_mutex_unlock(g_bleClientSendDataMutex);
+
+    return result;
+#else
+    CAStopLEGattClient();
+
+    return CA_STATUS_OK;
+#endif
+}
+
 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
                           CANetworkPacketReceivedCallback reqRespCallback,
                           CANetworkChangeCallback netCallback,
@@ -1644,18 +1739,33 @@ CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleAdapterMutex failed!");
         return CA_STATUS_FAILED;
     }
+
     result = CAInitializeLENetworkMonitor();
     if (CA_STATUS_OK != result)
     {
         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
         return CA_STATUS_FAILED;
     }
-
-    CAInitializeLEAdapter();
+    CAInitializeLEAdapter(handle);
 
     CASetLEClientThreadPoolHandle(handle);
+
+    result = CAInitializeLEGattClient();
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattClient() failed");
+        return CA_STATUS_FAILED;
+    }
+
     CASetLEReqRespClientCallback(CALEAdapterClientReceivedData);
     CASetLEServerThreadPoolHandle(handle);
+    result = CAInitializeLEGattServer();
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattServer() failed");
+        return CA_STATUS_FAILED;
+    }
+
     CASetLEAdapterThreadPoolHandle(handle);
     CASetLEReqRespServerCallback(CALEAdapterServerReceivedData);
     CASetLEReqRespAdapterCallback(reqRespCallback);
@@ -1677,10 +1787,11 @@ CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
             .sendDataToAll = CASendLEMulticastData,
             .GetnetInfo = CAGetLEInterfaceInformation,
             .readData = CAReadLEData,
-            .terminate = CATerminateLE
+            .terminate = CATerminateLE,
+            .cType = CA_ADAPTER_GATT_BTLE
         };
 
-    registerCallback(connHandler, CA_ADAPTER_GATT_BTLE);
+    registerCallback(connHandler);
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
 
@@ -1702,19 +1813,26 @@ static CAResult_t CAStopLE()
 #endif
 
     ca_mutex_lock(g_bleIsServerMutex);
-    if (true == g_isServer)
-    {
-        CAStopLEGattServer();
-    }
-    else
-    {
-        CAStopLEGattClient();
+    switch (g_adapterType)
+    {
+        case ADAPTER_SERVER:
+            CALEAdapterGattServerStop();
+            break;
+        case ADAPTER_CLIENT:
+            CALEAdapterGattClientStop();
+            break;
+        case ADAPTER_BOTH_CLIENT_SERVER:
+            CALEAdapterGattServerStop();
+            CALEAdapterGattClientStop();
+            break;
+        default:
+            break;
     }
     ca_mutex_unlock(g_bleIsServerMutex);
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
 
-    return CA_STATUS_OK;
+    return CAStopLEAdapter();
 }
 
 static void CATerminateLE()
@@ -1728,14 +1846,22 @@ static void CATerminateLE()
     CATerminateLENetworkMonitor();
 
     ca_mutex_lock(g_bleIsServerMutex);
-    if (true == g_isServer)
-    {
-        CATerminateLEGattServer();
-    }
-    else
-    {
-        CATerminateLEGattClient();
-    }
+    switch (g_adapterType)
+    {
+        case ADAPTER_SERVER:
+            CATerminateLEGattServer();
+            break;
+        case ADAPTER_CLIENT:
+            CATerminateLEGattClient();
+            break;
+        case ADAPTER_BOTH_CLIENT_SERVER:
+            CATerminateLEGattServer();
+            CATerminateLEGattClient();
+            break;
+        default:
+            break;
+    }
+    g_adapterType = ADAPTER_EMPTY;
     ca_mutex_unlock(g_bleIsServerMutex);
 
 #ifndef SINGLE_THREAD
@@ -1748,7 +1874,7 @@ static void CATerminateLE()
 
 static CAResult_t CAStartLEListeningServer()
 {
-    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAStartLEListeningServer");
 #ifndef ROUTING_GATEWAY
     CAResult_t result = CA_STATUS_OK;
 #ifndef SINGLE_THREAD
@@ -1756,32 +1882,40 @@ static CAResult_t CAStartLEListeningServer()
     if (CA_STATUS_OK != result)
     {
         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerQueues failed");
-        return CA_STATUS_FAILED;
+        return result;
     }
 #endif
 
-    result = CAGetLEAdapterState();
-    if (CA_ADAPTER_NOT_ENABLED == result)
+    ca_mutex_lock(g_bleIsServerMutex);
+    switch (g_adapterType)
     {
-        gLeServerStatus = CA_LISTENING_SERVER;
-        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Listen Server will be started once BT Adapter is enabled");
-        return CA_STATUS_OK;
+        case ADAPTER_CLIENT:
+            g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
+            break;
+        case ADAPTER_BOTH_CLIENT_SERVER:
+            break;
+        default:
+            g_adapterType = ADAPTER_SERVER;
     }
+    ca_mutex_unlock(g_bleIsServerMutex);
 
-    if (CA_STATUS_FAILED == result)
+    result = CAGetLEAdapterState();
+    if (CA_STATUS_OK != result)
     {
-        OIC_LOG(ERROR, CALEADAPTER_TAG, "Bluetooth get state failed!");
-        return CA_STATUS_FAILED;
+        if (CA_ADAPTER_NOT_ENABLED == result)
+        {
+            OIC_LOG(DEBUG,
+                    CALEADAPTER_TAG,
+                    "Listen Server will be started once BT Adapter is enabled");
+        }
+    }
+    else
+    {
+        result = CALEAdapterGattServerStart();
     }
-
-    CAStartLEGattServer();
-
-    ca_mutex_lock(g_bleIsServerMutex);
-    g_isServer = true;
-    ca_mutex_unlock(g_bleIsServerMutex);
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
-    return CA_STATUS_OK;
+    return result;
 #else
     // Routing Gateway only supports BLE client mode.
     OIC_LOG(ERROR, CALEADAPTER_TAG, "LE server not supported in Routing Gateway");
@@ -1797,38 +1931,47 @@ static CAResult_t CAStopLEListeningServer()
 
 static CAResult_t CAStartLEDiscoveryServer()
 {
-    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAStartLEDiscoveryServer");
     CAResult_t result = CA_STATUS_OK;
 #ifndef SINGLE_THREAD
     result = CAInitLEClientQueues();
     if (CA_STATUS_OK != result)
     {
         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
-        return CA_STATUS_FAILED;
+        return result;
     }
 #endif
-    result = CAGetLEAdapterState();
-    if (CA_ADAPTER_NOT_ENABLED == result)
+
+    ca_mutex_lock(g_bleIsServerMutex);
+    switch (g_adapterType)
     {
-        gLeServerStatus = CA_DISCOVERY_SERVER;
-        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Listen Server will be started once BT Adapter is enabled");
-        return CA_STATUS_OK;
+        case ADAPTER_SERVER:
+            g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
+            break;
+        case ADAPTER_BOTH_CLIENT_SERVER:
+            break;
+        default:
+            g_adapterType = ADAPTER_CLIENT;
     }
+    ca_mutex_unlock(g_bleIsServerMutex);
 
-    if (CA_STATUS_FAILED == result)
+    result = CAGetLEAdapterState();
+    if (CA_STATUS_OK != result)
     {
-        OIC_LOG(ERROR, CALEADAPTER_TAG, "Bluetooth get state failed!");
-        return CA_STATUS_FAILED;
+        if (CA_ADAPTER_NOT_ENABLED == result)
+        {
+            OIC_LOG(DEBUG,
+                    CALEADAPTER_TAG,
+                    "Discovery Server will be started once BT Adapter is enabled");
+        }
+    }
+    else
+    {
+        result = CALEAdapterGattClientStart();
     }
-
-    CAStartLEGattClient();
-
-    ca_mutex_lock(g_bleIsServerMutex);
-    g_isServer = false;
-    ca_mutex_unlock(g_bleIsServerMutex);
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
-    return CA_STATUS_OK;
+    return result;
 }
 
 static CAResult_t CAReadLEData()
@@ -1845,7 +1988,7 @@ static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
                                    const void *data,
                                    uint32_t dataLen)
 {
-    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CASendLEUnicastData");
 
     //Input validation
     VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
@@ -1853,32 +1996,41 @@ static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
 
     CAResult_t result = CA_STATUS_FAILED;
 
+    OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
+    if (ADAPTER_EMPTY == g_adapterType)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
+    }
+
     ca_mutex_lock(g_bleIsServerMutex);
-    if (true  == g_isServer)
+    if (ADAPTER_SERVER == g_adapterType || ADAPTER_BOTH_CLIENT_SERVER == g_adapterType)
     {
         result = CALEAdapterServerSendData(endpoint, data, dataLen);
         if (CA_STATUS_OK != result)
         {
-            OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data failed\n");
+            ca_mutex_unlock(g_bleIsServerMutex);
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed");
             if (g_errorHandler)
             {
                 g_errorHandler(endpoint, data, dataLen, result);
             }
-            ca_mutex_unlock(g_bleIsServerMutex);
+
             return -1;
         }
     }
-    else
+
+    if (ADAPTER_CLIENT == g_adapterType || ADAPTER_BOTH_CLIENT_SERVER == g_adapterType)
     {
         result = CALEAdapterClientSendData(endpoint, data, dataLen);
         if (CA_STATUS_OK != result)
         {
-            OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data failed \n");
-            if (g_errorHandler)
-            {
-                g_errorHandler(endpoint, data, dataLen, result);
-            }
             ca_mutex_unlock(g_bleIsServerMutex);
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
+
+             if (g_errorHandler)
+             {
+                 g_errorHandler(endpoint, data, dataLen, result);
+             }
             return -1;
         }
     }
@@ -1892,7 +2044,7 @@ static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
                                      const void *data,
                                      uint32_t dataLen)
 {
-    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CASendLEMulticastData");
 
     //Input validation
     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
@@ -1905,15 +2057,22 @@ static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
 
     CAResult_t result = CA_STATUS_FAILED;
 
+    OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
+    if (ADAPTER_EMPTY == g_adapterType)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
+    }
+
     ca_mutex_lock(g_bleIsServerMutex);
-    if (true  == g_isServer)
+    if (ADAPTER_SERVER == g_adapterType || ADAPTER_BOTH_CLIENT_SERVER == g_adapterType)
     {
         result = CALEAdapterServerSendData(NULL, data, dataLen);
         if (CA_STATUS_OK != result)
         {
-            OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data failed" );
-
             ca_mutex_unlock(g_bleIsServerMutex);
+
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data for server failed" );
+
             if (g_errorHandler)
             {
                 g_errorHandler(endpoint, data, dataLen, result);
@@ -1921,23 +2080,26 @@ static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
             return -1;
         }
     }
-    else
+
+    if (ADAPTER_CLIENT == g_adapterType || ADAPTER_BOTH_CLIENT_SERVER == g_adapterType)
     {
         result = CALEAdapterClientSendData(NULL, data, dataLen);
         if (CA_STATUS_OK != result)
         {
-            OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data failed" );
+            ca_mutex_unlock(g_bleIsServerMutex);
+
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data for client failed" );
+
             if (g_errorHandler)
             {
                 g_errorHandler(endpoint, data, dataLen, result);
             }
-            ca_mutex_unlock(g_bleIsServerMutex);
             return -1;
         }
     }
     ca_mutex_unlock(g_bleIsServerMutex);
 
-    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CASendLEMulticastData");
     return dataLen;
 }
 
@@ -2010,6 +2172,12 @@ static CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCa
         {
             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
         }
+
+        res = CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCb);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "CALEConnectionStateChangedCb failed!");
+        }
     }
     else
     {
@@ -2024,9 +2192,70 @@ static CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCa
     return res;
 }
 
+static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
+                                         bool isConnected)
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEConnectionStateChangedCb");
+
+    VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
+    (void)adapter;
+
+#ifdef __TIZEN__
+    ca_mutex_lock(g_bleIsServerMutex);
+    switch (g_adapterType)
+    {
+        case ADAPTER_SERVER:
+            CALEGattServerConnectionStateChanged(isConnected, address);
+            break;
+        case ADAPTER_CLIENT:
+            CALEGattConnectionStateChanged(isConnected, address);
+            break;
+        case ADAPTER_BOTH_CLIENT_SERVER:
+            CALEGattConnectionStateChanged(isConnected, address);
+            CALEGattServerConnectionStateChanged(isConnected, address);
+            break;
+        default:
+            break;
+    }
+    ca_mutex_unlock(g_bleIsServerMutex);
+#endif
+
+    if(!isConnected)
+    {
+#ifndef SINGLE_THREAD
+        if(g_bleClientSenderInfo)
+        {
+            CALERemoveReceiveQueueData(g_bleClientSenderInfo, address);
+        }
+
+        if(g_bleServerSenderInfo)
+        {
+            CALERemoveReceiveQueueData(g_bleServerSenderInfo, address);
+        }
+
+        // remove data of send queue.
+        if (g_bleClientSendQueueHandle)
+        {
+            CALERemoveSendQueueData(g_bleClientSendQueueHandle,
+                                    g_bleClientSendDataMutex,
+                                    address);
+        }
+
+        if (g_bleServerSendQueueHandle)
+        {
+            CALERemoveSendQueueData(g_bleServerSendQueueHandle,
+                                    g_bleServerSendDataMutex,
+                                    address);
+        }
+#endif
+    }
+
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+}
+
 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state)
 {
-    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEDeviceStateChangedCb");
 
     VERIFY_NON_NULL_VOID(g_localBLEAddress, CALEADAPTER_TAG, "g_localBLEAddress is null");
     CAEndpoint_t localEndpoint = { .adapter = CA_ADAPTER_GATT_BTLE };
@@ -2037,19 +2266,46 @@ static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state)
               g_localBLEAddress);
     ca_mutex_unlock(g_bleLocalAddressMutex);
 
-    g_bleAdapterState = adapter_state;
-    // Start a GattServer/Client if gLeServerStatus is SET
-    if (CA_LISTENING_SERVER == gLeServerStatus)
+    if (CA_ADAPTER_ENABLED == adapter_state)
     {
-        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartLEGattServer");
-        CAStartLEGattServer();
+        ca_mutex_lock(g_bleIsServerMutex);
+        switch (g_adapterType)
+        {
+            case ADAPTER_SERVER:
+                CALEAdapterGattServerStart();
+                break;
+            case ADAPTER_CLIENT:
+                CALEAdapterGattClientStart();
+                break;
+            case ADAPTER_BOTH_CLIENT_SERVER:
+                CALEAdapterGattServerStart();
+                CALEAdapterGattClientStart();
+                break;
+            default:
+                break;
+        }
+        ca_mutex_unlock(g_bleIsServerMutex);
     }
-    else if (CA_DISCOVERY_SERVER == gLeServerStatus)
+    else
     {
-        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartBleGattClient");
-        CAStartLEGattClient();
+        ca_mutex_lock(g_bleIsServerMutex);
+        switch (g_adapterType)
+        {
+            case ADAPTER_SERVER:
+                CALEAdapterGattServerStop();
+                break;
+            case ADAPTER_CLIENT:
+                CALEAdapterGattClientStop();
+                break;
+            case ADAPTER_BOTH_CLIENT_SERVER:
+                CALEAdapterGattServerStop();
+                CALEAdapterGattClientStop();
+                break;
+            default:
+                break;
+        }
+        ca_mutex_unlock(g_bleIsServerMutex);
     }
-    gLeServerStatus = CA_SERVER_NOTSTARTED;
 
     ca_mutex_lock(g_bleNetworkCbMutex);
     if (NULL != g_networkCallback)
@@ -2080,12 +2336,13 @@ static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
                         "g_bleClientSendDataMutex is NULL",
                         CA_STATUS_FAILED);
 
-    VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG, "g_bleClientSendQueueHandle",
+    VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
+                        "g_bleClientSendQueueHandle",
                         CA_STATUS_FAILED);
 
     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%u]", dataLen);
 
-    CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen);
+    CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen, NULL);
     if (!bleData)
     {
         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
@@ -2109,30 +2366,13 @@ static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
 
 #ifdef SINGLE_THREAD
-    uint8_t header[CA_HEADER_LENGTH] = { 0 };
-
-    CAResult_t result =
-        CAGenerateHeader(header, CA_HEADER_LENGTH, dataLen);
-
-    if (CA_STATUS_OK != result)
-    {
-        OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
-        return CA_STATUS_FAILED;
-    }
-
     if (!CAIsLEConnected())
     {
         OIC_LOG(ERROR, CALEADAPTER_TAG, "le not conn");
         return CA_STATUS_FAILED;
     }
 
-    result = CAUpdateCharacteristicsToAllGattClients(header, CA_HEADER_LENGTH);
-    if (CA_STATUS_OK != result)
-    {
-        OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
-        return CA_STATUS_FAILED;
-    }
-
+    CAResult_t result = CA_STATUS_OK;
     const uint32_t dataLimit = dataLen / CA_SUPPORTED_BLE_MTU_SIZE;
     for (uint32_t iter = 0; iter < dataLimit; iter++)
     {
@@ -2178,7 +2418,7 @@ static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
 
     CALEData_t * const bleData =
-        CACreateLEData(remoteEndpoint, data, dataLen);
+        CACreateLEData(remoteEndpoint, data, dataLen, NULL);
 
     if (!bleData)
     {
@@ -2244,7 +2484,7 @@ static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
               dataLength);
 
     CALEData_t * const bleData =
-        CACreateLEData(remoteEndpoint, data, dataLength);
+        CACreateLEData(remoteEndpoint, data, dataLength, g_bleServerSenderInfo);
 
     if (!bleData)
     {
@@ -2274,7 +2514,8 @@ static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
 #ifndef SINGLE_THREAD
-    VERIFY_NON_NULL_RET(g_bleReceiverQueue, CALEADAPTER_TAG, "g_bleReceiverQueue",
+    VERIFY_NON_NULL_RET(g_bleReceiverQueue, CALEADAPTER_TAG,
+                        "g_bleReceiverQueue",
                         CA_STATUS_FAILED);
 
     //Add message to data queue
@@ -2290,7 +2531,8 @@ static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received from LE layer [%u]", dataLength);
 
     // Create bleData to add to queue
-    CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLength);
+    CALEData_t *bleData = CACreateLEData(remoteEndpoint, data,
+                                         dataLength, g_bleClientSenderInfo);
     if (!bleData)
     {
         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
@@ -2353,3 +2595,69 @@ static void CALEErrorHandler(const char *remoteAddress,
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler OUT");
 }
+
+#ifndef SINGLE_THREAD
+static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle, ca_mutex mutex,
+                                    const char* address)
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALERemoveSendQueueData");
+
+    VERIFY_NON_NULL_VOID(queueHandle, CALEADAPTER_TAG, "queueHandle");
+    VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
+
+    ca_mutex_lock(mutex);
+    while (u_queue_get_size(queueHandle->dataQueue) > 0)
+    {
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "get data from queue");
+        u_queue_message_t *message = u_queue_get_element(queueHandle->dataQueue);
+        if (NULL != message)
+        {
+            CALEData_t *bleData = (CALEData_t *) message->msg;
+            if (bleData && bleData->remoteEndpoint)
+            {
+                if (!strcmp(bleData->remoteEndpoint->addr, address))
+                {
+                    OIC_LOG(DEBUG, CALEADAPTER_TAG, "found the message of disconnected device");
+                    if (NULL != queueHandle->destroy)
+                    {
+                        queueHandle->destroy(message->msg, message->size);
+                    }
+                    else
+                    {
+                        OICFree(message->msg);
+                    }
+
+                    OICFree(message);
+                }
+            }
+        }
+    }
+    ca_mutex_unlock(mutex);
+}
+
+static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList, const char* address)
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALERemoveSendQueueData");
+
+    VERIFY_NON_NULL_VOID(dataInfoList, CALEADAPTER_TAG, "dataInfoList");
+    VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
+
+    CABLESenderInfo_t *senderInfo = NULL;
+    uint32_t senderIndex = 0;
+
+    if(CA_STATUS_OK == CALEGetSenderInfo(address, dataInfoList, &senderInfo,
+                                         &senderIndex))
+    {
+        u_arraylist_remove(dataInfoList, senderIndex);
+        OICFree(senderInfo->defragData);
+        OICFree(senderInfo->remoteEndpoint);
+        OICFree(senderInfo);
+
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "SenderInfo is removed for disconnection");
+    }
+    else
+    {
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "SenderInfo doesn't exist");
+    }
+}
+#endif
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/linux/.gitignore b/resource/csdk/connectivity/src/bt_le_adapter/linux/.gitignore
new file mode 100644 (file)
index 0000000..4c86582
--- /dev/null
@@ -0,0 +1,2 @@
+# Ignore gbdus-codegen generated headers copied to this directory.
+*-glue.h
\ No newline at end of file
index bbf1674..e4f2fb1 100644 (file)
@@ -25,63 +25,15 @@ import os.path
 # Top-level build (variant) directory.
 root_build_dir = env['BUILD_DIR']
 
-# Build (variant) directory corresponding to this source directory.
-this_build_dir = os.path.join(root_build_dir,
-                              os.path.dirname(File(SConscript).srcnode().path))
-
-# The Linux BLE adapter implementation uses GDBus to make D-Bus based
-# method calls to BlueZ.  Pull in the necessary dependencies.
-env.ParseConfig("pkg-config gio-unix-2.0 --cflags --libs")
-
-# Set up commands to generate GDBus code from the D-Bus introspection
-# XML.
-freedesktop_prefix = 'org.freedesktop.DBus.'
-bluez_prefix = 'org.bluez.'
-
-dbus_introspection_xml = {
-    'object_manager' : freedesktop_prefix,
-    'bluez'          : bluez_prefix,
-}
-
-# The source files to be compiled as part of the connectivity
-# abstraction library.
-glue_files = []
-
-for file, prefix in dbus_introspection_xml.items():
-    source_xml  = file + '.xml'
-    glue        = file + '-glue'
-    glue_source = glue + '.c'
-    glue_header = glue + '.h'
-    targets     = [ glue_source, glue_header ]
-
-    # Include the glue header in the list as well to make sure it is
-    # generated before other source files that depend on it are
-    # compiled.
-    glue_files += targets
+# Source node that allows us to easily obtain paths and directories
+# related to this source directory.
+src_node = File(SConscript).Dir(os.curdir).srcnode()
 
-    # Generate GDBus skeletons in the variant (build) directory.
-    env.Command(targets,
-                source_xml,
-                'cd %s '
-                '&& gdbus-codegen --generate-c-code %s --interface-prefix %s %s '
-                '&& cd -'
-                % (this_build_dir,
-                   glue,
-                   prefix,
-                   os.path.join(env['SRC_DIR'], '$SOURCE')))
+# Absolute path of the source directory.
+this_src_dir = src_node.abspath
 
-    # Mark generated file for cleaning when running "scons -c".
-    #
-    # @todo Verify that the generated *-glue.[ch] files are removed on
-    #       running "scons -c" once that is working in the master
-    #       branch again.
-    for target in targets:
-        generated_target = os.path.join(this_build_dir, target)
-        env.Clean(target, generated_target)
-
-# The generated "glue" headers are found in the build directory
-# corresponding to this source directory.
-env.AppendUnique(CPPPATH = this_build_dir)
+# Build (variant) directory corresponding to this source directory.
+this_build_dir = os.path.join(root_build_dir, src_node.path)
 
 # The Linux BLE transport exports its GATT and LE advertisement
 # related D-Bus interfaces to the D-Bus system bus so that they may be
@@ -119,6 +71,22 @@ env.AppendUnique(
         ('GLIB_VERSION_MIN_REQUIRED', 'GLIB_VERSION_2_32')
     ])
 
+# The Linux BLE adapter implementation uses GDBus to make D-Bus based
+# method calls to BlueZ.  Pull in the necessary dependencies.
+env.ParseConfig("pkg-config gio-unix-2.0 --cflags --libs")
+
+# Set up commands to generate GDBus code from the D-Bus introspection
+# XML.
+freedesktop_prefix = 'org.freedesktop.DBus.'
+bluez_prefix = 'org.bluez.'
+
+dbus_introspection_xml = {
+    'object_manager' : freedesktop_prefix,
+    'bluez'          : bluez_prefix,
+}
+
+# The source files to be compiled as part of the connectivity
+# abstraction library.
 src_files = [ 'characteristic.c',
               'descriptor.c',
               'service.c',
@@ -131,7 +99,49 @@ src_files = [ 'characteristic.c',
               'recv.c',
               'caleinterface.c'
           ]
-src_files = glue_files + src_files
+
+glue_files = []
+
+for file, prefix in dbus_introspection_xml.items():
+    source_xml  = file + '.xml'
+    glue        = file + '-glue'
+    glue_source = glue + '.c'
+    glue_header = glue + '.h'
+
+    glue_files.append(glue_source)
+
+    # Generate GDBus skeletons in the variant (build) directory.
+    #
+    # A link to the generated GDBus glue header is also created in the
+    # source directory to avoid having to explicitly add the variant
+    # directory to the preprocessor include path.
+    targets     = [ glue_source, glue_header ]
+    glue_header_gen  = os.path.join(this_build_dir, glue_header)
+    glue_header_copy = os.path.join(this_src_dir, glue_header)
+
+    gen = env.Command(targets,
+                      source_xml,
+                      'cd %s '
+                      '&& gdbus-codegen --generate-c-code %s '
+                      '   --interface-prefix %s ${SOURCE.abspath} '
+                      '&& ln -sf %s %s '
+                      '&& cd -'
+                      % (this_build_dir,
+                         glue, prefix,
+                         glue_header_gen, glue_header_copy))
+
+    # Mark generated file for cleaning when running "scons -c".
+    for target in targets:
+        generated_target = os.path.join(this_build_dir, target)
+        env.Clean(target, generated_target)
+
+    env.Clean(glue_source, glue_header_copy)
+
+    # Force a dependency on copied glue header to make sure it exists
+    # before compilation of the non-generated source files begins.
+    env.Depends(src_files, gen)
+
+src_files += glue_files
 
 Return('src_files')
 
index 632240a..0b3e946 100644 (file)
@@ -57,7 +57,9 @@ static bool CALECheckStarted()
 {
     ca_mutex_lock(g_context.lock);
 
-    bool const started = (g_context.event_loop != NULL);
+    bool const started =
+        (g_context.event_loop != NULL
+         && g_main_loop_is_running(g_context.event_loop));
 
     ca_mutex_unlock(g_context.lock);
 
@@ -114,11 +116,6 @@ static void CALEOnInterfaceProxyPropertiesChanged(
     (void)manager;
     (void)object_proxy;
     (void)invalidated_properties;
-    OIC_LOG_V(DEBUG,
-              TAG,
-              "Properties Changed on %s:\n",
-              g_dbus_object_get_object_path(
-                  G_DBUS_OBJECT(object_proxy)));
 
     char const * const interface_name =
         g_dbus_proxy_get_interface_name(interface_proxy);
@@ -135,12 +132,23 @@ static void CALEOnInterfaceProxyPropertiesChanged(
         return;
     }
 
+    OIC_LOG_V(DEBUG,
+              TAG,
+              "%s properties Changed on %s:\n",
+              interface_name,
+              g_dbus_proxy_get_object_path(interface_proxy));
+
     CALEContext * const context = user_data;
 
     GVariantIter iter;
     gchar const * key   = NULL;
     GVariant    * value = NULL;
 
+    /**
+     * @todo Since we're only looking up one value here,
+     *       i.e. "Powered", can't we just use
+     *       g_variant_lookup_value() instead of this while() loop?
+     */
     g_variant_iter_init(&iter, changed_properties);
     while (g_variant_iter_next(&iter, "{&sv}", &key, &value))
     {
@@ -150,26 +158,10 @@ static void CALEOnInterfaceProxyPropertiesChanged(
               Report a change in the availability of the bluetooth
               adapter.
             */
-
             gboolean const powered = g_variant_get_boolean(value);
             CAAdapterState_t const status =
                 (powered ? CA_ADAPTER_ENABLED : CA_ADAPTER_DISABLED);
 
-            CAEndpoint_t info =
-                {
-                    .adapter = CA_ADAPTER_GATT_BTLE,
-                };
-
-            GVariant * const prop =
-                g_dbus_proxy_get_cached_property(interface_proxy,
-                                                 "Address");
-
-            gchar const * const address = g_variant_get_string(prop, NULL);
-
-            OICStrcpy(info.addr, sizeof(info.addr), address);
-
-            g_variant_unref(prop);
-
             /**
              * @todo Should we acquire the context lock here to
              *       prevent the @c CALEDeviceStateChangedCallback
@@ -346,6 +338,11 @@ static void CALEOnInterfacesRemoved(GDBusConnection * connection,
             if (strcmp(path,
                        g_dbus_proxy_get_object_path(proxy)) == 0)
             {
+                /**
+                 * @todo If a BlueZ Device was removed, update the
+                 *       characteristic map, accordingly.
+                 */
+
                 // Found a match!
                 g_object_unref(proxy);
 
@@ -366,40 +363,6 @@ static void CALEOnInterfacesRemoved(GDBusConnection * connection,
     }
 }
 
-static void CALEOnPropertiesChanged(GDBusConnection * connection,
-                                    char const * sender_name,
-                                    char const * object_path,
-                                    char const * interface_name,
-                                    char const * signal_name,
-                                    GVariant   * parameters,
-                                    gpointer     user_data)
-{
-    (void)connection;
-    (void)user_data;
-    CALEDumpDBusSignalParameters(sender_name,
-                                 object_path,
-                                 interface_name,
-                                 signal_name,
-                                 parameters);
-}
-
-static void CALEOnPropertyChanged(GDBusConnection * connection,
-                                  char const * sender_name,
-                                  char const * object_path,
-                                  char const * interface_name,
-                                  char const * signal_name,
-                                  GVariant   * parameters,
-                                  gpointer     user_data)
-{
-    (void)connection;
-    (void)user_data;
-    CALEDumpDBusSignalParameters(sender_name,
-                                 object_path,
-                                 interface_name,
-                                 signal_name,
-                                 parameters);
-}
-
 static void CALESubscribeToSignals(CALEContext * context,
                                    GDBusConnection * connection,
                                    GDBusObjectManager * object_manager)
@@ -437,52 +400,6 @@ static void CALESubscribeToSignals(CALEContext * context,
             NULL,  // user_data
             NULL);
 
-#if GLIB_CHECK_VERSION(2,38,0)
-    /*
-      The G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH flag was introduced in
-      GLib 2.38.
-    */
-    static GDBusSignalFlags const device_signal_flags =
-        G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH;
-#else
-    static GDBusSignalFlags const device_signal_flags =
-        G_DBUS_SIGNAL_FLAGS_NONE;
-#endif
-
-    /**
-     * @todo Verify that this signal subscription is needed.
-     *
-     * @bug The arg0 argument below should be a D-Bus object path, not
-     *      interface name.
-     */
-    guint const properties_changed_sub_id =
-        g_dbus_connection_signal_subscribe(
-            connection,
-            NULL,  // sender
-            "org.freedesktop.DBus.Properties",
-            "PropertiesChanged",
-            NULL,  // object path
-            "org.bluez.Device1",  // arg0
-            device_signal_flags,
-            CALEOnPropertiesChanged,
-            NULL,  // user_data
-            NULL);
-
-    /**
-     * @todo Verify that this signal subscription is needed.
-     */
-    guint const property_changed_sub_id =
-        g_dbus_connection_signal_subscribe(connection,
-                                           NULL,  // sender
-                                           BLUEZ_ADAPTER_INTERFACE,
-                                           "PropertyChanged",
-                                           NULL,  // object path
-                                           NULL,  // arg0
-                                           G_DBUS_SIGNAL_FLAGS_NONE,
-                                           CALEOnPropertyChanged,
-                                           NULL,  // user_data
-                                           NULL);
-
     g_signal_connect(object_manager,
                      "interface-proxy-properties-changed",
                      G_CALLBACK(CALEOnInterfaceProxyPropertiesChanged),
@@ -492,8 +409,6 @@ static void CALESubscribeToSignals(CALEContext * context,
 
     context->interfaces_added_sub_id   = interfaces_added_sub_id;
     context->interfaces_removed_sub_id = interfaces_removed_sub_id;
-    context->properties_changed_sub_id = properties_changed_sub_id;
-    context->property_changed_sub_id   = property_changed_sub_id;
 
     ca_mutex_unlock(context->lock);
 }
@@ -594,13 +509,9 @@ static void CALETearDownDBus(CALEContext * context)
 
     guint const interfaces_added   = context->interfaces_added_sub_id;
     guint const interfaces_removed = context->interfaces_removed_sub_id;
-    guint const properties_changed = context->properties_changed_sub_id;
-    guint const property_changed   = context->property_changed_sub_id;
 
     context->interfaces_added_sub_id   = 0;
     context->interfaces_removed_sub_id = 0;
-    context->properties_changed_sub_id = 0;
-    context->property_changed_sub_id   = 0;
 
     ca_mutex_unlock(context->lock);
 
@@ -626,10 +537,6 @@ static void CALETearDownDBus(CALEContext * context)
                                              interfaces_added);
         g_dbus_connection_signal_unsubscribe(connection,
                                              interfaces_removed);
-        g_dbus_connection_signal_unsubscribe(connection,
-                                             properties_changed);
-        g_dbus_connection_signal_unsubscribe(connection,
-                                             property_changed);
         g_object_unref(connection);
     }
 }
@@ -676,7 +583,6 @@ static bool CALEDeviceFilter(GDBusProxy * device)
     return accepted;
 }
 
-
 static bool CALESetUpBlueZObjects(CALEContext * context)
 {
     bool success = false;
@@ -734,11 +640,23 @@ static bool CALESetUpBlueZObjects(CALEContext * context)
         ca_mutex_unlock(context->lock);
     }
 
-    /* success = CAGattClientInitialize(context); */
-
     return success;
 }
 
+/**
+ * Inform thread waiting for the event loop to start that the loop has
+ * started.  This is done in the context of the event loop itself so
+ * that we can be certain that the event loop is indeed running.
+ */
+static gboolean CALEEventLoopStarted(gpointer user_data)
+{
+    sem_t * const sem = user_data;
+
+    (void) sem_post(sem);
+
+    return G_SOURCE_REMOVE;
+}
+
 static void CALEStartEventLoop(void * data)
 {
     CALEContext * const context = data;
@@ -749,13 +667,6 @@ static void CALEStartEventLoop(void * data)
     GMainContext * const loop_context = g_main_context_new();
     GMainLoop * const event_loop = g_main_loop_new(loop_context, FALSE);
 
-    ca_mutex_lock(context->lock);
-
-    assert(context->event_loop == NULL);
-    context->event_loop = event_loop;
-
-    ca_mutex_unlock(context->lock);
-
     g_main_context_push_thread_default(loop_context);
 
     /*
@@ -764,12 +675,41 @@ static void CALEStartEventLoop(void * data)
       signal handling occurs in the same thread as the one running the
       GLib event loop.
     */
-    if (!CALESetUpDBus(&g_context))
-        return;
+    if (CALESetUpDBus(&g_context))
+    {
+        ca_mutex_lock(context->lock);
+
+        assert(context->event_loop == NULL);
+        context->event_loop = event_loop;
 
-    ca_cond_signal(g_context.condition);
+        ca_mutex_unlock(context->lock);
+
+        /*
+          Add an idle handler that notifies a thread waiting for the
+          GLib event loop to run that the event loop is actually
+          running.  We do this in the context of the event loop itself
+          to avoid race conditions.
+        */
+        GSource * const source = g_idle_source_new();
+        g_source_set_priority(source, G_PRIORITY_HIGH_IDLE);
+        g_source_set_callback(source,
+                              CALEEventLoopStarted,
+                              &context->le_started,  // data
+                              NULL);                 // notify
+        (void) g_source_attach(source, loop_context);
+        g_source_unref(source);
+
+        g_main_loop_run(event_loop);  // Blocks until loop is quit.
+
+        CALETearDownDBus(&g_context);
+    }
 
-    g_main_loop_run(event_loop);
+    /*
+      Clean up in the same thread to avoid having to explicitly bump
+      the ref count to retain ownership.
+    */
+    g_main_context_unref(loop_context);
+    g_main_loop_unref(event_loop);
 }
 
 static void CALEStopEventLoop(CALEContext * context)
@@ -791,10 +731,7 @@ static void CALEStopEventLoop(CALEContext * context)
         if (loop_context != NULL)
         {
             g_main_context_wakeup(loop_context);
-            g_main_context_unref(loop_context);
         }
-
-        g_main_loop_unref(event_loop);
     }
 }
 
@@ -818,7 +755,7 @@ static bool CALEWaitForNonEmptyList(GList * const * list,
     {
         if (ca_cond_wait_for(g_context.condition,
                              g_context.lock,
-                             timeout) == 0)
+                             timeout) == CA_WAIT_SUCCESS)
         {
             /*
               Condition variable was signaled before the timeout was
@@ -833,52 +770,11 @@ static bool CALEWaitForNonEmptyList(GList * const * list,
     return success;
 }
 
-static CAResult_t CALEStop()
-{
-    CAResult_t result = CA_STATUS_FAILED;
-
-    OIC_LOG(DEBUG, TAG, "Stop Linux BLE adapter.");
-
-    // Only stop if we were previously started.
-    if (!CALECheckStarted())
-    {
-        return result;
-    }
-
-    // Stop the event loop thread regardless of previous errors.
-    CALEStopEventLoop(&g_context);
-
-    CALETearDownDBus(&g_context);
-
-    return result;
-}
-
-static void CALETerminate()
-{
-    OIC_LOG(DEBUG, TAG, "Terminate BLE adapter.");
-
-    CAPeripheralFinalize();
-
-    ca_mutex_lock(g_context.lock);
-
-    g_context.on_device_state_changed = NULL;
-    g_context.on_server_received_data = NULL;
-    g_context.on_client_received_data = NULL;
-    g_context.client_thread_pool      = NULL;
-    g_context.server_thread_pool      = NULL;
-    g_context.on_client_error         = NULL;
-    g_context.on_server_error         = NULL;
-
-    ca_mutex_unlock(g_context.lock);
-
-    ca_cond_free(g_context.condition);
-    ca_mutex_free(g_context.lock);
-}
-
 // -----------------------------------------------------------------------
 
-CAResult_t CAInitializeLEAdapter()
+CAResult_t CAInitializeLEAdapter(const ca_thread_pool_t threadPool)
 {
+    (void)threadPool;
 #if !GLIB_CHECK_VERSION(2,36,0)
     /*
       Initialize the GLib type system.
@@ -889,11 +785,6 @@ CAResult_t CAInitializeLEAdapter()
     g_type_init();
 #endif
 
-    g_context.lock      = ca_mutex_new();
-    g_context.condition = ca_cond_new();
-
-    CAPeripheralInitialize();
-
     return CA_STATUS_OK;
 }
 
@@ -911,7 +802,7 @@ CAResult_t CAStartLEAdapter()
     // Only start if we were previously stopped.
     if (CALECheckStarted())
     {
-      return result;
+        return result;
     }
 
     /**
@@ -926,94 +817,191 @@ CAResult_t CAStartLEAdapter()
      *       thread pool before the transport adapters prevents us
      *       from doing that without potentially triggering a
      *       @c pthread_join() call that blocks indefinitely due to
-     *       this event loop not be stopped.  See the comments in the
-     *       @c CAGetLEInterfaceInformation() function below for
+     *       this event loop not being stopped.  See the comments in
+     *       the @c CAGetLEInterfaceInformation() function below for
      *       further details.
      */
     result = ca_thread_pool_add_task(g_context.client_thread_pool,
                                      CALEStartEventLoop,
                                      &g_context);
 
-    if (result != CA_STATUS_OK)
+    /*
+      Wait for the GLib event loop to actually run before returning.
+
+      This addresses corner cases where operations are incorrectly
+      permitted to run in parallel before the event loop is run. For
+      example, the LE transport could have been stopped in a thread
+      parallel to the one starting the event loop start.  In that case
+      the GLib event loop may never exit since the stop operation that
+      causes the event loop to exit occurred before event loop
+      started.  That ultimately causes the CA layer termination to
+      block indefinitely on a pthread_join().  The solution is to only
+      return from the LE transport start operation once we know the
+      event loop is up and running.
+    */
+    struct timespec abs_timeout;
+    if (result == CA_STATUS_OK
+        && clock_gettime(CLOCK_REALTIME, &abs_timeout) == 0)
     {
-        return result;
+        static time_t const relative_timeout = 2;  // seconds
+        abs_timeout.tv_sec += relative_timeout;
+
+        int const wait_result =
+            sem_timedwait(&g_context.le_started, &abs_timeout);
+
+        if (wait_result == 0)
+        {
+            result = CA_STATUS_OK;
+        }
     }
 
+    return result;
+}
+
+CAResult_t CAStopLEAdapter()
+{
     /*
-      Wait until initialization completes before continuing, basically
-      until some Bluetooth adapters were found.
+      This function is called by the connectivity abstraction when
+      CAUnselectNetwork(CA_ADAPTER_GATT_BTLE) is called by the user.
     */
 
-    // Number of times to wait for initialization to complete.
-    static int const retries = 2;
-
-    static uint64_t const timeout =
-        2 * MICROSECS_PER_SEC;  // Microseconds
+    OIC_LOG(DEBUG, TAG, "Stop Linux BLE adapter.");
 
-    if (CALEWaitForNonEmptyList(&g_context.adapters, retries, timeout))
+    // Only stop if we were previously started.
+    if (!CALECheckStarted())
     {
-        result = CA_STATUS_OK;
+        return CA_STATUS_FAILED;
     }
 
-    return result;
+    CALEStopEventLoop(&g_context);
+
+    return CA_STATUS_OK;
 }
 
+
 CAResult_t CAGetLEAdapterState()
 {
-    /**
-     * @todo To be implemented shortly as part of the effort to
-     *       address a critical code review that stated this BLE
-     *       transport should implement the interface defined in
-     *       caleinterface.h.
-     */
-    return CA_NOT_SUPPORTED;
+    CAResult_t result = CA_ADAPTER_NOT_ENABLED;
+
+    ca_mutex_lock(g_context.lock);
+
+    for (GList * l = g_context.adapters; l != NULL; l = l->next)
+    {
+        GDBusProxy * const adapter = G_DBUS_PROXY(l->data);
+        GVariant * const prop =
+            g_dbus_proxy_get_cached_property(adapter, "Powered");
+
+        if (prop == NULL)
+        {
+            // This should never happen!
+            result = CA_STATUS_FAILED;
+            break;
+        }
+
+        gboolean const powered = g_variant_get_boolean(prop);
+        g_variant_unref(prop);
+
+        if (powered)
+        {
+            result = CA_STATUS_OK;
+            break;
+
+            /*
+              No need to continue iterating since we have at least
+              one enabled Bluetooth adapter.
+            */
+        }
+    }
+
+    ca_mutex_unlock(g_context.lock);
+
+    return result;
 }
 
 CAResult_t CAInitializeLENetworkMonitor()
 {
     /**
-     * @todo To be implemented shortly as part of the effort to
-     *       address a critical code review that stated this BLE
-     *       transport should implement the interface defined in
-     *       caleinterface.h.
+     * @note "Network monitor" operations are started in the
+     *       @c CAStartLEAdapter() function rather than this function
+     *       due to glib/D-Bus signal handling threads related
+     *       issues.
+     *
+     * @see @c CAStartLEAdapter() for further details.
+     */
+
+    g_context.lock      = ca_mutex_new();
+    g_context.condition = ca_cond_new();
+
+    static int const PSHARED        = 0;  // shared between threads
+    static unsigned int const VALUE = 0;  // force sem_wait() to block
+
+    if (sem_init(&g_context.le_started, PSHARED, VALUE) != 0)
+    {
+        return CA_STATUS_FAILED;
+    }
+
+    /*
+      The CA LE interface doesn't expose a CAInitializeLEGattServer()
+      function so perform initialization here.
      */
+    CAPeripheralInitialize();
+
     return CA_STATUS_OK;
 }
 
 void CATerminateLENetworkMonitor()
 {
     /**
-     * @todo To be implemented shortly as part of the effort to
-     *       address a critical code review that stated this BLE
-     *       transport should implement the interface defined in
-     *       caleinterface.h.
+     * @note "Network monitor" operations are stopped in @c CALEStop()
+     *       since they are started in @c CAStartLEAdapter() rather
+     *       than @c CAInitializeLENetworkMonitor().
+     *
+     * @see @c CAStartLEAdapter() for further details.
      */
-}
 
-CAResult_t CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCallback callback)
-{
+    /*
+      Since the CA LE interface doesn't expose a
+      CAInitializeLEGattServer() function, finalize the LE server
+      (peripheral) here rather than in CATerminateLEGattServer() to
+      ensure finalization is correctly paired with initialization.
+     */
+    CAPeripheralFinalize();
+
+    (void) sem_destroy(&g_context.le_started);
+
     ca_mutex_lock(g_context.lock);
-    g_context.on_device_state_changed = callback;
+
+    g_context.on_device_state_changed = NULL;
+    g_context.on_server_received_data = NULL;
+    g_context.on_client_received_data = NULL;
+    g_context.client_thread_pool      = NULL;
+    g_context.server_thread_pool      = NULL;
+    g_context.on_client_error         = NULL;
+    g_context.on_server_error         = NULL;
+
+    ca_cond_free(g_context.condition);
+    g_context.condition = NULL;
+
     ca_mutex_unlock(g_context.lock);
 
-    return CA_STATUS_OK;
+    ca_mutex_free(g_context.lock);
+    g_context.lock = NULL;
 }
 
-CAResult_t CAInitLENetworkMonitorMutexVariables()
+CAResult_t CASetLEAdapterStateChangedCb(
+    CALEDeviceStateChangedCallback callback)
 {
-    /*
-      This CA LE interface implementation doesn't use a network
-      monitor as the other platform implementationd do.
-    */
+    ca_mutex_lock(g_context.lock);
+    g_context.on_device_state_changed = callback;
+    ca_mutex_unlock(g_context.lock);
+
     return CA_STATUS_OK;
 }
 
-void CATerminateLENetworkMonitorMutexVariables()
+CAResult_t CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCallback callback)
 {
-    /*
-      This CA LE interface implementation doesn't use a network
-      monitor as the other platform implementationd do.
-    */
+    (void)callback;
+    return CA_NOT_SUPPORTED;
 }
 
 CAResult_t CAGetLEAddress(char **local_address)
@@ -1123,20 +1111,20 @@ CAResult_t CAStartLEGattServer()
 
 CAResult_t CAStopLEGattServer()
 {
-    CAResult_t result    = CAPeripheralStop();
-    CAResult_t const tmp = CALEStop();
-
-    if (result == CA_STATUS_OK && tmp != CA_STATUS_OK)
-    {
-        result = tmp;
-    }
+    return CAPeripheralStop();
+}
 
-    return result;
+CAResult_t CAInitializeLEGattServer()
+{
+    return CA_STATUS_OK;
 }
 
 void CATerminateLEGattServer()
 {
-    CALETerminate();
+    /*
+      See CATerminateLENetworkMonitor() to understand why the LE
+      peripheral is not finalized here.
+     */
 }
 
 void CASetLEReqRespServerCallback(CABLEDataReceivedCallback callback)
@@ -1150,90 +1138,25 @@ CAResult_t CAUpdateCharacteristicsToGattClient(char const * address,
                                                uint8_t const * value,
                                                uint32_t valueLen)
 {
-    (void)address;
-    (void)value;
-    (void)valueLen;
-    /**
-     * @todo To be implemented shortly as part of the effort to
-     *       address a critical code review that stated this BLE
-     *       transport should implement the interface defined in
-     *       caleinterface.h.
-     */
-    return CA_NOT_SUPPORTED;
+    return CAGattServerSendResponseNotification(address,
+                                                value,
+                                                valueLen);
 }
 
 CAResult_t CAUpdateCharacteristicsToAllGattClients(uint8_t const * value,
                                                    uint32_t valueLen)
 {
-    (void)value;
-    (void)valueLen;
-    /**
-     * @todo To be implemented shortly as part of the effort to
-     *       address a critical code review that stated this BLE
-     *       transport should implement the interface defined in
-     *       caleinterface.h.
-     */
-    return CA_NOT_SUPPORTED;
+    return CAGattServerSendResponseNotificationToAll(value, valueLen);
 }
 
 CAResult_t CAStartLEGattClient()
 {
-    return CACentralStart(&g_context);
-}
-
-void CAStopLEGattClient()
-{
-    (void) CACentralStop(&g_context);
-    (void) CALEStop();
-}
+    CAResult_t result = CACentralStart(&g_context);
 
-void CATerminateLEGattClient()
-{
-    CALETerminate();
-}
-
-void CACheckLEData()
-{
-    /*
-      This function is only used in single-threaded builds, but this
-      CA LE adapter implementation is multi-threaded.  Consequently,
-      this function is a no-op.
-     */
-}
-
-CAResult_t CAUpdateCharacteristicsToGattServer(
-    char const * remoteAddress,
-    uint8_t const * data,
-    uint32_t dataLen,
-    CALETransferType_t type,
-    int32_t position)
-{
-    (void)remoteAddress;
-    (void)data;
-    (void)dataLen;
-    (void)type;
-    (void)position;
-    /**
-     * @todo To be implemented shortly as part of the effort to
-     *       address a critical code review that stated this BLE
-     *       transport should implement the interface defined in
-     *       caleinterface.h.
-     */
-    return CA_NOT_SUPPORTED;
-}
-
-CAResult_t CAUpdateCharacteristicsToAllGattServers(uint8_t const * data,
-                                                   uint32_t length)
-{
-    OIC_LOG(DEBUG, TAG, "Send data to all");
-
-    /*
-      Multicast data is only sent when a request is sent from a client
-      across all endpoints.  We need not worry about sending a
-      response from a server here.
-    */
-
-    CAResult_t result = CA_STATUS_FAILED;
+    if (result != CA_STATUS_OK)
+    {
+        return result;
+    }
 
     ca_mutex_lock(g_context.lock);
     bool found_peripherals = (g_context.devices != NULL);
@@ -1241,17 +1164,6 @@ CAResult_t CAUpdateCharacteristicsToAllGattServers(uint8_t const * data,
 
     if (!found_peripherals)
     {
-        /*
-          Start discovery of LE peripherals that advertise the OIC
-          Transport Profile.
-        */
-        result = CACentralStartDiscovery(&g_context);
-
-        if (result != CA_STATUS_OK)
-        {
-            return -1;
-        }
-
         // Wait for LE peripherals to be discovered.
 
         // Number of times to wait for discovery to complete.
@@ -1264,17 +1176,7 @@ CAResult_t CAUpdateCharacteristicsToAllGattServers(uint8_t const * data,
                                      retries,
                                      timeout))
         {
-            return -1;
-        }
-
-        ca_mutex_lock(g_context.lock);
-        found_peripherals = (g_context.devices == NULL);
-        ca_mutex_unlock(g_context.lock);
-
-        if (!found_peripherals)
-        {
-            // No peripherals discovered!
-            return -1;
+            return result;
         }
     }
 
@@ -1288,32 +1190,74 @@ CAResult_t CAUpdateCharacteristicsToAllGattServers(uint8_t const * data,
 
     if (result != CA_STATUS_OK)
     {
-        return -1;
+        return result;
     }
 
     bool const connected = CACentralConnectToAll(&g_context);
 
     if (!connected)
     {
-        return -1;
+        return result;
     }
 
     /**
-     * @todo Start notifications on all response characteristics.
+     * @todo Verify notifications have been enabled on all response
+     *       characteristics.
      */
 
+    return CAGattClientInitialize(&g_context);
+}
+
+void CAStopLEGattClient()
+{
+    CAGattClientDestroy();
+    (void) CACentralStop(&g_context);
+}
+
+CAResult_t CAInitializeLEGattClient()
+{
+    return CA_STATUS_OK;
+}
+
+void CATerminateLEGattClient()
+{
+}
+
+CAResult_t CAUpdateCharacteristicsToGattServer(
+    char const * remoteAddress,
+    uint8_t const * data,
+    uint32_t dataLen,
+    CALETransferType_t type,
+    int32_t position)
+{
+    (void) position;
+
+    if (type != LE_UNICAST)
+    {
+        return CA_STATUS_INVALID_PARAM;
+    }
+
     /*
-      Now send the request through all BLE connections through the
-      corresponding OIC GATT request characterstics.
+      We can assume that we're already connected to the BLE device
+      with the given remote address - we wouldn't have a remote
+      address otherwise - so there is no need to start scanning for
+      BLE devices.
     */
 
-    CAGattRequestInfo const info =
-        {
-            .characteristic_info = NULL,  // g_context.characteristics
-            .context = &g_context
-        };
+    return CAGattClientSendData(remoteAddress,
+                                data,
+                                dataLen,
+                                &g_context);
+}
 
-    return CAGattClientSendDataToAll(&info, data, length);
+CAResult_t CAUpdateCharacteristicsToAllGattServers(uint8_t const * data,
+                                                   uint32_t length)
+{
+    /*
+      Now send the request through all BLE connections through the
+      corresponding OIC GATT request characterstics.
+    */
+    return CAGattClientSendDataToAll(data, length, &g_context);
 
     /**
      * @todo Should we restart discovery after the send?
index 72a8db6..8f70fea 100644 (file)
@@ -40,6 +40,9 @@ CAResult_t CACentralStart(CALEContext * context);
 /**
  * Stop the Linux BLE "central".
  *
+ * Shutdown all Linux BLE "central" operations, including stopping
+ * discovery, and disconnecting from all BLE peripherals.
+ *
  * @param[in] context Context containing BlueZ adapter information.
  *
  * @return @c CA_STATUS_OK on success.
index 3cf4c1b..5972837 100644 (file)
 #include "bluez.h"
 #include "server.h"
 
-#include "oic_malloc.h"
-#include "oic_string.h"
 #include "logger.h"
 #include "cagattservice.h"
 #include "caremotehandler.h"
 
-#include <inttypes.h>
-#include <string.h>
 #include <assert.h>
 
 
@@ -102,58 +98,6 @@ static gboolean CAGattCharacteristicHandleWriteValue(
 //                      GATT Response Handling
 // ---------------------------------------------------------------------
 /**
- * Make the peer address corresponding to the given GATT
- * characteristic.
- *
- * @param[in] c Information about GATT characteristic for which the
- *              peer (client) @c CAEndpoint_t object is being
- *              created.
- *
- * @return @c String containing an encoded address associated with the
- *         peer connected to the peripheral on which the characteristic
- *         implementation resides, or @c NULL on error.
- */
-static char * CAGattCharacteristicMakePeerAddress(
-    CAGattCharacteristic * c)
-{
-    assert(c != NULL);
-
-    /*
-      Length of stringified pointer in hexadecimal format, plus one
-      for null terminator.
-    */
-    static size_t const PSEUDO_ADDR_LEN = sizeof(intptr_t) / 4 + 1;
-
-    assert(MAX_ADDR_STR_SIZE_CA > PSEUDO_ADDR_LEN);
-
-    /*
-      Since there is no direct way to obtain the client endpoint
-      associated with the GATT characterstics on the server side,
-      embed a stringified pointer to the response charactertistic of
-      the form "&ABCDEF01" is the CAEndpoint_t instead.  This works
-      since:
-          1) only one LE central is ever connected to an LE peripheral
-          2) the CA layer doesn't directly interpret the address
-     */
-    char * const addr = OICMalloc(PSEUDO_ADDR_LEN);
-    int const count = snprintf(addr,
-                               PSEUDO_ADDR_LEN,
-                               "&%" PRIxPTR,
-                               (uintptr_t) c);
-
-    if (count >= (int) PSEUDO_ADDR_LEN)
-    {
-        OIC_LOG(ERROR,
-                TAG,
-                "Error creating peer address on server side.");
-
-        return NULL;
-    }
-
-    return addr;
-}
-
-/**
  * Handle @c org.bluez.GattCharacterstic1.StartNotify() method call.
  *
  * This handler is triggered when the
@@ -181,6 +125,8 @@ static gboolean CAGattCharacteristicHandleStartNotify(
     GDBusMethodInvocation * invocation,
     gpointer user_data)
 {
+    (void) user_data;
+
     /**
      * Only allow the client to start notifications once.
      *
@@ -197,82 +143,12 @@ static gboolean CAGattCharacteristicHandleStartNotify(
         return TRUE;
     }
 
-    // Retrieve the response characteristic information.
-    CAGattCharacteristic * const characteristic = user_data;
-
-    char * const peer =
-        CAGattCharacteristicMakePeerAddress(characteristic);
-
-    if (peer == NULL)
-    {
-        g_dbus_method_invocation_return_dbus_error(
-            invocation,
-            "org.bluez.Error.Failed",
-            "Error creating peer endpoint information");
-
-        return TRUE;
-    }
-
-    /*
-      Create an entry in the endpoint-to-characteristic map so that
-      responses may be sent to the GATT client through the OIC GATT
-      response characteristic through this BLE adapter's
-      CAAdapterSendUnicastData() implementation.
-     */
-    CALEContext * const context = characteristic->context;
-
-    ca_mutex_lock(context->lock);
-
-#if GLIB_CHECK_VERSION(2,40,0)
-    /*
-      GLib hash table functions started returning a boolean result in
-       version 2.40.x.
-    */
-    bool const inserted =
-#endif
-        g_hash_table_insert(context->characteristic_map,
-                            peer,
-                            characteristic);
-
-    ca_mutex_unlock(context->lock);
-
-#if GLIB_CHECK_VERSION(2,40,0)
-    if (!inserted)
-    {
-        g_dbus_method_invocation_return_dbus_error(
-            invocation,
-            "org.bluez.Error.Failed",
-            "Unable to set response endpoint.");
-
-        OICFree(peer);
-
-        return TRUE;
-    }
-#endif
-
     /**
      * @todo Do we need to explicitly emit the @c GObject @c notify or
      *       @c org.freedesktop.Dbus.Properties.PropertiesChanged
      *       signal here?
      */
     gatt_characteristic1_set_notifying(object, TRUE);
-
-    /*
-      Set the client endpoint field in the request characteristic so
-      that it may pass the appropriate endpoint object up the stack
-      through the CA request/response callback once a request has been
-      completely received and reassembled.
-    */
-    CAGattRecvInfo * const recv_info =
-        &characteristic->service->request_characteristic.recv_info;
-
-    recv_info->peer = peer;
-
-    ca_mutex_lock(context->lock);
-    recv_info->on_packet_received = context->on_server_received_data;
-    recv_info->context            = context;
-    ca_mutex_unlock(context->lock);
-
     gatt_characteristic1_complete_start_notify(object, invocation);
 
     return TRUE;
@@ -303,7 +179,7 @@ static gboolean CAGattCharacteristicHandleStopNotify(
     GDBusMethodInvocation * invocation,
     gpointer user_data)
 {
-    assert(user_data != NULL);
+    (void) user_data;
 
     /**
      * @todo Does BlueZ already prevent redundant calls to
@@ -319,44 +195,13 @@ static gboolean CAGattCharacteristicHandleStopNotify(
         return TRUE;
     }
 
-    CAGattCharacteristic * const characteristic = user_data;
-
-    // Clear the client endpoint from the request characteristic.
-    CAGattRecvInfo * const recv_info =
-        &characteristic->service->request_characteristic.recv_info;
-
-    /*
-      Remove the appropriate entry from the endpoint-to-characteristic
-      map so that attempts to send a response through it will fail.
-    */
-    CALEContext * const context = characteristic->context;
-    ca_mutex_lock(context->lock);
-
-    bool const removed =
-        g_hash_table_remove(context->characteristic_map, recv_info->peer);
-
-    ca_mutex_unlock(context->lock);
-
-    CAGattRecvInfoDestroy(recv_info);
-
     /**
      * @todo Do we need to explicitly emit the @c GObject @c notify or
      *       @c org.freedesktop.Dbus.Properties.PropertiesChanged
      *       signal here?
      */
     gatt_characteristic1_set_notifying(object, FALSE);
-
-    if (removed)
-    {
-        gatt_characteristic1_complete_stop_notify(object, invocation);
-    }
-    else
-    {
-        g_dbus_method_invocation_return_dbus_error(
-            invocation,
-            "org.bluez.Error.Failed",
-            "Error removing peer address information");
-    }
+    gatt_characteristic1_complete_stop_notify(object, invocation);
 
     return TRUE;
 }
@@ -419,7 +264,7 @@ static bool CAGattCharacteristicInitialize(
     gatt_characteristic1_set_service(c->characteristic, s->object_path);
     gatt_characteristic1_set_notifying(c->characteristic, FALSE);
 
-    char const * flags[] = { flag, NULL };
+    char const * const flags[] = { flag, NULL };
     gatt_characteristic1_set_flags(c->characteristic, flags);
 
     CAGattRecvInfoInitialize(&c->recv_info);
@@ -475,7 +320,7 @@ bool CAGattRequestCharacteristicInitialize(struct CAGattService * s,
       The descriptor object path is not fixed at compile-time.
       Retrieve the object path that was set at run-time.
     */
-    char const * descriptor_paths[] = {
+    char const * const descriptor_paths[] = {
         c->descriptor.object_path,
         NULL
     };
@@ -483,6 +328,21 @@ bool CAGattRequestCharacteristicInitialize(struct CAGattService * s,
     gatt_characteristic1_set_descriptors(c->characteristic,
                                          descriptor_paths);
 
+    char * const peer = CAGattServiceMakePeerAddress(s);
+
+    if (peer == NULL)
+    {
+        CAGattCharacteristicDestroy(c);
+        return false;
+    }
+
+    ca_mutex_lock(context->lock);
+    c->recv_info.on_packet_received = context->on_server_received_data;
+    ca_mutex_unlock(context->lock);
+
+    c->recv_info.peer    = peer;
+    c->recv_info.context = context;
+
     // The request characteristic only handles writes.
     g_signal_connect(c->characteristic,
                      "handle-write-value",
@@ -530,7 +390,7 @@ bool CAGattResponseCharacteristicInitialize(struct CAGattService * s,
       enable notifications by writing to the client characteristic
       configuration descriptor.
     */
-    char const * descriptor_paths[] = {
+    char const * const descriptor_paths[] = {
         c->descriptor.object_path,
         NULL
     };
index 373ee50..2888c7b 100644 (file)
 #include "bluez.h"
 #include "utils.h"
 
-#include "cafragmentation.h"
+#include "cagattservice.h"
 #include "logger.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
 
 #include <gio/gio.h>
 
-#include <string.h>
+#include <strings.h>
 #include <assert.h>
 
 
 // Logging tag.
 static char const TAG[] = "BLE_CLIENT";
 
+typedef struct _CAGattClientContext
+{
+    /**
+     * Bluetooth MAC address to GATT characteristic map.
+     *
+     * Hash table that maps Bluetooth MAC address to a OIC Transport
+     * Profile GATT characteristic.  The key is a string containing
+     * the LE peripheral Bluetooth adapter MAC address.   The value is
+     * an interface proxy (@c GDBusProxy) to an
+     * @c org.bluez.GattCharacteristic1 object, i.e. OIC Transport
+     * Profile GATT request characteristic.
+     */
+    GHashTable * characteristic_map;
+
+    /**
+     * Response characteristic object path to Bluetooth MAC address map.
+     *
+     * Hash table that maps OIC Transport Profile GATT response
+     * characteristic D-Bus object path to Bluetooth MAC address.  The
+     * key is the D-Bus object path.  The value is the LE peripheral
+     * Bluetooth adapter MAC address.
+     *
+     * @note This map exists to avoid having to create a hierarchy of
+     *       GLib D-Bus proxies to the client side BlueZ GATT response
+     *       Characteristic, its corresponding GATT Service, and the
+     *       Device object within that Service, along with the
+     *       resulting D-Bus calls, simply so that we obtain the MAC
+     *       address of the remote (peripheral) LE device.  We
+     *       unfortunately need the MAC address since the
+     *       shared/common caleadapter code requires it.
+     */
+    GHashTable * address_map;
+
+    /// Mutex used to synchronize access to context fields.
+    ca_mutex lock;
+
+} CAGattClientContext;
+
+static CAGattClientContext g_context = {
+    .lock = NULL
+};
+
 // ---------------------------------------------------------------------
-//                        GATT Client Set-up
+//                      GATT Response Receive
 // ---------------------------------------------------------------------
-static bool CAGattClientServiceFilter(GDBusProxy * service)
+static void CAGattClientOnCharacteristicPropertiesChanged(
+    GDBusProxy * characteristic,
+    GVariant * changed_properties,
+    GStrv invalidated_properties,
+    gpointer user_data)
 {
     /*
-      On the client side, we only care about the GATT services on
-      remote devices.  Ignore the locally created ones by checking for
-      the existence of the org.bluez.GattService1.Device property in
-      the service proxy.  GATT services on remote devices will have
-      that property.
+      This handler is trigged in a GATT client when receiving data
+      sent by a GATT server through a notification, e.g. such as when
+      a GATT server sent a response.
     */
-    GVariant * const remote_device =
-        g_dbus_proxy_get_cached_property(service, "Device");
 
-    if (remote_device == NULL)
+    (void) invalidated_properties;
+
+    if (g_variant_n_children(changed_properties) < 1)
     {
-        return false;
+        /*
+          No changed properties, only invalidated ones which we don't
+          care about.
+        */
+        return;
     }
 
+    CALEContext * const context = user_data;
+    char const * const object_path =
+        g_dbus_proxy_get_object_path(characteristic);
+
+    ca_mutex_lock(g_context.lock);
+
+    char * const address =
+        g_hash_table_lookup(g_context.address_map, object_path);
+
     /*
-      org.bluez.GattService1.Device property exists, meaning the
-      GATT service was advertised from a remote object.
+      Address lookup could fail if a property changed on a GATT
+      characteristic that isn't an OIC Transport Profile GATT response
+      characteristic.  This isn't necessarily a problem since it's
+      possible other unrelated GATT charactertistics with changed
+      properties are exposed by BlueZ on the D-Bus system bus.
     */
-    g_object_unref(remote_device);
-    return true;
+    if (address != NULL)
+    {
+        CAGattRecvInfo info =
+            {
+                .peer               = address,
+                .on_packet_received = context->on_client_received_data,
+                .context            = context
+            };
+
+        GVariant * const value =
+            g_variant_lookup_value(changed_properties, "Value", NULL);
+
+        if (value != NULL)
+        {
+            // GLib maps an octet to a guchar, which is of size 1.
+            gsize length = 0;
+            gconstpointer const data =
+                g_variant_get_fixed_array(value, &length, 1);
+
+            (void) CAGattRecv(&info, data, length);
+
+            g_variant_unref(value);
+        }
+    }
+
+    ca_mutex_unlock(g_context.lock);
+}
+
+// ---------------------------------------------------------------------
+//                        GATT Client Set-up
+// ---------------------------------------------------------------------
+static bool CAGattClientMapInsert(GHashTable * map,
+                                  gpointer key,
+                                  gpointer value)
+{
+    bool const insert = !g_hash_table_contains(map, key);
+
+    if (insert)
+    {
+        g_hash_table_insert(map, key, value);
+    }
+
+    return insert;
 }
 
-bool CAGattClientsInitialize(CALEContext * context)
+static bool CAGattClientSetupCharacteristics(
+    GDBusProxy * service,
+    char const * address,
+    GHashTable * characteristic_map,
+    GHashTable * address_map,
+    CALEContext * context)
 {
+    bool success = true;
+
+    GVariant * const characteristics_prop =
+        g_dbus_proxy_get_cached_property(service, "Characteristics");
+
+    gsize length = 0;
+    gchar const ** const characteristic_paths =
+        g_variant_get_objv(characteristics_prop, &length);
+
+#ifdef TB_LOG
+    if (length == 0)
+    {
+        OIC_LOG(ERROR,
+                TAG,
+                "Server side OIC GATT Service has no characteristics");
+    }
+#endif
+
     /*
-      Create a proxies to the org.bluez.GattService1 D-Bus objects that
-      will later be used to send requests and receive responses on the
-      client side.
+      Create a proxies to the org.bluez.GattCharacteristic1 D-Bus
+      objects that will later be used to send requests and receive
+      responses on the client side.
     */
-    GList * services = NULL;
-    bool success =
-        CAGetBlueZManagedObjectProxies(&services,
-                                       BLUEZ_GATT_SERVICE_INTERFACE,
-                                       context,
-                                       CAGattClientServiceFilter);
+    gchar const * const * const end = characteristic_paths + length;
+    for (gchar const * const * path = characteristic_paths;
+         path != end && success;
+         ++path)
+    {
+        // Find the request characteristic.
+        GError * error = NULL;
+
+        GDBusProxy * const characteristic =
+            g_dbus_proxy_new_sync(context->connection,
+                                  G_DBUS_PROXY_FLAGS_NONE,
+                                  NULL, // GDBusInterfaceInfo
+                                  BLUEZ_NAME,
+                                  *path,
+                                  BLUEZ_GATT_CHARACTERISTIC_INTERFACE,
+                                  NULL, // GCancellable
+                                  &error);
+
+        if (characteristic == NULL)
+        {
+            OIC_LOG_V(ERROR,
+                      TAG,
+                      "Unable to obtain proxy to GATT characteristic: %s",
+                      error->message);
 
-    /**
-     * @todo Is this really an error?
-     */
-    if (!success)
+            g_error_free(error);
+
+            success = false;
+
+            break;
+        }
+
+        GVariant * const uuid_prop =
+            g_dbus_proxy_get_cached_property(characteristic, "UUID");
+
+        char const * const uuid =
+            g_variant_get_string(uuid_prop, NULL);
+
+        if (strcasecmp(uuid, CA_GATT_REQUEST_CHRC_UUID) == 0)
+        {
+            char     * const addr = OICStrdup(address);
+            gpointer * const chrc = g_object_ref(characteristic);
+
+            // Map LE (MAC) address to request characteristic.
+            if (!CAGattClientMapInsert(characteristic_map, addr, chrc))
+            {
+                OIC_LOG_V(WARNING,
+                          TAG,
+                          "Possible duplicate OIC GATT "
+                          "request characteristic proxy detected.");
+
+                g_object_unref(chrc);
+                OICFree(addr);
+            }
+        }
+        else if (strcasecmp(uuid, CA_GATT_RESPONSE_CHRC_UUID) == 0)
+        {
+            char * const p    = OICStrdup(*path);
+            char * const addr = OICStrdup(address);
+
+            // Map GATT service D-Bus object path to client address.
+            if (!CAGattClientMapInsert(address_map, p, addr))
+            {
+                OIC_LOG_V(WARNING,
+                          TAG,
+                          "Unable to register duplicate "
+                          "peripheral MAC address");
+
+                success = false;
+
+                OICFree(addr);
+                OICFree(p);
+            }
+            else
+            {
+                /*
+                  Detect changes in GATT characteristic properties.
+                  This is only relevant to OIC response
+                  characteristics since only their "Value" property
+                  will ever change.
+                */
+                g_signal_connect(
+                    characteristic,
+                    "g-properties-changed",
+                    G_CALLBACK(CAGattClientOnCharacteristicPropertiesChanged),
+                    context);
+
+                // Enable notifications.
+                GVariant * const ret =
+                    g_dbus_proxy_call_sync(
+                        characteristic,
+                        "StartNotify",
+                        NULL,  // parameters
+                        G_DBUS_CALL_FLAGS_NONE,
+                        -1,    // timeout (default == -1),
+                        NULL,  // cancellable
+                        &error);
+
+                if (ret == NULL)
+                {
+                    OIC_LOG_V(ERROR,
+                              TAG,
+                              "Failed to enable GATT notifications: %s",
+                              error->message);
+
+                    g_error_free(error);
+                    g_hash_table_remove(address_map, address);
+                    success = false;
+                }
+                else
+                {
+                    g_variant_unref(ret);
+                }
+            }
+        }
+#ifdef TB_LOG
+        else
+        {
+            OIC_LOG_V(WARNING,
+                      TAG,
+                      "Unrecognized characteristic UUID "
+                      "in OIC GATT service: %s",
+                      uuid);
+        }
+#endif
+
+        g_variant_unref(uuid_prop);
+        g_object_unref(characteristic);
+    }
+
+    g_free(characteristic_paths);
+    g_variant_unref(characteristics_prop);
+
+    return success;
+}
+
+static bool CAGattClientSetupService(
+    GDBusProxy * device,
+    GHashTable * characteristic_map,
+    GHashTable * address_map,
+    GVariant   * services_prop,
+    CALEContext * context)
+{
+    bool success = true;
+
+    GVariant * const address_prop =
+        g_dbus_proxy_get_cached_property(device, "Address");
+
+    char const * const address =
+        g_variant_get_string(address_prop, NULL);
+
+    /*
+      Create a proxies to the org.bluez.GattService1 D-Bus objects
+      that implement the OIC Transport Profile on the client side.
+
+      The services_prop argument will be non-NULL if changes to the
+      org.bluez.Device1.GattServices property were detected
+      asynchronously through the PropertiesChanged signal.
+    */
+    if (services_prop != NULL)
+    {
+        /*
+          The caller owns the variant so hold on to a reference since
+          we assume ownership in this function.
+        */
+        g_variant_ref(services_prop);
+    }
+    else
+    {
+        // Check if GATT services have already been discovered.
+        services_prop =
+            g_dbus_proxy_get_cached_property(device, "GattServices");
+    }
+
+    gsize length = 0;
+    char const ** const service_paths =
+        services_prop != NULL
+        ? g_variant_get_objv(services_prop, &length)
+        : NULL;
+
+#ifdef TB_LOG
+    if (length == 0)
+    {
+        // GATT services may not yet have been discovered.
+        OIC_LOG_V(INFO,
+                  TAG,
+                  "GATT services not yet discovered "
+                  "on LE peripheral: %s\n",
+                  address);
+    }
+#endif
+
+    gchar const * const * const end = service_paths + length;
+    for (gchar const * const * path = service_paths;
+         path != end && success;
+         ++path)
+    {
+        // Find the OIC Transport Profile GATT service.
+        GError * error = NULL;
+
+        GDBusProxy * const service =
+            g_dbus_proxy_new_sync(context->connection,
+                                  G_DBUS_PROXY_FLAGS_NONE,
+                                  NULL, // GDBusInterfaceInfo
+                                  BLUEZ_NAME,
+                                  *path,
+                                  BLUEZ_GATT_SERVICE_INTERFACE,
+                                  NULL, // GCancellable
+                                  &error);
+
+        if (service == NULL)
+        {
+            OIC_LOG_V(ERROR,
+                      TAG,
+                      "Unable to obtain proxy to GATT service: %s",
+                      error->message);
+
+            g_error_free(error);
+
+            success = false;
+
+            break;
+        }
+
+        GVariant * const uuid_prop =
+            g_dbus_proxy_get_cached_property(service, "UUID");
+
+        char const * const uuid =
+            g_variant_get_string(uuid_prop, NULL);
+
+        if (strcasecmp(uuid, CA_GATT_SERVICE_UUID) == 0)
+        {
+            success = CAGattClientSetupCharacteristics(service,
+                                                       address,
+                                                       characteristic_map,
+                                                       address_map,
+                                                       context);
+
+#ifdef TB_LOG
+            if (!success)
+            {
+                OIC_LOG_V(ERROR,
+                          TAG,
+                          "Characteristic set up for "
+                          "GATT service at %s failed.",
+                          address);
+            }
+#endif  // TB_LOG
+        }
+
+        g_variant_unref(uuid_prop);
+        g_object_unref(service);
+    }
+
+    if (services_prop != NULL)
+    {
+        g_variant_unref(services_prop);
+    }
+
+    g_variant_unref(address_prop);
+
+    return success;
+}
+
+static void CAGattClientOnDevicePropertiesChanged(
+    GDBusProxy * device,
+    GVariant * changed_properties,
+    GStrv invalidated_properties,
+    gpointer user_data)
+{
+    /*
+      This handler is trigged in a GATT client when org.bluez.Device1
+      properties have changed.
+    */
+
+    (void) invalidated_properties;
+
+    /*
+      Retrieve the org.bluez.Device1.GattServices property from the
+      changed_properties dictionary parameter (index 1).
+    */
+    GVariant * const services_prop =
+        g_variant_lookup_value(changed_properties, "GattServices", NULL);
+
+    if (services_prop != NULL)
     {
-        return success;
+        CALEContext * const context = user_data;
+
+        ca_mutex_lock(g_context.lock);
+
+        CAGattClientSetupService(device,
+                                 g_context.characteristic_map,
+                                 g_context.address_map,
+                                 services_prop,
+                                 context);
+
+        ca_mutex_unlock(g_context.lock);
+
+        g_variant_unref(services_prop);
     }
+}
+
+CAResult_t CAGattClientInitialize(CALEContext * context)
+{
+    g_context.lock = ca_mutex_new();
 
     /*
       Map Bluetooth MAC address to OIC Transport Profile
-      characteristics.
+      request characteristics.
     */
     GHashTable * const characteristic_map =
         g_hash_table_new_full(g_str_hash,
@@ -96,57 +511,96 @@ bool CAGattClientsInitialize(CALEContext * context)
                               OICFree,
                               g_object_unref);
 
-    char const * const address = NULL;  // OICMalloc(...);
-    GDBusProxy * const client = NULL;
-
-#if GLIB_CHECK_VERSION(2,40,0)
     /*
-      GLib hash table functions started returning a boolean result in
-       version 2.40.x.
+      Map OIC Transport Profile response characteristic D-Bus object
+      path to Bluetooth MAC address.
     */
-    success =
-#endif
-        g_hash_table_insert(characteristic_map,
-                            OICStrdup(address),
-                            client);
+    GHashTable * const address_map =
+        g_hash_table_new_full(g_str_hash,
+                              g_str_equal,
+                              OICFree,
+                              OICFree);
 
-    // An empty services list is NULL.
-    if (success && services != NULL)
+    ca_mutex_lock(context->lock);
+
+    for (GList * l = context->devices; l != NULL; l = l->next)
     {
-        ca_mutex_lock(context->lock);
-        context->characteristic_map = characteristic_map;
-        ca_mutex_unlock(context->lock);
+        GDBusProxy * const device = G_DBUS_PROXY(l->data);
+
+        /*
+          Detect changes in BlueZ Device properties.  This is
+          predominantly used to detect GATT services that were
+          discovered asynchronously.
+        */
+        g_signal_connect(
+            device,
+            "g-properties-changed",
+            G_CALLBACK(CAGattClientOnDevicePropertiesChanged),
+            context);
+
+        CAGattClientSetupService(device,
+                                 characteristic_map,
+                                 address_map,
+                                 NULL,
+                                 context);
     }
 
-    return success;
+    ca_mutex_unlock(context->lock);
+
+    ca_mutex_lock(g_context.lock);
+
+    g_context.characteristic_map = characteristic_map;
+    g_context.address_map = address_map;
+
+    ca_mutex_unlock(g_context.lock);
+
+    return CA_STATUS_OK;
 }
 
-bool CAGattClientsDestroy(CALEContext * context)
+void CAGattClientDestroy()
 {
-    (void)context;
-    /* g_hash_table_destroy(...); */   // FIXME
-    return false;
+    if (g_context.lock == NULL)
+    {
+        return;  // Initialization did not complete.
+    }
+
+    ca_mutex_lock(g_context.lock);
+
+    if (g_context.characteristic_map != NULL)
+    {
+        g_hash_table_unref(g_context.characteristic_map);
+        g_context.characteristic_map = NULL;
+    }
+
+    if (g_context.address_map != NULL)
+    {
+        g_hash_table_unref(g_context.address_map);
+        g_context.address_map = NULL;
+    }
+
+    ca_mutex_unlock(g_context.lock);
+
+    ca_mutex_free(g_context.lock);
+    g_context.lock = NULL;
+
+    /*
+      We don't explicitly stop notifications on the response
+      characteristic since they should be stopped upon server side
+      disconnection.
+     */
 }
 
 // ---------------------------------------------------------------------
-//                        GATT Request Send
+//                      GATT Request Data Send
 // ---------------------------------------------------------------------
-/**
- * Send data to the GATT server through the given request
- * @a characteristic proxy.
- *
- * @param[in] characteristic The D-Bus proxy of the request
- *                           characteristic through which the
- *                           @c WriteValue() method will be invoked.
- * @param[in] data           The byte array to be sent.
- * @param[in] length         The number of elements in the byte
- *                           array.
- */
-static bool CAGattClientSendRequestData(GDBusProxy * characteristic,
-                                        CALEContext * context,
-                                        uint8_t const * data,
-                                        size_t length)
+
+static CAResult_t CAGattClientSendDataImpl(GDBusProxy * characteristic,
+                                           uint8_t const * data,
+                                           size_t length,
+                                           CALEContext * context)
 {
+    assert(characteristic != NULL);
+    assert(data != NULL);
     assert(context != NULL);
 
     GVariant * const value =
@@ -155,12 +609,18 @@ static bool CAGattClientSendRequestData(GDBusProxy * characteristic,
                                   length,
                                   1);  // sizeof(data[0]) == 1
 
+    /*
+      WriteValue() expects a byte array but it must be packed into a
+      tuple for the actual call through the proxy.
+    */
+    GVariant * const value_parameter = g_variant_new("(@ay)", value);
+
     GError * error = NULL;
 
     GVariant * const ret =
         g_dbus_proxy_call_sync(characteristic,
                                "WriteValue",
-                               value,  // parameters
+                               value_parameter,  // parameters
                                G_DBUS_CALL_FLAGS_NONE,
                                -1,    // timeout (default == -1),
                                NULL,  // cancellable
@@ -192,89 +652,92 @@ static bool CAGattClientSendRequestData(GDBusProxy * characteristic,
 
         ca_mutex_unlock(context->lock);
 
-        return false;
+        return CA_STATUS_FAILED;
     }
 
     g_variant_unref(ret);
 
-    return true;
+    return CA_STATUS_OK;
 }
 
-CAResult_t CAGattClientSendData(void const * method_info,
+CAResult_t CAGattClientSendData(char const * address,
                                 uint8_t const * data,
-                                size_t length)
+                                size_t length,
+                                CALEContext * context)
 {
-    assert(method_info != NULL);
-
-    CAGattRequestInfo const * const info = method_info;
-
-    GDBusProxy * const characteristic =
-        G_DBUS_PROXY(info->characteristic_info);
-
-    return CAGattClientSendRequestData(characteristic,
-                                       info->context,
-                                       data,
-                                       length);
-}
+    assert(context != NULL);
 
-CAResult_t CAGattClientSendDataToAll(void const * method_info,
-                                     uint8_t const * data,
-                                     size_t length)
-{
-    assert(method_info != NULL);
+    CAResult_t result = CA_STATUS_FAILED;
 
-    CAResult_t result = CA_STATUS_OK;
+    ca_mutex_lock(g_context.lock);
 
-    CAGattRequestInfo const * const info = method_info;
+    GDBusProxy * const characteristic =
+        G_DBUS_PROXY(
+            g_hash_table_lookup(g_context.characteristic_map,
+                                address));
 
-    for (GList const * l = info->characteristic_info;
-         l != NULL && result == CA_STATUS_OK;
-         l = l->next)
+    if (characteristic == NULL)
     {
-        GDBusProxy * const characteristic = G_DBUS_PROXY(l->data);
+        /*
+          GATT request characteristic corresponding to given address
+          was not found.
+        */
 
-        result = CAGattClientSendRequestData(characteristic,
-                                             info->context,
-                                             data,
-                                             length);
+        return result;
     }
 
+    result = CAGattClientSendDataImpl(characteristic,
+                                      data,
+                                      length,
+                                      context);
+
+    ca_mutex_unlock(g_context.lock);
+
     return result;
 }
 
-// ---------------------------------------------------------------------
-//                      GATT Response Receive
-// ---------------------------------------------------------------------
-void CAGattReceiveResponse(GDBusConnection * connection,
-                           char const * sender_name,
-                           char const * object_path,
-                           char const * interface_name,
-                           char const * signal_name,
-                           GVariant   * parameters,
-                           gpointer     user_data)
+CAResult_t CAGattClientSendDataToAll(uint8_t const * data,
+                                     size_t length,
+                                     CALEContext * context)
 {
-    (void)connection;
-    (void)sender_name;
-    (void)object_path;
-    (void)interface_name;
-    (void)signal_name;
-    /*
-      This handler is only trigged in a GATT client when receiving
-      data sent by a GATT server through a notification, e.g. such as
-      when a GATT server sent a response.
-    */
-    gsize fragment_len = 0;
-    gconstpointer const fragment =
-        g_variant_get_fixed_array(parameters,
-                                  &fragment_len,
-                                  1);  // sizeof(guchar) == 1
+    assert(context != NULL);
 
-    CAGattRecvInfo * const info = user_data;
+    CAResult_t result = CA_STATUS_FAILED;
 
-    if (CAGattRecv(info, fragment, fragment_len))
+    ca_mutex_lock(g_context.lock);
+
+    if (g_context.characteristic_map == NULL)
     {
+        // Remote OIC GATT service was not found prior to getting here.
+        ca_mutex_unlock(g_context.lock);
+        return result;
     }
-    else
+
+    GHashTableIter iter;
+    g_hash_table_iter_init(&iter, g_context.characteristic_map);
+
+    gpointer characteristic;  // Value
+
+    /**
+     * @todo Will content of this hash table be potentially changed by
+     *       another thread during iteration?
+     */
+    while(g_hash_table_iter_next(&iter,
+                                 NULL,  // Key - unused
+                                 &characteristic))
     {
+        result = CAGattClientSendDataImpl(G_DBUS_PROXY(characteristic),
+                                          data,
+                                          length,
+                                          context);
+
+        if (result != CA_STATUS_OK)
+        {
+            break;
+        }
     }
+
+    ca_mutex_unlock(g_context.lock);
+
+    return result;
 }
index 4000405..ad0f052 100644 (file)
 
 
 /**
- * Information needed to when sending a request through a GATT
- * client.
+ * Initialize the GATT client.
+ *
+ * @param[in] context
+ *
+ * @return @c CA_STATUS_OK on success, @c CA_STATUS_FAILED otherwise.
  */
-typedef struct _CAGattRequestInfo
-{
-    /**
-     * Proxy or list of proxies to @c org.bluez.GattCharacteristic1
-     * object(s) through which request data will be sent to the GATT
-     * server.
-     *
-     * In the case of a unicast-style send, @c info will be a
-     * @c GDBusProxy* to an @c org.bluez.GattCharacteristic1 object.
-     * For a multicast-style send, @c info will be a * @c GList* of
-     * @c GDBusProxy* to @c GattCharacterstic1 objects on all GATT
-     * servers to which a connection exists.
-     */
-    void * const characteristic_info;
-
-    /**
-     * Context containing additional information that may be needed
-     * when sending a request.
-     */
-    CALEContext * const context;
+CAResult_t CAGattClientInitialize(CALEContext * context);
 
-} CAGattRequestInfo;
+/**
+ * Destroy the GATT client.
+ */
+void CAGattClientDestroy();
 
 /**
  * Send request data through a single user-specified BLE connection.
  *
- * @param[in] method_info Information necessary to send request.
- * @param[in] data        Octet array of request data to be sent.
- * @param[in] length      Length of the @a data octet array.
+ * @param[in] address  MAC address of the BLE peripheral running the
+ *                     OIC Transport Profile GATT server to which the
+ *                     data will be sent.
+ * @param[in] data     Octet array of request data to be sent.
+ * @param[in] length   Length of the @a data octet array.
+ * @param[in] context  Object containing mutexes and error reporting
+ *                     callback used on failure to send.
  *
- * @see @c CAGattSendMethod() for further details.
+ * @return @c CA_STATUS_OK on success, @c CA_STATUS_FAILED otherwise.
  */
-bool CAGattSendRequest(void const * method_info,
-                       uint8_t const * data,
-                       size_t length);
+CAResult_t CAGattClientSendData(char const * address,
+                                uint8_t const * data,
+                                size_t length,
+                                CALEContext * context);
 
-// ---------------------------------------------------------------
-//                   Multicast-style Request Send
-// ---------------------------------------------------------------
 /**
  * Send request data through all BLE connections.
  *
  * Send the @a data to the GATT server found in all discovered LE
  * peripherals.
  *
- * @param[in] method_info Information necessary to send request.
- * @param[in] data        Octet array of request data to be sent.
- * @param[in] length      Length of the @a data octet array.
-
- * @note Since a multicast-like operation is being performed, an
- *       assumption is made that a GATT client is sending data to a
- *       server.  It makes no sense to multicast a response from a
- *       single GATT server to multiple GATT clients in IoTivity's
- *       case.
+ * @param[in] data    Octet array of request data to be sent.
+ * @param[in] length  Length of the @a data octet array.
+ * @param[in] context Object GATT request characteristic map.
  *
  * @return @c CA_STATUS_OK on success, @c CA_STATUS_FAILED otherwise.
  */
-CAResult_t CAGattClientSendDataToAll(void const * method_info,
-                                     uint8_t const * data,
-                                     size_t length);
+CAResult_t CAGattClientSendDataToAll(uint8_t const * data,
+                                     size_t length,
+                                     CALEContext * context);
 
 
 #endif  /* CA_BLE_LINUX_CLIENT_H */
index ce1ec01..e0db333 100644 (file)
@@ -25,6 +25,7 @@
 #include "caleinterface.h"
 
 #include <gio/gio.h>
+#include <semaphore.h>
 
 
 /**
@@ -76,28 +77,6 @@ typedef struct _CALEContext
     GList * devices;
 
     /**
-     * Bluetooth MAC address to GATT characteristic map.
-     *
-     * Hash table that maps Bluetooth MAC address to a OIC Transport
-     * Profile GATT characteristic.  The key is a string containing
-     * the peer Bluetooth adapter MAC address.   The value is an
-     * interface proxy (@c GDBusProxy) to an
-     * @c org.bluez.GattCharacteristic1 object.
-     *
-     * On the client side, this maps a Bluetooth peripheral MAC
-     * address to the corresponding request characteristic proxy.  On
-     * the server side, this maps Bluetooth central MAC address to the
-     * corresponding response characteristic proxy.
-     *
-     * @note On the server side a map is overkill since only one
-     *       client is ever connected to the server.  No?
-     *
-     * @todo We may want to have a seperate server-side map to reduce
-     *       contention on this map.
-     */
-    GHashTable * characteristic_map;
-
-    /**
      * GATT characteristics to Bluetooth MAC address map.
      *
      * Hash table that maps OIC Transport Profile GATT characteristic
@@ -125,8 +104,6 @@ typedef struct _CALEContext
      *
      * @li @c org.freedesktop.DBus.ObjectManager.InterfacesAdded
      * @li @c org.freedesktop.DBus.ObjectManager.InterfacesRemoved
-     * @li @c org.freedesktop.DBus.Properties.PropertiesChanged
-     * @li @c org.bluez.Adapter1.PropertyChanged
      *
      * These subscription identifiers are only used when unsubscribing
      * from the signals when stopping the LE transport.
@@ -137,8 +114,6 @@ typedef struct _CALEContext
     //@{
     guint interfaces_added_sub_id;
     guint interfaces_removed_sub_id;
-    guint properties_changed_sub_id;
-    guint property_changed_sub_id;
     //@}
 
     /// Glib event loop that drives D-Bus signal handling.
@@ -190,6 +165,21 @@ typedef struct _CALEContext
      */
     ca_cond condition;
 
+    /**
+     * Semaphore that indicates completed start of the LE transport.
+     *
+     * In some corner cases the transport stop will complete before
+     * transport start completes.  In such cases, the event loop
+     * run during LE transport start will never exit since the
+     * transport stop will have completed before the event loop that
+     * drives was
+     * run.  This semaphore is used to force the call to
+     * ::CAStartLEAdapter() to wait for the thread that runs the GLib
+     * event loop that drives D-Bus signal handling to completely
+     * start.
+     */
+    sem_t le_started;
+
 } CALEContext;
 
 
index 7066c33..eeccd50 100644 (file)
@@ -119,7 +119,7 @@ static bool CAGattDescriptorInitialize(CAGattCharacteristic * c,
                                 g_variant_new_bytestring(value));
 
     // Readable, no encryption, no authorization.
-    static char const * flags[] = { "read", NULL };
+    static char const * const flags[] = { "read", NULL };
     gatt_descriptor1_set_flags(d->descriptor, flags);
 
     /*
index 54a5479..9966198 100644 (file)
@@ -20,8 +20,6 @@
 #include "utils.h"
 #include "bluez.h"
 #include "service.h"
-#include "characteristic.h"
-#include "descriptor.h"
 
 #include "oic_malloc.h"
 #include "logger.h"
@@ -43,7 +41,9 @@ static bool CAPeripheralCheckStarted()
 {
     ca_mutex_lock(g_context.lock);
 
-    bool const started = (g_context.base != NULL);
+    bool const started =
+        (g_context.event_loop != NULL
+         && g_main_loop_is_running(g_context.event_loop));
 
     ca_mutex_unlock(g_context.lock);
 
@@ -127,7 +127,7 @@ static GList * CAPeripheralInitializeGattServices(CALEContext * context)
         char const * const hci_name = strrchr(path, '/');
 
         if (hci_name == NULL
-            || !CAGattServiceInitialize(service, context, hci_name + 1))
+            || !CAGattServiceInitialize(service, hci_name + 1, context))
         {
             g_list_free_full(gatt_services,
                              CAPeripheralDestroyGattServices);
@@ -138,9 +138,10 @@ static GList * CAPeripheralInitializeGattServices(CALEContext * context)
         service->gatt_manager = manager;
 
         /*
-          The GattManager1 proxies are now owned by the CAGattService
-          objects.
+          The GattManager1 proxy is now owned by the CAGattService
+          object.
         */
+
         GList * const tmp = l;
         l = l->next;
         gatt_managers = g_list_delete_link(gatt_managers, tmp);
@@ -159,7 +160,7 @@ static bool CAPeripheralRegisterGattServices(
 {
     assert(context != NULL);
 
-    bool success = false;
+    bool success = true;
 
     ca_mutex_lock(context->lock);
 
@@ -210,8 +211,6 @@ static bool CAPeripheralRegisterGattServices(
 
     ca_mutex_unlock(context->lock);
 
-    success = true;
-
     return success;
 }
 
@@ -330,8 +329,13 @@ static void CAPeripheralSetDiscoverable(gpointer data,
     /*
       Make sure the adapter is powered on before making it
       discoverable.
+
+      @todo We used to power off the adapter once we're done with it,
+            but that isn't always desirable.  We should only power it
+            off if it was off prior to us powering it on.
     */
-    if (!CASetBlueZObjectProperty(adapter,
+    if (discoverable
+        && !CASetBlueZObjectProperty(adapter,
                                   BLUEZ_ADAPTER_INTERFACE,
                                   "Powered",
                                   g_variant_new_boolean(discoverable)))
@@ -436,6 +440,20 @@ static void CAPeripheralOnNameLost(GDBusConnection * connection,
               "Lost name \"%s\" on D-Bus!", name);
 }
 
+/**
+ * Inform thread waiting for the event loop to start that the loop has
+ * started.  This is done in the context of the event loop itself so
+ * that we can be certain that the event loop is indeed running.
+ */
+static gboolean CAPeripheralEventLoopStarted(gpointer user_data)
+{
+    ca_cond const condition = user_data;
+
+    ca_cond_signal(condition);  // For service registration
+
+    return G_SOURCE_REMOVE;
+}
+
 static void CAPeripheralStartEventLoop(void * data)
 {
     CALEContext * const context = data;
@@ -497,6 +515,15 @@ static void CAPeripheralStartEventLoop(void * data)
                 "manager interface.");
     }
 
+    ca_mutex_lock(g_context.lock);
+
+    assert(g_context.event_loop == NULL);
+    g_context.event_loop = event_loop;
+
+    g_context.base = context;
+
+    g_context.owner_id = owner_id;
+
     /**
      * Initialize all GATT services.
      *
@@ -509,29 +536,37 @@ static void CAPeripheralStartEventLoop(void * data)
      *       a thread seperate from the one that initiates GATT
      *       service registration.
      */
-    GList * const gatt_services =
-        CAPeripheralInitializeGattServices(context);
-
-    ca_mutex_lock(g_context.lock);
-
-    assert(g_context.event_loop == NULL);
-    g_context.event_loop = event_loop;
-
-    g_context.base = context;
-
-    g_context.owner_id = owner_id;
+    g_context.gatt_services = CAPeripheralInitializeGattServices(context);
 
     CALEAdvertisementInitialize(&g_context.advertisement,
                                 context->connection,
                                 advertising_managers);
 
-    g_context.gatt_services = gatt_services;
-
     ca_mutex_unlock(g_context.lock);
 
-    ca_cond_signal(g_context.condition);
+    /*
+      Add an idle handler that notifies a thread waiting for the
+      GLib event loop to run that the event loop is actually
+      running.  We do this in the context of the event loop itself
+      to avoid race conditions.
+    */
+    GSource * const source = g_idle_source_new();
+    g_source_set_priority(source, G_PRIORITY_HIGH_IDLE);
+    g_source_set_callback(source,
+                          CAPeripheralEventLoopStarted,
+                          g_context.condition,  // data
+                          NULL);                // notify
+    (void) g_source_attach(source, loop_context);
+    g_source_unref(source);
+
+    g_main_loop_run(event_loop);  // Blocks until loop is quit.
 
-    g_main_loop_run(event_loop);
+    /*
+      Clean up in the same thread to avoid having to explicitly bump
+      the ref count to retain ownership.
+    */
+    g_main_context_unref(loop_context);
+    g_main_loop_unref(event_loop);
 }
 
 static void CAPeripheralStopEventLoop(CAPeripheralContext * context)
@@ -553,10 +588,7 @@ static void CAPeripheralStopEventLoop(CAPeripheralContext * context)
         if (loop_context != NULL)
         {
             g_main_context_wakeup(loop_context);
-            g_main_context_unref(loop_context);
         }
-
-        g_main_loop_unref(event_loop);
     }
 }
 
@@ -610,8 +642,9 @@ CAResult_t CAPeripheralStart(CALEContext * context)
     }
 
     /*
-      Wait until initialization completes before proceeding to
-      service and advertisement registration.
+      Wait until initialization completes and the event loop is up and
+      running before proceeding to service and advertisement
+      registration.
     */
 
     // Number of times to wait for initialization to complete.
@@ -628,7 +661,7 @@ CAResult_t CAPeripheralStart(CALEContext * context)
     {
         if (ca_cond_wait_for(g_context.condition,
                              g_context.lock,
-                             timeout) == 0)
+                             timeout) == CA_WAIT_SUCCESS)
         {
             result = CA_STATUS_OK;
         }
@@ -636,7 +669,7 @@ CAResult_t CAPeripheralStart(CALEContext * context)
 
     ca_mutex_unlock(g_context.lock);
 
-    if (result == CA_STATUS_FAILED)
+    if (result != CA_STATUS_OK)
     {
         return result;
     }
@@ -671,7 +704,6 @@ CAResult_t CAPeripheralStop()
     // Only stop if we were previously started.
     if (!CAPeripheralCheckStarted())
     {
-        result = CA_STATUS_OK;
         return result;
     }
 
@@ -706,3 +738,12 @@ CAResult_t CAPeripheralStop()
 
     return result;
 }
+
+void CAPeripheralForEachService(GFunc func, void * user_data)
+{
+    ca_mutex_lock(g_context.lock);
+
+    g_list_foreach(g_context.gatt_services, func, user_data);
+
+    ca_mutex_unlock(g_context.lock);
+}
index 89d9318..419edb4 100644 (file)
@@ -124,5 +124,23 @@ CAResult_t CAPeripheralStart(CALEContext * context);
  */
 CAResult_t CAPeripheralStop();
 
+/**
+ * Invoke function @a func for each registered GATT service.
+ *
+ * For each registered GATT service, invoke the function @a func,
+ * where the first (data) paramter will be a pointer to the
+ * ::CAGattService object, and the second will be the @a user_data
+ * argument provided to this function call.
+ *
+ * @param[in] func      Function to be invoked for each
+ *                      ::CAGattService.
+ * @param[in] user_data User provided data passed as the second
+ *                      argument to the function @a func.
+ *
+ * @note This function exists to avoid exposing the BLE peripheral
+ *       internals.
+ */
+void CAPeripheralForEachService(GFunc func, void * user_data);
+
 
 #endif  /* CA_BLE_LINUX_PERIPHERAL_H */
index 99bfdd8..c50ba1b 100644 (file)
@@ -19,7 +19,6 @@
 #include "recv.h"
 
 #include "caremotehandler.h"
-#include "cafragmentation.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
 
index 828183c..be7302d 100644 (file)
@@ -1,4 +1,4 @@
-/******************************************************************
+/* ****************************************************************
  *
  * Copyright 2015 Intel Corporation All Rights Reserved.
  *
  *
  ******************************************************************/
 
+
 #include "server.h"
+#include "service.h"
+#include "peripheral.h"
 
-#include "cacommon.h"
 #include "logger.h"
 
 #include <assert.h>
 // Logging tag.
 static char const TAG[] = "BLE_SERVER";
 
-// ---------------------------------------------------------------------
-//                      GATT Request Handling
-// ---------------------------------------------------------------------
-void CAGattServerHandleRequestData()
-{
-}
-
-// ---------------------------------------------------------------------
-//                      GATT Response Handling
-// ---------------------------------------------------------------------
-/**
- * Send response data to the GATT client.
- *
- * Respone data will be sent to the client through the given response
- * @a characteristic proxy as a GATT characteristic notification.
- *
- * @param[in] characteristic The D-Bus proxy for the response
- *                           characteristic through which the
- *                           notification will be sent.
- * @param[in] data           The byte array to be sent.
- * @param[in] length         The number of elements in the byte
- *                           array.
- */
-static bool CAGattServerSendResponseNotification(
-    GattCharacteristic1 * characteristic,
-    char const * data,
+static CAResult_t CAGattServerSendResponseNotificationImpl(
+    CAGattService * service,
+    uint8_t const * data,
     size_t length)
 {
+    assert(service != NULL);
+
+    GattCharacteristic1 * const characteristic =
+        service->response_characteristic.characteristic;
+
     if (!gatt_characteristic1_get_notifying(characteristic))
     {
         OIC_LOG(WARNING,
@@ -64,7 +48,7 @@ static bool CAGattServerSendResponseNotification(
                 "Client must enable notifications. "
                 "No response was sent.");
 
-        return false;
+        return CA_STATUS_FAILED;
     }
 
     GVariant * const value =
@@ -73,38 +57,78 @@ static bool CAGattServerSendResponseNotification(
                                   length,
                                   sizeof(data[0]));
 
-    /**
-     * Send the response fragment by setting the "Value" property on
-     * the response characteristic, and emitting the
-     * @c org.freedesktop.Dbus.Properties.PropertiesChanged signal,
-     * accordingly.
-     *
-     * @todo Do we need to explicitly emit the @c GObject @c notify or
-     *       @c org.freedesktop.Dbus.Properties.PropertiesChanged
-     *       signal here?
-     */
+    /*
+      Send the response fragment by setting the "Value" property on
+      the response characteristic, and emitting the
+      org.freedesktop.Dbus.Properties.PropertiesChanged signal,
+      accordingly.
+
+      @todo Do we need to explicitly emit the GObject notify or
+            org.freedesktop.Dbus.Properties.PropertiesChanged
+            signal here?
+
+      @todo It feels like this function should be part of the
+            response characteristic implementation.
+
+      @todo Do we need to decrease the ref count after setting the
+            value, i.e. is ownership of the value transferred to the
+            characteristic object?
+    */
     gatt_characteristic1_set_value(characteristic, value);
 
-    return true;
+    return CA_STATUS_OK;
 }
 
-bool CAGattServerSendResponse(void const * method_info,
-                              void const * data,
-                              size_t length)
+typedef struct _CAGattServerResponseInfo
 {
-    assert(method_info != NULL);
+    uint8_t const * const data;
+    size_t const length;
+    CAResult_t result;
 
-    CAGattResponseInfo const * const info = method_info;
+} CAGattServerResponseInfo;
 
-    GattCharacteristic1 * const characteristic =
-        info->characteristic;
+static void CAGattServerSendResponseNotificationToService(gpointer data,
+                                                          gpointer user_data)
+{
+    CAGattService * const service = data;
+    CAGattServerResponseInfo * const info = user_data;
+
+    CAResult_t const result =
+        CAGattServerSendResponseNotificationImpl(service,
+                                                 info->data,
+                                                 info->length);
 
-    if (!CAGattServerSendResponseNotification(characteristic,
-                                              (char const *) data,
-                                              length))
+    if (result != CA_STATUS_OK)
     {
-        return false;
+        // Propagate failure if any send operation fails.
+        info->result = result;
     }
+}
+
+CAResult_t CAGattServerSendResponseNotification(
+    char const * address,
+    uint8_t const * data,
+    size_t length)
+{
+    CAGattService * const s = CAGattServiceDecodeAddress(address);
+
+    return CAGattServerSendResponseNotificationImpl(s, data, length);
+}
+
+CAResult_t CAGattServerSendResponseNotificationToAll(
+    uint8_t const * data,
+    size_t length)
+{
+    CAGattServerResponseInfo info =
+    {
+        .data   = data,
+        .length = length,
+        .result = CA_STATUS_OK
+    };
+
+    CAPeripheralForEachService(
+        CAGattServerSendResponseNotificationToService,
+        &info);
 
-    return true;
+    return info.result;
 }
index 91dcc26..c4b707e 100644 (file)
 #ifndef CA_BLE_LINUX_SERVER_H
 #define CA_BLE_LINUX_SERVER_H
 
-#include "bluez-glue.h"
+#include "cacommon.h"
 
-#include <stdbool.h>
+#include <stdint.h>
 #include <sys/types.h>
 
+
 /**
- * Information needed to complete a GATT server response send.
+ * Send response/notification to the GATT client.
+ *
+ * Data will be sent to the client through the given response
+ * @a characteristic proxy as a GATT characteristic notification.
+ *
+ * @param[in] characteristic The D-Bus proxy for the response
+ *                           characteristic through which the
+ *                           notification will be sent.
+ * @param[in] data           The byte array to be sent.
+ * @param[in] length         The number of elements in the byte
+ *                           array.
+ *
+ * @return ::CA_STATUS_OK on success, ::CA_STATUS_FAILED otherwise.
  */
-typedef struct _CAGattResponseInfo
-{
-    /**
-     * The BlueZ @c org.bluez.GattCharacteristic1 skeleton object
-     * through which data will be sent.
-     */
-    GattCharacteristic1 * const characteristic;
+CAResult_t CAGattServerSendResponseNotification(
+    char const * address,
+    uint8_t const * data,
+    size_t length);
 
-} CAGattResponseInfo;
 
 /**
- * Send response notification to the GATT client.
+ * Send notification to all connected GATT clients.
+ *
+ * Data will be sent to the client through the given response
+ * @a characteristic proxy as a GATT characteristic notification.
  *
- * @param[in] method_info Pointer to @c GattResponseInfo object that
- *                        contains information necessary to complete
- *                        send of response.
- * @param[in] data        Octet array of response data to be sent.
- * @param[in] length      Length of the @a data octet array.
+ * @param[in] data    The byte array to be sent.
+ * @param[in] length  The number of elements in the byte array.
+ * @param[in] context Object containing mutexes and error reporting
+ *                    callback used on failure to send.
  *
- * @see @c CAGattSendMethod() for further details.
+ * @return ::CA_STATUS_OK on success, ::CA_STATUS_FAILED otherwise.
  */
-bool CAGattServerSendResponse(void const * method_info,
-                              void const * data,
-                              size_t length);
+CAResult_t CAGattServerSendResponseNotificationToAll(
+    uint8_t const * data,
+    size_t length);
 
 
 #endif  /* CA_BLE_LINUX_SERVER_H */
index ef204e5..bf89417 100644 (file)
 
 #include "cagattservice.h"
 #include "logger.h"
+#include "oic_malloc.h"
 
+#include <inttypes.h>
+#include <stdio.h>
 #include <assert.h>
 
 
@@ -158,9 +161,71 @@ static gboolean CAGattServiceHandleGetManagedObjects(
     return TRUE;
 }
 
+char * CAGattServiceMakePeerAddress(CAGattService * s)
+{
+    assert(s != NULL);
+
+    /*
+      Since there is no direct way to obtain the client address
+      associated with the GATT characterstics on the server side,
+      embed a stringified pointer to this GATT service of the form
+      "&ABCDEF01" as the address instead so that we can use it to
+      refer to the client.  This works since:
+          1) only one LE central is ever connected to an LE peripheral
+          2) the CA layer doesn't directly interpret the client
+             address
+     */
+
+    /*
+      Length of stringified pointer in hexadecimal format, plus one
+      for the leading ampersand, and one more for the null
+      terminator.
+    */
+    static size_t const PSEUDO_ADDR_LEN = sizeof(uintptr_t) * 2 + 2;
+
+    assert(MAX_ADDR_STR_SIZE_CA > PSEUDO_ADDR_LEN);
+
+    char * const addr = OICMalloc(PSEUDO_ADDR_LEN);
+
+    if (addr == NULL)
+    {
+        return addr;
+    }
+
+    int const count = snprintf(addr,
+                               PSEUDO_ADDR_LEN,
+                               "&%" PRIxPTR,
+                               (uintptr_t) s);
+
+    if (count < 0 || count >= (int) PSEUDO_ADDR_LEN)
+    {
+        OIC_LOG(ERROR,
+                TAG,
+                "Error creating peer address on server side.");
+
+        OICFree(addr);
+
+        return NULL;
+    }
+
+    return addr;
+}
+
+CAGattService * CAGattServiceDecodeAddress(char const * address)
+{
+    /*
+      The peer address is actually the value of the pointer to the
+      CAGattService object containing the response characteristic.
+     */
+    uintptr_t s = (uintptr_t) NULL;
+    (void) sscanf(address, "&%" SCNxPTR, &s);
+
+    return (CAGattService *) s;
+}
+
 bool CAGattServiceInitialize(CAGattService * s,
-                             CALEContext * context,
-                             char const * hci_name)
+                             char const * hci_name,
+                             CALEContext * context)
 {
     assert(s != NULL);
     assert(context != NULL);
@@ -192,7 +257,7 @@ bool CAGattServiceInitialize(CAGattService * s,
       The characteristic object paths are not fixed at compile-time.
       Retrieve the object paths that were set at run-time.
     */
-    char const * characteristic_paths[] = {
+    char const * const characteristic_paths[] = {
         s->request_characteristic.object_path,
         s->response_characteristic.object_path,
         NULL
index 2cfbc3e..ad1f146 100644 (file)
@@ -56,15 +56,40 @@ typedef struct CAGattService
 } CAGattService;
 
 /**
+ * Make the pseudo-address for the peer connected to the service.
+ *
+ * @param[in] c Information about GATT service for which the
+ *              peer (client) address is being created.
+ *
+ * @return @c String containing an encoded address associated with the
+ *         peer connected to the peripheral on which the service
+ *         implementation resides, or @c NULL on error.
+ */
+char * CAGattServiceMakePeerAddress(CAGattService * s);
+
+/**
+ * Decode @c CAGattService pointer from peer @c address.
+ *
+ * @param[in] address String containing a client/peer pseudo-address
+ *                    corresponding to the GATT service through which
+ *                    communication is performed.
+ *
+ * @return Pointer to ::CAGattService object corresponding to the
+ *         given address.
+ */
+CAGattService * CAGattServiceDecodeAddress(char const * address);
+
+/**
  * Initialize GATT service fields.
  *
  * This function initializes the @c CAGattService object fields.
  *
  * @param[out] service  GATT service information to be initialized.
- * @param[in]  context  Object containing the D-Bus connection to the
- *                      bus on which the service will be exported.
  * @param[in]  hci_name Name of the bluetooth adapter installed on the
  *                      system, e.g. @c "hci0".
+ * @param[in]  context  Object containing the D-Bus connection to the
+ *                      bus on which the service will be exported, as
+ *                      well as an address-to-characteristic map.
  *
  * @return @c true on success, @c false otherwise.
  *
@@ -73,8 +98,8 @@ typedef struct CAGattService
  *       memory.
  */
 bool CAGattServiceInitialize(CAGattService * service,
-                             CALEContext * context,
-                             char const * hci_name);
+                             char const * hci_name,
+                             CALEContext * context);
 
 /**
  * Destroy GATT service fields.
@@ -89,5 +114,4 @@ bool CAGattServiceInitialize(CAGattService * service,
  */
 void CAGattServiceDestroy(CAGattService * service);
 
-
 #endif  // CA_BLE_LINUX_SERVICE_H
index 40708f1..ac0f8f3 100644 (file)
@@ -196,7 +196,7 @@ bool CASetBlueZObjectProperty(GDBusProxy * proxy,
                   TAG,
                   "Attempt to set \"%s\" property for "
                   "\"%s\" interface failed.: %s",
-                  error->message);
+                  property, interface, error->message);
 
         g_error_free(error);
 
index 251b16e..4a2cb7a 100644 (file)
@@ -6,15 +6,13 @@ Import('env', 'src_dir')
 import os.path
 
 root_dir = os.pardir
-env.PrependUnique(CPPPATH = [ os.path.join(src_dir, 'tizen'),
-                              os.path.join(root_dir, 'lib/tizen/ble/inc'),
-                              os.path.join(root_dir, 'lib/tizen/ble/inc/mobile')])
+env.PrependUnique(CPPPATH = [ os.path.join(src_dir, 'tizen')])
 
-env.ParseConfig("pkg-config --cflags --libs capi-network-bluetooth glib-2.0")
+env.ParseConfig("pkg-config --cflags --libs capi-network-bluetooth")
 
-src_files = [ 'cableclient.c',
-              'cableserver.c',
-              'cableutil.c',
-              'cablenwmonitor.c']
+src_files = [ 'caleclient.c',
+              'caleserver.c',
+              'caleutil.c',
+              'calenwmonitor.c']
 
 Return('src_files')
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/cableclient.c b/resource/csdk/connectivity/src/bt_le_adapter/tizen/cableclient.c
deleted file mode 100644 (file)
index d7c505c..0000000
+++ /dev/null
@@ -1,1468 +0,0 @@
-/* ****************************************************************
-*
-* Copyright 2014 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 "cableclient.h"
-
-#include<stdio.h>
-#include<stdlib.h>
-#include<string.h>
-#include<arpa/inet.h>
-#include<sys/types.h>
-#include<sys/socket.h>
-#include<netinet/in.h>
-#include <pthread.h>
-#include <gio/gio.h>
-
-#include "camutex.h"
-#include "uarraylist.h"
-#include "caqueueingthread.h"
-#include "caadapterutils.h"
-#include "cafragmentation.h"
-#include "cagattservice.h"
-#include "oic_string.h"
-#include "oic_malloc.h"
-
-/**
- * Logging tag for module name.
- */
-#define TZ_BLE_CLIENT_TAG "TZ_BLE_GATT_CLIENT"
-
-/**
- * This contains the list of OIC services a client connect to.
- */
-static BLEServiceList *g_bLEServiceList = NULL;
-
-/**
- * Boolean variable to keep the state of the GATT Client.
- */
-static bool g_isBleGattClientStarted = false;
-
-/**
- * Mutex to synchronize access to BleServiceList.
- */
-static ca_mutex g_bleServiceListMutex = NULL;
-
-/**
- * Mutex to synchronize access to the requestResponse callback to be called
- *    when the data needs to be sent from GATTClient.
- */
-static ca_mutex g_bleReqRespClientCbMutex = NULL;
-
-/**
- * Mutex to synchronize access to the requestResponse callback to be called
- *    when the data needs to be sent from GATTClient.
- */
-static ca_mutex g_bleClientConnectMutex = NULL;
-
-
-/**
- * Mutex to synchronize the calls to be done to the platform from GATTClient
- *    interfaces from different threads.
- */
-static ca_mutex g_bleClientStateMutex = NULL;
-
-/**
- * Mutex to synchronize the Server BD Address update on client side.
- */
-static ca_mutex g_bleServerBDAddressMutex = NULL;
-
-/**
- * Condition used for notifying handler the presence of data in send queue.
- */
-static ca_cond g_bleClientSendCondWait = NULL;
-
-/**
- * Mutex to synchronize the task to be pushed to thread pool.
- */
-static ca_mutex g_bleClientThreadPoolMutex = NULL;
-
-/**
- * Maintains the callback to be notified on receival of network packets
- *    from other BLE devices
- */
-static CABLEDataReceivedCallback g_bleClientDataReceivedCallback = NULL;
-
-/**
- * callback to update the error to le adapter
- */
-static CABLEErrorHandleCallback g_clientErrorCallback;
-
-/**
- * gmainLoop to manage the threads to receive the callback from the platfrom.
- */
-static GMainLoop *g_eventLoop = NULL;
-
-/**
- * reference to threadpool.
- */
-static ca_thread_pool_t g_bleClientThreadPool = NULL;
-
-/**
- * structure to map the service attribute to BD Address.
- */
-typedef struct gattService
-{
-    bt_gatt_attribute_h serviceInfo;         /**< bluetoth attribute for oic service*/
-    char *address;                           /**< BD Address of */
-} stGattServiceInfo_t;
-
-/**
- * Remote address of Gatt Server.
- */
-static char *g_remoteAddress = NULL;
-
-void CABleGattCharacteristicChangedCb(bt_gatt_attribute_h characteristic,
-                                      unsigned char *value,
-                                      int valueLen,
-                                      void *userData)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Changed characteristic is  [%s]", (char *)characteristic);
-    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Changed characteristic value length [%d]", valueLen);
-
-    ca_mutex_lock(g_bleReqRespClientCbMutex);
-    if (NULL == g_bleClientDataReceivedCallback)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "gReqRespCallback is NULL!");
-        ca_mutex_unlock(g_bleReqRespClientCbMutex);
-        return;
-    }
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Sending data up !");
-
-    ca_mutex_lock(g_bleServerBDAddressMutex);
-    uint32_t sentLength = 0;
-    g_bleClientDataReceivedCallback(g_remoteAddress, value, valueLen,
-                                    &sentLength);
-
-    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Sent data Length is %d", sentLength);
-    ca_mutex_unlock(g_bleServerBDAddressMutex);
-
-    ca_mutex_unlock(g_bleReqRespClientCbMutex);
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-}
-
-void CABleGattCharacteristicWriteCb(int result, void *userData)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN ");
-
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT ");
-}
-
-void CABleGattDescriptorDiscoveredCb(int result, unsigned char format, int total,
-                                     bt_gatt_attribute_h descriptor,
-                                     bt_gatt_attribute_h characteristic, void *userData)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    stGattCharDescriptor_t *stTemp = (stGattCharDescriptor_t *)OICCalloc(1, sizeof(
-                                                                         stGattCharDescriptor_t));
-
-    VERIFY_NON_NULL_VOID(stTemp, TZ_BLE_CLIENT_TAG, "malloc failed!");
-
-    stTemp->desc = (uint8_t *)OICMalloc(total);
-    if (NULL == stTemp->desc)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "malloc failed");
-        OICFree(stTemp);
-        return;
-    }
-    memcpy(stTemp->desc, descriptor, total);
-
-    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "result[%d] format[%d] total[%d]", result, format, total);
-    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "characteristic [%s]", (const char *) characteristic);
-
-
-    bt_gatt_clone_attribute_handle(&(stTemp->characteristic), characteristic);
-    stTemp->total = total;
-
-    ca_mutex_lock(g_bleClientThreadPoolMutex);
-    if (NULL == g_bleClientThreadPool)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "g_bleClientThreadPool is NULL");
-        bt_gatt_destroy_attribute_handle(stTemp->characteristic);
-        OICFree(stTemp->desc);
-        OICFree(stTemp);
-        ca_mutex_unlock(g_bleClientThreadPoolMutex);
-        return;
-    }
-
-    CAResult_t ret = ca_thread_pool_add_task(g_bleClientThreadPool,
-                                            CASetCharacteristicDescriptorValueThread,
-                                            stTemp);
-    if (CA_STATUS_OK != ret)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "ca_thread_pool_add_task failed");
-        bt_gatt_destroy_attribute_handle(stTemp->characteristic);
-        OICFree(stTemp->desc);
-        OICFree(stTemp);
-        ca_mutex_unlock(g_bleClientThreadPoolMutex);
-        return;
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG,
-            "LE Client initialization flow complete");
-
-    ca_mutex_unlock(g_bleClientThreadPoolMutex);
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-}
-
-bool CABleGattCharacteristicsDiscoveredCb(int result,
-        int inputIndex, int total,
-        bt_gatt_attribute_h characteristic, void *userData)
-{
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    VERIFY_NON_NULL_RET(characteristic, TZ_BLE_CLIENT_TAG, "Param characteristic is NULL", false);
-
-    VERIFY_NON_NULL_RET(userData, TZ_BLE_CLIENT_TAG, "Param userData is NULL", false);
-
-    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
-              "result [%d] input_index [%d] total [%d]",
-              result, inputIndex, total);
-
-    BLEServiceInfo *bleServiceInfo = NULL;
-
-    ca_mutex_lock(g_bleServiceListMutex);
-
-    char *bdAddress = (char *) userData;
-    CAGetBLEServiceInfo(g_bLEServiceList, bdAddress, &bleServiceInfo);
-
-    ca_mutex_unlock(g_bleServiceListMutex);
-
-    char *uuid = NULL;
-    bt_gatt_get_service_uuid(characteristic, &uuid);
-
-    VERIFY_NON_NULL_RET(uuid, TZ_BLE_CLIENT_TAG, "uuid is NULL", false);
-
-    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "New Characteristics[%s] of uuid[%s] is obtained",
-              (char *)characteristic, uuid);
-
-    if(0 == strcasecmp(uuid, CA_GATT_RESPONSE_CHRC_UUID)) // Server will read on this characterisctics
-    {
-        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG , "Read characteristics is obtained");
-        OICFree(uuid);
-        CAResult_t retVal = CAAppendBLECharInfo(characteristic, BLE_GATT_READ_CHAR, bleServiceInfo);
-        if (CA_STATUS_OK != retVal)
-        {
-            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "CAAppendBLECharInfo failed! ");
-            return false;
-        }
-
-        stGattServiceInfo_t *stTemp = (stGattServiceInfo_t *)OICCalloc(1,
-                                                                      sizeof(stGattServiceInfo_t));
-
-        VERIFY_NON_NULL_RET(stTemp, TZ_BLE_CLIENT_TAG, "calloc failed!", false);
-
-        stTemp->address = OICStrdup(bdAddress);
-        if (NULL == stTemp->address)
-        {
-            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "Malloc failed!");
-            OICFree(stTemp);
-            return false;
-        }
-
-        bt_gatt_clone_attribute_handle(&(stTemp->serviceInfo), characteristic);
-
-        ca_mutex_lock(g_bleClientThreadPoolMutex);
-        if (NULL == g_bleClientThreadPool)
-        {
-            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "g_bleClientThreadPool is NULL");
-            bt_gatt_destroy_attribute_handle(stTemp->serviceInfo);
-            OICFree(stTemp->address);
-            OICFree(stTemp);
-            ca_mutex_unlock(g_bleClientThreadPoolMutex);
-            return false;
-        }
-
-        retVal = ca_thread_pool_add_task(g_bleClientThreadPool,
-                                        CADiscoverDescriptorThread,
-                                        stTemp);
-        if (CA_STATUS_OK != retVal)
-        {
-            OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                      "ca_thread_pool_add_task failed with ret [%d]", retVal);
-            bt_gatt_destroy_attribute_handle(stTemp->serviceInfo);
-            OICFree(stTemp->address);
-            OICFree(stTemp);
-            ca_mutex_unlock(g_bleClientThreadPoolMutex);
-            return false;
-        }
-        ca_mutex_unlock(g_bleClientThreadPoolMutex);
-    }
-    else if (0 == strcasecmp(uuid, CA_GATT_REQUEST_CHRC_UUID)) // Server will write on this characteristics.
-    {
-        OICFree(uuid);
-        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG , "Write characteristics is obtained");
-        CAResult_t retVal = CAAppendBLECharInfo(characteristic, BLE_GATT_WRITE_CHAR, bleServiceInfo);
-        if (CA_STATUS_OK != retVal)
-        {
-            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "CAAppendBLECharInfo failed ");
-            return false;
-        }
-    }
-    else
-    {
-        OICFree(uuid);
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "service_uuid characteristics is UNKNOWN");
-        return false;
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-    return true;
-}
-
-bool CABleGattPrimaryServiceCb(bt_gatt_attribute_h service, int index, int count,
-                               void *userData)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    VERIFY_NON_NULL_RET(service, TZ_BLE_CLIENT_TAG, "Param service is NULL", false);
-
-    VERIFY_NON_NULL_RET(userData, TZ_BLE_CLIENT_TAG, "Param userData is NULL", false);
-
-    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Service info [%s] index [%d] count [%d]", (char *)service,
-              index, count);
-
-    CAResult_t result = CAVerifyOICServiceByServiceHandle(service);
-
-    if (CA_STATUS_OK == result)
-    {
-        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Its OIC service");
-
-        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG , "Registering to watch characteristics changes");
-
-        result = CABleGattWatchCharacteristicChanges(service);
-        if (CA_STATUS_OK != result)
-        {
-            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG,
-                      "CABleGattWatchCharacteristicChanges failed!");
-            return false;
-        }
-
-        stGattServiceInfo_t *stTemp = (stGattServiceInfo_t *)OICCalloc(1,
-                                                                      sizeof(stGattServiceInfo_t));
-        VERIFY_NON_NULL_RET(stTemp, TZ_BLE_CLIENT_TAG, "Calloc Failed", false);
-
-        char *bdAddress = (char *)userData;
-
-        stTemp->address = OICStrdup(bdAddress);
-        if (NULL == stTemp->address)
-        {
-            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "Malloc failed!");
-            OICFree(stTemp);
-            return false;
-        }
-
-        BLEServiceInfo *bleServiceInfo = NULL;
-
-        result = CACreateBLEServiceInfo(bdAddress, service, &bleServiceInfo);
-        if (CA_STATUS_OK != result)
-        {
-            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "CACreateBLEServiceInfo failed! ");
-            OICFree(stTemp->address);
-            OICFree(stTemp);
-            OICFree(bleServiceInfo);
-            return false;
-        }
-        if (NULL == bleServiceInfo )
-        {
-            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , " bleServiceInfo is NULL");
-            OICFree(stTemp->address);
-            OICFree(stTemp);
-            OICFree(bleServiceInfo);
-            return false;
-        }
-
-        OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG ,
-                  " serviceInfo remote address [%s]", bleServiceInfo->bdAddress);
-
-        ca_mutex_lock(g_bleServiceListMutex);
-        result = CAAddBLEServiceInfoToList(&g_bLEServiceList, bleServiceInfo);
-        ca_mutex_unlock(g_bleServiceListMutex);
-        if (CA_STATUS_OK != result)
-        {
-            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "CAAddBLEServiceInfoToList failed!");
-            OICFree(stTemp->address);
-            OICFree(stTemp);
-            CAFreeBLEServiceInfo(bleServiceInfo);
-            return false;
-        }
-
-
-        ca_mutex_lock(g_bleClientThreadPoolMutex);
-        if (NULL == g_bleClientThreadPool)
-        {
-            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "g_bleClientThreadPool is NULL");
-            OICFree(stTemp->address);
-            OICFree(stTemp);
-            ca_mutex_lock(g_bleServiceListMutex);
-            CARemoveBLEServiceInfoToList(&g_bLEServiceList, bleServiceInfo,
-                                         bleServiceInfo->bdAddress);
-            ca_mutex_unlock(g_bleServiceListMutex);
-            ca_mutex_unlock(g_bleClientThreadPoolMutex);
-            return false;
-        }
-        bt_gatt_clone_attribute_handle(&(stTemp->serviceInfo), service);
-
-        result = ca_thread_pool_add_task(g_bleClientThreadPool,
-                                        CADiscoverCharThread,
-                                        stTemp);
-        if (CA_STATUS_OK != result)
-        {
-            OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                      "ca_thread_pool_add_task failed with ret [%d]", result);
-            OICFree(stTemp->address);
-            OICFree(stTemp);
-            ca_mutex_lock(g_bleServiceListMutex);
-            CARemoveBLEServiceInfoToList(&g_bLEServiceList, bleServiceInfo,
-                                         bleServiceInfo->bdAddress);
-            ca_mutex_unlock(g_bleServiceListMutex);
-            ca_mutex_unlock(g_bleClientThreadPoolMutex);
-            return false;
-        }
-        ca_mutex_unlock(g_bleClientThreadPoolMutex);
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT ");
-    return true;;
-}
-
-void CABleGattConnectionStateChangedCb(int result, bool connected,
-                                       const char *remoteAddress, void *userData)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN ");
-
-    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "CABleGattConnectionStateChangedCb result[%d] ", result);
-
-    VERIFY_NON_NULL_VOID(remoteAddress, TZ_BLE_CLIENT_TAG, "remote address is NULL");
-
-    CAResult_t ret = CA_STATUS_FAILED;
-    if (!connected)
-    {
-        OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "DisConnected from [%s] ", remoteAddress);
-
-        ret = CABleGattStartDeviceDiscovery();
-        if (CA_STATUS_OK != ret)
-        {
-            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "CABleGattStartDeviceDiscovery failed");
-            return;
-        }
-    }
-    else
-    {
-        OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Connected to [%s] ", remoteAddress);
-
-        ca_mutex_lock(g_bleServerBDAddressMutex);
-
-        g_remoteAddress = OICStrdup(remoteAddress);
-
-        ca_mutex_unlock(g_bleServerBDAddressMutex);
-
-        VERIFY_NON_NULL_VOID(g_remoteAddress, TZ_BLE_CLIENT_TAG, "Malloc failed");
-
-        char *addr = OICStrdup(remoteAddress);
-
-        ca_mutex_lock(g_bleClientThreadPoolMutex);
-        if (NULL == g_bleClientThreadPool)
-        {
-            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "g_bleClientThreadPool is NULL");
-            OICFree(addr);
-
-            ca_mutex_lock(g_bleServerBDAddressMutex);
-            OICFree(g_remoteAddress);
-            ca_mutex_unlock(g_bleServerBDAddressMutex);
-
-            ca_mutex_unlock(g_bleClientThreadPoolMutex);
-            return;
-        }
-
-        ret = ca_thread_pool_add_task(g_bleClientThreadPool, CADiscoverBLEServicesThread,
-                                     addr);
-        if (CA_STATUS_OK != ret)
-        {
-            OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "ca_thread_pool_add_task failed with ret [%d]", ret);
-            OICFree(addr);
-
-            ca_mutex_lock(g_bleServerBDAddressMutex);
-            OICFree(g_remoteAddress);
-            ca_mutex_unlock(g_bleServerBDAddressMutex);
-
-            ca_mutex_unlock(g_bleClientThreadPoolMutex);
-            return;
-        }
-        ca_mutex_unlock(g_bleClientThreadPoolMutex);
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-}
-
-void CABtAdapterLeDeviceDiscoveryStateChangedCb(int result,
-        bt_adapter_le_device_discovery_state_e discoveryState,
-        bt_adapter_le_device_discovery_info_s *discoveryInfo,
-        void *userData)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    if (NULL  == discoveryInfo && BT_ADAPTER_LE_DEVICE_DISCOVERY_FOUND == discoveryState)
-    {
-        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "discoveryInfo is NULL");
-        return;
-    }
-
-    if (BT_ADAPTER_LE_DEVICE_DISCOVERY_FOUND != discoveryState)
-    {
-        OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
-                  " LE Discovery state is [%s]",
-          discoveryState == BT_ADAPTER_LE_DEVICE_DISCOVERY_STARTED ? "Started" : "Finished");
-    }
-    else
-    {
-        CAPrintDiscoveryInformation(discoveryInfo);
-
-        if (discoveryInfo->service_uuid == NULL)
-        {
-            OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "NO UUIDS from device");
-        }
-        else
-        {
-            for (int32_t i = discoveryInfo->service_count - 1; i >= 0; i--)
-            {
-                OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "uuid[%d]: [%s]",
-                          i, discoveryInfo->service_uuid[i]);
-                CAResult_t res = CAVerifyOICServiceByUUID(discoveryInfo->service_uuid[i]);
-                if (CA_STATUS_OK == res)
-                {
-                    char *addr = OICStrdup(discoveryInfo->remote_address);
-                    VERIFY_NON_NULL_VOID(addr, TZ_BLE_CLIENT_TAG, "Malloc failed");
-
-                    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
-                              "Trying to do Gatt connection to [%s]", addr);
-
-                    ca_mutex_lock(g_bleClientThreadPoolMutex);
-                    if (NULL == g_bleClientThreadPool)
-                    {
-                        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "g_bleClientThreadPool is NULL");
-                        OICFree(addr);
-                        ca_mutex_unlock(g_bleClientThreadPoolMutex);
-                        return;
-                    }
-
-                    CAResult_t ret = ca_thread_pool_add_task(g_bleClientThreadPool,
-                                                  CAGattConnectThread, addr);
-                    if (CA_STATUS_OK != ret)
-                    {
-                        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                                  "ca_thread_pool_add_task failed with ret [%d]", ret);
-                        OICFree(addr);
-                        ca_mutex_unlock(g_bleClientThreadPoolMutex);
-                        return;
-                    }
-                    ca_mutex_unlock(g_bleClientThreadPoolMutex);
-                    if (discoveryInfo->adv_data_len > 31 || discoveryInfo->scan_data_len > 31)
-                    {
-                        bt_adapter_le_stop_device_discovery();
-                        return;
-                    }
-                    break;  // Found the OIC Service. No need to verify remaining services.
-                }
-            }
-        }
-    }
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-}
-
-
-void CAPrintDiscoveryInformation(const bt_adapter_le_device_discovery_info_s *discoveryInfo)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    if (NULL == discoveryInfo)
-    {
-        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "discoveryInfo is NULL ");
-        return;
-    }
-
-    if (discoveryInfo->remote_address)
-    {
-        OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Remote Address [%s]", discoveryInfo->remote_address);
-    }
-
-    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
-              " Adv data len [%d] Scan data len[%d]RSSI [%d] Addr_type [%d] ",
-              discoveryInfo->adv_data_len, discoveryInfo->scan_data_len, discoveryInfo->rssi,
-              discoveryInfo->address_type);
-    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
-              " Number of services present in device [%s] is [%d]",
-              discoveryInfo->remote_address, discoveryInfo->service_count);
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-}
-
-void CASetLEClientThreadPoolHandle(ca_thread_pool_t handle)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    ca_mutex_lock(g_bleClientThreadPoolMutex);
-    g_bleClientThreadPool = handle;
-    ca_mutex_unlock(g_bleClientThreadPoolMutex);
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-}
-
-void CASetLEReqRespClientCallback(CABLEDataReceivedCallback callback)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    ca_mutex_lock(g_bleReqRespClientCbMutex);
-
-    g_bleClientDataReceivedCallback = callback;
-
-    ca_mutex_unlock(g_bleReqRespClientCbMutex);
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-}
-
-
-void CASetBLEClientErrorHandleCallback(CABLEErrorHandleCallback callback)
-{
-    g_clientErrorCallback = callback;
-}
-
-CAResult_t CAStartLEGattClient()
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    CAResult_t retVal = CAInitGattClientMutexVariables();
-
-    if (CA_STATUS_OK != retVal)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "CAInitGattClientMutexVariables failed!");
-        CATerminateGattClientMutexVariables();
-        return CA_STATUS_FAILED;
-    }
-
-    ca_mutex_lock(g_bleClientThreadPoolMutex);
-    if (NULL == g_bleClientThreadPool)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "gBleServerThreadPool is NULL");
-        CATerminateGattClientMutexVariables();
-        ca_mutex_unlock(g_bleClientThreadPoolMutex);
-        return CA_STATUS_FAILED;
-    }
-
-    retVal = ca_thread_pool_add_task(g_bleClientThreadPool, CAStartBleGattClientThread,
-                                     NULL);
-    if (CA_STATUS_OK != retVal)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "ca_thread_pool_add_task failed");
-        CATerminateGattClientMutexVariables();
-        ca_mutex_unlock(g_bleClientThreadPoolMutex);
-        return CA_STATUS_FAILED;
-    }
-    ca_mutex_unlock(g_bleClientThreadPoolMutex);
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-void CAStartBleGattClientThread(void *data)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    ca_mutex_lock(g_bleClientStateMutex);
-
-    if (true  == g_isBleGattClientStarted)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "Gatt Client is already running!!");
-        ca_mutex_unlock(g_bleClientStateMutex);
-        return;
-    }
-
-    CAResult_t  ret = CABleGattSetScanParameter();
-    if (CA_STATUS_OK != ret)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "CABleSetScanParameter Failed");
-        ca_mutex_unlock(g_bleClientStateMutex);
-        CATerminateLEGattClient();
-        return;
-    }
-
-    ret = CABleGattSetCallbacks();
-    if (CA_STATUS_OK != ret)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "CABleGattSetCallbacks Failed");
-        ca_mutex_unlock(g_bleClientStateMutex);
-        CATerminateLEGattClient();
-        return;
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Starting LE device discovery");
-
-    ret = CABleGattStartDeviceDiscovery();
-    if (CA_STATUS_OK != ret)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "bt_adapter_le_start_device_discovery Failed");
-        ca_mutex_unlock(g_bleClientStateMutex);
-        CATerminateLEGattClient();
-        return;
-    }
-
-    g_isBleGattClientStarted = true;
-
-    ca_mutex_unlock(g_bleClientStateMutex);
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Giveing the control to threadPool");
-
-    GMainContext *thread_context = g_main_context_new();
-
-    g_eventLoop = g_main_loop_new(thread_context, FALSE);
-
-    g_main_context_push_thread_default(thread_context);
-
-    g_main_loop_run(g_eventLoop);
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-}
-
-void CAStopLEGattClient()
-{
-    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "IN");
-
-    ca_mutex_lock(g_bleClientStateMutex);
-
-    if (false == g_isBleGattClientStarted)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "Gatt Client is not running to stop");
-        ca_mutex_unlock(g_bleClientStateMutex);
-        return;
-    }
-
-    CABleGattUnSetCallbacks();
-
-    CABleGattUnWatchCharacteristicChanges();
-
-    CABleGattStopDeviceDiscovery();
-
-    g_isBleGattClientStarted = false;
-
-    GMainContext  *context_event_loop = NULL;
-    // Required for waking up the thread which is running in gmain loop
-    if (NULL != g_eventLoop)
-    {
-        context_event_loop = g_main_loop_get_context(g_eventLoop);
-    }
-    if (context_event_loop)
-    {
-        OIC_LOG_V(DEBUG,  TZ_BLE_CLIENT_TAG, "g_eventLoop context %x", context_event_loop);
-        g_main_context_wakeup(context_event_loop);
-
-        // Kill g main loops and kill threads.
-        g_main_loop_quit(g_eventLoop);
-    }
-    else
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "g_eventLoop context is NULL");
-    }
-
-    ca_mutex_unlock(g_bleClientStateMutex);
-
-    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "OUT");
-}
-
-void CATerminateLEGattClient()
-{
-    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "IN");
-    ca_mutex_lock(g_bleClientStateMutex);
-
-    ca_mutex_lock(g_bleServerBDAddressMutex);
-
-    OICFree(g_remoteAddress);
-
-    ca_mutex_unlock(g_bleServerBDAddressMutex);
-
-    ca_mutex_lock(g_bleServiceListMutex);
-    CAFreeBLEServiceList(g_bLEServiceList);
-    g_bLEServiceList = NULL;
-    ca_mutex_unlock(g_bleServiceListMutex);
-
-    CAResetRegisteredServiceCount();
-
-    ca_mutex_unlock(g_bleClientStateMutex);
-
-    CATerminateGattClientMutexVariables();
-
-    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "OUT");
-}
-
-CAResult_t CAInitGattClientMutexVariables()
-{
-    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "IN");
-    if (NULL == g_bleClientStateMutex)
-    {
-        g_bleClientStateMutex = ca_mutex_new();
-        if (NULL == g_bleClientStateMutex)
-        {
-            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "ca_mutex_new failed");
-            return CA_STATUS_FAILED;
-        }
-    }
-
-    if (NULL == g_bleServiceListMutex)
-    {
-        g_bleServiceListMutex = ca_mutex_new();
-        if (NULL == g_bleServiceListMutex)
-        {
-            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "ca_mutex_new failed");
-            return CA_STATUS_FAILED;
-        }
-    }
-
-    if (NULL == g_bleReqRespClientCbMutex)
-    {
-        g_bleReqRespClientCbMutex = ca_mutex_new();
-        if (NULL == g_bleReqRespClientCbMutex)
-        {
-            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "ca_mutex_new failed");
-            return CA_STATUS_FAILED;
-        }
-    }
-
-    if (NULL == g_bleClientThreadPoolMutex)
-    {
-        g_bleClientThreadPoolMutex = ca_mutex_new();
-        if (NULL == g_bleClientThreadPoolMutex)
-        {
-            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "ca_mutex_new failed");
-            return CA_STATUS_FAILED;
-        }
-    }
-
-    if (NULL == g_bleClientConnectMutex)
-    {
-        g_bleClientConnectMutex = ca_mutex_new();
-        if (NULL == g_bleClientConnectMutex)
-        {
-            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "ca_mutex_new failed");
-            return CA_STATUS_FAILED;
-        }
-    }
-
-    if (NULL == g_bleClientSendCondWait)
-    {
-        g_bleClientSendCondWait = ca_cond_new();
-        if (NULL == g_bleClientSendCondWait)
-        {
-            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "ca_cond_new failed");
-            return CA_STATUS_FAILED;
-        }
-    }
-
-    if (NULL == g_bleServerBDAddressMutex)
-    {
-        g_bleServerBDAddressMutex = ca_mutex_new();
-        if (NULL == g_bleServerBDAddressMutex)
-        {
-            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "ca_mutex_new failed");
-            return CA_STATUS_FAILED;
-        }
-    }
-
-    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-void CATerminateGattClientMutexVariables()
-{
-    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "IN");
-
-    ca_mutex_free(g_bleClientStateMutex);
-    g_bleClientStateMutex = NULL;
-
-    ca_mutex_free(g_bleServiceListMutex);
-    g_bleServiceListMutex = NULL;
-
-    ca_mutex_free(g_bleReqRespClientCbMutex);
-    g_bleReqRespClientCbMutex = NULL;
-
-    ca_mutex_free(g_bleClientConnectMutex);
-    g_bleClientConnectMutex = NULL;
-
-    ca_mutex_free(g_bleClientThreadPoolMutex);
-    g_bleClientThreadPoolMutex = NULL;
-
-    ca_mutex_free(g_bleServerBDAddressMutex);
-    g_bleServerBDAddressMutex = NULL;
-
-    ca_cond_free(g_bleClientSendCondWait);
-    g_bleClientSendCondWait = NULL;
-
-
-    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "OUT");
-}
-
-CAResult_t CABleGattSetScanParameter()
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    bt_adapter_le_scan_params_s scan_param = { 0, };
-    scan_param.type = BT_ADAPTER_LE_PASSIVE_SCAN;
-    scan_param.interval = 1560;
-    scan_param.window = 160;
-
-    int ret = bt_adapter_le_set_scan_parameter(&scan_param);
-    if (BT_ERROR_NONE != ret)
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "bt_adapter_le_set_scan_parameter Failed with ret [%d]", ret);
-        return CA_STATUS_FAILED;
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-CAResult_t CABleGattSetCallbacks()
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    int ret = bt_gatt_set_connection_state_changed_cb(CABleGattConnectionStateChangedCb, NULL);
-    if (BT_ERROR_NONE != ret)
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                  "bt_gatt_set_connection_state_changed_cb Failed with return as [%s ]",
-                  CABTGetErrorMsg(ret));
-        return CA_STATUS_FAILED;
-    }
-
-    ret = bt_adapter_le_set_device_discovery_state_changed_cb(
-              CABtAdapterLeDeviceDiscoveryStateChangedCb, NULL);
-    if (BT_ERROR_NONE != ret)
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                  "bt_adapter_le_set_device_discovery_state_changed_cb Failed with return as [%s ]",
-                  CABTGetErrorMsg(ret));;
-        return CA_STATUS_FAILED;
-    }
-
-    ret = bt_gatt_set_characteristic_changed_cb(CABleGattCharacteristicChangedCb, NULL);
-    if (BT_ERROR_NONE != ret)
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "bt_gatt_set_characteristic_changed_cb Failed as [%s ]",
-                  CABTGetErrorMsg(ret));
-        return CA_STATUS_FAILED;
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-void CABleGattUnSetCallbacks()
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    bt_gatt_unset_characteristic_changed_cb();
-
-    bt_gatt_unset_connection_state_changed_cb();
-
-    bt_adapter_le_unset_device_discovery_state_changed_cb();
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-}
-
-CAResult_t CABleGattWatchCharacteristicChanges(bt_gatt_attribute_h service)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    int ret = bt_gatt_watch_characteristic_changes(service);
-    if (BT_ERROR_NONE != ret)
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                  "bt_gatt_watch_characteristic_changes failed  with [%s]",
-                  CABTGetErrorMsg(ret));
-
-        return CA_STATUS_FAILED;
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-void CABleGattUnWatchCharacteristicChanges()
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    int32_t count = CAGetRegisteredServiceCount();
-
-    for (int32_t index = 0; index < count; index++)
-    {
-        BLEServiceInfo *bleServiceInfo = NULL;
-
-        ca_mutex_lock(g_bleServiceListMutex);
-
-        CAResult_t  result = CAGetBLEServiceInfoByPosition(g_bLEServiceList, index, &bleServiceInfo);
-        if (CA_STATUS_OK == result && NULL != bleServiceInfo
-            && NULL != bleServiceInfo->service_clone)
-        {
-            bt_gatt_unwatch_characteristic_changes(bleServiceInfo->service_clone);
-            OIC_LOG(INFO, TZ_BLE_CLIENT_TAG, "bt_gatt_unwatch_characteristic_changes done");
-        }
-
-        ca_mutex_unlock(g_bleServiceListMutex);
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-}
-
-CAResult_t CABleGattStartDeviceDiscovery()
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-    bool isDiscovering = false;
-
-    int ret = bt_adapter_le_is_discovering(&isDiscovering);
-    if (BT_ERROR_NONE != ret)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "bt_adapter_le_is_discovering Failed");
-        return CA_STATUS_FAILED;
-    }
-
-    if(!isDiscovering)
-    {
-        ret = bt_adapter_le_start_device_discovery();
-        if (BT_ERROR_NONE != ret)
-        {
-            OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "bt_adapter_le_start_device_discovery Failed Ret: %d, %x", ret, ret);
-            return CA_STATUS_FAILED;
-        }
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-void CABleGattStopDeviceDiscovery()
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    bool isDiscovering = false;
-
-    int ret = bt_adapter_le_is_discovering(&isDiscovering);
-    if (BT_ERROR_NONE != ret)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "bt_adapter_le_is_discovering Failed");
-        return;
-    }
-
-    if(isDiscovering)
-    {
-        ret = bt_adapter_le_stop_device_discovery();
-        if (BT_ERROR_NONE != ret)
-        {
-            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "bt_adapter_le_stop_device_discovery Failed");
-            return;
-        }
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-}
-
-void CAGattConnectThread (void *remoteAddress)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN ");
-
-    VERIFY_NON_NULL_VOID(remoteAddress, TZ_BLE_CLIENT_TAG, "remote address is NULL");
-
-    char *address  = (char *)remoteAddress;
-
-    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "remote address is [%s]", address);
-
-    CAResult_t result = CABleGattConnect(address);
-
-    if (CA_STATUS_OK != result)
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "bt_gatt_connect failed for [%s]", address);
-    }
-
-    OICFree(address);
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-}
-
-CAResult_t CABleGattConnect(const char *remoteAddress)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    VERIFY_NON_NULL_RET(remoteAddress, TZ_BLE_CLIENT_TAG,
-                        "remote address is NULL", CA_STATUS_FAILED);
-
-    //Because of the platform issue, we added. Once platform is stablized, then it will be removed
-    sleep(1);
-
-    ca_mutex_lock(g_bleClientConnectMutex);
-
-    int ret = bt_gatt_connect(remoteAddress, true);
-
-    if (BT_ERROR_NONE != ret)
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "bt_gatt_connect Failed with ret value [%s] ",
-                  CABTGetErrorMsg(ret));
-        ca_mutex_unlock(g_bleClientConnectMutex);
-        return CA_STATUS_FAILED;
-    }
-    ca_mutex_unlock(g_bleClientConnectMutex);
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-CAResult_t CABleGattDisConnect(const char *remoteAddress)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    VERIFY_NON_NULL_RET(remoteAddress, TZ_BLE_CLIENT_TAG,
-                        "remote address is NULL", CA_STATUS_FAILED);
-
-    int32_t ret = bt_gatt_disconnect(remoteAddress);
-
-    if (BT_ERROR_NONE != ret)
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "bt_gatt_disconnect Failed with ret value [%d] ",
-                  ret);
-        return CA_STATUS_FAILED;
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-void CADiscoverBLEServicesThread (void *remoteAddress)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    VERIFY_NON_NULL_VOID(remoteAddress, TZ_BLE_CLIENT_TAG, "remote address is NULL");
-
-    char *address  = (char *)remoteAddress;
-
-    CAResult_t result = CABleGattDiscoverServices(address);
-    if (CA_STATUS_OK != result)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "CABleGattDiscoverServices failed");
-    }
-
-    OICFree(address);
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT ");
-}
-
-CAResult_t CABleGattDiscoverServices(const char *remoteAddress)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    VERIFY_NON_NULL_RET(remoteAddress, TZ_BLE_CLIENT_TAG,
-                        "remote address is NULL", CA_STATUS_FAILED);
-
-    char *addr = OICStrdup(remoteAddress);
-    VERIFY_NON_NULL_RET(addr, TZ_BLE_CLIENT_TAG, "Malloc failed", CA_STATUS_FAILED);
-
-    int32_t ret = bt_gatt_foreach_primary_services(remoteAddress, CABleGattPrimaryServiceCb,
-                  (void *)addr); // addr memory will be free in callback.
-    if (BT_ERROR_NONE != ret)
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                  "bt_gatt_foreach_primary_services Failed with ret value [%d] ", ret);
-        OICFree(addr);
-        return CA_STATUS_FAILED;
-    }
-    else
-    {
-        OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
-                  "bt_gatt_foreach_primary_services success for address [%s]", remoteAddress);
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-void CADiscoverCharThread(void *stServiceInfo)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    VERIFY_NON_NULL_VOID(stServiceInfo, TZ_BLE_CLIENT_TAG, "stServiceInfo is NULL");
-
-    stGattServiceInfo_t *stTemp  = (stGattServiceInfo_t *)stServiceInfo;
-
-    VERIFY_NON_NULL_VOID(stTemp->address, TZ_BLE_CLIENT_TAG, "stTemp->address is NULL");
-
-    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "remote address [%s]", stTemp->address);
-
-    CAResult_t  result = CABleGattDiscoverCharacteristics(stTemp->serviceInfo, stTemp->address);
-    if (CA_STATUS_OK != result)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "CABleGattDiscoverCharacteristics failed!");
-        bt_gatt_destroy_attribute_handle(stTemp->serviceInfo);
-        OICFree(stTemp->address);
-        OICFree(stTemp);
-        return;
-    }
-    bt_gatt_destroy_attribute_handle(stTemp->serviceInfo);
-    OICFree(stTemp->address);
-    OICFree(stTemp);
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-}
-
-CAResult_t CABleGattDiscoverCharacteristics(bt_gatt_attribute_h service,
-        const char *remoteAddress)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    VERIFY_NON_NULL_RET(service, TZ_BLE_CLIENT_TAG, "service is NULL", CA_STATUS_FAILED);
-
-    VERIFY_NON_NULL_RET(remoteAddress, TZ_BLE_CLIENT_TAG, "remoteAddress is NULL", CA_STATUS_FAILED);
-
-    char *addr = OICStrdup(remoteAddress);
-    VERIFY_NON_NULL_RET(addr, TZ_BLE_CLIENT_TAG, "Malloc failed", CA_STATUS_FAILED);
-
-    int32_t ret = bt_gatt_discover_characteristics(service, CABleGattCharacteristicsDiscoveredCb,
-                  (void *)addr); // addr will be freed in callback.
-    if (BT_ERROR_NONE != ret)
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                  "bt_gatt_discover_characteristics failed with error [%d]", ret);
-        OICFree(addr);
-        return CA_STATUS_FAILED;
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-void CADiscoverDescriptorThread(void *stServiceInfo)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, " IN");
-
-    VERIFY_NON_NULL_VOID(stServiceInfo, TZ_BLE_CLIENT_TAG, "stServiceInfo is NULL");
-
-    stGattServiceInfo_t *stTemp  = (stGattServiceInfo_t *)stServiceInfo;
-
-    CAResult_t result = CABleGattDiscoverDescriptor(stTemp->serviceInfo, NULL);
-    if (CA_STATUS_OK != result)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG,
-                  "bt_gatt_discover_characteristic_descriptor failed");
-        bt_gatt_destroy_attribute_handle(stTemp->serviceInfo);
-        OICFree(stTemp->address);
-        OICFree(stTemp);
-        return;
-    }
-
-    bt_gatt_destroy_attribute_handle(stTemp->serviceInfo);
-    OICFree(stTemp->address);
-    OICFree(stTemp);
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-}
-
-CAResult_t CABleGattDiscoverDescriptor(bt_gatt_attribute_h service, const char *remoteAddress)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    VERIFY_NON_NULL_RET(service, TZ_BLE_CLIENT_TAG, "service is NULL", CA_STATUS_FAILED);
-
-    int ret = bt_gatt_discover_characteristic_descriptor(service,
-                  CABleGattDescriptorDiscoveredCb, NULL);
-    if (BT_ERROR_NONE != ret)
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                  "bt_gatt_discover_characteristic_descriptor failed with returns[%s]",
-                  CABTGetErrorMsg(ret));
-        return CA_STATUS_FAILED;
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-void CASetCharacteristicDescriptorValueThread(void *stServiceInfo)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    VERIFY_NON_NULL_VOID(stServiceInfo, TZ_BLE_CLIENT_TAG, "stServiceInfo is NULL");
-
-    stGattCharDescriptor_t *stTemp  = (stGattCharDescriptor_t *)stServiceInfo;
-
-    CAResult_t  result = CASetCharacteristicDescriptorValue(stTemp);
-    if (CA_STATUS_OK != result)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "CASetCharacteristicDescriptorValue failed!");
-        bt_gatt_destroy_attribute_handle(stTemp->characteristic);
-        OICFree(stTemp->desc);
-        OICFree(stTemp);
-        return;
-    }
-    bt_gatt_destroy_attribute_handle(stTemp->characteristic);
-    OICFree(stTemp->desc);
-    OICFree(stTemp);
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-}
-
-CAResult_t CASetCharacteristicDescriptorValue(stGattCharDescriptor_t *stGattCharDescInfo)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    unsigned char noti[4] = {0,};
-
-    char *strUUID = (char *)OICCalloc(5, sizeof(char));
-
-    VERIFY_NON_NULL_RET(strUUID, TZ_BLE_CLIENT_TAG, "calloc failed", CA_STATUS_FAILED);
-
-    snprintf(strUUID, 4, "%x%x", stGattCharDescInfo->desc[3], stGattCharDescInfo->desc[2]);
-    noti[0] = stGattCharDescInfo->desc[0];
-    noti[1] = stGattCharDescInfo->desc[1];
-    noti[2] = 0x01;
-    noti[3] = 0x00;
-
-    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "desc x0 [%x]", stGattCharDescInfo->desc[0]);
-    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "desc x1 [%x]", stGattCharDescInfo->desc[1]);
-    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "desc x2 [%x]", stGattCharDescInfo->desc[2]);
-    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "desc x3 [%x]", stGattCharDescInfo->desc[3]);
-
-
-    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "CA_GATT_CONFIGURATION_DESC_UUID strUUID is [%s]",
-              strUUID);
-    //if (!strncmp(strUUID, CA_GATT_CONFIGURATION_DESC_UUID, 2))
-    {
-        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "setting notification/indication for descriptor");
-
-        int ret =  bt_gatt_set_characteristic_desc_value_request(
-                           stGattCharDescInfo->characteristic,
-                           noti,  4, CABleGattCharacteristicWriteCb);
-        if (BT_ERROR_NONE != ret)
-        {
-            OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                      "bt_gatt_set_characteristic_desc_value_request failed with return[%s]",
-                      CABTGetErrorMsg(ret));
-            OICFree(strUUID);
-            return CA_STATUS_FAILED;
-        }
-    }
-    OICFree(strUUID);
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-CAResult_t  CAUpdateCharacteristicsToGattServer(const char *remoteAddress,
-        const uint8_t *data, uint32_t dataLen,
-        CALETransferType_t type, int32_t position)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
-    VERIFY_NON_NULL(data, TZ_BLE_CLIENT_TAG, "data is NULL");
-
-    if (0 >= dataLen)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "dataLen is less than or equal zero. Invalid input!");
-        return CA_STATUS_INVALID_PARAM;
-    }
-
-    BLEServiceInfo *bleServiceInfo = NULL;
-
-    CAResult_t ret =  CA_STATUS_FAILED;
-
-    ca_mutex_lock(g_bleServiceListMutex);
-    if ( LE_UNICAST == type)
-    {
-        VERIFY_NON_NULL(remoteAddress, TZ_BLE_CLIENT_TAG, "remoteAddress is NULL");
-
-        ret = CAGetBLEServiceInfo(g_bLEServiceList, remoteAddress, &bleServiceInfo);
-    }
-    else if ( LE_MULTICAST == type)
-    {
-        ret = CAGetBLEServiceInfoByPosition(g_bLEServiceList, position, &bleServiceInfo);
-    }
-    ca_mutex_unlock(g_bleServiceListMutex);
-
-    if (CA_STATUS_OK != ret)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "CAGetBLEServiceInfoByPosition is failed");
-        return CA_STATUS_FAILED;
-    }
-
-    VERIFY_NON_NULL(bleServiceInfo, TZ_BLE_CLIENT_TAG, "bleServiceInfo is NULL");
-
-    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Updating the data of length [%u] to [%s] ", dataLen,
-              bleServiceInfo->bdAddress);
-
-    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Updating to write char [%s]",
-              bleServiceInfo->read_char);
-
-    int result = bt_gatt_set_characteristic_value(bleServiceInfo->write_char, (unsigned char *)data,
-                     dataLen);
-    if (BT_ERROR_NONE != result)
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                  "bt_gatt_set_characteristic_value Failed with return val [%d]",
-                  result);
-        return CA_STATUS_FAILED;
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-CAResult_t  CAUpdateCharacteristicsToAllGattServers(const uint8_t *data,
-            uint32_t dataLen)
-{
-    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "IN");
-
-    VERIFY_NON_NULL(data, TZ_BLE_CLIENT_TAG, "data is NULL");
-
-    if (0 >= dataLen)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "dataLen is less than or equal zero. Invalid input !");
-        return CA_STATUS_INVALID_PARAM;
-    }
-
-    int numOfServersConnected = CAGetRegisteredServiceCount();
-
-    for (int32_t pos = 0; pos < numOfServersConnected; pos++)
-    {
-        /*remoteAddress will be NULL.
-          Since we have to send to all destinations. pos will be used for getting remote address.
-         */
-        CAResult_t  ret = CAUpdateCharacteristicsToGattServer(NULL, data, dataLen, LE_MULTICAST, pos);
-
-        if (CA_STATUS_OK != ret)
-        {
-            OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                      "CAUpdateCharacteristicsToGattServer Failed with return val [%d] ", ret);
-            g_clientErrorCallback(NULL, data, dataLen, ret);
-            continue;
-        }
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT ");
-    return CA_STATUS_OK;
-}
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/cableclient.h b/resource/csdk/connectivity/src/bt_le_adapter/tizen/cableclient.h
deleted file mode 100644 (file)
index d4a96fc..0000000
+++ /dev/null
@@ -1,396 +0,0 @@
-/* ****************************************************************
-*
-* Copyright 2014 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.
-*
-******************************************************************/
-
-/**
- * @file
- *
- * This file contains the functionalities of GATT Client. Functionalities
- * like LE device discovery, connecting to the LE device with OIC service,
- * registering to the service and there characteristics, registering to the
- * change in the charateristics, setting the value of the characteristcs
- * for the request and response will be done here.
- */
-
-#ifndef TZ_BLE_CLIENT_H_
-#define TZ_BLE_CLIENT_H_
-
-#include <bluetooth.h>
-#include <bluetooth_type.h>
-#include <bluetooth_product.h>
-
-#include "cacommon.h"
-#include "caadapterutils.h"
-#include "cableutil.h"
-#include "caadapterinterface.h"
-#include "logger.h"
-#include "cathreadpool.h"
-#include "caleinterface.h"
-#include "oic_malloc.h"
-
-
-/**
- * This is the callback which will be called after the characteristic
- * value changes happen.
- *
- * @param[in]  characteristic The attribute handle of characteristic.
- * @param[in]  value          Value of the characteristics of a service.
- * @param[in]  valueLen       length of data.
- * @param[in]  userData       The user data passed from the request function.
- */
-void CABleGattCharacteristicChangedCb(bt_gatt_attribute_h characteristic,
-                                      unsigned char *value,
-                                      int valueLen,
-                                      void *userData);
-/**
- * This is the callback which will be called after the characteristics changed.
- *
- * @param[in]  result   result of write value.
- * @param[in]  userData user context.
- */
-void CABleGattCharacteristicWriteCb(int result, void *userData);
-
-/**
- * This is the callback which will be called when descriptor of
- * characteristics is found.
- *
- * @param[in]  result         The result of discovering.
- * @param[in]  format         format of descriptor.
- * @param[in]  total          The total number of descriptor in a
- *                             characteristic.
- * @param[in]  descriptor     The attribute handle of descriptor.
- * @param[in]  characteristic The attribute handle of characteristic.
- * @param[in]  userData       The user data passed from the request function.
- */
-void CABleGattDescriptorDiscoveredCb(int result, unsigned char format, int total,
-                                     bt_gatt_attribute_h descriptor,
-                                     bt_gatt_attribute_h characteristic, void *userData);
-
-/**
- * This is the callback which will be called after the characteristics are
- * discovered by bt_gatt_discover_characteristics().
- *
- * @param[in]  result         The result of discovering.
- * @param[in]  inputIndex     The index of characteristics in a service,
- *                             starts from 0.
- * @param[in]  total          The total number of characteristics in a service.
- * @param[in]  characteristic The attribute handle of characteristic.
- * @param[in]  userData       The user data passed from the request function.
- *
- * @return  0 on failure and 1 on success.
- */
-bool CABleGattCharacteristicsDiscoveredCb(int result, int inputIndex, int total,
-                                          bt_gatt_attribute_h characteristic, void *userData);
-
-/**
- * This is the callback which will be called when we get the primary
- * services repeatedly.
- *
- * @param[in] service  The attribute handle of service. Unique identifier
- *                      for service.
- * @param[in] index    The current index of the service.
- * @param[in] count    Total number of services available in remote device.
- * @param[in] userData user data.
- *
- * @return  0 on failure and 1 on success.
- */
-bool CABleGattPrimaryServiceCb(bt_gatt_attribute_h service, int index, int count,
-                                   void *userData);
-
-/**
- * This is the callback which will be called whenever there is change in
- * gatt connection with server(Connected/Disconnected)
- *
- * @param[in]  result        The result of discovering.
- * @param[in]  connected     State of connection.
- * @param[in]  remoteAddress Mac address of the remote device in which we
- *                            made connection.
- * @param[in]  userData      The user data passed from the request function.
- */
-void CABleGattConnectionStateChangedCb(int result, bool connected,
-                const char *remoteAddress,void *userData);
-
-/**
- * This is the callback which will be called when the device discovery
- * state changes.
- *
- * @param[in]  result         The result of discovering.
- * @param[in]  discoveryState State of the discovery(FOUND/STARTED/ FINISHED).
- * @param[in]  discoveryInfo  Remote Device information.
- * @param[in]  userData       The user data passed from the request function.
- */
-void CABtAdapterLeDeviceDiscoveryStateChangedCb(int result,
-        bt_adapter_le_device_discovery_state_e discoveryState,
-        bt_adapter_le_device_discovery_info_s *discoveryInfo,
-        void *userData);
-
-/**
- * Used to print device information(Util method).
- * @param[in] discoveryInfo Device information structure.
- */
-void CAPrintDiscoveryInformation(const bt_adapter_le_device_discovery_info_s *discoveryInfo);
-
-/**
- * This thread will be used to initialize the Gatt Client and start device
- * discovery.
- *        1. Set scan parameters.
- *        2. Setting neccessary callbacks for connection, characteristics
- *          changed and discovery.
- *        3. Start device discovery.
- *
- * @param[in] data Currently it will be NULL(no parameter).
- */
-void CAStartBleGattClientThread(void *data);
-
-/**
- * Used to initialize all required mutex variable for Gatt Client
- * implementation.
- *
- * @return ::CA_STATUS_OK or Appropriate error code.
- * @retval ::CA_STATUS_OK  Successful.
- * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CAInitGattClientMutexVariables();
-
-/**
- * Used to terminate all required mutex variable for Gatt Client implementation.
- */
-void CATerminateGattClientMutexVariables();
-
-/**
- * Used to clear NonOICDeviceList.
- */
-void CAClearNonOICDeviceList();
-
-/**
- * Used to set scan parameter of starting discovery.
- *
- * @return ::CA_STATUS_OK or Appropriate error code.
- * @retval ::CA_STATUS_OK  Successful.
- * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CABleGattSetScanParameter();
-
-/**
- * Used to register required callbacks to BLE platform(connection,
- * discovery, etc).
- *
- * @return ::CA_STATUS_OK or Appropriate error code.
- * @retval ::CA_STATUS_OK  Successful.
- * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CABleGattSetCallbacks();
-
-/**
- * Used to unset all the registerd callbacks to BLE platform.
- */
-void CABleGattUnSetCallbacks();
-
-/**
- * Used to watch all the changes happening in characteristics of the service.
- *
- * @param[in] service The attribute handle of the service.
- *
- * @return ::CA_STATUS_OK or Appropriate error code.
- * @retval ::CA_STATUS_OK  Successful.
- * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CABleGattWatchCharacteristicChanges(bt_gatt_attribute_h service);
-
-/**
- * Used to unwatch characteristics changes using
- * bt_gatt_unwatch_characteristic_changes().
- */
-void CABleGattUnWatchCharacteristicChanges();
-
-/**
- * Used to start LE discovery for BLE  devices.
- *
- * @return ::CA_STATUS_OK or Appropriate error code.
- * @retval ::CA_STATUS_OK  Successful.
- * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CABleGattStartDeviceDiscovery();
-
-/**
- * Used to stop LE discovery for BLE  devices.
- */
-void CABleGattStopDeviceDiscovery();
-
-/**
- * This is the thread  which will be used for making gatt connection with
- * remote devices.
- * @param[in] remoteAddress MAC address of remote device to connect.
- */
-void CAGattConnectThread (void *remoteAddress);
-
-/**
- * Used to do connection with remote device.
- *
- * @param[in] remoteAddress Remote address inwhich we wants to connect with.
- *
- * @return ::CA_STATUS_OK or Appropriate error code.
- * @retval ::CA_STATUS_OK  Successful.
- * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CABleGattConnect(const char *remoteAddress);
-
-/**
- * Used to do disconnection with remote device.
- * @param[in] remoteAddress Remote address inwhich we wants to disconnect with.
- *
- * @return ::CA_STATUS_OK or Appropriate error code.
- * @retval ::CA_STATUS_OK  Successful.
- * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CABleGattDisConnect(const char *remoteAddress);
-
-/**
- * This is thread which will be spawned for discovering ble services. Once
- * called discover api, then it will be terminated.
- * @param[in] remoteAddress Mac address of the remote device in which we
- *                           want to search services.
- */
-void CADiscoverBLEServicesThread (void *remoteAddress);
-
-/**
- * Used to discover the services that is advertised by Gatt Server
- * asynchronously.
- *
- * @param[in] remoteAddress MAC address of remote device in which we want
- *                           to discover the services.
- *
- * @return ::CA_STATUS_OK or Appropriate error code.
- * @retval ::CA_STATUS_OK  Successful.
- * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CABleGattDiscoverServices(const char *remoteAddress);
-
-/**
- * This is the thread which will be used for finding characteristic of a
- * service.
- *
- * @param[in]  stServiceInfo Service Information which contains the remote
- *                            address, service handle and characteristic handle.
- */
-void CADiscoverCharThread(void *stServiceInfo);
-
-/**
- * Used to discover characteristics of service using
- * bt_gatt_discover_characteristics() api.
- *
- * @param[in] service        The attribute handle for service.
- * @param[in] remoteAddress  Remote address inwhich we wants to discover
- *                            characteristics of given service handle.
- * @return ::CA_STATUS_OK or Appropriate error code.
- * @retval ::CA_STATUS_OK  Successful.
- * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CABleGattDiscoverCharacteristics(bt_gatt_attribute_h service,
-                    const char *remoteAddress);
-
-/**
- * This is the thread which will be used for finding descriptor of
- * characteristic.
- *
- * @param[in]  stServiceInfo Service Information which contains the remote
- *                            address, service handle and characteristic handle.
- */
-void CADiscoverDescriptorThread(void *stServiceInfo);
-
-/**
- * This is thread which will be used for calling
- * CASetCharacteristicDescriptorValue() api.
- *
- * @param[in] service        The attribute handle for characteristics.
- * @param[in] remoteAddress  Remote address inwhich we wants to discover
- *                            descriptor of given char handle.
- * @return ::CA_STATUS_OK or Appropriate error code.
- * @retval ::CA_STATUS_OK  Successful.
- * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CABleGattDiscoverDescriptor(bt_gatt_attribute_h service,
-                const char *remoteAddress);
-
-/**
- * This is thread which will be used for calling
- * CASetCharacteristicDescriptorValue() api.
- *
- * @param[in]  stServiceInfo Service Information which contains the remote
- *                            address, service handle and characteristic handle.
- */
-void CASetCharacteristicDescriptorValueThread(void *stServiceInfo);
-
-/**
- * Used to set characteristic descriptor value using
- * bt_gatt_set_characteristic_desc_value_request() api.
- * @param[in]  stGattCharDescriptorInfo Structure which contains char
- *                                       handle and descriptor handle.
- *
- * @return ::CA_STATUS_OK or Appropriate error code.
- * @retval ::CA_STATUS_OK  Successful.
- * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CASetCharacteristicDescriptorValue
-            (stGattCharDescriptor_t *stGattCharDescriptorInfo);
-
-/**
- * Used to enqueue the message into sender queue using
- * CAAdapterEnqueueMessage() and make signal to the thread to process.
- *
- * @param[in]  remoteEndpoint Remote device information.
- * @param[in]  data           Data to be sent to remote device.
- * @param[in]  dataLen        Length of data..
- *
- * @return ::CA_STATUS_OK or Appropriate error code.
- * @retval ::CA_STATUS_OK  Successful.
- * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CABleClientSenderQueueEnqueueMessage
-                            (const CAEndpoint_t *remoteEndpoint,
-                                                const uint8_t *data, uint32_t dataLen);
-
-/**
- * This is the thread which will be used for processing sender queue.
- */
-void CABleClientSenderQueueProcessor();
-
-/**
- * Synchronous function for reading characteristic value.
- *
- * @return ::CA_STATUS_OK or Appropriate error code.
- * @retval ::CA_STATUS_OK  Successful.
- * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CALEReadDataFromLEClient();
-
-#endif /* TZ_BLE_CLIENT_H_ */
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/cablenwmonitor.c b/resource/csdk/connectivity/src/bt_le_adapter/tizen/cablenwmonitor.c
deleted file mode 100644 (file)
index 6d54736..0000000
+++ /dev/null
@@ -1,266 +0,0 @@
-/******************************************************************
-*
-* Copyright 2014 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 "caleinterface.h"
-
-#include<stdio.h>
-#include<stdlib.h>
-#include<string.h>
-#include<arpa/inet.h>
-#include<sys/types.h>
-#include<sys/socket.h>
-#include<netinet/in.h>
-
-#include <bluetooth.h>
-#include <bluetooth_type.h>
-#include <bluetooth_product.h>
-
-
-#include "camutex.h"
-#include "caleadapter.h"
-#include "caadapterutils.h"
-
-/**
- * @def TZ_LE_NWK_MONITOR_TAG
- * @brief Logging tag for module name
- */
-#define TZ_LE_NWK_MONITOR_TAG "TZ_BLE_ADAPTER_CONTROLLER"
-
-/**
- * @var g_bleDeviceStateChangedCallback
- * @brief Maintains the callback to be notified on device state changed.
- */
-static CALEDeviceStateChangedCallback g_bleDeviceStateChangedCallback = NULL;
-
-/**
- * @var g_bleDeviceStateChangedCbMutex
- * @brief Mutex to synchronize access to the deviceStateChanged Callback when the state
- *           of the LE adapter gets change.
- */
-static ca_mutex g_bleDeviceStateChangedCbMutex = NULL;
-
-/**
-* @fn  CALEAdapterStateChangedCb
-* @brief  This is the callback which will be called when the adapter state gets changed.
-*
-* @param result         [IN] Result of the query done to the platform.
-* @param adapter_state  [IN] State of the LE adapter.
-* @param user_data      [IN] Any user_data passed by the caller when querying for the state changed cb.
-*
-* @return  None.
-*/
-void CALEAdapterStateChangedCb(int result, bt_adapter_state_e adapter_state,
-                        void *user_data);
-
-CAResult_t CAInitializeLENetworkMonitor()
-{
-    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
-
-    CAResult_t res = CAInitLENetworkMonitorMutexVariables();
-    if (CA_STATUS_OK != res)
-    {
-        OIC_LOG(ERROR, TZ_LE_NWK_MONITOR_TAG, "CAInitLENetworkMonitorMutexVariables() failed");
-        return CA_STATUS_FAILED;
-    }
-    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
-
-    return CA_STATUS_OK;
-}
-
-void CATerminateLENetworkMonitorMutexVariables()
-{
-    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
-
-    ca_mutex_free(g_bleDeviceStateChangedCbMutex);
-    g_bleDeviceStateChangedCbMutex = NULL;
-
-    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
-}
-
-void CATerminateLENetworkMonitor()
-{
-    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
-
-    CATerminateLENetworkMonitorMutexVariables();
-
-    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
-}
-
-CAResult_t CAInitializeLEAdapter()
-{
-    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
-
-    int ret = bt_initialize();
-    if (0 != ret)
-    {
-        OIC_LOG(ERROR, TZ_LE_NWK_MONITOR_TAG, "bt_initialize failed");
-        return CA_STATUS_FAILED;
-    }
-
-    ret = bt_adapter_set_visibility(BT_ADAPTER_VISIBILITY_MODE_GENERAL_DISCOVERABLE, 0);
-    if (0 != ret)
-    {
-        OIC_LOG(ERROR, TZ_LE_NWK_MONITOR_TAG, "bt_adapter_set_visibility failed");
-        return CA_STATUS_FAILED;
-    }
-
-    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-CAResult_t CAStartLEAdapter()
-{
-    // Nothing to do.
-
-    return CA_STATUS_OK;
-}
-
-CAResult_t CAGetLEAdapterState()
-{
-    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
-
-    bt_adapter_state_e adapterState = BT_ADAPTER_DISABLED;
-
-    //Get Bluetooth adapter state
-    int ret = bt_adapter_get_state(&adapterState);
-    if (BT_ERROR_NONE != ret)
-    {
-        OIC_LOG_V(ERROR, TZ_LE_NWK_MONITOR_TAG, "Bluetooth get state failed!, error num [%x]",
-                  ret);
-        return CA_STATUS_FAILED;
-    }
-
-    if (BT_ADAPTER_ENABLED != adapterState)
-    {
-        OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "BT Adapter is not enabled");
-        return CA_ADAPTER_NOT_ENABLED;
-    }
-
-    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-CAResult_t CAGetLEAddress(char **local_address)
-{
-    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
-
-    VERIFY_NON_NULL(local_address, TZ_LE_NWK_MONITOR_TAG, "local_address is null")
-
-    char *address = NULL;
-
-    int ret = bt_adapter_get_address(&address);
-    if (BT_ERROR_NONE != ret || !address)
-    {
-        OIC_LOG_V(ERROR, TZ_LE_NWK_MONITOR_TAG, "bt_adapter_get_address failed!, error num [%x]",
-                  ret);
-        return CA_STATUS_FAILED;
-    }
-
-    OIC_LOG_V(DEBUG, TZ_LE_NWK_MONITOR_TAG, "bd address[%s]", address);
-
-    *local_address = address;
-
-    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
-
-    return CA_STATUS_OK;
-}
-
-CAResult_t CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCallback callback)
-{
-    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
-
-    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "Setting CALEDeviceStateChangedCallback");
-
-    ca_mutex_lock(g_bleDeviceStateChangedCbMutex);
-    g_bleDeviceStateChangedCallback = callback;
-    ca_mutex_unlock(g_bleDeviceStateChangedCbMutex);
-
-    int ret = bt_adapter_set_state_changed_cb(CALEAdapterStateChangedCb, NULL);
-    if (BT_ERROR_NONE != ret)
-    {
-        OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "bt_adapter_set_state_changed_cb failed");
-        return CA_STATUS_FAILED;
-    }
-
-    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-void CALEAdapterStateChangedCb(int result, bt_adapter_state_e adapter_state,
-                                          void *user_data)
-{
-    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
-
-    ca_mutex_lock(g_bleDeviceStateChangedCbMutex);
-
-    if (NULL == g_bleDeviceStateChangedCallback)
-    {
-        OIC_LOG(ERROR, TZ_LE_NWK_MONITOR_TAG, "g_bleDeviceStateChangedCallback is NULL!");
-        ca_mutex_unlock(g_bleDeviceStateChangedCbMutex);
-        return;
-    }
-
-    if (BT_ADAPTER_DISABLED == adapter_state)
-    {
-        OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "Adapter is disabled");
-        g_bleDeviceStateChangedCallback(CA_ADAPTER_DISABLED);
-        ca_mutex_unlock(g_bleDeviceStateChangedCbMutex);
-        return;
-    }
-
-    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "Adapter is Enabled");
-    g_bleDeviceStateChangedCallback(CA_ADAPTER_ENABLED);
-    ca_mutex_unlock(g_bleDeviceStateChangedCbMutex);
-
-    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
-}
-
-
-CAResult_t CAUnSetLEAdapterStateChangedCb()
-{
-    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
-
-    int ret = bt_adapter_unset_state_changed_cb();
-    if (BT_ERROR_NONE != ret)
-    {
-        OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "bt_adapter_unset_state_changed_cb failed");
-        return CA_STATUS_FAILED;
-    }
-
-    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-CAResult_t CAInitLENetworkMonitorMutexVariables()
-{
-    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
-    if (NULL == g_bleDeviceStateChangedCbMutex)
-    {
-        g_bleDeviceStateChangedCbMutex = ca_mutex_new();
-        if (NULL == g_bleDeviceStateChangedCbMutex)
-        {
-            OIC_LOG(ERROR, TZ_LE_NWK_MONITOR_TAG, "ca_mutex_new failed");
-            return CA_STATUS_FAILED;
-        }
-    }
-
-    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
-    return CA_STATUS_OK;
-}
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/cableserver.c b/resource/csdk/connectivity/src/bt_le_adapter/tizen/cableserver.c
deleted file mode 100644 (file)
index 807f1d9..0000000
+++ /dev/null
@@ -1,841 +0,0 @@
-/******************************************************************
-*
-* Copyright 2014 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 <bluetooth.h>
-#include <bluetooth_type.h>
-#include <bluetooth_product.h>
-
-#include "cableserver.h"
-#include <pthread.h>
-#include "cacommon.h"
-#include "caadapterutils.h"
-#include <gio/gio.h>
-#include "camutex.h"
-#include "caqueueingthread.h"
-#include "caadapterutils.h"
-#include "cafragmentation.h"
-#include "cagattservice.h"
-#include "cableutil.h"
-#include "oic_string.h"
-#include "oic_malloc.h"
-
-/**
- * @def TZ_BLE_SERVER_TAG
- * @brief Logging tag for module name
- */
-#define TZ_BLE_SERVER_TAG "TZ_BLE_GATT_SERVER"
-
-/**
- * @def CA_BLE_INITIAL_BUF_SIZE
- * @brief Initial buffer size for Gatt Server.
- */
-#define CA_BLE_INITIAL_BUF_SIZE 512
-
-/**
- * @var g_gattSvcPath
- * @brief attribute handler for OIC server attribute.
- */
-static char *g_gattSvcPath = NULL;
-
-/**
- * @var g_gattReadCharPath
- * @brief attribute handler for readCharacteristic of OIC server
- */
-static char *g_gattReadCharPath = NULL;
-
-/**
- * @var g_gattWriteCharPath
- * @brief attribute handler for writeCharacteristic of OIC server
- */
-static char *g_gattWriteCharPath = NULL;
-
-/**
- * @var g_hAdvertiser
- * @brief handler for OIC advertiser.
- */
-static bt_advertiser_h g_hAdvertiser = NULL;
-
-/**
- * @var    g_bleServerDataReceivedCallback
- * @brief  Maintains the callback to be notified on receival of network packets from other
- *           BLE devices
- */
-static CABLEDataReceivedCallback g_bleServerDataReceivedCallback = NULL;
-
-/**
- * @var g_serverErrorCallback
- * @brief callback to update the error to le adapter
- */
-static CABLEErrorHandleCallback g_serverErrorCallback;
-
-/**
- * @var g_isBleGattServerStarted
- * @brief Boolean variable to keep the state of the GATTServer
- */
-static bool g_isBleGattServerStarted = false;
-
-/**
- * @var g_bleServerStateMutex
- * @brief Mutex to synchronize the calls to be done to the platform from GATTServer
- *           interfaces from different threads.
- */
-static ca_mutex g_bleServerStateMutex = NULL;
-
-/**
- * @var g_bleCharacteristicMutex
- * @brief Mutex to synchronize writing operations on the characteristics.
- */
-static  ca_mutex g_bleCharacteristicMutex = NULL;
-
-/**
- * @var g_bleServiceMutex
- * @brief  Mutex to synchronize to create the OIC service..
- */
-static  ca_mutex g_bleServiceMutex = NULL;
-
-/**
- * @var g_bleReqRespCbMutex
- * @brief Mutex to synchronize access to the requestResponse callback to be called
- *           when the data needs to be sent from GATTClient.
- */
-static  ca_mutex g_bleReqRespCbMutex = NULL;
-
-/**
- * @var g_bleServerThreadPoolMutex
- * @brief Mutex to synchronize the task to be pushed to thread pool.
- */
-static ca_mutex g_bleServerThreadPoolMutex = NULL;
-
-/**
- * @var g_eventLoop
- * @brief gmainLoop to manage the threads to receive the callback from the platfrom.
- */
-static GMainLoop *g_eventLoop = NULL;
-
-/**
- * @var g_bleServerThreadPool
- * @brief reference to threadpool
- */
-static ca_thread_pool_t g_bleServerThreadPool = NULL;
-
-void CABleGattServerConnectionStateChangedCb(int result, bool connected,
-                                       const char *remoteAddress, void *userData)
-{
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
-
-    OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "CABleGattConnectionStateChangedCb result[%d]", result);
-
-    VERIFY_NON_NULL_VOID(remoteAddress, TZ_BLE_SERVER_TAG, "remote address is NULL");
-
-    if (connected)
-    {
-        OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "Connected to [%s]", remoteAddress);
-    }
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
-}
-
-CAResult_t CAStartLEGattServer()
-{
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
-
-    CAResult_t ret = CAInitGattServerMutexVariables();
-    if (CA_STATUS_OK != ret )
-    {
-        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "CAInitGattServerMutexVariables failed!");
-        CATerminateGattServerMutexVariables();
-        return CA_SERVER_NOT_STARTED;
-    }
-
-    ca_mutex_lock(g_bleServerThreadPoolMutex);
-    if (NULL == g_bleServerThreadPool)
-    {
-        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "g_bleServerThreadPool is NULL");
-        ca_mutex_unlock(g_bleServerThreadPoolMutex);
-        return CA_STATUS_FAILED;
-    }
-
-    ret = ca_thread_pool_add_task(g_bleServerThreadPool, CAStartBleGattServerThread,
-                                 NULL);
-    if (CA_STATUS_OK != ret)
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG, "ca_thread_pool_add_task failed with ret [%d]", ret);
-        ca_mutex_unlock(g_bleServerThreadPoolMutex);
-        return CA_STATUS_FAILED;
-    }
-
-    ca_mutex_unlock(g_bleServerThreadPoolMutex);
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-void CAStartBleGattServerThread(void *data)
-{
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
-    ca_mutex_lock(g_bleServerStateMutex);
-    if (true == g_isBleGattServerStarted)
-    {
-        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "Gatt Server is already running");
-        ca_mutex_unlock(g_bleServerStateMutex);
-        CATerminateLEGattServer();
-        return;
-    }
-
-    CAResult_t ret  =  CAInitBleGattService();
-    if (CA_STATUS_OK != ret )
-    {
-        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "_bt_gatt_init_service failed");
-        ca_mutex_unlock(g_bleServerStateMutex);
-        CATerminateLEGattServer();
-        return;
-    }
-
-    sleep(5); // Sleep is must because of the platform issue.
-
-    char *serviceUUID = CA_GATT_SERVICE_UUID;
-
-    ret  = CAAddNewBleServiceInGattServer(serviceUUID);
-    if (CA_STATUS_OK != ret )
-    {
-        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "CAAddNewBleServiceInGattServer failed");
-        ca_mutex_unlock(g_bleServerStateMutex);
-        CATerminateLEGattServer();
-        return;
-    }
-
-    static const char charReadUUID[] = CA_GATT_RESPONSE_CHRC_UUID;
-    uint8_t charReadValue[] = {33, 44, 55, 66}; // These are initial random values
-
-    ret = CAAddNewCharacteristicsToGattServer(g_gattSvcPath, charReadUUID, charReadValue,
-            CA_BLE_INITIAL_BUF_SIZE, true); // For Read Characteristics.
-    if (CA_STATUS_OK != ret )
-    {
-        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "CAAddNewCharacteristicsToGattServer failed");
-        ca_mutex_unlock(g_bleServerStateMutex);
-        CATerminateLEGattServer();
-        return;
-    }
-
-    static const char charWriteUUID[] = CA_GATT_REQUEST_CHRC_UUID;
-    uint8_t charWriteValue[] = {33, 44, 55, 66}; // These are initial random values
-
-
-    ret = CAAddNewCharacteristicsToGattServer(g_gattSvcPath, charWriteUUID, charWriteValue,
-            CA_BLE_INITIAL_BUF_SIZE, false); // For Write Characteristics.
-    if (CA_STATUS_OK != ret )
-    {
-        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "CAAddNewCharacteristicsToGattServer failed");
-        ca_mutex_unlock(g_bleServerStateMutex);
-        CATerminateLEGattServer();
-        return;
-    }
-
-    ret = CARegisterBleServicewithGattServer(g_gattSvcPath);
-    if (CA_STATUS_OK != ret )
-    {
-        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "CARegisterBleServicewithGattServer failed");
-        ca_mutex_unlock(g_bleServerStateMutex);
-        CATerminateLEGattServer();
-        return;
-    }
-
-    int res = bt_gatt_set_connection_state_changed_cb(CABleGattServerConnectionStateChangedCb,
-                                                          NULL);
-    if (BT_ERROR_NONE != res)
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG,
-                  "bt_gatt_set_connection_state_changed_cb Failed with return as [%s]",
-                  CABTGetErrorMsg(res));
-        return;
-    }
-
-    bt_adapter_le_create_advertiser(&g_hAdvertiser);
-    if (NULL == g_hAdvertiser)
-    {
-        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "g_hAdvertiser is NULL");
-        ca_mutex_unlock(g_bleServerStateMutex);
-        CATerminateLEGattServer();
-        return;
-    }
-
-    res = bt_adapter_le_start_advertising(g_hAdvertiser, NULL, NULL, NULL);
-    if (BT_ERROR_NONE != res)
-    {
-        OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "bt_adapter_le_start_advertising failed with ret [%d] ",
-                  res);
-        ca_mutex_unlock(g_bleServerStateMutex);
-        CATerminateLEGattServer();
-        return;
-    }
-
-    g_isBleGattServerStarted = true;
-
-    ca_mutex_unlock(g_bleServerStateMutex);
-
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG,
-            "LE Server initialization complete.");
-
-    GMainContext *thread_context = NULL;
-
-    thread_context = g_main_context_new();
-
-    g_eventLoop = g_main_loop_new(thread_context, FALSE);
-
-    g_main_context_push_thread_default(thread_context);
-
-    g_main_loop_run(g_eventLoop);
-
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
-}
-
-CAResult_t CAStopLEGattServer()
-{
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
-
-    ca_mutex_lock(g_bleServerStateMutex);
-
-    if (false == g_isBleGattServerStarted)
-    {
-        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "Gatt Server is not running to stop");
-
-        ca_mutex_unlock(g_bleServerStateMutex);
-        return CA_STATUS_OK;
-    }
-
-    g_isBleGattServerStarted = false;
-    if (NULL != g_hAdvertiser )
-    {
-        int ret = 0;
-        ret  = bt_adapter_le_stop_advertising(g_hAdvertiser);
-        if (0 != ret)
-        {
-            OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG,
-                      "bt_adapter_le_stop_advertising failed with ret [%d]", ret);
-        }
-
-        ret = bt_adapter_le_destroy_advertiser(g_hAdvertiser);
-        if (0 != ret)
-        {
-            OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG,
-                      "bt_adapter_le_destroy_advertiser failed with ret [%d]", ret);
-        }
-        g_hAdvertiser = NULL;
-    }
-
-    CAResult_t res = CARemoveAllBleServicesFromGattServer();
-    if (CA_STATUS_OK != res)
-    {
-        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "removeAllBleServicesFromGattServer failed");
-    }
-
-    res =  CADeInitBleGattService();
-    if (CA_STATUS_OK != res)
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG, "_bt_gatt_deinit_service failed with ret [%d]", res);
-    }
-
-    GMainContext  *context_event_loop = NULL;
-    // Required for waking up the thread which is running in gmain loop
-    if (NULL != g_eventLoop)
-    {
-        context_event_loop = g_main_loop_get_context(g_eventLoop);
-
-        if (context_event_loop)
-        {
-            OIC_LOG_V(DEBUG,  TZ_BLE_SERVER_TAG, "g_eventLoop context %x", context_event_loop);
-            g_main_context_wakeup(context_event_loop);
-
-            // Kill g main loops and kill threads
-            g_main_loop_quit(g_eventLoop);
-        }
-    }
-    else
-    {
-        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "g_eventLoop context is NULL");
-    }
-
-    ca_mutex_unlock(g_bleServerStateMutex);
-
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-void CATerminateLEGattServer()
-{
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
-
-    ca_mutex_lock(g_bleServerStateMutex);
-
-    // free service Path(unique identifier for ble service)
-    ca_mutex_lock(g_bleServiceMutex);
-    OICFree(g_gattSvcPath);
-    g_gattSvcPath = NULL;
-    ca_mutex_unlock(g_bleServiceMutex);
-
-    // freeing characteristics
-    ca_mutex_lock(g_bleCharacteristicMutex);
-    OICFree(g_gattReadCharPath);
-    g_gattReadCharPath = NULL;
-    OICFree(g_gattWriteCharPath);
-    g_gattWriteCharPath = NULL;
-    ca_mutex_unlock(g_bleCharacteristicMutex);
-
-    ca_mutex_unlock(g_bleServerStateMutex);
-
-    // Terminating all mutex variables.
-    CATerminateGattServerMutexVariables();
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
-}
-
-CAResult_t CAInitGattServerMutexVariables()
-{
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
-    if (NULL == g_bleServerStateMutex)
-    {
-        g_bleServerStateMutex = ca_mutex_new();
-        if (NULL == g_bleServerStateMutex)
-        {
-            OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "ca_mutex_new failed");
-            return CA_STATUS_FAILED;
-        }
-    }
-
-    if (NULL == g_bleServiceMutex)
-    {
-        g_bleServiceMutex = ca_mutex_new();
-        if (NULL == g_bleServiceMutex)
-        {
-            OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "ca_mutex_new failed");
-            return CA_STATUS_FAILED;
-        }
-    }
-
-    if (NULL == g_bleCharacteristicMutex)
-    {
-        g_bleCharacteristicMutex = ca_mutex_new();
-        if (NULL == g_bleCharacteristicMutex)
-        {
-            OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "ca_mutex_new failed");
-            return CA_STATUS_FAILED;
-        }
-    }
-
-    if (NULL == g_bleReqRespCbMutex)
-    {
-        g_bleReqRespCbMutex = ca_mutex_new();
-        if (NULL == g_bleReqRespCbMutex)
-        {
-            OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "ca_mutex_new failed");
-            return CA_STATUS_FAILED;
-        }
-    }
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-void CATerminateGattServerMutexVariables()
-{
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
-    ca_mutex_free(g_bleServerStateMutex);
-    g_bleServerStateMutex = NULL;
-
-
-    g_bleServerStateMutex = NULL;
-    ca_mutex_free(g_bleServiceMutex);
-    g_bleServiceMutex = NULL;
-    ca_mutex_free(g_bleCharacteristicMutex);
-    g_bleCharacteristicMutex = NULL;
-    ca_mutex_free(g_bleReqRespCbMutex);
-    g_bleReqRespCbMutex = NULL;
-
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
-}
-
-CAResult_t CAInitBleGattService()
-{
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
-
-    int ret =  _bt_gatt_init_service();
-    if (0 != ret)
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG, "_bt_gatt_deinit_service failed with ret [%d]", ret);
-        return CA_STATUS_FAILED;
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-CAResult_t CADeInitBleGattService()
-{
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
-
-    int ret =  _bt_gatt_deinit_service();
-    if (0 != ret)
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG, "_bt_gatt_deinit_service failed with ret [%d]", ret);
-        return CA_STATUS_FAILED;
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-void CASetLEServerThreadPoolHandle(ca_thread_pool_t handle)
-{
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
-    ca_mutex_lock(g_bleServerThreadPoolMutex);
-    g_bleServerThreadPool = handle;
-    ca_mutex_unlock(g_bleServerThreadPoolMutex);
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
-}
-
-CAResult_t CAAddNewBleServiceInGattServer(const char *serviceUUID)
-{
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
-
-    VERIFY_NON_NULL(serviceUUID, TZ_BLE_SERVER_TAG, "Param serviceUUID is NULL");
-
-    OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "service uuid %s", serviceUUID);
-
-    char *svcPath = NULL;
-
-    int ret = bt_gatt_add_service(serviceUUID, &svcPath);
-    if (0 != ret)
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG, "bt_gatt_add_service failed with ret [%d]", ret);
-        return CA_STATUS_FAILED;
-    }
-
-    if (NULL != svcPath)
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG,
-                  "AddNewBleServiceInGattServer ServicePath obtained is %s", svcPath);
-
-        ca_mutex_lock(g_bleServiceMutex);
-
-        if (NULL != g_gattSvcPath)
-        {
-            OICFree(g_gattSvcPath);
-            g_gattSvcPath = NULL;
-        }
-        g_gattSvcPath = svcPath;
-
-        ca_mutex_unlock(g_bleServiceMutex);
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-CAResult_t CARemoveBleServiceFromGattServer(const char *svcPath)
-{
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
-
-    VERIFY_NON_NULL(svcPath, TZ_BLE_SERVER_TAG, "Param svcPath is NULL");
-
-    int ret = bt_gatt_remove_service(svcPath);
-
-    if (0 != ret)
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG, "bt_gatt_remove_service failed [%d]", ret);
-        return CA_STATUS_FAILED;
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-CAResult_t CARemoveAllBleServicesFromGattServer()
-{
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
-    int ret = bt_gatt_delete_services();
-    if (0 != ret)
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG, "bt_gatt_delete_services  failed with ret [%d]", ret);
-        return CA_STATUS_FAILED;
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-void CABleGattRemoteCharacteristicWriteCb(char *charPath,
-                                          unsigned char *charValue,
-                                          int charValueLen,
-                                          const char *remoteAddress,
-                                          void *userData)
-{
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
-
-    if (NULL == charPath || NULL == charValue || NULL == remoteAddress)
-    {
-        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "Param callback values are NULL");
-        return;
-    }
-
-    OIC_LOG_V(DEBUG,
-              TZ_BLE_SERVER_TAG,
-              "charPath = [%s] charValue = [%p] len [%d]",
-              charPath,
-              charValue,
-              charValueLen);
-
-    uint8_t *data = OICMalloc(charValueLen);
-    if (NULL == data)
-    {
-        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "Malloc failed!");
-        return;
-    }
-
-    memcpy(data, charValue, charValueLen);
-
-    ca_mutex_lock(g_bleReqRespCbMutex);
-    if (NULL == g_bleServerDataReceivedCallback)
-    {
-        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "gReqRespCallback is NULL!");
-        ca_mutex_unlock(g_bleReqRespCbMutex);
-        OICFree(data);
-        return;
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "Sending data up !");
-    uint32_t sentLength = 0;
-    g_bleServerDataReceivedCallback(remoteAddress, data, charValueLen,
-                                    &sentLength);
-
-    ca_mutex_unlock(g_bleReqRespCbMutex);
-
-    OICFree(data);
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
-}
-
-CAResult_t CARegisterBleServicewithGattServer(const char *svcPath)
-{
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
-
-    VERIFY_NON_NULL(svcPath, TZ_BLE_SERVER_TAG, "Param svcPath is NULL");
-
-    OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "svcPath:%s", svcPath);
-
-    int ret = bt_gatt_register_service(svcPath, CABleGattRemoteCharacteristicWriteCb, NULL);
-
-    if (0 != ret)
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG, "bt_gatt_register_service failed with ret [%d]", ret);
-        return CA_STATUS_FAILED;
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-CAResult_t CAAddNewCharacteristicsToGattServer(const char *svcPath, const char *charUUID,
-        const uint8_t *charValue, int charValueLen, bool read)
-{
-
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
-
-    const char *charFlags[1];
-    if(read)
-    {
-        charFlags[0] = "notify";
-    }
-    else
-    {
-        charFlags[0] = "write-without-response";
-    }
-
-    size_t flagLen = sizeof(charFlags) / sizeof(charFlags[0]);
-
-    char *charPath = NULL;
-    int ret =
-        bt_gatt_add_characteristic(charUUID,
-                                   (const char *) charValue,
-                                   charValueLen,
-                                   charFlags,
-                                   flagLen,
-                                   svcPath,
-                                   &charPath);
-
-    if (0 != ret || NULL == charPath)
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG,
-                  "bt_gatt_add_characteristic  failed with ret [%d]", ret);
-        return CA_STATUS_FAILED;
-    }
-
-    OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG,
-              "bt_gatt_add_characteristic charPath obtained: %s", charPath);
-
-    ca_mutex_lock(g_bleCharacteristicMutex);
-
-    if (read)
-    {
-        if (NULL != g_gattReadCharPath)
-        {
-            OICFree(g_gattReadCharPath);
-            g_gattReadCharPath = NULL;
-        }
-        g_gattReadCharPath = charPath;
-
-    }
-    else
-    {
-        if (NULL != g_gattWriteCharPath)
-        {
-            OICFree(g_gattWriteCharPath);
-            g_gattWriteCharPath = NULL;
-        }
-        g_gattWriteCharPath = charPath;
-    }
-
-    ca_mutex_unlock(g_bleCharacteristicMutex);
-
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-CAResult_t CARemoveCharacteristicsFromGattServer(const char *charPath)
-{
-    ///TODO: There is no api provided in bluetooth.h for removing characteristics.
-    return CA_STATUS_OK;
-}
-
-CAResult_t CAUpdateCharacteristicsToGattClient(const char *address,
-                                               const uint8_t *charValue,
-                                               uint32_t charValueLen)
-{
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
-
-    VERIFY_NON_NULL(charValue, TZ_BLE_SERVER_TAG, "Param charValue is NULL");
-
-    VERIFY_NON_NULL(address, TZ_BLE_SERVER_TAG, "Param address is NULL");
-
-    OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "Client's Unicast address for sending data [%s]", address);
-
-    ca_mutex_lock(g_bleCharacteristicMutex);
-
-    if (NULL  == g_gattReadCharPath)
-    {
-        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "g_gattReadCharPath is NULL");
-        ca_mutex_unlock(g_bleCharacteristicMutex);
-        return CA_STATUS_FAILED;
-    }
-
-    char *data = OICCalloc(charValueLen, 1);
-    if (NULL == data)
-    {
-        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "malloc failed!");
-        ca_mutex_unlock(g_bleCharacteristicMutex);
-        return CA_STATUS_FAILED;
-    }
-
-    memcpy(data, charValue, charValueLen);   // Binary data
-
-    OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "updating characteristics char [%s] data [%p] dataLen [%u]",
-              (const char *)g_gattReadCharPath, data, charValueLen);
-
-    int ret =
-        bt_gatt_update_characteristic(g_gattReadCharPath,
-                                      data,
-                                      charValueLen,
-                                      address);
-    if (0 != ret)
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG,
-                  "bt_gatt_update_characteristic failed with return [%d]", ret);
-        OICFree(data);
-        ca_mutex_unlock(g_bleCharacteristicMutex);
-        return CA_STATUS_FAILED;
-    }
-
-    OICFree(data);
-    ca_mutex_unlock(g_bleCharacteristicMutex);
-
-    OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-CAResult_t CAUpdateCharacteristicsToAllGattClients(const uint8_t *charValue, uint32_t charValueLen)
-{
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
-
-    VERIFY_NON_NULL(charValue, TZ_BLE_SERVER_TAG, "Param charValue is NULL");
-
-    ca_mutex_lock(g_bleCharacteristicMutex);
-
-    if (NULL  == g_gattReadCharPath)
-    {
-        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "g_gattReadCharPath is NULL");
-        ca_mutex_unlock(g_bleCharacteristicMutex);
-        return CA_STATUS_FAILED;
-    }
-
-    char *data = OICMalloc(charValueLen);
-    if (NULL == data)
-    {
-        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "malloc failed!");
-        ca_mutex_unlock(g_bleCharacteristicMutex);
-        return CA_STATUS_FAILED;
-    }
-
-    memcpy(data, charValue, charValueLen);   // Binary data
-
-    OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "updating characteristics char [%s] data [%p] dataLen [%u]",
-              (const char *)g_gattReadCharPath, data, charValueLen);
-
-    int ret =
-        bt_gatt_update_characteristic(g_gattReadCharPath,
-                                      data,
-                                      charValueLen,
-                                      NULL);
-    if (0 != ret)
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG,
-                  "bt_gatt_update_characteristic failed with return [%d]", ret);
-        OICFree(data);
-        ca_mutex_unlock(g_bleCharacteristicMutex);
-        return CA_STATUS_FAILED;
-    }
-
-    OICFree(data);
-    ca_mutex_unlock(g_bleCharacteristicMutex);
-
-    OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-void CASetLEReqRespServerCallback(CABLEDataReceivedCallback callback)
-{
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
-
-    ca_mutex_lock(g_bleReqRespCbMutex);
-
-    g_bleServerDataReceivedCallback = callback;
-
-    ca_mutex_unlock(g_bleReqRespCbMutex);
-
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
-}
-
-void CASetBLEServerErrorHandleCallback(CABLEErrorHandleCallback callback)
-{
-    g_serverErrorCallback = callback;
-}
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/cableserver.h b/resource/csdk/connectivity/src/bt_le_adapter/tizen/cableserver.h
deleted file mode 100644 (file)
index f8bd414..0000000
+++ /dev/null
@@ -1,219 +0,0 @@
-/* ****************************************************************
- *
- * Copyright 2014 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.
- *
- ******************************************************************/
-
-/**
- * @file
- *
- * This file contains the APIs related to the GATT Server functionalities.
- * Creation of the GattServer with the characteristics. Enabling the
- * advertisement and updating the characteristics for the response and
- * notifying the change of characteristcs for the request will be done here.
- * LE adapter will interact with this sub module.
- */
-
-#ifndef TZ_BLE_SERVER_H_
-#define TZ_BLE_SERVER_H_
-
-#include "caadapterinterface.h"
-#include "logger.h"
-#include "cathreadpool.h"
-#include "caleinterface.h"
-
-/**
- * This is thread which will be used for creating ble service and advertise ble service.
- * 1. Create New OIC Service 2. Add two read & write characteristics to service.
- * 3. Register Service     4. Advertise service.
- *
- * @param[in] data  Currently it will be NULL.
- */
-void CAStartBleGattServerThread(void *data);
-
-/**
- * Used to initialize gatt service using _bt_gatt_init_service api.
- *
- * @return  ::CA_STATUS_OK or Appropriate error code.
- * @retval  ::CA_STATUS_OK  Successful.
- * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval  ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CAInitBleGattService();
-
-/**
- * Used to de-initialize gatt service using _bt_gatt_deinit_service api.
- *
- * @return  ::CA_STATUS_OK or Appropriate error code.
- * @retval  ::CA_STATUS_OK  Successful.
- * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval  ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CADeInitBleGattService();
-
-/**
- * Used to initialize all required mutex variables for GATT server implementation.
- *
- * @return  ::CA_STATUS_OK or Appropriate error code.
- * @retval  ::CA_STATUS_OK  Successful.
- * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval  ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CAInitGattServerMutexVariables();
-
-
-/**
- * Used to terminate all required mutex variables for GATT server implementation.
- */
-void CATerminateGattServerMutexVariables();
-
-/**
- * Used to add new OIC service in GATT server using bt_gatt_add_service api and
- * internally store service path(outparam) in global variable.
- *
- * @param[in]  serviceUUID  unique identifier for BLE OIC service.
- *
- * @return  ::CA_STATUS_OK or Appropriate error code.
- * @retval  ::CA_STATUS_OK  Successful.
- * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval  ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CAAddNewBleServiceInGattServer(const char *serviceUUID);
-
-/**
- * Used to remove already registered service from Gatt Server using
- * bt_gatt_remove_service api.
- * @param[in] svcPath  unique identifier for BLE OIC service which is outparam of
- *                     bt_gatt_add_service api.
- * @return  ::CA_STATUS_OK or Appropriate error code.
- * @retval  ::CA_STATUS_OK  Successful.
- * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval  ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CARemoveBleServiceFromGattServer(const char *svcPath);
-
-/**
- * Used to remove all the registered service from Gatt Server using
- * bt_gatt_delete_services api.
- * @return  ::CA_STATUS_OK or Appropriate error code.
- * @retval  ::CA_STATUS_OK  Successful.
- * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval  ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CARemoveAllBleServicesFromGattServer();
-
-/**
- * Used to register the service in Gatt Server using bt_gatt_register_service api.
- *
- * @param[in] svcPath  unique identifier for BLE OIC service which is outparam of
- *                     bt_gatt_add_service api.
- * @return  ::CA_STATUS_OK or Appropriate error code.
- * @retval  ::CA_STATUS_OK  Successful.
- * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval  ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CARegisterBleServicewithGattServer(const char *svcPath);
-
-/**
- * Used to add new characteristics(Read/Write) to the service in Gatt Server using
- * bt_gatt_add_characteristic api.
- * @param[in] svcPath         Service path to which this characteristic belongs to.
- * @param[in] charUUID        Gatt characteristic uuid.
- * @param[in] charValue       Gatt characteristic value.
- * @param[in] charValueLen    Characteristic value length.
- * @param[in] read            Boolean variable for checking whether read characteristics or
- *                            write characteristics.
- * @return  ::CA_STATUS_OK or Appropriate error code.
- */
-CAResult_t CAAddNewCharacteristicsToGattServer(const char *svcPath, const char *charUUID,
-                                               const uint8_t *charValue, int charValueLen,
-                                               bool read);
-
-/**
- * Used to remove characteristics(Read/Write) from the service in Gatt Server.
- *
- * @param[in]  charPath   Characteristic path registered on the interface and unique identifier
- *                        for added characteristics.
- *
- * @return  ::CA_STATUS_OK or Appropriate error code.
- * @retval  ::CA_STATUS_OK  Successful.
- * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval  ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CARemoveCharacteristicsFromGattServer(const char *charPath);
-
-/**
- * This is the callback which will be called when client update one of the characteristics
- * with data.
- * @param[in]  charPath       characteristic path registered on the interface and unique
- *                            identifier for added characteristics.
- * @param[in]  charValue      data which is send by client.
- * @param[in]  charValueLen   length of the data.
- * @param[in]  remoteAddress  remote device bluetooth address in which data is received.
- * @param[in]  userData       user data.
-
- */
-void CABleGattRemoteCharacteristicWriteCb(char *charPath, unsigned char *charValue,
-                                          int charValueLen, const char  *remoteAddress,
-                                          void *userData);
-
-/**
- * This is the callback which will be called whenever there is change in gatt connection
- * with Client(Connected/Disconnected).
- *
- * @param[in]  result         The result of discovering.
- * @param[in]  connected      State of connection.
- * @param[in]  remoteAddress  Mac address of the remote device in which we made connection.
- * @param[in]  userData       The user data passed from the request function.
-
- */
-void CABleGattServerConnectionStateChangedCb(int result, bool connected,
-                                             const char *remoteAddress, void *userData);
-
-/**
- * Synchronous function for reading characteristic value.
- *
- * @return  ::CA_STATUS_OK or Appropriate error code.
- * @retval  ::CA_STATUS_OK  Successful.
- * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval  ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CALEReadDataFromLEServer();
-
-/**
- * Used to enqueue the message into sender queue using CAAdapterEnqueueMessage and make
- * signal to the thread to process.
- *
- * @param[in]  remoteEndpoint  Remote device information.
- * @param[in]  data            Data to be sent to remote device.
- * @param[in]  dataLen         Length of data.
- *
- * @return  ::CA_STATUS_OK or Appropriate error code.
- * @retval  ::CA_STATUS_OK  Successful.
- * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval  ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CABleServerSenderQueueEnqueueMessage
-                (const CAEndpoint_t *remoteEndpoint, const uint8_t *data, uint32_t dataLen);
-
-/**
- * This is the thread which will be used for processing receiver queue.
- */
-void *CABleServerSenderQueueProcessor();
-
-#endif /* TZ_BLE_SERVER_H_ */
-
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/cableutil.c b/resource/csdk/connectivity/src/bt_le_adapter/tizen/cableutil.c
deleted file mode 100644 (file)
index a2e4ff6..0000000
+++ /dev/null
@@ -1,446 +0,0 @@
-/******************************************************************
-*
-* Copyright 2014 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 "cableutil.h"
-
-#include<stdio.h>
-#include<stdlib.h>
-#include<string.h>
-#include<arpa/inet.h>
-#include<sys/types.h>
-#include<sys/socket.h>
-#include<netinet/in.h>
-
-
-#include "caadapterutils.h"
-#include "cagattservice.h"
-#include "oic_string.h"
-#include "oic_malloc.h"
-
-/**
- * @def TZ_BLE_CLIENT_UTIL_TAG
- * @brief Logging tag for module name
- */
-#define TZ_BLE_CLIENT_UTIL_TAG "TZ_BLE_GATT_CLIENT_UTIL"
-
-/**
- * @var g_numberOfServiceConnected
- * @brief Number of services connected.
- */
-static int32_t g_numberOfServiceConnected = 0;
-
-void CAIncrementRegisteredServiceCount()
-{
-    g_numberOfServiceConnected++;
-}
-
-void CADecrementRegisteredServiceCount()
-{
-    g_numberOfServiceConnected--;
-}
-
-void CAResetRegisteredServiceCount()
-{
-    g_numberOfServiceConnected = 0;
-}
-
-int32_t  CAGetRegisteredServiceCount()
-{
-    return g_numberOfServiceConnected ;
-}
-
-CAResult_t CACreateBLEServiceInfo(const char *bdAddress, bt_gatt_attribute_h service,
-                                  BLEServiceInfo **bleServiceInfo)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
-
-    VERIFY_NON_NULL(bdAddress, TZ_BLE_CLIENT_UTIL_TAG, "Param bdAddress is NULL");
-    VERIFY_NON_NULL(service, TZ_BLE_CLIENT_UTIL_TAG, "Param service is NULL");
-    VERIFY_NON_NULL(bleServiceInfo, TZ_BLE_CLIENT_UTIL_TAG, "Param bleServiceInfo is NULL");
-
-    *bleServiceInfo = (BLEServiceInfo *) OICCalloc(1, sizeof(BLEServiceInfo));
-    if (NULL == *bleServiceInfo)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "Malloc failed!");
-        return CA_STATUS_FAILED;
-    }
-
-    (*bleServiceInfo)->bdAddress = OICStrdup(bdAddress);
-
-    if (NULL == (*bleServiceInfo)->bdAddress)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "Malloc failed!");
-        OICFree(*bleServiceInfo);
-        return CA_STATUS_FAILED;
-    }
-
-    if (service)
-    {
-        int32_t ret = bt_gatt_clone_attribute_handle(&((*bleServiceInfo)->service_clone), service);
-
-        if (BT_ERROR_NONE != ret)
-        {
-            OIC_LOG_V(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "service handle clone failed with ret [%d]",
-                      ret);
-            OICFree((*bleServiceInfo)->bdAddress);
-            OICFree(*bleServiceInfo);
-            return CA_STATUS_FAILED;
-        }
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "OUT");
-
-    return CA_STATUS_OK;
-}
-
-CAResult_t CAAppendBLECharInfo( bt_gatt_attribute_h characteristic, CHAR_TYPE type,
-                                BLEServiceInfo *bleServiceInfo)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
-
-    VERIFY_NON_NULL(characteristic, TZ_BLE_CLIENT_UTIL_TAG, "Param characteristic is NULL");
-    VERIFY_NON_NULL(bleServiceInfo, TZ_BLE_CLIENT_UTIL_TAG, "Param bleServiceInfo is NULL");
-
-    if (BLE_GATT_READ_CHAR == type )
-    {
-        int ret = bt_gatt_clone_attribute_handle(&((bleServiceInfo)->read_char),
-            characteristic);
-        if (BT_ERROR_NONE != ret)
-        {
-            OIC_LOG_V(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "read_char clone failed with ret [%d]",
-                      ret);
-            return CA_STATUS_FAILED;
-        }
-    }
-    else  if (BLE_GATT_WRITE_CHAR == type)
-    {
-        int ret = bt_gatt_clone_attribute_handle(&((bleServiceInfo)->write_char),
-            characteristic);
-        if (BT_ERROR_NONE != ret)
-        {
-            OIC_LOG_V(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "write_char clone failed with ret [%d]",
-                      ret);
-            return CA_STATUS_FAILED;
-        }
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "OUT");
-
-    return CA_STATUS_OK;
-}
-
-CAResult_t CAAddBLEServiceInfoToList(BLEServiceList **serviceList,
-    BLEServiceInfo *bleServiceInfo)
-{
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
-
-    VERIFY_NON_NULL(serviceList, TZ_BLE_CLIENT_UTIL_TAG, "Param serviceList is NULL");
-    VERIFY_NON_NULL(bleServiceInfo, TZ_BLE_CLIENT_UTIL_TAG, "Param bleServiceInfo is NULL");
-
-    BLEServiceList *node = (BLEServiceList *) OICCalloc(1, sizeof(BLEServiceList));
-    if (NULL == node)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "Malloc failed!");
-        return CA_STATUS_FAILED;
-    }
-
-    node->serviceInfo = bleServiceInfo;
-    node->next = NULL;
-
-    if (*serviceList == NULL)   // Empty list
-    {
-        *serviceList = node;
-    }
-    else     // Add at front end
-    {
-        node->next = *serviceList;
-        *serviceList = node;
-    }
-
-    CAIncrementRegisteredServiceCount();
-
-    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "Device [%s] added to list",
-        bleServiceInfo->bdAddress);
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "OUT");
-
-    return CA_STATUS_OK;
-}
-
-CAResult_t CARemoveBLEServiceInfoToList(BLEServiceList **serviceList,
-                                        BLEServiceInfo *bleServiceInfo,
-                                        const char *bdAddress)
-{
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
-
-    VERIFY_NON_NULL(serviceList, TZ_BLE_CLIENT_UTIL_TAG, "Param serviceList is NULL");
-    VERIFY_NON_NULL(*serviceList, TZ_BLE_CLIENT_UTIL_TAG, "Param *serviceList is NULL");
-    VERIFY_NON_NULL(bdAddress, TZ_BLE_CLIENT_UTIL_TAG, "Param bdAddress is NULL");
-
-    BLEServiceList *prev = NULL;
-    BLEServiceList *cur = *serviceList;
-    while (cur != NULL)
-    {
-        if (!strcasecmp(cur->serviceInfo->bdAddress, bdAddress))
-        {
-            if (cur == *serviceList)
-            {
-                *serviceList = cur->next;
-
-                cur->next = NULL;
-                CAFreeBLEServiceList(cur);
-                CADecrementRegisteredServiceCount();
-                OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "OUT");
-                return CA_STATUS_OK;
-            }
-            else
-            {
-                prev->next = cur->next;
-
-                cur->next = NULL;
-                CAFreeBLEServiceList(cur);
-                CADecrementRegisteredServiceCount();
-                OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "OUT");
-                return CA_STATUS_OK;
-            }
-        }
-        else
-        {
-            prev = cur;
-            cur = cur->next;
-        }
-    }
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, " OUT");
-    return CA_STATUS_FAILED;
-}
-
-CAResult_t CAGetBLEServiceInfo(BLEServiceList *serviceList, const char *bdAddress,
-                               BLEServiceInfo **bleServiceInfo)
-{
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
-
-    VERIFY_NON_NULL(serviceList, TZ_BLE_CLIENT_UTIL_TAG, "Param serviceList is NULL");
-    VERIFY_NON_NULL(bleServiceInfo, TZ_BLE_CLIENT_UTIL_TAG, "Param bleServiceInfo is NULL");
-    VERIFY_NON_NULL(bdAddress, TZ_BLE_CLIENT_UTIL_TAG, "Param bdAddress is NULL");
-
-
-    BLEServiceList *cur = serviceList;
-    *bleServiceInfo = NULL;
-    while (cur != NULL)
-    {
-        if (!strcasecmp(cur->serviceInfo->bdAddress, bdAddress))
-        {
-            *bleServiceInfo = cur->serviceInfo;
-            OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "OUT");
-            return CA_STATUS_OK;
-        }
-
-        cur = cur->next;
-    }
-
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, " OUT");
-    return CA_STATUS_FAILED;
-}
-
-CAResult_t CAGetBLEServiceInfoByPosition(BLEServiceList *serviceList, int32_t position,
-        BLEServiceInfo **bleServiceInfo)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
-
-    VERIFY_NON_NULL(serviceList, TZ_BLE_CLIENT_UTIL_TAG, "Param serviceList is NULL");
-    VERIFY_NON_NULL(bleServiceInfo, TZ_BLE_CLIENT_UTIL_TAG, "Param bleServiceInfo is NULL");
-
-    if (0 > position)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "Position Invalid input !");
-        return CA_STATUS_INVALID_PARAM;
-    }
-
-    *bleServiceInfo = NULL;
-    int32_t count = 0;
-    BLEServiceList *cur = serviceList;
-    while (cur != NULL)
-    {
-        if (position == count)
-        {
-            *bleServiceInfo = cur->serviceInfo;
-            OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "OUT");
-            return CA_STATUS_OK;
-        }
-        count++;
-        cur = cur->next;
-    }
-    return CA_STATUS_FAILED;
-}
-
-void CAFreeBLEServiceList(BLEServiceList *serviceList)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
-    while (serviceList)
-    {
-        BLEServiceList *temp = serviceList;
-        serviceList = serviceList->next;
-        CAFreeBLEServiceInfo(temp->serviceInfo);
-        OICFree(temp);
-    }
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "OUT");
-}
-
-void CAFreeBLEServiceInfo(BLEServiceInfo *bleServiceInfo)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
-    if (bleServiceInfo)
-    {
-        if (bleServiceInfo->bdAddress)
-        {
-            bt_gatt_disconnect(bleServiceInfo->bdAddress);
-            OICFree(bleServiceInfo->bdAddress);
-            bt_gatt_destroy_attribute_handle(bleServiceInfo->service_clone);
-            bt_gatt_destroy_attribute_handle(bleServiceInfo->read_char);
-            bt_gatt_destroy_attribute_handle(bleServiceInfo->write_char);
-        }
-        OICFree(bleServiceInfo);
-    }
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "OUT");
-}
-
-CAResult_t CAVerifyOICServiceByUUID(const char* serviceUUID)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
-
-    VERIFY_NON_NULL(serviceUUID, TZ_BLE_CLIENT_UTIL_TAG, "Param serviceHandle is NULL");
-
-    if (strcasecmp(serviceUUID, CA_GATT_SERVICE_UUID) != 0)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "It is not OIC service!");
-        return CA_STATUS_FAILED;
-    }
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-CAResult_t CAVerifyOICServiceByServiceHandle(bt_gatt_attribute_h serviceHandle)
-{
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
-
-    VERIFY_NON_NULL(serviceHandle, TZ_BLE_CLIENT_UTIL_TAG, "Param serviceHandle is NULL");
-
-    char *uuid = NULL;
-    int ret = bt_gatt_get_service_uuid(serviceHandle, &uuid);
-
-    if (0 != ret || NULL == uuid)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "bt_gatt_get_service_uuid failed !");
-        return CA_STATUS_FAILED;
-    }
-
-    if (strcasecmp(uuid, CA_GATT_SERVICE_UUID) != 0)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "It is not OIC service!");
-        OICFree(uuid);
-        return CA_STATUS_FAILED;
-    }
-
-    OICFree(uuid);
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-const char *CABTGetErrorMsg(bt_error_e err)
-{
-    const char *errStr = NULL;
-
-    switch (err)
-    {
-        case BT_ERROR_NONE:
-            errStr = "BT_ERROR_NONE";
-            break;
-        case BT_ERROR_CANCELLED:
-            errStr = "BT_ERROR_CANCELLED";
-            break;
-        case BT_ERROR_INVALID_PARAMETER:
-            errStr = "BT_ERROR_INVALID_PARAMETER";
-            break;
-        case BT_ERROR_OUT_OF_MEMORY:
-            errStr = "BT_ERROR_OUT_OF_MEMORY";
-            break;
-        case BT_ERROR_RESOURCE_BUSY:
-            errStr = "BT_ERROR_RESOURCE_BUSY";
-            break;
-        case BT_ERROR_TIMED_OUT:
-            errStr = "BT_ERROR_TIMED_OUT";
-            break;
-        case BT_ERROR_NOW_IN_PROGRESS:
-            errStr = "BT_ERROR_NOW_IN_PROGRESS";
-            break;
-        case BT_ERROR_NOT_INITIALIZED:
-            errStr = "BT_ERROR_NOT_INITIALIZED";
-            break;
-        case BT_ERROR_NOT_ENABLED:
-            errStr = "BT_ERROR_NOT_ENABLED";
-            break;
-        case BT_ERROR_ALREADY_DONE:
-            errStr = "BT_ERROR_ALREADY_DONE";
-            break;
-        case BT_ERROR_OPERATION_FAILED:
-            errStr = "BT_ERROR_OPERATION_FAILED";
-            break;
-        case BT_ERROR_NOT_IN_PROGRESS:
-            errStr = "BT_ERROR_NOT_IN_PROGRESS";
-            break;
-        case BT_ERROR_REMOTE_DEVICE_NOT_BONDED:
-            errStr = "BT_ERROR_REMOTE_DEVICE_NOT_BONDED";
-            break;
-        case BT_ERROR_AUTH_REJECTED:
-            errStr = "BT_ERROR_AUTH_REJECTED";
-            break;
-        case BT_ERROR_AUTH_FAILED:
-            errStr = "BT_ERROR_AUTH_FAILED";
-            break;
-        case BT_ERROR_REMOTE_DEVICE_NOT_FOUND:
-            errStr = "BT_ERROR_REMOTE_DEVICE_NOT_FOUND";
-            break;
-        case BT_ERROR_SERVICE_SEARCH_FAILED:
-            errStr = "BT_ERROR_SERVICE_SEARCH_FAILED";
-            break;
-        case BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED:
-            errStr = "BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED";
-            break;
-        case BT_ERROR_PERMISSION_DENIED:
-            errStr = "BT_ERROR_PERMISSION_DENIED";
-            break;
-        case BT_ERROR_SERVICE_NOT_FOUND:
-            errStr = "BT_ERROR_SERVICE_NOT_FOUND";
-            break;
-        case BT_ERROR_NOT_SUPPORTED:
-            errStr = "BT_ERROR_NOT_SUPPORTED";
-            break;
-        default:
-            errStr = "NOT Defined";
-            break;
-    }
-
-    return errStr;
-}
-
-
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/cableutil.h b/resource/csdk/connectivity/src/bt_le_adapter/tizen/cableutil.h
deleted file mode 100644 (file)
index e7fd434..0000000
+++ /dev/null
@@ -1,249 +0,0 @@
-/* ****************************************************************
- *
- * Copyright 2014 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.
- *
- ******************************************************************/
-
-/**
- * @file
- *
- * This file contains the util function for LE adapter. This maintains the
- * list of services an individual GATT Client connected to and operations on
- * that list, such as getting the service info with BD address or with
- * position etc. This is mainly useful for the multicast transmission of
- * data where client needs to have the info of all the services to which it
- * is connected.
- */
-
-#ifndef TZ_BLE_UTIL_H_
-#define TZ_BLE_UTIL_H_
-
-#include <bluetooth.h>
-
-#include "cacommon.h"
-
-/**
- * Information regarding the GATTServer.
- *
- * This structure holds the infomation about the GATTServer
- * in the service and the characteristic level.
- */
-typedef struct
-{
-    bt_gatt_attribute_h service_clone; /**< GATT attribute handler for the OIC service. */
-    bt_gatt_attribute_h read_char;     /**< GATT attribute handler for OIC read characteristic.
-                                            Server will read.*/
-    bt_gatt_attribute_h write_char;    /**< GATT attribute handler for OIC write characteristic.
-                                            server will write*/
-    char *bdAddress;                   /**< BD address where OIC service is running. */
-} BLEServiceInfo;
-
-/**
- * List of the BLEServiceInfo structures.
- *
- * A list of BLEServiceInfo and gives the info about all the
- * the registered services from the client side.
- */
-typedef struct _BLEServiceList
-{
-    BLEServiceInfo *serviceInfo;    /**< BLEServiceInfo structure from an OIC Server. */
-    struct _BLEServiceList *next;   /**< Next reference to the List. */
-} BLEServiceList;
-
-/**
- * Different characteristics types.
- *
- * This provides information of different characteristics
- * which will be added to OIC service.
- */
-typedef enum
-{
-    BLE_GATT_WRITE_CHAR = 0, /**< write_char This will be used to get the unicast response. */
-    BLE_GATT_READ_CHAR,      /**< read_char This will be used update value to OIC server. */
-    BLE_GATT_NOTIFY_CHAR     /**< Reserved char for the time being. */
-} CHAR_TYPE;
-
-/**
- * Stores the information required to set the descriptor value of the Service.
- */
-typedef struct gattCharDescriptor
-{
-    bt_gatt_attribute_h characteristic; /**< The attribute handle of descriptor. */
-    uint8_t *desc;                      /**< Descriptor handle of characteristic, in byte array. */
-    int total;                          /**< The total number of descriptor in a characteristic. */
-} stGattCharDescriptor_t;
-
-/**
- * Used to increment the registered service count.
- */
-void CAIncrementRegisteredServiceCount();
-
-/**
- * Used to decrement the registered service count.
- */
-void CADecrementRegisteredServiceCount();
-
-/**
- * Used to reset the registered service count.
- */
-void CAResetRegisteredServiceCount();
-
-/**
- * Used to get the total registered service count.
- * @return  Total registered service count.
- */
-int32_t  CAGetRegisteredServiceCount();
-
-/**
- * Used to create BLEServiceInfo structure with server handler and BD address will be
- * created.
- * @param[in] bdAddress        BD address of the device where GATTServer is running.
- * @param[in] service          service attribute handler.
- * @param[in] bleServiceInfo   Pointer where serviceInfo structure needs to be stored.
- *                             Memory will be allocated here and needs to be cleared by caller.
- * @return ::CA_STATUS_OK or Appropriate error code.
- * @retval ::CA_STATUS_OK  Successful.
- * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CACreateBLEServiceInfo(const char *bdAddress, bt_gatt_attribute_h service,
-                                  BLEServiceInfo **bleServiceInfo);
-
-/**
- * Used to append the characteristic info to the already created serviceInfo structure.
- *
- * @param[in] characteristic   Charecteristic attribute handler.
- * @param[in] type             Specifies whether its BLE_GATT_READ_CHAR or BLE_GATT_WRITE_CHAR
- * @param[in] bleServiceInfo   Pointer where serviceInfo structure needs to be appended with
- *                             char info.
- * @return ::CA_STATUS_OK or Appropriate error code.
- * @retval ::CA_STATUS_OK  Successful.
- * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CAAppendBLECharInfo(bt_gatt_attribute_h characteristic, CHAR_TYPE type,
-                               BLEServiceInfo *bleServiceInfo);
-
-/**
- * Used to add the ServiceInfo structure to the Service List.
- *
- * @param[in] serviceList      Pointer to the ble service list which holds the info of list of
- *                             service registered from client.
- * @param[in] bleServiceInfo   Pointer where serviceInfo structure needs to be appended with
- *                             char info.
- * @return ::CA_STATUS_OK or Appropriate error code.
- * @retval ::CA_STATUS_OK  Successful.
- * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CAAddBLEServiceInfoToList(BLEServiceList **serviceList,
-                BLEServiceInfo *bleServiceInfo);
-
-/**
- * Used to remove the ServiceInfo structure from the Service List.
- *
- * @param[in] serviceList      Pointer to the ble service list which holds the info of list of
- *                             service registered from client.
- * @param[in] bleServiceInfo   Pointer where serviceInfo structure needs to be appended with
- *                             char info.
- * @param[in] bdAddress        BD address of the device where GATTServer is disconnected.
- *
- * @return ::CA_STATUS_OK or Appropriate error code.
- * @retval ::CA_STATUS_OK  Successful.
- * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CARemoveBLEServiceInfoToList(BLEServiceList **serviceList,
-                                        BLEServiceInfo *bleServiceInfo,
-                                        const char *bdAddress);
-
-/**
- * Used to get the serviceInfo from the list.
- *
- * @param[in] serviceList       Pointer to the ble service list which holds the info of list
- *                              of service registered from client.
- * @param[in] bdAddress         BD address of the device where GATTServer information is required.
- * @param[out] bleServiceInfo   Pointer where serviceInfo structure needs to provide the service
- *                              and char info.
- * @return ::CA_STATUS_OK or Appropriate error code.
- * @retval ::CA_STATUS_OK  Successful.
- * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CAGetBLEServiceInfo(BLEServiceList *serviceList, const char *bdAddress,
-                               BLEServiceInfo **bleServiceInfo);
-
-/**
- * Used to get the serviceInfo from the list by position.
- *
- * @param[in] serviceList      Pointer to the ble service list which holds the info of list
- *                             of service registered from client.
- * @param[in] position         The service information of particular position in the list.
- * @param[out] bleServiceInfo  Pointer where serviceInfo structure needs to provide the service
- *                             and char info.
- * @return ::CA_STATUS_OK or Appropriate error code.
- * @retval ::CA_STATUS_OK  Successful.
- * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CAGetBLEServiceInfoByPosition(BLEServiceList *serviceList, int32_t position,
-                                         BLEServiceInfo **bleServiceInfo);
-
-/**
- * Used to clear BLE service list.
- *
- * @param[in]  serviceList   Pointer to the ble service list which holds the info of list of
- *                           service registered from client.
- */
-void CAFreeBLEServiceList(BLEServiceList *serviceList);
-
-/**
- * Used to get remove particular BLE service info from list.
- * @param[in] serviceinfo   Pointer to the structure which needs to be cleared.
- */
-void CAFreeBLEServiceInfo(BLEServiceInfo *bleServiceInfo);
-
-/**
- * Used to check whether found handle is OIC service handle or not.
- *
- * @param[in] serviceHandle   Discovered service handle(unique identifier for service).
- * @return  STATUS_OK or Appropriate error code.
- * @retval ::CA_STATUS_OK  Successful.
- * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CAVerifyOICServiceByServiceHandle(bt_gatt_attribute_h serviceHandle);
-
-/**
- * Used to check whether UUID of the discovered device is OIC service or not.
- *
- * @param[in]  serviceUUID   Service UUID.
- * @return ::CA_STATUS_OK or Appropriate error code.
- * @retval ::CA_STATUS_OK  Successful.
- * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CAVerifyOICServiceByUUID(const char* serviceUUID);
-
-/**
- * Used to get the Error message.
- * @param[in] err   Error code(::bt_error_e).
- * @return  Error string corresponding to the BT error code.
- */
-const char *CABTGetErrorMsg(bt_error_e err);
-
-#endif /* TZ_BLE_UTIL_H_ */
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleclient.c b/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleclient.c
new file mode 100644 (file)
index 0000000..3d4fd24
--- /dev/null
@@ -0,0 +1,1206 @@
+/* ****************************************************************
+*
+* Copyright 2014 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 "caleclient.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <arpa/inet.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <pthread.h>
+#include <gio/gio.h>
+
+#include "camutex.h"
+#include "uarraylist.h"
+#include "caqueueingthread.h"
+#include "caadapterutils.h"
+#include "cagattservice.h"
+#include "oic_string.h"
+#include "oic_malloc.h"
+
+/**
+ * Logging tag for module name.
+ */
+#define TAG "OIC_CA_LE_CLIENT"
+
+#define MICROSECS_PER_SEC 1000000
+#define WAIT_TIME_WRITE_CHARACTERISTIC 10 * MICROSECS_PER_SEC
+
+uint64_t const TIMEOUT = 30 * MICROSECS_PER_SEC;
+
+/**
+ * Flag to check if multicast is already in progress.
+ */
+static bool g_isMulticastInProgress = false;
+
+/**
+ * Pending multicast data list to be sent.
+ */
+static u_arraylist_t *g_multicastDataList = NULL;
+
+/**
+ * Mutex to synchronize the access to Pending multicast data list.
+ */
+static ca_mutex g_multicastDataListMutex = NULL;
+
+/**
+ * List of devices discovered.
+ */
+static u_arraylist_t *g_deviceDiscoveredList = NULL;
+
+/**
+ * Mutex to synchronize the access to discovered devices list.
+ */
+static ca_mutex g_deviceDiscoveredListMutex = NULL;
+
+/**
+ * Condition to start the timer for scanning.
+ */
+static ca_cond g_startTimerCond = NULL;
+
+/**
+ * Condition for scanning Time interval.
+ */
+static ca_cond g_scanningTimeCond = NULL;
+
+/**
+ * This contains the list of OIC services a client connect tot.
+ */
+static LEServerInfoList *g_LEServerList = NULL;
+
+/**
+ * Mutex to synchronize access to BleServiceList.
+ */
+static ca_mutex g_LEServerListMutex = NULL;
+
+/**
+ * Boolean variable to keep the state of the GATT Client.
+ */
+static bool g_isLEGattClientStarted = false;
+
+/**
+ * Mutex to synchronize access to the requestResponse callback to be called
+ * when the data needs to be sent from GATTClient.
+ */
+static ca_mutex g_LEReqRespClientCbMutex = NULL;
+
+/**
+ * Mutex to synchronize access to the requestResponse callback to be called
+ * when the data needs to be sent from GATTClient.
+ */
+static ca_mutex g_LEClientConnectMutex = NULL;
+
+/**
+ * Mutex to synchronize the calls to be done to the platform from GATTClient
+ * interfaces from different threads.
+ */
+static ca_mutex g_LEClientStateMutex = NULL;
+
+/**
+ * Mutex to synchronize the task to be pushed to thread pool.
+ */
+static ca_mutex g_LEClientThreadPoolMutex = NULL;
+
+/**
+ * Mutex to synchronize the task to write characteristic one packet after another.
+ */
+static ca_mutex g_threadWriteCharacteristicMutex = NULL;
+
+/**
+ * Condition for Writing characteristic.
+ */
+static ca_cond g_threadWriteCharacteristicCond = NULL;
+
+/**
+ * Flag to check status of write characteristic.
+ */
+static bool g_isSignalSetFlag = false;
+
+/**
+ * Maintains the callback to be notified on receival of network packets from other
+ *           BLE devices
+ */
+static CABLEDataReceivedCallback g_LEClientDataReceivedCallback = NULL;
+
+/**
+ * callback to update the error to le adapter
+ */
+static CABLEErrorHandleCallback g_clientErrorCallback;
+
+/**
+ * gmainLoop to manage the threads to receive the callback from the platfrom.
+ */
+static GMainLoop *g_eventLoop = NULL;
+
+/**
+ * Reference to threadpool
+ */
+static ca_thread_pool_t g_LEClientThreadPool = NULL;
+
+bt_scan_filter_h g_scanFilter = NULL;
+
+bool CALEIsDeviceDiscovered(const char * address)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    if (g_deviceDiscoveredList)
+    {
+        ca_mutex_lock(g_deviceDiscoveredListMutex);
+        uint32_t arrayLength = u_arraylist_length(g_deviceDiscoveredList);
+        for (int i = 0; i < arrayLength; i++)
+        {
+            char *deviceAddr = u_arraylist_get(g_deviceDiscoveredList, i);
+            if (0 == strcasecmp(deviceAddr, address))
+            {
+                OIC_LOG(DEBUG, TAG, "Device Found");
+                ca_mutex_unlock(g_deviceDiscoveredListMutex);
+                return true;
+            }
+
+        }
+        ca_mutex_unlock(g_deviceDiscoveredListMutex);
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return false;
+}
+
+void CALEGattCharacteristicChangedCb(bt_gatt_h characteristic,
+                                     char *value,
+                                     int valueLen, void *userData)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG_V(DEBUG, TAG, "Changed characteristic value length [%d]", valueLen);
+
+    ca_mutex_lock(g_LEReqRespClientCbMutex);
+    if (NULL == g_LEClientDataReceivedCallback)
+    {
+        OIC_LOG(ERROR, TAG, "Request response callback is not set");
+        ca_mutex_unlock(g_LEReqRespClientCbMutex);
+        return;
+    }
+
+    uint32_t sentLength = 0;
+    g_LEClientDataReceivedCallback(userData, (uint8_t *)value, valueLen, &sentLength);
+
+    OIC_LOG_V(DEBUG, TAG, "Sent data Length is %d", sentLength);
+
+    ca_mutex_unlock(g_LEReqRespClientCbMutex);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CALEGattCharacteristicWriteCb(int result, bt_gatt_h reqHandle, void *userData)
+{
+    OIC_LOG(DEBUG, TAG, "IN ");
+
+    if (BT_ERROR_NONE != result)
+    {
+        OIC_LOG(ERROR, TAG, "Write failed Need Retry ");
+        //Need to Implement retry mechanism
+    }
+    else
+    {
+        ca_mutex_lock(g_threadWriteCharacteristicMutex);
+        OIC_LOG(DEBUG, TAG, "g_isSignalSetFlag is set true and signal");
+        g_isSignalSetFlag = true;
+        ca_cond_signal(g_threadWriteCharacteristicCond);
+        ca_mutex_unlock(g_threadWriteCharacteristicMutex);
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT ");
+}
+
+void CALEGattConnectionStateChanged(bool connected, const char *remoteAddress)
+{
+    OIC_LOG(DEBUG, TAG, "IN ");
+
+    VERIFY_NON_NULL_VOID(remoteAddress, TAG, "remote address is NULL");
+
+    // Start the scanning.
+    CAResult_t ret = CALEGattStartDeviceScanning();
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEGattStartDeviceDiscovery Failed");
+    }
+    // Signal the start timer.
+    ca_cond_signal(g_scanningTimeCond);
+
+    if (!connected)
+    {
+        OIC_LOG_V(DEBUG, TAG, "DisConnected from [%s] ", remoteAddress);
+    }
+    else
+    {
+        OIC_LOG_V(DEBUG, TAG, "Connected to [%s] ", remoteAddress);
+
+        char *addr = OICStrdup(remoteAddress);
+
+        ca_mutex_lock(g_LEClientThreadPoolMutex);
+        if (NULL == g_LEClientThreadPool)
+        {
+            OIC_LOG(ERROR, TAG, "g_LEClientThreadPool is NULL");
+            OICFree(addr);
+            ca_mutex_unlock(g_LEClientThreadPoolMutex);
+            return;
+        }
+
+        ret = ca_thread_pool_add_task(g_LEClientThreadPool, CADiscoverLEServicesThread,
+                                      addr);
+        if (CA_STATUS_OK != ret)
+        {
+            OIC_LOG_V(ERROR, TAG, "ca_thread_pool_add_task failed with ret [%d]", ret);
+            OICFree(addr);
+        }
+        ca_mutex_unlock(g_LEClientThreadPoolMutex);
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CALEAdapterScanResultCb(int result, bt_adapter_le_device_scan_result_info_s *scanInfo,
+                             void *userData)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    VERIFY_NON_NULL_VOID(scanInfo, TAG, "scanInfo");
+    VERIFY_NON_NULL_VOID(scanInfo->remote_address, TAG, "scanInfo->remote_address");
+
+    OIC_LOG_V(DEBUG, TAG, "Remote Address [%s]", scanInfo->remote_address);
+    OIC_LOG_V(DEBUG, TAG, "Scan Result [%d]", result);
+    OIC_LOG_V(DEBUG, TAG,
+              " Adv data len [%d] Scan data len[%d]RSSI [%d] Addr_type [%d] ",
+              scanInfo->adv_data_len, scanInfo->scan_data_len, scanInfo->rssi,
+              scanInfo->address_type);
+
+    // Check if device is already discovered.
+    if (CALEIsDeviceDiscovered(scanInfo->remote_address))
+    {
+        OIC_LOG_V(INFO, TAG, "Device[%s] is already discovered", scanInfo->remote_address);
+        return;
+    }
+
+    // Stop the scan before invoking bt_gatt_connect().
+    CALEGattStopDeviceScanning();
+
+    ca_mutex_lock(g_deviceDiscoveredListMutex);
+    // Add the the device Discovered list.
+    if (NULL == g_deviceDiscoveredList)
+    {
+        g_deviceDiscoveredList = u_arraylist_create();
+    }
+    char *deviceAddr = OICStrdup(scanInfo->remote_address);
+    u_arraylist_add(g_deviceDiscoveredList, (void *) deviceAddr);
+    ca_mutex_unlock(g_deviceDiscoveredListMutex);
+
+    size_t len = strlen(scanInfo->remote_address);
+
+    char *addr = (char *)OICMalloc(sizeof(char) * (len + 1));
+    VERIFY_NON_NULL_VOID(addr, TAG, "Malloc failed");
+
+    strncpy(addr, scanInfo->remote_address, len + 1);
+
+    OIC_LOG_V(DEBUG, TAG,
+              "Trying to do Gatt connection to [%s]", addr);
+
+    ca_mutex_lock(g_LEClientThreadPoolMutex);
+    if (NULL == g_LEClientThreadPool)
+    {
+        OIC_LOG(ERROR, TAG, "g_LEClientThreadPool is NULL");
+        OICFree(addr);
+        ca_mutex_unlock(g_LEClientThreadPoolMutex);
+        return;
+    }
+
+    CAResult_t res = ca_thread_pool_add_task(g_LEClientThreadPool, CAGattConnectThread, addr);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG_V(ERROR, TAG,
+                  "ca_thread_pool_add_task failed with ret [%d]", res);
+        OICFree(addr);
+    }
+    ca_mutex_unlock(g_LEClientThreadPoolMutex);
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CASetLEClientThreadPoolHandle(ca_thread_pool_t handle)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    ca_mutex_lock(g_LEClientThreadPoolMutex);
+    g_LEClientThreadPool = handle;
+    ca_mutex_unlock(g_LEClientThreadPoolMutex);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CASetLEReqRespClientCallback(CABLEDataReceivedCallback callback)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    ca_mutex_lock(g_LEReqRespClientCbMutex);
+
+    g_LEClientDataReceivedCallback = callback;
+
+    ca_mutex_unlock(g_LEReqRespClientCbMutex);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CASetBLEClientErrorHandleCallback(CABLEErrorHandleCallback callback)
+{
+    g_clientErrorCallback = callback;
+}
+
+CAResult_t CAStartLEGattClient()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    ca_mutex_lock(g_LEClientThreadPoolMutex);
+    if (NULL == g_LEClientThreadPool)
+    {
+        OIC_LOG(ERROR, TAG, "gBleServerThreadPool is NULL");
+        CATerminateGattClientMutexVariables();
+        ca_mutex_unlock(g_LEClientThreadPoolMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    CAResult_t result = ca_thread_pool_add_task(g_LEClientThreadPool, CAStartLEGattClientThread,
+                                     NULL);
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, TAG, "ca_thread_pool_add_task failed");
+        CATerminateGattClientMutexVariables();
+        ca_mutex_unlock(g_LEClientThreadPoolMutex);
+        return CA_STATUS_FAILED;
+    }
+    ca_mutex_unlock(g_LEClientThreadPoolMutex);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAStartLEGattClientThread(void *data)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    ca_mutex_lock(g_LEClientStateMutex);
+    if (true  == g_isLEGattClientStarted)
+    {
+        OIC_LOG(ERROR, TAG, "Gatt Client is already running!!");
+        ca_mutex_unlock(g_LEClientStateMutex);
+        return;
+    }
+
+    CAResult_t  result = CALEGattSetCallbacks();
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, TAG, "CABleGattSetCallbacks Failed");
+        ca_mutex_unlock(g_LEClientStateMutex);
+        CATerminateLEGattClient();
+        return;
+    }
+
+    g_isLEGattClientStarted = true;
+    ca_mutex_unlock(g_LEClientStateMutex);
+
+    ca_mutex_lock(g_LEClientThreadPoolMutex);
+    if (NULL == g_LEClientThreadPool)
+    {
+        OIC_LOG(ERROR, TAG, "gBleServerThreadPool is NULL");
+        CATerminateGattClientMutexVariables();
+        ca_mutex_unlock(g_LEClientThreadPoolMutex);
+        return;
+    }
+
+    result = ca_thread_pool_add_task(g_LEClientThreadPool, CAStartTimerThread,
+                                     NULL);
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, TAG, "ca_thread_pool_add_task failed");
+        ca_mutex_unlock(g_LEClientThreadPoolMutex);
+        return;
+    }
+    ca_mutex_unlock(g_LEClientThreadPoolMutex);
+
+    OIC_LOG(DEBUG, TAG, "Giving the control to threadPool");
+
+    GMainContext *thread_context = g_main_context_new();
+
+    g_eventLoop = g_main_loop_new(thread_context, FALSE);
+
+    g_main_context_push_thread_default(thread_context);
+
+    g_main_loop_run(g_eventLoop);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CAStartTimerThread(void *data)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    while (g_isLEGattClientStarted)
+    {
+        ca_mutex_lock(g_multicastDataListMutex);
+        if (!g_isMulticastInProgress)
+        {
+            OIC_LOG(DEBUG, TAG, "waiting....");
+            ca_cond_wait(g_startTimerCond, g_multicastDataListMutex);
+            OIC_LOG(DEBUG, TAG, "Wake up");
+            g_isMulticastInProgress = true;
+        }
+
+        // Timed conditional wait for stopping the scan.
+        CAWaitResult_t ret = ca_cond_wait_for(g_scanningTimeCond, g_multicastDataListMutex,
+                                              TIMEOUT);
+        if (CA_WAIT_TIMEDOUT == ret)
+        {
+            OIC_LOG(DEBUG, TAG, "Scan is timed Out");
+            // Call stop scan.
+            CALEGattStopDeviceScanning();
+
+            // Clear the data list and device list.
+            u_arraylist_destroy(g_multicastDataList);
+            g_multicastDataList = NULL;
+
+            ca_mutex_lock(g_deviceDiscoveredListMutex);
+            u_arraylist_destroy(g_deviceDiscoveredList);
+            g_deviceDiscoveredList = NULL;
+            ca_mutex_unlock(g_deviceDiscoveredListMutex);
+
+            g_isMulticastInProgress = false;
+        }
+        ca_mutex_unlock(g_multicastDataListMutex);
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CAStopLEGattClient()
+{
+    OIC_LOG(DEBUG,  TAG, "IN");
+
+    ca_mutex_lock(g_LEClientStateMutex);
+
+    if (false == g_isLEGattClientStarted)
+    {
+        OIC_LOG(ERROR, TAG, "Gatt Client is not running to stop");
+        ca_mutex_unlock(g_LEClientStateMutex);
+        return;
+    }
+
+    CALEGattUnSetCallbacks();
+
+    CALEGattStopDeviceScanning();
+
+    g_isLEGattClientStarted = false;
+
+    // Signal the conditions waiting in Start timer.
+    ca_cond_signal(g_startTimerCond);
+    ca_cond_signal(g_scanningTimeCond);
+
+    // Destroy the multicast data list and device list if not empty.
+    if (NULL != g_multicastDataList)
+    {
+        ca_mutex_lock(g_multicastDataListMutex);
+        u_arraylist_destroy(g_multicastDataList);
+        g_multicastDataList = NULL;
+        ca_mutex_unlock(g_multicastDataListMutex);
+    }
+
+    if (NULL != g_deviceDiscoveredList)
+    {
+        ca_mutex_lock(g_deviceDiscoveredListMutex);
+        u_arraylist_destroy(g_deviceDiscoveredList);
+        g_deviceDiscoveredList = NULL;
+        ca_mutex_unlock(g_deviceDiscoveredListMutex);
+    }
+
+    ca_mutex_lock(g_LEServerListMutex);
+    CAFreeLEServerList(g_LEServerList);
+    g_LEServerList = NULL;
+    ca_mutex_unlock(g_LEServerListMutex);
+
+    ca_mutex_lock(g_threadWriteCharacteristicMutex);
+    ca_cond_signal(g_threadWriteCharacteristicCond);
+    ca_mutex_unlock(g_threadWriteCharacteristicMutex);
+
+    CAResetRegisteredServiceCount();
+
+    GMainContext  *context_event_loop = NULL;
+    // Required for waking up the thread which is running in gmain loop
+    if (NULL != g_eventLoop)
+    {
+        context_event_loop = g_main_loop_get_context(g_eventLoop);
+    }
+    if (context_event_loop)
+    {
+        OIC_LOG_V(DEBUG,  TAG, "g_eventLoop context %x", context_event_loop);
+        g_main_context_wakeup(context_event_loop);
+
+        // Kill g main loops and kill threads.
+        g_main_loop_quit(g_eventLoop);
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "g_eventLoop context is NULL");
+    }
+
+    ca_mutex_unlock(g_LEClientStateMutex);
+
+    OIC_LOG(DEBUG,  TAG, "OUT");
+}
+
+CAResult_t CAInitializeLEGattClient()
+{
+    OIC_LOG(DEBUG, TAG, "Initialize GATT Client");
+    CAResult_t res = CAInitGattClientMutexVariables();
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "CAInitGattClientMutexVariables failed!");
+        CATerminateGattClientMutexVariables();
+        return CA_STATUS_FAILED;
+    }
+    return res;
+}
+
+void CATerminateLEGattClient()
+{
+    OIC_LOG(DEBUG,  TAG, "IN");
+
+    CATerminateGattClientMutexVariables();
+
+    OIC_LOG(DEBUG,  TAG, "OUT");
+}
+
+CAResult_t CAInitGattClientMutexVariables()
+{
+    OIC_LOG(DEBUG,  TAG, "IN");
+    if (NULL == g_LEClientStateMutex)
+    {
+        g_LEClientStateMutex = ca_mutex_new();
+        if (NULL == g_LEClientStateMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_LEServerListMutex)
+    {
+        g_LEServerListMutex = ca_mutex_new();
+        if (NULL == g_LEServerListMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_LEReqRespClientCbMutex)
+    {
+        g_LEReqRespClientCbMutex = ca_mutex_new();
+        if (NULL == g_LEReqRespClientCbMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_LEClientThreadPoolMutex)
+    {
+        g_LEClientThreadPoolMutex = ca_mutex_new();
+        if (NULL == g_LEClientThreadPoolMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_LEClientConnectMutex)
+    {
+        g_LEClientConnectMutex = ca_mutex_new();
+        if (NULL == g_LEClientConnectMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_multicastDataListMutex)
+    {
+        g_multicastDataListMutex = ca_mutex_new();
+        if (NULL == g_multicastDataListMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_deviceDiscoveredListMutex)
+    {
+        g_deviceDiscoveredListMutex = ca_mutex_new();
+        if (NULL == g_deviceDiscoveredListMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_threadWriteCharacteristicMutex)
+    {
+        g_threadWriteCharacteristicMutex = ca_mutex_new();
+        if (NULL == g_threadWriteCharacteristicMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_startTimerCond)
+    {
+        g_startTimerCond = ca_cond_new();
+        if (NULL == g_startTimerCond)
+        {
+            OIC_LOG(ERROR, TAG, "ca_cond_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_scanningTimeCond)
+    {
+        g_scanningTimeCond = ca_cond_new();
+        if (NULL == g_scanningTimeCond)
+        {
+            OIC_LOG(ERROR, TAG, "ca_cond_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_threadWriteCharacteristicCond)
+    {
+        g_threadWriteCharacteristicCond = ca_cond_new();
+        if (NULL == g_threadWriteCharacteristicCond)
+        {
+            OIC_LOG(ERROR, TAG, "ca_cond_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    OIC_LOG(DEBUG,  TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CATerminateGattClientMutexVariables()
+{
+    OIC_LOG(DEBUG,  TAG, "IN");
+
+    ca_mutex_free(g_LEClientStateMutex);
+    g_LEClientStateMutex = NULL;
+
+    ca_mutex_free(g_LEServerListMutex);
+    g_LEServerListMutex = NULL;
+
+    ca_mutex_free(g_LEReqRespClientCbMutex);
+    g_LEReqRespClientCbMutex = NULL;
+
+    ca_mutex_free(g_LEClientConnectMutex);
+    g_LEClientConnectMutex = NULL;
+
+    ca_mutex_free(g_LEClientThreadPoolMutex);
+    g_LEClientThreadPoolMutex = NULL;
+
+    ca_mutex_free(g_multicastDataListMutex);
+    g_multicastDataListMutex = NULL;
+
+    ca_mutex_free(g_deviceDiscoveredListMutex);
+    g_deviceDiscoveredListMutex = NULL;
+
+    ca_mutex_free(g_threadWriteCharacteristicMutex);
+    g_threadWriteCharacteristicMutex = NULL;
+
+    ca_cond_free(g_startTimerCond);
+    g_startTimerCond = NULL;
+
+    ca_cond_free(g_scanningTimeCond);
+    g_scanningTimeCond = NULL;
+
+    ca_cond_free(g_threadWriteCharacteristicCond);
+    g_threadWriteCharacteristicCond = NULL;
+    g_isSignalSetFlag = false;
+
+    OIC_LOG(DEBUG,  TAG, "OUT");
+}
+
+CAResult_t CALEGattSetCallbacks()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CALEGattUnSetCallbacks()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    bt_gatt_unset_connection_state_changed_cb();
+
+    int numOfServersConnected = CAGetRegisteredServiceCount();
+    LEServerInfo *leServerInfo = NULL;
+
+    for (int32_t index = 0; index < numOfServersConnected; index++)
+    {
+        CAGetLEServerInfoByPosition(g_LEServerList, index, &leServerInfo);
+        bt_gatt_client_unset_characteristic_value_changed_cb(leServerInfo->readChar);
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CALEGattStartDeviceScanning()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    int ret = bt_adapter_le_start_scan(CALEAdapterScanResultCb, NULL);
+    if(BT_ERROR_NONE != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "bt_adapter_le_start_scan failed[%s]",
+                  CALEGetErrorMsg(ret));
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CALEGattStopDeviceScanning()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    int ret = bt_adapter_le_stop_scan();
+    if (BT_ERROR_NONE != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "bt_adapter_le_stop_scan failed[%s]",
+                  CALEGetErrorMsg(ret));
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CAGattConnectThread (void *remoteAddress)
+{
+    OIC_LOG(DEBUG, TAG, "IN ");
+
+    VERIFY_NON_NULL_VOID(remoteAddress, TAG, "remote address is NULL");
+
+    char *address  = (char *)remoteAddress;
+
+    OIC_LOG_V(DEBUG, TAG, "remote address is [%s]", address);
+
+    CAResult_t result = CALEGattConnect(address);
+
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG_V(ERROR, TAG, "bt_gatt_connect failed for [%s]", address);
+    }
+
+    OICFree(address);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CALEGattConnect(const char *remoteAddress)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    VERIFY_NON_NULL_RET(remoteAddress, TAG,
+                        "remote address is NULL", CA_STATUS_FAILED);
+
+    ca_mutex_lock(g_LEClientConnectMutex);
+    bool isConnected = false;
+    int ret = bt_device_is_profile_connected(remoteAddress, BT_PROFILE_GATT, &isConnected);
+    if (BT_ERROR_NONE != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "bt_device_is_profile_connected Failed with ret value [%s] ",
+                  CALEGetErrorMsg(ret));
+        ca_mutex_unlock(g_LEClientConnectMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    CAResult_t result = CA_STATUS_OK;
+    if (!isConnected)
+    {
+        ret = bt_gatt_connect(remoteAddress, true);
+
+        if (BT_ERROR_NONE != ret)
+        {
+            OIC_LOG_V(ERROR, TAG, "bt_gatt_connect Failed with ret value [%s] ",
+                      CALEGetErrorMsg(ret));
+            ca_mutex_unlock(g_LEClientConnectMutex);
+            return CA_STATUS_FAILED;
+        }
+    }
+    else
+    {
+        OIC_LOG_V(INFO, TAG, "Remote address[%s] is already connected",
+                  remoteAddress);
+        char *addr = OICStrdup(remoteAddress);
+        if (NULL == addr)
+        {
+            OIC_LOG(ERROR, TAG, "addr is NULL");
+            ca_mutex_unlock(g_LEClientConnectMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        ca_mutex_lock(g_LEClientThreadPoolMutex);
+        if (NULL == g_LEClientThreadPool)
+        {
+            OIC_LOG(ERROR, TAG, "g_LEClientThreadPool is NULL");
+            OICFree(addr);
+            ca_mutex_unlock(g_LEClientThreadPoolMutex);
+            ca_mutex_unlock(g_LEClientConnectMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        result = ca_thread_pool_add_task(g_LEClientThreadPool, CADiscoverLEServicesThread,
+                                      addr);
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG_V(ERROR, TAG, "ca_thread_pool_add_task failed with ret [%d]", result);
+            OICFree(addr);
+        }
+        ca_mutex_unlock(g_LEClientThreadPoolMutex);
+    }
+    ca_mutex_unlock(g_LEClientConnectMutex);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return result;
+}
+
+CAResult_t CALEGattDisConnect(const char *remoteAddress)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    VERIFY_NON_NULL_RET(remoteAddress, TAG,
+                        "remote address is NULL", CA_STATUS_FAILED);
+
+    int ret = bt_gatt_disconnect(remoteAddress);
+
+    if (BT_ERROR_NONE != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "bt_gatt_disconnect Failed with ret value [%d] ",
+                  CALEGetErrorMsg(ret));
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CADiscoverLEServicesThread (void *remoteAddress)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    VERIFY_NON_NULL_VOID(remoteAddress, TAG, "remote address is NULL");
+
+    char *address  = (char *)remoteAddress;
+
+    CAResult_t result = CALEGattDiscoverServices(address);
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, TAG, "CALEGattDiscoverServices failed");
+    }
+
+    OICFree(address);
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CALEGattDiscoverServices(const char *remoteAddress)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    VERIFY_NON_NULL_RET(remoteAddress, TAG,
+                        "remote address is NULL", CA_STATUS_FAILED);
+
+    bt_gatt_client_h clientHandle = NULL;
+    int32_t ret = bt_gatt_client_create(remoteAddress, &clientHandle);
+    if (BT_ERROR_NONE != ret || NULL == clientHandle)
+    {
+        OIC_LOG_V(ERROR, TAG,
+                  "bt_gatt_client_create Failed with ret value [%s] ", CALEGetErrorMsg(ret));
+        CALEGattDisConnect(remoteAddress);
+        return CA_STATUS_FAILED;
+    }
+
+    bt_gatt_h serviceHandle = NULL;
+    ret = bt_gatt_client_get_service(clientHandle, CA_GATT_SERVICE_UUID, &serviceHandle);
+    if (BT_ERROR_NONE != ret || NULL == serviceHandle)
+    {
+        OIC_LOG_V(ERROR, TAG,
+                  "bt_gatt_client_get_service Failed with ret value [%s] ", CALEGetErrorMsg(ret));
+        bt_gatt_client_destroy(clientHandle);
+        CALEGattDisConnect(remoteAddress);
+        return CA_STATUS_FAILED;
+    }
+
+    // Server will read data on this characteristic.
+    bt_gatt_h writeChrHandle = NULL;
+    ret = bt_gatt_service_get_characteristic(serviceHandle, CA_GATT_REQUEST_CHRC_UUID,
+                                             &writeChrHandle);
+    if (BT_ERROR_NONE != ret || NULL == writeChrHandle)
+    {
+        OIC_LOG_V(ERROR, TAG,
+                  "bt_gatt_service_get_characteristic Failed with ret value [%s] ",
+                  CALEGetErrorMsg(ret));
+        bt_gatt_client_destroy(clientHandle);
+        CALEGattDisConnect(remoteAddress);
+        return CA_STATUS_FAILED;
+    }
+
+    // Server will notify data on this characteristic.
+    bt_gatt_h readChrHandle = NULL;
+    ret = bt_gatt_service_get_characteristic(serviceHandle, CA_GATT_RESPONSE_CHRC_UUID,
+                                             &readChrHandle);
+    if (BT_ERROR_NONE != ret || NULL == readChrHandle)
+    {
+        OIC_LOG_V(ERROR, TAG,
+                  "bt_gatt_service_get_characteristic Failed with ret value [%s] ",
+                  CALEGetErrorMsg(ret));
+        bt_gatt_client_destroy(clientHandle);
+        CALEGattDisConnect(remoteAddress);
+        return CA_STATUS_FAILED;
+    }
+
+
+    //TODO: This data has to be freed while unsetting the callback.
+    char *addr = OICStrdup(remoteAddress);
+    ret = bt_gatt_client_set_characteristic_value_changed_cb(readChrHandle,
+                                                             CALEGattCharacteristicChangedCb,
+                                                             (void *)addr);
+    if (BT_ERROR_NONE != ret)
+    {
+        OIC_LOG_V(ERROR, TAG,
+                  "bt_gatt_client_set_characteristic_value_changed_cb Failed with ret value [%s]",
+                  CALEGetErrorMsg(ret));
+        bt_gatt_client_destroy(clientHandle);
+        CALEGattDisConnect(remoteAddress);
+        return CA_STATUS_FAILED;
+    }
+
+    LEServerInfo *serverInfo = (LEServerInfo *)OICCalloc(1, sizeof(LEServerInfo));
+    if (NULL == serverInfo)
+    {
+        OIC_LOG(ERROR, TAG, "Malloc failed");
+        CALEGattDisConnect(remoteAddress);
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+    serverInfo->clientHandle = clientHandle;
+    serverInfo->serviceHandle = serviceHandle;
+    serverInfo->readChar = readChrHandle;
+    serverInfo->writeChar = writeChrHandle;
+    serverInfo->remoteAddress = OICStrdup(remoteAddress);
+
+    ca_mutex_lock(g_LEServerListMutex);
+    CAResult_t result = CAAddLEServerInfoToList(&g_LEServerList, serverInfo);
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, TAG, "CAAddBLEClientInfoToList failed");
+        bt_gatt_client_destroy(clientHandle);
+        CALEGattDisConnect(remoteAddress);
+        return CA_STATUS_FAILED;
+    }
+    ca_mutex_unlock(g_LEServerListMutex);
+
+    // Send the data of pending multicast data list if any.
+    if (g_multicastDataList)
+    {
+        ca_mutex_lock(g_multicastDataListMutex);
+        uint32_t arrayLength = u_arraylist_length(g_multicastDataList);
+        for (int i = 0; i < arrayLength; i++)
+        {
+            CALEData_t *multicastData = u_arraylist_get(g_multicastDataList, i);
+            if (NULL == multicastData)
+            {
+                OIC_LOG(DEBUG, TAG, "multicastData is NULL");
+                continue;
+            }
+            CAUpdateCharacteristicsToGattServer(remoteAddress, multicastData->data,
+                                                multicastData->dataLen, LE_UNICAST, 0);
+        }
+        ca_mutex_unlock(g_multicastDataListMutex);
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t  CAUpdateCharacteristicsToGattServer(const char *remoteAddress,
+                                                const uint8_t *data, const uint32_t dataLen,
+                                                CALETransferType_t type, const int32_t position)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    VERIFY_NON_NULL(data, TAG, "data is NULL");
+
+    if (0 >= dataLen)
+    {
+        OIC_LOG(ERROR, TAG, "dataLen is less than or equal zero. Invalid input!");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    LEServerInfo *leServerInfo = NULL;
+    CAResult_t ret =  CA_STATUS_FAILED;
+
+    ca_mutex_lock(g_LEServerListMutex);
+    if (LE_UNICAST == type)
+    {
+        ret = CAGetLEServerInfo(g_LEServerList, remoteAddress, &leServerInfo);
+    }
+    else if (LE_MULTICAST == type)
+    {
+        ret = CAGetLEServerInfoByPosition(g_LEServerList, position, &leServerInfo);
+    }
+    ca_mutex_unlock(g_LEServerListMutex);
+
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CAGetBLEServiceInfoByPosition is failed");
+        return CA_STATUS_FAILED;
+    }
+
+    VERIFY_NON_NULL(leServerInfo, TAG, "bleServiceInfo is NULL");
+
+    OIC_LOG_V(DEBUG, TAG, "Updating the data of length [%d] to [%s] ", dataLen,
+              leServerInfo->remoteAddress);
+
+    int result = bt_gatt_set_value(leServerInfo->writeChar, (char *)data, dataLen);
+
+    if (BT_ERROR_NONE != result)
+    {
+        OIC_LOG_V(ERROR, TAG,
+                  "bt_gatt_set_value Failed with return val [%s]",
+                  CALEGetErrorMsg(result));
+        return CA_STATUS_FAILED;
+    }
+
+    result = bt_gatt_client_write_value(leServerInfo->writeChar, CALEGattCharacteristicWriteCb,
+                                        NULL);
+    if (BT_ERROR_NONE != result)
+    {
+        OIC_LOG_V(ERROR, TAG,
+                  "bt_gatt_client_write_value Failed with return val [%s]",
+                  CALEGetErrorMsg(result));
+        return CA_STATUS_FAILED;
+    }
+
+    // wait for callback for write Characteristic with success to sent data
+    OIC_LOG_V(DEBUG, TAG, "callback flag is %d", g_isSignalSetFlag);
+    ca_mutex_lock(g_threadWriteCharacteristicMutex);
+    if (!g_isSignalSetFlag)
+    {
+        OIC_LOG(DEBUG, TAG, "wait for callback to notify writeCharacteristic is success");
+        if (CA_WAIT_SUCCESS != ca_cond_wait_for(g_threadWriteCharacteristicCond,
+                                  g_threadWriteCharacteristicMutex,
+                                  WAIT_TIME_WRITE_CHARACTERISTIC))
+        {
+            OIC_LOG(ERROR, TAG, "there is no response. write has failed");
+            g_isSignalSetFlag = false;
+            ca_mutex_unlock(g_threadWriteCharacteristicMutex);
+            return CA_SEND_FAILED;
+        }
+    }
+    // reset flag set by writeCharacteristic Callback
+    g_isSignalSetFlag = false;
+    ca_mutex_unlock(g_threadWriteCharacteristicMutex);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAUpdateCharacteristicsToAllGattServers(const uint8_t *data, uint32_t dataLen)
+{
+    OIC_LOG(DEBUG,  TAG, "IN");
+
+    VERIFY_NON_NULL(data, TAG, "data is NULL");
+
+    if (0 >= dataLen)
+    {
+        OIC_LOG(ERROR, TAG, "dataLen is less than or equal zero. Invalid input !");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    int numOfServersConnected = CAGetRegisteredServiceCount();
+
+    // Send data to already connected devices.
+    for (int32_t pos = 0; pos < numOfServersConnected; pos++)
+    {
+        /*remoteAddress will be NULL.
+          Since we have to send to all destinations. pos will be used for getting remote address.
+         */
+        int32_t ret = CAUpdateCharacteristicsToGattServer(NULL, data, dataLen, LE_MULTICAST, pos);
+
+        if (CA_STATUS_OK != ret)
+        {
+            OIC_LOG_V(ERROR, TAG,
+                      "CAUpdateCharacteristicsToGattServer Failed with return val [%d] ", ret);
+            g_clientErrorCallback(NULL, data, dataLen, ret);
+        }
+    }
+
+    // Add the data to pending list.
+    CALEData_t *multicastData = (CALEData_t *)OICCalloc(1, sizeof(CALEData_t));
+    if (NULL == multicastData)
+    {
+        OIC_LOG(ERROR, TAG, "Calloc failed");
+        goto exit;
+    }
+    multicastData->data = OICCalloc(1, dataLen);
+    if (NULL == multicastData->data)
+    {
+        OIC_LOG(ERROR, TAG, "Calloc failed");
+        goto exit;
+    }
+    memcpy(multicastData->data, data, dataLen);
+    multicastData->dataLen = dataLen;
+
+    ca_mutex_lock(g_multicastDataListMutex);
+    if (NULL == g_multicastDataList)
+    {
+        g_multicastDataList = u_arraylist_create();
+    }
+    u_arraylist_add(g_multicastDataList, (void *)multicastData);
+    ca_mutex_unlock(g_multicastDataListMutex);
+
+    // Start the scanning.
+    CAResult_t result = CALEGattStartDeviceScanning();
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, TAG, "CALEGattStartDeviceDiscovery Failed");
+        goto exit;
+    }
+
+    // Start the timer by signalling it.
+    ca_cond_signal(g_startTimerCond);
+
+exit:
+    OIC_LOG(DEBUG, TAG, "OUT ");
+    return CA_STATUS_OK;
+}
+
+
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleclient.h b/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleclient.h
new file mode 100644 (file)
index 0000000..e11072f
--- /dev/null
@@ -0,0 +1,199 @@
+/* ****************************************************************
+*
+* Copyright 2014 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.
+*
+******************************************************************/
+
+/**
+ * @file
+ *
+ * This file contains the functionalities of GATT Client. Functionalities
+ * like LE device discovery, connecting to the LE device with OIC service,
+ * registering to the service and there characteristics, registering to the
+ * change in the charateristics, setting the value of the characteristcs
+ * for the request and response will be done here.
+ */
+
+#ifndef TZ_BLE_CLIENT_H_
+#define TZ_BLE_CLIENT_H_
+
+#include <bluetooth.h>
+#include <bluetooth_type.h>
+#include <bluetooth_type_internal.h>
+#include <bluetooth_internal.h>
+
+#include "cacommon.h"
+#include "caadapterutils.h"
+#include "caleutil.h"
+#include "caadapterinterface.h"
+#include "logger.h"
+#include "cathreadpool.h"
+#include "caleinterface.h"
+#include "oic_malloc.h"
+
+
+/**
+ * This callback is called when a characteristic value is changed by the GATT server.
+ *
+ * @param[in]  characteristic The attribute handle of characteristic.
+ * @param[in]  value          Value of the characteristics of a service.
+ * @param[in]  valueLen       Length of data.
+ * @param[in]  userData       The user data passed from the request function.
+ */
+void CALEGattCharacteristicChangedCb(bt_gatt_h characteristic,
+                                     char *value, int valueLen, void *userData);
+/**
+ * This callback will be called when the client write request is completed.
+ *
+ * @param[in]  result    Result of write value.
+ * @param[in]  reqHandle The request GATT handle.
+ * @param[in]  userData  User context
+ */
+void CALEGattCharacteristicWriteCb(int result, bt_gatt_h reqHandle, void *userData);
+
+/**
+ * This is the callback which will be called whenever there is change in gatt connection
+ * with server(Connected/Disconnected)
+ *
+ * @param[in]  connected     State of connection
+ * @param[in]  remoteAddress Mac address of the remote device in which we made connection.
+ */
+void CALEGattConnectionStateChanged(bool connected, const char *remoteAddress);
+
+/**
+ * This is the callback which will be called when LE advertisement is found.
+ *
+ * @param[in]  result         The result of Scanning
+ * @param[in]  scanInfo       Remote Device information.
+ * @param[in]  userData       The user data passed from the request function
+ */
+void CALEAdapterScanResultCb(int result, bt_adapter_le_device_scan_result_info_s *scanInfo,
+                             void *userData);
+
+/**
+ * This thread will be used to initialize the Gatt Client and start device discovery.
+ * 1. Setting neccessary callbacks for connection, characteristics changed and discovery.
+ * 2. Start device discovery
+ *
+ * @param[in] data Currently it will be NULL(no parameter)
+ */
+void CAStartLEGattClientThread(void *data);
+
+/**
+ * This thread will be used to Start the timer for scanning.
+ *
+ * @param[in] data Currently it will be NULL(no parameter)
+ */
+void CAStartTimerThread(void *data);
+
+/**
+ * Used to initialize all required mutex variable for Gatt Client implementation.
+ *
+ * @return ::CA_STATUS_OK or Appropriate error code.
+ * @retval ::CA_STATUS_OK  Successful.
+ * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
+ * @retval ::CA_STATUS_FAILED Operation failed.
+ */
+CAResult_t CAInitGattClientMutexVariables();
+
+/**
+ * Used to terminate all required mutex variable for Gatt Client implementation.
+ */
+void CATerminateGattClientMutexVariables();
+
+/**
+ * Used to register required callbacks to LE platform(connection, discovery, etc).
+ *
+ * @return ::CA_STATUS_OK or Appropriate error code.
+ * @retval ::CA_STATUS_OK  Successful.
+ * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
+ * @retval ::CA_STATUS_FAILED Operation failed.
+ */
+CAResult_t CALEGattSetCallbacks();
+
+/**
+ * Used to unset all the registerd callbacks to BLE platform.
+ */
+void CALEGattUnSetCallbacks();
+
+/**
+ * Used to start LE Scanning.
+ *
+ * @return ::CA_STATUS_OK or Appropriate error code.
+ * @retval ::CA_STATUS_OK  Successful.
+ * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
+ * @retval ::CA_STATUS_FAILED Operation failed.
+ */
+CAResult_t CALEGattStartDeviceScanning();
+
+/**
+ * Used to stop LE discovery for BLE  devices.
+ */
+void CALEGattStopDeviceScanning();
+
+/**
+ * This is the thread  which will be used for making gatt connection with
+ * remote devices.
+ * @param[in] remoteAddress MAC address of remote device to connect.
+ */
+void CAGattConnectThread (void *remoteAddress);
+
+/**
+ * Used to do connection with remote device.
+ *
+ * @param[in] remoteAddress Remote address inwhich we wants to connect with.
+ *
+ * @return ::CA_STATUS_OK or Appropriate error code.
+ * @retval ::CA_STATUS_OK  Successful.
+ * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
+ * @retval ::CA_STATUS_FAILED Operation failed.
+ */
+CAResult_t CALEGattConnect(const char *remoteAddress);
+
+/**
+ * Used to do disconnection with remote device.
+ * @param[in] remoteAddress Remote address inwhich we wants to disconnect with.
+ *
+ * @return ::CA_STATUS_OK or Appropriate error code.
+ * @retval ::CA_STATUS_OK  Successful.
+ * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
+ * @retval ::CA_STATUS_FAILED Operation failed.
+ */
+CAResult_t CALEGattDisConnect(const char *remoteAddress);
+
+/**
+ * This is thread which will be spawned for discovering ble services. Once
+ * called discover api, then it will be terminated.
+ * @param[in] remoteAddress Mac address of the remote device in which we
+ *                           want to search services.
+ */
+void CADiscoverLEServicesThread (void *remoteAddress);
+
+/**
+ * Used to discover the services and characteristics that is advertised by Gatt
+ * Server.
+ *
+ * @param[in] remoteAddress MAC address of remote device in which we want to discover
+ *                      the services and characteristics.
+ *
+ * @return ::CA_STATUS_OK or Appropriate error code.
+ * @retval ::CA_STATUS_OK  Successful.
+ * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
+ * @retval ::CA_STATUS_FAILED Operation failed.
+ */
+CAResult_t CALEGattDiscoverServices(const char *remoteAddress);
+#endif /* TZ_BLE_CLIENT_H_ */
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/calenwmonitor.c b/resource/csdk/connectivity/src/bt_le_adapter/tizen/calenwmonitor.c
new file mode 100644 (file)
index 0000000..47b1b5f
--- /dev/null
@@ -0,0 +1,363 @@
+/******************************************************************
+*
+* Copyright 2014 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 "caleinterface.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <glib.h>
+#include <arpa/inet.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+
+#include <bluetooth.h>
+#include <bluetooth_internal.h>
+#include <bluetooth_type.h>
+
+#include "camutex.h"
+#include "caleadapter.h"
+#include "caadapterutils.h"
+#include "oic_string.h"
+#include "oic_malloc.h"
+
+/**
+ * Logging tag for module name
+ */
+#define TAG "OIC_CA_LE_MONITOR"
+
+static GMainLoop *g_mainloop = NULL;
+static ca_thread_pool_t g_threadPoolHandle = NULL;
+
+/**
+ * Maintains the callback to be notified on device state changed.
+ */
+static CALEDeviceStateChangedCallback g_bleDeviceStateChangedCallback = NULL;
+
+/**
+ * Maintains the callback to be notified on device state changed.
+ */
+static CALEConnectionStateChangedCallback g_bleConnectionStateChangedCallback = NULL;
+
+/**
+ * Mutex to synchronize access to the deviceStateChanged Callback when the state
+ *           of the LE adapter gets change.
+ */
+static ca_mutex g_bleDeviceStateChangedCbMutex = NULL;
+
+/**
+ * Mutex to synchronize access to the ConnectionStateChanged Callback when the state
+ * of the LE adapter gets change.
+ */
+static ca_mutex g_bleConnectionStateChangedCbMutex = NULL;
+
+/**
+* This is the callback which will be called when the adapter state gets changed.
+*
+* @param result         [IN] Result of the query done to the platform.
+* @param adapter_state  [IN] State of the LE adapter.
+* @param user_data      [IN] Any user_data passed by the caller when querying for the state changed cb.
+*
+* @return  None.
+*/
+void CALEAdapterStateChangedCb(int result, bt_adapter_state_e adapter_state,
+                               void *user_data);
+
+/**
+* This is the callback which will be called when the connection state gets changed.
+*
+* @param result         [IN] Result of the query done to the platform.
+* @param connected      [IN] State of connection.
+* @param remoteAddress  [IN] LE address of the device to be notified.
+* @param user_data      [IN] Any user_data passed by the caller when querying for the state changed cb.
+*
+* @return  None.
+*/
+void CALENWConnectionStateChangedCb(int result, bool connected,
+                                    const char *remoteAddress, void *userData);
+
+void CALEMainLoopThread(void *param)
+{
+    g_main_loop_run(g_mainloop);
+}
+
+CAResult_t CAInitializeLENetworkMonitor()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    if (NULL == g_bleDeviceStateChangedCbMutex)
+    {
+        g_bleDeviceStateChangedCbMutex = ca_mutex_new();
+        if (NULL == g_bleDeviceStateChangedCbMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_bleConnectionStateChangedCbMutex)
+    {
+        g_bleConnectionStateChangedCbMutex = ca_mutex_new();
+        if (NULL == g_bleConnectionStateChangedCbMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            ca_mutex_free(g_bleDeviceStateChangedCbMutex);
+            return CA_STATUS_FAILED;
+        }
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+
+    return CA_STATUS_OK;
+}
+
+void CATerminateLENetworkMonitor()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    ca_mutex_free(g_bleDeviceStateChangedCbMutex);
+    g_bleDeviceStateChangedCbMutex = NULL;
+
+    ca_mutex_free(g_bleConnectionStateChangedCbMutex);
+    g_bleConnectionStateChangedCbMutex = NULL;
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CAInitializeLEAdapter(const ca_thread_pool_t threadPool)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    g_threadPoolHandle = threadPool;
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStartLEAdapter()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    g_mainloop = g_main_loop_new(NULL, 0);
+    if(!g_mainloop)
+    {
+        OIC_LOG(ERROR, TAG, "g_main_loop_new failed\n");
+        return CA_STATUS_FAILED;
+    }
+
+    if (CA_STATUS_OK != ca_thread_pool_add_task(g_threadPoolHandle, CALEMainLoopThread, (void *) NULL))
+    {
+        OIC_LOG(ERROR, TAG, "Failed to create thread!");
+        return CA_STATUS_FAILED;
+    }
+
+    int ret = bt_initialize();
+    if (0 != ret)
+    {
+        OIC_LOG(ERROR, TAG, "bt_initialize failed");
+        return CA_STATUS_FAILED;
+    }
+
+    ret = bt_adapter_set_visibility(BT_ADAPTER_VISIBILITY_MODE_GENERAL_DISCOVERABLE, 0);
+    if (0 != ret)
+    {
+        OIC_LOG(ERROR, TAG, "bt_adapter_set_visibility failed");
+        return CA_STATUS_FAILED;
+    }
+
+    ret = bt_adapter_set_state_changed_cb(CALEAdapterStateChangedCb, NULL);
+    if (BT_ERROR_NONE != ret)
+    {
+        OIC_LOG(DEBUG, TAG, "bt_adapter_set_state_changed_cb failed");
+        return CA_STATUS_FAILED;
+    }
+
+    ret = bt_gatt_set_connection_state_changed_cb(CALENWConnectionStateChangedCb, NULL);
+    if (BT_ERROR_NONE != ret)
+    {
+        OIC_LOG_V(ERROR, TAG,
+                  "bt_gatt_set_connection_state_changed_cb has failed");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStopLEAdapter()
+{
+
+    int ret = bt_adapter_unset_state_changed_cb();
+    if (BT_ERROR_NONE != ret)
+    {
+        OIC_LOG(DEBUG, TAG, "bt_adapter_unset_state_changed_cb failed");
+        return CA_STATUS_FAILED;
+    }
+
+    ret = bt_deinitialize();
+    if (0 != ret)
+    {
+        OIC_LOG(ERROR, TAG, "bt_deinitialize failed");
+        return CA_STATUS_FAILED;
+    }
+
+    if (g_mainloop)
+    {
+        g_main_loop_quit(g_mainloop);
+    }
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAGetLEAdapterState()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    bt_adapter_state_e adapterState = BT_ADAPTER_DISABLED;
+
+    //Get Bluetooth adapter state
+    int ret = bt_adapter_get_state(&adapterState);
+    if (BT_ERROR_NONE != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "Bluetooth get state failed!, error num [%x]",
+                  ret);
+        return CA_STATUS_FAILED;
+    }
+
+    if (BT_ADAPTER_ENABLED != adapterState)
+    {
+        OIC_LOG(DEBUG, TAG, "BT Adapter is not enabled");
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAGetLEAddress(char **local_address)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    VERIFY_NON_NULL(local_address, TAG, "local_address is null")
+
+    char *address = NULL;
+
+    int ret = bt_adapter_get_address(&address);
+    if (BT_ERROR_NONE != ret || !address)
+    {
+        OIC_LOG_V(ERROR, TAG, "bt_adapter_get_address failed!, error num [%x]",
+                  ret);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "bd address[%s]", address);
+
+    *local_address = address;
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCallback callback)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    ca_mutex_lock(g_bleDeviceStateChangedCbMutex);
+    g_bleDeviceStateChangedCallback = callback;
+    ca_mutex_unlock(g_bleDeviceStateChangedCbMutex);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAUnSetLEAdapterStateChangedCb()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    ca_mutex_lock(g_bleDeviceStateChangedCbMutex);
+    g_bleDeviceStateChangedCallback = NULL;
+    ca_mutex_unlock(g_bleDeviceStateChangedCbMutex);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCallback callback)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    ca_mutex_lock(g_bleConnectionStateChangedCbMutex);
+    g_bleConnectionStateChangedCallback = callback;
+    ca_mutex_unlock(g_bleConnectionStateChangedCbMutex);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAUnsetLENWConnectionStateChangedCb()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    ca_mutex_lock(g_bleConnectionStateChangedCbMutex);
+    g_bleConnectionStateChangedCallback = NULL;
+    ca_mutex_unlock(g_bleConnectionStateChangedCbMutex);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CALEAdapterStateChangedCb(int result, bt_adapter_state_e adapter_state,
+                                          void *user_data)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    ca_mutex_lock(g_bleDeviceStateChangedCbMutex);
+
+    if (NULL == g_bleDeviceStateChangedCallback)
+    {
+        OIC_LOG(ERROR, TAG, "g_bleDeviceStateChangedCallback is NULL!");
+        ca_mutex_unlock(g_bleDeviceStateChangedCbMutex);
+        return;
+    }
+
+    if (BT_ADAPTER_DISABLED == adapter_state)
+    {
+        OIC_LOG(DEBUG, TAG, "Adapter is disabled");
+        g_bleDeviceStateChangedCallback(CA_ADAPTER_DISABLED);
+        ca_mutex_unlock(g_bleDeviceStateChangedCbMutex);
+        return;
+    }
+
+    OIC_LOG(DEBUG, TAG, "Adapter is Enabled");
+    g_bleDeviceStateChangedCallback(CA_ADAPTER_ENABLED);
+    ca_mutex_unlock(g_bleDeviceStateChangedCbMutex);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CALENWConnectionStateChangedCb(int result, bool connected,
+                                    const char *remoteAddress, void *userData)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    VERIFY_NON_NULL_VOID(remoteAddress, TAG, "remote address is NULL");
+
+    ca_mutex_lock(g_bleConnectionStateChangedCbMutex);
+    char *addr = OICStrdup(remoteAddress);
+    if (NULL == addr)
+    {
+        OIC_LOG(ERROR, TAG, "addr is NULL");
+        ca_mutex_unlock(g_bleConnectionStateChangedCbMutex);
+        return;
+    }
+    g_bleConnectionStateChangedCallback(CA_ADAPTER_GATT_BTLE, addr, connected);
+    OICFree(addr);
+    ca_mutex_unlock(g_bleConnectionStateChangedCbMutex);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleserver.c b/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleserver.c
new file mode 100644 (file)
index 0000000..125de56
--- /dev/null
@@ -0,0 +1,888 @@
+/******************************************************************
+*
+* Copyright 2014 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 "caleserver.h"
+#include "cacommon.h"
+#include "cacommonutil.h"
+#include "camutex.h"
+#include "caqueueingthread.h"
+#include "cagattservice.h"
+#include "oic_malloc.h"
+#include "caleutil.h"
+
+/**
+ * Logging tag for module name
+ */
+#define TAG "OIC_CA_LE_SERVER"
+
+/**
+ * Initial buffer size for Gatt Server.
+ */
+#define CA_LE_INITIAL_BUF_SIZE 512
+
+/**
+ * The handle of the OIC server.
+ */
+static bt_gatt_server_h g_gattServer = NULL;
+
+/**
+ * The handle of the OIC service.
+ */
+static bt_gatt_h g_gattSvcPath = NULL;
+
+/**
+ * The handle of the OIC read characteristics.
+ */
+static bt_gatt_h g_gattReadCharPath = NULL;
+
+/**
+ * The handle of the OIC write characteristics.
+ */
+static bt_gatt_h g_gattWriteCharPath = NULL;
+
+/**
+ * The handle to control Bluetooth LE advertising.
+ */
+static bt_advertiser_h g_hAdvertiser = NULL;
+
+/**
+ * Callback register with LE adapter.  This callback is called on reception of any
+ * data from the remote device.
+ */
+static CABLEDataReceivedCallback g_leServerDataReceivedCallback = NULL;
+
+/**
+ * Callback to notify any error in LE adapter.
+ */
+static CABLEErrorHandleCallback g_serverErrorCallback;
+
+/**
+ * To keep the state of GATT server if started or not.
+ */
+static bool g_isLEGattServerStarted = false;
+
+/**
+ * Mutex to synchronize the calls to start and stop server.
+ */
+static ca_mutex g_leServerStateMutex = NULL;
+
+/**
+ * Mutex to synchronize writing operations on the characteristics.
+ */
+static  ca_mutex g_leCharacteristicMutex = NULL;
+
+/**
+ * Mutex to synchronize to creation of OIC service.
+ */
+static  ca_mutex g_leServiceMutex = NULL;
+
+/**
+ * Mutex to synchronize access to the requestResponse callback to be called
+ * when the data needs to be sent from GATTClient.
+ */
+static  ca_mutex g_leReqRespCbMutex = NULL;
+
+/**
+ * Mutex to synchronize the task to be pushed to thread pool.
+ */
+static ca_mutex g_leServerThreadPoolMutex = NULL;
+
+/**
+ * Reference to threadpool.
+ */
+static ca_thread_pool_t g_leServerThreadPool = NULL;
+
+/**
+ * GmainLoop to manage the threads to receive the callback from the platfrom.
+ */
+static GMainLoop *g_eventLoop = NULL;
+
+static CALEConnectionStateChangedCallback g_connStateCb = NULL;
+
+void CASetLEConnectionStateChangedCallback(CALEConnectionStateChangedCallback connStateCb)
+{
+    g_connStateCb = connStateCb;
+}
+
+void CALEGattServerConnectionStateChanged(bool connected, const char *remoteAddress)
+{
+    VERIFY_NON_NULL_VOID(remoteAddress, TAG, "remote address");
+
+    if (connected)
+    {
+        OIC_LOG_V(DEBUG, TAG, "Connected to [%s]", remoteAddress);
+        if (g_connStateCb)
+        {
+            g_connStateCb(CA_ADAPTER_GATT_BTLE, remoteAddress, true);
+        }
+    }
+    else
+    {
+        OIC_LOG_V(DEBUG, TAG, "Disconnected from [%s]", remoteAddress);
+        if (g_connStateCb)
+        {
+            g_connStateCb(CA_ADAPTER_GATT_BTLE, remoteAddress, false);
+        }
+    }
+}
+
+void CALEServerNotificationSentCB(int result, char *remote_address, bt_gatt_server_h server,
+                                  bt_gatt_h characteristic, bool completed, void *user_data)
+{
+    OIC_LOG_V(DEBUG, TAG, "Notification to the device[%s] result[%d]", remote_address, result);
+}
+
+CAResult_t CAStartLEGattServer()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    ca_mutex_lock(g_leServerThreadPoolMutex);
+    if (NULL == g_leServerThreadPool)
+    {
+        OIC_LOG(ERROR, TAG, "g_leServerThreadPool is NULL");
+        ca_mutex_unlock(g_leServerThreadPoolMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    CAResult_t ret = ca_thread_pool_add_task(g_leServerThreadPool, CAStartLEGattServerThread,
+                                             NULL);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "ca_thread_pool_add_task failed with ret [%d]", ret);
+        ca_mutex_unlock(g_leServerThreadPoolMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    ca_mutex_unlock(g_leServerThreadPoolMutex);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CALENotificationCb(bool notify, bt_gatt_server_h server, bt_gatt_h gatt_handle,
+                        void *user_data)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    if(notify)
+    {
+        OIC_LOG(DEBUG, TAG, "Notification is subscribed by the client");
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CALEStartAdvertise(const char *serviceUUID)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    int res = bt_adapter_le_create_advertiser(&g_hAdvertiser);
+    if (NULL == g_hAdvertiser || BT_ERROR_NONE != res)
+    {
+        OIC_LOG_V(ERROR, TAG, "g_hAdvertiser is NULL/ Result is %d", res);
+        return CA_STATUS_FAILED;
+    }
+
+    res = bt_adapter_le_add_advertising_service_uuid(g_hAdvertiser,
+                                                     BT_ADAPTER_LE_PACKET_ADVERTISING,
+                                                     serviceUUID);
+    if (BT_ERROR_NONE != res)
+    {
+        OIC_LOG_V(ERROR, TAG, "bt_adapter_le_add_advertising_service_uuid failed with ret[%s]",
+                  CALEGetErrorMsg(res));
+        return CA_STATUS_FAILED;
+    }
+
+    res = bt_adapter_le_start_advertising(g_hAdvertiser, NULL, NULL, NULL);
+    if (BT_ERROR_NONE != res)
+    {
+        OIC_LOG_V(ERROR, TAG, "bt_adapter_le_start_advertising failed with ret[%s]",
+                  CALEGetErrorMsg(res));
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEStopAdvertise()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    if (NULL != g_hAdvertiser)
+    {
+        int ret  = bt_adapter_le_stop_advertising(g_hAdvertiser);
+        if (0 != ret)
+        {
+            OIC_LOG_V(ERROR, TAG,
+                      "bt_adapter_le_stop_advertising failed with ret[%s]", CALEGetErrorMsg(ret));
+        }
+
+        ret = bt_adapter_le_destroy_advertiser(g_hAdvertiser);
+        if (0 != ret)
+        {
+            OIC_LOG_V(ERROR, TAG,
+                      "bt_adapter_le_destroy_advertiser failed with ret[%s]", CALEGetErrorMsg(ret));
+        }
+        g_hAdvertiser = NULL;
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "Advertising is not running");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAStartLEGattServerThread(void *data)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    ca_mutex_lock(g_leServerStateMutex);
+    if (true == g_isLEGattServerStarted)
+    {
+        OIC_LOG(ERROR, TAG, "Gatt Server is already running");
+        ca_mutex_unlock(g_leServerStateMutex);
+        CATerminateLEGattServer();
+        return;
+    }
+
+    CAResult_t ret  =  CAInitLEGattServer();
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "CAInitLEGattService failed[%d]", ret);
+        ca_mutex_unlock(g_leServerStateMutex);
+        CATerminateLEGattServer();
+        return;
+    }
+
+    char *serviceUUID = CA_GATT_SERVICE_UUID;
+
+    ret  = CAAddNewLEServiceInGattServer(serviceUUID);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "CAAddNewLEServiceInGattServer failed[%d]", ret);
+        ca_mutex_unlock(g_leServerStateMutex);
+        CATerminateLEGattServer();
+        return;
+    }
+
+    static const char charReadUUID[] = CA_GATT_RESPONSE_CHRC_UUID;
+    char charReadValue[] = {33, 44, 55, 66}; // These are initial random values
+
+    // For Read Characteristics.
+    ret = CAAddNewCharacteristicsToGattServer(g_gattSvcPath, charReadUUID, charReadValue,
+                                              CA_LE_INITIAL_BUF_SIZE, true);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "CAAddNewCharacteristicsToGattServer failed[%d]", ret);
+        ca_mutex_unlock(g_leServerStateMutex);
+        CATerminateLEGattServer();
+        return;
+    }
+
+    static const char charWriteUUID[] = CA_GATT_REQUEST_CHRC_UUID;
+    char charWriteValue[] = {33, 44, 55, 66}; // These are initial random values
+
+
+    ret = CAAddNewCharacteristicsToGattServer(g_gattSvcPath, charWriteUUID, charWriteValue,
+            CA_LE_INITIAL_BUF_SIZE, false); // For Write Characteristics.
+    if (CA_STATUS_OK != ret )
+    {
+        OIC_LOG_V(ERROR, TAG, "CAAddNewCharacteristicsToGattServer failed[%d]", ret);
+        ca_mutex_unlock(g_leServerStateMutex);
+        CATerminateLEGattServer();
+        return;
+    }
+
+    ret = CARegisterLEServicewithGattServer(g_gattSvcPath);
+    if (CA_STATUS_OK != ret )
+    {
+        OIC_LOG_V(ERROR, TAG, "CARegisterLEServicewithGattServer failed[%d]", ret);
+        ca_mutex_unlock(g_leServerStateMutex);
+        CATerminateLEGattServer();
+        return;
+    }
+
+    ret = CALEStartAdvertise(serviceUUID);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "CALEStartAdvertise failed[%d]", ret);
+        ca_mutex_unlock(g_leServerStateMutex);
+        CATerminateLEGattServer();
+        return;
+    }
+
+    g_isLEGattServerStarted = true;
+
+    ca_mutex_unlock(g_leServerStateMutex);
+
+    OIC_LOG(DEBUG, TAG, "LE Server initialization complete.");
+
+    GMainContext *thread_context = NULL;
+
+    thread_context = g_main_context_new();
+
+    g_eventLoop = g_main_loop_new(thread_context, FALSE);
+
+    g_main_context_push_thread_default(thread_context);
+
+    g_main_loop_run(g_eventLoop);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CAStopLEGattServer()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    ca_mutex_lock(g_leServerStateMutex);
+
+    if (false == g_isLEGattServerStarted)
+    {
+        OIC_LOG(ERROR, TAG, "Gatt Server is not running to stop");
+        ca_mutex_unlock(g_leServerStateMutex);
+        return CA_STATUS_OK;
+    }
+
+    g_isLEGattServerStarted = false;
+
+    CAResult_t res = CALEStopAdvertise();
+    {
+        OIC_LOG_V(ERROR, TAG, "CALEStopAdvertise failed with ret[%d]", res);
+    }
+
+    res = CADeInitLEGattServer();
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG_V(ERROR, TAG, "CADeInitLEGattService failed with ret[%d]", res);
+    }
+
+    GMainContext  *context_event_loop = NULL;
+    // Required for waking up the thread which is running in gmain loop
+    if (NULL != g_eventLoop)
+    {
+        context_event_loop = g_main_loop_get_context(g_eventLoop);
+
+        if (context_event_loop)
+        {
+            OIC_LOG_V(DEBUG,  TAG, "g_eventLoop context %x", context_event_loop);
+            g_main_context_wakeup(context_event_loop);
+
+            // Kill g main loops and kill threads
+            g_main_loop_quit(g_eventLoop);
+        }
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "g_eventLoop context is NULL");
+    }
+
+    ca_mutex_unlock(g_leServerStateMutex);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAInitializeLEGattServer()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    CAResult_t ret = CAInitGattServerMutexVariables();
+    if (CA_STATUS_OK != ret )
+    {
+        OIC_LOG(ERROR, TAG, "CAInitGattServerMutexVariables failed!");
+        CATerminateGattServerMutexVariables();
+        return CA_SERVER_NOT_STARTED;
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return ret;
+}
+
+void CATerminateLEGattServer()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    // Service and characteristics path will be freed by the platform.
+    ca_mutex_lock(g_leServiceMutex);
+    g_gattSvcPath = NULL;
+    ca_mutex_unlock(g_leServiceMutex);
+
+    ca_mutex_lock(g_leCharacteristicMutex);
+    g_gattReadCharPath = NULL;
+    g_gattWriteCharPath = NULL;
+    ca_mutex_unlock(g_leCharacteristicMutex);
+
+    ca_mutex_lock(g_leServerThreadPoolMutex);
+    g_leServerThreadPool = NULL;
+    ca_mutex_unlock(g_leServerThreadPoolMutex);
+
+    // Terminating all mutex variables.
+    CATerminateGattServerMutexVariables();
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CAInitGattServerMutexVariables()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    if (NULL == g_leServerStateMutex)
+    {
+        g_leServerStateMutex = ca_mutex_new();
+        if (NULL == g_leServerStateMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_leServiceMutex)
+    {
+        g_leServiceMutex = ca_mutex_new();
+        if (NULL == g_leServiceMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_leCharacteristicMutex)
+    {
+        g_leCharacteristicMutex = ca_mutex_new();
+        if (NULL == g_leCharacteristicMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_leReqRespCbMutex)
+    {
+        g_leReqRespCbMutex = ca_mutex_new();
+        if (NULL == g_leReqRespCbMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CATerminateGattServerMutexVariables()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    ca_mutex_free(g_leServerStateMutex);
+    g_leServerStateMutex = NULL;
+
+    ca_mutex_free(g_leServiceMutex);
+    g_leServiceMutex = NULL;
+
+    ca_mutex_free(g_leCharacteristicMutex);
+    g_leCharacteristicMutex = NULL;
+
+    ca_mutex_free(g_leReqRespCbMutex);
+    g_leReqRespCbMutex = NULL;
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CAInitLEGattServer()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    int ret =  bt_gatt_server_initialize();
+    if (0 != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "bt_gatt_server_initialize failed with ret[%s]",
+                  CALEGetErrorMsg(ret));
+        return CA_STATUS_FAILED;
+    }
+
+    bt_gatt_server_h server;
+
+    ret = bt_gatt_server_create(&server);
+    if (0 != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "bt_gatt_server_create failed with ret[%s]",
+                  CALEGetErrorMsg(ret));
+        return CA_STATUS_FAILED;
+    }
+
+    if (NULL != g_gattServer)
+    {
+        OICFree(g_gattServer);
+        g_gattServer = NULL;
+    }
+    g_gattServer = server;
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CADeInitLEGattServer()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    int ret = bt_gatt_server_unregister_all_services(g_gattServer);
+    if (0 != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "bt_gatt_server_unregister_all_services failed with ret[%s]",
+                  CALEGetErrorMsg(ret));
+        return CA_STATUS_FAILED;
+    }
+
+    ret = bt_gatt_server_destroy(g_gattServer);
+    if (0 != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "bt_gatt_server_destroy failed with ret[%s]",
+                  CALEGetErrorMsg(ret));
+        return CA_STATUS_FAILED;
+    }
+
+    ret =  bt_gatt_server_deinitialize();
+    if (0 != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "bt_gatt_server_deinitialize failed with ret[%s]",
+                  CALEGetErrorMsg(ret));
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CASetLEServerThreadPoolHandle(ca_thread_pool_t handle)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    ca_mutex_lock(g_leServerThreadPoolMutex);
+    g_leServerThreadPool = handle;
+    ca_mutex_unlock(g_leServerThreadPoolMutex);
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CAAddNewLEServiceInGattServer(const char *serviceUUID)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    VERIFY_NON_NULL(serviceUUID, TAG, "serviceUUID");
+
+    OIC_LOG_V(DEBUG, TAG, "service uuid %s", serviceUUID);
+
+    bt_gatt_h service = NULL;
+    bt_gatt_service_type_e type = BT_GATT_SERVICE_TYPE_PRIMARY;
+
+    int ret = bt_gatt_service_create(serviceUUID, type, &service);
+    if (0 != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "bt_gatt_service_create failed with ret [%s]",
+                  CALEGetErrorMsg(ret));
+        return CA_STATUS_FAILED;
+    }
+
+    if (NULL != service)
+    {
+        OIC_LOG_V(DEBUG, TAG, "ServicePath obtained is %s", (char *)service);
+
+        ca_mutex_lock(g_leServiceMutex);
+
+        if (NULL != g_gattSvcPath)
+        {
+            OICFree(g_gattSvcPath);
+            g_gattSvcPath = NULL;
+        }
+        g_gattSvcPath = service;
+
+        ca_mutex_unlock(g_leServiceMutex);
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CALEGattRemoteCharacteristicWriteCb(char *remoteAddress, bt_gatt_server_h server,
+                                         bt_gatt_h charPath, int offset, char *charValue,
+                                         int charValueLen, void *userData)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    if (NULL == charValue || NULL == remoteAddress)
+    {
+        OIC_LOG(ERROR, TAG, "Param callback values are NULL");
+        return;
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "charPath = [%s] charValue = [%s] len [%d]", (char *)charPath,
+              charValue, charValueLen);
+
+    uint8_t *data = OICMalloc(charValueLen);
+    if (NULL == data)
+    {
+        OIC_LOG(ERROR, TAG, "Malloc failed!");
+        return;
+    }
+
+    memcpy(data, charValue, charValueLen);
+
+    ca_mutex_lock(g_leReqRespCbMutex);
+    if (NULL == g_leServerDataReceivedCallback)
+    {
+        OIC_LOG(ERROR, TAG, "gReqRespCallback is NULL!");
+        ca_mutex_unlock(g_leReqRespCbMutex);
+        OICFree(data);
+        return;
+    }
+
+    OIC_LOG(DEBUG, TAG, "Sending data up !");
+    uint32_t sentLength = 0;
+    g_leServerDataReceivedCallback(remoteAddress, data, charValueLen,
+                                    &sentLength);
+    ca_mutex_unlock(g_leReqRespCbMutex);
+    OICFree(data);
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CARegisterLEServicewithGattServer(const bt_gatt_h svcPath)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    VERIFY_NON_NULL(svcPath, TAG, "svcPath");
+
+    OIC_LOG_V(DEBUG, TAG, "svcPath:%s", svcPath);
+
+    int ret = bt_gatt_server_register_service(g_gattServer, svcPath);
+    if (0 != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "bt_gatt_server_register_service failed with ret[%s]",
+                  CALEGetErrorMsg(ret));
+        return CA_STATUS_FAILED;
+    }
+
+    ret = bt_gatt_server_set_value_changed_cb(g_gattWriteCharPath,
+                                              CALEGattRemoteCharacteristicWriteCb, NULL);
+
+    if (0 != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "bt_gatt_server_set_value_changed_cb failed with ret[%s]",
+                  CALEGetErrorMsg(ret));
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAAddNewCharacteristicsToGattServer(const bt_gatt_h svcPath, const char *charUUID,
+                                               const char *charValue, int charValueLen, bool read)
+{
+
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    int permissions = BT_GATT_PERMISSION_READ | BT_GATT_PERMISSION_WRITE;
+    int properties = BT_GATT_PROPERTY_WRITE | BT_GATT_PROPERTY_NOTIFY;
+    if(read)
+    {
+        properties = BT_GATT_PROPERTY_NOTIFY | BT_GATT_PROPERTY_READ;
+    }
+    else
+    {
+        properties = BT_GATT_PROPERTY_WRITE | BT_GATT_PROPERTY_READ;
+    }
+
+    bt_gatt_h charPath;
+
+    int ret = bt_gatt_characteristic_create(charUUID, permissions, properties, charValue,
+                                            charValueLen, &charPath);
+
+    if (0 != ret || NULL == charPath)
+    {
+        OIC_LOG_V(ERROR, TAG,
+                  "bt_gatt_add_characteristic  failed with ret [%s]", CALEGetErrorMsg(ret));
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG_V(DEBUG, TAG,
+              "bt_gatt_characteristic_create charPath obtained: %s", (char *)charPath);
+
+    if (read)
+    {
+        ret = bt_gatt_server_set_notification_state_change_cb(charPath, CALENotificationCb, NULL);
+        if (0 != ret)
+        {
+            OIC_LOG_V(ERROR, TAG,
+                      "bt_gatt_server_set_notification_state_change_cb  failed with ret[%s]",
+                      CALEGetErrorMsg(ret));
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    ret =  bt_gatt_service_add_characteristic(svcPath, charPath);
+    if (0 != ret)
+    {
+        OIC_LOG_V(ERROR, TAG,
+                  "bt_gatt_service_add_characteristic  failed with ret[%s]",
+                  CALEGetErrorMsg(ret));
+        return CA_STATUS_FAILED;
+    }
+
+    ca_mutex_lock(g_leCharacteristicMutex);
+
+    if (read)
+    {
+        char desc_value[2] = {1, 0};  // Notification enabled.
+        bt_gatt_h descriptor = NULL;
+        permissions = BT_GATT_PERMISSION_READ | BT_GATT_PERMISSION_WRITE;
+        ret = bt_gatt_descriptor_create(CA_GATT_CONFIGURATION_DESC_UUID,
+                                        permissions, desc_value, sizeof(desc_value), &descriptor);
+        if (0 != ret)
+        {
+            OIC_LOG_V(ERROR, TAG,
+                      "bt_gatt_descriptor_create  failed with ret[%s]",
+                      CALEGetErrorMsg(ret));
+            return CA_STATUS_FAILED;
+        }
+
+        ret = bt_gatt_characteristic_add_descriptor(charPath, descriptor);
+        if (0 != ret)
+        {
+            OIC_LOG_V(ERROR, TAG,
+                      "bt_gatt_characteristic_add_descriptor  failed with ret[%s]",
+                      CALEGetErrorMsg(ret));
+            return CA_STATUS_FAILED;
+        }
+
+        if (NULL != g_gattReadCharPath)
+        {
+            OICFree(g_gattReadCharPath);
+            g_gattReadCharPath = NULL;
+        }
+        g_gattReadCharPath = charPath;
+
+    }
+    else
+    {
+        if (NULL != g_gattWriteCharPath)
+        {
+            OICFree(g_gattWriteCharPath);
+            g_gattWriteCharPath = NULL;
+        }
+        g_gattWriteCharPath = charPath;
+    }
+
+    ca_mutex_unlock(g_leCharacteristicMutex);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAUpdateCharacteristicsToGattClient(const char *address, const uint8_t *charValue,
+                                               uint32_t charValueLen)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    VERIFY_NON_NULL(charValue, TAG, "charValue");
+    VERIFY_NON_NULL(address, TAG, "address");
+
+    OIC_LOG_V(DEBUG, TAG, "Client's Unicast address for sending data [%s]", address);
+
+    ca_mutex_lock(g_leCharacteristicMutex);
+
+    if (NULL  == g_gattReadCharPath)
+    {
+        OIC_LOG(ERROR, TAG, "g_gattReadCharPath is NULL");
+        ca_mutex_unlock(g_leCharacteristicMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    int ret = bt_gatt_set_value(g_gattReadCharPath, (char *)charValue, charValueLen);
+    if (0 != ret)
+    {
+        OIC_LOG_V(ERROR, TAG,
+                  "bt_gatt_set_value failed with return [%s]", CALEGetErrorMsg(ret));
+        ca_mutex_unlock(g_leCharacteristicMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    ret = bt_gatt_server_notify(g_gattReadCharPath, false, CALEServerNotificationSentCB,
+                                address, NULL);
+    if (0 != ret)
+    {
+        OIC_LOG_V(ERROR, TAG,
+                  "bt_gatt_server_notify failed with return [%s]", CALEGetErrorMsg(ret));
+        ca_mutex_unlock(g_leCharacteristicMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    ca_mutex_unlock(g_leCharacteristicMutex);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAUpdateCharacteristicsToAllGattClients(const uint8_t *charValue, uint32_t charValueLen)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    VERIFY_NON_NULL(charValue, TAG, "charValue");
+
+    ca_mutex_lock(g_leCharacteristicMutex);
+
+    if (NULL  == g_gattReadCharPath)
+    {
+        OIC_LOG(ERROR, TAG, "g_gattReadCharPath is NULL");
+        ca_mutex_unlock(g_leCharacteristicMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    int ret = bt_gatt_set_value(g_gattReadCharPath, (char *)charValue, charValueLen);
+    if (0 != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "bt_gatt_set_value failed with return[%s]", CALEGetErrorMsg(ret));
+        ca_mutex_unlock(g_leCharacteristicMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    ret = bt_gatt_server_notify(g_gattReadCharPath, false, CALEServerNotificationSentCB,
+                                NULL, NULL);
+    if (0 != ret)
+    {
+        OIC_LOG_V(ERROR, TAG,
+                  "bt_gatt_server_notify failed with return[%s]", CALEGetErrorMsg(ret));
+        ca_mutex_unlock(g_leCharacteristicMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    ca_mutex_unlock(g_leCharacteristicMutex);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CASetLEReqRespServerCallback(CABLEDataReceivedCallback callback)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    ca_mutex_lock(g_leReqRespCbMutex);
+    g_leServerDataReceivedCallback = callback;
+    ca_mutex_unlock(g_leReqRespCbMutex);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CASetBLEServerErrorHandleCallback(CABLEErrorHandleCallback callback)
+{
+    g_serverErrorCallback = callback;
+}
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleserver.h b/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleserver.h
new file mode 100644 (file)
index 0000000..100ea9b
--- /dev/null
@@ -0,0 +1,177 @@
+/* ****************************************************************
+ *
+ * Copyright 2014 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ *
+ * This file contains the APIs related to the GATT Server functionalities.
+ * Creation of the GattServer with the characteristics. Enabling the
+ * advertisement and updating the characteristics for the response and
+ * notifying the change of characteristcs for the request will be done here.
+ * LE adapter will interact with this sub module.
+ */
+
+#ifndef TZ_BLE_SERVER_H_
+#define TZ_BLE_SERVER_H_
+
+#include <bluetooth.h>
+#include <bluetooth_type.h>
+#include <bluetooth_internal.h>
+
+#include "caadapterinterface.h"
+#include "logger.h"
+#include "cathreadpool.h"
+#include "caleinterface.h"
+
+/**
+ * This is thread which will be used for creating ble service and advertise ble service.
+ * 1. Create New OIC Service 2. Add read & write characteristics to service.
+ * 3. Register Service       4. Advertise service.
+ *
+ * @param[in] data  Currently it will be NULL.
+ */
+void CAStartLEGattServerThread(void *data);
+
+/**
+ * Used to initialize gatt server.
+ *
+ * @return  ::CA_STATUS_OK or Appropriate error code.
+ * @retval  ::CA_STATUS_OK  Successful.
+ * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
+ * @retval  ::CA_STATUS_FAILED Operation failed.
+ */
+CAResult_t CAInitLEGattServer();
+
+/**
+ * Used to de-initialize gatt service and destroy the GATT server.
+ *
+ * @return  ::CA_STATUS_OK or Appropriate error code.
+ * @retval  ::CA_STATUS_OK  Successful.
+ * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
+ * @retval  ::CA_STATUS_FAILED Operation failed.
+ */
+CAResult_t CADeInitLEGattServer();
+
+/**
+ * Used to initialize all required mutex variables for GATT server implementation.
+ *
+ * @return  ::CA_STATUS_OK or Appropriate error code.
+ * @retval  ::CA_STATUS_OK  Successful.
+ * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
+ * @retval  ::CA_STATUS_FAILED Operation failed.
+ */
+CAResult_t CAInitGattServerMutexVariables();
+
+/**
+ * Used to start advertising.
+ *
+ * @return  ::CA_STATUS_OK or Appropriate error code.
+ * @retval  ::CA_STATUS_OK  Successful.
+ * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
+ * @retval  ::CA_STATUS_FAILED Operation failed.
+ */
+CAResult_t CALEStartAdvertise(const char *serviceUUID);
+
+/**
+ * Used to stop advertising.
+ *
+ * @return  ::CA_STATUS_OK or Appropriate error code.
+ * @retval  ::CA_STATUS_OK  Successful.
+ * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
+ * @retval  ::CA_STATUS_FAILED Operation failed.
+ */
+CAResult_t CALEStopAdvertise();
+
+/**
+ * Used to terminate all required mutex variables for GATT server implementation.
+ */
+void CATerminateGattServerMutexVariables();
+
+/**
+ * Used to add new OIC service in GATT server using bt_gatt_add_service api and
+ * internally store service path(outparam) in global variable.
+ *
+ * @param[in]  serviceUUID  unique identifier for BLE OIC service.
+ *
+ * @return  ::CA_STATUS_OK or Appropriate error code.
+ * @retval  ::CA_STATUS_OK  Successful.
+ * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
+ * @retval  ::CA_STATUS_FAILED Operation failed.
+ */
+CAResult_t CAAddNewLEServiceInGattServer(const char *serviceUUID);
+
+/**
+ * Used to register the service in Gatt Server using bt_gatt_register_service api.
+ *
+ * @param[in] svcPath  unique identifier for BLE OIC service which is outparam of
+ *                     bt_gatt_service_create api.
+ * @return  ::CA_STATUS_OK or Appropriate error code.
+ * @retval  ::CA_STATUS_OK  Successful.
+ * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
+ * @retval  ::CA_STATUS_FAILED Operation failed.
+ */
+CAResult_t CARegisterLEServicewithGattServer(const bt_gatt_h svcPath);
+
+/**
+ * Used to add new characteristics(Read/Write) to the service in Gatt Server using
+ * bt_gatt_add_characteristic api.
+ * @param[in] svcPath         Service path to which this characteristic belongs to.
+ * @param[in] charUUID        Gatt characteristic uuid.
+ * @param[in] charValue       Gatt characteristic value.
+ * @param[in] charValueLen    Characteristic value length.
+ * @param[in] read            Boolean variable for checking whether read characteristics or
+ *                            write characteristics.
+ * @return  ::CA_STATUS_OK or Appropriate error code.
+ */
+CAResult_t CAAddNewCharacteristicsToGattServer(const bt_gatt_h svcPath, const char *charUUID,
+                                               const char *charValue, int charValueLen, bool read);
+
+/**
+ * This is the callback which will be called when client update one of the characteristics
+ * with data.
+ * @param[in] remote_address The address of the remote device which requests a change
+ * @param[in] server         The GATT server handle
+ * @param[in] gatt_handle    The characteristic or descriptor's GATT handle which has an old value
+ * @param[in] offset         The requested offset from where the @a gatt_handle value will be updated
+ * @param[in] value          The new value
+ * @param[in] len            The length of @a value
+ * @param[in] user_data      The user data passed from the registration function
+ */
+void CALEGattRemoteCharacteristicWriteCb(char *remoteAddress, bt_gatt_server_h server,
+                                         bt_gatt_h charPath, int offset, char *charValue,
+                                         int charValueLen, void *userData);
+
+/**
+ * This is the callback which will be called whenever there is change in gatt connection
+ * with Client(Connected/Disconnected).
+ *
+ * @param[in]  connected      State of connection.
+ * @param[in]  remoteAddress  Mac address of the remote device in which we made connection.
+ */
+void CALEGattServerConnectionStateChanged(bool connected, const char *remoteAddress);
+
+/**
+ * Setting the connection state changed callback.
+ * @param[in] connStateCb      callback for receiving the changed network info.
+ */
+void CASetLEConnectionStateChangedCallback(CALEConnectionStateChangedCallback connStateCb);
+
+#endif /* TZ_BLE_SERVER_H_ */
+
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleutil.c b/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleutil.c
new file mode 100644 (file)
index 0000000..8dc46dd
--- /dev/null
@@ -0,0 +1,279 @@
+/* ****************************************************************
+ *
+ * Copyright 2014 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 "caleutil.h"
+
+#include<stdio.h>
+#include<stdlib.h>
+#include<string.h>
+#include<arpa/inet.h>
+#include<sys/types.h>
+#include<sys/socket.h>
+#include<netinet/in.h>
+
+
+#include "caadapterutils.h"
+#include "oic_string.h"
+#include "oic_malloc.h"
+
+/**
+ * Logging tag for module name
+ */
+#define TAG "OIC_CA_LE_UTIL"
+
+/**
+ * Number of services connected.
+ */
+static int32_t g_numberOfServiceConnected = 0;
+
+void CAIncrementRegisteredServiceCount()
+{
+    g_numberOfServiceConnected++;
+}
+
+void CADecrementRegisteredServiceCount()
+{
+    g_numberOfServiceConnected--;
+}
+
+void CAResetRegisteredServiceCount()
+{
+    g_numberOfServiceConnected = 0;
+}
+
+int32_t  CAGetRegisteredServiceCount()
+{
+    return g_numberOfServiceConnected ;
+}
+
+CAResult_t CAAddLEServerInfoToList(LEServerInfoList **serverList,
+                                   LEServerInfo *leServerInfo)
+{
+
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    VERIFY_NON_NULL(serverList, TAG, "clientList");
+    VERIFY_NON_NULL(leServerInfo, TAG, "leClientInfo");
+
+    LEServerInfoList *node = (LEServerInfoList *) OICCalloc(1, sizeof(LEServerInfoList));
+    if (NULL == node)
+    {
+        OIC_LOG(ERROR, TAG, "Malloc failed!");
+        return CA_STATUS_FAILED;
+    }
+
+    node->serverInfo = leServerInfo;
+    node->next = NULL;
+
+    if (*serverList == NULL)   // Empty list
+    {
+        *serverList = node;
+    }
+    else     // Add at front end
+    {
+        node->next = *serverList;
+        *serverList = node;
+    }
+
+    CAIncrementRegisteredServiceCount();
+
+    OIC_LOG_V(DEBUG, TAG, "Device [%s] added to list",
+              leServerInfo->remoteAddress);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAGetLEServerInfo(LEServerInfoList *serverList, const char *leAddress,
+                             LEServerInfo **leServerInfo)
+{
+
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    VERIFY_NON_NULL(serverList, TAG, "clientList");
+    VERIFY_NON_NULL(leServerInfo, TAG, "leClientInfo");
+    VERIFY_NON_NULL(leAddress, TAG, "leAddress");
+
+    LEServerInfoList *cur = serverList;
+    *leServerInfo = NULL;
+    while (cur != NULL)
+    {
+        if (!strcasecmp(cur->serverInfo->remoteAddress , leAddress))
+        {
+            *leServerInfo = cur->serverInfo;
+            OIC_LOG(DEBUG, TAG, "OUT");
+            return CA_STATUS_OK;
+        }
+
+        cur = cur->next;
+    }
+
+    OIC_LOG(DEBUG, TAG, " OUT");
+    return CA_STATUS_FAILED;
+}
+
+CAResult_t CAGetLEServerInfoByPosition(LEServerInfoList *serverList, int32_t position,
+                                       LEServerInfo **leServerInfo)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    VERIFY_NON_NULL(serverList, TAG, "clientList");
+    VERIFY_NON_NULL(leServerInfo, TAG, "leClientInfo");
+
+    if (0 > position)
+    {
+        OIC_LOG(ERROR, TAG, "Position Invalid input !");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    *leServerInfo = NULL;
+    int32_t count = 0;
+    LEServerInfoList *cur = serverList;
+    while (cur != NULL)
+    {
+        if (position == count)
+        {
+            *leServerInfo = cur->serverInfo;
+            OIC_LOG(DEBUG, TAG, "OUT");
+            return CA_STATUS_OK;
+        }
+        count++;
+        cur = cur->next;
+    }
+    OIC_LOG(DEBUG, TAG, "Client info not found for the position");
+    return CA_STATUS_FAILED;
+}
+
+void CAFreeLEServerList(LEServerInfoList *clientList)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    while (clientList)
+    {
+        LEServerInfoList *temp = clientList;
+        clientList = clientList->next;
+        CAFreeLEServerInfo(temp->serverInfo);
+        OICFree(temp);
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CAFreeLEServerInfo(LEServerInfo *leServerInfo)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    if (leServerInfo)
+    {
+        if (leServerInfo->remoteAddress)
+        {
+            bt_gatt_client_destroy(leServerInfo->clientHandle);
+            int32_t ret = bt_gatt_disconnect(leServerInfo->remoteAddress);
+
+            if (BT_ERROR_NONE != ret)
+            {
+                OIC_LOG_V(ERROR, TAG,
+                          "bt_gatt_disconnect Failed with ret value [%d]",
+                          ret);
+                return;
+            }
+            OICFree(leServerInfo->remoteAddress);
+        }
+        OICFree(leServerInfo);
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+const char *CALEGetErrorMsg(bt_error_e err)
+{
+    const char *errStr = NULL;
+
+    switch (err)
+    {
+        case BT_ERROR_NONE:
+            errStr = "BT_ERROR_NONE";
+            break;
+        case BT_ERROR_CANCELLED:
+            errStr = "BT_ERROR_CANCELLED";
+            break;
+        case BT_ERROR_INVALID_PARAMETER:
+            errStr = "BT_ERROR_INVALID_PARAMETER";
+            break;
+        case BT_ERROR_OUT_OF_MEMORY:
+            errStr = "BT_ERROR_OUT_OF_MEMORY";
+            break;
+        case BT_ERROR_RESOURCE_BUSY:
+            errStr = "BT_ERROR_RESOURCE_BUSY";
+            break;
+        case BT_ERROR_TIMED_OUT:
+            errStr = "BT_ERROR_TIMED_OUT";
+            break;
+        case BT_ERROR_NOW_IN_PROGRESS:
+            errStr = "BT_ERROR_NOW_IN_PROGRESS";
+            break;
+        case BT_ERROR_NOT_INITIALIZED:
+            errStr = "BT_ERROR_NOT_INITIALIZED";
+            break;
+        case BT_ERROR_NOT_ENABLED:
+            errStr = "BT_ERROR_NOT_ENABLED";
+            break;
+        case BT_ERROR_ALREADY_DONE:
+            errStr = "BT_ERROR_ALREADY_DONE";
+            break;
+        case BT_ERROR_OPERATION_FAILED:
+            errStr = "BT_ERROR_OPERATION_FAILED";
+            break;
+        case BT_ERROR_NOT_IN_PROGRESS:
+            errStr = "BT_ERROR_NOT_IN_PROGRESS";
+            break;
+        case BT_ERROR_REMOTE_DEVICE_NOT_BONDED:
+            errStr = "BT_ERROR_REMOTE_DEVICE_NOT_BONDED";
+            break;
+        case BT_ERROR_AUTH_REJECTED:
+            errStr = "BT_ERROR_AUTH_REJECTED";
+            break;
+        case BT_ERROR_AUTH_FAILED:
+            errStr = "BT_ERROR_AUTH_FAILED";
+            break;
+        case BT_ERROR_REMOTE_DEVICE_NOT_FOUND:
+            errStr = "BT_ERROR_REMOTE_DEVICE_NOT_FOUND";
+            break;
+        case BT_ERROR_SERVICE_SEARCH_FAILED:
+            errStr = "BT_ERROR_SERVICE_SEARCH_FAILED";
+            break;
+        case BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED:
+            errStr = "BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED";
+            break;
+        case BT_ERROR_PERMISSION_DENIED:
+            errStr = "BT_ERROR_PERMISSION_DENIED";
+            break;
+        case BT_ERROR_SERVICE_NOT_FOUND:
+            errStr = "BT_ERROR_SERVICE_NOT_FOUND";
+            break;
+        case BT_ERROR_NOT_SUPPORTED:
+            errStr = "BT_ERROR_NOT_SUPPORTED";
+            break;
+        default:
+            errStr = "NOT Defined";
+            break;
+    }
+
+    return errStr;
+}
+
+
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleutil.h b/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleutil.h
new file mode 100644 (file)
index 0000000..5a38ec4
--- /dev/null
@@ -0,0 +1,156 @@
+/* ****************************************************************
+ *
+ * Copyright 2014 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ *
+ * This file contains the util function for LE adapter. This maintains the
+ * list of services an individual GATT Client connected to and operations on
+ * that list, such as getting the service info with BD address or with
+ * position etc. This is mainly useful for the multicast transmission of
+ * data where client needs to have the info of all the services to which it
+ * is connected.
+ */
+
+#ifndef TZ_BLE_UTIL_H_
+#define TZ_BLE_UTIL_H_
+
+#include <bluetooth.h>
+
+#include "cacommon.h"
+
+typedef struct
+{
+    bt_gatt_client_h clientHandle;
+    bt_gatt_h serviceHandle;
+    bt_gatt_h readChar;
+    bt_gatt_h writeChar;
+    char *remoteAddress;
+} LEServerInfo;
+
+typedef struct _LEServerInfoList
+{
+    LEServerInfo *serverInfo;
+    struct _LEServerInfoList *next;
+}LEServerInfoList;
+
+/**
+ * Different characteristics types.
+ *
+ * This provides information of different characteristics
+ * which will be added to OIC service.
+ */
+typedef enum
+{
+    BLE_GATT_WRITE_CHAR = 0, /**< write_char This will be used to get the unicast response. */
+    BLE_GATT_READ_CHAR,      /**< read_char This will be used update value to OIC server. */
+    BLE_GATT_NOTIFY_CHAR     /**< Reserved char for the time being. */
+} CHAR_TYPE;
+
+/**
+ * Used to increment the registered service count.
+ */
+void CAIncrementRegisteredServiceCount();
+
+/**
+ * Used to decrement the registered service count.
+ */
+void CADecrementRegisteredServiceCount();
+
+/**
+ * Used to reset the registered service count.
+ */
+void CAResetRegisteredServiceCount();
+
+/**
+ * Used to get the total registered service count.
+ * @return  Total registered service count.
+ */
+int32_t  CAGetRegisteredServiceCount();
+
+/**
+ * @brief  Used to add the serverListInfo structure to the Client List.
+ *
+ * @param[in] serverList     Pointer to the ble server list which holds the info of list of
+ *                           servers registered by the client.
+ * @param[in] leServerInfo   Pointer where serverInfo structure needs to be appended with
+ *                           serverList.
+ * @return ::CA_STATUS_OK or Appropriate error code.
+ * @retval ::CA_STATUS_OK  Successful.
+ * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
+ * @retval ::CA_STATUS_FAILED Operation failed.
+ */
+CAResult_t CAAddLEServerInfoToList(LEServerInfoList **serverList,
+                                   LEServerInfo *leServerInfo);
+
+/**
+ * Used to get the serviceInfo from the list.
+ *
+ * @param[in]  serverList       Pointer to the ble service list which holds the info of list
+ *                              of servers registered by the client.
+ * @param[in]  leAddress        BD address of the device where GATTServer information is required.
+ * @param[out] leServerInfo     Info of service and characteristic handle of the given BD address
+ *                              registered by client.
+ * @return ::CA_STATUS_OK or Appropriate error code.
+ * @retval ::CA_STATUS_OK  Successful.
+ * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
+ * @retval ::CA_STATUS_FAILED Operation failed.
+ */
+CAResult_t CAGetLEServerInfo(LEServerInfoList *serverList, const char *leAddress,
+                             LEServerInfo **leServerInfo);
+
+/**
+ * Used to get the clientInfo from the list by position.
+ *
+ * @param[in]  serverList      Pointer to the ble service list which holds the info of list
+ *                             of servers registered by the client.
+ * @param[in]  position        The service information of particular position in the list.
+ * @param[out] leServerInfo    Info of service and characteristic handle of the given BD address
+ *                              registered by client.
+ * @return ::CA_STATUS_OK or Appropriate error code.
+ * @retval ::CA_STATUS_OK  Successful.
+ * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
+ * @retval ::CA_STATUS_FAILED Operation failed.
+ */
+CAResult_t CAGetLEServerInfoByPosition(LEServerInfoList *serverList, int32_t position,
+                                       LEServerInfo **leServerInfo);
+
+/**
+ * Used to clear BLE service list.
+ *
+ * @param[in]  serverList   Pointer to the ble service list which holds the info of list of
+ *                          servers registered by the client.
+ */
+void CAFreeLEServerList(LEServerInfoList *serverList);
+
+/**
+ * @brief Used to get remove particular BLE service info from list
+ * @param[in] bleServerInfo Pointer to the structure which needs to be cleared.
+ */
+void CAFreeLEServerInfo(LEServerInfo *bleServerInfo);
+
+/**
+ * Used to get the Error message.
+ * @param[in] err   Error code(::bt_error_e).
+ * @return  Error string corresponding to the BT error code.
+ */
+const char *CALEGetErrorMsg(bt_error_e err);
+
+#endif /* TZ_BLE_UTIL_H_ */
index 6fc3443..f214067 100644 (file)
@@ -43,7 +43,7 @@
 #include "camutex.h"
 #include "logger.h"
 
-#define TAG "CA_BWT"
+#define TAG "OIC_CA_BWT"
 
 #define BLOCKWISE_OPTION_BUFFER    (sizeof(unsigned int))
 #define BLOCK_NUMBER_IDX           4
@@ -53,7 +53,9 @@
 #define BLOCK_SIZE(arg) (1 << ((arg) + 4))
 
 // context for block-wise transfer
-static CABlockWiseContext_t g_context = { 0 };
+static CABlockWiseContext_t g_context = { .sendThreadFunc = NULL,
+                                          .receivedThreadFunc = NULL,
+                                          .dataList = NULL };
 
 static bool CACheckPayloadLength(const CAData_t *sendData)
 {
@@ -62,7 +64,7 @@ static bool CACheckPayloadLength(const CAData_t *sendData)
 
     // check if message has to be transfered to a block
     size_t maxBlockSize = BLOCK_SIZE(CA_DEFAULT_BLOCK_SIZE);
-    OIC_LOG_V(DEBUG, TAG, "payloadLen=%d, maxBlockSize=%d", payloadLen, maxBlockSize);
+    OIC_LOG_V(DEBUG, TAG, "payloadLen=%zu, maxBlockSize=%zu", payloadLen, maxBlockSize);
 
     if (payloadLen <= maxBlockSize)
     {
@@ -75,7 +77,7 @@ static bool CACheckPayloadLength(const CAData_t *sendData)
 CAResult_t CAInitializeBlockWiseTransfer(CASendThreadFunc sendThreadFunc,
                                          CAReceiveThreadFunc receivedThreadFunc)
 {
-    OIC_LOG(DEBUG, TAG, "initialize");
+    OIC_LOG(DEBUG, TAG, "CAInitializeBlockWiseTransfer");
 
     // set block-wise transfer context
     if (!g_context.sendThreadFunc)
@@ -96,6 +98,8 @@ CAResult_t CAInitializeBlockWiseTransfer(CASendThreadFunc sendThreadFunc,
     CAResult_t res = CAInitBlockWiseMutexVariables();
     if (CA_STATUS_OK != res)
     {
+        u_arraylist_free(&g_context.dataList);
+        g_context.dataList = NULL;
         OIC_LOG(ERROR, TAG, "init has failed");
     }
 
@@ -104,7 +108,7 @@ CAResult_t CAInitializeBlockWiseTransfer(CASendThreadFunc sendThreadFunc,
 
 CAResult_t CATerminateBlockWiseTransfer()
 {
-    OIC_LOG(DEBUG, TAG, "terminate");
+    OIC_LOG(DEBUG, TAG, "CATerminateBlockWiseTransfer");
 
     if (g_context.dataList)
     {
@@ -162,13 +166,36 @@ CAResult_t CASendBlockWiseData(const CAData_t *sendData)
     VERIFY_NON_NULL(sendData, TAG, "sendData");
 
     // check if message type is CA_MSG_RESET
-    if (sendData->responseInfo)
+    if (sendData->requestInfo)
+    {
+        if (CA_MSG_RESET == sendData->requestInfo->info.type)
+        {
+            OIC_LOG(DEBUG, TAG, "reset message can't be sent to the block");
+            return CA_NOT_SUPPORTED;
+        }
+
+        /*
+         * Other uses of the Block options in conjunction with multicast
+         * messages are for further study.
+         */
+        if (sendData->requestInfo->isMulticast)
+        {
+            OIC_LOG(DEBUG, TAG, "multicast message can't be sent to the block");
+            return CA_NOT_SUPPORTED;
+        }
+    }
+    else if (sendData->responseInfo)
     {
         if (CA_MSG_RESET == sendData->responseInfo->info.type)
         {
             OIC_LOG(DEBUG, TAG, "reset message can't be sent to the block");
             return CA_NOT_SUPPORTED;
         }
+        if (sendData->responseInfo->isMulticast)
+        {
+            OIC_LOG(DEBUG, TAG, "multicast message can't be sent to the block");
+            return CA_NOT_SUPPORTED;
+        }
     }
 
     // #1. check if it is already included in block data list
@@ -211,7 +238,7 @@ CAResult_t CASendBlockWiseData(const CAData_t *sendData)
         // #4. send block message
         OIC_LOG(DEBUG, TAG, "send first block msg");
         res = CAAddSendThreadQueue(currData->sentData,
-                                   (const CABlockDataID_t *)&currData->blockDataId);
+                                   (const CABlockDataID_t *) &currData->blockDataId);
         if (CA_STATUS_OK != res)
         {
             OIC_LOG(ERROR, TAG, "add has failed");
@@ -287,20 +314,31 @@ CAResult_t CAReceiveBlockWiseData(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
     {
         OIC_LOG(DEBUG, TAG, "code is CA_EMPTY..");
 
-        // get token from block-wise transfer list when CA_EMPTY(RST/ACK) is received
-        CAResult_t res = CAGetTokenFromBlockDataList(pdu, endpoint, receivedData->responseInfo);
-        if (CA_STATUS_OK != res)
+        if (!receivedData->responseInfo->info.token)
         {
-            OIC_LOG(ERROR, TAG, "fail to get token");
-            return res;
+            // get token from block-wise transfer list when CA_EMPTY(RST/ACK) is received
+            CAResult_t res = CAGetTokenFromBlockDataList(pdu, endpoint,
+                                                         receivedData->responseInfo);
+            if (CA_STATUS_OK != res)
+            {
+                OIC_LOG(ERROR, TAG, "fail to get token");
+                return res;
+            }
         }
 
         CABlockDataID_t* blockDataID = CACreateBlockDatablockId(
                 receivedData->responseInfo->info.token,
                 receivedData->responseInfo->info.tokenLength,
                 endpoint->port);
-        if(NULL == blockDataID || NULL == blockDataID->id || blockDataID->idLength < 1)
+        if (NULL == blockDataID || blockDataID->idLength < 1)
         {
+            // if retransmission is timeout, callback msg will be send without token.
+            if (NULL == blockDataID && !receivedData->responseInfo->info.token)
+            {
+                OIC_LOG(INFO, TAG, "retransmission was stopped");
+                return CA_REQUEST_TIMEOUT;
+            }
+
             OIC_LOG(ERROR, TAG, "blockId is null");
             CADestroyBlockID(blockDataID);
             return CA_STATUS_FAILED;
@@ -312,7 +350,7 @@ CAResult_t CAReceiveBlockWiseData(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
     }
 
     // check if block option is set and get block data
-    coap_block_t block = {0, 0, 0};
+    coap_block_t block = { 0, 0, 0 };
 
     // get block1 option
     int isBlock1 = coap_get_block(pdu, COAP_OPTION_BLOCK1, &block);
@@ -338,63 +376,53 @@ CAResult_t CAReceiveBlockWiseData(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
         }
     }
 
-    // check if there is error code
+    // if there is no block option in pdu, check if there is error code.
     if (!isBlock1 && !isBlock2)
     {
+        CABlockDataID_t* blockDataID = CACreateBlockDatablockId(
+                (CAToken_t)pdu->hdr->coap_hdr_udp_t.token,
+                pdu->hdr->coap_hdr_udp_t.token_length,
+                endpoint->port);
+        if (NULL == blockDataID || blockDataID->idLength < 1)
+        {
+            OIC_LOG(ERROR, TAG, "blockId is null");
+            CADestroyBlockID(blockDataID);
+            return CA_STATUS_FAILED;
+        }
+
         uint32_t code = CA_RESPONSE_CODE(pdu->hdr->coap_hdr_udp_t.code);
         if (CA_REQUEST_ENTITY_INCOMPLETE == code)
         {
-            CABlockDataID_t* blockDataID = CACreateBlockDatablockId(
-                    (CAToken_t)pdu->hdr->coap_hdr_udp_t.token,
-                     pdu->hdr->coap_hdr_udp_t.token_length,
-                     endpoint->port);
-
-            if(NULL == blockDataID || NULL == blockDataID->id || blockDataID->idLength < 1)
+            CABlockData_t *data = CAGetBlockDataFromBlockDataList(blockDataID);
+            if (!data)
             {
-                OIC_LOG(ERROR, TAG, "blockId is null");
+                OIC_LOG(ERROR, TAG, "getting has failed");
                 CADestroyBlockID(blockDataID);
                 return CA_STATUS_FAILED;
             }
 
-            CABlockData_t *data = CAGetBlockDataFromBlockDataList(blockDataID);
-            if (!data)
+            coap_block_t *block = CAGetBlockOption(blockDataID, data->type);
+            if (!block)
             {
-                OIC_LOG(ERROR, TAG, "getting has failed");
+                OIC_LOG(ERROR, TAG, "block is null");
                 CADestroyBlockID(blockDataID);
                 return CA_STATUS_FAILED;
             }
 
+            CAResult_t res = CA_STATUS_OK;
             if (COAP_OPTION_BLOCK2 == data->type)
             {
-                coap_block_t *block2 = CAGetBlockOption(blockDataID, COAP_OPTION_BLOCK2);
-                if (!block2)
-                {
-                    OIC_LOG(ERROR, TAG, "block is null");
-                    CADestroyBlockID(blockDataID);
-                    return CA_STATUS_FAILED;
-                }
-
-                CAResult_t res = CASetNextBlockOption2(pdu, endpoint, receivedData, *block2,
-                                                       dataLen);
+                res = CASetNextBlockOption2(pdu, endpoint, receivedData, *block, dataLen);
                 if (CA_STATUS_OK != res)
                 {
                     OIC_LOG(ERROR, TAG, "setting has failed");
                     CADestroyBlockID(blockDataID);
-                    return res;
+                    return CA_STATUS_FAILED;
                 }
             }
             else if (COAP_OPTION_BLOCK1 == data->type)
             {
-                coap_block_t *block1 = CAGetBlockOption(blockDataID, COAP_OPTION_BLOCK1);
-                if (!block1)
-                {
-                    OIC_LOG(ERROR, TAG, "block is null");
-                    CADestroyBlockID(blockDataID);
-                    return CA_STATUS_FAILED;
-                }
-
-                CAResult_t res = CASetNextBlockOption1(pdu, endpoint, receivedData, *block1,
-                                                       dataLen);
+                res = CASetNextBlockOption1(pdu, endpoint, receivedData, *block, dataLen);
                 if (CA_STATUS_OK != res)
                 {
                     OIC_LOG(ERROR, TAG, "setting has failed");
@@ -402,6 +430,7 @@ CAResult_t CAReceiveBlockWiseData(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
                     return res;
                 }
             }
+            CADestroyBlockID(blockDataID);
         }
         else
         {
@@ -412,24 +441,12 @@ CAResult_t CAReceiveBlockWiseData(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
             // and sent data remain in block data list, remove block data
             if (receivedData->responseInfo)
             {
-                CABlockDataID_t* blockDataID = CACreateBlockDatablockId(
-                        (CAToken_t)pdu->hdr->coap_hdr_udp_t.token,
-                        pdu->hdr->coap_hdr_udp_t.token_length,
-                        endpoint->port);
-                if(NULL == blockDataID || NULL == blockDataID->id || blockDataID->idLength < 1)
-                {
-                    OIC_LOG(ERROR, TAG, "blockId is null");
-                    CADestroyBlockID(blockDataID);
-                    return CA_STATUS_FAILED;
-                }
-
                 CARemoveBlockDataFromList(blockDataID);
-                CADestroyBlockID(blockDataID);
             }
+            CADestroyBlockID(blockDataID);
             return CA_NOT_SUPPORTED;
         }
     }
-
     return CA_STATUS_OK;
 }
 
@@ -455,7 +472,7 @@ CAResult_t CAProcessNextStep(const coap_pdu_t *pdu, const CAData_t *receivedData
             }
             break;
 
-        case CA_OPTION2_CON:
+        case CA_OPTION2_REQUEST:
             // add data to send thread
             data = CAGetDataSetFromBlockDataList(blockID);
             if (!data)
@@ -483,11 +500,10 @@ CAResult_t CAProcessNextStep(const coap_pdu_t *pdu, const CAData_t *receivedData
 
             break;
 
-        case CA_OPTION1_ACK:
-        case CA_OPTION2_ACK:
-        case CA_SENT_PREVIOUS_NON_MSG:
-            res = CASendBlockMessage(pdu, CA_MSG_CONFIRM, blockWiseStatus,
-                                     blockID);
+        case CA_OPTION1_RESPONSE:
+        case CA_OPTION2_RESPONSE:
+        case CA_OPTION1_REQUEST_BLOCK:
+            res = CASendBlockMessage(pdu, pdu->hdr->coap_hdr_udp_t.type, blockID);
             if (CA_STATUS_OK != res)
             {
                 OIC_LOG(ERROR, TAG, "send has failed");
@@ -513,7 +529,7 @@ CAResult_t CAProcessNextStep(const coap_pdu_t *pdu, const CAData_t *receivedData
             }
             break;
 
-        case CA_OPTION1_NO_ACK_LAST_BLOCK:
+        case CA_OPTION1_REQUEST_LAST_BLOCK:
             // process last block and send upper layer
             res = CAReceiveLastBlock(blockID, receivedData);
             if (CA_STATUS_OK != res)
@@ -521,53 +537,22 @@ CAResult_t CAProcessNextStep(const coap_pdu_t *pdu, const CAData_t *receivedData
                 OIC_LOG(ERROR, TAG, "receive has failed");
                 return res;
             }
-
-            if (CA_MSG_NONCONFIRM == pdu->hdr->coap_hdr_udp_t.type)
-            {
-                // remove data from list
-                res = CARemoveBlockDataFromList(blockID);
-                if (CA_STATUS_OK != res)
-                {
-                    OIC_LOG(ERROR, TAG, "remove has failed");
-                    return res;
-                }
-            }
-            break;
-
-        case CA_OPTION1_NO_ACK_BLOCK:
-            if (CA_MSG_CONFIRM == pdu->hdr->coap_hdr_udp_t.type)
-            {
-                // add data to send thread
-                res = CASendBlockMessage(pdu, CA_MSG_ACKNOWLEDGE, blockWiseStatus,
-                                         blockID);
-                if (CA_STATUS_OK != res)
-                {
-                    OIC_LOG(ERROR, TAG, "send has failed");
-                    return res;
-                }
-            }
             break;
 
         case CA_BLOCK_INCOMPLETE:
-            if (CA_MSG_CONFIRM == pdu->hdr->coap_hdr_udp_t.type ||
-                    CA_MSG_ACKNOWLEDGE == pdu->hdr->coap_hdr_udp_t.type)
+            // add data to send thread
+            res = CASendErrorMessage(pdu, blockWiseStatus, CA_REQUEST_ENTITY_INCOMPLETE, blockID);
+            if (CA_STATUS_OK != res)
             {
-                // add data to send thread
-                res = CASendErrorMessage(pdu, blockWiseStatus,
-                                         CA_REQUEST_ENTITY_INCOMPLETE,
-                                         blockID);
-                if (CA_STATUS_OK != res)
-                {
-                    OIC_LOG(ERROR, TAG, "send has failed");
-                    return res;
-                }
+                OIC_LOG(ERROR, TAG, "send has failed");
+                return res;
             }
             break;
 
         case CA_BLOCK_TOO_LARGE:
-            if (CA_MSG_ACKNOWLEDGE == pdu->hdr->coap_hdr_udp_t.type)
+            if (receivedData->requestInfo)
             {
-                res = CASendBlockMessage(pdu, CA_MSG_CONFIRM, blockWiseStatus,
+                res = CASendErrorMessage(pdu, blockWiseStatus, CA_REQUEST_ENTITY_TOO_LARGE,
                                          blockID);
                 if (CA_STATUS_OK != res)
                 {
@@ -575,11 +560,9 @@ CAResult_t CAProcessNextStep(const coap_pdu_t *pdu, const CAData_t *receivedData
                     return res;
                 }
             }
-            else if (CA_MSG_CONFIRM == pdu->hdr->coap_hdr_udp_t.type)
+            else if (receivedData->responseInfo)
             {
-                res = CASendErrorMessage(pdu, blockWiseStatus,
-                                         CA_REQUEST_ENTITY_TOO_LARGE,
-                                         blockID);
+                res = CASendBlockMessage(pdu, pdu->hdr->coap_hdr_udp_t.type, blockID);
                 if (CA_STATUS_OK != res)
                 {
                     OIC_LOG(ERROR, TAG, "send has failed");
@@ -594,7 +577,7 @@ CAResult_t CAProcessNextStep(const coap_pdu_t *pdu, const CAData_t *receivedData
 }
 
 CAResult_t CASendBlockMessage(const coap_pdu_t *pdu, CAMessageType_t msgType,
-                              uint8_t status, const CABlockDataID_t *blockID)
+                              const CABlockDataID_t *blockID)
 {
     VERIFY_NON_NULL(pdu, TAG, "pdu");
     VERIFY_NON_NULL(pdu->hdr, TAG, "pdu->hdr");
@@ -607,34 +590,38 @@ CAResult_t CASendBlockMessage(const coap_pdu_t *pdu, CAMessageType_t msgType,
         return CA_STATUS_FAILED;
     }
 
-    if (CA_MSG_CONFIRM == msgType)
+    CAMessageType_t sentMsgType = CA_MSG_NONCONFIRM;
+    switch (msgType)
     {
-        OIC_LOG(DEBUG, TAG, "need new msgID");
-        if (data->requestInfo)
-        {
-            data->requestInfo->info.messageId = 0;
-        }
+        case CA_MSG_CONFIRM:
+            sentMsgType = CA_MSG_ACKNOWLEDGE;
+            break;
+        case CA_MSG_ACKNOWLEDGE:
+            sentMsgType = CA_MSG_CONFIRM;
+            break;
+        default:
+            sentMsgType = CA_MSG_NONCONFIRM;
+            break;
+    }
 
+    uint32_t code = pdu->hdr->coap_hdr_udp_t.code;
+    if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
+    {
         if (data->responseInfo)
         {
-            data->responseInfo->info.messageId = 0;
+            OIC_LOG(DEBUG, TAG, "set response info");
+            data->responseInfo->info.messageId = pdu->hdr->coap_hdr_udp_t.id;
+            data->responseInfo->info.type = sentMsgType;
+            data->responseInfo->result = CA_CONTINUE;
         }
     }
-    else if (CA_MSG_ACKNOWLEDGE == msgType)
+    else
     {
-        if (data->responseInfo)
+        OIC_LOG(DEBUG, TAG, "need new msgID");
+        if (data->requestInfo)
         {
-            OIC_LOG(DEBUG, TAG, "set ACK message");
-            data->responseInfo->info.messageId = pdu->hdr->coap_hdr_udp_t.id;
-            data->responseInfo->info.type = CA_MSG_ACKNOWLEDGE;
-            if (CA_OPTION1_NO_ACK_LAST_BLOCK == status)
-            {
-                data->responseInfo->result = CA_CHANGED;
-            }
-            else if (CA_OPTION1_NO_ACK_BLOCK == status)
-            {
-                data->responseInfo->result = CA_CONTINUE;
-            }
+            data->requestInfo->info.messageId = 0;
+            data->requestInfo->info.type = sentMsgType;
         }
     }
 
@@ -649,8 +636,7 @@ CAResult_t CASendBlockMessage(const coap_pdu_t *pdu, CAMessageType_t msgType,
 }
 
 CAResult_t CASendErrorMessage(const coap_pdu_t *pdu, uint8_t status,
-                              CAResponseResult_t responseResult,
-                              const CABlockDataID_t *blockID)
+                              CAResponseResult_t responseResult, const CABlockDataID_t *blockID)
 {
     VERIFY_NON_NULL(pdu, TAG, "pdu");
     VERIFY_NON_NULL(pdu->hdr, TAG, "pdu->hdr");
@@ -664,32 +650,57 @@ CAResult_t CASendErrorMessage(const coap_pdu_t *pdu, uint8_t status,
         return CA_STATUS_FAILED;
     }
 
+    CAMessageType_t sentMsgType = CA_MSG_NONCONFIRM;
+    switch (pdu->hdr->coap_hdr_udp_t.type)
+    {
+        case CA_MSG_CONFIRM:
+            sentMsgType = CA_MSG_ACKNOWLEDGE;
+            break;
+        case CA_MSG_ACKNOWLEDGE:
+            sentMsgType = CA_MSG_CONFIRM;
+            break;
+    }
+
     CAData_t *cloneData = NULL;
-    if (data->sentData && data->sentData->responseInfo)
+    if (data->sentData)
     {
-        data->sentData->responseInfo->info.messageId = pdu->hdr->coap_hdr_udp_t.id;
-        data->sentData->responseInfo->info.type = CA_MSG_ACKNOWLEDGE;
-        data->sentData->responseInfo->result = responseResult;
         cloneData = CACloneCAData(data->sentData);
         if (!cloneData)
         {
             OIC_LOG(ERROR, TAG, "clone has failed");
             return CA_MEMORY_ALLOC_FAILED;
         }
-        OIC_LOG(DEBUG, TAG, "set ACK message");
-    }
-    else if (data->sentData)
-    {
-        cloneData = CACreateNewDataSet(pdu, data->sentData->remoteEndpoint);
-        if(!cloneData)
+
+        if (cloneData->responseInfo)
         {
-            OIC_LOG(ERROR, TAG, PCF("CACreateNewDataSet failed"));
-            return CA_MEMORY_ALLOC_FAILED;
+            cloneData->responseInfo->info.messageId = pdu->hdr->coap_hdr_udp_t.id;
+            cloneData->responseInfo->info.type = sentMsgType;
+            cloneData->responseInfo->result = responseResult;
         }
+        else
+        {
+            CAInfo_t responseData = { .tokenLength = pdu->hdr->coap_hdr_udp_t.token_length };
+            responseData.token = (CAToken_t) OICMalloc(responseData.tokenLength);
+            if (!responseData.token)
+            {
+                OIC_LOG(ERROR, TAG, "out of memory");
+                return CA_MEMORY_ALLOC_FAILED;
+            }
+            memcpy(responseData.token, pdu->hdr->coap_hdr_udp_t.token, responseData.tokenLength);
 
-        cloneData->responseInfo->info.type = CA_MSG_CONFIRM;
-        cloneData->responseInfo->result = responseResult;
-        OIC_LOG(DEBUG, TAG, "set CON message");
+            cloneData->responseInfo = (CAResponseInfo_t*) OICCalloc(1, sizeof(CAResponseInfo_t));
+            if (!cloneData->responseInfo)
+            {
+                OIC_LOG(ERROR, TAG, "out of memory");
+                OICFree(responseData.token);
+                return CA_MEMORY_ALLOC_FAILED;
+            }
+
+            cloneData->responseInfo->info = responseData;
+            cloneData->responseInfo->info.type = sentMsgType;
+            cloneData->responseInfo->result = responseResult;
+        }
+        OIC_LOG(DEBUG, TAG, "set response message to send error code");
     }
     else
     {
@@ -697,6 +708,13 @@ CAResult_t CASendErrorMessage(const coap_pdu_t *pdu, uint8_t status,
         return CA_MEMORY_ALLOC_FAILED;
     }
 
+    // if there is a requestInfo, remove it to send response message
+    if (cloneData->requestInfo)
+    {
+        CADestroyRequestInfoInternal(cloneData->requestInfo);
+        cloneData->requestInfo = NULL;
+    }
+
     // add data to send thread
     if (g_context.sendThreadFunc)
     {
@@ -723,8 +741,7 @@ CAResult_t CASendErrorMessage(const coap_pdu_t *pdu, uint8_t status,
     return CA_STATUS_OK;
 }
 
-CAResult_t CAReceiveLastBlock(const CABlockDataID_t *blockID,
-                              const CAData_t *receivedData)
+CAResult_t CAReceiveLastBlock(const CABlockDataID_t *blockID, const CAData_t *receivedData)
 {
     VERIFY_NON_NULL(blockID, TAG, "blockID");
     VERIFY_NON_NULL(receivedData, TAG, "receivedData");
@@ -739,8 +756,7 @@ CAResult_t CAReceiveLastBlock(const CABlockDataID_t *blockID,
 
     // update payload
     size_t fullPayloadLen = 0;
-    CAPayload_t fullPayload = CAGetPayloadFromBlockDataList(blockID,
-                                                            &fullPayloadLen);
+    CAPayload_t fullPayload = CAGetPayloadFromBlockDataList(blockID, &fullPayloadLen);
     if (fullPayload)
     {
         CAResult_t res = CAUpdatePayloadToCAData(cloneData, fullPayload, fullPayloadLen);
@@ -781,117 +797,59 @@ CAResult_t CASetNextBlockOption1(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
             (CAToken_t)pdu->hdr->coap_hdr_udp_t.token,
             pdu->hdr->coap_hdr_udp_t.token_length,
             endpoint->port);
-
-    if(NULL == blockDataID || NULL == blockDataID->id || blockDataID->idLength < 1)
+    if (NULL == blockDataID || blockDataID->idLength < 1)
     {
         OIC_LOG(ERROR, TAG, "blockId is null");
         CADestroyBlockID(blockDataID);
         return CA_STATUS_FAILED;
     }
 
-    // BlockData data is created if it not existed
-    if (!CAIsBlockDataInList(blockDataID))
+    // Get BlockData data. If does not exist, create a new data
+    CABlockData_t *data = CAGetBlockDataFromBlockDataList(blockDataID);
+    if (!data)
     {
-        OIC_LOG(DEBUG, TAG, "no message in list");
+        OIC_LOG(DEBUG, TAG, "block data doesn't exist in list. create new one");
 
-        CAData_t *data = CACreateNewDataSet(pdu, endpoint);
-        if (!data)
+        CAData_t *cadata = CACreateNewDataSet(pdu, endpoint);
+        if (!cadata)
         {
             OIC_LOG(ERROR, TAG, "data is null");
             CADestroyBlockID(blockDataID);
             return CA_STATUS_FAILED;
         }
 
-        CABlockData_t *currData = CACreateNewBlockData(data);
-        if (!currData)
+        data = CACreateNewBlockData(cadata);
+        if (!data)
         {
-            OIC_LOG(ERROR, TAG, "currData is null");
-            CADestroyDataSet(data);
+            OIC_LOG(ERROR, TAG, "failed to create a new block data");
+            CADestroyDataSet(cadata);
             CADestroyBlockID(blockDataID);
             return CA_STATUS_FAILED;
         }
-        CADestroyDataSet(data);
+        CADestroyDataSet(cadata);
     }
 
     // update BLOCK OPTION1 type
-    CAResult_t res = CAUpdateBlockOptionType(blockDataID,
-                                             COAP_OPTION_BLOCK1);
+    CAResult_t res = CAUpdateBlockOptionType(blockDataID, COAP_OPTION_BLOCK1);
     if (CA_STATUS_OK != res)
     {
         OIC_LOG(ERROR, TAG, "update has failed");
-        CARemoveBlockDataFromList(blockDataID);
-        CADestroyBlockID(blockDataID);
-        return res;
-    }
-
-    CABlockData_t *data = CAGetBlockDataFromBlockDataList(blockDataID);
-    if (!data)
-    {
-        OIC_LOG(ERROR, TAG, "getting has failed");
-        CADestroyBlockID(blockDataID);
-        return CA_STATUS_FAILED;
+        goto exit;
     }
 
     uint8_t blockWiseStatus = CA_BLOCK_UNKNOWN;
-    // received type from remote device
-    if (CA_MSG_ACKNOWLEDGE == pdu->hdr->coap_hdr_udp_t.type)
-    {
-        uint32_t code = CA_RESPONSE_CODE(pdu->hdr->coap_hdr_udp_t.code);
-        if (0 == block.m &&
-                (CA_REQUEST_ENTITY_INCOMPLETE != code && CA_REQUEST_ENTITY_TOO_LARGE != code))
-        {
-            int isBlock2 = coap_get_block(pdu, COAP_OPTION_BLOCK2, &block);
-            if (isBlock2)
-            {
-                OIC_LOG(INFO, TAG, "received data is combining block1 and block2");
-                // initialize block number for response message
-                data->block1.num = 0;
-                CADestroyBlockID(blockDataID);
-                return CA_STATUS_OK;
-            }
-            else
-            {
-                OIC_LOG(INFO, TAG, "received data is not bulk data");
-                CAReceiveLastBlock(blockDataID, receivedData);
-                CARemoveBlockDataFromList(blockDataID);
-                CADestroyBlockID(blockDataID);
-                return CA_STATUS_OK;
-            }
-        }
-
-        blockWiseStatus = CA_OPTION1_ACK;
-        res = CAUpdateBlockOptionItems(data, pdu, &block, COAP_OPTION_BLOCK1, blockWiseStatus);
-        if (CA_STATUS_OK != res)
-        {
-            OIC_LOG(ERROR, TAG, "update has failed");
-            CADestroyBlockID(blockDataID);
-            return res;
-        }
-
-        res = CAUpdateBlockData(data, block, COAP_OPTION_BLOCK1);
-        if (CA_STATUS_OK != res)
-        {
-            OIC_LOG(ERROR, TAG, "update has failed");
-            CARemoveBlockDataFromList(blockDataID);
-            CADestroyBlockID(blockDataID);
-            return res;
-        }
-    }
-    else // CON or NON message
+    uint32_t code = pdu->hdr->coap_hdr_udp_t.code;
+    if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
     {
+        // received message type is request
         OIC_LOG_V(INFO, TAG, "num:%d, M:%d", block.num, block.m);
 
         // check the size option
-        bool isSizeOption = CAIsPayloadLengthInPduWithBlockSizeOption(pdu,
-                                                                      COAP_OPTION_SIZE1,
+        bool isSizeOption = CAIsPayloadLengthInPduWithBlockSizeOption(pdu, COAP_OPTION_SIZE1,
                                                                       &(data->payloadLength));
 
-        // check if received payload is exact
-        if (CA_MSG_CONFIRM == pdu->hdr->coap_hdr_udp_t.type)
-        {
-            blockWiseStatus = CACheckBlockErrorType(data, &block, receivedData,
-                                                    COAP_OPTION_BLOCK1, dataLen);
-        }
+        blockWiseStatus = CACheckBlockErrorType(data, &block, receivedData,
+                                                COAP_OPTION_BLOCK1, dataLen);
 
         if (CA_BLOCK_RECEIVED_ALREADY != blockWiseStatus)
         {
@@ -901,18 +859,15 @@ CAResult_t CASetNextBlockOption1(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
             if (CA_STATUS_OK != res)
             {
                 OIC_LOG(ERROR, TAG, "update has failed");
-                CARemoveBlockDataFromList(blockDataID);
-                CADestroyBlockID(blockDataID);
-                return res;
+                goto exit;
             }
 
-            res = CAUpdateBlockOptionItems(data, pdu, &block, COAP_OPTION_BLOCK1, blockWiseStatus);
+            res = CAUpdateBlockOptionItems(data, pdu, &block, COAP_OPTION_BLOCK1,
+                                           blockWiseStatus);
             if (CA_STATUS_OK != res)
             {
                 OIC_LOG(ERROR, TAG, "update has failed");
-                CARemoveBlockDataFromList(blockDataID);
-                CADestroyBlockID(blockDataID);
-                return res;
+                goto exit;
             }
 
             // update block data
@@ -920,37 +875,82 @@ CAResult_t CASetNextBlockOption1(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
             if (CA_STATUS_OK != res)
             {
                 OIC_LOG(ERROR, TAG, "update has failed");
-                CARemoveBlockDataFromList(blockDataID);
-                CADestroyBlockID(blockDataID);
-                return res;
+                goto exit;
             }
         }
 
         // check the blcok-wise transfer status for next step
         if (CA_BLOCK_UNKNOWN == blockWiseStatus || CA_BLOCK_RECEIVED_ALREADY == blockWiseStatus)
         {
-            if (0 == block.m) // Last block is received
+            OIC_LOG_V(DEBUG, TAG, "M bit is %d", block.m);
+
+            if (0 == block.m)
             {
-                OIC_LOG(DEBUG, TAG, "M bit is 0");
-                blockWiseStatus = CA_OPTION1_NO_ACK_LAST_BLOCK;
+                // Last block is received
+                blockWiseStatus = CA_OPTION1_REQUEST_LAST_BLOCK;
+            }
+            else
+            {
+                blockWiseStatus = CA_OPTION1_REQUEST_BLOCK;
+            }
+        }
+    }
+    else
+    {
+        // received message type is response
+        uint32_t code = CA_RESPONSE_CODE(pdu->hdr->coap_hdr_udp_t.code);
+        if (0 == block.m && (CA_REQUEST_ENTITY_INCOMPLETE != code
+                && CA_REQUEST_ENTITY_TOO_LARGE != code))
+        {
+            int isBlock2 = coap_get_block(pdu, COAP_OPTION_BLOCK2, &block);
+            if (isBlock2)
+            {
+                OIC_LOG(INFO, TAG, "received data is combining block1 and block2");
+                // initialize block number for response message
+                data->block1.num = 0;
+                CADestroyBlockID(blockDataID);
+                return CA_STATUS_OK;
             }
             else
             {
-                OIC_LOG(DEBUG, TAG, "M bit is 1");
-                blockWiseStatus = CA_OPTION1_NO_ACK_BLOCK;
+                OIC_LOG(INFO, TAG, "received data is not bulk data");
+                CAReceiveLastBlock(blockDataID, receivedData);
+                res = CA_STATUS_OK;
+                goto exit;
             }
         }
+
+        blockWiseStatus = CA_OPTION1_RESPONSE;
+        res = CAUpdateBlockOptionItems(data, pdu, &block, COAP_OPTION_BLOCK1, blockWiseStatus);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "update has failed");
+            CADestroyBlockID(blockDataID);
+            return res;
+        }
+
+        res = CAUpdateBlockData(data, block, COAP_OPTION_BLOCK1);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "update has failed");
+            goto exit;
+        }
     }
 
     res = CAProcessNextStep(pdu, receivedData, blockWiseStatus, blockDataID);
     if (CA_STATUS_OK != res)
     {
         OIC_LOG(ERROR, TAG, "setting has failed");
-        CARemoveBlockDataFromList(blockDataID);
+        goto exit;
     }
 
     CADestroyBlockID(blockDataID);
     return res;
+
+exit:
+    CARemoveBlockDataFromList(blockDataID);
+    CADestroyBlockID(blockDataID);
+    return res;
 }
 
 // TODO make pdu const after libcoap is updated to support that.
@@ -970,56 +970,44 @@ CAResult_t CASetNextBlockOption2(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
             (CAToken_t)pdu->hdr->coap_hdr_udp_t.token,
             pdu->hdr->coap_hdr_udp_t.token_length,
             endpoint->port);
-
-    if(NULL == blockDataID || NULL == blockDataID->id || blockDataID->idLength < 1)
+    if (NULL == blockDataID || blockDataID->idLength < 1)
     {
         OIC_LOG(ERROR, TAG, "blockId is null");
         CADestroyBlockID(blockDataID);
         return CA_STATUS_FAILED;
     }
 
-    // BlockData data is created if it not existed
-    if (!CAIsBlockDataInList(blockDataID))
+    // Get BlockData data. If does not exist, create a new data
+    CABlockData_t *data = CAGetBlockDataFromBlockDataList(blockDataID);
+    if (!data)
     {
-        OIC_LOG(DEBUG, TAG, "no msg in list.");
+        OIC_LOG(DEBUG, TAG, "block data doesn't exist in list. create new one");
 
-        CAData_t *data = CACreateNewDataSet(pdu, endpoint);
-        if (!data)
+        CAData_t *cadata = CACreateNewDataSet(pdu, endpoint);
+        if (!cadata)
         {
             OIC_LOG(ERROR, TAG, "data is null");
             CADestroyBlockID(blockDataID);
             return CA_STATUS_FAILED;
         }
 
-        CABlockData_t *currData = CACreateNewBlockData(data);
-        if (!currData)
+        data = CACreateNewBlockData(cadata);
+        if (!data)
         {
-            OIC_LOG(ERROR, TAG, "data is null");
-            CADestroyDataSet(data);
+            OIC_LOG(ERROR, TAG, "failed to create a new block data");
+            CADestroyDataSet(cadata);
             CADestroyBlockID(blockDataID);
             return CA_STATUS_FAILED;
         }
-        CADestroyDataSet(data);
+        CADestroyDataSet(cadata);
     }
 
     // set Block Option Type
-    CAResult_t res = CAUpdateBlockOptionType(blockDataID,
-                                             COAP_OPTION_BLOCK2);
+    CAResult_t res = CAUpdateBlockOptionType(blockDataID, COAP_OPTION_BLOCK2);
     if (CA_STATUS_OK != res)
     {
         OIC_LOG(ERROR, TAG, "update has failed");
-        CARemoveBlockDataFromList(blockDataID);
-        CADestroyBlockID(blockDataID);
-        return res;
-    }
-
-    CABlockData_t *data = CAGetBlockDataFromBlockDataList(blockDataID);
-    if (!data)
-    {
-        OIC_LOG(ERROR, TAG, "getting has failed");
-        CARemoveBlockDataFromList(blockDataID);
-        CADestroyBlockID(blockDataID);
-        return CA_STATUS_FAILED;
+        goto exit;
     }
 
     uint8_t blockWiseStatus = CA_BLOCK_UNKNOWN;
@@ -1031,9 +1019,7 @@ CAResult_t CASetNextBlockOption2(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
         if (CA_STATUS_OK != res)
         {
             OIC_LOG(ERROR, TAG, "update has failed");
-            CARemoveBlockDataFromList(blockDataID);
-            CADestroyBlockID(blockDataID);
-            return res;
+            goto exit;
         }
 
         // first block data have to notify to Application
@@ -1041,29 +1027,48 @@ CAResult_t CASetNextBlockOption2(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
         if (CA_STATUS_OK != res)
         {
             OIC_LOG(ERROR, TAG, "update has failed");
-            CARemoveBlockDataFromList(blockDataID);
-            CADestroyBlockID(blockDataID);
-            return res;
+            goto exit;
         }
         blockWiseStatus = CA_OPTION2_FIRST_BLOCK;
     }
     else
     {
-        // received type from remote device
-        if (CA_MSG_ACKNOWLEDGE == pdu->hdr->coap_hdr_udp_t.type ||
-                (CA_MSG_NONCONFIRM == pdu->hdr->coap_hdr_udp_t.type &&
-                        NULL != receivedData->responseInfo))
+        uint32_t code = pdu->hdr->coap_hdr_udp_t.code;
+        if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
+        {
+            // received message type is request
+            OIC_LOG_V(INFO, TAG, "num:%d, M:%d", block.num, block.m);
+
+            blockWiseStatus = CA_OPTION2_REQUEST;
+
+            res = CAUpdateBlockOptionItems(data, pdu, &block, COAP_OPTION_BLOCK2, blockWiseStatus);
+            if (CA_STATUS_OK != res)
+            {
+                OIC_LOG(ERROR, TAG, "update has failed");
+                goto exit;
+            }
+
+            res = CAUpdateBlockData(data, block, COAP_OPTION_BLOCK2);
+            if (CA_STATUS_OK != res)
+            {
+                OIC_LOG(ERROR, TAG, "update has failed");
+                goto exit;
+            }
+        }
+        else
         {
-            OIC_LOG(DEBUG, TAG, "received ACK or NON");
+            // received message type is response
+            OIC_LOG(DEBUG, TAG, "received response message with block option2");
 
             // check the size option
             bool isSizeOption = CAIsPayloadLengthInPduWithBlockSizeOption(pdu,
                                                                           COAP_OPTION_SIZE2,
                                                                           &(data->payloadLength));
 
-            // check if received payload is exact
-            if (CA_MSG_ACKNOWLEDGE == pdu->hdr->coap_hdr_udp_t.type)
+            uint32_t code = CA_RESPONSE_CODE(pdu->hdr->coap_hdr_udp_t.code);
+            if (CA_REQUEST_ENTITY_INCOMPLETE != code && CA_REQUEST_ENTITY_TOO_LARGE != code)
             {
+                // check if received payload is exact
                 blockWiseStatus = CACheckBlockErrorType(data, &block, receivedData,
                                                         COAP_OPTION_BLOCK2, dataLen);
             }
@@ -1076,9 +1081,7 @@ CAResult_t CASetNextBlockOption2(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
                 if (CA_STATUS_OK != res)
                 {
                     OIC_LOG(ERROR, TAG, "update has failed");
-                    CARemoveBlockDataFromList(blockDataID);
-                    CADestroyBlockID(blockDataID);
-                    return res;
+                    goto exit;
                 }
             }
 
@@ -1093,15 +1096,7 @@ CAResult_t CASetNextBlockOption2(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
                         CA_BLOCK_RECEIVED_ALREADY == blockWiseStatus)
                 {
                     OIC_LOG(DEBUG, TAG, "M bit is 1");
-
-                    if (CA_MSG_ACKNOWLEDGE == pdu->hdr->coap_hdr_udp_t.type)
-                    {
-                        blockWiseStatus = CA_OPTION2_ACK;
-                    }
-                    else
-                    {
-                        blockWiseStatus = CA_OPTION2_NON;
-                    }
+                    blockWiseStatus = CA_OPTION2_RESPONSE;
                 }
 
                 res = CAUpdateBlockOptionItems(data, pdu, &block, COAP_OPTION_BLOCK2,
@@ -1109,58 +1104,33 @@ CAResult_t CASetNextBlockOption2(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
                 if (CA_STATUS_OK != res)
                 {
                     OIC_LOG(ERROR, TAG, "update has failed");
-                    CARemoveBlockDataFromList(blockDataID);
-                    CADestroyBlockID(blockDataID);
-                    return res;
+                    goto exit;
                 }
 
                 res = CAUpdateBlockData(data, block, COAP_OPTION_BLOCK2);
                 if (CA_STATUS_OK != res)
                 {
                     OIC_LOG(ERROR, TAG, "update has failed");
-                    CARemoveBlockDataFromList(blockDataID);
-                    CADestroyBlockID(blockDataID);
-                    return res;
+                    goto exit;
                 }
             }
         }
-        else // CON message and so on.
-        {
-            OIC_LOG_V(INFO, TAG, "num:%d, M:%d", block.num, block.m);
-
-            blockWiseStatus = CA_OPTION2_CON;
-
-            res = CAUpdateBlockOptionItems(data, pdu, &block, COAP_OPTION_BLOCK2, blockWiseStatus);
-            if (CA_STATUS_OK != res)
-            {
-                OIC_LOG(ERROR, TAG, "update has failed");
-                CARemoveBlockDataFromList(blockDataID);
-                CADestroyBlockID(blockDataID);
-                return res;
-            }
-
-            res = CAUpdateBlockData(data, block, COAP_OPTION_BLOCK2);
-            if (CA_STATUS_OK != res)
-            {
-                OIC_LOG(ERROR, TAG, "update has failed");
-                CARemoveBlockDataFromList(blockDataID);
-                CADestroyBlockID(blockDataID);
-                return res;
-            }
-        }
     }
 
     res = CAProcessNextStep(pdu, receivedData, blockWiseStatus, blockDataID);
     if (CA_STATUS_OK != res)
     {
         OIC_LOG(ERROR, TAG, "setting has failed");
-        CARemoveBlockDataFromList(blockDataID);
-        CADestroyBlockID(blockDataID);
-        return res;
+        goto exit;
     }
 
     CADestroyBlockID(blockDataID);
-    return CA_STATUS_OK;
+    return CA_STATUS_OK;
+
+exit:
+    CARemoveBlockDataFromList(blockDataID);
+    CADestroyBlockID(blockDataID);
+    return res;
 }
 
 CAResult_t CAUpdateBlockOptionItems(CABlockData_t *currData, const coap_pdu_t *pdu,
@@ -1190,7 +1160,7 @@ CAResult_t CAUpdateBlockOptionItems(CABlockData_t *currData, const coap_pdu_t *p
         // update block option items
         switch (status)
         {
-            case CA_OPTION1_ACK:
+            case CA_OPTION1_RESPONSE:
                 if (currData->block1.num > block->num)
                 {
                     OIC_LOG(ERROR, TAG, "received incorrect block num");
@@ -1198,14 +1168,10 @@ CAResult_t CAUpdateBlockOptionItems(CABlockData_t *currData, const coap_pdu_t *p
                 }
                 block->num++;
                 break;
-            case CA_OPTION2_NON:
-                block->num++;
-                block->m = 0;
-                break;
-            case CA_OPTION2_CON:
+            case CA_OPTION2_REQUEST:
                 block->m = 0;
                 break;
-            case CA_OPTION2_ACK:
+            case CA_OPTION2_RESPONSE:
                 if (currData->block2.num > block->num)
                 {
                     OIC_LOG(ERROR, TAG, "received incorrect block num");
@@ -1235,7 +1201,7 @@ CAResult_t CAUpdateBlockOptionItems(CABlockData_t *currData, const coap_pdu_t *p
         if (CA_BLOCK_INCOMPLETE != status && CA_BLOCK_TOO_LARGE != status)
         {
             // negotiate block size
-            res = CANegotiateBlockSize(currData, block, pdu->hdr->coap_hdr_udp_t.type, blockType);
+            res = CANegotiateBlockSize(currData, block, pdu, blockType);
             if (CA_STATUS_OK != res)
             {
                 OIC_LOG(ERROR, TAG, "negotiation has failed");
@@ -1246,12 +1212,11 @@ CAResult_t CAUpdateBlockOptionItems(CABlockData_t *currData, const coap_pdu_t *p
     return res;
 }
 
-CAResult_t CAGetMoreBitFromBlock(size_t payloadLen, coap_block_t *block)
+CAResult_t CASetMoreBitFromBlock(size_t payloadLen, coap_block_t *block)
 {
     VERIFY_NON_NULL(block, TAG, "block");
 
-    if ((size_t)((block->num + 1) << (block->szx + BLOCK_NUMBER_IDX))
-        < payloadLen)
+    if ((size_t) ((block->num + 1) << (block->szx + BLOCK_NUMBER_IDX)) < payloadLen)
     {
         OIC_LOG(DEBUG, TAG, "Set the M-bit(1)");
         block->m = 1;
@@ -1266,18 +1231,27 @@ CAResult_t CAGetMoreBitFromBlock(size_t payloadLen, coap_block_t *block)
 }
 
 CAResult_t CANegotiateBlockSize(CABlockData_t *currData, coap_block_t *block,
-                                CAMessageType_t msgType, uint16_t blockType)
+                                coap_pdu_t *pdu, uint16_t blockType)
 {
     OIC_LOG(DEBUG, TAG, "IN-NegotiateBlockSize");
 
     VERIFY_NON_NULL(currData, TAG, "currData");
     VERIFY_NON_NULL(block, TAG, "block");
+    VERIFY_NON_NULL(pdu, TAG, "pdu");
+    VERIFY_NON_NULL(pdu->hdr, TAG, "pdu->hdr");
+
+    bool isReqMsg = false;
+    uint32_t code = pdu->hdr->coap_hdr_udp_t.code;
+    if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
+    {
+        isReqMsg = true;
+    }
 
     // #1. check the block option type
     if (COAP_OPTION_BLOCK2 == blockType)
     {
         // #2. check the message type
-        if (CA_MSG_ACKNOWLEDGE == msgType)
+        if (!isReqMsg)
         {
             if (block->szx > currData->block2.szx)
             {
@@ -1303,7 +1277,7 @@ CAResult_t CANegotiateBlockSize(CABlockData_t *currData, coap_block_t *block,
     }
     else if (COAP_OPTION_BLOCK1 == blockType)
     {
-        if (CA_MSG_ACKNOWLEDGE == msgType)
+        if (!isReqMsg)
         {
             if (block->szx < currData->block1.szx)
             {
@@ -1364,22 +1338,20 @@ CAResult_t CAUpdateBlockData(CABlockData_t *currData, coap_block_t block,
 CAResult_t CAUpdateMessageId(coap_pdu_t *pdu, const CABlockDataID_t *blockID)
 {
     VERIFY_NON_NULL(pdu, TAG, "pdu");
+    VERIFY_NON_NULL(pdu->hdr, TAG, "pdu->hdr");
     VERIFY_NON_NULL(blockID, TAG, "blockID");
 
-    // if CON message is sent, update messageId in block-wise transfer list
-    if (CA_MSG_CONFIRM == pdu->hdr->coap_hdr_udp_t.type)
+    // if message is sent, update messageId in block-wise transfer list
+    CAData_t * cadata = CAGetDataSetFromBlockDataList(blockID);
+    if (!cadata)
     {
-        CAData_t * cadata = CAGetDataSetFromBlockDataList(blockID);
-        if (!cadata)
-        {
-            OIC_LOG(ERROR, TAG, "CAData is unavailable");
-            return CA_STATUS_FAILED;
-        }
+        OIC_LOG(ERROR, TAG, "CAData is unavailable");
+        return CA_STATUS_FAILED;
+    }
 
-        if (cadata->requestInfo)
-        {
-            cadata->requestInfo->info.messageId = pdu->hdr->coap_hdr_udp_t.id;
-        }
+    if (cadata->requestInfo)
+    {
+        cadata->requestInfo->info.messageId = pdu->hdr->coap_hdr_udp_t.id;
     }
 
     return CA_STATUS_OK;
@@ -1396,35 +1368,33 @@ CAResult_t CAAddBlockOption(coap_pdu_t **pdu, const CAInfo_t *info,
     VERIFY_NON_NULL(endpoint, TAG, "endpoint");
     VERIFY_NON_NULL(options, TAG, "options");
 
+    CAResult_t res = CA_STATUS_OK;
     size_t dataLength = 0;
     if (info->payload)
     {
         dataLength = info->payloadSize;
-        OIC_LOG_V(DEBUG, TAG, "dataLength - %d", dataLength);
-    }
-
-    OIC_LOG_V(DEBUG, TAG, "previous payload - %s", (*pdu)->data);
-
-    CAResult_t res = CA_STATUS_OK;
-    uint32_t code = CA_RESPONSE_CODE((*pdu)->hdr->coap_hdr_udp_t.code);
-    if (CA_REQUEST_ENTITY_INCOMPLETE == code)
-    {
-        OIC_LOG(INFO, TAG, "don't use option");
-        return res;
+        OIC_LOG_V(DEBUG, TAG, "dataLength - %zu", dataLength);
     }
 
     CABlockDataID_t* blockDataID = CACreateBlockDatablockId(
             (CAToken_t)(*pdu)->hdr->coap_hdr_udp_t.token,
             (*pdu)->hdr->coap_hdr_udp_t.token_length,
             endpoint->port);
-
-    if(NULL == blockDataID || NULL == blockDataID->id || blockDataID->idLength < 1)
+    if (NULL == blockDataID || blockDataID->idLength < 1)
     {
         OIC_LOG(ERROR, TAG, "blockId is null");
         res = CA_STATUS_FAILED;
         goto exit;
     }
 
+    uint32_t repCode = CA_RESPONSE_CODE((*pdu)->hdr->coap_hdr_udp_t.code);
+    if (CA_REQUEST_ENTITY_INCOMPLETE == repCode)
+    {
+        OIC_LOG(INFO, TAG, "don't use option");
+        res = CA_STATUS_OK;
+        goto exit;
+    }
+
     uint8_t blockType = CAGetBlockOptionType(blockDataID);
     if (COAP_OPTION_BLOCK2 == blockType)
     {
@@ -1469,28 +1439,33 @@ CAResult_t CAAddBlockOption(coap_pdu_t **pdu, const CAInfo_t *info,
         if (!coap_add_data(*pdu, dataLength, (const unsigned char *) info->payload))
         {
             OIC_LOG(INFO, TAG, "it have to use block");
+            res = CA_STATUS_FAILED;
+            goto exit;
         }
         else
         {
             OIC_LOG(INFO, TAG, "not Blockwise Transfer");
-            goto exit;
         }
     }
 
-    // if received message type is RESET from remote device,
-    // we have to use the updated message id to find token.
-    res = CAUpdateMessageId(*pdu, blockDataID);
-    if (CA_STATUS_OK != res)
+    uint32_t code = (*pdu)->hdr->coap_hdr_udp_t.code;
+    if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
     {
-        OIC_LOG(ERROR, TAG, "fail to update CON message id ");
-        goto exit;
+        // if received message type is RESET from remote device,
+        // we have to use the updated message id of request message to find token.
+        CABlockData_t *blockData = CAGetBlockDataFromBlockDataList(blockDataID);
+        if (blockData)
+        {
+            res = CAUpdateMessageId(*pdu, blockDataID);
+            if (CA_STATUS_OK != res)
+            {
+                OIC_LOG(ERROR, TAG, "fail to update message id");
+                goto exit;
+            }
+        }
     }
 
 exit:
-    if (CA_ADAPTER_IP == endpoint->adapter && 0 == endpoint->port)
-    {
-        CARemoveBlockDataFromList(blockDataID);
-    }
     CADestroyBlockID(blockDataID);
     OIC_LOG(DEBUG, TAG, "OUT-AddBlockOption");
     return res;
@@ -1516,34 +1491,28 @@ CAResult_t CAAddBlockOption2(coap_pdu_t **pdu, const CAInfo_t *info, size_t data
         return CA_STATUS_FAILED;
     }
 
-    CALogBlockInfo(block2);
-
-    uint8_t code = 0;
-    if (CA_MSG_ACKNOWLEDGE == (*pdu)->hdr->coap_hdr_udp_t.type ||
-            (CA_MSG_NONCONFIRM == (*pdu)->hdr->coap_hdr_udp_t.type &&
-                    CA_GET != (*pdu)->hdr->coap_hdr_udp_t.code))
+    CAResult_t res = CA_STATUS_OK;
+    uint32_t code = (*pdu)->hdr->coap_hdr_udp_t.code;
+    if (CA_GET != code && CA_POST != code && CA_PUT != code && CA_DELETE != code)
     {
-        CAGetMoreBitFromBlock(dataLength, block2);
-        CALogBlockInfo(block2);
+        CASetMoreBitFromBlock(dataLength, block2);
 
         // if block number is 0, add size2 option
         if (0 == block2->num)
         {
-            CAResult_t res = CAAddBlockSizeOption(*pdu, COAP_OPTION_SIZE2, dataLength, options);
+            res = CAAddBlockSizeOption(*pdu, COAP_OPTION_SIZE2, dataLength, options);
             if (CA_STATUS_OK != res)
             {
                 OIC_LOG(ERROR, TAG, "add has failed");
-                CARemoveBlockDataFromList(blockID);
-                return res;
+                goto exit;
             }
         }
 
-        CAResult_t res = CAAddBlockOptionImpl(block2, COAP_OPTION_BLOCK2, options);
+        res = CAAddBlockOptionImpl(block2, COAP_OPTION_BLOCK2, options);
         if (CA_STATUS_OK != res)
         {
             OIC_LOG(ERROR, TAG, "add has failed");
-            CARemoveBlockDataFromList(blockID);
-            return res;
+            goto exit;
         }
 
         if (block1->num)
@@ -1553,8 +1522,7 @@ CAResult_t CAAddBlockOption2(coap_pdu_t **pdu, const CAInfo_t *info, size_t data
             if (CA_STATUS_OK != res)
             {
                 OIC_LOG(ERROR, TAG, "add has failed");
-                CARemoveBlockDataFromList(blockID);
-                return res;
+                goto exit;
             }
             // initialize block number
             block1->num = 0;
@@ -1564,8 +1532,7 @@ CAResult_t CAAddBlockOption2(coap_pdu_t **pdu, const CAInfo_t *info, size_t data
         if (CA_STATUS_OK != res)
         {
             OIC_LOG(ERROR, TAG, "add has failed");
-            CARemoveBlockDataFromList(blockID);
-            return res;
+            goto exit;
         }
 
         if (!coap_add_block(*pdu, dataLength, (const unsigned char *) info->payload,
@@ -1575,62 +1542,38 @@ CAResult_t CAAddBlockOption2(coap_pdu_t **pdu, const CAInfo_t *info, size_t data
             return CA_STATUS_FAILED;
         }
 
+        CALogBlockInfo(block2);
+
         if (!block2->m)
         {
             // if sent message is last response block message, remove data
             CARemoveBlockDataFromList(blockID);
         }
-        else
-        {
-            if (CA_MSG_NONCONFIRM == (*pdu)->hdr->coap_hdr_udp_t.type)
-            {
-                OIC_LOG(DEBUG, TAG, "NON, send next block..");
-                // update block data
-                block2->num++;
-                CAResult_t res = CAProcessNextStep(*pdu, NULL,
-                                                   CA_SENT_PREVIOUS_NON_MSG,
-                                                   blockID);
-                if (CA_STATUS_OK != res)
-                {
-                    OIC_LOG(ERROR, TAG, "failed to process next step");
-                    CARemoveBlockDataFromList(blockID);
-                    return res;
-                }
-            }
-        }
     }
     else
     {
-        OIC_LOG(DEBUG, TAG, "option2, not ACK msg");
-        CAResult_t res = CAAddBlockOptionImpl(block2, COAP_OPTION_BLOCK2, options);
+        OIC_LOG(DEBUG, TAG, "option2, not response msg");
+        res = CAAddBlockOptionImpl(block2, COAP_OPTION_BLOCK2, options);
         if (CA_STATUS_OK != res)
         {
             OIC_LOG(ERROR, TAG, "add has failed");
-            CARemoveBlockDataFromList(blockID);
-            return res;
+            goto exit;
         }
 
         res = CAAddOptionToPDU(*pdu, options);
         if (CA_STATUS_OK != res)
         {
             OIC_LOG(ERROR, TAG, "add has failed");
-            CARemoveBlockDataFromList(blockID);
-            return res;
+            goto exit;
         }
+        CALogBlockInfo(block2);
     }
 
     return CA_STATUS_OK;
 
-error:
-    OIC_LOG_V(ERROR, TAG, "error : %d", code);
-
-    char* phrase = coap_response_phrase(code);
-    if(phrase)
-    {
-        coap_add_data(*pdu, strlen(phrase),
-                      (unsigned char *) phrase);
-    }
-    return CA_STATUS_FAILED;
+exit:
+    CARemoveBlockDataFromList(blockID);
+    return res;
 }
 
 CAResult_t CAAddBlockOption1(coap_pdu_t **pdu, const CAInfo_t *info, size_t dataLength,
@@ -1652,115 +1595,96 @@ CAResult_t CAAddBlockOption1(coap_pdu_t **pdu, const CAInfo_t *info, size_t data
         return CA_STATUS_FAILED;
     }
 
-    CALogBlockInfo(block1);
-
-    if (CA_MSG_ACKNOWLEDGE == (*pdu)->hdr->coap_hdr_udp_t.type)
+    CAResult_t res = CA_STATUS_OK;
+    uint32_t code = (*pdu)->hdr->coap_hdr_udp_t.code;
+    if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
     {
-        OIC_LOG(DEBUG, TAG, "option1 and ACK msg..");
-        CAResult_t res = CAAddBlockOptionImpl(block1, COAP_OPTION_BLOCK1, options);
+        CASetMoreBitFromBlock(dataLength, block1);
+
+        // if block number is 0, add size1 option
+        if (0 == block1->num)
+        {
+            res = CAAddBlockSizeOption(*pdu, COAP_OPTION_SIZE1, dataLength, options);
+            if (CA_STATUS_OK != res)
+            {
+                OIC_LOG(ERROR, TAG, "add has failed");
+                goto exit;
+            }
+        }
+
+        // add block option to option list.
+        res = CAAddBlockOptionImpl(block1, COAP_OPTION_BLOCK1, options);
         if (CA_STATUS_OK != res)
         {
             OIC_LOG(ERROR, TAG, "add has failed");
-            CARemoveBlockDataFromList(blockID);
-            return res;
+            goto exit;
         }
 
+        // add option list to pdu.
         res = CAAddOptionToPDU(*pdu, options);
         if (CA_STATUS_OK != res)
         {
             OIC_LOG(ERROR, TAG, "add has failed");
-            CARemoveBlockDataFromList(blockID);
-            return res;
+            goto exit;
         }
 
-        if (!coap_add_data(*pdu, dataLength, (const unsigned char *) info->payload))
+        // add the payload data as the block size.
+        if (!coap_add_block(*pdu, dataLength, (const unsigned char *) info->payload, block1->num,
+                            block1->szx))
         {
-            OIC_LOG(ERROR, TAG, "failed to add payload");
+            OIC_LOG(ERROR, TAG, "Data length is smaller than the start index");
             return CA_STATUS_FAILED;
         }
-
-        // reset block-list after write block
-        if (0 == block1->m)
-        {
-            // remove data from list
-            CAResult_t res = CARemoveBlockDataFromList(blockID);
-            if (CA_STATUS_OK != res)
-            {
-                OIC_LOG(ERROR, TAG, "remove has failed");
-                return res;
-            }
-        }
     }
     else
     {
-        CAGetMoreBitFromBlock(dataLength, block1);
-
-        CAResult_t res = CA_STATUS_OK;
-        // if block number is 0, add size1 option
-        if (0 == block1->num)
-        {
-            res = CAAddBlockSizeOption(*pdu, COAP_OPTION_SIZE1, dataLength, options);
-            if (CA_STATUS_OK != res)
-            {
-                OIC_LOG(ERROR, TAG, "add has failed");
-                CARemoveBlockDataFromList(blockID);
-                return res;
-            }
-        }
+        OIC_LOG(DEBUG, TAG, "received response message with block option1");
 
+        // add block option to option list.
         res = CAAddBlockOptionImpl(block1, COAP_OPTION_BLOCK1, options);
         if (CA_STATUS_OK != res)
         {
             OIC_LOG(ERROR, TAG, "add has failed");
-            CARemoveBlockDataFromList(blockID);
-            return res;
+            goto exit;
         }
 
+        // add option list to pdu.
         res = CAAddOptionToPDU(*pdu, options);
         if (CA_STATUS_OK != res)
         {
             OIC_LOG(ERROR, TAG, "add has failed");
-            CARemoveBlockDataFromList(blockID);
-            return res;
+            goto exit;
         }
 
-        CALogBlockInfo(block1);
-
-        if (!coap_add_block(*pdu, dataLength, (const unsigned char *) info->payload,
-                            block1->num, block1->szx))
+        // add the payload data as the block size.
+        if (!coap_add_data(*pdu, dataLength, (const unsigned char *) info->payload))
         {
-            OIC_LOG(ERROR, TAG, "Data length is smaller than the start index");
+            OIC_LOG(ERROR, TAG, "failed to add payload");
             return CA_STATUS_FAILED;
         }
 
-        // check the message type and if message type is NON, next block message will be sent
-        if (CA_MSG_NONCONFIRM == (*pdu)->hdr->coap_hdr_udp_t.type)
+        // if it is last block message, remove block data from list.
+        if (0 == block1->m)
         {
-            if (block1->m)
-            {
-                OIC_LOG(DEBUG, TAG, "NON, send next block..");
-                // update block data
-                block1->num++;
-                CAResult_t res = CAProcessNextStep(*pdu, NULL,
-                                                   CA_SENT_PREVIOUS_NON_MSG,
-                                                   blockID);
-                if (CA_STATUS_OK != res)
-                {
-                    OIC_LOG(ERROR, TAG, "failed to process next step");
-                    CARemoveBlockDataFromList(blockID);
-                    return res;
-                }
-            }
-            else
+            // remove data from list
+            res = CARemoveBlockDataFromList(blockID);
+            if (CA_STATUS_OK != res)
             {
-                CARemoveBlockDataFromList(blockID);
+                OIC_LOG(ERROR, TAG, "remove has failed");
+                return res;
             }
         }
     }
 
+    CALogBlockInfo(block1);
+
     OIC_LOG(DEBUG, TAG, "OUT-AddBlockOption1");
 
     return CA_STATUS_OK;
+
+exit:
+    CARemoveBlockDataFromList(blockID);
+    return res;
 }
 
 CAResult_t CAAddBlockOptionImpl(coap_block_t *block, uint8_t blockType,
@@ -1866,7 +1790,7 @@ bool CAIsPayloadLengthInPduWithBlockSizeOption(coap_pdu_t *pdu,
         *totalPayloadLen = coap_decode_var_bytes(COAP_OPT_VALUE(option),
                                                  COAP_OPT_LENGTH(option));
 
-        OIC_LOG_V(DEBUG, TAG, "the total payload length to be received is [%d]bytes",
+        OIC_LOG_V(DEBUG, TAG, "the total payload length to be received is [%zu]bytes",
                   *totalPayloadLen);
 
         return true;
@@ -1895,8 +1819,7 @@ uint8_t CACheckBlockErrorType(CABlockData_t *currData, coap_block_t *receivedBlo
     if (COAP_OPTION_BLOCK1 == blockType)
     {
         size_t prePayloadLen = currData->receivedPayloadLen;
-        if (prePayloadLen != (size_t)BLOCK_SIZE(receivedBlock->szx)
-            * receivedBlock->num)
+        if (prePayloadLen != (size_t) BLOCK_SIZE(receivedBlock->szx) * receivedBlock->num)
         {
             if (receivedBlock->num > currData->block1.num + 1)
             {
@@ -1925,8 +1848,7 @@ uint8_t CACheckBlockErrorType(CABlockData_t *currData, coap_block_t *receivedBlo
 
     // #3. check if error check logic is required
     size_t optionLen = dataLen - blockPayloadLen;
-    if (receivedBlock->m && blockPayloadLen !=
-        (size_t)BLOCK_SIZE(receivedBlock->szx))
+    if (receivedBlock->m && blockPayloadLen != (size_t) BLOCK_SIZE(receivedBlock->szx))
     {
         // 413 Error handling of too large entity
         if (COAP_MAX_PDU_SIZE < BLOCK_SIZE(receivedBlock->szx) + optionLen)
@@ -1941,14 +1863,8 @@ uint8_t CACheckBlockErrorType(CABlockData_t *currData, coap_block_t *receivedBlo
                 if (COAP_MAX_PDU_SIZE >= BLOCK_SIZE(size) + optionLen)
                 {
                     OIC_LOG_V(ERROR, TAG, "replace sze with %d", size);
-                    if (COAP_OPTION_BLOCK2 == blockType)
-                    {
-                        currData->block2.szx = size;
-                    }
-                    else
-                    {
-                        currData->block1.szx = size;
-                    }
+                    currData->block2.szx = size;
+                    currData->block1.szx = size;
                     break;
                 }
             }
@@ -2054,7 +1970,7 @@ CAResult_t CAUpdatePayloadData(CABlockData_t *currData, const CAData_t *received
         // update received payload length
         currData->receivedPayloadLen += blockPayloadLen;
 
-        OIC_LOG_V(DEBUG, TAG, "updated payload: %s, len: %d", currData->payload,
+        OIC_LOG_V(DEBUG, TAG, "updated payload: %s, len: %zu", currData->payload,
                   currData->receivedPayloadLen);
     }
 
@@ -2068,33 +1984,69 @@ CAData_t* CACreateNewDataSet(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint
     VERIFY_NON_NULL_RET(pdu->hdr, TAG, "pdu->hdr", NULL);
     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", NULL);
 
-    CAInfo_t responseData = { .tokenLength = pdu->hdr->coap_hdr_udp_t.token_length };
-    responseData.token = (CAToken_t) OICMalloc(responseData.tokenLength);
-    if (!responseData.token)
+    CARequestInfo_t* requestInfo = NULL;
+    CAResponseInfo_t* responseInfo = NULL;
+
+    uint32_t code = pdu->hdr->coap_hdr_udp_t.code;
+    if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
     {
-        OIC_LOG(ERROR, TAG, "out of memory");
-        return NULL;
-    }
-    memcpy(responseData.token, pdu->hdr->coap_hdr_udp_t.token, responseData.tokenLength);
+        CAInfo_t responseData = { .tokenLength = pdu->hdr->coap_hdr_udp_t.token_length };
+        responseData.token = (CAToken_t) OICMalloc(responseData.tokenLength);
+        if (!responseData.token)
+        {
+            OIC_LOG(ERROR, TAG, "out of memory");
+            return NULL;
+        }
+        memcpy(responseData.token, pdu->hdr->coap_hdr_udp_t.token, responseData.tokenLength);
 
-    CAResponseInfo_t* responseInfo = (CAResponseInfo_t*) OICCalloc(1, sizeof(CAResponseInfo_t));
-    if (!responseInfo)
+        responseInfo = (CAResponseInfo_t*) OICCalloc(1, sizeof(CAResponseInfo_t));
+        if (!responseInfo)
+        {
+            OIC_LOG(ERROR, TAG, "out of memory");
+            OICFree(responseData.token);
+            return NULL;
+        }
+        responseInfo->info = responseData;
+    }
+    else
     {
-        OIC_LOG(ERROR, TAG, "out of memory");
-        OICFree(responseData.token);
-        return NULL;
+        CAInfo_t requestData = { .tokenLength = pdu->hdr->coap_hdr_udp_t.token_length };
+        requestData.token = (CAToken_t) OICMalloc(requestData.tokenLength);
+        if (!requestData.token)
+        {
+            OIC_LOG(ERROR, TAG, "out of memory");
+            return NULL;
+        }
+        memcpy(requestData.token, pdu->hdr->coap_hdr_udp_t.token, requestData.tokenLength);
+
+        requestInfo = (CARequestInfo_t*) OICCalloc(1, sizeof(CARequestInfo_t));
+        if (!requestInfo)
+        {
+            OIC_LOG(ERROR, TAG, "out of memory");
+            OICFree(requestData.token);
+            return NULL;
+        }
+        requestInfo->info = requestData;
+
+        // get resource uri information from received response message
+        // to send next request message to remote device
+        CAResponseInfo_t resInfo = { 0 };
+        CAGetResponseInfoFromPDU(pdu, &resInfo, endpoint);
+
+        requestInfo->method = CA_GET;
+        requestInfo->info.resourceUri = resInfo.info.resourceUri;
     }
-    responseInfo->info = responseData;
 
     CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
     if (!data)
     {
         OIC_LOG(ERROR, TAG, "out of memory");
+        OICFree(requestInfo);
         OICFree(responseInfo);
         return NULL;
     }
 
-    data->requestInfo = NULL;
+    data->requestInfo = requestInfo;
     data->responseInfo = responseInfo;
     data->remoteEndpoint = CACloneEndpoint(endpoint);
     data->type = SEND_TYPE_UNICAST;
@@ -2118,8 +2070,7 @@ CAData_t *CACloneCAData(const CAData_t *data)
     {
         clone->requestInfo = CACloneRequestInfo(data->requestInfo);
     }
-
-    if (data->responseInfo)
+    else if (data->responseInfo)
     {
         clone->responseInfo = CACloneResponseInfo(data->responseInfo);
     }
@@ -2144,6 +2095,11 @@ CAResult_t CAUpdatePayloadToCAData(CAData_t *data, const CAPayload_t payload,
     switch (data->dataType)
     {
         case CA_REQUEST_DATA:
+            if (!data->requestInfo)
+            {
+                OIC_LOG(ERROR, TAG, "request info is null");
+                return CA_STATUS_FAILED;
+            }
             // allocate payload field
             newPayload = OICRealloc(data->requestInfo->info.payload, payloadLen);
             if (!newPayload)
@@ -2157,6 +2113,11 @@ CAResult_t CAUpdatePayloadToCAData(CAData_t *data, const CAPayload_t payload,
             break;
 
         case CA_RESPONSE_DATA:
+            if (!data->responseInfo)
+            {
+                OIC_LOG(ERROR, TAG, "response info is null");
+                return CA_STATUS_FAILED;
+            }
             // allocate payload field
             newPayload = OICRealloc(data->responseInfo->info.payload, payloadLen);
             if (!newPayload)
@@ -2226,6 +2187,7 @@ CAResult_t CAHandleBlockErrorResponse(coap_block_t *block, uint16_t blockType,
             break;
         default:
             OIC_LOG_V(ERROR, TAG, "there is no Error Code of BWT[%d]", responseResult);
+            return CA_STATUS_FAILED;
     }
 
     OIC_LOG(DEBUG, TAG, "OUT-HandleBlockErrorRes");
@@ -2352,7 +2314,7 @@ CAResult_t CAGetTokenFromBlockDataList(const coap_pdu_t *pdu, const CAEndpoint_t
     ca_mutex_unlock(g_context.blockDataListMutex);
 
     OIC_LOG(DEBUG, TAG, "OUT-CAGetTokenFromBlockDataList");
-    return CA_STATUS_OK;
+    return CA_STATUS_FAILED;
 }
 
 CAResult_t CACheckBlockDataValidation(const CAData_t *sendData, CABlockData_t **blockData)
@@ -2360,13 +2322,40 @@ 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
+    {
+        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)
         {
             continue;
@@ -2380,25 +2369,11 @@ CAResult_t CACheckBlockDataValidation(const CAData_t *sendData, CABlockData_t **
                     && currData->blockDataId->idLength > 0
                     && NULL != sendData->requestInfo->info.token)
             {
-                CABlockDataID_t* blockDataID = CACreateBlockDatablockId(
-                        (CAToken_t)sendData->requestInfo->info.token,
-                        sendData->requestInfo->info.tokenLength,
-                        sendData->remoteEndpoint->port);
-
-                if(NULL == blockDataID || NULL == blockDataID->id || blockDataID->idLength < 1)
-                {
-                    OIC_LOG(ERROR, TAG, "blockId is null");
-                    CADestroyBlockID(blockDataID);
-                    return CA_STATUS_FAILED;
-                }
-
                 if (CABlockidMatches(currData, blockDataID))
                 {
                     OIC_LOG(ERROR, TAG, "already sent");
-                    CADestroyBlockID(blockDataID);
                     continue;
                 }
-                CADestroyBlockID(blockDataID);
             }
         }
         else if (sendData->responseInfo) // sendData is responseMessage
@@ -2409,18 +2384,6 @@ CAResult_t CACheckBlockDataValidation(const CAData_t *sendData, CABlockData_t **
                     && currData->blockDataId->idLength > 0
                     && NULL != sendData->responseInfo->info.token)
             {
-                CABlockDataID_t* blockDataID = CACreateBlockDatablockId(
-                        (CAToken_t)sendData->responseInfo->info.token,
-                        sendData->responseInfo->info.tokenLength,
-                        sendData->remoteEndpoint->port);
-
-                if(NULL == blockDataID || NULL == blockDataID->id || blockDataID->idLength < 1)
-                {
-                    OIC_LOG(ERROR, TAG, "blockId is null");
-                    CADestroyBlockID(blockDataID);
-                    return CA_STATUS_FAILED;
-                }
-
                 if (CABlockidMatches(currData, blockDataID))
                 {
                     // set sendData
@@ -2431,11 +2394,10 @@ CAResult_t CACheckBlockDataValidation(const CAData_t *sendData, CABlockData_t **
                     }
                     currData->sentData = CACloneCAData(sendData);
                     *blockData = currData;
-                    CADestroyBlockID(blockDataID);
                     ca_mutex_unlock(g_context.blockDataListMutex);
+                    CADestroyBlockID(blockDataID);
                     return CA_STATUS_OK;
                 }
-                CADestroyBlockID(blockDataID);
             }
         }
         else
@@ -2446,6 +2408,8 @@ CAResult_t CACheckBlockDataValidation(const CAData_t *sendData, CABlockData_t **
     }
     ca_mutex_unlock(g_context.blockDataListMutex);
 
+    CADestroyBlockID(blockDataID);
+
     return CA_STATUS_FAILED;
 }
 
@@ -2470,8 +2434,7 @@ CABlockData_t *CAGetBlockDataFromBlockDataList(const CABlockDataID_t *blockID)
     return NULL;
 }
 
-coap_block_t *CAGetBlockOption(const CABlockDataID_t *blockID,
-                               uint16_t blockType)
+coap_block_t *CAGetBlockOption(const CABlockDataID_t *blockID, uint16_t blockType)
 {
     OIC_LOG(DEBUG, TAG, "IN-GetBlockOption");
     VERIFY_NON_NULL_RET(blockID, TAG, "blockID", NULL);
@@ -2490,7 +2453,7 @@ coap_block_t *CAGetBlockOption(const CABlockDataID_t *blockID,
             {
                 return &currData->block2;
             }
-            else
+            else if (COAP_OPTION_BLOCK1 == blockType)
             {
                 return &currData->block1;
             }
@@ -2545,7 +2508,7 @@ CABlockData_t *CACreateNewBlockData(const CAData_t *sendData)
     data->block1.szx = CA_DEFAULT_BLOCK_SIZE;
     data->block2.szx = CA_DEFAULT_BLOCK_SIZE;
     data->sentData = CACloneCAData(sendData);
-    if(!data->sentData)
+    if (!data->sentData)
     {
         OIC_LOG(ERROR, TAG, PCF("memory alloc has failed"));
         OICFree(data);
@@ -2560,16 +2523,23 @@ CABlockData_t *CACreateNewBlockData(const CAData_t *sendData)
         tokenLength = data->sentData->requestInfo->info.tokenLength;
         token = data->sentData->requestInfo->info.token;
     }
-    else if(data->sentData->responseInfo)
+    else if (data->sentData->responseInfo)
     {
         tokenLength = data->sentData->responseInfo->info.tokenLength;
         token = data->sentData->responseInfo->info.token;
     }
 
-    CABlockDataID_t* blockDataID = CACreateBlockDatablockId(
-            token, tokenLength,
-            data->sentData->remoteEndpoint->port);
-    if (NULL == blockDataID || NULL == blockDataID->id || blockDataID->idLength < 1)
+    if (!data->sentData->remoteEndpoint)
+    {
+        OIC_LOG(ERROR, TAG, "remoteEndpoint is null");
+        CADestroyDataSet(data->sentData);
+        OICFree(data);
+        return NULL;
+    }
+
+    CABlockDataID_t* blockDataID = CACreateBlockDatablockId(token, tokenLength,
+                                                            data->sentData->remoteEndpoint->port);
+    if (NULL == blockDataID || blockDataID->idLength < 1)
     {
         OIC_LOG(ERROR, TAG, "blockId is null");
         CADestroyBlockID(blockDataID);
@@ -2619,10 +2589,7 @@ CAResult_t CARemoveBlockDataFromList(const CABlockDataID_t *blockID)
             }
 
             // destroy memory
-            if (currData->sentData)
-            {
-                CADestroyDataSet(currData->sentData);
-            }
+            CADestroyDataSet(currData->sentData);
             CADestroyBlockID(currData->blockDataId);
             OICFree(currData->payload);
             OICFree(currData);
@@ -2635,30 +2602,6 @@ CAResult_t CARemoveBlockDataFromList(const CABlockDataID_t *blockID)
     return CA_STATUS_OK;
 }
 
-bool CAIsBlockDataInList(const CABlockDataID_t *blockID)
-{
-    OIC_LOG(DEBUG, TAG, "IN-IsBlockDataInList");
-    VERIFY_NON_NULL_RET(blockID, TAG, "blockID", false);
-
-    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 (CABlockidMatches(currData, blockID))
-        {
-            OIC_LOG(DEBUG, TAG, "found block data");
-            ca_mutex_unlock(g_context.blockDataListMutex);
-            return true;
-        }
-    }
-    ca_mutex_unlock(g_context.blockDataListMutex);
-
-    OIC_LOG(DEBUG, TAG, "OUT-IsBlockDataInList");
-    return false;
-}
-
 void CADestroyDataSet(CAData_t* data)
 {
     VERIFY_NON_NULL_VOID(data, TAG, "data");
@@ -2672,11 +2615,9 @@ void CADestroyDataSet(CAData_t* data)
 CABlockDataID_t* CACreateBlockDatablockId(const CAToken_t token, uint8_t tokenLength,
                                           uint16_t portNumber)
 {
-    VERIFY_NON_NULL_RET(token, TAG, "token", NULL);
-
-    char port[PORT_LENGTH] = {0,};
-    port[0] = (char)((portNumber>>8) & 0xFF);
-    port[1] = (char)(portNumber & 0xFF);
+    char port[PORT_LENGTH] = { 0, };
+    port[0] = (char) ((portNumber >> 8) & 0xFF);
+    port[1] = (char) (portNumber & 0xFF);
 
     CABlockDataID_t* blockDataID = (CABlockDataID_t *) OICMalloc(sizeof(CABlockDataID_t));
     if (!blockDataID)
@@ -2693,7 +2634,11 @@ CABlockDataID_t* CACreateBlockDatablockId(const CAToken_t token, uint8_t tokenLe
         return NULL;
     }
 
-    memcpy(blockDataID->id, token, tokenLength);
+    if (token)
+    {
+        memcpy(blockDataID->id, token, tokenLength);
+    }
+
     memcpy(blockDataID->id + tokenLength, port, sizeof(port));
 
     OIC_LOG(DEBUG, TAG, "BlockID is ");
index a71b849..691e2bc 100644 (file)
@@ -23,6 +23,7 @@
 #include <stdint.h>
 #include <stdbool.h>
 
+#include "ocrandom.h"
 #include "cainterface.h"
 #include "caremotehandler.h"
 #include "camessagehandler.h"
 #include "catcpadapter.h"
 #endif
 
-CAGlobals_t caglobals = { 0 };
+CAGlobals_t caglobals = { .clientFlags = 0,
+                          .serverFlags = 0, };
 
-#define TAG "CA_CONN_MGR"
+#define TAG "OIC_CA_CONN_MGR"
 
 static bool g_isInitialized = false;
 
@@ -59,6 +61,7 @@ extern void CADTLSSetCrlCallback(CAGetDTLSCrlHandler crlCallback);
 
 CAResult_t CAInitialize()
 {
+    OIC_LOG_V(DEBUG, TAG, "IoTivity version is v%s", IOTIVITY_VERSION);
     OIC_LOG(DEBUG, TAG, "CAInitialize");
 
     if (!g_isInitialized)
@@ -144,6 +147,20 @@ void CARegisterHandler(CARequestCallback ReqHandler, CAResponseCallback RespHand
 }
 
 #ifdef __WITH_DTLS__
+CAResult_t CARegisterDTLSHandshakeCallback(CAErrorCallback dtlsHandshakeCallback)
+{
+    OIC_LOG(DEBUG, TAG, "CARegisterDTLSHandshakeCallback");
+
+    if(!g_isInitialized)
+    {
+        return CA_STATUS_NOT_INITIALIZED;
+    }
+
+    CADTLSSetHandshakeCallback(dtlsHandshakeCallback);
+
+    return CA_STATUS_OK;
+}
+
 CAResult_t CARegisterDTLSCredentialsHandler(CAGetDTLSPskCredentialsHandler GetDTLSCredentialsHandler)
 {
     OIC_LOG(DEBUG, TAG, "CARegisterDTLSCredentialsHandler");
@@ -242,16 +259,67 @@ CAResult_t CAGetNetworkInformation(CAEndpoint_t **info, uint32_t *size)
     return CAGetNetworkInformationInternal(info, size);
 }
 
-CAResult_t CASendRequest(const CAEndpoint_t *object,const CARequestInfo_t *requestInfo)
+static CAResult_t CASendMessageMultiAdapter(const CAEndpoint_t *object, const void *sendMsg,
+                                            CADataType_t dataType)
+{
+    OIC_LOG(DEBUG, TAG, "CASendMessageMultipleAdapter");
+
+    CATransportAdapter_t connTypes[] = {
+            CA_ADAPTER_IP
+#ifdef LE_ADAPTER
+            ,CA_ADAPTER_GATT_BTLE
+#endif
+#ifdef EDR_ADAPTER
+            ,CA_ADAPTER_RFCOMM_BTEDR
+#endif
+#ifdef NFC_ADAPTER
+            ,CA_ADAPTER_NFC
+#endif
+#ifdef RA_ADAPTER
+            ,CA_ADAPTER_REMOTE_ACCESS
+#endif
+#ifdef TCP_ADAPTER
+            ,CA_ADAPTER_TCP
+#endif
+        };
+
+    CAEndpoint_t *cloneEp = CACloneEndpoint(object);
+    if (!cloneEp)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to clone CAEndpoint");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    CAResult_t ret = CA_STATUS_OK;
+    size_t numConnTypes = sizeof(connTypes) / sizeof(connTypes[0]);
+
+    for (size_t i = 0; i < numConnTypes && ret == CA_STATUS_OK; i++)
+    {
+        cloneEp->adapter = connTypes[i];
+        ret = CADetachSendMessage(cloneEp, sendMsg, dataType);
+    }
+    CAFreeEndpoint(cloneEp);
+    return ret;
+}
+
+CAResult_t CASendRequest(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo)
 {
-    OIC_LOG(DEBUG, TAG, "CASendGetRequest");
+    OIC_LOG(DEBUG, TAG, "CASendRequest");
 
     if(!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
 
-    return CADetachRequestMessage(object, requestInfo);
+    if (requestInfo && requestInfo->isMulticast &&
+            (object->adapter == CA_DEFAULT_ADAPTER || object->adapter == CA_ALL_ADAPTERS))
+    {
+        return CASendMessageMultiAdapter(object, requestInfo, CA_REQUEST_DATA);
+    }
+    else
+    {
+        return CADetachSendMessage(object, requestInfo, CA_REQUEST_DATA);
+    }
 }
 
 CAResult_t CASendResponse(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
@@ -263,7 +331,15 @@ CAResult_t CASendResponse(const CAEndpoint_t *object, const CAResponseInfo_t *re
         return CA_STATUS_NOT_INITIALIZED;
     }
 
-    return CADetachResponseMessage(object, responseInfo);
+    if (responseInfo && responseInfo->isMulticast &&
+            (object->adapter == CA_DEFAULT_ADAPTER || object->adapter == CA_ALL_ADAPTERS))
+    {
+        return CASendMessageMultiAdapter(object, responseInfo, CA_RESPONSE_DATA);
+    }
+    else
+    {
+        return CADetachSendMessage(object, responseInfo, CA_RESPONSE_DATA);
+    }
 }
 
 CAResult_t CASelectNetwork(CATransportAdapter_t interestedNetwork)
@@ -310,7 +386,11 @@ CAResult_t CASelectNetwork(CATransportAdapter_t interestedNetwork)
                   "CAAddNetworkType(CA_ADAPTER_TCP) function returns result : %d", res);
     }
 #endif
-
+    else if (interestedNetwork & CA_ADAPTER_NFC)
+    {
+        res = CAAddNetworkType(CA_ADAPTER_NFC);
+        OIC_LOG_V(DEBUG, TAG, "CAAddNetworkType(CA_ADAPTER_NFC) function returns result : %d", res);
+    }
     else
     {
         res = CA_NOT_SUPPORTED;
@@ -384,7 +464,6 @@ CAResult_t CAHandleRequestResponse()
 }
 
 #ifdef __WITH_DTLS__
-
 CAResult_t CASelectCipherSuite(const uint16_t cipher)
 {
     OIC_LOG_V(DEBUG, TAG, "CASelectCipherSuite");
@@ -472,3 +551,11 @@ CAResult_t CACloseDtlsSession(const CAEndpoint_t *endpoint)
 }
 
 #endif /* __WITH_DTLS__ */
+
+#ifdef TCP_ADAPTER
+void CARegisterKeepAliveHandler(CAKeepAliveConnectedCallback ConnHandler,
+                                CAKeepAliveDisconnectedCallback DisconnHandler)
+{
+    CATCPSetKeepAliveCallbacks(ConnHandler, DisconnHandler);
+}
+#endif
index 71124d3..a21f5b5 100644 (file)
@@ -30,6 +30,7 @@
 #include "cainterfacecontroller.h"
 #include "caedradapter.h"
 #include "caleadapter.h"
+#include "canfcadapter.h"
 #include "caremotehandler.h"
 #include "cathreadpool.h"
 #include "caipadapter.h"
 #include "catcpadapter.h"
 #endif
 
-#define TAG "CA_INTRFC_CNTRLR"
+#define TAG "OIC_CA_INF_CTR"
 
 #define CA_MEMORY_ALLOC_CHECK(arg) {if (arg == NULL) \
     {OIC_LOG(ERROR, TAG, "memory error");goto memory_error_exit;} }
 
-#ifdef TCP_ADAPTER
-#define CA_TRANSPORT_TYPE_NUM   5
-#elif RA_ADAPTER
-#define CA_TRANSPORT_TYPE_NUM   4
-#else
-#define CA_TRANSPORT_TYPE_NUM   3
-#endif
 
-static CAConnectivityHandler_t g_adapterHandler[CA_TRANSPORT_TYPE_NUM] = {};
+
+static CAConnectivityHandler_t *g_adapterHandler = NULL;
+
+static uint32_t g_numberOfAdapters = 0;
 
 static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
 
@@ -66,35 +63,18 @@ static CAErrorHandleCallback g_errorHandleCallback = NULL;
 
 static int CAGetAdapterIndex(CATransportAdapter_t cType)
 {
-    switch (cType)
+    for (uint32_t index=0 ; index < g_numberOfAdapters ; index++)
     {
-        case CA_ADAPTER_IP:
-            return 0;
-        case CA_ADAPTER_GATT_BTLE:
-            return 1;
-        case CA_ADAPTER_RFCOMM_BTEDR:
-            return 2;
-
-#ifdef RA_ADAPTER
-        case CA_ADAPTER_REMOTE_ACCESS:
-            return 3;
-#endif
-
-#ifdef TCP_ADAPTER
-        case CA_ADAPTER_TCP:
-            return 4;
-#endif
-
-        default:
-            break;
+        if (cType == g_adapterHandler[index].cType )
+         {
+             return index;
+         }
     }
     return -1;
 }
 
-static void CARegisterCallback(CAConnectivityHandler_t handler, CATransportAdapter_t cType)
+static void CARegisterCallback(CAConnectivityHandler_t handler)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     if(handler.startAdapter == NULL ||
         handler.startListenServer == NULL ||
         handler.stopListenServer == NULL ||
@@ -109,19 +89,19 @@ static void CARegisterCallback(CAConnectivityHandler_t handler, CATransportAdapt
         OIC_LOG(ERROR, TAG, "connectivity handler is not enough to be used!");
         return;
     }
-
-    int index = CAGetAdapterIndex(cType);
-
-    if (index == -1)
+    uint32_t numberofAdapters = g_numberOfAdapters + 1;
+    CAConnectivityHandler_t *adapterHandler = OICRealloc(g_adapterHandler,
+                                   (numberofAdapters) * sizeof(*adapterHandler));
+    if (NULL == adapterHandler)
     {
-        OIC_LOG(ERROR, TAG, "unknown connectivity type!");
+        OIC_LOG(ERROR, TAG, "Memory allocation failed during registration");
         return;
     }
+    g_adapterHandler = adapterHandler;
+    g_numberOfAdapters = numberofAdapters;
+    g_adapterHandler[g_numberOfAdapters-1] = handler;
 
-    g_adapterHandler[index] = handler;
-
-    OIC_LOG_V(DEBUG, TAG, "%d type adapter, register complete!", cType);
-    OIC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG_V(DEBUG, TAG, "%d type adapter, register complete!", handler.cType);
 }
 
 #ifdef RA_ADAPTER
@@ -134,8 +114,6 @@ CAResult_t CASetAdapterRAInfo(const CARAInfo_t *caraInfo)
 static void CAReceivedPacketCallback(const CASecureEndpoint_t *sep,
                                      const void *data, uint32_t dataLen)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     if (g_networkPacketReceivedCallback != NULL)
     {
         g_networkPacketReceivedCallback(sep, data, dataLen);
@@ -144,21 +122,15 @@ static void CAReceivedPacketCallback(const CASecureEndpoint_t *sep,
     {
         OIC_LOG(ERROR, TAG, "network packet received callback is NULL!");
     }
-
-    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 static void CANetworkChangedCallback(const CAEndpoint_t *info, CANetworkStatus_t status)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     // Call the callback.
     if (g_networkChangeCallback != NULL)
     {
         g_networkChangeCallback(info, status);
     }
-
-    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 static void CAAdapterErrorHandleCallback(const CAEndpoint_t *endpoint,
@@ -178,8 +150,6 @@ void CAInitializeAdapters(ca_thread_pool_t handle)
 {
     OIC_LOG(DEBUG, TAG, "initialize adapters..");
 
-    memset(g_adapterHandler, 0, sizeof(CAConnectivityHandler_t) * CA_TRANSPORT_TYPE_NUM);
-
     // Initialize adapters and register callback.
 #ifdef IP_ADAPTER
     CAInitializeIP(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback,
@@ -205,24 +175,25 @@ void CAInitializeAdapters(ca_thread_pool_t handle)
     CAInitializeTCP(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback,
                     CAAdapterErrorHandleCallback, handle);
 #endif /* TCP_ADAPTER */
+
+#ifdef NFC_ADAPTER
+    CAInitializeNFC(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback,
+                    CAAdapterErrorHandleCallback, handle);
+#endif /* NFC_ADAPTER */
 }
 
 void CASetPacketReceivedCallback(CANetworkPacketReceivedCallback callback)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "Set Receiver handle callback");
 
     g_networkPacketReceivedCallback = callback;
-
-    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 void CASetNetworkChangeCallback(CANetworkChangeCallback callback)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "Set network handle callback");
 
     g_networkChangeCallback = callback;
-
-    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 void CASetErrorHandleCallback(CAErrorHandleCallback errorCallback)
@@ -236,19 +207,19 @@ CAResult_t CAStartAdapter(CATransportAdapter_t transportType)
     OIC_LOG_V(DEBUG, TAG, "Start the adapter of CAConnectivityType[%d]", transportType);
 
     int index = CAGetAdapterIndex(transportType);
-
-    if (index == -1)
+    if (0 > index)
     {
         OIC_LOG(ERROR, TAG, "unknown connectivity type!");
         return CA_STATUS_FAILED;
     }
 
+    CAResult_t res = CA_STATUS_FAILED;
     if (g_adapterHandler[index].startAdapter != NULL)
     {
-        g_adapterHandler[index].startAdapter();
+        res = g_adapterHandler[index].startAdapter();
     }
 
-    return CA_STATUS_OK;
+    return res;
 }
 
 void CAStopAdapter(CATransportAdapter_t transportType)
@@ -256,8 +227,7 @@ void CAStopAdapter(CATransportAdapter_t transportType)
     OIC_LOG_V(DEBUG, TAG, "Stop the adapter of CATransportType[%d]", transportType);
 
     int index = CAGetAdapterIndex(transportType);
-
-    if (index == -1)
+    if (0 > index)
     {
         OIC_LOG(ERROR, TAG, "unknown transport type!");
         return;
@@ -276,12 +246,23 @@ CAResult_t CAGetNetworkInfo(CAEndpoint_t **info, uint32_t *size)
         return CA_STATUS_INVALID_PARAM;
     }
 
-    CAEndpoint_t *tempInfo[CA_TRANSPORT_TYPE_NUM] = { 0 };
-    uint32_t tempSize[CA_TRANSPORT_TYPE_NUM] = { 0 };
+    CAEndpoint_t **tempInfo = (CAEndpoint_t**) OICCalloc(g_numberOfAdapters, sizeof(*tempInfo));
+    if (!tempInfo)
+    {
+        OIC_LOG(ERROR, TAG, "Out of memory!");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+    uint32_t *tempSize =(uint32_t*) OICCalloc(g_numberOfAdapters, sizeof(*tempSize));
+    if (!tempSize)
+    {
+        OIC_LOG(ERROR, TAG, "Out of memory!");
+        OICFree(tempInfo);
+        return CA_MEMORY_ALLOC_FAILED;
+    }
 
     CAResult_t res = CA_STATUS_FAILED;
-    uint32_t resSize = 0;
-    for (int index = 0; index < CA_TRANSPORT_TYPE_NUM; index++)
+    size_t resSize = 0;
+    for (uint32_t index = 0; index < g_numberOfAdapters; index++)
     {
         if (g_adapterHandler[index].GetnetInfo != NULL)
         {
@@ -297,22 +278,27 @@ CAResult_t CAGetNetworkInfo(CAEndpoint_t **info, uint32_t *size)
 
             OIC_LOG_V(DEBUG,
                       TAG,
-                      "%d adapter network info size is %" PRIu32 " res:%d",
+                      "%zu adapter network info size is %" PRIu32 " res:%d",
                       index,
                       tempSize[index],
                       res);
         }
     }
 
-    OIC_LOG_V(DEBUG, TAG, "network info total size is %d!", resSize);
+    OIC_LOG_V(DEBUG, TAG, "network info total size is %zu!", resSize);
 
     if (resSize == 0)
     {
+        OICFree(tempInfo);
+        OICFree(tempSize);
         if (res == CA_ADAPTER_NOT_ENABLED || res == CA_NOT_SUPPORTED)
         {
             return res;
         }
-        return CA_STATUS_FAILED;
+        else
+        {
+            return CA_STATUS_FAILED;
+        }
     }
 
     // #3. add data into result
@@ -324,7 +310,7 @@ CAResult_t CAGetNetworkInfo(CAEndpoint_t **info, uint32_t *size)
     *info = resInfo;
     *size = resSize;
 
-    for (int index = 0; index < CA_TRANSPORT_TYPE_NUM; index++)
+    for (uint32_t index = 0; index < g_numberOfAdapters; index++)
     {
         // check information
         if (tempSize[index] == 0)
@@ -342,6 +328,8 @@ CAResult_t CAGetNetworkInfo(CAEndpoint_t **info, uint32_t *size)
         OICFree(tempInfo[index]);
         tempInfo[index] = NULL;
     }
+    OICFree(tempInfo);
+    OICFree(tempSize);
 
     OIC_LOG(DEBUG, TAG, "each network info save success!");
     return CA_STATUS_OK;
@@ -349,60 +337,81 @@ CAResult_t CAGetNetworkInfo(CAEndpoint_t **info, uint32_t *size)
     // memory error label.
 memory_error_exit:
 
-    for (int index = 0; index < CA_TRANSPORT_TYPE_NUM; index++)
+    for (uint32_t index = 0; index < g_numberOfAdapters; index++)
     {
-
         OICFree(tempInfo[index]);
         tempInfo[index] = NULL;
     }
+    OICFree(tempInfo);
+    OICFree(tempSize);
 
     return CA_MEMORY_ALLOC_FAILED;
 }
 
 CAResult_t CASendUnicastData(const CAEndpoint_t *endpoint, const void *data, uint32_t length)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     if (endpoint == NULL)
     {
         OIC_LOG(DEBUG, TAG, "Invalid endpoint");
         return CA_STATUS_INVALID_PARAM;
     }
 
-    CATransportAdapter_t type = endpoint->adapter;
 
-    int index = CAGetAdapterIndex(type);
-
-    if (index == -1)
+    u_arraylist_t *list = CAGetSelectedNetworkList();
+    if (!list)
     {
-        OIC_LOG(ERROR, TAG, "unknown transport type!");
-        return CA_STATUS_INVALID_PARAM;
+        OIC_LOG(ERROR, TAG, "No selected network");
+        return CA_SEND_FAILED;
     }
+    CATransportAdapter_t requestedAdapter = endpoint->adapter ? endpoint->adapter : CA_ALL_ADAPTERS;
 
-    int32_t sentDataLen = 0;
-
-    if (g_adapterHandler[index].sendData != NULL)
+    for (uint32_t i = 0; i < u_arraylist_length(list); i++)
     {
-        sentDataLen = g_adapterHandler[index].sendData(endpoint, data, length);
-    }
+        void* ptrType = u_arraylist_get(list, i);
 
-    if (sentDataLen != (int)length)
-    {
-        OIC_LOG(ERROR, TAG, "error in sending data. Error will be reported in adapter");
+        if (NULL == ptrType)
+        {
+            continue;
+        }
+
+        CATransportAdapter_t connType = *(CATransportAdapter_t *)ptrType;
+        if (0 == (connType & requestedAdapter))
+        {
+            continue;
+        }
+
+        int index = CAGetAdapterIndex(connType);
+
+        if (-1 == index)
+        {
+            OIC_LOG(ERROR, TAG, "unknown transport type!");
+            return CA_STATUS_INVALID_PARAM;
+        }
+
+        int32_t sentDataLen = 0;
+
+        if (NULL != g_adapterHandler[index].sendData)
+        {
+            OIC_LOG(DEBUG, TAG, "unicast message to adapter");
+            sentDataLen = g_adapterHandler[index].sendData(endpoint, data, length);
+        }
+
+        if (sentDataLen != (int32_t)length)
+        {
+            OIC_LOG(ERROR, TAG, "error in sending data. Error will be reported in adapter");
 #ifdef SINGLE_THREAD
-        //in case of single thread, no error handler. Report error immediately
-        return CA_SEND_FAILED;
+            //in case of single thread, no error handler. Report error immediately
+            return CA_SEND_FAILED;
 #endif
+        }
+
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
 
 CAResult_t CASendMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t length)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     u_arraylist_t *list = CAGetSelectedNetworkList();
     if (!list)
     {
@@ -410,26 +419,26 @@ CAResult_t CASendMulticastData(const CAEndpoint_t *endpoint, const void *data, u
         return CA_SEND_FAILED;
     }
 
-    CATransportFlags_t requestedAdapter = endpoint->adapter ? endpoint->adapter : CA_ALL_ADAPTERS;
-
-    for (uint32_t i = 0; i < u_arraylist_length(list); i++)
+    CATransportAdapter_t requestedAdapter = endpoint->adapter ? endpoint->adapter : CA_ALL_ADAPTERS;
+    size_t selectedLength = u_arraylist_length(list);
+    for (size_t i = 0; i < selectedLength; i++)
     {
         void* ptrType = u_arraylist_get(list, i);
 
-        if(ptrType == NULL)
+        if(NULL == ptrType)
         {
             continue;
         }
 
         CATransportAdapter_t connType = *(CATransportAdapter_t *)ptrType;
-        if ((connType & requestedAdapter) == 0)
+        if (0 == (connType & requestedAdapter))
         {
             continue;
         }
 
         int index = CAGetAdapterIndex(connType);
-
-        if (index == -1)
+        if (0 > index)
+        if (-1 == index)
         {
             OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
             continue;
@@ -437,7 +446,7 @@ CAResult_t CASendMulticastData(const CAEndpoint_t *endpoint, const void *data, u
 
         uint32_t sentDataLen = 0;
 
-        if (g_adapterHandler[index].sendDataToAll != NULL)
+        if (NULL != g_adapterHandler[index].sendDataToAll)
         {
             void *payload = (void *) OICMalloc(length);
             if (!payload)
@@ -460,23 +469,22 @@ CAResult_t CASendMulticastData(const CAEndpoint_t *endpoint, const void *data, u
         }
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT");
-
     return CA_STATUS_OK;
 }
 
 CAResult_t CAStartListeningServerAdapters()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
+    CAResult_t result = CA_STATUS_FAILED;
 
     u_arraylist_t *list = CAGetSelectedNetworkList();
     if (!list)
     {
         OIC_LOG(ERROR, TAG, "No selected network");
-        return CA_STATUS_FAILED;
+        return result;
     }
 
-    for (uint32_t i = 0; i < u_arraylist_length(list); i++)
+    size_t length = u_arraylist_length(list);
+    for (size_t i = 0; i < length; i++)
     {
         void* ptrType = u_arraylist_get(list, i);
 
@@ -488,7 +496,7 @@ CAResult_t CAStartListeningServerAdapters()
         CATransportAdapter_t connType = *(CATransportAdapter_t *)ptrType;
 
         int index = CAGetAdapterIndex(connType);
-        if (index == -1)
+        if (0 > index)
         {
             OIC_LOG(ERROR, TAG, "unknown connectivity type!");
             continue;
@@ -496,18 +504,22 @@ CAResult_t CAStartListeningServerAdapters()
 
         if (g_adapterHandler[index].startListenServer != NULL)
         {
-            g_adapterHandler[index].startListenServer();
+            const CAResult_t tmp =
+                g_adapterHandler[index].startListenServer();
+
+            // Successful listen if at least one adapter started.
+            if (CA_STATUS_OK == tmp)
+            {
+                result = tmp;
+            }
         }
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT");
-    return CA_STATUS_OK;
+    return result;
 }
 
 CAResult_t CAStopListeningServerAdapters()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     u_arraylist_t *list = CAGetSelectedNetworkList();
     if (!list)
     {
@@ -515,7 +527,8 @@ CAResult_t CAStopListeningServerAdapters()
         return CA_STATUS_FAILED;
     }
 
-    for (uint32_t i = 0; i < u_arraylist_length(list); i++)
+    size_t length = u_arraylist_length(list);
+    for (size_t i = 0; i < length; i++)
     {
         void* ptrType = u_arraylist_get(list, i);
         if(ptrType == NULL)
@@ -526,7 +539,7 @@ CAResult_t CAStopListeningServerAdapters()
         CATransportAdapter_t connType = *(CATransportAdapter_t *)ptrType;
 
         int index = CAGetAdapterIndex(connType);
-        if (index == -1)
+        if (0 > index)
         {
             OIC_LOG(ERROR, TAG, "unknown connectivity type!");
             continue;
@@ -538,23 +551,23 @@ CAResult_t CAStopListeningServerAdapters()
         }
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
 
 CAResult_t CAStartDiscoveryServerAdapters()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
+    CAResult_t result = CA_STATUS_FAILED;
 
     u_arraylist_t *list = CAGetSelectedNetworkList();
 
     if (!list)
     {
         OIC_LOG(ERROR, TAG, "No selected network");
-        return CA_STATUS_FAILED;
+        return result;
     }
 
-    for (uint32_t i = 0; i < u_arraylist_length(list); i++)
+    size_t length = u_arraylist_length(list);
+    for (size_t i = 0; i < length; i++)
     {
         void* ptrType = u_arraylist_get(list, i);
 
@@ -566,8 +579,7 @@ CAResult_t CAStartDiscoveryServerAdapters()
         CATransportAdapter_t connType = *(CATransportAdapter_t *)ptrType;
 
         int index = CAGetAdapterIndex(connType);
-
-        if (index == -1)
+        if (0 > index)
         {
             OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
             continue;
@@ -575,20 +587,23 @@ CAResult_t CAStartDiscoveryServerAdapters()
 
         if (g_adapterHandler[index].startDiscoveryServer != NULL)
         {
-            g_adapterHandler[index].startDiscoveryServer();
+            const CAResult_t tmp =
+                g_adapterHandler[index].startDiscoveryServer();
+
+            // Successful discovery if at least one adapter started.
+            if (CA_STATUS_OK == tmp)
+            {
+                result = tmp;
+            }
         }
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT");
-    return CA_STATUS_OK;
+    return result;
 }
 
 void CATerminateAdapters()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
-    uint32_t index;
-    for (index = 0; index < CA_TRANSPORT_TYPE_NUM; index++)
+    for (uint32_t index = 0; index < g_numberOfAdapters; index++)
     {
         if (g_adapterHandler[index].terminate != NULL)
         {
@@ -596,13 +611,14 @@ void CATerminateAdapters()
         }
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT");
+    OICFree(g_adapterHandler);
+    g_adapterHandler = NULL;
+    g_numberOfAdapters = 0;
 }
 
 #ifdef SINGLE_THREAD
 CAResult_t CAReadData()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
     u_arraylist_t *list = CAGetSelectedNetworkList();
 
     if (!list)
@@ -623,8 +639,7 @@ CAResult_t CAReadData()
         CATransportAdapter_t connType = *(CATransportAdapter_t *) ptrType;
 
         int index = CAGetAdapterIndex(connType);
-
-        if (-1 == index)
+        if (0 > index)
         {
             OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
             continue;
@@ -636,7 +651,6 @@ CAResult_t CAReadData()
         }
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
 #endif
index e007d87..e2eb295 100644 (file)
@@ -56,9 +56,9 @@ static CAQueueingThread_t g_receiveThread;
 
 #else
 #define CA_MAX_RT_ARRAY_SIZE    3
-#endif  /* SINGLE_THREAD */
+#endif  // SINGLE_THREAD
 
-#define TAG "CA_MSG_HNDLR"
+#define TAG "OIC_CA_MSG_HANDLE"
 
 static CARetransmission_t g_retransmissionContext;
 
@@ -66,6 +66,7 @@ static CARetransmission_t g_retransmissionContext;
 static CARequestCallback g_requestHandler = NULL;
 static CAResponseCallback g_responseHandler = NULL;
 static CAErrorCallback g_errorHandler = NULL;
+static CANetworkMonitorCallback g_nwMonitorHandler = NULL;
 
 static void CAErrorHandler(const CAEndpoint_t *endpoint,
                            const void *data, uint32_t dataLen,
@@ -243,9 +244,8 @@ static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
     cadata->remoteEndpoint = ep;
     cadata->dataType = dataType;
 
-    return cadata;
-
     OIC_LOG(DEBUG, TAG, "CAGenerateHandlerData OUT");
+    return cadata;
 }
 
 static void CATimeoutCallback(const CAEndpoint_t *endpoint, const void *pdu, uint32_t size)
@@ -376,16 +376,13 @@ static void CAProcessReceivedData(CAData_t *data)
         g_errorHandler(rep, data->errorInfo);
     }
 
-#ifdef SINGLE_THREAD
     CADestroyData(data, sizeof(CAData_t));
-#endif
 
     OIC_LOG(DEBUG, TAG, "CAProcessReceivedData OUT");
 }
 #endif
 
 #ifndef SINGLE_THREAD
-
 static void CAReceiveThreadProcess(void *threadData)
 {
 #ifndef SINGLE_HANDLE
@@ -395,7 +392,108 @@ static void CAReceiveThreadProcess(void *threadData)
     (void)threadData;
 #endif
 }
-#endif
+#endif // SINGLE_THREAD
+
+static CAResult_t CAProcessMulticastData(const CAData_t *data)
+{
+    VERIFY_NON_NULL(data, TAG, "data");
+    VERIFY_NON_NULL(data->remoteEndpoint, TAG, "remoteEndpoint");
+
+    coap_pdu_t *pdu = NULL;
+    CAInfo_t *info = NULL;
+    coap_list_t *options = NULL;
+    coap_transport_type transport;
+    CAResult_t res = CA_SEND_FAILED;
+    if (NULL != data->requestInfo)
+    {
+        OIC_LOG(DEBUG, TAG, "requestInfo is available..");
+
+        info = &data->requestInfo->info;
+        pdu = CAGeneratePDU(CA_GET, info, data->remoteEndpoint, &options, &transport);
+
+        if (NULL != pdu)
+        {
+#ifdef WITH_BWT
+            if (CAIsSupportedBlockwiseTransfer(data->remoteEndpoint->adapter))
+            {
+                // Blockwise transfer
+                res = CAAddBlockOption(&pdu, info, data->remoteEndpoint, &options);
+                if (CA_STATUS_OK != res)
+                {
+                    OIC_LOG(DEBUG, TAG, "CAAddBlockOption has failed");
+                    goto exit;
+                }
+            }
+#endif // WITH_BWT
+        }
+        else
+        {
+            OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
+            CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
+            return res;
+        }
+    }
+    else if (NULL != data->responseInfo)
+    {
+        OIC_LOG(DEBUG, TAG, "responseInfo is available..");
+
+        info = &data->responseInfo->info;
+        pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
+                            &options, &transport);
+
+        if (NULL != pdu)
+        {
+#ifdef WITH_BWT
+            if (CAIsSupportedBlockwiseTransfer(data->remoteEndpoint->adapter))
+            {
+                // Blockwise transfer
+                if (NULL != info)
+                {
+                    res = CAAddBlockOption(&pdu, info, data->remoteEndpoint, &options);
+                    if (CA_STATUS_OK != res)
+                    {
+                        OIC_LOG(INFO, TAG, "to write block option has failed");
+                        goto exit;
+                    }
+                }
+            }
+#endif // WITH_BWT
+        }
+        else
+        {
+            OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
+            CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
+            return res;
+        }
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "request or response info is empty");
+        return res;
+    }
+
+    CALogPDUInfo(pdu, data->remoteEndpoint);
+
+    OIC_LOG(DEBUG, TAG, "pdu to send :");
+    OIC_LOG_BUFFER(DEBUG, TAG,  (uint8_t*)pdu->hdr, pdu->length);
+
+    res = CASendMulticastData(data->remoteEndpoint, pdu->hdr, pdu->length);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
+        goto exit;
+    }
+
+    coap_delete_list(options);
+    coap_delete_pdu(pdu);
+    return res;
+
+exit:
+    CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
+    coap_delete_list(options);
+    coap_delete_pdu(pdu);
+    return res;
+}
 
 static CAResult_t CAProcessSendData(const CAData_t *data)
 {
@@ -454,11 +552,7 @@ static CAResult_t CAProcessSendData(const CAData_t *data)
         if (NULL != pdu)
         {
 #ifdef WITH_BWT
-            if (CA_ADAPTER_GATT_BTLE != data->remoteEndpoint->adapter
-#ifdef TCP_ADAPTER
-                    && CA_ADAPTER_TCP != data->remoteEndpoint->adapter
-#endif
-                    )
+            if (CAIsSupportedBlockwiseTransfer(data->remoteEndpoint->adapter))
             {
                 // Blockwise transfer
                 if (NULL != info)
@@ -476,7 +570,7 @@ static CAResult_t CAProcessSendData(const CAData_t *data)
                     }
                 }
             }
-#endif
+#endif // WITH_BWT
             CALogPDUInfo(pdu, data->remoteEndpoint);
 
             res = CASendUnicastData(data->remoteEndpoint, pdu->hdr, pdu->length);
@@ -489,8 +583,8 @@ static CAResult_t CAProcessSendData(const CAData_t *data)
                 return res;
             }
 
-#ifdef TCP_ADAPTER
-            if (CA_ADAPTER_TCP == data->remoteEndpoint->adapter)
+#ifdef WITH_TCP
+            if (CAIsSupportedCoAPOverTCP(data->remoteEndpoint->adapter))
             {
                 OIC_LOG(INFO, TAG, "retransmission will be not worked");
             }
@@ -526,109 +620,36 @@ static CAResult_t CAProcessSendData(const CAData_t *data)
     else if (SEND_TYPE_MULTICAST == type)
     {
         OIC_LOG(DEBUG,TAG,"Multicast message");
-        if (NULL != data->requestInfo)
-        {
-            OIC_LOG(DEBUG, TAG, "requestInfo is available..");
-
-            info = &data->requestInfo->info;
-            pdu = CAGeneratePDU(CA_GET, info, data->remoteEndpoint, &options, &transport);
-
-            if (NULL != pdu)
-            {
-#ifdef WITH_BWT
-                if (CA_ADAPTER_GATT_BTLE != data->remoteEndpoint->adapter
-#ifdef TCP_ADAPTER
-                        && CA_ADAPTER_TCP != data->remoteEndpoint->adapter
-#endif
-                        )
-                {
-                    // Blockwise transfer
-                    CAResult_t res = CAAddBlockOption(&pdu, &data->requestInfo->info,
-                                                      data->remoteEndpoint,
-                                                      &options);
-                    if (CA_STATUS_OK != res)
-                    {
-                        OIC_LOG(DEBUG, TAG, "CAAddBlockOption has failed");
-                        CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
-                        coap_delete_list(options);
-                        coap_delete_pdu(pdu);
-                        return res;
-                    }
-                }
-#endif
-            }
-            else
-            {
-                OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
-                CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
-                return CA_SEND_FAILED;
-            }
-        }
-        else if (NULL != data->responseInfo)
+#ifdef WITH_TCP
+        /*
+         * If CoAP over TCP is enabled, the CoAP pdu wont be same for IP and other adapters.
+         * That's why we need to generate two pdu's, one for IP and second for other transports.
+         * Two possible cases we might have to split: a) when adapter is CA_DEFAULT_ADAPTER
+         * b) when one of the adapter is IP adapter(ex: CA_ADAPTER_IP | CA_ADAPTER_GATT_BTLE)
+         */
+        if (data->remoteEndpoint->adapter == CA_DEFAULT_ADAPTER ||
+                (CA_ADAPTER_IP & data->remoteEndpoint->adapter &&
+                    CA_ADAPTER_IP != data->remoteEndpoint->adapter))
         {
-            OIC_LOG(DEBUG, TAG, "responseInfo is available..");
-
-            info = &data->responseInfo->info;
-            pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
-                                &options, &transport);
-
-            if (NULL != pdu)
+            if (data->remoteEndpoint->adapter == CA_DEFAULT_ADAPTER)
             {
-#ifdef WITH_BWT
-                if (CA_ADAPTER_GATT_BTLE != data->remoteEndpoint->adapter
-#ifdef TCP_ADAPTER
-                        && CA_ADAPTER_TCP != data->remoteEndpoint->adapter
-#endif
-                        )
-                {
-                    // Blockwise transfer
-                    if (NULL != info)
-                    {
-                        CAResult_t res = CAAddBlockOption(&pdu, info,
-                                                          data->remoteEndpoint,
-                                                          &options);
-                        if (CA_STATUS_OK != res)
-                        {
-                            OIC_LOG(INFO, TAG, "to write block option has failed");
-                            CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
-                            coap_delete_list(options);
-                            coap_delete_pdu(pdu);
-                            return res;
-                        }
-                    }
-                }
-#endif
+                data->remoteEndpoint->adapter = CA_ALL_ADAPTERS ^ CA_ADAPTER_IP;
             }
             else
             {
-                OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
-                CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
-                return CA_SEND_FAILED;
+                data->remoteEndpoint->adapter = data->remoteEndpoint->adapter ^ CA_ADAPTER_IP;
             }
+            CAProcessMulticastData(data);
+            data->remoteEndpoint->adapter = CA_ADAPTER_IP;
+            CAProcessMulticastData(data);
         }
         else
         {
-            OIC_LOG(ERROR, TAG, "request or response info is empty");
-            return CA_SEND_FAILED;
-        }
-
-        CALogPDUInfo(pdu, data->remoteEndpoint);
-
-        OIC_LOG(DEBUG, TAG, "pdu to send :");
-        OIC_LOG_BUFFER(DEBUG, TAG,  pdu->hdr, pdu->length);
-
-        res = CASendMulticastData(data->remoteEndpoint, pdu->hdr, pdu->length);
-        if (CA_STATUS_OK != res)
-        {
-            OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
-            CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
-            coap_delete_list(options);
-            coap_delete_pdu(pdu);
-            return res;
+            CAProcessMulticastData(data);
         }
-
-        coap_delete_list(options);
-        coap_delete_pdu(pdu);
+#else
+        CAProcessMulticastData(data);
+#endif
     }
 
     return CA_STATUS_OK;
@@ -640,7 +661,6 @@ static void CASendThreadProcess(void *threadData)
     CAData_t *data = (CAData_t *) threadData;
     CAProcessSendData(data);
 }
-
 #endif
 
 /*
@@ -684,7 +704,7 @@ static bool CADropSecondMessage(CAHistory_t *history, const CAEndpoint_t *ep, ui
             if ((familyFlags ^ item->flags) == CA_IPFAMILY_MASK)
             {
                 OIC_LOG_V(INFO, TAG, "IPv%c duplicate message ignored",
-                                            familyFlags & CA_IPV6 ? '6' : '4');
+                          familyFlags & CA_IPV6 ? '6' : '4');
                 ret = true;
                 break;
             }
@@ -748,8 +768,8 @@ static void CAReceivedPacketCallback(const CASecureEndpoint_t *sep,
             return;
         }
 
-#ifdef TCP_ADAPTER
-        if (CA_ADAPTER_TCP == sep->endpoint.adapter)
+#ifdef WITH_TCP
+        if (CAIsSupportedCoAPOverTCP(sep->endpoint.adapter))
         {
             OIC_LOG(INFO, TAG, "retransmission is not supported");
         }
@@ -787,14 +807,10 @@ static void CAReceivedPacketCallback(const CASecureEndpoint_t *sep,
     CAProcessReceivedData(cadata);
 #else
 #ifdef WITH_BWT
-    if (CA_ADAPTER_GATT_BTLE != sep->endpoint.adapter
-#ifdef TCP_ADAPTER
-            && CA_ADAPTER_TCP != sep->endpoint.adapter
-#endif
-            )
+    if (CAIsSupportedBlockwiseTransfer(sep->endpoint.adapter))
     {
         CAResult_t res = CAReceiveBlockWiseData(pdu, &(sep->endpoint), cadata, dataLen);
-        if (CA_NOT_SUPPORTED == res)
+        if (CA_NOT_SUPPORTED == res || CA_REQUEST_TIMEOUT == res)
         {
             OIC_LOG(ERROR, TAG, "this message does not have block option");
             CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
@@ -809,7 +825,7 @@ static void CAReceivedPacketCallback(const CASecureEndpoint_t *sep,
     {
         CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
     }
-#endif
+#endif // SINGLE_THREAD
 
     coap_delete_pdu(pdu);
 }
@@ -818,9 +834,11 @@ static void CANetworkChangedCallback(const CAEndpoint_t *info, CANetworkStatus_t
 {
     (void)info;
     (void)status;
-    OIC_LOG(DEBUG, TAG, "IN");
 
-    OIC_LOG(DEBUG, TAG, "OUT");
+    if (g_nwMonitorHandler)
+    {
+        g_nwMonitorHandler(info, status);
+    }
 }
 
 void CAHandleRequestResponseCallbacks()
@@ -840,21 +858,13 @@ void CAHandleRequestResponseCallbacks()
 
     ca_mutex_unlock(g_receiveThread.threadMutex);
 
-    if (NULL == item)
-    {
-        return;
-    }
-
-    // get values
-    void *msg = item->msg;
-
-    if (NULL == msg)
+    if (NULL == item || NULL == item->msg)
     {
         return;
     }
 
     // get endpoint
-    CAData_t *td = (CAData_t *) msg;
+    CAData_t *td = (CAData_t *) item->msg;
 
     if (td->requestInfo && g_requestHandler)
     {
@@ -872,11 +882,11 @@ void CAHandleRequestResponseCallbacks()
         g_errorHandler(td->remoteEndpoint, td->errorInfo);
     }
 
-    CADestroyData(msg, sizeof(CAData_t));
+    CADestroyData(item->msg, sizeof(CAData_t));
     OICFree(item);
 
-#endif /* SINGLE_HANDLE */
-#endif
+#endif // SINGLE_HANDLE
+#endif // SINGLE_THREAD
 }
 
 static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sendData,
@@ -899,8 +909,7 @@ static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sen
         if(!request)
         {
             OIC_LOG(ERROR, TAG, "CACloneRequestInfo failed");
-            OICFree(cadata);
-            return NULL;
+            goto exit;
         }
 
         cadata->type = request->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
@@ -914,8 +923,7 @@ static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sen
         if(!response)
         {
             OIC_LOG(ERROR, TAG, "CACloneResponseInfo failed");
-            OICFree(cadata);
-            return NULL;
+            goto exit;
         }
 
         cadata->type = response->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
@@ -924,8 +932,7 @@ static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sen
     else
     {
         OIC_LOG(ERROR, TAG, "CAPrepareSendData unknown data type");
-        OICFree(cadata);
-        return NULL;
+        goto exit;
     }
 
     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
@@ -939,12 +946,17 @@ static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sen
     cadata->remoteEndpoint = ep;
     cadata->dataType = dataType;
     return cadata;
+
+exit:
+    OICFree(cadata);
+    return NULL;
 }
 
-CAResult_t CADetachRequestMessage(const CAEndpoint_t *object, const CARequestInfo_t *request)
+CAResult_t CADetachSendMessage(const CAEndpoint_t *endpoint, const void *sendMsg,
+                               CADataType_t dataType)
 {
-    VERIFY_NON_NULL(object, TAG, "object");
-    VERIFY_NON_NULL(request, TAG, "request");
+    VERIFY_NON_NULL(endpoint, TAG, "endpoint");
+    VERIFY_NON_NULL(sendMsg, TAG, "sendMsg");
 
     if (false == CAIsSelectedNetworkAvailable())
     {
@@ -958,9 +970,9 @@ CAResult_t CADetachRequestMessage(const CAEndpoint_t *object, const CARequestInf
         OIC_LOG(ERROR, TAG, "max RT queue size reached!");
         return CA_SEND_FAILED;
     }
-#endif /* ARDUINO */
+#endif // ARDUINO
 
-    CAData_t *data = CAPrepareSendData(object, request, CA_REQUEST_DATA);
+    CAData_t *data = CAPrepareSendData(endpoint, sendMsg, dataType);
     if(!data)
     {
         OIC_LOG(ERROR, TAG, "CAPrepareSendData failed");
@@ -972,76 +984,14 @@ CAResult_t CADetachRequestMessage(const CAEndpoint_t *object, const CARequestInf
     if(CA_STATUS_OK != result)
     {
         OIC_LOG(ERROR, TAG, "CAProcessSendData failed");
+        CADestroyData(data, sizeof(CAData_t));
         return result;
     }
 
     CADestroyData(data, sizeof(CAData_t));
 #else
 #ifdef WITH_BWT
-    if (CA_ADAPTER_GATT_BTLE != object->adapter
-#ifdef TCP_ADAPTER
-            && CA_ADAPTER_TCP != object->adapter
-#endif
-            )
-    {
-        // send block data
-        CAResult_t res = CASendBlockWiseData(data);
-        if(CA_NOT_SUPPORTED == res)
-        {
-            OIC_LOG(DEBUG, TAG, "normal msg will be sent");
-            CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
-            return CA_STATUS_OK;
-        }
-        else
-        {
-            CADestroyData(data, sizeof(CAData_t));
-        }
-        return res;
-    }
-    else
-#endif
-    {
-        CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
-    }
-#endif
-
-    return CA_STATUS_OK;
-}
-
-CAResult_t CADetachResponseMessage(const CAEndpoint_t *object,
-                                   const CAResponseInfo_t *response)
-{
-    VERIFY_NON_NULL(object, TAG, "object");
-    VERIFY_NON_NULL(response, TAG, "response");
-
-    if (false == CAIsSelectedNetworkAvailable())
-    {
-        return CA_STATUS_FAILED;
-    }
-
-    CAData_t *data = CAPrepareSendData(object, response, CA_RESPONSE_DATA);
-    if(!data)
-    {
-        OIC_LOG(ERROR, TAG, "CAPrepareSendData failed");
-        return CA_MEMORY_ALLOC_FAILED;
-    }
-
-#ifdef SINGLE_THREAD
-    CAResult_t result = CAProcessSendData(data);
-    if(result != CA_STATUS_OK)
-    {
-        OIC_LOG(ERROR, TAG, "CAProcessSendData failed");
-        return result;
-    }
-
-    CADestroyData(data, sizeof(CAData_t));
-#else
-#ifdef WITH_BWT
-    if (CA_ADAPTER_GATT_BTLE != object->adapter
-#ifdef TCP_ADAPTER
-            && CA_ADAPTER_TCP != object->adapter
-#endif
-            )
+    if (CAIsSupportedBlockwiseTransfer(endpoint->adapter))
     {
         // send block data
         CAResult_t res = CASendBlockWiseData(data);
@@ -1058,27 +1008,15 @@ CAResult_t CADetachResponseMessage(const CAEndpoint_t *object,
         return res;
     }
     else
-#endif
+#endif // WITH_BWT
     {
         CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
     }
-#endif
+#endif // SINGLE_THREAD
 
     return CA_STATUS_OK;
 }
 
-CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t token,
-                                      uint8_t tokenLength, const CAHeaderOption_t *options,
-                                      uint8_t numOptions)
-{
-    (void)resourceUri;
-    (void)token;
-    (void)tokenLength;
-    (void)options;
-    (void)numOptions;
-    return CA_NOT_SUPPORTED;
-}
-
 void CASetInterfaceCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler,
                              CAErrorCallback errorHandler)
 {
@@ -1087,6 +1025,11 @@ void CASetInterfaceCallbacks(CARequestCallback ReqHandler, CAResponseCallback Re
     g_errorHandler = errorHandler;
 }
 
+void CASetNetworkMonitorCallback(CANetworkMonitorCallback nwMonitorHandler)
+{
+    g_nwMonitorHandler = nwMonitorHandler;
+}
+
 CAResult_t CAInitializeMessageHandler()
 {
     CASetPacketReceivedCallback(CAReceivedPacketCallback);
@@ -1097,7 +1040,6 @@ CAResult_t CAInitializeMessageHandler()
 #ifndef SINGLE_THREAD
     // create thread pool
     CAResult_t res = ca_thread_pool_init(MAX_THREAD_POOL_SIZE, &g_threadPoolHandle);
-
     if (CA_STATUS_OK != res)
     {
         OIC_LOG(ERROR, TAG, "thread pool initialize error.");
@@ -1105,58 +1047,91 @@ CAResult_t CAInitializeMessageHandler()
     }
 
     // send thread initialize
-    if (CA_STATUS_OK != CAQueueingThreadInitialize(&g_sendThread, g_threadPoolHandle,
-                                                   CASendThreadProcess, CADestroyData))
+    res = CAQueueingThreadInitialize(&g_sendThread, g_threadPoolHandle,
+                                     CASendThreadProcess, CADestroyData);
+    if (CA_STATUS_OK != res)
     {
         OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
-        return CA_STATUS_FAILED;
+        ca_thread_pool_free(g_threadPoolHandle);
+        g_threadPoolHandle = NULL;
+        return res;
     }
 
     // start send thread
     res = CAQueueingThreadStart(&g_sendThread);
-
     if (CA_STATUS_OK != res)
     {
         OIC_LOG(ERROR, TAG, "thread start error(send thread).");
         ca_thread_pool_free(g_threadPoolHandle);
         g_threadPoolHandle = NULL;
+        CAQueueingThreadDestroy(&g_sendThread);
         return res;
     }
 
     // receive thread initialize
-    if (CA_STATUS_OK != CAQueueingThreadInitialize(&g_receiveThread, g_threadPoolHandle,
-                                                   CAReceiveThreadProcess, CADestroyData))
+    res = CAQueueingThreadInitialize(&g_receiveThread, g_threadPoolHandle,
+                                     CAReceiveThreadProcess, CADestroyData);
+    if (CA_STATUS_OK != res)
     {
         OIC_LOG(ERROR, TAG, "Failed to Initialize receive queue thread");
-        return CA_STATUS_FAILED;
+        ca_thread_pool_free(g_threadPoolHandle);
+        g_threadPoolHandle = NULL;
+        CAQueueingThreadDestroy(&g_sendThread);
+        return res;
     }
 
 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
     // start receive thread
-    res = CAQueueingThreadStart(&gReceiveThread);
-
-    if (res != CA_STATUS_OK)
+    res = CAQueueingThreadStart(&g_receiveThread);
+    if (CA_STATUS_OK != res)
     {
         OIC_LOG(ERROR, TAG, "thread start error(receive thread).");
+        ca_thread_pool_free(g_threadPoolHandle);
+        g_threadPoolHandle = NULL;
+        CAQueueingThreadDestroy(&g_sendThread);
+        CAQueueingThreadDestroy(&g_receiveThread);
         return res;
     }
-#endif /* SINGLE_HANDLE */
+#endif // SINGLE_HANDLE
 
     // retransmission initialize
-    CARetransmissionInitialize(&g_retransmissionContext, g_threadPoolHandle, CASendUnicastData,
-                               CATimeoutCallback, NULL);
+    res = CARetransmissionInitialize(&g_retransmissionContext, g_threadPoolHandle,
+                                     CASendUnicastData, CATimeoutCallback, NULL);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
+        ca_thread_pool_free(g_threadPoolHandle);
+        g_threadPoolHandle = NULL;
+        CAQueueingThreadDestroy(&g_sendThread);
+        CAQueueingThreadDestroy(&g_receiveThread);
+        return res;
+    }
 
 #ifdef WITH_BWT
     // block-wise transfer initialize
-    CAInitializeBlockWiseTransfer(CAAddDataToSendThread, CAAddDataToReceiveThread);
+    res = CAInitializeBlockWiseTransfer(CAAddDataToSendThread, CAAddDataToReceiveThread);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to Initialize BlockWiseTransfer.");
+        ca_thread_pool_free(g_threadPoolHandle);
+        g_threadPoolHandle = NULL;
+        CAQueueingThreadDestroy(&g_sendThread);
+        CAQueueingThreadDestroy(&g_receiveThread);
+        CARetransmissionDestroy(&g_retransmissionContext);
+        return res;
+    }
 #endif
 
     // start retransmission
     res = CARetransmissionStart(&g_retransmissionContext);
-
     if (CA_STATUS_OK != res)
     {
         OIC_LOG(ERROR, TAG, "thread start error(retransmission thread).");
+        ca_thread_pool_free(g_threadPoolHandle);
+        g_threadPoolHandle = NULL;
+        CAQueueingThreadDestroy(&g_sendThread);
+        CAQueueingThreadDestroy(&g_receiveThread);
+        CARetransmissionDestroy(&g_retransmissionContext);
         return res;
     }
 
@@ -1164,10 +1139,16 @@ CAResult_t CAInitializeMessageHandler()
     CAInitializeAdapters(g_threadPoolHandle);
 #else
     // retransmission initialize
-    CARetransmissionInitialize(&g_retransmissionContext, NULL, CASendUnicastData,
-                               CATimeoutCallback, NULL);
+    CAResult_t res = CARetransmissionInitialize(&g_retransmissionContext, NULL, CASendUnicastData,
+                                                CATimeoutCallback, NULL);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
+        return res;
+    }
+
     CAInitializeAdapters();
-#endif
+#endif // SINGLE_THREAD
 
     return CA_STATUS_OK;
 }
@@ -1211,8 +1192,8 @@ void CATerminateMessageHandler()
     if (NULL != g_receiveThread.threadMutex)
     {
 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
-        CAQueueingThreadStop(&gReceiveThread);
-#endif /* SINGLE_HANDLE */
+        CAQueueingThreadStop(&g_receiveThread);
+#endif
     }
 
     // destroy thread pool
@@ -1238,20 +1219,21 @@ void CATerminateMessageHandler()
     // stop retransmission
     CARetransmissionStop(&g_retransmissionContext);
     CARetransmissionDestroy(&g_retransmissionContext);
-#endif
+#endif // SINGLE_THREAD
 }
 
 void CALogPDUInfo(coap_pdu_t *pdu, const CAEndpoint_t *endpoint)
 {
     VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
+    VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
 
     OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
 
-#ifdef TCP_ADAPTER
-    if (CA_ADAPTER_TCP == endpoint->adapter)
+#ifdef WITH_TCP
+    if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
     {
         OIC_LOG(DEBUG, TAG, "pdu header data :");
-        OIC_LOG_BUFFER(DEBUG, TAG,  pdu->hdr, pdu->length);
+        OIC_LOG_BUFFER(DEBUG, TAG,  (const uint8_t *) pdu->hdr, pdu->length);
     }
     else
 #endif
@@ -1283,7 +1265,7 @@ static void CALogPayloadInfo(CAInfo_t *info)
 
         if (info->payload)
         {
-            OIC_LOG_V(DEBUG, TAG, "payload: %p(%u)", info->payload,
+            OIC_LOG_V(DEBUG, TAG, "payload: %p(%zu)", info->payload,
                       info->payloadSize);
         }
 
@@ -1308,7 +1290,6 @@ void CAErrorHandler(const CAEndpoint_t *endpoint,
     OIC_LOG(DEBUG, TAG, "CAErrorHandler IN");
 
 #ifndef SINGLE_THREAD
-
     VERIFY_NON_NULL_VOID(endpoint, TAG, "remoteEndpoint");
     VERIFY_NON_NULL_VOID(data, TAG, "data");
 
@@ -1347,7 +1328,7 @@ static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info,
     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
     if (!cadata)
     {
-        OIC_LOG(ERROR, TAG, "memory allocation failed");
+        OIC_LOG(ERROR, TAG, "cadata memory allocation failed");
         return;
     }
 
@@ -1362,6 +1343,7 @@ static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info,
     CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
     if (!errorInfo)
     {
+        OIC_LOG(ERROR, TAG, "errorInfo memory allocation failed");
         OICFree(cadata);
         CAFreeEndpoint(ep);
         return;
@@ -1370,6 +1352,7 @@ static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info,
     CAResult_t res = CACloneInfo(info, &errorInfo->info);
     if (CA_STATUS_OK != res)
     {
+        OIC_LOG(ERROR, TAG, "info clone failed");
         OICFree(cadata);
         OICFree(errorInfo);
         CAFreeEndpoint(ep);
index d1d1e5c..1db90e8 100644 (file)
 #include "uarraylist.h"
 #include "logger.h"
 
-#define TAG "CA_NW_CONFIG"
+#define TAG "OIC_CA_NW_CONFIG"
 
 static u_arraylist_t *g_selectedNetworkList = NULL;
-static uint32_t NETWORK_IP = CA_ADAPTER_IP;
+
+#ifdef EDR_ADAPTER
 static uint32_t NETWORK_RFCOMM = CA_ADAPTER_RFCOMM_BTEDR;
+#endif
+
+#ifdef LE_ADAPTER
 static uint32_t NETWORK_GATT = CA_ADAPTER_GATT_BTLE;
+#endif
+
+#ifdef IP_ADAPTER
+static uint32_t NETWORK_IP = CA_ADAPTER_IP;
+#endif
+
+#ifdef NFC_ADAPTER
+static uint32_t NETWORK_NFC = CA_ADAPTER_NFC;
+#endif
 
 #ifdef RA_ADAPTER
 static uint32_t NETWORK_RA = CA_ADAPTER_REMOTE_ACCESS;
@@ -42,7 +55,6 @@ static uint32_t NETWORK_TCP = CA_ADAPTER_TCP;
 
 CAResult_t CAAddNetworkType(CATransportAdapter_t transportType)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
     if (NULL == g_selectedNetworkList)
     {
         OIC_LOG(DEBUG, TAG, "Create network list");
@@ -61,7 +73,7 @@ CAResult_t CAAddNetworkType(CATransportAdapter_t transportType)
 #ifndef IP_ADAPTER
             OIC_LOG(DEBUG, TAG, "Add network type(IP) - Not Supported");
             return CA_NOT_SUPPORTED;
-#endif /* IP_ADAPTER */
+#else
 
             OIC_LOG(DEBUG, TAG, "Add network type(IP)");
             if (u_arraylist_contains(g_selectedNetworkList, &NETWORK_IP))
@@ -69,13 +81,15 @@ CAResult_t CAAddNetworkType(CATransportAdapter_t transportType)
                 goto exit;
             }
             res = u_arraylist_add(g_selectedNetworkList, &NETWORK_IP);
+
             break;
+#endif // IP_ADAPTER
 
         case CA_ADAPTER_RFCOMM_BTEDR:
 #ifndef EDR_ADAPTER
             OIC_LOG(DEBUG, TAG, "Add network type(EDR) - Not Supported");
             return CA_NOT_SUPPORTED;
-#endif /* EDR_ADAPTER */
+#else
 
             OIC_LOG(DEBUG, TAG, "Add network type(EDR)");
             if (u_arraylist_contains(g_selectedNetworkList, &NETWORK_RFCOMM))
@@ -83,13 +97,15 @@ CAResult_t CAAddNetworkType(CATransportAdapter_t transportType)
                 goto exit;
             }
             res = u_arraylist_add(g_selectedNetworkList, &NETWORK_RFCOMM);
+
             break;
+#endif // EDR_ADAPTER
 
         case CA_ADAPTER_GATT_BTLE:
 #ifndef LE_ADAPTER
             OIC_LOG(DEBUG, TAG, "Add network type(LE) - Not Supported");
             return CA_NOT_SUPPORTED;
-#endif /* LE_ADAPTER */
+#else
 
             OIC_LOG(DEBUG, TAG, "Add network type(LE)");
             if (u_arraylist_contains(g_selectedNetworkList, &NETWORK_GATT))
@@ -97,7 +113,9 @@ CAResult_t CAAddNetworkType(CATransportAdapter_t transportType)
                 goto exit;
             }
             res = u_arraylist_add(g_selectedNetworkList, &NETWORK_GATT);
+
             break;
+#endif // LE_ADAPTER
 
 #ifdef RA_ADAPTER
         case CA_ADAPTER_REMOTE_ACCESS:
@@ -109,7 +127,7 @@ CAResult_t CAAddNetworkType(CATransportAdapter_t transportType)
            }
            res = u_arraylist_add(g_selectedNetworkList, &NETWORK_RA);
            break;
-#endif /* RA_ADAPTER */
+#endif // RA_ADAPTER
 
 #ifdef TCP_ADAPTER
         case CA_ADAPTER_TCP:
@@ -121,7 +139,24 @@ CAResult_t CAAddNetworkType(CATransportAdapter_t transportType)
            }
            res = u_arraylist_add(g_selectedNetworkList, &NETWORK_TCP);
            break;
-#endif /* TCP_ADAPTER */
+#endif // TCP_ADAPTER
+
+
+        case CA_ADAPTER_NFC:
+ #ifndef NFC_ADAPTER
+            OIC_LOG(DEBUG, TAG, "Add network type(NFC) - Not Supported");
+            return CA_NOT_SUPPORTED;
+
+#else
+           OIC_LOG(DEBUG, TAG, "Add network type(NFC)");
+           if (u_arraylist_contains(g_selectedNetworkList, &NETWORK_NFC))
+           {
+               goto exit;
+           }
+           res = u_arraylist_add(g_selectedNetworkList, &NETWORK_NFC);
+
+           break;
+#endif // CA_ADAPTER_NFC
 
         default:
             break;
@@ -134,7 +169,6 @@ CAResult_t CAAddNetworkType(CATransportAdapter_t transportType)
     }
     // start selected interface adapter
     CAResult_t result = CAStartAdapter(transportType);
-    OIC_LOG(DEBUG, TAG, "OUT");
     return result;
 
 exit:
@@ -144,8 +178,6 @@ exit:
 
 CAResult_t CARemoveNetworkType(CATransportAdapter_t transportType)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     if (NULL == g_selectedNetworkList)
     {
         OIC_LOG(ERROR, TAG, "SelectedNetwork list is NULL");
@@ -176,8 +208,9 @@ CAResult_t CARemoveNetworkType(CATransportAdapter_t transportType)
 
                     OIC_LOG(DEBUG, TAG, "Remove network type(IP)");
                     u_arraylist_remove(g_selectedNetworkList, index);
-#endif /* IP_ADAPTER */
+
                     break;
+#endif //IP_ADAPTER
 
                 case CA_ADAPTER_RFCOMM_BTEDR:
 #ifndef EDR_ADAPTER
@@ -186,8 +219,9 @@ CAResult_t CARemoveNetworkType(CATransportAdapter_t transportType)
 #else
                     OIC_LOG(DEBUG, TAG, "Remove network type(EDR)");
                     u_arraylist_remove(g_selectedNetworkList, index);
-#endif /* EDR_ADAPTER */
+
                     break;
+#endif // EDR_ADAPTER
 
                 case CA_ADAPTER_GATT_BTLE:
 #ifndef LE_ADAPTER
@@ -196,23 +230,34 @@ CAResult_t CARemoveNetworkType(CATransportAdapter_t transportType)
 #else
                     OIC_LOG(DEBUG, TAG, "Remove network type(LE)");
                     u_arraylist_remove(g_selectedNetworkList, index);
-#endif /* LE_ADAPTER */
 
                     break;
+#endif // LE_ADAPTER
+
 #ifdef RA_ADAPTER
                 case CA_ADAPTER_REMOTE_ACCESS:
                     OIC_LOG(DEBUG, TAG, "Remove network type(RA)");
                     u_arraylist_remove(g_selectedNetworkList, index);
                     break;
-#endif /* RA_ADAPTER */
+#endif // RA_ADAPTER
 
 #ifdef TCP_ADAPTER
                 case CA_ADAPTER_TCP:
                     OIC_LOG(DEBUG, TAG, "Remove network type(TCP)");
                     u_arraylist_remove(g_selectedNetworkList, index);
                     break;
-#endif /* TCP_ADAPTER */
+#endif // TCP_ADAPTER
+
+#ifndef NFC_ADAPTER
+                case CA_ADAPTER_NFC:
+                    OIC_LOG(DEBUG, TAG, "Add network type(NFC) - Not Supported");
+                    return CA_NOT_SUPPORTED;
+#else
+                   OIC_LOG(DEBUG, TAG, "Add network type(NFC)");
+                   u_arraylist_remove(g_selectedNetworkList, index);
 
+                   break;
+#endif // CA_ADAPTER_NFC
                 default:
                     break;
             }
index 0cb8a18..5ef5a87 100644 (file)
 #include "oic_malloc.h"
 #include "oic_string.h"
 #include "ocrandom.h"
+#include "cacommonutil.h"
 
-#define TAG "CA_PRTCL_MSG"
-
-/**
- * @def VERIFY_NON_NULL_RET
- * @brief Macro to verify the validity of input argument
- */
-#define VERIFY_NON_NULL_RET(arg, log_tag, log_message,ret) \
-    if (NULL == arg ){ \
-        OIC_LOG_V(ERROR, log_tag, "Invalid input:%s", log_message); \
-        return ret; \
-    }
+#define TAG "OIC_CA_PRTCL_MSG"
 
 #define CA_BUFSIZE (128)
 #define CA_PDU_MIN_SIZE (4)
@@ -63,11 +54,8 @@ static const char COAP_URI_HEADER[] = "coap://[::]/";
 CAResult_t CAGetRequestInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
                                    CARequestInfo_t *outReqInfo)
 {
-    if (NULL == pdu || NULL == outReqInfo)
-    {
-        OIC_LOG(ERROR, TAG, "parameter is null");
-        return CA_STATUS_INVALID_PARAM;
-    }
+    VERIFY_NON_NULL(pdu, TAG, "pdu");
+    VERIFY_NON_NULL(outReqInfo, TAG, "outReqInfo");
 
     uint32_t code = CA_NOT_FOUND;
     CAResult_t ret = CAGetInfoFromPDU(pdu, endpoint, &code, &(outReqInfo->info));
@@ -79,11 +67,8 @@ CAResult_t CAGetRequestInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *en
 CAResult_t CAGetResponseInfoFromPDU(const coap_pdu_t *pdu, CAResponseInfo_t *outResInfo,
                                     const CAEndpoint_t *endpoint)
 {
-    if (NULL == pdu || NULL == outResInfo)
-    {
-        OIC_LOG(ERROR, TAG, "parameter is null");
-        return CA_STATUS_INVALID_PARAM;
-    }
+    VERIFY_NON_NULL(pdu, TAG, "pdu");
+    VERIFY_NON_NULL(outResInfo, TAG, "outResInfo");
 
     uint32_t code = CA_NOT_FOUND;
     CAResult_t ret = CAGetInfoFromPDU(pdu, endpoint, &code, &(outResInfo->info));
@@ -95,11 +80,7 @@ CAResult_t CAGetResponseInfoFromPDU(const coap_pdu_t *pdu, CAResponseInfo_t *out
 CAResult_t CAGetErrorInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
                                  CAErrorInfo_t *errorInfo)
 {
-    if (!pdu)
-    {
-        OIC_LOG(ERROR, TAG, "parameter is null");
-        return CA_STATUS_INVALID_PARAM;
-    }
+    VERIFY_NON_NULL(pdu, TAG, "pdu");
 
     uint32_t code = 0;
     CAResult_t ret = CAGetInfoFromPDU(pdu, endpoint, &code, &errorInfo->info);
@@ -120,8 +101,13 @@ coap_pdu_t *CAGeneratePDU(uint32_t code, const CAInfo_t *info, const CAEndpoint_
     // and ACKNOWLEDGE can use empty message when code is empty.
     if (CA_MSG_RESET == info->type || (CA_EMPTY == code && CA_MSG_ACKNOWLEDGE == info->type))
     {
-        if ((CA_EMPTY == code) && (info->payloadSize > 0 || info->payload
-            || info->token || info->tokenLength > 0))
+        if (CA_EMPTY != code)
+        {
+            OIC_LOG(ERROR, TAG, "reset is not empty message");
+            return NULL;
+        }
+
+        if (info->payloadSize > 0 || info->payload || info->token || info->tokenLength > 0)
         {
             OIC_LOG(ERROR, TAG, "Empty message has unnecessary data after messageID");
             return NULL;
@@ -187,15 +173,12 @@ coap_pdu_t *CAGeneratePDU(uint32_t code, const CAInfo_t *info, const CAEndpoint_
 coap_pdu_t *CAParsePDU(const char *data, uint32_t length, uint32_t *outCode,
                        const CAEndpoint_t *endpoint)
 {
-    if (NULL == data)
-    {
-        OIC_LOG(ERROR, TAG, "data is null");
-        return NULL;
-    }
+    VERIFY_NON_NULL_RET(data, TAG, "data", NULL);
+    VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", NULL);
 
     coap_transport_type transport;
-#ifdef TCP_ADAPTER
-    if (CA_ADAPTER_TCP == endpoint->adapter)
+#ifdef WITH_TCP
+    if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
     {
         transport = coap_get_tcp_header_type_from_initbyte(((unsigned char *)data)[0] >> 4);
     }
@@ -223,8 +206,8 @@ coap_pdu_t *CAParsePDU(const char *data, uint32_t length, uint32_t *outCode,
         return NULL;
     }
 
-#ifdef TCP_ADAPTER
-    if (CA_ADAPTER_TCP == endpoint->adapter)
+#ifdef WITH_TCP
+    if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
     {
         OIC_LOG(INFO, TAG, "there is no version info in coap header");
     }
@@ -264,9 +247,9 @@ coap_pdu_t *CAGeneratePDUImpl(code_t code, const CAInfo_t *info,
     VERIFY_NON_NULL_RET(transport, TAG, "transport", NULL);
 
     unsigned int length = COAP_MAX_PDU_SIZE;
-#ifdef TCP_ADAPTER
+#ifdef WITH_TCP
     unsigned int msgLength = 0;
-    if (CA_ADAPTER_TCP == endpoint->adapter)
+    if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
     {
         if (options)
         {
@@ -289,8 +272,8 @@ coap_pdu_t *CAGeneratePDUImpl(code_t code, const CAInfo_t *info,
                 }
                 msgLength += optLength;
                 prevOptNumber = curOptNumber;
-                OIC_LOG_V(DEBUG, TAG, "curOptNumber[%d], prevOptNumber[%d], optValueLen[%d], "
-                        "optLength[%d], msgLength[%d]",
+                OIC_LOG_V(DEBUG, TAG, "curOptNumber[%d], prevOptNumber[%d], optValueLen[%zu], "
+                        "optLength[%zu], msgLength[%d]",
                           curOptNumber, prevOptNumber, optValueLen, optLength, msgLength);
             }
         }
@@ -317,11 +300,11 @@ coap_pdu_t *CAGeneratePDUImpl(code_t code, const CAInfo_t *info,
         return NULL;
     }
 
-    OIC_LOG_V(DEBUG, TAG, "transport type: %d, payload size: %d",
+    OIC_LOG_V(DEBUG, TAG, "transport type: %d, payload size: %zu",
               *transport, info->payloadSize);
 
-#ifdef TCP_ADAPTER
-    if (CA_ADAPTER_TCP == endpoint->adapter)
+#ifdef WITH_TCP
+    if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
     {
         coap_add_length(pdu, *transport, msgLength);
     }
@@ -365,8 +348,8 @@ coap_pdu_t *CAGeneratePDUImpl(code_t code, const CAInfo_t *info,
 
 #ifdef WITH_BWT
     if (CA_ADAPTER_GATT_BTLE != endpoint->adapter
-#ifdef TCP_ADAPTER
-            && CA_ADAPTER_TCP != endpoint->adapter
+#ifdef WITH_TCP
+            && !CAIsSupportedCoAPOverTCP(endpoint->adapter)
 #endif
             )
     {
@@ -402,20 +385,11 @@ coap_pdu_t *CAGeneratePDUImpl(code_t code, const CAInfo_t *info,
 
 CAResult_t CAParseURI(const char *uriInfo, coap_list_t **optlist)
 {
-    if (NULL == uriInfo)
-    {
-        OIC_LOG(ERROR, TAG, "uriInfo is null");
-        return CA_STATUS_INVALID_PARAM;
-    }
+    VERIFY_NON_NULL(uriInfo, TAG, "uriInfo");
+    VERIFY_NON_NULL(optlist, TAG, "optlist");
 
     OIC_LOG_V(DEBUG, TAG, "url : %s", uriInfo);
 
-    if (NULL == optlist)
-    {
-        OIC_LOG(ERROR, TAG, "optlist is null");
-        return CA_STATUS_INVALID_PARAM;
-    }
-
     /* split arg into Uri-* options */
     coap_uri_t uri;
     coap_split_uri((unsigned char *) uriInfo, strlen(uriInfo), &uri);
@@ -462,11 +436,7 @@ CAResult_t CAParseURI(const char *uriInfo, coap_list_t **optlist)
 CAResult_t CAParseUriPartial(const unsigned char *str, size_t length, int target,
                              coap_list_t **optlist)
 {
-    if (!optlist)
-    {
-        OIC_LOG(ERROR, TAG, "optlist is null");
-        return CA_STATUS_INVALID_PARAM;
-    }
+    VERIFY_NON_NULL(optlist, TAG, "optlist");
 
     if ((target != COAP_OPTION_URI_PATH) && (target != COAP_OPTION_URI_QUERY))
     {
@@ -522,7 +492,7 @@ CAResult_t CAParseUriPartial(const unsigned char *str, size_t length, int target
 CAResult_t CAParseHeadOption(uint32_t code, const CAInfo_t *info, coap_list_t **optlist)
 {
     (void)code;
-    VERIFY_NON_NULL_RET(info, TAG, "info is NULL", CA_STATUS_INVALID_PARAM);
+    VERIFY_NON_NULL_RET(info, TAG, "info", CA_STATUS_INVALID_PARAM);
 
     OIC_LOG_V(DEBUG, TAG, "parse Head Opt: %d", info->numOptions);
 
@@ -566,7 +536,8 @@ CAResult_t CAParseHeadOption(uint32_t code, const CAInfo_t *info, coap_list_t **
     {
         coap_list_t* node = NULL;
         uint8_t buf[3] = {0};
-        switch (info->payloadFormat) {
+        switch (info->payloadFormat)
+        {
             case CA_FORMAT_APPLICATION_CBOR:
                 node = CACreateNewOptionNode(
                         COAP_OPTION_CONTENT_FORMAT,
@@ -593,7 +564,8 @@ CAResult_t CAParseHeadOption(uint32_t code, const CAInfo_t *info, coap_list_t **
     {
         coap_list_t* node = NULL;
         uint8_t buf[3] = {0};
-        switch (info->acceptFormat) {
+        switch (info->acceptFormat)
+        {
             case CA_FORMAT_APPLICATION_CBOR:
                 node = CACreateNewOptionNode(
                         COAP_OPTION_ACCEPT,
@@ -622,11 +594,7 @@ CAResult_t CAParseHeadOption(uint32_t code, const CAInfo_t *info, coap_list_t **
 
 coap_list_t *CACreateNewOptionNode(uint16_t key, uint32_t length, const char *data)
 {
-    if (!data)
-    {
-        OIC_LOG(ERROR, TAG, "invalid pointer parameter");
-        return NULL;
-    }
+    VERIFY_NON_NULL_RET(data, TAG, "data", NULL);
 
     coap_option *option = coap_malloc(sizeof(coap_option) + length + 1);
     if (!option)
@@ -713,15 +681,14 @@ uint32_t CAGetOptionCount(coap_opt_iterator_t opt_iter)
 CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
                             uint32_t *outCode, CAInfo_t *outInfo)
 {
-    if (!pdu || !outCode || !outInfo)
-    {
-        OIC_LOG(ERROR, TAG, "NULL pointer param");
-        return CA_STATUS_INVALID_PARAM;
-    }
+    VERIFY_NON_NULL(pdu, TAG, "pdu");
+    VERIFY_NON_NULL(endpoint, TAG, "endpoint");
+    VERIFY_NON_NULL(outCode, TAG, "outCode");
+    VERIFY_NON_NULL(outInfo, TAG, "outInfo");
 
     coap_transport_type transport;
-#ifdef TCP_ADAPTER
-    if (CA_ADAPTER_TCP == endpoint->adapter)
+#ifdef WITH_TCP
+    if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
     {
         transport = coap_get_tcp_header_type_from_initbyte(((unsigned char *)pdu->hdr)[0] >> 4);
     }
@@ -745,14 +712,16 @@ CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
 
     outInfo->numOptions = count;
 
-#ifdef TCP_ADAPTER
-    if (CA_ADAPTER_TCP == endpoint->adapter)
+#ifdef WITH_TCP
+    if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
     {
         // set type
         outInfo->type = CA_MSG_NONCONFIRM;
         outInfo->payloadFormat = CA_FORMAT_UNDEFINED;
     }
     else
+#else
+    (void) endpoint;
 #endif
     {
         // set type
@@ -953,7 +922,7 @@ CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
 
     if (optionResult[0] != '\0')
     {
-        OIC_LOG_V(DEBUG, TAG, "URL length:%d", strlen(optionResult));
+        OIC_LOG_V(DEBUG, TAG, "URL length:%zu", strlen(optionResult));
         outInfo->resourceUri = OICStrdup(optionResult);
         if (!outInfo->resourceUri)
         {
@@ -975,21 +944,13 @@ exit:
 CAResult_t CAGetTokenFromPDU(const coap_hdr_t *pdu_hdr, CAInfo_t *outInfo,
                              const CAEndpoint_t *endpoint)
 {
-    if (NULL == pdu_hdr)
-    {
-        OIC_LOG(ERROR, TAG, "pdu_hdr is null");
-        return CA_STATUS_INVALID_PARAM;
-    }
-
-    if (NULL == outInfo)
-    {
-        OIC_LOG(ERROR, TAG, "outInfo is null");
-        return CA_STATUS_INVALID_PARAM;
-    }
+    VERIFY_NON_NULL(pdu_hdr, TAG, "pdu_hdr");
+    VERIFY_NON_NULL(outInfo, TAG, "outInfo");
+    VERIFY_NON_NULL(endpoint, TAG, "endpoint");
 
     coap_transport_type transport;
-#ifdef TCP_ADAPTER
-    if (CA_ADAPTER_TCP == endpoint->adapter)
+#ifdef WITH_TCP
+    if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
     {
         transport = coap_get_tcp_header_type_from_initbyte(((unsigned char *)pdu_hdr)[0] >> 4);
     }
@@ -1023,11 +984,7 @@ CAResult_t CAGetTokenFromPDU(const coap_hdr_t *pdu_hdr, CAInfo_t *outInfo,
 
 CAResult_t CAGenerateTokenInternal(CAToken_t *token, uint8_t tokenLength)
 {
-    if (!token)
-    {
-        OIC_LOG(ERROR, TAG, "invalid token pointer");
-        return CA_STATUS_INVALID_PARAM;
-    }
+    VERIFY_NON_NULL(token, TAG, "token");
 
     if ((tokenLength > CA_MAX_TOKEN_LEN) || (0 == tokenLength))
     {
@@ -1059,21 +1016,6 @@ void CADestroyTokenInternal(CAToken_t token)
     OICFree(token);
 }
 
-void CADestroyInfo(CAInfo_t *info)
-{
-    if (NULL != info)
-    {
-        OIC_LOG(DEBUG, TAG, "free options");
-        OICFree(info->options);
-
-        OIC_LOG(DEBUG, TAG, "free token");
-        OICFree(info->token);
-
-        OIC_LOG(DEBUG, TAG, "free payload");
-        OICFree(info->payload);
-    }
-}
-
 uint32_t CAGetOptionData(uint16_t key, const uint8_t *data, uint32_t len,
         uint8_t *option, uint32_t buflen)
 {
@@ -1090,7 +1032,8 @@ uint32_t CAGetOptionData(uint16_t key, const uint8_t *data, uint32_t len,
     }
 
     coap_option_def_t* def = coap_opt_def(key);
-    if(NULL != def && coap_is_var_bytes(def) && 0 == len) {
+    if (NULL != def && coap_is_var_bytes(def) && 0 == len)
+    {
         // A 0 length option is permitted in CoAP but the
         // rest or the stack is unaware of variable byte encoding
         // should remain that way so a 0 byte of length 1 is inserted.
@@ -1106,11 +1049,7 @@ uint32_t CAGetOptionData(uint16_t key, const uint8_t *data, uint32_t len,
 
 CAMessageType_t CAGetMessageTypeFromPduBinaryData(const void *pdu, uint32_t size)
 {
-    if (NULL == pdu)
-    {
-        OIC_LOG(ERROR, TAG, "pdu is null");
-        return CA_MSG_NONCONFIRM;
-    }
+    VERIFY_NON_NULL_RET(pdu, TAG, "pdu", CA_MSG_NONCONFIRM);
 
     // pdu minimum size is 4 byte.
     if (size < CA_PDU_MIN_SIZE)
@@ -1126,11 +1065,7 @@ CAMessageType_t CAGetMessageTypeFromPduBinaryData(const void *pdu, uint32_t size
 
 uint16_t CAGetMessageIdFromPduBinaryData(const void *pdu, uint32_t size)
 {
-    if (NULL == pdu)
-    {
-        OIC_LOG(ERROR, TAG, "pdu is null");
-        return 0;
-    }
+    VERIFY_NON_NULL_RET(pdu, TAG, "pdu", 0);
 
     // pdu minimum size is 4 byte.
     if (size < CA_PDU_MIN_SIZE)
@@ -1146,11 +1081,7 @@ uint16_t CAGetMessageIdFromPduBinaryData(const void *pdu, uint32_t size)
 
 CAResponseResult_t CAGetCodeFromPduBinaryData(const void *pdu, uint32_t size)
 {
-    if (NULL == pdu)
-    {
-        OIC_LOG(ERROR, TAG, "pdu is null");
-        return CA_NOT_FOUND;
-    }
+    VERIFY_NON_NULL_RET(pdu, TAG, "pdu", CA_NOT_FOUND);
 
     // pdu minimum size is 4 byte.
     if (size < CA_PDU_MIN_SIZE)
@@ -1188,3 +1119,27 @@ CAPayloadFormat_t CAConvertFormat(uint8_t format)
             return CA_FORMAT_UNSUPPORTED;
     }
 }
+
+#ifdef WITH_BWT
+bool CAIsSupportedBlockwiseTransfer(CATransportAdapter_t adapter)
+{
+    if (CA_ADAPTER_IP & adapter || CA_ADAPTER_NFC & adapter
+            || CA_DEFAULT_ADAPTER == adapter)
+    {
+        return true;
+    }
+    return false;
+}
+#endif
+
+#ifdef WITH_TCP
+bool CAIsSupportedCoAPOverTCP(CATransportAdapter_t adapter)
+{
+    if (CA_ADAPTER_GATT_BTLE & adapter || CA_ADAPTER_RFCOMM_BTEDR & adapter
+            || CA_ADAPTER_TCP & adapter || CA_DEFAULT_ADAPTER == adapter)
+    {
+        return true;
+    }
+    return false;
+}
+#endif
index 672198a..754b1c2 100644 (file)
@@ -28,7 +28,7 @@
 #include "oic_malloc.h"
 #include "logger.h"
 
-#define TAG PCF("CA_QING")
+#define TAG PCF("OIC_CA_QING")
 
 static void CAQueueingThreadBaseRoutine(void *threadValue)
 {
@@ -59,8 +59,6 @@ static void CAQueueingThreadBaseRoutine(void *threadValue)
             OIC_LOG(DEBUG, TAG, "wake up..");
         }
 
-
-
         // check stop flag
         if (thread->isStop)
         {
index 4f212c2..5fa8df9 100644 (file)
@@ -61,7 +61,7 @@
 #include "oic_malloc.h"
 #include "logger.h"
 
-#define TAG "CA_RETRANS"
+#define TAG "OIC_CA_RETRANS"
 
 typedef struct
 {
@@ -140,7 +140,7 @@ static bool CACheckTimeout(uint64_t currentTime, CARetransmissionData_t *retData
 
     if (currentTime >= retData->timeStamp + timeout)
     {
-        OIC_LOG_V(DEBUG, TAG, "%d microseconds time out!!, tried count(%ld)",
+        OIC_LOG_V(DEBUG, TAG, "%llu microseconds time out!!, tried count(%d)",
                   timeout, retData->triedCount);
         return true;
     }
@@ -274,7 +274,7 @@ void CARetransmissionBaseRoutine(void *threadValue)
         else if (!context->isStop)
         {
             // check each RETRANSMISSION_CHECK_PERIOD_SEC time.
-            OIC_LOG_V(DEBUG, TAG, "wait..(%ld)microseconds",
+            OIC_LOG_V(DEBUG, TAG, "wait..(%lld)microseconds",
                       RETRANSMISSION_CHECK_PERIOD_SEC * (uint64_t) USECS_PER_SEC);
 
             // wait
@@ -490,10 +490,13 @@ CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
     // ACK, RST --> remove the CON data
     CAMessageType_t type = CAGetMessageTypeFromPduBinaryData(pdu, size);
     uint16_t messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
+    CAResponseResult_t code = CAGetCodeFromPduBinaryData(pdu, size);
 
-    OIC_LOG_V(DEBUG, TAG, "received pdu, msgtype=%d, msgid=%d", type, messageId);
+    OIC_LOG_V(DEBUG, TAG, "received pdu, msgtype=%d, msgid=%d, code=%d",
+              type, messageId, code);
 
-    if ((CA_MSG_ACKNOWLEDGE != type) && (CA_MSG_RESET != type))
+    if (((CA_MSG_ACKNOWLEDGE != type) && (CA_MSG_RESET != type))
+        || (CA_MSG_RESET == type && CA_EMPTY != code))
     {
         return CA_STATUS_OK;
     }
@@ -634,7 +637,7 @@ uint64_t getCurrentTimeInMicroSeconds()
     clock_gettime(CLOCK_MONOTONIC, &getTs);
 
     currentTime = (getTs.tv_sec * (uint64_t)1000000000 + getTs.tv_nsec)/1000;
-    OIC_LOG_V(DEBUG, TAG, "current time = %ld", currentTime);
+    OIC_LOG_V(DEBUG, TAG, "current time = %lld", currentTime);
 #elif defined __ARDUINO__
     currentTime = millis() * 1000;
     OIC_LOG_V(DEBUG, TAG, "currtime=%lu", currentTime);
old mode 100755 (executable)
new mode 100644 (file)
index 544f561..3598110
@@ -36,7 +36,7 @@
 #include "oic_string.h"
 #include "org_iotivity_ca_CaIpInterface.h"
 
-#define TAG "IP_MONITOR"
+#define TAG "OIC_CA_IP_MONITOR"
 
 static CAInterface_t *CANewInterfaceItem(int index, const char *name, int family,
                                          uint32_t addr, int flags);
@@ -46,6 +46,12 @@ static CAResult_t CAAddInterfaceItem(u_arraylist_t *iflist, int index,
 
 CAResult_t CAIPJniInit();
 
+/**
+ * destroy JNI interface.
+ * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
+ */
+static CAResult_t CAIPDestroyJniInterface();
+
 #define MAX_INTERFACE_INFO_LENGTH 1024 // allows 32 interfaces from SIOCGIFCONF
 
 CAResult_t CAIPStartNetworkMonitor()
@@ -55,7 +61,7 @@ CAResult_t CAIPStartNetworkMonitor()
 
 CAResult_t CAIPStopNetworkMonitor()
 {
-    return CA_STATUS_OK;
+    return CAIPDestroyJniInterface();
 }
 
 int CAGetPollingInterval(int interval)
@@ -361,6 +367,78 @@ CAResult_t CAIPJniInit()
     return CA_STATUS_OK;
 }
 
+static CAResult_t CAIPDestroyJniInterface()
+{
+    OIC_LOG(DEBUG, TAG, "CAIPDestroyJniInterface");
+
+    JavaVM *jvm = CANativeJNIGetJavaVM();
+    if (!jvm)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get JavaVM pointer");
+        return CA_STATUS_FAILED;
+    }
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
+        res = (*jvm)->AttachCurrentThread(jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return CA_STATUS_FAILED;
+        }
+        isAttached = true;
+    }
+
+    jclass jni_IpInterface = (*env)->FindClass(env, "org/iotivity/ca/CaIpInterface");
+    if (!jni_IpInterface)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get CaIpInterface class");
+        goto error_exit;
+    }
+
+    jmethodID jni_InterfaceDestroyMethod = (*env)->GetStaticMethodID(env, jni_IpInterface,
+                                                                     "destroyIpInterface",
+                                                                     "()V");
+    if (!jni_InterfaceDestroyMethod)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get CaIpInterface destroy method");
+        goto error_exit;
+    }
+
+    (*env)->CallStaticVoidMethod(env, jni_IpInterface, jni_InterfaceDestroyMethod);
+
+    if ((*env)->ExceptionCheck(env))
+    {
+        OIC_LOG(ERROR, TAG, "destroyIpInterface has failed");
+        (*env)->ExceptionDescribe(env);
+        (*env)->ExceptionClear(env);
+        goto error_exit;
+    }
+
+    OIC_LOG(DEBUG, TAG, "Destroy instance for CaIpInterface");
+
+    if (isAttached)
+    {
+        (*jvm)->DetachCurrentThread(jvm);
+    }
+
+    return CA_STATUS_OK;
+
+error_exit:
+
+    if (isAttached)
+    {
+        (*jvm)->DetachCurrentThread(jvm);
+    }
+
+    return CA_STATUS_FAILED;
+}
+
 JNIEXPORT void JNICALL
 Java_org_iotivity_ca_CaIpInterface_caIpStateEnabled(JNIEnv *env, jclass class)
 {
index d8ac060..d8be9e6 100644 (file)
@@ -95,7 +95,8 @@ CAResult_t CAIPStartUnicastServer(const char *localAddress, uint16_t *port,
     uint8_t rawIPAddr[4];
     char address[16];
     W5100.getIPAddress(rawIPAddr);
-    sprintf(address, "%d.%d.%d.%d", rawIPAddr[0], rawIPAddr[1], rawIPAddr[2], rawIPAddr[3]);
+    snprintf(address, sizeof(address), "%d.%d.%d.%d", rawIPAddr[0], rawIPAddr[1], rawIPAddr[2],
+             rawIPAddr[3]);
     OIC_LOG_V(DEBUG, TAG, "address:%s", address);
     int serverFD = 1;
     if (CAArduinoInitUdpSocket(port, &serverFD) != CA_STATUS_OK)
index f139af8..02bcaea 100644 (file)
@@ -127,7 +127,11 @@ CAResult_t CAIPStartMulticastServer(const char *localAddress, const char *multic
     // wifi shield does not support multicast
     OIC_LOG(DEBUG, TAG, "IN");
     OIC_LOG(DEBUG, TAG, "OUT");
-    return CA_NOT_SUPPORTED;
+    //Arduino wifi shiled does not support multicast.
+    //OCInit() is failing if an error code is returned here,
+    //hence blocking even uni-cast operations.
+    //So default return value is changed to CA_STATUS_OK.
+    return CA_STATUS_OK;
 }
 
 CAResult_t CAIPStartServer()
index 998e26c..308ec6d 100644 (file)
@@ -40,7 +40,7 @@
 /**
  * Logging tag for module name.
  */
-#define TAG "IP_ADAP"
+#define TAG "OIC_CA_IP_ADAP"
 
 #ifndef SINGLE_THREAD
 /**
@@ -52,7 +52,7 @@ typedef struct
     void *data;
     uint32_t dataLen;
     bool isMulticast;
-} CAIPData;
+} CAIPData_t;
 
 /**
  * Queue handle for Send Data.
@@ -90,17 +90,16 @@ static void CAIPDeinitializeQueueHandles();
 
 static void CAIPSendDataThread(void *threadData);
 
-static CAIPData *CACreateIPData(const CAEndpoint_t *remoteEndpoint,
-                                const void *data, uint32_t dataLength,
-                                bool isMulticast);
-void CAFreeIPData(CAIPData *ipData);
+static CAIPData_t *CACreateIPData(const CAEndpoint_t *remoteEndpoint,
+                                  const void *data, uint32_t dataLength,
+                                  bool isMulticast);
+
+void CAFreeIPData(CAIPData_t *ipData);
 
 static void CADataDestroyer(void *data, uint32_t size);
 
 CAResult_t CAIPInitializeQueueHandles()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     // Check if the message queue is already initialized
     if (g_sendQueueHandle)
     {
@@ -126,19 +125,14 @@ CAResult_t CAIPInitializeQueueHandles()
         return CA_STATUS_FAILED;
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
 
 void CAIPDeinitializeQueueHandles()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     CAQueueingThreadDestroy(g_sendQueueHandle);
     OICFree(g_sendQueueHandle);
     g_sendQueueHandle = NULL;
-
-    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 #endif // SINGLE_THREAD
@@ -147,20 +141,15 @@ void CAIPConnectionStateCB(const char *ipAddress, CANetworkStatus_t status)
 {
     (void)ipAddress;
     (void)status;
-    OIC_LOG(DEBUG, TAG, "IN");
 }
 
 #ifdef __WITH_DTLS__
 static void CAIPPacketSendCB(CAEndpoint_t *endpoint, const void *data, uint32_t dataLength)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
 
     CAIPSendData(endpoint, data, dataLength, false);
-
-    OIC_LOG(DEBUG, TAG, "OUT");
 }
 #endif
 
@@ -168,8 +157,6 @@ static void CAIPPacketSendCB(CAEndpoint_t *endpoint, const void *data, uint32_t
 void CAIPPacketReceivedCB(const CASecureEndpoint_t *sep, const void *data,
                           uint32_t dataLength)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     VERIFY_NON_NULL_VOID(sep, TAG, "sep is NULL");
     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
 
@@ -179,35 +166,18 @@ void CAIPPacketReceivedCB(const CASecureEndpoint_t *sep, const void *data,
     {
         g_networkPacketCallback(sep, data, dataLength);
     }
-    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
-void CAIPErrorHandler (const CAEndpoint_t *endpoint, const void *data,
-                       uint32_t dataLength, CAResult_t result)
+void CAIPErrorHandler(const CAEndpoint_t *endpoint, const void *data,
+                      uint32_t dataLength, CAResult_t result)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
-
     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
 
-    void *buf = (void*)OICMalloc(sizeof(char) * dataLength);
-    if (!buf)
-    {
-        OIC_LOG(ERROR, TAG, "Memory Allocation failed!");
-        return;
-    }
-    memcpy(buf, data, dataLength);
     if (g_errorCallback)
     {
-        g_errorCallback(endpoint, buf, dataLength, result);
-    }
-    else
-    {
-        OICFree(buf);
+        g_errorCallback(endpoint, data, dataLength, result);
     }
-
-    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 static void CAInitializeIPGlobals()
@@ -270,18 +240,21 @@ CAResult_t CAInitializeIP(CARegisterConnectivityCallback registerCallback,
     CADTLSSetAdapterCallbacks(CAIPPacketReceivedCB, CAIPPacketSendCB, 0);
 #endif
 
-    CAConnectivityHandler_t ipHandler;
-    ipHandler.startAdapter = CAStartIP;
-    ipHandler.startListenServer = CAStartIPListeningServer;
-    ipHandler.stopListenServer = CAStopIPListeningServer;
-    ipHandler.startDiscoveryServer = CAStartIPDiscoveryServer;
-    ipHandler.sendData = CASendIPUnicastData;
-    ipHandler.sendDataToAll = CASendIPMulticastData;
-    ipHandler.GetnetInfo = CAGetIPInterfaceInformation;
-    ipHandler.readData = CAReadIPData;
-    ipHandler.stopAdapter = CAStopIP;
-    ipHandler.terminate = CATerminateIP;
-    registerCallback(ipHandler, CA_ADAPTER_IP);
+    static const CAConnectivityHandler_t ipHandler =
+        {
+            .startAdapter = CAStartIP,
+            .stopAdapter = CAStopIP,
+            .startListenServer = CAStartIPListeningServer,
+            .stopListenServer = CAStopIPListeningServer,
+            .startDiscoveryServer = CAStartIPDiscoveryServer,
+            .sendData = CASendIPUnicastData,
+            .sendDataToAll = CASendIPMulticastData,
+            .GetnetInfo = CAGetIPInterfaceInformation,
+            .readData = CAReadIPData,
+            .terminate = CATerminateIP,
+            .cType = CA_ADAPTER_IP
+        };
+    registerCallback(ipHandler);
 
     OIC_LOG(INFO, TAG, "OUT IntializeIP is Success");
     return CA_STATUS_OK;
@@ -289,8 +262,6 @@ CAResult_t CAInitializeIP(CARegisterConnectivityCallback registerCallback,
 
 CAResult_t CAStartIP()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     CAIPStartNetworkMonitor();
 #ifdef SINGLE_THREAD
     uint16_t unicastPort = 55555;
@@ -325,47 +296,40 @@ CAResult_t CAStartIP()
 
 #endif
 
-    OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
 
 CAResult_t CAStartIPListeningServer()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
     CAResult_t ret = CAIPStartListenServer();
     if (CA_STATUS_OK != ret)
     {
         OIC_LOG_V(ERROR, TAG, "Failed to start listening server![%d]", ret);
         return ret;
     }
-    OIC_LOG(DEBUG, TAG, "OUT");
+
     return CA_STATUS_OK;
 }
 
 CAResult_t CAStopIPListeningServer()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
     CAResult_t ret = CAIPStopListenServer();
     if (CA_STATUS_OK != ret)
     {
         OIC_LOG_V(ERROR, TAG, "Failed to stop listening server![%d]", ret);
-        return ret;
     }
-    OIC_LOG(DEBUG, TAG, "OUT");
-    return CA_STATUS_OK;
+
+    return ret;
 }
 
 CAResult_t CAStartIPDiscoveryServer()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
     return CAStartIPListeningServer();
 }
 
 static int32_t CAQueueIPData(bool isMulticast, const CAEndpoint_t *endpoint,
-                            const void *data, uint32_t dataLength)
+                             const void *data, uint32_t dataLength)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     VERIFY_NON_NULL_RET(endpoint, TAG, "remoteEndpoint", -1);
     VERIFY_NON_NULL_RET(data, TAG, "data", -1);
 
@@ -384,46 +348,39 @@ static int32_t CAQueueIPData(bool isMulticast, const CAEndpoint_t *endpoint,
 
     VERIFY_NON_NULL_RET(g_sendQueueHandle, TAG, "sendQueueHandle", -1);
     // Create IPData to add to queue
-    CAIPData *ipData = CACreateIPData(endpoint, data, dataLength, isMulticast);
+    CAIPData_t *ipData = CACreateIPData(endpoint, data, dataLength, isMulticast);
     if (!ipData)
     {
         OIC_LOG(ERROR, TAG, "Failed to create ipData!");
         return -1;
     }
     // Add message to send queue
-    CAQueueingThreadAddData(g_sendQueueHandle, ipData, sizeof(CAIPData));
+    CAQueueingThreadAddData(g_sendQueueHandle, ipData, sizeof(CAIPData_t));
 
 #endif // SINGLE_THREAD
 
-    OIC_LOG(DEBUG, TAG, "OUT");
     return dataLength;
 }
 
 int32_t CASendIPUnicastData(const CAEndpoint_t *endpoint,
                             const void *data, uint32_t dataLength)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
     return CAQueueIPData(false, endpoint, data, dataLength);
 }
 
 int32_t CASendIPMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLength)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
     return CAQueueIPData(true, endpoint, data, dataLength);
 }
 
 CAResult_t CAReadIPData()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
     CAIPPullData();
-    OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
 
 CAResult_t CAStopIP()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
 #ifdef __WITH_DTLS__
     CAAdapterNetDtlsDeInit();
 #endif
@@ -433,8 +390,6 @@ CAResult_t CAStopIP()
     {
         CAQueueingThreadStop(g_sendQueueHandle);
     }
-
-    CAIPDeinitializeQueueHandles();
 #endif
 
     CAIPStopNetworkMonitor();
@@ -442,14 +397,11 @@ CAResult_t CAStopIP()
     //Re-initializing the Globals to start them again
     CAInitializeIPGlobals();
 
-    OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
 
 void CATerminateIP()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
 #ifdef __WITH_DTLS__
     CADTLSSetAdapterCallbacks(NULL, NULL, 0);
 #endif
@@ -457,19 +409,16 @@ void CATerminateIP()
     CAIPSetPacketReceiveCallback(NULL);
 
 #ifndef SINGLE_THREAD
+    CADeInitializeIPGlobals();
     CAIPDeinitializeQueueHandles();
 #endif
-
-    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 #ifndef SINGLE_THREAD
 
 void CAIPSendDataThread(void *threadData)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
-    CAIPData *ipData = (CAIPData *) threadData;
+    CAIPData_t *ipData = (CAIPData_t *) threadData;
     if (!ipData)
     {
         OIC_LOG(DEBUG, TAG, "Invalid ip data!");
@@ -486,7 +435,7 @@ void CAIPSendDataThread(void *threadData)
     {
         //Processing for sending unicast
 #ifdef __WITH_DTLS__
-        if (ipData->remoteEndpoint->flags & CA_SECURE)
+        if (ipData->remoteEndpoint && ipData->remoteEndpoint->flags & CA_SECURE)
         {
             OIC_LOG(DEBUG, TAG, "CAAdapterNetDtlsEncrypt called!");
             CAResult_t result = CAAdapterNetDtlsEncrypt(ipData->remoteEndpoint,
@@ -507,20 +456,18 @@ void CAIPSendDataThread(void *threadData)
         CAIPSendData(ipData->remoteEndpoint, ipData->data, ipData->dataLen, false);
 #endif
     }
-
-    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 #endif
 
 #ifndef SINGLE_THREAD
-
-CAIPData *CACreateIPData(const CAEndpoint_t *remoteEndpoint, const void *data,
-                                     uint32_t dataLength, bool isMulticast)
+CAIPData_t *CACreateIPData(const CAEndpoint_t *remoteEndpoint, const void *data,
+                           uint32_t dataLength, bool isMulticast)
 {
+    VERIFY_NON_NULL_RET(remoteEndpoint, TAG, "remoteEndpoint is NULL", NULL);
     VERIFY_NON_NULL_RET(data, TAG, "IPData is NULL", NULL);
 
-    CAIPData *ipData = (CAIPData *) OICMalloc(sizeof(CAIPData));
+    CAIPData_t *ipData = (CAIPData_t *) OICMalloc(sizeof(*ipData));
     if (!ipData)
     {
         OIC_LOG(ERROR, TAG, "Memory allocation failed!");
@@ -544,7 +491,7 @@ CAIPData *CACreateIPData(const CAEndpoint_t *remoteEndpoint, const void *data,
     return ipData;
 }
 
-void CAFreeIPData(CAIPData *ipData)
+void CAFreeIPData(CAIPData_t *ipData)
 {
     VERIFY_NON_NULL_VOID(ipData, TAG, "ipData is NULL");
 
@@ -555,11 +502,11 @@ void CAFreeIPData(CAIPData *ipData)
 
 void CADataDestroyer(void *data, uint32_t size)
 {
-    if (size < sizeof(CAIPData))
+    if (size < sizeof(CAIPData_t))
     {
         OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %d", data, size);
     }
-    CAIPData *etdata = (CAIPData *) data;
+    CAIPData_t *etdata = (CAIPData_t *) data;
 
     CAFreeIPData(etdata);
 }
index 08c46b0..c49b064 100644 (file)
  *
  ******************************************************************/
 
+#ifndef __APPLE_USE_RFC_3542
 #define __APPLE_USE_RFC_3542 // for PKTINFO
+#endif
+#ifndef _GNU_SOURCE
 #define _GNU_SOURCE // for in6_pktinfo
+#endif
 
 #include <sys/types.h>
 #include <sys/socket.h>
 #include "oic_malloc.h"
 #include "oic_string.h"
 
-/**
- * @def TAG
- * @brief Logging tag for module name
+/*
+ * Logging tag for module name
  */
-#define TAG "IP_SERVER"
+#define TAG "OIC_CA_IP_SERVER"
 
 #define SELECT_TIMEOUT 1     // select() seconds (and termination latency)
 
@@ -116,16 +119,65 @@ static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags);
         flags = FLAGS; \
     }
 
+void CADeInitializeIPGlobals()
+{
+    if (caglobals.ip.u6.fd != -1)
+    {
+        close(caglobals.ip.u6.fd);
+        caglobals.ip.u6.fd = -1;
+    }
+
+    if (caglobals.ip.u6s.fd != -1)
+    {
+        close(caglobals.ip.u6s.fd);
+        caglobals.ip.u6s.fd = -1;
+    }
+
+    if (caglobals.ip.u4.fd != -1)
+    {
+        close(caglobals.ip.u4.fd);
+        caglobals.ip.u4.fd = -1;
+    }
+
+    if (caglobals.ip.u4s.fd != -1)
+    {
+        close(caglobals.ip.u4s.fd);
+        caglobals.ip.u4s.fd = -1;
+    }
+
+    if (caglobals.ip.m6.fd != -1)
+    {
+        close(caglobals.ip.m6.fd);
+        caglobals.ip.m6.fd = -1;
+    }
+
+    if (caglobals.ip.m6s.fd != -1)
+    {
+        close(caglobals.ip.m6s.fd);
+        caglobals.ip.m6s.fd = -1;
+    }
+
+    if (caglobals.ip.m4.fd != -1)
+    {
+        close(caglobals.ip.m4.fd);
+        caglobals.ip.m4.fd = -1;
+    }
+
+    if (caglobals.ip.m4s.fd != -1)
+    {
+        close(caglobals.ip.m4s.fd);
+        caglobals.ip.m4s.fd = -1;
+    }
+}
+
 static void CAReceiveHandler(void *data)
 {
     (void)data;
-    OIC_LOG(DEBUG, TAG, "IN");
+
     while (!caglobals.ip.terminate)
     {
         CAFindReadyMessage();
     }
-
-    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 static void CAFindReadyMessage()
@@ -197,8 +249,13 @@ static void CASelectReturned(fd_set *readFds, int ret)
         }
         else if (FD_ISSET(caglobals.ip.shutdownFds[0], readFds))
         {
-            char buf[10];
-            (void)read(caglobals.ip.shutdownFds[0], buf, sizeof (buf));
+            char buf[10] = {0};
+            ssize_t len = read(caglobals.ip.shutdownFds[0], buf, sizeof (buf));
+            if (-1 == len)
+            {
+                continue;
+            }
+
             CAInterface_t *ifchanged = CAFindInterfaceChange();
             if (ifchanged)
             {
@@ -222,11 +279,10 @@ static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags)
     char recvBuffer[COAP_MAX_PDU_SIZE];
 
     size_t len;
-    int level, type;
+    int level, type, namelen;
     struct sockaddr_storage srcAddr;
     unsigned char *pktinfo = NULL;
-    struct msghdr msg = { 0 };
-    struct cmsghdr *cmp;
+    struct cmsghdr *cmp = NULL;
     struct iovec iov = { recvBuffer, sizeof (recvBuffer) };
     union control
     {
@@ -236,24 +292,25 @@ static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags)
 
     if (flags & CA_IPV6)
     {
-        msg.msg_namelen = sizeof (struct sockaddr_in6);
+        namelen = sizeof (struct sockaddr_in6);
         level = IPPROTO_IPV6;
         type = IPV6_PKTINFO;
         len = sizeof (struct in6_pktinfo);
     }
     else
     {
-        msg.msg_namelen = sizeof (struct sockaddr_in);
+        namelen = sizeof (struct sockaddr_in);
         level = IPPROTO_IP;
         type = IP_PKTINFO;
         len = sizeof (struct in6_pktinfo);
     }
 
-    msg.msg_name = &srcAddr;
-    msg.msg_iov = &iov;
-    msg.msg_iovlen = 1;
-    msg.msg_control = &cmsg;
-    msg.msg_controllen = CMSG_SPACE(len);
+    struct msghdr msg = { .msg_name = &srcAddr,
+                          .msg_namelen = namelen,
+                          .msg_iov = &iov,
+                          .msg_iovlen = 1,
+                          .msg_control = &cmsg,
+                          .msg_controllen = CMSG_SPACE(len) };
 
     ssize_t recvLen = recvmsg(fd, &msg, flags);
     if (-1 == recvLen)
@@ -335,9 +392,9 @@ void CAIPPullData()
 static int CACreateSocket(int family, uint16_t *port)
 {
     int socktype = SOCK_DGRAM;
-    #ifdef SOCK_CLOEXEC
+#ifdef SOCK_CLOEXEC
     socktype |= SOCK_CLOEXEC;
-    #endif
+#endif
     int fd = socket(family, socktype, IPPROTO_UDP);
     if (-1 == fd)
     {
@@ -345,7 +402,7 @@ static int CACreateSocket(int family, uint16_t *port)
         return -1;
     }
 
-    #ifndef SOCK_CLOEXEC
+#ifndef SOCK_CLOEXEC
     int fl = fcntl(fd, F_GETFD);
     if (-1 == fl || -1 == fcntl(fd, F_SETFD, fl|FD_CLOEXEC))
     {
@@ -353,7 +410,7 @@ static int CACreateSocket(int family, uint16_t *port)
         close(fd);
         return -1;
     }
-    #endif
+#endif
 
     struct sockaddr_storage sa = { .ss_family = family };
     socklen_t socklen;
@@ -511,7 +568,7 @@ CAResult_t CAIPStartServer(const ca_thread_pool_t threadPool)
 
     if (!IPv4MulticastAddress.s_addr)
     {
-        (void)inet_aton(IPv4_MULTICAST, &IPv4MulticastAddress);
+        (void)inet_pton(AF_INET, IPv4_MULTICAST, &IPv4MulticastAddress);
         (void)inet_pton(AF_INET6, IPv6_MULTICAST_INT, &IPv6MulticastAddressInt);
         (void)inet_pton(AF_INET6, IPv6_MULTICAST_LNK, &IPv6MulticastAddressLnk);
         (void)inet_pton(AF_INET6, IPv6_MULTICAST_RLM, &IPv6MulticastAddressRlm);
@@ -586,8 +643,6 @@ CAResult_t CAIPStartServer(const ca_thread_pool_t threadPool)
 
 void CAIPStopServer()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     caglobals.ip.started = false;
     caglobals.ip.terminate = true;
 
@@ -600,8 +655,6 @@ void CAIPStopServer()
     {
         // receive thread will stop in SELECT_TIMEOUT seconds.
     }
-
-    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 void CAWakeUpForChange()
@@ -627,8 +680,9 @@ static void applyMulticastToInterface4(struct in_addr inaddr)
         return;
     }
 
-    struct ip_mreq mreq = { .imr_multiaddr = IPv4MulticastAddress,
-                            .imr_interface = inaddr};
+    struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
+                             .imr_address = inaddr,
+                             .imr_ifindex = 0 };
     if (setsockopt(caglobals.ip.m4.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof (mreq)))
     {
         if (EADDRINUSE != errno)
@@ -647,9 +701,8 @@ static void applyMulticastToInterface4(struct in_addr inaddr)
 
 static void applyMulticast6(int fd, struct in6_addr *addr, uint32_t interface)
 {
-    struct ipv6_mreq mreq;
-    mreq.ipv6mr_multiaddr = *addr;
-    mreq.ipv6mr_interface = interface;
+    struct ipv6_mreq mreq = {.ipv6mr_multiaddr = *addr, .ipv6mr_interface = interface};
+
     if (setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq, sizeof (mreq)))
     {
         if (EADDRINUSE != errno)
@@ -672,6 +725,7 @@ static void applyMulticastToInterface6(uint32_t interface)
     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressSit, interface);
     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressOrg, interface);
     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressGlb, interface);
+
     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressInt, interface);
     applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressLnk, interface);
     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressRlm, interface);
@@ -771,9 +825,14 @@ CAResult_t CAIPStopListenServer()
 
 static void CAProcessNewInterface(CAInterface_t *ifitem)
 {
+    if (!ifitem)
+    {
+        OIC_LOG(DEBUG, TAG, "ifitem is null");
+        return;
+    }
+
     applyMulticastToInterface6(ifitem->index);
-    struct in_addr inaddr;
-    inaddr.s_addr = ifitem->ipv4addr;
+    struct in_addr inaddr = { .s_addr = ifitem->ipv4addr };
     applyMulticastToInterface4(inaddr);
 }
 static void CAHandleNetlink()
@@ -789,7 +848,7 @@ static void CAHandleNetlink()
 
     for (nh = (struct nlmsghdr *)buf; NLMSG_OK(nh, len); nh = NLMSG_NEXT(nh, len))
     {
-        if (nh->nlmsg_type != RTM_NEWLINK)
+        if (nh != NULL && nh->nlmsg_type != RTM_NEWLINK)
         {
             continue;
         }
@@ -833,20 +892,12 @@ static void CAHandleNetlink()
 
 void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     g_packetReceivedCallback = callback;
-
-    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 void CAIPSetExceptionCallback(CAIPExceptionCallback callback)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     g_exceptionCallback = callback;
-
-    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 static void sendData(int fd, const CAEndpoint_t *endpoint,
@@ -855,6 +906,12 @@ static void sendData(int fd, const CAEndpoint_t *endpoint,
 {
     OIC_LOG(DEBUG, TAG, "IN");
 
+    if (!endpoint)
+    {
+        OIC_LOG(DEBUG, TAG, "endpoint is null");
+        return;
+    }
+
     char *secure = (endpoint->flags & CA_SECURE) ? "secure " : "";
     (void)secure;   // eliminates release warning
     struct sockaddr_storage sock;
@@ -885,7 +942,7 @@ static void sendData(int fd, const CAEndpoint_t *endpoint,
     }
     else
     {
-        OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %ld bytes", secure, cast, fam, len);
+        OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %zd bytes", secure, cast, fam, len);
     }
 }
 
@@ -893,6 +950,12 @@ static void sendMulticastData6(const u_arraylist_t *iflist,
                                CAEndpoint_t *endpoint,
                                const void *data, uint32_t datalen)
 {
+    if (!endpoint)
+    {
+        OIC_LOG(DEBUG, TAG, "endpoint is null");
+        return;
+    }
+
     int scope = endpoint->flags & CA_SCOPE_MASK;
     char *ipv6mcname = ipv6mcnames[scope];
     if (!ipv6mcname)
@@ -934,7 +997,10 @@ static void sendMulticastData4(const u_arraylist_t *iflist,
                                CAEndpoint_t *endpoint,
                                const void *data, uint32_t datalen)
 {
-    struct ip_mreq mreq = { .imr_multiaddr = IPv4MulticastAddress };
+    VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
+
+    struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
+                             .imr_ifindex = 0 };
     OICStrcpy(endpoint->addr, sizeof(endpoint->addr), IPv4_MULTICAST);
     int fd = caglobals.ip.u4.fd;
 
@@ -957,7 +1023,7 @@ static void sendMulticastData4(const u_arraylist_t *iflist,
 
         struct in_addr inaddr;
         inaddr.s_addr = ifitem->ipv4addr;
-        mreq.imr_interface = inaddr;
+        mreq.imr_address = inaddr;
         if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, &mreq, sizeof (mreq)))
         {
             OIC_LOG_V(ERROR, TAG, "send IP_MULTICAST_IF failed: %s (using defualt)",
@@ -968,7 +1034,7 @@ static void sendMulticastData4(const u_arraylist_t *iflist,
 }
 
 void CAIPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
-                                                            bool isMulticast)
+                  bool isMulticast)
 {
     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
@@ -1008,17 +1074,17 @@ void CAIPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
         if (caglobals.ip.ipv6enabled && (endpoint->flags & CA_IPV6))
         {
             fd = isSecure ? caglobals.ip.u6s.fd : caglobals.ip.u6.fd;
-            #ifndef __WITH_DTLS__
+#ifndef __WITH_DTLS__
             fd = caglobals.ip.u6.fd;
-            #endif
+#endif
             sendData(fd, endpoint, data, datalen, "unicast", "ipv6");
         }
         if (caglobals.ip.ipv4enabled && (endpoint->flags & CA_IPV4))
         {
             fd = isSecure ? caglobals.ip.u4s.fd : caglobals.ip.u4.fd;
-            #ifndef __WITH_DTLS__
+#ifndef __WITH_DTLS__
             fd = caglobals.ip.u4.fd;
-            #endif
+#endif
             sendData(fd, endpoint, data, datalen, "unicast", "ipv4");
         }
     }
@@ -1026,8 +1092,6 @@ void CAIPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
 
 CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     VERIFY_NON_NULL(info, TAG, "info is NULL");
     VERIFY_NON_NULL(size, TAG, "size is NULL");
 
@@ -1075,9 +1139,7 @@ CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
             eps[j].flags = CA_IPV4;
             eps[j].port = caglobals.ip.u4.port;
 
-            unsigned char *addr=  (unsigned char *) &(ifitem->ipv4addr);
-            snprintf(eps[j].addr, MAX_ADDR_STR_SIZE_CA, "%d.%d.%d.%d",
-                     addr[0], addr[1], addr[2], addr[3]);
+            inet_ntop(AF_INET, &(ifitem->ipv4addr), eps[j].addr, MAX_ADDR_STR_SIZE_CA);
         }
 
 #ifdef __WITH_DTLS__
@@ -1095,10 +1157,7 @@ CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
         {
             eps[j].flags = CA_IPV4 | CA_SECURE;
             eps[j].port = caglobals.ip.u4s.port;
-
-            unsigned char *addr=  (unsigned char *) &(ifitem->ipv4addr);
-            snprintf(eps[j].addr, MAX_ADDR_STR_SIZE_CA, "%d.%d.%d.%d",
-                     addr[0], addr[1], addr[2], addr[3]);
+            inet_ntop(AF_INET, &(ifitem->ipv4addr), eps[j].addr, MAX_ADDR_STR_SIZE_CA);
         }
 #endif
         j++;
@@ -1109,6 +1168,5 @@ CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
 
     u_arraylist_destroy(iflist);
 
-    OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
index c70e9cc..f1d5211 100644 (file)
@@ -34,7 +34,7 @@
 #include "oic_malloc.h"
 #include "oic_string.h"
 
-#define TAG "IP_MONITOR"
+#define TAG "OIC_CA_IP_MONITOR"
 
 CAResult_t CAIPStartNetworkMonitor()
 {
index 88427f3..437e535 100644 (file)
@@ -254,7 +254,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;
@@ -286,7 +285,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;
diff --git a/resource/csdk/connectivity/src/nfc_adapter/SConscript b/resource/csdk/connectivity/src/nfc_adapter/SConscript
new file mode 100644 (file)
index 0000000..a4b240f
--- /dev/null
@@ -0,0 +1,40 @@
+#######################################################
+#    Build NFC adapter
+#######################################################
+
+Import('env')
+import os.path
+
+print "Reading IP adapter script"
+
+target_os = env.get('TARGET_OS')
+inc_files = env.get('CPPPATH')
+src_dir = './nfc_adapter/'
+
+
+# Source files to build common for all platforms
+common_files = [ os.path.join(src_dir,
+                                  'canfcadapter.c') ]
+
+# Get list of target-specific source file base names, i.e. no parent
+# directories prepended to the path.
+#
+# Target-specific SConscript files are expected to return that list.
+target_files = []
+target_sconscript = os.path.join(target_os, 'SConscript')
+
+# Check for the existence of the platform-specific SConscript file
+# relative to the top-level source directory, not the build (variant)
+# directory, before calling that SConscript file to prevent a missing
+# file warning platforms that don't provide one.
+target_sconscript_abspath = str(File(target_sconscript).srcnode().abspath)
+if os.path.exists(target_sconscript_abspath):
+        target_files = env.SConscript(target_sconscript, exports='src_dir')
+
+# Now prepend the appropriate parent directories
+# (e.g. ./nfc_adapter/android) to each of the target source files in
+# the list.
+target_files = [ os.path.join(src_dir, target_os, f) for f in target_files ]
+
+#common and target-specific source file lists.
+env.AppendUnique(CA_SRC = common_files + target_files)
diff --git a/resource/csdk/connectivity/src/nfc_adapter/android/SConscript b/resource/csdk/connectivity/src/nfc_adapter/android/SConscript
new file mode 100644 (file)
index 0000000..0dd1a74
--- /dev/null
@@ -0,0 +1,12 @@
+#######################################################
+#       Build NFC Client and Server for Android
+#######################################################
+
+Import('env', 'src_dir')
+import os.path
+
+env.AppendUnique(CPPPATH = [ os.path.join(src_dir, 'android') ])
+
+src_files = [ 'canfcserver.c' ]
+
+Return('src_files')
diff --git a/resource/csdk/connectivity/src/nfc_adapter/android/canfcserver.c b/resource/csdk/connectivity/src/nfc_adapter/android/canfcserver.c
new file mode 100644 (file)
index 0000000..aa23348
--- /dev/null
@@ -0,0 +1,576 @@
+/* ****************************************************************j\r
+ *\r
+ * Copyright 2015 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
+#include "canfcinterface.h"\r
+\r
+#include "caadapterutils.h"\r
+#include "camutex.h"\r
+#include "oic_malloc.h"\r
+#include "oic_string.h"\r
+\r
+/**\r
+ * TAG\r
+ * Logging tag for module name\r
+ */\r
+#define TAG "NFC_SERVER"\r
+\r
+static CANFCPacketReceivedCallback g_packetReceivedCallback;\r
+\r
+static JavaVM *g_jvm = NULL;\r
+static jobject g_context = NULL;\r
+static jobject g_activity = NULL;\r
+static jobject g_nfcInterface = NULL;\r
+static jmethodID g_sendMethod = NULL;\r
+\r
+static void CANfcJniInit();\r
+static void CANfcJNISetContext();\r
+static CAResult_t CANfcCreateJniInterfaceObject();\r
+static CAResult_t CANfcSendDataImpl(const CAEndpoint_t * ep, const char* data, uint32_t dataLen);\r
+\r
+static const char CLASS_NFCINTERFACE[] = "org/iotivity/ca/CaNfcInterface";\r
+\r
+static void CANfcJniInit()\r
+{\r
+    OIC_LOG(DEBUG, TAG, "CANfcJniInit");\r
+    g_jvm = (JavaVM*) CANativeJNIGetJavaVM();\r
+}\r
+\r
+static void CANfcJNISetContext()\r
+{\r
+    OIC_LOG(DEBUG, TAG, "CANfcJNISetContext");\r
+    g_context = (jobject) CANativeJNIGetContext();\r
+    g_activity = (jobject) CANativeGetActivity();\r
+}\r
+\r
+void CANFCSetPacketReceiveCallback(CANFCPacketReceivedCallback callback)\r
+{\r
+    OIC_LOG(DEBUG, TAG, "IN");\r
+\r
+    g_packetReceivedCallback = callback;\r
+\r
+    OIC_LOG(DEBUG, TAG, "OUT");\r
+}\r
+\r
+CAResult_t SetCreateNdefMessageCallbackfromNative(JNIEnv* env)\r
+{\r
+    OIC_LOG(DEBUG, TAG, "SetCreateNdefMessageCallbackfromNative IN");\r
+\r
+    VERIFY_NON_NULL(env, TAG, "env");\r
+    VERIFY_NON_NULL(g_context, TAG, "g_context");\r
+    VERIFY_NON_NULL(g_activity, TAG, "g_activity");\r
+    VERIFY_NON_NULL(g_nfcInterface, TAG, "g_nfcInterface");\r
+\r
+    jclass cid_NfcAdapter = (*env)->FindClass(env, "android/nfc/NfcAdapter");\r
+    if (!cid_NfcAdapter)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Could not get NfcAdapter class");\r
+        return CA_STATUS_FAILED;\r
+    }\r
+\r
+    jmethodID mid_getAdapter = (*env)->GetStaticMethodID(env, cid_NfcAdapter,\r
+                                       "getDefaultAdapter",\r
+                                       "(Landroid/content/Context;)Landroid/nfc/NfcAdapter;");\r
+    if (!mid_getAdapter)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Could not get methodId mid_getAdapter");\r
+        return CA_STATUS_FAILED;\r
+    }\r
+\r
+    jobject adapter = (*env)->CallStaticObjectMethod(env, cid_NfcAdapter, mid_getAdapter,\r
+                                                     g_context);\r
+    if (!adapter)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Could not get NfcAdapter");\r
+        return CA_STATUS_FAILED;\r
+    }\r
+\r
+    jmethodID mid_setCallback = (*env)->GetMethodID(\r
+        env, cid_NfcAdapter, "setNdefPushMessageCallback",\r
+        "(Landroid/nfc/NfcAdapter$CreateNdefMessageCallback;Landroid/app/Activity;"\r
+        "[Landroid/app/Activity;)V");\r
+    if (!mid_setCallback)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Could not get mid_setCallback");\r
+        return CA_STATUS_FAILED;\r
+    }\r
+\r
+    jclass cid_Activity = (*env)->FindClass(env, "android/app/Activity");\r
+    if (!cid_Activity)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Could not get Activity class");\r
+        return CA_STATUS_FAILED;\r
+    }\r
+\r
+    jobjectArray tempArr = (jobjectArray) (*env)->NewObjectArray(env, 0, cid_Activity, NULL);\r
+    (*env)->CallVoidMethod(env, adapter, mid_setCallback, g_nfcInterface, g_activity, tempArr);\r
+\r
+    OIC_LOG(DEBUG, TAG, "SetCreateNdefMessageCallbackfromNative OUT");\r
+    return CA_STATUS_OK;\r
+}\r
+\r
+CAResult_t CANfcCreateJniInterfaceObject()\r
+{\r
+    OIC_LOG(DEBUG, TAG, "CANfcCreateJniInterfaceObject IN");\r
+\r
+    VERIFY_NON_NULL(g_activity, TAG, "g_activity");\r
+    VERIFY_NON_NULL(g_context, TAG, "g_context");\r
+    VERIFY_NON_NULL(g_jvm, TAG, "g_jvm");\r
+\r
+    bool isAttached = false;\r
+    JNIEnv* env;\r
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);\r
+    if (JNI_OK != res)\r
+    {\r
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");\r
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);\r
+\r
+        if (JNI_OK != res)\r
+        {\r
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");\r
+            return CA_STATUS_FAILED;\r
+        }\r
+        isAttached = true;\r
+    }\r
+\r
+    jclass jni_NfcInterface = (*env)->FindClass(env, "org/iotivity/ca/CaNfcInterface");\r
+    if (!jni_NfcInterface)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Could not get CaNfcInterface class");\r
+        goto error_exit;\r
+    }\r
+\r
+    jmethodID NfcInterfaceConstructorMethod = (*env)->GetMethodID(env, jni_NfcInterface, "<init>",\r
+                                            "(Landroid/content/Context;Landroid/app/Activity;)V");\r
+    if (!NfcInterfaceConstructorMethod)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Could not get CaNfcInterface constructor method");\r
+        goto error_exit;\r
+    }\r
+\r
+    jobject jni_nfcInstance = (*env)->NewObject(env, jni_NfcInterface,\r
+                                                NfcInterfaceConstructorMethod, g_context,\r
+                                                g_activity);\r
+    if (!jni_nfcInstance)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Create instance for CaNfcInterface failed");\r
+        goto error_exit;\r
+    }\r
+\r
+    g_nfcInterface = (*env)->NewGlobalRef(env, jni_nfcInstance);\r
+    if (!g_nfcInterface)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "NewGlobalRef  for nfcInterface failed");\r
+        goto error_exit;\r
+    }\r
+\r
+    OIC_LOG(DEBUG, TAG, "Create instance for CaNfcInterface");\r
+\r
+    CAResult_t result = SetCreateNdefMessageCallbackfromNative(env);\r
+    if (CA_STATUS_OK != result)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "SetCreateNdefMessageCallbackfromNative failed");\r
+        goto error_exit;\r
+    }\r
+\r
+    if (isAttached)\r
+    {\r
+        (*g_jvm)->DetachCurrentThread(g_jvm);\r
+    }\r
+\r
+    OIC_LOG(DEBUG, TAG, "CANfcCreateJniInterfaceObject OUT");\r
+    return CA_STATUS_OK;\r
+\r
+error_exit:\r
+    if (isAttached)\r
+    {\r
+        (*g_jvm)->DetachCurrentThread(g_jvm);\r
+    }\r
+\r
+    return CA_STATUS_FAILED;\r
+}\r
+\r
+CAResult_t CAInitializeNfcServer()\r
+{\r
+    CANfcJniInit();\r
+    CANfcJNISetContext();\r
+\r
+    CAResult_t result = CANfcCreateJniInterfaceObject();\r
+    if (CA_STATUS_OK != result)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "CANfcJniInit failed");\r
+    }\r
+\r
+    return result;\r
+}\r
+\r
+CAResult_t CANFCStartServer()\r
+{\r
+    bool isAttached = false;\r
+\r
+    OIC_LOG(INFO, TAG, "CANFCStartServer : IN");\r
+\r
+    JNIEnv* env;\r
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);\r
+    if (JNI_OK != res)\r
+    {\r
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");\r
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);\r
+\r
+        if (JNI_OK != res)\r
+        {\r
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");\r
+            return CA_STATUS_FAILED;\r
+        }\r
+        isAttached = true;\r
+    }\r
+\r
+    jclass jni_NfcInterface = (*env)->FindClass(env, "org/iotivity/ca/CaNfcInterface");\r
+    if (!jni_NfcInterface)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Could not get CaNFCClientInterface class");\r
+        goto error_exit;\r
+    }\r
+\r
+    jmethodID methodId = (*env)->GetMethodID(env, jni_NfcInterface, "caNfcInitialize", "()V");\r
+    if (!methodId)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Could not get methodId");\r
+        goto error_exit;\r
+    }\r
+\r
+    if (!g_nfcInterface)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "g_nfcInterface NULL");\r
+        goto error_exit;\r
+    }\r
+\r
+    (*env)->CallVoidMethod(env, g_nfcInterface, methodId);\r
+    OIC_LOG(DEBUG, TAG, "caNfcInitialize");\r
+\r
+    jmethodID sendDataMethodId = (*env)->GetMethodID(env, jni_NfcInterface, "processSendRquest",\r
+                                                     "([B)V");\r
+    if (!sendDataMethodId)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Could not get sendDataMethodId");\r
+        goto error_exit;\r
+    }\r
+\r
+    g_sendMethod = sendDataMethodId;\r
+\r
+    if (isAttached)\r
+    {\r
+        (*g_jvm)->DetachCurrentThread(g_jvm);\r
+    }\r
+\r
+    return CA_STATUS_OK;\r
+\r
+error_exit:\r
+    if (isAttached)\r
+    {\r
+        (*g_jvm)->DetachCurrentThread(g_jvm);\r
+    }\r
+    return CA_STATUS_FAILED;\r
+\r
+}\r
+\r
+void CANFCStopServer()\r
+{\r
+    // JNI Call to unregstier nfc adapter\r
+}\r
+\r
+/*\r
+ * Class:     org_iotivity_ca_CaNfcInterface\r
+ * Method:    caNativeNfcCreateNdefMessage\r
+ * Signature: ([B)Landroid/nfc/NdefMessage;\r
+ */\r
+JNIEXPORT jobject JNICALL\r
+Java_org_iotivity_ca_CaNfcInterface_caNativeNfcCreateNdefMessage(JNIEnv *env, jobject obj,\r
+                                                                 jbyteArray sendData)\r
+{\r
+    OIC_LOG(DEBUG, TAG, "caNativeNfcCreateNdefMessage : IN");\r
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);\r
+    VERIFY_NON_NULL_RET(obj, TAG, "obj is null", NULL);\r
+\r
+    const char *mime = "application/org.iotivity.ca.sample_service";\r
+    jstring mimeString = (*env)->NewStringUTF(env, mime);\r
+    if (!mimeString)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "NewStringUTF failed for mimeString");\r
+        return NULL;\r
+    }\r
+\r
+    const char *type = "US_ASCII";\r
+    jstring charSetString = (*env)->NewStringUTF(env, type);\r
+    if (!charSetString)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "NewStringUTF failed for charSetString");\r
+        return NULL;\r
+    }\r
+\r
+    jclass cid_string = (*env)->FindClass(env, "java/lang/String");\r
+    if (!cid_string)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Could not get NfcAdapter class for cid_string");\r
+        return NULL;\r
+    }\r
+\r
+    jmethodID mid_getBytes = (*env)->GetMethodID(env, cid_string, "getBytes",\r
+                                                 "(Ljava/lang/String;)[B");\r
+    if (!mid_getBytes)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Could not get methodId for mid_getBytes");\r
+        return NULL;\r
+    }\r
+\r
+    jbyteArray mimeTypeArr = (*env)->CallObjectMethod(env, mimeString, mid_getBytes,\r
+                                                      charSetString);\r
+    if (!mimeTypeArr)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "getBytes failed for mimeTypeArr");\r
+    }\r
+\r
+    jclass cid_NdefRecord = (*env)->FindClass(env, "android/nfc/NdefRecord");\r
+    if (!cid_NdefRecord)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Could not get NdefRecord class for cid_NdefRecord");\r
+        return NULL;\r
+    }\r
+\r
+    jmethodID mid_createRecord = (*env)->GetMethodID(env, cid_NdefRecord, "<init>",\r
+                                                     "(S[B[B[B)V");\r
+    if (!mid_createRecord)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Could not get methodId for mid_createRecord");\r
+        return NULL;\r
+    }\r
+\r
+    jfieldID fid_tnfType = (*env)->GetStaticFieldID(env, cid_NdefRecord, "TNF_MIME_MEDIA", "S");\r
+\r
+    jint tnfType = (*env)->GetStaticShortField(env, cid_NdefRecord, fid_tnfType);\r
+    OIC_LOG_V(ERROR, TAG, "tnfType : %d", tnfType);\r
+\r
+    jbyteArray nullArr = (*env)->NewByteArray(env, 0);\r
+\r
+    jobject ndefRecord = (*env)->NewObject(env, cid_NdefRecord, mid_createRecord, tnfType,\r
+                                           mimeTypeArr, nullArr, sendData);\r
+    if (!ndefRecord)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "createNdefRecord failed for ndefRecord");\r
+        return NULL;\r
+    }\r
+\r
+    jclass cid_NdefMsg = (*env)->FindClass(env, "android/nfc/NdefMessage");\r
+    if (!cid_NdefMsg)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Could not get NdefMessage class for cid_NdefMsg");\r
+        return NULL;\r
+    }\r
+\r
+    jmethodID mid_createMsg = (*env)->GetMethodID(env, cid_NdefMsg, "<init>",\r
+                                                  "([Landroid/nfc/NdefRecord;)V");\r
+    if (!mid_createMsg)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Could not get methodId for mid_createMsg");\r
+        return NULL;\r
+    }\r
+    jobjectArray tempArr = (jobjectArray) (*env)->NewObjectArray(env, 1, cid_NdefRecord,\r
+                                                                 ndefRecord);\r
+\r
+    jobject ndefMsg = (*env)->NewObject(env, cid_NdefMsg, mid_createMsg, tempArr);\r
+    if (!ndefMsg)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "createNdefMessage failed for ndefMsg");\r
+        return NULL;\r
+    }\r
+\r
+    OIC_LOG(DEBUG, TAG, "caNativeNfcCreateNdefMessage : OUT");\r
+    return ndefMsg;\r
+}\r
+\r
+/*\r
+ * Class:     org_iotivity_ca_CaNfcInterface\r
+ * Method:    caNativeNfcInvokeBeam\r
+ * Signature: ()Z\r
+ */\r
+JNIEXPORT jboolean JNICALL\r
+Java_org_iotivity_ca_CaNfcInterface_caNativeNfcInvokeBeam(JNIEnv *env, jobject obj)\r
+{\r
+    OIC_LOG(DEBUG, TAG, "cANativeNfcInvokeBeam : IN");\r
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", false);\r
+    VERIFY_NON_NULL_RET(obj, TAG, "obj is null", false);\r
+    VERIFY_NON_NULL_RET(g_context, TAG, "g_context is null", false);\r
+    VERIFY_NON_NULL_RET(g_activity, TAG, "g_activity is null", false);\r
+\r
+    jclass cid_NfcAdapter = (*env)->FindClass(env, "android/nfc/NfcAdapter");\r
+    if (!cid_NfcAdapter)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Could not get NfcAdapter cid_NfcAdapter ");\r
+        return JNI_FALSE;\r
+    }\r
+\r
+    jmethodID mid_getAdapter = (*env)->GetStaticMethodID(env, cid_NfcAdapter,\r
+                                       "getDefaultAdapter",\r
+                                       "(Landroid/content/Context;)Landroid/nfc/NfcAdapter;");\r
+    if (!mid_getAdapter)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Could not get methodId mid_getAdapter");\r
+        return JNI_FALSE;\r
+    }\r
+\r
+    jobject adapter = (*env)->CallStaticObjectMethod(env, cid_NfcAdapter, mid_getAdapter,\r
+                                                     g_context);\r
+    if (!adapter)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "getDefaultAdapter failed adapter");\r
+        return JNI_FALSE;\r
+    }\r
+\r
+    jmethodID mid_invokeBeam = (*env)->GetMethodID(env, cid_NfcAdapter, "invokeBeam",\r
+                                                   "(Landroid/app/Activity;)Z");\r
+    if (!mid_invokeBeam)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Could not get methodId mid_invokeBeam");\r
+        return JNI_FALSE;\r
+    }\r
+\r
+\r
+    jboolean isSuccess = (*env)->CallBooleanMethod(env, adapter, mid_invokeBeam, g_activity);\r
+    if (!isSuccess)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "invokeBeam has failed");\r
+    }\r
+    OIC_LOG(DEBUG, TAG, "cANativeNfcInvokeBeam : OUT");\r
+\r
+    return isSuccess;\r
+}\r
+\r
+/*\r
+ * Class:     org_iotivity_ca_CaNfcInterface\r
+ * Method:    caNativeNfcPacketReceived\r
+ * Signature: ([B)V\r
+ */\r
+JNIEXPORT void JNICALL\r
+Java_org_iotivity_ca_CaNfcInterface_caNativeNfcPacketReceived(JNIEnv *env, jobject obj,\r
+                                                              jbyteArray data)\r
+{\r
+    OIC_LOG(DEBUG, TAG, "caNfcPacketReceived : IN");\r
+    VERIFY_NON_NULL_VOID(env, TAG, "env is null");\r
+    VERIFY_NON_NULL_VOID(obj, TAG, "obj is null");\r
+    VERIFY_NON_NULL_VOID(data, TAG, "data is null");\r
+\r
+    char recvBuffer[COAP_MAX_PDU_SIZE] = {0};\r
+\r
+    // get Byte Array and covert to char*\r
+    jint length = (*env)->GetArrayLength(env, data);\r
+\r
+    if (length >= COAP_MAX_PDU_SIZE)\r
+    {\r
+        OIC_LOG_V(ERROR, TAG, "caNfcPacketReceived - Invalid CoAP length : %d",\r
+                  length);\r
+        return;\r
+    }\r
+\r
+    jboolean isCopy;\r
+    jbyte *jni_received_data = (jbyte*) (*env)->GetByteArrayElements(env, data, &isCopy);\r
+\r
+    OIC_LOG_V(DEBUG, TAG, "caNfcPacketReceived - raw data received : %s",\r
+              jni_received_data);\r
+\r
+    memcpy(recvBuffer, (const char*) jni_received_data, length);\r
+    (*env)->ReleaseByteArrayElements(env, data, jni_received_data, JNI_ABORT);\r
+\r
+    const char* address = "AA:BB:CC:DD:EE:FF";\r
+\r
+    OIC_LOG_V(DEBUG, TAG, "caNfcPacketReceived - data. : %s, %d",\r
+              recvBuffer, length);\r
+\r
+    CASecureEndpoint_t sep =\r
+            {.endpoint =\r
+                {.adapter = CA_ADAPTER_NFC,\r
+                 .flags = CA_DEFAULT_FLAGS\r
+                }\r
+             };\r
+    OICStrcpy(sep.endpoint.addr, sizeof(sep.endpoint.addr), address);\r
+\r
+    g_packetReceivedCallback(&sep, recvBuffer, length);\r
+    OIC_LOG(DEBUG, TAG, "caNfcPacketReceived : OUT");\r
+}\r
+\r
+CAResult_t CANfcSendDataImpl(const CAEndpoint_t * ep, const char* data, uint32_t dataLen)\r
+{\r
+    VERIFY_NON_NULL(ep, TAG, "CANfcSendDataImpl : endpoint is null");\r
+    VERIFY_NON_NULL(data, TAG, "CANfcSendDataImpl : data is null");\r
+    VERIFY_NON_NULL(g_jvm, TAG, "CANfcSendDataImpl : g_jvm is null");\r
+\r
+    OIC_LOG(INFO, TAG, "CANfcSendDataImpl moved env outside");\r
+    bool isAttached = false;\r
+    JNIEnv* env;\r
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);\r
+    if (JNI_OK != res)\r
+    {\r
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");\r
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);\r
+\r
+        if (JNI_OK != res)\r
+        {\r
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");\r
+            return CA_STATUS_FAILED;\r
+        }\r
+        isAttached = true;\r
+    }\r
+\r
+    OIC_LOG(INFO, TAG, "creating send buffer");\r
+    jbyteArray sendData = (*env)->NewByteArray(env, dataLen);\r
+    if (!sendData)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Failed to create ByteArray");\r
+        if (isAttached)\r
+        {\r
+            (*g_jvm)->DetachCurrentThread(g_jvm);\r
+        }\r
+\r
+        return CA_SEND_FAILED;\r
+\r
+    }\r
+\r
+    (*env)->SetByteArrayRegion(env, sendData, 0, dataLen, (jbyte*) data);\r
+\r
+    (*env)->CallVoidMethod(env, g_nfcInterface, g_sendMethod, sendData);\r
+    OIC_LOG(DEBUG, TAG, "send data through NFC");\r
+\r
+    (*env)->DeleteLocalRef(env, sendData);\r
+\r
+    if (isAttached)\r
+    {\r
+        (*g_jvm)->DetachCurrentThread(g_jvm);\r
+    }\r
+\r
+    return CA_STATUS_OK;\r
+}\r
+\r
+void CANFCSendData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLength)\r
+{\r
+    VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");\r
+    VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");\r
+\r
+    // JNI to Send data\r
+    CANfcSendDataImpl(endpoint, data, dataLength);\r
+    return;\r
+}\r
+\r
diff --git a/resource/csdk/connectivity/src/nfc_adapter/canfcadapter.c b/resource/csdk/connectivity/src/nfc_adapter/canfcadapter.c
new file mode 100644 (file)
index 0000000..cc34caa
--- /dev/null
@@ -0,0 +1,421 @@
+/* *****************************************************************
+ * 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 "canfcadapter.h"
+
+#include "canfcinterface.h"
+#include "caqueueingthread.h"
+#include "caadapterutils.h"
+#include "camutex.h"
+#include "uarraylist.h"
+#include "caremotehandler.h"
+#include "logger.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+
+/**
+ * Logging tag for module name
+ */
+#define TAG "NFC_ADAP"
+
+/**
+ * Holds inter thread nfc data information.
+ */
+
+typedef struct
+{
+    CAEndpoint_t *remoteEndpoint;
+    void *data;
+    uint32_t dataLen;
+} CANFCData;
+
+/**
+ * Reference to threadpool.
+ */
+static ca_thread_pool_t g_nfcThreadPool = NULL;
+
+/**
+ * Queue handle for Send Data
+ */
+static CAQueueingThread_t *g_sendQueueHandle = NULL;
+
+/**
+ * Network Packet Received Callback to CA
+ */
+static CANetworkPacketReceivedCallback g_packetReceivedCallback = NULL;
+
+/**
+ *  Network Changed Callback to CA
+ */
+static CANetworkChangeCallback g_connectionStateCallback = NULL;
+
+/**
+ * error Callback to CA adapter
+ */
+static CAErrorHandleCallback g_errorCallback = NULL;
+
+static void CANFCPacketReceivedCB(const CASecureEndpoint_t *endpoint, const void *data,
+                                  uint32_t dataLength);
+#ifndef SINGLE_THREAD
+
+static CAResult_t CANFCInitializeQueueHandles();
+
+static void CANFCDeinitializeQueueHandles();
+
+static void CANFCSendDataThread(void *threadData);
+
+CANFCData *CACreateNFCData(const CAEndpoint_t *remoteEndpoint, const void *data,
+                           uint32_t dataLength);
+
+void CAFreeNFCData(CANFCData *ipData);
+
+static void CANFCDataDestroyer(void *data, uint32_t size);
+
+CAResult_t CANFCInitializeQueueHandles()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    // Check if the message queue is already initialized
+    if (g_sendQueueHandle)
+    {
+        OIC_LOG(DEBUG, TAG, "send queue handle is already initialized!");
+        return CA_STATUS_OK;
+    }
+
+    // Create send message queue
+    g_sendQueueHandle = OICCalloc(1, sizeof(*g_sendQueueHandle));
+    if (!g_sendQueueHandle)
+    {
+        OIC_LOG(ERROR, TAG, "Memory allocation failed!");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    if (CA_STATUS_OK
+        != CAQueueingThreadInitialize(g_sendQueueHandle, (const ca_thread_pool_t) g_nfcThreadPool,
+                                      CANFCSendDataThread, CANFCDataDestroyer))
+    {
+        OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
+        OICFree(g_sendQueueHandle);
+        g_sendQueueHandle = NULL;
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CANFCDeinitializeQueueHandles()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    CAQueueingThreadDestroy(g_sendQueueHandle);
+    OICFree(g_sendQueueHandle);
+    g_sendQueueHandle = NULL;
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+#endif // SINGLE_THREAD
+void CANFCConnectionStateCB(const char *nfcAddress, CANetworkStatus_t status)
+{
+    OIC_LOG(DEBUG, TAG, "Currently Not Supported");
+
+    (void)nfcAddress;
+    (void)status;
+}
+
+void CANFCPacketReceivedCB(const CASecureEndpoint_t *sep, const void *data, uint32_t dataLength)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    VERIFY_NON_NULL_VOID(sep, TAG, "endpoint is NULL");
+    VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
+
+    if (0 == dataLength)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid call, data length is 0");
+        return;
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "Address: %s, port:%d", sep->endpoint.addr, sep->endpoint.port);
+
+    if (g_packetReceivedCallback)
+    {
+        g_packetReceivedCallback(sep, data, dataLength);
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CANFCErrorHandler(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLength,
+                       CAResult_t result)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
+
+    VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
+    if (g_errorCallback)
+    {
+        g_errorCallback(endpoint, data, dataLength, result);
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CAInitializeNFC(CARegisterConnectivityCallback registerCallback,
+                           CANetworkPacketReceivedCallback packetReceivedCallback,
+                           CANetworkChangeCallback connectionStateCallback,
+                           CAErrorHandleCallback errorCallback, ca_thread_pool_t handle)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL(registerCallback, TAG, "registerCallback");
+    VERIFY_NON_NULL(packetReceivedCallback, TAG, "packetReceivedCallback");
+    VERIFY_NON_NULL(connectionStateCallback, TAG, "connectionStateCallback");
+    VERIFY_NON_NULL(handle, TAG, "thread pool handle");
+
+    g_connectionStateCallback = connectionStateCallback;
+    g_packetReceivedCallback = packetReceivedCallback;
+    g_errorCallback = errorCallback;
+
+    g_nfcThreadPool = handle;
+
+    CAResult_t result = CAInitializeNfcServer();
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, TAG, "CAInitializeNfcServer failed");
+        return result;
+    }
+
+    CANFCSetPacketReceiveCallback(CANFCPacketReceivedCB);
+    static const CAConnectivityHandler_t nfcHandler =
+        {
+            .startAdapter = CAStartNFC,
+            .stopAdapter = CAStopNFC,
+            .startListenServer = CAStartNFCListeningServer,
+            .stopListenServer = CAStopNFCListeningServer,
+            .startDiscoveryServer = CAStartNFCDiscoveryServer,
+            .sendData = CASendNFCUnicastData,
+            .sendDataToAll = CASendNFCMulticastData,
+            .GetnetInfo = CAGetNFCInterfaceInformation,
+            .readData = CAReadNFCData,
+            .terminate = CATerminateNFC,
+            .cType = CA_ADAPTER_NFC
+        };
+    registerCallback(nfcHandler);
+
+    OIC_LOG(INFO, TAG, "OUT Intialize NFC is Success");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStartNFC()
+{
+
+    OIC_LOG(DEBUG, TAG, "IN");
+    CAResult_t res = CANFCInitializeQueueHandles();
+
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to Initialize Queue Handle");
+        return res;
+    }
+
+    res = CAQueueingThreadStart(g_sendQueueHandle);
+    // Start send queue thread
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to Start Send Data Thread");
+        return res;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStartNFCListeningServer()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    CAResult_t ret = CANFCStartServer();
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "Failed to start server![%d]", ret);
+        return ret;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStopNFCListeningServer()
+{
+    CANFCStopServer();
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStartNFCDiscoveryServer()
+{
+    return CAStartNFCListeningServer();
+}
+
+static int32_t CAQueueNFCData(const CAEndpoint_t *endpoint, const void *data,
+                              uint32_t dataLength)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    VERIFY_NON_NULL_RET(endpoint, TAG, "remoteEndpoint", -1);
+    VERIFY_NON_NULL_RET(data, TAG, "data", -1);
+
+    if (0 == dataLength)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid Data Length");
+        return -1;
+    }
+
+    VERIFY_NON_NULL_RET(g_sendQueueHandle, TAG, "sendQueueHandle", -1);
+    // Create NFCData to add to queue
+    CANFCData *nfcData = CACreateNFCData(endpoint, data, dataLength);
+    if (!nfcData)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to create ipData!");
+        return -1;
+    }
+    // Add message to send queue
+    CAQueueingThreadAddData(g_sendQueueHandle, nfcData, sizeof(CANFCData));
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return dataLength;
+
+}
+
+int32_t CASendNFCUnicastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLength)
+{
+    return CAQueueNFCData(endpoint, data, dataLength);
+}
+
+int32_t CASendNFCMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLength)
+{
+    return CAQueueNFCData(endpoint, data, dataLength);
+}
+
+CAResult_t CAReadNFCData()
+{
+#if 0
+    OIC_LOG(DEBUG, TAG, "IN");
+    CANFCPullData();
+    OIC_LOG(DEBUG, TAG, "OUT");
+#endif
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStopNFC()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    if (g_sendQueueHandle && g_sendQueueHandle->threadMutex)
+    {
+        CAQueueingThreadStop(g_sendQueueHandle);
+    }
+
+    CANFCDeinitializeQueueHandles();
+
+    CANFCStopServer();
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+
+    return CA_STATUS_OK;
+}
+
+void CATerminateNFC()
+{
+
+    OIC_LOG(DEBUG, TAG, "IN");
+    CANFCSetPacketReceiveCallback(NULL);
+    CANFCDeinitializeQueueHandles();
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CANFCSendDataThread(void *threadData)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    CANFCData *nfcData = (CANFCData *) threadData;
+    if (!nfcData)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid ip data!");
+        return;
+    }
+
+    CANFCSendData(nfcData->remoteEndpoint, nfcData->data, nfcData->dataLen);
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CANFCData *CACreateNFCData(const CAEndpoint_t *remoteEndpoint, const void *data,
+                           uint32_t dataLength)
+{
+    VERIFY_NON_NULL_RET(data, TAG, "NFCData is NULL", NULL);
+
+    CANFCData *nfcData = (CANFCData *) OICCalloc(1,sizeof(*nfcData));
+    if (!nfcData)
+    {
+        OIC_LOG(ERROR, TAG, "Memory allocation failed!");
+        return NULL;
+    }
+
+    nfcData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
+    nfcData->data = (void *) OICMalloc(dataLength);
+    if (!nfcData->data)
+    {
+        OIC_LOG(ERROR, TAG, "Memory allocation failed!");
+        CAFreeNFCData(nfcData);
+        return NULL;
+    }
+
+    memcpy(nfcData->data, data, dataLength);
+    nfcData->dataLen = dataLength;
+
+    return nfcData;
+
+}
+
+void CAFreeNFCData(CANFCData *nfcData)
+{
+    if (nfcData)
+    {
+        CAFreeEndpoint(nfcData->remoteEndpoint);
+        OICFree(nfcData->data);
+        OICFree(nfcData);
+    }
+}
+
+void CANFCDataDestroyer(void *data, uint32_t size)
+{
+    CANFCData *nfcData = (CANFCData *) data;
+
+    CAFreeNFCData(nfcData);
+    (void)size;
+}
+
+CAResult_t CAGetNFCInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
+{
+    OIC_LOG(DEBUG, TAG, "CAGetNFCInterfaceInformation not supported");
+    if (!info || !size)
+    {
+        OIC_LOG(ERROR, TAG, "CAGetNFCInterfaceInformation : Invalid Input");
+        return CA_STATUS_FAILED;
+    }
+
+    return CA_STATUS_OK;
+}
index 2b077bb..3cce282 100644 (file)
@@ -25,7 +25,11 @@ print "Reading RA adapter script"
 
 target_os = env.get('TARGET_OS')
 inc_files = env.get('CPPPATH')
+with_ra_ibb = env.get('WITH_RA_IBB')
 src_dir = './ra_adapter'
 
 #Source files to build in Linux platform
 env.AppendUnique(CA_SRC=[os.path.join(src_dir, 'caraadapter.c')])
+
+if with_ra_ibb:
+       env.AppendUnique(CPPDEFINES = ['RA_ADAPTER_IBB'])
index ff84862..b34cb83 100644 (file)
 #include "logger.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
-#include "ra_xmpp.h"
 #include "caremotehandler.h"
 #include "cacommon.h"
 
+#ifdef RA_ADAPTER_IBB
+#include "caprotocolmessage.h"
+#include "xmpp_helper.h"
+#include "xmpp_utils.h"
+#include "xmpp_ibb.h"
+#include "xmpp_utils.h"
+#else
+#include "ra_xmpp.h"
+#endif
+
+#ifdef RA_ADAPTER_IBB
+#define SET_BUT_NOT_USED(x) (void) x
+/**
+ * Logging tag for module name.
+ */
+#define RA_ADAPTER_TAG "OIC_RA_ADAP_IBB"
+
+/**
+ * Network Packet Received Callback to CA.
+ */
+static CANetworkPacketReceivedCallback g_networkPacketCallback = NULL;
+
+/**
+ * Network Changed Callback to CA.
+ */
+static CANetworkChangeCallback g_networkChangeCallback = NULL;
+
+/**
+ * Holds XMPP data information.
+ */
+#define RA_MAX_HOSTNAME_LENGTH 256
+#define RA_MAX_PASSWORD_LENGTH 64
+typedef struct
+{
+    xmpp_t     *xmpp;
+    int         port;
+    char        hostName[RA_MAX_HOSTNAME_LENGTH];
+    char        password[RA_MAX_PASSWORD_LENGTH];
+    char        jid[CA_RAJABBERID_SIZE];
+    CANetworkStatus_t connectionStatus;
+    CAJidBoundCallback jidBoundCallback;
+} CARAXmppData_t;
+
+static ca_mutex g_raadapterMutex = NULL;
+
+static CARAXmppData_t g_xmppData = {.xmpp = NULL, .port = 5222, .hostName = {0},
+    .password = {0}, .jid = {0}, .connectionStatus = CA_INTERFACE_DOWN,
+    .jidBoundCallback = NULL};
+
+static void CARANotifyNetworkChange(const char *address, CANetworkStatus_t status);
+
+void CARANotifyNetworkChange(const char *address, CANetworkStatus_t status)
+{
+    OIC_LOG(DEBUG, RA_ADAPTER_TAG, "CARANotifyNetworkChange IN");
+
+    g_xmppData.connectionStatus = status;
+
+    CAEndpoint_t *localEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
+                                CA_ADAPTER_REMOTE_ACCESS,
+                                address, 0);
+    if (!localEndpoint)
+    {
+        OIC_LOG(ERROR, RA_ADAPTER_TAG, "localEndpoint creation failed!");
+        return;
+    }
+    CANetworkChangeCallback networkChangeCallback = g_networkChangeCallback;
+    if (networkChangeCallback)
+    {
+        networkChangeCallback(localEndpoint, status);
+    }
+    else
+    {
+        OIC_LOG(ERROR, RA_ADAPTER_TAG, "g_networkChangeCallback is NULL");
+    }
+
+    CAFreeEndpoint(localEndpoint);
+
+    OIC_LOG(DEBUG, RA_ADAPTER_TAG, "CARANotifyNetworkChange OUT");
+}
+
+#define MAX_IBB_SESSION_ID_LENGTH 32
+/* Ref. octypes.h */
+#define OBSERVE_REGISTER    0
+#define OBSERVE_DEREGISTER  1
+/* Ref. octypes.h */
+
+static ilist_t * g_observerList = NULL;
+
+typedef struct _obs_item_t
+{
+    char sessid[MAX_IBB_SESSION_ID_LENGTH + 1];
+    int  option;
+} obs_item_t;
+
+static bool CARAFindSessID(obs_item_t *item, char *key)
+{
+    if (item == NULL || key == NULL)
+    {
+        return false;
+    }
+    if (strcmp(item->sessid, key) == 0)
+    {
+        return true;
+    }
+    else
+    {
+        return false;
+    }
+}
+
+static bool CARAPDUIsRequest(uint32_t x)
+{
+    return (x == CA_GET || x == CA_POST || x == CA_PUT || x == CA_DELETE);
+}
+
+static void CARAUpdateObsList(int option, char *sid)
+{
+    if (option == OBSERVE_REGISTER)
+    {
+        obs_item_t *item = (obs_item_t *) OICMalloc(sizeof(*item));
+        OICStrcpy(item->sessid, sizeof(item->sessid), sid);
+        item->option = OBSERVE_REGISTER;
+        ilist_add(g_observerList, item);
+    }
+    else if (option == OBSERVE_DEREGISTER)
+    {
+        obs_item_t *item = ilist_finditem_func(g_observerList, (find_fp) CARAFindSessID, sid);
+        if (item != NULL)
+        {
+            item->option = OBSERVE_DEREGISTER;
+        }
+    }
+}
+
+static int CARAGetReqObsOption(coap_pdu_t *pdu, const CAEndpoint_t *endPoint)
+{
+    uint32_t obsopt = -1;
+
+    CARequestInfo_t *reqInfo = (CARequestInfo_t *) OICMalloc(sizeof(*reqInfo));
+    VERIFY_NON_NULL_RET(reqInfo, RA_ADAPTER_TAG, "Memory alloc of CARequestInfo_t failed!", -1);
+
+    CAResult_t result = CAGetRequestInfoFromPDU(pdu, endPoint, reqInfo);
+    if (CA_STATUS_OK != result)
+    {
+        OICFree(reqInfo);
+        OIC_LOG(ERROR, RA_ADAPTER_TAG, "Get Request Info failed!");
+        return -1;
+    }
+    if (!CARAPDUIsRequest(reqInfo->method))
+    {
+        OICFree(reqInfo);
+        OIC_LOG(DEBUG, RA_ADAPTER_TAG, "It is not a request data.");
+        return -1;
+    }
+
+    uint8_t numOpt = reqInfo->info.numOptions;
+    CAHeaderOption_t *options = reqInfo->info.options;
+    for (uint8_t i = 0; i < numOpt; i++)
+    {
+        if(options[i].protocolID == CA_COAP_ID &&
+                options[i].optionID == COAP_OPTION_OBSERVE)
+        {
+            obsopt = options[i].optionData[0];
+            break;
+        }
+    }
+    OICFree(reqInfo);
+    return obsopt;
+}
+
+static int CARAErrorCB(xmpp_ibb_session_t *sess, xmpperror_t *xerr)
+{
+    OIC_LOG_V(ERROR, RA_ADAPTER_TAG, "%s(): code(%d) tyep'%s' mesg'%s'",
+            __FUNCTION__, xerr->code, xerr->type, xerr->mesg);
+    SET_BUT_NOT_USED(sess);
+    SET_BUT_NOT_USED(xerr);
+    return 0;
+}
+
+static int CARAOpenCB(xmpp_ibb_session_t *sess, char *type)
+{
+    OIC_LOG_V(DEBUG, RA_ADAPTER_TAG, "%s(): set type '%s'", __FUNCTION__, type);
+    SET_BUT_NOT_USED(sess);
+    SET_BUT_NOT_USED(type);
+    return 0;
+}
+
+static int CARACloseCB(xmpp_ibb_session_t *sess, char *type)
+{
+    OIC_LOG_V(DEBUG, RA_ADAPTER_TAG, "%s(): set type '%s'", __FUNCTION__, type);
+    char *sid = xmpp_ibb_get_sid(sess);
+    obs_item_t *item = ilist_finditem_func(g_observerList, (find_fp) CARAFindSessID, sid);
+    if (item != NULL)
+    {
+        ilist_remove(g_observerList, item);
+        OICFree(item);
+    }
+    SET_BUT_NOT_USED(type);
+    return 0;
+}
+
+static char *CARAGetSIDFromPDU(coap_pdu_t *pdu)
+{
+    static char s_sid[MAX_IBB_SESSION_ID_LENGTH + 1] = {0};
+
+    VERIFY_NON_NULL_RET(pdu, RA_ADAPTER_TAG, "Invalid parameter!", NULL);
+
+    if (pdu->hdr->coap_hdr_udp_t.token_length * 2 > MAX_IBB_SESSION_ID_LENGTH)
+    {
+        OIC_LOG(ERROR, RA_ADAPTER_TAG, "Token length more than expected!");
+        return NULL;
+    }
+
+    char hex[3] = {0};
+    for (int i = 0; i < pdu->hdr->coap_hdr_udp_t.token_length; i++)
+    {
+        snprintf(hex, 3, "%02x", pdu->hdr->coap_hdr_udp_t.token[i]);
+        OICStrcat(s_sid, sizeof(s_sid), hex);
+    }
+
+    return s_sid;
+}
+
+static int CARARecvCB(xmpp_ibb_session_t *sess, xmppdata_t *xdata)
+{
+    if (xdata == NULL)
+    {
+        /* xdata == NULL, send ack result */
+        return 0;
+    }
+
+    char *msg = xdata->data;
+    char *from = xmpp_ibb_get_remote_jid(sess);
+    if (g_networkPacketCallback)
+    {
+        VERIFY_NON_NULL_RET(from, RA_ADAPTER_TAG, "from sender is NULL", -1);
+        VERIFY_NON_NULL_RET(msg, RA_ADAPTER_TAG, "message is NULL", -1);
+
+        OIC_LOG_V (DEBUG, RA_ADAPTER_TAG, "Message received from %s", from);
+
+        CAEndpoint_t *endPoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
+                        CA_ADAPTER_REMOTE_ACCESS, from, 0);
+        if (!endPoint)
+        {
+            OIC_LOG(ERROR, RA_ADAPTER_TAG, "EndPoint creation failed!");
+            return -1;
+        }
+        uint32_t code = CA_NOT_FOUND;
+        coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU(xdata->data, xdata->size, &code,
+            endPoint);
+        char *sid = CARAGetSIDFromPDU(pdu);
+        int obsopt = CARAGetReqObsOption(pdu, endPoint);
+        coap_delete_pdu(pdu);
+
+        if (CARAPDUIsRequest(code))
+        {
+            OIC_LOG(DEBUG, RA_ADAPTER_TAG, "this is a request data");
+            if (obsopt == OBSERVE_DEREGISTER || obsopt == OBSERVE_REGISTER)
+            {
+                CARAUpdateObsList(obsopt, sid);
+            }
+        }
+        else
+        {
+            OIC_LOG(DEBUG, RA_ADAPTER_TAG, "this is a response data");
+            obs_item_t *item = ilist_finditem_func(g_observerList, (find_fp) CARAFindSessID, sid);
+            if (item != NULL)
+            {
+                if (item->option == OBSERVE_DEREGISTER)
+                {
+                    xmpp_ibb_close(sess);
+                    ilist_remove(g_observerList, item);
+                    OICFree(item);
+                }
+            }
+            else
+            {
+                xmpp_ibb_close(sess);
+            }
+        }
+
+        void *buf = NULL;
+        xmpp_ibb_userdata_alloc(sess, &buf, xdata->size);
+        if (!buf)
+        {
+            OIC_LOG(ERROR, RA_ADAPTER_TAG, "Memory alloc of message failed!");
+            CAFreeEndpoint(endPoint);
+            return -1;
+        }
+        memcpy(buf, xdata->data, xdata->size);
+        CASecureEndpoint_t sep =
+        {.endpoint = {.adapter = CA_ADAPTER_IP, .flags = CA_DEFAULT_FLAGS}};
+        memcpy(&sep.endpoint, endPoint, sizeof(sep.endpoint));
+        g_networkPacketCallback(&sep, buf, xdata->size);
+
+        CAFreeEndpoint (endPoint);
+    }
+    else
+    {
+        OIC_LOG(ERROR, RA_ADAPTER_TAG, "No callback for RA received message found");
+    }
+    return 0;
+}
+
+static int CARAConnHandler(xmpp_t *xmpp, xmppconn_info_t *conninfo, void *udata)
+{
+    if (conninfo->connevent != 0)
+    {
+        OIC_LOG_V(ERROR, RA_ADAPTER_TAG, " status(%d) error(%d) errorType(%d) errorText '%s'\n",
+                conninfo->connevent, conninfo->error, conninfo->errortype,
+                conninfo->errortext);
+        CARANotifyNetworkChange(g_xmppData.jid, CA_INTERFACE_DOWN);
+        return -1;
+    }
+    OIC_LOG_V(DEBUG, RA_ADAPTER_TAG, "Bound JID: '%s'", xmpphelper_get_bound_jid(xmpp));
+    if (g_xmppData.jidBoundCallback != NULL)
+    {
+        g_xmppData.jidBoundCallback((char *) xmpphelper_get_bound_jid(xmpp));
+    }
+    CARANotifyNetworkChange(xmpphelper_get_bound_jid(xmpp), CA_INTERFACE_UP);
+    VERIFY_NON_NULL_RET(udata, RA_ADAPTER_TAG, "Invalid parameter!", 0);
+    return 0;
+}
+
+CAResult_t CAInitializeRA(CARegisterConnectivityCallback registerCallback,
+                                CANetworkPacketReceivedCallback networkPacketCallback,
+                                CANetworkChangeCallback netCallback, ca_thread_pool_t handle)
+{
+    OIC_LOG(DEBUG, RA_ADAPTER_TAG, "CAInitializeRA IN");
+    if (!registerCallback || !networkPacketCallback || !netCallback || !handle)
+    {
+        OIC_LOG(ERROR, RA_ADAPTER_TAG, "Invalid parameter!");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    g_networkChangeCallback = netCallback;
+    g_networkPacketCallback = networkPacketCallback;
+
+    CAConnectivityHandler_t raHandler = {
+        .startAdapter = CAStartRA,
+        .stopAdapter = CAStopRA,
+        .startListenServer = CAStartRAListeningServer,
+        .startDiscoveryServer = CAStartRADiscoveryServer,
+        .sendData = CASendRAUnicastData,
+        .sendDataToAll = CASendRAMulticastData,
+        .GetnetInfo = CAGetRAInterfaceInformation,
+        .readData = CAReadRAData,
+        .terminate = CATerminateRA,
+        .cType = CA_ADAPTER_REMOTE_ACCESS};
+
+    registerCallback(raHandler);
+#ifdef NDEBUG
+    xmpp_log_t *log = xmpp_get_default_logger(XMPP_LEVEL_ERROR);
+#else
+    xmpp_log_t *log = xmpp_get_default_logger(XMPP_LEVEL_DEBUG);
+#endif
+    g_xmppData.xmpp = xmpphelper_new(CARAConnHandler, NULL, log, NULL);
+    xmpphelper_force_tls(g_xmppData.xmpp);
+    g_observerList = ilist_new();
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CASetRAInfo(const CARAInfo_t *caraInfo)
+{
+    if (!caraInfo)
+    {
+        OIC_LOG(ERROR, RA_ADAPTER_TAG, "Invalid parameter!");
+        return CA_STATUS_INVALID_PARAM;
+    }
+    if (caraInfo->hostName != NULL)
+    {
+        OICStrcpy(g_xmppData.hostName, sizeof(g_xmppData.hostName), caraInfo->hostName);
+    }
+    else
+    {
+        OIC_LOG(ERROR, RA_ADAPTER_TAG, "Invalid parameter!");
+        return CA_STATUS_INVALID_PARAM;
+    }
+    if (caraInfo->userName != NULL && strlen(caraInfo->userName) != 0)
+    {
+        OICStrcpy(g_xmppData.jid, sizeof(g_xmppData.jid), caraInfo->userName);
+    }
+    else
+    {
+        OIC_LOG(ERROR, RA_ADAPTER_TAG, "Invalid parameter!");
+        return CA_STATUS_INVALID_PARAM;
+    }
+    if (caraInfo->xmppDomain != NULL && strlen(caraInfo->xmppDomain) != 0)
+    {
+        OICStrcat(g_xmppData.jid, sizeof(g_xmppData.jid), "@");
+        OICStrcat(g_xmppData.jid, sizeof(g_xmppData.jid), caraInfo->xmppDomain);
+        if (caraInfo->resource != NULL && strlen(caraInfo->resource) != 0)
+        {
+            OICStrcat(g_xmppData.jid, sizeof(g_xmppData.jid), "/");
+            OICStrcat(g_xmppData.jid, sizeof(g_xmppData.jid), caraInfo->resource);
+        }
+    }
+    if (caraInfo->password != NULL)
+    {
+        OICStrcpy(g_xmppData.password, sizeof(g_xmppData.password), caraInfo->password);
+    }
+    g_xmppData.port = caraInfo->port;
+    g_xmppData.jidBoundCallback = caraInfo->jidBoundCallback;
+
+    return CA_STATUS_OK;
+}
+
+void CATerminateRA()
+{
+    CAStopRA();
+    ilist_destroy(g_observerList);
+    xmpphelper_join(g_xmppData.xmpp);
+    xmpphelper_release(g_xmppData.xmpp);
+    g_xmppData.xmpp = NULL;
+}
+
+CAResult_t CAStartRA()
+{
+    OIC_LOG(DEBUG, RA_ADAPTER_TAG, PCF("Starting RA adapter"));
+
+    if (!g_xmppData.xmpp)
+    {
+        OIC_LOG (ERROR, RA_ADAPTER_TAG, "CAStartRA(): g_xmppData.xmpp == NULL");
+        return CA_STATUS_FAILED;
+    }
+
+    g_raadapterMutex = ca_mutex_new ();
+    if (!g_raadapterMutex)
+    {
+        OIC_LOG (ERROR, RA_ADAPTER_TAG, PCF("Memory allocation for mutex failed."));
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    ca_mutex_lock (g_raadapterMutex);
+
+    xmpphelper_connect(g_xmppData.xmpp, g_xmppData.hostName, g_xmppData.port,
+                    g_xmppData.jid, g_xmppData.password);
+    xmpp_ibb_reg_funcs_t regfuncs;
+    regfuncs.open_cb = CARAOpenCB;
+    regfuncs.close_cb = CARACloseCB;
+    regfuncs.recv_cb = CARARecvCB;
+    regfuncs.error_cb = CARAErrorCB;
+    xmpp_ibb_register(xmpphelper_get_conn(g_xmppData.xmpp), &regfuncs);
+
+    xmpphelper_run(g_xmppData.xmpp);
+
+    ca_mutex_unlock (g_raadapterMutex);
+
+    OIC_LOG(DEBUG, RA_ADAPTER_TAG, "RA adapter started succesfully");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStopRA()
+{
+    OIC_LOG(DEBUG, RA_ADAPTER_TAG, PCF("Stopping RA adapter"));
+
+    xmpphelper_stop(g_xmppData.xmpp);
+    xmpp_ibb_unregister(xmpphelper_get_conn(g_xmppData.xmpp));
+    if (!g_raadapterMutex)
+    {
+        ca_mutex_free (g_raadapterMutex);
+        g_raadapterMutex = NULL;
+    }
+    OIC_LOG(DEBUG, RA_ADAPTER_TAG, PCF("Stopped RA adapter successfully"));
+    return CA_STATUS_OK;
+}
+
+int32_t CASendRAUnicastData(const CAEndpoint_t *remoteEndpoint, const void *data,
+                                  uint32_t dataLength)
+{
+    if (!remoteEndpoint || !data)
+    {
+        OIC_LOG(ERROR, RA_ADAPTER_TAG, "Invalid parameter!");
+        return -1;
+    }
+
+    if (0 == dataLength)
+    {
+        OIC_LOG(ERROR, RA_ADAPTER_TAG, "Data length is 0!");
+        return 0;
+    }
+    OIC_LOG_V(DEBUG, RA_ADAPTER_TAG, "Sending unicast data to %s", remoteEndpoint->addr);
+
+    uint32_t code = CA_NOT_FOUND;
+    coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU(data, dataLength, &code, remoteEndpoint);
+    char *sid = CARAGetSIDFromPDU(pdu);
+    int obsopt = CARAGetReqObsOption(pdu, remoteEndpoint);
+    coap_delete_pdu(pdu);
+
+    ca_mutex_lock (g_raadapterMutex);
+    if (CA_INTERFACE_UP != g_xmppData.connectionStatus)
+    {
+        OIC_LOG(ERROR, RA_ADAPTER_TAG, "Unable to send XMPP message, RA not connected");
+        ca_mutex_unlock (g_raadapterMutex);
+        return -1;
+    }
+
+    xmpp_ibb_session_t *sess = xmpp_ibb_get_session_by_sid(sid);
+    if (sess == NULL)
+    {
+        sess = xmpp_ibb_open(xmpphelper_get_conn(g_xmppData.xmpp), (char * const) remoteEndpoint->addr, sid);
+        if (sess == NULL)
+        {
+            OIC_LOG(ERROR, RA_ADAPTER_TAG, "IBB session establish failed!");
+            ca_mutex_unlock (g_raadapterMutex);
+            return -1;
+        }
+    }
+    if (CARAPDUIsRequest(code))
+    {
+        if (obsopt == OBSERVE_REGISTER || obsopt == OBSERVE_DEREGISTER)
+        {
+            CARAUpdateObsList(obsopt, sid);
+        }
+    }
+    xmppdata_t xdata = {.data = (char *) data, .size = dataLength};
+    int rc = xmpp_ibb_send_data(sess, &xdata);
+    ca_mutex_unlock (g_raadapterMutex);
+    if (rc < 0)
+    {
+        OIC_LOG(ERROR, RA_ADAPTER_TAG, "IBB send data failed!");
+        return -1;
+    }
+
+    OIC_LOG_V(INFO, RA_ADAPTER_TAG, "Successfully dispatched bytes[%d] to addr[%s]",
+            dataLength, remoteEndpoint->addr);
+
+    return dataLength;
+}
+
+CAResult_t CAGetRAInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
+{
+    VERIFY_NON_NULL(info, RA_ADAPTER_TAG, "info is NULL");
+    VERIFY_NON_NULL(size, RA_ADAPTER_TAG, "size is NULL");
+    return CA_STATUS_OK;
+}
+
+int32_t CASendRAMulticastData(const CAEndpoint_t *endpoint,
+                    const void *data, uint32_t dataLength)
+{
+    OIC_LOG(INFO, RA_ADAPTER_TAG, "RA adapter does not support sending multicast data");
+    SET_BUT_NOT_USED(endpoint);
+    SET_BUT_NOT_USED(data);
+    SET_BUT_NOT_USED(dataLength);
+    return 0;
+}
+
+CAResult_t CAStartRAListeningServer()
+{
+    OIC_LOG(INFO, RA_ADAPTER_TAG, "RA adapter does not support listening for multicast data");
+    return CA_NOT_SUPPORTED;
+}
+
+CAResult_t CAStartRADiscoveryServer()
+{
+    OIC_LOG(INFO, RA_ADAPTER_TAG, "RA adapter does not support discovery of multicast servers");
+    return CA_NOT_SUPPORTED;
+}
+
+CAResult_t CAReadRAData()
+{
+    OIC_LOG(INFO, RA_ADAPTER_TAG, "Read data is not implemented for the RA adapter");
+    return CA_NOT_SUPPORTED;
+}
+
+#else /* #ifdef RA_ADAPTER_IBB */
+
 /**
  * Logging tag for module name.
  */
@@ -228,18 +795,19 @@ CAResult_t CAInitializeRA(CARegisterConnectivityCallback registerCallback,
     g_networkChangeCallback = netCallback;
     g_networkPacketCallback = networkPacketCallback;
 
-    CAConnectivityHandler_t raHandler = {};
-    raHandler.startAdapter = CAStartRA;
-    raHandler.startListenServer = CAStartRAListeningServer;
-    raHandler.stopListenServer = CAStopRAListeningServer;
-    raHandler.startDiscoveryServer = CAStartRADiscoveryServer;
-    raHandler.sendData = CASendRAUnicastData;
-    raHandler.sendDataToAll = CASendRAMulticastData;
-    raHandler.GetnetInfo = CAGetRAInterfaceInformation;
-    raHandler.readData = CAReadRAData;
-    raHandler.stopAdapter = CAStopRA;
-    raHandler.terminate = CATerminateRA;
-    registerCallback(raHandler, CA_ADAPTER_REMOTE_ACCESS);
+    CAConnectivityHandler_t raHandler = {
+        .startAdapter = CAStartRA,
+        .stopAdapter = CAStopRA,
+        .startListenServer = CAStartRAListeningServer,
+        .stopListenServer = CAStopRAListeningServer,
+        .startDiscoveryServer = CAStartRADiscoveryServer,
+        .sendData = CASendRAUnicastData,
+        .sendDataToAll = CASendRAMulticastData,
+        .GetnetInfo = CAGetRAInterfaceInformation,
+        .readData = CAReadRAData,
+        .terminate = CATerminateRA,
+        .cType = CA_ADAPTER_REMOTE_ACCESS};
+    registerCallback(raHandler);
 
     return CA_STATUS_OK;
 }
@@ -428,3 +996,4 @@ CAResult_t CAReadRAData()
     OIC_LOG(INFO, RA_ADAPTER_TAG, "Read data is not implemented for the RA adapter");
     return CA_NOT_SUPPORTED;
 }
+#endif
index d2dcf44..df48527 100644 (file)
@@ -15,7 +15,7 @@ src_dir = './tcp_adapter/'
 
 # Source files to build common for all platforms
 common_files = None
-if target_os in ['linux', 'tizen']:
+if target_os in ['linux', 'tizen', 'android']:
     common_files = [
         os.path.join(src_dir, 'catcpadapter.c'),
         os.path.join(src_dir, 'catcpserver.c') ]
index 31eca32..1108877 100644 (file)
 #include <string.h>
 #include <stdint.h>
 
+#ifndef __STDC_FORMAT_MACROS
+#define __STDC_FORMAT_MACROS
+#endif
+#include <inttypes.h>
+
+#include "cainterface.h"
 #include "catcpadapter.h"
 #include "catcpinterface.h"
 #include "caqueueingthread.h"
@@ -37,7 +43,7 @@
 /**
  * Logging tag for module name.
  */
-#define TAG "TCP_ADAP"
+#define TAG "OIC_CA_TCP_ADAP"
 
 /**
  * Holds internal thread TCP data information.
@@ -50,10 +56,10 @@ typedef struct
     bool isMulticast;
 } CATCPData;
 
-#define CA_TCP_TIMEOUT 1000
-
 #define CA_TCP_LISTEN_BACKLOG  3
 
+#define CA_TCP_SELECT_TIMEOUT 10
+
 /**
  * Queue handle for Send Data.
  */
@@ -74,8 +80,18 @@ static CANetworkChangeCallback g_networkChangeCallback = NULL;
  */
 static CAErrorHandleCallback g_errorCallback = NULL;
 
-static void CATCPPacketReceivedCB(const CAEndpoint_t *endpoint,
-                                  const void *data, size_t dataLength);
+static void CATCPPacketReceivedCB(const CASecureEndpoint_t *sep,
+                                  const void *data, uint32_t dataLength);
+
+/**
+ * KeepAlive Connected Callback to CA adapter.
+ */
+static CAKeepAliveConnectedCallback g_connCallback = NULL;
+
+/**
+ * KeepAlive Disconnected Callback to CA adapter.
+ */
+static CAKeepAliveDisconnectedCallback g_disconnCallback = NULL;
 
 static CAResult_t CATCPInitializeQueueHandles();
 
@@ -88,12 +104,10 @@ static CATCPData *CACreateTCPData(const CAEndpoint_t *remoteEndpoint,
                                   bool isMulticast);
 void CAFreeTCPData(CATCPData *ipData);
 
-static void CADataDestroyer(void *data, size_t size);
+static void CADataDestroyer(void *data, uint32_t size);
 
 CAResult_t CATCPInitializeQueueHandles()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     // Check if the message queue is already initialized
     if (g_sendQueueHandle)
     {
@@ -119,65 +133,76 @@ CAResult_t CATCPInitializeQueueHandles()
         return CA_STATUS_FAILED;
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
 
 void CATCPDeinitializeQueueHandles()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     CAQueueingThreadDestroy(g_sendQueueHandle);
     OICFree(g_sendQueueHandle);
     g_sendQueueHandle = NULL;
-
-    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 void CATCPConnectionStateCB(const char *ipAddress, CANetworkStatus_t status)
 {
     (void)ipAddress;
     (void)status;
-    OIC_LOG(DEBUG, TAG, "IN");
 }
 
-void CATCPPacketReceivedCB(const CAEndpoint_t *endpoint, const void *data,
-                           size_t dataLength)
+void CATCPPacketReceivedCB(const CASecureEndpoint_t *sep, const void *data,
+                           uint32_t dataLength)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
-    VERIFY_NON_NULL_VOID(endpoint, TAG, "ipAddress is NULL");
+    VERIFY_NON_NULL_VOID(sep, TAG, "sep is NULL");
     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
 
-    OIC_LOG_V(DEBUG, TAG, "Address: %s, port:%d", endpoint->addr, endpoint->port);
+    OIC_LOG_V(DEBUG, TAG, "Address: %s, port:%d", sep->endpoint.addr, sep->endpoint.port);
 
     if (g_networkPacketCallback)
     {
-        g_networkPacketCallback(endpoint, data, dataLength);
+        g_networkPacketCallback(sep, data, dataLength);
     }
-    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 void CATCPErrorHandler(const CAEndpoint_t *endpoint, const void *data,
-                       size_t dataLength, CAResult_t result)
+                       uint32_t dataLength, CAResult_t result)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
-
     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
 
     if (g_errorCallback)
     {
         g_errorCallback(endpoint, data, dataLength, result);
     }
+}
+
+static void CATCPKeepAliveHandler(const char *addr, uint16_t port, bool isConnected)
+{
+    CAEndpoint_t endpoint = { .adapter =  CA_ADAPTER_TCP,
+                              .port = port };
+    OICStrcpy(endpoint.addr, sizeof(endpoint.addr), addr);
 
-    OIC_LOG(DEBUG, TAG, "OUT");
+    if (isConnected)
+    {
+        g_connCallback(&endpoint);
+    }
+    else
+    {
+        g_disconnCallback(&endpoint);
+    }
+}
+
+void CATCPSetKeepAliveCallbacks(CAKeepAliveConnectedCallback ConnHandler,
+                                CAKeepAliveDisconnectedCallback DisconnHandler)
+{
+    g_connCallback = ConnHandler;
+    g_disconnCallback = DisconnHandler;
+
+    CATCPSetKeepAliveCallback(CATCPKeepAliveHandler);
 }
 
 static void CAInitializeTCPGlobals()
 {
-    caglobals.tcp.selectTimeout = CA_TCP_TIMEOUT;
+    caglobals.tcp.selectTimeout = CA_TCP_SELECT_TIMEOUT;
     caglobals.tcp.listenBacklog = CA_TCP_LISTEN_BACKLOG;
     caglobals.tcp.svrlist = NULL;
 
@@ -215,7 +240,7 @@ CAResult_t CAInitializeTCP(CARegisterConnectivityCallback registerCallback,
     CATCPSetPacketReceiveCallback(CATCPPacketReceivedCB);
     CATCPSetErrorHandler(CATCPErrorHandler);
 
-    CAConnectivityHandler_t TCPHandler = {
+    CAConnectivityHandler_t tcpHandler = {
         .startAdapter = CAStartTCP,
         .startListenServer = CAStartTCPListeningServer,
         .stopListenServer = CAStopTCPListeningServer,
@@ -225,8 +250,10 @@ CAResult_t CAInitializeTCP(CARegisterConnectivityCallback registerCallback,
         .GetnetInfo = CAGetTCPInterfaceInformation,
         .readData = CAReadTCPData,
         .stopAdapter = CAStopTCP,
-        .terminate = CATerminateTCP };
-    registerCallback(TCPHandler, CA_ADAPTER_TCP);
+        .terminate = CATerminateTCP,
+        .cType = CA_ADAPTER_TCP};
+
+    registerCallback(tcpHandler);
 
     OIC_LOG(INFO, TAG, "OUT IntializeTCP is Success");
     return CA_STATUS_OK;
@@ -234,8 +261,6 @@ CAResult_t CAInitializeTCP(CARegisterConnectivityCallback registerCallback,
 
 CAResult_t CAStartTCP()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     if (CA_STATUS_OK != CATCPInitializeQueueHandles())
     {
         OIC_LOG(ERROR, TAG, "Failed to Initialize Queue Handle");
@@ -250,47 +275,52 @@ CAResult_t CAStartTCP()
         return CA_STATUS_FAILED;
     }
 
-    CAResult_t ret = CATCPStartServer((const ca_thread_pool_t)caglobals.tcp.threadpool);
-    if (CA_STATUS_OK != ret)
-    {
-        OIC_LOG_V(ERROR, TAG, "Failed to start server![%d]", ret);
-        return ret;
-    }
-
-    OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
 
 CAResult_t CAStartTCPListeningServer()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
+    if (!caglobals.server)
+    {
+        caglobals.server = true;    // only needed to run CA tests
+    }
+
+    CAResult_t ret = CATCPStartServer((const ca_thread_pool_t)caglobals.tcp.threadpool);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "Failed to start listening server![%d]", ret);
+        return ret;
+    }
 
-    OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
 
 CAResult_t CAStopTCPListeningServer()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
-    OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
 
 CAResult_t CAStartTCPDiscoveryServer()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
+    if (!caglobals.client)
+    {
+        caglobals.client = true;    // only needed to run CA tests
+    }
+
+    CAResult_t ret = CATCPStartServer((const ca_thread_pool_t)caglobals.tcp.threadpool);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "Failed to start discovery server![%d]", ret);
+        return ret;
+    }
 
-    OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
 
 static size_t CAQueueTCPData(bool isMulticast, const CAEndpoint_t *endpoint,
                              const void *data, size_t dataLength)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
-    VERIFY_NON_NULL_RET(endpoint, TAG, "remoteEndpoint", -1);
+    VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", -1);
     VERIFY_NON_NULL_RET(data, TAG, "data", -1);
 
     if (0 == dataLength)
@@ -302,80 +332,67 @@ static size_t CAQueueTCPData(bool isMulticast, const CAEndpoint_t *endpoint,
     VERIFY_NON_NULL_RET(g_sendQueueHandle, TAG, "sendQueueHandle", -1);
 
     // Create TCPData to add to queue
-    CATCPData *TCPData = CACreateTCPData(endpoint, data, dataLength, isMulticast);
-    if (!TCPData)
+    CATCPData *tcpData = CACreateTCPData(endpoint, data, dataLength, isMulticast);
+    if (!tcpData)
     {
         OIC_LOG(ERROR, TAG, "Failed to create ipData!");
         return -1;
     }
     // Add message to send queue
-    CAQueueingThreadAddData(g_sendQueueHandle, TCPData, sizeof(CATCPData));
+    CAQueueingThreadAddData(g_sendQueueHandle, tcpData, sizeof(CATCPData));
 
-    OIC_LOG(DEBUG, TAG, "OUT");
     return dataLength;
 }
 
 int32_t CASendTCPUnicastData(const CAEndpoint_t *endpoint,
                              const void *data, uint32_t dataLength)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
     return CAQueueTCPData(false, endpoint, data, dataLength);
 }
 
 int32_t CASendTCPMulticastData(const CAEndpoint_t *endpoint,
                                const void *data, uint32_t dataLength)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
     return CAQueueTCPData(true, endpoint, data, dataLength);
 }
 
 CAResult_t CAReadTCPData()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-    OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
 
 CAResult_t CAStopTCP()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     if (g_sendQueueHandle && g_sendQueueHandle->threadMutex)
     {
         CAQueueingThreadStop(g_sendQueueHandle);
     }
 
-    CATCPDeinitializeQueueHandles();
-
     CATCPStopServer();
 
-    OIC_LOG(DEBUG, TAG, "OUT");
+    //Re-initializing the Globals to start them again
+    CAInitializeTCPGlobals();
+
     return CA_STATUS_OK;
 }
 
 void CATerminateTCP()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     CATCPSetPacketReceiveCallback(NULL);
 
     CATCPDeinitializeQueueHandles();
-
-    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 void CATCPSendDataThread(void *threadData)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
-    CATCPData *TCPData = (CATCPData *) threadData;
-    if (!TCPData)
+    CATCPData *tcpData = (CATCPData *) threadData;
+    if (!tcpData)
     {
         OIC_LOG(DEBUG, TAG, "Invalid TCP data!");
         return;
     }
 
-    if (TCPData->isMulticast)
+    if (tcpData->isMulticast)
     {
         //Processing for sending multicast
         OIC_LOG(DEBUG, TAG, "Send Multicast Data is called, not supported");
@@ -384,55 +401,54 @@ void CATCPSendDataThread(void *threadData)
     else
     {
         //Processing for sending unicast
-        CATCPSendData(TCPData->remoteEndpoint, TCPData->data, TCPData->dataLen, false);
+        CATCPSendData(tcpData->remoteEndpoint, tcpData->data, tcpData->dataLen, false);
     }
-
-    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 CATCPData *CACreateTCPData(const CAEndpoint_t *remoteEndpoint, const void *data,
                            size_t dataLength, bool isMulticast)
 {
-    VERIFY_NON_NULL_RET(data, TAG, "TCPData is NULL", NULL);
+    VERIFY_NON_NULL_RET(remoteEndpoint, TAG, "remoteEndpoint is NULL", NULL);
+    VERIFY_NON_NULL_RET(data, TAG, "data is NULL", NULL);
 
-    CATCPData *TCPData = (CATCPData *) OICMalloc(sizeof(CATCPData));
-    if (!TCPData)
+    CATCPData *tcpData = (CATCPData *) OICCalloc(1, sizeof(*tcpData));
+    if (!tcpData)
     {
         OIC_LOG(ERROR, TAG, "Memory allocation failed!");
         return NULL;
     }
 
-    TCPData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
-    TCPData->data = (void *) OICMalloc(dataLength);
-    if (!TCPData->data)
+    tcpData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
+    tcpData->data = (void *) OICMalloc(dataLength);
+    if (!tcpData->data)
     {
         OIC_LOG(ERROR, TAG, "Memory allocation failed!");
-        CAFreeTCPData(TCPData);
+        CAFreeTCPData(tcpData);
         return NULL;
     }
 
-    memcpy(TCPData->data, data, dataLength);
-    TCPData->dataLen = dataLength;
+    memcpy(tcpData->data, data, dataLength);
+    tcpData->dataLen = dataLength;
 
-    TCPData->isMulticast = isMulticast;
+    tcpData->isMulticast = isMulticast;
 
-    return TCPData;
+    return tcpData;
 }
 
-void CAFreeTCPData(CATCPData *TCPData)
+void CAFreeTCPData(CATCPData *tcpData)
 {
-    VERIFY_NON_NULL_VOID(TCPData, TAG, "TCPData is NULL");
+    VERIFY_NON_NULL_VOID(tcpData, TAG, "tcpData is NULL");
 
-    CAFreeEndpoint(TCPData->remoteEndpoint);
-    OICFree(TCPData->data);
-    OICFree(TCPData);
+    CAFreeEndpoint(tcpData->remoteEndpoint);
+    OICFree(tcpData->data);
+    OICFree(tcpData);
 }
 
-void CADataDestroyer(void *data, size_t size)
+void CADataDestroyer(void *data, uint32_t size)
 {
     if (size < sizeof(CATCPData))
     {
-        OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %d", data, size);
+        OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %" PRIu32, data, size);
     }
     CATCPData *TCPData = (CATCPData *) data;
 
index b0fca46..5334502 100644 (file)
@@ -1,4 +1,4 @@
-/* ****************************************************************j
+/* ****************************************************************
  *
  * Copyright 2015 Samsung Electronics All Rights Reserved.
  *
@@ -48,7 +48,7 @@
 /**
  * Logging tag for module name.
  */
-#define TAG "TCP_SERVER"
+#define TAG "OIC_CA_TCP_SERVER"
 
 /**
  * Server port number for local test.
 #define TCP_MAX_HEADER_LEN  6
 
 /**
- * Default Thread Counts in TCP adapter
- */
-#define CA_TCP_DEFAULT_THREAD_COUNTS    2
-
-/**
  * Accept server file descriptor.
  */
 static int g_acceptServerFD = -1;
@@ -82,11 +77,6 @@ static ca_mutex g_mutexObjectList = NULL;
 static ca_cond g_condObjectList = NULL;
 
 /**
- * Maintains the current running thread counts.
- */
-static uint32_t g_threadCounts = CA_TCP_DEFAULT_THREAD_COUNTS;
-
-/**
  * Maintains the callback to be notified when data received from remote device.
  */
 static CATCPPacketReceivedCallback g_packetReceivedCallback;
@@ -96,17 +86,26 @@ static CATCPPacketReceivedCallback g_packetReceivedCallback;
  */
 static CATCPErrorHandleCallback g_TCPErrorHandler = NULL;
 
+/**
+ * Connected Callback to pass the connection information to RI.
+ */
+static CATCPKeepAliveHandleCallback g_keepaliveCallback = NULL;
+
 static CAResult_t CATCPCreateMutex();
 static void CATCPDestroyMutex();
 static CAResult_t CATCPCreateCond();
 static void CATCPDestroyCond();
-static void CAAcceptHandler(void *data);
+static CAResult_t CACreateAcceptSocket();
+static void CAAcceptConnection();
+static void CAFindReadyMessage();
+static void CASelectReturned(fd_set *readFds, int ret);
+static void CAReceiveMessage(int fd);
 static void CAReceiveHandler(void *data);
-static CAResult_t CAReceiveMessage();
-static int CASetNonblocking(int fd);
-static int CATCPCreateSocket(int family, CATCPServerInfo_t *TCPServerInfo);
-static size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer);
-static void CATCPDisconnectAll();
+static int CATCPCreateSocket(int family, CATCPSessionInfo_t *tcpServerInfo);
+
+#define CHECKFD(FD) \
+    if (FD > caglobals.tcp.maxfd) \
+        caglobals.tcp.maxfd = FD;
 
 static void CATCPDestroyMutex()
 {
@@ -155,189 +154,250 @@ static CAResult_t CATCPCreateCond()
     return CA_STATUS_OK;
 }
 
-static void CATCPDisconnectAll()
+static void CAReceiveHandler(void *data)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
+    (void)data;
+    OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");
+
+    while (!caglobals.tcp.terminate)
+    {
+        CAFindReadyMessage();
+    }
 
     ca_mutex_lock(g_mutexObjectList);
-    uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
+    ca_cond_signal(g_condObjectList);
+    ca_mutex_unlock(g_mutexObjectList);
 
-    CATCPServerInfo_t *svritem = NULL;
+    OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
+}
+
+static void CAFindReadyMessage()
+{
+    fd_set readFds;
+    struct timeval timeout = { .tv_sec = caglobals.tcp.selectTimeout };
+
+    FD_ZERO(&readFds);
+
+    if (-1 != g_acceptServerFD)
+    {
+        FD_SET(g_acceptServerFD, &readFds);
+    }
+    if (-1 != caglobals.tcp.shutdownFds[0])
+    {
+        FD_SET(caglobals.tcp.shutdownFds[0], &readFds);
+    }
+    if (-1 != caglobals.tcp.connectionFds[0])
+    {
+        FD_SET(caglobals.tcp.connectionFds[0], &readFds);
+    }
+
+    uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
     for (size_t i = 0; i < length; i++)
     {
-        svritem = (CATCPServerInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
-        if (svritem && svritem->u4tcp.fd >= 0)
+        CATCPSessionInfo_t *svritem =
+                (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
+        if (svritem && 0 <= svritem->fd)
         {
-            shutdown(svritem->u4tcp.fd, SHUT_RDWR);
-            close(svritem->u4tcp.fd);
+            FD_SET(svritem->fd, &readFds);
         }
     }
-    u_arraylist_destroy(caglobals.tcp.svrlist);
-    caglobals.tcp.svrlist = NULL;
-    ca_mutex_unlock(g_mutexObjectList);
 
-    OIC_LOG(DEBUG, TAG, "OUT");
+    int ret = select(caglobals.tcp.maxfd + 1, &readFds, NULL, NULL, &timeout);
+
+    if (caglobals.tcp.terminate)
+    {
+        OIC_LOG_V(DEBUG, TAG, "Packet receiver Stop request received.");
+        return;
+    }
+    if (0 >= ret)
+    {
+        if (0 > ret)
+        {
+            OIC_LOG_V(FATAL, TAG, "select error %s", strerror(errno));
+        }
+        return;
+    }
+
+    CASelectReturned(&readFds, ret);
 }
 
-static void CAReceiveHandler(void *data)
+static void CASelectReturned(fd_set *readFds, int ret)
 {
-    (void)data;
-    OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");
+    (void)ret;
 
-    while (!caglobals.tcp.terminate)
+    if (g_acceptServerFD != -1 && FD_ISSET(g_acceptServerFD, readFds))
     {
-        CAReceiveMessage();
+        CAAcceptConnection();
+        return;
     }
-
-    ca_mutex_lock(g_mutexObjectList);
-    // notify the thread
-    g_threadCounts--;
-    if (!g_threadCounts)
+    else if (-1 != caglobals.tcp.connectionFds[0] &&
+            FD_ISSET(caglobals.tcp.connectionFds[0], readFds))
     {
-        ca_cond_signal(g_condObjectList);
+        // new connection was created from remote device.
+        // exit the function to update read file descriptor.
+        char buf[MAX_ADDR_STR_SIZE_CA] = {0};
+        ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
+        if (-1 == len)
+        {
+            return;
+        }
+        OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
+        FD_CLR(caglobals.tcp.connectionFds[0], readFds);
+        return;
+    }
+    else
+    {
+        uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
+        for (size_t i = 0; i < length; i++)
+        {
+            CATCPSessionInfo_t *svritem =
+                    (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
+            if (svritem && svritem->fd >= 0)
+            {
+                if (FD_ISSET(svritem->fd, readFds))
+                {
+                    CAReceiveMessage(svritem->fd);
+                    FD_CLR(svritem->fd, readFds);
+                }
+            }
+        }
     }
-    ca_mutex_unlock(g_mutexObjectList);
-
-    OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
 }
 
-static size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
+static void CAAcceptConnection()
 {
-    OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
+    struct sockaddr_storage clientaddr;
+    socklen_t clientlen = sizeof (struct sockaddr_in);
 
-    coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
-            ((unsigned char *)recvBuffer)[0] >> 4);
-    size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
-                                                        transport);
-    size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
+    int sockfd = accept(g_acceptServerFD, (struct sockaddr *)&clientaddr,
+                        &clientlen);
+    if (-1 != sockfd)
+    {
+        CATCPSessionInfo_t *svritem =
+                (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
+        if (!svritem)
+        {
+            OIC_LOG(ERROR, TAG, "Out of memory");
+            close(sockfd);
+            return;
+        }
 
-    OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%d]", optPaylaodLen);
-    OIC_LOG_V(DEBUG, TAG, "header length [%d]", headerLen);
-    OIC_LOG_V(DEBUG, TAG, "total data length [%d]", headerLen + optPaylaodLen);
+        svritem->fd = sockfd;
+        CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
+                            (char *) &svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
 
-    OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
-    return headerLen + optPaylaodLen;
+        ca_mutex_lock(g_mutexObjectList);
+        bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
+        if (!result)
+        {
+            OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
+            close(sockfd);
+            OICFree(svritem);
+            ca_mutex_unlock(g_mutexObjectList);
+            return;
+        }
+        ca_mutex_unlock(g_mutexObjectList);
+
+        CHECKFD(sockfd);
+    }
 }
 
-static CAResult_t CAReceiveMessage()
+static void CAReceiveMessage(int fd)
 {
-    uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
+    // #1. get remote device information from file descriptor.
+    size_t index = 0;
+    CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFD(fd, &index);
+    if (!svritem)
+    {
+        OIC_LOG(ERROR, TAG, "there is no connection information in list");
+        return;
+    }
 
-    size_t i = 0;
-    unsigned char *recvBuffer = NULL;
-    CATCPServerInfo_t *svritem = NULL;
-    for (i = 0; i < length; i++)
+    // #2. get already allocated memory size.
+    size_t bufSize = (svritem->totalDataLen == 0) ? TCP_MAX_HEADER_LEN : svritem->totalDataLen;
+    if (!svritem->recvData)
     {
-        svritem = (CATCPServerInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
-        if (svritem->u4tcp.fd < 0)
+        svritem->recvData = (unsigned char *) OICCalloc(1, bufSize);
+        if (!svritem->recvData)
         {
-            continue;
+            OIC_LOG(ERROR, TAG, "out of memory");
+            CADisconnectTCPSession(svritem, index);
+            return;
         }
+    }
 
-        size_t bufSize = TCP_MAX_HEADER_LEN;
-        recvBuffer = (unsigned char *) OICCalloc(1, bufSize);
-        if (!recvBuffer)
+    // #3. receive data from remote device.
+    ssize_t recvLen = recv(fd, svritem->recvData + svritem->recvDataLen,
+                           bufSize - svritem->recvDataLen, 0);
+    if (recvLen <= 0)
+    {
+        if(EWOULDBLOCK != errno)
         {
-            OIC_LOG(ERROR, TAG, "out of memory");
-            goto exit;
+            OIC_LOG_V(ERROR, TAG, "Recvfrom failed %s", strerror(errno));
+            CADisconnectTCPSession(svritem, index);
         }
+        return;
+    }
+    svritem->recvDataLen += recvLen;
 
-        bool isHeaderChecked = false;
-        size_t totalLen = 0;
-        size_t totalReceivedLen = 0;
-        do
-        {
-            ssize_t recvLen = recv(svritem->u4tcp.fd, recvBuffer + totalReceivedLen,
-                                   bufSize - totalReceivedLen, 0);
-            if (recvLen <= 0)
-            {
-                if(EWOULDBLOCK != errno)
-                {
-                    OIC_LOG_V(ERROR, TAG, "Recvfrom failed %s", strerror(errno));
-                    goto exit;
-                }
-                // if received data length is zero, we are breaking loop.
-                // because we use non-blocking socket to receive data from remote device.
-                if (!totalReceivedLen)
-                {
-                    break;
-                }
-                continue;
-            }
+    // #4. get actual data length from coap over tcp header.
+    if (!svritem->totalDataLen)
+    {
+        coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
+                ((unsigned char *) svritem->recvData)[0] >> 4);
 
-            totalReceivedLen += recvLen;
-            if (!isHeaderChecked && totalReceivedLen)
+        size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
+        if (svritem->recvDataLen >= headerLen)
+        {
+            svritem->totalDataLen = CAGetTotalLengthFromHeader(
+                    (unsigned char *) svritem->recvData);
+            bufSize = svritem->totalDataLen;
+            unsigned char *newBuf = OICRealloc(svritem->recvData, bufSize);
+            if (!newBuf)
             {
-                coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
-                        ((unsigned char *)recvBuffer)[0] >> 4);
-                size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
-                if (totalReceivedLen >= headerLen)
-                {
-                    // get actual data length from coap over tcp header
-                    totalLen = CAGetTotalLengthFromHeader((unsigned char *) recvBuffer);
-                    bufSize = totalLen;
-                    unsigned char *newBuf = OICRealloc(recvBuffer, bufSize);
-                    if (NULL == newBuf)
-                    {
-                        OIC_LOG(ERROR, TAG, "out of memory");
-                        goto exit;
-                    }
-                    recvBuffer = newBuf;
-                    isHeaderChecked = true;
-                }
+                OIC_LOG(ERROR, TAG, "out of memory");
+                CADisconnectTCPSession(svritem, index);
+                return;
             }
-            if (totalLen == totalReceivedLen)
-            {
-                CAEndpoint_t ep = { .adapter = CA_ADAPTER_TCP,
-                                    .port = svritem->u4tcp.port };
-                strncpy(ep.addr, svritem->addr, sizeof(ep.addr));
+            svritem->recvData = newBuf;
+        }
+    }
 
-                if (g_packetReceivedCallback)
-                {
-                    g_packetReceivedCallback(&ep, recvBuffer, totalLen);
-                }
-                OIC_LOG_V(DEBUG, TAG, "received data len:%d", totalLen);
-                break;
-            }
-        } while (!totalLen || totalLen > totalReceivedLen);
+    // #5. pass the received data information to upper layer.
+    if ((svritem->totalDataLen == svritem->recvDataLen) && g_packetReceivedCallback)
+    {
+        svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
+        g_packetReceivedCallback(&svritem->sep, svritem->recvData, svritem->recvDataLen);
+        OIC_LOG_V(DEBUG, TAG, "total received data len:%d", svritem->recvDataLen);
 
-        OICFree(recvBuffer);
+        // initialize data info to receive next message.
+        OICFree(svritem->recvData);
+        svritem->recvData = NULL;
+        svritem->recvDataLen = 0;
+        svritem->totalDataLen = 0;
     }
 
-    return CA_STATUS_OK;
-
-exit:
-    ca_mutex_lock(g_mutexObjectList);
-    close(svritem->u4tcp.fd);
-    u_arraylist_remove(caglobals.tcp.svrlist, i);
-    ca_mutex_unlock(g_mutexObjectList);
-    OICFree(recvBuffer);
-    return CA_STATUS_FAILED;
+    return;
 }
 
-// TODO: resolving duplication.
-static int CASetNonblocking(int fd)
+static void CAWakeUpForReadFdsUpdate(const char *host)
 {
-    int fl = fcntl(fd, F_GETFL);
-    if (fl == -1)
+    if (caglobals.tcp.connectionFds[1] != -1)
     {
-        OIC_LOG_V(ERROR, TAG, "Failed to get existing flags, Error code: %s",
-                  strerror(errno));
-    }
-    else if ((fl & O_NONBLOCK) != O_NONBLOCK)
-    {
-        fl = fcntl(fd, F_SETFL, fl | O_NONBLOCK);
-        if (fl == -1)
+        ssize_t len = 0;
+        do
         {
-            OIC_LOG_V(ERROR, TAG, "Failed to set non-blocking mode, Error code: %s",
-                      strerror(errno));
+            len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
+        } while ((len == -1) && (errno == EINTR));
+
+        if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
+        {
+            OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
         }
     }
-
-    return fl;
 }
 
-static int CATCPCreateSocket(int family, CATCPServerInfo_t *TCPServerInfo)
+static int CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
 {
     // create tcp socket
     int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
@@ -347,14 +407,8 @@ static int CATCPCreateSocket(int family, CATCPServerInfo_t *TCPServerInfo)
         goto exit;
     }
 
-    // set non-blocking socket
-    if (-1 == CASetNonblocking(fd))
-    {
-        goto exit;
-    }
-
     struct sockaddr_storage sa = { .ss_family = family };
-    CAConvertNameToAddr(TCPServerInfo->addr, TCPServerInfo->u4tcp.port, &sa);
+    CAConvertNameToAddr(svritem->sep.endpoint.addr, svritem->sep.endpoint.port, &sa);
     socklen_t socklen = sizeof (struct sockaddr_in);
 
     // connect to TCP server
@@ -362,28 +416,7 @@ static int CATCPCreateSocket(int family, CATCPServerInfo_t *TCPServerInfo)
     if (0 == ret)
     {
         OIC_LOG(DEBUG, TAG, "connect socket success");
-    }
-    else if (EINPROGRESS == errno)
-    {
-        int error = 0;
-        socklen_t len = sizeof(error);
-        if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &len) < 0)
-        {
-            OIC_LOG(ERROR, TAG, "getsockopt() error");
-            goto exit;
-        }
-
-        if (error)
-        {
-            if (ECONNREFUSED == error)
-            {
-                OIC_LOG(ERROR, TAG, "connection refused");
-                goto exit;
-            }
-            OIC_LOG(ERROR, TAG, "failed to connect socket");
-            goto exit;
-        }
-        OIC_LOG(DEBUG, TAG, "connect socket success");
+        CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
     }
     else
     {
@@ -401,15 +434,19 @@ exit:
     return -1;
 }
 
-static void CAAcceptHandler(void *data)
+static CAResult_t CACreateAcceptSocket()
 {
-    (void)data;
-    OIC_LOG(DEBUG, TAG, "IN - CAAcceptHandler");
+    if (g_acceptServerFD != -1)
+    {
+        OIC_LOG(DEBUG, TAG, "accept socket created already");
+        return CA_STATUS_OK;
+    }
 
     int reuse = 1;
     struct sockaddr_in server = { .sin_addr.s_addr = INADDR_ANY,
                                   .sin_family = AF_INET,
-                                  .sin_port = htons(SERVER_PORT) };
+                                  .sin_port = htons(SERVER_PORT),
+                                  .sin_zero = { 0 } };
 
     g_acceptServerFD = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
     if (g_acceptServerFD < 0)
@@ -437,89 +474,48 @@ static void CAAcceptHandler(void *data)
         goto exit;
     }
 
-    struct pollfd acceptServerFD = { .fd = g_acceptServerFD,
-                                     .events = POLLIN };
+    CHECKFD(g_acceptServerFD);
 
-    while (!caglobals.tcp.terminate)
+    return CA_STATUS_OK;
+
+exit:
+    if (g_acceptServerFD >= 0)
+    {
+        close(g_acceptServerFD);
+        g_acceptServerFD = -1;
+    }
+    return CA_STATUS_FAILED;
+}
+
+static void CAInitializePipe(int *fds)
+{
+    int ret = pipe(fds);
+    if (-1 != ret)
     {
-        int pollState = poll(&acceptServerFD, 1, caglobals.tcp.selectTimeout);
-        if (pollState < 0)
+        ret = fcntl(fds[0], F_GETFD);
+        if (-1 != ret)
         {
-            OIC_LOG_V(FATAL, TAG, "polling error %s", strerror(errno));
-            goto exit;
+            ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
         }
-        else if (!pollState)
+        if (-1 != ret)
         {
-            continue;
+            ret = fcntl(fds[1], F_GETFD);
         }
-
-        if (acceptServerFD.revents & POLLIN)
+        if (-1 != ret)
         {
-            struct sockaddr_storage clientaddr;
-            socklen_t clientlen = sizeof (struct sockaddr_in);
-
-            int sockfd = accept(g_acceptServerFD, (struct sockaddr *)&clientaddr, &clientlen);
-            if (sockfd != -1)
-            {
-                CATCPServerInfo_t *svritem = (CATCPServerInfo_t *) OICMalloc(sizeof (*svritem));
-                if (!svritem)
-                {
-                    OIC_LOG(ERROR, TAG, "Out of memory");
-                    close(sockfd);
-                    return;
-                }
-
-                // set non-blocking socket
-                if (-1 == CASetNonblocking(sockfd))
-                {
-                    close(sockfd);
-                    OICFree(svritem);
-                    continue;
-                }
-                svritem->u4tcp.fd = sockfd;
-
-                CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
-                                    (char *) &svritem->addr, &svritem->u4tcp.port);
-
-                ca_mutex_lock(g_mutexObjectList);
-                bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
-                if (!res)
-                {
-                    OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
-                    close(sockfd);
-                    OICFree(svritem);
-                    ca_mutex_unlock(g_mutexObjectList);
-                    continue;
-                }
-                ca_mutex_unlock(g_mutexObjectList);
-            }
+            ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
         }
-    }
-
-    ca_mutex_lock(g_mutexObjectList);
-    // notify the thread
-    g_threadCounts--;
-    if (!g_threadCounts)
-    {
-        ca_cond_signal(g_condObjectList);
-    }
-    ca_mutex_unlock(g_mutexObjectList);
+        if (-1 == ret)
+        {
+            close(fds[1]);
+            close(fds[0]);
 
-    OIC_LOG(DEBUG, TAG, "OUT - CAAcceptHandler");
+            fds[0] = -1;
+            fds[1] = -1;
 
-exit:
-    if (g_acceptServerFD >= 0)
-    {
-        close(g_acceptServerFD);
-    }
-    ca_mutex_lock(g_mutexObjectList);
-    g_threadCounts--;
-    if (!g_threadCounts)
-    {
-        ca_cond_signal(g_condObjectList);
+            OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
+        }
     }
-    ca_mutex_unlock(g_mutexObjectList);
-    return;
 }
 
 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
@@ -535,16 +531,13 @@ CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
     }
 
     CAResult_t res = CATCPCreateMutex();
-    if (CA_STATUS_OK != res)
+    if (CA_STATUS_OK == res)
     {
-        OIC_LOG(ERROR, TAG, "failed to create mutex");
-        return res;
+        res = CATCPCreateCond();
     }
-
-    res = CATCPCreateCond();
     if (CA_STATUS_OK != res)
     {
-        OIC_LOG(ERROR, TAG, "failed to create cond");
+        OIC_LOG(ERROR, TAG, "failed to create mutex/cond");
         return res;
     }
 
@@ -555,16 +548,27 @@ CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
     }
     ca_mutex_unlock(g_mutexObjectList);
 
-    caglobals.tcp.terminate = false;
-
-    res = ca_thread_pool_add_task(threadPool, CAAcceptHandler, NULL);
-    if (CA_STATUS_OK != res)
+    if (caglobals.server)
     {
-        OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
-        return res;
+        res = CACreateAcceptSocket();
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "failed to create accept socket");
+            return res;
+        }
     }
-    OIC_LOG(DEBUG, TAG, "CAAcceptHandler thread started successfully.");
 
+    // create pipe for fast shutdown
+    CAInitializePipe(caglobals.tcp.shutdownFds);
+    CHECKFD(caglobals.tcp.shutdownFds[0]);
+    CHECKFD(caglobals.tcp.shutdownFds[1]);
+
+    // create pipe for connection event
+    CAInitializePipe(caglobals.tcp.connectionFds);
+    CHECKFD(caglobals.tcp.connectionFds[0]);
+    CHECKFD(caglobals.tcp.connectionFds[1]);
+
+    caglobals.tcp.terminate = false;
     res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
     if (CA_STATUS_OK != res)
     {
@@ -574,24 +578,33 @@ CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
     OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
 
     caglobals.tcp.started = true;
-
-    g_threadCounts = CA_TCP_DEFAULT_THREAD_COUNTS;
-
     return CA_STATUS_OK;
 }
 
 void CATCPStopServer()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     // mutex lock
     ca_mutex_lock(g_mutexObjectList);
 
     // set terminate flag
     caglobals.tcp.terminate = true;
-    caglobals.tcp.started = false;
 
-    ca_cond_wait(g_condObjectList, g_mutexObjectList);
+    if (caglobals.tcp.shutdownFds[1] != -1)
+    {
+        close(caglobals.tcp.shutdownFds[1]);
+        // receive thread will stop immediately
+    }
+
+    if (caglobals.tcp.connectionFds[1] != -1)
+    {
+        close(caglobals.tcp.connectionFds[1]);
+    }
+
+    if (caglobals.tcp.started)
+    {
+        ca_cond_wait(g_condObjectList, g_mutexObjectList);
+    }
+    caglobals.tcp.started = false;
 
     // mutex unlock
     ca_mutex_unlock(g_mutexObjectList);
@@ -605,21 +618,22 @@ void CATCPStopServer()
     CATCPDisconnectAll();
     CATCPDestroyMutex();
     CATCPDestroyCond();
-
-    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     g_packetReceivedCallback = callback;
+}
 
-    OIC_LOG(DEBUG, TAG, "OUT");
+void CATCPSetKeepAliveCallback(CATCPKeepAliveHandleCallback keepaliveHandler)
+{
+    g_keepaliveCallback = keepaliveHandler;
 }
 
 static size_t CACheckPayloadLength(const void *data, size_t dlen)
 {
+    VERIFY_NON_NULL_RET(data, TAG, "data", -1);
+
     coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
             ((unsigned char *)data)[0] >> 4);
 
@@ -645,9 +659,10 @@ static size_t CACheckPayloadLength(const void *data, size_t dlen)
     if (pdu->length > headerSize)
     {
         payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
-        OICFree(pdu);
     }
 
+    OICFree(pdu);
+
     return payloadLen;
 }
 
@@ -655,13 +670,12 @@ static void sendData(const CAEndpoint_t *endpoint,
                      const void *data, size_t dlen)
 {
     // #1. get TCP Server object from list
-    uint32_t index = 0;
-    CATCPServerInfo_t *svritem = CAGetTCPServerInfoFromList(endpoint->addr, endpoint->port,
-                                                            &index);
+    size_t index = 0;
+    CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
     if (!svritem)
     {
         // if there is no connection info, connect to TCP Server
-        svritem = CAConnectToTCPServer(endpoint);
+        svritem = CAConnectTCPSession(endpoint);
         if (!svritem)
         {
             OIC_LOG(ERROR, TAG, "Failed to create TCP server object");
@@ -676,25 +690,25 @@ static void sendData(const CAEndpoint_t *endpoint,
     if (!payloadLen)
     {
         OIC_LOG(DEBUG, TAG, "payload length is zero, disconnect from remote device");
-        CADisconnectFromTCPServer(endpoint);
+        CADisconnectTCPSession(svritem, index);
         return;
     }
 
     // #3. check connection state
-    if (svritem->u4tcp.fd < 0)
+    if (svritem->fd < 0)
     {
         // if file descriptor value is wrong, remove TCP Server info from list
         OIC_LOG(ERROR, TAG, "Failed to connect to TCP server");
-        CADisconnectFromTCPServer(endpoint);
+        CADisconnectTCPSession(svritem, index);
         g_TCPErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
         return;
     }
 
     // #4. send data to TCP Server
-    size_t remainLen = dlen;
+    ssize_t remainLen = dlen;
     do
     {
-        size_t len = send(svritem->u4tcp.fd, data, remainLen, 0);
+        ssize_t len = send(svritem->fd, data, remainLen, 0);
         if (-1 == len)
         {
             if (EWOULDBLOCK != errno)
@@ -709,7 +723,7 @@ static void sendData(const CAEndpoint_t *endpoint,
         remainLen -= len;
     } while (remainLen > 0);
 
-    OIC_LOG_V(INFO, TAG, "unicast ipv4tcp sendTo is successful: %d bytes", dlen);
+    OIC_LOG_V(INFO, TAG, "unicast ipv4tcp sendTo is successful: %zu bytes", dlen);
 }
 
 void CATCPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
@@ -729,106 +743,130 @@ void CATCPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
 
 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     VERIFY_NON_NULL(info, TAG, "info is NULL");
     VERIFY_NON_NULL(size, TAG, "size is NULL");
 
     return CA_NOT_SUPPORTED;
 }
 
-CATCPServerInfo_t *CAConnectToTCPServer(const CAEndpoint_t *TCPServerInfo)
+CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint)
 {
-    VERIFY_NON_NULL_RET(TCPServerInfo, TAG, "TCPServerInfo is NULL", NULL);
+    VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
 
     // #1. create TCP server object
-    CATCPServerInfo_t *svritem = (CATCPServerInfo_t *) OICMalloc(sizeof (*svritem));
+    CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
     if (!svritem)
     {
         OIC_LOG(ERROR, TAG, "Out of memory");
         return NULL;
     }
-    memcpy(svritem->addr, TCPServerInfo->addr, sizeof(svritem->addr));
-    svritem->u4tcp.port = TCPServerInfo->port;
+    memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
+    svritem->sep.endpoint.port = endpoint->port;
 
     // #2. create the socket and connect to TCP server
     if (caglobals.tcp.ipv4tcpenabled)
     {
-        svritem->u4tcp.fd = CATCPCreateSocket(AF_INET, svritem);
-        if (-1 == svritem->u4tcp.fd)
+        int fd = CATCPCreateSocket(AF_INET, svritem);
+        if (-1 == fd)
         {
             OICFree(svritem);
             return NULL;
         }
-    }
 
-    // #3. add TCP connection info to list
-    ca_mutex_lock(g_mutexObjectList);
-    if (caglobals.tcp.svrlist)
-    {
-        bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
-        if (!res)
+        // #3. add TCP connection info to list
+        svritem->fd = fd;
+        ca_mutex_lock(g_mutexObjectList);
+        if (caglobals.tcp.svrlist)
         {
-            OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
-            close(svritem->u4tcp.fd);
-            OICFree(svritem);
-            ca_mutex_unlock(g_mutexObjectList);
-            return NULL;
+            bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
+            if (!res)
+            {
+                OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
+                close(svritem->fd);
+                OICFree(svritem);
+                ca_mutex_unlock(g_mutexObjectList);
+                return NULL;
+            }
+        }
+        ca_mutex_unlock(g_mutexObjectList);
+
+        CHECKFD(fd);
+
+        // pass the connection information to RI for keepalive.
+        if (g_keepaliveCallback)
+        {
+            g_keepaliveCallback(svritem->sep.endpoint.addr, svritem->sep.endpoint.port, true);
         }
     }
-    ca_mutex_unlock(g_mutexObjectList);
 
     return svritem;
 }
 
-CAResult_t CADisconnectFromTCPServer(const CAEndpoint_t *TCPServerInfo)
+CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index)
 {
-    VERIFY_NON_NULL(TCPServerInfo, TAG, "TCP server info is NULL");
+    VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
 
-    // #1. get server info
-    uint32_t index = 0;
     ca_mutex_lock(g_mutexObjectList);
-    CATCPServerInfo_t *svritem = CAGetTCPServerInfoFromList(TCPServerInfo->addr,
-                                                            TCPServerInfo->port,
-                                                            &index);
-    if (!svritem)
-    {
-        OIC_LOG(ERROR, TAG, "there is no connection info");
-        ca_mutex_unlock(g_mutexObjectList);
-        return CA_STATUS_FAILED;
-    }
 
-    // #2. close the socket and remove TCP connection info in list
-    if (svritem->u4tcp.fd >= 0)
+    // close the socket and remove TCP connection info in list
+    if (svritem->fd >= 0)
     {
-        close(svritem->u4tcp.fd);
+        close(svritem->fd);
     }
     u_arraylist_remove(caglobals.tcp.svrlist, index);
+    OICFree(svritem->recvData);
+    OICFree(svritem);
     ca_mutex_unlock(g_mutexObjectList);
 
+    // pass the connection information to RI for keepalive.
+    if (g_keepaliveCallback)
+    {
+        g_keepaliveCallback(svritem->sep.endpoint.addr, svritem->sep.endpoint.port, false);
+    }
+
     return CA_STATUS_OK;
 }
 
-CATCPServerInfo_t *CAGetTCPServerInfoFromList(const char *addr, const uint16_t port,
-                                              uint32_t *index)
+void CATCPDisconnectAll()
+{
+    ca_mutex_lock(g_mutexObjectList);
+    uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
+
+    CATCPSessionInfo_t *svritem = NULL;
+    for (size_t i = 0; i < length; i++)
+    {
+        svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
+        if (svritem && svritem->fd >= 0)
+        {
+            shutdown(svritem->fd, SHUT_RDWR);
+            close(svritem->fd);
+            OICFree(svritem->recvData);
+        }
+    }
+    u_arraylist_destroy(caglobals.tcp.svrlist);
+    ca_mutex_unlock(g_mutexObjectList);
+}
+
+CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint,
+                                                    size_t *index)
 {
-    VERIFY_NON_NULL_RET(addr, TAG, "addr is NULL", NULL);
+    VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
     VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
 
     // get connection info from list
     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
-
     for (size_t i = 0; i < length; i++)
     {
-        CATCPServerInfo_t *svritem = (CATCPServerInfo_t *) u_arraylist_get(
+        CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
                 caglobals.tcp.svrlist, i);
         if (!svritem)
         {
             continue;
         }
 
-        if (!strncmp(svritem->addr, addr, sizeof(svritem->addr))
-                && (svritem->u4tcp.port == port))
+        if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
+                     sizeof(svritem->sep.endpoint.addr))
+                && (svritem->sep.endpoint.port == endpoint->port))
         {
             *index = i;
             return svritem;
@@ -838,6 +876,48 @@ CATCPServerInfo_t *CAGetTCPServerInfoFromList(const char *addr, const uint16_t p
     return NULL;
 }
 
+CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
+{
+    ca_mutex_lock(g_mutexObjectList);
+
+    // check from the last item.
+    CATCPSessionInfo_t *svritem = NULL;
+    uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
+    for (size_t i = 0; i < length; i++)
+    {
+        svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
+
+        if (svritem && svritem->fd == fd)
+        {
+            *index = i;
+            ca_mutex_unlock(g_mutexObjectList);
+            return svritem;
+        }
+    }
+
+    ca_mutex_unlock(g_mutexObjectList);
+
+    return NULL;
+}
+
+size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
+
+    coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
+            ((unsigned char *)recvBuffer)[0] >> 4);
+    size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
+                                                        transport);
+    size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
+
+    OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%d]", optPaylaodLen);
+    OIC_LOG_V(DEBUG, TAG, "header length [%d]", headerLen);
+    OIC_LOG_V(DEBUG, TAG, "total data length [%d]", headerLen + optPaylaodLen);
+
+    OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
+    return headerLen + optPaylaodLen;
+}
+
 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
 {
     g_TCPErrorHandler = errorHandleCallback;
index 7d66ab8..a226291 100644 (file)
@@ -20,6 +20,7 @@
 
 #include "gtest/gtest.h"
 #include "cainterface.h"
+#include "cautilinterface.h"
 #include "cacommon.h"
 
 #define CA_TRANSPORT_ADAPTER_SCOPE  1000
@@ -39,6 +40,8 @@ class CATests : public testing::Test {
 void request_handler(CAEndpoint_t* object, CARequestInfo_t* requestInfo);
 void response_handler(CAEndpoint_t* object, CAResponseInfo_t* responseInfo);
 void error_handler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
+void adapter_handler(CATransportAdapter_t adapter, bool enabled);
+void connection_handler(CATransportAdapter_t adapter, const char *remote_address, bool connected);
 CAResult_t checkGetNetworkInfo();
 CAResult_t checkSelectNetwork();
 
@@ -65,6 +68,19 @@ void error_handler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo)
     return;
 }
 
+void adapter_handler(CATransportAdapter_t adapter,
+                     bool enabled)
+{
+
+}
+
+void connection_handler(CATransportAdapter_t adapter,
+                        const char *remote_address,
+                        bool connected)
+{
+
+}
+
 static char* addr = NULL;
 static CAEndpoint_t* tempRep = NULL;
 static CARequestInfo_t requestInfo;
@@ -202,11 +218,8 @@ TEST_F(CATests, CreateRemoteEndpointTestGood)
     EXPECT_EQ(CA_STATUS_OK, CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, addr,
                                              PORT, &tempRep));
 
-    if (tempRep != NULL)
-    {
-        CADestroyEndpoint(tempRep);
-        tempRep = NULL;
-    }
+    CADestroyEndpoint(tempRep);
+    tempRep = NULL;
 }
 
 // check remoteEndpoint and values of remoteEndpoint
@@ -218,11 +231,8 @@ TEST_F(CATests, CreateRemoteEndpointTestValues)
 
     EXPECT_TRUE(tempRep != NULL);
 
-    if (tempRep != NULL)
-    {
-        CADestroyEndpoint(tempRep);
-        tempRep = NULL;
-    }
+    CADestroyEndpoint(tempRep);
+    tempRep = NULL;
 }
 
 // CAGerateToken TC
@@ -281,12 +291,9 @@ TEST(SendRequestTest, DISABLED_TC_16_Positive_01)
     EXPECT_EQ(CA_STATUS_OK, CASendRequest(tempRep, &requestInfo));
 
     CADestroyToken(tempToken);
-
-    free(requestData.payload);
-
     CADestroyEndpoint(tempRep);
+    free(requestData.payload);
     tempRep = NULL;
-
 }
 
 // check return value when a NULL is passed instead of a valid CARequestInfo_t address
@@ -297,11 +304,8 @@ TEST_F(CATests, SendRequestTestWithNullAddr)
 
     EXPECT_EQ(CA_STATUS_INVALID_PARAM, CASendRequest(tempRep, NULL));
 
-    if (tempRep != NULL)
-    {
-        CADestroyEndpoint(tempRep);
-        tempRep = NULL;
-    }
+    CADestroyEndpoint(tempRep);
+    tempRep = NULL;
 }
 
 // CASendResponse TC
@@ -374,12 +378,9 @@ TEST(SendResponseTest, DISABLED_TC_20_Negative_01)
     EXPECT_EQ(CA_STATUS_OK, CASendResponse(tempRep, &responseInfo));
 
     CADestroyToken(tempToken);
-    if (tempRep != NULL)
-    {
-        CADestroyEndpoint(tempRep);
-        tempRep = NULL;
-    }
+    CADestroyEndpoint(tempRep);
     free (responseData.payload);
+    tempRep = NULL;
 }
 
 // check return value NULL is passed instead of a valid CAResponseInfo_t address
@@ -390,19 +391,15 @@ TEST_F(CATests, SendResponseTest)
 
     EXPECT_EQ(CA_STATUS_INVALID_PARAM, CASendResponse(tempRep, NULL));
 
-    if (tempRep != NULL)
-    {
-        CADestroyEndpoint(tempRep);
-        tempRep = NULL;
-    }
+    CADestroyEndpoint(tempRep);
+    tempRep = NULL;
 }
 
 // CASelectNewwork TC
 // check return value
 TEST_F(CATests, SelectNetworkTestGood)
 {
-    CAResult_t res = checkSelectNetwork();
-    EXPECT_EQ(CA_STATUS_OK, res);
+    EXPECT_EQ(CA_STATUS_OK, checkSelectNetwork());
 }
 
 CAResult_t checkSelectNetwork()
@@ -460,6 +457,45 @@ TEST_F(CATests, RegisterDTLSCredentialsHandlerTest)
 #endif
 }
 
+// CARegisterNetworkMonitorHandler TC
+// check return value
+TEST_F(CATests, RegisterNetworkMonitorHandler)
+{
+#ifdef LE_ADAPTER
+    EXPECT_EQ(CA_STATUS_OK, CARegisterNetworkMonitorHandler(adapter_handler,
+                                                            connection_handler));
+#else
+    EXPECT_EQ(CA_NOT_SUPPORTED, CARegisterNetworkMonitorHandler(adapter_handler,
+                                                                connection_handler));
+#endif
+}
+
+// CASetAutoConnectionDeviceInfo TC
+// check return value
+TEST_F(CATests, SetAutoConnectionDeviceInfo)
+{
+    addr = (char *) ADDRESS;
+
+#if defined(__ANDROID__) && defined(LE_ADAPTER)
+    EXPECT_EQ(CA_STATUS_OK, CASetAutoConnectionDeviceInfo(addr));
+#else
+    EXPECT_EQ(CA_NOT_SUPPORTED, CASetAutoConnectionDeviceInfo(addr));
+#endif
+}
+
+// CAUnsetAutoConnectionDeviceInfo TC
+// check return value
+TEST_F(CATests, UnsetAutoConnectionDeviceInfo)
+{
+    addr = (char *) ADDRESS;
+
+#if defined(__ANDROID__) && defined(LE_ADAPTER)
+    EXPECT_EQ(CA_STATUS_OK, CAUnsetAutoConnectionDeviceInfo(addr));
+#else
+    EXPECT_EQ(CA_NOT_SUPPORTED, CAUnsetAutoConnectionDeviceInfo(addr));
+#endif
+}
+
 CAResult_t checkGetNetworkInfo()
 {
     CAEndpoint_t *tempInfo = NULL;
diff --git a/resource/csdk/connectivity/util/SConscript b/resource/csdk/connectivity/util/SConscript
new file mode 100644 (file)
index 0000000..33e15f6
--- /dev/null
@@ -0,0 +1,47 @@
+#######################################################
+#      Build Common Util
+#######################################################
+
+Import('env')
+import os.path
+
+print "Reading util folder script"
+
+ca_os = env.get('TARGET_OS')
+ca_transport = env.get('TARGET_TRANSPORT')
+src_dir = env.get('SRC_DIR')
+root_dir = './../'
+src_dir = './../util/src/'
+
+env.PrependUnique(CPPPATH = [ os.path.join(root_dir, 'api') ])
+env.AppendUnique(CPPPATH = [ os.path.join(root_dir, 'inc'),
+                             os.path.join(root_dir, 'lib/libcoap-4.1.1'),
+                             os.path.join(src_dir, '/resource/csdk/logger/include/'),
+                             os.path.join(root_dir, 'common/inc'),
+                             os.path.join(root_dir, 'util/inc') ])
+
+if ca_os == 'android':
+       env.AppendUnique(CPPPATH = [ os.path.join(root_dir, 'util/src/android') ])
+
+######################################################################
+# Source files to build common for platforms
+######################################################################
+
+env.AppendUnique(CA_SRC = [os.path.join(src_dir,'cautilinterface.c')])
+
+if (('BLE' in ca_transport) or ('ALL' in ca_transport)):
+    if ca_os in ['linux', 'tizen', 'arduino']:
+               env.AppendUnique(CA_SRC = [
+               os.path.join(src_dir,'camanager/' + ca_os + '/caleconnectionmanager.c')])
+
+    if ca_os == 'android':
+               env.AppendUnique(CA_SRC = [
+               os.path.join(src_dir,'camanager/android/caleconnectionmanager.c'),
+               os.path.join(src_dir,'camanager/android/caleautoconnector.c'),
+               os.path.join(src_dir,'camanager/android/camanagerleutil.c'),
+               os.path.join(src_dir,'camanager/android/camanagerdevice.c')])
+
+if (('BT' in ca_transport) or ('ALL' in ca_transport)):
+    if ca_os == 'android':
+               env.AppendUnique(CA_SRC = [
+               os.path.join(src_dir,'btpairing/android/cabtpairing.c')])
\ No newline at end of file
diff --git a/resource/csdk/connectivity/util/inc/cabtpairinginterface.h b/resource/csdk/connectivity/util/inc/cabtpairinginterface.h
new file mode 100644 (file)
index 0000000..507b063
--- /dev/null
@@ -0,0 +1,82 @@
+/* ****************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef CA_BT_PAIRING_INTERFACE_H_
+#define CA_BT_PAIRING_INTERFACE_H_
+
+#include "cacommon.h"
+#include "cautilinterface.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#ifdef __ANDROID__
+#ifdef EDR_ADAPTER
+/**
+ * initialize BT Pairing manager
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   jvm                   invocation inferface for JAVA virtual machine.
+ * @param[in]   context               application context.
+ *
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h).
+ */
+CAResult_t CABTPairingInitialize(JNIEnv *env, JavaVM *jvm, jobject context);
+
+/**
+ * start discovery for BT device which has iotivity UUID.
+ * @param[in]  env              JNI interface pointer.
+ *
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h).
+ */
+CAResult_t CABTPairingStartScan(JNIEnv *env);
+
+/**
+ * stop discovery
+ * @param[in]  env              JNI interface pointer.
+ *
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h).
+ */
+CAResult_t CABTPairingStopScan(JNIEnv *env);
+
+/**
+ * bonding between devices.
+ * @param[in]  env              JNI interface pointer.
+ * @param[in]  device           bluetooth device object.
+ *
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h).
+ */
+CAResult_t CABTPairingCreateBond(JNIEnv *env, jobject device);
+
+/**
+ * set callback listener of found device.
+ * @param[in]  listener         callback listener
+ */
+void CABTPairingSetFoundDeviceListener(jobject listener);
+#endif
+#endif
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* CA_LE_MANAGER_H_ */
+
diff --git a/resource/csdk/connectivity/util/inc/camanagerleinterface.h b/resource/csdk/connectivity/util/inc/camanagerleinterface.h
new file mode 100644 (file)
index 0000000..9a175bf
--- /dev/null
@@ -0,0 +1,88 @@
+/* ****************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef CA_MANAGER_LE_INF_H_
+#define CA_MANAGER_LE_INF_H_
+
+#include "cacommon.h"
+#include "cautilinterface.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * Register network monitor callbacks.
+ * Adapter state changes and network state changes are delivered these callbacks.
+ * @param[in]   adapterStateCB  Adapter state changed callback.
+ * @param[in]   connStateCB     Connection state changed callback.
+ */
+void CASetLENetworkMonitorCallbacks(CAAdapterStateChangedCB adapterStateCB,
+                                    CAConnectionStateChangedCB connStateCB);
+
+/**
+ * Set device information for auto connection.
+ */
+CAResult_t CASetLEClientAutoConnectionDeviceInfo();
+
+/**
+ * Unset device information to stop auto connection.
+ */
+CAResult_t CAUnsetLEClientAutoConnectionDeviceInfo();
+
+/**
+ * Start advertise to receive request for scanning or connecting.
+ */
+void CAStartServerLEAdvertising();
+
+/**
+ * Stop advertise to destroy advertiser.
+ */
+void CAStopServerLEAdvertising();
+
+#ifdef __ANDROID__
+#ifdef LE_ADAPTER
+/**
+ * initialize client connection manager
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   jvm                   invocation inferface for JAVA virtual machine.
+ * @param[in]   context               application context.
+ *
+ * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED or ::CA_MEMORY_ALLOC_FAILED
+ */
+CAResult_t CAManagerLEClientInitialize(JNIEnv *env, JavaVM *jvm, jobject context);
+
+/**
+ * terminate client connection manager
+ * @param[in]   env                   JNI interface pointer.
+ *
+ * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED or ::CA_MEMORY_ALLOC_FAILED
+ */
+CAResult_t CAManagerLEClientTerminate(JNIEnv *env);
+#endif
+#endif
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* CA_MANAGER_LE_INF_H_ */
+
diff --git a/resource/csdk/connectivity/util/src/btpairing/android/cabtpairing.c b/resource/csdk/connectivity/util/src/btpairing/android/cabtpairing.c
new file mode 100644 (file)
index 0000000..b982b74
--- /dev/null
@@ -0,0 +1,370 @@
+/* ****************************************************************
+ *
+ * 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 "cabtpairinginterface.h"
+#include "cabtpairing.h"
+#include "cacommon.h"
+#include "logger.h"
+#include <jni.h>
+
+#define  TAG   "OIC_CA_BT_PAIRING"
+
+/**
+ * pointer to store JavaVM
+ */
+static JavaVM *g_jvm = NULL;
+
+/**
+ * pointer to store context for android callback interface
+ */
+static jobject g_context = NULL;
+static jobject g_listener = NULL;
+
+static const char CLASSPATH_CONTEXT[] = "android/content/Context";
+static const char METHODID_CONTEXTNONPARAM[] = "()Landroid/content/Context;";
+static const char CLASSPATH_BT_PAIRING_INTERFACE[] = "org/iotivity/ca/CaBtPairingInterface";
+static const char CLASSPATH_BT_ADAPTER[] = "android/bluetooth/BluetoothAdapter";
+static const char METHODID_OBJECTNONPARAM[] = "()Landroid/bluetooth/BluetoothAdapter;";
+static const char CLASSPATH_BT_DEVICE[] = "android/bluetooth/BluetoothDevice";
+
+static void CABTPaitingCreateJNIInterfaceObject(jobject context)
+{
+    JNIEnv* env;
+    OIC_LOG(INFO, TAG, "OICEDRCreateJNIInterfaceObject");
+
+    if ((*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6) != JNI_OK)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get JNIEnv pointer");
+        return;
+    }
+
+    //getApplicationContext
+    jclass contextClass = (*env)->FindClass(env, CLASSPATH_CONTEXT);
+    if (!contextClass)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get context object class");
+        return;
+    }
+
+    jmethodID getApplicationContextMethod = (*env)->GetMethodID(env, contextClass,
+                                                                "getApplicationContext",
+                                                                METHODID_CONTEXTNONPARAM);
+    if (!getApplicationContextMethod)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get getApplicationContext method");
+        return;
+    }
+
+    //Create EDRJniInterface instance
+    jclass EDRJniInterface = (*env)->FindClass(env, CLASSPATH_BT_PAIRING_INTERFACE);
+    if (!EDRJniInterface)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get CaEdrInterface class");
+        return;
+    }
+
+    jmethodID EDRInterfaceConstructorMethod = (*env)->GetMethodID(env, EDRJniInterface, "<init>",
+                                                                  "(Landroid/content/Context;)V");
+    if (!EDRInterfaceConstructorMethod)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get CaEdrInterface constructor method");
+        return;
+    }
+
+    (*env)->NewObject(env, EDRJniInterface, EDRInterfaceConstructorMethod, context);
+    OIC_LOG(INFO, TAG, "New Object has been created successfully");
+}
+
+CAResult_t CABTPairingInitialize(JNIEnv *env, JavaVM *jvm, jobject context)
+{
+    OIC_LOG(INFO, TAG, "CABTPairingInitialize");
+
+    if (!context)
+    {
+        OIC_LOG(ERROR, TAG, "context is null");
+        return CA_STATUS_FAILED;
+    }
+
+    g_jvm = jvm;
+    g_context = (*env)->NewGlobalRef(env, context);
+
+    if (g_context)
+    {
+        /* create java interface instance*/
+        CABTPaitingCreateJNIInterfaceObject(g_context);
+    }
+    return CA_STATUS_OK;
+}
+
+void CABTPairingSetFoundDeviceListener(jobject listener)
+{
+    g_listener = listener;
+}
+
+CAResult_t CABTPairingStartScan(JNIEnv *env)
+{
+    OIC_LOG(INFO, TAG, "CABTPairingStartScan");
+    if (!env)
+    {
+        OIC_LOG(ERROR, TAG, "parameter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    CABTPairingStopScan(env);
+
+    // get default bt adapter class
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADAPTER);
+    if (!jni_cid_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BTAdapter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // get remote bt adapter method ID
+    jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
+                                                                    "getDefaultAdapter",
+                                                                    METHODID_OBJECTNONPARAM);
+    if (!jni_mid_getDefaultAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // get startDiscovery() method ID
+    jmethodID jni_mid_startDiscovery = (*env)->GetMethodID(env, jni_cid_BTAdapter, "startDiscovery",
+                                                           "()Z");
+    if (!jni_mid_startDiscovery)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_startDiscovery is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // get bluetooth adapter object
+    jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+                                                               jni_mid_getDefaultAdapter);
+    if (!jni_obj_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_BTAdapter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // call startDiscovery() method
+    jboolean jni_obj_startDiscovery = (*env)->CallBooleanMethod(env, jni_obj_BTAdapter,
+                                                                jni_mid_startDiscovery);
+    if (!jni_obj_startDiscovery)
+    {
+        OIC_LOG(ERROR, TAG, "startDiscovery has failed");
+        return CA_STATUS_FAILED;
+    }
+    else
+    {
+        OIC_LOG(INFO, TAG, "startDiscovery has started");
+        return CA_STATUS_OK;
+    }
+}
+
+CAResult_t CABTPairingStopScan(JNIEnv *env)
+{
+    OIC_LOG(INFO, TAG, "CABTPairingStopScan");
+    if (!env)
+    {
+        OIC_LOG(ERROR, TAG, "parameter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // get default bt adapter class
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADAPTER);
+    if (!jni_cid_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BTAdapter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // get remote bt adapter method ID
+    jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
+                                                                    "getDefaultAdapter",
+                                                                    METHODID_OBJECTNONPARAM);
+    if (!jni_mid_getDefaultAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // get cancelDiscovery() method ID
+    jmethodID jni_mid_cancelDiscovery = (*env)->GetMethodID(env, jni_cid_BTAdapter, "cancelDiscovery",
+                                                           "()Z");
+    if (!jni_mid_cancelDiscovery)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_cancelDiscovery is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // gat bt adapter object
+    jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+                                                               jni_mid_getDefaultAdapter);
+    if (!jni_obj_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_BTAdapter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // call cancelDiscovery() method
+    jboolean jni_obj_cancelDiscovery = (*env)->CallBooleanMethod(env, jni_obj_BTAdapter,
+                                                                 jni_mid_cancelDiscovery);
+    if (!jni_obj_cancelDiscovery)
+    {
+        OIC_LOG(ERROR, TAG, "cancelDiscovery has failed");
+        return CA_STATUS_FAILED;
+    }
+    else
+    {
+        OIC_LOG(INFO, TAG, "cancelDiscovery has started");
+        return CA_STATUS_OK;
+    }
+}
+
+CAResult_t CABTPairingCreateBond(JNIEnv *env, jobject device)
+{
+    OIC_LOG(INFO, TAG, "CABTPairingCreateBond");
+    if (!env || !device)
+    {
+        OIC_LOG(ERROR, TAG, "parameter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // get default bt adapter class
+    jclass jni_cid_BTDevice = (*env)->FindClass(env, CLASSPATH_BT_DEVICE);
+    if (!jni_cid_BTDevice)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BTDevice is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // get createBond() method ID
+    jmethodID jni_mid_createBond = (*env)->GetMethodID(env, jni_cid_BTDevice, "createBond",
+                                                       "()Z");
+    if (!jni_mid_createBond)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_createBond is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // call createBond() method
+    jboolean jni_obj_createBond = (*env)->CallBooleanMethod(env, device, jni_mid_createBond);
+    if (!jni_obj_createBond)
+    {
+        OIC_LOG(ERROR, TAG, "createBond has failed");
+        return CA_STATUS_FAILED;
+    }
+    else
+    {
+        OIC_LOG(INFO, TAG, "createBond has started");
+        return CA_STATUS_OK;
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaBtPairingInterface_oicEdrStateChangedCallback(JNIEnv *env, jobject obj,
+                                                                     jint status)
+{
+    OIC_LOG(INFO, TAG, "oicEdrStateChangedCallback");
+    if (!env || !obj)
+    {
+        OIC_LOG(ERROR, TAG, "parameter is null");
+        return;
+    }
+
+    // STATE_ON:12, STATE_OFF:10
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADAPTER);
+    if (!jni_cid_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BTAdapter is null");
+        return;
+    }
+
+    jfieldID id_state_on = (*env)->GetStaticFieldID(env, jni_cid_BTAdapter, "STATE_ON", "I");
+    if (!id_state_on)
+    {
+        OIC_LOG(ERROR, TAG, "id_state_on is null");
+        return;
+    }
+
+    jfieldID id_state_off = (*env)->GetStaticFieldID(env, jni_cid_BTAdapter, "STATE_OFF", "I");
+    if (!id_state_off)
+    {
+        OIC_LOG(ERROR, TAG, "id_state_off is null");
+        return;
+    }
+
+    jint state_on = (*env)->GetStaticIntField(env, jni_cid_BTAdapter, id_state_on);
+    jint state_off = (*env)->GetStaticIntField(env, jni_cid_BTAdapter, id_state_off);
+
+    if (state_on == status)
+    {
+        OIC_LOG(INFO, TAG, "oicEdrStateChangedCallback : state_on");
+    }
+    else if (state_off == status)
+    {
+        OIC_LOG(INFO, TAG, "oicEdrStateChangedCaloicEdrFoundDeviceCallbacklback : state_off");
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaBtPairingInterface_oicEdrBondStateChangedCallback(JNIEnv *env, jobject obj,
+                                                                         jstring addr)
+{
+    OIC_LOG(INFO, TAG, "oicEdrBondStateChangedCallback");
+    (void)env;
+    (void)obj;
+    (void)addr;
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaBtPairingInterface_oicEdrFoundDeviceCallback(JNIEnv *env, jobject obj,
+                                                                    jobject device)
+{
+    if (!env || !obj || !device)
+    {
+        return;
+    }
+
+    if (!g_listener)
+    {
+        return;
+    }
+
+    jclass jni_cls_listener = (*env)->GetObjectClass(env, g_listener);
+    if (!jni_cls_listener)
+    {
+        OIC_LOG(ERROR, TAG, "could not get jni_cls_listener");
+        return;
+    }
+
+    jmethodID jni_mid_listener = (*env)->GetMethodID(env, jni_cls_listener, "onBtDeviceFound",
+                                        "(Landroid/bluetooth/BluetoothDevice;)V");
+    if (!jni_mid_listener)
+    {
+        OIC_LOG(ERROR, TAG, "could not get Method ID");
+        return;
+    }
+
+    (*env)->CallVoidMethod(env, g_listener, jni_mid_listener, device);
+}
+
diff --git a/resource/csdk/connectivity/util/src/btpairing/android/cabtpairing.h b/resource/csdk/connectivity/util/src/btpairing/android/cabtpairing.h
new file mode 100644 (file)
index 0000000..0a0e973
--- /dev/null
@@ -0,0 +1,62 @@
+/******************************************************************
+ *
+ * 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"
+/* Header for class org_iotivity_ca_CaBtPairingInterface */
+
+#ifndef Included_org_iotivity_ca_CaBtPairingInterface
+#define Included_org_iotivity_ca_CaBtPairingInterface
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/*
+ * Class:     org_iotivity_ca_CaBtPairingInterface
+ * Method:    oicEdrStateChangedCallback
+ * Signature: (I)V
+ */
+JNIEXPORT void JNICALL
+org_iotivity_ca_CaBtPairingInterface_oicEdrStateChangedCallback
+(JNIEnv *, jobject, jint);
+
+/*
+ * Class:     org_iotivity_ca_OicBtUtilClientInterface
+ * Method:    oicEdrBondStateChangedCallback
+ * Signature: (java/lang/String;)V
+ */
+JNIEXPORT void JNICALL
+org_iotivity_ca_CaBtPairingInterface_oicEdrBondStateChangedCallback
+(JNIEnv *, jobject, jstring);
+
+/*
+ * Class:     org_iotivity_ca_OicBtUtilClientInterface
+ * Method:    oicEdrFoundDeviceCallback
+ * Signature: (BluetoothDevice)V
+ */
+JNIEXPORT void JNICALL
+org_iotivity_ca_CaBtPairingInterface_oicEdrFoundDeviceCallback
+(JNIEnv *, jobject, jobject);
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/resource/csdk/connectivity/util/src/camanager/android/caleautoconnector.c b/resource/csdk/connectivity/util/src/camanager/android/caleautoconnector.c
new file mode 100644 (file)
index 0000000..76f439c
--- /dev/null
@@ -0,0 +1,237 @@
+/* ****************************************************************
+ *
+ * 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 "cacommon.h"
+#include "caleclient.h"
+#include "camanagerleutil.h"
+#include "camanagerdevice.h"
+#include "caleautoconnector.h"
+#include "cacommonutil.h"
+#include "logger.h"
+#include "camutex.h"
+
+#define TAG "OIC_CA_LE_AUTO_CONN"
+
+static const size_t MAX_RETRY_COUNT = 5;
+static const size_t TIMEOUT = 1000000;
+static const size_t WAITING_TIME = 500000;
+
+static ca_mutex g_connectRetryMutex = NULL;
+static ca_cond g_connectRetryCond = NULL;
+
+static ca_mutex g_recoveryMutex = NULL;
+static ca_cond g_recoveryCond = NULL;
+
+CAResult_t CAManagerInitLEAutoConnection()
+{
+    if (NULL == g_connectRetryMutex)
+    {
+        g_connectRetryMutex = ca_mutex_new();
+        if (NULL == g_connectRetryMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_connectRetryCond)
+    {
+        g_connectRetryCond = ca_cond_new();
+        if (NULL == g_connectRetryCond)
+        {
+            OIC_LOG(ERROR, TAG, "ca_cond_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_recoveryMutex)
+    {
+        g_recoveryMutex = ca_mutex_new();
+        if (NULL == g_recoveryMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_recoveryCond)
+    {
+        g_recoveryCond = ca_cond_new();
+        if (NULL == g_recoveryCond)
+        {
+            OIC_LOG(ERROR, TAG, "ca_cond_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    return CA_STATUS_OK;
+}
+
+void CAManagerTerminateLEAutoConnection()
+{
+    if (g_connectRetryCond)
+    {
+        ca_cond_signal(g_connectRetryCond);
+        ca_cond_free(g_connectRetryCond);
+        g_connectRetryCond = NULL;
+    }
+
+    if (g_connectRetryMutex)
+    {
+        ca_mutex_free(g_connectRetryMutex);
+        g_connectRetryMutex = NULL;
+    }
+
+    if (g_recoveryCond)
+    {
+        ca_cond_signal(g_recoveryCond);
+        ca_cond_free(g_recoveryCond);
+        g_recoveryCond = NULL;
+    }
+
+    if (g_recoveryMutex)
+    {
+        ca_mutex_free(g_recoveryMutex);
+        g_recoveryMutex = NULL;
+    }
+}
+
+CAResult_t CAManagerStartAutoConnection(JNIEnv *env, jstring remote_le_address)
+{
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(remote_le_address, TAG, "remote_le_address is null");
+
+    OIC_LOG(DEBUG, TAG, "IN - CAManagerStartAutoConnection");
+
+    if (true == CAManagerGetAutoConnectionFlag(env, remote_le_address))
+    {
+        OIC_LOG(INFO, TAG, "auto connecting.");
+        return CA_STATUS_FAILED;
+    }
+
+    ca_mutex_lock(g_connectRetryMutex);
+
+    for (size_t retry_cnt = 0 ; retry_cnt < MAX_RETRY_COUNT ; retry_cnt++)
+    {
+        // there is retry logic 5 times when connectGatt call has failed
+        // because BT adapter might be not ready yet.
+        if (NULL == CAManagerConnectGatt(env, remote_le_address))
+        {
+            OIC_LOG_V(INFO, TAG, "retry will be started at least %d times after delay 1sec",
+                      MAX_RETRY_COUNT - retry_cnt - 1);
+            if (ca_cond_wait_for(g_connectRetryCond, g_connectRetryMutex, TIMEOUT) == 0)
+            {
+                OIC_LOG(INFO, TAG, "request to connect gatt was canceled");
+                ca_mutex_unlock(g_connectRetryMutex);
+                return CA_STATUS_OK;
+            }
+            // time out. retry connection
+        }
+        else
+        {
+            OIC_LOG(INFO, TAG, "ConnectGatt has called successfully");
+            break;
+        }
+    }
+    ca_mutex_unlock(g_connectRetryMutex);
+    OIC_LOG(DEBUG, TAG, "OUT - CAManagerStartAutoConnection");
+    return CA_STATUS_OK;
+}
+
+jobject CAManagerConnectGatt(JNIEnv *env, jstring remote_le_address)
+{
+    VERIFY_NON_NULL_RET(env, TAG, "env", NULL);
+    VERIFY_NON_NULL_RET(remote_le_address, TAG, "remote_le_address", NULL);
+
+    OIC_LOG(DEBUG, TAG, "IN - CAManagerConnectGatt");
+
+    jobject jni_bluetooth = CAManagerGetRemoteDevice(env, remote_le_address);
+    if (!jni_bluetooth)
+    {
+        OIC_LOG(ERROR, TAG, "jni_bluetooth is null");
+        return NULL;
+    }
+
+    if (!CAManagerIsDeviceBonded(env, jni_bluetooth))
+    {
+        OIC_LOG(INFO, TAG, "device is BONDED_NONE");
+    }
+
+    // request to connection with AutoConnection Flag
+    OIC_LOG(INFO, TAG, "request to gatt connection for auto connection");
+    jobject newGatt = (jobject)CALEClientConnect(env, jni_bluetooth, JNI_TRUE);
+    if (NULL == newGatt)
+    {
+        OIC_LOG(INFO, TAG, "re-connection will be started");
+        return NULL;
+    }
+
+    // set flag auto connection is requested.
+    CAManagerSetAutoConnectionFlag(env, remote_le_address, true);
+
+    OIC_LOG(DEBUG, TAG, "OUT - CAManagerConnectGatt");
+    return newGatt;
+}
+
+CAResult_t CAManagerProcessRecovery(JNIEnv *env, uint16_t adapter_state)
+{
+    VERIFY_NON_NULL(env, TAG, "env");
+    OIC_LOG(DEBUG, TAG, "IN - CAManagerProcessRecovery");
+
+    ca_mutex_lock(g_recoveryMutex);
+    CAResult_t res = CA_STATUS_OK;
+
+    switch(adapter_state)
+    {
+        case STATE_OFF:
+            // adapter will be enabled automatically after WAITING_TIME.
+            if (ca_cond_wait_for(g_recoveryCond, g_recoveryMutex, WAITING_TIME) == 0)
+            {
+                OIC_LOG(INFO, TAG, "BT recovery was canceled");
+            }
+            else
+            {
+                // enabled
+                if (!CAManagerControlAdapter(env, true))
+                {
+                    OIC_LOG(ERROR, TAG, "BT recovery(enable) failure");
+                    res = CA_STATUS_FAILED;
+                }
+            }
+            CAManagerSetBTRecovery(false);
+            break;
+        case START_RECOVERY:
+            if (!CAManagerControlAdapter(env, false))
+            {
+                OIC_LOG(ERROR, TAG, "BT recovery(disable) failure");
+                res = CA_STATUS_FAILED;
+            }
+            CAManagerSetBTRecovery(true);
+            break;
+        default:
+            break;
+    }
+
+    ca_mutex_unlock(g_recoveryMutex);
+    OIC_LOG(DEBUG, TAG, "OUT - CAManagerProcessRecovery");
+
+    return res;
+}
diff --git a/resource/csdk/connectivity/util/src/camanager/android/caleautoconnector.h b/resource/csdk/connectivity/util/src/camanager/android/caleautoconnector.h
new file mode 100644 (file)
index 0000000..4875a88
--- /dev/null
@@ -0,0 +1,74 @@
+/* ****************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef CA_AUTO_CONNECTOR_H_
+#define CA_AUTO_CONNECTOR_H_
+
+#include <jni.h>
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#define STATE_OFF 10
+#define START_RECOVERY 1
+
+/**
+ * start auto connection.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   remote_le_address     remote address.
+ * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
+ */
+CAResult_t CAManagerStartAutoConnection(JNIEnv *env, jstring remote_le_address);
+
+/**
+ * request connect gatt on client in adapter
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   remote_le_address     remote address.
+ * @return  gatt profile object.
+ */
+jobject CAManagerConnectGatt(JNIEnv *env, jstring remote_le_address);
+
+/**
+ * initialize LE AutoConnection.
+ * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
+ */
+CAResult_t CAManagerInitLEAutoConnection();
+
+/**
+ * terminate LE AutoConnection
+ */
+void CAManagerTerminateLEAutoConnection();
+
+/**
+ * process BT recovery.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   adapter_state         recovery state to process.
+ * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
+ */
+CAResult_t CAManagerProcessRecovery(JNIEnv *env, uint16_t adapter_state);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* CA_AUTO_CONNECTOR_H_ */
+
diff --git a/resource/csdk/connectivity/util/src/camanager/android/caleconnectionmanager.c b/resource/csdk/connectivity/util/src/camanager/android/caleconnectionmanager.c
new file mode 100644 (file)
index 0000000..c4e43e3
--- /dev/null
@@ -0,0 +1,685 @@
+/* ****************************************************************
+ *
+ * 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 "logger.h"
+#include "cautilinterface.h"
+#include "camanagerleinterface.h"
+#include "camanagerleutil.h"
+#include "caleautoconnector.h"
+#include "cacommon.h"
+#include "cacommonutil.h"
+#include "camanagerdevice.h"
+#include "caleclient.h"
+#include "caleutils.h"
+
+#define TAG "OIC_CA_MANAGER_LE"
+
+static CAAdapterStateChangedCB g_adapterStateCB = NULL;
+static CAConnectionStateChangedCB g_connStateCB = NULL;
+
+static const jint SUPPORT_ADNROID_API_LEVEL = 18;
+static const jint AUTH_FAIL = 5;
+static const jint LINK_LOSS = 8;
+static const jint ACCEPT_TIMEOUT_EXCEPTION = 16;
+static const jint REMOTE_DISCONNECT = 19;
+static const jint LOCAL_DISCONNECT = 22;
+static const jint CONNECTION_FAILED_TO_BE_EASTABLISHED = 62;
+static const jint USER_REMOVED_BOND = 68;
+static JavaVM *g_jvm = NULL;
+static jobject g_context = NULL;
+static jobject g_connectedDeviceSet = NULL;
+
+void CASetLENetworkMonitorCallbacks(CAAdapterStateChangedCB adapterStateCB,
+                                    CAConnectionStateChangedCB connStateCB)
+{
+    OIC_LOG(DEBUG, TAG, "CASetLENetworkMonitorCallbacks");
+
+    g_adapterStateCB = adapterStateCB;
+    g_connStateCB = connStateCB;
+}
+
+CAResult_t CASetLEClientAutoConnectionDeviceInfo(const char* address)
+{
+    OIC_LOG(DEBUG, TAG, "CASetClientAutoConnectionDeviceInfo");
+    VERIFY_NON_NULL(address, TAG, "address");
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(DEBUG, TAG, "AttachCurrentThread will be called for JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return CA_STATUS_FAILED;
+        }
+        isAttached = true;
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "set [%s] for Auto Connection", address);
+    jstring jni_leAddress = (*env)->NewStringUTF(env, address);
+
+    if (!CAManagerCheckBTAddress(env, jni_leAddress))
+    {
+        OIC_LOG(ERROR, TAG, "this address is not BT address string format");
+        if (isAttached)
+        {
+            (*g_jvm)->DetachCurrentThread(g_jvm);
+        }
+        return CA_STATUS_FAILED;
+    }
+
+    // if there is target address in SharedPreference. it will be reseted.
+    if (CAManagerIsConnectedDeviceAddress(env, g_context,
+                                          jni_leAddress,
+                                          g_connectedDeviceSet))
+    {
+        if (!CAManagerRemoveConnectedDeviceAddress(env, g_context,
+                                                   jni_leAddress,
+                                                   g_connectedDeviceSet))
+        {
+            OIC_LOG(ERROR, TAG, "Preference - remove has failed");
+        }
+        else
+        {
+            OIC_LOG(INFO, TAG, "Preference - remove success");
+        }
+    }
+
+    // it will be added new target address.
+    if (!CAManagerAddConnectedDeviceAddress(env, g_context,
+                                            jni_leAddress, g_connectedDeviceSet))
+    {
+        OIC_LOG(ERROR, TAG, "Preference - putting has failed");
+    }
+    else
+    {
+        OIC_LOG(INFO, TAG, "Preference - putting success");
+    }
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAUnsetLEClientAutoConnectionDeviceInfo(const char* address)
+{
+    OIC_LOG(DEBUG, TAG, "CAUnsetClientAutoConnectionDeviceInfo");
+    VERIFY_NON_NULL(address, TAG, "address");
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(DEBUG, TAG, "AttachCurrentThread will be called for JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return CA_STATUS_FAILED;
+        }
+        isAttached = true;
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "unset [%s] for Auto Connection", address);
+    jstring jni_leAddress = (*env)->NewStringUTF(env, address);
+
+    if (!CAManagerCheckBTAddress(env, jni_leAddress))
+    {
+        OIC_LOG(ERROR, TAG, "this address is not BT address string format");
+        if (isAttached)
+        {
+            (*g_jvm)->DetachCurrentThread(g_jvm);
+        }
+        return CA_STATUS_FAILED;
+    }
+
+    // if there is target address in SharedPreference. it would be removed
+    if (CAManagerIsConnectedDeviceAddress(env, g_context,
+                                          jni_leAddress,
+                                          g_connectedDeviceSet))
+    {
+        if (!CAManagerRemoveConnectedDeviceAddress(env, g_context,
+                                                   jni_leAddress,
+                                                   g_connectedDeviceSet))
+        {
+            OIC_LOG(ERROR, TAG, "Preference - remove has failed");
+        }
+        else
+        {
+            OIC_LOG(INFO, TAG, "Preference - remove success");
+        }
+    }
+
+    // remove target device for auto connection
+    CAResult_t ret = CAManagerRemoveData(env, jni_leAddress);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CAManagerRemoveData has failed");
+    }
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAManagerLEClientInitialize(JNIEnv *env, JavaVM *jvm, jobject context)
+{
+    OIC_LOG(DEBUG, TAG, "CAManagerClientInitialize");
+    VERIFY_NON_NULL(env, TAG, "env");
+    VERIFY_NON_NULL(jvm, TAG, "jvm");
+    VERIFY_NON_NULL(context, TAG, "context");
+
+    jint jni_int_sdk = CALEGetBuildVersion(env);
+    if (jni_int_sdk < SUPPORT_ADNROID_API_LEVEL)
+    {
+        OIC_LOG_V(ERROR, TAG, "it is not supported (%d)", jni_int_sdk);
+        return CA_STATUS_FAILED;
+    }
+
+    g_jvm = jvm;
+    g_context = (*env)->NewGlobalRef(env, context);;
+    CAManagerInitMutexVaraibles();
+    CAManagerInitLEAutoConnection();
+
+    CAManagerCreateACDataList(env);
+
+    // get last connected device list
+    jobject set = NULL;
+    set = CAManagerGetConnectedDeviceAddress(env, g_context);
+    if (!set)
+    {
+        // create new set<String> object
+        set = CAManagerCreateSetString(env);
+        if (set)
+        {
+            OIC_LOG(DEBUG, TAG, "created new SetString");
+        }
+        else
+        {
+            OIC_LOG(ERROR, TAG, "CAManagerCreateSetString has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+    else
+    {
+        OIC_LOG(DEBUG, TAG, "get previous Set<String> object");
+    }
+
+    g_connectedDeviceSet = (jobject)(*env)->NewGlobalRef(env, set);
+    if (!g_connectedDeviceSet)
+    {
+        OIC_LOG(ERROR, TAG, "g_connectedDeviceSet is null");
+        return CA_STATUS_FAILED;
+    }
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAManagerLEClientTerminate(JNIEnv *env)
+{
+    OIC_LOG(DEBUG, TAG, "CAManagerClientTerminate");
+    VERIFY_NON_NULL(env, TAG, "env");
+
+    // stop gatt connection
+    CAResult_t res = CALEClientDisconnectAll(env);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "CALEClientDisconnectAll has failed");
+    }
+
+    res = CAManagerRemoveAllData(env);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "CAManagerRemoveAllData has failed");
+    }
+
+    CAManagerTerminateLEAutoConnection();
+    CAManagerTerminateMutexVariables();
+
+    if (g_context)
+    {
+        (*env)->DeleteGlobalRef(env, g_context);
+        g_context = NULL;
+    }
+
+    if (g_connectedDeviceSet)
+    {
+        (*env)->DeleteGlobalRef(env, g_connectedDeviceSet);
+        g_connectedDeviceSet = NULL;
+    }
+
+    return res;
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaLeClientInterface_caManagerAdapterStateChangedCallback(
+        JNIEnv *env, jobject obj, jint state)
+{
+    OIC_LOG(DEBUG, TAG, "caManagerAdapterStateChangedCallback");
+    VERIFY_NON_NULL_VOID(env, TAG, "env");
+    VERIFY_NON_NULL_VOID(obj, TAG, "obj");
+
+    jint state_on = CALEGetConstantsValue(env, CLASSPATH_BT_ADAPTER, "STATE_ON");
+    jint state_off = CALEGetConstantsValue(env, CLASSPATH_BT_ADAPTER, "STATE_OFF");
+    jint state_turning_off = CALEGetConstantsValue(env, CLASSPATH_BT_ADAPTER, "STATE_TURNING_OFF");
+
+    if (state_on == state)
+    {
+        OIC_LOG(DEBUG, TAG, "AdapterStateChangedCallback : state_on");
+        if (g_adapterStateCB)
+        {
+            g_adapterStateCB(CA_ADAPTER_GATT_BTLE, true);
+        }
+
+        // when BT state is on. recovery flag has to be reset.
+        CAManagerSetBTRecovery(false);
+
+        // find target device for autoconnect
+        size_t length = CAManagerGetACDataLength();
+        OIC_LOG_V(DEBUG, TAG, "target device : %d", length);
+        for (size_t idx = 0; idx < length; idx++)
+        {
+            jstring leAddress = CAManagerGetLEAddressFromACData(env, idx);
+            if (leAddress)
+            {
+                CAResult_t res = CAManagerStartAutoConnection(env, leAddress);
+                if (CA_STATUS_OK != res)
+                {
+                    OIC_LOG(ERROR, TAG, "CAManagerStartAutoConnection has failed");
+                    return;
+                }
+            }
+        }
+    }
+    else if (state_off == state)
+    {
+        OIC_LOG(DEBUG, TAG, "AdapterStateChangedCallback : state_off");
+        if (g_adapterStateCB)
+        {
+            g_adapterStateCB(CA_ADAPTER_GATT_BTLE, false);
+        }
+
+        // reset autoconnect flag for all target devices
+        size_t length = CAManagerGetACDataLength();
+        for (size_t idx = 0; idx < length; idx++)
+        {
+            jstring address = CAManagerGetLEAddressFromACData(env, idx);
+            if (address)
+            {
+                CAManagerSetAutoConnectionFlag(env, address, false);
+            }
+        }
+
+        // check whether BT recovery is needed or not
+        if (CAManagerIsRecoveryFlagSet())
+        {
+            CAManagerProcessRecovery(env, STATE_OFF);
+        }
+    }
+    else if (state_turning_off == state)
+    {
+        OIC_LOG(DEBUG, TAG, "AdapterStateChangedCallback : state_turning_off");
+        return;
+    }
+    else
+    {
+        OIC_LOG(INFO, TAG, "AdapterStateChangedCallback state is not available");
+        return;
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaLeClientInterface_caManagerBondStateChangedCallback(
+        JNIEnv *env, jobject obj, jobject device)
+{
+    OIC_LOG(DEBUG, TAG, "caManagerBondStateChangedCallback");
+    VERIFY_NON_NULL_VOID(env, TAG, "env");
+    VERIFY_NON_NULL_VOID(obj, TAG, "obj");
+    VERIFY_NON_NULL_VOID(device, TAG, "device");
+
+    // get ble address from Bluetooth Device object
+    jstring jni_leAddress = CALEClientGetLEAddressFromBTDevice(env, device);
+    if (!jni_leAddress)
+    {
+        OIC_LOG(INFO, TAG, "unbonded : it isn't same device type");
+        return;
+    }
+
+    char* leAddress = (char*)(*env)->GetStringUTFChars(env, jni_leAddress, NULL);
+    if (!leAddress)
+    {
+        OIC_LOG(ERROR, TAG, "leAddress is null");
+        return;
+    }
+
+    // if there is no data, CAData will be created.
+    OIC_LOG_V(DEBUG, TAG, "bond none device : %s", leAddress);
+
+    CAResult_t res = CAManagerRemoveData(env, jni_leAddress);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "CAManagerRemoveData has failed");
+    }
+
+    (*env)->ReleaseStringUTFChars(env, jni_leAddress, leAddress);
+
+    if (!CAManagerRemoveConnectedDeviceAddress(env, g_context,
+                                               jni_leAddress,
+                                               g_connectedDeviceSet))
+    {
+        OIC_LOG(ERROR, TAG, "CAManagerRemoveConnectedDeviceAddress has failed");
+    }
+
+    OIC_LOG(INFO, TAG, "bonded state changed bone_none");
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaLeClientInterface_caManagerLeGattConnectionStateChangeCB(
+        JNIEnv *env, jobject obj, jobject gatt, jint status, jint newState)
+{
+    OIC_LOG_V(DEBUG, TAG, "caManagerLeGattConnectionStateChangeCB-status(%d), newState(%d)",
+              status, newState);
+
+    VERIFY_NON_NULL_VOID(env, TAG, "env");
+    VERIFY_NON_NULL_VOID(obj, TAG, "obj");
+    VERIFY_NON_NULL_VOID(gatt, TAG, "gatt");
+
+    jint state_connected = CALEGetConstantsValue(env, CLASSPATH_BT_PROFILE, "STATE_CONNECTED");
+    jint state_disconnected = CALEGetConstantsValue(env, CLASSPATH_BT_PROFILE, "STATE_DISCONNECTED");
+    jint gatt_success = CALEGetConstantsValue(env, CLASSPATH_BT_GATT, "GATT_SUCCESS");
+
+    jstring jni_address = CAManagerGetAddressFromGatt(env, gatt);
+    if (!jni_address)
+    {
+        OIC_LOG(ERROR, TAG, "CAManagerGetAddressFromGatt is null");
+        return;
+    }
+
+    char* address = (char*)(*env)->GetStringUTFChars(env, jni_address, NULL);
+    if (!address)
+    {
+        OIC_LOG(ERROR, TAG, "address is null");
+        return;
+    }
+
+    OIC_LOG_V(INFO, TAG, "connection state : status(%d), addr:(%s), newState(%d)",
+              status, address, newState);
+
+    if (gatt_success == status && state_connected == newState) // le connected
+    {
+        OIC_LOG(DEBUG, TAG, "LE is connected");
+        CAResult_t res = CAManagerReadRemoteRssi(env, gatt);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "CAManagerReadRemoteRssi has failed");
+            (*env)->ReleaseStringUTFChars(env, jni_address, address);
+            return;
+        }
+    }
+    else if (state_disconnected == newState)// le disconnected
+    {
+        if (LINK_LOSS == status || REMOTE_DISCONNECT == status)
+        {
+            OIC_LOG(DEBUG, TAG, "LE is disconnected");
+
+            if (g_connStateCB)
+            {
+                OIC_LOG_V(DEBUG, TAG, "LE Disconnected state is %d, %s", newState, address);
+                g_connStateCB(CA_ADAPTER_GATT_BTLE, address, false);
+                OIC_LOG(DEBUG, TAG, "LE Disconnected state callback is called");
+            }
+
+            if (!CAManagerIsMatchedACData(env, jni_address))
+            {
+                OIC_LOG_V(DEBUG, TAG, "this[%s] is not target address for Auto Connection",
+                          address);
+                (*env)->ReleaseStringUTFChars(env, jni_address, address);
+                return;
+            }
+
+            CAManagerSetAutoConnectionFlag(env, jni_address, false);
+
+            CAResult_t res = CAManagerStartAutoConnection(env, jni_address);
+            if (CA_STATUS_OK != res)
+            {
+                (*env)->ReleaseStringUTFChars(env, jni_address, address);
+                OIC_LOG(ERROR, TAG, "CAManagerStartAutoConnection has failed");
+                return;
+            }
+        }
+        else if (ACCEPT_TIMEOUT_EXCEPTION == status)
+        {
+            CAManagerProcessRecovery(env, START_RECOVERY);
+        }
+    }
+    (*env)->ReleaseStringUTFChars(env, jni_address, address);
+    (*env)->DeleteLocalRef(env, jni_address);
+}
+
+/*
+ * Class:     org_iotivity_ca_jar_caleinterface
+ * Method:    caManagerLeServicesDiscoveredCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;I)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaLeClientInterface_caManagerLeServicesDiscoveredCallback(JNIEnv *env,
+                                                                               jobject obj,
+                                                                               jobject gatt,
+                                                                               jint status)
+{
+    OIC_LOG_V(DEBUG, TAG, "caManagerLeServicesDiscoveredCallback - status %d: ", status);
+    VERIFY_NON_NULL_VOID(env, TAG, "env");
+    VERIFY_NON_NULL_VOID(obj, TAG, "obj");
+    VERIFY_NON_NULL_VOID(gatt, TAG, "gatt");
+
+    if (GATT_SUCCESS == status)
+    {
+        if (!g_connectedDeviceSet)
+        {
+            OIC_LOG(ERROR, TAG, "g_connectedDeviceSet is null");
+            return;
+        }
+
+        jstring jni_address = CAManagerGetAddressFromGatt(env, gatt);
+        if (!jni_address)
+        {
+            OIC_LOG(ERROR, TAG, "CAManagerGetAddressFromGatt is null");
+            return;
+        }
+
+        char* address = (char*)(*env)->GetStringUTFChars(env, jni_address, NULL);
+        if (!address)
+        {
+            OIC_LOG(ERROR, TAG, "address is null");
+            (*env)->DeleteLocalRef(env, jni_address);
+            return;
+        }
+        OIC_LOG_V(DEBUG, TAG, "ServicesDiscovered device : %s", address);
+
+        // target address for auto connection will be set in device list.
+        // check set connected address information by user
+        jclass jni_cls_set = (*env)->FindClass(env, "java/util/HashSet");
+        if (!jni_cls_set)
+        {
+            OIC_LOG(ERROR, TAG, "jni_cls_set is null");
+            (*env)->ReleaseStringUTFChars(env, jni_address, address);
+            (*env)->DeleteLocalRef(env, jni_address);
+            return;
+        }
+
+        jmethodID jni_mid_iterator = (*env)->GetMethodID(env, jni_cls_set, "iterator",
+                                                            "()Ljava/util/Iterator;");
+        if (!jni_mid_iterator)
+        {
+            OIC_LOG(ERROR, TAG, "jni_mid_iterator is null");
+            (*env)->DeleteLocalRef(env, jni_cls_set);
+            (*env)->ReleaseStringUTFChars(env, jni_address, address);
+            (*env)->DeleteLocalRef(env, jni_address);
+            return;
+        }
+
+        jobject jni_obj_iter = (*env)->CallObjectMethod(env, g_connectedDeviceSet, jni_mid_iterator);
+        if (!jni_obj_iter)
+        {
+            OIC_LOG(ERROR, TAG, "jni_obj_iter is null");
+            (*env)->DeleteLocalRef(env, jni_cls_set);
+            (*env)->ReleaseStringUTFChars(env, jni_address, address);
+            (*env)->DeleteLocalRef(env, jni_address);
+            return;
+        }
+
+        // Get the Iterator method IDs
+        jclass jni_cls_iterator = (*env)->FindClass(env, "java/util/Iterator");
+        if (!jni_cls_iterator)
+        {
+            OIC_LOG(ERROR, TAG, "jni_cls_iterator is null");
+            (*env)->DeleteLocalRef(env, jni_obj_iter);
+            (*env)->DeleteLocalRef(env, jni_cls_set);
+            (*env)->ReleaseStringUTFChars(env, jni_address, address);
+            (*env)->DeleteLocalRef(env, jni_address);
+            return;
+        }
+
+        jmethodID jni_mid_hasNext = (*env)->GetMethodID(env, jni_cls_iterator, "hasNext", "()Z");
+        if (!jni_mid_hasNext)
+        {
+            OIC_LOG(ERROR, TAG, "jni_mid_hasNext is null");
+            (*env)->DeleteLocalRef(env, jni_cls_iterator);
+            (*env)->DeleteLocalRef(env, jni_obj_iter);
+            (*env)->DeleteLocalRef(env, jni_cls_set);
+            (*env)->ReleaseStringUTFChars(env, jni_address, address);
+            (*env)->DeleteLocalRef(env, jni_address);
+            return;
+        }
+
+        jmethodID jni_mid_next = (*env)->GetMethodID(env, jni_cls_iterator, "next",
+                                                        "()Ljava/lang/Object;");
+        if (!jni_mid_next)
+        {
+            OIC_LOG(ERROR, TAG, "jni_mid_next is null");
+            (*env)->DeleteLocalRef(env, jni_cls_iterator);
+            (*env)->DeleteLocalRef(env, jni_obj_iter);
+            (*env)->DeleteLocalRef(env, jni_cls_set);
+            (*env)->ReleaseStringUTFChars(env, jni_address, address);
+            (*env)->DeleteLocalRef(env, jni_address);
+            return;
+        }
+
+        // Iterate over the entry Set
+        while ((*env)->CallBooleanMethod(env, jni_obj_iter, jni_mid_hasNext))
+        {
+            jstring jni_str_entry = (jstring)(*env)->CallObjectMethod(env, jni_obj_iter,
+                                                                        jni_mid_next);
+            if (!jni_str_entry)
+            {
+                OIC_LOG(ERROR, TAG, "jni_str_entry is null");
+                (*env)->DeleteLocalRef(env, jni_cls_iterator);
+                (*env)->DeleteLocalRef(env, jni_obj_iter);
+                (*env)->DeleteLocalRef(env, jni_cls_set);
+                (*env)->ReleaseStringUTFChars(env, jni_address, address);
+                (*env)->DeleteLocalRef(env, jni_address);
+                return;
+            }
+            const char* foundAddress = (*env)->GetStringUTFChars(env, jni_str_entry, NULL);
+            if (!foundAddress)
+            {
+                OIC_LOG(ERROR, TAG, "addr is null");
+                (*env)->DeleteLocalRef(env, jni_str_entry);
+                (*env)->DeleteLocalRef(env, jni_cls_iterator);
+                (*env)->DeleteLocalRef(env, jni_obj_iter);
+                (*env)->DeleteLocalRef(env, jni_cls_set);
+                (*env)->ReleaseStringUTFChars(env, jni_address, address);
+                (*env)->DeleteLocalRef(env, jni_address);
+                return;
+            }
+            OIC_LOG_V(INFO, TAG, "found last connected address [%s] from SharedPreferences",
+                      foundAddress);
+
+            if (!strcmp(foundAddress, address))
+            {
+                // if BLE address is matched each other
+                // this address will be added into auto connection list.
+                OIC_LOG(INFO, TAG, "AC list - address will be added into ACData list");
+                CAManagerAddACData(env, jni_address);
+                CAManagerSetAutoConnectionFlag(env, jni_address, false);
+
+                // next connection will be requested as JNI_TRUE flag
+                // after first connection
+                CALEClientSetAutoConnectFlag(env, jni_str_entry, JNI_TRUE);
+            }
+            else
+            {
+                OIC_LOG(INFO, TAG, "AC list - device is not matched");
+            }
+
+            (*env)->ReleaseStringUTFChars(env, jni_str_entry, foundAddress);
+            (*env)->DeleteLocalRef(env, jni_str_entry);
+        }
+
+        if (g_connStateCB)
+        {
+            g_connStateCB(CA_ADAPTER_GATT_BTLE, address, true);
+            OIC_LOG(DEBUG, TAG, "LE Connected callback is called");
+        }
+
+        (*env)->DeleteLocalRef(env, jni_cls_iterator);
+        (*env)->DeleteLocalRef(env, jni_obj_iter);
+        (*env)->DeleteLocalRef(env, jni_cls_set);
+        (*env)->ReleaseStringUTFChars(env, jni_address, address);
+        (*env)->DeleteLocalRef(env, jni_address);
+        OIC_LOG(INFO, TAG, "ServicesDiscovery is successful");
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "ServicesDiscovery has failed");
+    }
+}
+
+/*
+ * Class:     org_iotivity_ca_jar_caleinterface
+ * Method:    caManagerLeRemoteRssiCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;I)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaLeClientInterface_caManagerLeRemoteRssiCallback(JNIEnv *env,
+                                                                       jobject obj,
+                                                                       jobject gatt,
+                                                                       jint rssi,
+                                                                       jint status)
+{
+    OIC_LOG_V(DEBUG, TAG, "caManagerLeRemoteRssiCallback - rssi : %d: ", rssi);
+    OIC_LOG_V(DEBUG, TAG, "caManagerLeRemoteRssiCallback - status : %d: ", status);
+    VERIFY_NON_NULL_VOID(env, TAG, "env");
+    VERIFY_NON_NULL_VOID(obj, TAG, "obj");
+    VERIFY_NON_NULL_VOID(gatt, TAG, "gatt");
+}
diff --git a/resource/csdk/connectivity/util/src/camanager/android/camanagerdevice.c b/resource/csdk/connectivity/util/src/camanager/android/camanagerdevice.c
new file mode 100644 (file)
index 0000000..6950361
--- /dev/null
@@ -0,0 +1,427 @@
+/* ****************************************************************
+ *
+ * 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 "cacommon.h"
+#include "logger.h"
+#include "cacommonutil.h"
+#include "camanagerleutil.h"
+#include "uarraylist.h"
+#include "camutex.h"
+#include "camanagerdevice.h"
+#include "oic_malloc.h"
+
+#define TAG "OIC_CA_MANAGER_DEVICE"
+
+static u_arraylist_t *g_deviceACDataList = NULL;
+static ca_mutex g_deviceACDataListMutex = NULL;
+static bool g_isBTRecovery = false;
+
+jstring CAManagerGetLEAddressFromACData(JNIEnv *env, size_t idx)
+{
+    OIC_LOG(DEBUG, TAG, "CAManagerGetLEAddressFromACData");
+    OIC_LOG_V(DEBUG, TAG, "idx : %d", idx);
+    if (idx <= u_arraylist_length(g_deviceACDataList))
+    {
+        CAManagerACData_t *curData = (CAManagerACData_t *) u_arraylist_get(
+                g_deviceACDataList, idx);
+        if (!curData)
+        {
+            OIC_LOG(ERROR, TAG, "curData is null");
+            return NULL;
+        }
+
+        const char* address = (*env)->GetStringUTFChars(env, curData->address, NULL);
+        if (!address)
+        {
+            OIC_LOG(ERROR, TAG, "address is null");
+            return NULL;
+        }
+        OIC_LOG_V(INFO, TAG, "found out target address : %s", address);
+        (*env)->ReleaseStringUTFChars(env, curData->address, address);
+
+        return curData->address;
+    }
+    return NULL;
+}
+
+void CAManagerCreateACDataList(JNIEnv *env)
+{
+    OIC_LOG(DEBUG, TAG, "CAManagerCreateACDataList");
+    VERIFY_NON_NULL_VOID(env, TAG, "env");
+
+    ca_mutex_lock(g_deviceACDataListMutex);
+    // create new object array
+    if (g_deviceACDataList == NULL)
+    {
+        OIC_LOG(DEBUG, TAG, "Create AC Data list");
+
+        g_deviceACDataList = u_arraylist_create();
+    }
+    ca_mutex_unlock(g_deviceACDataListMutex);
+}
+
+CAResult_t CAManagerInitMutexVaraibles()
+{
+    if (NULL == g_deviceACDataListMutex)
+    {
+        g_deviceACDataListMutex = ca_mutex_new();
+        if (NULL == g_deviceACDataListMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+    return CA_STATUS_OK;
+}
+
+void CAManagerTerminateMutexVariables()
+{
+    if (g_deviceACDataListMutex)
+    {
+        ca_mutex_free(g_deviceACDataListMutex);
+        g_deviceACDataListMutex = NULL;
+    }
+}
+
+static CAManagerACData_t *CAManagerCreateACData(jstring jaddress)
+{
+    OIC_LOG(DEBUG, TAG, "IN-CAManagerCreateACData");
+    VERIFY_NON_NULL_RET(jaddress, TAG, "jaddress", NULL);
+
+    // create block data
+    CAManagerACData_t *data = (CAManagerACData_t *) OICCalloc(1, sizeof(*data));
+    if (!data)
+    {
+        OIC_LOG(ERROR, TAG, "memory alloc has failed");
+        return NULL;
+    }
+
+    data->address = jaddress;
+    data->isAutoConnect = false;
+
+    OIC_LOG(DEBUG, TAG, "OUT-CAManagerCreateACData");
+    return data;
+}
+
+bool CAManagerIsMatchedACData(JNIEnv *env, jstring jaddress)
+{
+    VERIFY_NON_NULL_RET(env, TAG, "env", NULL);
+    VERIFY_NON_NULL_RET(jaddress, TAG, "jaddress", false);
+
+    const char* address = (*env)->GetStringUTFChars(env, jaddress, NULL);
+    if (!address)
+    {
+        OIC_LOG(ERROR, TAG, "address is null");
+        return false;
+    }
+
+    size_t length = u_arraylist_length(g_deviceACDataList);
+    for (size_t idx = 0; idx < length; idx++)
+    {
+        CAManagerACData_t *curData = (CAManagerACData_t *) u_arraylist_get(g_deviceACDataList,
+                                                                           idx);
+        if (!curData)
+        {
+            OIC_LOG(ERROR, TAG, "curData is null");
+            (*env)->ReleaseStringUTFChars(env, jaddress, address);
+            return false;
+        }
+
+        const char* setAddress = (*env)->GetStringUTFChars(env, curData->address, NULL);
+        if (!setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "address is null");
+            (*env)->ReleaseStringUTFChars(env, jaddress, address);
+            return false;
+        }
+
+        if (!strcmp(setAddress, address))
+        {
+            (*env)->ReleaseStringUTFChars(env, curData->address, setAddress);
+            (*env)->ReleaseStringUTFChars(env, jaddress, address);
+            return true;
+        }
+        (*env)->ReleaseStringUTFChars(env, curData->address, setAddress);
+    }
+    (*env)->ReleaseStringUTFChars(env, jaddress, address);
+
+    return false;
+}
+
+void CAManagerAddACData(JNIEnv *env, jstring jaddress)
+{
+    OIC_LOG(DEBUG, TAG, "IN-CAManagerAddACData");
+
+    VERIFY_NON_NULL_VOID(env, TAG, "env");
+    VERIFY_NON_NULL_VOID(jaddress, TAG, "jaddress");
+
+    ca_mutex_lock(g_deviceACDataListMutex);
+
+    if(!CAManagerIsMatchedACData(env, jaddress))
+    {
+        OIC_LOG(DEBUG, TAG, "ACdata will be added");
+        // add CAManagerACData
+        jobject gaddress = (*env)->NewGlobalRef(env, jaddress);
+
+        CAManagerACData_t *data = CAManagerCreateACData(gaddress);
+        u_arraylist_add(g_deviceACDataList, data);
+    }
+    ca_mutex_unlock(g_deviceACDataListMutex);
+
+    OIC_LOG(DEBUG, TAG, "OUT-CAManagerAddACData");
+}
+
+CAResult_t CAManagerRemoveData(JNIEnv *env, jstring jaddress)
+{
+    OIC_LOG(DEBUG, TAG, "IN-CAManagerRemoveData");
+    VERIFY_NON_NULL(env, TAG, "env");
+    VERIFY_NON_NULL(jaddress, TAG, "jaddress");
+
+    ca_mutex_lock(g_deviceACDataListMutex);
+
+    const char* address = (*env)->GetStringUTFChars(env, jaddress, NULL);
+    if (!address)
+    {
+        OIC_LOG(ERROR, TAG, "address is null");
+        ca_mutex_unlock(g_deviceACDataListMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "(%s) will be removed", address);
+
+    size_t length = u_arraylist_length(g_deviceACDataList);
+    for (size_t idx = 0; idx < length; idx++)
+    {
+        CAManagerACData_t *curData = (CAManagerACData_t *) u_arraylist_get(g_deviceACDataList,
+                                                                           idx);
+        if (!curData)
+        {
+            OIC_LOG(ERROR, TAG, "curData is null");
+            (*env)->ReleaseStringUTFChars(env, jaddress, address);
+            ca_mutex_unlock(g_deviceACDataListMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        const char* setAddress = (*env)->GetStringUTFChars(env, curData->address, NULL);
+        if (!setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "address is null");
+            (*env)->ReleaseStringUTFChars(env, jaddress, address);
+            ca_mutex_unlock(g_deviceACDataListMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        if (!strcmp(setAddress, address))
+        {
+            if (NULL == u_arraylist_remove(g_deviceACDataList, idx))
+            {
+                OIC_LOG(ERROR, TAG, "removal has failed.");
+                (*env)->ReleaseStringUTFChars(env, jaddress, address);
+                (*env)->ReleaseStringUTFChars(env, curData->address, setAddress);
+                ca_mutex_unlock(g_deviceACDataListMutex);
+                return CA_STATUS_FAILED;
+            }
+
+            (*env)->ReleaseStringUTFChars(env, curData->address, setAddress);
+
+            if (curData->address)
+            {
+                (*env)->DeleteGlobalRef(env, curData->address);
+            }
+
+            OICFree(curData);
+            (*env)->ReleaseStringUTFChars(env, jaddress, address);
+            ca_mutex_unlock(g_deviceACDataListMutex);
+            OIC_LOG(DEBUG, TAG, "remove done");
+            return CA_STATUS_OK;
+        }
+        (*env)->ReleaseStringUTFChars(env, curData->address, setAddress);
+    }
+
+    (*env)->ReleaseStringUTFChars(env, jaddress, address);
+    ca_mutex_unlock(g_deviceACDataListMutex);
+    OIC_LOG(DEBUG, TAG, "OUT-CAManagerRemoveData");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAManagerRemoveAllData(JNIEnv *env)
+{
+    OIC_LOG(DEBUG, TAG, "IN-CAManagerRemoveAllData");
+    VERIFY_NON_NULL(env, TAG, "env");
+
+    ca_mutex_lock(g_deviceACDataListMutex);
+
+    size_t length = u_arraylist_length(g_deviceACDataList);
+    for (size_t idx = 0; idx < length; idx++)
+    {
+        CAManagerACData_t *curData = (CAManagerACData_t *) u_arraylist_get(g_deviceACDataList,
+                                                                           idx);
+        if (!curData)
+        {
+            OIC_LOG(ERROR, TAG, "curData is null");
+            ca_mutex_unlock(g_deviceACDataListMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        if (NULL == u_arraylist_remove(g_deviceACDataList, idx))
+        {
+            OIC_LOG(ERROR, TAG, "removal has failed.");
+            ca_mutex_unlock(g_deviceACDataListMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        if (curData->address)
+        {
+            (*env)->DeleteGlobalRef(env, curData->address);
+        }
+
+        OICFree(curData);
+    }
+    ca_mutex_unlock(g_deviceACDataListMutex);
+    OIC_LOG(DEBUG, TAG, "OUT-CAManagerRemoveAllData");
+    return CA_STATUS_OK;
+}
+
+bool CAManagerGetAutoConnectionFlag(JNIEnv *env, jstring jaddress)
+{
+    OIC_LOG(DEBUG, TAG, "IN-CAManagerGetAutoConnectionFlag");
+    VERIFY_NON_NULL_RET(env, TAG, "env", NULL);
+    VERIFY_NON_NULL_RET(jaddress, TAG, "jaddress", NULL);
+
+    ca_mutex_lock(g_deviceACDataListMutex);
+
+    const char* address = (*env)->GetStringUTFChars(env, jaddress, NULL);
+    if (!address)
+    {
+        OIC_LOG(ERROR, TAG, "address is null");
+        ca_mutex_unlock(g_deviceACDataListMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    size_t length = u_arraylist_length(g_deviceACDataList);
+    for (size_t idx = 0; idx < length; idx++)
+    {
+        CAManagerACData_t *curData = (CAManagerACData_t *) u_arraylist_get(g_deviceACDataList,
+                                                                           idx);
+        if (!curData)
+        {
+            OIC_LOG(ERROR, TAG, "curData is null");
+            (*env)->ReleaseStringUTFChars(env, jaddress, address);
+            ca_mutex_unlock(g_deviceACDataListMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        const char* setAddress = (*env)->GetStringUTFChars(env, curData->address, NULL);
+        if (!setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "setAddress is null");
+            (*env)->ReleaseStringUTFChars(env, jaddress, address);
+            ca_mutex_unlock(g_deviceACDataListMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        if (!strcmp(setAddress, address))
+        {
+            (*env)->ReleaseStringUTFChars(env, curData->address, setAddress);
+            (*env)->ReleaseStringUTFChars(env, jaddress, address);
+            ca_mutex_unlock(g_deviceACDataListMutex);
+            OIC_LOG_V(DEBUG, TAG, "flag is %d", curData->isAutoConnect);
+            return curData->isAutoConnect;
+        }
+        (*env)->ReleaseStringUTFChars(env, curData->address, setAddress);
+    }
+    (*env)->ReleaseStringUTFChars(env, jaddress, address);
+    ca_mutex_unlock(g_deviceACDataListMutex);
+
+    OIC_LOG(DEBUG, TAG, "OUT-CAManagerGetAutoConnectionFlag");
+    return false;
+}
+
+void CAManagerSetAutoConnectionFlag(JNIEnv *env, jstring jaddress, bool flag)
+{
+    OIC_LOG(DEBUG, TAG, "IN-CAManagerSetAutoConnectionFlag");
+    VERIFY_NON_NULL_VOID(env, TAG, "env");
+    VERIFY_NON_NULL_VOID(jaddress, TAG, "jaddress");
+
+    ca_mutex_lock(g_deviceACDataListMutex);
+
+    const char* address = (*env)->GetStringUTFChars(env, jaddress, NULL);
+    if (!address)
+    {
+        OIC_LOG(ERROR, TAG, "address is null");
+        ca_mutex_unlock(g_deviceACDataListMutex);
+        return;
+    }
+
+    size_t length = u_arraylist_length(g_deviceACDataList);
+    for (size_t idx = 0; idx < length; idx++)
+    {
+        CAManagerACData_t *curData = (CAManagerACData_t *) u_arraylist_get(g_deviceACDataList,
+                                                                           idx);
+        if (!curData)
+        {
+            OIC_LOG(ERROR, TAG, "curData is null");
+            (*env)->ReleaseStringUTFChars(env, jaddress, address);
+            ca_mutex_unlock(g_deviceACDataListMutex);
+            return;
+        }
+
+        const char* setAddress = (*env)->GetStringUTFChars(env, curData->address, NULL);
+        if (!setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "address is null");
+            (*env)->ReleaseStringUTFChars(env, jaddress, address);
+            ca_mutex_unlock(g_deviceACDataListMutex);
+            return;
+        }
+
+        if (!strcmp(setAddress, address))
+        {
+            OIC_LOG_V(DEBUG, TAG, "flag is set to %d", flag);
+            curData->isAutoConnect = flag;
+            (*env)->ReleaseStringUTFChars(env, curData->address, setAddress);
+            (*env)->ReleaseStringUTFChars(env, jaddress, address);
+            ca_mutex_unlock(g_deviceACDataListMutex);
+            return;
+        }
+        (*env)->ReleaseStringUTFChars(env, curData->address, setAddress);
+    }
+    (*env)->ReleaseStringUTFChars(env, jaddress, address);
+    ca_mutex_unlock(g_deviceACDataListMutex);
+
+    OIC_LOG(DEBUG, TAG, "OUT-CAManagerSetAutoConnectionFlag");
+}
+
+size_t CAManagerGetACDataLength()
+{
+    return u_arraylist_length(g_deviceACDataList);
+}
+
+void CAManagerSetBTRecovery(bool flag)
+{
+    g_isBTRecovery = flag;
+    OIC_LOG_V(DEBUG, TAG, "BT recovery flag : %d", g_isBTRecovery);
+}
+
+bool CAManagerIsRecoveryFlagSet()
+{
+    return g_isBTRecovery;
+}
diff --git a/resource/csdk/connectivity/util/src/camanager/android/camanagerdevice.h b/resource/csdk/connectivity/util/src/camanager/android/camanagerdevice.h
new file mode 100644 (file)
index 0000000..f3ec358
--- /dev/null
@@ -0,0 +1,135 @@
+/* ****************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef CA_MANAGER_DEVICE_H_
+#define CA_MANAGER_DEVICE_H_
+
+#include <jni.h>
+#include "uarraylist.h"
+#include "camutex.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/*
+ * Auto Connection Target Device Identity
+ */
+typedef struct
+{
+    jstring address;      /**< remote address */
+    bool isAutoConnect;   /**< auto connection flag */
+} CAManagerACData_t;
+
+/**
+ * get address from auto connection list.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   idx                   index of auto connection data list.
+ * @return  address
+ */
+jstring CAManagerGetLEAddressFromACData(JNIEnv *env, size_t idx);
+
+/**
+ * create auto connection list.
+ * @param[in]   env                   JNI interface pointer.
+ */
+void CAManagerCreateACDataList(JNIEnv *env);
+
+/**
+ * initialize mutex.
+ * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
+ */
+CAResult_t CAManagerInitMutexVaraibles();
+
+/**
+ * terminate mutex.
+ */
+void CAManagerTerminateMutexVariables();
+
+/**
+ * check whether target address is already contained in list or not.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   jaddress              ble address.
+ */
+bool CAManagerIsMatchedACData(JNIEnv *env, jstring jaddress);
+
+/**
+ * add auto connection data into list.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   jaddress              ble address.
+ */
+void CAManagerAddACData(JNIEnv *env, jstring jaddress);
+
+/**
+ * remove auto connection data for selected ble address.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   jaddress              ble address.
+ * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
+ */
+CAResult_t CAManagerRemoveData(JNIEnv *env, jstring jaddress);
+
+/**
+ * remove auto connection data for all devices.
+ * @param[in]   env                   JNI interface pointer.
+ * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
+ */
+CAResult_t CAManagerRemoveAllData(JNIEnv *env);
+
+/**
+ * get current auto connection flag.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   jaddress              ble address.
+ * @return  true or false
+ */
+bool CAManagerGetAutoConnectionFlag(JNIEnv *env, jstring jaddress);
+
+/**
+ * set auto connection flag.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   jaddress              ble address.
+ * @param[in]   flag                  auto connection flag.
+ */
+void CAManagerSetAutoConnectionFlag(JNIEnv *env, jstring jaddress, bool flag);
+
+/**
+ * get length of auto connection list.
+ * @return  list size
+ */
+size_t CAManagerGetACDataLength();
+
+/**
+ * set BT adapter recovery flag.
+ * @param[in]   flag                  recovery flag.
+ */
+void CAManagerSetBTRecovery(bool flag);
+
+/**
+ * get BT adapter recovery flag.
+ * @return  recovery flag.
+ */
+bool CAManagerIsRecoveryFlagSet();
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* CA_MANAGER_DEVICE_H_ */
+
diff --git a/resource/csdk/connectivity/util/src/camanager/android/camanagerleutil.c b/resource/csdk/connectivity/util/src/camanager/android/camanagerleutil.c
new file mode 100644 (file)
index 0000000..67ed86e
--- /dev/null
@@ -0,0 +1,807 @@
+/* ****************************************************************
+ *
+ * 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 "cacommon.h"
+#include "logger.h"
+#include "cacommonutil.h"
+#include "camanagerleutil.h"
+#include "caleclient.h"
+#include "caleutils.h"
+
+#define TAG "OIC_CA_MANAGER_UTIL"
+
+static const char CLASSPATH_CONTENT_PREF[] = "android/content/SharedPreferences";
+static const char CLASSPATH_CONTENT_PREF_EDITOR[] = "android/content/SharedPreferences$Editor";
+static const char CLASSPATH_CONTEXT[] = "android/content/Context";
+
+static const char PREF_NAME_CONNECTED_DEVICE[] = "PREF_NAME_CONNECTED_DEVICE";
+static const char PREF_KEY_CONNECTED_DEVICE[] = "PREF_KEY_CONNECTED_DEVICE";
+
+static const char METHODID_BOOLEAN_RET_STRING_PARAM[] = "(Ljava/lang/String;)Z";
+
+static jobject CAManagerGetAdapterContext(JNIEnv *env)
+{
+    OIC_LOG(DEBUG, TAG, "CAManagerGetAdapterContext");
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
+
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADAPTER);
+    if (!jni_cid_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BTAdapter: jni_cid_BTAdapter is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
+                                                                    "getDefaultAdapter",
+                                                                    METHODID_OBJECTNONPARAM);
+    if (!jni_mid_getDefaultAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null");
+        return NULL;
+    }
+
+    jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+                                                               jni_mid_getDefaultAdapter);
+    if (!jni_obj_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_BTAdapter is null");
+        return NULL;
+    }
+    return jni_obj_BTAdapter;
+}
+
+jobject CAManagerGetRemoteDevice(JNIEnv *env, jstring address)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CAManagerGetRemoteDevice");
+
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
+    VERIFY_NON_NULL_RET(address, TAG, "address is null", NULL);
+
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADAPTER);
+    if (!jni_cid_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BTAdapter is null");
+        return NULL;
+    }
+
+    // get remote bt adapter method
+    jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
+                                                                    "getDefaultAdapter",
+                                                                    METHODID_OBJECTNONPARAM);
+    if (!jni_mid_getDefaultAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null");
+        return NULL;
+    }
+
+    // gat bt adapter object
+    jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+                                                               jni_mid_getDefaultAdapter);
+    if (!jni_obj_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_BTAdapter is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_getRemoteDevice = (*env)->GetMethodID(env, jni_cid_BTAdapter,
+                                                            "getRemoteDevice",
+                                                            METHODID_BT_REMOTE_DEVICE);
+    if (!jni_mid_getRemoteDevice)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getRemoteDevice is null");
+        return NULL;
+    }
+
+    jobject jni_obj_device = (*env)->CallObjectMethod(env, jni_obj_BTAdapter,
+                                                      jni_mid_getRemoteDevice,
+                                                      address);
+    if (!jni_obj_device)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_device is null");
+        return NULL;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT - CAManagerGetRemoteDevice");
+    return jni_obj_device;
+}
+
+jstring CAManagerGetAddressFromGatt(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);
+
+    jclass jni_cid_gattdevice_list = (*env)->FindClass(env, CLASSPATH_BT_GATT);
+    if (!jni_cid_gattdevice_list)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_gattdevice_list is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_getDevice = (*env)->GetMethodID(env, jni_cid_gattdevice_list, "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;
+}
+
+bool CAManagerIsDeviceBonded(JNIEnv *env, jobject btDevice)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CAManagerIsDeviceBonded");
+
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(btDevice, TAG, "btDevice is null");
+
+    jclass jni_cid_BTDevice = (*env)->FindClass(env, CLASSPATH_BT_DEVICE);
+    if (!jni_cid_BTDevice)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BTDevice is null");
+        return false;
+    }
+
+    jmethodID jni_mid_getBondState = (*env)->GetMethodID(env, jni_cid_BTDevice,
+                                                         "getBondState", "()I");
+    if (!jni_mid_getBondState)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getBondState is null");
+        return false;
+    }
+
+    jint jni_bond_state = (*env)->CallIntMethod(env, btDevice, jni_mid_getBondState);
+    OIC_LOG_V(DEBUG, TAG, "bond state is %d", jni_bond_state);
+
+    // BOND_BONDED - Constant value : 12 (0x0000000c)
+    jfieldID id_bonded = (*env)->GetStaticFieldID(env, jni_cid_BTDevice,
+                                                  "BOND_BONDED", "I");
+    if (!id_bonded)
+    {
+        OIC_LOG(ERROR, TAG, "id_bonded is null");
+        return false;;
+    }
+
+    jint jni_bonded_const = (*env)->GetStaticIntField(env, jni_cid_BTDevice, id_bonded);
+
+    if (jni_bond_state == jni_bonded_const)
+    {
+        OIC_LOG(INFO, TAG, "it is not bonded to each other");
+        return false;
+    }
+    OIC_LOG(DEBUG, TAG, "OUT - CAManagerIsDeviceBonded");
+    return true;
+}
+
+bool CAManagerControlAdapter(JNIEnv *env, bool control_flag)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CAManagerControlAdapter");
+
+    VERIFY_NON_NULL_RET(env, TAG, "env", false);
+
+    jobject jni_obj_BTAdapter = CAManagerGetAdapterContext(env);
+    if (!jni_obj_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_BTAdapter is null");
+        return false;
+    }
+
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADAPTER);
+    if (!jni_cid_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BTAdapter: jni_cid_BTAdapter is null");
+        return NULL;
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "change adapter : %d", control_flag);
+    jmethodID jni_mid_control = NULL;
+    if (control_flag)
+    {
+        // enable()
+        jni_mid_control = (*env)->GetMethodID(env, jni_cid_BTAdapter, "enable", "()Z");
+    }
+    else
+    {
+        // disable()
+        jni_mid_control = (*env)->GetMethodID(env, jni_cid_BTAdapter, "disable", "()Z");
+    }
+
+    if (!jni_mid_control)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_control is null");
+        return false;
+    }
+
+    OIC_LOG(DEBUG, TAG, "CALL API - Adapter Will be Changed");
+    jboolean jni_res = (*env)->CallBooleanMethod(env, jni_obj_BTAdapter, jni_mid_control);
+
+    return jni_res;
+}
+
+CAResult_t CAManagerReadRemoteRssi(JNIEnv *env, jobject bluetoothGatt)
+{
+    OIC_LOG(DEBUG, TAG, "CAManagerReadRemoteRssi");
+
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(bluetoothGatt, TAG, "bluetoothGatt is null");
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(INFO, TAG, "BT adapter is not enabled");
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    // get BluetoothGatt class
+    OIC_LOG(DEBUG, TAG, "get BluetoothGatt class");
+    jclass jni_cid_BluetoothGatt = (*env)->FindClass(env, CLASSPATH_BT_GATT);
+    if (!jni_cid_BluetoothGatt)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BluetoothGatt is null");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "discovery gatt services method");
+    jmethodID jni_mid_readRemoteRssi = (*env)->GetMethodID(env, jni_cid_BluetoothGatt,
+                                                             "readRemoteRssi", "()Z");
+    if (!jni_mid_readRemoteRssi)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_readRemoteRssi is null");
+        return CA_STATUS_FAILED;
+    }
+    // call disconnect gatt method
+    OIC_LOG(DEBUG, TAG, "CALL API - request readremoteRssi");
+    jboolean ret = (*env)->CallBooleanMethod(env, bluetoothGatt, jni_mid_readRemoteRssi);
+    if (!ret)
+    {
+        OIC_LOG(ERROR, TAG, "readremoteRssi has not been called");
+        return CA_STATUS_FAILED;
+    }
+
+    return CA_STATUS_OK;
+}
+
+jobject CAManagerGetSharedPreference(JNIEnv *env, jobject context, jstring prefName)
+{
+    VERIFY_NON_NULL_RET(env, TAG, "env", NULL);
+    VERIFY_NON_NULL_RET(context, TAG, "context", NULL);
+    VERIFY_NON_NULL_RET(prefName, TAG, "prefName", NULL);
+
+    jclass jni_cls_context = (*env)->FindClass(env, CLASSPATH_CONTEXT);
+    if (!jni_cls_context)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cls_context is null");
+        return NULL;
+    }
+
+    // getSharedPreferences
+    jmethodID jni_mid_getPref = (*env)->GetMethodID(env, jni_cls_context, "getSharedPreferences",
+                                                    "(Ljava/lang/String;I)"
+                                                    "Landroid/content/SharedPreferences;");
+    if (!jni_mid_getPref)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getPref is null");
+        return NULL;
+    }
+
+    jobject jni_obj_sharedPref = (*env)->CallObjectMethod(env, context,
+                                                          jni_mid_getPref,
+                                                          prefName,
+                                                          0);
+    if (!jni_obj_sharedPref)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_sharedPref is null");
+        return NULL;
+    }
+
+    return jni_obj_sharedPref;
+}
+
+jobject CAManagerGetPrefEditObject(JNIEnv *env, jobject context)
+{
+    OIC_LOG(DEBUG, TAG, "IN-CAManagerGetPrefEditObject");
+    VERIFY_NON_NULL_RET(env, TAG, "env", NULL);
+    VERIFY_NON_NULL_RET(context, TAG, "context", NULL);
+
+    jstring jni_str_prefName = (*env)->NewStringUTF(env, PREF_NAME_CONNECTED_DEVICE);
+    if (!jni_str_prefName)
+    {
+        OIC_LOG(ERROR, TAG, "jni_str_prefName is null");
+        return NULL;
+    }
+
+    jstring jni_str_prefKey = (*env)->NewStringUTF(env, PREF_KEY_CONNECTED_DEVICE);
+    if (!jni_str_prefKey)
+    {
+        OIC_LOG(ERROR, TAG, "jni_str_prefKey is null");
+        return NULL;
+    }
+
+    // get SharedPreference
+    jobject jni_obj_pref = CAManagerGetSharedPreference(env, context, jni_str_prefName);
+    if (!jni_obj_pref)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_pref is null");
+        return NULL;
+    }
+
+    // edit()
+    jobject jni_cls_pref = (*env)->FindClass(env, CLASSPATH_CONTENT_PREF);
+    if (!jni_cls_pref)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cls_pref is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_prefEdit = (*env)->GetMethodID(env, jni_cls_pref, "edit",
+                                                     "()Landroid/content/SharedPreferences$Editor;");
+    if (!jni_mid_prefEdit)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_prefEdit is null");
+        return NULL;
+    }
+
+    jobject jni_obj_prefEdit = (*env)->CallObjectMethod(env, jni_obj_pref, jni_mid_prefEdit);
+    if (!jni_obj_prefEdit)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_prefEdit is null");
+        return NULL;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT-CAManagerGetPrefEditObject");
+    return jni_obj_prefEdit;
+}
+
+bool CAManagerUpdatePrefStringSet(JNIEnv *env, jobject context, jobject set)
+{
+    OIC_LOG(DEBUG, TAG, "IN-CAManagerUpdatePrefStringSet");
+
+    VERIFY_NON_NULL_RET(env, TAG, "env", false);
+    VERIFY_NON_NULL_RET(context, TAG, "context", false);
+    VERIFY_NON_NULL_RET(set, TAG, "set", false);
+
+    jstring jni_str_prefKey = (*env)->NewStringUTF(env, PREF_KEY_CONNECTED_DEVICE);
+    if (!jni_str_prefKey)
+    {
+        OIC_LOG(ERROR, TAG, "jni_str_prefKey is null");
+        return false;
+    }
+
+    jobject jni_obj_prefEdit = CAManagerGetPrefEditObject(env, context);
+    if (!jni_obj_prefEdit)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_prefEdit is null");
+        return false;
+    }
+
+    // putString()
+    jobject jni_cls_edit = (*env)->FindClass(env, CLASSPATH_CONTENT_PREF_EDITOR);
+    if (!jni_cls_edit)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cls_edit is null");
+        return false;
+    }
+
+    // get putString method interface
+    jmethodID jni_mid_PrefPutStringSet = (*env)->GetMethodID(env, jni_cls_edit, "putStringSet",
+                                                             "(Ljava/lang/String;Ljava/util/Set;)"
+                                                             "Landroid/content/SharedPreferences"
+                                                             "$Editor;");
+    if (!jni_mid_PrefPutStringSet)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_PrefPutStringSet is null");
+        return false;
+    }
+
+    jobject gSetString = (jobject)(*env)->NewGlobalRef(env, set);
+    if (!gSetString)
+    {
+        OIC_LOG(ERROR, TAG, "gAddress is null");
+        return false;
+    }
+
+    OIC_LOG(DEBUG, TAG, "CALL API - request putString for SharedPreferences.Editor");
+    (*env)->CallObjectMethod(env, jni_obj_prefEdit, jni_mid_PrefPutStringSet,
+                             jni_str_prefKey, gSetString);
+
+    // get commit method interface
+    jmethodID jni_mid_PrefCommit = (*env)->GetMethodID(env, jni_cls_edit, "commit",
+                                                       "()Z");
+    if (!jni_mid_PrefCommit)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_PrefCommit is null");
+        return false;
+    }
+
+    jboolean res = (*env)->CallBooleanMethod(env, jni_obj_prefEdit, jni_mid_PrefCommit);
+
+    OIC_LOG(DEBUG, TAG, "OUT-CAManagerUpdatePrefStringSet");
+    return res;
+}
+
+jobject CAManagerGetPrefStringSet(JNIEnv *env, jobject context)
+{
+    OIC_LOG(DEBUG, TAG, "CAManagerGetPrefStringSet");
+
+    VERIFY_NON_NULL_RET(env, TAG, "env", NULL);
+    VERIFY_NON_NULL_RET(context, TAG, "context", NULL);
+
+    jstring jni_str_prefName = (*env)->NewStringUTF(env, PREF_NAME_CONNECTED_DEVICE);
+    if (!jni_str_prefName)
+    {
+        OIC_LOG(ERROR, TAG, "jni_str_prefName is null");
+        return NULL;
+    }
+
+    jstring jni_str_prefKey = (*env)->NewStringUTF(env, PREF_KEY_CONNECTED_DEVICE);
+    if (!jni_str_prefKey)
+    {
+        OIC_LOG(ERROR, TAG, "jni_str_prefKey is null");
+        return NULL;
+    }
+
+    // get SharedPreference
+    jobject jni_obj_pref = CAManagerGetSharedPreference(env, context, jni_str_prefName);
+    if (!jni_obj_pref)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_pref is null");
+        return NULL;
+    }
+
+    // contains(String key)
+    jobject jni_cls_pref = (*env)->FindClass(env, CLASSPATH_CONTENT_PREF);
+    if (!jni_cls_pref)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cls_pref is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_getStringSet = (*env)->GetMethodID(env, jni_cls_pref, "getStringSet",
+                                                         "(Ljava/lang/String;Ljava/util/Set;)"
+                                                         "Ljava/util/Set;");
+    if (!jni_mid_getStringSet)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getStringSet is null");
+        return NULL;
+    }
+
+    jobject jni_defSet = CAManagerCreateSetString(env);
+    if (!jni_defSet)
+    {
+        OIC_LOG(ERROR, TAG, "jni_defSet is null");
+        return NULL;
+    }
+
+    jobject value = (*env)->CallObjectMethod(env, jni_obj_pref,
+                                             jni_mid_getStringSet,
+                                             jni_str_prefKey,
+                                             jni_defSet);
+
+    return value;
+}
+
+bool CAManagerContainsPrefStringSet(JNIEnv *env, jobject context)
+{
+    OIC_LOG(DEBUG, TAG, "CAManagerContainsPrefStringSet");
+
+    VERIFY_NON_NULL_RET(env, TAG, "env", false);
+    VERIFY_NON_NULL_RET(context, TAG, "context", false);
+
+    jstring jni_str_prefName = (*env)->NewStringUTF(env, PREF_NAME_CONNECTED_DEVICE);
+    if (!jni_str_prefName)
+    {
+        OIC_LOG(ERROR, TAG, "jni_str_prefName is null");
+        return false;
+    }
+
+    jstring jni_str_prefKey = (*env)->NewStringUTF(env, PREF_KEY_CONNECTED_DEVICE);
+    if (!jni_str_prefKey)
+    {
+        OIC_LOG(ERROR, TAG, "jni_str_prefKey is null");
+        return false;
+    }
+
+    // get SharedPreference
+    jobject jni_obj_pref = CAManagerGetSharedPreference(env, context, jni_str_prefName);
+    if (!jni_obj_pref)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_pref is null");
+        return false;
+    }
+
+    // contains(String key)
+    jobject jni_cls_pref = (*env)->FindClass(env, CLASSPATH_CONTENT_PREF);
+    if (!jni_cls_pref)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cls_pref is null");
+        return false;
+    }
+
+    jmethodID jni_mid_prefContains = (*env)->GetMethodID(env, jni_cls_pref, "contains",
+                                                         METHODID_BOOLEAN_RET_STRING_PARAM);
+    if (!jni_mid_prefContains)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_prefContains is null");
+        return false;
+    }
+
+    jboolean res = (*env)->CallBooleanMethod(env, jni_obj_pref,
+                                             jni_mid_prefContains,
+                                             jni_str_prefKey);
+
+    OIC_LOG_V(DEBUG, TAG, "Preference - contains (%d)", res);
+    return res;
+}
+
+bool CAManagerRemovePrefStringSet(JNIEnv *env, jobject context)
+{
+    OIC_LOG(DEBUG, TAG, "CAManagerRemovePrefStringSet");
+
+    VERIFY_NON_NULL_RET(env, TAG, "env", false);
+    VERIFY_NON_NULL_RET(context, TAG, "context", false);
+
+    jstring jni_str_prefKey = (*env)->NewStringUTF(env, PREF_KEY_CONNECTED_DEVICE);
+    if (!jni_str_prefKey)
+    {
+        OIC_LOG(ERROR, TAG, "jni_str_prefKey is null");
+        return false;
+    }
+
+    jobject jni_obj_prefEdit = CAManagerGetPrefEditObject(env, context);
+    if (!jni_obj_prefEdit)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_prefEdit is null");
+        return false;
+    }
+
+    // putString()
+    jobject jni_cls_edit = (*env)->FindClass(env, CLASSPATH_CONTENT_PREF_EDITOR);
+    if (!jni_cls_edit)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cls_edit is null");
+        return false;
+    }
+
+    // get remove method interface
+    jmethodID jni_mid_PrefRemove = (*env)->GetMethodID(env, jni_cls_edit, "remove",
+                                                       "(Ljava/lang/String;)"
+                                                       "Landroid/content/SharedPreferences"
+                                                       "$Editor;");
+    if (!jni_mid_PrefRemove)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_PrefRemove is null");
+        return false;
+    }
+
+    OIC_LOG(DEBUG, TAG, "CALL API - request remove for SharedPreferences.Editor");
+    (*env)->CallObjectMethod(env, jni_obj_prefEdit, jni_mid_PrefRemove, jni_str_prefKey);
+
+    // get commit method interface
+    jmethodID jni_mid_PrefCommit = (*env)->GetMethodID(env, jni_cls_edit, "commit",
+                                                       "()Z");
+    if (!jni_mid_PrefCommit)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_PrefCommit is null");
+        return false;
+    }
+
+    jboolean res = (*env)->CallBooleanMethod(env, jni_obj_prefEdit, jni_mid_PrefCommit);
+
+    OIC_LOG(DEBUG, TAG, "OUT-CAManagerAddConnectedDeviceAddress");
+    return res;
+}
+
+bool CAManagerAddConnectedDeviceAddress(JNIEnv *env, jobject context,
+                                        jstring address, jobject set)
+{
+    OIC_LOG(DEBUG, TAG, "IN-CAManagerAddConnectedDeviceAddress");
+
+    VERIFY_NON_NULL_RET(env, TAG, "env", false);
+    VERIFY_NON_NULL_RET(context, TAG, "context", false);
+    VERIFY_NON_NULL_RET(address, TAG, "address", false);
+    VERIFY_NON_NULL_RET(set, TAG, "set", false);
+
+    if (CAManagerCallFuncSetString(env, address, set, CM_CONTAINS))
+    {
+        OIC_LOG(DEBUG, TAG, "it's already done");
+        return true;
+    }
+
+    if (!CAManagerCallFuncSetString(env, address, set, CM_ADD))
+    {
+        OIC_LOG(ERROR, TAG, "CAManagerAddSetString has failed");
+        return false;
+    }
+
+    return CAManagerUpdatePrefStringSet(env, context, set);
+}
+
+bool CAManagerIsConnectedDeviceAddress(JNIEnv *env, jobject context,
+                                       jstring address, jobject set)
+{
+    OIC_LOG(DEBUG, TAG, "CAManagerIsConnectedDeviceAddress");
+    VERIFY_NON_NULL_RET(env, TAG, "env", false);
+    VERIFY_NON_NULL_RET(context, TAG, "context", false);
+
+    return CAManagerCallFuncSetString(env, address, set, CM_CONTAINS);
+}
+
+jobject CAManagerGetConnectedDeviceAddress(JNIEnv *env, jobject context)
+{
+    OIC_LOG(DEBUG, TAG, "CAManagerGetConnectedDeviceAddress");
+
+    if (!CAManagerContainsPrefStringSet(env, context))
+    {
+        OIC_LOG(DEBUG, TAG, "there is no set data");
+        return NULL;
+    }
+
+    return CAManagerGetPrefStringSet(env, context);
+}
+
+bool CAManagerRemoveConnectedDeviceAddress(JNIEnv *env, jobject context,
+                                           jstring address, jobject set)
+{
+    OIC_LOG(DEBUG, TAG, "IN-CAManagerRemoveConnectedDeviceAddress");
+
+    VERIFY_NON_NULL_RET(env, TAG, "env", false);
+    VERIFY_NON_NULL_RET(context, TAG, "context", false);
+    VERIFY_NON_NULL_RET(address, TAG, "address", false);
+    VERIFY_NON_NULL_RET(set, TAG, "set", false);
+
+    if (!CAManagerCallFuncSetString(env, address, set, CM_CONTAINS))
+    {
+        OIC_LOG(DEBUG, TAG, "it's already done");
+        return true;
+    }
+
+    if (!CAManagerCallFuncSetString(env, address, set, CM_REMOVE))
+    {
+        OIC_LOG(ERROR, TAG, "CAManagerAddSetString has failed");
+        return false;
+    }
+
+    return CAManagerUpdatePrefStringSet(env, context, set);
+}
+
+jboolean CAManagerCheckBTAddress(JNIEnv *env, jstring address)
+{
+    OIC_LOG(DEBUG, TAG, "CAManagerCheckBTAddress");
+
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", JNI_FALSE);
+    VERIFY_NON_NULL_RET(address, TAG, "address is null", JNI_FALSE);
+
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADAPTER);
+    if (!jni_cid_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BTAdapter is null");
+        return JNI_FALSE;
+    }
+
+    // get remote bt adapter method
+    jmethodID jni_mid_checkBTAddress =
+            (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
+                                      "checkBluetoothAddress",
+                                      METHODID_BOOLEAN_RET_STRING_PARAM);
+    if (!jni_mid_checkBTAddress)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_checkBTAddress is null");
+        return JNI_FALSE;
+    }
+
+    jboolean jni_obj_isAddress = (*env)->CallStaticBooleanMethod(env, jni_cid_BTAdapter,
+                                                                 jni_mid_checkBTAddress,
+                                                                 address);
+    return jni_obj_isAddress;
+}
+
+jobject CAManagerCreateSetString(JNIEnv *env)
+{
+    OIC_LOG(DEBUG, TAG, "CAManagerCallFuncSetString");
+
+    VERIFY_NON_NULL_RET(env, TAG, "env", NULL);
+
+    jclass jclazzMap = (*env)->FindClass(env, "java/util/HashSet" );
+    if (!jclazzMap)
+    {
+        OIC_LOG(ERROR, TAG, "jclazzMap is null");
+        return NULL;
+    }
+
+    jmethodID jinitMap = (*env)->GetMethodID(env, jclazzMap, "<init>", "()V");
+    if (!jinitMap)
+    {
+        OIC_LOG(ERROR, TAG, "jinitMap is null");
+        return NULL;
+    }
+
+    jobject jpropertyMap = (*env)->NewObject(env, jclazzMap, jinitMap);
+    if (!jpropertyMap)
+    {
+        OIC_LOG(ERROR, TAG, "jpropertyMap is null");
+        return NULL;
+    }
+
+    return jpropertyMap;
+}
+
+bool CAManagerCallFuncSetString(JNIEnv *env, jstring address, jobject set,
+                                CASetMethod_t method_type)
+{
+    OIC_LOG(DEBUG, TAG, "CAManagerCallFuncSetString");
+    VERIFY_NON_NULL_RET(env, TAG, "env", false);
+    VERIFY_NON_NULL_RET(address, TAG, "address", false);
+    VERIFY_NON_NULL_RET(set, TAG, "set", false);
+
+    jclass jni_cls_set = (*env)->FindClass(env, "java/util/HashSet");
+    if (!jni_cls_set)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cls_set is null");
+        return false;
+    }
+
+    jmethodID jni_mid_setMethod = NULL;
+    switch (method_type)
+    {
+        case CM_CONTAINS:
+            OIC_LOG(DEBUG, TAG, "java/util/HashSet.contains");
+            jni_mid_setMethod = (*env)->GetMethodID(env, jni_cls_set, "contains",
+                                                    "(Ljava/lang/Object;)Z");
+            break;
+        case CM_ADD:
+            OIC_LOG(DEBUG, TAG, "java/util/HashSet.add");
+            jni_mid_setMethod = (*env)->GetMethodID(env, jni_cls_set, "add",
+                                                    "(Ljava/lang/Object;)Z");
+            break;
+        case CM_REMOVE:
+            OIC_LOG(DEBUG, TAG, "java/util/HashSet.remove");
+            jni_mid_setMethod = (*env)->GetMethodID(env, jni_cls_set, "remove",
+                                                    "(Ljava/lang/Object;)Z");
+            break;
+        default:
+            break;
+    }
+    if (!jni_mid_setMethod)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_setMethod is null");
+        return false;
+    }
+
+    jboolean res = (*env)->CallBooleanMethod(env, set, jni_mid_setMethod, address);
+    OIC_LOG_V(DEBUG, TAG, "method return result : %d", res);
+    return res;
+}
diff --git a/resource/csdk/connectivity/util/src/camanager/android/camanagerleutil.h b/resource/csdk/connectivity/util/src/camanager/android/camanagerleutil.h
new file mode 100644 (file)
index 0000000..95b648b
--- /dev/null
@@ -0,0 +1,189 @@
+/* ****************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef CA_MANAGER_LE_UTILS_H_
+#define CA_MANAGER_LE_UTILS_H_
+
+#include <jni.h>
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+typedef enum {
+    CM_CONTAINS = 1,
+    CM_ADD,
+    CM_REMOVE
+} CASetMethod_t;
+/**
+ * get bluetooth device object from bluetooth adapter.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   remote_address        remote address.
+ * @return  bluetooth device object.
+ */
+jobject CAManagerGetRemoteDevice(JNIEnv *env, jstring address);
+
+/**
+ * get address from gatt profile object.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   gatt                  gatt profile object.
+ * @return  LE address.
+ */
+jstring CAManagerGetAddressFromGatt(JNIEnv *env, jobject gatt);
+
+/**
+ * check whether the devie is bonded or not.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   btDevice              bluetooth device object.
+ * @return  true(bonded) or false(bond none)
+ */
+bool CAManagerIsDeviceBonded(JNIEnv *env, jobject btDevice);
+
+/**
+ * change bluetooth adapter state.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   controlFlag           true : enable(), false : disable()
+ * @return  true or false
+ */
+bool CAManagerControlAdapter(JNIEnv *env, bool controlFlag);
+
+/**
+ * request to get rssi value from bluetooth
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   bluetoothGatt         connected gatt object.
+ * @return  ::CA_STATUS_OK or Appropriate error code.
+ */
+CAResult_t CAManagerReadRemoteRssi(JNIEnv *env, jobject bluetoothGatt);
+
+/**
+ * get SharedPreference from context of application.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   context               Application context interface.
+ * @param[in]   prefName              preferences name.
+ * @return  SharedPreferences object.
+ */
+jobject CAManagerGetSharedPreference(JNIEnv *env, jobject context, jstring prefName);
+
+/**
+ * check whether the device is already put or not.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   context               Application context interface.
+ * @param[in]   address               LE address.
+ * @param[in]   set                   set<String> object related to connected list.
+ * @return  true or false
+ */
+bool CAManagerIsConnectedDeviceAddress(JNIEnv *env, jobject context,
+                                       jstring address, jobject set);
+
+/**
+ * get SharedPreferences.Editor object.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   context               Application context interface.
+ * @return  SharedPreferences.Editor object.
+ */
+jobject CAManagerGetPrefStringSet(JNIEnv *env, jobject context);
+
+/**
+ * update SharedPreferences for set<String> object.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   context               Application context interface.
+ * @param[in]   set                   set<String> object related to connected list.
+ * @return  true or false
+ */
+bool CAManagerUpdatePrefStringSet(JNIEnv *env, jobject context, jobject set);
+
+/**
+ * get SharedPreferences for set<String> object.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   context               Application context interface.
+ * @return  set<String> object from SharedPreferences
+ */
+jobject CAManagerGetPrefStringSet(JNIEnv *env, jobject context);
+
+/**
+ * checks whether the preferences contains a preference.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   context               Application context interface.
+ * @return  true or false
+ */
+bool CAManagerContainsPrefStringSet(JNIEnv *env, jobject context);
+
+/**
+ * add connected device into SharedPreference.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   context               Application context interface.
+ * @param[in]   address               ble address.
+ * @param[in]   set                   set<String> object related to connected list.
+ * @return  true or false
+ */
+bool CAManagerAddConnectedDeviceAddress(JNIEnv *env, jobject context,
+                                        jstring address, jobject set);
+
+/**
+ * get connected device from SharedPreference.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   context               Application context interface.
+ * @return  LE address of connected device.
+ */
+jobject CAManagerGetConnectedDeviceAddress(JNIEnv *env, jobject context);
+
+/**
+ * remove connected device to SharedPreference.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   context               Application context interface.
+ * @param[in]   address               LE address.
+ * @param[in]   set                   set<String> object related to connected list.
+ * @return  true or false
+ */
+bool CAManagerRemoveConnectedDeviceAddress(JNIEnv *env, jobject context,
+                                           jstring address, jobject set);
+
+/**
+ * Vaildate a String bluetooth address.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   address               LE address.
+ * @return  JNI_TRUE or JNI_FALSE
+ */
+jboolean CAManagerCheckBTAddress(JNIEnv *env, jstring address);
+
+/**
+ * create new set<String> object.
+ * @param[in]   env                   JNI interface pointer.
+ * @return  set<String> object
+ */
+jobject CAManagerCreateSetString(JNIEnv *env);
+
+/**
+ * remove connected device to SharedPreference.
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   address               LE address.
+ * @param[in]   set                   set<String> object related to connected list.
+ * @param[in]   method_type           method name to get its ID.
+ * @return  true or false
+ */
+bool CAManagerCallFuncSetString(JNIEnv *env, jstring address,
+                                jobject set, CASetMethod_t method_type);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* CA_MANAGER_LE_UTILS_H_ */
diff --git a/resource/csdk/connectivity/util/src/camanager/arduino/caleconnectionmanager.c b/resource/csdk/connectivity/util/src/camanager/arduino/caleconnectionmanager.c
new file mode 100644 (file)
index 0000000..33f7648
--- /dev/null
@@ -0,0 +1,61 @@
+/* ****************************************************************
+ *
+ * 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 "camanagerleinterface.h"
+#include "cacommon.h"
+#include "logger.h"
+
+#define TAG "OIC_CA_MANAGER_AR_LE"
+
+static CAAdapterStateChangedCB g_adapterStateCB = NULL;
+static CAConnectionStateChangedCB g_connStateCB = NULL;
+
+void CASetLENetworkMonitorCallbacks(CAAdapterStateChangedCB adapterStateCB,
+                                    CAConnectionStateChangedCB connStateCB)
+{
+    OIC_LOG(DEBUG, TAG, "CASetLENetworkMonitorCallbacks");
+
+    g_adapterStateCB = adapterStateCB;
+    g_connStateCB = connStateCB;
+}
+
+CAResult_t CASetLEClientAutoConnectionDeviceInfo(const char * address)
+{
+    OIC_LOG(DEBUG, TAG, "CASetClientAutoConnectionDeviceInfo");
+    (void)address;
+    return CA_NOT_SUPPORTED;
+}
+
+CAResult_t CAUnsetLEClientAutoConnectionDeviceInfo(const char * address)
+{
+    OIC_LOG(DEBUG, TAG, "CAUnsetClientAutoConnectionDeviceInfo");
+    (void)address;
+    return CA_NOT_SUPPORTED;
+}
+
+void CAStartServerLEAdvertising()
+{
+    OIC_LOG(DEBUG, TAG, "CAStartServerLEAdvertising");
+}
+
+void CAStopServerLEAdvertising()
+{
+    OIC_LOG(DEBUG, TAG, "CAStopServerLEAdvertising");
+}
diff --git a/resource/csdk/connectivity/util/src/camanager/linux/caleconnectionmanager.c b/resource/csdk/connectivity/util/src/camanager/linux/caleconnectionmanager.c
new file mode 100644 (file)
index 0000000..98f336e
--- /dev/null
@@ -0,0 +1,61 @@
+/* ****************************************************************
+ *
+ * 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 "camanagerleinterface.h"
+#include "cacommon.h"
+#include "logger.h"
+
+#define TAG "OIC_CA_MANAGER_LI_LE"
+
+static CAAdapterStateChangedCB g_adapterStateCB = NULL;
+static CAConnectionStateChangedCB g_connStateCB = NULL;
+
+void CASetLENetworkMonitorCallbacks(CAAdapterStateChangedCB adapterStateCB,
+                                    CAConnectionStateChangedCB connStateCB)
+{
+    OIC_LOG(DEBUG, TAG, "CASetLENetworkMonitorCallbacks");
+
+    g_adapterStateCB = adapterStateCB;
+    g_connStateCB = connStateCB;
+}
+
+CAResult_t CASetLEClientAutoConnectionDeviceInfo(const char * address)
+{
+    OIC_LOG(DEBUG, TAG, "CASetLEClientAutoConnectionDeviceInfo");
+    (void)address;
+    return CA_NOT_SUPPORTED;
+}
+
+CAResult_t CAUnsetLEClientAutoConnectionDeviceInfo(const char * address)
+{
+    OIC_LOG(DEBUG, TAG, "CAUnsetLEClientAutoConnectionDeviceInfo");
+    (void)address;
+    return CA_NOT_SUPPORTED;
+}
+
+void CAStartServerLEAdvertising()
+{
+    OIC_LOG(DEBUG, TAG, "CAStartServerLEAdvertising");
+}
+
+void CAStopServerLEAdvertising()
+{
+    OIC_LOG(DEBUG, TAG, "CAStopServerLEAdvertising");
+}
diff --git a/resource/csdk/connectivity/util/src/camanager/tizen/caleconnectionmanager.c b/resource/csdk/connectivity/util/src/camanager/tizen/caleconnectionmanager.c
new file mode 100644 (file)
index 0000000..cc196f2
--- /dev/null
@@ -0,0 +1,144 @@
+/* ****************************************************************
+ *
+ * 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 <bluetooth.h>
+#include <bluetooth_type.h>
+#include <bluetooth_internal.h>
+
+#include "camanagerleinterface.h"
+#include "cacommon.h"
+#include "camessagehandler.h"
+#include "caleserver.h"
+#include "cagattservice.h"
+#include "logger.h"
+
+#define TAG "OIC_CA_MANAGER_TZ_LE"
+
+static CAAdapterStateChangedCB g_adapterStateCB = NULL;
+static CAConnectionStateChangedCB g_connStateCB = NULL;
+
+static void CAManagerAdapterMonitorHandler(const CAEndpoint_t *info, CANetworkStatus_t status);
+static void CAManagerConnectionMonitorHandler(CATransportAdapter_t adapter,
+                                              const char *remoteAddress, bool connected);
+
+void CASetLENetworkMonitorCallbacks(CAAdapterStateChangedCB adapterStateCB,
+                                    CAConnectionStateChangedCB connStateCB)
+{
+    OIC_LOG(DEBUG, TAG, "CASetLENetworkMonitorCallbacks");
+
+    g_adapterStateCB = adapterStateCB;
+    CASetNetworkMonitorCallback(CAManagerAdapterMonitorHandler);
+
+    g_connStateCB = connStateCB;
+    CASetLEConnectionStateChangedCallback(CAManagerConnectionMonitorHandler);
+}
+
+void CAStartServerLEAdvertising()
+{
+    OIC_LOG(DEBUG, TAG, "CAStartServerLEAdvertising");
+
+    CAResult_t res = CALEStartAdvertise(CA_GATT_SERVICE_UUID);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG_V(ERROR, TAG, "Failed to start le advertising [%d]", res);
+        return;
+    }
+}
+
+void CAStopServerLEAdvertising()
+{
+    OIC_LOG(DEBUG, TAG, "CAStopServerLEAdvertising");
+
+    CAResult_t res = CALEStopAdvertise();
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG_V(ERROR, TAG, "Failed to stop le advertising [%d]", res);
+        return;
+    }
+}
+
+CAResult_t CASetLEClientAutoConnectionDeviceInfo(const char * address)
+{
+    OIC_LOG(DEBUG, TAG, "CASetLEClientAutoConnectionDeviceInfo");
+    (void)address;
+    return CA_NOT_SUPPORTED;
+}
+
+CAResult_t CAUnsetLEClientAutoConnectionDeviceInfo(const char * address)
+{
+    OIC_LOG(DEBUG, TAG, "CAUnsetLEClientAutoConnectionDeviceInfo");
+    (void)address;
+    return CA_NOT_SUPPORTED;
+}
+
+static void CAManagerAdapterMonitorHandler(const CAEndpoint_t *info, CANetworkStatus_t status)
+{
+    if (CA_INTERFACE_DOWN == status)
+    {
+        if (info && g_adapterStateCB)
+        {
+            g_adapterStateCB(info->adapter, false);
+            OIC_LOG(DEBUG, TAG, "Pass the disabled adapter state to upper layer");
+        }
+    }
+    else if (CA_INTERFACE_UP == status)
+    {
+        if (info && g_adapterStateCB)
+        {
+            g_adapterStateCB(info->adapter, true);
+            OIC_LOG(DEBUG, TAG, "Pass the enabled adapter state to upper layer");
+        }
+    }
+}
+
+static void CAManagerConnectionMonitorHandler(CATransportAdapter_t adapter,
+                                              const char *remoteAddress, bool connected)
+{
+    (void)adapter;
+
+    if (!remoteAddress)
+    {
+        OIC_LOG(ERROR, TAG, "remoteAddress is NULL");
+        return;
+    }
+
+    if (connected)
+    {
+        if (g_connStateCB)
+        {
+            g_connStateCB(CA_ADAPTER_GATT_BTLE, remoteAddress, true);
+            OIC_LOG(DEBUG, TAG, "Pass the connected device info to upper layer");
+
+            // stop le advertising
+            CAStopServerLEAdvertising();
+        }
+    }
+    else
+    {
+        if (g_connStateCB)
+        {
+            g_connStateCB(CA_ADAPTER_GATT_BTLE, remoteAddress, false);
+            OIC_LOG(DEBUG, TAG, "Pass the disconnected device info to upper layer");
+
+            // start le advertising to receive new connection request.
+            CAStartServerLEAdvertising();
+        }
+    }
+}
diff --git a/resource/csdk/connectivity/util/src/cautilinterface.c b/resource/csdk/connectivity/util/src/cautilinterface.c
new file mode 100644 (file)
index 0000000..83513f7
--- /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 "camanagerleinterface.h"
+#include "cabtpairinginterface.h"
+#include "cautilinterface.h"
+
+#include "cacommon.h"
+#include "logger.h"
+
+#define TAG "OIC_CA_COMMON_UTILS"
+
+CAResult_t CARegisterNetworkMonitorHandler(CAAdapterStateChangedCB adapterStateCB,
+                                           CAConnectionStateChangedCB connStateCB)
+{
+    OIC_LOG(DEBUG, TAG, "CARegisterNetworkMonitorHandler");
+
+#ifdef LE_ADAPTER
+    CASetLENetworkMonitorCallbacks(adapterStateCB, connStateCB);
+    return CA_STATUS_OK;
+#else
+    (void)adapterStateCB;
+    (void)connStateCB;
+    return CA_NOT_SUPPORTED;
+#endif
+
+}
+
+CAResult_t CASetAutoConnectionDeviceInfo(const char *address)
+{
+    OIC_LOG(DEBUG, TAG, "CASetAutoConnectionDeviceInfo");
+
+#ifdef LE_ADAPTER
+    return CASetLEClientAutoConnectionDeviceInfo(address);
+#else
+    (void)address;
+    return CA_NOT_SUPPORTED;
+#endif
+}
+
+CAResult_t CAUnsetAutoConnectionDeviceInfo(const char *address)
+{
+    OIC_LOG(DEBUG, TAG, "CAUnsetAutoConnectionDeviceInfo");
+
+#ifdef LE_ADAPTER
+    return CAUnsetLEClientAutoConnectionDeviceInfo(address);
+#else
+    (void)address;
+    return CA_NOT_SUPPORTED;
+#endif
+}
+
+#ifdef __ANDROID__
+/**
+ * initialize client connection manager
+ * @param[in]   env                   JNI interface pointer.
+ * @param[in]   jvm                   invocation inferface for JAVA virtual machine.
+ * @param[in]   context               application context.
+ */
+CAResult_t CAUtilClientInitialize(JNIEnv *env, JavaVM *jvm, jobject context)
+{
+    OIC_LOG(DEBUG, TAG, "CAUtilClientInitialize");
+
+    CAResult_t res = CA_STATUS_OK;
+#ifdef LE_ADAPTER
+    if (CA_STATUS_OK != CAManagerLEClientInitialize(env, jvm, context))
+    {
+        OIC_LOG(ERROR, TAG, "CAManagerLEClientInitialize has failed");
+        res = CA_STATUS_FAILED;
+    }
+#endif
+
+#ifdef EDR_ADAPTER
+    if (CA_STATUS_OK != CABTPairingInitialize(env, jvm, context))
+    {
+        OIC_LOG(ERROR, TAG, "CABTPairingInitialize has failed");
+        res = CA_STATUS_FAILED;
+    }
+#endif
+    return res;
+}
+
+/**
+ * terminate client connection manager
+ * @param[in]   env                   JNI interface pointer.
+ */
+CAResult_t CAUtilClientTerminate(JNIEnv *env)
+{
+    OIC_LOG(DEBUG, TAG, "CAUtilClientTerminate");
+#ifdef LE_ADAPTER
+    return CAManagerLEClientTerminate(env);
+#else
+    OIC_LOG(DEBUG, TAG, "it is not supported");
+    (void)env;
+    return CA_NOT_SUPPORTED;
+#endif
+}
+
+// BT pairing
+CAResult_t CAUtilStartScan(JNIEnv *env)
+{
+#ifdef EDR_ADAPTER
+    return CABTPairingStartScan(env);
+#else
+    OIC_LOG(DEBUG, TAG, "it is not supported");
+    (void)env;
+    return CA_NOT_SUPPORTED;
+#endif
+}
+
+CAResult_t CAUtilStopScan(JNIEnv *env)
+{
+#ifdef EDR_ADAPTER
+    return CABTPairingStopScan(env);
+#else
+    OIC_LOG(DEBUG, TAG, "it is not supported");
+    (void)env;
+    return CA_NOT_SUPPORTED;
+#endif
+}
+
+CAResult_t CAUtilCreateBond(JNIEnv *env, jobject device)
+{
+#ifdef EDR_ADAPTER
+    return CABTPairingCreateBond(env, device);
+#else
+    OIC_LOG(DEBUG, TAG, "it is not supported");
+    (void)env;
+    (void)device;
+    return CA_NOT_SUPPORTED;
+#endif
+}
+
+void CAUtilSetFoundDeviceListener(jobject listener)
+{
+#ifdef EDR_ADAPTER
+    CABTPairingSetFoundDeviceListener(listener);
+#else
+    (void)listener;
+#endif
+}
+#endif
diff --git a/resource/csdk/logger/SConscript b/resource/csdk/logger/SConscript
new file mode 100644 (file)
index 0000000..40c60bb
--- /dev/null
@@ -0,0 +1,32 @@
+Import('env')
+import os
+
+env.AppendUnique(CPPPATH = [os.path.join(Dir('.').abspath, './include')])
+if env.get('TARGET_OS') in ['arduino']:
+       env.AppendUnique(CPPPATH = [os.path.join(env.get('BUILD_DIR'), 'resource/c_common/oic_string/include')])
+if env.get('TARGET_OS') == 'tizen':
+       env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+else:
+       env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource/csdk/logger/')])
+
+env.PrependUnique(LIBS = ['logger'])
+
+local_env = env.Clone()
+
+######################################################################
+# Source files and Targets
+######################################################################
+
+#TODO work-around: at the moment if an Arduino build is done the logger.c file
+# ends up using C++ such as for the arduino Time Library, Serial, etc.
+# Therefore we copy it to a .cpp name so it is compiled correctly.
+
+if env.get('TARGET_OS') in ['arduino']:
+       Command("./src/logger.cpp", "./src/logger.c", Copy("$TARGET", "$SOURCE"))
+       logger_src = ['./src/logger.cpp']
+else:
+       logger_src = ['./src/logger.c']
+
+loggerlib = local_env.StaticLibrary('logger', logger_src)
+local_env.InstallTarget(loggerlib, 'logger')
+
index 3c69eae..fcab193 100644 (file)
 #ifndef LOGGER_H_
 #define LOGGER_H_
 
+#define IOTIVITY_VERSION "1.1.0"
+
 #include <stdint.h>
 #include <stdio.h>
 #include <stdarg.h>
-#include "oc_logger.h"
-#include "oc_console_logger.h"
+#include "logger_types.h"
 
 #ifdef __ANDROID__
-    #include <android/log.h>
+#include <android/log.h>
 #elif defined(__TIZEN__)
 #include <dlog.h>
-#elif defined ARDUINO
-    #include "Arduino.h"
-    #include <avr/pgmspace.h>
+#elif defined(ARDUINO)
+#include "Arduino.h"
+#include "avr/pgmspace.h"
 #endif
 
 #ifdef __cplusplus
-extern "C" {
+extern "C"
+{
 #endif
 
 // Use the PCF macro to wrap strings stored in FLASH on the Arduino
-// Example:  OC_LOG(INFO, TAG, PCF("Entering function"));
+// Example:  OIC_LOG(INFO, TAG, PCF("Entering function"));
 #ifdef ARDUINO
 #ifdef __cplusplus
 #define PCF(str)  ((PROGMEM const char *)(F(str)))
@@ -105,7 +107,11 @@ typedef enum {
      * @param tag    - Module name
      * @param format - variadic log string
      */
-    void OCLogv(LogLevel level, const char * tag, const char * format, ...);
+    void OCLogv(LogLevel level, const char * tag, const char * format, ...)
+#if defined(__GNUC__)
+    __attribute__ ((format(printf, 3, 4)))
+#endif
+    ;
 
     /**
      * Output a log string with the specified priority level.
@@ -126,7 +132,7 @@ typedef enum {
      * @param bufferSize - max number of byte in buffer
      */
     void OCLogBuffer(LogLevel level, const char * tag, const uint8_t * buffer, uint16_t bufferSize);
-#else
+#else  // For arduino platforms
     /**
      * Initialize the serial logger for Arduino
      * Only defined for Arduino
@@ -139,9 +145,11 @@ typedef enum {
      *
      * @param level  - DEBUG, INFO, WARNING, ERROR, FATAL
      * @param tag    - Module name
+     * @param lineNum- line Number
      * @param logStr - log string
      */
-    void OCLog(LogLevel level, PROGMEM const char * tag, PROGMEM const char * logStr);
+    void OCLog(LogLevel level, PROGMEM const char *tag, const int lineNum,
+               PROGMEM const char *logStr);
 
     /**
      * Output the contents of the specified buffer (in hex) with the specified priority level.
@@ -151,50 +159,67 @@ typedef enum {
      * @param buffer     - pointer to buffer of bytes
      * @param bufferSize - max number of byte in buffer
      */
-    void OCLogBuffer(LogLevel level, PROGMEM const char * tag, const uint8_t * buffer, uint16_t bufferSize);
+    void OCLogBuffer(LogLevel level, const char *tag, const uint8_t *buffer, size_t bufferSize);
 
     /**
      * Output a variable argument list log string with the specified priority level.
      *
      * @param level  - DEBUG, INFO, WARNING, ERROR, FATAL
      * @param tag    - Module name
+     * @param lineNum- line Number
      * @param format - variadic log string
      */
-    void OCLogv(LogLevel level, const char * tag, const char * format, ...);
+    void OCLogv(LogLevel level, PROGMEM const char *tag, const int lineNum,
+                PROGMEM const char *format, ...)
+#if defined(__GNUC__)
+    __attribute__ ((format(printf, 4, 5)))
+#endif
+;
 #endif
 
 #ifdef TB_LOG
+
 #ifdef __TIZEN__
-    #define OC_LOG(level,tag,mes) LOG_(LOG_ID_MAIN, level, tag, mes)
-    #define OC_LOG_V(level,tag,fmt,args...) LOG_(LOG_ID_MAIN, level, tag, fmt,##args)
-    #define OC_LOG_BUFFER(level, tag, buffer, bufferSize)
+
+#define OIC_LOG(level,tag,mes) LOG_(LOG_ID_MAIN, (level), (tag), mes)
+#define OIC_LOG_V(level,tag,fmt,args...) LOG_(LOG_ID_MAIN, level, tag, fmt, ##args)
+#define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)
+
 #else // These macros are defined for Linux, Android, and Arduino
-    #define OC_LOG_INIT()    OCLogInit()
-    #define OC_LOG_BUFFER(level, tag, buffer, bufferSize)  OCLogBuffer((level), PCF(tag), (buffer), (bufferSize))
-
-    #ifdef ARDUINO
-        #define OC_LOG_CONFIG(ctx)
-        #define OC_LOG_SHUTDOWN()
-        #define OC_LOG(level, tag, logStr)  OCLog((level), PCF(tag), PCF(logStr))
-        // Use full namespace for logInit to avoid function name collision
-        #define OC_LOG_INIT()    OCLogInit()
-        // Don't define variable argument log function for Arduino
-        #define OC_LOG_V(level, tag, format, ...) OCLogv((level), PCF(tag), PCF(format), __VA_ARGS__)
-    #else
-        #define OC_LOG_CONFIG(ctx)    OCLogConfig((ctx))
-        #define OC_LOG(level, tag, logStr)  OCLog((level), (tag), (logStr))
-        #define OC_LOG_SHUTDOWN()     OCLogShutdown()
-        // Define variable argument log function for Linux and Android
-        #define OC_LOG_V(level, tag, ...)  OCLogv((level), (tag), __VA_ARGS__)
-    #endif
-#endif
+
+#define OIC_LOG_INIT()    OCLogInit()
+
+#ifdef ARDUINO
+
+#define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)  OCLogBuffer((level), PCF(tag), (buffer), (bufferSize))
+// Don't define variable argument log function for Arduino
+#define OIC_LOG_V(level, tag, format, ...) OCLogv((level), PCF(tag), __LINE__, PCF(format),__VA_ARGS__)
+
+#define OIC_LOG_CONFIG(ctx)
+#define OIC_LOG_SHUTDOWN()
+#define OIC_LOG(level, tag, logStr) OCLog((level), PCF(tag), __LINE__, PCF(logStr))
+#define OIC_LOG_V(level, tag, ...)
+
 #else
-    #define OC_LOG_CONFIG(ctx)
-    #define OC_LOG_SHUTDOWN()
-    #define OC_LOG(level, tag, logStr)
-    #define OC_LOG_V(level, tag, ...)
-    #define OC_LOG_BUFFER(level, tag, buffer, bufferSize)
-    #define OC_LOG_INIT()
+
+#define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)  OCLogBuffer((level), (tag), (buffer), (bufferSize))
+#define OIC_LOG_CONFIG(ctx)    OCLogConfig((ctx))
+#define OIC_LOG_SHUTDOWN()     OCLogShutdown()
+#define OIC_LOG(level, tag, logStr)  OCLog((level), (tag), (logStr))
+// Define variable argument log function for Linux and Android
+#define OIC_LOG_V(level, tag, ...)  OCLogv((level), (tag), __VA_ARGS__)
+
+#endif //ARDUINO
+#endif //__TIZEN__
+
+#else //TB_LOG
+
+#define OIC_LOG_CONFIG(ctx)
+#define OIC_LOG_SHUTDOWN()
+#define OIC_LOG(level, tag, logStr)
+#define OIC_LOG_V(level, tag, ...)
+#define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)
+#define OIC_LOG_INIT()
 #endif
 
 #ifdef __cplusplus
diff --git a/resource/csdk/logger/include/logger_types.h b/resource/csdk/logger/include/logger_types.h
new file mode 100644 (file)
index 0000000..69496bb
--- /dev/null
@@ -0,0 +1,85 @@
+//******************************************************************
+//
+// Copyright 2014 Intel Mobile Communications GmbH 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef OC_LOGGER_TYPES_H_
+#define OC_LOGGER_TYPES_H_
+
+#include <stddef.h>
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+typedef enum
+{
+    OC_LOG_MIN_VAL__   = -1,
+    OC_LOG_ALL         = 0,
+    OC_LOG_FATAL,
+    OC_LOG_ERROR,
+    OC_LOG_WARNING,
+    OC_LOG_INFO,
+    OC_LOG_DEBUG,
+    OC_LOG_DISABLED,
+    OC_LOG_MAX_VAL__
+} oc_log_level;
+
+typedef struct _oc_log_ctx
+{
+    void*                  ctx;
+
+    oc_log_level           log_level;
+
+    char*                  module_name;
+
+    /* Required interface: */
+    int  (*init)           (struct _oc_log_ctx *, void *);
+    void (*destroy)        (struct _oc_log_ctx *);
+    void (*flush)          (struct _oc_log_ctx *);
+    void (*set_level)      (struct _oc_log_ctx *, const int);
+    size_t (*write_level)  (struct _oc_log_ctx *, const int, const char *);
+    int  (*set_module)     (struct _oc_log_ctx *, const char *);
+
+    /* Optional interface (if one is implemented, all must be implemented): */
+    int (*lock)            (struct _oc_log_ctx *);
+    int (*unlock)          (struct _oc_log_ctx *);
+    int (*try_lock)        (struct _oc_log_ctx *);
+    int (*locked_destroy)  (struct _oc_log_ctx *);
+} oc_log_ctx_t;
+
+/* Notice that these are all passed the /top level/ ctx-- it's "public" with respect to
+these functions, they have full access to fiddle with the structure all they want (but,
+generally should avoid doing that); I could certainly be convinced to go the other direction,
+and have most functions only take the inner context: */
+typedef int    (*oc_log_init_t)          (oc_log_ctx_t *, void *);
+typedef void   (*oc_log_destroy_t)       (oc_log_ctx_t *);
+typedef void   (*oc_log_flush_t)         (oc_log_ctx_t *);
+typedef void   (*oc_log_set_level_t)     (oc_log_ctx_t *, const int);
+typedef size_t (*oc_log_write_level_t)   (oc_log_ctx_t *, const int, const char *);
+typedef int    (*oc_log_set_module_t)    (oc_log_ctx_t *, const char *);
+typedef int    (*oc_log_lock_t)          (oc_log_ctx_t *);
+typedef int    (*oc_log_unlock_t)        (oc_log_ctx_t *);
+typedef int    (*oc_log_try_lock_t)      (oc_log_ctx_t *);
+
+#ifdef __cplusplus
+ } // extern "C"
+#endif
+
+#endif
+
index b75147d..295ac5f 100644 (file)
 
 #include "logger.h"
 #include "string.h"
-#include "oc_logger.h"
-#include "oc_console_logger.h"
+#include "logger_types.h"
 
 #ifndef __TIZEN__
 static oc_log_ctx_t *logCtx = 0;
-
-static oc_log_level LEVEL_XTABLE[] = {OC_LOG_DEBUG, OC_LOG_INFO, OC_LOG_WARNING, OC_LOG_ERROR, OC_LOG_FATAL};
-
 #endif
-static const uint16_t LINE_BUFFER_SIZE = (16 * 2) + 16 + 1;  // Show 16 bytes, 2 chars/byte, spaces between bytes, null termination
+#ifdef __ANDROID__
+#elif defined __linux__ || defined __APPLE__
+static oc_log_level LEVEL_XTABLE[] = {OC_LOG_DEBUG, OC_LOG_INFO,
+                                      OC_LOG_WARNING, OC_LOG_ERROR, OC_LOG_FATAL};
+#endif
+
+// Show 16 bytes, 2 chars/byte, spaces between bytes, null termination
+static const uint16_t LINE_BUFFER_SIZE = (16 * 2) + 16 + 1;
 
 // Convert LogLevel to platform-specific severity level.  Store in PROGMEM on Arduino
 #ifdef __ANDROID__
-    static android_LogPriority LEVEL[] = {ANDROID_LOG_DEBUG, ANDROID_LOG_INFO, ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL};
-#elif defined(__linux__) || defined(__APPLE__)
-    static const char * LEVEL[] __attribute__ ((unused)) = {"DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
+#ifdef ADB_SHELL
+    static const char *LEVEL[] =
+    {"DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
+
+#else
+    static android_LogPriority LEVEL[] =
+    {ANDROID_LOG_DEBUG, ANDROID_LOG_INFO, ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL};
+#endif
+#elif defined (__linux__) || defined (__APPLE__)
+    static const char *LEVEL[] __attribute__ ((unused)) =
+    {"DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
 #elif defined ARDUINO
-    #include <stdarg.h>
+#include <stdarg.h>
+#include "Arduino.h"
+#include "oic_string.h"
 
     PROGMEM const char level0[] = "DEBUG";
     PROGMEM const char level1[] = "INFO";
@@ -78,10 +91,10 @@ static const uint16_t LINE_BUFFER_SIZE = (16 * 2) + 16 + 1;  // Show 16 bytes, 2
     static void OCLogString(LogLevel level, PROGMEM const char * tag, PROGMEM const char * logStr);
 #ifdef ARDUINO_ARCH_AVR
     //Mega2560 and other 8-bit AVR microcontrollers
-    #define GET_PROGMEM_BUFFER(buffer, addr) { strcpy_P(buffer, (char*)pgm_read_word(addr));}
+    #define GET_PROGMEM_BUFFER(buffer, addr) { OICStrcpy(buffer, sizeof(buffer), (char*)pgm_read_word(addr));}
 #elif defined ARDUINO_ARCH_SAM
     //Arduino Due and other 32-bit ARM micro-controllers
-    #define GET_PROGMEM_BUFFER(buffer, addr) { strcpy_P(buffer, (char*)pgm_read_dword(addr));}
+    #define GET_PROGMEM_BUFFER(buffer, addr) { OICStrcpy(buffer, sizeof(buffer), (char*)pgm_read_dword(addr));}
 #else
     #define GET_PROGMEM_BUFFER(buffer, addr) { buffer[0] = '\0';}
 #endif
@@ -90,15 +103,18 @@ static const uint16_t LINE_BUFFER_SIZE = (16 * 2) + 16 + 1;  // Show 16 bytes, 2
 
 #ifndef ARDUINO
 #ifndef __TIZEN__
-void OCLogConfig(oc_log_ctx_t *ctx) {
+void OCLogConfig(oc_log_ctx_t *ctx)
+{
     logCtx = ctx;
 }
 
-void OCLogInit() {
+void OCLogInit()
+{
 
 }
 
-void OCLogShutdown() {
+void OCLogShutdown()
+{
 #if defined(__linux__) || defined(__APPLE__)
     if (logCtx && logCtx->destroy)
     {
@@ -115,7 +131,8 @@ void OCLogShutdown() {
  * @param tag    - Module name
  * @param format - variadic log string
  */
-void OCLogv(LogLevel level, const char * tag, const char * format, ...) {
+void OCLogv(LogLevel level, const char * tag, const char * format, ...)
+{
     if (!format || !tag) {
         return;
     }
@@ -127,34 +144,6 @@ void OCLogv(LogLevel level, const char * tag, const char * format, ...) {
     OCLog(level, tag, buffer);
 }
 
-static void osalGetTime(int *min,int *sec, int *ms)
-{
-    if (min && sec && ms)
-    {
-#if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
-        struct timespec when = { .tv_sec = 0 };
-        clockid_t clk = CLOCK_REALTIME;
-#ifdef CLOCK_REALTIME_COARSE
-        clk = CLOCK_REALTIME_COARSE;
-#endif
-        if (!clock_gettime(clk, &when))
-        {
-            *min = (when.tv_sec / 60) % 60;
-            *sec = when.tv_sec % 60;
-            *ms = when.tv_nsec / 1000000;
-        }
-#else
-        struct timeval now;
-        if (!gettimeofday(&now, NULL))
-        {
-            *min = (now.tv_sec / 60) % 60;
-            *sec = now.tv_sec % 60;
-            *ms = now.tv_usec * 1000;
-        }
-#endif
-    }
-}
-
 /**
  * Output a log string with the specified priority level.
  * Only defined for Linux and Android
@@ -163,29 +152,57 @@ static void osalGetTime(int *min,int *sec, int *ms)
  * @param tag    - Module name
  * @param logStr - log string
  */
-void OCLog(LogLevel level, const char * tag, const char * logStr) {
-    if (!logStr || !tag) {
-        return;
-    }
-
-#ifdef __ANDROID__
-    __android_log_write(LEVEL[level], tag, logStr);
-#elif defined(__linux__) || defined(__APPLE__)
-    if (logCtx && logCtx->write_level)
+void OCLog(LogLevel level, const char * tag, const char * logStr)
+{
+    if (!logStr || !tag)
     {
-        logCtx->write_level(logCtx, LEVEL_XTABLE[level], logStr);
+       return;
     }
-    else
-    {
-        int min = 0;
-        int sec = 0;
-        int ms = 0;
-        osalGetTime(&min,&sec,&ms);
 
-        printf("%02d:%02d.%03d %s: %s: %s\n", min, sec, ms, LEVEL[level], tag, logStr);
-    }
-#endif
-}
+   #ifdef __ANDROID__
+
+   #ifdef ADB_SHELL
+       printf("%s: %s: %s\n", LEVEL[level], tag, logStr);
+   #else
+       __android_log_write(LEVEL[level], tag, logStr);
+   #endif
+
+   #elif defined __linux__ || defined __APPLE__
+       if (logCtx && logCtx->write_level)
+       {
+           logCtx->write_level(logCtx, LEVEL_XTABLE[level], logStr);
+
+       }
+       else
+       {
+           int min = 0;
+           int sec = 0;
+           int ms = 0;
+   #if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
+           struct timespec when = { .tv_sec = 0, .tv_nsec = 0 };
+           clockid_t clk = CLOCK_REALTIME;
+   #ifdef CLOCK_REALTIME_COARSE
+           clk = CLOCK_REALTIME_COARSE;
+   #endif
+           if (!clock_gettime(clk, &when))
+           {
+               min = (when.tv_sec / 60) % 60;
+               sec = when.tv_sec % 60;
+               ms = when.tv_nsec / 1000000;
+           }
+   #else
+           struct timeval now;
+           if (!gettimeofday(&now, NULL))
+           {
+               min = (now.tv_sec / 60) % 60;
+               sec = now.tv_sec % 60;
+               ms = now.tv_usec * 1000;
+           }
+   #endif
+           printf("%02d:%02d.%03d %s: %s: %s\n", min, sec, ms, LEVEL[level], tag, logStr);
+       }
+   #endif
+   }
 
 /**
  * Output the contents of the specified buffer (in hex) with the specified priority level.
@@ -195,8 +212,10 @@ void OCLog(LogLevel level, const char * tag, const char * logStr) {
  * @param buffer     - pointer to buffer of bytes
  * @param bufferSize - max number of byte in buffer
  */
-void OCLogBuffer(LogLevel level, const char * tag, const uint8_t * buffer, uint16_t bufferSize) {
-    if (!buffer || !tag || (bufferSize == 0)) {
+void OCLogBuffer(LogLevel level, const char * tag, const uint8_t * buffer, uint16_t bufferSize)
+{
+    if (!buffer || !tag || (bufferSize == 0))
+    {
         return;
     }
 
@@ -206,168 +225,235 @@ void OCLogBuffer(LogLevel level, const char * tag, const uint8_t * buffer, uint1
     memset(lineBuffer, 0, sizeof lineBuffer);
     int lineIndex = 0;
     int i;
-    for (i = 0; i < bufferSize; i++) {
+    for (i = 0; i < bufferSize; i++)
+    {
         // Format the buffer data into a line
         snprintf(&lineBuffer[lineIndex*3], sizeof(lineBuffer)-lineIndex*3, "%02X ", buffer[i]);
         lineIndex++;
         // Output 16 values per line
-        if (((i+1)%16) == 0) {
+        if (((i+1)%16) == 0)
+        {
             OCLog(level, tag, lineBuffer);
             memset(lineBuffer, 0, sizeof lineBuffer);
             lineIndex = 0;
         }
     }
     // Output last values in the line, if any
-    if (bufferSize % 16) {
+    if (bufferSize % 16)
+    {
         OCLog(level, tag, lineBuffer);
     }
 }
 #endif //__TIZEN__
-#else
-    /**
-     * Initialize the serial logger for Arduino
-     * Only defined for Arduino
-     */
-    void OCLogInit() {
-        Serial.begin(115200);
-    }
-
-    /**
-     * Output a log string with the specified priority level.
-     * Only defined for Arduino.  Only uses PROGMEM strings
-     * for the tag parameter
-     *
-     * @param level  - DEBUG, INFO, WARNING, ERROR, FATAL
-     * @param tag    - Module name
-     * @param logStr - log string
-     */
-    void OCLogString(LogLevel level, PROGMEM const char * tag, const char * logStr) {
-        if (!logStr || !tag) {
-          return;
-        }
-
-        char buffer[LINE_BUFFER_SIZE];
-
-        GET_PROGMEM_BUFFER(buffer, &(LEVEL[level]));
-        Serial.print(buffer);
-
-        char c;
-        Serial.print(F(": "));
-        while ((c = pgm_read_byte(tag))) {
-          Serial.write(c);
-          tag++;
-        }
-        Serial.print(F(": "));
+#endif //ARDUINO
+#ifdef ARDUINO
+/**
+ * Initialize the serial logger for Arduino
+ * Only defined for Arduino
+ */
+void OCLogInit()
+{
+    Serial.begin(115200);
+}
 
-        Serial.println(logStr);
+/**
+ * Output a log string with the specified priority level.
+ * Only defined for Arduino.  Only uses PROGMEM strings
+ * for the tag parameter
+ *
+ * @param level  - DEBUG, INFO, WARNING, ERROR, FATAL
+ * @param tag    - Module name
+ * @param logStr - log string
+ */
+void OCLogString(LogLevel level, PROGMEM const char * tag, const char * logStr)
+{
+    if (!logStr || !tag)
+    {
+      return;
     }
 
-    /**
-     * Output the contents of the specified buffer (in hex) with the specified priority level.
-     *
-     * @param level      - DEBUG, INFO, WARNING, ERROR, FATAL
-     * @param tag        - Module name
-     * @param buffer     - pointer to buffer of bytes
-     * @param bufferSize - max number of byte in buffer
-     */
-    void OCLogBuffer(LogLevel level, PROGMEM const char * tag, const uint8_t * buffer, uint16_t bufferSize) {
-        if (!buffer || !tag || (bufferSize == 0)) {
-            return;
-        }
+    char buffer[LINE_BUFFER_SIZE];
 
-        char lineBuffer[LINE_BUFFER_SIZE] = {0};
-        uint8_t lineIndex = 0;
-        for (uint8_t i = 0; i < bufferSize; i++) {
-            // Format the buffer data into a line
-            snprintf(&lineBuffer[lineIndex*3], sizeof(lineBuffer)-lineIndex*3, "%02X ", buffer[i]);
-            lineIndex++;
-            // Output 16 values per line
-            if (((i+1)%16) == 0) {
-                OCLogString(level, tag, lineBuffer);
-                memset(lineBuffer, 0, sizeof lineBuffer);
-                lineIndex = 0;
-            }
-        }
-        // Output last values in the line, if any
-        if (bufferSize % 16) {
-            OCLogString(level, tag, lineBuffer);
-        }
-    }
-
-    /**
-     * Output a log string with the specified priority level.
-     * Only defined for Arduino.  Uses PROGMEM strings
-     *
-     * @param level  - DEBUG, INFO, WARNING, ERROR, FATAL
-     * @param tag    - Module name
-     * @param logStr - log string
-     */
-    void OCLog(LogLevel level, PROGMEM const char * tag, PROGMEM const char * logStr) {
-        if (!logStr || !tag) {
-          return;
-        }
+    GET_PROGMEM_BUFFER(buffer, &(LEVEL[level]));
+    Serial.print(buffer);
 
-        char buffer[LINE_BUFFER_SIZE];
+    char c;
+    Serial.print(F(": "));
+    while ((c = pgm_read_byte(tag)))
+    {
+      Serial.write(c);
+      tag++;
+    }
+    Serial.print(F(": "));
 
-        GET_PROGMEM_BUFFER(buffer, &(LEVEL[level]));
-        Serial.print(buffer);
+    Serial.println(logStr);
+}
 
-        char c;
-        Serial.print(F(": "));
-        while ((c = pgm_read_byte(tag))) {
-          Serial.write(c);
-          tag++;
-        }
-        Serial.print(F(": "));
+/**
+ * Output the contents of the specified buffer (in hex) with the specified
+ * priority level.
+ *
+ * @param level      - DEBUG, INFO, WARNING, ERROR, FATAL
+ * @param tag        - Module name
+ * @param buffer     - pointer to buffer of bytes
+ * @param bufferSize - max number of byte in buffer
+ */
+ void OCLogBuffer(LogLevel level, PROGMEM const char * tag,
+                  const uint8_t * buffer, size_t bufferSize)
+ {
+     if (!buffer || !tag || (bufferSize == 0))
+     {
+         return;
+     }
+
+     char lineBuffer[LINE_BUFFER_SIZE] = {0};
+     uint8_t lineIndex = 0;
+     for (uint8_t i = 0; i < bufferSize; i++)
+     {
+        // Format the buffer data into a line
+        snprintf(&lineBuffer[lineIndex*3], sizeof(lineBuffer)-lineIndex*3, "%02X ", buffer[i]);
+        lineIndex++;
+         // Output 16 values per line
+         if (((i+1)%16) == 0)
+         {
+             OCLogString(level, tag, lineBuffer);
+             memset(lineBuffer, 0, sizeof lineBuffer);
+             lineIndex = 0;
+         }
+     }
+     // Output last values in the line, if any
+     if (bufferSize % 16)
+     {
+         OCLogString(level, tag, lineBuffer);
+     }
+ }
 
-        while ((c = pgm_read_byte(logStr))) {
-          Serial.write(c);
-          logStr++;
-        }
-        Serial.println();
+/**
+ * Output a log string with the specified priority level.
+ * Only defined for Arduino.  Uses PROGMEM strings
+ *
+ * @param level  - DEBUG, INFO, WARNING, ERROR, FATAL
+ * @param tag    - Module name
+ * @param logStr - log string
+ */
+void OCLog(LogLevel level, PROGMEM const char *tag, const int lineNum,
+           PROGMEM const char *logStr)
+{
+    if (!logStr || !tag)
+    {
+        return;
     }
-
-    /**
-     * Output a variable argument list log string with the specified priority level.
-     * Only defined for Arduino as depicted below.
-     *
-     * @param level  - DEBUG, INFO, WARNING, ERROR, FATAL
-     * @param tag    - Module name
-     * @param format - variadic log string
-     */
-    void OCLogv(LogLevel level, PROGMEM const char * tag, PROGMEM const char * format, ...)
+    char buffer[LINE_BUFFER_SIZE] = {0};
+    GET_PROGMEM_BUFFER(buffer, &(LEVEL[level]));
+    Serial.print(buffer);
+    char c;
+    Serial.print(F(": "));
+    while ((c = pgm_read_byte(tag)))
     {
-        char buffer[LINE_BUFFER_SIZE];
-        va_list ap;
-        va_start(ap, format);
-
-        GET_PROGMEM_BUFFER(buffer, &(LEVEL[level]));
-        Serial.print(buffer);
+        Serial.write(c);
+        tag++;
+    }
+    Serial.print(F(": "));
+    Serial.print(lineNum);
+    Serial.print(F(": "));
+    while ((c = pgm_read_byte(logStr)))
+    {
+        Serial.write(c);
+        logStr++;
+    }
+    Serial.println();
+}
 
-        char c;
-        Serial.print(F(": "));
+/**
+ * Output a variable argument list log string with the specified priority level.
+ * Only defined for Arduino as depicted below.
+ *
+ * @param level  - DEBUG, INFO, WARNING, ERROR, FATAL
+ * @param tag    - Module name
+ * @param format - variadic log string
+ */
+void OCLogv(LogLevel level, PROGMEM const char *tag, const int lineNum,
+                PROGMEM const char *format, ...)
+{
+    char buffer[LINE_BUFFER_SIZE];
+    va_list ap;
+    va_start(ap, format);
+    GET_PROGMEM_BUFFER(buffer, &(LEVEL[level]));
+    Serial.print(buffer);
+
+    char c;
+    Serial.print(F(": "));
+    while ((c = pgm_read_byte(tag)))
+    {
+     Serial.write(c);
+     tag++;
+     }
+    Serial.print(F(": "));
+    Serial.print(lineNum);
+    Serial.print(F(": "));
 
-        while ((c = pgm_read_byte(tag))) {
-            Serial.write(c);
-            tag++;
+#ifdef __AVR__
+    vsnprintf_P(buffer, sizeof(buffer), format, ap);
+#else
+    vsnprintf(buffer, sizeof(buffer), format, ap);
+#endif
+    for (char *p = &buffer[0]; *p; p++)
+    {
+        // emulate cooked mode for newlines
+        if (*p == '\n')
+        {
+            Serial.write('\r');
         }
-        Serial.print(F(": "));
+        Serial.write(*p);
+    }
+    Serial.println();
+    va_end(ap);
+}
+/**
+ * Output a variable argument list log string with the specified priority level.
+ * Only defined for Arduino as depicted below.
+ *
+ * @param level  - DEBUG, INFO, WARNING, ERROR, FATAL
+ * @param tag    - Module name
+ * @param format - variadic log string
+ */
+void OCLogv(LogLevel level, const char *tag, const __FlashStringHelper *format, ...)
+{
+    char buffer[LINE_BUFFER_SIZE];
+    va_list ap;
+    va_start(ap, format);
+    // strcpy_P(buffer, (char*)pgm_read_word(&(LEVEL[level])));
+    // Serial.print(buffer);
+
+    Serial.print(LEVEL[level]);
+    // char c;
+    Serial.print(F(": "));
+
+    /*while ((c = pgm_read_byte(tag))) {
+     Serial.write(c);
+     tag++;
+     }*/
+    Serial.print(tag);
+    Serial.print(F(": "));
 
 #ifdef __AVR__
-        vsnprintf_P(buffer, sizeof(buffer), format, ap);
+    vsnprintf_P(buffer, sizeof(buffer), (const char *)format, ap); // progmem for AVR
 #else
-        vsnprintf(buffer, sizeof(buffer), format, ap);
+    vsnprintf(buffer, sizeof(buffer), (const char *)format, ap); // for the rest of the world
 #endif
-        for(char *p = &buffer[0]; *p; p++) // emulate cooked mode for newlines
+    for (char *p = &buffer[0]; *p; p++)
+    {
+        // emulate cooked mode for newlines
+        if (*p == '\n')
         {
-            if(*p == '\n')
-            {
-                Serial.write('\r');
-            }
-            Serial.write(*p);
+            // Serial.write('\r');
+            Serial.print('\r');
         }
-        Serial.println();
-        va_end(ap);
+        //Serial.write(*p);
+        Serial.print(p);
     }
+    Serial.println();
+    va_end(ap);
+}
 
-#endif
+#endif //ARDUINO
index e9d264a..52120c1 100644 (file)
@@ -39,31 +39,31 @@ static const char multiLineMsg[] = "this is a DEBUG message\non multiple\nlines"
 //  Tests
 //-----------------------------------------------------------------------------
 static void test0() {
-  OC_LOG(INFO, tag, msg);
+  OIC_LOG(INFO, tag, msg);
 }
 
 static void test1() {
-  OC_LOG(INFO, 0, msg);
+  OIC_LOG(INFO, 0, msg);
 }
 
 static void test2() {
-  OC_LOG(INFO, tag, 0);
+  OIC_LOG(INFO, tag, 0);
 }
 
 static void test3() {
-  OC_LOG(INFO, 0, 0);
+  OIC_LOG(INFO, 0, 0);
 }
 
 static void test4() {
-  OC_LOG(DEBUG, tag, debugMsg);
-  OC_LOG(INFO, tag, infoMsg);
-  OC_LOG(WARNING, tag, warningMsg);
-  OC_LOG(ERROR, tag, errorMsg);
-  OC_LOG(FATAL, tag, fatalMsg);
+  OIC_LOG(DEBUG, tag, debugMsg);
+  OIC_LOG(INFO, tag, infoMsg);
+  OIC_LOG(WARNING, tag, warningMsg);
+  OIC_LOG(ERROR, tag, errorMsg);
+  OIC_LOG(FATAL, tag, fatalMsg);
 }
 
 static void test5() {
-  OC_LOG(DEBUG, tag, multiLineMsg);
+  OIC_LOG(DEBUG, tag, multiLineMsg);
 }
 
 
@@ -73,42 +73,42 @@ static void test6() {
     for (int i = 0; i < (int)(sizeof buffer); i++) {
         buffer[i] = i;
     }
-    OC_LOG_BUFFER(DEBUG, tag, buffer, sizeof buffer);
+    OIC_LOG_BUFFER(DEBUG, tag, buffer, sizeof buffer);
 
     // Log buffer, 128 bytes is a good boundary (8 rows of 16 values)
     uint8_t buffer1[128];
     for (int i = 0; i < (int)(sizeof buffer1); i++) {
         buffer1[i] = i;
     }
-    OC_LOG_BUFFER(DEBUG, tag, buffer1, sizeof buffer1);
+    OIC_LOG_BUFFER(DEBUG, tag, buffer1, sizeof buffer1);
 
     // 1 below 128 byte boundary
     uint8_t buffer2[127];
     for (int i = 0; i < (int)(sizeof buffer2); i++) {
         buffer2[i] = i;
     }
-    OC_LOG_BUFFER(DEBUG, tag, buffer2, sizeof buffer2);
+    OIC_LOG_BUFFER(DEBUG, tag, buffer2, sizeof buffer2);
 
     // 1 above 128 byte boundary
     uint8_t buffer3[129];
     for (int i = 0; i < (int)(sizeof buffer3); i++) {
         buffer3[i] = i;
     }
-    OC_LOG_BUFFER(DEBUG, tag, buffer3, sizeof buffer3);
+    OIC_LOG_BUFFER(DEBUG, tag, buffer3, sizeof buffer3);
 }
 
 static void test7() {
-  OC_LOG_V(DEBUG, tag, "this is a char: %c", 'A');
-  OC_LOG_V(DEBUG, tag, "this is an integer: %d", 123);
-  OC_LOG_V(DEBUG, tag, "this is a string: %s", "hello");
-  OC_LOG_V(DEBUG, tag, "this is a float: %5.2f", 123.45);
+  OIC_LOG_V(DEBUG, tag, "this is a char: %c", 'A');
+  OIC_LOG_V(DEBUG, tag, "this is an integer: %d", 123);
+  OIC_LOG_V(DEBUG, tag, "this is a string: %s", "hello");
+  OIC_LOG_V(DEBUG, tag, "this is a float: %5.2f", 123.45);
 }
 
 //-----------------------------------------------------------------------------
 //  loggertests
 //-----------------------------------------------------------------------------
 void loggertests() {
-  OC_LOG(INFO, tag, "Starting logger test");
+  OIC_LOG(INFO, tag, "Starting logger test");
 
   test0();
   test1();
index a1a6987..450e544 100644 (file)
 //  Tests
 //-----------------------------------------------------------------------------
 void test0() {
-    OC_LOG(INFO, tag, msg);
+    OIC_LOG(INFO, tag, msg);
 }
 
 void test1() {
-    OC_LOG(INFO, 0, msg);
+    OIC_LOG(INFO, 0, msg);
 }
 
 void test2() {
-    OC_LOG(INFO, tag, 0);
+    OIC_LOG(INFO, tag, 0);
 }
 
 void test3() {
-    OC_LOG(INFO, 0, 0);
+    OIC_LOG(INFO, 0, 0);
 }
 
 void test4() {
-    OC_LOG(DEBUG, tag, debugMsg);
-    OC_LOG(INFO, tag, infoMsg);
-    OC_LOG(WARNING, tag, warningMsg);
-    OC_LOG(ERROR, tag, errorMsg);
-    OC_LOG(FATAL, tag, fatalMsg);
+    OIC_LOG(DEBUG, tag, debugMsg);
+    OIC_LOG(INFO, tag, infoMsg);
+    OIC_LOG(WARNING, tag, warningMsg);
+    OIC_LOG(ERROR, tag, errorMsg);
+    OIC_LOG(FATAL, tag, fatalMsg);
 }
 
 void test5() {
-    OC_LOG(DEBUG, tag, multiLineMsg);
+    OIC_LOG(DEBUG, tag, multiLineMsg);
 }
 
 
@@ -73,35 +73,35 @@ void test6() {
     for (int i = 0; i < (int)(sizeof buffer); i++) {
         buffer[i] = i;
     }
-    OC_LOG_BUFFER(DEBUG, tag, buffer, sizeof buffer);
+    OIC_LOG_BUFFER(DEBUG, tag, buffer, sizeof buffer);
 
     // Log buffer, 128 bytes is a good boundary (8 rows of 16 values)
     uint8_t buffer1[128];
     for (int i = 0; i < (int)(sizeof buffer1); i++) {
         buffer1[i] = i;
     }
-    OC_LOG_BUFFER(DEBUG, tag, buffer1, sizeof buffer1);
+    OIC_LOG_BUFFER(DEBUG, tag, buffer1, sizeof buffer1);
 
     // 1 below 128 byte boundary
     uint8_t buffer2[127];
     for (int i = 0; i < (int)(sizeof buffer2); i++) {
         buffer2[i] = i;
     }
-    OC_LOG_BUFFER(DEBUG, tag, buffer2, sizeof buffer2);
+    OIC_LOG_BUFFER(DEBUG, tag, buffer2, sizeof buffer2);
 
     // 1 above 128 byte boundary
     uint8_t buffer3[129];
     for (int i = 0; i < (int)(sizeof buffer3); i++) {
         buffer3[i] = i;
     }
-    OC_LOG_BUFFER(DEBUG, tag, buffer3, sizeof buffer3);
+    OIC_LOG_BUFFER(DEBUG, tag, buffer3, sizeof buffer3);
 }
 
 //The setup function is called once at startup of the sketch
 void setup()
 {
     // Add your initialization code here
-    OC_LOG_INIT();
+    OIC_LOG_INIT();
 
     test0();
     delay(2000);
index 27971ba..9e7b59a 100644 (file)
@@ -136,7 +136,7 @@ TEST(LoggerTest, StringArg) {
 
     directStdOutToFile(testFile);
     const char *tag = "StringArg";
-       OC_LOG(INFO, tag, "This is a fixed string call");
+       OIC_LOG(INFO, tag, "This is a fixed string call");
     directStdOutToConsole();
 
     bool testFileExists = file_exist(testFile);
@@ -160,7 +160,7 @@ TEST(LoggerTest, StringArgNoTag) {
     char stdFile[]  = "std_stringargnotag.txt";
 
     directStdOutToFile(testFile);
-    OC_LOG(INFO, 0, "This is a fixed string call");
+    OIC_LOG(INFO, 0, "This is a fixed string call");
     directStdOutToConsole();
 
     bool testFileExists = file_exist(testFile);
@@ -185,7 +185,7 @@ TEST(LoggerTest, StringArgNoLogStr) {
 
     directStdOutToFile(testFile);
     const char *tag = "StringArgNoLogStr";
-    OC_LOG(INFO, tag, 0);
+    OIC_LOG(INFO, tag, 0);
     directStdOutToConsole();
 
     bool testFileExists = file_exist(testFile);
@@ -209,7 +209,7 @@ TEST(LoggerTest, StringArgNoTagNoLogStr) {
     char stdFile[]  = "std_stringargnotagnologstr.txt";
 
     directStdOutToFile(testFile);
-    OC_LOG(INFO, 0, 0);
+    OIC_LOG(INFO, 0, 0);
     directStdOutToConsole();
 
     bool testFileExists = file_exist(testFile);
@@ -235,11 +235,11 @@ TEST(LoggerTest, StringArgLevels) {
     directStdOutToFile(testFile);
     const char *tag = "StringArgLevels";
     // DEBUG, INFO, WARNING, ERROR, FATAL
-    OC_LOG(DEBUG, tag, "this is a DEBUG message");
-    OC_LOG(INFO, tag, "this is a INFO message");
-    OC_LOG(WARNING, tag, "this is a WARNING message");
-    OC_LOG(ERROR, tag, "this is a ERROR message");
-    OC_LOG(FATAL, tag, "this is a FATAL message");
+    OIC_LOG(DEBUG, tag, "this is a DEBUG message");
+    OIC_LOG(INFO, tag, "this is a INFO message");
+    OIC_LOG(WARNING, tag, "this is a WARNING message");
+    OIC_LOG(ERROR, tag, "this is a ERROR message");
+    OIC_LOG(FATAL, tag, "this is a FATAL message");
     directStdOutToConsole();
 
     bool testFileExists = file_exist(testFile);
@@ -264,7 +264,7 @@ TEST(LoggerTest, StringArgMultiline) {
 
     directStdOutToFile(testFile);
     const char *tag = "StringArgMultiline";
-    OC_LOG(DEBUG, tag, "this is a DEBUG message\non multiple\nlines");
+    OIC_LOG(DEBUG, tag, "this is a DEBUG message\non multiple\nlines");
     directStdOutToConsole();
 
     bool testFileExists = file_exist(testFile);
@@ -290,10 +290,10 @@ TEST(LoggerTest, VariableArg) {
     directStdOutToFile(testFile);
     const char *tag = "VariableArg";
     // DEBUG, INFO, WARNING, ERROR, FATAL
-    OC_LOG_V(DEBUG, tag, "this is a char: %c", 'A');
-    OC_LOG_V(DEBUG, tag, "this is an integer: %d", 123);
-    OC_LOG_V(DEBUG, tag, "this is a string: %s", "hello");
-    OC_LOG_V(DEBUG, tag, "this is a float: %5.2f", 123.45);
+    OIC_LOG_V(DEBUG, tag, "this is a char: %c", 'A');
+    OIC_LOG_V(DEBUG, tag, "this is an integer: %d", 123);
+    OIC_LOG_V(DEBUG, tag, "this is a string: %s", "hello");
+    OIC_LOG_V(DEBUG, tag, "this is a float: %5.2f", 123.45);
     directStdOutToConsole();
 
     bool testFileExists = file_exist(testFile);
@@ -324,28 +324,28 @@ TEST(LoggerTest, LogBuffer) {
     for (int i = 0; i < (int)(sizeof buffer); i++) {
         buffer[i] = i;
     }
-    OC_LOG_BUFFER(DEBUG, tag, buffer, sizeof buffer);
+    OIC_LOG_BUFFER(DEBUG, tag, buffer, sizeof buffer);
 
     // Log buffer, 128 bytes is a good boundary (8 rows of 16 values)
     uint8_t buffer1[128];
     for (int i = 0; i < (int)(sizeof buffer1); i++) {
         buffer1[i] = i;
     }
-    OC_LOG_BUFFER(DEBUG, tag, buffer1, sizeof buffer1);
+    OIC_LOG_BUFFER(DEBUG, tag, buffer1, sizeof buffer1);
 
     // 1 below 128 byte boundary
     uint8_t buffer2[127];
     for (int i = 0; i < (int)(sizeof buffer2); i++) {
         buffer2[i] = i;
     }
-    OC_LOG_BUFFER(DEBUG, tag, buffer2, sizeof buffer2);
+    OIC_LOG_BUFFER(DEBUG, tag, buffer2, sizeof buffer2);
 
     // 1 above 128 byte boundary
     uint8_t buffer3[129];
     for (int i = 0; i < (int)(sizeof buffer3); i++) {
         buffer3[i] = i;
     }
-    OC_LOG_BUFFER(DEBUG, tag, buffer3, sizeof buffer3);
+    OIC_LOG_BUFFER(DEBUG, tag, buffer3, sizeof buffer3);
 
     directStdOutToConsole();
 
index 1d2a067..f2464b7 100644 (file)
@@ -58,4 +58,4 @@ elif env.get('ROUTING') == 'EP':
 
 routinglib = local_env.StaticLibrary('routingmanager', routing_src)
 local_env.InstallTarget(routinglib, 'routingmanager')
-local_env.UserInstallTargetLib(routinglib, 'routingmanager')
+
index 3cd6156..2dcbd08 100644 (file)
@@ -95,14 +95,16 @@ uint16_t RMGetMcastSeqNumber();
  * On reception of request from CA, RI sends to this function.
  * This checks if the route option is present and adds routing information to
  * to the route option data.
- * @param[in,out]   message      Received coap packet.
+ * @param[in,out]  message       Received coap packet.
  * @param[in]      sender        RemoteEndpoint which sent the packet.
  * @param[out]     destination   Populated by RM by parsing message, CA then forwards packet to
  *                               "destination".
+ * @param[out]     isEmptyMsg    Populated by RM by parsing the RouteOption.  If the MSGType is ACK
+ *                               in route option and is for self, then this flag is set.
  * @return  ::CA_STATUS_OK or Appropriate error code.
  */
 OCStackResult RMHandleRequest(CARequestInfo_t *message, const CAEndpoint_t *sender,
-                              bool *selfDestination);
+                              bool *selfDestination, bool *isEmptyMsg);
 
 /**
  * On reception of response from CA, RI sends to this function.
index 3e05341..b77d3b0 100644 (file)
@@ -65,7 +65,7 @@ extern "C"
  */
 #define RM_NULL_CHECK_WITH_RET(arg, log_tag, log_message) \
     if (NULL == arg ){ \
-        OC_LOG_V(ERROR, log_tag, "Invalid input:%s", log_message); \
+        OIC_LOG_V(ERROR, log_tag, "Invalid input:%s", log_message); \
         return OC_STACK_INVALID_PARAM; \
     } \
 
@@ -74,7 +74,7 @@ extern "C"
  */
 #define RM_NULL_CHECK_VOID(arg, log_tag, log_message) \
     if (NULL == arg ){ \
-        OC_LOG_V(ERROR, log_tag, "Invalid input:%s", log_message); \
+        OIC_LOG_V(ERROR, log_tag, "Invalid input:%s", log_message); \
         return; \
     } \
 
@@ -82,31 +82,50 @@ extern "C"
  * Macro to verify the return of an API.
  */
 #define RM_VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
-            {OC_LOG_V(ERROR, TAG, "%s failed!!", #op); goto exit;} }
+            {OIC_LOG_V(ERROR, TAG, "%s failed!!", #op); goto exit;} }
 
 /**
- * This structure is used to hold the hopcount, source and destination address.
+ * Message types in RouteOption to differentiate a normal response and Empty response.
+ */
+typedef enum
+{
+   NOR = 0,  /**< Normal Message. */
+   ACK,      /**< Empty Acknowledgement message. */
+   RST      /**< Empty Reset message. */
+}MSGType;
+
+/**
+ * This structure is used to hold the source address, destination address, message type and
+ * sequence number. This collectively forms the value of Route option in the message.
  */
 typedef struct
 {
     uint32_t srcGw;               /**< Source gateway for this packet. */
     uint32_t destGw;              /**< Destination gateway for this packet. */
-    uint16_t mSeqNum;             /**< HopCount. */
+    uint16_t mSeqNum;             /**< Multicast sequence Number. */
     uint16_t srcEp;               /**< Source endpoint for this packet. */
     uint16_t destEp;              /**< Destination endpoint for this packet. */
+    uint8_t msgType;              /**< Type of Message: Empty or normal. */
 } RMRouteOption_t;
 
 /**
+ * To set the stack mode in Routing manager.
+ */
+void RMSetStackMode(OCMode mode);
+
+/**
  * Adds the destination address to the Route options.
  * If Route option is already present, it adds the destination address information to
  * Route option else creates a new Route option with the destination address info.
  * @param[in]       endpoint        Destination address.
- * @param[in,out]   options         Header options present in the Request/response message.
- * @param[in,out]   numOptions      Number of options present in the message.
+ * @param[in,out]   message         Request/response message to add the route option
+ * @param[in]       isRequest       True if message is request else false.
+ * @param[out]      doPost          True if a POST message be sent for empty packet to
+ *                                  Routing gateway.
  * @return  ::CA_STATUS_OK or Appropriate error code.
  */
-OCStackResult RMAddInfo(const char *destination, CAHeaderOption_t **options,
-                        uint8_t *numOptions);
+OCStackResult RMAddInfo(const char *destination, void *message, bool isRequest,
+                        bool *doPost);
 
 /**
  * Removes the Route Option from the header options.
index 41024e4..23618d5 100644 (file)
 /**
  * Logging tag for module name.
  */
-#define TAG "RM"
+#define TAG "OIC_RM"
 
 /**
  * Tag for printing the logs of forwarding the packet.
  */
-#define RM_TAG "RAP"
+#define RM_TAG "OIC_RM_RAP"
 
 
 /**
@@ -143,16 +143,16 @@ void RMSendDeleteToNeighbourNodes();
 
 void RMGenerateGatewayID(uint8_t *id, size_t idLen)
 {
-    OC_LOG(DEBUG, TAG, "RMGenerateGatewayID IN");
+    OIC_LOG(DEBUG, TAG, "RMGenerateGatewayID IN");
     OCFillRandomMem(id, idLen);
-    OC_LOG(DEBUG, TAG, "RMGenerateGatewayID OUT");
+    OIC_LOG(DEBUG, TAG, "RMGenerateGatewayID OUT");
 }
 OCStackResult RMInitialize()
 {
-    OC_LOG(DEBUG, TAG, "RMInitialize IN");
+    OIC_LOG(DEBUG, TAG, "RMInitialize IN");
     if (g_isRMInitialized)
     {
-        OC_LOG(DEBUG, TAG, "RM already initialized");
+        OIC_LOG(DEBUG, TAG, "RM already initialized");
         return OC_STACK_OK;
     }
 
@@ -160,20 +160,20 @@ OCStackResult RMInitialize()
     OCStackResult result = RMInitGatewayResource();
     if (OC_STACK_OK != result)
     {
-        OC_LOG_V(ERROR, TAG, "RMInitGatewayResource failed[%d]", result);
+        OIC_LOG_V(ERROR, TAG, "RMInitGatewayResource failed[%d]", result);
         return result;
     }
 
     // Generates a 4 byte Gateway ID.
     RMGenerateGatewayID((uint8_t *)&g_GatewayID, sizeof(g_GatewayID));
 
-    OC_LOG_V(INFO, RM_TAG, "Gateway ID: %u", g_GatewayID);
+    OIC_LOG_V(INFO, RM_TAG, "Gateway ID: %u", g_GatewayID);
 
     // Initialize the Routing table manager.
     result = RTMInitialize(&g_routingGatewayTable, &g_routingEndpointTable);
     if (OC_STACK_OK != result)
     {
-        OC_LOG_V(ERROR, TAG, "RTMInitialize failed[%d]", result);
+        OIC_LOG_V(ERROR, TAG, "RTMInitialize failed[%d]", result);
         return result;
     }
 
@@ -183,7 +183,7 @@ OCStackResult RMInitialize()
     result = RMDiscoverGatewayResource();
     if (OC_STACK_OK != result)
     {
-        OC_LOG_V(ERROR, TAG, "RMDiscoverGatewayResource failed[%d]", result);
+        OIC_LOG_V(ERROR, TAG, "RMDiscoverGatewayResource failed[%d]", result);
         RTMTerminate(&g_routingGatewayTable, &g_routingEndpointTable);
         return result;
     }
@@ -192,16 +192,16 @@ OCStackResult RMInitialize()
     g_aliveTime = RTMGetCurrentTime();
     g_refreshTableTime = g_aliveTime;
 
-    OC_LOG(DEBUG, TAG, "RMInitialize OUT");
+    OIC_LOG(DEBUG, TAG, "RMInitialize OUT");
     return result;
 }
 
 OCStackResult RMTerminate()
 {
-    OC_LOG(DEBUG, TAG, "RMTerminate IN");
+    OIC_LOG(DEBUG, TAG, "RMTerminate IN");
     if (!g_isRMInitialized)
     {
-        OC_LOG(ERROR, TAG, "RM not initialized");
+        OIC_LOG(ERROR, TAG, "RM not initialized");
         return OC_STACK_ERROR;
     }
     // Send DELETE request to neighbour nodes
@@ -210,96 +210,96 @@ OCStackResult RMTerminate()
     OCStackResult result = RTMTerminate(&g_routingGatewayTable, &g_routingEndpointTable);
     if (OC_STACK_OK != result)
     {
-        OC_LOG_V(ERROR, TAG, "CARegisterRoutingMessageHandler failed[%d]", result);
+        OIC_LOG_V(ERROR, TAG, "CARegisterRoutingMessageHandler failed[%d]", result);
         return result;
     }
     g_isRMInitialized = false;
-    OC_LOG(DEBUG, TAG, "RMTerminate OUT");
+    OIC_LOG(DEBUG, TAG, "RMTerminate OUT");
     return result;
 }
 
 OCStackResult RMHandleGatewayRequest(OCServerRequest *request, const OCResource *resource)
 {
-    OC_LOG(DEBUG, TAG, "RMHandleGatewayRequest IN");
+    OIC_LOG(DEBUG, TAG, "RMHandleGatewayRequest IN");
 
     if (!g_isRMInitialized)
     {
-        OC_LOG(ERROR, TAG, "RM not initialized");
+        OIC_LOG(ERROR, TAG, "RM not initialized");
         return OC_STACK_ERROR;
     }
 
     RM_NULL_CHECK_WITH_RET(request, TAG, "request");
     RM_NULL_CHECK_WITH_RET(resource, TAG, "resource");
 
-    OC_LOG_V(DEBUG, TAG, "Received request of method: %d", request->method);
+    OIC_LOG_V(DEBUG, TAG, "Received request of method: %d", request->method);
 
     if (OC_REST_GET == request->method)
     {
         switch((OCObserveAction)request->observationOption)
         {
             case OC_OBSERVE_REGISTER:
-                OC_LOG(DEBUG, TAG, "Received OBSERVE request");
+                OIC_LOG(DEBUG, TAG, "Received OBSERVE request");
                 RMHandleOBSERVERequest(request, resource);
                 break;
             case OC_OBSERVE_DEREGISTER:
                 //TODO: Handle this case
-                OC_LOG(DEBUG, TAG, "Received OBSERVE deregister");
+                OIC_LOG(DEBUG, TAG, "Received OBSERVE deregister");
                 break;
             case OC_OBSERVE_NO_OPTION:
-                OC_LOG(DEBUG, TAG, "Received GET request");
+                OIC_LOG(DEBUG, TAG, "Received GET request");
                 RMHandleGETRequest(request, resource);
                 break;
             default:
-                OC_LOG(DEBUG, TAG, "Not Supported by Routing Manager");
+                OIC_LOG(DEBUG, TAG, "Not Supported by Routing Manager");
         }
     }
     else if (OC_REST_DELETE == request->method)
     {
-        OC_LOG(DEBUG, TAG, "Received a Delete request");
+        OIC_LOG(DEBUG, TAG, "Received a Delete request");
         RMHandleDELETERequest(request, resource);
     }
-    OC_LOG(DEBUG, TAG, "RMHandleGatewayRequest OUT");
+    OIC_LOG(DEBUG, TAG, "RMHandleGatewayRequest OUT");
     return OC_STACK_OK;
 }
 
 OCStackResult RMHandleRequestPayload(OCDevAddr devAddr, const uint8_t *reqPayload,
                                      size_t payloadSize)
 {
-    OC_LOG(DEBUG, TAG, "RMHandleRequestPayload IN");
+    OIC_LOG(DEBUG, TAG, "RMHandleRequestPayload IN");
     RM_NULL_CHECK_WITH_RET(reqPayload, TAG, "reqPayload");
 
     uint32_t gatewayId = 0;
 
     OCStackResult result = RMPParseRequestPayload(reqPayload, payloadSize, &gatewayId);
     RM_VERIFY_SUCCESS(result, OC_STACK_OK);
-    OC_LOG(INFO, TAG, "RMPParseRequestPayload is success");
+    OIC_LOG(INFO, TAG, "RMPParseRequestPayload is success");
     // Check if the entry is its own.
     if (gatewayId == g_GatewayID)
     {
-        OC_LOG(INFO, TAG, "Own Request Received!!");
+        OIC_LOG(INFO, TAG, "Own Request Received!!");
         return OC_STACK_CONTINUE;
     }
 
     CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
     CopyDevAddrToEndpoint(&devAddr, &endpoint);
 
-    OC_LOG_V(INFO, TAG, "Add the gateway ID: %u", gatewayId);
+    OIC_LOG_V(INFO, TAG, "Add the gateway ID: %u", gatewayId);
     RTMDestIntfInfo_t destInterfaces = {.observerId = 0};
     destInterfaces.destIntfAddr = endpoint;
     result = RTMAddGatewayEntry(gatewayId, 0, 1, &destInterfaces, &g_routingGatewayTable);
 
     if (OC_STACK_OK != result)
     {
-        OC_LOG(DEBUG, TAG, "Gateway was not added to the routing table");
+        OIC_LOG(DEBUG, TAG, "Gateway was not added to the routing table");
         return result;
     }
 
-    OC_LOG(INFO, TAG, "Gateway was added");
+    OIC_LOG(INFO, TAG, "Gateway was added");
     // Create a list to add the updated entries and notify the observers
     u_linklist_t *updatedTableList = u_linklist_create();
     if(!updatedTableList)
     {
-        OC_LOG(DEBUG, TAG, "Failure to notify");
+        OIC_LOG(DEBUG, TAG, "Failure to notify");
         return OC_STACK_NO_MEMORY;
     }
 
@@ -318,7 +318,7 @@ OCStackResult RMHandleRequestPayload(OCDevAddr devAddr, const uint8_t *reqPayloa
                                            &updatedPayload);
     if (OC_STACK_OK != result)
     {
-        OC_LOG_V(ERROR, TAG, "RMPConstructObserveResPayload failed[%d]", result);
+        OIC_LOG_V(ERROR, TAG, "RMPConstructObserveResPayload failed[%d]", result);
         RMPFreePayload(updatedPayload);
         goto exit;
     }
@@ -329,13 +329,13 @@ OCStackResult RMHandleRequestPayload(OCDevAddr devAddr, const uint8_t *reqPayloa
 
 exit:
     u_linklist_free(&updatedTableList);
-    OC_LOG(DEBUG, TAG, "RMHandleRequestPayload OUT");
+    OIC_LOG(DEBUG, TAG, "RMHandleRequestPayload OUT");
     return result;
 }
 
 OCStackResult RMHandleResponsePayload(const OCDevAddr *devAddr, const OCRepPayload *respPayload)
 {
-    OC_LOG(DEBUG, TAG, "RMHandleResponsePayload IN");
+    OIC_LOG(DEBUG, TAG, "RMHandleResponsePayload IN");
     RM_NULL_CHECK_WITH_RET(respPayload, TAG, "respPayload");
 
     // Parse the Payload to get the Gateway ID of neighbouring node.
@@ -350,7 +350,7 @@ OCStackResult RMHandleResponsePayload(const OCDevAddr *devAddr, const OCRepPaylo
     // Check if the entry is its own.
     if (gatewayId == g_GatewayID)
     {
-        OC_LOG(INFO, TAG, "-------------->Own entry, continue!!");
+        OIC_LOG(INFO, TAG, "-------------->Own entry, continue!!");
         RTMFreeGatewayRouteTable(&gatewayTableList);
         return OC_STACK_ERROR;
     }
@@ -361,13 +361,13 @@ OCStackResult RMHandleResponsePayload(const OCDevAddr *devAddr, const OCRepPaylo
     destInterfaces.destIntfAddr = endpoint;
     if (0 < seqNum)
     {
-        OC_LOG_V(DEBUG, TAG, "Sequence Number of Resp payload is %d, Forceupdate: %d",
+        OIC_LOG_V(DEBUG, TAG, "Sequence Number of Resp payload is %d, Forceupdate: %d",
                  seqNum, isUpdateSeqNum);
         result = RTMUpdateEntryParameters(gatewayId, seqNum, &destInterfaces,
                                           &g_routingGatewayTable, isUpdateSeqNum);
         if (OC_STACK_COMM_ERROR == result)
         {
-            OC_LOG(ERROR, TAG, "Few packet drops are found, sequence number is not matching");
+            OIC_LOG(ERROR, TAG, "Few packet drops are found, sequence number is not matching");
             // Send a observe request to the gateway.
             RMSendObserveRequest(devAddr, NULL);
             RTMFreeGatewayRouteTable(&gatewayTableList);
@@ -375,7 +375,7 @@ OCStackResult RMHandleResponsePayload(const OCDevAddr *devAddr, const OCRepPaylo
         }
         else if (OC_STACK_DUPLICATE_REQUEST == result)
         {
-            OC_LOG(ERROR, TAG, "Same sequence number is received");
+            OIC_LOG(ERROR, TAG, "Same sequence number is received");
             RTMFreeGatewayRouteTable(&gatewayTableList);
             return result;
         }
@@ -389,7 +389,7 @@ OCStackResult RMHandleResponsePayload(const OCDevAddr *devAddr, const OCRepPaylo
         RTMGatewayEntry_t *headPtr = u_linklist_get_data(gatewayTableList->list);
         if (headPtr && 0 == headPtr->routeCost)
         {
-            OC_LOG(INFO, TAG, "Remove entry is called");
+            OIC_LOG(INFO, TAG, "Remove entry is called");
             doRemoveEntry = true;
         }
     }
@@ -398,25 +398,25 @@ OCStackResult RMHandleResponsePayload(const OCDevAddr *devAddr, const OCRepPaylo
     u_linklist_t *updatedTableList = u_linklist_create();
     if(!updatedTableList)
     {
-        OC_LOG(DEBUG, TAG, "Failed to allocate memory");
+        OIC_LOG(DEBUG, TAG, "Failed to allocate memory");
         return OC_STACK_NO_MEMORY;
     }
 
     u_linklist_t *alternativeRouteList = u_linklist_create();
     if(!alternativeRouteList)
     {
-        OC_LOG(DEBUG, TAG, "Failed to allocate memory");
+        OIC_LOG(DEBUG, TAG, "Failed to allocate memory");
         return OC_STACK_NO_MEMORY;
     }
 
     OCRepPayload *updatedPayload = NULL;
     if (false == doRemoveEntry)
     {
-        OC_LOG_V(INFO, TAG, "Add the gateway ID: %u", gatewayId);
+        OIC_LOG_V(INFO, TAG, "Add the gateway ID: %u", gatewayId);
         result = RTMAddGatewayEntry(gatewayId, 0, 1, &destInterfaces, &g_routingGatewayTable);
         if (OC_STACK_OK == result)
         {
-            OC_LOG(INFO, TAG, "Node was added");
+            OIC_LOG(INFO, TAG, "Node was added");
             RTMGatewayId_t gwId = {.gatewayId = gatewayId};
             RTMGatewayEntry_t newNode;
             newNode.destination = &gwId;
@@ -426,7 +426,7 @@ OCStackResult RMHandleResponsePayload(const OCDevAddr *devAddr, const OCRepPaylo
 
             if (NULL == gatewayTableList)
             {
-                OC_LOG(INFO, TAG, "Received a Discover Payload");
+                OIC_LOG(INFO, TAG, "Received a Discover Payload");
                 g_sequenceNumber++;
                 result = RMPConstructObserveResPayload(g_GatewayID, g_sequenceNumber,
                                                        updatedTableList, false,
@@ -447,12 +447,12 @@ OCStackResult RMHandleResponsePayload(const OCDevAddr *devAddr, const OCRepPaylo
         // Check if the entry is its own.
         if (!entry || entry->destination->gatewayId == g_GatewayID)
         {
-            OC_LOG(INFO, TAG, "Ignore entry, continue!!");
+            OIC_LOG(INFO, TAG, "Ignore entry, continue!!");
             u_linklist_get_next(&iterTable);
             continue;
         }
 
-        OC_LOG_V(INFO, TAG, "Gateway ID: %u", entry->destination->gatewayId);
+        OIC_LOG_V(INFO, TAG, "Gateway ID: %u", entry->destination->gatewayId);
         if (true == doRemoveEntry)
         {
             // Remove the entry from RTM.
@@ -475,7 +475,7 @@ OCStackResult RMHandleResponsePayload(const OCDevAddr *devAddr, const OCRepPaylo
 
         if (OC_STACK_OK == result)
         {
-            OC_LOG(INFO, TAG, "Gateway was added/removed");
+            OIC_LOG(INFO, TAG, "Gateway was added/removed");
             u_linklist_add(updatedTableList, (void *)entry);
             RTMPrintTable(g_routingGatewayTable, g_routingEndpointTable);
         }
@@ -484,7 +484,7 @@ OCStackResult RMHandleResponsePayload(const OCDevAddr *devAddr, const OCRepPaylo
 
     if ( 0 < u_linklist_length(alternativeRouteList))
     {
-        OC_LOG(DEBUG, TAG, "Alternative routing found");
+        OIC_LOG(DEBUG, TAG, "Alternative routing found");
         // Send the notification.
         OCRepPayload *removeTablePayload = NULL;
         g_sequenceNumber++;
@@ -493,7 +493,7 @@ OCStackResult RMHandleResponsePayload(const OCDevAddr *devAddr, const OCRepPaylo
                                                &removeTablePayload);
         if (OC_STACK_OK != result)
         {
-            OC_LOG_V(ERROR, TAG, "RMPConstructObserveResPayload failed[%d]", result);
+            OIC_LOG_V(ERROR, TAG, "RMPConstructObserveResPayload failed[%d]", result);
             RMPFreePayload(removeTablePayload);
             goto exit;
         }
@@ -504,7 +504,7 @@ OCStackResult RMHandleResponsePayload(const OCDevAddr *devAddr, const OCRepPaylo
 
     if ( 0 >= u_linklist_length(updatedTableList))
     {
-        OC_LOG_V(DEBUG, TAG, "No updation is needed, Length is %d",
+        OIC_LOG_V(DEBUG, TAG, "No updation is needed, Length is %d",
                  u_linklist_length(updatedTableList));
         goto exit;
     }
@@ -532,13 +532,13 @@ exit:
     RTMFreeGatewayRouteTable(&gatewayTableList);
     u_linklist_free(&updatedTableList);
     u_linklist_free(&alternativeRouteList);
-    OC_LOG(DEBUG, TAG, "RMHandleResponsePayload OUT");
+    OIC_LOG(DEBUG, TAG, "RMHandleResponsePayload OUT");
     return OC_STACK_OK;
 }
 
 OCStackResult RMHandleGETRequest(const OCServerRequest *request, const OCResource *resource)
 {
-    OC_LOG(DEBUG, TAG, "RMHandleGETRequest IN");
+    OIC_LOG(DEBUG, TAG, "RMHandleGETRequest IN");
     RM_NULL_CHECK_WITH_RET(request, TAG, "request");
     RM_NULL_CHECK_WITH_RET(resource, TAG, "resource");
 
@@ -546,7 +546,7 @@ OCStackResult RMHandleGETRequest(const OCServerRequest *request, const OCResourc
     OCStackResult result = RMPConstructGatewayPayload(g_GatewayID, &payload);
     if (OC_STACK_OK != result)
     {
-        OC_LOG_V(DEBUG, TAG, "RMPConstructDiscoverPayload failed[%d]", result);
+        OIC_LOG_V(DEBUG, TAG, "RMPConstructDiscoverPayload failed[%d]", result);
         return result;
     }
 
@@ -554,7 +554,7 @@ OCStackResult RMHandleGETRequest(const OCServerRequest *request, const OCResourc
     result = RMSendResponse(request, resource, payload);
     if (OC_STACK_OK != result)
     {
-        OC_LOG_V(DEBUG, TAG, "Send response failed[%d]", result);
+        OIC_LOG_V(DEBUG, TAG, "Send response failed[%d]", result);
         RMPFreePayload(payload);
         return result;
     }
@@ -564,15 +564,15 @@ OCStackResult RMHandleGETRequest(const OCServerRequest *request, const OCResourc
     result = RMSendObserveRequest(&(request->devAddr), NULL);
     if (OC_STACK_OK != result)
     {
-        OC_LOG_V(DEBUG, TAG, "Send response failed[%d]", result);
+        OIC_LOG_V(DEBUG, TAG, "Send response failed[%d]", result);
     }
-    OC_LOG(DEBUG, TAG, "RMHandleGETRequest OUT");
+    OIC_LOG(DEBUG, TAG, "RMHandleGETRequest OUT");
     return result;
 }
 
 OCStackResult RMHandleOBSERVERequest(OCServerRequest *request, const OCResource *resource)
 {
-    OC_LOG(DEBUG, TAG, "RMHandleOBSERVERequest IN");
+    OIC_LOG(DEBUG, TAG, "RMHandleOBSERVERequest IN");
     RM_NULL_CHECK_WITH_RET(request, TAG, "request");
     RM_NULL_CHECK_WITH_RET(resource, TAG, "resource");
 
@@ -586,19 +586,19 @@ OCStackResult RMHandleOBSERVERequest(OCServerRequest *request, const OCResource
     OCObservationId obsID = 0;
     OCStackResult result = RMAddObserver(request, &obsID);
     RM_VERIFY_SUCCESS(result, OC_STACK_OK);
-    OC_LOG_V(DEBUG, TAG, "Observer ID is %d", obsID);
+    OIC_LOG_V(DEBUG, TAG, "Observer ID is %d", obsID);
 
 
     // Get the Routing table from RTM
     OCRepPayload *payload = NULL;
     RTMPrintTable(g_routingGatewayTable, g_routingEndpointTable);
-    OC_LOG(DEBUG, TAG, "Construct Routing table payload");
+    OIC_LOG(DEBUG, TAG, "Construct Routing table payload");
     result = RMPConstructObserveResPayload(g_GatewayID, g_sequenceNumber,
                                            g_routingGatewayTable, true,
                                            &payload);
     if (OC_STACK_OK != result)
     {
-        OC_LOG_V(ERROR, TAG, "RMPConstructObserveResPayload failed[%d]", result);
+        OIC_LOG_V(ERROR, TAG, "RMPConstructObserveResPayload failed[%d]", result);
         RMPFreePayload(payload);
         goto exit;
     }
@@ -607,13 +607,13 @@ OCStackResult RMHandleOBSERVERequest(OCServerRequest *request, const OCResource
     RMPFreePayload(payload);
     RM_VERIFY_SUCCESS(result, OC_STACK_OK);
 exit:
-    OC_LOG(DEBUG, TAG, "RMHandleOBSERVERequest OUT");
+    OIC_LOG(DEBUG, TAG, "RMHandleOBSERVERequest OUT");
     return result;
 }
 
 OCStackResult RMHandleDELETERequest(const OCServerRequest *request, const OCResource *resource)
 {
-    OC_LOG(DEBUG, TAG, "RMHandleDELETERequest IN");
+    OIC_LOG(DEBUG, TAG, "RMHandleDELETERequest IN");
     RM_NULL_CHECK_WITH_RET(request, TAG, "request");
     RM_NULL_CHECK_WITH_RET(resource, TAG, "resource");
 
@@ -621,9 +621,9 @@ OCStackResult RMHandleDELETERequest(const OCServerRequest *request, const OCReso
     OCStackResult result = RMPParseRequestPayload(request->payload, request->payloadSize,
                                                   &gatewayId);
     RM_VERIFY_SUCCESS(result, OC_STACK_OK);
-    OC_LOG(INFO, TAG, "RMPParseRequestPayload is success");
+    OIC_LOG(INFO, TAG, "RMPParseRequestPayload is success");
 
-    OC_LOG_V(INFO, TAG, "Remove the gateway ID: %u", gatewayId);
+    OIC_LOG_V(INFO, TAG, "Remove the gateway ID: %u", gatewayId);
 
     u_linklist_t *removedGatewayNodes = NULL;
     result = RTMRemoveGatewayEntry(gatewayId, &removedGatewayNodes, &g_routingGatewayTable);
@@ -637,7 +637,7 @@ OCStackResult RMHandleDELETERequest(const OCServerRequest *request, const OCReso
                                             false, &resPayloads);
         if (OC_STACK_OK != result)
         {
-            OC_LOG_V(ERROR, TAG, "RMPConstructRemovalPayload failed[%d]", result);
+            OIC_LOG_V(ERROR, TAG, "RMPConstructRemovalPayload failed[%d]", result);
             RMPFreePayload(resPayloads);
             goto exit;
         }
@@ -649,13 +649,13 @@ OCStackResult RMHandleDELETERequest(const OCServerRequest *request, const OCReso
 
 exit:
     RTMFreeGatewayRouteTable(&removedGatewayNodes);
-    OC_LOG(DEBUG, TAG, "RMHandleDELETERequest OUT");
+    OIC_LOG(DEBUG, TAG, "RMHandleDELETERequest OUT");
     return result;
 }
 
 OCStackResult RMAddObserver(OCServerRequest *request, OCObservationId *obsID)
 {
-    OC_LOG(DEBUG, TAG, "RMAddObserverForGateway OUT");
+    OIC_LOG(DEBUG, TAG, "RMAddObserverForGateway OUT");
     RM_NULL_CHECK_WITH_RET(request, TAG, "request");
     RM_NULL_CHECK_WITH_RET(obsID, TAG, "obsID");
 
@@ -666,7 +666,7 @@ OCStackResult RMAddObserver(OCServerRequest *request, OCObservationId *obsID)
     // Check if observer is already added.
     if (true == RTMIsObserverPresent(endpoint, obsID, g_routingGatewayTable))
     {
-        OC_LOG(DEBUG, TAG, "Observer is present");
+        OIC_LOG(DEBUG, TAG, "Observer is present");
         request->observeResult = OC_STACK_OK;
         return OC_STACK_OK;
     }
@@ -675,22 +675,22 @@ OCStackResult RMAddObserver(OCServerRequest *request, OCObservationId *obsID)
     request->observeResult = result;
     if (OC_STACK_OK == result)
     {
-        OC_LOG(DEBUG, TAG, "Added observer successfully");
+        OIC_LOG(DEBUG, TAG, "Added observer successfully");
 
         // Add the observer to the list.
         result = RTMAddObserver(*obsID, endpoint, &g_routingGatewayTable);
         if (OC_STACK_OK != result)
         {
-            OC_LOG_V(DEBUG, TAG, "RMAddObserver failed[%d]", result);
+            OIC_LOG_V(DEBUG, TAG, "RMAddObserver failed[%d]", result);
         }
     }
-    OC_LOG(DEBUG, TAG, "RMAddObserverForGateway OUT");
+    OIC_LOG(DEBUG, TAG, "RMAddObserverForGateway OUT");
     return result;
 }
 
 OCStackResult RMSendNotificationToAll(const OCRepPayload *payload)
 {
-    OC_LOG(DEBUG, TAG, "RMSendNotificationToAll IN");
+    OIC_LOG(DEBUG, TAG, "RMSendNotificationToAll IN");
     RM_NULL_CHECK_WITH_RET(payload, TAG, "payload");
 
     OCObservationId *obsList = NULL;
@@ -698,11 +698,11 @@ OCStackResult RMSendNotificationToAll(const OCRepPayload *payload)
     // Get the complete observer list.
     RTMGetObserverList(&obsList, &obsLen, g_routingGatewayTable);
     OCStackResult result = OC_STACK_OK;
-    OC_LOG_V(DEBUG, TAG, "Number of observers is %d", obsLen);
+    OIC_LOG_V(DEBUG, TAG, "Number of observers is %d", obsLen);
     if (0 < obsLen)
     {
         // Send notification to the list of observers.
-        OC_LOG_V(DEBUG, TAG, "Sending notification with Sequence Number: %d", g_sequenceNumber);
+        OIC_LOG_V(DEBUG, TAG, "Sending notification with Sequence Number: %d", g_sequenceNumber);
         result = RMSendNotificationForListofObservers(obsList, obsLen, payload);
         RM_VERIFY_SUCCESS(result, OC_STACK_OK);
         g_aliveTime = RTMGetCurrentTime();
@@ -710,7 +710,7 @@ OCStackResult RMSendNotificationToAll(const OCRepPayload *payload)
 
 exit:
     OICFree(obsList);
-    OC_LOG(DEBUG, TAG, "RMSendNotificationToAll OUT");
+    OIC_LOG(DEBUG, TAG, "RMSendNotificationToAll OUT");
     return result;
 }
 
@@ -732,11 +732,11 @@ void RMProcess()
                                                false, &payload);
         if (OC_STACK_OK != result)
         {
-            OC_LOG_V(ERROR, TAG, "RMPConstructObserveResPayload failed[%d]", result);
+            OIC_LOG_V(ERROR, TAG, "RMPConstructObserveResPayload failed[%d]", result);
             RMPFreePayload(payload);
             goto exit;
         }
-        OC_LOG(DEBUG, TAG, "Sending the alive notification to all");
+        OIC_LOG(DEBUG, TAG, "Sending the alive notification to all");
         // Send notification for every 15s to all the neighbours.
         result = RMSendNotificationToAll(payload);
         RMPFreePayload(payload);
@@ -745,7 +745,7 @@ void RMProcess()
 
     if (ROUTINGTABLE_VALIDATION_TIMEOUT <= currentTime - g_refreshTableTime)
     {
-        OC_LOG(DEBUG, TAG, "Validating the routing table");
+        OIC_LOG(DEBUG, TAG, "Validating the routing table");
         u_linklist_t *removedEntries = NULL;
         // Remove the invalid gateway entries.
         RTMRemoveInvalidGateways(&removedEntries, &g_routingGatewayTable);
@@ -758,7 +758,7 @@ void RMProcess()
             RTMFreeGatewayRouteTable(&removedEntries);
             if (OC_STACK_OK != result)
             {
-                OC_LOG_V(ERROR, TAG, "RMPConstructRemovalPayload failed[%d]", result);
+                OIC_LOG_V(ERROR, TAG, "RMPConstructRemovalPayload failed[%d]", result);
                 RMPFreePayload(resPayloads);
                 goto exit;
             }
@@ -775,7 +775,7 @@ void RMProcess()
 
     if (!g_isValidated && ROUTINGTABLE_REFRESH_TIMEOUT <= (currentTime - g_refreshTableTime))
     {
-        OC_LOG_V(DEBUG, TAG, "Refreshing the routing table: %u", currentTime);
+        OIC_LOG_V(DEBUG, TAG, "Refreshing the routing table: %llu", currentTime);
         u_linklist_t* invalidInterfaces = NULL;
         RTMUpdateDestAddrValidity(&invalidInterfaces, &g_routingGatewayTable);
         if (0 < u_linklist_length(invalidInterfaces))
@@ -807,22 +807,22 @@ exit:
 
 OCStackResult RMGetGatewayPayload(OCRepPayload **payload)
 {
-    OC_LOG(DEBUG, TAG, "RMGetGatewayPayload IN");
+    OIC_LOG(DEBUG, TAG, "RMGetGatewayPayload IN");
     OCStackResult result = RMPConstructGatewayPayload(g_GatewayID, payload);
-    OC_LOG_V(DEBUG, TAG, "RMPConstructDiscoverPayload result is %d", result);
-    OC_LOG(DEBUG, TAG, "RMGetGatewayPayload OUT");
+    OIC_LOG_V(DEBUG, TAG, "RMPConstructDiscoverPayload result is %d", result);
+    OIC_LOG(DEBUG, TAG, "RMGetGatewayPayload OUT");
     return result;
 }
 
 void RMSendDeleteToNeighbourNodes()
 {
-    OC_LOG(DEBUG, TAG, "RMSendDeleteToNeighbourNodes IN");
+    OIC_LOG(DEBUG, TAG, "RMSendDeleteToNeighbourNodes IN");
     u_linklist_t *neighbourNodes = NULL;
     RTMGetNeighbours(&neighbourNodes, g_routingGatewayTable);
 
     if (0 >= u_linklist_length(neighbourNodes))
     {
-        OC_LOG(DEBUG, TAG, "No neighbour nodes present");
+        OIC_LOG(DEBUG, TAG, "No neighbour nodes present");
         return;
     }
 
@@ -836,7 +836,7 @@ void RMSendDeleteToNeighbourNodes()
         OCStackResult result = RMPConstructGatewayPayload(g_GatewayID, &payload);
         if (OC_STACK_OK != result)
         {
-            OC_LOG_V(DEBUG, TAG, "RMPConstructGatewayPayload failed[%d]", result);
+            OIC_LOG_V(DEBUG, TAG, "RMPConstructGatewayPayload failed[%d]", result);
             RMPFreePayload(payload);
             u_linklist_free(&neighbourNodes);
             return;
@@ -850,12 +850,12 @@ void RMSendDeleteToNeighbourNodes()
                 RTMDestIntfInfo_t *dest = u_arraylist_get(entry->destination->destIntfAddr, i);
                 if (!dest)
                 {
-                    OC_LOG(ERROR, RM_TAG, "Failed to get dest address");
+                    OIC_LOG(ERROR, RM_TAG, "Failed to get dest address");
                     continue;
                 }
                 OCDevAddr devAddr = {.adapter = OC_DEFAULT_ADAPTER};
                 CopyEndpointToDevAddr(&(dest->destIntfAddr), &devAddr);
-                OC_LOG_V(DEBUG, TAG, "\nDestination interface addresses: %s[%d], OCDevAddr: %s[%d]",
+                OIC_LOG_V(DEBUG, TAG, "\nDestination interface addresses: %s[%d], OCDevAddr: %s[%d]",
                          dest->destIntfAddr.addr, dest->destIntfAddr.port, devAddr.addr, devAddr.port);
                 RMSendDeleteRequest(&devAddr, payload);
             }
@@ -865,14 +865,14 @@ void RMSendDeleteToNeighbourNodes()
     }
 
     u_linklist_free(&neighbourNodes);
-    OC_LOG(DEBUG, TAG, "RMSendDeleteToNeighbourNodes OUT");
+    OIC_LOG(DEBUG, TAG, "RMSendDeleteToNeighbourNodes OUT");
 }
 
 uint32_t RMGetGatewayId()
 {
     if (!g_isRMInitialized)
     {
-        OC_LOG(ERROR, TAG, "RM not initialized");
+        OIC_LOG(ERROR, TAG, "RM not initialized");
         return 0;
     }
     return g_GatewayID;
@@ -882,7 +882,7 @@ uint16_t RMGetMcastSeqNumber()
 {
     if (!g_isRMInitialized)
     {
-        OC_LOG(DEBUG, TAG, "RM not initialized");
+        OIC_LOG(DEBUG, TAG, "RM not initialized");
         return 0;
     }
     return ++g_mcastsequenceNumber;
@@ -906,13 +906,14 @@ uint16_t RMGetMcastSeqNumber()
  */
 
 OCStackResult RMHandlePacket(bool isRequest, void *message, const CAEndpoint_t *sender,
-                             bool *selfDestination)
+                             bool *selfDestination, bool *isEmptyMsg)
 {
     RM_NULL_CHECK_WITH_RET(message, RM_TAG, "message");
     RM_NULL_CHECK_WITH_RET(sender, RM_TAG, "sender");
     RM_NULL_CHECK_WITH_RET(selfDestination, RM_TAG, "selfDestination");
 
     bool forward = false;
+    bool isEMPTYPacket = false;
     CAEndpoint_t nextHop = {.adapter = CA_DEFAULT_ADAPTER};
     CAInfo_t *info = NULL;
     if (isRequest)
@@ -933,7 +934,7 @@ OCStackResult RMHandlePacket(bool isRequest, void *message, const CAEndpoint_t *
     RMGetRouteOptionIndex(info->options, info->numOptions, &routeIndex);
     if (-1 >= routeIndex)
     {
-        OC_LOG(ERROR, RM_TAG, "No route option present. Let RI Handle");
+        OIC_LOG(ERROR, RM_TAG, "No route option present. Let RI Handle");
         // Let RI handle this packet.
         *selfDestination = true;
         return OC_STACK_OK;
@@ -944,7 +945,7 @@ OCStackResult RMHandlePacket(bool isRequest, void *message, const CAEndpoint_t *
     OCStackResult res = RMParseRouteOption(&info->options[routeIndex], &routeOption);
     if (OC_STACK_OK != res)
     {
-        OC_LOG_V(ERROR, RM_TAG, "RMParseRouteOption failed");
+        OIC_LOG_V(ERROR, RM_TAG, "RMParseRouteOption failed");
         return OC_STACK_ERROR;
     }
 
@@ -954,7 +955,7 @@ OCStackResult RMHandlePacket(bool isRequest, void *message, const CAEndpoint_t *
      */
     if (g_GatewayID == routeOption.srcGw)
     {
-        OC_LOG_V(ERROR, RM_TAG, "Packet is of its own");
+        OIC_LOG_V(ERROR, RM_TAG, "Packet is of its own");
         if (0 == routeOption.destGw && g_mcastsequenceNumber < routeOption.mSeqNum)
         {
             g_mcastsequenceNumber = routeOption.mSeqNum;
@@ -964,29 +965,29 @@ OCStackResult RMHandlePacket(bool isRequest, void *message, const CAEndpoint_t *
     }
     else if (0 == routeOption.srcGw)
     {
-        OC_LOG(INFO, RM_TAG, "Source missing in option");
+        OIC_LOG(INFO, RM_TAG, "Source missing in option");
         // Packet from end device as Gateway will add source in option.
         uint16_t endpointId = g_EndpointCount + 1;
         OCStackResult res = RTMAddEndpointEntry(&endpointId, sender, &g_routingEndpointTable);
         if (OC_STACK_OK == res)
         {
             g_EndpointCount = endpointId;
-            OC_LOG_V(INFO, RM_TAG, "New endpoint added [%d]:[%s]", g_EndpointCount, sender->addr);
+            OIC_LOG_V(INFO, RM_TAG, "New endpoint added [%d]:[%s]", g_EndpointCount, sender->addr);
         }
         else if (OC_STACK_DUPLICATE_REQUEST == res)
         {
-            OC_LOG_V(INFO, RM_TAG, "Endpoint exist [%d]", endpointId);
+            OIC_LOG_V(INFO, RM_TAG, "Endpoint exist [%d]", endpointId);
         }
         else
         {
-            OC_LOG(ERROR, RM_TAG, "Add Endpoint failed");
+            OIC_LOG(ERROR, RM_TAG, "Add Endpoint failed");
             return OC_STACK_ERROR;
         }
 
         // add source option.
         routeOption.srcGw = g_GatewayID;
         routeOption.srcEp = endpointId;
-        OC_LOG_V(INFO, RM_TAG, "Added source: [%u:%u]", g_GatewayID, endpointId);
+        OIC_LOG_V(INFO, RM_TAG, "Added source: [%u:%u]", g_GatewayID, endpointId);
     }
 
     /*
@@ -996,7 +997,7 @@ OCStackResult RMHandlePacket(bool isRequest, void *message, const CAEndpoint_t *
      */
     if (0 == routeOption.destGw)
     {
-        OC_LOG(INFO, RM_TAG, "Destination missing in option");
+        OIC_LOG(INFO, RM_TAG, "Destination missing in option");
         // This is a multicast packet.
         if (g_GatewayID == routeOption.srcGw)
         {
@@ -1009,7 +1010,7 @@ OCStackResult RMHandlePacket(bool isRequest, void *message, const CAEndpoint_t *
             if (OC_STACK_OK != update)
             {
                 // this shouldnt have been forwarded. ignore.
-                OC_LOG_V(ERROR, RM_TAG, "Multicast Sequence number not proper: %d",
+                OIC_LOG_V(ERROR, RM_TAG, "Multicast Sequence number not proper: %d",
                          routeOption.mSeqNum);
                 return OC_STACK_ERROR;
             }
@@ -1047,7 +1048,14 @@ OCStackResult RMHandlePacket(bool isRequest, void *message, const CAEndpoint_t *
     }
     else if (g_GatewayID == routeOption.destGw)
     {
-        OC_LOG(INFO, RM_TAG, "GatewayId found in destination");
+        OIC_LOG(INFO, RM_TAG, "GatewayId found in destination");
+
+        // Check the MSGType of RouteOption to find if the packet is EMPTY packet.
+        if (ACK == routeOption.msgType || RST == routeOption.msgType)
+        {
+            isEMPTYPacket = true;
+        }
+
         /*
          * This unicast packet either belongs to us or any of our connected end devices
          * check if packet belongs to end device.
@@ -1055,12 +1063,12 @@ OCStackResult RMHandlePacket(bool isRequest, void *message, const CAEndpoint_t *
         if (0 != routeOption.destEp)
         {
             // forward packet to the client.
-            OC_LOG_V(INFO, RM_TAG, "Forwarding packet to client id [%u]", routeOption.destEp);
+            OIC_LOG_V(INFO, RM_TAG, "Forwarding packet to client id [%u]", routeOption.destEp);
             CAEndpoint_t *clientInfo = RTMGetEndpointEntry(routeOption.destEp,
                                                            g_routingEndpointTable);
             if(!clientInfo)
             {
-                OC_LOG(ERROR, RM_TAG, "Failed to get Client info");
+                OIC_LOG(ERROR, RM_TAG, "Failed to get Client info");
                 return OC_STACK_ERROR;
             }
 
@@ -1072,7 +1080,7 @@ OCStackResult RMHandlePacket(bool isRequest, void *message, const CAEndpoint_t *
         else
         {
             // packet is for us.
-            OC_LOG(INFO, RM_TAG, "Received packet for self");
+            OIC_LOG(INFO, RM_TAG, "Received packet for self");
             forward = false;
             *selfDestination = true;
             goto rewriteandexit;
@@ -1084,11 +1092,11 @@ OCStackResult RMHandlePacket(bool isRequest, void *message, const CAEndpoint_t *
          * This unicast packet belongs to other gateway.
          * we only want to print first 4 bytes of packet as readable GatewayId.
          */
-        OC_LOG_V(INFO, RM_TAG, "Forwarding packet to Gateway: %u", routeOption.destGw);
+        OIC_LOG_V(INFO, RM_TAG, "Forwarding packet to Gateway: %u", routeOption.destGw);
         RTMGatewayId_t *nextHopGw = RTMGetNextHop(routeOption.destGw, g_routingGatewayTable);
         if(!nextHopGw)
         {
-            OC_LOG(ERROR, RM_TAG, "Failed to get next hop");
+            OIC_LOG(ERROR, RM_TAG, "Failed to get next hop");
             return OC_STACK_ERROR;
         }
 
@@ -1096,7 +1104,7 @@ OCStackResult RMHandlePacket(bool isRequest, void *message, const CAEndpoint_t *
         RTMDestIntfInfo_t *address = u_arraylist_get(nextHopGw->destIntfAddr, 0);
         if (!address)
         {
-            OC_LOG(ERROR, RM_TAG, "Failed to get address for next hop");
+            OIC_LOG(ERROR, RM_TAG, "Failed to get address for next hop");
             return OC_STACK_ERROR;
         }
 
@@ -1111,22 +1119,47 @@ rewriteandexit:
     if (forward)
     {
         // Don't forward any packet meant for gateway resource.
-        if (info->resourceUri && (0 == strcmp(info->resourceUri, OC_RSRVD_GATEWAY_URI)))
+        if (info->resourceUri && (0 == strcmp(info->resourceUri, OC_RSRVD_GATEWAY_URI)) &&
+            (ACK != routeOption.msgType))
         {
-            OC_LOG(ERROR, RM_TAG, "Not forwarding gateway resource packet");
+            OIC_LOG(ERROR, RM_TAG, "Not forwarding gateway resource packet");
         }
         else if (sender->flags & CA_SECURE)
         {
-            OC_LOG(ERROR, RM_TAG, "This is secured request. Not supported by routing manager");
+            OIC_LOG(ERROR, RM_TAG, "This is secured request. Not supported by routing manager");
             return OC_STACK_ERROR;
         }
+        else if (isEMPTYPacket)
+        {
+            OIC_LOG(DEBUG, TAG, "The message to be Forwarded is a EMPTY message");
+            CAResponseInfo_t responseMessage = {.result = CA_EMPTY};
+            if (ACK == routeOption.msgType)
+            {
+                responseMessage.info.type = CA_MSG_ACKNOWLEDGE;
+            }
+            else
+            {
+                responseMessage.info.type = CA_MSG_RESET;
+            }
+
+            responseMessage.info.messageId = info->messageId;
+
+            CAResult_t caRes = CASendResponse(&nextHop, &responseMessage);
+            if (CA_STATUS_OK != caRes)
+            {
+                OIC_LOG_V(ERROR, RM_TAG, "Failed to forward response to next hop [%d][%s]",
+                         caRes, nextHop.addr);
+                // Since a response is always unicast, return error here.
+                return OC_STACK_ERROR;
+            }
+        }
         else
         {
             // rewrite any changes in routing option.
             res = RMCreateRouteOption(&routeOption, &info->options[routeIndex]);
             if (OC_STACK_OK != res)
             {
-                OC_LOG_V(ERROR, RM_TAG, "Rewriting RM option failed");
+                OIC_LOG_V(ERROR, RM_TAG, "Rewriting RM option failed");
                 return res;
             }
             /*
@@ -1140,7 +1173,7 @@ rewriteandexit:
                 CAResult_t caRes = CASendRequest(&nextHop, msg);
                 if (CA_STATUS_OK != caRes)
                 {
-                    OC_LOG_V(ERROR, RM_TAG, "Failed to forward request to next hop [%d][%s]", caRes,
+                    OIC_LOG_V(ERROR, RM_TAG, "Failed to forward request to next hop [%d][%s]", caRes,
                              nextHop.addr);
                     if(0 == routeOption.destGw)
                     {
@@ -1159,7 +1192,7 @@ rewriteandexit:
                 CAResult_t caRes = CASendResponse(&nextHop, msg);
                 if (CA_STATUS_OK != caRes)
                 {
-                    OC_LOG_V(ERROR, RM_TAG, "Failed to forward response to next hop [%d][%s]",
+                    OIC_LOG_V(ERROR, RM_TAG, "Failed to forward response to next hop [%d][%s]",
                              caRes, nextHop.addr);
                     // Since a response is always unicast, return error here.
                     return OC_STACK_ERROR;
@@ -1167,21 +1200,52 @@ rewriteandexit:
             }
         }
     }
+    else
+    {
+        if (isEMPTYPacket)
+        {
+            if (isRequest)
+            {
+                OIC_LOG(DEBUG, TAG, "POST message with type ACK in Route Option");
+                if (NULL != isEmptyMsg)
+                {
+                    *isEmptyMsg = true;
+                }
+            }
+            else
+            {
+                OIC_LOG(DEBUG, TAG, "Response for EMPTY message is received");
+                CAResponseInfo_t *msg = message;
+                if (ACK == (MSGType)routeOption.msgType)
+                {
+                    msg->info.type = CA_MSG_ACKNOWLEDGE;
+                }
+                else
+                {
+                    msg->info.type = CA_MSG_RESET;
+                }
+                msg->result = CA_EMPTY;
+                OICFree(msg->info.token);
+                msg->info.token = NULL;
+                msg->info.tokenLength = 0;
+            }
+        }
+    }
 
-    OC_LOG_V(INFO, RM_TAG, "Sender: [%u] Destination: [%u]", routeOption.srcGw, routeOption.destGw);
+    OIC_LOG_V(INFO, RM_TAG, "Sender: [%u] Destination: [%u]", routeOption.srcGw, routeOption.destGw);
     return OC_STACK_OK;
 }
 
 OCStackResult RMHandleRequest(CARequestInfo_t *message, const CAEndpoint_t *sender,
-                              bool *selfDestination)
+                              bool *selfDestination, bool *isEmptyMsg)
 {
     if (!g_isRMInitialized)
     {
-        OC_LOG(ERROR, TAG, "RM not initialized");
+        OIC_LOG(ERROR, TAG, "RM not initialized");
         *selfDestination = true;
         return OC_STACK_OK;
     }
-    OCStackResult res = RMHandlePacket(true, message, sender, selfDestination);
+    OCStackResult res = RMHandlePacket(true, message, sender, selfDestination, isEmptyMsg);
     return res;
 }
 
@@ -1190,10 +1254,10 @@ OCStackResult RMHandleResponse(CAResponseInfo_t *message, const CAEndpoint_t *se
 {
     if (!g_isRMInitialized)
     {
-        OC_LOG(ERROR, TAG, "RM not initialized");
+        OIC_LOG(ERROR, TAG, "RM not initialized");
         *selfDestination = true;
         return OC_STACK_OK;
     }
-    OCStackResult res = RMHandlePacket(false, message, sender, selfDestination);
+    OCStackResult res = RMHandlePacket(false, message, sender, selfDestination, NULL);
     return res;
 }
index 86c53c9..e0172fb 100644 (file)
@@ -31,7 +31,7 @@
 /**
  * Logging tag for module name.
  */
-#define TAG "RM_INTERFACE"
+#define TAG "OIC_RM_INTERFACE"
 
 /**
  * Name of resource type.
@@ -83,14 +83,14 @@ OCConnectivityType RMGetConnectivityType(OCTransportAdapter adapter)
         case OC_DEFAULT_ADAPTER:
             break;
         default:
-            OC_LOG(DEBUG, TAG, "Default option will be selected");
+            OIC_LOG(DEBUG, TAG, "Default option will be selected");
     }
     return CT_DEFAULT;
 }
 
 OCStackResult RMInitGatewayResource()
 {
-    OC_LOG(DEBUG, TAG, "RMInitGatewayResource IN");
+    OIC_LOG(DEBUG, TAG, "RMInitGatewayResource IN");
 
     // Create a Gateway resource
     OCStackResult result = OCCreateResource(&g_gateWayHandle,
@@ -103,16 +103,16 @@ OCStackResult RMInitGatewayResource()
 
     if (OC_STACK_OK != result)
     {
-        OC_LOG_V(ERROR, TAG, "Create resource for gateway failed[%d]", result);
+        OIC_LOG_V(ERROR, TAG, "Create resource for gateway failed[%d]", result);
     }
 
-    OC_LOG(DEBUG, TAG, "RMInitGatewayResource OUT");
+    OIC_LOG(DEBUG, TAG, "RMInitGatewayResource OUT");
     return result;
 }
 
 OCStackResult RMDiscoverGatewayResource()
 {
-    OC_LOG(DEBUG, TAG, "RMDiscoverGatewayResource IN");
+    OIC_LOG(DEBUG, TAG, "RMDiscoverGatewayResource IN");
     OCCallbackData discoverData = {.cb = RMDiscoverGatewayCallback};
     OCStackResult result = OC_STACK_OK;
 
@@ -127,19 +127,19 @@ OCStackResult RMDiscoverGatewayResource()
                               CT_ADAPTER_IP, OC_LOW_QOS, &discoverData, NULL, 0);
         usleep(100000);
     }
-    OC_LOG(DEBUG, TAG, "RMDiscoverGatewayResource OUT");
+    OIC_LOG(DEBUG, TAG, "RMDiscoverGatewayResource OUT");
     return result;
 }
 
 OCStackApplicationResult RMDiscoverGatewayCallback(void* ctx, OCDoHandle handle,
                                                    OCClientResponse * clientResponse)
 {
-    OC_LOG(DEBUG, TAG, "RMDiscoverGatewayCallback IN");
+    OIC_LOG(DEBUG, TAG, "RMDiscoverGatewayCallback IN");
     (void)ctx;
     (void)handle;
     if (NULL == clientResponse)
     {
-        OC_LOG(DEBUG, TAG, "clientResponse is NULL");
+        OIC_LOG(DEBUG, TAG, "clientResponse is NULL");
         return OC_STACK_KEEP_TRANSACTION;
     }
 
@@ -147,7 +147,7 @@ OCStackApplicationResult RMDiscoverGatewayCallback(void* ctx, OCDoHandle handle,
                                                    (OCRepPayload *)clientResponse->payload);
     if (OC_STACK_OK != result)
     {
-        OC_LOG_V(ERROR, TAG, "RMHandleResponsePayload Failed[%d]", result);
+        OIC_LOG_V(ERROR, TAG, "RMHandleResponsePayload Failed[%d]", result);
     }
 
     OCRepPayload *payload = NULL;
@@ -155,21 +155,21 @@ OCStackApplicationResult RMDiscoverGatewayCallback(void* ctx, OCDoHandle handle,
     result= RMGetGatewayPayload(&payload);
     if (OC_STACK_OK != result)
     {
-        OC_LOG_V(ERROR, TAG, "RMGetGatewayPayload Failed[%d]", result);
+        OIC_LOG_V(ERROR, TAG, "RMGetGatewayPayload Failed[%d]", result);
     }
 
     RMSendObserveRequest(&(clientResponse->devAddr), payload);
 
-    OC_LOG(DEBUG, TAG, "RMDiscoverGatewayCallback OUT");
+    OIC_LOG(DEBUG, TAG, "RMDiscoverGatewayCallback OUT");
     return OC_STACK_KEEP_TRANSACTION;
 }
 
 OCStackResult RMSendObserveRequest(const OCDevAddr *devAddr, OCRepPayload *payload)
 {
-    OC_LOG(DEBUG, TAG, "RMSendObserveRequest IN");
-    OC_LOG_V(DEBUG, TAG, "Destination address is %s:%d", devAddr->addr, devAddr->port);
+    OIC_LOG(DEBUG, TAG, "RMSendObserveRequest IN");
+    OIC_LOG_V(DEBUG, TAG, "Destination address is %s:%d", devAddr->addr, devAddr->port);
     OCCallbackData observeData = {.cb = RMObserveRequestCallback};
-    OC_LOG(DEBUG, TAG, "RMSendObserveRequest OUT");
+    OIC_LOG(DEBUG, TAG, "RMSendObserveRequest OUT");
 
     return OCDoResource(NULL, OC_REST_OBSERVE, GW_RESOURCE_URI, devAddr, (OCPayload *)payload,
                         RMGetConnectivityType(devAddr->adapter), OC_HIGH_QOS,
@@ -178,12 +178,12 @@ OCStackResult RMSendObserveRequest(const OCDevAddr *devAddr, OCRepPayload *paylo
 
 OCStackResult RMSendDeleteRequest(const OCDevAddr *devAddr, OCRepPayload *payload)
 {
-    OC_LOG(DEBUG, TAG, "RMSendDeleteRequest IN");
+    OIC_LOG(DEBUG, TAG, "RMSendDeleteRequest IN");
     RM_NULL_CHECK_WITH_RET(payload, TAG, "payload");
-    OC_LOG_V(DEBUG, TAG, "Destination address is %s:%d", devAddr->addr, devAddr->port);
+    OIC_LOG_V(DEBUG, TAG, "Destination address is %s:%d", devAddr->addr, devAddr->port);
 
     OCCallbackData deleteCb = {.cb = RMDiscoverGatewayCallback};
-    OC_LOG(DEBUG, TAG, "RMSendDeleteRequest OUT");
+    OIC_LOG(DEBUG, TAG, "RMSendDeleteRequest OUT");
     return OCDoResource(NULL, OC_REST_DELETE, GW_RESOURCE_URI, devAddr, (OCPayload *)payload,
                     RMGetConnectivityType(devAddr->adapter), OC_LOW_QOS,
                     &deleteCb, NULL, 0);
@@ -192,14 +192,14 @@ OCStackResult RMSendDeleteRequest(const OCDevAddr *devAddr, OCRepPayload *payloa
 OCStackResult RMSendResponse(const OCServerRequest *request, const OCResource *resource,
                              const OCRepPayload *payload)
 {
-    OC_LOG(DEBUG, TAG, "RMSendResponse IN");
+    OIC_LOG(DEBUG, TAG, "RMSendResponse IN");
     OCEntityHandlerResponse response = {.ehResult = OC_EH_OK,
                                         .payload = (OCPayload *)payload,
                                         .persistentBufferFlag = 0,
                                         .requestHandle = (OCRequestHandle) request,
                                         .resourceHandle = (OCResourceHandle) resource
                                         };
-    OC_LOG(DEBUG, TAG, "RMSendResponse OUT");
+    OIC_LOG(DEBUG, TAG, "RMSendResponse OUT");
 
     return OCDoResponse(&response);
 }
@@ -207,31 +207,31 @@ OCStackResult RMSendResponse(const OCServerRequest *request, const OCResource *r
 OCStackResult RMSendNotificationForListofObservers(OCObservationId *obsId, uint8_t obsLen,
                                                    const OCRepPayload *payload)
 {
-    OC_LOG(DEBUG, TAG, "RMSendNotificationForListofObservers IN");
+    OIC_LOG(DEBUG, TAG, "RMSendNotificationForListofObservers IN");
     RM_NULL_CHECK_WITH_RET(obsId, TAG, "obsId");
     RM_NULL_CHECK_WITH_RET(payload, TAG, "payload");
     OCStackResult result = OCNotifyListOfObservers(g_gateWayHandle, obsId, obsLen,
                                                    payload, OC_LOW_QOS);
-    OC_LOG_V(DEBUG, TAG, "Result is %d", result);
-    OC_LOG(DEBUG, TAG, "RMSendNotificationForListofObservers OUT");
+    OIC_LOG_V(DEBUG, TAG, "Result is %d", result);
+    OIC_LOG(DEBUG, TAG, "RMSendNotificationForListofObservers OUT");
     return result;
 }
 
 OCStackApplicationResult RMObserveRequestCallback(void* ctx, OCDoHandle handle,
                                                   OCClientResponse *clientResponse)
 {
-    OC_LOG(DEBUG, TAG, "RMObserveRequestCallback IN");
+    OIC_LOG(DEBUG, TAG, "RMObserveRequestCallback IN");
     (void)ctx;
     (void)handle;
     if (NULL == clientResponse)
     {
-        OC_LOG(DEBUG, TAG, "clientResponse is NULL");
+        OIC_LOG(DEBUG, TAG, "clientResponse is NULL");
         return OC_STACK_KEEP_TRANSACTION;
     }
 
     if (OC_STACK_COMM_ERROR == clientResponse->result)
     {
-        OC_LOG(DEBUG, TAG, "Received TIMEOUT ERROR");
+        OIC_LOG(DEBUG, TAG, "Received TIMEOUT ERROR");
         return OC_STACK_KEEP_TRANSACTION;
     }
 
@@ -239,16 +239,16 @@ OCStackApplicationResult RMObserveRequestCallback(void* ctx, OCDoHandle handle,
                                                    (OCRepPayload *)clientResponse->payload);
     if (OC_STACK_OK != result)
     {
-        OC_LOG_V(ERROR, TAG, "RMHandleResponsePayload Failed[%d]", result);
+        OIC_LOG_V(ERROR, TAG, "RMHandleResponsePayload Failed[%d]", result);
     }
 
-    OC_LOG(DEBUG, TAG, "RMObserveRequestCallback OUT");
+    OIC_LOG(DEBUG, TAG, "RMObserveRequestCallback OUT");
     return OC_STACK_KEEP_TRANSACTION;
 }
 
 OCStackResult RMAddObserverToStack(const OCServerRequest *request, OCObservationId *obsID)
 {
-    OC_LOG(DEBUG, TAG, "RMAddObserverToStack IN");
+    OIC_LOG(DEBUG, TAG, "RMAddObserverToStack IN");
     RM_NULL_CHECK_WITH_RET(request, TAG, "request");
     RM_NULL_CHECK_WITH_RET(obsID, TAG, "obsID");
 
@@ -259,17 +259,17 @@ OCStackResult RMAddObserverToStack(const OCServerRequest *request, OCObservation
     }
     if (OC_STACK_OK != result)
     {
-        OC_LOG_V(DEBUG, TAG, "GenerateObserverId failed[%d]", result);
+        OIC_LOG_V(DEBUG, TAG, "GenerateObserverId failed[%d]", result);
         return result;
     }
 
-    OC_LOG_V(DEBUG, TAG, "Observer ID is %d", *obsID);
+    OIC_LOG_V(DEBUG, TAG, "Observer ID is %d", *obsID);
     // Add the observer
     result = AddObserver((const char*)(request->resourceUrl),
                 (const char *)(request->query),
                 *obsID, request->requestToken, request->tokenLength,
                 (OCResource *)g_gateWayHandle, request->qos, OC_FORMAT_CBOR,
                 &request->devAddr);
-    OC_LOG(DEBUG, TAG, "RMAddObserverToStack OUT");
+    OIC_LOG(DEBUG, TAG, "RMAddObserverToStack OUT");
     return result;
 }
index 323b3aa..7ee337c 100644 (file)
@@ -32,7 +32,7 @@
 /**
  * Logging tag for module name.
  */
-#define TAG "RPM"
+#define TAG "OIC_RM_PARSER"
 
 /**
  * Table key to parser Payload Table.
@@ -66,13 +66,13 @@ static const char UPDATE_SEQ_NUM[] = "updateseqnum";
 
 OCStackResult RMPConstructGatewayPayload(uint32_t gatewayId, OCRepPayload **payload)
 {
-    OC_LOG(DEBUG, TAG, "RMPConstructGatewayPayload IN");
+    OIC_LOG(DEBUG, TAG, "RMPConstructGatewayPayload IN");
     RM_NULL_CHECK_WITH_RET(payload, TAG, "payload");
 
     *payload = OCRepPayloadCreate();
     if(!*payload)
     {
-        OC_LOG(ERROR, TAG, "Failed to allocate Payload");
+        OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
         return OC_STACK_ERROR;
     }
 
@@ -80,7 +80,7 @@ OCStackResult RMPConstructGatewayPayload(uint32_t gatewayId, OCRepPayload **payl
     OCRepPayloadSetPropInt(*payload, GATEWAY, gatewayId);
     OCRepPayloadSetPropInt(*payload, LENGTH_PROP, 0);
 
-    OC_LOG(DEBUG, TAG, "RMPConstructGatewayPayload OUT");
+    OIC_LOG(DEBUG, TAG, "RMPConstructGatewayPayload OUT");
 
     return OC_STACK_OK;
 }
@@ -89,13 +89,13 @@ OCStackResult RMPConstructObserveResPayload(uint32_t gatewayId, uint32_t seqNum,
                                             const u_linklist_t *routingtable, bool isUpdateSeqNeeded,
                                             OCRepPayload **payload)
 {
-    OC_LOG(DEBUG, TAG, "RMPConstructObserveResPayload IN");
+    OIC_LOG(DEBUG, TAG, "RMPConstructObserveResPayload IN");
     RM_NULL_CHECK_WITH_RET(payload, TAG, "payload");
 
     *payload =  (OCRepPayload *)OCRepPayloadCreate();
     if(!*payload)
     {
-        OC_LOG(ERROR, TAG, "Failed to allocate Payload");
+        OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
         return OC_STACK_ERROR;
     }
 
@@ -106,7 +106,7 @@ OCStackResult RMPConstructObserveResPayload(uint32_t gatewayId, uint32_t seqNum,
     if (NULL == routingtable)
     {
         OCRepPayloadSetPropInt(*payload, LENGTH_PROP, 0);
-        OC_LOG(DEBUG, TAG, "Routing Table NULL for ObserveRes Payload");
+        OIC_LOG(DEBUG, TAG, "Routing Table NULL for ObserveRes Payload");
         return OC_STACK_OK;
     }
 
@@ -126,7 +126,7 @@ OCStackResult RMPConstructObserveResPayload(uint32_t gatewayId, uint32_t seqNum,
         OCRepPayload *add = OCRepPayloadCreate();
         if(!add)
         {
-            OC_LOG(ERROR, TAG, "Failed to allocate Payload");
+            OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
             return OC_STACK_ERROR;
         }
 
@@ -144,12 +144,12 @@ OCStackResult RMPConstructObserveResPayload(uint32_t gatewayId, uint32_t seqNum,
         bool res = OCRepPayloadSetPropObjectArray(*payload, TABLE, arrayPayload, dimensions);
         if (!res)
         {
-            OC_LOG(ERROR, TAG, "Failed to Construct Observer response Payload");
+            OIC_LOG(ERROR, TAG, "Failed to Construct Observer response Payload");
             return OC_STACK_ERROR;
         }
     }
 
-    OC_LOG(DEBUG, TAG, "RMPConstructObserveResPayload OUT");
+    OIC_LOG(DEBUG, TAG, "RMPConstructObserveResPayload OUT");
     return OC_STACK_OK;
 }
 
@@ -157,7 +157,7 @@ OCStackResult RMPConstructRemovalPayload(uint32_t gatewayId, uint32_t seqNum,
                                          const u_linklist_t *removedGateways, bool isUpdateSeqNeeded,
                                          OCRepPayload **removedPayload)
 {
-    OC_LOG(DEBUG, TAG, "RMPConstructRemovalPayload IN");
+    OIC_LOG(DEBUG, TAG, "RMPConstructRemovalPayload IN");
     RM_NULL_CHECK_WITH_RET(removedGateways, TAG, "removedGateways");
     RM_NULL_CHECK_WITH_RET(removedPayload, TAG, "removedPayload");
 
@@ -167,7 +167,7 @@ OCStackResult RMPConstructRemovalPayload(uint32_t gatewayId, uint32_t seqNum,
     *removedPayload =  OCRepPayloadCreate();
     if(!*removedPayload)
     {
-        OC_LOG(ERROR, TAG, "Failed to allocate Payload");
+        OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
         return OC_STACK_ERROR;
     }
 
@@ -193,12 +193,12 @@ OCStackResult RMPConstructRemovalPayload(uint32_t gatewayId, uint32_t seqNum,
         OCRepPayload *add = OCRepPayloadCreate();
         if(!add)
         {
-            OC_LOG(ERROR, TAG, "Failed to allocate Payload");
+            OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
             return OC_STACK_ERROR;
         }
 
         add->base.type = PAYLOAD_TYPE_REPRESENTATION;
-        OC_LOG_V(DEBUG, TAG, "Removing the gateway entry: %u", entry->destination->gatewayId);
+        OIC_LOG_V(DEBUG, TAG, "Removing the gateway entry: %u", entry->destination->gatewayId);
         OCRepPayloadSetPropInt(add, GATEWAY, entry->destination->gatewayId);
         OCRepPayloadSetPropInt(add, ROUTE_COST, 0);
         arrayPayload[i] = add;
@@ -210,11 +210,11 @@ OCStackResult RMPConstructRemovalPayload(uint32_t gatewayId, uint32_t seqNum,
     bool res = OCRepPayloadSetPropObjectArray(*removedPayload, TABLE, arrayPayload, dimensions);
     if (!res)
     {
-        OC_LOG(ERROR, TAG, "Failed to Construct Removal Payload");
+        OIC_LOG(ERROR, TAG, "Failed to Construct Removal Payload");
         return OC_STACK_ERROR;
     }
 
-    OC_LOG(DEBUG, TAG, "RMPConstructRemovalPayload OUT");
+    OIC_LOG(DEBUG, TAG, "RMPConstructRemovalPayload OUT");
     return OC_STACK_OK;
 }
 
@@ -227,7 +227,7 @@ OCStackResult RMPParseRequestPayload(const uint8_t* payload, size_t payloadSize,
     OCStackResult res = RMPParseResponsePayload(repPayload, gatewayId, NULL, NULL, NULL);
     if (OC_STACK_OK != res)
     {
-        OC_LOG(DEBUG, TAG, "ParseResponsePayload failed");
+        OIC_LOG(DEBUG, TAG, "ParseResponsePayload failed");
     }
 
     return res;
@@ -237,7 +237,7 @@ OCStackResult RMPParseResponsePayload(const OCRepPayload *payload, uint32_t *gat
                                       uint32_t *seqNum, u_linklist_t **gatewayTable,
                                       bool *isUpdateSeqNeeded)
 {
-    OC_LOG(DEBUG, TAG, "RMPParsePayload IN");
+    OIC_LOG(DEBUG, TAG, "RMPParsePayload IN");
     RM_NULL_CHECK_WITH_RET(payload, TAG, "payload");
     RM_NULL_CHECK_WITH_RET(gatewayId, TAG, "gatewayId");
 
@@ -268,13 +268,13 @@ OCStackResult RMPParseResponsePayload(const OCRepPayload *payload, uint32_t *gat
     int len = length;
     if (0 == len)
     {
-        OC_LOG(DEBUG, TAG, "Parsed Gateway Payload");
+        OIC_LOG(DEBUG, TAG, "Parsed Gateway Payload");
         return OC_STACK_OK;
     }
 
     if (NULL == gatewayTable)
     {
-        OC_LOG(DEBUG, TAG, "gatewayTable is NULL");
+        OIC_LOG(DEBUG, TAG, "gatewayTable is NULL");
         return OC_STACK_OK;
     }
 
@@ -285,14 +285,14 @@ OCStackResult RMPParseResponsePayload(const OCRepPayload *payload, uint32_t *gat
 
     if (NULL == *responsePayload)
     {
-        OC_LOG(DEBUG, TAG, "RMPParsePayload OUT");
+        OIC_LOG(DEBUG, TAG, "RMPParsePayload OUT");
         return OC_STACK_OK;
     }
 
     *gatewayTable = u_linklist_create();
     if (NULL == *gatewayTable)
     {
-        OC_LOG(DEBUG, TAG, "Gateway table create failed");
+        OIC_LOG(DEBUG, TAG, "Gateway table create failed");
         return OC_STACK_ERROR;
     }
 
@@ -302,21 +302,21 @@ OCStackResult RMPParseResponsePayload(const OCRepPayload *payload, uint32_t *gat
 
         if (NULL == entry)
         {
-            OC_LOG(DEBUG, TAG, "RTMGatewayEntry_t Calloc failed");
+            OIC_LOG(DEBUG, TAG, "RTMGatewayEntry_t Calloc failed");
             return OC_STACK_ERROR;
         }
         // Filling new Entry
         entry->destination = (RTMGatewayId_t*)OICCalloc(1, sizeof(RTMGatewayId_t));
         if (NULL == entry->destination)
         {
-            OC_LOG(DEBUG, TAG, "Destination Calloc failed");
+            OIC_LOG(DEBUG, TAG, "Destination Calloc failed");
             OICFree(entry);
             return OC_STACK_ERROR;
         }
         entry->nextHop = (RTMGatewayId_t*)OICCalloc(1, sizeof(RTMGatewayId_t));
         if (NULL == entry->nextHop)
         {
-            OC_LOG(DEBUG, TAG, "nextHop Calloc failed");
+            OIC_LOG(DEBUG, TAG, "nextHop Calloc failed");
             OICFree(entry->destination);
             OICFree(entry);
             return OC_STACK_ERROR;
@@ -333,14 +333,14 @@ OCStackResult RMPParseResponsePayload(const OCRepPayload *payload, uint32_t *gat
         entry->routeCost = routeCost;
         u_linklist_add(*gatewayTable, (void *)entry);
     }
-    OC_LOG(DEBUG, TAG, "RMPParsePayload OUT");
+    OIC_LOG(DEBUG, TAG, "RMPParsePayload OUT");
     return OC_STACK_OK;
 }
 
 void RMPFreePayload(OCRepPayload *payload)
 {
-    OC_LOG(DEBUG, TAG, "RMPFreePayload IN");
+    OIC_LOG(DEBUG, TAG, "RMPFreePayload IN");
     RM_NULL_CHECK_VOID(payload, TAG, "payload");
     OCRepPayloadDestroy(payload);
-    OC_LOG(DEBUG, TAG, "RMPFreePayload OUT");
+    OIC_LOG(DEBUG, TAG, "RMPFreePayload OUT");
 }
index b611490..4eb8501 100644 (file)
 /**
  * Logging tag for module name.
  */
-#define TAG "RTM"
+#define TAG "OIC_RM_TM"
 
 /**
  * Tag for printing the Routing table.
  */
-#define RM_TAG "RAP"
+#define RM_TAG "OIC_RM_RAP"
 
 
 /**
@@ -46,7 +46,7 @@ static const uint64_t USECS_PER_SEC = 1000000;
 
 OCStackResult RTMInitialize(u_linklist_t **gatewayTable, u_linklist_t **endpointTable)
 {
-    OC_LOG(DEBUG, TAG, "RTMInitialize IN");
+    OIC_LOG(DEBUG, TAG, "RTMInitialize IN");
     RM_NULL_CHECK_WITH_RET(gatewayTable, TAG, "gatewayTable");
     RM_NULL_CHECK_WITH_RET(endpointTable, TAG, "endpointTable");
     if (NULL == *gatewayTable)
@@ -54,7 +54,7 @@ OCStackResult RTMInitialize(u_linklist_t **gatewayTable, u_linklist_t **endpoint
         *gatewayTable = u_linklist_create();
         if (NULL == *gatewayTable)
         {
-            OC_LOG(ERROR, TAG, "Creating Routing Table failed");
+            OIC_LOG(ERROR, TAG, "Creating Routing Table failed");
             RTMTerminate(gatewayTable, endpointTable);
             return OC_STACK_ERROR;
         }
@@ -65,12 +65,12 @@ OCStackResult RTMInitialize(u_linklist_t **gatewayTable, u_linklist_t **endpoint
         *endpointTable = u_linklist_create();
         if (NULL == *endpointTable)
         {
-           OC_LOG(ERROR, TAG, "Creating Routing Table failed");
+           OIC_LOG(ERROR, TAG, "Creating Routing Table failed");
             RTMTerminate(gatewayTable, endpointTable);
            return OC_STACK_ERROR;
         }
     }
-    OC_LOG(DEBUG, TAG, "RTMInitialize OUT");
+    OIC_LOG(DEBUG, TAG, "RTMInitialize OUT");
     return OC_STACK_OK;
 }
 
@@ -79,7 +79,7 @@ OCStackResult RTMInitialize(u_linklist_t **gatewayTable, u_linklist_t **endpoint
  */
 OCStackResult RTMFreeGatewayRouteTable(u_linklist_t **gatewayTable)
 {
-    OC_LOG(DEBUG, TAG, "RTMFreeGatewayRouteTable IN");
+    OIC_LOG(DEBUG, TAG, "RTMFreeGatewayRouteTable IN");
     if (NULL == gatewayTable || NULL == *gatewayTable)
     {
         return OC_STACK_OK;
@@ -109,12 +109,12 @@ OCStackResult RTMFreeGatewayRouteTable(u_linklist_t **gatewayTable)
         OCStackResult ret = u_linklist_remove(*gatewayTable, &iterTable);
         if (OC_STACK_OK != ret)
         {
-           OC_LOG(ERROR, TAG, "Deleting Entry from Routing Table failed");
+           OIC_LOG(ERROR, TAG, "Deleting Entry from Routing Table failed");
            return OC_STACK_ERROR;
         }
     }
     u_linklist_free(gatewayTable);
-    OC_LOG(DEBUG, TAG, "RTMFreeGatewayRouteTable OUT");
+    OIC_LOG(DEBUG, TAG, "RTMFreeGatewayRouteTable OUT");
     return OC_STACK_OK;
 }
 
@@ -123,7 +123,7 @@ OCStackResult RTMFreeGatewayRouteTable(u_linklist_t **gatewayTable)
  */
 OCStackResult RTMFreeEndpointRouteTable(u_linklist_t **endpointTable)
 {
-    OC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
     if (NULL == endpointTable || NULL == *endpointTable)
     {
         return OC_STACK_OK;
@@ -142,18 +142,18 @@ OCStackResult RTMFreeEndpointRouteTable(u_linklist_t **endpointTable)
         OCStackResult ret = u_linklist_remove(*endpointTable, &iterTable);
         if (OC_STACK_OK != ret)
         {
-            OC_LOG(ERROR, TAG, "Deleting Entry from Routing Table failed");
+            OIC_LOG(ERROR, TAG, "Deleting Entry from Routing Table failed");
             return OC_STACK_ERROR;
         }
     }
     u_linklist_free(endpointTable);
-    OC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "OUT");
     return OC_STACK_OK;
 }
 
 OCStackResult RTMFreeGatewayIdList(u_linklist_t **gatewayIdTable)
 {
-    OC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
     if (NULL == gatewayIdTable || NULL == *gatewayIdTable)
     {
         return OC_STACK_OK;
@@ -177,7 +177,7 @@ OCStackResult RTMFreeGatewayIdList(u_linklist_t **gatewayIdTable)
             OCStackResult ret = u_linklist_remove(*gatewayIdTable, &iterTable);
             if (OC_STACK_OK != ret)
             {
-               OC_LOG(ERROR, TAG, "Deleting Entry from Routing Table failed");
+               OIC_LOG(ERROR, TAG, "Deleting Entry from Routing Table failed");
                return OC_STACK_ERROR;
             }
         }
@@ -186,12 +186,12 @@ OCStackResult RTMFreeGatewayIdList(u_linklist_t **gatewayIdTable)
             OCStackResult res = u_linklist_remove(*gatewayIdTable, &iterTable);
             if (OC_STACK_OK != res)
             {
-                OC_LOG(ERROR, TAG, "Deleting Entry from Routing Table failed");
+                OIC_LOG(ERROR, TAG, "Deleting Entry from Routing Table failed");
                 return OC_STACK_ERROR;
             }
         }
     }
-    OC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "OUT");
     return OC_STACK_OK;
 }
 
@@ -200,12 +200,12 @@ OCStackResult RTMFreeGatewayIdList(u_linklist_t **gatewayIdTable)
  */
 OCStackResult RTMTerminate(u_linklist_t **gatewayTable, u_linklist_t **endpointTable)
 {
-    OC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
 
     OCStackResult ret = RTMFreeGatewayRouteTable(gatewayTable);
     if (OC_STACK_OK != ret)
     {
-        OC_LOG(ERROR, TAG, "Deleting Gateway Routing Table failed");
+        OIC_LOG(ERROR, TAG, "Deleting Gateway Routing Table failed");
     }
     if (NULL != *gatewayTable)
     {
@@ -215,13 +215,13 @@ OCStackResult RTMTerminate(u_linklist_t **gatewayTable, u_linklist_t **endpointT
     ret = RTMFreeEndpointRouteTable(endpointTable);
     if (OC_STACK_OK != ret)
     {
-        OC_LOG(ERROR, TAG, "Deleting Endpoint Routing Table failed");
+        OIC_LOG(ERROR, TAG, "Deleting Endpoint Routing Table failed");
     }
     if (NULL != *endpointTable)
     {
         *endpointTable = NULL;
     }
-    OC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "OUT");
     return OC_STACK_OK;
 }
 
@@ -235,27 +235,27 @@ OCStackResult RTMTerminate(u_linklist_t **gatewayTable, u_linklist_t **endpointT
 OCStackResult RTMAddGatewayEntry(uint32_t gatewayId, uint32_t nextHop, uint32_t routeCost,
                                  const RTMDestIntfInfo_t *destInterfaces, u_linklist_t **gatewayTable)
 {
-    OC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
     RM_NULL_CHECK_WITH_RET(gatewayTable, TAG, "gatewayTable");
     if (NULL == *gatewayTable)
     {
         *gatewayTable = u_linklist_create();
         if (NULL == *gatewayTable)
         {
-            OC_LOG(ERROR, TAG, "u_linklist_create failed");
+            OIC_LOG(ERROR, TAG, "u_linklist_create failed");
             return OC_STACK_NO_MEMORY;
         }
     }
 
     if (1 == routeCost && 0 != nextHop)
     {
-        OC_LOG(ERROR, TAG, "Adding Gateway Failed as Next Hop should be 0 for route cost 1");
+        OIC_LOG(ERROR, TAG, "Adding Gateway Failed as Next Hop should be 0 for route cost 1");
         return OC_STACK_ERROR;
     }
 
     if (0 == routeCost)
     {
-        OC_LOG(ERROR, TAG, "Adding Gateway Failed as Route cost shouldnot be less than 1");
+        OIC_LOG(ERROR, TAG, "Adding Gateway Failed as Route cost shouldnot be less than 1");
         return OC_STACK_ERROR;
     }
 
@@ -297,7 +297,7 @@ OCStackResult RTMAddGatewayEntry(uint32_t gatewayId, uint32_t nextHop, uint32_t
 
     if (1 < routeCost && NULL == gatewayNodeMap)
     {
-        OC_LOG(ERROR, TAG, "Adding Gateway Failed as Next Hop is invalid");
+        OIC_LOG(ERROR, TAG, "Adding Gateway Failed as Next Hop is invalid");
         return OC_STACK_ERROR;
     }
 
@@ -310,14 +310,14 @@ OCStackResult RTMAddGatewayEntry(uint32_t gatewayId, uint32_t nextHop, uint32_t
         {
             if (NULL == destInterfaces)
             {
-                OC_LOG(ERROR, TAG, "Not Adding Gateway destInterfaces is NULL");
+                OIC_LOG(ERROR, TAG, "Not Adding Gateway destInterfaces is NULL");
                 return OC_STACK_ERROR;
             }
             OCStackResult update = RTMUpdateDestinationIntfAdr(gatewayId, *destInterfaces, true,
                                                                gatewayTable);
             if (OC_STACK_OK != update)
             {
-                OC_LOG(ERROR, TAG, "RTMUpdateDestinationIntfAdr failed");
+                OIC_LOG(ERROR, TAG, "RTMUpdateDestinationIntfAdr failed");
             }
             return update;
         }
@@ -326,7 +326,7 @@ OCStackResult RTMAddGatewayEntry(uint32_t gatewayId, uint32_t nextHop, uint32_t
             if (entry->routeCost == routeCost && NULL != entry->nextHop &&
                 (nextHop == entry->nextHop->gatewayId))
             {
-                OC_LOG(ERROR, TAG, "Not Adding Gateway As it is Duplicate request");
+                OIC_LOG(ERROR, TAG, "Not Adding Gateway As it is Duplicate request");
                 return OC_STACK_DUPLICATE_REQUEST;
             }
 
@@ -342,12 +342,12 @@ OCStackResult RTMAddGatewayEntry(uint32_t gatewayId, uint32_t nextHop, uint32_t
             {
                 entry->routeCost = 1;
                 // Entry can't be updated if Next hop is not same as existing Destinations of Table.
-                OC_LOG(DEBUG, TAG, "Updating the gateway");
+                OIC_LOG(DEBUG, TAG, "Updating the gateway");
                 entry->nextHop = NULL;
                 entry->destination->destIntfAddr = u_arraylist_create();
                 if (NULL == entry->destination->destIntfAddr)
                 {
-                    OC_LOG(ERROR, TAG, "Failed to create array list");
+                    OIC_LOG(ERROR, TAG, "Failed to create array list");
                     return OC_STACK_ERROR;
                 }
 
@@ -355,7 +355,7 @@ OCStackResult RTMAddGatewayEntry(uint32_t gatewayId, uint32_t nextHop, uint32_t
                     (RTMDestIntfInfo_t *) OICCalloc(1, sizeof(RTMDestIntfInfo_t));
                 if (NULL == destAdr)
                 {
-                    OC_LOG(ERROR, TAG, "Failed to Calloc destAdr");
+                    OIC_LOG(ERROR, TAG, "Failed to Calloc destAdr");
                     return OC_STACK_ERROR;
                 }
 
@@ -366,21 +366,21 @@ OCStackResult RTMAddGatewayEntry(uint32_t gatewayId, uint32_t nextHop, uint32_t
                     u_arraylist_add(entry->destination->destIntfAddr, (void *)destAdr);
                 if (!result)
                 {
-                    OC_LOG(ERROR, TAG, "Adding node to head failed");
+                    OIC_LOG(ERROR, TAG, "Adding node to head failed");
                     OICFree(destAdr);
                     return OC_STACK_ERROR;
                 }
             }
             else
             {
-                OC_LOG(ERROR, TAG, "Adding Gateway Failed as Next hop is invalid");
+                OIC_LOG(ERROR, TAG, "Adding Gateway Failed as Next hop is invalid");
                 return OC_STACK_ERROR;
             }
 
         }
         else if (NULL != entry  && entry->routeCost < routeCost)
         {
-            OC_LOG(ERROR, TAG, "Adding Gateway Failed as Route cost is more than old");
+            OIC_LOG(ERROR, TAG, "Adding Gateway Failed as Route cost is more than old");
             return OC_STACK_ERROR;
         }
 
@@ -390,14 +390,14 @@ OCStackResult RTMAddGatewayEntry(uint32_t gatewayId, uint32_t nextHop, uint32_t
             OCStackResult res = u_linklist_remove(*gatewayTable, &destNode);
             if (OC_STACK_OK != res)
             {
-                OC_LOG(ERROR, TAG, "Removing node failed");
+                OIC_LOG(ERROR, TAG, "Removing node failed");
             }
             else
             {
                 res = u_linklist_add_head(*gatewayTable, (void *)entry);
                 if (OC_STACK_OK != res)
                 {
-                    OC_LOG(ERROR, TAG, "Adding node to head failed");
+                    OIC_LOG(ERROR, TAG, "Adding node to head failed");
                 }
             }
         }
@@ -408,14 +408,14 @@ OCStackResult RTMAddGatewayEntry(uint32_t gatewayId, uint32_t nextHop, uint32_t
         RTMGatewayEntry_t *hopEntry = (RTMGatewayEntry_t *)OICCalloc(1, sizeof(RTMGatewayEntry_t));
         if (NULL == hopEntry)
         {
-            OC_LOG(ERROR, TAG, "Calloc failed for hop entry");
+            OIC_LOG(ERROR, TAG, "Calloc failed for hop entry");
             return OC_STACK_ERROR;
         }
 
         hopEntry->destination = (RTMGatewayId_t*)OICCalloc(1, sizeof(RTMGatewayId_t));
         if (NULL == hopEntry->destination)
         {
-            OC_LOG(ERROR, TAG, "Calloc failed for hop entry destination");
+            OIC_LOG(ERROR, TAG, "Calloc failed for hop entry destination");
             OICFree(hopEntry);
             return OC_STACK_ERROR;
         }
@@ -428,7 +428,7 @@ OCStackResult RTMAddGatewayEntry(uint32_t gatewayId, uint32_t nextHop, uint32_t
                 (RTMDestIntfInfo_t *) OICCalloc(1, sizeof(RTMDestIntfInfo_t));
             if (NULL == destAdr)
             {
-                OC_LOG(ERROR, TAG, "Calloc failed for destAdr");
+                OIC_LOG(ERROR, TAG, "Calloc failed for destAdr");
                 u_arraylist_free(&(hopEntry->destination->destIntfAddr));
                 OICFree(hopEntry->destination);
                 OICFree(hopEntry);
@@ -457,7 +457,7 @@ OCStackResult RTMAddGatewayEntry(uint32_t gatewayId, uint32_t nextHop, uint32_t
         }
         else
         {
-            OC_LOG(ERROR, TAG, "Adding Gateway Failed as Next Hop is invalid");
+            OIC_LOG(ERROR, TAG, "Adding Gateway Failed as Next Hop is invalid");
             while (u_arraylist_length(hopEntry->destination->destIntfAddr) > 0)
             {
                 RTMDestIntfInfo_t *data =
@@ -483,7 +483,7 @@ OCStackResult RTMAddGatewayEntry(uint32_t gatewayId, uint32_t nextHop, uint32_t
 
         if (OC_STACK_OK != ret)
         {
-            OC_LOG(ERROR, TAG, "Adding Gateway Entry to Routing Table failed");
+            OIC_LOG(ERROR, TAG, "Adding Gateway Entry to Routing Table failed");
             while (u_arraylist_length(hopEntry->destination->destIntfAddr) > 0)
             {
                 RTMDestIntfInfo_t *data = u_arraylist_remove(hopEntry->destination->destIntfAddr, 0);
@@ -495,14 +495,14 @@ OCStackResult RTMAddGatewayEntry(uint32_t gatewayId, uint32_t nextHop, uint32_t
             return OC_STACK_ERROR;
         }
     }
-    OC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "OUT");
     return OC_STACK_OK;
 }
 
 OCStackResult RTMAddEndpointEntry(uint16_t *endpointId, const CAEndpoint_t *destAddr,
                                   u_linklist_t **endpointTable)
 {
-    OC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
     RM_NULL_CHECK_WITH_RET(endpointId, TAG, "endpointId");
     RM_NULL_CHECK_WITH_RET(destAddr, TAG, "destAddr");
     RM_NULL_CHECK_WITH_RET(endpointTable, TAG, "endpointTable");
@@ -511,7 +511,7 @@ OCStackResult RTMAddEndpointEntry(uint16_t *endpointId, const CAEndpoint_t *dest
         *endpointTable = u_linklist_create();
         if (NULL == *endpointTable)
         {
-            OC_LOG(ERROR, TAG, "u_linklist_create failed");
+            OIC_LOG(ERROR, TAG, "u_linklist_create failed");
             return OC_STACK_NO_MEMORY;
         }
     }
@@ -529,7 +529,7 @@ OCStackResult RTMAddEndpointEntry(uint16_t *endpointId, const CAEndpoint_t *dest
             && destAddr->port == entry->destIntfAddr.port)
         {
             *endpointId = entry->endpointId;
-            OC_LOG(ERROR, TAG, "Adding failed as Enpoint Entry Already present in Table");
+            OIC_LOG(ERROR, TAG, "Adding failed as Enpoint Entry Already present in Table");
             return OC_STACK_DUPLICATE_REQUEST;
         }
         u_linklist_get_next(&iterTable);
@@ -540,7 +540,7 @@ OCStackResult RTMAddEndpointEntry(uint16_t *endpointId, const CAEndpoint_t *dest
 
     if (NULL == hopEntry)
     {
-       OC_LOG(ERROR, TAG, "Malloc failed for hop entry");
+       OIC_LOG(ERROR, TAG, "Malloc failed for hop entry");
        return OC_STACK_ERROR;
     }
 
@@ -550,17 +550,17 @@ OCStackResult RTMAddEndpointEntry(uint16_t *endpointId, const CAEndpoint_t *dest
     OCStackResult ret = u_linklist_add(*endpointTable, (void *)hopEntry);
     if (OC_STACK_OK != ret)
     {
-       OC_LOG(ERROR, TAG, "Adding Enpoint Entry to Routing Table failed");
+       OIC_LOG(ERROR, TAG, "Adding Enpoint Entry to Routing Table failed");
        OICFree(hopEntry);
        return OC_STACK_ERROR;
     }
-    OC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "OUT");
     return OC_STACK_OK;
 }
 
 OCStackResult RTMAddObserver(uint32_t obsID, CAEndpoint_t devAddr, u_linklist_t **gatewayTable)
 {
-    OC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
     RM_NULL_CHECK_WITH_RET(gatewayTable, TAG, "gatewayTable");
     RM_NULL_CHECK_WITH_RET(*gatewayTable, TAG, "*gatewayTable");
 
@@ -578,29 +578,29 @@ OCStackResult RTMAddObserver(uint32_t obsID, CAEndpoint_t devAddr, u_linklist_t
                 && devAddr.port == destCheck->destIntfAddr.port)
             {
                 destCheck->observerId = obsID;
-                OC_LOG(DEBUG, TAG, "OUT");
+                OIC_LOG(DEBUG, TAG, "OUT");
                 return OC_STACK_OK;
             }
         }
         u_linklist_get_next(&iterTable);
     }
-    OC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "OUT");
     return OC_STACK_ERROR;
 }
 
 bool RTMIsObserverPresent(CAEndpoint_t devAddr, OCObservationId *obsID,
                           const u_linklist_t *gatewayTable)
 {
-    OC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
     if (NULL == obsID)
     {
-        OC_LOG(ERROR, TAG, "obsID is null");
+        OIC_LOG(ERROR, TAG, "obsID is null");
         return false;
     }
 
     if (NULL == gatewayTable)
     {
-        OC_LOG(ERROR, TAG, "gatewayTable is null");
+        OIC_LOG(ERROR, TAG, "gatewayTable is null");
         return false;
     }
 
@@ -611,7 +611,7 @@ bool RTMIsObserverPresent(CAEndpoint_t devAddr, OCObservationId *obsID,
         RTMGatewayEntry_t *entry = u_linklist_get_data(iterTable);
         if (NULL == entry || NULL == entry->destination)
         {
-            OC_LOG(ERROR, TAG, "entry is NULL");
+            OIC_LOG(ERROR, TAG, "entry is NULL");
             return false;
         }
         for (uint32_t i = 0; i < u_arraylist_length(entry->destination->destIntfAddr); i++)
@@ -623,20 +623,20 @@ bool RTMIsObserverPresent(CAEndpoint_t devAddr, OCObservationId *obsID,
                 && devAddr.port == destCheck->destIntfAddr.port && 0 != destCheck->observerId)
             {
                 *obsID = destCheck->observerId;
-                OC_LOG(DEBUG, TAG, "OUT");
+                OIC_LOG(DEBUG, TAG, "OUT");
                 return true;
             }
         }
         u_linklist_get_next(&iterTable);
     }
-    OC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "OUT");
     return false;
 }
 
 OCStackResult RTMRemoveGatewayEntry(uint32_t gatewayId, u_linklist_t **removedGatewayNodes,
                                     u_linklist_t **gatewayTable)
 {
-    OC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
     RM_NULL_CHECK_WITH_RET(gatewayTable, TAG, "gatewayTable");
     RM_NULL_CHECK_WITH_RET(*gatewayTable, TAG, "*gatewayTable");
 
@@ -648,7 +648,7 @@ OCStackResult RTMRemoveGatewayEntry(uint32_t gatewayId, u_linklist_t **removedGa
         *removedGatewayNodes = u_linklist_create();
         if (NULL == *removedGatewayNodes)
         {
-            OC_LOG(ERROR, TAG, "u_linklist_create failed");
+            OIC_LOG(ERROR, TAG, "u_linklist_create failed");
             return OC_STACK_NO_MEMORY;
         }
     }
@@ -666,11 +666,11 @@ OCStackResult RTMRemoveGatewayEntry(uint32_t gatewayId, u_linklist_t **removedGa
         if (gatewayId == entry->destination->gatewayId || (NULL != entry->nextHop &&
             (gatewayId == entry->nextHop->gatewayId)))
         {
-            OC_LOG_V(DEBUG, TAG, "Removing the gateway entry: %u", entry->destination->gatewayId);
+            OIC_LOG_V(DEBUG, TAG, "Removing the gateway entry: %u", entry->destination->gatewayId);
             ret = u_linklist_remove(*gatewayTable, &iterTable);
             if (OC_STACK_OK != ret)
             {
-               OC_LOG(ERROR, TAG, "Deleting Entry from Routing Table failed");
+               OIC_LOG(ERROR, TAG, "Deleting Entry from Routing Table failed");
                return OC_STACK_ERROR;
             }
             else
@@ -683,7 +683,7 @@ OCStackResult RTMRemoveGatewayEntry(uint32_t gatewayId, u_linklist_t **removedGa
             u_linklist_get_next(&iterTable);
         }
     }
-    OC_LOG(DEBUG, TAG, "RTMRemoveGatewayEntry OUT");
+    OIC_LOG(DEBUG, TAG, "RTMRemoveGatewayEntry OUT");
     return OC_STACK_OK;
 }
 
@@ -691,7 +691,7 @@ OCStackResult RTMRemoveGatewayDestEntry(uint32_t gatewayId, uint32_t nextHop,
                                         const RTMDestIntfInfo_t *destInfAdr,
                                         RTMGatewayEntry_t **existEntry, u_linklist_t **gatewayTable)
 {
-    OC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
     RM_NULL_CHECK_WITH_RET(gatewayTable, TAG, "gatewayTable");
     RM_NULL_CHECK_WITH_RET(*gatewayTable, TAG, "*gatewayTable");
     RM_NULL_CHECK_WITH_RET(destInfAdr, TAG, "destInfAdr");
@@ -732,13 +732,13 @@ OCStackResult RTMRemoveGatewayDestEntry(uint32_t gatewayId, uint32_t nextHop,
         // Remove node with given gatewayid and nextHop if not found update exist entry.
         if (NULL != entry->destination && (gatewayId == entry->destination->gatewayId))
         {
-            OC_LOG_V(INFO, TAG, "Remove the gateway ID: %u", entry->destination->gatewayId);
+            OIC_LOG_V(INFO, TAG, "Remove the gateway ID: %u", entry->destination->gatewayId);
             if (NULL != entry->nextHop && nextHop == entry->nextHop->gatewayId)
             {
                 ret = u_linklist_remove(*gatewayTable, &iterTable);
                 if (OC_STACK_OK != ret)
                 {
-                   OC_LOG(ERROR, TAG, "Deleting Entry from Routing Table failed");
+                   OIC_LOG(ERROR, TAG, "Deleting Entry from Routing Table failed");
                    return OC_STACK_ERROR;
                 }
                 OICFree(entry);
@@ -746,19 +746,19 @@ OCStackResult RTMRemoveGatewayDestEntry(uint32_t gatewayId, uint32_t nextHop,
             }
 
             *existEntry = entry;
-            OC_LOG(DEBUG, TAG, "OUT");
+            OIC_LOG(DEBUG, TAG, "OUT");
             return OC_STACK_ERROR;
         }
 
         u_linklist_get_next(&iterTable);
     }
-    OC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "OUT");
     return OC_STACK_ERROR;
 }
 
 OCStackResult RTMRemoveEndpointEntry(uint16_t endpointId, u_linklist_t **endpointTable)
 {
-    OC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
     RM_NULL_CHECK_WITH_RET(endpointTable, TAG, "endpointTable");
     RM_NULL_CHECK_WITH_RET(*endpointTable, TAG, "*endpointTable");
 
@@ -772,7 +772,7 @@ OCStackResult RTMRemoveEndpointEntry(uint16_t endpointId, u_linklist_t **endpoin
             OCStackResult ret = u_linklist_remove(*endpointTable, &iterTable);
             if (OC_STACK_OK != ret)
             {
-               OC_LOG(ERROR, TAG, "Deleting Entry from Routing Table failed");
+               OIC_LOG(ERROR, TAG, "Deleting Entry from Routing Table failed");
                return OC_STACK_ERROR;
             }
             OICFree(entry);
@@ -782,52 +782,52 @@ OCStackResult RTMRemoveEndpointEntry(uint16_t endpointId, u_linklist_t **endpoin
             u_linklist_get_next(&iterTable);
         }
     }
-    OC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "OUT");
     return OC_STACK_OK;
 }
 
 OCStackResult RTMRemoveGateways(u_linklist_t **gatewayTable)
 {
-    OC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
 
     if (NULL == gatewayTable || NULL == *gatewayTable)
     {
-        OC_LOG(DEBUG, TAG, "OUT");
+        OIC_LOG(DEBUG, TAG, "OUT");
         return OC_STACK_OK;
     }
 
     OCStackResult ret = RTMFreeGatewayRouteTable(gatewayTable);
     if (OC_STACK_OK != ret)
     {
-        OC_LOG(ERROR, TAG, "Removing Gateways failed");
+        OIC_LOG(ERROR, TAG, "Removing Gateways failed");
         return ret;
     }
-    OC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "OUT");
     return OC_STACK_OK;
 }
 
 OCStackResult RTMRemoveEndpoints(u_linklist_t **endpointTable)
 {
-    OC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
     if (NULL == endpointTable || NULL == *endpointTable)
     {
-        OC_LOG(DEBUG, TAG, "OUT");
+        OIC_LOG(DEBUG, TAG, "OUT");
         return OC_STACK_OK;
     }
 
     OCStackResult ret = RTMFreeEndpointRouteTable(endpointTable);
     if (OC_STACK_OK != ret)
     {
-        OC_LOG(ERROR, TAG, "Freeing Endpoints failed");
+        OIC_LOG(ERROR, TAG, "Freeing Endpoints failed");
         return OC_STACK_ERROR;
     }
-    OC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "OUT");
     return OC_STACK_OK;
 }
 
 void RTMFreeGateway(RTMGatewayId_t *gateway, u_linklist_t **gatewayTable)
 {
-    OC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
     RM_NULL_CHECK_VOID(gateway, TAG, "gateway");
     RM_NULL_CHECK_VOID(gatewayTable, TAG, "gatewayTable");
     RM_NULL_CHECK_VOID(*gatewayTable, TAG, "*gatewayTable");
@@ -838,19 +838,19 @@ void RTMFreeGateway(RTMGatewayId_t *gateway, u_linklist_t **gatewayTable)
     }
     u_arraylist_free(&(gateway->destIntfAddr));
     OICFree(gateway);
-    OC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 void RTMGetNeighbours(u_linklist_t **neighbourNodes, const u_linklist_t *gatewayTable)
 {
-    OC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
     RM_NULL_CHECK_VOID(neighbourNodes, TAG, "neighbourNodes");
     RM_NULL_CHECK_VOID(gatewayTable, TAG, "gatewayTable");
 
     *neighbourNodes = u_linklist_create();
     if (NULL == *neighbourNodes)
     {
-        OC_LOG(ERROR, TAG, "u_linklist_create failed");
+        OIC_LOG(ERROR, TAG, "u_linklist_create failed");
         return;
     }
     u_linklist_iterator_t *iterTable = NULL;
@@ -864,27 +864,27 @@ void RTMGetNeighbours(u_linklist_t **neighbourNodes, const u_linklist_t *gateway
         }
         else if (NULL != entry && 1 < entry->routeCost)
         {
-            OC_LOG(DEBUG, TAG, "OUT");
+            OIC_LOG(DEBUG, TAG, "OUT");
             return;
         }
 
         u_linklist_get_next(&iterTable);
     }
-    OC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 RTMGatewayId_t *RTMGetNextHop(uint32_t gatewayId, const u_linklist_t *gatewayTable)
 {
-    OC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
     if (0 == gatewayId)
     {
-        OC_LOG(ERROR, TAG, "gatewayId is invalid");
+        OIC_LOG(ERROR, TAG, "gatewayId is invalid");
         return NULL;
     }
 
     if (NULL == gatewayTable)
     {
-        OC_LOG(ERROR, TAG, "gatewayTable is null");
+        OIC_LOG(ERROR, TAG, "gatewayTable is null");
         return NULL;
     }
 
@@ -897,24 +897,24 @@ RTMGatewayId_t *RTMGetNextHop(uint32_t gatewayId, const u_linklist_t *gatewayTab
         {
             if (1 == entry->routeCost)
             {
-                OC_LOG(DEBUG, TAG, "OUT");
+                OIC_LOG(DEBUG, TAG, "OUT");
                 return entry->destination;
             }
-            OC_LOG(DEBUG, TAG, "OUT");
+            OIC_LOG(DEBUG, TAG, "OUT");
             return entry->nextHop;
         }
         u_linklist_get_next(&iterTable);
     }
-    OC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "OUT");
     return NULL;
 }
 
 CAEndpoint_t *RTMGetEndpointEntry(uint16_t endpointId, const u_linklist_t *endpointTable)
 {
-    OC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
     if (NULL == endpointTable)
     {
-        OC_LOG(ERROR, TAG, "endpointTable is null");
+        OIC_LOG(ERROR, TAG, "endpointTable is null");
         return NULL;
     }
 
@@ -926,26 +926,26 @@ CAEndpoint_t *RTMGetEndpointEntry(uint16_t endpointId, const u_linklist_t *endpo
         RTMEndpointEntry_t *entry = u_linklist_get_data(iterTable);
         if (NULL != entry && (endpointId == entry->endpointId))
         {
-            OC_LOG(DEBUG, TAG, "OUT");
+            OIC_LOG(DEBUG, TAG, "OUT");
             return &(entry->destIntfAddr);
         }
         u_linklist_get_next(&iterTable);
     }
-    OC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "OUT");
     return NULL;
 }
 
 void RTMGetObserverList(OCObservationId **obsList, uint8_t *obsListLen,
                         const u_linklist_t *gatewayTable)
 {
-    OC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
     RM_NULL_CHECK_VOID(gatewayTable, TAG, "gatewayTable");
     RM_NULL_CHECK_VOID(obsList, TAG, "obsList");
 
     *obsList = (OCObservationId *) OICCalloc(MAX_OBSERVER_LIST_LENGTH, sizeof(OCObservationId));
     if (!(*obsList))
     {
-        OC_LOG(ERROR, TAG, "out of memory");
+        OIC_LOG(ERROR, TAG, "out of memory");
         return;
     }
 
@@ -960,12 +960,12 @@ void RTMGetObserverList(OCObservationId **obsList, uint8_t *obsListLen,
             RTMDestIntfInfo_t *destCheck = u_arraylist_get(entry->destination->destIntfAddr, 0);
             if (NULL == destCheck)
             {
-                OC_LOG(ERROR, TAG, "destCheck is null");
+                OIC_LOG(ERROR, TAG, "destCheck is null");
                 return;
             }
             if (0 != destCheck->observerId)
             {
-                OC_LOG_V(DEBUG, TAG, "Observer ID is %d", destCheck->observerId);
+                OIC_LOG_V(DEBUG, TAG, "Observer ID is %d", destCheck->observerId);
                 *(*obsList + len) = destCheck->observerId;
                 len++;
             }
@@ -979,13 +979,13 @@ void RTMGetObserverList(OCObservationId **obsList, uint8_t *obsListLen,
     }
 
     *obsListLen = len;
-    OC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 OCStackResult RTMUpdateDestinationIntfAdr(uint32_t gatewayId, RTMDestIntfInfo_t destInterfaces,
                                           bool addAdr, u_linklist_t **gatewayTable)
 {
-    OC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
     RM_NULL_CHECK_WITH_RET(gatewayTable, TAG, "gatewayTable");
     RM_NULL_CHECK_WITH_RET(*gatewayTable, TAG, "*gatewayTable");
 
@@ -1005,7 +1005,7 @@ OCStackResult RTMUpdateDestinationIntfAdr(uint32_t gatewayId, RTMDestIntfInfo_t
                         u_arraylist_get(entry->destination->destIntfAddr, i);
                     if (NULL == destCheck)
                     {
-                        OC_LOG(ERROR, TAG, "Destination adr get failed");
+                        OIC_LOG(ERROR, TAG, "Destination adr get failed");
                         continue;
                     }
 
@@ -1015,7 +1015,7 @@ OCStackResult RTMUpdateDestinationIntfAdr(uint32_t gatewayId, RTMDestIntfInfo_t
                     {
                         destCheck->timeElapsed = RTMGetCurrentTime();
                         destCheck->isValid = true;
-                        OC_LOG(ERROR, TAG, "destInterfaces already present");
+                        OIC_LOG(ERROR, TAG, "destInterfaces already present");
                         return OC_STACK_ERROR;
                     }
                 }
@@ -1024,7 +1024,7 @@ OCStackResult RTMUpdateDestinationIntfAdr(uint32_t gatewayId, RTMDestIntfInfo_t
                         (RTMDestIntfInfo_t *) OICCalloc(1, sizeof(RTMDestIntfInfo_t));
                 if (NULL == destAdr)
                 {
-                    OC_LOG(ERROR, TAG, "Calloc destAdr failed");
+                    OIC_LOG(ERROR, TAG, "Calloc destAdr failed");
                     return OC_STACK_ERROR;
                 }
                 *destAdr = destInterfaces;
@@ -1034,11 +1034,11 @@ OCStackResult RTMUpdateDestinationIntfAdr(uint32_t gatewayId, RTMDestIntfInfo_t
                     u_arraylist_add(entry->destination->destIntfAddr, (void *)destAdr);
                 if (!result)
                 {
-                    OC_LOG(ERROR, TAG, "Updating Destinterface address failed");
+                    OIC_LOG(ERROR, TAG, "Updating Destinterface address failed");
                     OICFree(destAdr);
                     return OC_STACK_ERROR;
                 }
-                OC_LOG(DEBUG, TAG, "OUT");
+                OIC_LOG(DEBUG, TAG, "OUT");
                 return OC_STACK_DUPLICATE_REQUEST;
             }
 
@@ -1063,14 +1063,14 @@ OCStackResult RTMUpdateDestinationIntfAdr(uint32_t gatewayId, RTMDestIntfInfo_t
         }
         u_linklist_get_next(&iterTable);
     }
-    OC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "OUT");
     return OC_STACK_OK;
 }
 
 OCStackResult RTMUpdateMcastSeqNumber(uint32_t gatewayId, uint16_t seqNum,
                                       u_linklist_t **gatewayTable)
 {
-    OC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
     RM_NULL_CHECK_WITH_RET(gatewayTable, TAG, "gatewayTable");
     RM_NULL_CHECK_WITH_RET(*gatewayTable, TAG, "*gatewayTable");
 
@@ -1098,7 +1098,7 @@ OCStackResult RTMUpdateMcastSeqNumber(uint32_t gatewayId, uint16_t seqNum,
         }
         u_linklist_get_next(&iterTable);
     }
-    OC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "OUT");
     return OC_STACK_OK;
 }
 
@@ -1130,7 +1130,7 @@ uint64_t RTMGetCurrentTime()
 
 OCStackResult RTMUpdateDestAddrValidity(u_linklist_t **invalidTable, u_linklist_t **gatewayTable)
 {
-    OC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
     RM_NULL_CHECK_WITH_RET(invalidTable, TAG, "invalidTable");
     RM_NULL_CHECK_WITH_RET(gatewayTable, TAG, "gatewayTable");
     RM_NULL_CHECK_WITH_RET(*gatewayTable, TAG, "*gatewayTable");
@@ -1138,7 +1138,7 @@ OCStackResult RTMUpdateDestAddrValidity(u_linklist_t **invalidTable, u_linklist_
     *invalidTable = u_linklist_create();
     if (NULL == *invalidTable)
     {
-        OC_LOG(ERROR, TAG, "u_linklist_create failed");
+        OIC_LOG(ERROR, TAG, "u_linklist_create failed");
         return OC_STACK_NO_MEMORY;
     }
 
@@ -1176,13 +1176,13 @@ OCStackResult RTMUpdateDestAddrValidity(u_linklist_t **invalidTable, u_linklist_
         }
         u_linklist_get_next(&iterTable);
     }
-    OC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "OUT");
     return OC_STACK_OK;
 }
 
 OCStackResult RTMRemoveInvalidGateways(u_linklist_t **invalidTable, u_linklist_t **gatewayTable)
 {
-    OC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
     RM_NULL_CHECK_WITH_RET(invalidTable, TAG, "invalidTable");
     RM_NULL_CHECK_WITH_RET(gatewayTable, TAG, "gatewayTable");
     RM_NULL_CHECK_WITH_RET(*gatewayTable, TAG, "*gatewayTable");
@@ -1190,7 +1190,7 @@ OCStackResult RTMRemoveInvalidGateways(u_linklist_t **invalidTable, u_linklist_t
     *invalidTable = u_linklist_create();
     if (NULL == *invalidTable)
     {
-        OC_LOG(ERROR, TAG, "u_linklist_create failed");
+        OIC_LOG(ERROR, TAG, "u_linklist_create failed");
         return OC_STACK_NO_MEMORY;
     }
 
@@ -1225,7 +1225,7 @@ OCStackResult RTMRemoveInvalidGateways(u_linklist_t **invalidTable, u_linklist_t
                     RTMRemoveGatewayEntry(entry->destination->gatewayId, invalidTable, gatewayTable);
                 if (OC_STACK_OK != res)
                 {
-                    OC_LOG(ERROR, TAG, "Removing Entries failed");
+                    OIC_LOG(ERROR, TAG, "Removing Entries failed");
                     return OC_STACK_ERROR;
                 }
                 u_linklist_get_next(&iterTable);
@@ -1244,7 +1244,7 @@ OCStackResult RTMRemoveInvalidGateways(u_linklist_t **invalidTable, u_linklist_t
             u_linklist_get_next(&iterTable);
         }
     }
-    OC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "OUT");
     return OC_STACK_OK;
 }
 
@@ -1252,7 +1252,7 @@ OCStackResult RTMUpdateEntryParameters(uint32_t gatewayId, uint32_t seqNum,
                                        const RTMDestIntfInfo_t *destAdr, u_linklist_t **gatewayTable,
                                        bool forceUpdate)
 {
-    OC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
     RM_NULL_CHECK_WITH_RET(gatewayTable, TAG, "gatewayTable");
     RM_NULL_CHECK_WITH_RET(*gatewayTable, TAG, "*gatewayTable");
     RM_NULL_CHECK_WITH_RET(destAdr, TAG, "destAdr");
@@ -1295,20 +1295,20 @@ OCStackResult RTMUpdateEntryParameters(uint32_t gatewayId, uint32_t seqNum,
             else
             {
                 entry->seqNum = seqNum;
-                OC_LOG(DEBUG, TAG, "OUT");
+                OIC_LOG(DEBUG, TAG, "OUT");
                 return OC_STACK_OK;
             }
         }
         u_linklist_get_next(&iterTable);
     }
-    OC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "OUT");
     return OC_STACK_OK;
 }
 
 void RTMPrintTable(const u_linklist_t *gatewayTable, const u_linklist_t *endpointTable)
 {
     RM_NULL_CHECK_VOID(gatewayTable, TAG, "gatewayTable");
-    OC_LOG(DEBUG, RM_TAG, "=================Gateway List table============================\n");
+    OIC_LOG(DEBUG, RM_TAG, "=================Gateway List table============================\n");
     u_linklist_iterator_t *iterTable = NULL;
     u_linklist_init_iterator(gatewayTable, &iterTable);
     while (NULL != iterTable)
@@ -1317,20 +1317,20 @@ void RTMPrintTable(const u_linklist_t *gatewayTable, const u_linklist_t *endpoin
             (RTMGatewayEntry_t *) u_linklist_get_data(iterTable);
         if (NULL == hop)
         {
-            OC_LOG(ERROR, RM_TAG, "Printing Table Failed");
+            OIC_LOG(ERROR, RM_TAG, "Printing Table Failed");
             return;
         }
         if (NULL == hop->nextHop || 0 == hop->nextHop->gatewayId)
         {
-            OC_LOG_V(DEBUG, RM_TAG, "\nDestination : %u\nNextHop : (null)\nHopCount : %d",
+            OIC_LOG_V(DEBUG, RM_TAG, "\nDestination : %u\nNextHop : (null)\nHopCount : %d",
                      hop->destination->gatewayId, hop->routeCost);
-            OC_LOG_V(DEBUG, RM_TAG, "\nSequence Number :%u", hop->seqNum);
+            OIC_LOG_V(DEBUG, RM_TAG, "\nSequence Number :%u", hop->seqNum);
         }
         else
         {
-            OC_LOG_V(DEBUG, RM_TAG, "\nDestination : %u\nNextHop : %u\nHopCount : %d",
+            OIC_LOG_V(DEBUG, RM_TAG, "\nDestination : %u\nNextHop : %u\nHopCount : %d",
                      hop->destination->gatewayId, hop->nextHop->gatewayId, hop->routeCost);
-            OC_LOG_V(DEBUG, RM_TAG, "\nSequence Number :%u", hop->seqNum);
+            OIC_LOG_V(DEBUG, RM_TAG, "\nSequence Number :%u", hop->seqNum);
         }
         if (1 == hop->routeCost && NULL != hop->destination &&
             hop->destination->destIntfAddr != NULL)
@@ -1340,17 +1340,17 @@ void RTMPrintTable(const u_linklist_t *gatewayTable, const u_linklist_t *endpoin
                 RTMDestIntfInfo_t *dest = u_arraylist_get(hop->destination->destIntfAddr, i);
                 if (NULL != dest)
                 {
-                    OC_LOG_V(DEBUG, RM_TAG, "\nDestination interface addresses: %s Port : %d Obs ID: %d",
+                    OIC_LOG_V(DEBUG, RM_TAG, "\nDestination interface addresses: %s Port : %d Obs ID: %d",
                              dest->destIntfAddr.addr, dest->destIntfAddr.port, dest->observerId);
-                    OC_LOG_V(DEBUG, RM_TAG, "Validity: %d", dest->isValid);
+                    OIC_LOG_V(DEBUG, RM_TAG, "Validity: %d", dest->isValid);
                 }
             }
         }
-        OC_LOG(DEBUG, RM_TAG, "********************************************\n");
+        OIC_LOG(DEBUG, RM_TAG, "********************************************\n");
         u_linklist_get_next(&iterTable);
     }
 
-    OC_LOG(DEBUG, RM_TAG, "=================Endpoint List table============================\n");
+    OIC_LOG(DEBUG, RM_TAG, "=================Endpoint List table============================\n");
     u_linklist_iterator_t *iterEndpointTable = NULL;
     u_linklist_init_iterator(endpointTable, &iterEndpointTable);
 
@@ -1361,13 +1361,13 @@ void RTMPrintTable(const u_linklist_t *gatewayTable, const u_linklist_t *endpoin
             (RTMEndpointEntry_t *) u_linklist_get_data(iterEndpointTable);
         if (NULL == hop)
         {
-            OC_LOG(ERROR, RM_TAG, "Printing Table Failed");
+            OIC_LOG(ERROR, RM_TAG, "Printing Table Failed");
             return;
         }
-        OC_LOG_V(DEBUG, RM_TAG, "EndpointId : %u\naddr : %s Port : %d",
+        OIC_LOG_V(DEBUG, RM_TAG, "EndpointId : %u\naddr : %s Port : %d",
                   hop->endpointId, hop->destIntfAddr.addr, hop->destIntfAddr.port);
 
-        OC_LOG(DEBUG, RM_TAG, "********************************************\n");
+        OIC_LOG(DEBUG, RM_TAG, "********************************************\n");
         u_linklist_get_next(&iterEndpointTable);
     }
 }
index a0925c2..cabd07c 100644 (file)
 /**
  * Logging tag for module name.
  */
-#define TAG "RM_UTIL"
+#define TAG "OIC_RM_UTIL"
 
 /**
  * Tag for printing the logs of forwarding the packet.
  */
-#define RM_TAG "RAP"
+#define RM_TAG "OIC_RM_RAP"
+
+/**
+ * Default routing option data length is 1 byte with any of the following values.
+ * 00 - source and destination address is not present.
+ * 01 - source and destination address is present with message type as ACK.
+ * 10 - source and destination address is present with message type as RESET.
+ * 11 - source and destination address is present with message type as NORMAL.
+ */
+#define DEFAULT_ROUTE_OPTION_LEN 1
 
 /**
  * Minimum routing option data length is
- * length of src address(1byte) + length of destination address(1byte) + hop count(2bytes)
+ * Msg Type(1 bytes) + length of src address(1byte) + length of destination address(1byte) +
+ * Seq Num(2bytes)
  */
-#define MIN_ROUTE_OPTION_LEN 4
+#define MIN_ROUTE_OPTION_LEN 5
+
+/**
+ * Acknowledge message type is denoted as 01000000
+ */
+#define ACK_MESSAGE_TYPE (1 << 6)
+
+/**
+ * Reset message type is denoted as 10000000
+ */
+#define RST_MESSAGE_TYPE (1 << 7)
+
+/**
+ * Normal message type is denoted as 11000000
+ */
+#define NORMAL_MESSAGE_TYPE (3 << 6)
+
+/**
+ * Stack mode.
+ */
+static OCMode g_rmStackMode = OC_CLIENT;
+
+void RMSetStackMode(OCMode mode)
+{
+    g_rmStackMode = mode;
+}
 
 // destination and source are <GatewayId><ClientId> here, where ClientId is optional.
-OCStackResult RMAddInfo(const char *destination, CAHeaderOption_t **options,
-                        uint8_t *numOptions)
+OCStackResult RMAddInfo(const char *destination, void *message, bool isRequest,
+                        bool *doPost)
 {
-    OC_LOG(DEBUG, TAG, "IN");
-    RM_NULL_CHECK_WITH_RET(options, TAG, "options");
-    RM_NULL_CHECK_WITH_RET(numOptions, TAG, "numOptions");
+    OIC_LOG(DEBUG, TAG, "IN");
+    RM_NULL_CHECK_WITH_RET(message, TAG, "options");
+
+    CAHeaderOption_t **options = NULL;
+    uint8_t *numOptions = NULL;
+
+    if (isRequest)
+    {
+        CARequestInfo_t *requestMsg = message;
+        options = &(requestMsg->info.options);
+        RM_NULL_CHECK_WITH_RET(options, TAG, "options");
+        numOptions = &(requestMsg->info.numOptions);
+        RM_NULL_CHECK_WITH_RET(numOptions, TAG, "numOptions");
+    }
+    else
+    {
+        CAResponseInfo_t *respMsg = message;
+        if ('\0' == destination[0] && (CA_EMPTY == respMsg->result))
+        {
+            OIC_LOG(DEBUG, TAG, "Response is for an Endpoint, No need to add the routing Option");
+            return OC_STACK_OK;
+        }
+        options = &(respMsg->info.options);
+        RM_NULL_CHECK_WITH_RET(options, TAG, "options");
+        numOptions = &(respMsg->info.numOptions);
+        RM_NULL_CHECK_WITH_RET(numOptions, TAG, "numOptions");
+    }
+
 
     CAHeaderOption_t *optionPtr = NULL;
     int8_t index = -1;
@@ -56,17 +116,17 @@ OCStackResult RMAddInfo(const char *destination, CAHeaderOption_t **options,
 
     if (-1 < index)
     {
-        OC_LOG(INFO, TAG, "Route option is present");
+        OIC_LOG(INFO, TAG, "Route option is present");
         optionPtr = *options;
     }
     else
     {
-        OC_LOG(INFO, TAG, "Route option is not present");
+        OIC_LOG(INFO, TAG, "Route option is not present");
         index = *numOptions;
         optionPtr = OICCalloc((*numOptions + 1), sizeof(CAHeaderOption_t));
         if (!optionPtr)
         {
-            OC_LOG(ERROR, TAG, "OICCalloc failed");
+            OIC_LOG(ERROR, TAG, "OICCalloc failed");
             return OC_STACK_NO_MEMORY;
         }
 
@@ -77,15 +137,47 @@ OCStackResult RMAddInfo(const char *destination, CAHeaderOption_t **options,
     RMRouteOption_t routeOption = {.destGw = 0};
     if (*numOptions != index)
     {
-        OC_LOG(INFO, TAG, "Route option is already present");
+        OIC_LOG(INFO, TAG, "Route option is already present");
         res = RMParseRouteOption(&optionPtr[index], &routeOption);
         if (OC_STACK_OK != res)
         {
-            OC_LOG(ERROR, TAG, "RMParseRouteOption failed");
+            OIC_LOG(ERROR, TAG, "RMParseRouteOption failed");
             return OC_STACK_ERROR;
         }
     }
 
+    if (!isRequest)
+    {
+        CAResponseInfo_t *respMsg = message;
+        if (CA_EMPTY == respMsg->result && CA_MSG_ACKNOWLEDGE == respMsg->info.type)
+        {
+            OIC_LOG(DEBUG, TAG, "CA_EMPTY WITH ACKNOWLEDGEMENT");
+            routeOption.msgType = ACK;
+            if (OC_SERVER == g_rmStackMode)
+            {
+                OIC_LOG(DEBUG, TAG, "This is server mode");
+                // Send the Empty message in the response with adding the MSGType in Route option.
+                respMsg->info.type = CA_MSG_NONCONFIRM;
+                respMsg->result = CA_CONTENT;
+            }
+            else
+            {
+                OIC_LOG(DEBUG, TAG, "Send a POST request");
+                if (NULL != doPost)
+                {
+                    *doPost = true;
+                }
+            }
+        }
+        else if (CA_EMPTY == respMsg->result && CA_MSG_RESET == respMsg->info.type)
+        {
+            OIC_LOG(DEBUG, TAG, "CA_EMPTY WITH RESET");
+            routeOption.msgType = RST;
+            respMsg->info.type = CA_MSG_NONCONFIRM;
+            respMsg->result = CA_CONTENT;
+        }
+    }
+
     if(destination)
     {
         memcpy(&(routeOption.destGw), destination, sizeof(routeOption.destGw));
@@ -110,7 +202,7 @@ OCStackResult RMAddInfo(const char *destination, CAHeaderOption_t **options,
     res = RMCreateRouteOption(&routeOption, optionPtr + index);
     if (OC_STACK_OK != res)
     {
-        OC_LOG(ERROR, TAG, "Creation of routing option failed");
+        OIC_LOG(ERROR, TAG, "Creation of routing option failed");
         OICFree(optionPtr);
         return res;
     }
@@ -122,14 +214,14 @@ OCStackResult RMAddInfo(const char *destination, CAHeaderOption_t **options,
         *options = optionPtr;
     }
 
-    OC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "OUT");
     return OC_STACK_OK;
 }
 
 OCStackResult RMUpdateInfo(CAHeaderOption_t **options, uint8_t *numOptions,
                            CAEndpoint_t *endpoint)
 {
-    OC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
     RM_NULL_CHECK_WITH_RET(options, TAG, "options");
     RM_NULL_CHECK_WITH_RET(*options, TAG, "invalid option");
     RM_NULL_CHECK_WITH_RET(numOptions, TAG, "numOptions");
@@ -137,7 +229,7 @@ OCStackResult RMUpdateInfo(CAHeaderOption_t **options, uint8_t *numOptions,
 
     if (0 >= *numOptions)
     {
-        OC_LOG(ERROR, TAG, "Invalid arguement: numOptions");
+        OIC_LOG(ERROR, TAG, "Invalid arguement: numOptions");
         return OC_STACK_ERROR;
     }
 
@@ -146,16 +238,16 @@ OCStackResult RMUpdateInfo(CAHeaderOption_t **options, uint8_t *numOptions,
 
     if (-1 >= routeIndex)
     {
-        OC_LOG(DEBUG, TAG, "Nothing to remove.");
+        OIC_LOG(DEBUG, TAG, "Nothing to remove.");
         return OC_STACK_OK;
     }
 
     // Update Endpoint with source address from RM header option.
-    if (0 != (*options + routeIndex)->optionLength)
+    if (DEFAULT_ROUTE_OPTION_LEN < (*options + routeIndex)->optionLength )
     {
         uint8_t dLen = 0;
-        uint16_t count = sizeof(dLen);
-        memcpy(&dLen, (*options + routeIndex)->optionData, sizeof(dLen));
+        uint16_t count = sizeof(dLen) + DEFAULT_ROUTE_OPTION_LEN;
+        memcpy(&dLen, (*options + routeIndex)->optionData + DEFAULT_ROUTE_OPTION_LEN, sizeof(dLen));
         count += dLen;
         uint8_t sLen = 0;
         memcpy(&sLen, (*options + routeIndex)->optionData + count, sizeof(sLen));
@@ -164,7 +256,7 @@ OCStackResult RMUpdateInfo(CAHeaderOption_t **options, uint8_t *numOptions,
         {
             memcpy(endpoint->routeData, (*options + routeIndex)->optionData + count,
                    GATEWAY_ID_LENGTH);
-            OC_LOG_V(DEBUG, TAG, "adding srcgid: %u in endpoint [%d]",
+            OIC_LOG_V(DEBUG, TAG, "adding srcgid: %u in endpoint [%d]",
                      *((uint32_t *)endpoint->routeData), sLen);
 
             count += GATEWAY_ID_LENGTH;
@@ -173,7 +265,7 @@ OCStackResult RMUpdateInfo(CAHeaderOption_t **options, uint8_t *numOptions,
             {
                 memcpy(endpoint->routeData + GATEWAY_ID_LENGTH,
                        (*options + routeIndex)->optionData + count, ENDPOINT_ID_LENGTH);
-                OC_LOG_V(DEBUG, TAG, "adding srceid: %u in endpoint",
+                OIC_LOG_V(DEBUG, TAG, "adding srceid: %u in endpoint",
                          *((uint16_t *)(endpoint->routeData + GATEWAY_ID_LENGTH)));
             }
         }
@@ -192,31 +284,31 @@ OCStackResult RMUpdateInfo(CAHeaderOption_t **options, uint8_t *numOptions,
         OICFree(*options);
         *options = NULL;
     }
-    OC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "OUT");
     return OC_STACK_OK;
 }
 
 void RMGetRouteOptionIndex(const CAHeaderOption_t *options, uint8_t numOptions, int8_t *index)
 {
-    OC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
     RM_NULL_CHECK_VOID(options, TAG, "options");
     RM_NULL_CHECK_VOID(index, TAG, "index");
     for (uint32_t i = 0; i < numOptions; i++)
     {
-        OC_LOG_V(DEBUG, TAG, "Request- optionID: %u", options[i].optionID);
+        OIC_LOG_V(DEBUG, TAG, "Request- optionID: %u", options[i].optionID);
         if (RM_OPTION_MESSAGE_SWITCHING == options[i].optionID)
         {
-            OC_LOG_V(INFO, TAG, "Found Option at %d", i);
+            OIC_LOG_V(INFO, TAG, "Found Option at %d", i);
             *index = i;
             break;
         }
     }
-    OC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 OCStackResult RMCreateRouteOption(const RMRouteOption_t *optValue, CAHeaderOption_t *options)
 {
-    OC_LOG(DEBUG, RM_TAG, "IN");
+    OIC_LOG(DEBUG, RM_TAG, "IN");
     RM_NULL_CHECK_WITH_RET(optValue, RM_TAG, "optValue");
     RM_NULL_CHECK_WITH_RET(options, RM_TAG, "options");
 
@@ -225,106 +317,186 @@ OCStackResult RMCreateRouteOption(const RMRouteOption_t *optValue, CAHeaderOptio
     uint8_t sLen = (optValue->srcGw ? GATEWAY_ID_LENGTH:0) +
                         (optValue->srcEp ? ENDPOINT_ID_LENGTH:0);
 
-    OC_LOG_V(DEBUG, RM_TAG, "createoption dlen %u slen [%u]", dLen, sLen);
-    unsigned int totalLength = MIN_ROUTE_OPTION_LEN + dLen + sLen;
-    void *tempData = OICCalloc(totalLength, sizeof(char));
-    if (NULL == tempData)
+    OIC_LOG_V(DEBUG, RM_TAG, "createoption dlen %u slen [%u]", dLen, sLen);
+
+    unsigned int totalLength = 0;
+    void *tempData = NULL;
+    if (0 == dLen && 0 == sLen)
     {
-        OC_LOG(ERROR, RM_TAG, "Calloc failed");
-        return OC_STACK_NO_MEMORY;
+        OIC_LOG(DEBUG, RM_TAG, "Source and destination is not present");
+        totalLength = DEFAULT_ROUTE_OPTION_LEN;
+        tempData = OICCalloc(totalLength, sizeof(char));
+        if (NULL == tempData)
+        {
+            OIC_LOG(ERROR, RM_TAG, "Calloc failed");
+            return OC_STACK_NO_MEMORY;
+        }
+
+        if (ACK == optValue->msgType)
+        {
+            OIC_LOG(DEBUG, RM_TAG, "OptValue ACK Message Type");
+            memset(tempData, ACK_MESSAGE_TYPE, DEFAULT_ROUTE_OPTION_LEN);
+        }
+        else if (RST == optValue->msgType)
+        {
+            OIC_LOG(DEBUG, RM_TAG, "OptValue RST Message Type");
+            memset(tempData, RST_MESSAGE_TYPE, DEFAULT_ROUTE_OPTION_LEN);
+        }
+        else
+        {
+            OIC_LOG(DEBUG, RM_TAG, "OptValue NOR Message Type");
+            memset(tempData, NORMAL_MESSAGE_TYPE, DEFAULT_ROUTE_OPTION_LEN);
+        }
     }
-    memcpy(tempData, &dLen, sizeof(dLen));
-    unsigned int count = sizeof(dLen);
-    if (0 < dLen)
+    else
     {
-        if (optValue->destGw)
+        totalLength = MIN_ROUTE_OPTION_LEN + dLen + sLen;
+        tempData = OICCalloc(totalLength, sizeof(char));
+        if (NULL == tempData)
         {
-            memcpy(tempData + count, &(optValue->destGw), GATEWAY_ID_LENGTH);
-            count += GATEWAY_ID_LENGTH;
+            OIC_LOG(ERROR, RM_TAG, "Calloc failed");
+            return OC_STACK_NO_MEMORY;
         }
 
-        if (optValue->destEp)
+        if (ACK == optValue->msgType)
         {
-            memcpy(tempData + count, &(optValue->destEp), ENDPOINT_ID_LENGTH);
-            count += ENDPOINT_ID_LENGTH;
+            OIC_LOG(DEBUG, RM_TAG, "OptValue ACK Message Type");
+            memset(tempData, ACK_MESSAGE_TYPE, DEFAULT_ROUTE_OPTION_LEN);
+        }
+        else if (RST == optValue->msgType)
+        {
+            OIC_LOG(DEBUG, RM_TAG, "OptValue RST Message Type");
+            memset(tempData, RST_MESSAGE_TYPE, DEFAULT_ROUTE_OPTION_LEN);
+        }
+        else
+        {
+            OIC_LOG(DEBUG, RM_TAG, "OptValue NOR Message Type");
+            memset(tempData, NORMAL_MESSAGE_TYPE, DEFAULT_ROUTE_OPTION_LEN);
         }
-    }
 
-    memcpy(tempData + count, &sLen, sizeof(sLen));
-    count += sizeof(sLen);
-    if (0 < sLen)
-    {
-        if (optValue->srcGw)
+        memcpy(tempData + DEFAULT_ROUTE_OPTION_LEN, &dLen, sizeof(dLen));
+        unsigned int count = sizeof(dLen) + DEFAULT_ROUTE_OPTION_LEN;
+        if (0 < dLen)
         {
-            memcpy(tempData + count, &(optValue->srcGw), GATEWAY_ID_LENGTH);
-            count += GATEWAY_ID_LENGTH;
+            if (optValue->destGw)
+            {
+                memcpy(tempData + count, &(optValue->destGw), GATEWAY_ID_LENGTH);
+                count += GATEWAY_ID_LENGTH;
+            }
+
+            if (optValue->destEp)
+            {
+                memcpy(tempData + count, &(optValue->destEp), ENDPOINT_ID_LENGTH);
+                count += ENDPOINT_ID_LENGTH;
+            }
         }
 
-        if (optValue->srcEp)
+        memcpy(tempData + count, &sLen, sizeof(sLen));
+        count += sizeof(sLen);
+        if (0 < sLen)
         {
-            memcpy(tempData + count, &(optValue->srcEp), ENDPOINT_ID_LENGTH);
-            count += ENDPOINT_ID_LENGTH;
+            if (optValue->srcGw)
+            {
+                memcpy(tempData + count, &(optValue->srcGw), GATEWAY_ID_LENGTH);
+                count += GATEWAY_ID_LENGTH;
+            }
+
+            if (optValue->srcEp)
+            {
+                memcpy(tempData + count, &(optValue->srcEp), ENDPOINT_ID_LENGTH);
+                count += ENDPOINT_ID_LENGTH;
+            }
         }
+
+        memcpy(tempData + count, &optValue->mSeqNum, sizeof(optValue->mSeqNum));
     }
 
-    memcpy(tempData + count, &optValue->mSeqNum, sizeof(optValue->mSeqNum));
     memcpy(options->optionData, tempData, totalLength);
 
     options->optionID = RM_OPTION_MESSAGE_SWITCHING;
     options->optionLength = totalLength;
 
-    OC_LOG_V(INFO, RM_TAG, "Option Length is %d", options->optionLength);
+    OIC_LOG_V(INFO, RM_TAG, "Option Length is %d", options->optionLength);
 
     OICFree(tempData);
-    OC_LOG(DEBUG, RM_TAG, "OUT");
+    OIC_LOG(DEBUG, RM_TAG, "OUT");
     return OC_STACK_OK;
 }
 
 OCStackResult RMParseRouteOption(const CAHeaderOption_t *options, RMRouteOption_t *optValue)
 {
-    OC_LOG(DEBUG, RM_TAG, "IN");
+    OIC_LOG(DEBUG, RM_TAG, "IN");
     RM_NULL_CHECK_WITH_RET(options, RM_TAG, "options");
     RM_NULL_CHECK_WITH_RET(optValue, RM_TAG, "optValue");
     if (0 == options->optionLength)
     {
-        OC_LOG(ERROR, RM_TAG, "Option data is not present");
+        OIC_LOG(ERROR, RM_TAG, "Option data is not present");
         return OC_STACK_ERROR;
     }
 
-    uint8_t dLen = 0 ;
-    uint16_t count = sizeof(dLen);
-    memcpy(&dLen, options->optionData, sizeof(dLen));
-    if (0 < dLen)
-    {
-        memcpy(&(optValue->destGw), options->optionData + count, GATEWAY_ID_LENGTH);
-        count += GATEWAY_ID_LENGTH;
+    OIC_LOG_V(DEBUG, RM_TAG, "Option Length is %d", options->optionLength);
+    uint8_t mType = 0;
+    memcpy(&mType, options->optionData, sizeof(mType));
 
-        if (GATEWAY_ID_LENGTH < dLen)
-        {
-            memcpy(&(optValue->destEp), options->optionData + count, ENDPOINT_ID_LENGTH);
-            count += ENDPOINT_ID_LENGTH;
-        }
+    if (ACK_MESSAGE_TYPE == mType)
+    {
+        OIC_LOG(INFO, RM_TAG, "ACK_MESSAGE_TYPE");
+        optValue->msgType = ACK;
+    }
+    else if (RST_MESSAGE_TYPE == mType)
+    {
+        OIC_LOG(INFO, RM_TAG, "RST_MESSAGE_TYPE");
+        optValue->msgType = RST;
+    }
+    else if (NORMAL_MESSAGE_TYPE == mType)
+    {
+        OIC_LOG(INFO, RM_TAG, "NOR_MESSAGE_TYPE");
+        optValue->msgType = NOR;
     }
 
-    uint8_t sLen = 0;
-    memcpy(&sLen, options->optionData + count, sizeof(sLen));
-    count += sizeof(sLen);
-    if (0 < sLen)
+    if (DEFAULT_ROUTE_OPTION_LEN == options->optionLength)
+    {
+        OIC_LOG(INFO, RM_TAG, "No source and destination are present");
+    }
+    else
     {
-        memcpy(&(optValue->srcGw), options->optionData + count, GATEWAY_ID_LENGTH);
-        count += GATEWAY_ID_LENGTH;
+        uint8_t dLen = 0 ;
+        uint16_t count = DEFAULT_ROUTE_OPTION_LEN;
+        memcpy(&dLen, options->optionData + count, sizeof(dLen));
+        count += sizeof(dLen);
+        if (0 < dLen)
+        {
+            memcpy(&(optValue->destGw), options->optionData + count, GATEWAY_ID_LENGTH);
+            count += GATEWAY_ID_LENGTH;
 
-        if (GATEWAY_ID_LENGTH < sLen)
+            if (GATEWAY_ID_LENGTH < dLen)
+            {
+                memcpy(&(optValue->destEp), options->optionData + count, ENDPOINT_ID_LENGTH);
+                count += ENDPOINT_ID_LENGTH;
+            }
+        }
+
+        uint8_t sLen = 0;
+        memcpy(&sLen, options->optionData + count, sizeof(sLen));
+        count += sizeof(sLen);
+        if (0 < sLen)
         {
-            memcpy(&(optValue->srcEp), options->optionData + count, ENDPOINT_ID_LENGTH);
-            count += ENDPOINT_ID_LENGTH;
+            memcpy(&(optValue->srcGw), options->optionData + count, GATEWAY_ID_LENGTH);
+            count += GATEWAY_ID_LENGTH;
+
+            if (GATEWAY_ID_LENGTH < sLen)
+            {
+                memcpy(&(optValue->srcEp), options->optionData + count, ENDPOINT_ID_LENGTH);
+                count += ENDPOINT_ID_LENGTH;
+            }
         }
+        memcpy(&optValue->mSeqNum, options->optionData + count, sizeof(optValue->mSeqNum));
     }
-    memcpy(&optValue->mSeqNum, options->optionData + count, sizeof(optValue->mSeqNum));
 
-    OC_LOG_V(INFO, RM_TAG, "Option hopcount is %d", optValue->mSeqNum);
-    OC_LOG_V(INFO, RM_TAG, "Option Sender Addr is [%u][%u]", optValue->srcGw, optValue->srcEp);
-    OC_LOG_V(INFO, RM_TAG, "Option Dest Addr is [%u][%u]", optValue->destGw, optValue->destEp);
-    OC_LOG(DEBUG, RM_TAG, "OUT");
+    OIC_LOG_V(INFO, RM_TAG, "Option hopcount is %d", optValue->mSeqNum);
+    OIC_LOG_V(INFO, RM_TAG, "Option Sender Addr is [%u][%u]", optValue->srcGw, optValue->srcEp);
+    OIC_LOG_V(INFO, RM_TAG, "Option Dest Addr is [%u][%u]", optValue->destGw, optValue->destEp);
+    OIC_LOG_V(INFO, RM_TAG, "Message Type is [%u]", optValue->msgType);
+    OIC_LOG(DEBUG, RM_TAG, "OUT");
     return OC_STACK_OK;
 }
old mode 100755 (executable)
new mode 100644 (file)
index 4dcb4c2..ccfcda0
@@ -52,7 +52,8 @@ libocsrm_env.PrependUnique(CPPPATH = [
                '../connectivity/inc',
                '../connectivity/api',
                '../security/include',
-               '../security/include/internal'
+               '../security/include/internal',
+               '../security/provisioning/include'
                ])
 
 if target_os not in ['arduino', 'windows', 'winrt']:
@@ -97,6 +98,9 @@ if env.get('SECURED') == '1':
                OCSRM_SRC + 'doxmresource.c',
                OCSRM_SRC + 'credresource.c',
                OCSRM_SRC + 'svcresource.c',
+               OCSRM_SRC + 'pconfresource.c',
+               OCSRM_SRC + 'dpairingresource.c',
+               OCSRM_SRC + 'verresource.c',
                OCSRM_SRC + 'policyengine.c',
                OCSRM_SRC + 'psinterface.c',
                OCSRM_SRC + 'srmresourcestrings.c',
@@ -106,7 +110,8 @@ if env.get('SECURED') == '1':
                OCSRM_SRC + 'base64.c',
                #pbkdf2.c is required to PIN based OxM only.
                #But we did not use a separate build options to prevent the build command becomes complicated.
-               OCSRM_SRC + 'pbkdf2.c'
+               OCSRM_SRC + 'pbkdf2.c',
+               OCSRM_SRC + 'directpairing.c'
                ]
 else:
        libocsrm_src = [
@@ -119,12 +124,16 @@ else:
                OCSRM_SRC + 'doxmresource.c',
                OCSRM_SRC + 'credresource.c',
                OCSRM_SRC + 'svcresource.c',
+               OCSRM_SRC + 'pconfresource.c',
+               OCSRM_SRC + 'dpairingresource.c',
                OCSRM_SRC + 'policyengine.c',
+               OCSRM_SRC + 'verresource.c',
                OCSRM_SRC + 'psinterface.c',
                OCSRM_SRC + 'srmresourcestrings.c',
                OCSRM_SRC + 'srmutility.c',
                OCSRM_SRC + 'iotvticalendar.c',
-               OCSRM_SRC + 'base64.c'
+               OCSRM_SRC + 'base64.c',
+               OCSRM_SRC + 'directpairing.c'
                ]
 
 if env.get('DTLS_WITH_X509') == '1' and env.get('SECURED') == '1':
@@ -135,8 +144,9 @@ if env.get('DTLS_WITH_X509') == '1' and env.get('SECURED') == '1':
 libocsrm = libocsrm_env.StaticLibrary('libocsrm', libocsrm_src)
 
 libocsrm_env.InstallTarget(libocsrm, 'libocsrm')
-libocsrm_env.UserInstallTargetLib(libocsrm, 'libocsrm')
 
 if target_os in ['linux', 'android', 'tizen'] and env.get('SECURED') == '1':
        SConscript('provisioning/SConscript')
 
+if target_os in ['linux'] and env.get('SECURED') == '1':
+       SConscript('tool/SConscript')
index 4d5837d..a983f1e 100644 (file)
@@ -1,22 +1,22 @@
- /******************************************************************
-  *
-  * 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.
-  *
-  ******************************************************************/
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #ifndef _IOTVT_B64_H_
 #define _IOTVT_B64_H_
@@ -41,27 +41,27 @@ extern "C" {
 #define B64DECODE_OUT_SAFESIZE(x) (((x)*3)/4)
 
 /**
- * Result code of base64 functions
+ * Result code of base64 functions.
  */
-typedef enum {
+typedef enum
+{
     B64_OK = 0,
     B64_INVALID_PARAM,
     B64_OUTPUT_BUFFER_TOO_SMALL,
     B64_ERROR
-}B64Result;
+} B64Result;
 
 /**
  * Encode the plain message in base64.
  *
- * @param[in] in  Plain message
- * @param[in] inLen  Byte length of 'in'
- * @param[in,out] outBuf Output buffer
- *                Base64 encoded message will be written into 'outBuf'
- *                NOTE : This method adds a NULL to the string configuration
- * @param[in] outBufSize Size of output buffer
- * @param[out] outLen  Byte length of encoded message
+ * @param in is the plain message to be converted.
+ * @param inLen is the byte length of plain message.
+ * @param outBuf is the output buffer containing Base64 encoded message.
+ * @note outBuf adds a NULL to the string configuration.
+ * @param outBufSize is the size of output buffer.
+ * @param outLen is the byte length of encoded message.
  *
- * @return  B64_OK for Success, otherwise some error value
+ * @return ::B64_OK for Success, otherwise some error value.
  */
 B64Result b64Encode(const uint8_t* in, const size_t inLen,
                char* outBuf, const size_t outBufSize, uint32_t *outLen);
@@ -69,14 +69,14 @@ B64Result b64Encode(const uint8_t* in, const size_t inLen,
 /**
  * Decode the encoded message in base64.
  *
- * @param[in] in  Base64 encoded message
- * @param[in] inLen  Byte lenth of 'in'
- * @param[in, out] outBuf  Output buffer
- *                 Base64 decoded message will be written into 'outBuf'
- * @param[in] outBufSize Size of output buffer
- * @param[out] outLen  Byte length of decoded message
+ * @param in is the Base64 encoded message to be converted.
+ * @param inLen is the byte length of the encoded message.
+ * @param outBuf is the output buffer containing decoded message.
+ * @note outBuf adds a NULL to the string configuration.
+ * @param outBufSize is the size of output buffer.
+ * @param outLen is the byte length of decoded message.
  *
- * @return  B64_OK for Success, otherwise some error value
+ * @return ::B64_OK for Success, otherwise some error value.
  */
 B64Result b64Decode(const char* in, const size_t inLen,
                uint8_t* outBuf, size_t outBufSize, uint32_t *outLen);
index 564d23f..5f1ac9d 100644 (file)
@@ -28,16 +28,15 @@ extern "C" {
 /**
  * Initialize ACL resource by loading data from persistent storage.
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult InitACLResource();
 
 /**
  * Perform cleanup for ACL resources.
  *
- * @retval  none
  */
-void DeInitACLResource();
+OCStackResult DeInitACLResource();
 
 /**
  * This method is used by PolicyEngine to retrieve ACL for a Subject.
@@ -46,39 +45,65 @@ void DeInitACLResource();
  * @param savePtr is used internally by @ref GetACLResourceData to maintain index between
  *                successive calls for same subjectId.
  *
- * @retval  reference to @ref OicSecAcl_t if ACL is found, else NULL
+ * @note On the first call to @ref GetACLResourceData, savePtr should point to NULL.
  *
- * @note On the first call to @ref GetACLResourceData, savePtr should point to NULL
+ * @return reference to @ref OicSecAcl_t if ACL is found, else NULL.
  */
 const OicSecAcl_t* GetACLResourceData(const OicUuid_t* subjectId, OicSecAcl_t **savePtr);
 
 /**
- * This function converts ACL data into JSON format.
- * Caller needs to invoke 'free' when done using
- * returned string.
- * @param acl  instance of OicSecAcl_t structure.
+ * This function converts ACL data into CBOR format.
  *
- * @retval  pointer to ACL in json format.
+ * @param acl instance of @ref OicSecAcl_t structure.
+ * @param outPayload is the pointer to allocated memory for cbor payload.
+ * @param size of the cbor payload.
+ *
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
-char* BinToAclJSON(const OicSecAcl_t * acl);
-
+OCStackResult AclToCBORPayload(const OicSecAcl_t * acl, uint8_t **outPayload, size_t *size);
 
 /**
  * This function deletes ACL data.
  *
- * @param acl  instance of OicSecAcl_t structure.
+ * @param acl instance of @ref OicSecAcl_t structure to be deleted.
  */
 void DeleteACLList(OicSecAcl_t* acl);
 
-
 /**
  * This function installs a new ACL.
- * @param newJsonStr JSON string representing a new ACL.
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @param payload cbor value representing a new ACL.
+ * @param size of the cbor payload.
+ *
+ * @return ::OC_STACK_OK for Success, otherwise some error value
  */
-OCStackResult InstallNewACL(const char* newJsonStr);
+OCStackResult InstallNewACL(const uint8_t* payload, const size_t size);
 
+/**
+ * This function updates default ACL which is required for ownership transfer.
+ * This function should be invoked after OTM is complete to prevent anonymous user access.
+ *
+ * @retval OC_STACK_OK for Success, otherwise some error value
+ */
+OCStackResult UpdateDefaultSecProvACL();
+
+/**
+ * Internal function to update resource owner
+ *
+ * @param newROwner new owner
+ *
+ * @retval ::OC_STACK_OK for Success, otherwise some error value
+ */
+OCStackResult SetAclRownerId(const OicUuid_t* newROwner);
+
+
+/**
+ * Gets the OicUuid_t value for the rownerid of the acl resource.
+ *
+ * @param rowneruuid a pointer to be assigned to the rowneruuid property
+ * @return ::OC_STACK_OK if rowneruuid is assigned correctly, else ::OC_STACK_ERROR.
+ */
+OCStackResult GetAclRownerId(OicUuid_t *rowneruuid);
 
 #ifdef __cplusplus
 }
old mode 100755 (executable)
new mode 100644 (file)
index 9c37a0e..052b959
@@ -36,14 +36,12 @@ extern "C" {
 /**
  * Initialize Amacl resource by loading data from persistent storage.
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult InitAmaclResource();
 
 /**
  * Perform cleanup for Amacl resources.
- *
- * @retval  none
  */
 void DeInitAmaclResource();
 
@@ -52,30 +50,48 @@ void DeInitAmaclResource();
  * If the Amacl is found for the given resource then populate the parameter
  * amsId with Amacl resource amss id.
  *
- * @param resource  resource for which AMS service is required.
- * @param amsId     ID of the ams service for the given resource
- *
- * @retval
- *  OC_STACK_OK     If Amacl found for the resource
- *  OC_STACK_ERROR  If no Amacl found for the resource
+ * @param resource for which AMS service is required.
+ * @param amsId of the ams service for the given resource.
  *
+ * @return ::OC_STACK_OK, if Amacl is found for the resource, else ::OC_STACK_ERROR,
+ *  if no Amacl found for the resource.
  */
 OCStackResult AmaclGetAmsDeviceId(const char *resource, OicUuid_t *amsId);
 
 /**
- * This function converts Amacl data into JSON format.
- * Caller needs to invoke 'free' when done using
- * returned string.
- * @param Amacl  instance of OicSecAmacl_t structure.
+ * This function converts Amacl data into CBOR format.
+ * Caller needs to invoke 'free' when done using returned string.
+ *
+ * @param amacl instance of @ref OicSecAmacl_t structure.
+ * @param cborPayload is the converted cbor value of @ref OicSecAmacl_t structure.
+ * @param cborSize is the size of the cbor payload. This value is the size of the
+ * cborPayload. It should not be NON-NULL value.
+ *
+ * @return ::OC_STACK_OK for Success. ::OC_STACK_INVALID in case of invalid parameters.
+ * ::OC_STACK_ERROR in case of error in converting to cbor.
+ */
+OCStackResult AmaclToCBORPayload(const OicSecAmacl_t *amacl, uint8_t **cborPayload,
+                                 size_t *cborSize);
+
+/**
+ * Internal function to update resource owner
  *
- * @retval  pointer to Amacl in json format.
+ * @param newROwner new owner
+ *
+ * @retval ::OC_STACK_OK for Success, otherwise some error value
  */
-char* BinToAmaclJSON(const OicSecAmacl_t * amacl);
+OCStackResult SetAmaclRownerId(const OicUuid_t* newROwner);
+
+/**
+ * Gets the OicUuid_t value for the rownerid of the amacl resource.
+ *
+ * @param rowneruuid a pointer to be assigned to the rowneruuid property
+ * @return ::OC_STACK_OK if rowneruuid is assigned correctly, else ::OC_STACK_ERROR.
+ */
+OCStackResult GetAmaclRownerId(OicUuid_t *rowneruuid);
 
 #ifdef __cplusplus
 }
 #endif
 
 #endif //IOTVT_SRM_AMACLR_H
-
-
index c83530f..e07b442 100644 (file)
 #ifndef IOTVT_SRM_AMSMGR_H
 #define IOTVT_SRM_AMSMGR_H
 
+#include <stdlib.h>
+#include <stdint.h>
+
 #include "ocstack.h"
 #include "logger.h"
 #include "policyengine.h"
 #include "securevirtualresourcetypes.h"
 #include "cainterface.h"
-#include <stdlib.h>
-#include <stdint.h>
 
 typedef struct PEContext PEContext_t;
 /**
- * @brief   The AMS context..
+ * The AMS context.
  */
 typedef struct AmsMgrContext
 {
@@ -40,96 +41,96 @@ typedef struct AmsMgrContext
     CARequestInfo_t     *requestInfo;
 } AmsMgrContext_t;
 
-
 /**
- * @brief This method updates AmsMgr context's endpoint & requestInfo
+ * This method updates AmsMgr context's endpoint & requestInfo.
  *
- * @param context          Policy engine context.
- * @param endpoint         CA Endpoint info of the requester
- * @param requestInfo      CA RequestInfo of the requester
+ * @param context is the policy engine context.
+ * @param endpoint is the CA Endpoint info of the requester.
+ * @param requestInfo is the CA RequestInfo of the requester.
+ *
+ * @return ::OC_STACK_OK if successful, else other value in case of error.
  */
-OCStackResult UpdateAmsMgrContext(PEContext_t *context, const CAEndpoint_t *endpoint,
-                       const CARequestInfo_t *requestInfo);
+OCStackResult UpdateAmsMgrContext(PEContext_t *context,
+                                  const CAEndpoint_t *endpoint,
+                                  const CARequestInfo_t *requestInfo);
 
 /**
- *
  * This method is called by PolicyEngine to Discover AMS service.
  * It sends muticast discovery request such as
  * /oic/sec/doxm?deviceid="AMSSrvcDeviceID" to discover AMS service
- * with deviceId="AMSSrvcDeviceID"
- *
- * @param context   Policy engine context.
+ * with deviceId="AMSSrvcDeviceID".
  *
- * @retval
- *  OC_STACK_OK     If able to successfully send multicast discovery request.
- *  OC_STACK_ERROR  If unable to successfully send multicast discovery request due to error.
+ * @param context is the policy engine context.
  *
+ * @return ::OC_STACK_OK,If able to successfully send multicast discovery request.
+ * else ::OC_STACK_ERROR, If unable to successfully send multicast discovery request
+ * due to error.
  */
 OCStackResult DiscoverAmsService(PEContext_t *context);
 
-
 /**
- *
  * This method sends unicast request to retrieve the secured port info of the
  * discovered AMS service. It sends unicast discovery request such as
- * /oic/res?rt="oic.sec.doxm" to the discovered AMS service
- *
- * @param context   Policy engine context.
+ * /oic/res?rt="oic.sec.doxm" to the discovered AMS service.
  *
- * @retval
- *  OC_STACK_OK     If able to successfully send unicast discovery request
- *  OC_STACK_ERROR  If unable to successfully send unicast discovery request due to error
+ * @param context is the policy engine context.
  *
+ * @return ::OC_STACK_OK,If able to successfully send unicast discovery request.
+ * else ::OC_STACK_ERROR, If unable to successfully send unicast discovery request
+ * due to error.
  */
-OCStackResult SendUnicastSecurePortDiscovery(PEContext_t *context,OCDevAddr *devAddr,
-                                      OCConnectivityType connType);
-
+OCStackResult SendUnicastSecurePortDiscovery(PEContext_t *context,
+                                             OCDevAddr *devAddr,
+                                             OCConnectivityType connType);
 
 /**
- *
  * This method sends unicast request to AMS service to get ACL for
  * the Subject and/or Resource. It sends unicast request such as
  * /oic/sec/acl?sub="subjectId";rsrc="/a/led" to get the ACL for
- * the subject & resource
+ * the subject & resource.
  *
- * @param context   Policy engine context.
+ * @param context is the policy engine context.
  *
- * @retval
- *  OC_STACK_OK     If able to successfully send unicast ACL request
- *  OC_STACK_ERROR  If unable to successfully send unicast ACL request due to error
+ * @return ::OC_STACK_OK, If able to successfully send unicast ACL request.
+ * ::OC_STACK_ERROR, If unable to successfully send unicast ACL request due to error.
  *
  */
-OCStackResult SendAclReq(PEContext_t *context, OCDevAddr *devAddr, OCConnectivityType connType,
-        uint16_t securedPort);
-
+OCStackResult SendAclReq(PEContext_t *context,
+                         OCDevAddr *devAddr,
+                         OCConnectivityType connType,
+                         uint16_t securedPort);
 
 /*
- * Cleanup CARequestInfo_t object
- * @param requestInfo        pointer to RequestInfo_t object
+ * Cleanup CARequestInfo_t object.
+ *
+ * @param requestInfo is the pointer to @ref CARequestInfo_t.
  */
 void FreeCARequestInfo(CARequestInfo_t *requestInfo);
 
-
 /*
  * This method is used by Policy engine to checks Amacl resource.
  * If Amacl is found then it fills up context->amsMgrContext->amsDeviceId
  * with amsID of the Amacl else leaves it empty.
  *
- * @param context   Policy engine context.
+ * @param context is the policy engine context.
  *
- * @return          true if AMacl for the resource is found
- *                  false if AMacl for the resource is not found
+ * @return true, if Amacl for the resource is found. false, if Amacl for the
+ * resource is not found
  */
 bool FoundAmaclForRequest(PEContext_t *context);
 
-
 /*
- * This method is used by Policy engine to process AMS request
- * *
- * @param context   Policy engine context.
+ * This method is used by Policy engine to process AMS request.
  *
- * @return          None
+ * @param context is the policy engine context.
  */
 void ProcessAMSRequest(PEContext_t *context);
 
+/*
+ * This method is used by Policy engine to free AMS context requestInfo/
+ *
+ * @param requestInfo is the pointer to @ref CARequestInfo_t.
+ */
+void FreeCARequestInfo(CARequestInfo_t *requestInfo);
+
 #endif //IOTVT_SRM_AMSMGR_H
index 74ea373..7e12912 100644 (file)
@@ -32,45 +32,42 @@ extern "C" {
 /**
  * Initialize credential resource by loading data from persistent storage.
  *
- * @retval
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack process error
+ * @return ::OC_STACK_OK, if initialization is successful, else ::OC_STACK_ERROR if
+ * initialization fails.
  */
 OCStackResult InitCredResource();
 
 /**
  * Perform cleanup for credential resources.
  *
- * @retval
- *     OC_STACK_OK              - no errors
- *     OC_STACK_ERROR           - stack process error
- *     OC_STACK_NO_RESOURCE     - resource not found
- *     OC_STACK_INVALID_PARAM   - invalid param
+ * @return ::OC_STACK_OK, if no errors. ::OC_STACK_ERROR, if stack process error.
+ * ::OC_STACK_NO_RESOURCE, if resource not found.
+ * ::OC_STACK_INVALID_PARAM, if invalid param.
  */
 OCStackResult DeInitCredResource();
 
 /**
- * This method is used by tinydtls/SRM to retrieve credential for given Subject.
+ * This method is used by tinydtls/SRM to retrieve credential for given subject.
  *
- * @param subject - subject for which credential is required.
+ * @param subjectId for which credential is required.
  *
- * @retval
- *     reference to OicSecCred_t - if credential is found
- *     NULL                      - if credential not found
+ * @return reference to @ref OicSecCred_t, if credential is found, else NULL, if credential
+ * not found.
  */
 const OicSecCred_t* GetCredResourceData(const OicUuid_t* subjectId);
 
 /**
- * This function converts credential data into JSON format.
- * Caller needs to invoke 'free' when done using
- * returned string.
- * @param cred  pointer to instance of OicSecCred_t structure.
- *
- * @retval
- *      pointer to JSON credential representation - if credential for subjectId found
- *      NULL                                      - if credential for subjectId not found
+ * This function converts credential data into CBOR format.
+ * Caller needs to invoke 'free' when done using returned string.
+ *
+ * @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.
+ *
+ * @return ::OC_STACK_OK if conversion is successful, else ::OC_STACK_ERROR if unsuccessful.
  */
-char* BinToCredJSON(const OicSecCred_t* cred);
+OCStackResult CredToCBORPayload(const OicSecCred_t* cred, uint8_t **cborPayload,
+                                size_t *cborSize);
 
 /**
  * This function generates the bin credential data.
@@ -79,56 +76,44 @@ char* BinToCredJSON(const OicSecCred_t* cred);
  * @param credType credential type.
  * @param publicData public data such as public key.
  * @param privateData private data such as private key.
- * @param ownersLen length of owners array
- * @param owners array of owners.
+ * @param rownerID Resource owner's UUID.
  *
- * @retval
- *      pointer to instance of OicSecCred_t  - success
- *      NULL                                 - error
+ * @return pointer to instance of @ref OicSecCred_t if successful. else NULL in case of error.
+
  */
 OicSecCred_t * GenerateCredential(const OicUuid_t* subject, OicSecCredType_t credType,
-                     const char * publicData, const char * privateData, size_t ownersLen,
-                     const OicUuid_t * owners);
+                     const OicSecCert_t * publicData, const OicSecKey_t * privateData,
+                     const OicUuid_t * rownerID);
 
 /**
  * This function adds the new cred to the credential list.
  *
- * @param cred pointer to new credential.
+ * @param cred is the pointer to new credential.
  *
- * @retval
- *      OC_STACK_OK     - cred not NULL and persistent storage gets updated
- *      OC_STACK_ERROR  - cred is NULL or fails to update persistent storage
+ * @return ::OC_STACK_OK, cred not NULL and persistent storage gets updated.
+ * ::OC_STACK_ERROR, cred is NULL or fails to update persistent storage.
  */
 OCStackResult AddCredential(OicSecCred_t * cred);
 
 /**
  * Function to remove the credential from SVR DB.
  *
- * @param credId Credential ID to be deleted.
+ * @param credId is the Credential ID to be deleted.
  *
- * @return OC_STACK_OK for success and errorcode otherwise.
+ * @return ::OC_STACK_OK for success, or errorcode otherwise.
  */
-OCStackResult RemoveCredential(const OicUuid_t* credId);
-
-/**
- * Remove all credential data on credential resource and persistent storage
- *
- * @retval
- *     OC_STACK_OK              - no errors
- *     OC_STACK_ERROR           - stack process error
- */
-OCStackResult RemoveAllCredentials(void);
+OCStackResult RemoveCredential(const OicUuid_t *credId);
 
 #if defined(__WITH_DTLS__)
 /**
  * This internal callback is used by lower stack (i.e. CA layer) to
  * retrieve PSK credentials from RI security layer.
  *
- * @param[in]  type type of PSK data required by CA layer during DTLS handshake.
- * @param[in]  desc Additional request information.
- * @param[in]  desc_len The actual length of desc.
- * @param[out] result  Must be filled with the requested information.
- * @param[in]  result_length  Maximum size of @p result.
+ * @param type of PSK data required by CA layer during DTLS handshake.
+ * @param desc Additional request information.
+ * @param desc_len is the actual length of desc.
+ * @param result  is must be filled with the requested information.
+ * @param result_length is the maximum size of @p result.
  *
  * @return The number of bytes written to @p result or a value
  *         less than zero on error.
@@ -138,21 +123,21 @@ int32_t GetDtlsPskCredentials( CADtlsPskCredType_t type,
               unsigned char *result, size_t result_length);
 
 /**
- * Add temporal PSK to PIN based OxM
+ * Add temporal PSK to PIN based OxM.
  *
- * @param[in] tmpSubject UUID of target device
- * @param[in] credType Type of credential to be added
- * @param[in] pin numeric characters
- * @param[in] pinSize length of 'pin'
- * @param[in] ownersLen Number of owners
- * @param[in] owners Array of owners
- * @param[out] tmpCredSubject Generated credential's subject.
+ * @param tmpSubject is the UUID of target device
+ * @param credType is the type of credential to be added
+ * @param pin is the numeric characters
+ * @param pinSize is the length of 'pin'
+ * @param rownerID Resource owner's UUID
+ * @param tmpCredSubject is the generated credential's subject.
  *
- * @return OC_STACK_OK for success and errorcode otherwise.
+ * @return ::OC_STACK_OK for success or else errorcode.
  */
 OCStackResult AddTmpPskWithPIN(const OicUuid_t* tmpSubject, OicSecCredType_t credType,
                             const char * pin, size_t pinSize,
-                            size_t ownersLen, const OicUuid_t * owners, OicUuid_t* tmpCredSubject);
+                            const OicUuid_t * rownerID,
+                            OicUuid_t* tmpCredSubject);
 
 #endif /* __WITH_DTLS__ */
 
@@ -160,26 +145,40 @@ OCStackResult AddTmpPskWithPIN(const OicUuid_t* tmpSubject, OicSecCredType_t cre
 /**
  * This function is used toretrieve certificate credentials from RI security layer.
  *
- * @param credInfo
- *     binary structure containing certificate credentials
+ * @param credInfo is the binary structure containing certificate credentials
  *
- * @retval 0  on scuccess
+ * @return 0 on success.
  */
 int GetDtlsX509Credentials(CADtlsX509Creds_t *credInfo);
 #endif /*__WITH_X509__*/
 
 /**
- * Function to deallocate allocated memory to OicSecCred_t
+ * Function to deallocate allocated memory to OicSecCred_t.
  *
- * @param cred pointer to cred type
+ * @param cred pointer to cred type.
  *
  */
 void DeleteCredList(OicSecCred_t* cred);
 
+/**
+ * Internal function to update resource owner
+ *
+ * @param newROwner new owner
+ *
+ * @retval ::OC_STACK_OK for Success, otherwise some error value
+ */
+OCStackResult SetCredRownerId(const OicUuid_t* newROwner);
+
+/**
+ * Gets the OicUuid_t value for the rownerid of the cred resource.
+ *
+ * @param rowneruuid a pointer to be assigned to the rowneruuid property
+ * @return ::OC_STACK_OK if rowneruuid is assigned correctly, else ::OC_STACK_ERROR.
+ */
+OCStackResult GetCredRownerId(OicUuid_t *rowneruuid);
+
 #ifdef __cplusplus
 }
 #endif
 
 #endif //IOTVT_SRM_CREDR_H
-
-
index 75178d8..454bec7 100644 (file)
@@ -29,43 +29,62 @@ extern "C" {
 #endif
 
 /**
- * This function stores CRL in SRM
- * @param crl - CRL
+ * This function stores CRL in SRM.
  *
- * @returns OC_STACK_OK for Success, otherwise some error value
+ * @param crl to be stored in SRM.
+ *
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult UpdateCRLResource(const OicSecCrl_t *crl);
 
 /**
- * This function get encoded with base64 CRL from SRM
+ * This function get encoded with base64 CRL from SRM.
+ *
+ * @note Caller responsible for resulting string memory (use OICFree to remove it).
  *
- * @returns encoded CRL with base64 format. NULL if error occured (e.g. CRL did not set)
- * @note Caller responsible for resulting string memory (use OICFree to remove it)
+ * @return NULL if error occured (e.g. CRL did not set).
  */
-char* GetBase64CRL();
+uint8_t* GetCrl();
+
 /**
- * This function get encoded with DER CRL from SRM
+ * This function get encoded with DER CRL from SRM.
  *
- * @returns encoded CRL with DER format. array len is 0 if error occured (e.g. CRL did not set)
+ * @return encoded CRL with DER format. array len is 0 if error occured (e.g. CRL did not set).
  */
 void  GetDerCrl(ByteArray crlArray);
 
 /**
- * This function get CRL from SRM
+ * This function converts CRL to CBOR
  *
- * @param crl [out] - pointer to buffer that contains crl. Shoul be not NULL. Buffer
+ * @param crl is a pointer to buffer that contains crl. Shoul be not NULL. Buffer
  * will be allocated by the function and content of *crl will be ignored.
- * @param outlen [out] - pointer to length of the CRL buffer. Shoul be not NULL.
+ * @param payload is the converted cbor value.
+ * @param size is a pointer to length of the CRL buffer. Should be not NULL.
+ *
+ * @note Caller responsible for crl buffer memory (use OICFree to free it).
  *
- * @returns OC_STACK_OK if success and errorcode otherwise.
- * @note Caller responsible for crl buffer memory (use OICFree to free it)
+ * @return ::OC_STACK_OK if success, otherwise some error value.
  */
-OicSecCrl_t * JSONToCrlBin(const char * jsonStr);
+OCStackResult CrlToCBORPayload(const OicSecCrl_t *crl, uint8_t **payload, size_t *size);
 
 /**
- * Initialize CLR resource by loading data from persistent storage.
+ * This function converts CBOR to CRL
  *
- * @returns OC_STACK_OK for Success, otherwise some error value
+ * will be allocated by the function and content of *crl will be ignored.
+ * @param cborPayload is the cbor vlaue
+ * @param size is a pointer to length of the CRL buffer. Should be not NULL.
+ * @param crl is a pointer to buffer that contains crl. Shoul be not NULL. Buffer
+ *
+ * @note Caller responsible for crl buffer memory (use OICFree to free it).
+ *
+ * @return ::OC_STACK_OK if success, otherwise some error value.
+ */
+OCStackResult CBORPayloadToCrl(const uint8_t *cborPayload, const size_t size,
+                               OicSecCrl_t **secCrl);
+/**
+ * Initialize CRL resource by loading data from persistent storage.
+ *
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult InitCRLResource();
 
@@ -74,15 +93,15 @@ OCStackResult InitCRLResource();
  */
 void DeInitCRLResource();
 
+/**
+ * Get an instance of CRL resource.
+ *
+ * @return reference to the @ref OicSecCrl_t, holding reference to CRL resource.
+ */
 OicSecCrl_t *GetCRLResource();
 
-OCEntityHandlerResult CRLEntityHandler(OCEntityHandlerFlag flag,
-                                        OCEntityHandlerRequest * ehRequest,
-                                        void* callbackParameter);
 #ifdef __cplusplus
 }
 #endif
 
 #endif //IOTVT_SRM_CRLR_H
-
-
diff --git a/resource/csdk/security/include/internal/directpairing.h b/resource/csdk/security/include/internal/directpairing.h
new file mode 100644 (file)
index 0000000..e884c9a
--- /dev/null
@@ -0,0 +1,82 @@
+/* *****************************************************************\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
+#ifndef _DIRECT_PAIRING_H_\r
+#define _DIRECT_PAIRING_H_\r
+\r
+#include <stdbool.h>\r
+#include "ocstack.h"\r
+#include "pmtypes.h"\r
+#include "securevirtualresourcetypes.h"\r
+\r
+#ifdef __cplusplus\r
+extern "C"\r
+{\r
+#endif\r
+\r
+/**\r
+ * Discover direct-pairing devices in the same IP subnet. .\r
+ *\r
+ * @param[in] waittime  Timeout in seconds.\r
+ *\r
+ * @return OC_STACK_OK on success otherwise error.\r
+ */\r
+OCStackResult DPDeviceDiscovery(unsigned short waittime);\r
+\r
+/**\r
+ * Start direct-pairing processes.\r
+ *\r
+ * @param[in] peer  target device to establish direct-pairing.\r
+ * @param[in] pmSel  selected pairing method.\r
+ * @param[in] pinNumber  secret value for dtls connection.\r
+ * @param[in] resultCallback  result event callback.\r
+ *\r
+ * @return OC_STACK_OK on success otherwise error.\r
+ */\r
+OCStackResult DPDirectPairing(OCDirectPairingDev_t* peer, OicSecPrm_t pmSel, char *pinNumber,\r
+                                                     OCDirectPairingResultCB resultCallback);\r
+\r
+/**\r
+ * This function returns discovered devices list in direct-pairing discovery\r
+ * Caller must NOT free returned constant pointer\r
+ *\r
+ * @return OCDirectPairingDev_t pointer on success otherwise NULL.\r
+ */\r
+const OCDirectPairingDev_t* DPGetDiscoveredDevices();\r
+\r
+/**\r
+ * This function returns paired devices list until now\r
+ * Caller must NOT free returned constant pointer\r
+ *\r
+ * @return OCDirectPairingDev_t pointer on success otherwise NULL.\r
+ */\r
+const OCDirectPairingDev_t* DPGetPairedDevices();\r
+\r
+/**\r
+ * This function delete both discovered devices and paired devices list\r
+ *\r
+ */\r
+void DPDeleteLists();\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+#endif //_DIRECT_PAIRING_H_\r
+\r
index e0f2fc9..d6f98af 100644 (file)
@@ -30,75 +30,91 @@ extern "C" {
 /**
  * Initialize DOXM resource by loading data from persistent storage.
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult InitDoxmResource();
 
 /**
  * Perform cleanup for DOXM resources.
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult DeInitDoxmResource();
 
 /**
  * This method is used by SRM to retrieve DOXM resource data..
  *
- * @retval  reference to @ref OicSecDoxm_t, binary format of Doxm resource data
+ * @return reference to @ref OicSecDoxm_t, binary format of Doxm resource data.
  */
 const OicSecDoxm_t* GetDoxmResourceData();
 
 /**
- * This method converts JSON DOXM into binary DOXM.
- * The JSON DOXM can be from persistent database or
+ * This method converts CBOR DOXM into binary DOXM.
+ * The CBOR DOXM can be from persistent database or
  * or received as PUT/POST request.
  *
- * @param[in] jsonStr  doxm data in json string.
- * @return pointer to OicSecDoxm_t.
+ * @param cborPayload is a doxm data in cbor.
+ * @note Caller needs to invoke OCFree after done using the return pointer.
+ * @param doxm is the pointer to @ref OicSecDoxm_t.
+ * @param size of the cborPayload. In case value is 0, CBOR_SIZE value is assigned.
  *
- * @note Caller needs to invoke OCFree after done
- *       using the return pointer
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
-OicSecDoxm_t * JSONToDoxmBin(const char * jsonStr);
+OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
+                                OicSecDoxm_t **doxm);
 
 /**
- * This method converts DOXM data into JSON format.
+ * This method converts DOXM data into CBOR format.
  * Caller needs to invoke 'free' when finished done using
- * return string
+ * return string.
  *
- * @param[in] doxm  Pointer to OicSecDoxm_t.
- * @return pointer to json string.
+ * @param doxm Pointer to @ref OicSecDoxm_t.
+ * @note Caller needs to invoke OCFree after done using the return pointer.
+ * @param cborPayload is the payload of the cbor.
+ * @param cborSize is the size of the cbor payload. Passed parameter should not be NULL.
  *
- * @note Caller needs to invoke OCFree after done
- *       using the return pointer
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
-char * BinToDoxmJSON(const OicSecDoxm_t * doxm);
+OCStackResult DoxmToCBORPayload(const OicSecDoxm_t * doxm, uint8_t **cborPayload,
+                                size_t *cborSize);
 
 /**
  * This method returns the SRM device ID for this device.
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID);
 
 /**
- * @brief Gets the OicUuid_t value for the owner of this device.
+ * Gets the OicUuid_t value for the owner of this device.
  *
- * @return OC_STACK_OK if devOwner is a valid UUID, otherwise OC_STACK_ERROR.
+ * @param devownerid a pointer to be assigned to the devownerid property
+ * @return ::OC_STACK_OK if devownerid is assigned correctly, else ::OC_STACK_ERROR.
  */
-OCStackResult GetDoxmDevOwnerId(OicUuid_t *devOwner);
+OCStackResult GetDoxmDevOwnerId(OicUuid_t *devownerid);
+
+/**
+ * Gets the OicUuid_t value for the rowneruuid of the doxm resource.
+ *
+ * @param rowneruuid a pointer to be assigned to the rowneruuid property
+ * @return ::OC_STACK_OK if rowneruuid is assigned correctly, else ::OC_STACK_ERROR.
+ */
+OCStackResult GetDoxmRownerId(OicUuid_t *rowneruuid);
 
 /** This function deallocates the memory for OicSecDoxm_t .
  *
- * @param[in] doxm  Pointer to OicSecDoxm_t.
+ * @param doxm is the pointer to @ref OicSecDoxm_t.
  */
 void DeleteDoxmBinData(OicSecDoxm_t* doxm);
 
+/**
+ * Function to restore doxm resurce to initial status.
+ * This function will use in case of error while ownership transfer
+ */
+void RestoreDoxmToInitState();
 
 #ifdef __cplusplus
 }
 #endif
 
 #endif //IOTVT_SRM_DOXMR_H
-
-
diff --git a/resource/csdk/security/include/internal/dpairingresource.h b/resource/csdk/security/include/internal/dpairingresource.h
new file mode 100644 (file)
index 0000000..c69c5e6
--- /dev/null
@@ -0,0 +1,118 @@
+/* *****************************************************************\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
+#ifndef IOTVT_SRM_DPAIRING_H\r
+#define IOTVT_SRM_DPAIRING_H\r
+\r
+#include "octypes.h"\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+/**\r
+ * Initialize DPAIRING resource by loading data from persistent storage.\r
+ *\r
+ * @retval  OC_STACK_OK for Success, otherwise some error value\r
+ */\r
+OCStackResult InitDpairingResource();\r
+\r
+/**\r
+ * Perform cleanup for DPAIRING resources.\r
+ *\r
+ * @retval  OC_STACK_OK for Success, otherwise some error value\r
+ */\r
+OCStackResult DeInitDpairingResource();\r
+\r
+/**\r
+ * This method converts CBOR DPAIRING into binary DPAIRING.\r
+ * The CBOR DPAIRING can be from persistent database or\r
+ * or received as POST request.\r
+ *\r
+ * @param cborPayload pconf data in cbor format.\r
+ * @param size size of the cbor payload\r
+ * @param secDpair binary Dpairing resource\r
+ * @return OC_STACK_OK for Success, otherwise some error value.\r
+ *\r
+ * @note Caller needs to invoke OICFree after done\r
+ *       using the return pointer\r
+ */\r
+OCStackResult CBORPayloadToDpair(const uint8_t *cborPayload, size_t size,\r
+        OicSecDpairing_t **secDpair);\r
+\r
+/**\r
+ * This method converts DPAIRING data into CBOR format.\r
+ *\r
+ * @param dpair  Pointer to OicSecDpairing_t.\r
+ * @param payload CBOR format converted from binary dpairing\r
+ * @param size Size of the coverted payload\r
+ * @return OC_STACK_OK for Success, otherwise some error value.\r
+ *\r
+ * @note Caller needs to invoke OICFree after done\r
+ *       using the return pointer\r
+ */\r
+OCStackResult DpairingToCBORPayload(const OicSecDpairing_t *dpair, uint8_t **payload, size_t *size);\r
+\r
+/** This function deallocates the memory for OicSecPconf_t .\r
+ *\r
+ * @param[in] dpair  Pointer to OicSecDpairing_t.\r
+ */\r
+void DeleteDpairingBinData(OicSecDpairing_t* dpair);\r
+\r
+#ifdef __WITH_DTLS__\r
+/**\r
+ * Function to save PairingPSK.\r
+ *\r
+ * @param[in] endpoint   current endpoint.\r
+ * @param[in] peerDevID   peer device indentitiy.\r
+ * @param[in] isPairingServer   indicate if it generates PairingPSK for server or client.\r
+ *\r
+ * @return  OC_STACK_OK on success\r
+ */\r
+OCStackResult SavePairingPSK(OCDevAddr *endpoint,\r
+            OicUuid_t *peerDevID, OicUuid_t *owner, bool isPairingServer);\r
+#endif // __WITH_DTLS__\r
+\r
+/**\r
+ * Gets the OicUuid_t value for the rownerid of the Dpairing resource.\r
+ *\r
+ * @param rowneruuid a pointer to be assigned to the rowneruuid property\r
+ * @return ::OC_STACK_OK if rowneruuid is assigned correctly, else ::OC_STACK_ERROR.\r
+ */\r
+OCStackResult GetDpairingRownerId(OicUuid_t *rowneruuid);\r
+\r
+/**\r
+ * Internal function to update resource owner\r
+ *\r
+ * @param newROwner new owner\r
+ *\r
+ * @retval ::OC_STACK_OK for Success, otherwise some error value\r
+ */\r
+OCStackResult SetDpairingRownerId(const OicUuid_t* newROwner);\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+#endif //IOTVT_SRM_DPAIRING_H\r
+\r
+\r
+\r
+\r
diff --git a/resource/csdk/security/include/internal/pconfresource.h b/resource/csdk/security/include/internal/pconfresource.h
new file mode 100644 (file)
index 0000000..4ad7baf
--- /dev/null
@@ -0,0 +1,144 @@
+/* *****************************************************************\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
+#ifndef IOTVT_SRM_PCONF_H\r
+#define IOTVT_SRM_PCONF_H\r
+\r
+#include "octypes.h"\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+/**\r
+ * Initialize PCONF resource by loading data from persistent storage.\r
+ *\r
+ * @retval  OC_STACK_OK for Success, otherwise some error value\r
+ */\r
+OCStackResult InitPconfResource();\r
+\r
+/**\r
+ * Perform cleanup for PCONF resources.\r
+ *\r
+ * @retval  OC_STACK_OK for Success, otherwise some error value\r
+ */\r
+OCStackResult DeInitPconfResource();\r
+\r
+/**\r
+ * This method is used by SRM to retrieve PCONF resource data..\r
+ *\r
+ * @retval  reference to @ref OicSecPconf_t, binary format of Pconf resource data\r
+ */\r
+const OicSecPconf_t* GetPconfResourceData();\r
+\r
+/**\r
+ * This method converts CBOR PCONF into binary PCONF.\r
+ * The JSON PCONF can be from persistent database or\r
+ * or received as PUT request.\r
+ *\r
+ * @param cborPayload  pconf data in cbor format.\r
+ * @param size cbor payload size\r
+ * @param secPconf converted pconf\r
+ * @return OC_STACK_OK for success.\r
+ *\r
+ * @note Caller needs to invoke OCFree after done\r
+ *       using the return pointer\r
+ */\r
+OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSecPconf_t **secPconf);\r
+\r
+/**\r
+ * This method converts PCONF data into CBOR format.\r
+ * Caller needs to invoke 'free' when finished done using\r
+ * return string\r
+ *\r
+ * @param pconf  Pointer to OicSecPconf_t.\r
+ * @param payload pconf converted in cbor format\r
+ * @param size size of the converted payload\r
+ * @return OC_STACK_OK for success.\r
+ *\r
+ * @note Caller needs to invoke OCFree after done\r
+ *       using the return pointer\r
+ */\r
+OCStackResult PconfToCBORPayload(const OicSecPconf_t *pconf,uint8_t **payload,size_t *size);\r
+\r
+/**\r
+ * This method might be used to add a paired device id after direct-pairing process complete.\r
+ *\r
+ * @param pdeviceId ID of the paired device.\r
+ *\r
+ * @retval  OC_STACK_OK for Success, otherwise some error value\r
+ */\r
+OCStackResult AddPairedDevice(OicUuid_t *pdeviceId);\r
+\r
+/**\r
+ * This method might be used by PolicyEngine to retrieve PDACL for a Subject.\r
+ *\r
+ * @param subjectId ID of the subject for which PDACL is required.\r
+ * @param savePtr is used internally by @ref GetACLResourceData to maintain index between\r
+ *                successive calls for same subjectId.\r
+ *\r
+ * @retval  reference to @ref OicSecPdAcl_t if PDACL is found, else NULL\r
+ */\r
+const OicSecPdAcl_t* GetPdAclData(const OicUuid_t* subjectId, OicSecPdAcl_t **savePtr);\r
+\r
+/**\r
+ * This method return whether device is paired or not.\r
+ *\r
+ * @param pdeviceId Target device ID to find in paired list.\r
+ * @retval  ture if device is already paired, else false\r
+ */\r
+bool IsPairedDevice(const OicUuid_t* pdeviceId);\r
+\r
+/** This function deallocates the memory for OicSecPconf_t .\r
+ *\r
+ * @param[in] pconf  Pointer to OicSecPconf_t.\r
+ */\r
+void DeletePconfBinData(OicSecPconf_t* pconf);\r
+\r
+/**\r
+ * This function frees OicSecPdAcl_t object's fields and object itself.\r
+ */\r
+void FreePdAclList(OicSecPdAcl_t* pdacls);\r
+\r
+/**\r
+ * Internal function to update resource owner\r
+ *\r
+ * @param newROwner new owner\r
+ *\r
+ * @retval ::OC_STACK_OK for Success, otherwise some error value\r
+ */\r
+OCStackResult SetPconfRownerId(const OicUuid_t* newROwner);\r
+\r
+/**\r
+ * Gets the OicUuid_t value for the rownerid of the pconf resource.\r
+ *\r
+ * @param rowneruuid a pointer to be assigned to the rowneruuid property\r
+ * @return ::OC_STACK_OK if rowneruuid is assigned correctly, else ::OC_STACK_ERROR.\r
+ */\r
+OCStackResult GetPconfRownerId(OicUuid_t *rowneruuid);\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+#endif //IOTVT_SRM_PCONF_H\r
+\r
+\r
+\r
index ba40d68..f28498e 100644 (file)
@@ -31,7 +31,6 @@
 
 typedef struct AmsMgrContext AmsMgrContext_t;
 
-
 typedef enum PEState
 {
     STOPPED = 0,              //Policy engine state machine is not running
@@ -40,12 +39,12 @@ typedef enum PEState
     BUSY                      //Can't process new request as processing other requests
 } PEState_t;
 
-
 typedef struct PEContext
 {
     PEState_t   state;
     OicUuid_t   subject;
     char        resource[MAX_URI_LENGTH];
+    OicSecSvrType_t resourceType;
     uint16_t    permission;
     bool        matchingAclFound;
     bool        amsProcessing;
@@ -56,13 +55,12 @@ typedef struct PEContext
 /**
  * Check whether a request should be allowed.
  *
- * @param   context     Pointer to Policy Engine context to use.
- * @param   subjectId   Pointer to Id of the requesting entity.
- * @param   resource    Pointer to URI of Resource being requested.
- * @param   permission  Requested permission.
+ * @param context is the pointer to Policy Engine context to use.
+ * @param subjectId is the pointer to Id of the requesting entity.
+ * @param resource is the pointer to URI of Resource being requested.
+ * @param permission is the requested permission.
  *
- * @return  ACCESS_GRANTED if request should go through,
- *          otherwise some flavor of ACCESS_DENIED
+ * @return ::ACCESS_GRANTED if request should go through, otherwise some flavor of ACCESS_DENIED.
  */
 SRMAccessResponse_t CheckPermission(
     PEContext_t     *context,
@@ -74,34 +72,38 @@ SRMAccessResponse_t CheckPermission(
  * Initialize the Policy Engine. Call this before calling CheckPermission().
  * TODO Eventually this and DeInit() need to be called from a new
  *      "SRMInit(SRMContext_t *)" function, TBD after BeachHead.
- * @param   context     Pointer to Policy Engine context to initialize.
- * @return  OC_STACK_OK for Success, otherwise some error value
+ * @param context is the pointer to Policy Engine context to initialize.
+ *
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult InitPolicyEngine(PEContext_t *context);
 
 /**
  * De-Initialize the Policy Engine. Call this before exiting to allow Policy
  * Engine to do cleanup on context.
- * @param   context     Pointer to Policy Engine context to de-initialize.
- * @return  none
+ *
+ * @param context is the pointer to Policy Engine context to de-initialize.
  */
 void DeInitPolicyEngine(PEContext_t *context);
 
 /**
- * Return the uint16_t CRUDN permission corresponding to passed CAMethod_t.
+ * Get CRUDN permission for a method.
+ *
+ * @param method is CRUDN permission being seeked.
+ *
+ * @return the uint16_t CRUDN permission .
  */
 uint16_t GetPermissionFromCAMethod_t(const CAMethod_t method);
 
-
 /*
  * This method reset Policy Engine context to default state and update
  * it's state to @param state.
  *
- * @param context  Policy engine context.
- * @param state    Set Policy engine state to this.
- *
- * @return         none
+ * @param context is the policy engine context.
+ * @param state set Policy engine state to this.
  */
 void SetPolicyEngineState(PEContext_t *context, const PEState_t state);
 
+typedef OCStackResult (*GetSvrRownerId_t)(OicUuid_t *rowner);
+
 #endif //IOTVT_SRM_PE_H
index b48c674..34a7822 100644 (file)
@@ -21,6 +21,8 @@
 #ifndef IOTVT_SRM_PSI_H
 #define IOTVT_SRM_PSI_H
 
+#include "cJSON.h"
+
 /**
  * Reads the Secure Virtual Database from PS into dynamically allocated
  * memory buffer.
@@ -28,7 +30,7 @@
  * @note Caller of this method MUST use OCFree() method to release memory
  *       referenced by return value.
  *
- * @retval  reference to memory buffer containing SVR database.
+ * @return char * reference to memory buffer containing SVR database.
  */
 char * GetSVRDatabase();
 
@@ -39,8 +41,34 @@ char * GetSVRDatabase();
  * @param rsrcName string denoting the SVR name ("acl", "cred", "pstat" etc).
  * @param jsonObj JSON object containing the SVR contents.
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @return ::OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult UpdateSVRDatabase(const char* rsrcName, cJSON* jsonObj);
 
+/**
+ * Reads the Secure Virtual Database from PS
+ *
+ * @note Caller of this method MUST use OCFree() method to release memory
+ *       referenced by return value.
+ *
+ * @param rsrcName is the name of the field for which file content are read.
+                   if the value is NULL it will send the content of the whole file.
+ * @param data is the pointer to the file contents read from the database.
+ * @param size is the size to the file contents read.
+ *
+ * @return ::OC_STACK_OK for Success, otherwise some error value
+ */
+OCStackResult GetSecureVirtualDatabaseFromPS(const char *rsrcName, uint8_t **data, size_t *size);
+
+/**
+ * This method converts updates the persistent storage.
+ *
+ * @param rsrcName is the name of the secure resource that will be updated.
+ * @param cborPayload is the pointer holding cbor payload.
+ * @param cborPayload is the size of the cbor payload.
+ *
+ * @return ::OC_STACK_OK for Success, otherwise some error value
+ */
+OCStackResult UpdateSecureResourceInPS(const char* rsrcName, uint8_t* cborPayload, size_t size);
+
 #endif //IOTVT_SRM_PSI_H
index 40c41ab..a36d142 100644 (file)
@@ -28,44 +28,80 @@ extern "C" {
 /**
  * Initialize Pstat resource by loading data from persistent storage.
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult InitPstatResource();
 
 /**
  * Perform cleanup for Pstat resources.
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult DeInitPstatResource();
 
 /**
- * This method converts JSON PSTAT into binary PSTAT.
+ * This method converts PSTAT into the cbor payload.
  *
- * @param[in] jsonStr  pstat data in json string.
- * @return pointer to OicSecPstat_t.
+ * @param pstat pointer to the initialized pstat structure.
+ * @param cborPayload pointer to pstat cbor payload.
+ * @param size of the cbor payload converted. It is 0 in case of error,
+ * else a positive value if succcessful.
+ *
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
-OicSecPstat_t * JSONToPstatBin(const char * jsonStr);
+ OCStackResult PstatToCBORPayload(const OicSecPstat_t *pstat, uint8_t **cborPayload,
+                                  size_t *cborSize);
 
 /**
- * This method converts pstat data into JSON format.
+ * This method converts cbor into PSTAT data.
  *
- * @param[in] pstat  pstat data in binary format.
- * @return pointer to pstat json string.
+ * @param cborPayload is the pstat data in cbor format.
+ * @param size of the cborPayload. In case 0 is provided it assigns CBOR_SIZE (255) value.
+ * @param pstat pointer to @ref OicSecPstat_t.
+  *
+  * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
-char * BinToPstatJSON(const OicSecPstat_t * pstat);
+ OCStackResult CBORPayloadToPstat(const uint8_t *cborPayload, const size_t cborSize,
+                                  OicSecPstat_t **pstat);
 
 /** This function deallocates the memory for OicSecPstat_t.
  *
- * @param[in] pstat  Pointer to OicSecPstat_t.
+ * @param pstat is the pointer to @ref OicSecPstat_t.
  */
 void DeletePstatBinData(OicSecPstat_t* pstat);
 
+/**
+ * Function to restore pstat resurce to initial status.
+ * This function will use in case of error while ownership transfer
+ */
+void RestorePstatToInitState();
+
+/**
+ * Internal function to update resource owner
+ *
+ * @param newROwner new owner
+ *
+ * @retval ::OC_STACK_OK for Success, otherwise some error value
+ */
+OCStackResult SetPstatRownerId(const OicUuid_t* newROwner);
+
+/**
+ * Gets the OicUuid_t value for the rownerid of the pstat resource.
+ *
+ * @param rowneruuid a pointer to be assigned to the rowneruuid property
+ * @return ::OC_STACK_OK if rowneruuid is assigned correctly, else ::OC_STACK_ERROR.
+ */
+OCStackResult GetPstatRownerId(OicUuid_t *rowneruuid);
+
+/**
+ * This function returns the "isop" status of the device.
+ *
+ * @return true iff pstat.isop == 1, else false
+ */
+bool GetPstatIsop();
 
 #ifdef __cplusplus
 }
 #endif
 
 #endif //IOTVT_SRM_PSTATR_H
-
-
index 3e946f5..a75cb7a 100644 (file)
 #include "ocstack.h"
 #include "securevirtualresourcetypes.h"
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 /**
  * Initialize all secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @return ::OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult InitSecureResources();
 
 /**
  * Perform cleanup for secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @return ::OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult DestroySecureResources();
 
@@ -44,13 +48,17 @@ OCStackResult DestroySecureResources();
  *
  * @param ehRequest pointer to entity handler request data structure.
  * @param ehRet result code from entity handler.
- * @param rspPayload response payload in JSON.
+ * @param cborPayload response payload.
+ * @param size is the cborpayload size
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult SendSRMResponse(const OCEntityHandlerRequest *ehRequest,
-        OCEntityHandlerResult ehRet, const char *rspPayload);
+        OCEntityHandlerResult ehRet, uint8_t *cborPayload, size_t size);
 
-#endif //IOTVT_SRM_RM_H
+#ifdef __cplusplus
+}
+#endif
 
+#endif //IOTVT_SRM_RM_H
 
index eb2643b..7976452 100644 (file)
@@ -28,83 +28,91 @@ extern "C" {
 #endif
 
 /**
- * @brief   Register Persistent storage callback.
- * @param   persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
- * @return
- *     OC_STACK_OK    - No errors; Success
- *     OC_STACK_INVALID_PARAM - Invalid parameter
+ * Register Persistent storage callback.
+ *
+ * @param  persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
+ *
+ * @return ::OC_STACK_OK  is no errors and successful. ::OC_STACK_INVALID_PARAM for invalid parameter.
  */
 OCStackResult SRMRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler);
 
 /**
- * @brief   Get Persistent storage handler pointer.
- * @return
- *     The pointer to Persistent Storage callback handler
+ * Get Persistent storage handler pointer.
+ *
+ * @return The pointer to Persistent Storage callback handler.
  */
 OCPersistentStorage* SRMGetPersistentStorageHandler();
 
 /**
- * @brief   Register request and response callbacks.
- *          Requests and responses are delivered in these callbacks.
- * @param   reqHandler   [IN] Request handler callback ( for GET,PUT ..etc)
- * @param   respHandler  [IN] Response handler callback.
- * @param   errHandler   [IN] Error handler callback.
- * @return
- *     OC_STACK_OK    - No errors; Success
- *     OC_STACK_INVALID_PARAM - Invalid parameter
+ * Register request and response callbacks. Requests and responses are delivered in these callbacks.
+ *
+ * @param reqHandler Request handler callback ( for GET,PUT ..etc)
+ * @param respHandler Response handler callback.
+ * @param errHandler Error handler callback.
+ *
+ * @return ::OC_STACK_OK  is no errors and successful. ::OC_STACK_INVALID_PARAM for invalid parameter.
  */
 OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
                                  CAResponseCallback respHandler,
                                  CAErrorCallback errHandler);
 
 /**
- * @brief   Initialize all secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
- * @return  OC_STACK_OK for Success, otherwise some error value
+ * Initialize all secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
+ * @return  ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult SRMInitSecureResources();
 
 /**
- * @brief   Perform cleanup for secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
- * @return  none
+ * Perform cleanup for secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
  */
 void SRMDeInitSecureResources();
 
 /**
- * @brief   Initialize Policy Engine context.
- * @return  OC_STACK_OK for Success, otherwise some error value.
+ * Initialize Policy Engine context.
+ *
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult SRMInitPolicyEngine();
 
 /**
- * @brief   Cleanup Policy Engine context.
- * @return  none
+ * Cleanup Policy Engine context.
  */
 void SRMDeInitPolicyEngine();
 
 /**
- * @brief   Provisioning API response callback.
- * @param object[IN]       endpoint instance.
- * @param responseInfo[IN] instance of CAResponseInfo_t structure.
+ * Provisioning API response callback.
+ *
+ * @param object endpoint instance.
+ * @param responseInfo instance of CAResponseInfo_t structure.
+ *
  * @return true if received response is for provisioning API false otherwise.
  */
 typedef bool (*SPResponseCallback) (const CAEndpoint_t *object,
                                     const CAResponseInfo_t *responseInfo);
 
 /**
- * @brief function to register provisoning API's response callback.
+ * Function to register provisoning API's response callback.
+ *
  * @param respHandler response handler callback.
  */
 void SRMRegisterProvisioningResponseHandler(SPResponseCallback respHandler);
 
 /**
- * @brief   Check the security resource URI.
- * @param   uri [IN] Pointers to security resource URI.
- * @return  true if the URI is one of security resources, otherwise false.
+ * Check the security resource URI.
+ * @param uri Pointers to security resource URI.
+ * @return true if the URI is one of security resources, otherwise false.
  */
 bool SRMIsSecurityResourceURI(const char* uri);
 
 /**
- * @brief   Sends Response
+ * Get the resource type from the URI.
+ * @param   uri [IN] Pointers to security resource URI.
+ * @return  SVR type (note that "NOT_A_SVR_RESOURCE" is returned if not a SVR)
+ */
+OicSecSvrType_t GetSvrTypeFromUri(const char* uri);
+
+/**
+ * Sends Response
  * @param   resposeVal       SRMAccessResponse_t value
  * @return  NONE
  */
diff --git a/resource/csdk/security/include/internal/security_internals.h b/resource/csdk/security/include/internal/security_internals.h
new file mode 100644 (file)
index 0000000..13030d9
--- /dev/null
@@ -0,0 +1,135 @@
+//******************************************************************
+//
+//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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#ifndef IOTVT_SRM_SECURITY_INTERNALS_H
+#define IOTVT_SRM_SECURITY_INTERNALS_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+OicSecAcl_t* CBORPayloadToAcl(const uint8_t *payload, const size_t size);
+
+void DeleteACLList(OicSecAcl_t* acl);
+
+/**
+ * This internal method is to retrieve the default ACL.
+ * If SVR database in persistent storage got corrupted or
+ * is not available for some reason, a default ACL is created
+ * which allows user to initiate ACL provisioning again.
+ */
+OCStackResult  GetDefaultACL(OicSecAcl_t** defaultAcl);
+
+/**
+ * This internal method is the entity handler for ACL resources and
+ * will handle REST request (GET/PUT/POST/DEL) for them.
+ */
+OCEntityHandlerResult ACLEntityHandler(OCEntityHandlerFlag flag,
+            OCEntityHandlerRequest * ehRequest, void* callbackParameter);
+
+OCStackResult SetDefaultACL(OicSecAcl_t *acl);
+
+/**
+ * Converts CBOR payload to SVC.
+ *
+ * @param cborPayload is the svc payload cbor value that neds to be converted.
+ * @param cborSize of the cborPayload. In case size is not known, it is 0.
+ * @param svc is the value that is initialized. It is NULL in case of error.
+ *
+ * @return ::OC_STACK_OK in case successful. ::OC_STACK_INVALID_PARAM if one of
+ * the passed parameter is NULL. ::OC_STACK_ERROR in case of error.
+ */
+OCStackResult CBORPayloadToSVC(const uint8_t *cborPayload, size_t size, OicSecSvc_t **svc);
+
+/**
+ * Deletes the passed initialized reference to @ref OicSecSvc_t.
+ *
+ * @param svc is the reference to be deleted.
+ */
+void DeleteSVCList(OicSecSvc_t* svc);
+
+/**
+ * Create PSTAT resource after default PSTAT initialization is done.
+ */
+OCStackResult CreatePstatResource();
+
+/**
+ * This internal method is the entity handler for PSTAT resources and
+ * will handle REST request (GET/PUT/POST/DEL) for them.
+ */
+OCEntityHandlerResult PstatEntityHandler(OCEntityHandlerFlag flag,
+                                         OCEntityHandlerRequest * ehRequest);
+
+/**
+ * Converts CBOR payload to AMACL.
+ *
+ * @param cborPayload is the amacl payload cbor value that neds to be converted.
+ * @param cborSize of the cborPayload. In case size is not known, it is 0.
+ * It should be NON-NULL.
+ * @param amacl is the value that is initialized. It is NULL in case of error.
+ */
+OCStackResult CBORPayloadToAmacl(const uint8_t *cborPayload, size_t cborSize,
+                                 OicSecAmacl_t **amacl);
+
+void DeleteAmaclList(OicSecAmacl_t *amacl);
+
+/**
+ * This internal method is the entity handler for Cred resources
+ * to handle REST request (PUT/POST/DEL)
+ */
+OCEntityHandlerResult CredEntityHandler(OCEntityHandlerFlag flag,
+                                        OCEntityHandlerRequest * ehRequest,
+                                        void* callbackParameter);
+
+/**
+ * This internal method is used to create '/oic/sec/Cred' resource.
+ */
+OCStackResult CreateCredResource();
+
+/**
+ * This function converts from CBOR format into credential structure .
+ * Caller needs to invoke 'free' for allocated structure.
+ *
+ * @param cborPayload is the CBOR value that is assigned to the structure.
+ * @param size is the size of the CBOR.
+ * @param secCred is the pointer to instance of @ref OicSecCred_t structure that will be allocated.
+ * If it fails it will return NULL.
+ *
+ * @return ::OC_STACK_OK if conversion is successful, else ::OC_STACK_ERROR if unsuccessful.
+ */
+OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
+                                OicSecCred_t **secCred);
+
+/**
+ * This internal method is used to create '/oic/sec/doxm' resource.
+ */
+OCStackResult CreateDoxmResource();
+
+/**
+ * This internal method is the entity handler for DOXM resources.
+ */
+OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
+                                        OCEntityHandlerRequest * ehRequest,
+                                        void* callbackParam);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //IOTVT_SRM_SECURITY_INTERNALS_H
old mode 100755 (executable)
new mode 100644 (file)
index 1ac3fb0..c1900ac
@@ -24,6 +24,7 @@
 #include "securevirtualresourcetypes.h"
 
 extern const char * SVR_DB_FILE_NAME;
+extern const char * SVR_DB_DAT_FILE_NAME;
 extern const char * OIC_MI_DEF;
 
 //AMACL
@@ -35,6 +36,8 @@ extern const char * OIC_JSON_AMACL_NAME;
 extern const char * OIC_RSRC_TYPE_SEC_ACL;
 extern const char * OIC_RSRC_ACL_URI;
 extern const char * OIC_JSON_ACL_NAME;
+extern const char * OIC_JSON_ACLIST_NAME;
+extern const char * OIC_JSON_ACES_NAME;
 
 //PSTAT
 extern const char * OIC_RSRC_TYPE_SEC_PSTAT;
@@ -51,25 +54,50 @@ extern const char * OIC_JSON_DOXM_NAME;
 extern const char * OIC_RSRC_TYPE_SEC_CRED;
 extern const char * OIC_RSRC_CRED_URI;
 extern const char * OIC_JSON_CRED_NAME;
+extern const char * OIC_JSON_CREDS_NAME;
 
 //CRL
 extern const char * OIC_RSRC_TYPE_SEC_CRL;
 extern const char * OIC_RSRC_CRL_URI;
 extern const char * OIC_JSON_CRL_NAME;
 
+//SACL
+extern const char * OIC_RSRC_TYPE_SEC_SACL;
+extern const char * OIC_RSRC_SACL_URI;
+extern const char * OIC_JSON_SACL_NAME;
+
 //SVC
 extern const char * OIC_RSRC_TYPE_SEC_SVC;
 extern const char * OIC_RSRC_SVC_URI;
 extern const char * OIC_JSON_SVC_NAME;
 
+//PCONF
+extern const char * OIC_RSRC_TYPE_SEC_PCONF;
+extern const char * OIC_RSRC_PCONF_URI;
+extern const char * OIC_JSON_PCONF_NAME;
+
+//DPAIRING
+extern const char * OIC_RSRC_TYPE_SEC_DPAIRING;
+extern const char * OIC_RSRC_DPAIRING_URI;
+extern const char * OIC_JSON_DPAIRING_NAME;
+
+//version
+extern const char * OIC_RSRC_TYPE_SEC_VER;
+extern const char * OIC_RSRC_VER_URI;
+extern const char * OIC_JSON_VER_NAME;
+
 extern const char * OIC_JSON_SUBJECT_NAME;
+extern const char * OIC_JSON_SUBJECTID_NAME;
 extern const char * OIC_JSON_RESOURCES_NAME;
 extern const char * OIC_JSON_AMSS_NAME;
+extern const char * OIC_JSON_AMS_NAME;
 extern const char * OIC_JSON_PERMISSION_NAME;
 extern const char * OIC_JSON_OWNERS_NAME;
 extern const char * OIC_JSON_OWNER_NAME;
+extern const char * OIC_JSON_DEVOWNERID_NAME;
 extern const char * OIC_JSON_OWNED_NAME;
 extern const char * OIC_JSON_OXM_NAME;
+extern const char * OIC_JSON_OXMS_NAME;
 extern const char * OIC_JSON_OXM_TYPE_NAME;
 extern const char * OIC_JSON_OXM_SEL_NAME;
 extern const char * OIC_JSON_DEVICE_ID_FORMAT_NAME;
@@ -78,6 +106,10 @@ extern const char * OIC_JSON_ROLEIDS_NAME;
 extern const char * OIC_JSON_CREDTYPE_NAME;
 extern const char * OIC_JSON_PUBLICDATA_NAME;
 extern const char * OIC_JSON_PRIVATEDATA_NAME;
+extern const char * OIC_JSON_PUBDATA_NAME;
+extern const char * OIC_JSON_PRIVDATA_NAME;
+extern const char * OIC_JSON_OPTDATA_NAME;
+extern const char * OIC_JSON_CRMS_NAME;
 extern const char * OIC_JSON_PERIOD_NAME;
 extern const char * OIC_JSON_PERIODS_NAME;
 extern const char * OIC_JSON_RECURRENCES_NAME;
@@ -91,8 +123,29 @@ extern const char * OIC_JSON_SM_NAME;
 extern const char * OIC_JSON_SERVICE_DEVICE_ID;
 extern const char * OIC_JSON_SERVICE_TYPE;
 extern const char * OIC_JSON_SUPPORTED_CRED_TYPE_NAME;
+extern const char * OIC_JSON_DPC_NAME;
+extern const char * OIC_JSON_EDP_NAME;
+extern const char * OIC_JSON_PIN_NAME;
+extern const char * OIC_JSON_PDACL_NAME;
+extern const char * OIC_JSON_PDDEV_LIST_NAME;
+extern const char * OIC_JSON_ROWNER_NAME;
+extern const char * OIC_JSON_PRM_NAME;
+extern const char * OIC_JSON_SPM_NAME;
+extern const char * OIC_JSON_PDEVICE_ID_NAME;
+extern const char * OIC_JSON_RLIST_NAME;
+extern const char * OIC_JSON_HREF_NAME;
+extern const char * OIC_JSON_REL_NAME;
+extern const char * OIC_JSON_RT_NAME;
+extern const char * OIC_JSON_IF_NAME;
+extern const char * OIC_JSON_ROWNERID_NAME;
+extern const char * OIC_JSON_ENCODING_NAME;
+extern const char * OIC_JSON_DATA_NAME;
+extern const char * OIC_JSON_SEC_V_NAME;
+
+extern const char * OIC_JSON_EMPTY_STRING;
 
 extern OicUuid_t WILDCARD_SUBJECT_ID;
+extern OicUuid_t WILDCARD_SUBJECT_B64_ID;
 extern size_t WILDCARD_SUBJECT_ID_LEN;
 extern const char * WILDCARD_RESOURCE_URI;
 
@@ -101,11 +154,17 @@ extern const char * OXM_JUST_WORKS;
 extern const char * OXM_RANDOM_DEVICE_PIN;
 extern const char * OXM_MANUFACTURER_CERTIFICATE;
 
+extern const char * OIC_SEC_ENCODING_BASE64;
+extern const char * OIC_SEC_ENCODING_RAW;
+
 extern const char * OIC_SEC_TRUE;
 extern const char * OIC_SEC_FALSE;
 
 extern const char * OIC_SEC_REST_QUERY_SEPARATOR;
 extern char OIC_SEC_REST_QUERY_DELIMETER;
 
+//Security Version
+extern const char * DEFAULT_SEC_VERSION;
+
 #endif //IOTVT_SRM_RSRC_STRINGS_H
 
index 9db42c5..ce759f8 100644 (file)
@@ -28,31 +28,33 @@ extern "C" {
 /**
  * Initialize SVC resource by loading data from persistent storage.
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult InitSVCResource();
 
 /**
  * Perform cleanup for SVC resources.
- *
- * @retval  none
  */
 void DeInitSVCResource();
 
 /**
- * This function converts SVC data into JSON format.
- * Caller needs to invoke 'free' when done using
- * returned string.
- * @param svc  instance of OicSecSvc_t structure.
+ * This function converts SVC data into CBOR format.
+ * Caller needs to invoke 'free' when done using returned string.
+ *
+ * @param svc is the instance of @ref OicSecSvc_t structure. In case of NULL it
+ * will return ::OC_STACK_INVALID_PARAM.
+ * @param cborPayload is the converted cbor value of SVC structure.
+ * @param cborSize is the size of the cbor payload. This value is the size of the
+ * cborPayload. It should not be NON-NULL value.
  *
- * @retval  pointer to SVC in json format.
+ * @return ::OC_STACK_OK for Success. ::OC_STACK_INVALID in case of invalid parameters.
+ * ::OC_STACK_ERROR in case of error in converting to cbor.
  */
-char* BinToSvcJSON(const OicSecSvc_t * svc);
+ OCStackResult SVCToCBORPayload(const OicSecSvc_t *svc, uint8_t **cborPayload,
+                                size_t *cborSize);
 
 #ifdef __cplusplus
 }
 #endif
 
 #endif //IOTVT_SRM_SVCR_H
-
-
diff --git a/resource/csdk/security/include/internal/verresource.h b/resource/csdk/security/include/internal/verresource.h
new file mode 100644 (file)
index 0000000..18fa03d
--- /dev/null
@@ -0,0 +1,98 @@
+/* *****************************************************************
+ *
+ * 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.
+ *
+ * *****************************************************************/
+
+#ifndef IOTVT_SRM_VER_H
+#define IOTVT_SRM_VER_H
+
+#include "octypes.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * Initialize VER resource by loading data from persistent storage.
+ *
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
+ */
+OCStackResult InitVerResource();
+
+/**
+ * Perform cleanup for VER resources.
+ *
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
+ */
+OCStackResult DeInitVerResource();
+
+/**
+ * This method is used by SRM to retrieve VER resource data..
+ *
+ * @return reference to @ref OicSecDoxm_t, binary format of Doxm resource data.
+ */
+const OicSecVer_t* GetVerResourceData();
+
+/**
+ * This method converts CBOR VER into binary VER.
+ * The CBOR VER can be from persistent database or
+ * or received as PUT/POST request.
+ *
+ * @param cborPayload is a ver data in cbor.
+ * @note Caller needs to invoke OCFree after done using the return pointer.
+ * @param doxm is the pointer to @ref OicSecVer_t.
+ * @param size of the cborPayload. In case value is 0, CBOR_SIZE value is assigned.
+ *
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
+ */
+OCStackResult CBORPayloadToVer(const uint8_t *cborPayload, size_t size,
+                                OicSecVer_t **ver);
+
+/**
+ * This method converts VER data into CBOR format.
+ * Caller needs to invoke 'free' when finished done using
+ * return string.
+ *
+ * @param ver Pointer to @ref OicSecVer_t.
+ * @note Caller needs to invoke OCFree after done using the return pointer.
+ * @param cborPayload is the payload of the cbor.
+ * @param cborSize is the size of the cbor payload. Passed parameter should not be NULL.
+ *
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
+ */
+OCStackResult VerToCBORPayload(const OicSecVer_t * ver, uint8_t **cborPayload,
+                                size_t *cborSize);
+
+/**
+ * Get the security version.
+ *
+ * @return the version string of security.
+ */
+const char* GetSecVersion();
+
+/** This function deallocates the memory for OicSecVer_t .
+ *
+ * @param ver is the pointer to @ref OicSecVer_t.
+ */
+void DeleteVerBinData(OicSecVer_t* ver);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //IOTVT_SRM_VER_H
\ No newline at end of file
index 2d77be0..1fec23e 100644 (file)
@@ -43,8 +43,8 @@ extern "C"
 typedef struct IotvtICalRecur IotvtICalRecur_t;
 typedef struct IotvtICalPeriod IotvtICalPeriod_t;
 
-/*
- *  date-time  = date "T" time
+/**
+ *  date-time  = date "T" time.
  *
  *  date               = date-value
  *  date-value         = date-fullyear date-month date-mday
@@ -65,8 +65,8 @@ typedef struct IotvtICalPeriod IotvtICalPeriod_t;
  */
 typedef struct tm IotvtICalDateTime_t; //c-lang tm date-time struct
 
-/*
- * Bit mask for weekdays
+/**
+ * Bit mask for weekdays.
  */
 typedef enum
 {
@@ -78,24 +78,24 @@ typedef enum
     THURSDAY    = (0x1 << 4),
     FRIDAY      = (0x1 << 5),
     SATURDAY    = (0x1 << 6)
-}IotvtICalWeekdayBM_t;
+} IotvtICalWeekdayBM_t;
 
-/*
- * Result code for IotvtICalendar
+/**
+ * Result code for IotvtICalendar.
  */
 typedef enum
 {
-    IOTVTICAL_SUCCESS = 0,       //successfully completed operation
-    IOTVTICAL_VALID_ACCESS,      //access is within allowable time
-    IOTVTICAL_INVALID_ACCESS,    //access is not within allowable time
-    IOTVTICAL_INVALID_PARAMETER, //invalid method parameter
-    IOTVTICAL_INVALID_RRULE,     //rrule is not well form, missing FREQ
-    IOTVTICAL_INVALID_PERIOD,    //period is not well form, start-datetime is after end-datetime
-    IOTVTICAL_ERROR              //encounter error
-}IotvtICalResult_t;
+    IOTVTICAL_SUCCESS = 0,       /**< successfully completed operation. */
+    IOTVTICAL_VALID_ACCESS,      /**< access is within allowable time. */
+    IOTVTICAL_INVALID_ACCESS,    /**< access is not within allowable time. */
+    IOTVTICAL_INVALID_PARAMETER, /**< invalid method parameter. */
+    IOTVTICAL_INVALID_RRULE,     /**< rrule is not well form, missing FREQ. */
+    IOTVTICAL_INVALID_PERIOD,    /**< period is not well form, start-datetime is after end-datetime. */
+    IOTVTICAL_ERROR              /**< encounter error. */
+} IotvtICalResult_t;
 
-/*
- *  Grammar for iCalendar data type PERIOD
+/**
+ *  Grammar for iCalendar data type PERIOD.
  *
  *  period = date-time "/" date-time  ; start-time / end-time.
  *                                    ;The start-time MUST be before the end-time.
@@ -108,7 +108,7 @@ struct IotvtICalPeriod
 };
 
 /*
- * Grammar for iCalendar data type RECUR
+ * Grammar for iCalendar data type RECUR.
  *
  * recur      = "FREQ"=freq *(
  *            ( ";" "UNTIL" "=" enddate ) /
@@ -143,11 +143,11 @@ struct IotvtICalRecur
  * @param period string representing period.
  * @param recur string representing recurrence rule
  *
- * @return  IOTVTICAL_VALID_ACCESS      -- if the request is within valid time period
- *          IOTVTICAL_INVALID_ACCESS    -- if the request is not within valid time period
- *          IOTVTICAL_INVALID_PARAMETER -- if parameter are invalid
- *          IOTVTICAL_INVALID_PERIOD    -- if period string has invalid format
- *          IOTVTICAL_INVALID_RRULE     -- if rrule string has invalid format
+ * @return ::IOTVTICAL_VALID_ACCESS, if the request is within valid time period
+ * ::IOTVTICAL_INVALID_ACCESS, if the request is not within valid time period
+ * ::IOTVTICAL_INVALID_PARAMETER, if parameter are invalid
+ * ::IOTVTICAL_INVALID_PERIOD, if period string has invalid format
+ * ::IOTVTICAL_INVALID_RRULE, if rrule string has invalid format.
  *
  *Eg: if(IOTVTICAL_VALID_ACCESS == IsRequestWithinValidTime(period, recur))
  *    {
@@ -158,29 +158,31 @@ struct IotvtICalRecur
  *      //Access is not within allowable time.
  *    }
  */
-IotvtICalResult_t IsRequestWithinValidTime(char *period, char *recur);
+IotvtICalResult_t IsRequestWithinValidTime(const char *period, const char *recur);
 
 /**
- * Parses periodStr and populate struct IotvtICalPeriod_t
+ * Parses periodStr and populate struct IotvtICalPeriod_t.
  *
  * @param periodStr string to be parsed.
- * @param period    IotvtICalPeriod_t struct to be populated.
+ * @param period IotvtICalPeriod_t struct to be populated.
  *
- * @return  IOTVTICAL_INVALID_PARAMETER -- if parameter are invalid
- *          IOTVTICAL_INVALID_PERIOD    -- if period string has invalid format
- *          IOTVTICAL_INVALID_SUCCESS   -- if no error while parsing
+ * @return ::IOTVTICAL_VALID_ACCESS, if the request is within valid time period
+ * ::IOTVTICAL_INVALID_PARAMETER, if parameter are invalid
+ * ::IOTVTICAL_INVALID_PERIOD, if period string has invalid format
+ * ::IOTVTICAL_INVALID_SUCCESS, if no error while parsing.
  */
 IotvtICalResult_t ParsePeriod(const char *periodStr, IotvtICalPeriod_t *period);
 
 /**
- * Parses recurStr and populate struct IotvtICalRecur_t
+ * Parses recurStr and populate struct IotvtICalRecur_t.
  *
  * @param recurStr string to be parsed.
- * @param recur    IotvtICalPeriod_t struct to be populated.
+ * @param recur is the IotvtICalPeriod_t struct to be populated.
  *
- * @return  IOTVTICAL_INVALID_PARAMETER -- if parameter are invalid
- *          IOTVTICAL_INVALID_PERIOD    -- if period string has invalid format
- *          IOTVTICAL_INVALID_RRULE     -- if rrule string has invalid format
+ * @return ::IOTVTICAL_VALID_ACCESS, if the request is within valid time period
+ * ::IOTVTICAL_INVALID_PARAMETER, if parameter are invalid
+ * ::IOTVTICAL_INVALID_PERIOD, if period string has invalid format
+ * ::IOTVTICAL_INVALID_RRULE, if rrule string has invalid format.
  */
 IotvtICalResult_t ParseRecur(const char *recurStr, IotvtICalRecur_t *recur);
 
index ff2e3e5..2957db8 100644 (file)
@@ -1,22 +1,22 @@
-/*****************************************************************
- *
- * 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.
- *
- * *****************************************************************/
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #ifndef _PBKDF2_H
 #define _PBKDF2_H
@@ -39,14 +39,14 @@ extern "C"
  * Function to derive cryptographic key from the password. (RFC 2898)
  * In this implementation, HMAC with SHA2 is considered as a pseudorandom function
  *
- * @param[in] passwd is the master password from which a derived key is generated.
- * @param[in] pLen is the byte size of the passwd.
- * @param[in] salt is a cryptographic salt.
- * @param[in] saltlen is the byte size of the salt.
- * @param[in] iteration is the number of iterations desired.
- * @param[in] keyLen is the desired byte size of the derived key. (should be the same as
+ * @param passwd is the master password from which a derived key is generated.
+ * @param pLen is the byte size of the passwd.
+ * @param salt is a cryptographic salt.
+ * @param saltlen is the byte size of the salt.
+ * @param iteration is the number of iterations desired.
+ * @param keyLen is the desired byte size of the derived key. (should be the same as
  *       derivedKey size)
- * @param[out] derivedKey is the generated derived key
+ * @param derivedKey is the generated derived key
  *
  * @return  0 on success
  */
index b4658ad..67f07ac 100644 (file)
@@ -1,26 +1,29 @@
-/*****************************************************************
- *
- * 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.
- *
- * *****************************************************************/
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #ifndef PIN_CALLBACK_DEF_H_
 #define PIN_CALLBACK_DEF_H_
 
+#include "securevirtualresourcetypes.h"
+#include "casecurityinterface.h"
+
 #ifdef __cplusplus
  extern "C" {
 #endif // __cplusplus
 #define OXM_RANDOM_PIN_SIZE 8
 
 /**
- * Function pointer to print pin code
+ * Function pointer to print pin code.
  */
 typedef void (*GeneratePinCallback)(char* pinData, size_t pinSize);
 
 /**
- * Function pointer to input pin code
+ * Function pointer to input pin code.
  */
 typedef void (*InputPinCallback)(char* pinBuf, size_t bufSize);
 
 /**
- * Function to setting generate PIN callback from user
+ * Function to setting generate PIN callback from user.
  *
- * @param[in] pinCB implementation of generate PIN callback
+ * @param pinCB implementation of generate PIN callback.
  */
 void SetGeneratePinCB(GeneratePinCallback pinCB);
 
 /**
- * Function to setting input PIN callback from user
+ * Function to setting input PIN callback from user.
  *
- * @param[in] pinCB implementation of input PIN callback
+ * @param pinCB implementation of input PIN callback.
  */
 void SetInputPinCB(InputPinCallback pinCB);
 
@@ -55,21 +58,49 @@ void SetInputPinCB(InputPinCallback pinCB);
  * Function to generate random PIN.
  * This function will send generated PIN to user via callback.
  *
- * @param[in,out] pinBuffer   Buffer to store the generated PIN data.
- * @param[in] bufferSize   Size of buffer
- * @return OC_STACK_SUCCESS in case of success and other value otherwise.
+ * @param pinBuffer is the reference to the buffer to store the generated PIN data.
+ * @param bufferSize is the size of buffer.
+ *
+ * @return ::OC_STACK_SUCCESS in case of success or other value in case of error.
  */
 OCStackResult GeneratePin(char* pinBuffer, size_t bufferSize);
 
 /**
- * Function to input PIN callback via input callback
+ * Function to input PIN callback via input callback.
  *
- * @param[in,out] pinBuffer Buffer to store the inputed PIN data.
- * @param[in] bufferSize Size of buffer
- * @return OC_STACK_SUCCESS in case of success and other value otherwise.
+ * @param[in,out] pinBuffer is the reference to the buffer to store the inputed PIN data.
+ * @param[in] bufferSize is the size of buffer.
+ *
+ * @return ::OC_STACK_SUCCESS in case of success or other value in ccase of error.
  */
 OCStackResult InputPin(char* pinBuffer, size_t bufferSize);
 
+#ifdef __WITH_DTLS__
+
+/**
+ * This function is used by OTM and SRM to
+ * register device UUID is required to derive the temporal PSK.
+ */
+void SetUuidForRandomPinOxm(const OicUuid_t* uuid);
+
+/**
+ * This internal callback is used while PIN based ownership transfer.
+ * This callback will be used to establish a temporary secure session according to
+ * TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256.
+ *
+ * @param[in]  type type of PSK data required by tinyDTLS layer during DTLS handshake.
+ * @param[in]  desc UNUSED.
+ * @param[in]  desc_len UNUSED.
+ * @param[out] result  Must be filled with the requested information.
+ * @param[in]  result_length  Maximum size of @p result.
+ *
+ * @return The number of bytes written to @p result or a value
+ *         less than zero on error.
+ */
+int32_t GetDtlsPskForRandomPinOxm( CADtlsPskCredType_t type,
+              const unsigned char *UNUSED1, size_t UNUSED2,
+              unsigned char *result, size_t result_length);
+#endif //__WITH_DTLS__
 
 #ifdef __cplusplus
 }
old mode 100755 (executable)
new mode 100644 (file)
index 83dc60f..786658e
@@ -52,8 +52,8 @@ extern "C" {
 #endif
 
 /**
- * @brief   Values used to create bit-maskable enums for single-value
- *          response with embedded code.
+ * Values used to create bit-maskable enums for single-value response with
+ * embedded code.
  */
 #define ACCESS_GRANTED_DEF            (1 << 0)
 #define ACCESS_DENIED_DEF             (1 << 1)
@@ -189,8 +189,8 @@ typedef enum OSCTBitmask
 } OSCTBitmask_t;
 
 /**
- * @brief   /oic/sec/credtype (Credential Type) data type.
- *          Derived from OIC Security Spec /oic/sec/cred; see Spec for details.
+ * /oic/sec/credtype (Credential Type) data type.
+ * Derived from OIC Security Spec /oic/sec/cred; see Spec for details.
  *              0:  no security mode
  *              1:  symmetric pair-wise key
  *              2:  symmetric group key
@@ -239,13 +239,29 @@ typedef enum
 
 typedef enum
 {
+    OIC_R_ACL_TYPE = 0,
+    OIC_R_AMACL_TYPE,
+    OIC_R_CRED_TYPE,
+    OIC_R_CRL_TYPE,
+    OIC_R_DOXM_TYPE,
+    OIC_R_DPAIRING_TYPE,
+    OIC_R_PCONF_TYPE,
+    OIC_R_PSTAT_TYPE,
+    OIC_R_SACL_TYPE,
+    OIC_R_SVC_TYPE,
+    OIC_SEC_SVR_TYPE_COUNT, //define the value to number of SVR
+    NOT_A_SVR_RESOURCE = 99
+}OicSecSvrType_t;
+
+typedef enum
+{
     OIC_JUST_WORKS                          = 0x0,
     OIC_RANDOM_DEVICE_PIN                   = 0x1,
     OIC_MANUFACTURER_CERTIFICATE           = 0x2,
     OIC_OXM_COUNT
 }OicSecOxm_t;
 
-typedef struct OicSecJwk OicSecJwk_t;
+typedef struct OicSecKey OicSecKey_t;
 
 typedef struct OicSecPstat OicSecPstat_t;
 
@@ -262,10 +278,13 @@ typedef struct OicUuid OicUuid_t; //TODO is UUID type defined elsewhere?
 
 #ifdef __WITH_X509__
 typedef struct OicSecCrl OicSecCrl_t;
+typedef ByteArray OicSecCert_t;
+#else
+typedef void OicSecCert_t;
 #endif /* __WITH_X509__ */
 
 /**
- * @brief   /oic/uuid (Universal Unique Identifier) data type.
+ * /oic/uuid (Universal Unique Identifier) data type.
  */
 #define UUID_LENGTH 128/8 // 128-bit GUID length
 //TODO: Confirm the length and type of ROLEID.
@@ -281,18 +300,19 @@ struct OicUuid
 };
 
 /**
- * @brief   /oic/sec/jwk (JSON Web Key) data type.
- *          See JSON Web Key (JWK)  draft-ietf-jose-json-web-key-41
+ * /oic/sec/jwk (JSON Web Key) data type.
+ * See JSON Web Key (JWK)  draft-ietf-jose-json-web-key-41
  */
 #define JWK_LENGTH 256/8 // 256 bit key length
-struct OicSecJwk
+struct OicSecKey
 {
-    char                *data;
+    uint8_t                *data;
+    size_t                  len;
 };
 
 /**
- * @brief   /oic/sec/acl (Access Control List) data type.
- *          Derived from OIC Security Spec; see Spec for details.
+ * /oic/sec/acl (Access Control List) data type.
+ * Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecAcl
 {
@@ -306,19 +326,13 @@ struct OicSecAcl
     size_t              prdRecrLen;     // the number of elts in Periods
     char                **periods;       // 3:R:M*:N:String (<--M*; see Spec)
     char                **recurrences;   // 5:R:M:N:String
-    size_t              ownersLen;      // the number of elts in Owners
-    OicUuid_t           *owners;        // 8:R:M:Y:oic.uuid
-    // NOTE: we are using UUID for Owners instead of Svc type for mid-April
-    // SRM version only; this will change to Svc type for full implementation.
-    //TODO change Owners type to oic.sec.svc
-    //OicSecSvc_t         *Owners;        // 6:R:M:Y:oic.sec.svc
+    OicUuid_t           rownerID;        // 8:R:S:Y:oic.uuid
     OicSecAcl_t         *next;
 };
 
 /**
- * @brief   /oic/sec/amacl (Access Manager Service Accesss Control List)
- *          data type.
- *          Derived from OIC Security Spec; see Spec for details.
+ * /oic/sec/amacl (Access Manager Service Accesss Control List) data type.
+ * Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecAmacl
 {
@@ -327,18 +341,13 @@ struct OicSecAmacl
     char                **resources;    // 0:R:M:Y:String
     size_t              amssLen;        // the number of elts in Amss
     OicUuid_t           *amss;          // 1:R:M:Y:acl
-    size_t              ownersLen;      // the number of elts in Owners
-    OicUuid_t           *owners;        // 2:R:M:Y:oic.uuid
-    // NOTE: we are using UUID for Owners instead of Svc type for mid-April
-    // SRM version only; this will change to Svc type for full implementation.
-    //TODO change Owners type to oic.sec.svc
-    //OicSecSvc_t         *Owners;        // 2:R:M:Y:oic.sec.svc
+    OicUuid_t           rownerID;        // 2:R:S:Y:oic.uuid
     OicSecAmacl_t         *next;
 };
 
 /**
- * @brief   /oic/sec/cred (Credential) data type.
- *          Derived from OIC Security Spec; see Spec for details.
+ * /oic/sec/cred (Credential) data type.
+ * Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecCred
 {
@@ -350,21 +359,18 @@ struct OicSecCred
     //size_t              roleIdsLen;     // the number of elts in RoleIds
     //OicSecRole_t        *roleIds;       // 2:R:M:N:oic.sec.role
     OicSecCredType_t    credType;       // 3:R:S:Y:oic.sec.credtype
-    OicSecJwk_t         publicData;     // 5:R:S:N:oic.sec.jwk
-    OicSecJwk_t         privateData;    // 6:R:S:N:oic.sec.jwk
+#ifdef __WITH_X509__
+    OicSecCert_t        publicData;     // chain of certificates
+#endif /* __WITH_X509__ */
+    OicSecKey_t         privateData;    // 6:R:S:N:oic.sec.key
     char                *period;        // 7:R:S:N:String
-    size_t              ownersLen;      // the number of elts in Owners
-    OicUuid_t           *owners;        // 8:R:M:Y:oic.uuid
-    // NOTE: we are using UUID for Owners instead of Svc type for mid-April
-    // SRM version only; this will change to Svc type for full implementation.
-    //OicSecSvc_t         *Owners;        // 8:R:M:Y:oic.sec.svc
-    //TODO change Owners type to oic.sec.svc
+    OicUuid_t           rownerID;        // 8:R:S:Y:oic.uuid
     OicSecCred_t        *next;
 };
 
 /**
- * @brief   /oic/sec/doxm (Device Owner Transfer Methods) data type
- *          Derived from OIC Security Spec; see Spec for details.
+ * /oic/sec/doxm (Device Owner Transfer Methods) data type
+ * Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecDoxm
 {
@@ -379,16 +385,13 @@ struct OicSecDoxm
     //TODO: Need more clarification on deviceIDFormat field type.
     //OicSecDvcIdFrmt_t   deviceIDFormat; // 5:R:S:Y:UINT8
     OicUuid_t           deviceID;       // 6:R:S:Y:oic.uuid
-    OicUuid_t           owner;         // 7:R:S:Y:oic.uuid
-    // NOTE: we are using UUID for Owner instead of Svc type for mid-April
-    // SRM version only; this will change to Svc type for full implementation.
-    //OicSecSvc_t       devOwner;        // 7:R:S:Y:oic.sec.svc
-    //OicSecSvc_t       rOwner;        // 8:R:S:Y:oic.sec.svc
-    //TODO change Owner type to oic.sec.svc
+    bool                dpc;            // 7:R:S:Y:Boolean
+    OicUuid_t           owner;          // 8:R:S:Y:oic.uuid
+    OicUuid_t           rownerID;       // 9:R:S:Y:oic.uuid
 };
 
 /**
- * @brief   /oic/sec/pstat (Provisioning Status) data type.
+ * /oic/sec/pstat (Provisioning Status) data type.
  * NOTE: this struct is ahead of Spec v0.95 in definition to include Sm.
  * TODO: change comment when reconciled to Spec v0.96.
  */
@@ -403,13 +406,12 @@ struct OicSecPstat
     size_t              smLen;          // the number of elts in Sm
     OicSecDpom_t        *sm;            // 5:R:M:Y:oic.sec.dpom
     uint16_t            commitHash;     // 6:R:S:Y:oic.sec.sha256
-    //TODO: this is supposed to be a 256-bit uint; temporarily use uint16_t
-    //TODO: need to decide which 256 bit and 128 bit types to use... boost?
+    OicUuid_t           rownerID;       // 7:R:S:Y:oic.uuid
 };
 
 /**
- * @brief   /oic/sec/role (Role) data type.
- *          Derived from OIC Security Spec; see Spec for details.
+ * /oic/sec/role (Role) data type.
+ * Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecRole
 {
@@ -419,8 +421,8 @@ struct OicSecRole
 };
 
 /**
- * @brief   /oic/sec/sacl (Signed Access Control List) data type.
- *          Derived from OIC Security Spec; see Spec for details.
+ * /oic/sec/sacl (Signed Access Control List) data type.
+ * Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecSacl
 {
@@ -429,8 +431,8 @@ struct OicSecSacl
 };
 
 /**
- * @brief   /oic/sec/svc (Service requiring a secure connection) data type.
- *          Derived from OIC Security Spec; see Spec for details.
+ * /oic/sec/svc (Service requiring a secure connection) data type.
+ * Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecSvc
 {
@@ -451,6 +453,100 @@ struct OicSecCrl
 };
 #endif /* __WITH_X509__ */
 
+/**
+ * @brief   direct pairing data type
+ */
+typedef struct OicPin OicDpPin_t;
+
+typedef struct OicSecPdAcl OicSecPdAcl_t;
+
+typedef struct OicSecPconf OicSecPconf_t;
+
+typedef struct OicSecDpairing OicSecDpairing_t;
+
+#define DP_PIN_LENGTH 8 // temporary length
+
+/**
+ * @brief   /oic/sec/prmtype (Pairing Method Type) data type.
+ *              0:  not allowed
+ *              1:  pre-configured pin
+ *              2:  random pin
+ */
+typedef enum PRMBitmask
+{
+    PRM_NOT_ALLOWED             = 0x0,
+    PRM_PRE_CONFIGURED        = (0x1 << 0),
+    PRM_RANDOM_PIN               = (0x1 << 1),
+} PRMBitmask_t;
+
+typedef PRMBitmask_t OicSecPrm_t;
+
+
+struct OicPin
+{
+    uint8_t             val[DP_PIN_LENGTH];
+};
+
+/**
+ * @brief   oic.sec.dpacltype (Device Pairing Access Control List) data type.
+ */
+struct OicSecPdAcl
+{
+    // <Attribute ID>:<Read/Write>:<Multiple/Single>:<Mandatory?>:<Type>
+    char                  **resources;        // 0:R:M:Y:String
+    size_t                resourcesLen;      // the number of elts in Resources
+    uint16_t             permission;        // 1:R:S:Y:UINT16
+    char                  **periods;            // 2:R:M*:N:String (<--M*; see Spec)
+    char                  **recurrences;    // 3:R:M:N:String
+    size_t                prdRecrLen;         // the number of elts in Periods/Recurrences
+    OicSecPdAcl_t    *next;
+};
+
+/**
+ * @brief   /oic/sec/pconf (Pairing Configuration) data type
+ */
+struct OicSecPconf
+{
+    // <Attribute ID>:<Read/Write>:<Multiple/Single>:<Mandatory?>:<Type>
+    bool                  edp;                // 0:W:S:M:Boolean
+    OicSecPrm_t      *prm;              // 1:R:M:N:UINT16
+    size_t                prmLen;          // the number of elts in Prm
+    OicDpPin_t          pin;               // 2:R:S:Y:String
+    OicSecPdAcl_t    *pdacls;         // 3:R:M:Y:oic.sec.pdacltype
+    OicUuid_t           *pddevs;        // 4:R:M:Y:oic.uuid
+    size_t                 pddevLen;     // the number of elts in pddev
+    OicUuid_t           deviceID;       // 5:R:S:Y:oic.uuid
+    OicUuid_t           rownerID;          // 6:R:S:Y:oic.uuid
+};
+
+/**
+ * @brief   /oic/sec/dpairing (Device Pairing) data type
+ */
+struct OicSecDpairing
+{
+    // <Attribute ID>:<Read/Write>:<Multiple/Single>:<Mandatory?>:<Type>
+    OicSecPrm_t      spm;               // 0:R/W:S:Y:UINT16
+    OicUuid_t           pdeviceID;     // 1:R:S:Y:oic.uuid
+    OicUuid_t           rownerID;          // 2:R:S:Y:oic.uuid
+};
+
+#define MAX_VERSION_LEN 16 // Security Version length. i.e., 00.00.000 + reserved space
+
+/**
+ * @brief   security version data type
+ */
+typedef struct OicSecVer OicSecVer_t;
+
+/**
+ * @brief   /oic/sec/ver (Security Version) data type
+ */
+struct OicSecVer
+{
+    // <Attribute ID>:<Read/Write>:<Multiple/Single>:<Mandatory?>:<Type>
+    char              secv[MAX_VERSION_LEN];          // 0:R:S:Y:String
+    OicUuid_t       deviceID;     // 1:R:S:Y:oic.uuid
+};
+
 #ifdef __cplusplus
 }
 #endif
index b14d469..4e6c02a 100644 (file)
@@ -33,86 +33,108 @@ extern "C"
 }
 #endif
 
-
 #ifdef __cplusplus
 extern "C" {
 #endif // __cplusplus
 
-
 typedef struct OicParseQueryIter OicParseQueryIter_t;
 
 /**
- * @brief   OicRestQueryIter data structure is used for book-keeping
- *          sub-REST query's attribute's and value's, starting location &
- *          length between calls to GetNextQuery(). This struct needs
- *          to be first initialized with ParseQueryIterInit().
+ * OicRestQueryIter data structure is used for book-keeping
+ * sub-REST query's attribute's and value's, starting location &
+ * length between calls to GetNextQuery(). This struct needs
+ * to be first initialized with ParseQueryIterInit().
  *
  */
 struct OicParseQueryIter
 {
-    unsigned char * attrPos;    /**<stating location of attribute */
-    size_t attrLen;             /**<length of the attribute */
-    unsigned char * valPos;     /**<starting location of value*/
-    size_t valLen;              /**<length of the value*/
-    coap_parse_iterator_t pi;   /**<coap struct for tokenizing the query*/
+    unsigned char * attrPos;    /**< stating location of attribute. */
+    size_t attrLen;             /**< length of the attribute. */
+    unsigned char * valPos;     /**< starting location of value. */
+    size_t valLen;              /**< length of the value. */
+    coap_parse_iterator_t pi;   /**< coap struct for tokenizing the query.*/
 };
 
 /**
- * @def VERIFY_SUCCESS
- * @brief Macro to verify success of operation.
+ * Macro to verify success of operation.
  * eg: VERIFY_SUCCESS(TAG, OC_STACK_OK == foo(), ERROR);
  * @note Invoking function must define "exit:" label for goto functionality to work correctly.
- *
  */
 #define VERIFY_SUCCESS(tag, op, logLevel) do{ if (!(op)) \
-            {OC_LOG((logLevel), tag, #op " failed!!"); goto exit; } }while(0)
+            {OIC_LOG((logLevel), tag, #op " failed!!"); goto exit; } }while(0)
 
 /**
- * @def VERIFY_NON_NULL
- * @brief Macro to verify argument is not equal to NULL.
+ * Macro to verify argument is not equal to NULL.
  * eg: VERIFY_NON_NULL(TAG, ptrData, ERROR);
  * @note Invoking function must define "exit:" label for goto functionality to work correctly.
- *
  */
 #define VERIFY_NON_NULL(tag, arg, logLevel) do{ if (NULL == (arg)) \
-            { OC_LOG((logLevel), tag, #arg " is NULL"); goto exit; } }while(0)
+            { OIC_LOG((logLevel), tag, #arg " is NULL"); goto exit; } }while(0)
 
 /**
- * This method initializes the OicParseQueryIter_t struct
+ * This method initializes the @ref OicParseQueryIter_t struct.
  *
- *@param query     - REST query, to be parsed
- *@param parseIter - OicParseQueryIter_t struct, to be initialized
+ * @param query is the REST query, to be parsed.
+ * @param parseIter is the @ref OicParseQueryIter_t struct, to be initialized based on the query.
+ */
+void ParseQueryIterInit(const unsigned char * query, OicParseQueryIter_t * parseIter);
+
+/**
+ * This method fills the @ref OicParseQueryIter_t struct with next REST query's
+ * attribute's and value's information.
+ *
+ * @param parseIter is the @ref OicParseQueryIter_t struct, has next query's attribute's
+ *  & value's info.
  *
+ * @return reference to the @ref OicParseQueryIter_t if it has parsed query info, else
+ * NULL if it has no query to parse.
  */
-void ParseQueryIterInit(unsigned char * query, OicParseQueryIter_t * parseIter);
+OicParseQueryIter_t * GetNextQuery(OicParseQueryIter_t * parseIter);
 
+/**
+ * This method acts as a helper function for JSON unmarshalling by various SVR's.
+ *
+ * @param jsonRoot point to the root JSON node containing the OicUuid array.
+ * @param arrayItem is the name of the JSON OicUuid array item.
+ * @param numUuids is the pointer to the number of OicUuid's available in JSON array.
+ * @param uuids is the pointer to the array of OicUuid's.
+ *
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
+OCStackResult AddUuidArray(const cJSON* jsonRoot, const char* arrayItem,
+                           size_t *numUuids, OicUuid_t** uuids);
 
 /**
- * This method fills the OicParseQueryIter_t struct with next REST query's
- * attribute's and value's information
+ * Function to getting string of ownership transfer method
  *
- *@param parseIter - OicParseQueryIter_t struct, has next query's attribute's & value's info
+ * @prarm oxmType ownership transfer method
  *
- * @retval
- *     OicParseQueryIter_t *  - has parsed query info
- *     NULL                   - has no query to parse
+ * @return string value of ownership transfer method
  */
-OicParseQueryIter_t * GetNextQuery(OicParseQueryIter_t * parseIter);
+const char* GetOxmString(OicSecOxm_t oxmType);
 
+/*
+ * This method converts UUID to canonical format string.
+ *
+ * @param uuid Device UUID
+ * @param strUuid converted UUID in canonical format
+ * @return OC_STACK_OK for success.
+ *
+ * @note Caller needs to invoke OICFree after done using the return pointer
+ */
+OCStackResult ConvertUuidToStr(const OicUuid_t* uuid, char** strUuid);
 
 
-/**
- * This method acts as a helper funtion for JSON unmarshalling by various SVR's.
+/*
+ * This method converts string UUID to OicUuid_t.
  *
- * @param jsonRoot  - root JSON node containing the OicUuid array
- * @param arrayItem - name of the JSON OicUuid array item
- * @param numUuids  - pointer to the number of OicUuid's available in JSON array
- * @param uuids     - pointer to the array of OicUuid's
+ * @param strUuid Device UUID in string format
+ * @param uuid converted UUID in OicUuid_t format
+ * @return OC_STACK_OK for success.
  *
- * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult AddUuidArray(cJSON* jsonRoot, const char* arrayItem,
-                           size_t *numUuids, OicUuid_t** uuids );
+OCStackResult ConvertStrToUuid(const char* strUuid, OicUuid_t* uuid);
+
 
 #ifdef __cplusplus
 }
index 0387090..329aaca 100644 (file)
@@ -65,7 +65,7 @@ if target_os not in ['windows', 'winrt']:
        # Note: 'pthread' is in libc for android. On other platform, if use
        # new gcc(>4.9?) it isn't required, otherwise, it's required
        if target_os != 'android':
-               provisioning_env.AppendUnique(LIBS = ['-lpthread'])
+               provisioning_env.AppendUnique(LIBS = ['-lpthread', '-ldl'])
 
 
 provisioning_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
@@ -74,9 +74,10 @@ provisioning_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connecti
 provisioning_env.AppendUnique(LIBS = ['tinydtls'])
 
 if env.get('DTLS_WITH_X509') == '1':
-       provisioning_env.AppendUnique(LIBS = ['CKManger'])
+       provisioning_env.AppendUnique(LIBS = ['CKManager', 'asn1'])
 
-provisioning_env.ParseConfig('pkg-config --libs glib-2.0')
+if target_os != 'android':
+       provisioning_env.ParseConfig('pkg-config --libs glib-2.0')
 
 if target_os == 'tizen':
        provisioning_env.ParseConfig('pkg-config --cflags --libs sqlite3')
@@ -86,7 +87,7 @@ if target_os == 'android':
        provisioning_env.AppendUnique(LIBS = ['gnustl_static'])
 
        if not env.get('RELEASE'):
-               provisioning_env.AppendUnique(LIBS = ['log'])
+               provisioning_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
 
 if target_os in ['darwin', 'ios']:
        provisioning_env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
@@ -107,7 +108,7 @@ provisioning_src = [
 if target_os != 'tizen':
        provisioning_src = provisioning_src + [root_dir+'/extlibs/sqlite3/sqlite3.c' ]
 
-provisioningserver = provisioning_env.StaticLibrary('ocpmapi', provisioning_src)
+provisioningserver = provisioning_env.SharedLibrary('ocpmapi', provisioning_src)
 
 provisioning_env.InstallTarget(provisioningserver, 'libocpmapi')
 provisioning_env.UserInstallTargetLib(provisioningserver, 'libocpmapi')
index 00e2cbe..a473e5e 100644 (file)
@@ -46,6 +46,5 @@ x509_env.AppendUnique(LIBS = ['asn1'])
 x509_env.AppendUnique(LIBS = ['Base64'])
 x509_env.AppendUnique(LIBS = ['Json'])
 
-SConscript('tools/SConscript')
 SConscript('sample/SConscript')
 SConscript('unittest/SConscript')
index 02ac6a3..19b5081 100644 (file)
@@ -135,7 +135,7 @@ PKIError CKMIssueDeviceCertificate (const uint8_t *uint8SubjectName,
  * @param[in] certFileName pointer to null-terminated string with file name
  * @return PKI_SUCCESS if success, error code otherwise
  */
-PKIError GenerateDERCertificateFile (const ByteArray *certificate, const char *certFileName);
+PKIError GenerateDERCertificateFile (const ByteArray *certificate, const char * const certFileName);
 
 /**
  * Issues certificate signing request with specified parameters.
index c3ce9d3..c5b1f80 100644 (file)
@@ -96,9 +96,9 @@ PKIError CloseCKMInfo(void);
 /**
  * Sets CKM Info.
  *
- * @param[in] nextSN pointer to the next serial number to set
+ * @param[in] nextSN next serial number to set
  *                   or 0 to skip this parameter
- * @param[in] CRLSerialNumber pointer to the next CRL serial number to set
+ * @param[in] CRLSerialNumber next CRL serial number to set
  *                   or 0 to skip this parameter
  * @param[in] CAPrivateKey pointer to the CA's private key to set
  *                   or 0 to skip this parameter
@@ -108,7 +108,7 @@ PKIError CloseCKMInfo(void);
  *                   or 0 to skip this parameter
  * @return PKI_SUCCESS if success, error code otherwise
  */
-PKIError SetCKMInfo (const long *nextSN, const long *CRLSerialNumber,
+PKIError SetCKMInfo (long nextSN, long CRLSerialNumber,
                      const ByteArray *CAPrivateKey, const ByteArray *CAPublicKey,
                      const ByteArray *CAName);
 
@@ -206,10 +206,10 @@ PKIError SaveCRT(void);
 /**
  * Sets next serial number for certificate issuer.
  *
- * @param[in] nextSN pointer to the next serial number to set
+ * @param[in] nextSN next serial number to set
  * @return PKI_SUCCESS if success, error code otherwise
  */
-PKIError SetNextSerialNumber (const long *nextSN);
+PKIError SetNextSerialNumber (const long nextSN);
 
 /**
  * Gets next serial number for certificate issuer.
@@ -273,10 +273,10 @@ PKIError SaveCRL(void);
 /**
  * Sets next CRL serial number for certificate issuer.
  *
- * @param[in] CRLSerialNumber pointer to the next CRL serial number to set
+ * @param[in] CRLSerialNumber next CRL serial number to set
  * @return PKI_SUCCESS if success, error code otherwise
  */
-PKIError SetCRLSerialNumber (const long *CRLSerialNumber);
+PKIError SetCRLSerialNumber (const long CRLSerialNumber);
 
 /**
  * Gets next CRL serial number for certificate issuer.
@@ -307,10 +307,10 @@ PKIError GetCertificateRevocationList (ByteArray *certificateRevocationList);
 /**
  * Sets number of revoked certificates.
  *
- * @param[in] numberOfRevoked pointer to number of revoked certificates to set
+ * @param[in] numberOfRevoked number of revoked certificates to set
  * @return PKI_SUCCESS if success, error code otherwise
  */
-PKIError SetNumberOfRevoked (const long *numberOfRevoked);
+PKIError SetNumberOfRevoked (const long numberOfRevoked);
 
 /**
  * Gets number of revoked certificates.
old mode 100755 (executable)
new mode 100644 (file)
index 2f2bdbd..316d0da
@@ -40,6 +40,7 @@
 #define DEFAULT_CONTEXT_VALUE 0x99
 #define STATE "state"
 #define OPEN_DURATION "openDuration"
+#define OPEN_DURATION_TIME "10min"
 #define OPEN_ALARM "openAlarm"
 
 static const char MULTICAST_DISCOVERY_QUERY[] = "/oic/res";
@@ -59,7 +60,7 @@ static std::string address;
 
 static int coapSecureResource;
 
-static const char CRED_FILE[] = "oic_svr_db_door.json";
+static const char CRED_FILE[] = "oic_svr_db_door.dat";
 
 CAEndpoint_t endpoint = {CA_DEFAULT_ADAPTER, CA_DEFAULT_FLAGS, 0, {0}, 0};
 
@@ -98,7 +99,7 @@ int parseClientResponse(OCClientResponse * clientResponse)
     while (res)
     {
         coapServerResource.assign(res->uri);
-        OC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
+        OIC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
 
         if (res->secure)
         {
@@ -106,7 +107,7 @@ int parseClientResponse(OCClientResponse * clientResponse)
             coapSecureResource = 1;
         }
 
-        OC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
+        OIC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
 
         // If we discovered a secure resource, exit from here
         if (coapSecureResource)
@@ -125,7 +126,7 @@ OCRepPayload* getPayload(const char* uri, int64_t state, char* openDuration, boo
     OCRepPayload* payload = OCRepPayloadCreate();
     if (!payload)
     {
-        OC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
+        OIC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
         return nullptr;
     }
 
@@ -142,7 +143,7 @@ OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
 {
     if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
     {
-        OC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
+        OIC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
         return nullptr;
     }
 
@@ -171,7 +172,7 @@ OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag,
                                         OCEntityHandlerRequest *entityHandlerRequest,
                                         void* /*callbackParam*/)
 {
-    OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
+    OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
 
     OCEntityHandlerResult ehResult = OC_EH_ERROR;
     OCEntityHandlerResponse response;
@@ -179,7 +180,7 @@ OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag,
     // Validate pointer
     if (!entityHandlerRequest)
     {
-        OC_LOG (ERROR, TAG, "Invalid request pointer");
+        OIC_LOG (ERROR, TAG, "Invalid request pointer");
         return OC_EH_ERROR;
     }
 
@@ -187,7 +188,7 @@ OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag,
 
     if (flag & OC_REQUEST_FLAG)
     {
-        OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
+        OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
 
         if (entityHandlerRequest)
         {
@@ -195,13 +196,13 @@ OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag,
             {
             case OC_REST_GET:
             {
-                OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
+                OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
                 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
             }
             break;
             default:
             {
-                OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
+                OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
                         entityHandlerRequest->method);
                 ehResult = OC_EH_ERROR;
             }
@@ -224,7 +225,7 @@ OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag,
                 // Send the response
                 if (OCDoResponse(&response) != OC_STACK_OK)
                 {
-                    OC_LOG(ERROR, TAG, "Error sending response");
+                    OIC_LOG(ERROR, TAG, "Error sending response");
                     ehResult = OC_EH_ERROR;
                 }
             }
@@ -331,13 +332,12 @@ int  createDoorResource (const char *uri, DoorResource *doorResource)
 {
     if (!uri)
     {
-        OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
+        OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
 
     }
 
     doorResource->state = STATE_CLOSED; //1:closed , 0: open
-    char str[] = "10min";
-    doorResource->openDuration = str;
+    doorResource->openDuration = OPEN_DURATION_TIME;
     doorResource->openAlarm = false;
     OCStackResult res = OCCreateResource(&(doorResource->handle),
                                          "core.door",
@@ -347,7 +347,7 @@ int  createDoorResource (const char *uri, DoorResource *doorResource)
                                          NULL,
                                          OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE);
 
-    OC_LOG_V(INFO, TAG, "Created Door resource with result: %s", getResult(res));
+    OIC_LOG_V(INFO, TAG, "Created Door resource with result: %s", getResult(res));
     return 0;
 }
 
@@ -355,17 +355,17 @@ OCStackApplicationResult putReqCB(void * ctx, OCDoHandle /*handle*/, OCClientRes
 {
     if (ctx == (void *)DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
+        OIC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
     }
 
     if (clientResponse)
     {
-        OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
-        OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
-        OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
+        OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
+        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
         if ((OCSecurityPayload*)clientResponse->payload)
         {
-            OC_LOG_V(INFO, TAG, "=============> Put Response",
+            OIC_LOG_V(INFO, TAG, "=============> Put Response",
                     ((OCSecurityPayload*)clientResponse->payload)->securityData);
         }
     }
@@ -374,16 +374,16 @@ OCStackApplicationResult putReqCB(void * ctx, OCDoHandle /*handle*/, OCClientRes
 
 OCStackApplicationResult getReqCB(void * /*ctx*/, OCDoHandle /*handle*/, OCClientResponse *clientResponse)
 {
-    OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
+    OIC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
 
     if (clientResponse)
     {
-        OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
-        OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
-        OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
+        OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
+        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
         if ((OCSecurityPayload*)clientResponse->payload)
         {
-            OC_LOG(INFO, TAG, PCF("=============> Get Response"));
+            OIC_LOG(INFO, TAG, PCF("=============> Get Response"));
         }
     }
     return OC_STACK_DELETE_TRANSACTION;
@@ -393,19 +393,19 @@ OCStackApplicationResult getReqCB(void * /*ctx*/, OCDoHandle /*handle*/, OCClien
 OCStackApplicationResult discoveryReqCB(void* /*ctx*/, OCDoHandle /*handle*/,
         OCClientResponse * clientResponse)
 {
-    OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
+    OIC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
 
     if (clientResponse)
     {
-        OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
-        OC_LOG_V(INFO, TAG,
+        OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
+        OIC_LOG_V(INFO, TAG,
                 "Device =============> Discovered @ %s:%d",
                 clientResponse->devAddr.addr,
                 clientResponse->devAddr.port);
 
         if (clientResponse->result == OC_STACK_OK)
         {
-            OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+            OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
             ocConnType = clientResponse->connType;
             parseClientResponse(clientResponse);
         }
@@ -422,9 +422,9 @@ void initAddress()
     static bool initFlag = false;
     if (!initFlag)
     {
-        OC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
-        OC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
-        OC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
+        OIC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
+        OIC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
+        OIC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
 
         std::cin >> address;
     }
@@ -435,7 +435,10 @@ void initAddress()
 void SendGetRequest()
 {
     OCStackResult ret;
-    OC_LOG(INFO, TAG, "Send Get REQ to Light server");
+    OIC_LOG(INFO, TAG, "Send Get REQ to Light server");
+
+    //select ciphersuite for certificates
+    CASelectCipherSuite(TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
 
     initAddress();
 
@@ -445,13 +448,13 @@ void SendGetRequest()
     cbData.cb = getReqCB;
     cbData.context = (void *)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
-    OC_LOG_V(INFO, TAG, "Get payload from Door sample = /a/light ");
+    OIC_LOG_V(INFO, TAG, "Get payload from Door sample = /a/light ");
     snprintf(szQueryUri,  sizeof(szQueryUri), "coaps://%s/a/light", const_cast<char*> (address.c_str())); // lightPortNu);
     ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, NULL, ocConnType, OC_LOW_QOS,
                  &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack resource error");
+        OIC_LOG(ERROR, TAG, "OCStack resource error");
     }
 }
 
@@ -466,7 +469,7 @@ void *input_function(void * /*data*/)
     cbData.context = (void *)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
 
-    strcpy(szQueryUri, MULTICAST_DISCOVERY_QUERY);
+    strncpy(szQueryUri, MULTICAST_DISCOVERY_QUERY, sizeof(szQueryUri));
 
     while (1)
     {
@@ -477,8 +480,12 @@ void *input_function(void * /*data*/)
             case 'd':
                 if (isUpdated == false)
                 {
-                    OC_LOG(INFO, TAG, "isUpdated is false...");
-                    OCDoResource(&handle, OC_REST_DISCOVER, szQueryUri, 0, 0, CT_DEFAULT, OC_LOW_QOS, &cbData, NULL, 0);
+                    OIC_LOG(INFO, TAG, "isUpdated is false...");
+                    if (OCDoResource(&handle, OC_REST_DISCOVER, szQueryUri, 0, 0, CT_DEFAULT,
+                                     OC_LOW_QOS, &cbData, NULL, 0) != OC_STACK_OK)
+                    {
+                        OIC_LOG(ERROR, TAG, "OCDoResource error");
+                    }
 
                 }
                 break;
@@ -487,7 +494,7 @@ void *input_function(void * /*data*/)
                 isUpdated = true;
                 if (isUpdated == true)
                 {
-                    OC_LOG(INFO, TAG, "isUpdated is true...");
+                    OIC_LOG(INFO, TAG, "isUpdated is true...");
                     SendGetRequest();
                 }
                 break;
@@ -503,22 +510,22 @@ void *input_function(void * /*data*/)
 
 static void PrintUsage()
 {
-    OC_LOG(INFO, TAG, "*******************************************");
-    OC_LOG(INFO, TAG, "Input D or d to discover Resources");
-    OC_LOG(INFO, TAG, "Input G or g to initiate Get Request");
-    OC_LOG(INFO, TAG, "Input Q or q to exit");
-    OC_LOG(INFO, TAG, "*******************************************");
+    OIC_LOG(INFO, TAG, "*******************************************");
+    OIC_LOG(INFO, TAG, "Input D or d to discover Resources");
+    OIC_LOG(INFO, TAG, "Input G or g to initiate Get Request");
+    OIC_LOG(INFO, TAG, "Input Q or q to exit");
+    OIC_LOG(INFO, TAG, "*******************************************");
 }
 
 int main()
 {
 
-    OC_LOG(INFO, TAG, "OCServer is starting...");
+    OIC_LOG(INFO, TAG, "OCServer is starting...");
     SetPersistentHandler(&ps);
     //PrintUsage();
     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack init error");
+        OIC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
 
@@ -536,14 +543,14 @@ int main()
     timeout.tv_nsec = 100000000L;
 
     // Break from loop with Ctrl-C
-    OC_LOG(INFO, TAG, "Entering ocserver main loop...");
+    OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
     signal(SIGINT, handleSigInt);
     int thr_id;
     pthread_t p_thread;
     thr_id = pthread_create(&p_thread, NULL, input_function, (void *)NULL);
     if (thr_id < 0)
     {
-        OC_LOG(ERROR, TAG, "create thread error");
+        OIC_LOG(ERROR, TAG, "create thread error");
         return 0;
     }
 
@@ -552,7 +559,7 @@ int main()
 
         if (OCProcess() != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             return 0;
         }
 
@@ -562,11 +569,11 @@ int main()
 
     pthread_join(p_thread, NULL);
 
-    OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
+    OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
 
     if (OCStop() != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack process error");
+        OIC_LOG(ERROR, TAG, "OCStack process error");
     }
 
     return 0;
index 9a3f82e..11c7991 100755 (executable)
@@ -42,7 +42,7 @@ const char *gResourceUri = (char *)"/a/light";
 //Secure Virtual Resource database for Iotivity Server
 //It contains Server's Identity and the PSK credentials
 //of other devices which the server trusts
-static char CRED_FILE[] = "oic_svr_db_light.json";
+static char CRED_FILE[] = "oic_svr_db_light.dat";
 
 
 //Structure to represent a light resource  and its attributes
@@ -61,7 +61,7 @@ OCRepPayload* getPayload(const char* uri, int64_t brightness)
     OCRepPayload* payload = OCRepPayloadCreate();
     if(!payload)
     {
-        OC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
+        OIC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
         return nullptr;
     }
 
@@ -81,7 +81,7 @@ OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest)
 
     if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
     {
-        OC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
+        OIC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
         return nullptr;
     }
 
@@ -109,7 +109,7 @@ OCEntityHandlerResult OCEntityHandlerCb (OCEntityHandlerFlag flag,
                                          OCEntityHandlerRequest *entityHandlerRequest,
                                          void* /*callbackParam*/)
 {
-    OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
+    OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
 
     OCEntityHandlerResult ehResult = OC_EH_ERROR;
     OCEntityHandlerResponse response;
@@ -117,7 +117,7 @@ OCEntityHandlerResult OCEntityHandlerCb (OCEntityHandlerFlag flag,
     // Validate pointer
     if (!entityHandlerRequest)
     {
-        OC_LOG (ERROR, TAG, "Invalid request pointer");
+        OIC_LOG (ERROR, TAG, "Invalid request pointer");
         return OC_EH_ERROR;
     }
 
@@ -125,20 +125,20 @@ OCEntityHandlerResult OCEntityHandlerCb (OCEntityHandlerFlag flag,
 
     if (flag & OC_REQUEST_FLAG)
     {
-        OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
+        OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
         if (entityHandlerRequest)
         {
             switch(entityHandlerRequest->method)
             {
             case OC_REST_GET:
             {
-                OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
+                OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
                 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
             }
             break;
             default:
             {
-                OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
+                OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
                         entityHandlerRequest->method);
                 ehResult = OC_EH_ERROR;
             }
@@ -161,7 +161,7 @@ OCEntityHandlerResult OCEntityHandlerCb (OCEntityHandlerFlag flag,
                 // Send the response
                 if (OCDoResponse(&response) != OC_STACK_OK)
                 {
-                    OC_LOG(ERROR, TAG, "Error sending response");
+                    OIC_LOG(ERROR, TAG, "Error sending response");
                     ehResult = OC_EH_ERROR;
                 }
             }
@@ -270,7 +270,7 @@ int createLightResource (const char *uri, LightResource *lightResource)
 {
     if (!uri)
     {
-        OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
+        OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
 
     }
 
@@ -283,18 +283,18 @@ int createLightResource (const char *uri, LightResource *lightResource)
                                          NULL,
                                          OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
 
-    OC_LOG_V(INFO, TAG, "Created Light resource with result: %s", getResult(res));
+    OIC_LOG_V(INFO, TAG, "Created Light resource with result: %s", getResult(res));
     return 0;
 }
 
 
 int main()
 {
-    OC_LOG(DEBUG, TAG, "OCServer is starting...");
+    OIC_LOG(DEBUG, TAG, "OCServer is starting...");
     SetPersistentHandler(&ps);
     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack init error");
+        OIC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
 
@@ -310,24 +310,24 @@ int main()
     timeout.tv_nsec = 100000000L;
 
     // Break from loop with Ctrl-C
-    OC_LOG(INFO, TAG, "Entering ocserver main loop...");
+    OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
     signal(SIGINT, handleSigInt);
     while (!gQuitFlag)
     {
         if (OCProcess() != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             return 0;
         }
 
         nanosleep(&timeout, NULL);
     }
 
-    OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
+    OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
 
     if (OCStop() != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack process error");
+        OIC_LOG(ERROR, TAG, "OCStack process error");
     }
 
     return 0;
index b368fe3..d41b38b 100644 (file)
@@ -88,4 +88,10 @@ provisioning_env.Alias("install", provisioning_env.Install( sec_provisioning_bui
 provisioning_env.Alias("install", provisioning_env.Install( sec_provisioning_build_dir,
        sec_provisioning_src_dir + 'oic_svr_db_door.json'))
 provisioning_env.Alias("install", provisioning_env.Install( sec_provisioning_build_dir,
+       sec_provisioning_src_dir + 'oic_svr_db_pt.dat'))
+provisioning_env.Alias("install", provisioning_env.Install( sec_provisioning_build_dir,
+       sec_provisioning_src_dir + 'oic_svr_db_light.dat'))
+provisioning_env.Alias("install", provisioning_env.Install( sec_provisioning_build_dir,
+       sec_provisioning_src_dir + 'oic_svr_db_door.dat'))
+provisioning_env.Alias("install", provisioning_env.Install( sec_provisioning_build_dir,
        sec_provisioning_src_dir + 'README.txt'))
diff --git a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.dat b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.dat
new file mode 100755 (executable)
index 0000000..bf440f2
Binary files /dev/null and b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.dat differ
old mode 100644 (file)
new mode 100755 (executable)
index 8bcb39f..20062b4
-{
-    "acl": [
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/res",
-                "/oic/res/d",
-                "/oic/res/types/d",
-                "/oic/presence"
-                       ],
-                       "perms": 2,
-                       "ownrs" : [
-                               "ZG9vckRldmljZVVVSUQwMA=="
-                       ]
-               },
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/sec/doxm",
-                "/oic/sec/pstat",
-                "/oic/sec/acl",
-                "/oic/sec/crl",
-                "/oic/sec/cred"
-             ],
-             "perms": 6,
-             "ownrs" : [
-                 "ZG9vckRldmljZVVVSUQwMA=="
-             ]
-        }
-       ],
-       "pstat":        {
-               "isop": false,
-               "deviceid":     "ZG9vckRldmljZVVVSUQwMA==",
-               "commithash": 0,
-               "cm":   0,
-               "tm":   0,
-               "om":   3,
-               "sm":   [3]
-       },
-       "doxm": {
-               "oxm":  [0],
-               "oxmsel": 0,
-               "sct": 1,
-               "owned": false,
-               "deviceid":     "ZG9vckRldmljZVVVSUQwMA=="
-       }
+{\r
+    "acl": {\r
+        "aclist": {\r
+            "aces": [\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/res",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/p",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/types/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/presence",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/doxm",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/pstat",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/acl",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/crl",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/cred",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 6\r
+                }\r
+            ]\r
+        },\r
+        "rowneruuid" : "646F6F72-4465-7669-6365-555549443030"\r
+    },\r
+    "pstat": {\r
+        "isop": false,\r
+        "deviceuuid": "646F6F72-4465-7669-6365-555549443030",\r
+        "rowneruuid": "646F6F72-4465-7669-6365-555549443030",\r
+        "cm": 2,\r
+        "tm": 0,\r
+        "om": 3,\r
+        "sm": 3\r
+        },\r
+    "doxm": {\r
+        "oxms": [0],\r
+        "oxmsel": 0,\r
+        "sct": 1,\r
+        "owned": false,\r
+        "deviceuuid": "646F6F72-4465-7669-6365-555549443030",\r
+        "rowneruuid": "646F6F72-4465-7669-6365-555549443030",\r
+        "dpc": false\r
+    }\r
 }
diff --git a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.dat b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.dat
new file mode 100755 (executable)
index 0000000..59f65e5
Binary files /dev/null and b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.dat differ
old mode 100644 (file)
new mode 100755 (executable)
index 048384b..a7598d4
-{
-    "acl": [
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/res",
-                "/oic/res/d",
-                "/oic/res/types/d",
-                "/oic/presence"
-                       ],
-                       "perms": 2,
-                       "ownrs" : [
-                               "bGlnaHREZXZpY2VVVUlEMA=="
-                       ]
-               },
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/sec/doxm",
-                "/oic/sec/pstat",
-                "/oic/sec/acl",
-                "/oic/sec/crl",
-                "/oic/sec/cred"
-             ],
-             "perms": 6,
-             "ownrs" : [
-                 "bGlnaHREZXZpY2VVVUlEMA=="
-             ]
-        }
-       ],
-       "pstat":        {
-               "isop": false,
-               "deviceid":     "bGlnaHREZXZpY2VVVUlEMA==",
-               "commithash": 0,
-               "cm":   0,
-               "tm":   0,
-               "om":   3,
-               "sm":   [3]
-       },
-       "doxm": {
-               "oxm":  [0],
-               "oxmsel": 0,
-               "sct": 1,
-               "owned": false,
-               "deviceid":     "bGlnaHREZXZpY2VVVUlEMA=="
-       }
+{\r
+    "acl": {\r
+        "aclist": {\r
+            "aces": [\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/res",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/p",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/types/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/presence",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/doxm",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/pstat",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/acl",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/crl",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/cred",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 6\r
+                }\r
+            ]\r
+        },\r
+        "rowneruuid" : "6C696768-7444-6576-6963-655555494430"\r
+    },\r
+    "pstat": {\r
+        "isop": false,\r
+        "deviceuuid": "6C696768-7444-6576-6963-655555494430",\r
+        "rowneruuid": "6C696768-7444-6576-6963-655555494430",\r
+        "cm": 2,\r
+        "tm": 0,\r
+        "om": 3,\r
+        "sm": 3\r
+        },\r
+    "doxm": {\r
+        "oxms": [0],\r
+        "oxmsel": 0,\r
+        "sct": 1,\r
+        "owned": false,\r
+        "deviceuuid": "6C696768-7444-6576-6963-655555494430",\r
+        "rowneruuid": "6C696768-7444-6576-6963-655555494430",\r
+        "dpc": false\r
+    }\r
 }
diff --git a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.dat b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.dat
new file mode 100755 (executable)
index 0000000..6143d32
Binary files /dev/null and b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.dat differ
old mode 100644 (file)
new mode 100755 (executable)
index dd5dec4..2e33796
@@ -1,44 +1,82 @@
-{
-    "acl": [
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/res",
-                "/oic/d",
-                "/oic/p",
-                "/oic/res/types/d",
-                "/oic/ad"
-                       ],
-                       "perms": 2,
-                       "ownrs" : ["YWRtaW5EZXZpY2VVVUlEMA=="]
-               },
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/sec/doxm",
-                "/oic/sec/pstat",
-                "/oic/sec/acl",
-                "/oic/sec/cred"
-             ],
-             "perms": 7,
-             "ownrs" : ["YWRtaW5EZXZpY2VVVUlEMA=="]
-        }
-       ],
-       "pstat":        {
-               "isop": true,
-               "deviceid":     "YWRtaW5EZXZpY2VVVUlEMA==",
-               "ch": 0,
-               "cm":   0,
-               "tm":   0,
-               "om":   3,
-               "sm":   [3]
-       },
-       "doxm": {
-               "oxm":  [0],
-               "oxmsel": 0,
-               "sct": 1,
-               "owned": true,
-               "deviceid":     "YWRtaW5EZXZpY2VVVUlEMA==",
-               "ownr": "YWRtaW5EZXZpY2VVVUlEMA=="
-       }
-}
+{\r
+    "acl": {\r
+        "aclist": {\r
+            "aces": [\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/res",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/p",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/types/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/ad",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/doxm",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        } ,\r
+                        {\r
+                            "href": "/oic/sec/pstat",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                }\r
+            ]\r
+        },\r
+        "rowneruuid" : "61646D69-6E44-6576-6963-655555494430"\r
+    },\r
+    "pstat": {\r
+        "isop": true,\r
+        "deviceuuid": "61646D69-6E44-6576-6963-655575696430",\r
+        "rowneruuid": "61646D69-6E44-6576-6963-655575696430",\r
+        "cm": 2,\r
+        "tm": 0,\r
+        "om": 3,\r
+        "sm": 3\r
+        },\r
+    "doxm": {\r
+        "oxms": [0],\r
+        "oxmsel": 0,\r
+        "sct": 1,\r
+        "owned": true,\r
+        "deviceuuid": "61646D69-6E44-6576-6963-655575696430",\r
+        "devowneruuid": "61646D69-6E44-6576-6963-655575696430",\r
+        "rowneruuid": "61646D69-6E44-6576-6963-655575696430",\r
+        "dpc": false\r
+    }\r
+}
\ No newline at end of file
index 972a373..91a7619 100644 (file)
@@ -50,7 +50,7 @@
 
 static OicSecAcl_t        *gAcl = NULL;
 static OicSecCrl_t        *gCrl = NULL;
-static char PROV_TOOL_DB_FILE[] = "oic_svr_db_pt.json";
+static char PROV_TOOL_DB_FILE[] = "oic_svr_db_pt.dat";
 static const char* PRVN_DB_FILE_NAME = "oic_prvn_mng.db";
 static int gOwnershipState = 0;
 
@@ -80,9 +80,6 @@ static void deleteACL(OicSecAcl_t *acl)
         }
         OICFree((acl)->resources);
 
-        /* Clean Owners */
-        OICFree((acl)->owners);
-
         /* Clean ACL node itself */
         OICFree((acl));
 
@@ -205,7 +202,7 @@ static int InputACL(OicSecAcl_t *acl)
     {
         if (DASH != temp_id[i])
         {
-            if(j>UUID_LENGTH)
+            if(j >= UUID_LENGTH)
             {
                 printf("Invalid input\n");
                 return -1;
@@ -217,12 +214,17 @@ static int InputACL(OicSecAcl_t *acl)
     //Set Resource.
     printf("Num. of Resource : \n");
     ret = scanf("%zu", &acl->resourcesLen);
+    if(-1 == ret)
+    {
+        printf("Error while input\n");
+        return -1;
+    }
     printf("-URI of resource\n");
     printf("ex) /a/light (Max_URI_Length: 64 Byte )\n");
     acl->resources = (char **)OICCalloc(acl->resourcesLen, sizeof(char *));
     if (NULL == acl->resources)
     {
-        OC_LOG(ERROR, TAG, "Error while memory allocation");
+        OIC_LOG(ERROR, TAG, "Error while memory allocation");
         return -1;
     }
     for (size_t i = 0; i < acl->resourcesLen; i++)
@@ -244,7 +246,7 @@ static int InputACL(OicSecAcl_t *acl)
 
         if (NULL == acl->resources[i])
         {
-            OC_LOG(ERROR, TAG, "Error while memory allocation");
+            OIC_LOG(ERROR, TAG, "Error while memory allocation");
             return -1;
         }
     }
@@ -270,38 +272,28 @@ static int InputACL(OicSecAcl_t *acl)
     }
     while (0 != CalculateAclPermission(temp_pms, &(acl->permission)) );
     // Set Rowner
-    printf("Num. of Rowner : ");
-    ret = scanf("%zu", &acl->ownersLen);
     printf("-URN identifying the rowner\n");
     printf("ex) lightDeviceUUID0 (16 Numbers except to '-')\n");
-    acl->owners = (OicUuid_t *)OICCalloc(acl->ownersLen, sizeof(OicUuid_t));
-    if (NULL == acl->owners)
+
+    printf("Rowner : ");
+    char *ptr_temp_id = NULL;
+    ret = scanf("%19ms", &ptr_temp_id);
+    if (1 == ret)
+    {
+        OICStrcpy(temp_id, sizeof(temp_id), ptr_temp_id);
+        OICFree(ptr_temp_id);
+    }
+    else
     {
-        OC_LOG(ERROR, TAG, "Error while memory allocation");
+        printf("Error while input\n");
         return -1;
     }
-    for (size_t i = 0; i < acl->ownersLen; i++)
+    j = 0;
+    for (int k = 0; temp_id[k] != '\0'; k++)
     {
-        printf("[%zu]Rowner : ", i + 1);
-        char *ptr_temp_id = NULL;
-        ret = scanf("%19ms", &ptr_temp_id);
-        if (1 == ret)
-        {
-            OICStrcpy(temp_id, sizeof(temp_id), ptr_temp_id);
-            OICFree(ptr_temp_id);
-        }
-        else
-        {
-            printf("Error while input\n");
-            return -1;
-        }
-        j = 0;
-        for (int k = 0; temp_id[k] != '\0'; k++)
+        if (DASH != temp_id[k])
         {
-            if (DASH != temp_id[k])
-            {
-                acl->owners[i].id[j++] = temp_id[k];
-            }
+            acl->rownerID.id[j++] = temp_id[k];
         }
     }
     return 0;
@@ -446,19 +438,43 @@ static int InputCRL(OicSecCrl_t *crlRes)
    // const uint8_t revocationDatesContent[MAX_Revoked_NUMBER][DATE_LENGTH];
     uint32_t nuberOfRevoked = 0;
     printf("Enter number of Revoked certificates(1..%d)\n", MAX_Revoked_NUMBER);
-    scanf("%u", &nuberOfRevoked);
+    int ret = 0;
+    ret = scanf("%u", &nuberOfRevoked);
+    if(-1 == ret)
+    {
+        printf("Error while input\n");
+        return PKI_UNKNOWN_ERROR;
+    }
+
+    if((uint32_t)MAX_Revoked_NUMBER < nuberOfRevoked)
+    {
+        OIC_LOG(ERROR, TAG, "Wrong revoked certificate number");
+        return PKI_UNKNOWN_ERROR;
+    }
 
     for (size_t i = 0; i < nuberOfRevoked; ++i)
     {
         printf("Revoked certificate %d:", i);
         printf("Serial number (E. g.: 100):");
-        scanf("%u", &revokedNumbers[i]);
+        ret = scanf("%u", &revokedNumbers[i]);
+        if(-1 == ret)
+        {
+            printf("Error while input\n");
+            return PKI_UNKNOWN_ERROR;
+        }
+
         revocationDates[i] = (const uint8_t*)"130101000005Z";
     }
 
     crl.len = CRL_MIN_SIZE + nuberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4)/* + 1000*/;
     crl.data = (uint8_t *)OICCalloc(1, crl.len);
 
+    if (NULL == crl.data)
+    {
+        OIC_LOG(ERROR, TAG, "Error while memory allocation");
+        return PKI_MEMORY_ALLOC_FAILED;
+    }
+
     CHECK_CALL(CKMIssueCRL, uint8ThisUpdateTime, nuberOfRevoked, revokedNumbers,
             revocationDates, &crl);
     PRINT_BYTE_ARRAY("CRL:\n",crl);
@@ -481,6 +497,8 @@ static int InputCRL(OicSecCrl_t *crlRes)
 int main()
 {
     OCStackResult res = OC_STACK_OK;
+    OCProvisionDev_t* pDeviceList = NULL;
+    OCProvisionDev_t *pOwnedList = NULL;
 
     // Initialize Persistent Storage for SVR database
     OCPersistentStorage ps = { .open = client_fopen,
@@ -493,20 +511,19 @@ int main()
 
     if (OC_STACK_OK != OCInit(NULL, 0, OC_CLIENT_SERVER))
     {
-        OC_LOG(ERROR, TAG, "OCStack init error");
+        OIC_LOG(ERROR, TAG, "OCStack init error");
         goto error;
     }
     if(OC_STACK_OK != OCInitPM(PRVN_DB_FILE_NAME))
     {
-        OC_LOG(ERROR, TAG, "OC_PM init error");
+        OIC_LOG(ERROR, TAG, "OC_PM init error");
         goto error;
     }
 
-    OCProvisionDev_t* pDeviceList = NULL;
     res = OCDiscoverUnownedDevices(PREDEFINED_TIMEOUT, &pDeviceList);
     if(OC_STACK_OK != res)
     {
-        OC_LOG_V(ERROR, TAG, "Failed to PMDeviceDiscovery : %d", res);
+        OIC_LOG_V(ERROR, TAG, "Failed to PMDeviceDiscovery : %d", res);
         goto error;
     }
 
@@ -538,11 +555,11 @@ int main()
     res = OCDoOwnershipTransfer((void*)myContext, pDeviceList, OwnershipTransferCB);
     if(OC_STACK_OK == res)
     {
-        OC_LOG(INFO, TAG, "Request for ownership transfer is sent successfully.");
+        OIC_LOG(INFO, TAG, "Request for ownership transfer is sent successfully.");
     }
     else
     {
-        OC_LOG_V(ERROR, TAG, "Failed to OCDoOwnershipTransfer : %d", res);
+        OIC_LOG_V(ERROR, TAG, "Failed to OCDoOwnershipTransfer : %d", res);
     }
 
     gOwnershipState = 0;
@@ -550,7 +567,7 @@ int main()
     {
         if (OCProcess() != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             goto error;
         }
         sleep(1);
@@ -558,7 +575,6 @@ int main()
 
 // Credential & ACL provisioning between two devices.
 
-    OCProvisionDev_t *pOwnedList = NULL;
     OCProvisionDev_t *pOwnedDevices [MAX_OWNED_DEVICE] = {0,};
     int nOwnedDevice = 0;
 
@@ -581,29 +597,46 @@ int main()
     }
     else
     {
-        OC_LOG(ERROR, TAG, "Error while Owned Device Discovery");
+        OIC_LOG(ERROR, TAG, "Error while Owned Device Discovery");
     }
 
     int Device1 = 0;
     int Device2 = 0;
+    int ret = 0;
 
     printf("Select 2 devices for Credential & ACL provisioning\n");
     printf("Device 1: ");
-    scanf("%d", &Device1);
+    ret = scanf("%d", &Device1);
+    if(-1 == ret)
+    {
+        printf("Error while input\n");
+        goto error;
+    }
+
     printf("Device 2: ");
-    scanf("%d", &Device2);
+    ret = scanf("%d", &Device2);
+    if(-1 == ret)
+    {
+        printf("Error while input\n");
+        goto error;
+    }
 
+    if( 0 > Device1 || 0 > Device2 || Device1 > nOwnedDevice || Device2 > nOwnedDevice)
+    {
+        OIC_LOG(ERROR, TAG, "Wrong devices number");
+        goto error;
+    }
 
     gAcl = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
     if (NULL == gAcl)
     {
-        OC_LOG(ERROR, TAG, "Error while memory allocation");
+        OIC_LOG(ERROR, TAG, "Error while memory allocation");
         goto error;
     }
 
     if (PKI_SUCCESS != InitCA())
     {
-        OC_LOG(ERROR, TAG, "CA init error");
+        OIC_LOG(ERROR, TAG, "CA init error");
         goto error;
     }
 
@@ -612,13 +645,13 @@ int main()
 
     res = OCProvisionCredentials(ctx, SIGNED_ASYMMETRIC_KEY, 0, pOwnedDevices[Device1],
                                                                 NULL, ProvisionCertCB);
-    if (OC_STACK_OK != res) OC_LOG_V(ERROR, TAG, "Failed to provision Device 1 : %d", res);
+    if (OC_STACK_OK != res) OIC_LOG_V(ERROR, TAG, "Failed to provision Device 1 : %d", res);
     gOwnershipState = 0;
     while ( gOwnershipState == 0 )
     {
         if (OCProcess() != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             goto error;
         }
         sleep(1);
@@ -628,7 +661,7 @@ int main()
                                                                 NULL, ProvisionCertCB);
     if (OC_STACK_OK != res)
     {
-        OC_LOG_V(ERROR, TAG, "Failed to provision Device 2 : %d", res);
+        OIC_LOG_V(ERROR, TAG, "Failed to provision Device 2 : %d", res);
     }
 
     gOwnershipState = 0;
@@ -636,7 +669,7 @@ int main()
     {
         if (OCProcess() != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             goto error;
         }
         sleep(1);
@@ -649,13 +682,13 @@ int main()
     }
     else
     {
-        OC_LOG(ERROR, TAG, "InputACL error");
+        OIC_LOG(ERROR, TAG, "InputACL error");
         goto error;
     }
     res = OCProvisionACL(ctx, pOwnedDevices[Device2], gAcl, &ProvisionAclCB);
     if (OC_STACK_OK != res)
     {
-        OC_LOG_V(ERROR, TAG, "Failed to ACL provision Device 2 : %d", res);
+        OIC_LOG_V(ERROR, TAG, "Failed to ACL provision Device 2 : %d", res);
     }
 
     gOwnershipState = 0;
@@ -663,29 +696,36 @@ int main()
     {
         if (OCProcess() != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             goto error;
         }
         sleep(1);
     }
     gCrl = (OicSecCrl_t *)OICMalloc(sizeof(OicSecCrl_t));
+
+    if (NULL == gCrl)
+    {
+        OIC_LOG(ERROR, TAG, "Error while memory allocation");
+        goto error;
+    }
+
     if (PKI_SUCCESS != InputCRL(gCrl))
     {
-        OC_LOG(ERROR, TAG, "CA init error");
+        OIC_LOG(ERROR, TAG, "CA init error");
         goto error;
     }
 
     PRINT_BYTE_ARRAY("gCrl = \n", gCrl->CrlData);
 
     res = OCProvisionCRL(ctx, pOwnedDevices[Device2], gCrl, &ProvisionCrlCB);
-    if (OC_STACK_OK != res) OC_LOG_V(ERROR, TAG, "Failed to CRL provision Device 2 : %d", res);
+    if (OC_STACK_OK != res) OIC_LOG_V(ERROR, TAG, "Failed to CRL provision Device 2 : %d", res);
 
     gOwnershipState = 0;
     while (gOwnershipState == 0)
     {
         if (OCProcess() != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             goto error;
         }
         sleep(1);
@@ -693,7 +733,7 @@ int main()
 
     if (OCStop() != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack process error");
+        OIC_LOG(ERROR, TAG, "OCStack process error");
         goto error;
     }
 
index ec9bf74..dd02862 100644 (file)
@@ -111,7 +111,7 @@ PKIError GenerateCertificate (const UTF8String_t *subjectName, const UTF8String_
     CHECK_CALL(GetNextSerialNumber, &serialNumber);
     certificate->tbsCertificate.serialNumber = serialNumber;
     serialNumber++;
-    CHECK_CALL(SetNextSerialNumber, &serialNumber);
+    CHECK_CALL(SetNextSerialNumber, serialNumber);
     CHECK_CALL(SaveCKMInfo);
 
     //set signature algorithm in TBS
@@ -234,7 +234,10 @@ PKIError GenerateCertificate (const UTF8String_t *subjectName, const UTF8String_
             certificate->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.buf          = NULL;
             certificate->tbsCertificate.signature.algorithm.buf                            = NULL;
             certificate->tbsCertificate.subjectPublicKeyInfo.algorithm.algorithm.buf       = NULL;
-            certificate->tbsCertificate.subjectPublicKeyInfo.algorithm.id_ecPublicKey->buf = NULL;
+            if (certificate->tbsCertificate.subjectPublicKeyInfo.algorithm.id_ecPublicKey)
+            {
+                certificate->tbsCertificate.subjectPublicKeyInfo.algorithm.id_ecPublicKey->buf = NULL;
+            }
             certificate->signatureAlgorithm.algorithm.buf                                  = NULL;
         }
         ASN_STRUCT_FREE(asn_DEF_Certificate, certificate);
index df79fd5..ade8815 100644 (file)
 #include "crlresource.h"
 #include "oic_malloc.h"
 
+#ifdef __unix__
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+#endif // __unix__
+
 /* The first octet of the OCTET STRING indicates whether the key is
 compressed or uncompressed.  The uncompressed form is indicated by 0x04
 and the compressed form is indicated by either 0x02 or 0x03 (RFC 5480)*/
@@ -197,7 +203,6 @@ PKIError CKMIssueDeviceCertificate (const uint8_t *uint8SubjectName,
     uint8_t caPrivateKey[PRIVATE_KEY_SIZE];
     uint8_t uint8caName[ISSUER_MAX_NAME_SIZE];
 
-    CHECK_NULL(uint8SubjectPublicKey, ISSUER_NULL_PASSED);
     CHECK_NULL(issuedCertificate, ISSUER_NULL_PASSED);
     CHECK_NULL(issuedCertificate->data, ISSUER_NULL_PASSED);
     CHECK_LESS_EQUAL(ISSUER_MAX_CERT_SIZE, issuedCertificate->len, ISSUER_WRONG_BYTE_ARRAY_LEN);
@@ -311,14 +316,37 @@ PKIError CKMIssueDeviceCertificate (const uint8_t *uint8SubjectName,
     );
 }
 
-PKIError GenerateDERCertificateFile (const ByteArray *certificate, const char *certFileName)
+PKIError GenerateDERCertificateFile (const ByteArray *certificate, const char * const certFileName)
 {
     FUNCTION_INIT();
+
+#ifdef __unix__
+    struct stat st;
+    int fd = -1;
+#else
     FILE *filePointer = NULL;
+#endif
 
     CHECK_NULL(certFileName, ISSUER_NULL_PASSED);
     CHECK_NULL(certificate, ISSUER_NULL_PASSED);
     CHECK_NULL(certificate->data, ISSUER_NULL_PASSED);
+
+#ifdef __unix__
+    fd = open(certFileName, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
+    CHECK_NOT_EQUAL(fd, -1, ISSUER_NULL_PASSED);
+    CHECK_EQUAL(fstat(fd, &st), 0, ISSUER_NULL_PASSED);
+    CHECK_COND(S_ISREG(st.st_mode), ISSUER_FILE_WRITE_ERROR);
+    CHECK_COND(!S_ISLNK(st.st_mode), ISSUER_FILE_WRITE_ERROR);
+    CHECK_EQUAL(write(fd, certificate->data, certificate->len), (ssize_t) certificate->len,
+            ISSUER_FILE_WRITE_ERROR);
+
+    FUNCTION_CLEAR(
+        if(-1 != fd)
+        {
+            close(fd);
+        }
+    );
+#else
     filePointer = fopen(certFileName, "wb");
     CHECK_NULL(filePointer, ISSUER_FILE_WRITE_ERROR);
     CHECK_EQUAL(fwrite(certificate->data, 1, certificate->len, filePointer), certificate->len,
@@ -326,11 +354,13 @@ PKIError GenerateDERCertificateFile (const ByteArray *certificate, const char *c
 
     FUNCTION_CLEAR(
         if(filePointer)
-            {
-                fclose(filePointer);
-            }
+        {
+            fclose(filePointer);
+        }
         filePointer = NULL;
     );
+#endif
+
 }
 
 PKIError SetSerialNumber (const long serNum)
@@ -339,7 +369,7 @@ PKIError SetSerialNumber (const long serNum)
 
     CHECK_LESS_EQUAL(0, serNum, ISSUER_WRONG_SERIAL_NUMBER);
     CHECK_CALL(InitCKMInfo);
-    CHECK_CALL(SetNextSerialNumber, &serNum);
+    CHECK_CALL(SetNextSerialNumber, serNum);
     CHECK_CALL(SaveCKMInfo);
 
     FUNCTION_CLEAR();
@@ -426,8 +456,11 @@ PKIError GenerateCSR (const uint8_t *uint8SubjectName,
     FUNCTION_CLEAR(
         OICFree(subjectName);
         OICFree(subjectPublicKey);
-        OICFree(subjectPrivateKey->buf);
-        OICFree(subjectPrivateKey);
+        if (subjectPrivateKey)
+        {
+            OICFree(subjectPrivateKey->buf);
+            OICFree(subjectPrivateKey);
+        }
     );
 }
 
@@ -582,7 +615,7 @@ PKIError CKMRevocateCertificate (const uint8_t *uint8ThisUpdateTime, const long
     CHECK_CALL(InitCKMInfo);
     CHECK_CALL(GetNumberOfRevoked, &numberOfRevoked);
 
-    crlMaxSize = (CRL_MIN_SIZE +
+    crlMaxSize = (uint32_t)(CRL_MIN_SIZE +
             (numberOfRevoked + 1) * (sizeof(CertificateRevocationInfo_t) + 4));
 
     CHECK_NULL(encodedCRL, ISSUER_NULL_PASSED);
@@ -643,9 +676,9 @@ PKIError CKMRevocateCertificate (const uint8_t *uint8ThisUpdateTime, const long
     CHECK_CALL(InitCKMInfo);
     CHECK_CALL(GetCRLSerialNumber, &serialNumber);
     serialNumber++;
-    CHECK_CALL(SetCRLSerialNumber, &serialNumber);
+    CHECK_CALL(SetCRLSerialNumber, serialNumber);
     numberOfRevoked++;
-    CHECK_CALL(SetNumberOfRevoked, &numberOfRevoked);
+    CHECK_CALL(SetNumberOfRevoked, numberOfRevoked);
     CHECK_CALL(SetCertificateRevocationList, encodedCRL);
     CHECK_CALL(SaveCKMInfo);
 
index cd4bf15..2aea365 100644 (file)
 #include "crlresource.h"
 #include "crl_generator.h"
 
+#ifdef __unix__
+#include <sys/stat.h>
+#endif // __unix__
+
 //constants used in ckmInfo
 #define CKM_INFO_IS_NOT_LOADED                       (0)
 #define CKM_INFO_IS_LOADED                           (1)
@@ -84,6 +88,14 @@ PKIError InitCKMInfo(void)
         }
         else ////create new storage
         {
+#ifdef __unix__
+            struct stat st;
+            if (0 == lstat(CA_STORAGE_FILE, &st))
+            {
+                CHECK_COND(S_ISREG(st.st_mode), ISSUER_FILE_WRITE_ERROR);
+                CHECK_COND(!S_ISLNK(st.st_mode), ISSUER_FILE_WRITE_ERROR);
+            }
+#endif
             filePointer = fopen(CA_STORAGE_FILE, "wb");
             CHECK_NULL(filePointer, ISSUER_CA_STORAGE_FILE_WRITE_ERROR);
             objectsWrote = fwrite(&g_ckmInfo, sizeof(CKMInfo_t), count, filePointer);
@@ -108,8 +120,18 @@ PKIError SaveCKMInfo(void)
     FILE *filePointer = NULL;
     int count = 1;
     int objectsWrote = 0;
+#ifdef __unix__
+    struct stat st;
+#endif
 
     CHECK_COND(g_ckmInfo.CKMInfoIsLoaded, CKM_INFO_IS_NOT_INIT);
+#ifdef __unix__
+    if (0 == lstat(CA_STORAGE_FILE, &st))
+    {
+        CHECK_COND(S_ISREG(st.st_mode), ISSUER_FILE_WRITE_ERROR);
+        CHECK_COND(!S_ISLNK(st.st_mode), ISSUER_FILE_WRITE_ERROR);
+    }
+#endif
     filePointer = fopen(CA_STORAGE_FILE, "wb");
     CHECK_NULL(filePointer, ISSUER_CA_STORAGE_FILE_WRITE_ERROR);
     objectsWrote = fwrite(&g_ckmInfo, sizeof(CKMInfo_t), count, filePointer);
@@ -146,7 +168,7 @@ PKIError CloseCKMInfo(void)
     FUNCTION_CLEAR();
 }
 
-PKIError SetCKMInfo (const long *nextSN, const long *CRLSerialNumber,
+PKIError SetCKMInfo (const long nextSN, const long CRLSerialNumber,
                      const ByteArray *CAPrivateKey, const ByteArray *CAPublicKey,
                      const ByteArray *CAName)
 {
@@ -237,7 +259,7 @@ PKIError SetCAName (const ByteArray *CAName)
     CHECK_NULL_BYTE_ARRAY_PTR(CAName, ISSUER_CA_STORAGE_NULL_PASSED);
     CHECK_LESS_EQUAL(CAName->len, ISSUER_MAX_NAME_SIZE, ISSUER_CA_STORAGE_WRONG_CA_NAME_LEN);
     memcpy(g_ckmInfo.CAName, CAName->data, CAName->len);
-    g_ckmInfo.CANameSize = CAName->len;
+    g_ckmInfo.CANameSize = (uint32_t)CAName->len;
 
     FUNCTION_CLEAR();
 }
@@ -297,7 +319,7 @@ PKIError InitCRT(void)
 
         for (int i = 0; i < g_ckmInfo.CAChainLength; i++)
         {
-            objectsRead = fread(prefix, sizeof(uint8_t), CERT_LEN_PREFIX, filePointer);
+            objectsRead = (uint32_t)fread(prefix, sizeof(uint8_t), CERT_LEN_PREFIX, filePointer);
             CHECK_EQUAL(objectsRead, CERT_LEN_PREFIX, ISSUER_CA_STORAGE_CRT_READ_ERROR);
             g_ckmInfo.CACertificateChain[i].len = ParseCertPrefix(prefix);
 
@@ -305,7 +327,7 @@ PKIError InitCRT(void)
                             (uint8_t *)OICMalloc(g_ckmInfo.CACertificateChain[i].len);
             CHECK_NULL(g_ckmInfo.CACertificateChain[i].data,
                        ISSUER_CA_STORAGE_MEMORY_ALLOC_FAILED);
-            objectsRead = fread(g_ckmInfo.CACertificateChain[i].data, sizeof(uint8_t),
+            objectsRead = (uint32_t)fread(g_ckmInfo.CACertificateChain[i].data, sizeof(uint8_t),
                                 g_ckmInfo.CACertificateChain[i].len, filePointer);
             CHECK_EQUAL(objectsRead, g_ckmInfo.CACertificateChain[i].len,
                         ISSUER_CA_STORAGE_CRT_READ_ERROR);
@@ -326,16 +348,23 @@ PKIError SaveCRT(void)
     FILE *filePointer = NULL;
     uint32_t objectsWrote = 0;
     uint8_t prefix[CERT_LEN_PREFIX] = {0};
-
+#ifdef __unix__
+    struct stat st;
+    if (0 == lstat(CA_STORAGE_CRT_FILE, &st))
+    {
+        CHECK_COND(S_ISREG(st.st_mode), ISSUER_FILE_WRITE_ERROR);
+        CHECK_COND(!S_ISLNK(st.st_mode), ISSUER_FILE_WRITE_ERROR);
+    }
+#endif
     filePointer = fopen(CA_STORAGE_CRT_FILE, "wb");
     CHECK_NULL(filePointer, ISSUER_CA_STORAGE_CRT_WRITE_ERROR);
 
     for (int i = 0; i < g_ckmInfo.CAChainLength; i++)
     {
         WriteCertPrefix(prefix, g_ckmInfo.CACertificateChain[i].len);
-        objectsWrote = fwrite(prefix, sizeof(uint8_t), CERT_LEN_PREFIX, filePointer);
+        objectsWrote = (uint32_t)fwrite(prefix, sizeof(uint8_t), CERT_LEN_PREFIX, filePointer);
         CHECK_EQUAL(objectsWrote, CERT_LEN_PREFIX, ISSUER_CA_STORAGE_CRT_WRITE_ERROR);
-        objectsWrote = fwrite(g_ckmInfo.CACertificateChain[i].data, sizeof(uint8_t),
+        objectsWrote = (uint32_t)fwrite(g_ckmInfo.CACertificateChain[i].data, sizeof(uint8_t),
                               g_ckmInfo.CACertificateChain[i].len, filePointer);
         CHECK_EQUAL(objectsWrote, g_ckmInfo.CACertificateChain[i].len,
                     ISSUER_CA_STORAGE_CRT_WRITE_ERROR);
@@ -351,12 +380,11 @@ PKIError SaveCRT(void)
 }
 
 /*Serial Number*/
-PKIError SetNextSerialNumber (const long *nextSN)
+PKIError SetNextSerialNumber (const long nextSN)
 {
     FUNCTION_INIT();
-    CHECK_NULL(nextSN, ISSUER_CA_STORAGE_NULL_PASSED);
-    CHECK_LESS_EQUAL(0, *nextSN, ISSUER_CA_STORAGE_WRONG_SERIAL_NUMBER);
-    g_ckmInfo.nextSerialNumber = *nextSN;
+    CHECK_LESS_EQUAL(0, nextSN, ISSUER_CA_STORAGE_WRONG_SERIAL_NUMBER);
+    g_ckmInfo.nextSerialNumber = nextSN;
 
     FUNCTION_CLEAR();
 }
@@ -457,12 +485,11 @@ PKIError SaveCRL(void)
 }
 
 /*CRL Serial Number*/
-PKIError SetCRLSerialNumber (const long *CRLSerialNumber)
+PKIError SetCRLSerialNumber (const long CRLSerialNumber)
 {
     FUNCTION_INIT();
-    CHECK_NULL(CRLSerialNumber, ISSUER_CA_STORAGE_NULL_PASSED);
-    CHECK_LESS_EQUAL(0, *CRLSerialNumber, ISSUER_CA_STORAGE_WRONG_CRL_SERIAL_NUMBER);
-    g_ckmInfo.CRLSerialNumber = *CRLSerialNumber;
+    CHECK_LESS_EQUAL(0, CRLSerialNumber, ISSUER_CA_STORAGE_WRONG_CRL_SERIAL_NUMBER);
+    g_ckmInfo.CRLSerialNumber = CRLSerialNumber;
 
     FUNCTION_CLEAR();
 }
@@ -498,11 +525,13 @@ PKIError SetCertificateRevocationList (const ByteArray *certificateRevocationLis
 
 PKIError GetCertificateRevocationList (ByteArray *certificateRevocationList)
 {
-    FUNCTION_INIT();
+    FUNCTION_INIT(
+        OicSecCrl_t *tmpCRL = NULL;
+    );
     CHECK_COND(g_crlInfo.CrlData.data, ISSUER_CA_STORAGE_CRL_UNDEFINED);
     CHECK_NULL_BYTE_ARRAY_PTR(certificateRevocationList, ISSUER_CA_STORAGE_NULL_PASSED);
-    OicSecCrl_t *tmpCRL;
     tmpCRL = (OicSecCrl_t *)GetCRLResource();
+    CHECK_NULL(tmpCRL, ISSUER_CA_STORAGE_NULL_PASSED);
     g_crlInfo.CrlId = tmpCRL->CrlId;
     g_crlInfo.CrlData = tmpCRL->CrlData;
     g_crlInfo.ThisUpdate = tmpCRL->ThisUpdate;
@@ -513,16 +542,15 @@ PKIError GetCertificateRevocationList (ByteArray *certificateRevocationList)
     certificateRevocationList->len = g_crlInfo.CrlData.len;
 
     FUNCTION_CLEAR(
-            OICFree(tmpCRL);
+        OICFree(tmpCRL);
     );
 }
 
-PKIError SetNumberOfRevoked (const long *numberOfRevoked)
+PKIError SetNumberOfRevoked (const long numberOfRevoked)
 {
     FUNCTION_INIT();
-    CHECK_NULL(numberOfRevoked, ISSUER_CA_STORAGE_NULL_PASSED);
-    CHECK_LESS_EQUAL(0, *numberOfRevoked, ISSUER_CA_STORAGE_WRONG_CRL_SERIAL_NUMBER);
-    g_ckmInfo.numberOfRevoked = *numberOfRevoked;
+    CHECK_LESS_EQUAL(0, numberOfRevoked, ISSUER_CA_STORAGE_WRONG_CRL_SERIAL_NUMBER);
+    g_ckmInfo.numberOfRevoked = numberOfRevoked;
 
     FUNCTION_CLEAR();
 }
index 1c48dea..e6b0666 100644 (file)
@@ -31,7 +31,7 @@ static const uint8_t g_ECDSA_WITH_SHA256_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D,
 static const uint8_t g_COMMON_NAME_OID[] = {0x55, 0x04, 0x03};
 
 PKIError GenerateCRL (const UTF8String_t *issuerName,
-                       const UTCTime_t *thisUpdateTime, const uint32_t nuberOfRevoked,
+                       const UTCTime_t *thisUpdateTime, const uint32_t numberOfRevoked,
                        const CertificateRevocationInfo_t *certificateRevocationInfo,
                        const BIT_STRING_t *issuerPrivateKey, ByteArray *encodedCRL)
 {
@@ -42,8 +42,8 @@ PKIError GenerateCRL (const UTF8String_t *issuerName,
     RelativeDistinguishedName_t *issuerRDN          = NULL;
     CertificateRevocationInfo_t *cri                = NULL;
 
-    uint32_t crlMaxSize = (CRL_MIN_SIZE +
-            nuberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4));
+    uint32_t crlMaxSize = (uint32_t)(CRL_MIN_SIZE +
+            numberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4));
 
     uint32_t i;
     long serialNumber = 0;
@@ -95,7 +95,7 @@ PKIError GenerateCRL (const UTF8String_t *issuerName,
     certificateRevocationList->tbsCertList.thisUpdate = *thisUpdateTime;
 
     //add revoked info
-    for ( i = 0; i < nuberOfRevoked; i++)
+    for ( i = 0; i < numberOfRevoked; i++)
     {
         cri = OICCalloc(1, sizeof(CertificateRevocationInfo_t));
         CHECK_NULL(cri, ISSUER_CRL_ENCODER_MEMORY_ALLOC_FAILED);
@@ -116,8 +116,8 @@ PKIError GenerateCRL (const UTF8String_t *issuerName,
     CHECK_CALL(InitCKMInfo);
     CHECK_CALL(GetCRLSerialNumber, &serialNumber);
     serialNumber++;
-    CHECK_CALL(SetCRLSerialNumber, &serialNumber);
-    CHECK_CALL(SetNumberOfRevoked, (const long *)&nuberOfRevoked);
+    CHECK_CALL(SetCRLSerialNumber, serialNumber);
+    CHECK_CALL(SetNumberOfRevoked, numberOfRevoked);
     CHECK_CALL(SaveCKMInfo);
 
     FUNCTION_CLEAR(
diff --git a/resource/csdk/security/provisioning/ck_manager/tools/x509_check.c b/resource/csdk/security/provisioning/ck_manager/tools/x509_check.c
deleted file mode 100644 (file)
index bb63292..0000000
+++ /dev/null
@@ -1,197 +0,0 @@
-/******************************************************************
- *
- * 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
- *
- *      LICENSE-2.0" target="_blank">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 <stdio.h>
-#include <stdint.h>
-#include <getopt.h>
-
-#include "byte_array.h"
-#include "pki_errors.h"
-#include "pki.h"
-#include "crl.h"
-#include "oic_malloc.h"
-
-#define SUCCESS_RES            0
-#define FAIL_RES               1
-
-const char COMMAND_CRT[] = "crt";
-const char COMMAND_CRL[] = "crl";
-
-/**
- * Shows program usage hint.
- */
-void Usage()
-{
-    printf("Use next command:\n");
-    printf("x509_check -c <crt/crl> -f <path to crt/crl file> -s <path to CA certificate>\n");
-    printf("\t[-c]\t command name crt | crl\n");
-    printf("\t[-f]\t path to crt/crl file\n");
-    printf("\t[-s]\t path to CA certificate>\n");
-}
-
-/**
- * Converts DER file to byte array.
- *
- * @param[in]  filePath - path to DER file (Certificate or CRL)
- * @param[out] caPublicKey - ByteArray with DER encoded CRT or CRL
- */
-void FileToByteArray(const char *filePath, ByteArray *out)
-{
-    if (!filePath)
-    {
-        printf("File path is NULL!\n");
-        exit(0);
-    }
-
-    FILE *inFile = fopen(filePath, "rb");
-
-    if (!inFile)
-    {
-        printf("Specified file doesn't exist!\n");
-        exit(0);
-    }
-
-    fseek(inFile, 0, SEEK_END);
-    out->len = ftell(inFile);
-    rewind(inFile);
-    out->data = (uint8_t *)OICMalloc(out->len);
-
-    if (!out->data)
-    {
-        printf("Impossible to allocate memory!\n");
-        exit(0);
-    }
-
-    if (!fread(out->data, sizeof(uint8_t), out->len, inFile))
-    {
-        printf("No info in file!\n");
-        exit(0);
-    }
-    fclose(inFile);
-}
-
-/**
- * Main function.
- *
- * Checks certificate and certificate revocation list
- *
- * @param[in]  argc An integer argument count of the command line arguments
- * @param[in]  argv An argument vector of the command line arguments
- *
- * @return[out] an integer 0 upon exit success
- */
-int main(int argc, char *argv[])
-{
-    int isCrt = 0;
-    const char *testedFileName = 0;
-    const char *caCrtFileName = 0;
-
-    // Parse command line arguments
-    int opt;
-
-    while ((opt = getopt(argc, argv, "c:f:s:")) != -1)
-    {
-        switch (opt)
-        {
-            case 'c':
-                if (!strcmp(COMMAND_CRT, optarg))
-                {
-                    isCrt = 1;
-                }
-                else if (!strcmp(COMMAND_CRL, optarg))
-                {
-                    isCrt = 0;
-                }
-                else
-                {
-                    printf("Wrong command(-c)!\n");
-                    Usage();
-                    exit(0);
-                }
-                break;
-            case 'f':
-                testedFileName = optarg;
-                break;
-            case 's':
-                caCrtFileName = optarg;
-                break;
-            default:
-                Usage();
-                exit(0);
-        }
-    }
-
-    if (testedFileName == NULL || caCrtFileName == NULL)
-    {
-        printf("Wrong file name\n");
-        Usage();
-        exit(0);
-    }
-
-    // main
-    ByteArray testedCrtCrl = BYTE_ARRAY_INITIALIZER; // Could contain either Certificate or CRL
-    ByteArray caCrt = BYTE_ARRAY_INITIALIZER;
-
-    // Copy DER files, specified in command line to ByteArray structure
-    FileToByteArray(testedFileName, &testedCrtCrl);
-    FileToByteArray(caCrtFileName, &caCrt);
-
-    // Decoding CA certificate
-    CertificateX509 caCrtStuct = CERTIFICATE_X509_INITIALIZER;
-    PKIError errorCode = DecodeCertificate(caCrt, &caCrtStuct);
-
-    if (errorCode != PKI_SUCCESS)
-    {
-        printf("Unable to decode CA Certificate!\n");
-        printf("Error code: %d\n", errorCode);
-    }
-
-    ByteArray caPublicKey = BYTE_ARRAY_INITIALIZER;
-    // Verifies Certificate or CRL depending on request
-    if (isCrt)
-    {
-        errorCode = CheckCertificate(testedCrtCrl, caCrtStuct.pubKey);
-    }
-    else
-    {
-        caPublicKey.data = caCrtStuct.pubKey.data;
-        caPublicKey.len = caCrtStuct.pubKey.len;
-        ParsePublicKey(&caPublicKey);
-        CertificateList crlStruct = CRL_INITIALIZER;
-        errorCode = DecodeCertificateList(testedCrtCrl, &crlStruct, caPublicKey);
-    }
-
-    if (errorCode == PKI_SUCCESS)
-    {
-        printf("Verification SUCCESS!\n");
-    }
-    else
-    {
-        printf("Verification FAILED!\n");
-        printf("Error code: %d\n", errorCode);
-    }
-
-    // Free the allocated memory
-    OICFree(testedCrtCrl.data);
-    OICFree(caCrt.data);
-
-    return 0;
-}
diff --git a/resource/csdk/security/provisioning/ck_manager/tools/x509_issue.c b/resource/csdk/security/provisioning/ck_manager/tools/x509_issue.c
deleted file mode 100644 (file)
index 353971e..0000000
+++ /dev/null
@@ -1,256 +0,0 @@
-/******************************************************************
- *
- * 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
- *
- *      LICENSE-2.0" target="_blank">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 <stdio.h>
-#include <stdint.h>
-#include <getopt.h>
-
-#include "byte_array.h"
-#include "ck_manager.h"
-#include "crl.h"
-
-#define SUCCESS_RES            0
-#define FAIL_RES               1
-
-const char COMMAND_CRT[] = "crt";
-const char COMMAND_CRL[] = "crl";
-
-#define DEFAULT_SN             1
-
-#define DEFAULT_CA_CRT_NAME           "ca_crt.der"
-#define DEFAULT_CA_PUBLIC_KEY_NAME    "ca_public.key"
-#define DEFAULT_USER_PRIVATE_KEY_NAME "user_private.key"
-#define DEFAULT_USER_CRT_NAME         "user_crt.der"
-#define DEFAULT_CRL_NAME              "crl.der"
-
-#define DEFAULT_DER_DATA_SIZE  1024
-#define SET_OF_SEQUENCE_SIZE   4
-#define NUMBER_OF_REVOKED      1
-
-/**
- * Shows program usage hint.
- */
-void Usage()
-{
-    printf("Use next command:\n");
-    printf("x509_issue -c <crt/crl> [-n]\n");
-    printf("\t[-c]\t command name crt | crl\n");
-    printf("\t[-n]\t generate new CA key pair\n");
-}
-
-/**
- * Generates CA Certificate File, writes CA private and public keys to storage
- *
- * @param[in]  updateCAkeys use new or old keys
-*/
-int GenerateCACertificateFile(const int updateCAkeys)
-{
-    // Variables definition
-    uint8_t derData[DEFAULT_DER_DATA_SIZE] = {0};
-    uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0};
-    uint8_t caPrivKey[PRIVATE_KEY_SIZE] = {0};
-    uint8_t defaultCaName[] = "Default_CA_Name";
-
-    ByteArray certDer = BYTE_ARRAY_CONSTRUCTOR(derData);
-    ByteArray pubKeyIss = BYTE_ARRAY_CONSTRUCTOR(caPubKey);
-    ByteArray privKeyIss = BYTE_ARRAY_CONSTRUCTOR(caPrivKey);
-    ByteArray rootName = BYTE_ARRAY_CONSTRUCTOR(defaultCaName);
-
-    // Generate
-    if (updateCAkeys)
-    {
-        GenerateCAKeyPair(&privKeyIss, &pubKeyIss);
-        printf("CA key pair was changed!\n");
-        if (GenerateDERCertificateFile(&pubKeyIss, DEFAULT_CA_PUBLIC_KEY_NAME) != PKI_SUCCESS)
-        {
-            printf("Unable to generate CA public key file!\n");
-            exit(0);
-        }
-        else
-        {
-            printf("CA public key file generated: %s\n", DEFAULT_CA_PUBLIC_KEY_NAME);
-        };
-    }
-
-    SetSerialNumber(DEFAULT_SN);
-    SetRootName(rootName);
-    CKMIssueRootCertificate(0, 0, &certDer);
-
-    // Writes ByteArray to file
-    if (GenerateDERCertificateFile(&certDer, DEFAULT_CA_CRT_NAME) != PKI_SUCCESS)
-    {
-        printf("Unable to generate CA Certificate file!\n");
-        exit(0);
-    }
-    else
-    {
-        printf("CA Certificate File generated: %s\n", DEFAULT_CA_CRT_NAME);
-    };
-    return 0;
-}
-
-/**
- * Generates User Certificate File
- */
-void GenerateUserCertificateFile()
-{
-    uint8_t subjPubKey[PUBLIC_KEY_SIZE] = {0};
-    uint8_t subjPrivKey[PRIVATE_KEY_SIZE] = {0};
-
-    ByteArray pubKeySubj = BYTE_ARRAY_CONSTRUCTOR(subjPubKey);
-    ByteArray privKeySubj = BYTE_ARRAY_CONSTRUCTOR(subjPrivKey);
-
-    // TODO: Uncomment GenerateKeyPair
-    GenerateKeyPair(&privKeySubj, &pubKeySubj);
-
-    if (GenerateDERCertificateFile(&privKeySubj, DEFAULT_USER_PRIVATE_KEY_NAME) != PKI_SUCCESS)
-    {
-        printf("Unable to generate user private key file!\n");
-        exit(0);
-    }
-    else
-    {
-        printf("User private key file generated: %s\n", DEFAULT_USER_PRIVATE_KEY_NAME);
-    };
-
-    uint8_t derData[DEFAULT_DER_DATA_SIZE] = {0};
-    ByteArray certDer = BYTE_ARRAY_CONSTRUCTOR(derData);
-
-    const uint8_t defaultUserName[]   = "Default_USER_Name";
-
-    CKMIssueDeviceCertificate(defaultUserName, 0, 0, subjPubKey, &certDer);
-
-    if (GenerateDERCertificateFile(&certDer, DEFAULT_USER_CRT_NAME) != PKI_SUCCESS)
-    {
-        printf("Unable to generate User Certificate file!\n");
-        exit(0);
-    }
-    else
-    {
-        printf("User Certificate File generated: %s\n", DEFAULT_USER_CRT_NAME);
-    };
-}
-
-/**
- * Generates Certificate Revocation List File
- */
-void GenerateCRLFile()
-{
-    const uint8_t *uint8ThisUpdateTime = (const uint8_t *)"130101000000Z";
-    uint32_t revokedNumbers[NUMBER_OF_REVOKED] = {100};
-    const uint8_t *revocationDates[NUMBER_OF_REVOKED] =
-    {
-        (const uint8_t *)"130101000001Z"
-    };
-
-    ByteArray code =
-    {
-        .len = CRL_MIN_SIZE + NUMBER_OF_REVOKED * (sizeof(CertificateRevocationInfo_t) + SET_OF_SEQUENCE_SIZE),
-        .data = (uint8_t *)calloc(1, CRL_MIN_SIZE + NUMBER_OF_REVOKED * (sizeof(CertificateRevocationInfo_t) + SET_OF_SEQUENCE_SIZE))
-    };
-
-    if (!code.data)
-    {
-        printf("calloc error\n");
-        exit(0);
-    }
-
-    int errorCode = CKMIssueCRL(uint8ThisUpdateTime, NUMBER_OF_REVOKED, revokedNumbers, revocationDates,
-                                &code);
-
-    printf("Gen CRL err code: %d\n", errorCode);
-
-    //CRL ByteArray to file
-    if (GenerateDERCertificateFile(&code, DEFAULT_CRL_NAME) != PKI_SUCCESS)
-    {
-        printf("Unable to generate CRL file!\n");
-        free(code.data);
-        exit(0);
-    }
-    else
-    {
-        printf("CRL File generated: %s\n", DEFAULT_CRL_NAME);
-    };
-
-    free(code.data);
-}
-
-/**
- * Main function.
- *
- * Generates certificate and certificate revocation list
- *
- * @param[in]  argc An integer argument count of the command line arguments
- * @param[in]  argv An argument vector of the command line arguments
- *
- * @return[out] an integer 0 upon exit success
- */
-int main(int argc, char *argv[])
-{
-    int isCrt = 0;
-    int updateCAkeys = 0;
-
-    // Parse command line arguments
-    int opt;
-
-    while ((opt = getopt(argc, argv, "c:n")) != -1)
-    {
-        switch (opt)
-        {
-            case 'c':
-                if (!strcmp(COMMAND_CRT, optarg))
-                {
-                    isCrt = 1;
-                }
-                else if (!strcmp(COMMAND_CRL, optarg))
-                {
-                    isCrt = 0;
-                }
-                else
-                {
-                    printf("Wrong command(-c)!\n");
-                    Usage();
-                    exit(0);
-                }
-                break;
-            case 'n':
-                updateCAkeys = 1;
-                break;
-            default:
-                Usage();
-                exit(0);
-        }
-    }
-
-    // main
-    GenerateCACertificateFile(updateCAkeys);
-
-    if (isCrt)
-    {
-        GenerateUserCertificateFile();
-    }
-    else
-    {
-        GenerateCRLFile();
-    }
-
-    return 0;
-}
index f92fcdf..6218806 100644 (file)
@@ -82,7 +82,7 @@ pki_test_env.Alias("install",env.Install( unittest_build_dir, [ unittest_src_dir
                                                                unittest_src_dir + 'capub.der',
                                                                unittest_src_dir + 'cert_chain.dat',
                                                                unittest_src_dir + 'chain.der',
-                                                               unittest_src_dir + 'CKMInfo.json' ]))
+                                                               unittest_src_dir + 'CKMInfo.dat' ]))
 
 env.AppendTarget('test')
 if env.get('TEST') == '1':
index e2dc42d..e224b42 100644 (file)
@@ -19,7 +19,7 @@
 
  ******************************************************************/
 
-
+#include <fcntl.h>
 #include <iostream>
 #include <string.h>
 #include <oic_malloc.h>
@@ -43,7 +43,7 @@
 #define READ_WRITE_BLOCK_N 1ul
 #define N_LENGTH_BYTES 3
 
-const char *CKMI_JSON_FILE_NAME = "CKMInfo.json";
+const char *CKMI_PS_FILE_NAME = "CKMInfo.dat";
 
 #define CRL_DEFAULT_CRL_ID           1
 #define CRL_DEFAULT_THIS_UPDATE     "150101000000Z"
@@ -57,7 +57,7 @@ OCPersistentStorage ps = { NULL, NULL, NULL, NULL, NULL};
 
 FILE* ckm_fopen(const char * /*path*/, const char *mode)
 {
-    return fopen(CKMI_JSON_FILE_NAME, mode);
+    return fopen(CKMI_PS_FILE_NAME, mode);
 }
 
 void SetPersistentHandler(OCPersistentStorage *ps)
@@ -173,7 +173,7 @@ TEST(X509Certificate, RandomDecode)
 
     for (unsigned int i = 0; i < RUNS; i++)
     {
-        code.len = rand() % MAX_LEN;
+        code.len = (size_t)((size_t)rand() % MAX_LEN);
         code.data = (uint8_t *)malloc(code.len * sizeof(uint8_t));
 
         EXPECT_NE(code.data, (uint8_t *)NULL);
@@ -285,7 +285,7 @@ TEST_F(PKITest, TimeValidity)
         ASSERT_EQ(PKI_CERT_DATE_INVALID, CheckCertificate(certDer, pubKey));
 
         certDer.len = sizeof(derData);
-        ASSERT_EQ(PKI_SUCCESS, CKMIssueRootCertificate((uint8_t *)"160101000000Z", 0, &certDer));
+        ASSERT_EQ(PKI_SUCCESS, CKMIssueRootCertificate((uint8_t *)"170101000000Z", 0, &certDer));
         ASSERT_EQ(PKI_CERT_DATE_INVALID, CheckCertificate(certDer, pubKey));
     }
     ASSERT_EQ(PKI_SUCCESS, CloseCKMInfo());
@@ -368,44 +368,48 @@ TEST(X509Certificate, testParsePublicKey)
 //test checking of certificate generated by OpenSSL
 TEST(OpenSSLCompatibility, verifyOpenSslCertSign)
 {
+    struct stat st;
+    uint8_t crtData[ISSUER_MAX_CERT_SIZE] = {0};
+    uint8_t pubKeyData[PUBLIC_KEY_SIZE] = {0};
     ByteArray crtDer = BYTE_ARRAY_INITIALIZER;
+    ByteArray pubKey = BYTE_ARRAY_INITIALIZER;
     CertificateX509 certificate;
 
-    FILE *fileCert = fopen("01.der", "rb");
-    ASSERT_TRUE(fileCert != NULL);
+    crtDer.data = crtData;
+    crtDer.len = sizeof(crtData);
+    pubKey.data = pubKeyData;
+    pubKey.len = sizeof(pubKeyData);
 
-    //get the length
-    fseek(fileCert, 0, SEEK_END);
-    crtDer.len = ftell(fileCert);
-    fseek(fileCert, 0, SEEK_SET);
-    //allocate memory
-    crtDer.data = (uint8_t*)malloc(crtDer.len+1);
+    //open file
+    int fileCert = open("01.der", O_RDONLY);
+    ASSERT_TRUE(fileCert != -1);
+    //get status
+    ASSERT_TRUE(fstat(fileCert, &st) == 0);
     //read the content
-    EXPECT_EQ(READ_WRITE_BLOCK_N, fread(crtDer.data, crtDer.len, READ_WRITE_BLOCK_N, fileCert));
-    fclose(fileCert);
-
-    ByteArray pubKey = BYTE_ARRAY_INITIALIZER;
-    FILE * fileKey = fopen("capub.der", "rb");
-    ASSERT_TRUE(fileKey != NULL);
-    fseek(fileKey, 0, SEEK_END);
-    pubKey.len = ftell(fileKey);
-    fseek(fileKey, 0, SEEK_SET);
-    //openssl generates a public key that is longer than 64 bytes
-    //with additional 27 bytes prepending the actual key
-    if(pubKey.len > PUBLIC_KEY_SIZE){
-        fseek(fileKey, (pubKey.len - PUBLIC_KEY_SIZE), SEEK_SET);
-        pubKey.len = PUBLIC_KEY_SIZE;
+    int res = read(fileCert, crtDer.data, crtDer.len);
+    ASSERT_NE(-1, res);
+    EXPECT_EQ(st.st_size, res);
+    close(fileCert);
+
+     //open file
+    int fileKey = open("capub.der", O_RDONLY);
+    ASSERT_TRUE(fileKey != -1);
+    //get status
+    ASSERT_TRUE(fstat(fileKey, &st) == 0);
+
+    if(st.st_size > PUBLIC_KEY_SIZE)
+    {
+        ASSERT_NE(-1, lseek(fileKey, (st.st_size - PUBLIC_KEY_SIZE), SEEK_SET));
     }
-    pubKey.data = (uint8_t*)malloc(pubKey.len+1);
+
     //read the content
-    EXPECT_EQ(READ_WRITE_BLOCK_N, fread(pubKey.data, pubKey.len, READ_WRITE_BLOCK_N, fileKey));
-    fclose(fileKey);
+    res = read(fileKey, pubKey.data, pubKey.len);
+    ASSERT_NE(-1, res);
+    EXPECT_EQ(PUBLIC_KEY_SIZE, res);
+    close(fileKey);
 
     EXPECT_EQ(PKI_SUCCESS, DecodeCertificate(crtDer, &certificate));
     EXPECT_EQ(PKI_SUCCESS, CheckCertificate(crtDer, pubKey));
-
-    free(crtDer.data);
-    free(pubKey.data);
 }
 
 //test parsing of certificate chain generated by OpenSSL
@@ -441,30 +445,37 @@ TEST(CertificateChain, LoadCertificateChain)
 //test checking CA certificate generated by OpenSSL
 TEST(OpenSSLCompatibility, testOpenSSLCertificate)
 {
+    struct stat st;
     ByteArray crtDer = BYTE_ARRAY_INITIALIZER;
-    FILE *fileCert = fopen("cacert.der", "rb");
-    ASSERT_TRUE(fileCert != NULL);
+    uint8_t crtData[ISSUER_MAX_CERT_SIZE] = {0};
+
+    crtDer.data = crtData;
+    crtDer.len = sizeof(crtData);
+
+    //open file
+    int fd = open("cacert.der", O_RDONLY);
+    ASSERT_TRUE(fd != -1);
+    //get status
+    ASSERT_TRUE(fstat(fd, &st) == 0);
 
-    //get the length
-    fseek(fileCert, 0, SEEK_END);
-    crtDer.len = ftell(fileCert);
-    fseek(fileCert, 0, SEEK_SET);
-    //allocate memory
-    crtDer.data = (uint8_t*)malloc(crtDer.len+1);
     //read the content
-    EXPECT_EQ(READ_WRITE_BLOCK_N, fread(crtDer.data, crtDer.len, READ_WRITE_BLOCK_N, fileCert));
+    int res = read(fd, crtDer.data, crtDer.len);
+    ASSERT_NE(-1, res);
+    ASSERT_EQ(st.st_size, res);
+    close(fd);
+
+    crtDer.len = st.st_size;
 
-    fclose(fileCert);
     #ifdef X509_DEBUG
     printf("Length of cert: %lu\n", crtDer.len);
     #endif
     EXPECT_EQ(PKI_SUCCESS, DecodeCertificate(crtDer, &PKITest::g_certificate));
-    free(crtDer.data);
 }
 
 //test signatures checking of certificate chain generated by OpenSSL
 TEST(OpenSSLCompatibility, ParseAndCheckCertificateChain)
 {
+    struct stat st;
     ByteArray crtChainDer[MAX_CHAIN_LEN] = {{0,0},};
     CertificateX509 crtChain[MAX_CHAIN_LEN] = {{{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}},};
     ByteArray msg = BYTE_ARRAY_INITIALIZER;
@@ -475,13 +486,15 @@ TEST(OpenSSLCompatibility, ParseAndCheckCertificateChain)
     ASSERT_TRUE(fileChain != NULL);
 
     //get the length
-    fseek(fileChain, 0, SEEK_END);
-    msg.len = ftell(fileChain);
-    fseek(fileChain, 0, SEEK_SET);
+    ASSERT_NE(-1, fseek(fileChain, 0, SEEK_END));
+    int len = ftell(fileChain);
+    ASSERT_NE(-1, len);
+    msg.len = (size_t) len;
+    ASSERT_NE(-1, fseek(fileChain, 0, SEEK_SET));
     //allocate memory
     msg.data = (uint8_t*)malloc(msg.len+1);
     //read the content
-    EXPECT_EQ(READ_WRITE_BLOCK_N, fread(msg.data, msg.len, READ_WRITE_BLOCK_N, fileChain));
+    ASSERT_EQ(READ_WRITE_BLOCK_N, fread(msg.data, msg.len, READ_WRITE_BLOCK_N, fileChain));
 
     fclose (fileChain);
 
@@ -495,27 +508,31 @@ TEST(OpenSSLCompatibility, ParseAndCheckCertificateChain)
     EXPECT_EQ(PKI_SUCCESS, ParseCertificateChain(crtChainDer, crtChain, chainLength));
 
     ByteArray caPubKey = BYTE_ARRAY_INITIALIZER;
+    uint8_t pubKeyData[PUBLIC_KEY_SIZE] = {0};
+
+    caPubKey.data = pubKeyData;
+    caPubKey.len = sizeof(pubKeyData);
 
-    const char* caPubKeyPath = {"capub.der"};
-    FILE *fileCaPubKey = fopen(caPubKeyPath, "rb");
-    ASSERT_TRUE(fileCaPubKey != NULL);
+     //open file
+    int fileKey = open("capub.der", O_RDONLY);
+    ASSERT_TRUE(fileKey != -1);
+    //get status
+    ASSERT_TRUE(fstat(fileKey, &st) == 0);
 
-    fseek(fileCaPubKey, 0, SEEK_END);
-    caPubKey.len = ftell(fileCaPubKey);
-    fseek(fileCaPubKey, 0, SEEK_SET);
-    if(caPubKey.len > PUBLIC_KEY_SIZE){
-        fseek(fileCaPubKey, (caPubKey.len - PUBLIC_KEY_SIZE), SEEK_SET);
-        caPubKey.len = PUBLIC_KEY_SIZE;
+    if(st.st_size > PUBLIC_KEY_SIZE)
+    {
+        ASSERT_NE(-1, lseek(fileKey, (st.st_size - PUBLIC_KEY_SIZE), SEEK_SET));
     }
-    caPubKey.data = (uint8_t*)malloc(caPubKey.len+1);
+
     //read the content
-    EXPECT_EQ(READ_WRITE_BLOCK_N, fread(caPubKey.data, caPubKey.len, READ_WRITE_BLOCK_N, fileCaPubKey));
-    fclose(fileCaPubKey);
+    int res = read(fileKey, caPubKey.data, caPubKey.len);
+    ASSERT_NE(-1, res);
+    EXPECT_EQ(PUBLIC_KEY_SIZE, res);
+    close(fileKey);
 
     EXPECT_EQ(PKI_SUCCESS, CheckCertificateChain(crtChain, chainLength, caPubKey));
 
     free(msg.data - 3);
-    free(caPubKey.data);
 }
 
 //testing correctness of decoding certificate length from ASN.1 structure
@@ -578,7 +595,7 @@ TEST(SNStore, MemoryOverflow)
 TEST_F(PKITest, CAInitAndSerialNum)
 {
     ASSERT_EQ(PKI_SUCCESS, InitCKMInfo());
-    long serialNum = rand() % (MAX_LEN - 1) + 1;
+    long serialNum = (long)((long)rand() % (MAX_LEN - 1) + 1);
     ASSERT_EQ(PKI_SUCCESS, InitCKMInfo());
     //all the serials should start from
     ASSERT_EQ(PKI_SUCCESS, SetSerialNumber(serialNum));
@@ -592,7 +609,7 @@ TEST_F(PKITest, CAInitAndSerialNum)
 TEST_F(PKITest, testCAName)
 {
     ByteArray caName = BYTE_ARRAY_INITIALIZER;
-    caName.len = ((size_t)rand() % (ISSUER_MAX_NAME_SIZE - 1) + 1);
+    caName.len = (size_t)((size_t)rand() % (ISSUER_MAX_NAME_SIZE - 1) + 1);
     caName.data = (uint8_t*)malloc(caName.len);
     size_t i;
     for(i = 0; i < caName.len; i++){
@@ -768,6 +785,7 @@ TEST_F(PKITest, testRevocateCertificate)
 //checck correctness of saving root certificate to binary file
 TEST_F(PKITest, StoreCKMInfo)
 {
+    struct stat st;
     ASSERT_EQ(PKI_SUCCESS, InitCKMInfo());
     uint8_t derData[ISSUER_MAX_CERT_SIZE] = {0};
     uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0};
@@ -818,18 +836,22 @@ TEST_F(PKITest, StoreCKMInfo)
     // Check Certificate file
     CertificateX509 certificate;
     ByteArray crtDer = BYTE_ARRAY_INITIALIZER;
-    FILE *filePtr = fopen(CA_STORAGE_CRT_FILE , "rb");
-    ASSERT_TRUE(filePtr != NULL);
+    uint8_t crtDerData[ISSUER_MAX_CERT_SIZE] = {0};
 
-    //get the length
-    fseek(filePtr, 0, SEEK_END);
-    crtDer.len = ftell(filePtr);
-    fseek(filePtr, 0, SEEK_SET);
-    //allocate memory
-    crtDer.data = (uint8_t*)malloc(crtDer.len+1);
+    crtDer.data = crtDerData;
+    crtDer.len = sizeof(crtDerData);
+
+    //open file
+    int fd = open(CA_STORAGE_CRT_FILE, O_RDONLY);
+    ASSERT_TRUE(fd != -1);
+    //get status
+    ASSERT_TRUE(fstat(fd, &st) == 0);
     //read the content
-    EXPECT_EQ(READ_WRITE_BLOCK_N, fread(crtDer.data, crtDer.len, READ_WRITE_BLOCK_N, filePtr));
-    fclose(filePtr);
+    int res = read(fd, crtDer.data, crtDer.len);
+    ASSERT_NE(-1, res);
+    EXPECT_EQ(st.st_size > ISSUER_MAX_CERT_SIZE ? ISSUER_MAX_CERT_SIZE : st.st_size, res);
+    close(fd);
+
     ByteArray crtCheck;
     crtCheck.data = crtDer.data + 3;    //now file contains length of certificate
     crtCheck.len = crtDer.len - 3;
@@ -852,7 +874,6 @@ TEST_F(PKITest, StoreCKMInfo)
     EXPECT_EQ(PKI_SUCCESS, CloseCKMInfo());
     free(crlDer.data);
     free(code.data);
-    free(crtDer.data);
 }
 
 //check correctness of root certificate generation
@@ -948,6 +969,7 @@ TEST_F(PKITest, CRLSetGet)
 {
     OicSecCrl_t *defaultCrl = NULL;
     defaultCrl = (OicSecCrl_t *)OICCalloc(1, sizeof(OicSecCrl_t));
+    ASSERT_NE(defaultCrl, (OicSecCrl_t *) NULL);
     defaultCrl->CrlId = CRL_DEFAULT_CRL_ID;
     defaultCrl->CrlData.data = (uint8_t *)CRL_DEFAULT_CRL_DATA;
     defaultCrl->CrlData.len = strlen(CRL_DEFAULT_CRL_DATA);
@@ -955,7 +977,7 @@ TEST_F(PKITest, CRLSetGet)
     defaultCrl->ThisUpdate.len = strlen(CRL_DEFAULT_THIS_UPDATE);
     EXPECT_EQ(OC_STACK_OK, UpdateCRLResource(defaultCrl));
 
-    EXPECT_NE((void *)NULL, GetBase64CRL());
+    EXPECT_NE((void *)NULL, GetCrl());
     OICFree(defaultCrl);
 
 
@@ -963,6 +985,25 @@ TEST_F(PKITest, CRLSetGet)
 
 int main(int argc, char **argv)
 {
+    int urandom;
+    unsigned int seed = 0;
+
+    urandom = open ("/dev/urandom", O_RDONLY);
+    if(urandom)
+    {
+        fprintf(stderr, "Cannot open /dev/urandom\n");
+    }
+    else
+    {
+        if(read(urandom, &seed, sizeof(seed)) != sizeof(seed))
+        {
+            fprintf(stderr, "Error read from /dev/urandom\n");
+        }
+        close(urandom);
+    }
+
+    srand(seed);
+
     ::testing::InitGoogleTest(&argc, argv);
     return RUN_ALL_TESTS();
 }
diff --git a/resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.dat b/resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.dat
new file mode 100644 (file)
index 0000000..06454be
Binary files /dev/null and b/resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.dat differ
index d036473..dbdee77 100644 (file)
@@ -1,48 +1,99 @@
-{
-    "acl": [
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/res",
-                "/oic/d",
-                "/oic/p",
-                "/oic/res/types/d",
-                "/oic/ad"
-            ],
-            "perms": 2,
-            "ownrs" : ["YWRtaW5EZXZpY2VVVUlE"]
-        },
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/sec/doxm",
-                "/oic/sec/pstat",
-                "/oic/sec/acl",
-                "/oic/sec/cred"
-             ],
-             "perms": 7,
-             "ownrs" : ["YWRtaW5EZXZpY2VVVUlE"]
-        }
-    ],
-    "crl": {
-        "CRLId": 1,
-        "ThisUpdate": "MTUwMTAxMDAwMDAwWg==",
-        "CRLData": "LQ=="
-    },
-    "pstat": {
-        "isop": true,
-        "deviceid": "YWRtaW5EZXZpY2VVVUlE",
-        "ch": 0,
-        "cm":   0,
-        "tm":   0,
-        "om":   3,
-        "sm":   [3]
-    },
-    "doxm": {
-        "oxm":  [0],
-        "oxmsel": 0,
-        "owned": true,
-        "deviceid": "YWRtaW5EZXZpY2VVVUlE",
-        "ownr": "YWRtaW5EZXZpY2VVVUlE"
-    }
-}
+{\r
+    "acl": {\r
+        "aclist": {\r
+            "aces": [\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/res",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/p",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/types/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/ad",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/doxm",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        } ,\r
+                        {\r
+                            "href": "/oic/sec/pstat",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/acl",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/cred",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 7\r
+                }\r
+            ]\r
+        },\r
+        "rowneruuid" : "61646d69-6e44-6576-6963-655555494430"\r
+    },\r
+    "crl": {\r
+        "CRLId": 1,\r
+        "ThisUpdate": "150101000000Z",\r
+        "CRLData": "-"\r
+    },\r
+    "pstat": {\r
+        "isop": true,\r
+        "deviceuuid": "61646d69-6e44-6576-6963-655555494430",\r
+        "rowneruuid": "61646d69-6e44-6576-6963-655555494430",\r
+        "cm": 0,\r
+        "tm": 0,\r
+        "om": 3,\r
+        "sm": 3\r
+        },\r
+    "doxm": {\r
+        "oxms": [0],\r
+        "oxmsel": 0,\r
+        "sct": 1,\r
+        "owned": true,\r
+        "deviceuuid": "61646d69-6e44-6576-6963-655555494430",\r
+        "devowneruuid": "61646d69-6e44-6576-6963-655555494430",\r
+        "rowneruuid": "61646d69-6e44-6576-6963-655555494430",\r
+        "dpc": false\r
+    }\r
+}
\ No newline at end of file
index bcd7b8a..546bb28 100644 (file)
@@ -31,19 +31,20 @@ extern "C" {
 #endif // __cplusplus\r
 \r
 #define OXM_STRING_MAX_LENGTH 32\r
-\r
+#define WRONG_PIN_MAX_ATTEMP 5\r
 \r
 /**\r
  * Context for ownership transfer(OT)\r
  */\r
 typedef struct OTMContext{\r
-    void* userCtx;                         /**< Context for user.*/\r
-    OCProvisionDev_t* selectedDeviceInfo;  /**< Selected device info for OT. */\r
-    OicUuid_t subIdForPinOxm;              /**< Subject Id which uses PIN based OTM. */\r
-    OCProvisionResultCB ctxResultCallback; /**< Function pointer to store result callback. */\r
-    OCProvisionResult_t* ctxResultArray;   /**< Result array having result of all device. */\r
-    size_t ctxResultArraySize;             /**< No of elements in result array. */\r
-    bool ctxHasError;                      /**< Does OT process have any error. */\r
+    void* userCtx;                            /**< Context for user.*/\r
+    OCProvisionDev_t* selectedDeviceInfo;     /**< Selected device info for OT. */\r
+    OicUuid_t subIdForPinOxm;                 /**< Subject Id which uses PIN based OTM. */\r
+    OCProvisionResultCB ctxResultCallback;    /**< Function pointer to store result callback. */\r
+    OCProvisionResult_t* ctxResultArray;      /**< Result array having result of all device. */\r
+    size_t ctxResultArraySize;                /**< No of elements in result array. */\r
+    bool ctxHasError;                         /**< Does OT process have any error. */\r
+    int attemptCnt;\r
 }OTMContext_t;\r
 \r
 /**\r
@@ -74,17 +75,19 @@ typedef OCStackResult (*OTMCreateSecureSession)(OTMContext_t* otmCtx);
 /*\r
  * Callback for creating CoAP payload.\r
  */\r
-typedef char* (*OTMCreatePayloadCallback)(OTMContext_t* otmCtx);\r
+typedef OCStackResult (*OTMCreatePayloadCallback)(OTMContext_t* otmCtx, uint8_t **payload,\r
+                                                  size_t *size);\r
 \r
 /**\r
  * Required callback for performing ownership transfer\r
  */\r
-typedef struct OTMCallbackData{\r
+typedef struct OTMCallbackData\r
+{\r
     OTMLoadSecret loadSecretCB;\r
     OTMCreateSecureSession createSecureSessionCB;\r
     OTMCreatePayloadCallback createSelectOxmPayloadCB;\r
     OTMCreatePayloadCallback createOwnerTransferPayloadCB;\r
-}OTMCallbackData_t;\r
+} OTMCallbackData_t;\r
 \r
 /**\r
  * Set the callbacks for ownership transfer\r
@@ -95,7 +98,6 @@ typedef struct OTMCallbackData{
  */\r
 OCStackResult OTMSetOwnershipTransferCallbackData(OicSecOxm_t oxm, OTMCallbackData_t* callbackData);\r
 \r
-\r
 #ifdef __cplusplus\r
 }\r
 #endif\r
index 6a31a91..d37c48e 100644 (file)
@@ -120,6 +120,15 @@ OCStackResult PDMGetLinkedDevices(const OicUuid_t* uuidOfDevice, OCUuidList_t**
 OCStackResult PDMSetLinkStale(const OicUuid_t* uuidOfDevice1, const OicUuid_t* uuidOfDevice2);
 
 /**
+ * This method is used by provisioning manager to update device status as stale.
+ *
+ * @param[in] uuidOfDevice id of stale device.
+ *
+ * @return OC_STACK_OK in case of success and other value otherwise.
+ */
+OCStackResult PDMSetDeviceStale(const OicUuid_t* uuidOfDevice);
+
+/**
  * This method is used by provisioning manager to get stale devices.
  *
  * @note in case of sqllite, the caller should set NULL for parameters.
@@ -164,7 +173,8 @@ void PDMDestoryStaleLinkList(OCPairList_t* ptr);
  * @return OC_STACK_OK in case of success and other value otherwise.
  */
 OCStackResult PDMIsLinkExists(const OicUuid_t* uuidOfDevice1, const OicUuid_t* uuidOfDevice2,
-                                bool *result );
+                                bool *result);
+
 
 #ifdef __cplusplus
 }
index 2fff7f7..cc1f689 100644 (file)
@@ -41,6 +41,31 @@ extern "C"
  */
 OCStackResult SRPProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
                                         OicSecAcl_t *acl, OCProvisionResultCB resultCallback);
+                                        
+#ifdef __WITH_X509__
+/**
+ * API to send CRL information to resource.
+ *
+ * @param[in] selectedDeviceInfo Selected target device.
+ * @param[in] crl CRL to provision.
+ * @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 SRPProvisionCRL(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
+        OicSecCrl_t *crl, OCProvisionResultCB resultCallback);
+#endif // __WITH_X509__
+/**
+ * API to send Direct-Pairing Configuration to a device.
+ *
+ * @param[in] selectedDeviceInfo Selected target device.
+ * @param[in] pconf PCONF pointer.
+ * @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 SRPProvisionDirectPairing(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
+                                        OicSecPconf_t *pconf, OCProvisionResultCB resultCallback);
 
 /**
  * API to provision credential to devices.
index f5a057e..986c360 100644 (file)
@@ -47,7 +47,7 @@ OCStackResult OCInitPM(const char* dbPath);
  * OCMode.\r
  *\r
  * @param[in] timeout Timeout in seconds, value till which function will listen to responses from\r
- *                    client before returning the list of devices.\r
+ *                    server before returning the list of devices.\r
  * @param[out] ppList List of candidate devices to be provisioned\r
  * @return OTM_SUCCESS in case of success and other value otherwise.\r
  */\r
@@ -79,7 +79,7 @@ OCStackResult OCSetOwnerTransferCallbackData(OicSecOxm_t oxm, OTMCallbackData_t*
  * all the device in subnet which are owned by calling provisioning client.\r
  *\r
  * @param[in] timeout Timeout in seconds, value till which function will listen to responses from\r
- *                    client before returning the list of devices.\r
+ *                    server before returning the list of devices.\r
  * @param[out] ppList List of device owned by provisioning tool.\r
  * @return OTM_SUCCESS in case of success and other value otherwise.\r
  */\r
@@ -117,6 +117,19 @@ OCStackResult OCProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceIn
                              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
+ * @param[in] selectedDeviceInfo Selected target device.\r
+ * @param[in] pconf PCONF pointer.\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 OCProvisionDirectPairing(void* ctx, const OCProvisionDev_t *selectedDeviceInfo, OicSecPconf_t *pconf,\r
+                             OCProvisionResultCB resultCallback);\r
+\r
+/**\r
  * API to provision credential to devices.\r
  *\r
  * @param[in] ctx Application context would be returned in result callback.\r
@@ -176,7 +189,8 @@ OCStackResult OCRemoveDevice(void* ctx,
  * variables pOwnedDevList and pUnownedDevList.\r
  *\r
  * @param[in] waitime Wait time for the API. The wait time will be divided by 2, and half of wait time\r
- * will be used for unowned discovery and remaining half for owned discovery.\r
+ * will be used for unowned discovery and remaining half for owned discovery. So the wait time should be
+ * equal to or more than 2.
  * @param[out] pOwnedDevList  list of owned devices.\r
  * @param[out] pUnownedDevList  list of unowned devices.\r
  * @return OC_STACK_OK in case of success and other value otherwise.\r
@@ -216,6 +230,13 @@ void OCDeleteUuidList(OCUuidList_t* pList);
  * @param pAcl Pointer to OicSecAcl_t structure.\r
  */\r
 void OCDeleteACLList(OicSecAcl_t* pAcl);
+\r
+/**\r
+ * This function deletes PDACL data.\r
+ *\r
+ * @param pPdAcl Pointer to OicSecPdAcl_t structure.\r
+ */\r
+void OCDeletePdAclList(OicSecPdAcl_t* pPdAcl);\r
 
 #ifdef __WITH_X509__
 /**
index 4f2b112..0b9f81e 100644 (file)
@@ -1,22 +1,22 @@
-/*****************************************************************
- *
- * 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.
- *
- * *****************************************************************/
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #ifndef OXM_JUST_WORKS_H_
 #define OXM_JUST_WORKS_H_
@@ -35,36 +35,46 @@ extern "C" {
 
 /**
  * In case of just works OxM, no need to implement.
+ *
+ * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
  */
 OCStackResult LoadSecretJustWorksCallback(OTMContext_t* UNUSED_PARAM);
 
 /**
  * To establish a secure channel with anonymous cipher suite
  *
- * @param[in] selectedDeviceInfo Selected device infomation
- * @return OC_STACK_SUCCESS in case of success and other value otherwise.
+ * @param otmCtx Context of OTM, It includes current device information.
+ *
+ * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
  */
 OCStackResult CreateSecureSessionJustWorksCallback(OTMContext_t* otmCtx);
 
 /**
  * Generate payload for select OxM request.
  *
- * @param[in] selectedDeviceInfo Selected device infomation
- * @return DOXM JSON payload including the selected OxM.
- *         NOTE : Returned memory should be deallocated by caller.
+ * @param otmCtx Context of OTM, It includes current device information.
+ * @param cborPayload is the DOXM CBOR payload including the selected OxM.
+ * @note Returned memory should be deallocated by caller.
+ * @param cborSize is the size of the cborPayload.
+ *
+ * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
  */
-char* CreateJustWorksSelectOxmPayload(OTMContext_t* otmCtx);
+OCStackResult CreateJustWorksSelectOxmPayload(OTMContext_t *otmCtx, uint8_t **cborPayload,
+                                             size_t *cborSize);
 
 /**
  * Generate payload for owner transfer request.
  *
- * @param[in] selectedDeviceInfo Selected device infomation
- * @return DOXM JSON payload including the owner information.
- *         NOTE : Returned memory should be deallocated by caller.
+ * @param otmCtx Context of OTM, It includes current device information.
+ * @param cborPayload is the DOXM CBOR payload including the owner information.
+ * @note Returned memory should be deallocated by caller.
+ * @param cborSize is the size of the cborPayload.
+ *
+ * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
  */
-char* CreateJustWorksOwnerTransferPayload(OTMContext_t* otmCtx);
-
+OCStackResult CreateJustWorksOwnerTransferPayload(OTMContext_t *otmCtx, uint8_t **cborPayload,
+                                                  size_t *cborSize);
 #ifdef __cplusplus
 }
 #endif
-#endif //OXM_JUST_WORKS_H_
\ No newline at end of file
+#endif //OXM_JUST_WORKS_H_
index db5556f..ae7b110 100644 (file)
@@ -1,22 +1,22 @@
-/*****************************************************************
- *
- * 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.
- *
- * *****************************************************************/
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #ifndef OXM_RANDOM_PIN_H_
 #define OXM_RANDOM_PIN_H_
 extern "C" {
 #endif // __cplusplus
 
-#define OXM_PBKDF2_ITERATIONS 1000
-
 /**
  * Callback implementation to input the PIN code from user.
  *
- * @otmCtx  Context of OTM, It includes current device infomation.
- * @return OC_STACK_SUCCESS in case of success and other value otherwise.
+ * @param otmCtx Context of OTM, It includes current device information.
+ *
+ * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
  */
-OCStackResult InputPinCodeCallback(OTMContext_totmCtx);
+OCStackResult InputPinCodeCallback(OTMContext_t *otmCtx);
 
 /**
- * Callback implemenration to establish a secure channel with PSK cipher suite
+ * Callback implemenration to establish a secure channel with PSK cipher suite.
  *
- * @param[in] selectedDeviceInfo Selected device infomation
- * @return OC_STACK_SUCCESS in case of success and other value otherwise.
+ * @param otmCtx Context of OTM, It includes current device information.
+ *
+ * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
  */
-OCStackResult CreateSecureSessionRandomPinCallbak(OTMContext_t* otmCtx);
+OCStackResult CreateSecureSessionRandomPinCallback(OTMContext_t *otmCtx);
 
 /**
  * Generate payload for select OxM request.
  *
- * @param[in] selectedDeviceInfo Selected device infomation
- * @return DOXM JSON payload including the selected OxM.
- *         NOTE : Returned memory should be deallocated by caller.
+ * @param otmCtx Context of OTM, It includes current device information.
+ * @param cborPaylaod is the DOXM CBOR payload including the selected OxM.
+ * @note Returned memory should be deallocated by caller.
+ * @param cborSize is the size of the cborPayload.
+ *
+ * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
  */
-char* CreatePinBasedSelectOxmPayload(OTMContext_t* otmCtx);
+OCStackResult CreatePinBasedSelectOxmPayload(OTMContext_t *otmCtx, uint8_t **cborPayload,
+                                             size_t *cborSize);
 
 /**
  * Generate payload for owner transfer request.
  *
- * @param[in] selectedDeviceInfo Selected device infomation
- * @return DOXM JSON payload including the owner information.
- *         NOTE : Returned memory should be deallocated by caller.
+ * @param otmCtx Context of OTM, It includes current device information.
+ * @param cborPaylaod is the DOXM CBOR payload including the owner information.
+ * @note Returned memory should be deallocated by caller.
+ * @param cborSize is the size of the cborPayload.
+ *
+ * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
  */
-char* CreatePinBasedOwnerTransferPayload(OTMContext_t* otmCtx);
+OCStackResult CreatePinBasedOwnerTransferPayload(OTMContext_t *otmCtx, uint8_t **cborPayload,
+                                                 size_t *cborSize);
 
 #ifdef __cplusplus
 }
 #endif
-#endif //OXM_RANDOM_PIN_H_
\ No newline at end of file
+#endif //OXM_RANDOM_PIN_H_
index 4313e36..eede02d 100644 (file)
@@ -67,11 +67,28 @@ typedef struct OCProvisionDev
     OicSecDoxm_t    *doxm;           /**< Pointer to target's doxm resource. **/
     OCConnectivityType connType;     /**< Connectivity type of endpoint */
     uint16_t        securePort;      /**< secure port **/
+    char             secVer[MAX_VERSION_LEN];         /**< security version **/
     DeviceStatus    devStatus;       /**< status of device **/
     struct OCProvisionDev  *next;    /**< Next pointer. **/
 }OCProvisionDev_t;
 
 /**
+ * Device Information of discoverd direct pairing device(s).
+ */
+typedef struct OCDirectPairingDev
+{
+    OCDevAddr               endpoint;
+    OCConnectivityType   connType;
+    uint16_t                     securePort;
+    bool              edp;
+    OicSecPrm_t  *prm;
+    size_t            prmLen;
+    OicUuid_t       deviceID;
+    OicUuid_t       rowner;
+    struct OCDirectPairingDev *next;
+} OCDirectPairingDev_t;
+
+/**
  * Result information for each target device.
  */
 typedef struct OCPMResult{
@@ -90,6 +107,17 @@ typedef struct OCPMResult{
  */
 typedef void (*OCProvisionResultCB)(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError);
 
+
+/**
+ * Callback function definition of direct-pairing
+ *
+ * @param[OUT] peer - pairing device info.
+ * @param[OUT} result - It's returned with 'OC_STACK_XXX'. It will return 'OC_STACK_OK'
+ *                                   if D2D pairing is success without error
+ */
+typedef void (*OCDirectPairingResultCB)(OCDirectPairingDev_t *peer, OCStackResult result);
+
+
 #ifdef __cplusplus
 }
 #endif
index 15a5f8e..c36b204 100644 (file)
@@ -96,7 +96,7 @@ bool PMGenerateQuery(bool isSecure,
 /**
  * Function to print OCProvisionDev_t for debug purpose.
  *
- * @param[in] pDev Pointer to OCProvisionDev_t. It's information will be printed by OC_LOG_XX
+ * @param[in] pDev Pointer to OCProvisionDev_t. It's information will be printed by OIC_LOG_XX
  *
  */
 void PMPrintOCProvisionDev(const OCProvisionDev_t* pDev);
index 45d750f..88bdba8 100644 (file)
@@ -1,23 +1,62 @@
-LAST UPDATED 7/16/2015
+LAST UPDATED 3/28/2016
 
 To execute Provisioning Tool sample:
 
 1) Build IoTivity with security enabled:
-       $ cd <iotivity-base>
-       $ scons resource SECURED=1
 
+    $ cd <iotivity-base>
+       $ scons resource SECURED=1
+       
 2) Verify Provisioning Tool functionality using secure sample apps:
 
-    On Resource Server Device which needs to be 'provisioned':
-       $ cd <iotivity-base>/out/<...>/release/resource/csdk/stack/samples/linux/secure
-       $ export LD_LIBRARY_PATH=<iotivity-base>/out/<...>/release
-       $ cp ../../../../security/provisioning/sample/oic_svr_db_unowned_server.json oic_svr_db_server.json
-       $ ./ocserverbasicops
+    Run Resource Server Device which needs to be 'provisioned' in the directory:
+    $ ./sampleserver_justworks (Just Works)
+       or
+       $ ./sampleserver_randompin (Random Pin)
+       
+    Run Provisioning Tool Device:
+    $ ./provisioningclient
+    
+    Provisioning Tool will provide prompts for discovery, ownership transfer, and provisioning.
+
+    Enter 10 (Discover All Un/Owned Devices on Network)
+    and you should see the list of discovered owned and unowned devices.
+    
+    Then enter 20 (Register/Own All Discovered Unowned Devices) to perform ownership transfer
+    between the Server device and the Provisioning Tool device.
+
+    If the random pin server is running, you must enter the PIN code that 
+    appears on the server terminal to finish ownership transfer.
+
+    Enter 12 (Discover Only Owned Devices on Network) to confirm that
+    ownership transfer succeeded. If successful,
+    you should find the Server device on the Owned device list.
+    
+ 3) Verify Ownership Transfer using sample apps:
+
+    If you would like to check whether ownership transfer successfully 
+    created credentials, replace the server and client sample DAT files
+    with oic_svr_db_client.dat and oic_svr_db_server.dat files from the 
+    ownership transfer as follows:
+    $ cp ./oic_svr_db_client.dat <iotivity-base>/out/<...>/release/resource/csdk/stack/samples/linux/secure/oic_svr_db.client.dat
+    $ cp ./oic_svr_db_server_<...>.dat <iotivity-base>/out/<...>/release/resource/csdk/stack/samples/linux/secure/oic_svr_db.server.dat
 
+    Then move to the sample app directory
+    and execute the server and client apps:
+    $ cd <iotivity-base>/out/release/resource/csdk/stack/samples/linux/secure/
+    $ export LD_LIBRARY_PATH=<iotivity-base>/out/<...>/release/
+    $ ./ocserverbasicops
+    $ ./occlientbasicops -u 0 -t 3
 
-    On Provisioning Tool Device:
-       $ cd <iotivity-base>/out/<...>/release/resource/csdk/security/provisioning/sample
-       $ ./provisioningclient
+    If successful, the client and server should successfully send and receive payloads.
 
-    Follow the prompts on Provisioning Tool device and provisioning should be completed
-    successfully. You should see a message 'Provisioning Success~!!'.
+    All security functionality operate using CBOR data (DAT files).
+    JSON files are for reference only as they are human-readable.
+    JSON files are not used by security-related functions.
+    
+    If you wish to test functionality with data file
+    different from the provided default DAT file, modify the JSON files
+    (oic_svr_db_server_justworks.json, oic_svr_db_server_randompin.json)
+    and then use the JSON-to-CBOR conversion tool
+    (<iotivity-base>/out/<...>/release/resource/csdk/security/tool/json2cbor)
+    to create a new DAT file.
index 87a1970..a4f645d 100644 (file)
@@ -70,17 +70,20 @@ provisioningclient = provisioning_env.Program('provisioningclient', 'provisionin
 sampleserver_justworks = provisioning_env.Program('sampleserver_justworks', 'sampleserver_justworks.cpp')
 sampleserver_randompin = provisioning_env.Program('sampleserver_randompin', 'sampleserver_randompin.cpp')
 
-Alias("samples", [provisioningclient, sampleserver_justworks, sampleserver_randompin])
-
-provisioning_env.AppendTarget('samples')
-
 src_dir = provisioning_env.get('SRC_DIR')
 sec_provisioning_src_dir = src_dir + '/resource/csdk/security/provisioning/sample/'
 sec_provisioning_build_dir = env.get('BUILD_DIR') +'/resource/csdk/security/provisioning/sample/'
 
-provisioning_env.Alias("install", provisioning_env.Install( sec_provisioning_build_dir,
-    sec_provisioning_src_dir + 'oic_svr_db_client.json'))
-provisioning_env.Alias("install", provisioning_env.Install( sec_provisioning_build_dir,
-    sec_provisioning_src_dir + 'oic_svr_db_server_justworks.json'))
-provisioning_env.Alias("install", provisioning_env.Install( sec_provisioning_build_dir,
-    sec_provisioning_src_dir + 'oic_svr_db_server_randompin.json'))
+clientdat = provisioning_env.Install(sec_provisioning_build_dir,
+                                        sec_provisioning_src_dir + 'oic_svr_db_client.dat')
+justworksdat = provisioning_env.Install(sec_provisioning_build_dir,
+                                    sec_provisioning_src_dir + 'oic_svr_db_server_justworks.dat')
+randompindat = provisioning_env.Install(sec_provisioning_build_dir,
+                                    sec_provisioning_src_dir+ 'oic_svr_db_server_randompin.dat')
+randompin_with_emptyuuid_dat = provisioning_env.Install(sec_provisioning_build_dir,
+                                    sec_provisioning_src_dir+ 'oic_svr_db_randompin_with_empty_deviceid.dat')
+
+Alias("samples", [provisioningclient, sampleserver_justworks, sampleserver_randompin, clientdat, justworksdat, randompindat, randompin_with_emptyuuid_dat])
+
+provisioning_env.AppendTarget('samples')
+
diff --git a/resource/csdk/security/provisioning/sample/oic_svr_db_client.dat b/resource/csdk/security/provisioning/sample/oic_svr_db_client.dat
new file mode 100644 (file)
index 0000000..781f654
Binary files /dev/null and b/resource/csdk/security/provisioning/sample/oic_svr_db_client.dat differ
index 1219d6a..fb3c609 100644 (file)
@@ -1,43 +1,88 @@
-{
-    "acl": [
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/res",
-                "/oic/d",
-                "/oic/p",
-                "/oic/res/types/d",
-                "/oic/ad",
-                "/oic/sec/amacl"
-                       ],
-                       "perms": 2,
-                       "ownrs" : ["YWRtaW5EZXZpY2VVVUlEMA=="]
-               },
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/sec/doxm",
-                "/oic/sec/pstat"
-             ],
-             "perms": 2,
-             "ownrs" : ["YWRtaW5EZXZpY2VVVUlEMA=="]
-        }
-       ],
-       "pstat":        {
-               "isop": true,
-               "deviceid":     "YWRtaW5EZXZpY2VVVUlEMA==",
-               "ch": 0,
-               "cm":   0,
-               "tm":   0,
-               "om":   3,
-               "sm":   [3]
-       },
-       "doxm": {
-               "oxm":  [0],
-               "oxmsel": 0,
-               "sct": 1,
-               "owned": true,
-               "deviceid":     "YWRtaW5EZXZpY2VVVUlEMA==",
-               "ownr": "YWRtaW5EZXZpY2VVVUlEMA=="
-       }
-}
+{\r
+    "acl": {\r
+        "aclist": {\r
+            "aces": [\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/res",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/p",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/types/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/ad",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/amacl",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/doxm",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/pstat",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }                  \r
+                    ],\r
+                    "permission": 2\r
+                }\r
+            ]\r
+        },\r
+        "rowneruuid" : "61646D69-6E44-6576-6963-655575696430"\r
+    },    \r
+    "pstat": {\r
+        "isop": true,\r
+        "cm": 0,\r
+        "tm": 0,\r
+        "om": 3,\r
+        "sm": 3,\r
+        "deviceuuid": "61646D69-6E44-6576-6963-655575696430",\r
+        "rowneruuid": "61646D69-6E44-6576-6963-655575696430"\r
+    },\r
+    "doxm": {\r
+        "oxms": [0],\r
+        "oxmsel": 0,\r
+        "sct": 1,\r
+        "owned": true,\r
+        "deviceuuid": "61646D69-6E44-6576-6963-655575696430",\r
+        "dpc": false,\r
+        "devowneruuid": "61646D69-6E44-6576-6963-655575696430",\r
+        "rowneruuid": "61646D69-6E44-6576-6963-655575696430"\r
+    }\r
+}\r
diff --git a/resource/csdk/security/provisioning/sample/oic_svr_db_prov_tool.json b/resource/csdk/security/provisioning/sample/oic_svr_db_prov_tool.json
deleted file mode 100755 (executable)
index 7172a01..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-{
-    "acl": [
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/res",
-                "/oic/d",
-                "/oic/p",
-                "/oic/res/types/d",
-                "/oic/ad"
-                       ],
-                       "perms": 2,
-                       "ownrs" : ["YWRtaW5EZXZpY2VVVUlE"]
-               },
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/sec/doxm",
-                "/oic/sec/pstat",
-                "/oic/sec/acl",
-                "/oic/sec/cred"
-             ],
-             "perms": 7,
-             "ownrs" : ["YWRtaW5EZXZpY2VVVUlE"]
-        }
-       ],
-       "pstat":        {
-               "isop": true,
-               "deviceid":     "YWRtaW5EZXZpY2VVVUlE",
-               "ch": 0,
-               "cm":   0,
-               "tm":   0,
-               "om":   3,
-               "sm":   [3]
-       },
-       "doxm": {
-               "oxm":  [0],
-               "oxmsel": 0,
-               "sct": 1,
-               "owned": true,
-               "deviceid":     "YWRtaW5EZXZpY2VVVUlE",
-               "ownr": "YWRtaW5EZXZpY2VVVUlE"
-       }
-}
diff --git a/resource/csdk/security/provisioning/sample/oic_svr_db_randompin_with_empty_deviceid.dat b/resource/csdk/security/provisioning/sample/oic_svr_db_randompin_with_empty_deviceid.dat
new file mode 100644 (file)
index 0000000..3796ce7
Binary files /dev/null and b/resource/csdk/security/provisioning/sample/oic_svr_db_randompin_with_empty_deviceid.dat differ
diff --git a/resource/csdk/security/provisioning/sample/oic_svr_db_randompin_with_empty_deviceid.json b/resource/csdk/security/provisioning/sample/oic_svr_db_randompin_with_empty_deviceid.json
new file mode 100644 (file)
index 0000000..20f2c36
--- /dev/null
@@ -0,0 +1,130 @@
+{
+    "acl": {
+        "aclist": {
+            "aces": [
+                {
+                    "subjectuuid": "*",
+                    "resources": [
+                        {
+                            "href": "/oic/res",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/d",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/p",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/res/d",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/res/types/d",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/presence",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        }
+                    ],
+                    "permission": 2
+                },
+                {
+                    "subjectuuid": "*",
+                    "resources": [
+                        {
+                            "href": "/oic/sec/doxm",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/sec/pstat",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/sec/acl",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/sec/cred",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        }
+                    ],
+                    "permission": 6
+                },
+                {
+                    "subjectuuid": "*",
+                    "resources": [
+                        {
+                            "href": "/oic/sec/pconf",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/sec/dpairing",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        }
+                    ],
+                    "permission": 6
+                },
+                {
+                    "subjectuuid": "*",
+                    "resources": [
+                        {
+                            "href": "/oic/sec/ver",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        }
+                    ],
+                    "permission": 2
+                }
+            ]
+        },
+        "rowneruuid" : ""
+    },
+    "pstat": {
+        "isop": false,
+        "deviceuuid": "",
+        "rowneruuid": "",
+        "cm": 2,
+        "tm": 0,
+        "om": 3,
+        "sm": 3
+        },
+    "doxm": {
+        "oxms": [0, 1],
+        "oxmsel": 0,
+        "sct": 1,
+        "owned": false,
+        "deviceuuid": "",
+        "devowneruuid": "",
+        "rowneruuid": "",
+        "dpc": true
+    }
+}
diff --git a/resource/csdk/security/provisioning/sample/oic_svr_db_server_justworks.dat b/resource/csdk/security/provisioning/sample/oic_svr_db_server_justworks.dat
new file mode 100644 (file)
index 0000000..4adbf4d
Binary files /dev/null and b/resource/csdk/security/provisioning/sample/oic_svr_db_server_justworks.dat differ
index bde9010..59b56a7 100644 (file)
-{
-    "acl": [
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/res",
-                "/oic/res/d",
-                "/oic/res/types/d",
-                "/oic/presence"
-                       ],
-                       "perms": 2,
-                       "ownrs" : [
-                               "anVzdHdvcmtzRGV2VVVJRA=="
-                       ]
-               },
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/sec/doxm",
-                "/oic/sec/pstat",
-                "/oic/sec/acl",
-                "/oic/sec/cred"
-             ],
-             "perms": 6,
-             "ownrs" : [
-                 "anVzdHdvcmtzRGV2VVVJRA=="
-             ]
-        }
-       ],
-       "pstat":        {
-               "isop": false,
-               "deviceid":     "anVzdHdvcmtzRGV2VVVJRA==",
-               "commithash": 0,
-               "cm":   0,
-               "tm":   0,
-               "om":   3,
-               "sm":   [3]
-       },
-       "doxm": {
-               "oxm":  [0],
-               "oxmsel": 0,
-               "sct": 1,
-               "owned": false,
-               "deviceid":     "anVzdHdvcmtzRGV2VVVJRA=="
-       }
-}
+{\r
+    "acl": {\r
+        "aclist": {\r
+            "aces": [\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/res",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },{\r
+                            "href": "/oic/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },{\r
+                            "href": "/oic/p",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/types/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/presence",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/doxm",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/pstat",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/acl",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/cred",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 6\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/pconf",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/dpairing",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 6\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/ver",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                }\r
+            ]\r
+        },\r
+        "rowneruuid" : "6A757374-776F-726B-4465-765575696430"\r
+    },\r
+    "pstat": {\r
+        "isop": false,\r
+        "deviceuuid": "6A757374-776F-726B-4465-765575696430",\r
+        "rowneruuid": "6A757374-776F-726B-4465-765575696430",\r
+        "cm": 2,\r
+        "tm": 0,\r
+        "om": 3,\r
+        "sm": 3\r
+        },\r
+    "doxm": {\r
+        "oxms": [0],\r
+        "oxmsel": 0,\r
+        "sct": 1,\r
+        "owned": false,\r
+        "deviceuuid": "6A757374-776F-726B-4465-765575696430",\r
+        "devowneruuid": "",\r
+        "rowneruuid": "6A757374-776F-726B-4465-765575696430",\r
+        "dpc": true\r
+    }\r
+}
\ No newline at end of file
diff --git a/resource/csdk/security/provisioning/sample/oic_svr_db_server_randompin.dat b/resource/csdk/security/provisioning/sample/oic_svr_db_server_randompin.dat
new file mode 100644 (file)
index 0000000..cfce7f8
Binary files /dev/null and b/resource/csdk/security/provisioning/sample/oic_svr_db_server_randompin.dat differ
old mode 100755 (executable)
new mode 100644 (file)
index a79a2b2..dc595bd
-{
-    "acl": [
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/res",
-                "/oic/res/d",
-                "/oic/res/types/d",
-                "/oic/presence"
-                       ],
-                       "perms": 2,
-                       "ownrs" : [
-                               "cmFuZG9tUGluRGV2VVVJRA=="
-                       ]
-               },
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/sec/doxm",
-                "/oic/sec/pstat",
-                "/oic/sec/acl",
-                "/oic/sec/cred"
-             ],
-             "perms": 6,
-             "ownrs" : [
-                 "cmFuZG9tUGluRGV2VVVJRA=="
-             ]
-        }
-       ],
-       "pstat":        {
-               "isop": false,
-               "deviceid":     "cmFuZG9tUGluRGV2VVVJRA==",
-               "commithash": 0,
-               "cm":   0,
-               "tm":   0,
-               "om":   3,
-               "sm":   [3]
-       },
-       "doxm": {
-               "oxm":  [0,1],
-               "oxmsel": 0,
-               "sct": 1,
-               "owned": false,
-               "deviceid":     "cmFuZG9tUGluRGV2VVVJRA=="
-       }
-}
+{\r
+    "acl": {\r
+        "aclist": {\r
+            "aces": [\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/res",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/p",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/types/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/presence",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/doxm",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/pstat",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/acl",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/cred",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 6\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/pconf",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/dpairing",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 6\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/ver",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                }\r
+            ]\r
+        },\r
+        "rowneruuid" : "72616E64-5069-6E44-6576-557569643030"\r
+    },\r
+    "pstat": {\r
+        "isop": false,\r
+        "deviceuuid": "72616E64-5069-6E44-6576-557569643030",\r
+        "rowneruuid": "72616E64-5069-6E44-6576-557569643030",\r
+        "cm": 2,\r
+        "tm": 0,\r
+        "om": 3,\r
+        "sm": 3\r
+        },\r
+    "doxm": {\r
+        "oxms": [0, 1],\r
+        "oxmsel": 0,\r
+        "sct": 1,\r
+        "owned": false,\r
+        "deviceuuid": "72616E64-5069-6E44-6576-557569643030",\r
+        "devowneruuid": "",\r
+        "rowneruuid": "72616E64-5069-6E44-6576-557569643030",\r
+        "dpc": true\r
+    }\r
+}\r
diff --git a/resource/csdk/security/provisioning/sample/oic_svr_db_unowned_server.json b/resource/csdk/security/provisioning/sample/oic_svr_db_unowned_server.json
deleted file mode 100644 (file)
index fa804dd..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-{
-    "acl": [
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/res",
-                "/oic/d",
-                "/oic/p",
-                "/oic/res/types/d",
-                "/oic/ad",
-                "/oic/sec/acl",
-                "/oic/sec/svc",
-                "/oic/sec/amacl"
-                       ],
-                       "perms": 2,
-                       "ownrs" : ["MTExMTExMTExMTExMTExMQ=="]
-               },
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/sec/doxm",
-                "/oic/sec/pstat"
-             ],
-             "perms": 6,
-             "ownrs" : ["MTExMTExMTExMTExMTExMQ=="]
-        }
-    ],
-       "pstat":        {
-               "isop": false,
-               "deviceid":     "ZGV2aWNlaWQAAAAAABhanw==",
-               "ch": 0,
-               "cm":   0,
-               "tm":   0,
-               "om":   3,
-               "sm":   [3]
-       },
-       "doxm": {
-               "oxm":  [0],
-               "oxmsel": 0,
-               "sct": 1,
-               "owned": false,
-               "deviceid":     "MTExMTExMTExMTExMTExMQ=="
-       }
-}
index 75eb699..ab423b4 100644 (file)
@@ -46,7 +46,8 @@ extern "C"
 #define _30_PROVIS_PAIR_DEVS_   30
 #define _31_PROVIS_CRED_        31
 #define _32_PROVIS_ACL_         32
-#define _33_CHECK_LINK_STATUS_  33
+#define _33_PROVIS_DP_           33
+#define _34_CHECK_LINK_STATUS_  34
 #define _40_UNLINK_PAIR_DEVS_   40
 #define _50_REMOVE_SELEC_DEV_   50
 #define _99_EXIT_PRVN_CLT_      99
@@ -59,9 +60,14 @@ extern "C"
 #define TAG "provisioningclient"
 
 static const char* ACL_PEMISN[5] = {"CREATE", "READ", "WRITE", "DELETE", "NOTIFY"};
-static const char* SVR_DB_FILE_NAME = "oic_svr_db_client.json";
+static const char* SVR_DB_FILE_NAME = "oic_svr_db_client.dat";
         // '_' for separaing from the same constant variable in |srmresourcestrings.c|
 static const char* PRVN_DB_FILE_NAME = "oic_prvn_mng.db";
+static const OicSecPrm_t  SUPPORTED_PRMS[1] =
+{
+    PRM_PRE_CONFIGURED,
+};
+
 // |g_ctx| means provision manager application context and
 // the following, includes |un/own_list|, could be variables, which |g_ctx| has,
 // for accessing all function(s) for these, they are declared on global domain
@@ -76,6 +82,7 @@ static bool g_doneCB;
 
 // function declaration(s) for calling them before implementing
 static OicSecAcl_t* createAcl(const int);
+static OicSecPdAcl_t* createPdAcl(const int);
 static OCProvisionDev_t* getDevInst(const OCProvisionDev_t*, const int);
 static int printDevList(const OCProvisionDev_t*);
 static size_t printUuidList(const OCUuidList_t*);
@@ -90,11 +97,11 @@ static void ownershipTransferCB(void* ctx, int nOfRes, OCProvisionResult_t* arr,
 {
     if(!hasError)
     {
-        OC_LOG_V(INFO, TAG, "Ownership Transfer SUCCEEDED - ctx: %s", (char*) ctx);
+        OIC_LOG_V(INFO, TAG, "Ownership Transfer SUCCEEDED - ctx: %s", (char*) ctx);
     }
     else
     {
-        OC_LOG_V(ERROR, TAG, "Ownership Transfer FAILED - ctx: %s", (char*) ctx);
+        OIC_LOG_V(ERROR, TAG, "Ownership Transfer FAILED - ctx: %s", (char*) ctx);
         printResultList((const OCProvisionResult_t*) arr, nOfRes);
     }
     g_doneCB = true;
@@ -104,11 +111,11 @@ static void provisionPairwiseCB(void* ctx, int nOfRes, OCProvisionResult_t* arr,
 {
     if(!hasError)
     {
-        OC_LOG_V(INFO, TAG, "Provision Pairwise SUCCEEDED - ctx: %s", (char*) ctx);
+        OIC_LOG_V(INFO, TAG, "Provision Pairwise SUCCEEDED - ctx: %s", (char*) ctx);
     }
     else
     {
-        OC_LOG_V(ERROR, TAG, "Provision Pairwise FAILED - ctx: %s", (char*) ctx);
+        OIC_LOG_V(ERROR, TAG, "Provision Pairwise FAILED - ctx: %s", (char*) ctx);
         printResultList((const OCProvisionResult_t*) arr, nOfRes);
     }
     g_doneCB = true;
@@ -118,11 +125,11 @@ static void provisionCredCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, boo
 {
     if(!hasError)
     {
-        OC_LOG_V(INFO, TAG, "Provision Credential SUCCEEDED - ctx: %s", (char*) ctx);
+        OIC_LOG_V(INFO, TAG, "Provision Credential SUCCEEDED - ctx: %s", (char*) ctx);
     }
     else
     {
-        OC_LOG_V(ERROR, TAG, "Provision Credential FAILED - ctx: %s", (char*) ctx);
+        OIC_LOG_V(ERROR, TAG, "Provision Credential FAILED - ctx: %s", (char*) ctx);
         printResultList((const OCProvisionResult_t*) arr, nOfRes);
     }
     g_doneCB = true;
@@ -132,11 +139,25 @@ static void provisionAclCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, bool
 {
     if(!hasError)
     {
-        OC_LOG_V(INFO, TAG, "Provision ACL SUCCEEDED - ctx: %s", (char*) ctx);
+        OIC_LOG_V(INFO, TAG, "Provision ACL SUCCEEDED - ctx: %s", (char*) ctx);
     }
     else
     {
-        OC_LOG_V(ERROR, TAG, "Provision ACL FAILED - ctx: %s", (char*) ctx);
+        OIC_LOG_V(ERROR, TAG, "Provision ACL 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)
+    {
+        OIC_LOG_V(INFO, TAG, "Provision Direct-Pairing SUCCEEDED - ctx: %s", (char*) ctx);
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "Provision Direct-Pairing FAILED - ctx: %s", (char*) ctx);
         printResultList((const OCProvisionResult_t*) arr, nOfRes);
     }
     g_doneCB = true;
@@ -146,11 +167,11 @@ static void unlinkDevicesCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, boo
 {
     if(!hasError)
     {
-        OC_LOG_V(INFO, TAG, "Unlink Devices SUCCEEDED - ctx: %s", (char*) ctx);
+        OIC_LOG_V(INFO, TAG, "Unlink Devices SUCCEEDED - ctx: %s", (char*) ctx);
     }
     else
     {
-        OC_LOG_V(ERROR, TAG, "Unlink Devices FAILED - ctx: %s", (char*) ctx);
+        OIC_LOG_V(ERROR, TAG, "Unlink Devices FAILED - ctx: %s", (char*) ctx);
         printResultList((const OCProvisionResult_t*) arr, nOfRes);
     }
     g_doneCB = true;
@@ -160,11 +181,11 @@ static void removeDeviceCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, bool
 {
     if(!hasError)
     {
-        OC_LOG_V(INFO, TAG, "Remove Device SUCCEEDED - ctx: %s", (char*) ctx);
+        OIC_LOG_V(INFO, TAG, "Remove Device SUCCEEDED - ctx: %s", (char*) ctx);
     }
     else
     {
-        OC_LOG_V(ERROR, TAG, "Remove Device FAILED - ctx: %s", (char*) ctx);
+        OIC_LOG_V(ERROR, TAG, "Remove Device FAILED - ctx: %s", (char*) ctx);
         printResultList((const OCProvisionResult_t*) arr, nOfRes);
     }
     g_doneCB = true;
@@ -174,7 +195,7 @@ static void inputPinCB(char* pin, size_t len)
 {
     if(!pin || OXM_RANDOM_PIN_SIZE>=len)
     {
-        OC_LOG(ERROR, TAG, "inputPinCB invalid parameters");
+        OIC_LOG(ERROR, TAG, "inputPinCB invalid parameters");
         return;
     }
 
@@ -201,14 +222,14 @@ static int initProvisionClient(void)
     };
     if(OC_STACK_OK != OCRegisterPersistentStorageHandler(&pstStr))
     {
-        OC_LOG(ERROR, TAG, "OCRegisterPersistentStorageHandler error");
+        OIC_LOG(ERROR, TAG, "OCRegisterPersistentStorageHandler error");
         return -1;
     }
 
     // initialize OC stack and provisioning manager
     if(OC_STACK_OK != OCInit(NULL, 0, OC_CLIENT_SERVER))
     {
-        OC_LOG(ERROR, TAG, "OCStack init error");
+        OIC_LOG(ERROR, TAG, "OCStack init error");
         return -1;
     }
 
@@ -227,7 +248,7 @@ static int initProvisionClient(void)
 
     if(OC_STACK_OK != OCInitPM(PRVN_DB_FILE_NAME))
     {
-        OC_LOG(ERROR, TAG, "OC_PM init error");
+        OIC_LOG(ERROR, TAG, "OC_PM init error");
         return -1;
     }
 
@@ -241,16 +262,16 @@ static int initProvisionClient(void)
     };
     if(OC_STACK_OK != OCSetOwnerTransferCallbackData(OIC_JUST_WORKS, &otmcb))
     {
-        OC_LOG(ERROR, TAG, "OCSetOwnerTransferCallbackData error: OIC_JUST_WORKS");
+        OIC_LOG(ERROR, TAG, "OCSetOwnerTransferCallbackData error: OIC_JUST_WORKS");
         return -1;
     }
     otmcb.loadSecretCB = InputPinCodeCallback;
-    otmcb.createSecureSessionCB = CreateSecureSessionRandomPinCallbak;
+    otmcb.createSecureSessionCB = CreateSecureSessionRandomPinCallback;
     otmcb.createSelectOxmPayloadCB = CreatePinBasedSelectOxmPayload;
     otmcb.createOwnerTransferPayloadCB = CreatePinBasedOwnerTransferPayload;
     if(OC_STACK_OK != OCSetOwnerTransferCallbackData(OIC_RANDOM_DEVICE_PIN, &otmcb))
     {
-        OC_LOG(ERROR, TAG, "OCSetOwnerTransferCallbackData error: OIC_RANDOM_DEVICE_PIN");
+        OIC_LOG(ERROR, TAG, "OCSetOwnerTransferCallbackData error: OIC_RANDOM_DEVICE_PIN");
         return -1;
     }
     SetInputPinCB(inputPinCB);
@@ -276,7 +297,7 @@ static int discoverAllDevices(void)
     printf("   Discovering All Un/Owned Devices on Network..\n");
     if(OC_STACK_OK != OCGetDevInfoFromNetwork(DISCOVERY_TIMEOUT, &g_own_list, &g_unown_list))
     {
-        OC_LOG(ERROR, TAG, "OCGetDevInfoFromNetwork API error");
+        OIC_LOG(ERROR, TAG, "OCGetDevInfoFromNetwork API error");
         return -1;
     }
 
@@ -303,7 +324,7 @@ static int discoverUnownedDevices(void)
     printf("   Discovering Only Unowned Devices on Network..\n");
     if(OC_STACK_OK != OCDiscoverUnownedDevices(DISCOVERY_TIMEOUT, &g_unown_list))
     {
-        OC_LOG(ERROR, TAG, "OCDiscoverUnownedDevices API error");
+        OIC_LOG(ERROR, TAG, "OCDiscoverUnownedDevices API error");
         return -1;
     }
 
@@ -327,7 +348,7 @@ static int discoverOwnedDevices(void)
     printf("   Discovering Only Owned Devices on Network..\n");
     if(OC_STACK_OK != OCDiscoverOwnedDevices(DISCOVERY_TIMEOUT, &g_own_list))
     {
-        OC_LOG(ERROR, TAG, "OCDiscoverOwnedDevices API error");
+        OIC_LOG(ERROR, TAG, "OCDiscoverOwnedDevices API error");
         return -1;
     }
 
@@ -356,12 +377,12 @@ static int registerDevices(void)
     OCStackResult rst = OCDoOwnershipTransfer((void*) g_ctx, g_unown_list, ownershipTransferCB);
     if(OC_STACK_OK != rst)
     {
-        OC_LOG_V(ERROR, TAG, "OCDoOwnershipTransfer API error: %d", rst);
+        OIC_LOG_V(ERROR, TAG, "OCDoOwnershipTransfer API error: %d", rst);
         return -1;
     }
     if(waitCallbackRet())  // input |g_doneCB| flag implicitly
     {
-        OC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
+        OIC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
         return -1;
     }
 
@@ -386,7 +407,7 @@ static int provisionPairwise(void)
     int dev_num[2] = {0};
     if(selectTwoDiffNum(&(dev_num[0]), &(dev_num[1]), g_own_cnt, "for Linking Devices"))
     {
-        OC_LOG(ERROR, TAG, "selectTwoDiffNum error return");
+        OIC_LOG(ERROR, TAG, "selectTwoDiffNum error return");
         return -1;  // not need to 'goto' |ERROR| before allocating |acl|
     }
 
@@ -397,7 +418,7 @@ static int provisionPairwise(void)
         acl[i] = createAcl(dev_num[i]);
         if(!acl[i])
         {
-            OC_LOG(ERROR, TAG, "createAcl error return");
+            OIC_LOG(ERROR, TAG, "createAcl error return");
             goto PVPWS_ERROR;
         }
     }
@@ -415,12 +436,12 @@ static int provisionPairwise(void)
                     provisionPairwiseCB);
     if(OC_STACK_OK != rst)
     {
-        OC_LOG_V(ERROR, TAG, "OCProvisionPairwiseDevices API error: %d", rst);
+        OIC_LOG_V(ERROR, TAG, "OCProvisionPairwiseDevices API error: %d", rst);
         goto PVPWS_ERROR;
     }
     if(waitCallbackRet())  // input |g_doneCB| flag implicitly
     {
-        OC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
+        OIC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
         goto PVPWS_ERROR;
     }
     OCDeleteACLList(acl[0]);
@@ -452,7 +473,7 @@ static int provisionCred(void)
     int dev_num[2] = {0};
     if(selectTwoDiffNum(&(dev_num[0]), &(dev_num[1]), g_own_cnt, "for Linking CRED(s)"))
     {
-        OC_LOG(ERROR, TAG, "selectTwoDiffNum error return");
+        OIC_LOG(ERROR, TAG, "selectTwoDiffNum error return");
         return -1;
     }
 
@@ -502,12 +523,12 @@ static int provisionCred(void)
                     provisionCredCB);
     if(OC_STACK_OK != rst)
     {
-        OC_LOG_V(ERROR, TAG, "OCProvisionCredentials API error: %d", rst);
+        OIC_LOG_V(ERROR, TAG, "OCProvisionCredentials API error: %d", rst);
         return -1;
     }
     if(waitCallbackRet())  // input |g_doneCB| flag implicitly
     {
-        OC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
+        OIC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
         return -1;
     }
 
@@ -551,7 +572,7 @@ static int provisionAcl(void)
     acl = createAcl(dev_num);
     if(!acl)
     {
-        OC_LOG(ERROR, TAG, "createAcl error return");
+        OIC_LOG(ERROR, TAG, "createAcl error return");
         goto PVACL_ERROR;
     }
 
@@ -560,18 +581,21 @@ static int provisionAcl(void)
     // for error checking, the return value saved and printed
     g_doneCB = false;
     printf("   Provisioning Selected ACL..\n");
-    OCStackResult rst =
-            OCProvisionACL((void*) g_ctx,
-                    getDevInst((const OCProvisionDev_t*) g_own_list, dev_num),
-                    acl, provisionAclCB);
+    OCProvisionDev_t* dev = getDevInst((const OCProvisionDev_t*) g_own_list, dev_num);
+    if(!dev)
+    {
+        OIC_LOG(ERROR, TAG, "provisionAcl: device instance empty");
+        goto PVACL_ERROR;
+    }
+    OCStackResult rst = OCProvisionACL((void*) g_ctx, dev, acl, provisionAclCB);
     if(OC_STACK_OK != rst)
     {
-        OC_LOG_V(ERROR, TAG, "OCProvisionACL API error: %d", rst);
+        OIC_LOG_V(ERROR, TAG, "OCProvisionACL API error: %d", rst);
         goto PVACL_ERROR;
     }
     if(waitCallbackRet())  // input |g_doneCB| flag implicitly
     {
-        OC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
+        OIC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
         goto PVACL_ERROR;
     }
     OCDeleteACLList(acl);  // after here |acl| points nothing
@@ -586,6 +610,104 @@ PVACL_ERROR:
     return -1;
 }
 
+static int provisionDirectPairing(void)
+{
+    // check |own_list| for provisioning direct-pairing
+    if(!g_own_list || 1>g_own_cnt)
+    {
+        printf("   > Owned Device List, to Provision ACL, is Empty\n");
+        printf("   > Please Register Unowned Devices first, with [20] Menu\n");
+        return 0;  // normal case
+    }
+
+    // select device for provisioning direct-pairing
+    int dev_num = 0;
+    for( ; ; )
+    {
+        printf("   > Enter Device Number, for Provisioning Direct-Pairing: ");
+        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");
+    }
+
+    // create Direct-Pairing Configuration(PIN, PDACL) for selected device
+    // TODO: default acl -> input from user !
+    OicSecPconf_t pconf;
+    memset(&pconf, 0, sizeof(OicSecPconf_t));
+
+    // set enable dp
+    pconf.edp = true;
+
+    // set default supported PRM types
+    pconf.prmLen = sizeof(SUPPORTED_PRMS)/sizeof(OicSecPrm_t);
+    pconf.prm = (OicSecPrm_t *)OICCalloc(pconf.prmLen, sizeof(OicSecPrm_t));
+    if(pconf.prm)
+    {
+        for (size_t i=0; i<pconf.prmLen; i++)
+        {
+            pconf.prm[i] = SUPPORTED_PRMS[i];
+        }
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "create prm error return");
+        goto PVDP_ERROR;
+    }
+
+    // set default pin
+    const char DP_DEFAULT_PIN[] = "00000000";
+    memcpy(pconf.pin.val, DP_DEFAULT_PIN, DP_PIN_LENGTH);
+
+    // set default pdacl
+    pconf.pdacls = createPdAcl(dev_num);
+    if(!pconf.pdacls)
+    {
+        OIC_LOG(ERROR, TAG, "createPdAcl error return");
+        goto PVDP_ERROR;
+    }
+
+    // call |OCProvisionDirectPairing| API actually
+    // calling this API with callback actually acts like blocking
+    // for error checking, the return value saved and printed
+    g_doneCB = false;
+    printf("   Atempt Direct-Pairing Provisioning (PIN : [%s])..\n", (char*)pconf.pin.val);
+    OCStackResult rst = OCProvisionDirectPairing((void*) g_ctx,
+                                       getDevInst((const OCProvisionDev_t*) g_own_list, dev_num),
+                                       &pconf, provisionDPCB);
+    if(OC_STACK_OK != rst)
+    {
+        OIC_LOG_V(ERROR, TAG, "OCProvisionDirectPairing API error: %d", rst);
+        if (OC_STACK_UNAUTHORIZED_REQ == rst)
+        {
+            OIC_LOG(ERROR, TAG, "Target Server NOT Support Direct-Pairing !!! (DPC == false)");
+        }
+        goto PVDP_ERROR;
+    }
+    if(waitCallbackRet())  // input |g_doneCB| flag implicitly
+    {
+        OIC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
+        goto PVDP_ERROR;
+    }
+    OCDeletePdAclList(pconf.pdacls);
+
+    // display the PCONF-provisioned result
+    printf("   > SUCCESS to provision Direct-Pairing !!\n");
+
+    return 0;
+
+PVDP_ERROR:
+    OCDeletePdAclList(pconf.pdacls);  // after here |acl| points nothing
+    return -1;
+}
+
 static int checkLinkedStatus(void)
 {
     // check |own_list| for checking selected link status on PRVN DB
@@ -618,12 +740,19 @@ static int checkLinkedStatus(void)
     printf("   Checking Selected Link Status on PRVN DB..\n");
     OCUuidList_t* dvid_lst = NULL;
     size_t dvid_cnt = 0;
+    OCProvisionDev_t* dev = getDevInst((const OCProvisionDev_t*)g_own_list, dev_num);
+    if(!dev || !dev->doxm)
+    {
+        OIC_LOG(ERROR, TAG, "checkLinkedStatus: device instance empty");
+        goto CKLST_ERROR;
+    }
+
     if(OC_STACK_OK !=
             OCGetLinkedStatus(
-                    &getDevInst((const OCProvisionDev_t*) g_own_list, dev_num)->doxm->deviceID,
+                    &dev->doxm->deviceID,
                     &dvid_lst, &dvid_cnt))  // allow empty list
     {
-        OC_LOG(ERROR, TAG, "OCGetLinkedStatus API error");
+        OIC_LOG(ERROR, TAG, "OCGetLinkedStatus API error");
         goto CKLST_ERROR;
     }
 
@@ -636,7 +765,7 @@ static int checkLinkedStatus(void)
     }
     if(dvid_cnt != printUuidList((const OCUuidList_t*) dvid_lst))
     {
-        OC_LOG(ERROR, TAG, "printUuidList error return");
+        OIC_LOG(ERROR, TAG, "printUuidList error return");
         goto CKLST_ERROR;
     }
     OCDeleteUuidList(dvid_lst);
@@ -662,7 +791,7 @@ static int unlinkPairwise(void)
     int dev_num[2] = {0};
     if(selectTwoDiffNum(&(dev_num[0]), &(dev_num[1]), g_own_cnt, "for Unlinking Devices"))
     {
-        OC_LOG(ERROR, TAG, "selectTwoDiffNum error return");
+        OIC_LOG(ERROR, TAG, "selectTwoDiffNum error return");
         return -1;
     }
 
@@ -678,12 +807,12 @@ static int unlinkPairwise(void)
                     unlinkDevicesCB);
     if(OC_STACK_OK != rst)
     {
-        OC_LOG_V(ERROR, TAG, "OCUnlinkDevices API error: %d", rst);
+        OIC_LOG_V(ERROR, TAG, "OCUnlinkDevices API error: %d", rst);
         return -1;
     }
     if(waitCallbackRet())  // input |g_doneCB| flag implicitly
     {
-        OC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
+        OIC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
         return -1;
     }
 
@@ -732,12 +861,12 @@ static int removeDevice(void)
                     getDevInst((const OCProvisionDev_t*) g_own_list, dev_num), removeDeviceCB);
     if(OC_STACK_OK != rst)
     {
-        OC_LOG_V(ERROR, TAG, "OCRemoveDevice API error: %d", rst);
+        OIC_LOG_V(ERROR, TAG, "OCRemoveDevice API error: %d", rst);
         return -1;
     }
     if(waitCallbackRet())  // input |g_doneCB| flag implicitly
     {
-        OC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
+        OIC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
         return -1;
     }
 
@@ -752,7 +881,7 @@ static OicSecAcl_t* createAcl(const int dev_num)
 {
     if(0>=dev_num || g_own_cnt<dev_num)
     {
-        OC_LOG(ERROR, TAG, "createAcl invalid parameters");
+        OIC_LOG(ERROR, TAG, "createAcl invalid parameters");
         return NULL;  // not need to 'goto' |ERROR| before allocating |acl|
     }
 
@@ -761,7 +890,7 @@ static OicSecAcl_t* createAcl(const int dev_num)
     OicSecAcl_t* acl = (OicSecAcl_t*) OICCalloc(1, sizeof(OicSecAcl_t));
     if(!acl)
     {
-        OC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
+        OIC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
         return NULL;  // not need to 'goto' |ERROR| before allocating |acl|
     }
 
@@ -776,15 +905,20 @@ static OicSecAcl_t* createAcl(const int dev_num)
             for( ; 0x20<=getchar(); );  // for removing overflow garbages
                                         // '0x20<=code' is character region
         }
-        if(num && g_own_cnt>=num && dev_num!=num)
+        if(0<num && g_own_cnt>=num && dev_num!=num)
         {
             break;
         }
         printf("     Entered Wrong Number. Please Enter Again\n");
     }
-    memcpy(&acl->subject,
-            &getDevInst((const OCProvisionDev_t*) g_own_list, num)->doxm->deviceID,
-            UUID_LENGTH);  // not need |*sizeof(uint8_t)|
+
+    OCProvisionDev_t* dev = getDevInst((const OCProvisionDev_t*)g_own_list, num);
+    if(!dev || !dev->doxm)
+    {
+        OIC_LOG(ERROR, TAG, "createAcl: device instance empty");
+        goto CRACL_ERROR;
+    }
+    memcpy(&acl->subject, &dev->doxm->deviceID, UUID_LENGTH);
 
     // enter number of |resources| in 'accessed' device
     for( ; ; )
@@ -793,12 +927,11 @@ static OicSecAcl_t* createAcl(const int dev_num)
                 // '16' is |ACL_RESRC_MAX_NUM|
         for(int ret=0; 1!=ret; )
         {
-            ret = scanf("%zu", &acl->resourcesLen);
+            ret = scanf("%d", &num);
             for( ; 0x20<=getchar(); );  // for removing overflow garbages
                                         // '0x20<=code' is character region
         }
-        if(acl->resourcesLen && ACL_RESRC_MAX_NUM>=acl->resourcesLen)
-                // |acl->resourcesLen| is unsigned
+        if(0<num && ACL_RESRC_MAX_NUM>=num)
         {
             break;
         }
@@ -809,15 +942,15 @@ static OicSecAcl_t* createAcl(const int dev_num)
     // enter actually each 'accessed' |resources| name
     printf("         Enter Each Accessed Resource Name (each under 128 char)\n");
             // '128' is ACL_RESRC_MAX_LEN
-    num = acl->resourcesLen;
-    acl->resources = (char**) OICCalloc(num, sizeof(char*));
+    acl->resourcesLen = (unsigned) num;
+    acl->resources = (char**) OICCalloc(acl->resourcesLen, sizeof(char*));
     if(!acl->resources)
     {
-        OC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
+        OIC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
         goto CRACL_ERROR;
     }
     char rsrc_in[ACL_RESRC_MAX_LEN+1] = {0};  // '1' for null termination
-    for(int i=0; num>i; ++i)
+    for(int i=0; acl->resourcesLen>(unsigned)i; ++i)
     {
         printf("         Enter Accessed Resource[%d] Name: ", i+1);
         for(int ret=0; 1!=ret; )
@@ -830,7 +963,7 @@ static OicSecAcl_t* createAcl(const int dev_num)
         char* rsrc = (char*) OICCalloc(len, sizeof(char));
         if(!rsrc)
         {
-            OC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
+            OIC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
             goto CRACL_ERROR;
         }
         OICStrcpy(rsrc, len, rsrc_in);
@@ -869,31 +1002,30 @@ static OicSecAcl_t* createAcl(const int dev_num)
     acl->permission = pmsn;
 
     // enter |owner| device number
+    int own_num = 0;
     for( ; ; )
     {
         printf("   > [D] Enter Owner Device Number: ");
         for(int ret=0; 1!=ret; )
         {
-            ret = scanf("%d", &num);
+            ret = scanf("%d", &own_num);
             for( ; 0x20<=getchar(); );  // for removing overflow garbages
                                         // '0x20<=code' is character region
         }
-        if(num && g_own_cnt>=num)
+        if(0<own_num && g_own_cnt>=own_num)
         {
             break;
         }
         printf("         Entered Wrong Number. Please Enter Again\n");
     }
-    acl->ownersLen = 1;
-    acl->owners = (OicUuid_t*) OICCalloc(1, sizeof(OicUuid_t));
-    if(!acl->owners)
+
+    dev = getDevInst((const OCProvisionDev_t*)g_own_list, own_num);
+    if(!dev || !dev->doxm)
     {
-        OC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
+        OIC_LOG(ERROR, TAG, "createAcl: device instance empty");
         goto CRACL_ERROR;
     }
-    memcpy(acl->owners,
-            &getDevInst((const OCProvisionDev_t*) g_own_list, num)->doxm->deviceID,
-            UUID_LENGTH);  // not need |*sizeof(uint8_t)|
+    memcpy(&acl->rownerID, &dev->doxm->deviceID, sizeof(OicUuid_t));
     printf("\n");
 
     return acl;
@@ -903,6 +1035,59 @@ CRACL_ERROR:
     return NULL;
 }
 
+static OicSecPdAcl_t* createPdAcl(const int dev_num)
+{
+    if(0>=dev_num || g_own_cnt<dev_num)
+    {
+        OIC_LOG(ERROR, TAG, "createAcl invalid parameters");
+        return NULL;  // not need to 'goto' |ERROR| before allocating |acl|
+    }
+
+    // allocate memory for |pdacl| struct
+    printf("   **** Create PDACL for the Selected Device[%d]\n", dev_num);
+    OicSecPdAcl_t* pdAcl = (OicSecPdAcl_t*) OICCalloc(1, sizeof(OicSecPdAcl_t));
+    if(!pdAcl)
+    {
+        OIC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
+        return NULL;  // not need to 'goto' |ERROR| before allocating |acl|
+    }
+
+
+    // number of resources
+    char rsrc_in[][ACL_RESRC_MAX_LEN+1] = {"*", "/rsrc/*"};
+    pdAcl->resourcesLen = 1;
+
+    // resource
+    int num = pdAcl->resourcesLen;
+    pdAcl->resources = (char**) OICCalloc(num, sizeof(char*));
+    if(!pdAcl->resources)
+    {
+        OIC_LOG(ERROR, TAG, "createPdAcl: OICCalloc error return");
+        goto CRPDACL_ERROR;
+    }
+    for(int i=0; num>i; ++i)
+    {
+        size_t len = strlen(rsrc_in[i])+1;  // '1' for null termination
+        char* rsrc = (char*) OICCalloc(len, sizeof(char));
+        if(!rsrc)
+        {
+            OIC_LOG(ERROR, TAG, "createPdAcl: OICCalloc error return");
+            goto CRPDACL_ERROR;
+        }
+        OICStrcpy(rsrc, len, rsrc_in[i]);
+        pdAcl->resources[i] = rsrc;  // after here, |rsrc| points nothing
+    }
+
+    // permission
+    pdAcl->permission = PERMISSION_FULL_CONTROL;
+
+    return pdAcl;
+
+CRPDACL_ERROR:
+    OCDeletePdAclList(pdAcl);
+    return NULL;
+}
+
 static OCProvisionDev_t* getDevInst(const OCProvisionDev_t* dev_lst, const int dev_num)
 {
     if(!dev_lst || 0>=dev_num)
@@ -1017,7 +1202,7 @@ static int waitCallbackRet(void)
         sleep(1);
         if(OC_STACK_OK != OCProcess())
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             return -1;
         }
     }
@@ -1081,7 +1266,8 @@ static void printMenu(void)
     printf("** 30. Provision/Link Pairwise Things\n");
     printf("** 31. Provision Credentials for Pairwise Things\n");
     printf("** 32. Provision the Selected Access Control List(ACL)\n");
-    printf("** 33. Check Linked Status of the Selected Device on PRVN DB\n\n");
+    printf("** 33. Provision Direct-Pairing Configuration\n");
+    printf("** 34. Check Linked Status of the Selected Device on PRVN DB\n\n");
 
     printf("** [D] UNLINK PAIRWISE THINGS\n");
     printf("** 40. Unlink Pairwise Things\n\n");
@@ -1121,7 +1307,7 @@ int main()
     // initialize provisioning client
     if(initProvisionClient())
     {
-        OC_LOG(ERROR, TAG, "ProvisionClient init error");
+        OIC_LOG(ERROR, TAG, "ProvisionClient init error");
         goto PMCLT_ERROR;
     }
 
@@ -1144,61 +1330,67 @@ int main()
         case _10_DISCOV_ALL_DEVS_:
             if(discoverAllDevices())
             {
-                OC_LOG(ERROR, TAG, "_10_DISCOV_ALL_DEVS_: error");
+                OIC_LOG(ERROR, TAG, "_10_DISCOV_ALL_DEVS_: error");
             }
             break;
         case _11_DISCOV_UNOWN_DEVS_:
             if(discoverUnownedDevices())
             {
-                OC_LOG(ERROR, TAG, "_11_DISCOV_UNOWN_DEVS_: error");
+                OIC_LOG(ERROR, TAG, "_11_DISCOV_UNOWN_DEVS_: error");
             }
             break;
         case _12_DISCOV_OWN_DEVS_:
             if(discoverOwnedDevices())
             {
-                OC_LOG(ERROR, TAG, "_12_DISCOV_OWN_DEVS_: error");
+                OIC_LOG(ERROR, TAG, "_12_DISCOV_OWN_DEVS_: error");
             }
             break;
         case _20_REGIST_DEVS_:
             if(registerDevices())
             {
-                OC_LOG(ERROR, TAG, "_20_REGIST_DEVS_: error");
+                OIC_LOG(ERROR, TAG, "_20_REGIST_DEVS_: error");
             }
             break;
         case _30_PROVIS_PAIR_DEVS_:
             if(provisionPairwise())
             {
-                OC_LOG(ERROR, TAG, "_30_PROVIS_PAIR_DEVS_: error");
+                OIC_LOG(ERROR, TAG, "_30_PROVIS_PAIR_DEVS_: error");
             }
             break;
         case _31_PROVIS_CRED_:
             if(provisionCred())
             {
-                OC_LOG(ERROR, TAG, "_31_PROVIS_CRED_: error");
+                OIC_LOG(ERROR, TAG, "_31_PROVIS_CRED_: error");
             }
             break;
         case _32_PROVIS_ACL_:
             if(provisionAcl())
             {
-                OC_LOG(ERROR, TAG, "_32_PROVIS_ACL_: error");
+                OIC_LOG(ERROR, TAG, "_32_PROVIS_ACL_: error");
             }
             break;
-        case _33_CHECK_LINK_STATUS_:
+        case _33_PROVIS_DP_:
+            if(provisionDirectPairing())
+            {
+                OIC_LOG(ERROR, TAG, "_33_PROVIS_DP_: error");
+            }
+            break;
+        case _34_CHECK_LINK_STATUS_:
             if(checkLinkedStatus())
             {
-                OC_LOG(ERROR, TAG, "_33_CHECK_LINK_STATUS_: error");
+                OIC_LOG(ERROR, TAG, "_34_CHECK_LINK_STATUS_: error");
             }
             break;
         case _40_UNLINK_PAIR_DEVS_:
             if(unlinkPairwise())
             {
-                OC_LOG(ERROR, TAG, "_40_UNLINK_PAIR_DEVS_: error");
+                OIC_LOG(ERROR, TAG, "_40_UNLINK_PAIR_DEVS_: error");
             }
             break;
         case _50_REMOVE_SELEC_DEV_:
             if(removeDevice())
             {
-                OC_LOG(ERROR, TAG, "_50_REMOVE_SELEC_DEV_: error");
+                OIC_LOG(ERROR, TAG, "_50_REMOVE_SELEC_DEV_: error");
             }
             break;
         case _99_EXIT_PRVN_CLT_:
@@ -1212,7 +1404,7 @@ int main()
 PMCLT_ERROR:
     if(OC_STACK_OK != OCStop())
     {
-        OC_LOG(ERROR, TAG, "OCStack stop error");
+        OIC_LOG(ERROR, TAG, "OCStack stop error");
     }
     OCDeleteDiscoveredDevices(g_own_list);  // after here |g_own_list| points nothing
     OCDeleteDiscoveredDevices(g_unown_list);  // after here |g_unown_list| points nothing
@@ -1230,4 +1422,4 @@ PMCLT_ERROR:
 
 #ifdef __cplusplus
 }
-#endif //__cplusplus
\ No newline at end of file
+#endif //__cplusplus
index c31a612..7047ae9 100644 (file)
@@ -53,7 +53,7 @@ char *gResourceUri= (char *)"/a/led";
 //Secure Virtual Resource database for Iotivity Server
 //It contains Server's Identity and the PSK credentials
 //of other devices which the server trusts
-static char CRED_FILE[] = "oic_svr_db_server_justworks.json";
+static char CRED_FILE[] = "oic_svr_db_server_justworks.dat";
 
 /* Function that creates a new LED resource by calling the
  * OCCreateResource() method.
@@ -132,7 +132,7 @@ OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
     OCRepPayload* payload = OCRepPayloadCreate();
     if(!payload)
     {
-        OC_LOG(ERROR, TAG, "Failed to allocate Payload");
+        OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
         return NULL;
     }
 
@@ -148,7 +148,7 @@ OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
 {
     if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
     {
-        OC_LOG(ERROR, TAG, "Incoming payload not a representation");
+        OIC_LOG(ERROR, TAG, "Incoming payload not a representation");
         return NULL;
     }
 
@@ -258,7 +258,7 @@ OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
 
             if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
             {
-                OC_LOG (INFO, TAG, "Created new LED instance");
+                OIC_LOG (INFO, TAG, "Created new LED instance");
                 gLedInstance[gCurrLedInstance].state = 0;
                 gLedInstance[gCurrLedInstance].power = 0;
                 gCurrLedInstance++;
@@ -297,7 +297,7 @@ OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
     }
     else
     {
-        OC_LOG_V (INFO, TAG, "Payload was NULL");
+        OIC_LOG_V (INFO, TAG, "Payload was NULL");
         ehResult = OC_EH_ERROR;
     }
 
@@ -309,7 +309,7 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
         OCEntityHandlerRequest *entityHandlerRequest,
         void* callbackParam)
 {
-    OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
+    OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
     (void)callbackParam;
     OCEntityHandlerResult ehResult = OC_EH_ERROR;
 
@@ -319,7 +319,7 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
     // Validate pointer
     if (!entityHandlerRequest)
     {
-        OC_LOG (ERROR, TAG, "Invalid request pointer");
+        OIC_LOG (ERROR, TAG, "Invalid request pointer");
         return OC_EH_ERROR;
     }
 
@@ -327,27 +327,27 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
 
     if (flag & OC_REQUEST_FLAG)
     {
-        OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
+        OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
         if (entityHandlerRequest)
         {
             if (OC_REST_GET == entityHandlerRequest->method)
             {
-                OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
+                OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
                 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
             }
             else if (OC_REST_PUT == entityHandlerRequest->method)
             {
-                OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
+                OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
                 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
             }
             else if (OC_REST_POST == entityHandlerRequest->method)
             {
-                OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
+                OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
                 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
             }
             else
             {
-                OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
+                OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
                         entityHandlerRequest->method);
                 ehResult = OC_EH_ERROR;
             }
@@ -369,7 +369,7 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
                 // Send the response
                 if (OCDoResponse(&response) != OC_STACK_OK)
                 {
-                    OC_LOG(ERROR, TAG, "Error sending response");
+                    OIC_LOG(ERROR, TAG, "Error sending response");
                     ehResult = OC_EH_ERROR;
                 }
             }
@@ -399,7 +399,7 @@ int main()
 {
     struct timespec timeout;
 
-    OC_LOG(DEBUG, TAG, "OCServer is starting...");
+    OIC_LOG(DEBUG, TAG, "OCServer is starting...");
 
     // Initialize Persistent Storage for SVR database
     OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink};
@@ -408,7 +408,7 @@ int main()
 
     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack init error");
+        OIC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
 
@@ -421,23 +421,23 @@ int main()
     timeout.tv_nsec = 100000000L;
 
     // Break from loop with Ctrl-C
-    OC_LOG(INFO, TAG, "Entering ocserver main loop...");
+    OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
     signal(SIGINT, handleSigInt);
     while (!gQuitFlag)
     {
         if (OCProcess() != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             return 0;
         }
         nanosleep(&timeout, NULL);
     }
 
-    OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
+    OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
 
     if (OCStop() != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack process error");
+        OIC_LOG(ERROR, TAG, "OCStack process error");
     }
 
     return 0;
@@ -447,7 +447,7 @@ int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState,
 {
     if (!uri)
     {
-        OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
+        OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
         return -1;
     }
 
@@ -460,7 +460,7 @@ int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState,
             OCEntityHandlerCb,
             NULL,
             OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
-    OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
+    OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
 
     return 0;
 }
index f00f3dc..5ca0e7a 100644 (file)
@@ -54,7 +54,7 @@ char *gResourceUri= (char *)"/a/led";
 //Secure Virtual Resource database for Iotivity Server
 //It contains Server's Identity and the PSK credentials
 //of other devices which the server trusts
-static char CRED_FILE[] = "oic_svr_db_server_randompin.json";
+static char CRED_FILE[] = "oic_svr_db_server_randompin.dat";
 
 /* Function that creates a new LED resource by calling the
  * OCCreateResource() method.
@@ -133,7 +133,7 @@ OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
     OCRepPayload* payload = OCRepPayloadCreate();
     if(!payload)
     {
-        OC_LOG(ERROR, TAG, "Failed to allocate Payload");
+        OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
         return NULL;
     }
 
@@ -149,7 +149,7 @@ OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
 {
     if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
     {
-        OC_LOG(ERROR, TAG, "Incoming payload not a representation");
+        OIC_LOG(ERROR, TAG, "Incoming payload not a representation");
         return NULL;
     }
 
@@ -259,7 +259,7 @@ OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
 
             if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
             {
-                OC_LOG (INFO, TAG, "Created new LED instance");
+                OIC_LOG (INFO, TAG, "Created new LED instance");
                 gLedInstance[gCurrLedInstance].state = 0;
                 gLedInstance[gCurrLedInstance].power = 0;
                 gCurrLedInstance++;
@@ -298,7 +298,7 @@ OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
     }
     else
     {
-        OC_LOG_V (INFO, TAG, "Payload was NULL");
+        OIC_LOG_V (INFO, TAG, "Payload was NULL");
         ehResult = OC_EH_ERROR;
     }
 
@@ -310,7 +310,7 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
         OCEntityHandlerRequest *entityHandlerRequest,
         void* callbackParam)
 {
-    OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
+    OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
     (void)callbackParam;
     OCEntityHandlerResult ehResult = OC_EH_ERROR;
 
@@ -320,7 +320,7 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
     // Validate pointer
     if (!entityHandlerRequest)
     {
-        OC_LOG (ERROR, TAG, "Invalid request pointer");
+        OIC_LOG (ERROR, TAG, "Invalid request pointer");
         return OC_EH_ERROR;
     }
 
@@ -328,27 +328,27 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
 
     if (flag & OC_REQUEST_FLAG)
     {
-        OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
+        OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
         if (entityHandlerRequest)
         {
             if (OC_REST_GET == entityHandlerRequest->method)
             {
-                OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
+                OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
                 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
             }
             else if (OC_REST_PUT == entityHandlerRequest->method)
             {
-                OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
+                OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
                 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
             }
             else if (OC_REST_POST == entityHandlerRequest->method)
             {
-                OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
+                OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
                 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
             }
             else
             {
-                OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
+                OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
                         entityHandlerRequest->method);
                 ehResult = OC_EH_ERROR;
             }
@@ -370,7 +370,7 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
                 // Send the response
                 if (OCDoResponse(&response) != OC_STACK_OK)
                 {
-                    OC_LOG(ERROR, TAG, "Error sending response");
+                    OIC_LOG(ERROR, TAG, "Error sending response");
                     ehResult = OC_EH_ERROR;
                 }
             }
@@ -400,20 +400,20 @@ void GeneratePinCB(char* pin, size_t pinSize)
 {
     if(NULL == pin || pinSize <= 0)
     {
-        OC_LOG(INFO, TAG, "Invalid PIN");
+        OIC_LOG(INFO, TAG, "Invalid PIN");
         return;
     }
 
-    OC_LOG(INFO, TAG, "============================");
-    OC_LOG_V(INFO, TAG, "    PIN CODE : %s", pin);
-    OC_LOG(INFO, TAG, "============================");
+    OIC_LOG(INFO, TAG, "============================");
+    OIC_LOG_V(INFO, TAG, "    PIN CODE : %s", pin);
+    OIC_LOG(INFO, TAG, "============================");
 }
 
 int main()
 {
     struct timespec timeout;
 
-    OC_LOG(DEBUG, TAG, "OCServer is starting...");
+    OIC_LOG(DEBUG, TAG, "OCServer is starting...");
 
     // Initialize Persistent Storage for SVR database
     OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink};
@@ -421,7 +421,7 @@ int main()
 
     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack init error");
+        OIC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
 
@@ -440,23 +440,23 @@ int main()
     timeout.tv_nsec = 100000000L;
 
     // Break from loop with Ctrl-C
-    OC_LOG(INFO, TAG, "Entering ocserver main loop...");
+    OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
     signal(SIGINT, handleSigInt);
     while (!gQuitFlag)
     {
         if (OCProcess() != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             return 0;
         }
         nanosleep(&timeout, NULL);
     }
 
-    OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
+    OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
 
     if (OCStop() != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack process error");
+        OIC_LOG(ERROR, TAG, "OCStack process error");
     }
 
     return 0;
@@ -466,7 +466,7 @@ int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState,
 {
     if (!uri)
     {
-        OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
+        OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
         return -1;
     }
 
@@ -479,7 +479,7 @@ int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState,
             OCEntityHandlerCb,
             NULL,
             OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
-    OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
+    OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
 
     return 0;
 }
index 1dc263f..44e80a4 100644 (file)
  * *****************************************************************/
 #include <string.h>
 #include "credentialgenerator.h"
+#include "base64.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
-#include "logger.h"
+#include "ocpayload.h"
+#include "payload_logging.h"
 #include "credresource.h"
 #include "ocrandom.h"
-#include "base64.h"
+#include "srmutility.h"
 #include "stdbool.h"
 #include "securevirtualresourcetypes.h"
 #ifdef __WITH_X509__
 #include "ck_manager.h"
+//Certificate-related functions
+#define CERT_LEN_PREFIX (3)
+#define BYTE_SIZE (8) //bits
 
 #define CHAIN_LEN (2) //TODO: replace by external define or a runtime value
 #endif  //__WITH_X509__
 
 #define TAG "SRPAPI-CG"
 
-/**
- * @def PM_VERIFY_SUCCESS
- * @brief Macro to verify success of operation.
- *        eg: PM_VERIFY_SUCCESS(TAG, OC_STACK_OK == foo(), OC_STACK_ERROR, ERROR);
- * @note Invoking function must define "bail:" label for goto functionality to work correctly and
- *       must define "OCStackResult res" for setting error code.
- * */
-#define PM_VERIFY_SUCCESS(tag, op, errCode, logLevel) { if (!(op)) \
-                       {OC_LOG((logLevel), tag, #op " failed!!"); res = errCode; goto bail;} }
-/**
- * @def PM_VERIFY_NON_NULL
- * @brief Macro to verify argument is not equal to NULL.
- *        eg: PM_VERIFY_NON_NULL(TAG, ptrData, ERROR);
- * @note Invoking function must define "bail:" label for goto functionality to work correctly.
- * */
-#define PM_VERIFY_NON_NULL(tag, arg, errCode, logLevel) { if (NULL == (arg)) \
-                   { OC_LOG((logLevel), tag, #arg " is NULL"); res = errCode; goto bail;} }
-
 OCStackResult PMGeneratePairWiseCredentials(OicSecCredType_t type, size_t keySize,
-                                    const OicUuid_t *ptDeviceId,
-                                    const OicUuid_t *firstDeviceId, const OicUuid_t *secondDeviceId,
-                                    OicSecCred_t **firstCred, OicSecCred_t **secondCred)
+        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)
     {
-        OC_LOG(INFO, TAG, "Invalid params");
+        OIC_LOG(INFO, TAG, "Invalid params");
         return OC_STACK_INVALID_PARAM;
     }
     if(!(keySize == OWNER_PSK_LENGTH_128 || keySize == OWNER_PSK_LENGTH_256))
     {
-        OC_LOG(INFO, TAG, "Invalid key size");
+        OIC_LOG(INFO, TAG, "Invalid key size");
         return OC_STACK_INVALID_PARAM;
     }
     OCStackResult res = OC_STACK_ERROR;
-    uint8_t* privData = NULL;
-    char* base64Buff = NULL;
     OicSecCred_t *tempFirstCred = NULL;
     OicSecCred_t *tempSecondCred = NULL;
 
     size_t privDataKeySize = keySize;
 
-    privData = (uint8_t*) OICCalloc(privDataKeySize,sizeof(uint8_t));
-    PM_VERIFY_NON_NULL(TAG, privData, OC_STACK_NO_MEMORY, ERROR);
-
-    OCFillRandomMem(privData,privDataKeySize);
+    uint8_t *privData = (uint8_t *)OICCalloc(privDataKeySize, sizeof(uint8_t));
+    VERIFY_NON_NULL(TAG, privData, ERROR);
+    OicSecKey_t privKey = {privData, keySize};
 
-    uint32_t outLen = 0;
-
-    base64Buff = (char*) OICCalloc(B64ENCODE_OUT_SAFESIZE(privDataKeySize) + 1, sizeof(char));
-    PM_VERIFY_NON_NULL(TAG, base64Buff, OC_STACK_NO_MEMORY, ERROR);
-    int memReq = (B64ENCODE_OUT_SAFESIZE(privDataKeySize) + 1) * sizeof(char);
-    B64Result b64Ret = b64Encode(privData, privDataKeySize*sizeof(uint8_t), base64Buff,
-                                 memReq, &outLen);
-    PM_VERIFY_SUCCESS(TAG, B64_OK == b64Ret, OC_STACK_ERROR, ERROR);
+    OCFillRandomMem(privData, privDataKeySize);
 
     // TODO: currently owner array is 1. only provisioning tool's id.
-    tempFirstCred =  GenerateCredential(secondDeviceId, type, NULL, base64Buff, 1, ptDeviceId);
-    PM_VERIFY_NON_NULL(TAG, tempFirstCred, OC_STACK_ERROR, ERROR);
+    tempFirstCred =  GenerateCredential(secondDeviceId, type, NULL, &privKey, ptDeviceId);
+    VERIFY_NON_NULL(TAG, tempFirstCred, ERROR);
 
     // TODO: currently owner array is 1. only provisioning tool's id.
-    tempSecondCred =  GenerateCredential(firstDeviceId, type, NULL, base64Buff, 1, ptDeviceId);
-    PM_VERIFY_NON_NULL(TAG, tempSecondCred, OC_STACK_ERROR, ERROR);
+    tempSecondCred =  GenerateCredential(firstDeviceId, type, NULL, &privKey, ptDeviceId);
+    VERIFY_NON_NULL(TAG, tempSecondCred, ERROR);
 
     *firstCred = tempFirstCred;
     *secondCred = tempSecondCred;
     res = OC_STACK_OK;
 
-bail:
+exit:
     OICFree(privData);
-    OICFree(base64Buff);
 
     if(res != OC_STACK_OK)
     {
@@ -120,95 +94,27 @@ bail:
 }
 
 #ifdef __WITH_X509__
-/**
- * Function to compose JSON Web Key (JWK) string from a certificate and a public key.
- *
- * @param[in]  certificateChain    Array of Base64 encoded certificate strings.
- * @param[in]  chainLength         Number of the certificates in certificateChain.
- * @return     Valid JWK string on success, or NULL on fail.
- */
-static char *CreateCertificatePublicJWK(const char *const *certificateChain,
-                                        const size_t chainLength)
+static void writeCertPrefix(uint8_t *prefix, uint32_t certLen)
 {
-    if (NULL == certificateChain || chainLength == 0)
-    {
-        OC_LOG(ERROR, TAG, "Error CreateCertificatePublicJWK: Invalid params");
-        return NULL;
-    }
-
-    size_t certChainSize = 0;
-    for (size_t i = 0; i < chainLength; ++i)
-    {
-        if (NULL != certificateChain[i])
-        {
-            certChainSize += strlen(certificateChain[i]);
-        }
-        else
-        {
-            OC_LOG(ERROR, TAG, "Error CreateCertificatePublicJWK: Invalid params");
-            return NULL;
-        }
-
-    }
-    /* certificates in the json array taken in quotes and separated by a comma
-     * so we have to count the number of characters (number of commas and quotes) required
-     * for embedding certificates in the array depending on the number of certificates in chain
-     * each certificate except last embeded in  "\"%s\"," */
-    const int numCommasAndQuotes = chainLength * 3 - 1;
-    const char firstPart[] = "{\"kty\":\"EC\",\"crv\":\"P-256\",\"x5c\":[";
-    const char secondPart[] = "]}";
-    /* to calculate the size of JWK public part we need to add the value of first and  second parts,
-     * size of certificate chain, number of additional commas and quotes and 1 for string termination symbol */
-    size_t certPubJWKLen = strlen(firstPart) + strlen(secondPart)
-                                             + certChainSize + numCommasAndQuotes + 1;
-    char *certPubJWK = (char *)OICMalloc(certPubJWKLen);
-
-    if (NULL != certPubJWK)
-    {
-        OICStrcpy(certPubJWK, certPubJWKLen, firstPart);
-        size_t offset = strlen(firstPart);
-        for (size_t i = 0; i < chainLength; ++i)
-        {
-            offset += sprintf(certPubJWK + offset, "\"%s\",", certificateChain[i]);
-        }
-        sprintf(certPubJWK + offset - 1, secondPart);
-    }
-    else
+    for (size_t i = 0; i < CERT_LEN_PREFIX; ++i)
     {
-        OC_LOG(ERROR, TAG, "Error while memory allocation");
+        prefix[i] = (certLen >> (BYTE_SIZE * (CERT_LEN_PREFIX - 1 - i))) & 0xFF;
     }
-    return certPubJWK;
 }
 
-/**
- * Function to compose JWK string from a private key.
- *
- * @param[in]  privateKey    Base64 encoded private key.
- * @return     Valid JWK string on success, or NULL on fail.
- */
-static char *CreateCertificatePrivateJWK(const char *privateKey)
+static uint32_t appendCert2Chain(uint8_t *appendPoint, uint8_t *cert, size_t len)
 {
-    if (NULL == privateKey)
-    {
-        OC_LOG(ERROR, TAG, "Error privateKey is NULL");
-        return NULL;
-    }
-    const char firstPart[] = "{\"kty\":\"EC\",\"crv\":\"P-256\",\"d\":\"";
-    const char secondPart[] = "\"}";
-    char *certPrivJWK = (char *)OICMalloc(strlen(firstPart) + strlen(secondPart) + strlen(
-            privateKey) + 1);
+    uint32_t ret = 0;
+    VERIFY_NON_NULL(TAG, appendPoint, ERROR);
+    VERIFY_NON_NULL(TAG, cert, ERROR);
 
-    if (NULL != certPrivJWK)
-    {
-        sprintf(certPrivJWK, "%s%s%s", firstPart, privateKey, secondPart);
-    }
-    else
-    {
-        OC_LOG(ERROR, TAG, "Error while memory allocation");
-    }
-    return certPrivJWK;
-}
+    memcpy(appendPoint + CERT_LEN_PREFIX, cert, len);
+    writeCertPrefix(appendPoint, len);
 
+    ret = len + CERT_LEN_PREFIX;
+exit:
+    return ret;
+}
 
 /**
  * Function to generate Base64 encoded credential data for device.
@@ -219,15 +125,15 @@ static char *CreateCertificatePrivateJWK(const char *privateKey)
  * @param[out]  privKey             Pointer to Base64 encoded private key.
  * @return  OC_STACK_OK on success
  */
-static OCStackResult GenerateCertificateAndKeys(const OicUuid_t * subject, char *** const certificateChain,
-        size_t * const chainLength, char ** const privKey)
+static OCStackResult GenerateCertificateAndKeys(const OicUuid_t * subject, OicSecCert_t * certificateChain,
+        OicSecKey_t * privKey)
 {
-    if (NULL == subject || NULL == certificateChain || NULL == chainLength || NULL == privKey)
+    if (NULL == subject || NULL == certificateChain || NULL == privKey)
     {
         return  OC_STACK_INVALID_PARAM;
     }
-    *certificateChain = NULL;
-    *privKey     = NULL;
+    certificateChain->data = NULL;
+    privKey->data = NULL;
 
     ByteArray pubKeyBA  = BYTE_ARRAY_INITIALIZER;
     ByteArray privKeyBA = BYTE_ARRAY_INITIALIZER;
@@ -253,93 +159,61 @@ static OCStackResult GenerateCertificateAndKeys(const OicUuid_t * subject, char
 
     if (PKI_SUCCESS != GenerateKeyPair(&privKeyBA, &pubKeyBA))
     {
-        OC_LOG(ERROR, TAG, "Error generating keys.");
+        OIC_LOG(ERROR, TAG, "Error generating keys.");
         return OC_STACK_ERROR;
     }
     if (PKI_SUCCESS != CKMIssueDeviceCertificate(subjName, NULL, NULL, pubKeyBA.data, cert))
     {
-        OC_LOG(ERROR, TAG, "Error generating certificate.");
+        OIC_LOG(ERROR, TAG, "Error generating certificate.");
         return OC_STACK_ERROR;
     }
 
-    char privB64buf[B64ENCODE_OUT_SAFESIZE(PRIVATE_KEY_SIZE) + 1] = {0};
-    uint32_t privB64len = 0;
-    if (B64_OK != b64Encode(privKeyBA.data,  privKeyBA.len, privB64buf,
-                             B64ENCODE_OUT_SAFESIZE(PRIVATE_KEY_SIZE) + 1, &privB64len))
+    uint8_t numCert = 0;
+    if (PKI_SUCCESS != GetCAChain(&numCert , cert + 1))
     {
-        OC_LOG(ERROR, TAG, "Error while encoding key");
+        OIC_LOG(ERROR, TAG, "Error getting CA certificate chain.");
         return OC_STACK_ERROR;
     }
 
-    if (PKI_SUCCESS != GetCAChain(chainLength , cert + 1))
+    numCert ++;
+    uint32_t len = 0;
+    for (size_t i = 0; i < numCert; i++)
     {
-        OC_LOG(ERROR, TAG, "Error getting CA certificate chain.");
-        return OC_STACK_ERROR;
-    }
-
-    ++(*chainLength);
-    *certificateChain = (char **)OICMalloc(sizeof(char *) * (*chainLength));
-
-    OCStackResult ret = OC_STACK_NO_MEMORY;
-    if (NULL == *certificateChain)
-    {
-        goto memclean;
-    }
-
-
-    for (size_t i = 0; i < *chainLength; ++i)
-    {
-        (*certificateChain)[i] = NULL;
-
-        char certB64buf[B64ENCODE_OUT_SAFESIZE(ISSUER_MAX_CERT_SIZE) + 1] = {0};
-        uint32_t certB64len = 0;
-        if (B64_OK != b64Encode(cert[i].data, cert[i].len, certB64buf,
-                                B64ENCODE_OUT_SAFESIZE(ISSUER_MAX_CERT_SIZE) + 1, &certB64len))
+        certificateChain->data = (uint8_t *) OICRealloc(certificateChain->data,
+                                                        len + cert[i].len + CERT_LEN_PREFIX);
+        if (NULL == certificateChain->data)
         {
-            OC_LOG(ERROR, TAG, "Error while encoding certificate");
-            ret = OC_STACK_ERROR;
-            goto memclean;
+            OIC_LOG(ERROR, TAG, "Error while memory allocation");
+            return OC_STACK_ERROR;
         }
 
-        (*certificateChain)[i] = (char *) OICMalloc(certB64len + 1);
-        if (NULL == (*certificateChain)[i])
+        uint32_t appendedLen = appendCert2Chain(certificateChain->data + len,
+                                                cert[i].data, cert[i].len);
+        if (0 == appendedLen)
         {
-            goto memclean;
+            OIC_LOG(ERROR, TAG, "Error while certifiacate chain creation.");
+            OICFree(certificateChain->data);
+            certificateChain->len = 0;
+            return OC_STACK_ERROR;
         }
-
-        memcpy((*certificateChain)[i], certB64buf, certB64len + 1);
+        len += appendedLen;
     }
-
-
-    *privKey     = (char *)OICMalloc(privB64len + 1);
-
-    if (NULL == *privKey)
+    certificateChain->len = len;
+    privKey->data = (uint8_t*) OICMalloc(PRIVATE_KEY_SIZE);
+    if (NULL == privKey->data)
     {
-memclean:
-        if (NULL != *certificateChain)
-        {
-            for (size_t i = 0; i < *chainLength; ++i)
-            {
-                OICFree((*certificateChain)[i]);
-            }
-        }
-        OICFree(*certificateChain);
-        *certificateChain = NULL;
-        *privKey     = NULL;
-        *chainLength = 0;
-        if (OC_STACK_NO_MEMORY == ret)
-        {
-            OC_LOG(ERROR, TAG, "Error while memory allocation");
-        }
-        return ret;
+        OIC_LOG(ERROR, TAG, "Error while memory allocation");
+        OICFree(certificateChain->data);
+        certificateChain->len = 0;
+        privKey->len = 0;
+        return OC_STACK_ERROR;
     }
-
-    memcpy(*privKey, privB64buf, privB64len + 1);
+    memcpy(privKey->data, privKeyData, PRIVATE_KEY_SIZE);
+    privKey->len = PRIVATE_KEY_SIZE;
 
     return OC_STACK_OK;
 }
 
-
 OCStackResult PMGenerateCertificateCredentials(const OicUuid_t *ptDeviceId,
         const OicUuid_t *deviceId, OicSecCred_t **const cred)
 {
@@ -347,42 +221,16 @@ OCStackResult PMGenerateCertificateCredentials(const OicUuid_t *ptDeviceId,
     {
         return OC_STACK_INVALID_PARAM;
     }
-    char **certificateChain = NULL;
-    char *privKey = NULL;
-    size_t certChainLen = 0;
-    if (OC_STACK_OK != GenerateCertificateAndKeys(deviceId, &certificateChain,
-            &certChainLen, &privKey))
-    {
-        OC_LOG(ERROR, TAG, "Error while generating credential data.");
-        return OC_STACK_ERROR;
-    }
-
-    char *publicJWK = CreateCertificatePublicJWK(certificateChain, certChainLen);
-    char *privateJWK = CreateCertificatePrivateJWK(privKey);
-    for (size_t i = 0; i < certChainLen; ++i)
-    {
-        OICFree(certificateChain[i]);
-    }
-    OICFree(certificateChain);
-    OICFree(privKey);
-    if (NULL == publicJWK || NULL == privateJWK)
+    OicSecCert_t certificateChain;
+    OicSecKey_t privKey;
+    if (OC_STACK_OK != GenerateCertificateAndKeys(deviceId, &certificateChain, &privKey))
     {
-        OICFree(publicJWK);
-        OICFree(privateJWK);
-        OC_LOG(ERROR, TAG, "Error while converting keys to JWK format.");
+        OIC_LOG(ERROR, TAG, "Error while generating credential data.");
         return OC_STACK_ERROR;
     }
 
-    OicSecCred_t *tempCred =  GenerateCredential(deviceId, SIGNED_ASYMMETRIC_KEY, publicJWK,
-                              privateJWK, 1, ptDeviceId);
-    OICFree(publicJWK);
-    OICFree(privateJWK);
-    if (NULL == tempCred)
-    {
-        OC_LOG(ERROR, TAG, "Error while generating credential.");
-        return OC_STACK_ERROR;
-    }
-    *cred = tempCred;
+    *cred = GenerateCredential(deviceId, SIGNED_ASYMMETRIC_KEY, &certificateChain,
+                              &privKey, ptDeviceId);
     return OC_STACK_OK;
 }
 #endif // __WITH_X509__
index 59f6895..b5d4bed 100644 (file)
@@ -30,6 +30,7 @@
 #include "credresource.h"
 #include "utlist.h"
 #include "aclresource.h" //Note: SRM internal header
+#include "pconfresource.h"
 
 #define TAG "OCPMAPI"
 
@@ -69,13 +70,13 @@ OCStackResult OCInitPM(const char* dbPath)
  * OCMode.
  *
  * @param[in] timeout Timeout in seconds, value till which function will listen to responses from
- *                    client before returning the list of devices.
+ *                    server before returning the list of devices.
  * @param[out] ppList List of candidate devices to be provisioned
  * @return OTM_SUCCESS in case of success and other value otherwise.
  */
 OCStackResult OCDiscoverUnownedDevices(unsigned short timeout, OCProvisionDev_t **ppList)
 {
-    if( ppList == NULL || *ppList != NULL)
+    if( ppList == NULL || *ppList != NULL || 0 == timeout)
     {
         return OC_STACK_INVALID_PARAM;
     }
@@ -88,13 +89,13 @@ OCStackResult OCDiscoverUnownedDevices(unsigned short timeout, OCProvisionDev_t
  * all the device in subnet which are owned by calling provisioning client.
  *
  * @param[in] timeout Timeout in seconds, value till which function will listen to responses from
- *                    client before returning the list of devices.
+ *                    server before returning the list of devices.
  * @param[out] ppList List of device owned by provisioning tool.
  * @return OTM_SUCCESS in case of success and other value otherwise.
  */
 OCStackResult OCDiscoverOwnedDevices(unsigned short timeout, OCProvisionDev_t **ppList)
 {
-    if( ppList == NULL || *ppList != NULL)
+    if( ppList == NULL || *ppList != NULL || 0 == timeout)
     {
         return OC_STACK_INVALID_PARAM;
     }
@@ -113,7 +114,7 @@ OCStackResult OCSetOwnerTransferCallbackData(OicSecOxm_t oxm, OTMCallbackData_t*
 {
     if(NULL == callbackData)
     {
-        return OC_STACK_INVALID_PARAM;
+        return OC_STACK_INVALID_CALLBACK ;
     }
 
     return OTMSetOwnershipTransferCallbackData(oxm, callbackData);
@@ -127,7 +128,11 @@ OCStackResult OCDoOwnershipTransfer(void* ctx,
     {
         return OC_STACK_INVALID_PARAM;
     }
-
+    if (!resultCallback)
+    {
+        OIC_LOG(INFO, TAG, "OCDoOwnershipTransfer : NULL Callback");
+        return OC_STACK_INVALID_CALLBACK;
+    }
     return OTMDoOwnershipTransfer(ctx, targetDevices, resultCallback);
 }
 
@@ -178,6 +183,22 @@ OCStackResult OCProvisionCredentials(void *ctx, OicSecCredType_t type, size_t ke
 
 }
 
+/**
+ * this function sends Direct-Pairing Configuration to a device.
+ *
+ * @param[in] ctx Application context would be returned in result callback.
+ * @param[in] selectedDeviceInfo Selected target device.
+ * @param[in] pconf PCONF pointer.
+ * @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 OCProvisionDirectPairing(void* ctx, const OCProvisionDev_t *selectedDeviceInfo, OicSecPconf_t *pconf,
+                             OCProvisionResultCB resultCallback)
+{
+    return SRPProvisionDirectPairing(ctx, selectedDeviceInfo, pconf, resultCallback);
+}
+
 /*
 * Function to unlink devices.
 * This function will remove the credential & relationship between the two devices.
@@ -194,13 +215,23 @@ OCStackResult OCUnlinkDevices(void* ctx,
                               const OCProvisionDev_t* pTargetDev2,
                               OCProvisionResultCB resultCallback)
 {
-    OC_LOG(INFO, TAG, "IN OCUnlinkDevices");
+    OIC_LOG(INFO, TAG, "IN OCUnlinkDevices");
     OCUuidList_t* idList = NULL;
     size_t numOfDev = 0;
 
-    if (!pTargetDev1 || !pTargetDev2 || !resultCallback)
+    if (!pTargetDev1 || !pTargetDev2 || !pTargetDev1->doxm || !pTargetDev2->doxm)
     {
-        OC_LOG(ERROR, TAG, "OCUnlinkDevices : NULL parameters");
+        OIC_LOG(ERROR, TAG, "OCUnlinkDevices : NULL parameters");
+        return OC_STACK_INVALID_PARAM;
+    }
+    if (!resultCallback)
+    {
+        OIC_LOG(INFO, TAG, "OCUnlinkDevices : NULL Callback");
+        return OC_STACK_INVALID_CALLBACK;
+    }
+    if (0 == memcmp(&pTargetDev1->doxm->deviceID, &pTargetDev2->doxm->deviceID, sizeof(OicUuid_t)))
+    {
+        OIC_LOG(INFO, TAG, "OCUnlinkDevices : Same device ID");
         return OC_STACK_INVALID_PARAM;
     }
 
@@ -208,12 +239,12 @@ OCStackResult OCUnlinkDevices(void* ctx,
     OCStackResult res = PDMGetLinkedDevices(&(pTargetDev1->doxm->deviceID), &idList, &numOfDev);
     if (OC_STACK_OK != res)
     {
-        OC_LOG(ERROR, TAG, "OCUnlinkDevices : PDMgetOwnedDevices failed");
+        OIC_LOG(ERROR, TAG, "OCUnlinkDevices : PDMgetOwnedDevices failed");
         goto error;
     }
     if (1 > numOfDev)
     {
-        OC_LOG(DEBUG, TAG, "OCUnlinkDevices : Can not find linked devices");
+        OIC_LOG(DEBUG, TAG, "OCUnlinkDevices : Can not find linked devices");
         res = OC_STACK_INVALID_PARAM; // Input devices are not linked, No request is made
         goto error;
     }
@@ -227,17 +258,17 @@ OCStackResult OCUnlinkDevices(void* ctx,
             res = SRPUnlinkDevices(ctx, pTargetDev1, pTargetDev2, resultCallback);
             if (OC_STACK_OK != res)
             {
-                OC_LOG(ERROR, TAG, "OCUnlinkDevices : Failed to unlink devices.");
+                OIC_LOG(ERROR, TAG, "OCUnlinkDevices : Failed to unlink devices.");
             }
             goto error;
         }
         curDev = curDev->next;
     }
-    OC_LOG(DEBUG, TAG, "No matched pair found from provisioning database");
+    OIC_LOG(DEBUG, TAG, "No matched pair found from provisioning database");
     res = OC_STACK_INVALID_PARAM; // Input devices are not linked, No request is made
 
 error:
-    OC_LOG(INFO, TAG, "OUT OCUnlinkDevices");
+    OIC_LOG(INFO, TAG, "OUT OCUnlinkDevices");
 
     PDMDestoryOicUuidLinkList(idList);
     return res;
@@ -258,13 +289,18 @@ OCStackResult OCRemoveDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDis
                             const OCProvisionDev_t* pTargetDev,
                             OCProvisionResultCB resultCallback)
 {
-    OC_LOG(INFO, TAG, "IN OCRemoveDevice");
+    OIC_LOG(INFO, TAG, "IN OCRemoveDevice");
     OCStackResult res = OC_STACK_ERROR;
-    if (!pTargetDev || !resultCallback || 0 == waitTimeForOwnedDeviceDiscovery)
+    if (!pTargetDev || 0 == waitTimeForOwnedDeviceDiscovery)
     {
-        OC_LOG(INFO, TAG, "OCRemoveDevice : Invalied parameters");
+        OIC_LOG(INFO, TAG, "OCRemoveDevice : Invalied parameters");
         return OC_STACK_INVALID_PARAM;
     }
+    if (!resultCallback)
+    {
+        OIC_LOG(INFO, TAG, "OCRemoveDevice : NULL Callback");
+        return OC_STACK_INVALID_CALLBACK;
+    }
 
     // Send DELETE requests to linked devices
     OCStackResult resReq = OC_STACK_ERROR; // Check that we have to wait callback or not.
@@ -273,11 +309,11 @@ OCStackResult OCRemoveDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDis
     {
         if (OC_STACK_CONTINUE == resReq)
         {
-            OC_LOG(DEBUG, TAG, "OCRemoveDevice : Revoked device has no linked device except PT.");
+            OIC_LOG(DEBUG, TAG, "OCRemoveDevice : Revoked device has no linked device except PT.");
         }
         else
         {
-            OC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to invoke SRPRemoveDevice");
+            OIC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to invoke SRPRemoveDevice");
             res = resReq;
             goto error;
         }
@@ -288,30 +324,56 @@ OCStackResult OCRemoveDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDis
     cred = GetCredResourceData(&pTargetDev->doxm->deviceID);
     if (cred == NULL)
     {
-        OC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to get credential of remove device.");
+        OIC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to get credential of remove device.");
         goto error;
     }
 
     res = RemoveCredential(&cred->subject);
     if (res != OC_STACK_RESOURCE_DELETED)
     {
-        OC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to remove credential.");
+        OIC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to remove credential.");
         goto error;
     }
 
-    // Remove device info from prvisioning database.
-    res = PDMDeleteDevice(&pTargetDev->doxm->deviceID);
+    /**
+     * Change the device status as stale status.
+     * If all request are successed, this device information will be deleted.
+     */
+    res = PDMSetDeviceStale(&pTargetDev->doxm->deviceID);
     if (res != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to delete device in PDM.");
+        OIC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to set device status as stale");
         goto error;
     }
 
-    // Check that we have to wait callback for DELETE request or not
+    // TODO: We need to add new mechanism to clean up the stale state of the device.
+
     res = resReq;
 
+    //Close the DTLS session of the removed device.
+    CAEndpoint_t* endpoint = (CAEndpoint_t *)&pTargetDev->endpoint;
+    endpoint->port = pTargetDev->securePort;
+    CAResult_t caResult = CACloseDtlsSession(endpoint);
+    if(CA_STATUS_OK != caResult)
+    {
+        OIC_LOG_V(WARNING, TAG, "OCRemoveDevice : Failed to close DTLS session : %d", caResult);
+    }
+
+    /**
+     * If there is no linked device, PM does not send any request.
+     * So we should directly invoke the result callback to inform the result of OCRemoveDevice.
+     */
+    if(OC_STACK_CONTINUE == res)
+    {
+        if(resultCallback)
+        {
+            resultCallback(ctx, 0, NULL, false);
+        }
+        res = OC_STACK_OK;
+    }
+
 error:
-    OC_LOG(INFO, TAG, "OUT OCRemoveDevice");
+    OIC_LOG(INFO, TAG, "OUT OCRemoveDevice");
     return res;
 }
 
@@ -322,7 +384,7 @@ error:
 static void UpdateLinkResults(Linkdata_t *link, int device, OCStackResult stackresult)
 {
 
-    OC_LOG_V(INFO,TAG,"value of link->currentCountResults is %d",link->currentCountResults);
+    OIC_LOG_V(INFO,TAG,"value of link->currentCountResults is %d",link->currentCountResults);
     if (1 == device)
     {
         memcpy(link->resArr[(link->currentCountResults)].deviceId.id, link->pDev1->doxm->deviceID.id,UUID_LENGTH);
@@ -344,7 +406,7 @@ static void AclProv2CB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool has
 
     if (NULL == ctx)
     {
-        OC_LOG(ERROR,TAG,"Context is Null in ACLProv 2");
+        OIC_LOG(ERROR,TAG,"Context is Null in ACLProv 2");
         return;
     }
     (void)nOfRes;
@@ -355,7 +417,7 @@ static void AclProv2CB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool has
     if (hasError)
     {
         UpdateLinkResults(link, 2,arr[0].res);
-        OC_LOG(ERROR,TAG,"Error occured while ACL provisioning device 1");
+        OIC_LOG(ERROR,TAG,"Error occured while ACL provisioning device 1");
         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
                                                 link->resArr,
                                                 true);
@@ -380,7 +442,7 @@ static void AclProv1CB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool has
 
     if (NULL == ctx)
     {
-        OC_LOG(ERROR,TAG,"Context is Null in ACLProv1");
+        OIC_LOG(ERROR,TAG,"Context is Null in ACLProv1");
         return;
     }
     (void)nOfRes;
@@ -389,7 +451,7 @@ static void AclProv1CB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool has
 
     if (hasError)
     {
-        OC_LOG(ERROR,TAG,"Error occured while ACL provisioning device 1");
+        OIC_LOG(ERROR,TAG,"Error occured while ACL provisioning device 1");
         UpdateLinkResults(link, 1, arr[0].res);
         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
                                                 link->resArr,
@@ -430,17 +492,17 @@ static void ProvisionCredsCB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bo
 {
     if (NULL == ctx)
     {
-        OC_LOG(ERROR,TAG,"Error occured while credential provisioning");
+        OIC_LOG(ERROR,TAG,"Error occured while credential provisioning");
         return;
     }
     Linkdata_t *link = (Linkdata_t*)ctx;
     OCProvisionResultCB resultCallback = link->resultCallback;
-    OC_LOG_V(INFO, TAG, "has error returned %d",hasError);
+    OIC_LOG_V(INFO, TAG, "has error returned %d",hasError);
     UpdateLinkResults(link, 1, arr[0].res);
     UpdateLinkResults(link, 2, arr[1].res);
     if (hasError)
     {
-        OC_LOG(ERROR,TAG,"Error occured while credential provisioning");
+        OIC_LOG(ERROR,TAG,"Error occured while credential provisioning");
         ((OCProvisionResultCB)(resultCallback))(link->ctx, nOfRes,
                                                 link->resArr,
                                                 true);
@@ -454,7 +516,7 @@ static void ProvisionCredsCB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bo
         OCStackResult res =  SRPProvisionACL(ctx, link->pDev1, link->pDev1Acl, &AclProv1CB);
         if (OC_STACK_OK!=res)
         {
-             OC_LOG(ERROR, TAG, "Error while provisioning ACL for device 1");
+             OIC_LOG(ERROR, TAG, "Error while provisioning ACL for device 1");
              UpdateLinkResults(link, 1, res);
              ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
                                                      link->resArr,
@@ -465,11 +527,11 @@ static void ProvisionCredsCB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bo
     }
     else if (NULL!=link->pDev2Acl)
     {
-        OC_LOG(ERROR, TAG, "ACL for device 1 is NULL");
+        OIC_LOG(ERROR, TAG, "ACL for device 1 is NULL");
         OCStackResult res =  SRPProvisionACL(ctx, link->pDev2, link->pDev2Acl, &AclProv2CB);
         if (OC_STACK_OK!=res)
         {
-             OC_LOG(ERROR, TAG, "Error while provisioning ACL for device 2");
+             OIC_LOG(ERROR, TAG, "Error while provisioning ACL for device 2");
               UpdateLinkResults(link, 2, res);
              ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
                                                      link->resArr,
@@ -480,7 +542,7 @@ static void ProvisionCredsCB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bo
     }
     else
     {
-        OC_LOG(INFO, TAG, "ACLs of both devices are NULL");
+        OIC_LOG(INFO, TAG, "ACLs of both devices are NULL");
         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
                                                 link->resArr,
                                                 false);
@@ -508,28 +570,38 @@ OCStackResult OCProvisionPairwiseDevices(void* ctx, OicSecCredType_t type, size_
                                          OCProvisionResultCB resultCallback)
 {
 
-    if (!pDev1 || !pDev2 || !resultCallback)
+    if (!pDev1 || !pDev2 || !pDev1->doxm || !pDev2->doxm)
     {
-        OC_LOG(ERROR, TAG, "OCProvisionPairwiseDevices : Invalid parameters");
+        OIC_LOG(ERROR, TAG, "OCProvisionPairwiseDevices : Invalid parameters");
         return OC_STACK_INVALID_PARAM;
     }
+    if (!resultCallback)
+    {
+        OIC_LOG(INFO, TAG, "OCProvisionPairwiseDevices : NULL Callback");
+        return OC_STACK_INVALID_CALLBACK;
+    }
     if (!(keySize == OWNER_PSK_LENGTH_128 || keySize == OWNER_PSK_LENGTH_256))
     {
-        OC_LOG(INFO, TAG, "OCProvisionPairwiseDevices : Invalid key size");
+        OIC_LOG(INFO, TAG, "OCProvisionPairwiseDevices : Invalid key size");
+        return OC_STACK_INVALID_PARAM;
+    }
+    if (0 == memcmp(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, sizeof(OicUuid_t)))
+    {
+        OIC_LOG(INFO, TAG, "OCProvisionPairwiseDevices : Same device ID");
         return OC_STACK_INVALID_PARAM;
     }
 
-    OC_LOG(DEBUG, TAG, "Checking link in DB");
+    OIC_LOG(DEBUG, TAG, "Checking link in DB");
     bool linkExists = true;
     OCStackResult res = PDMIsLinkExists(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, &linkExists);
     if(res != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "Internal Error Occured");
+        OIC_LOG(ERROR, TAG, "Internal Error Occured");
         return res;
     }
     if (linkExists)
     {
-        OC_LOG(ERROR, TAG, "Link already exists");
+        OIC_LOG(ERROR, TAG, "Link already exists");
         return OC_STACK_INVALID_PARAM;
     }
 
@@ -545,10 +617,10 @@ OCStackResult OCProvisionPairwiseDevices(void* ctx, OicSecCredType_t type, size_
     Linkdata_t *link = (Linkdata_t*) OICMalloc(sizeof(Linkdata_t));
     if (!link)
     {
-        OC_LOG(ERROR, TAG, "Failed to memory allocation");
+        OIC_LOG(ERROR, TAG, "Failed to memory allocation");
         return OC_STACK_NO_MEMORY;
     }
-    OC_LOG_V(INFO,TAG, "Maximum no od results %d",noOfResults);
+    OIC_LOG_V(INFO,TAG, "Maximum no od results %d",noOfResults);
 
     link->pDev1 = pDev1;
     link->pDev1Acl = pDev1Acl;
@@ -578,7 +650,7 @@ OCStackResult OCGetDevInfoFromNetwork(unsigned short waittime,
 {
     //TODO will be replaced by more efficient logic
     if (pOwnedDevList == NULL || *pOwnedDevList != NULL || pUnownedDevList == NULL
-         || *pUnownedDevList != NULL)
+         || *pUnownedDevList != NULL || 0 == waittime)
     {
         return OC_STACK_INVALID_PARAM;
     }
@@ -588,7 +660,7 @@ OCStackResult OCGetDevInfoFromNetwork(unsigned short waittime,
     OCStackResult res =  OCDiscoverUnownedDevices(waittime/2, &unownedDevice);
     if (OC_STACK_OK != res)
     {
-        OC_LOG(ERROR,TAG, "Error in unowned discovery");
+        OIC_LOG(ERROR,TAG, "Error in unowned discovery");
         return res;
     }
 
@@ -597,7 +669,7 @@ OCStackResult OCGetDevInfoFromNetwork(unsigned short waittime,
     res =  OCDiscoverOwnedDevices(waittime/2, &ownedDevice);
     if (OC_STACK_OK != res)
     {
-        OC_LOG(ERROR,TAG, "Error in owned discovery");
+        OIC_LOG(ERROR,TAG, "Error in owned discovery");
         PMDeleteDeviceList(unownedDevice);
         return res;
     }
@@ -608,7 +680,7 @@ OCStackResult OCGetDevInfoFromNetwork(unsigned short waittime,
     res =  PDMGetOwnedDevices(&uuidList, &numOfDevices);
     if (OC_STACK_OK != res)
     {
-        OC_LOG(ERROR, TAG, "Error while getting info from DB");
+        OIC_LOG(ERROR, TAG, "Error while getting info from DB");
         PMDeleteDeviceList(unownedDevice);
         PMDeleteDeviceList(ownedDevice);
         return res;
@@ -637,7 +709,7 @@ OCStackResult OCGetDevInfoFromNetwork(unsigned short waittime,
         OCProvisionDev_t *ptr = (OCProvisionDev_t *)OICCalloc(1, sizeof (OCProvisionDev_t));
         if (NULL == ptr)
         {
-            OC_LOG(ERROR,TAG,"Fail to allocate memory");
+            OIC_LOG(ERROR,TAG,"Fail to allocate memory");
             PMDeleteDeviceList(unownedDevice);
             PMDeleteDeviceList(ownedDevice);
             OCDeleteUuidList(uuidList);
@@ -647,7 +719,7 @@ OCStackResult OCGetDevInfoFromNetwork(unsigned short waittime,
         ptr->doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t));
         if (NULL == ptr->doxm)
         {
-            OC_LOG(ERROR,TAG,"Fail to allocate memory");
+            OIC_LOG(ERROR,TAG,"Fail to allocate memory");
             PMDeleteDeviceList(unownedDevice);
             PMDeleteDeviceList(ownedDevice);
             OCDeleteUuidList(uuidList);
@@ -689,6 +761,16 @@ void OCDeleteACLList(OicSecAcl_t* pAcl)
     DeleteACLList(pAcl);
 }
 
+/**
+ * This function deletes PDACL data.
+ *
+ * @param pPdAcl Pointer to OicSecPdAcl_t structure.
+ */
+void OCDeletePdAclList(OicSecPdAcl_t* pPdAcl)
+{
+    FreePdAclList(pPdAcl);
+}
+
 
 #ifdef __WITH_X509__
 /**
old mode 100755 (executable)
new mode 100644 (file)
index 6ac1ff0..7b22d46
@@ -58,6 +58,8 @@
 #include "srmutility.h"
 #include "provisioningdatabasemanager.h"
 #include "oxmrandompin.h"
+#include "ocpayload.h"
+#include "payload_logging.h"
 
 #define TAG "OTM"
 
 static OTMCallbackData_t g_OTMDatas[OIC_OXM_COUNT];
 
 /**
- * Variable for storing provisioning tool's provisioning capabilities
- * Must be in decreasing order of preference. More prefered method should
- * have lower array index.
+ * Variables for pointing the OTMContext to be used in the DTLS handshake result callback.
  */
-static OicSecDpom_t gProvisioningToolCapability[] = { SINGLE_SERVICE_CLIENT_DRIVEN };
-
-/**
- * Number of supported provisioning methods
- * current version supports only one.
- */
-static size_t gNumOfProvisioningMethodsPT = 1;
-
-/**
- * Function to getting string of ownership transfer method
- */
-static const char* GetOxmString(OicSecOxm_t oxmType)
-{
-    switch(oxmType)
-    {
-        case OIC_JUST_WORKS:
-            return OXM_JUST_WORKS;
-        case OIC_RANDOM_DEVICE_PIN:
-            return OXM_RANDOM_DEVICE_PIN;
-        case OIC_MANUFACTURER_CERTIFICATE:
-            return OXM_MANUFACTURER_CERTIFICATE;
-        default:
-            return NULL;
-    }
-}
+static OTMContext_t* g_otmCtx = NULL;
 
 /**
  * Function to select appropriate  provisioning method.
@@ -106,14 +82,13 @@ static const char* GetOxmString(OicSecOxm_t oxmType)
  * @return  OC_STACK_OK on success
  */
 static OCStackResult SelectProvisioningMethod(const OicSecOxm_t *supportedMethods,
-                                                            size_t numberOfMethods,
-                                                            OicSecOxm_t *selectedMethod)
+        size_t numberOfMethods, OicSecOxm_t *selectedMethod)
 {
-    OC_LOG(DEBUG, TAG, "IN SelectProvisioningMethod");
+    OIC_LOG(DEBUG, TAG, "IN SelectProvisioningMethod");
 
     if(numberOfMethods == 0 || !supportedMethods)
     {
-        OC_LOG(WARNING, TAG, "Could not find a supported OxM.");
+        OIC_LOG(WARNING, TAG, "Could not find a supported OxM.");
         return OC_STACK_ERROR;
     }
 
@@ -139,31 +114,23 @@ static OCStackResult SelectProvisioningMethod(const OicSecOxm_t *supportedMethod
 static void SelectOperationMode(const OCProvisionDev_t *selectedDeviceInfo,
                                 OicSecDpom_t *selectedMode)
 {
-    OC_LOG(DEBUG, TAG, "IN SelectOperationMode");
-
-    size_t i = 0;
-    size_t j = 0;
-
-    while (i < gNumOfProvisioningMethodsPT && j < selectedDeviceInfo->pstat->smLen)
-    {
-        if (gProvisioningToolCapability[i] < selectedDeviceInfo->pstat->sm[j])
-        {
-            i++;
-        }
-        else if (selectedDeviceInfo->pstat->sm[j] < gProvisioningToolCapability[i])
-        {
-            j++;
-        }
-        else /* if gProvisioningToolCapability[i] == deviceSupportedMethods[j] */
-        {
-            *selectedMode = gProvisioningToolCapability[j];
-            break;
-        }
-    }
-    OC_LOG(DEBUG, TAG, "OUT SelectOperationMode");
+    OIC_LOG(DEBUG, TAG, "IN SelectOperationMode");
+    *selectedMode = selectedDeviceInfo->pstat->sm[0];
+    OIC_LOG_V(DEBUG, TAG, "Selected Operation Mode = %d", *selectedMode);
 }
 
 /**
+ * Function to start ownership transfer.
+ * This function will send the first request for provisioning,
+ * The next request message is sent from the response handler for this request.
+ *
+ * @param[in] ctx   context value passed to callback from calling function.
+ * @param[in] selectedDevice   selected device information to performing provisioning.
+ * @return  OC_STACK_OK on success
+ */
+static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selectedDevice);
+
+/**
  * Function to update owner transfer mode
  *
  * @param[in]  otmCtx  Context value of ownership transfer.
@@ -181,45 +148,60 @@ static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx);
 
 
 /**
- * Function to send ownerShip info. This function would update Owned as true and
- * owner as UUID for provisioning tool
+ * Function to send  uuid of owner device to new device.
+ * This function would update 'owner of doxm' as UUID for provisioning tool.
  *
  * @param[in]  otmCtx  Context value of ownership transfer.
  * @return  OC_STACK_OK on success
  */
-static OCStackResult PutOwnershipInformation(OTMContext_t* otmCtx);
+static OCStackResult PutOwnerUuid(OTMContext_t* otmCtx);
 
 /**
  * Function to update the operation mode. As per the spec. Operation mode in client driven
  * single service provisioning it will be updated to 0x3
  *
  * @param[in]  otmCtx  Context value of ownership transfer.
+ * @return  OC_STACK_OK on success
+ */
+static OCStackResult PutUpdateOperationMode(OTMContext_t* otmCtx);
+
+/**
+ * Function to update the owner credential to new device
+ *
+ * @param[in]  otmCtx  Context value of ownership transfer.
  * @param[in] selectedOperationMode selected operation mode
  * @return  OC_STACK_OK on success
  */
-static OCStackResult PutUpdateOperationMode(OTMContext_t* otmCtx,
-                                    OicSecDpom_t selectedOperationMode);
+static OCStackResult PutOwnerCredential(OTMContext_t* otmCtx);
 
 /**
- * Function to start ownership transfer.
- * This function will send the first request for provisioning,
- * The next request message is sent from the response handler for this request.
+ * Function to send ownerShip info.
+ * This function would update 'owned of doxm' as true.
+ *
+ * @param[in]  otmCtx  Context value of ownership transfer.
+ * @return  OC_STACK_OK on success
+ */
+static OCStackResult PutOwnershipInformation(OTMContext_t* otmCtx);
+
+/**
+ * Function to update pstat as Ready for provisioning.
+ * This function would update 'cm' from bx0000,0010 to bx0000,0000.
  *
  * @param[in] ctx   context value passed to callback from calling function.
  * @param[in] selectedDevice   selected device information to performing provisioning.
  * @return  OC_STACK_OK on success
  */
-static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selectedDevice);
+static OCStackResult PutProvisioningStatus(OTMContext_t* otmCtx);
 
-/*
- * Function to finalize provisioning.
- * This function will send default ACL and commit hash.
+/**
+ * Function to update pstat as Ready for Normal Operation.
+ * This function would update 'isop' from false to true.
  *
- * @param[in] otmCtx   Context value of ownership transfer.
+ * @param[in] ctx   context value passed to callback from calling function.
+ * @param[in] selectedDevice   selected device information to performing provisioning.
  * @return  OC_STACK_OK on success
  */
-static OCStackResult FinalizeProvisioning(OTMContext_t* otmCtx);
-
+static OCStackResult PutNormalOperationStatus(OTMContext_t* otmCtx);
 
 static bool IsComplete(OTMContext_t* otmCtx)
 {
@@ -242,16 +224,27 @@ static bool IsComplete(OTMContext_t* otmCtx)
  */
 static void SetResult(OTMContext_t* otmCtx, const OCStackResult res)
 {
-    OC_LOG(DEBUG, TAG, "IN SetResult");
+    OIC_LOG_V(DEBUG, TAG, "IN SetResult : %d ", res);
 
     if(!otmCtx)
     {
-        OC_LOG(WARNING, TAG, "OTMContext is NULL");
+        OIC_LOG(WARNING, TAG, "OTMContext is NULL");
         return;
     }
 
     if(otmCtx->selectedDeviceInfo)
     {
+        //Revert psk_info callback and new deivce uuid in case of random PIN OxM
+        if(OIC_RANDOM_DEVICE_PIN == otmCtx->selectedDeviceInfo->doxm->oxmSel)
+        {
+            if(CA_STATUS_OK != CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials))
+            {
+                OIC_LOG(WARNING, TAG, "Failed to revert  is DTLS credential handler.");
+            }
+            OicUuid_t emptyUuid = { .id={0}};
+            SetUuidForRandomPinOxm(&emptyUuid);
+        }
+
         for(size_t i = 0; i < otmCtx->ctxResultArraySize; i++)
         {
             if(memcmp(otmCtx->selectedDeviceInfo->doxm->deviceID.id,
@@ -265,6 +258,8 @@ static void SetResult(OTMContext_t* otmCtx, const OCStackResult res)
             }
         }
 
+        g_otmCtx = NULL;
+
         //If all request is completed, invoke the user callback.
         if(IsComplete(otmCtx))
         {
@@ -278,14 +273,105 @@ static void SetResult(OTMContext_t* otmCtx, const OCStackResult res)
             if(OC_STACK_OK != StartOwnershipTransfer(otmCtx,
                                                      otmCtx->selectedDeviceInfo->next))
             {
-                OC_LOG(ERROR, TAG, "Failed to StartOwnershipTransfer");
+                OIC_LOG(ERROR, TAG, "Failed to StartOwnershipTransfer");
             }
         }
     }
 
-    OC_LOG(DEBUG, TAG, "OUT SetResult");
+    OIC_LOG(DEBUG, TAG, "OUT SetResult");
 }
 
+/**
+ * Function to handle the handshake result in OTM.
+ * This function will be invoked after DTLS handshake
+ * @param   endPoint  [IN] The remote endpoint.
+ * @param   errorInfo [IN] Error information from the endpoint.
+ * @return  NONE
+ */
+void DTLSHandshakeCB(const CAEndpoint_t *endpoint, const CAErrorInfo_t *info)
+{
+    if(NULL != g_otmCtx && NULL != g_otmCtx->selectedDeviceInfo &&
+       NULL != endpoint && NULL != info)
+    {
+        OIC_LOG_V(INFO, TAG, "Received status from remote device(%s:%d) : %d",
+                 endpoint->addr, endpoint->port, info->result);
+
+        OicSecDoxm_t* newDevDoxm = g_otmCtx->selectedDeviceInfo->doxm;
+
+        if(NULL != newDevDoxm)
+        {
+            OicUuid_t emptyUuid = {.id={0}};
+
+            //Make sure the address matches.
+            if(strncmp(g_otmCtx->selectedDeviceInfo->endpoint.addr,
+               endpoint->addr,
+               sizeof(endpoint->addr)) == 0 &&
+               g_otmCtx->selectedDeviceInfo->securePort == endpoint->port)
+            {
+                OCStackResult res = OC_STACK_ERROR;
+
+                //If temporal secure sesstion established successfully
+                if(CA_STATUS_OK == info->result &&
+                   false == newDevDoxm->owned &&
+                   memcmp(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t)) == 0)
+                {
+                    //Send request : PUT /oic/sec/doxm [{... , "devowner":"PT's UUID"}]
+                    res = PutOwnerUuid(g_otmCtx);
+                    if(OC_STACK_OK != res)
+                    {
+                        OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to send owner information");
+                        SetResult(g_otmCtx, res);
+                    }
+                }
+                //In case of authentication failure
+                else if(CA_DTLS_AUTHENTICATION_FAILURE == info->result)
+                {
+                    //in case of error from owner credential
+                    if(memcmp(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t)) != 0 &&
+                        true == newDevDoxm->owned)
+                    {
+                        OIC_LOG(ERROR, TAG, "The owner credential may incorrect.");
+
+                        if(OC_STACK_OK != RemoveCredential(&(newDevDoxm->deviceID)))
+                        {
+                            OIC_LOG(WARNING, TAG, "Failed to remove the invaild owner credential");
+                        }
+                        SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
+                    }
+                    //in case of error from wrong PIN, re-start the ownership transfer
+                    else if(OIC_RANDOM_DEVICE_PIN == newDevDoxm->oxmSel)
+                    {
+                        OIC_LOG(ERROR, TAG, "The PIN number may incorrect.");
+
+                        memcpy(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
+                        newDevDoxm->owned = false;
+                        g_otmCtx->attemptCnt++;
+
+                        if(WRONG_PIN_MAX_ATTEMP > g_otmCtx->attemptCnt)
+                        {
+                            res = StartOwnershipTransfer(g_otmCtx, g_otmCtx->selectedDeviceInfo);
+                            if(OC_STACK_OK != res)
+                            {
+                                SetResult(g_otmCtx, res);
+                                OIC_LOG(ERROR, TAG, "Failed to Re-StartOwnershipTransfer");
+                            }
+                        }
+                        else
+                        {
+                            OIC_LOG(ERROR, TAG, "User has exceeded the number of authentication attempts.");
+                            SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
+                        }
+                    }
+                    else
+                    {
+                        OIC_LOG(ERROR, TAG, "Failed to establish secure session.");
+                        SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
+                    }
+                }
+            }
+        }
+    }
+}
 
 /**
  * Function to save ownerPSK at provisioning tool end.
@@ -295,7 +381,7 @@ static void SetResult(OTMContext_t* otmCtx, const OCStackResult res)
  */
 static OCStackResult SaveOwnerPSK(OCProvisionDev_t *selectedDeviceInfo)
 {
-    OC_LOG(DEBUG, TAG, "IN SaveOwnerPSK");
+    OIC_LOG(DEBUG, TAG, "IN SaveOwnerPSK");
 
     OCStackResult res = OC_STACK_ERROR;
 
@@ -308,36 +394,29 @@ static OCStackResult SaveOwnerPSK(OCProvisionDev_t *selectedDeviceInfo)
     OicUuid_t ptDeviceID = {.id={0}};
     if (OC_STACK_OK != GetDoxmDeviceID(&ptDeviceID))
     {
-        OC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
+        OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
         return res;
     }
 
     uint8_t ownerPSK[OWNER_PSK_LENGTH_128] = {0};
+    OicSecKey_t ownerKey = {ownerPSK, OWNER_PSK_LENGTH_128};
 
     //Generating OwnerPSK
     CAResult_t pskRet = CAGenerateOwnerPSK(&endpoint,
             (uint8_t *)GetOxmString(selectedDeviceInfo->doxm->oxmSel),
-            strlen(GetOxmString(selectedDeviceInfo->doxm->oxmSel)), ptDeviceID.id,
-            sizeof(ptDeviceID.id), selectedDeviceInfo->doxm->deviceID.id,
-            sizeof(selectedDeviceInfo->doxm->deviceID.id), ownerPSK,
-            OWNER_PSK_LENGTH_128);
+            strlen(GetOxmString(selectedDeviceInfo->doxm->oxmSel)),
+            ptDeviceID.id, sizeof(ptDeviceID.id),
+            selectedDeviceInfo->doxm->deviceID.id, sizeof(selectedDeviceInfo->doxm->deviceID.id),
+            ownerPSK, OWNER_PSK_LENGTH_128);
 
     if (CA_STATUS_OK == pskRet)
     {
-        OC_LOG(INFO, TAG,"ownerPSK dump:\n");
-        OC_LOG_BUFFER(INFO, TAG,ownerPSK, OWNER_PSK_LENGTH_128);
+        OIC_LOG(INFO, TAG,"ownerPSK dump:\n");
+        OIC_LOG_BUFFER(INFO, TAG,ownerPSK, OWNER_PSK_LENGTH_128);
         //Generating new credential for provisioning tool
-        size_t ownLen = 1;
-        uint32_t outLen = 0;
-
-        char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(ownerPSK)) + 1] = {};
-        B64Result b64Ret = b64Encode(ownerPSK, sizeof(ownerPSK), base64Buff, sizeof(base64Buff),
-                &outLen);
-        VERIFY_SUCCESS(TAG, B64_OK == b64Ret, ERROR);
-
         OicSecCred_t *cred = GenerateCredential(&selectedDeviceInfo->doxm->deviceID,
                 SYMMETRIC_PAIR_WISE_KEY, NULL,
-                base64Buff, ownLen, &ptDeviceID);
+                &ownerKey, &ptDeviceID);
         VERIFY_NON_NULL(TAG, cred, ERROR);
 
         res = AddCredential(cred);
@@ -349,10 +428,10 @@ static OCStackResult SaveOwnerPSK(OCProvisionDev_t *selectedDeviceInfo)
     }
     else
     {
-        OC_LOG(ERROR, TAG, "CAGenerateOwnerPSK failed");
+        OIC_LOG(ERROR, TAG, "CAGenerateOwnerPSK failed");
     }
 
-    OC_LOG(DEBUG, TAG, "OUT SaveOwnerPSK");
+    OIC_LOG(DEBUG, TAG, "OUT SaveOwnerPSK");
 exit:
     return res;
 }
@@ -369,7 +448,7 @@ exit:
 static OCStackApplicationResult OwnerTransferModeHandler(void *ctx, OCDoHandle UNUSED,
                                                          OCClientResponse *clientResponse)
 {
-    OC_LOG(DEBUG, TAG, "IN OwnerTransferModeHandler");
+    OIC_LOG(DEBUG, TAG, "IN OwnerTransferModeHandler");
 
     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
     VERIFY_NON_NULL(TAG, ctx, WARNING);
@@ -378,23 +457,23 @@ static OCStackApplicationResult OwnerTransferModeHandler(void *ctx, OCDoHandle U
     (void)UNUSED;
     if(clientResponse->result == OC_STACK_OK)
     {
-        OC_LOG(INFO, TAG, "OwnerTransferModeHandler : response result = OC_STACK_OK");
+        OIC_LOG(INFO, TAG, "OwnerTransferModeHandler : response result = OC_STACK_OK");
         //Send request : GET /oic/sec/pstat
         OCStackResult res = GetProvisioningStatusResource(otmCtx);
         if(OC_STACK_OK != res)
         {
-            OC_LOG(WARNING, TAG, "Failed to get pstat information");
+            OIC_LOG(WARNING, TAG, "Failed to get pstat information");
             SetResult(otmCtx, res);
         }
     }
     else
     {
-        OC_LOG_V(WARNING, TAG, "OwnerTransferModeHandler : Client response is incorrect : %d",
+        OIC_LOG_V(WARNING, TAG, "OwnerTransferModeHandler : Client response is incorrect : %d",
         clientResponse->result);
         SetResult(otmCtx, clientResponse->result);
     }
 
-    OC_LOG(DEBUG, TAG, "OUT OwnerTransferModeHandler");
+    OIC_LOG(DEBUG, TAG, "OUT OwnerTransferModeHandler");
 
 exit:
     return  OC_STACK_DELETE_TRANSACTION;
@@ -412,7 +491,7 @@ exit:
 static OCStackApplicationResult ListMethodsHandler(void *ctx, OCDoHandle UNUSED,
                                                     OCClientResponse *clientResponse)
 {
-    OC_LOG(DEBUG, TAG, "IN ListMethodsHandler");
+    OIC_LOG(DEBUG, TAG, "IN ListMethodsHandler");
 
     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
     VERIFY_NON_NULL(TAG, ctx, WARNING);
@@ -423,54 +502,61 @@ static OCStackApplicationResult ListMethodsHandler(void *ctx, OCDoHandle UNUSED,
     {
         if  (NULL == clientResponse->payload)
         {
-            OC_LOG(INFO, TAG, "Skiping Null payload");
+            OIC_LOG(INFO, TAG, "Skiping Null payload");
             SetResult(otmCtx, OC_STACK_ERROR);
             return OC_STACK_DELETE_TRANSACTION;
         }
 
         if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
         {
-            OC_LOG(INFO, TAG, "Unknown payload type");
+            OIC_LOG(INFO, TAG, "Unknown payload type");
             SetResult(otmCtx, OC_STACK_ERROR);
             return OC_STACK_DELETE_TRANSACTION;
         }
-
-        OicSecPstat_t* pstat = JSONToPstatBin(
-                ((OCSecurityPayload*)clientResponse->payload)->securityData);
-        if(NULL == pstat)
+        OicSecPstat_t* pstat = NULL;
+        OCStackResult result = CBORPayloadToPstat(
+                ((OCSecurityPayload*)clientResponse->payload)->securityData,
+                ((OCSecurityPayload*)clientResponse->payload)->payloadSize,
+                &pstat);
+        if(NULL == pstat || result != OC_STACK_OK)
+        {
+            OIC_LOG(ERROR, TAG, "Error while converting cbor to pstat.");
+            SetResult(otmCtx, OC_STACK_ERROR);
+            return OC_STACK_DELETE_TRANSACTION;
+        }
+        if(false == (TAKE_OWNER & pstat->cm))
         {
-            OC_LOG(ERROR, TAG, "Error while converting json to pstat bin");
+            OIC_LOG(ERROR, TAG, "Device pairing mode enabling owner transfer operations is disabled");
             SetResult(otmCtx, OC_STACK_ERROR);
             return OC_STACK_DELETE_TRANSACTION;
         }
         otmCtx->selectedDeviceInfo->pstat = pstat;
 
         //Select operation mode (Currently supported SINGLE_SERVICE_CLIENT_DRIVEN only)
-        OicSecDpom_t selectedOperationMode;
-        SelectOperationMode(otmCtx->selectedDeviceInfo, &selectedOperationMode);
+        SelectOperationMode(otmCtx->selectedDeviceInfo, &(otmCtx->selectedDeviceInfo->pstat->om));
 
-        //Send request : PUT /oic/sec/pstat [{"OM":"0x11", .. }]
-        OCStackResult res = PutUpdateOperationMode(otmCtx, selectedOperationMode);
+        //Send request : PUT /oic/sec/pstat [{"om":"bx11", .. }]
+        OCStackResult res = PutUpdateOperationMode(otmCtx);
         if (OC_STACK_OK != res)
         {
-            OC_LOG(ERROR, TAG, "Error while updating operation mode.");
+            OIC_LOG(ERROR, TAG, "Error while updating operation mode.");
             SetResult(otmCtx, res);
         }
     }
     else
     {
-        OC_LOG_V(WARNING, TAG, "ListMethodsHandler : Client response is incorrect : %d",
+        OIC_LOG_V(WARNING, TAG, "ListMethodsHandler : Client response is incorrect : %d",
             clientResponse->result);
         SetResult(otmCtx, clientResponse->result);
     }
 
-    OC_LOG(DEBUG, TAG, "OUT ListMethodsHandler");
+    OIC_LOG(DEBUG, TAG, "OUT ListMethodsHandler");
 exit:
     return  OC_STACK_DELETE_TRANSACTION;
 }
 
 /**
- * Callback handler for OwnershipInformationHandler API.
+ * Response handler for update owner uuid request.
  *
  * @param[in] ctx             ctx value passed to callback from calling function.
  * @param[in] UNUSED          handle to an invocation
@@ -478,73 +564,48 @@ exit:
  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
  */
-static OCStackApplicationResult OwnershipInformationHandler(void *ctx, OCDoHandle UNUSED,
+static OCStackApplicationResult OwnerUuidUpdateHandler(void *ctx, OCDoHandle UNUSED,
                                 OCClientResponse *clientResponse)
 {
     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
     VERIFY_NON_NULL(TAG, ctx, WARNING);
 
-    OC_LOG(DEBUG, TAG, "IN OwnershipInformationHandler");
+    OIC_LOG(DEBUG, TAG, "IN OwnerUuidUpdateHandler");
     (void)UNUSED;
     OCStackResult res = OC_STACK_OK;
     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
-    if  (OC_STACK_OK == clientResponse->result)
+
+    if(OC_STACK_OK == clientResponse->result)
     {
-        if(OIC_RANDOM_DEVICE_PIN == otmCtx->selectedDeviceInfo->doxm->oxmSel)
+        if(otmCtx && otmCtx->selectedDeviceInfo)
         {
-            res = RemoveCredential(&otmCtx->subIdForPinOxm);
-            if(OC_STACK_RESOURCE_DELETED != res)
+            res = SaveOwnerPSK(otmCtx->selectedDeviceInfo);
+            if(OC_STACK_OK != res)
             {
-                OC_LOG_V(ERROR, TAG, "Failed to remove temporal PSK : %d", res);
+                OIC_LOG(ERROR, TAG, "OwnerUuidUpdateHandler:Failed to owner PSK generation");
+                SetResult(otmCtx, res);
                 return OC_STACK_DELETE_TRANSACTION;
             }
-        }
 
-        res = SaveOwnerPSK(otmCtx->selectedDeviceInfo);
-        if(OC_STACK_OK != res)
-        {
-            OC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to owner PSK generation");
-            SetResult(otmCtx, res);
-            return OC_STACK_DELETE_TRANSACTION;
-        }
-
-        CAEndpoint_t* endpoint = (CAEndpoint_t *)&otmCtx->selectedDeviceInfo->endpoint;
-        endpoint->port = otmCtx->selectedDeviceInfo->securePort;
-        CAResult_t caResult = CACloseDtlsSession(endpoint);
-        if(CA_STATUS_OK != caResult)
-        {
-            OC_LOG(ERROR, TAG, "Failed to close DTLS session");
-            SetResult(otmCtx, caResult);
-            return OC_STACK_DELETE_TRANSACTION;
-        }
-
-        /**
-         * If we select NULL cipher,
-         * client will select appropriate cipher suite according to server's cipher-suite list.
-         */
-        caResult = CASelectCipherSuite(TLS_NULL_WITH_NULL_NULL);
-        if(CA_STATUS_OK != caResult)
-        {
-            OC_LOG(ERROR, TAG, "Failed to select TLS_NULL_WITH_NULL_NULL");
-            SetResult(otmCtx, caResult);
-            return OC_STACK_DELETE_TRANSACTION;
-        }
-
-        OC_LOG(INFO, TAG, "Ownership transfer was successfully completed.");
-        OC_LOG(INFO, TAG, "Start defualt ACL & commit-hash provisioning.");
-
-        res = FinalizeProvisioning(otmCtx);
-        if(OC_STACK_OK != res)
-        {
-            SetResult(otmCtx, res);
+            //PUT owner credential to new device according to security spec B.
+            res = PutOwnerCredential(otmCtx);
+            if(OC_STACK_OK != res)
+            {
+                OIC_LOG(ERROR, TAG,
+                        "OwnerUuidUpdateHandler:Failed to send PUT request for onwer credential");
+                SetResult(otmCtx, res);
+                return OC_STACK_DELETE_TRANSACTION;
+            }
         }
     }
     else
     {
         res = clientResponse->result;
+        OIC_LOG_V(ERROR, TAG, "OwnerUuidHandler : Unexpected result %d", res);
+        SetResult(otmCtx, res);
     }
 
-    OC_LOG(DEBUG, TAG, "OUT OwnershipInformationHandler");
+    OIC_LOG(DEBUG, TAG, "OUT OwnerUuidUpdateHandler");
 
 exit:
     return  OC_STACK_DELETE_TRANSACTION;
@@ -562,7 +623,7 @@ exit:
 static OCStackApplicationResult OperationModeUpdateHandler(void *ctx, OCDoHandle UNUSED,
                                 OCClientResponse *clientResponse)
 {
-    OC_LOG(DEBUG, TAG, "IN OperationModeUpdateHandler");
+    OIC_LOG(DEBUG, TAG, "IN OperationModeUpdateHandler");
 
     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
     VERIFY_NON_NULL(TAG, ctx, WARNING);
@@ -580,52 +641,365 @@ static OCStackApplicationResult OperationModeUpdateHandler(void *ctx, OCDoHandle
             res = g_OTMDatas[selOxm].loadSecretCB(otmCtx);
             if(OC_STACK_OK != res)
             {
-                OC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to load secret");
+                OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to load secret");
                 SetResult(otmCtx, res);
                 return  OC_STACK_DELETE_TRANSACTION;
             }
         }
 
+        //It will be used in handshake event handler
+        g_otmCtx = otmCtx;
+
         //Try DTLS handshake to generate secure session
         if(g_OTMDatas[selOxm].createSecureSessionCB)
         {
             res = g_OTMDatas[selOxm].createSecureSessionCB(otmCtx);
             if(OC_STACK_OK != res)
             {
-                OC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to create DTLS session");
+                OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to create DTLS session");
+                SetResult(otmCtx, res);
+                return OC_STACK_DELETE_TRANSACTION;
+            }
+        }
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "Error while update operation mode");
+        SetResult(otmCtx, clientResponse->result);
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT OperationModeUpdateHandler");
+
+exit:
+    return  OC_STACK_DELETE_TRANSACTION;
+}
+
+/**
+ * Response handler for update owner crendetial request.
+ *
+ * @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 OwnerCredentialHandler(void *ctx, OCDoHandle UNUSED,
+                                OCClientResponse *clientResponse)
+{
+    VERIFY_NON_NULL(TAG, clientResponse, WARNING);
+    VERIFY_NON_NULL(TAG, ctx, WARNING);
+
+    OIC_LOG(DEBUG, TAG, "IN OwnerCredentialHandler");
+    (void)UNUSED;
+    OCStackResult res = OC_STACK_OK;
+    OTMContext_t* otmCtx = (OTMContext_t*)ctx;
+
+    if(OC_STACK_RESOURCE_CREATED == clientResponse->result)
+    {
+        if(otmCtx && otmCtx->selectedDeviceInfo)
+        {
+            //Close the temporal secure session to verify the owner credential
+            CAEndpoint_t* endpoint = (CAEndpoint_t *)&otmCtx->selectedDeviceInfo->endpoint;
+            endpoint->port = otmCtx->selectedDeviceInfo->securePort;
+            CAResult_t caResult = CACloseDtlsSession(endpoint);
+            if(CA_STATUS_OK != caResult)
+            {
+                OIC_LOG(ERROR, TAG, "Failed to close DTLS session");
+                SetResult(otmCtx, caResult);
+                return OC_STACK_DELETE_TRANSACTION;
+            }
+
+            /**
+             * If we select NULL cipher,
+             * client will select appropriate cipher suite according to server's cipher-suite list.
+             */
+            caResult = CASelectCipherSuite(TLS_NULL_WITH_NULL_NULL);
+            if(CA_STATUS_OK != caResult)
+            {
+                OIC_LOG(ERROR, TAG, "Failed to select TLS_NULL_WITH_NULL_NULL");
+                SetResult(otmCtx, caResult);
+                return OC_STACK_DELETE_TRANSACTION;
+            }
+
+            /**
+             * in case of random PIN based OxM,
+             * revert get_psk_info callback of tinyDTLS to use owner credential.
+             */
+            if(OIC_RANDOM_DEVICE_PIN == otmCtx->selectedDeviceInfo->doxm->oxmSel)
+            {
+                OicUuid_t emptyUuid = { .id={0}};
+                SetUuidForRandomPinOxm(&emptyUuid);
+
+                if(CA_STATUS_OK != CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials))
+                {
+                    OIC_LOG(ERROR, TAG, "Failed to revert DTLS credential handler.");
+                    SetResult(otmCtx, OC_STACK_INVALID_CALLBACK);
+                    return OC_STACK_DELETE_TRANSACTION;
+                }
+            }
+
+            //PUT /oic/sec/doxm [{ ..., "owned":"TRUE" }]
+            res = PutOwnershipInformation(otmCtx);
+            if(OC_STACK_OK != res)
+            {
+                OIC_LOG(ERROR, TAG, "Failed to put ownership information to new device");
                 SetResult(otmCtx, res);
                 return OC_STACK_DELETE_TRANSACTION;
             }
         }
+    }
+    else
+    {
+        res = clientResponse->result;
+        OIC_LOG_V(ERROR, TAG, "OwnerCredentialHandler : Unexpected result %d", res);
+        SetResult(otmCtx, res);
+    }
 
-        //Send request : PUT /oic/sec/doxm [{"Owned":"True", .. , "Owner":"PT's UUID"}]
-        res = PutOwnershipInformation(otmCtx);
-        if(OC_STACK_OK != res)
+    OIC_LOG(DEBUG, TAG, "OUT OwnerCredentialHandler");
+
+exit:
+    return  OC_STACK_DELETE_TRANSACTION;
+}
+
+
+/**
+ * Response handler for update owner information request.
+ *
+ * @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 OwnershipInformationHandler(void *ctx, OCDoHandle UNUSED,
+                                OCClientResponse *clientResponse)
+{
+    VERIFY_NON_NULL(TAG, clientResponse, WARNING);
+    VERIFY_NON_NULL(TAG, ctx, WARNING);
+
+    OIC_LOG(DEBUG, TAG, "IN OwnershipInformationHandler");
+    (void)UNUSED;
+    OCStackResult res = OC_STACK_OK;
+    OTMContext_t* otmCtx = (OTMContext_t*)ctx;
+
+    if(OC_STACK_OK == clientResponse->result)
+    {
+        if(otmCtx && otmCtx->selectedDeviceInfo)
         {
-            OC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to send owner information");
-            SetResult(otmCtx, res);
+            OIC_LOG(INFO, TAG, "Ownership transfer was successfully completed.");
+            OIC_LOG(INFO, TAG, "Set Ready for provisioning state .");
+
+            res = PutProvisioningStatus(otmCtx);
+            if(OC_STACK_OK != res)
+            {
+                OIC_LOG(ERROR, TAG, "Failed to update pstat");
+                SetResult(otmCtx, res);
+            }
         }
     }
     else
     {
-        OC_LOG(ERROR, TAG, "Error while update operation mode");
-        SetResult(otmCtx, clientResponse->result);
+        res = clientResponse->result;
+        OIC_LOG_V(ERROR, TAG, "OwnershipInformationHandler : Unexpected result %d", res);
+        SetResult(otmCtx, res);
     }
 
-    OC_LOG(DEBUG, TAG, "OUT OperationModeUpdateHandler");
+    OIC_LOG(DEBUG, TAG, "OUT OwnershipInformationHandler");
 
 exit:
     return  OC_STACK_DELETE_TRANSACTION;
 }
 
+/**
+ * Response handler of update provisioning status.
+ *
+ * @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 ProvisioningStatusHandler(void *ctx, OCDoHandle UNUSED,
+                                                       OCClientResponse *clientResponse)
+{
+    OIC_LOG_V(INFO, TAG, "IN ProvisioningStatusHandler.");
+
+    VERIFY_NON_NULL(TAG, clientResponse, ERROR);
+    VERIFY_NON_NULL(TAG, ctx, ERROR);
+
+    OTMContext_t* otmCtx = (OTMContext_t*) ctx;
+    (void)UNUSED;
+    OCStackResult res = OC_STACK_OK;
+
+    if(OC_STACK_OK == clientResponse->result)
+    {
+        if(otmCtx && otmCtx->selectedDeviceInfo)
+        {
+            OIC_LOG(INFO, TAG, "Device state is in Ready for Provisionig.");
+
+            res = PutNormalOperationStatus(otmCtx);
+            if(OC_STACK_OK != res)
+            {
+                OIC_LOG(ERROR, TAG, "Failed to update pstat");
+                SetResult(otmCtx, res);
+            }
+        }
+    }
+    else
+    {
+        OIC_LOG_V(INFO, TAG, "Error occured in provisionDefaultACLCB :: %d\n",
+                            clientResponse->result);
+        SetResult(otmCtx, clientResponse->result);
+    }
+
+exit:
+    OIC_LOG_V(INFO, TAG, "OUT ProvisioningStatusHandler.");
+    return OC_STACK_DELETE_TRANSACTION;
+}
+
+/**
+ * Response handler of update provisioning status to Ready for Normal..
+ *
+ * @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 ReadyForNomalStatusHandler(void *ctx, OCDoHandle UNUSED,
+                                                       OCClientResponse *clientResponse)
+{
+    OIC_LOG_V(INFO, TAG, "IN ReadyForNomalStatusHandler.");
+
+    VERIFY_NON_NULL(TAG, clientResponse, ERROR);
+    VERIFY_NON_NULL(TAG, ctx, ERROR);
+
+    OTMContext_t* otmCtx = (OTMContext_t*) ctx;
+    (void)UNUSED;
+
+    if (OC_STACK_OK == clientResponse->result)
+    {
+        OIC_LOG(INFO, TAG, "Device state is in Ready for Normal Operation.");
+        OCStackResult res = PDMAddDevice(&otmCtx->selectedDeviceInfo->doxm->deviceID);
+         if (OC_STACK_OK == res)
+         {
+                OIC_LOG_V(INFO, TAG, "Add device's UUID in PDM_DB");
+                SetResult(otmCtx, OC_STACK_OK);
+                return OC_STACK_DELETE_TRANSACTION;
+         }
+          else
+         {
+              OIC_LOG(ERROR, TAG, "Ownership transfer is complete but adding information to DB is failed.");
+         }
+    }
+    else
+    {
+        OIC_LOG_V(INFO, TAG, "Error occured in provisionDefaultACLCB :: %d\n",
+                            clientResponse->result);
+        SetResult(otmCtx, clientResponse->result);
+    }
+
+exit:
+    OIC_LOG_V(INFO, TAG, "OUT ReadyForNomalStatusHandler.");
+    return OC_STACK_DELETE_TRANSACTION;
+}
+
+static OCStackResult PutOwnerCredential(OTMContext_t* otmCtx)
+{
+    OIC_LOG(DEBUG, TAG, "IN PutOwnerCredential");
+
+    if(!otmCtx || !otmCtx->selectedDeviceInfo)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid parameters");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
+    char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
+
+    if(!PMGenerateQuery(true,
+                        deviceInfo->endpoint.addr, deviceInfo->securePort,
+                        deviceInfo->connType,
+                        query, sizeof(query), OIC_RSRC_CRED_URI))
+    {
+        OIC_LOG(ERROR, TAG, "PutOwnerCredential : Failed to generate query");
+        return OC_STACK_ERROR;
+    }
+    OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
+    OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
+    if(!secPayload)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to memory allocation");
+        return OC_STACK_NO_MEMORY;
+    }
+
+    //Generate owner credential for new device
+    secPayload->base.type = PAYLOAD_TYPE_SECURITY;
+    const OicSecCred_t* ownerCredential = GetCredResourceData(&(deviceInfo->doxm->deviceID));
+    if(!ownerCredential)
+    {
+        OIC_LOG(ERROR, TAG, "Can not find OwnerPSK.");
+        return OC_STACK_NO_RESOURCE;
+    }
+
+    OicUuid_t credSubjectId = {.id={0}};
+    if(OC_STACK_OK == GetDoxmDeviceID(&credSubjectId))
+    {
+        OicSecCred_t newCredential;
+        memcpy(&newCredential, ownerCredential, sizeof(OicSecCred_t));
+        newCredential.next = NULL;
+
+        //Set subject ID as PT's ID
+        memcpy(&(newCredential.subject), &credSubjectId, sizeof(OicUuid_t));
+
+        //Fill private data as empty string
+        newCredential.privateData.data = NULL;
+        newCredential.privateData.len = 0;
+#ifdef __WITH_X509__
+        newCredential.publicData.data = NULL;
+        newCredential.publicData.len = 0;
+#endif
+
+        //Send owner credential to new device : PUT /oic/sec/cred [ owner credential ]
+        if (OC_STACK_OK != CredToCBORPayload(&newCredential, &secPayload->securityData, &secPayload->payloadSize))
+        {
+            OICFree(secPayload);
+            OIC_LOG(ERROR, TAG, "Error while converting bin to cbor.");
+            return OC_STACK_ERROR;
+        }
+        OIC_LOG(DEBUG, TAG, "Cred Payload:");
+        OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
+
+        OCCallbackData cbData;
+        cbData.cb = &OwnerCredentialHandler;
+        cbData.context = (void *)otmCtx;
+        cbData.cd = NULL;
+        OCStackResult res = OCDoResource(NULL, OC_REST_PUT, query,
+                                         &deviceInfo->endpoint, (OCPayload*)secPayload,
+                                         deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
+        if (res != OC_STACK_OK)
+        {
+            OIC_LOG(ERROR, TAG, "OCStack resource error");
+        }
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "Failed to read DOXM device ID.");
+        return OC_STACK_NO_RESOURCE;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT PutOwnerCredential");
+
+    return OC_STACK_OK;
+}
 
 static OCStackResult PutOwnerTransferModeToResource(OTMContext_t* otmCtx)
 {
-    OC_LOG(DEBUG, TAG, "IN PutOwnerTransferModeToResource");
+    OIC_LOG(DEBUG, TAG, "IN PutOwnerTransferModeToResource");
 
     if(!otmCtx || !otmCtx->selectedDeviceInfo)
     {
-        OC_LOG(ERROR, TAG, "Invalid parameters");
+        OIC_LOG(ERROR, TAG, "Invalid parameters");
         return OC_STACK_INVALID_PARAM;
     }
 
@@ -638,50 +1012,50 @@ static OCStackResult PutOwnerTransferModeToResource(OTMContext_t* otmCtx)
                         deviceInfo->connType,
                         query, sizeof(query), OIC_RSRC_DOXM_URI))
     {
-        OC_LOG(ERROR, TAG, "PutOwnerTransferModeToResource : Failed to generate query");
+        OIC_LOG(ERROR, TAG, "PutOwnerTransferModeToResource : Failed to generate query");
         return OC_STACK_ERROR;
     }
-    OC_LOG_V(DEBUG, TAG, "Query=%s", query);
+    OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
     if(!secPayload)
     {
-        OC_LOG(ERROR, TAG, "Failed to memory allocation");
+        OIC_LOG(ERROR, TAG, "Failed to memory allocation");
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    secPayload->securityData = g_OTMDatas[selectedOxm].createSelectOxmPayloadCB(otmCtx);
-    if (NULL == secPayload->securityData)
+    OCStackResult res = g_OTMDatas[selectedOxm].createSelectOxmPayloadCB(otmCtx,
+            &secPayload->securityData, &secPayload->payloadSize);
+    if (OC_STACK_OK != res && NULL == secPayload->securityData)
     {
-        OICFree(secPayload);
-        OC_LOG(ERROR, TAG, "Error while converting bin to json");
+        OCPayloadDestroy((OCPayload *)secPayload);
+        OIC_LOG(ERROR, TAG, "Error while converting bin to cbor");
         return OC_STACK_ERROR;
     }
-    OC_LOG_V(DEBUG, TAG, "Payload : %s", secPayload->securityData);
 
     OCCallbackData cbData;
     cbData.cb = &OwnerTransferModeHandler;
     cbData.context = (void *)otmCtx;
     cbData.cd = NULL;
-    OCStackResult res = OCDoResource(NULL, OC_REST_PUT, query,
-                                     &deviceInfo->endpoint, (OCPayload*)secPayload,
-                                     deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
+    res = OCDoResource(NULL, OC_REST_PUT, query,
+                       &deviceInfo->endpoint, (OCPayload *)secPayload,
+                       deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
     if (res != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack resource error");
+        OIC_LOG(ERROR, TAG, "OCStack resource error");
     }
 
-    OC_LOG(DEBUG, TAG, "OUT PutOwnerTransferModeToResource");
+    OIC_LOG(DEBUG, TAG, "OUT PutOwnerTransferModeToResource");
 
     return res;
 }
 
 static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx)
 {
-    OC_LOG(DEBUG, TAG, "IN GetProvisioningStatusResource");
+    OIC_LOG(DEBUG, TAG, "IN GetProvisioningStatusResource");
 
     if(!otmCtx || !otmCtx->selectedDeviceInfo)
     {
-        OC_LOG(ERROR, TAG, "Invailed parameters");
+        OIC_LOG(ERROR, TAG, "Invailed parameters");
         return OC_STACK_INVALID_PARAM;
     }
 
@@ -692,10 +1066,10 @@ static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx)
                         deviceInfo->connType,
                         query, sizeof(query), OIC_RSRC_PSTAT_URI))
     {
-        OC_LOG(ERROR, TAG, "GetProvisioningStatusResource : Failed to generate query");
+        OIC_LOG(ERROR, TAG, "GetProvisioningStatusResource : Failed to generate query");
         return OC_STACK_ERROR;
     }
-    OC_LOG_V(DEBUG, TAG, "Query=%s", query);
+    OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
 
     OCCallbackData cbData;
     cbData.cb = &ListMethodsHandler;
@@ -705,22 +1079,78 @@ static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx)
                                      deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
     if (res != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack resource error");
+        OIC_LOG(ERROR, TAG, "OCStack resource error");
     }
 
-    OC_LOG(DEBUG, TAG, "OUT GetProvisioningStatusResource");
+    OIC_LOG(DEBUG, TAG, "OUT GetProvisioningStatusResource");
 
     return res;
 }
 
+static OCStackResult PutOwnerUuid(OTMContext_t* otmCtx)
+{
+    OIC_LOG(DEBUG, TAG, "IN PutOwnerUuid");
+
+    if(!otmCtx || !otmCtx->selectedDeviceInfo)
+    {
+        OIC_LOG(ERROR, TAG, "Invailed parameters");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
+    char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
+    if(!PMGenerateQuery(true,
+                        deviceInfo->endpoint.addr, deviceInfo->securePort,
+                        deviceInfo->connType,
+                        query, sizeof(query), OIC_RSRC_DOXM_URI))
+    {
+        OIC_LOG(ERROR, TAG, "PutOwnershipInformation : Failed to generate query");
+        return OC_STACK_ERROR;
+    }
+    OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
+
+    //PUT PT's uuid to new device
+    OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
+    if(!secPayload)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to memory allocation");
+        return OC_STACK_NO_MEMORY;
+    }
+    secPayload->base.type = PAYLOAD_TYPE_SECURITY;
+    OCStackResult res =  g_OTMDatas[deviceInfo->doxm->oxmSel].createOwnerTransferPayloadCB(
+            otmCtx, &secPayload->securityData, &secPayload->payloadSize);
+    if (OC_STACK_OK != res && NULL == secPayload->securityData)
+    {
+        OCPayloadDestroy((OCPayload *)secPayload);
+        OIC_LOG(ERROR, TAG, "Error while converting doxm bin to cbor.");
+        return OC_STACK_INVALID_PARAM;
+    }
+    OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
+
+    OCCallbackData cbData;
+    cbData.cb = &OwnerUuidUpdateHandler;
+    cbData.context = (void *)otmCtx;
+    cbData.cd = NULL;
+
+    res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload *)secPayload,
+            deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
+    if (res != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, TAG, "OCStack resource error");
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT PutOwnerUuid");
+
+    return res;
+}
 
 static OCStackResult PutOwnershipInformation(OTMContext_t* otmCtx)
 {
-    OC_LOG(DEBUG, TAG, "IN PutOwnershipInformation");
+    OIC_LOG(DEBUG, TAG, "IN PutOwnershipInformation");
 
     if(!otmCtx || !otmCtx->selectedDeviceInfo)
     {
-        OC_LOG(ERROR, TAG, "Invailed parameters");
+        OIC_LOG(ERROR, TAG, "Invailed parameters");
         return OC_STACK_INVALID_PARAM;
     }
 
@@ -731,25 +1161,28 @@ static OCStackResult PutOwnershipInformation(OTMContext_t* otmCtx)
                         deviceInfo->connType,
                         query, sizeof(query), OIC_RSRC_DOXM_URI))
     {
-        OC_LOG(ERROR, TAG, "PutOwnershipInformation : Failed to generate query");
+        OIC_LOG(ERROR, TAG, "PutOwnershipInformation : Failed to generate query");
         return OC_STACK_ERROR;
     }
-    OC_LOG_V(DEBUG, TAG, "Query=%s", query);
+    OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
 
     //OwnershipInformationHandler
-    OicSecOxm_t selOxm = deviceInfo->doxm->oxmSel;
-    OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
-    if(!secPayload)
+    OCSecurityPayload *secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
+    if (!secPayload)
     {
-        OC_LOG(ERROR, TAG, "Failed to memory allocation");
+        OIC_LOG(ERROR, TAG, "Failed to memory allocation");
         return OC_STACK_NO_MEMORY;
     }
+
+    otmCtx->selectedDeviceInfo->doxm->owned = true;
+
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    secPayload->securityData = g_OTMDatas[selOxm].createOwnerTransferPayloadCB(otmCtx);
-    if (NULL == secPayload->securityData)
+    OCStackResult res = DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm,
+            &secPayload->securityData, &secPayload->payloadSize);
+    if (OC_STACK_OK != res && NULL == secPayload->securityData)
     {
-        OICFree(secPayload);
-        OC_LOG(ERROR, TAG, "Error while converting doxm bin to json");
+        OCPayloadDestroy((OCPayload *)secPayload);
+        OIC_LOG(ERROR, TAG, "Error while converting doxm bin to json");
         return OC_STACK_INVALID_PARAM;
     }
 
@@ -757,22 +1190,22 @@ static OCStackResult PutOwnershipInformation(OTMContext_t* otmCtx)
     cbData.cb = &OwnershipInformationHandler;
     cbData.context = (void *)otmCtx;
     cbData.cd = NULL;
-    OCStackResult res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
-                                     deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
+
+    res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
+                       deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
     if (res != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack resource error");
+        OIC_LOG(ERROR, TAG, "OCStack resource error");
     }
 
-    OC_LOG(DEBUG, TAG, "OUT PutOwnershipInformation");
+    OIC_LOG(DEBUG, TAG, "OUT PutOwnershipInformation");
 
     return res;
 }
 
-static OCStackResult PutUpdateOperationMode(OTMContext_t* otmCtx,
-                                    OicSecDpom_t selectedOperationMode)
+static OCStackResult PutUpdateOperationMode(OTMContext_t* otmCtx)
 {
-    OC_LOG(DEBUG, TAG, "IN PutUpdateOperationMode");
+    OIC_LOG(DEBUG, TAG, "IN PutUpdateOperationMode");
 
     if(!otmCtx || !otmCtx->selectedDeviceInfo)
     {
@@ -786,25 +1219,24 @@ static OCStackResult PutUpdateOperationMode(OTMContext_t* otmCtx,
                         deviceInfo->connType,
                         query, sizeof(query), OIC_RSRC_PSTAT_URI))
     {
-        OC_LOG(ERROR, TAG, "PutUpdateOperationMode : Failed to generate query");
+        OIC_LOG(ERROR, TAG, "PutUpdateOperationMode : Failed to generate query");
         return OC_STACK_ERROR;
     }
-    OC_LOG_V(DEBUG, TAG, "Query=%s", query);
-
-    deviceInfo->pstat->om = selectedOperationMode;
+    OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
 
     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
     if(!secPayload)
     {
-        OC_LOG(ERROR, TAG, "Failed to memory allocation");
+        OIC_LOG(ERROR, TAG, "Failed to memory allocation");
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    secPayload->securityData = BinToPstatJSON(deviceInfo->pstat);
-    if (NULL == secPayload->securityData)
+    OCStackResult res = PstatToCBORPayload(deviceInfo->pstat, &secPayload->securityData,
+                                           &secPayload->payloadSize);
+   if (OC_STACK_OK != res)
     {
-        OICFree(secPayload);
-        OC_LOG(ERROR, TAG, "Error while converting pstat bin to json");
+        OCPayloadDestroy((OCPayload *)secPayload);
+        OIC_LOG(ERROR, TAG, "Error while converting pstat to cbor.");
         return OC_STACK_INVALID_PARAM;
     }
 
@@ -812,21 +1244,21 @@ static OCStackResult PutUpdateOperationMode(OTMContext_t* otmCtx,
     cbData.cb = &OperationModeUpdateHandler;
     cbData.context = (void *)otmCtx;
     cbData.cd = NULL;
-    OCStackResult res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
-                                     deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
+    res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload *)secPayload,
+                       deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
     if (res != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack resource error");
+        OIC_LOG(ERROR, TAG, "OCStack resource error");
     }
 
-    OC_LOG(DEBUG, TAG, "OUT PutUpdateOperationMode");
+    OIC_LOG(DEBUG, TAG, "OUT PutUpdateOperationMode");
 
     return res;
 }
 
 static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selectedDevice)
 {
-    OC_LOG(INFO, TAG, "IN StartOwnershipTransfer");
+    OIC_LOG(INFO, TAG, "IN StartOwnershipTransfer");
     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
     otmCtx->selectedDeviceInfo = selectedDevice;
 
@@ -836,22 +1268,28 @@ static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selecte
                                                  &selectedDevice->doxm->oxmSel);
     if(OC_STACK_OK != res)
     {
-        OC_LOG(ERROR, TAG, "Failed to select the provisioning method");
+        OIC_LOG(ERROR, TAG, "Failed to select the provisioning method");
         SetResult(otmCtx, res);
         return res;
     }
-    OC_LOG_V(DEBUG, TAG, "Selected provisoning method = %d", selectedDevice->doxm->oxmSel);
+    OIC_LOG_V(DEBUG, TAG, "Selected provisoning method = %d", selectedDevice->doxm->oxmSel);
 
     //Send Req: PUT /oic/sec/doxm [{..."OxmSel" :g_OTMDatas[Index of Selected OxM].OXMString,...}]
     res = PutOwnerTransferModeToResource(otmCtx);
     if(OC_STACK_OK != res)
     {
-        OC_LOG(WARNING, TAG, "Failed to select the provisioning method");
+        OIC_LOG(WARNING, TAG, "Failed to select the provisioning method");
         SetResult(otmCtx, res);
         return res;
     }
 
-    OC_LOG(INFO, TAG, "OUT StartOwnershipTransfer");
+    //Register DTLS event handler to catch the dtls event while handshake
+    if(CA_STATUS_OK != CARegisterDTLSHandshakeCallback(DTLSHandshakeCB))
+    {
+        OIC_LOG(WARNING, TAG, "StartOwnershipTransfer : Failed to register DTLS handshake callback.");
+    }
+
+    OIC_LOG(INFO, TAG, "OUT StartOwnershipTransfer");
 
     return res;
 
@@ -859,16 +1297,16 @@ static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selecte
 
 OCStackResult OTMSetOwnershipTransferCallbackData(OicSecOxm_t oxmType, OTMCallbackData_t* data)
 {
-    OC_LOG(DEBUG, TAG, "IN OTMSetOwnerTransferCallbackData");
+    OIC_LOG(DEBUG, TAG, "IN OTMSetOwnerTransferCallbackData");
 
     if(!data)
     {
-        OC_LOG(ERROR, TAG, "OTMSetOwnershipTransferCallbackData : Invalid parameters");
+        OIC_LOG(ERROR, TAG, "OTMSetOwnershipTransferCallbackData : Invalid parameters");
         return OC_STACK_INVALID_PARAM;
     }
     if(oxmType >= OIC_OXM_COUNT)
     {
-        OC_LOG(INFO, TAG, "Unknow ownership transfer method");
+        OIC_LOG(INFO, TAG, "Unknow ownership transfer method");
         return OC_STACK_INVALID_PARAM;
     }
 
@@ -877,7 +1315,7 @@ OCStackResult OTMSetOwnershipTransferCallbackData(OicSecOxm_t oxmType, OTMCallba
     g_OTMDatas[oxmType].createSelectOxmPayloadCB = data->createSelectOxmPayloadCB;
     g_OTMDatas[oxmType].createOwnerTransferPayloadCB = data->createOwnerTransferPayloadCB;
 
-    OC_LOG(DEBUG, TAG, "OUT OTMSetOwnerTransferCallbackData");
+    OIC_LOG(DEBUG, TAG, "OUT OTMSetOwnerTransferCallbackData");
 
     return OC_STACK_OK;
 }
@@ -889,17 +1327,21 @@ OCStackResult OTMDoOwnershipTransfer(void* ctx,
                                      OCProvisionDev_t *selectedDevicelist,
                                      OCProvisionResultCB resultCallback)
 {
-    OC_LOG(DEBUG, TAG, "IN OTMDoOwnershipTransfer");
+    OIC_LOG(DEBUG, TAG, "IN OTMDoOwnershipTransfer");
 
-    if (NULL == selectedDevicelist || NULL == resultCallback )
+    if (NULL == selectedDevicelist)
     {
         return OC_STACK_INVALID_PARAM;
     }
+    if (NULL == resultCallback)
+    {
+        return OC_STACK_INVALID_CALLBACK;
+    }
 
     OTMContext_t* otmCtx = (OTMContext_t*)OICCalloc(1,sizeof(OTMContext_t));
     if(!otmCtx)
     {
-        OC_LOG(ERROR, TAG, "Failed to create OTM Context");
+        OIC_LOG(ERROR, TAG, "Failed to create OTM Context");
         return OC_STACK_NO_MEMORY;
     }
     otmCtx->ctxResultCallback = resultCallback;
@@ -919,30 +1361,28 @@ OCStackResult OTMDoOwnershipTransfer(void* ctx,
         (OCProvisionResult_t*)OICCalloc(otmCtx->ctxResultArraySize, sizeof(OCProvisionResult_t));
     if(NULL == otmCtx->ctxResultArray)
     {
-        OC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Failed to memory allocation");
+        OIC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Failed to memory allocation");
         OICFree(otmCtx);
         return OC_STACK_NO_MEMORY;
     }
     pCurDev = selectedDevicelist;
 
+    OCStackResult res = OC_STACK_OK;
     //Fill the device UUID for result array.
     for(size_t devIdx = 0; devIdx < otmCtx->ctxResultArraySize; devIdx++)
     {
         //Checking duplication of Device ID.
         bool isDuplicate = true;
-        OCStackResult res = PDMIsDuplicateDevice(&pCurDev->doxm->deviceID, &isDuplicate);
+        res = PDMIsDuplicateDevice(&pCurDev->doxm->deviceID, &isDuplicate);
         if (OC_STACK_OK != res)
         {
-            OICFree(otmCtx->ctxResultArray);
-            OICFree(otmCtx);
-            return res;
+            goto error;
         }
         if (isDuplicate)
         {
-            OC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Device ID is duplicated");
-            OICFree(otmCtx->ctxResultArray);
-            OICFree(otmCtx);
-            return OC_STACK_INVALID_PARAM;
+            OIC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Device ID is duplicated");
+            res = OC_STACK_INVALID_PARAM;
+            goto error;
         }
         memcpy(otmCtx->ctxResultArray[devIdx].deviceId.id,
                pCurDev->doxm->deviceID.id,
@@ -950,228 +1390,130 @@ OCStackResult OTMDoOwnershipTransfer(void* ctx,
         otmCtx->ctxResultArray[devIdx].res = OC_STACK_CONTINUE;
         pCurDev = pCurDev->next;
     }
+
     StartOwnershipTransfer(otmCtx, selectedDevicelist);
 
-    OC_LOG(DEBUG, TAG, "OUT OTMDoOwnershipTransfer");
+    OIC_LOG(DEBUG, TAG, "OUT OTMDoOwnershipTransfer");
     return OC_STACK_OK;
+
+error:
+    OICFree(otmCtx->ctxResultArray);
+    OICFree(otmCtx);
+    return res;
 }
 
-/**
- * Callback handler of SRPFinalizeProvisioning.
- *
- * @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 FinalizeProvisioningCB(void *ctx, OCDoHandle UNUSED,
-                                                       OCClientResponse *clientResponse)
+OCStackResult PutProvisioningStatus(OTMContext_t* otmCtx)
 {
-    OC_LOG_V(INFO, TAG, "IN FinalizeProvisioningCB.");
+    OIC_LOG(INFO, TAG, "IN PutProvisioningStatus");
 
-    VERIFY_NON_NULL(TAG, clientResponse, ERROR);
-    VERIFY_NON_NULL(TAG, ctx, ERROR);
-
-    OTMContext_t* otmCtx = (OTMContext_t*)ctx;
-    (void)UNUSED;
-    if(OC_STACK_OK == clientResponse->result)
+    if(!otmCtx || !otmCtx->selectedDeviceInfo)
     {
-        OCStackResult res = PDMAddDevice(&otmCtx->selectedDeviceInfo->doxm->deviceID);
-
-         if (OC_STACK_OK == res)
-         {
-                OC_LOG_V(INFO, TAG, "Add device's UUID in PDM_DB");
-                SetResult(otmCtx, OC_STACK_OK);
-                return OC_STACK_DELETE_TRANSACTION;
-         }
-         else
-         {
-              OC_LOG(ERROR, TAG, "Ownership transfer is complete but adding information to DB is failed.");
-         }
+        OIC_LOG(ERROR, TAG, "OTMContext is NULL");
+        return OC_STACK_INVALID_PARAM;
     }
-exit:
-    return OC_STACK_DELETE_TRANSACTION;
-}
 
-/**
- * Callback handler of default ACL provisioning.
- *
- * @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 ProvisionDefaultACLCB(void *ctx, OCDoHandle UNUSED,
-                                                       OCClientResponse *clientResponse)
-{
-    OC_LOG_V(INFO, TAG, "IN ProvisionDefaultACLCB.");
+    //Change the TAKE_OWNER bit of CM to 0.
+    otmCtx->selectedDeviceInfo->pstat->cm &= (~TAKE_OWNER);
 
-    VERIFY_NON_NULL(TAG, clientResponse, ERROR);
-    VERIFY_NON_NULL(TAG, ctx, ERROR);
-
-    OTMContext_t* otmCtx = (OTMContext_t*) ctx;
-    (void)UNUSED;
-
-    if (OC_STACK_RESOURCE_CREATED == clientResponse->result)
+    OCSecurityPayload *secPayload = (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
+    if (!secPayload)
     {
-        OC_LOG_V(INFO, TAG, "Staring commit hash task.");
-        // TODO hash currently have fixed value 0.
-        uint16_t aclHash = 0;
-        otmCtx->selectedDeviceInfo->pstat->commitHash = aclHash;
-        otmCtx->selectedDeviceInfo->pstat->tm = NORMAL;
-        OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
-        if(!secPayload)
-        {
-            OC_LOG(ERROR, TAG, "Failed to memory allocation");
-            return OC_STACK_NO_MEMORY;
-        }
-        secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-        secPayload->securityData = BinToPstatJSON(otmCtx->selectedDeviceInfo->pstat);
-        if (NULL == secPayload->securityData)
-        {
-            OICFree(secPayload);
-            SetResult(otmCtx, OC_STACK_INVALID_JSON);
-            return OC_STACK_DELETE_TRANSACTION;
-        }
-        OC_LOG_V(INFO, TAG, "Created payload for commit hash: %s",secPayload->securityData);
-
-        char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
-        if(!PMGenerateQuery(true,
-                            otmCtx->selectedDeviceInfo->endpoint.addr,
-                            otmCtx->selectedDeviceInfo->securePort,
-                            otmCtx->selectedDeviceInfo->connType,
-                            query, sizeof(query), OIC_RSRC_PSTAT_URI))
-        {
-            OC_LOG(ERROR, TAG, "ProvisionDefaultACLCB : Failed to generate query");
-            return OC_STACK_ERROR;
-        }
-        OC_LOG_V(DEBUG, TAG, "Query=%s", query);
+        OIC_LOG(ERROR, TAG, "Failed to memory allocation");
+        return OC_STACK_NO_MEMORY;
+    }
+    secPayload->base.type = PAYLOAD_TYPE_SECURITY;
+    if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
+            &secPayload->securityData, &secPayload->payloadSize))
+    {
+        OCPayloadDestroy((OCPayload *)secPayload);
+        return OC_STACK_INVALID_JSON;
+    }
+    OIC_LOG(DEBUG, TAG, "Created payload for chage to Provisiong state");
+    OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
 
-        OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
-        cbData.cb = &FinalizeProvisioningCB;
-        cbData.context = (void*)otmCtx;
-        cbData.cd = NULL;
-        OCStackResult ret = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
-                otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
-        OC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
-        if (ret != OC_STACK_OK)
-        {
-            OC_LOG(ERROR, TAG, "OCStack resource error");
-            SetResult(otmCtx, ret);
-        }
+    char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
+    if(!PMGenerateQuery(true,
+                        otmCtx->selectedDeviceInfo->endpoint.addr,
+                        otmCtx->selectedDeviceInfo->securePort,
+                        otmCtx->selectedDeviceInfo->connType,
+                        query, sizeof(query), OIC_RSRC_PSTAT_URI))
+    {
+        OIC_LOG(ERROR, TAG, "PutProvisioningStatus : Failed to generate query");
+        return OC_STACK_ERROR;
     }
-    else
+    OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
+
+    OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
+    cbData.cb = &ProvisioningStatusHandler;
+    cbData.context = (void*)otmCtx;
+    cbData.cd = NULL;
+    OCStackResult ret = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
+            otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
+    OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
+    if (ret != OC_STACK_OK)
     {
-        OC_LOG_V(INFO, TAG, "Error occured in provisionDefaultACLCB :: %d\n",
-                            clientResponse->result);
-        SetResult(otmCtx, clientResponse->result);
+        OIC_LOG(ERROR, TAG, "OCStack resource error");
     }
-exit:
-    return OC_STACK_DELETE_TRANSACTION;
-}
 
+    OIC_LOG(INFO, TAG, "OUT PutProvisioningStatus");
 
-OCStackResult FinalizeProvisioning(OTMContext_t* otmCtx)
+    return ret;
+}
+
+OCStackResult PutNormalOperationStatus(OTMContext_t* otmCtx)
 {
-    OC_LOG(INFO, TAG, "IN FinalizeProvisioning");
+    OIC_LOG(INFO, TAG, "IN PutNormalOperationStatus");
 
-    if(!otmCtx)
-    {
-        OC_LOG(ERROR, TAG, "OTMContext is NULL");
-        return OC_STACK_INVALID_PARAM;
-    }
-    if(!otmCtx->selectedDeviceInfo)
+    if(!otmCtx || !otmCtx->selectedDeviceInfo)
     {
-        OC_LOG(ERROR, TAG, "Can't find device information in OTMContext");
-        OICFree(otmCtx);
+        OIC_LOG(ERROR, TAG, "OTMContext is NULL");
         return OC_STACK_INVALID_PARAM;
     }
-    // Provision Default ACL to device
-    OicSecAcl_t defaultAcl =
-    { {.id={0}},
-        1,
-        NULL,
-        0x001F,
-        0,
-        NULL,
-        NULL,
-        1,
-        NULL,
-        NULL,
-    };
-
-    OicUuid_t provTooldeviceID = {.id={0}};
-    if (OC_STACK_OK != GetDoxmDeviceID(&provTooldeviceID))
-    {
-        OC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
-        SetResult(otmCtx, OC_STACK_ERROR);
-        return OC_STACK_ERROR;
-    }
-    OC_LOG(INFO, TAG, "Retieved deviceID");
-    memcpy(defaultAcl.subject.id, provTooldeviceID.id, sizeof(defaultAcl.subject.id));
-    char *wildCardResource = "*";
-    defaultAcl.resources = &wildCardResource;
 
-    defaultAcl.owners = (OicUuid_t *) OICCalloc(1, UUID_LENGTH);
-    if(!defaultAcl.owners)
-    {
-        OC_LOG(ERROR, TAG, "Failed to memory allocation for default ACL");
-        SetResult(otmCtx, OC_STACK_NO_MEMORY);
-        return OC_STACK_NO_MEMORY;
-    }
-    memcpy(defaultAcl.owners->id, provTooldeviceID.id, UUID_LENGTH);
-    OC_LOG(INFO, TAG, "Provisioning default ACL");
+    //Set isop to true.
+    otmCtx->selectedDeviceInfo->pstat->isOp = true;
 
-    OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
-    if(!secPayload)
+    OCSecurityPayload *secPayload = (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
+    if (!secPayload)
     {
-        OC_LOG(ERROR, TAG, "Failed to memory allocation");
+        OIC_LOG(ERROR, TAG, "Failed to memory allocation");
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    secPayload->securityData = BinToAclJSON(&defaultAcl);
-    OICFree(defaultAcl.owners);
-    if(!secPayload->securityData)
+    if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
+            &secPayload->securityData, &secPayload->payloadSize))
     {
-        OICFree(secPayload);
-        OC_LOG(INFO, TAG, "FinalizeProvisioning : Failed to BinToAclJSON");
-        SetResult(otmCtx, OC_STACK_ERROR);
-        return OC_STACK_ERROR;
+        OCPayloadDestroy((OCPayload *)secPayload);
+        return OC_STACK_INVALID_JSON;
     }
-    OC_LOG_V(INFO, TAG, "Provisioning default ACL : %s",secPayload->securityData);
+    OIC_LOG(DEBUG, TAG, "Created payload for chage to Provisiong state");
+    OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
 
     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
     if(!PMGenerateQuery(true,
                         otmCtx->selectedDeviceInfo->endpoint.addr,
                         otmCtx->selectedDeviceInfo->securePort,
                         otmCtx->selectedDeviceInfo->connType,
-                        query, sizeof(query), OIC_RSRC_ACL_URI))
+                        query, sizeof(query), OIC_RSRC_PSTAT_URI))
     {
-        OC_LOG(ERROR, TAG, "FinalizeProvisioning : Failed to generate query");
+        OIC_LOG(ERROR, TAG, "PutNormalOperationStatus : Failed to generate query");
         return OC_STACK_ERROR;
     }
-    OC_LOG_V(DEBUG, TAG, "Query=%s", query);
-
-    OC_LOG_V(INFO, TAG, "Request URI for Provisioning default ACL : %s", query);
+    OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
 
-    OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
-    cbData.cb = &ProvisionDefaultACLCB;
-    cbData.context = (void *)otmCtx;
+    OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
+    cbData.cb = &ReadyForNomalStatusHandler;
+    cbData.context = (void*)otmCtx;
     cbData.cd = NULL;
-    OCStackResult ret = OCDoResource(NULL, OC_REST_POST, query,
-            &otmCtx->selectedDeviceInfo->endpoint, (OCPayload*)secPayload,
+    OCStackResult ret = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
             otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
-    if (OC_STACK_OK != ret)
+    OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
+    if (ret != OC_STACK_OK)
     {
-        SetResult(otmCtx, ret);
-        return ret;
+        OIC_LOG(ERROR, TAG, "OCStack resource error");
     }
 
-    OC_LOG(INFO, TAG, "OUT FinalizeProvisioning");
+    OIC_LOG(INFO, TAG, "OUT PutNormalOperationStatus");
 
     return ret;
-
 }
-
index 7a0d561..a0f1e96 100644 (file)
 
 #define TAG "OXM_JustWorks"
 
-char* CreateJustWorksSelectOxmPayload(OTMContext_t* otmCtx)
+OCStackResult CreateJustWorksSelectOxmPayload(OTMContext_t *otmCtx, uint8_t **payload, size_t *size)
 {
-    if(!otmCtx || !otmCtx->selectedDeviceInfo)
+    if (!otmCtx || !otmCtx->selectedDeviceInfo || !payload || *payload || !size)
     {
-        return NULL;
+        return OC_STACK_INVALID_PARAM;
     }
 
     otmCtx->selectedDeviceInfo->doxm->oxmSel = OIC_JUST_WORKS;
-    return BinToDoxmJSON(otmCtx->selectedDeviceInfo->doxm);
+    *payload = NULL;
+    *size = 0;
+
+    return DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm, payload, size);
 }
 
-char* CreateJustWorksOwnerTransferPayload(OTMContext_t* otmCtx)
+OCStackResult CreateJustWorksOwnerTransferPayload(OTMContext_t* otmCtx, uint8_t **payload, size_t *size)
 {
-    if(!otmCtx || !otmCtx->selectedDeviceInfo)
+    if (!otmCtx || !otmCtx->selectedDeviceInfo || !payload || *payload || !size)
     {
-        return NULL;
+        return OC_STACK_INVALID_PARAM;
     }
 
     OicUuid_t uuidPT = {.id={0}};
 
     if (OC_STACK_OK != GetDoxmDeviceID(&uuidPT))
     {
-        OC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
-        return NULL;
+        OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
+        return OC_STACK_ERROR;
     }
     memcpy(otmCtx->selectedDeviceInfo->doxm->owner.id, uuidPT.id , UUID_LENGTH);
-    otmCtx->selectedDeviceInfo->doxm->owned = true;
 
-    return BinToDoxmJSON(otmCtx->selectedDeviceInfo->doxm);
+    *payload = NULL;
+    *size = 0;
+
+    return DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm, payload, size);
 }
 
 OCStackResult LoadSecretJustWorksCallback(OTMContext_t* UNUSED_PARAM)
@@ -72,8 +77,8 @@ OCStackResult LoadSecretJustWorksCallback(OTMContext_t* UNUSED_PARAM)
 
 OCStackResult CreateSecureSessionJustWorksCallback(OTMContext_t* otmCtx)
 {
-    OC_LOG(INFO, TAG, "IN CreateSecureSessionJustWorksCallback");
-    if(!otmCtx || !otmCtx->selectedDeviceInfo)
+    OIC_LOG(INFO, TAG, "IN CreateSecureSessionJustWorksCallback");
+    if (!otmCtx || !otmCtx->selectedDeviceInfo)
     {
         return OC_STACK_INVALID_PARAM;
     }
@@ -81,45 +86,45 @@ OCStackResult CreateSecureSessionJustWorksCallback(OTMContext_t* otmCtx)
     CAResult_t caresult = CAEnableAnonECDHCipherSuite(true);
     if (CA_STATUS_OK != caresult)
     {
-        OC_LOG_V(ERROR, TAG, "Unable to enable anon cipher suite");
+        OIC_LOG_V(ERROR, TAG, "Unable to enable anon cipher suite");
         return OC_STACK_ERROR;
     }
-    OC_LOG(INFO, TAG, "Anonymous cipher suite Enabled.");
+    OIC_LOG(INFO, TAG, "Anonymous cipher suite Enabled.");
 
     caresult  = CASelectCipherSuite(TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256);
     if (CA_STATUS_OK != caresult)
     {
-        OC_LOG_V(ERROR, TAG, "Failed to select TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256");
+        OIC_LOG_V(ERROR, TAG, "Failed to select TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256");
         caresult = CAEnableAnonECDHCipherSuite(false);
         if (CA_STATUS_OK != caresult)
         {
-            OC_LOG_V(ERROR, TAG, "Unable to enable anon cipher suite");
+            OIC_LOG_V(ERROR, TAG, "Unable to enable anon cipher suite");
         }
         else
         {
-            OC_LOG(INFO, TAG, "Anonymous cipher suite Disabled.");
+            OIC_LOG(INFO, TAG, "Anonymous cipher suite Disabled.");
         }
         return OC_STACK_ERROR;
     }
-    OC_LOG(INFO, TAG, "TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256 cipher suite selected.");
+    OIC_LOG(INFO, TAG, "TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256 cipher suite selected.");
 
-    OCProvisionDev_tselDevInfo = otmCtx->selectedDeviceInfo;
+    OCProvisionDev_t *selDevInfo = otmCtx->selectedDeviceInfo;
     CAEndpoint_t *endpoint = (CAEndpoint_t *)OICCalloc(1, sizeof (CAEndpoint_t));
     if(NULL == endpoint)
     {
         return OC_STACK_NO_MEMORY;
     }
-    memcpy(endpoint,&selDevInfo->endpoint,sizeof(CAEndpoint_t));
+    memcpy(endpoint, &selDevInfo->endpoint, sizeof(CAEndpoint_t));
     endpoint->port = selDevInfo->securePort;
 
     caresult = CAInitiateHandshake(endpoint);
     OICFree(endpoint);
     if (CA_STATUS_OK != caresult)
     {
-        OC_LOG_V(ERROR, TAG, "DTLS handshake failure.");
+        OIC_LOG_V(ERROR, TAG, "DTLS handshake failure.");
         return OC_STACK_ERROR;
     }
 
-    OC_LOG(INFO, TAG, "OUT CreateSecureSessionJustWorksCallback");
+    OIC_LOG(INFO, TAG, "OUT CreateSecureSessionJustWorksCallback");
     return OC_STACK_OK;
 }
index 8e9ad1e..4efc238 100644 (file)
 
 #define TAG "OXM_RandomPIN"
 
-char* CreatePinBasedSelectOxmPayload(OTMContext_t* otmCtx)
+OCStackResult CreatePinBasedSelectOxmPayload(OTMContext_t* otmCtx, uint8_t **payload, size_t *size)
 {
-    if(!otmCtx || !otmCtx->selectedDeviceInfo)
+    if(!otmCtx || !otmCtx->selectedDeviceInfo || !payload || *payload || !size)
     {
-        return NULL;
+        return OC_STACK_INVALID_PARAM;
     }
 
     otmCtx->selectedDeviceInfo->doxm->oxmSel = OIC_RANDOM_DEVICE_PIN;
 
-    OicUuid_t uuidPT = {.id={0}};
-    if (OC_STACK_OK != GetDoxmDeviceID(&uuidPT))
-    {
-        OC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
-        return NULL;
-    }
-    memcpy(otmCtx->selectedDeviceInfo->doxm->owner.id, uuidPT.id, UUID_LENGTH);
-
-    return BinToDoxmJSON(otmCtx->selectedDeviceInfo->doxm);
+    return DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm, payload, size);
 }
 
-char* CreatePinBasedOwnerTransferPayload(OTMContext_t* otmCtx)
+OCStackResult CreatePinBasedOwnerTransferPayload(OTMContext_t* otmCtx, uint8_t **payload, size_t *size)
 {
-    if(!otmCtx || !otmCtx->selectedDeviceInfo)
+    if(!otmCtx || !otmCtx->selectedDeviceInfo || !payload || *payload || !size)
     {
-        return NULL;
+        return OC_STACK_INVALID_PARAM;
     }
 
     OicUuid_t uuidPT = {.id={0}};
+    *payload = NULL;
+    *size = 0;
 
     if (OC_STACK_OK != GetDoxmDeviceID(&uuidPT))
     {
-        OC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
-        return NULL;
+        OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
+        return OC_STACK_ERROR;
     }
     memcpy(otmCtx->selectedDeviceInfo->doxm->owner.id, uuidPT.id , UUID_LENGTH);
-    otmCtx->selectedDeviceInfo->doxm->owned = true;
 
-    return BinToDoxmJSON(otmCtx->selectedDeviceInfo->doxm);
+    return DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm, payload, size);
 }
 
-OCStackResult InputPinCodeCallback(OTMContext_totmCtx)
+OCStackResult InputPinCodeCallback(OTMContext_t *otmCtx)
 {
-    if(!otmCtx || !otmCtx->selectedDeviceInfo)
+    if (!otmCtx || !otmCtx->selectedDeviceInfo)
     {
         return OC_STACK_INVALID_PARAM;
     }
@@ -88,36 +81,34 @@ OCStackResult InputPinCodeCallback(OTMContext_t* otmCtx)
     uint8_t pinData[OXM_RANDOM_PIN_SIZE + 1];
 
     OCStackResult res = InputPin((char*)pinData, OXM_RANDOM_PIN_SIZE + 1);
-    if(OC_STACK_OK != res)
+    if (OC_STACK_OK != res)
     {
-        OC_LOG(ERROR, TAG, "Failed to input PIN");
+        OIC_LOG(ERROR, TAG, "Failed to input PIN");
         return res;
     }
 
-    OicUuid_t deviceUUID = {.id={0}};
-    if (OC_STACK_OK != GetDoxmDeviceID(&deviceUUID))
+    /**
+     * Since PSK will be used directly while PIN based ownership transfer,
+     * Credential should not be saved into SVR.
+     * For this reason, We will use a temporary get_psk_info callback to random PIN OxM.
+     */
+    if(CA_STATUS_OK != CARegisterDTLSCredentialsHandler(GetDtlsPskForRandomPinOxm))
     {
-        OC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
-        return OC_STACK_ERROR;
+        OIC_LOG(ERROR, TAG, "Failed to register DTLS credentials handler for random PIN OxM.");
+        res = OC_STACK_ERROR;
     }
 
-    res = AddTmpPskWithPIN(&otmCtx->selectedDeviceInfo->doxm->deviceID,
-                           SYMMETRIC_PAIR_WISE_KEY,
-                           (char*)pinData, OXM_RANDOM_PIN_SIZE,
-                           1, &deviceUUID, &otmCtx->subIdForPinOxm);
-    if(res != OC_STACK_OK)
-    {
-        OC_LOG_V(ERROR, TAG, "Failed to save the temporal PSK : %d", res);
-    }
+    //Set the device id to derive temporal PSK
+    SetUuidForRandomPinOxm(&(otmCtx->selectedDeviceInfo->doxm->deviceID));
 
     return res;
 }
 
-OCStackResult CreateSecureSessionRandomPinCallbak(OTMContext_t* otmCtx)
+OCStackResult CreateSecureSessionRandomPinCallback(OTMContext_t* otmCtx)
 {
-    OC_LOG(INFO, TAG, "IN CreateSecureSessionRandomPinCallbak");
+    OIC_LOG(INFO, TAG, "IN CreateSecureSessionRandomPinCallbak");
 
-    if(!otmCtx || !otmCtx->selectedDeviceInfo)
+    if (!otmCtx || !otmCtx->selectedDeviceInfo)
     {
         return OC_STACK_INVALID_PARAM;
     }
@@ -125,23 +116,22 @@ OCStackResult CreateSecureSessionRandomPinCallbak(OTMContext_t* otmCtx)
     CAResult_t caresult = CAEnableAnonECDHCipherSuite(false);
     if (CA_STATUS_OK != caresult)
     {
-        OC_LOG_V(ERROR, TAG, "Unable to disable anon cipher suite");
+        OIC_LOG_V(ERROR, TAG, "Unable to disable anon cipher suite");
         return OC_STACK_ERROR;
     }
-    OC_LOG(INFO, TAG, "Anonymous cipher suite disabled.");
+    OIC_LOG(INFO, TAG, "Anonymous cipher suite disabled.");
 
     caresult  = CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256);
     if (CA_STATUS_OK != caresult)
     {
-        OC_LOG_V(ERROR, TAG, "Failed to select TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256");
+        OIC_LOG_V(ERROR, TAG, "Failed to select TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256");
         return OC_STACK_ERROR;
     }
-    OC_LOG(INFO, TAG, "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256 cipher suite selected.");
-
+    OIC_LOG(INFO, TAG, "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256 cipher suite selected.");
 
     OCProvisionDev_t* selDevInfo = otmCtx->selectedDeviceInfo;
     CAEndpoint_t *endpoint = (CAEndpoint_t *)OICCalloc(1, sizeof (CAEndpoint_t));
-    if(NULL == endpoint)
+    if (NULL == endpoint)
     {
         return OC_STACK_NO_MEMORY;
     }
@@ -151,11 +141,11 @@ OCStackResult CreateSecureSessionRandomPinCallbak(OTMContext_t* otmCtx)
     OICFree(endpoint);
     if (CA_STATUS_OK != caresult)
     {
-        OC_LOG_V(ERROR, TAG, "DTLS handshake failure.");
+        OIC_LOG_V(ERROR, TAG, "DTLS handshake failure.");
         return OC_STACK_ERROR;
     }
 
-    OC_LOG(INFO, TAG, "OUT CreateSecureSessionRandomPinCallbak");
+    OIC_LOG(INFO, TAG, "OUT CreateSecureSessionRandomPinCallbak");
 
     return OC_STACK_OK;
 }
old mode 100755 (executable)
new mode 100644 (file)
index 60daa64..e55e9a6
@@ -38,6 +38,7 @@
 #include "srmresourcestrings.h" //@note: SRM's internal header
 #include "doxmresource.h"       //@note: SRM's internal header
 #include "pstatresource.h"      //@note: SRM's internal header
+#include "verresource.h"      //@note: SRM's internal header
 
 #include "pmtypes.h"
 #include "pmutility.h"
@@ -51,6 +52,65 @@ typedef struct _DiscoveryInfo{
     bool                isOwnedDiscovery;
 } DiscoveryInfo;
 
+/*
+ * Function to discover secre port information through unicast
+ *
+ * @param[in] discoveryInfo The pointer of discovery information to matain result of discovery
+ * @param[in] clientResponse  Response information(It will contain payload)
+ *
+ * @return OC_STACK_OK on success otherwise error.
+ */
+static OCStackResult SecurePortDiscovery(DiscoveryInfo* discoveryInfo,
+                                         const OCClientResponse *clientResponse);
+
+/*
+ * Function to discover security version information through unicast
+ *
+ * @param[in] discoveryInfo The pointer of discovery information to matain result of discovery
+ * @param[in] clientResponse  Response information(It will contain payload)
+ *
+ * @return OC_STACK_OK on success otherwise error.
+ */
+static OCStackResult SecurityVersionDiscovery(DiscoveryInfo* discoveryInfo,
+                                              const OCClientResponse *clientResponse);
+
+/**
+ * Callback handler for PMDeviceDiscovery API.
+ *
+ * @param[in] ctx             User context
+ * @param[in] handle          Handler for response
+ * @param[in] clientResponse  Response information (It will contain payload)
+ * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
+ *         OC_STACK_DELETE_TRANSACTION to delete it.
+ */
+static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
+                                OCClientResponse *clientResponse);
+
+/**
+ * Callback handler for getting secure port information using /oic/res discovery.
+ *
+ * @param[in] ctx             user context
+ * @param[in] handle          Handle for response
+ * @param[in] clientResponse  Response information(It will contain payload)
+ *
+ * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
+ *         OC_STACK_DELETE_TRANSACTION to delete it.
+ */
+static OCStackApplicationResult SecurePortDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
+                                 OCClientResponse *clientResponse);
+
+/**
+ * Callback handler for security version discovery.
+ *
+ * @param[in] ctx             User context
+ * @param[in] handle          Handler for response
+ * @param[in] clientResponse  Response information (It will contain payload)
+ * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
+ *         OC_STACK_DELETE_TRANSACTION to delete it.
+ */
+static OCStackApplicationResult SecVersionDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
+                                OCClientResponse *clientResponse);
+
 /**
  * Function to search node in linked list that matches given IP and port.
  *
@@ -64,7 +124,7 @@ OCProvisionDev_t* GetDevice(OCProvisionDev_t **ppDevicesList, const char* addr,
 {
     if(NULL == addr || NULL == *ppDevicesList)
     {
-        OC_LOG_V(ERROR, TAG, "Invalid Input parameters in [%s]\n", __FUNCTION__);
+        OIC_LOG_V(ERROR, TAG, "Invalid Input parameters in [%s]\n", __FUNCTION__);
         return NULL;
     }
 
@@ -107,7 +167,7 @@ OCStackResult AddDevice(OCProvisionDev_t **ppDevicesList, const char* addr, cons
         ptr = (OCProvisionDev_t *)OICCalloc(1, sizeof (OCProvisionDev_t));
         if (NULL == ptr)
         {
-            OC_LOG(ERROR, TAG, "Error while allocating memory for linkedlist node !!");
+            OIC_LOG(ERROR, TAG, "Error while allocating memory for linkedlist node !!");
             return OC_STACK_NO_MEMORY;
         }
 
@@ -119,6 +179,7 @@ OCStackResult AddDevice(OCProvisionDev_t **ppDevicesList, const char* addr, cons
         ptr->next = NULL;
         ptr->connType = connType;
         ptr->devStatus = DEV_STATUS_ON; //AddDevice is called when discovery(=alive)
+        OICStrcpy(ptr->secVer, MAX_VERSION_LEN, DEFAULT_SEC_VERSION); // version initialization
 
         LL_PREPEND(*ppDevicesList, ptr);
     }
@@ -143,7 +204,7 @@ OCStackResult UpdateSecurePortOfDevice(OCProvisionDev_t **ppDevicesList, const c
 
     if(!ptr)
     {
-        OC_LOG(ERROR, TAG, "Can not find device information in the discovery device list");
+        OIC_LOG(ERROR, TAG, "Can not find device information in the discovery device list");
         return OC_STACK_ERROR;
     }
 
@@ -153,6 +214,37 @@ OCStackResult UpdateSecurePortOfDevice(OCProvisionDev_t **ppDevicesList, const c
 }
 
 /**
+ * Function to set security version information from the given list of devices.
+ *
+ * @param[in] pList         List of OCProvisionDev_t.
+ * @param[in] addr          address of target device.
+ * @param[in] port          port of remote server.
+ * @param[in] secVer    security version information.
+ *
+ * @return OC_STACK_OK for success and errorcode otherwise.
+ */
+OCStackResult UpdateSecVersionOfDevice(OCProvisionDev_t **ppDevicesList, const char *addr,
+                                       uint16_t port, const char* secVer)
+{
+    if (NULL == secVer)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCProvisionDev_t *ptr = GetDevice(ppDevicesList, addr, port);
+
+    if(!ptr)
+    {
+        OIC_LOG(ERROR, TAG, "Can not find device information in the discovery device list");
+        return OC_STACK_ERROR;
+    }
+
+    OICStrcpy(ptr->secVer, MAX_VERSION_LEN, secVer);
+
+    return OC_STACK_OK;
+}
+
+/**
  * This function deletes list of provision target devices
  *
  * @param[in] pDevicesList         List of OCProvisionDev_t.
@@ -175,11 +267,11 @@ void PMDeleteDeviceList(OCProvisionDev_t *pDevicesList)
 
 OCProvisionDev_t* PMCloneOCProvisionDev(const OCProvisionDev_t* src)
 {
-    OC_LOG(DEBUG, TAG, "IN PMCloneOCProvisionDev");
+    OIC_LOG(DEBUG, TAG, "IN PMCloneOCProvisionDev");
 
     if (!src)
     {
-        OC_LOG(ERROR, TAG, "PMCloneOCProvisionDev : Invalid parameter");
+        OIC_LOG(ERROR, TAG, "PMCloneOCProvisionDev : Invalid parameter");
         return NULL;
     }
 
@@ -210,17 +302,26 @@ OCProvisionDev_t* PMCloneOCProvisionDev(const OCProvisionDev_t* src)
         newDev->doxm->oxm = NULL;
     }
 
+    if (0 == strlen(src->secVer))
+    {
+        OICStrcpy(newDev->secVer, MAX_VERSION_LEN, DEFAULT_SEC_VERSION);
+    }
+    else
+    {
+        OICStrcpy(newDev->secVer, MAX_VERSION_LEN, src->secVer);
+    }
+
     newDev->securePort = src->securePort;
     newDev->devStatus = src->devStatus;
     newDev->connType = src->connType;
     newDev->next = NULL;
 
-    OC_LOG(DEBUG, TAG, "OUT PMCloneOCProvisionDev");
+    OIC_LOG(DEBUG, TAG, "OUT PMCloneOCProvisionDev");
 
     return newDev;
 
 exit:
-    OC_LOG(ERROR, TAG, "PMCloneOCProvisionDev : Failed to allocate memory");
+    OIC_LOG(ERROR, TAG, "PMCloneOCProvisionDev : Failed to allocate memory");
     if (newDev)
     {
         OICFree(newDev->pstat);
@@ -333,7 +434,7 @@ bool PMGenerateQuery(bool isSecure,
 {
     if(!address || !buffer || !uri)
     {
-        OC_LOG(ERROR, TAG, "PMGenerateQuery : Invalid parameters.");
+        OIC_LOG(ERROR, TAG, "PMGenerateQuery : Invalid parameters.");
         return false;
     }
 
@@ -354,18 +455,18 @@ bool PMGenerateQuery(bool isSecure,
                                          prefix, address, port, uri);
                     break;
                 default:
-                    OC_LOG(ERROR, TAG, "Unknown address format.");
+                    OIC_LOG(ERROR, TAG, "Unknown address format.");
                     return false;
             }
             // snprintf return value check
             if (snRet < 0)
             {
-                OC_LOG_V(ERROR, TAG, "PMGenerateQuery : Error (snprintf) %d\n", snRet);
+                OIC_LOG_V(ERROR, TAG, "PMGenerateQuery : Error (snprintf) %d\n", snRet);
                 return false;
             }
             else if ((size_t)snRet >= bufferSize)
             {
-                OC_LOG_V(ERROR, TAG, "PMGenerateQuery : Truncated (snprintf) %d\n", snRet);
+                OIC_LOG_V(ERROR, TAG, "PMGenerateQuery : Truncated (snprintf) %d\n", snRet);
                 return false;
             }
 
@@ -373,33 +474,96 @@ bool PMGenerateQuery(bool isSecure,
         // TODO: We need to verify tinyDTLS in below cases
         case CT_ADAPTER_GATT_BTLE:
         case CT_ADAPTER_RFCOMM_BTEDR:
-            OC_LOG(ERROR, TAG, "Not supported connectivity adapter.");
+            OIC_LOG(ERROR, TAG, "Not supported connectivity adapter.");
             return false;
             break;
         default:
-            OC_LOG(ERROR, TAG, "Unknown connectivity adapter.");
+            OIC_LOG(ERROR, TAG, "Unknown connectivity adapter.");
             return false;
     }
 
     return true;
 }
 
-/**
- * Callback handler for getting secure port information using /oic/res discovery.
- *
- * @param[in] ctx             user context
- * @param[in] handle          Handle for response
- * @param[in] clientResponse  Response information(It will contain payload)
- *
- * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
- *         OC_STACK_DELETE_TRANSACTION to delete it.
- */
+static OCStackApplicationResult SecurityVersionDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
+                                OCClientResponse *clientResponse)
+{
+    if (ctx == NULL)
+    {
+        OIC_LOG(ERROR, TAG, "Lost List of device information");
+        return OC_STACK_KEEP_TRANSACTION;
+    }
+    (void)UNUSED;
+    if (clientResponse)
+    {
+        if  (NULL == clientResponse->payload)
+        {
+            OIC_LOG(INFO, TAG, "Skiping Null payload");
+            return OC_STACK_KEEP_TRANSACTION;
+        }
+        if (OC_STACK_OK != clientResponse->result)
+        {
+            OIC_LOG(INFO, TAG, "Error in response");
+            return OC_STACK_KEEP_TRANSACTION;
+        }
+        else
+        {
+            if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
+            {
+                OIC_LOG(INFO, TAG, "Unknown payload type");
+                return OC_STACK_KEEP_TRANSACTION;
+            }
+
+            OicSecVer_t *ptrVer = NULL;
+            uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
+            size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
+
+            OCStackResult res = CBORPayloadToVer(payload, size, &ptrVer);
+            if ((NULL == ptrVer) && (OC_STACK_OK != res))
+            {
+                OIC_LOG(INFO, TAG, "Ignoring malformed CBOR");
+                return OC_STACK_KEEP_TRANSACTION;
+            }
+            else
+            {
+                OIC_LOG(DEBUG, TAG, "Successfully converted ver cbor to bin.");
+
+                //If this is owend device discovery we have to filter out the responses.
+                DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
+                res = UpdateSecVersionOfDevice(pDInfo->ppDevicesList, clientResponse->devAddr.addr,
+                                                         clientResponse->devAddr.port, ptrVer->secv);
+                if (OC_STACK_OK != res)
+                {
+                    OIC_LOG(ERROR, TAG, "Error while getting security version.");
+                    DeleteVerBinData(ptrVer);
+                    return OC_STACK_KEEP_TRANSACTION;
+                }
+
+                OIC_LOG(INFO, TAG, "= Discovered security version =");
+                OIC_LOG_V(DEBUG, TAG, "IP %s", clientResponse->devAddr.addr);
+                OIC_LOG_V(DEBUG, TAG, "PORT %d", clientResponse->devAddr.port);
+                OIC_LOG_V(DEBUG, TAG, "VERSION %s", ptrVer->secv);
+
+                OIC_LOG(INFO, TAG, "Exiting SecVersionDiscoveryHandler.");
+                DeleteVerBinData(ptrVer);
+            }
+        }
+    }
+    else
+    {
+        OIC_LOG(INFO, TAG, "Skiping Null response");
+        return OC_STACK_KEEP_TRANSACTION;
+    }
+
+    return  OC_STACK_DELETE_TRANSACTION;
+}
+
 static OCStackApplicationResult SecurePortDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
                                  OCClientResponse *clientResponse)
 {
     if (ctx == NULL)
     {
-        OC_LOG(ERROR, TAG, "Lost List of device information");
+        OIC_LOG(ERROR, TAG, "Lost List of device information");
         return OC_STACK_DELETE_TRANSACTION;
     }
     (void)UNUSED;
@@ -407,13 +571,13 @@ static OCStackApplicationResult SecurePortDiscoveryHandler(void *ctx, OCDoHandle
     {
         if  (NULL == clientResponse->payload)
         {
-            OC_LOG(INFO, TAG, "Skiping Null payload");
+            OIC_LOG(INFO, TAG, "Skiping Null payload");
         }
         else
         {
             if (PAYLOAD_TYPE_DISCOVERY != clientResponse->payload->type)
             {
-                OC_LOG(INFO, TAG, "Wrong payload type");
+                OIC_LOG(INFO, TAG, "Wrong payload type");
                 return OC_STACK_DELETE_TRANSACTION;
             }
 
@@ -426,47 +590,46 @@ static OCStackApplicationResult SecurePortDiscoveryHandler(void *ctx, OCDoHandle
             }
             else
             {
-                OC_LOG(INFO, TAG, "Can not find secure port information.");
+                OIC_LOG(INFO, TAG, "Can not find secure port information.");
                 return OC_STACK_DELETE_TRANSACTION;
             }
 
             DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
-            OCProvisionDev_t **ppDevicesList = pDInfo->ppDevicesList;
-
-            OCStackResult res = UpdateSecurePortOfDevice(ppDevicesList, clientResponse->devAddr.addr,
+            OCStackResult res = UpdateSecurePortOfDevice(pDInfo->ppDevicesList,
+                                                         clientResponse->devAddr.addr,
                                                          clientResponse->devAddr.port, securePort);
             if (OC_STACK_OK != res)
             {
-                OC_LOG(ERROR, TAG, "Error while getting secure port.");
+                OIC_LOG(ERROR, TAG, "Error while getting secure port.");
                 return OC_STACK_DELETE_TRANSACTION;
             }
-            OC_LOG(INFO, TAG, "Exiting SecurePortDiscoveryHandler.");
+
+            res = SecurityVersionDiscovery(pDInfo, clientResponse);
+            if(OC_STACK_OK != res)
+            {
+                OIC_LOG(ERROR, TAG, "Failed to SecurityVersionDiscovery");
+                return OC_STACK_DELETE_TRANSACTION;
+            }
+
+            OIC_LOG(INFO, TAG, "Exiting SecurePortDiscoveryHandler.");
         }
 
         return  OC_STACK_DELETE_TRANSACTION;
     }
     else
     {
-        OC_LOG(INFO, TAG, "Skiping Null response");
+        OIC_LOG(INFO, TAG, "Skiping Null response");
     }
+
     return  OC_STACK_DELETE_TRANSACTION;
 }
 
-/**
- * Callback handler for PMDeviceDiscovery API.
- *
- * @param[in] ctx             User context
- * @param[in] handle          Handler for response
- * @param[in] clientResponse  Response information (It will contain payload)
- * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
- *         OC_STACK_DELETE_TRANSACTION to delete it.
- */
 static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
                                 OCClientResponse *clientResponse)
 {
     if (ctx == NULL)
     {
-        OC_LOG(ERROR, TAG, "Lost List of device information");
+        OIC_LOG(ERROR, TAG, "Lost List of device information");
         return OC_STACK_KEEP_TRANSACTION;
     }
     (void)UNUSED;
@@ -474,31 +637,35 @@ static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNU
     {
         if  (NULL == clientResponse->payload)
         {
-            OC_LOG(INFO, TAG, "Skiping Null payload");
+            OIC_LOG(INFO, TAG, "Skiping Null payload");
             return OC_STACK_KEEP_TRANSACTION;
         }
         if (OC_STACK_OK != clientResponse->result)
         {
-            OC_LOG(INFO, TAG, "Error in response");
+            OIC_LOG(INFO, TAG, "Error in response");
             return OC_STACK_KEEP_TRANSACTION;
         }
         else
         {
             if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
             {
-                OC_LOG(INFO, TAG, "Unknown payload type");
+                OIC_LOG(INFO, TAG, "Unknown payload type");
                 return OC_STACK_KEEP_TRANSACTION;
             }
-            OicSecDoxm_t *ptrDoxm = JSONToDoxmBin(
-                            ((OCSecurityPayload*)clientResponse->payload)->securityData);
-            if (NULL == ptrDoxm)
+
+            OicSecDoxm_t *ptrDoxm = NULL;
+            uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
+            size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
+
+            OCStackResult res = CBORPayloadToDoxm(payload, size, &ptrDoxm);
+            if ((NULL == ptrDoxm) || (OC_STACK_OK != res))
             {
-                OC_LOG(INFO, TAG, "Ignoring malformed JSON");
+                OIC_LOG(INFO, TAG, "Ignoring malformed CBOR");
                 return OC_STACK_KEEP_TRANSACTION;
             }
             else
             {
-                OC_LOG(DEBUG, TAG, "Successfully converted doxm json to bin.");
+                OIC_LOG(DEBUG, TAG, "Successfully converted doxm cbor to bin.");
 
                 //If this is owend device discovery we have to filter out the responses.
                 DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
@@ -510,7 +677,7 @@ static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNU
                 OCStackResult res = GetDoxmDevOwnerId(&myId);
                 if(OC_STACK_OK != res)
                 {
-                    OC_LOG(ERROR, TAG, "Error while getting my device ID.");
+                    OIC_LOG(ERROR, TAG, "Error while getting my device ID.");
                     DeleteDoxmBinData(ptrDoxm);
                     return OC_STACK_KEEP_TRANSACTION;
                 }
@@ -519,7 +686,7 @@ static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNU
                 if( (pDInfo->isOwnedDiscovery) &&
                     (0 != memcmp(&ptrDoxm->owner.id, &myId.id, sizeof(myId.id))) )
                 {
-                    OC_LOG(DEBUG, TAG, "Discovered device is not owend by me");
+                    OIC_LOG(DEBUG, TAG, "Discovered device is not owend by me");
                     DeleteDoxmBinData(ptrDoxm);
                     return OC_STACK_KEEP_TRANSACTION;
                 }
@@ -530,47 +697,20 @@ static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNU
                         clientResponse->connType, ptrDoxm);
                 if (OC_STACK_OK != res)
                 {
-                    OC_LOG(ERROR, TAG, "Error while adding data to linkedlist.");
+                    OIC_LOG(ERROR, TAG, "Error while adding data to linkedlist.");
                     DeleteDoxmBinData(ptrDoxm);
                     return OC_STACK_KEEP_TRANSACTION;
                 }
-                char rsrc_uri[MAX_URI_LENGTH+1] = {0};
-                int wr_len = snprintf(rsrc_uri, sizeof(rsrc_uri), "%s?%s=%s",
-                          OC_RSRVD_WELL_KNOWN_URI, OC_RSRVD_RESOURCE_TYPE, OIC_RSRC_TYPE_SEC_DOXM);
-                if(wr_len <= 0 || (size_t)wr_len >= sizeof(rsrc_uri))
-                {
-                    OC_LOG(ERROR, TAG, "rsrc_uri_string_print failed");
-                    return OC_STACK_ERROR;
-                }
-                //Try to the unicast discovery to getting secure port
-                char query[MAX_URI_LENGTH+MAX_QUERY_LENGTH+1] = {0};
-                if(!PMGenerateQuery(false,
-                                    clientResponse->devAddr.addr, clientResponse->devAddr.port,
-                                    clientResponse->connType,
-                                    query, sizeof(query), rsrc_uri))
-                {
-                    OC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
-                    return OC_STACK_KEEP_TRANSACTION;
-                }
-                OC_LOG_V(DEBUG, TAG, "Query=%s", query);
-
-                OCCallbackData cbData;
-                cbData.cb = &SecurePortDiscoveryHandler;
-                cbData.context = ctx;
-                cbData.cd = NULL;
-                OCStackResult ret = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
-                        clientResponse->connType, OC_LOW_QOS, &cbData, NULL, 0);
-                // TODO: Should we use the default secure port in case of error?
-                if(OC_STACK_OK != ret)
+
+                res = SecurePortDiscovery(pDInfo, clientResponse);
+                if(OC_STACK_OK != res)
                 {
-                    OC_LOG(ERROR, TAG, "Failed to Secure Port Discovery");
+                    OIC_LOG(ERROR, TAG, "Failed to SecurePortDiscovery");
+                    DeleteDoxmBinData(ptrDoxm);
                     return OC_STACK_KEEP_TRANSACTION;
                 }
-                else
-                {
-                    OC_LOG_V(INFO, TAG, "OCDoResource with [%s] Success", query);
-                }
-                OC_LOG(INFO, TAG, "Exiting ProvisionDiscoveryHandler.");
+
+                OIC_LOG(INFO, TAG, "Exiting ProvisionDiscoveryHandler.");
             }
 
             return  OC_STACK_KEEP_TRANSACTION;
@@ -578,7 +718,7 @@ static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNU
     }
     else
     {
-        OC_LOG(INFO, TAG, "Skiping Null response");
+        OIC_LOG(INFO, TAG, "Skiping Null response");
         return OC_STACK_KEEP_TRANSACTION;
     }
 
@@ -596,11 +736,11 @@ static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNU
  */
 OCStackResult PMDeviceDiscovery(unsigned short waittime, bool isOwned, OCProvisionDev_t **ppDevicesList)
 {
-    OC_LOG(DEBUG, TAG, "IN PMDeviceDiscovery");
+    OIC_LOG(DEBUG, TAG, "IN PMDeviceDiscovery");
 
     if (NULL != *ppDevicesList)
     {
-        OC_LOG(ERROR, TAG, "List is not null can cause memory leak");
+        OIC_LOG(ERROR, TAG, "List is not null can cause memory leak");
         return OC_STACK_INVALID_PARAM;
     }
 
@@ -610,7 +750,7 @@ OCStackResult PMDeviceDiscovery(unsigned short waittime, bool isOwned, OCProvisi
     DiscoveryInfo *pDInfo = OICCalloc(1, sizeof(DiscoveryInfo));
     if(NULL == pDInfo)
     {
-        OC_LOG(ERROR, TAG, "PMDeviceDiscovery : Memory allocation failed.");
+        OIC_LOG(ERROR, TAG, "PMDeviceDiscovery : Memory allocation failed.");
         return OC_STACK_NO_MEMORY;
     }
 
@@ -631,7 +771,7 @@ OCStackResult PMDeviceDiscovery(unsigned short waittime, bool isOwned, OCProvisi
                                      CT_DEFAULT, OC_LOW_QOS, &cbData, NULL, 0);
     if (res != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack resource error");
+        OIC_LOG(ERROR, TAG, "OCStack resource error");
         OICFree(pDInfo);
         return res;
     }
@@ -640,46 +780,140 @@ OCStackResult PMDeviceDiscovery(unsigned short waittime, bool isOwned, OCProvisi
     res = PMTimeout(waittime, true);
     if(OC_STACK_OK != res)
     {
-        OC_LOG(ERROR, TAG, "Failed to wait response for secure discovery.");
+        OIC_LOG(ERROR, TAG, "Failed to wait response for secure discovery.");
         OICFree(pDInfo);
         OCStackResult resCancel = OCCancel(handle, OC_LOW_QOS, NULL, 0);
         if(OC_STACK_OK !=  resCancel)
         {
-            OC_LOG(ERROR, TAG, "Failed to remove registered callback");
+            OIC_LOG(ERROR, TAG, "Failed to remove registered callback");
         }
         return res;
     }
     res = OCCancel(handle,OC_LOW_QOS,NULL,0);
     if (OC_STACK_OK != res)
     {
-        OC_LOG(ERROR, TAG, "Failed to remove registered callback");
+        OIC_LOG(ERROR, TAG, "Failed to remove registered callback");
         OICFree(pDInfo);
         return res;
     }
-    OC_LOG(DEBUG, TAG, "OUT PMDeviceDiscovery");
+    OIC_LOG(DEBUG, TAG, "OUT PMDeviceDiscovery");
     OICFree(pDInfo);
     return res;
 }
 
+static OCStackResult SecurePortDiscovery(DiscoveryInfo* discoveryInfo,
+                                         const OCClientResponse *clientResponse)
+{
+    OIC_LOG(DEBUG, TAG, "IN SecurePortDiscovery");
+
+    if(NULL == discoveryInfo || NULL == clientResponse)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    char rsrc_uri[MAX_URI_LENGTH+1] = {0};
+    int wr_len = snprintf(rsrc_uri, sizeof(rsrc_uri), "%s?%s=%s",
+              OC_RSRVD_WELL_KNOWN_URI, OC_RSRVD_RESOURCE_TYPE, OIC_RSRC_TYPE_SEC_DOXM);
+    if(wr_len <= 0 || (size_t)wr_len >= sizeof(rsrc_uri))
+    {
+        OIC_LOG(ERROR, TAG, "rsrc_uri_string_print failed");
+        return OC_STACK_ERROR;
+    }
+    //Try to the unicast discovery to getting secure port
+    char query[MAX_URI_LENGTH+MAX_QUERY_LENGTH+1] = {0};
+    if(!PMGenerateQuery(false,
+                        clientResponse->devAddr.addr, clientResponse->devAddr.port,
+                        clientResponse->connType,
+                        query, sizeof(query), rsrc_uri))
+    {
+        OIC_LOG(ERROR, TAG, "SecurePortDiscovery : Failed to generate query");
+        return OC_STACK_ERROR;
+    }
+    OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
+
+    OCCallbackData cbData;
+    cbData.cb = &SecurePortDiscoveryHandler;
+    cbData.context = (void*)discoveryInfo;
+    cbData.cd = NULL;
+    OCStackResult ret = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
+            clientResponse->connType, OC_LOW_QOS, &cbData, NULL, 0);
+    if(OC_STACK_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to Secure Port Discovery");
+        return ret;
+    }
+    else
+    {
+        OIC_LOG_V(INFO, TAG, "OCDoResource with [%s] Success", query);
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT SecurePortDiscovery");
+
+    return ret;
+}
+
+static OCStackResult SecurityVersionDiscovery(DiscoveryInfo* discoveryInfo,
+                                              const OCClientResponse *clientResponse)
+{
+    OIC_LOG(DEBUG, TAG, "IN SecurityVersionDiscovery");
+
+    if(NULL == discoveryInfo || NULL == clientResponse)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    //Try to the unicast discovery to getting security version
+    char query[MAX_URI_LENGTH+MAX_QUERY_LENGTH+1] = {0};
+    if(!PMGenerateQuery(false,
+                        clientResponse->devAddr.addr, clientResponse->devAddr.port,
+                        clientResponse->connType,
+                        query, sizeof(query), OIC_RSRC_VER_URI))
+    {
+        OIC_LOG(ERROR, TAG, "SecurityVersionDiscovery : Failed to generate query");
+        return OC_STACK_ERROR;
+    }
+    OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
+
+    OCCallbackData cbData;
+    cbData.cb = &SecurityVersionDiscoveryHandler;
+    cbData.context = (void*)discoveryInfo;
+    cbData.cd = NULL;
+    OCStackResult ret = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
+            clientResponse->connType, OC_LOW_QOS, &cbData, NULL, 0);
+    if(OC_STACK_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to Security Version Discovery");
+        return ret;
+    }
+    else
+    {
+        OIC_LOG_V(INFO, TAG, "OCDoResource with [%s] Success", query);
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT SecurityVersionDiscovery");
+
+    return ret;
+}
+
 /**
  * Function to print OCProvisionDev_t for debug purpose.
  *
- * @param[in] pDev Pointer to OCProvisionDev_t. It's information will be printed by OC_LOG_XX
+ * @param[in] pDev Pointer to OCProvisionDev_t. It's information will be printed by OIC_LOG_XX
  *
  */
 void PMPrintOCProvisionDev(const OCProvisionDev_t* pDev)
 {
     if (pDev)
     {
-        OC_LOG(DEBUG, TAG, "+++++ OCProvisionDev_t Information +++++");
-        OC_LOG_V(DEBUG, TAG, "IP %s", pDev->endpoint.addr);
-        OC_LOG_V(DEBUG, TAG, "PORT %d", pDev->endpoint.port);
-        OC_LOG_V(DEBUG, TAG, "S-PORT %d", pDev->securePort);
-        OC_LOG(DEBUG, TAG, "++++++++++++++++++++++++++++++++++++++++");
+        OIC_LOG(DEBUG, TAG, "+++++ OCProvisionDev_t Information +++++");
+        OIC_LOG_V(DEBUG, TAG, "IP %s", pDev->endpoint.addr);
+        OIC_LOG_V(DEBUG, TAG, "PORT %d", pDev->endpoint.port);
+        OIC_LOG_V(DEBUG, TAG, "S-PORT %d", pDev->securePort);
+        OIC_LOG(DEBUG, TAG, "++++++++++++++++++++++++++++++++++++++++");
     }
     else
     {
-        OC_LOG(DEBUG, TAG, "+++++ OCProvisionDev_t is NULL +++++");
+        OIC_LOG(DEBUG, TAG, "+++++ OCProvisionDev_t is NULL +++++");
     }
 }
 
index e50b5f8..80b3eb2 100644 (file)
@@ -47,7 +47,7 @@
 #define PDM_BIND_INDEX_THIRD 3
 
 #define PDM_CREATE_T_DEVICE_LIST "create table T_DEVICE_LIST(ID INTEGER PRIMARY KEY AUTOINCREMENT,\
-                                  UUID BLOB NOT NULL UNIQUE);"
+                                  UUID BLOB NOT NULL UNIQUE, STATE INT NOT NULL);"
 
 #define PDM_CREATE_T_DEVICE_LINK  "create table T_DEVICE_LINK_STATE(ID INT NOT NULL, ID2 INT NOT \
                                    NULL,STATE INT NOT NULL, PRIMARY KEY (ID, ID2));"
  * eg: VERIFY_NON_NULL(TAG, ptrData, ERROR,OC_STACK_ERROR);
  */
 #define PDM_VERIFY_SQLITE_OK(tag, arg, logLevel, retValue) do{ if (SQLITE_OK != (arg)) \
-            { OC_LOG_V((logLevel), tag, "Error in " #arg ", Error Message: %s", \
+            { OIC_LOG_V((logLevel), tag, "Error in " #arg ", Error Message: %s", \
                sqlite3_errmsg(g_db)); return retValue; }}while(0)
 
 #define PDM_SQLITE_TRANSACTION_BEGIN "BEGIN TRANSACTION;"
 #define PDM_SQLITE_TRANSACTION_COMMIT "COMMIT;"
 #define PDM_SQLITE_TRANSACTION_ROLLBACK "ROLLBACK;"
 #define PDM_SQLITE_GET_STALE_INFO "SELECT ID,ID2 FROM T_DEVICE_LINK_STATE WHERE STATE = ?"
-#define PDM_SQLITE_INSERT_T_DEVICE_LIST "INSERT INTO T_DEVICE_LIST VALUES(?,?)"
+#define PDM_SQLITE_INSERT_T_DEVICE_LIST "INSERT INTO T_DEVICE_LIST VALUES(?,?,?)"
 #define PDM_SQLITE_GET_ID "SELECT ID FROM T_DEVICE_LIST WHERE UUID like ?"
 #define PDM_SQLITE_INSERT_LINK_DATA "INSERT INTO T_DEVICE_LINK_STATE VALUES(?,?,?)"
 #define PDM_SQLITE_DELETE_LINK "DELETE FROM T_DEVICE_LINK_STATE WHERE ID = ? and ID2 = ?"
 #define PDM_SQLITE_DELETE_DEVICE_LINK "DELETE FROM T_DEVICE_LINK_STATE WHERE ID = ? or ID2 = ?"
 #define PDM_SQLITE_DELETE_DEVICE "DELETE FROM T_DEVICE_LIST  WHERE ID = ?"
 #define PDM_SQLITE_UPDATE_LINK "UPDATE T_DEVICE_LINK_STATE SET STATE = ?  WHERE ID = ? and ID2 = ?"
-#define PDM_SQLITE_LIST_ALL_UUID "SELECT UUID FROM T_DEVICE_LIST"
-#define PDM_SQLITE_GET_UUID "SELECT UUID FROM T_DEVICE_LIST WHERE ID = ?"
-#define PDM_SQLITE_GET_LINKED_DEVICES "SELECT ID,ID2 FROM T_DEVICE_LINK_STATE WHERE ID = ? or ID2 = ?"
-#define PDM_SQLITE_GET_DEVICE_LINKS "SELECT ID,ID2 FROM T_DEVICE_LINK_STATE WHERE ID = ? and ID2 = ?"
+#define PDM_SQLITE_LIST_ALL_UUID "SELECT UUID FROM T_DEVICE_LIST WHERE STATE = 0"
+#define PDM_SQLITE_GET_UUID "SELECT UUID,STATE FROM T_DEVICE_LIST WHERE ID = ?"
+#define PDM_SQLITE_GET_LINKED_DEVICES "SELECT ID,ID2 FROM T_DEVICE_LINK_STATE WHERE \
+                                           (ID = ? or ID2 = ?) and state = 0"
+#define PDM_SQLITE_GET_DEVICE_LINKS "SELECT ID,ID2 FROM T_DEVICE_LINK_STATE WHERE \
+                                          ID = ? and ID2 = ? and state = 0"
+#define PDM_SQLITE_UPDATE_DEVICE "UPDATE T_DEVICE_LIST SET STATE = ?  WHERE UUID like ?"
+#define PDM_SQLITE_GET_DEVICE_STATUS "SELECT STATE FROM T_DEVICE_LIST WHERE UUID like ?"
+#define PDM_SQLITE_UPDATE_LINK_STALE_FOR_STALE_DEVICE "UPDATE T_DEVICE_LINK_STATE SET STATE = 1\
+                                                          WHERE ID = ? or ID2 = ?"
 
 #define ASCENDING_ORDER(id1, id2) do{if( (id1) > (id2) )\
   { int temp; temp = id1; id1 = id2; id2 = temp; }}while(0)
 
 #define CHECK_PDM_INIT(tag) do{if(true != gInit)\
-  { OC_LOG(ERROR, (tag), "PDB is not initialized"); \
+  { OIC_LOG(ERROR, (tag), "PDB is not initialized"); \
     return OC_STACK_PDM_IS_NOT_INITIALIZED; }}while(0)
 
 static sqlite3 *g_db = NULL;
@@ -98,11 +104,11 @@ static OCStackResult createDB(const char* path)
     result = sqlite3_exec(g_db, PDM_CREATE_T_DEVICE_LIST, NULL, NULL, NULL);
     PDM_VERIFY_SQLITE_OK(TAG, result, ERROR, OC_STACK_ERROR);
 
-    OC_LOG(INFO, TAG, "Created T_DEVICE_LIST");
+    OIC_LOG(INFO, TAG, "Created T_DEVICE_LIST");
     result = sqlite3_exec(g_db, PDM_CREATE_T_DEVICE_LINK, NULL, NULL, NULL);
     PDM_VERIFY_SQLITE_OK(TAG, result, ERROR, OC_STACK_ERROR);
 
-    OC_LOG(INFO, TAG, "Created T_DEVICE_LINK_STATE");
+    OIC_LOG(INFO, TAG, "Created T_DEVICE_LINK_STATE");
     gInit = true;
     return OC_STACK_OK;
 }
@@ -149,7 +155,7 @@ void errLogCallback(void *pArg, int iErrCode, const char *zMsg)
     (void) pArg;
     (void) iErrCode;
     (void) zMsg;
-    OC_LOG_V(DEBUG,TAG, "(%d) %s", iErrCode, zMsg);
+    OIC_LOG_V(DEBUG,TAG, "(%d) %s", iErrCode, zMsg);
 }
 
 OCStackResult PDMInit(const char *path)
@@ -158,7 +164,7 @@ OCStackResult PDMInit(const char *path)
     const char *dbPath = NULL;
     if (SQLITE_OK !=  sqlite3_config(SQLITE_CONFIG_LOG, errLogCallback, NULL))
     {
-        OC_LOG(INFO, TAG, "Unable to enable debug log of sqlite");
+        OIC_LOG(INFO, TAG, "Unable to enable debug log of sqlite");
     }
 
     if (NULL == path || !*path)
@@ -172,7 +178,7 @@ OCStackResult PDMInit(const char *path)
     rc = sqlite3_open_v2(dbPath, &g_db, SQLITE_OPEN_READWRITE, NULL);
     if (SQLITE_OK != rc)
     {
-        OC_LOG_V(INFO, TAG, "ERROR: Can't open database: %s", sqlite3_errmsg(g_db));
+        OIC_LOG_V(INFO, TAG, "ERROR: Can't open database: %s", sqlite3_errmsg(g_db));
         return createDB(dbPath);
     }
     gInit = true;
@@ -197,17 +203,20 @@ OCStackResult PDMAddDevice(const OicUuid_t *UUID)
     res = sqlite3_bind_blob(stmt, PDM_BIND_INDEX_SECOND, UUID, UUID_LENGTH, SQLITE_STATIC);
     PDM_VERIFY_SQLITE_OK(TAG, res, ERROR, OC_STACK_ERROR);
 
+    res = sqlite3_bind_int(stmt, PDM_BIND_INDEX_THIRD, PDM_ACTIVE_STATE);
+    PDM_VERIFY_SQLITE_OK(TAG, res, ERROR, OC_STACK_ERROR);
+
     res = sqlite3_step(stmt);
     if (SQLITE_DONE != res)
     {
         if (SQLITE_CONSTRAINT == res)
         {
             //new OCStack result code
-            OC_LOG_V(ERROR, TAG, "Error Occured: %s",sqlite3_errmsg(g_db));
+            OIC_LOG_V(ERROR, TAG, "Error Occured: %s",sqlite3_errmsg(g_db));
             sqlite3_finalize(stmt);
             return OC_STACK_DUPLICATE_UUID;
         }
-        OC_LOG_V(ERROR, TAG, "Error Occured: %s",sqlite3_errmsg(g_db));
+        OIC_LOG_V(ERROR, TAG, "Error Occured: %s",sqlite3_errmsg(g_db));
         sqlite3_finalize(stmt);
         return OC_STACK_ERROR;
     }
@@ -216,6 +225,42 @@ OCStackResult PDMAddDevice(const OicUuid_t *UUID)
 }
 
 /**
+ * Function to check whether device is stale or not
+ */
+static OCStackResult isDeviceStale(const OicUuid_t *uuid, bool *result)
+{
+    if (NULL == uuid || NULL == result)
+    {
+        OIC_LOG(ERROR, TAG, "UUID or result is NULL");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    sqlite3_stmt *stmt = 0;
+    int res = 0;
+    res = sqlite3_prepare_v2(g_db, PDM_SQLITE_GET_DEVICE_STATUS, strlen(PDM_SQLITE_GET_DEVICE_STATUS) + 1,
+                              &stmt, NULL);
+    PDM_VERIFY_SQLITE_OK(TAG, res, ERROR, OC_STACK_ERROR);
+
+    res = sqlite3_bind_blob(stmt, PDM_BIND_INDEX_FIRST, uuid, UUID_LENGTH, SQLITE_STATIC);
+    PDM_VERIFY_SQLITE_OK(TAG, res, ERROR, OC_STACK_ERROR);
+
+    bool retValue = false;
+    while(SQLITE_ROW == sqlite3_step(stmt))
+    {
+        int tempStaleStateFromDb = sqlite3_column_int(stmt, PDM_FIRST_INDEX);
+        OIC_LOG_V(DEBUG, TAG, "Stale state is %d", tempStaleStateFromDb);
+        if (PDM_STALE_STATE == tempStaleStateFromDb)
+        {
+            OIC_LOG(INFO, TAG, "Device is stale");
+            retValue = true;
+        }
+    }
+    *result = retValue;
+    sqlite3_finalize(stmt);
+    return OC_STACK_OK;
+}
+
+/**
  *function to get Id for given UUID
  */
 static OCStackResult getIdForUUID(const OicUuid_t *UUID , int *id)
@@ -228,11 +273,11 @@ static OCStackResult getIdForUUID(const OicUuid_t *UUID , int *id)
     res = sqlite3_bind_blob(stmt, PDM_BIND_INDEX_FIRST, UUID, UUID_LENGTH, SQLITE_STATIC);
     PDM_VERIFY_SQLITE_OK(TAG, res, ERROR, OC_STACK_ERROR);
 
-    OC_LOG(DEBUG, TAG, "Binding Done");
+    OIC_LOG(DEBUG, TAG, "Binding Done");
     while (SQLITE_ROW == sqlite3_step(stmt))
     {
         int tempId = sqlite3_column_int(stmt, PDM_FIRST_INDEX);
-        OC_LOG_V(DEBUG, TAG, "ID is %d", tempId);
+        OIC_LOG_V(DEBUG, TAG, "ID is %d", tempId);
         *id = tempId;
         sqlite3_finalize(stmt);
         return OC_STACK_OK;
@@ -250,7 +295,7 @@ OCStackResult PDMIsDuplicateDevice(const OicUuid_t* UUID, bool *result)
     CHECK_PDM_INIT(TAG);
     if (NULL == UUID || NULL == result)
     {
-        OC_LOG(ERROR, TAG, "UUID or result is NULL");
+        OIC_LOG(ERROR, TAG, "UUID or result is NULL");
         return OC_STACK_INVALID_PARAM;
     }
     sqlite3_stmt *stmt = 0;
@@ -261,11 +306,11 @@ OCStackResult PDMIsDuplicateDevice(const OicUuid_t* UUID, bool *result)
     res = sqlite3_bind_blob(stmt, PDM_BIND_INDEX_FIRST, UUID, UUID_LENGTH, SQLITE_STATIC);
     PDM_VERIFY_SQLITE_OK(TAG, res, ERROR, OC_STACK_ERROR);
 
-    OC_LOG(DEBUG, TAG, "Binding Done");
+    OIC_LOG(DEBUG, TAG, "Binding Done");
     bool retValue = false;
     while(SQLITE_ROW == sqlite3_step(stmt))
     {
-        OC_LOG(INFO, TAG, "Duplicated UUID");
+        OIC_LOG(INFO, TAG, "Duplicated UUID");
         retValue = true;
     }
 
@@ -296,7 +341,7 @@ static OCStackResult addlink(int id1, int id2)
 
     if (sqlite3_step(stmt) != SQLITE_DONE)
     {
-        OC_LOG_V(ERROR, TAG, "Error Occured: %s",sqlite3_errmsg(g_db));
+        OIC_LOG_V(ERROR, TAG, "Error Occured: %s",sqlite3_errmsg(g_db));
         sqlite3_finalize(stmt);
         return OC_STACK_ERROR;
     }
@@ -309,21 +354,46 @@ OCStackResult PDMLinkDevices(const OicUuid_t *UUID1, const OicUuid_t *UUID2)
     CHECK_PDM_INIT(TAG);
     if (NULL == UUID1 || NULL == UUID2)
     {
-        OC_LOG(ERROR, TAG, "Invalid PARAM");
+        OIC_LOG(ERROR, TAG, "Invalid PARAM");
         return  OC_STACK_INVALID_PARAM;
     }
+
+    bool result = false;
+    if (OC_STACK_OK != isDeviceStale(UUID1, &result))
+    {
+        OIC_LOG(ERROR, TAG, "Internal error occured");
+        return OC_STACK_ERROR;
+    }
+    if (result)
+    {
+        OIC_LOG(ERROR, TAG, "UUID1:Stale device");
+        return OC_STACK_INVALID_PARAM;
+    }
+    result = false;
+    if (OC_STACK_OK != isDeviceStale(UUID2, &result))
+    {
+        OIC_LOG(ERROR, TAG, "Internal error occured");
+        return OC_STACK_ERROR;
+    }
+    if (result)
+    {
+        OIC_LOG(ERROR, TAG, "UUID2:Stale device");
+        return OC_STACK_INVALID_PARAM;
+    }
+
     int id1 = 0;
     if (OC_STACK_OK != getIdForUUID(UUID1, &id1))
     {
-        OC_LOG(ERROR, TAG, "Requested value not found");
+        OIC_LOG(ERROR, TAG, "Requested value not found");
         return OC_STACK_INVALID_PARAM;
     }
     int id2 = 0;
     if (OC_STACK_OK != getIdForUUID(UUID2, &id2))
     {
-        OC_LOG(ERROR, TAG, "Requested value not found");
+        OIC_LOG(ERROR, TAG, "Requested value not found");
         return OC_STACK_INVALID_PARAM;
     }
+
     ASCENDING_ORDER(id1, id2);
     return addlink(id1, id2);
 }
@@ -346,7 +416,7 @@ static OCStackResult removeLink(int id1, int id2)
 
     if (SQLITE_DONE != sqlite3_step(stmt))
     {
-        OC_LOG_V(ERROR, TAG, "Error message: %s", sqlite3_errmsg(g_db));
+        OIC_LOG_V(ERROR, TAG, "Error message: %s", sqlite3_errmsg(g_db));
         sqlite3_finalize(stmt);
         return OC_STACK_ERROR;
     }
@@ -359,21 +429,21 @@ OCStackResult PDMUnlinkDevices(const OicUuid_t *UUID1, const OicUuid_t *UUID2)
     CHECK_PDM_INIT(TAG);
     if (NULL == UUID1 || NULL == UUID2)
     {
-        OC_LOG(ERROR, TAG, "Invalid PARAM");
+        OIC_LOG(ERROR, TAG, "Invalid PARAM");
         return  OC_STACK_INVALID_PARAM;
     }
 
     int id1 = 0;
     if (OC_STACK_OK != getIdForUUID(UUID1, &id1))
     {
-        OC_LOG(ERROR, TAG, "Requested value not found");
+        OIC_LOG(ERROR, TAG, "Requested value not found");
         return OC_STACK_INVALID_PARAM;
     }
 
     int id2 = 0;
     if (OC_STACK_OK != getIdForUUID(UUID2, &id2))
     {
-        OC_LOG(ERROR, TAG, "Requested value not found");
+        OIC_LOG(ERROR, TAG, "Requested value not found");
         return OC_STACK_INVALID_PARAM;
     }
     ASCENDING_ORDER(id1, id2);
@@ -393,7 +463,7 @@ static OCStackResult removeFromDeviceList(int id)
 
     if (sqlite3_step(stmt) != SQLITE_DONE)
     {
-        OC_LOG_V(ERROR, TAG, "Error message: %s", sqlite3_errmsg(g_db));
+        OIC_LOG_V(ERROR, TAG, "Error message: %s", sqlite3_errmsg(g_db));
         sqlite3_finalize(stmt);
         return OC_STACK_ERROR;
     }
@@ -411,14 +481,14 @@ OCStackResult PDMDeleteDevice(const OicUuid_t *UUID)
     int id = 0;
     if (OC_STACK_OK != getIdForUUID(UUID, &id))
     {
-        OC_LOG(ERROR, TAG, "Requested value not found");
+        OIC_LOG(ERROR, TAG, "Requested value not found");
         return OC_STACK_INVALID_PARAM;
     }
     begin();
     if(OC_STACK_OK != removeFromDeviceList(id))
     {
         rollback();
-        OC_LOG(ERROR, TAG, "Requested value not found");
+        OIC_LOG(ERROR, TAG, "Requested value not found");
         return OC_STACK_ERROR;
     }
     commit();
@@ -445,7 +515,7 @@ static OCStackResult updateLinkState(int id1, int id2, int state)
 
     if (SQLITE_DONE != sqlite3_step(stmt))
     {
-        OC_LOG_V(ERROR, TAG, "Error message: %s", sqlite3_errmsg(g_db));
+        OIC_LOG_V(ERROR, TAG, "Error message: %s", sqlite3_errmsg(g_db));
         sqlite3_finalize(stmt);
         return OC_STACK_ERROR;
     }
@@ -458,21 +528,21 @@ OCStackResult PDMSetLinkStale(const OicUuid_t* uuidOfDevice1, const OicUuid_t* u
     CHECK_PDM_INIT(TAG);
     if (NULL == uuidOfDevice1 || NULL == uuidOfDevice2)
     {
-        OC_LOG(ERROR, TAG, "Invalid PARAM");
+        OIC_LOG(ERROR, TAG, "Invalid PARAM");
         return  OC_STACK_INVALID_PARAM;
     }
 
     int id1 = 0;
     if (OC_STACK_OK != getIdForUUID(uuidOfDevice1, &id1))
     {
-        OC_LOG(ERROR, TAG, "Requested value not found");
+        OIC_LOG(ERROR, TAG, "Requested value not found");
         return OC_STACK_INVALID_PARAM;
     }
 
     int id2 = 0;
     if (OC_STACK_OK != getIdForUUID(uuidOfDevice2, &id2))
     {
-        OC_LOG(ERROR, TAG, "Requested value not found");
+        OIC_LOG(ERROR, TAG, "Requested value not found");
         return OC_STACK_INVALID_PARAM;
     }
     ASCENDING_ORDER(id1, id2);
@@ -485,7 +555,7 @@ OCStackResult PDMGetOwnedDevices(OCUuidList_t **uuidList, size_t *numOfDevices)
     CHECK_PDM_INIT(TAG);
     if (NULL != *uuidList)
     {
-        OC_LOG(ERROR, TAG, "Not null list will cause memory leak");
+        OIC_LOG(ERROR, TAG, "Not null list will cause memory leak");
         return OC_STACK_INVALID_PARAM;
     }
     sqlite3_stmt *stmt = 0;
@@ -494,16 +564,15 @@ OCStackResult PDMGetOwnedDevices(OCUuidList_t **uuidList, size_t *numOfDevices)
                               strlen(PDM_SQLITE_LIST_ALL_UUID) + 1, &stmt, NULL);
     PDM_VERIFY_SQLITE_OK(TAG, res, ERROR, OC_STACK_ERROR);
 
-    int counter  = 0;
+    size_t counter  = 0;
     while (SQLITE_ROW == sqlite3_step(stmt))
     {
-
         const void *ptr = sqlite3_column_blob(stmt, PDM_FIRST_INDEX);
         OicUuid_t *uid = (OicUuid_t *)ptr;
         OCUuidList_t *temp = (OCUuidList_t *) OICCalloc(1,sizeof(OCUuidList_t));
         if (NULL == temp)
         {
-            OC_LOG_V(ERROR, TAG, "Memory allocation problem");
+            OIC_LOG_V(ERROR, TAG, "Memory allocation problem");
             sqlite3_finalize(stmt);
             return OC_STACK_NO_MEMORY;
         }
@@ -516,7 +585,7 @@ OCStackResult PDMGetOwnedDevices(OCUuidList_t **uuidList, size_t *numOfDevices)
     return OC_STACK_OK;
 }
 
-static OCStackResult getUUIDforId(int id, OicUuid_t *uid)
+static OCStackResult getUUIDforId(int id, OicUuid_t *uid, bool *result)
 {
     sqlite3_stmt *stmt = 0;
     int res = 0;
@@ -531,30 +600,61 @@ static OCStackResult getUUIDforId(int id, OicUuid_t *uid)
     {
         const void *ptr = sqlite3_column_blob(stmt, PDM_FIRST_INDEX);
         memcpy(uid, ptr, sizeof(OicUuid_t));
+
+        int temp = sqlite3_column_int(stmt, PDM_SECOND_INDEX);
+        if(PDM_STALE_STATE == temp)
+        {
+            if(result)
+            {
+                *result = true;
+            }
+        }
+        else
+        {
+            if(result)
+            {
+                *result = false;
+            }
+        }
+        sqlite3_finalize(stmt);
+        return OC_STACK_OK;
     }
     sqlite3_finalize(stmt);
-    return OC_STACK_OK;
+    return OC_STACK_INVALID_PARAM;
 }
 
 OCStackResult PDMGetLinkedDevices(const OicUuid_t *UUID, OCUuidList_t **UUIDLIST, size_t *numOfDevices)
 {
     CHECK_PDM_INIT(TAG);
-    if (NULL != *UUIDLIST)
+    if (NULL == UUID || NULL == numOfDevices || !UUIDLIST)
     {
-        OC_LOG(ERROR, TAG, "Not null list will cause memory leak");
         return OC_STACK_INVALID_PARAM;
     }
-    if (NULL == UUID)
+    if (NULL != *UUIDLIST )
     {
+        OIC_LOG(ERROR, TAG, "Not null list will cause memory leak");
+        return OC_STACK_INVALID_PARAM;
+    }
+    bool result = false;
+    OCStackResult ret = isDeviceStale(UUID, &result);
+    if (OC_STACK_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "Internal error occured");
+        return OC_STACK_ERROR;
+    }
+    if (result)
+    {
+        OIC_LOG(ERROR, TAG, "Device is stale");
         return OC_STACK_INVALID_PARAM;
     }
     int id = 0;
     if (OC_STACK_OK != getIdForUUID(UUID, &id))
     {
-        OC_LOG(ERROR, TAG, "Requested value not found");
+        OIC_LOG(ERROR, TAG, "Requested value not found");
         return OC_STACK_INVALID_PARAM;
     }
 
+
     sqlite3_stmt *stmt = 0;
     int res = 0;
     res = sqlite3_prepare_v2(g_db, PDM_SQLITE_GET_LINKED_DEVICES,
@@ -567,7 +667,7 @@ OCStackResult PDMGetLinkedDevices(const OicUuid_t *UUID, OCUuidList_t **UUIDLIST
     res = sqlite3_bind_int(stmt, PDM_BIND_INDEX_SECOND, id);
     PDM_VERIFY_SQLITE_OK(TAG, res, ERROR, OC_STACK_ERROR);
 
-    int counter  = 0;
+    size_t counter  = 0;
     while (SQLITE_ROW == sqlite3_step(stmt))
     {
         int i1 = sqlite3_column_int(stmt, PDM_FIRST_INDEX);
@@ -576,17 +676,17 @@ OCStackResult PDMGetLinkedDevices(const OicUuid_t *UUID, OCUuidList_t **UUIDLIST
         OicUuid_t temp = {{0,}};
         if (i1 != id)
         {
-            getUUIDforId(i1, &temp);
+            getUUIDforId(i1, &temp, NULL);
         }
         if (i2 != id)
         {
-            getUUIDforId(i2, &temp);
+            getUUIDforId(i2, &temp, NULL);
         }
 
         OCUuidList_t *tempNode = (OCUuidList_t *) OICCalloc(1,sizeof(OCUuidList_t));
         if (NULL == tempNode)
         {
-            OC_LOG(ERROR, TAG, "No Memory");
+            OIC_LOG(ERROR, TAG, "No Memory");
             sqlite3_finalize(stmt);
             return OC_STACK_NO_MEMORY;
         }
@@ -604,7 +704,7 @@ OCStackResult PDMGetToBeUnlinkedDevices(OCPairList_t **staleDevList, size_t *num
     CHECK_PDM_INIT(TAG);
     if (NULL != *staleDevList)
     {
-        OC_LOG(ERROR, TAG, "Not null list will cause memory leak");
+        OIC_LOG(ERROR, TAG, "Not null list will cause memory leak");
         return OC_STACK_INVALID_PARAM;
     }
 
@@ -617,20 +717,20 @@ OCStackResult PDMGetToBeUnlinkedDevices(OCPairList_t **staleDevList, size_t *num
     res = sqlite3_bind_int(stmt, PDM_BIND_INDEX_FIRST, PDM_STALE_STATE);
     PDM_VERIFY_SQLITE_OK(TAG, res, ERROR, OC_STACK_ERROR);
 
-    int counter  = 0;
+    size_t counter  = 0;
     while (SQLITE_ROW == sqlite3_step(stmt))
     {
         int i1 = sqlite3_column_int(stmt, PDM_FIRST_INDEX);
         int i2 = sqlite3_column_int(stmt, PDM_SECOND_INDEX);
         OicUuid_t temp1 = {{0,}};
         OicUuid_t temp2 = {{0,}};;
-        getUUIDforId(i1, &temp1);
-        getUUIDforId(i2, &temp2);
+        getUUIDforId(i1, &temp1, NULL);
+        getUUIDforId(i2, &temp2, NULL);
 
         OCPairList_t *tempNode = (OCPairList_t *) OICCalloc(1, sizeof(OCPairList_t));
         if (NULL == tempNode)
         {
-            OC_LOG(ERROR, TAG, "No Memory");
+            OIC_LOG(ERROR, TAG, "No Memory");
             sqlite3_finalize(stmt);
             return OC_STACK_NO_MEMORY;
         }
@@ -691,13 +791,37 @@ OCStackResult PDMIsLinkExists(const OicUuid_t* uuidOfDevice1, const OicUuid_t* u
     int id2 = 0;
     if (OC_STACK_OK != getIdForUUID(uuidOfDevice1, &id1))
     {
-        OC_LOG(ERROR, TAG, "Requested value not found");
+        OIC_LOG(ERROR, TAG, "Requested value not found");
         return OC_STACK_INVALID_PARAM;
     }
 
     if (OC_STACK_OK != getIdForUUID(uuidOfDevice2, &id2))
     {
-        OC_LOG(ERROR, TAG, "Requested value not found");
+        OIC_LOG(ERROR, TAG, "Requested value not found");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    bool isStale = false;
+    if (OC_STACK_OK != isDeviceStale(uuidOfDevice1, &isStale))
+    {
+        OIC_LOG(ERROR, TAG, "uuidOfDevice1:Internal error occured");
+        return OC_STACK_ERROR;
+    }
+    if (isStale)
+    {
+        OIC_LOG(ERROR, TAG, "uuidOfDevice1:Device is stale");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    isStale = false;
+    if (OC_STACK_OK != isDeviceStale(uuidOfDevice2, &isStale))
+    {
+        OIC_LOG(ERROR, TAG, "uuidOfDevice2:Internal error occured");
+        return OC_STACK_ERROR;
+    }
+    if (isStale)
+    {
+        OIC_LOG(ERROR, TAG, "uuidOfDevice2:Device is stale");
         return OC_STACK_INVALID_PARAM;
     }
 
@@ -718,10 +842,94 @@ OCStackResult PDMIsLinkExists(const OicUuid_t* uuidOfDevice1, const OicUuid_t* u
     bool ret = false;
     while(SQLITE_ROW == sqlite3_step(stmt))
     {
-        OC_LOG(INFO, TAG, "Link already exists between devices");
+        OIC_LOG(INFO, TAG, "Link already exists between devices");
         ret = true;
     }
     sqlite3_finalize(stmt);
     *result = ret;
     return OC_STACK_OK;
 }
+
+static OCStackResult updateDeviceState(const OicUuid_t *uuid, int state)
+{
+    sqlite3_stmt *stmt = 0;
+    int res = 0 ;
+    res = sqlite3_prepare_v2(g_db, PDM_SQLITE_UPDATE_DEVICE,
+                              strlen(PDM_SQLITE_UPDATE_DEVICE) + 1, &stmt, NULL);
+    PDM_VERIFY_SQLITE_OK(TAG, res, ERROR, OC_STACK_ERROR);
+
+    res = sqlite3_bind_int(stmt, PDM_BIND_INDEX_FIRST, state);
+    PDM_VERIFY_SQLITE_OK(TAG, res, ERROR, OC_STACK_ERROR);
+
+    res = sqlite3_bind_blob(stmt, PDM_BIND_INDEX_SECOND, uuid, UUID_LENGTH, SQLITE_STATIC);
+    PDM_VERIFY_SQLITE_OK(TAG, res, ERROR, OC_STACK_ERROR);
+
+    if (SQLITE_DONE != sqlite3_step(stmt))
+    {
+        OIC_LOG_V(ERROR, TAG, "Error message: %s", sqlite3_errmsg(g_db));
+        sqlite3_finalize(stmt);
+        return OC_STACK_ERROR;
+    }
+    sqlite3_finalize(stmt);
+    return OC_STACK_OK;
+}
+
+static OCStackResult updateLinkForStaleDevice(const OicUuid_t *devUuid)
+{
+    sqlite3_stmt *stmt = 0;
+    int res = 0 ;
+
+    int id = 0;
+    if (OC_STACK_OK != getIdForUUID(devUuid, &id))
+    {
+        OIC_LOG(ERROR, TAG, "Requested value not found");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    res = sqlite3_prepare_v2(g_db, PDM_SQLITE_UPDATE_LINK_STALE_FOR_STALE_DEVICE,
+                              strlen(PDM_SQLITE_UPDATE_LINK_STALE_FOR_STALE_DEVICE) + 1,
+                               &stmt, NULL);
+    PDM_VERIFY_SQLITE_OK(TAG, res, ERROR, OC_STACK_ERROR);
+
+    res = sqlite3_bind_int(stmt, PDM_BIND_INDEX_FIRST, id);
+    PDM_VERIFY_SQLITE_OK(TAG, res, ERROR, OC_STACK_ERROR);
+
+    res = sqlite3_bind_int(stmt, PDM_BIND_INDEX_SECOND, id);
+    PDM_VERIFY_SQLITE_OK(TAG, res, ERROR, OC_STACK_ERROR);
+
+    if (SQLITE_DONE != sqlite3_step(stmt))
+    {
+        OIC_LOG_V(ERROR, TAG, "Error message: %s", sqlite3_errmsg(g_db));
+        sqlite3_finalize(stmt);
+        return OC_STACK_ERROR;
+    }
+    sqlite3_finalize(stmt);
+    return OC_STACK_OK;
+}
+
+OCStackResult PDMSetDeviceStale(const OicUuid_t* uuidOfDevice)
+{
+    CHECK_PDM_INIT(TAG);
+    if (NULL == uuidOfDevice)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid PARAM");
+        return  OC_STACK_INVALID_PARAM;
+    }
+    begin();
+    OCStackResult res = updateLinkForStaleDevice(uuidOfDevice);
+    if (OC_STACK_OK != res)
+    {
+        rollback();
+        OIC_LOG(ERROR, TAG, "unable to update links");
+        return res;
+    }
+    res = updateDeviceState(uuidOfDevice, PDM_STALE_STATE);
+    if (OC_STACK_OK != res)
+    {
+        rollback();
+        OIC_LOG(ERROR, TAG, "unable to update device state");
+        return res;
+    }
+    commit();
+    return OC_STACK_OK;
+}
old mode 100755 (executable)
new mode 100644 (file)
index b9761ee..9799ea4
@@ -31,6 +31,7 @@
 #include "srmresourcestrings.h"
 #include "credresource.h"
 #include "doxmresource.h"
+#include "pconfresource.h"
 #include "credentialgenerator.h"
 #include "cainterface.h"
 #include "cJSON.h"
@@ -39,6 +40,7 @@
 #include "provisioningdatabasemanager.h"
 #include "base64.h"
 #include "utlist.h"
+#include "ocpayload.h"
 
 #ifdef __WITH_X509__
 #include "crlresource.h"
  * eg: VERIFY_NON_NULL(TAG, ptrData, ERROR,OC_STACK_ERROR);
  */
 #define VERIFY_NON_NULL(tag, arg, logLevel, retValue) { if (NULL == (arg)) \
-            { OC_LOG((logLevel), tag, #arg " is NULL"); return retValue; } }
+            { OIC_LOG((logLevel), tag, #arg " is NULL"); return retValue; } }
 
 /**
  * Macro to verify success of operation.
  * eg: VERIFY_SUCCESS(TAG, OC_STACK_OK == foo(), ERROR, OC_STACK_ERROR);
  */
 #define VERIFY_SUCCESS(tag, op, logLevel, retValue) { if (!(op)) \
-            {OC_LOG((logLevel), tag, #op " failed!!"); return retValue;} }
+            {OIC_LOG((logLevel), tag, #op " failed!!"); return retValue;} }
 
 /**
  * Structure to carry credential data to callback.
@@ -89,6 +91,19 @@ struct ACLData
     int numOfResults;                           /**< Number of results in result array.**/
 };
 
+/**
+ * Structure to carry PCONF provision API data to callback.
+ */
+typedef struct PconfData PconfData_t;
+struct PconfData
+{
+    void *ctx;                                  /**< Pointer to user context.**/
+    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.**/
+};
+
 // Enum type index for unlink callback.
 typedef enum {
     IDX_FIRST_DEVICE_RES = 0, // index for resulf of the first device
@@ -137,7 +152,7 @@ static void registerResultForCredProvisioning(CredentialData_t *credData,
                                               OCStackResult stackresult, int cause)
 {
 
-   OC_LOG_V(INFO,TAG,"value of credData->numOfResults is %d",credData->numOfResults);
+   OIC_LOG_V(INFO,TAG,"value of credData->numOfResults is %d",credData->numOfResults);
    if(1 == cause)
    {
        memcpy(credData->resArr[(credData->numOfResults)].deviceId.id,
@@ -169,7 +184,7 @@ static OCStackApplicationResult provisionCredentialCB2(void *ctx, OCDoHandle UNU
     (void)UNUSED;
 
     OCProvisionResultCB resultCallback = credData->resultCallback;
-    OC_LOG(INFO, TAG, "provisionCredentialCB2 called");
+    OIC_LOG(INFO, TAG, "provisionCredentialCB2 called");
     if (clientResponse)
     {
         if(OC_STACK_RESOURCE_CREATED == clientResponse->result)
@@ -179,10 +194,10 @@ static OCStackApplicationResult provisionCredentialCB2(void *ctx, OCDoHandle UNU
                     &credData->deviceInfo2->doxm->deviceID);
             if (OC_STACK_OK != res)
             {
-                OC_LOG(ERROR, TAG, "Error occured on PDMLinkDevices");
+                OIC_LOG(ERROR, TAG, "Error occured on PDMLinkDevices");
                 return OC_STACK_DELETE_TRANSACTION;
             }
-            OC_LOG(INFO, TAG, "Link created successfully");
+            OIC_LOG(INFO, TAG, "Link created successfully");
 
             ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
                                                     credData->resArr,
@@ -193,7 +208,7 @@ static OCStackApplicationResult provisionCredentialCB2(void *ctx, OCDoHandle UNU
         }
 
     }
-    OC_LOG(INFO, TAG, "provisionCredentialCB2 received Null clientResponse");
+    OIC_LOG(INFO, TAG, "provisionCredentialCB2 received Null clientResponse");
     registerResultForCredProvisioning(credData, OC_STACK_ERROR, 2);
     ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
                                             credData->resArr,
@@ -255,7 +270,7 @@ static OCStackApplicationResult provisionCredentialCB1(void *ctx, OCDoHandle UNU
     }
     else
     {
-        OC_LOG(INFO, TAG, "provisionCredentialCB received Null clientResponse for first device");
+        OIC_LOG(INFO, TAG, "provisionCredentialCB received Null clientResponse for first device");
         registerResultForCredProvisioning(credData, OC_STACK_ERROR,1);
        ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
                                                      credData->resArr,
@@ -283,21 +298,22 @@ static OCStackResult provisionCredentials(const OicSecCred_t *cred,
         OCClientResponseHandler responseHandler)
 {
     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
-    if(!secPayload)
+    if (!secPayload)
     {
-        OC_LOG(ERROR, TAG, "Failed to memory allocation");
+        OIC_LOG(ERROR, TAG, "Failed to memory allocation");
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    secPayload->securityData = BinToCredJSON(cred);
-    if(NULL == secPayload->securityData)
+    OCStackResult res = CredToCBORPayload(cred, &secPayload->securityData, &secPayload->payloadSize);
+    if((OC_STACK_OK != res) && (NULL == secPayload->securityData))
     {
-        OICFree(secPayload);
-        OC_LOG(ERROR, TAG, "Failed to BinToCredJSON");
+        OCPayloadDestroy((OCPayload *)secPayload);
+        OIC_LOG(ERROR, TAG, "Failed to CredToCBORPayload");
         return OC_STACK_NO_MEMORY;
     }
 
-    OC_LOG_V(INFO, TAG, "Credential for provisioning : %s",secPayload->securityData);
+    OIC_LOG(DEBUG, TAG, "Created payload for Cred:");
+    OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
     if(!PMGenerateQuery(true,
                         deviceInfo->endpoint.addr,
@@ -305,10 +321,10 @@ static OCStackResult provisionCredentials(const OicSecCred_t *cred,
                         deviceInfo->connType,
                         query, sizeof(query), OIC_RSRC_CRED_URI))
     {
-        OC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
+        OIC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
         return OC_STACK_ERROR;
     }
-    OC_LOG_V(DEBUG, TAG, "Query=%s", query);
+    OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
 
     OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
     cbData.cb = responseHandler;
@@ -319,10 +335,10 @@ static OCStackResult provisionCredentials(const OicSecCred_t *cred,
     OCMethod method = OC_REST_POST;
     OCStackResult ret = OCDoResource(&handle, method, query, 0, (OCPayload*)secPayload,
             deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
-    OC_LOG_V(INFO, TAG, "OCDoResource::Credential provisioning returned : %d",ret);
+    OIC_LOG_V(INFO, TAG, "OCDoResource::Credential provisioning returned : %d",ret);
     if (ret != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack resource error");
+        OIC_LOG(ERROR, TAG, "OCStack resource error");
         return ret;
     }
     return OC_STACK_OK;
@@ -363,7 +379,7 @@ static void registerResultForCertProvisioning(CertData_t *certData,
                                               OCStackResult stackresult)
 {
 
-   OC_LOG_V(INFO,TAG,"value of credData->numOfResults is %d",certData->numOfResults);
+   OIC_LOG_V(INFO,TAG,"value of credData->numOfResults is %d",certData->numOfResults);
    memcpy(certData->resArr[(certData->numOfResults)].deviceId.id,
           certData->deviceInfo->doxm->deviceID.id,UUID_LENGTH);
    certData->resArr[(certData->numOfResults)].res = stackresult;
@@ -376,7 +392,7 @@ static void registerResultForCertProvisioning(CertData_t *certData,
 static void registerResultForCRLProvisioning(CRLData_t *crlData,
                                              OCStackResult stackresult)
 {
-   OC_LOG_V(INFO, TAG, "Inside registerResultForCRLProvisioning crlData->numOfResults is %d\n",
+   OIC_LOG_V(INFO, TAG, "Inside registerResultForCRLProvisioning crlData->numOfResults is %d\n",
                        crlData->numOfResults);
    memcpy(crlData->resArr[(crlData->numOfResults)].deviceId.id,
           crlData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
@@ -397,7 +413,7 @@ static void registerResultForCRLProvisioning(CRLData_t *crlData,
 static OCStackApplicationResult SRPProvisionCRLCB(void *ctx, OCDoHandle UNUSED,
                                                   OCClientResponse *clientResponse)
 {
-    OC_LOG_V(INFO, TAG, "Inside SRPProvisionCRLCB.");
+    OIC_LOG_V(INFO, TAG, "Inside SRPProvisionCRLCB.");
     (void)UNUSED;
     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
     CRLData_t *crlData = (CRLData_t*)ctx;
@@ -420,7 +436,7 @@ static OCStackApplicationResult SRPProvisionCRLCB(void *ctx, OCDoHandle UNUSED,
     ((OCProvisionResultCB)(resultCallback))(crlData->ctx, crlData->numOfResults,
                                             crlData->resArr,
                                             true);
-    OC_LOG_V(ERROR, TAG, "SRPProvisionCRLCB received Null clientResponse");
+    OIC_LOG_V(ERROR, TAG, "SRPProvisionCRLCB received Null clientResponse");
     OICFree(crlData->resArr);
     OICFree(crlData);
     return OC_STACK_DELETE_TRANSACTION;
@@ -436,19 +452,20 @@ OCStackResult SRPProvisionCRL(void *ctx, const OCProvisionDev_t *selectedDeviceI
     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
     if (!secPayload)
     {
-        OC_LOG(ERROR, TAG, "Failed to memory allocation");
+        OIC_LOG(ERROR, TAG, "Failed to memory allocation");
         return OC_STACK_NO_MEMORY;
     }
 
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    secPayload->securityData = BinToCrlJSON(crl);
-    if (NULL == secPayload->securityData)
+    OCStackResult res = CrlToCBORPayload(crl, &secPayload->securityData, &secPayload->payloadSize);
+    if((OC_STACK_OK != res) && (NULL == secPayload->securityData))
     {
         OICFree(secPayload);
-        OC_LOG(ERROR, TAG, "Failed to BinToCrlJSON");
+        OIC_LOG(ERROR, TAG, "Failed to BinToCrlJSON");
         return OC_STACK_NO_MEMORY;
     }
-    OC_LOG_V(INFO, TAG, "CRL : %s", secPayload->securityData);
+    OIC_LOG(DEBUG, TAG, "Created payload for CRL:");
+    OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
 
     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
     if(!PMGenerateQuery(true,
@@ -457,21 +474,19 @@ OCStackResult SRPProvisionCRL(void *ctx, const OCProvisionDev_t *selectedDeviceI
                         selectedDeviceInfo->connType,
                         query, sizeof(query), OIC_RSRC_CRL_URI))
     {
-        OC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
-        OICFree(secPayload->securityData);
-        OICFree(secPayload);
+        OIC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
+        OCPayloadDestroy((OCPayload *)secPayload);
         return OC_STACK_ERROR;
     }
-    OC_LOG_V(DEBUG, TAG, "Query=%s", query);
+    OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
 
     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
     cbData.cb = &SRPProvisionCRLCB;
     CRLData_t *crlData = (CRLData_t *) OICCalloc(1, sizeof(CRLData_t));
     if (crlData == NULL)
     {
-        OICFree(secPayload->securityData);
-        OICFree(secPayload);
-        OC_LOG(ERROR, TAG, "Unable to allocate memory");
+        OCPayloadDestroy((OCPayload *)secPayload);
+        OIC_LOG(ERROR, TAG, "Unable to allocate memory");
         return OC_STACK_NO_MEMORY;
     }
 
@@ -483,9 +498,8 @@ OCStackResult SRPProvisionCRL(void *ctx, const OCProvisionDev_t *selectedDeviceI
     crlData->resArr = (OCProvisionResult_t*)OICCalloc(1, sizeof(OCProvisionResult_t));
     if (crlData->resArr == NULL)
     {
-        OICFree(secPayload->securityData);
-        OICFree(secPayload);
-        OC_LOG(ERROR, TAG, "Unable to allocate memory");
+        OCPayloadDestroy((OCPayload *)secPayload);
+        OIC_LOG(ERROR, TAG, "Unable to allocate memory");
         return OC_STACK_NO_MEMORY;
     }
 
@@ -493,7 +507,7 @@ OCStackResult SRPProvisionCRL(void *ctx, const OCProvisionDev_t *selectedDeviceI
     cbData.cd = NULL;
     OCMethod method = OC_REST_POST;
     OCDoHandle handle = NULL;
-    OC_LOG(DEBUG, TAG, "Sending CRL info to resource server");
+    OIC_LOG(DEBUG, TAG, "Sending CRL info to resource server");
 
     OCStackResult ret = OCDoResource(&handle, method, query,
             &selectedDeviceInfo->endpoint, (OCPayload*)secPayload,
@@ -523,20 +537,22 @@ static OCStackResult provisionCertCred(const OicSecCred_t *cred,
     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
     if(!secPayload)
     {
-        OC_LOG(ERROR, TAG, "Failed to memory allocation");
+        OIC_LOG(ERROR, TAG, "Failed to memory allocation");
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    secPayload->securityData = BinToCredJSON(cred);
+    OCStackResult res = CredToCBORPayload(cred, &secPayload->securityData,
+        &secPayload->payloadSize);
 
-    if (NULL == secPayload->securityData)
+    if ((OC_STACK_OK != res) || (NULL == secPayload->securityData))
     {
         OICFree(secPayload);
-        OC_LOG(ERROR, TAG, "Failed to BinToCredJSON");
+        OIC_LOG(ERROR, TAG, "Failed to CredToCBORPayload");
         return OC_STACK_NO_MEMORY;
     }
 
-    OC_LOG_V(INFO, TAG, "Credential for provisioning : %s",secPayload->securityData);
+    OIC_LOG(DEBUG, TAG, "Created payload for Cred:");
+    OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
     if(!PMGenerateQuery(true,
                         deviceInfo->endpoint.addr,
@@ -544,12 +560,11 @@ static OCStackResult provisionCertCred(const OicSecCred_t *cred,
                         deviceInfo->connType,
                         query, sizeof(query), OIC_RSRC_CRED_URI))
     {
-        OC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
-        OICFree(secPayload->securityData);
-        OICFree(secPayload);
+        OIC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
+        OCPayloadDestroy((OCPayload *)secPayload);
         return OC_STACK_ERROR;
     }
-    OC_LOG_V(DEBUG, TAG, "Query=%s", query);
+    OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
 
     OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
     cbData.cb = responseHandler;
@@ -560,10 +575,10 @@ static OCStackResult provisionCertCred(const OicSecCred_t *cred,
     OCMethod method = OC_REST_POST;
     OCStackResult ret = OCDoResource(&handle, method, query, 0, (OCPayload*)secPayload,
             deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
-    OC_LOG_V(INFO, TAG, "OCDoResource::Certificate provisioning returned : %d",ret);
+    OIC_LOG_V(INFO, TAG, "OCDoResource::Certificate provisioning returned : %d",ret);
     if (ret != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack resource error");
+        OIC_LOG(ERROR, TAG, "OCStack resource error");
     }
 
     return ret;
@@ -586,7 +601,7 @@ static OCStackApplicationResult provisionCertCB(void *ctx, OCDoHandle UNUSED,
     (void)UNUSED;
 
     OCProvisionResultCB resultCallback = certData->resultCallback;
-    OC_LOG(INFO, TAG, "provisionCertCred called");
+    OIC_LOG(INFO, TAG, "provisionCertCred called");
     if (clientResponse)
     {
         if(OC_STACK_RESOURCE_CREATED == clientResponse->result)
@@ -601,7 +616,7 @@ static OCStackApplicationResult provisionCertCB(void *ctx, OCDoHandle UNUSED,
         }
 
     }
-    OC_LOG(INFO, TAG, "provisionCertCredCB received Null clientResponse");
+    OIC_LOG(INFO, TAG, "provisionCertCredCB received Null clientResponse");
     registerResultForCertProvisioning(certData, OC_STACK_ERROR);
     ((OCProvisionResultCB)(resultCallback))(certData->ctx, certData->numOfResults,
                                             certData->resArr,
@@ -622,16 +637,26 @@ OCStackResult SRPProvisionCredentials(void *ctx, OicSecCredType_t type, size_t k
     {
         VERIFY_NON_NULL(TAG, pDev2, ERROR,  OC_STACK_INVALID_PARAM);
     }
-    VERIFY_NON_NULL(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
+    if (!resultCallback)
+    {
+        OIC_LOG(INFO, TAG, "SRPUnlinkDevices : NULL Callback");
+        return OC_STACK_INVALID_CALLBACK;
+    }
+    if (SYMMETRIC_PAIR_WISE_KEY == type &&
+        0 == memcmp(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, sizeof(OicUuid_t)))
+    {
+        OIC_LOG(INFO, TAG, "SRPUnlinkDevices : Same device ID");
+        return OC_STACK_INVALID_PARAM;
+    }
 
     if (SYMMETRIC_PAIR_WISE_KEY == type &&
        !(OWNER_PSK_LENGTH_128 == keySize || OWNER_PSK_LENGTH_256 == keySize))
     {
-        OC_LOG(INFO, TAG, "Invalid key size");
+        OIC_LOG(INFO, TAG, "Invalid key size");
         return OC_STACK_INVALID_PARAM;
     }
 
-    OC_LOG(INFO, TAG, "In SRPProvisionCredentials");
+    OIC_LOG(INFO, TAG, "In SRPProvisionCredentials");
 
     if (SYMMETRIC_PAIR_WISE_KEY == type)
     {
@@ -640,12 +665,12 @@ OCStackResult SRPProvisionCredentials(void *ctx, OicSecCredType_t type, size_t k
 
         if (res != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "Internal error occured");
+            OIC_LOG(ERROR, TAG, "Internal error occured");
             return res;
         }
         if (linkExisits)
         {
-            OC_LOG(ERROR, TAG, "Link already exists");
+            OIC_LOG(ERROR, TAG, "Link already exists");
             return OC_STACK_INVALID_PARAM;
         }
     }
@@ -653,10 +678,10 @@ OCStackResult SRPProvisionCredentials(void *ctx, OicSecCredType_t type, size_t k
     OicUuid_t provTooldeviceID =   {{0,}};
     if (OC_STACK_OK != GetDoxmDeviceID(&provTooldeviceID))
     {
-        OC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
+        OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
         return OC_STACK_ERROR;
     }
-    OC_LOG(INFO, TAG, "retrieved deviceid");
+    OIC_LOG(INFO, TAG, "retrieved deviceid");
     switch (type)
     {
         case SYMMETRIC_PAIR_WISE_KEY:
@@ -670,14 +695,14 @@ OCStackResult SRPProvisionCredentials(void *ctx, OicSecCredType_t type, size_t k
                     &firstDevice->doxm->deviceID, &secondDevice->doxm->deviceID,
                     &firstCred, &secondCred);
             VERIFY_SUCCESS(TAG, (res==OC_STACK_OK), ERROR, OC_STACK_ERROR);
-            OC_LOG(INFO, TAG, "Credentials generated successfully");
+            OIC_LOG(INFO, TAG, "Credentials generated successfully");
             CredentialData_t *credData =
                 (CredentialData_t *) OICCalloc(1, sizeof(CredentialData_t));
             if (NULL == credData)
             {
                 OICFree(firstCred);
                 OICFree(secondCred);
-                OC_LOG(ERROR, TAG, "Memory allocation problem");
+                OIC_LOG(ERROR, TAG, "Memory allocation problem");
                 return OC_STACK_NO_MEMORY;
             }
             credData->deviceInfo1 = firstDevice;
@@ -697,7 +722,7 @@ OCStackResult SRPProvisionCredentials(void *ctx, OicSecCredType_t type, size_t k
                 OICFree(firstCred);
                 OICFree(secondCred);
                 OICFree(credData);
-                OC_LOG(ERROR, TAG, "Memory allocation problem");
+                OIC_LOG(ERROR, TAG, "Memory allocation problem");
                 return OC_STACK_NO_MEMORY;
             }
             res = provisionCredentials(firstCred, firstDevice, credData, &provisionCredentialCB1);
@@ -708,7 +733,7 @@ OCStackResult SRPProvisionCredentials(void *ctx, OicSecCredType_t type, size_t k
                 OICFree(credData->resArr);
                 OICFree(credData);
             }
-            OC_LOG_V(INFO, TAG, "provisionCredentials returned: %d",res);
+            OIC_LOG_V(INFO, TAG, "provisionCredentials returned: %d",res);
             VERIFY_SUCCESS(TAG, (res==OC_STACK_OK), ERROR, OC_STACK_ERROR);
             return res;
         }
@@ -720,12 +745,12 @@ OCStackResult SRPProvisionCredentials(void *ctx, OicSecCredType_t type, size_t k
             OCStackResult res = PMGenerateCertificateCredentials(&provTooldeviceID,
                                                                 &firstDevice->doxm->deviceID,&cred);
             VERIFY_SUCCESS(TAG, (res==OC_STACK_OK), ERROR, OC_STACK_ERROR);
-            OC_LOG(INFO, TAG, "Certificate credentials generated successfully");
+            OIC_LOG(INFO, TAG, "Certificate credentials generated successfully");
             CertData_t *certData = (CertData_t *) OICCalloc(1, sizeof(CertData_t));
             if (NULL == certData)
             {
                 OICFree(cred);
-                OC_LOG(ERROR, TAG, "Memory allocation problem");
+                OIC_LOG(ERROR, TAG, "Memory allocation problem");
                 return OC_STACK_NO_MEMORY;
             }
 
@@ -740,7 +765,7 @@ OCStackResult SRPProvisionCredentials(void *ctx, OicSecCredType_t type, size_t k
             {
                 DeleteCredList(cred);
                 OICFree(certData);
-                OC_LOG(ERROR, TAG, "Memory allocation problem");
+                OIC_LOG(ERROR, TAG, "Memory allocation problem");
                 return OC_STACK_NO_MEMORY;
             }
 
@@ -751,14 +776,14 @@ OCStackResult SRPProvisionCredentials(void *ctx, OicSecCredType_t type, size_t k
                 OICFree(certData);
             }
             DeleteCredList(cred);
-            OC_LOG_V(INFO, TAG, "provisionCertCredentials returned: %d",res);
+            OIC_LOG_V(INFO, TAG, "provisionCertCredentials returned: %d",res);
 
             return res;
         }
 #endif
         default:
         {
-            OC_LOG(ERROR, TAG, "Invalid option.");
+            OIC_LOG(ERROR, TAG, "Invalid option.");
             return OC_STACK_INVALID_PARAM;
         }
     }
@@ -771,7 +796,7 @@ OCStackResult SRPProvisionCredentials(void *ctx, OicSecCredType_t type, size_t k
 static void registerResultForACLProvisioning(ACLData_t *aclData,
                                              OCStackResult stackresult)
 {
-   OC_LOG_V(INFO, TAG, "Inside registerResultForACLProvisioning aclData->numOfResults is %d\n",
+   OIC_LOG_V(INFO, TAG, "Inside registerResultForACLProvisioning aclData->numOfResults is %d\n",
                        aclData->numOfResults);
    memcpy(aclData->resArr[(aclData->numOfResults)].deviceId.id,
           aclData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
@@ -791,7 +816,7 @@ static void registerResultForACLProvisioning(ACLData_t *aclData,
 static OCStackApplicationResult SRPProvisionACLCB(void *ctx, OCDoHandle UNUSED,
                                                   OCClientResponse *clientResponse)
 {
-    OC_LOG_V(INFO, TAG, "Inside SRPProvisionACLCB.");
+    OIC_LOG_V(INFO, TAG, "Inside SRPProvisionACLCB.");
     (void)UNUSED;
     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
     ACLData_t *aclData = (ACLData_t*)ctx;
@@ -814,7 +839,7 @@ static OCStackApplicationResult SRPProvisionACLCB(void *ctx, OCDoHandle UNUSED,
     ((OCProvisionResultCB)(resultCallback))(aclData->ctx, aclData->numOfResults,
                                             aclData->resArr,
                                             true);
-    OC_LOG_V(ERROR, TAG, "SRPProvisionACLCB received Null clientResponse");
+    OIC_LOG_V(ERROR, TAG, "SRPProvisionACLCB received Null clientResponse");
     OICFree(aclData->resArr);
     OICFree(aclData);
     return OC_STACK_DELETE_TRANSACTION;
@@ -830,19 +855,16 @@ OCStackResult SRPProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceI
     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
     if(!secPayload)
     {
-        OC_LOG(ERROR, TAG, "Failed to memory allocation");
+        OIC_LOG(ERROR, TAG, "Failed to memory allocation");
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    secPayload->securityData = BinToAclJSON(acl);
-    if(NULL == secPayload->securityData)
+    if(OC_STACK_OK != AclToCBORPayload(acl, &secPayload->securityData, &secPayload->payloadSize))
     {
-        OICFree(secPayload);
-        OC_LOG(ERROR, TAG, "Failed to BinToAclJSON");
+        OCPayloadDestroy((OCPayload *)secPayload);
+        OIC_LOG(ERROR, TAG, "Failed to AclToCBORPayload");
         return OC_STACK_NO_MEMORY;
     }
-    OC_LOG_V(INFO, TAG, "ACL : %s", secPayload->securityData);
-
     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
     if(!PMGenerateQuery(true,
                         selectedDeviceInfo->endpoint.addr,
@@ -850,19 +872,18 @@ OCStackResult SRPProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceI
                         selectedDeviceInfo->connType,
                         query, sizeof(query), OIC_RSRC_ACL_URI))
     {
-        OC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
+        OIC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
         return OC_STACK_ERROR;
     }
-    OC_LOG_V(DEBUG, TAG, "Query=%s", query);
+    OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
 
     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
     cbData.cb = &SRPProvisionACLCB;
     ACLData_t *aclData = (ACLData_t *) OICCalloc(1, sizeof(ACLData_t));
     if (aclData == NULL)
     {
-        OICFree(secPayload->securityData);
-        OICFree(secPayload);
-        OC_LOG(ERROR, TAG, "Unable to allocate memory");
+        OCPayloadDestroy((OCPayload *)secPayload);
+        OIC_LOG(ERROR, TAG, "Unable to allocate memory");
         return OC_STACK_NO_MEMORY;
     }
     aclData->deviceInfo = selectedDeviceInfo;
@@ -875,16 +896,15 @@ OCStackResult SRPProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceI
     if (aclData->resArr == NULL)
     {
         OICFree(aclData);
-        OICFree(secPayload->securityData);
-        OICFree(secPayload);
-        OC_LOG(ERROR, TAG, "Unable to allocate memory");
+        OCPayloadDestroy((OCPayload *)secPayload);
+        OIC_LOG(ERROR, TAG, "Unable to allocate memory");
         return OC_STACK_NO_MEMORY;
     }
     cbData.context = (void *)aclData;
     cbData.cd = NULL;
     OCMethod method = OC_REST_POST;
     OCDoHandle handle = NULL;
-    OC_LOG(DEBUG, TAG, "Sending ACL info to resource server");
+    OIC_LOG(DEBUG, TAG, "Sending ACL info to resource server");
     OCStackResult ret = OCDoResource(&handle, method, query,
             &selectedDeviceInfo->endpoint, (OCPayload*)secPayload,
             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
@@ -897,6 +917,154 @@ OCStackResult SRPProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceI
     return OC_STACK_OK;
 }
 
+/**
+ * Internal Function to store results in result array during Direct-Pairing provisioning.
+ */
+static void registerResultForDirectPairingProvisioning(PconfData_t *pconfData,
+                                             OCStackResult stackresult)
+{
+   OIC_LOG_V(INFO, TAG, "Inside registerResultForDirectPairingProvisioning "
+           "pconfData->numOfResults is %d\n", pconfData->numOfResults);
+   memcpy(pconfData->resArr[(pconfData->numOfResults)].deviceId.id,
+          pconfData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
+   pconfData->resArr[(pconfData->numOfResults)].res = stackresult;
+   ++(pconfData->numOfResults);
+}
+
+/**
+ * Callback handler of SRPProvisionDirectPairing.
+ *
+ * @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 SRPProvisionDirectPairingCB(void *ctx, OCDoHandle UNUSED,
+                                                  OCClientResponse *clientResponse)
+{
+    OIC_LOG_V(INFO, TAG, "Inside SRPProvisionDirectPairingCB.");
+    (void)UNUSED;
+    VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
+    PconfData_t *pconfData = (PconfData_t*)ctx;
+    OCProvisionResultCB resultCallback = pconfData->resultCallback;
+
+    if (clientResponse)
+    {
+        if(OC_STACK_RESOURCE_CREATED == clientResponse->result)
+        {
+            registerResultForDirectPairingProvisioning(pconfData, OC_STACK_OK);
+            ((OCProvisionResultCB)(resultCallback))(pconfData->ctx, pconfData->numOfResults,
+                                                    pconfData->resArr,
+                                                    false);
+             OICFree(pconfData->resArr);
+             OICFree(pconfData);
+             return OC_STACK_DELETE_TRANSACTION;
+        }
+    }
+    registerResultForDirectPairingProvisioning(pconfData, OC_STACK_ERROR);
+    ((OCProvisionResultCB)(resultCallback))(pconfData->ctx, pconfData->numOfResults,
+                                            pconfData->resArr,
+                                            true);
+    OIC_LOG_V(ERROR, TAG, "SRPProvisionDirectPairingCB received Null clientResponse");
+    OICFree(pconfData->resArr);
+    OICFree(pconfData);
+    return OC_STACK_DELETE_TRANSACTION;
+}
+
+OCStackResult SRPProvisionDirectPairing(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
+        OicSecPconf_t *pconf, OCProvisionResultCB resultCallback)
+{
+    VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL(TAG, pconf, ERROR,  OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
+
+    // check direct-pairing capability
+    if (true != selectedDeviceInfo->doxm->dpc)
+    {
+        OIC_LOG(ERROR, TAG, "Resouce server does not have Direct-Pairing Capability ");
+        return OC_STACK_UNAUTHORIZED_REQ;
+    }
+
+    OicUuid_t provTooldeviceID =   {.id={0}};
+    if (OC_STACK_OK != GetDoxmDeviceID(&provTooldeviceID))
+    {
+        OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
+        return OC_STACK_ERROR;
+    }
+    memcpy(&pconf->rownerID, &provTooldeviceID, sizeof(OicUuid_t));
+
+    OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
+    if(!secPayload)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to memory allocation");
+        return OC_STACK_NO_MEMORY;
+    }
+    secPayload->base.type = PAYLOAD_TYPE_SECURITY;
+
+    if (OC_STACK_OK != PconfToCBORPayload(pconf, &(secPayload->securityData),
+                &(secPayload->payloadSize)))
+    {
+        OCPayloadDestroy((OCPayload*)secPayload);
+        OIC_LOG(ERROR, TAG, "Failed to PconfToCborPayload");
+        return OC_STACK_NO_MEMORY;
+    }
+    OIC_LOG(DEBUG, TAG, "Created payload for pconf set");
+    OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
+
+
+    char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
+    if(!PMGenerateQuery(true,
+                selectedDeviceInfo->endpoint.addr,
+                selectedDeviceInfo->securePort,
+                selectedDeviceInfo->connType,
+                query, sizeof(query), OIC_RSRC_PCONF_URI))
+    {
+        OIC_LOG(ERROR, TAG, "SRPProvisionDirectPairing : 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 = &SRPProvisionDirectPairingCB;
+    PconfData_t *pconfData = (PconfData_t *) OICCalloc(1, sizeof(PconfData_t));
+    if (NULL == pconfData)
+    {
+        OCPayloadDestroy((OCPayload*)secPayload);
+        OIC_LOG(ERROR, TAG, "Unable to allocate memory");
+        return OC_STACK_NO_MEMORY;
+    }
+    pconfData->deviceInfo = selectedDeviceInfo;
+    pconfData->resultCallback = resultCallback;
+    pconfData->numOfResults=0;
+    pconfData->ctx = ctx;
+    // call to provision PCONF to device1.
+    int noOfRiCalls = 1;
+    pconfData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
+    if (NULL == pconfData->resArr)
+    {
+        OICFree(pconfData);
+        OCPayloadDestroy((OCPayload*)secPayload);
+        OIC_LOG(ERROR, TAG, "Unable to allocate memory");
+        return OC_STACK_NO_MEMORY;
+    }
+    cbData.context = (void *)pconfData;
+    cbData.cd = NULL;
+    OCMethod method = OC_REST_POST;
+    OCDoHandle handle = NULL;
+    OIC_LOG(DEBUG, TAG, "Sending PCONF info to resource server");
+    OCStackResult ret = OCDoResource(&handle, method, query,
+            &selectedDeviceInfo->endpoint, (OCPayload*)secPayload,
+            selectedDeviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
+    if (OC_STACK_OK != ret)
+    {
+        OICFree(pconfData->resArr);
+        OICFree(pconfData);
+    }
+    VERIFY_SUCCESS(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
+    return OC_STACK_OK;
+}
+
 static void DeleteUnlinkData_t(UnlinkData_t *unlinkData)
 {
     if (unlinkData)
@@ -912,9 +1080,9 @@ static void registerResultForUnlinkDevices(UnlinkData_t *unlinkData, OCStackResu
 {
     if (NULL != unlinkData)
     {
-        OC_LOG_V(INFO, TAG, "Inside registerResultForUnlinkDevices unlinkData->numOfResults is %d\n",
+        OIC_LOG_V(INFO, TAG, "Inside registerResultForUnlinkDevices unlinkData->numOfResults is %d\n",
                             unlinkData->numOfResults);
-        OC_LOG_V(INFO, TAG, "Stack result :: %d", stackresult);
+        OIC_LOG_V(INFO, TAG, "Stack result :: %d", stackresult);
 
         OicUuid_t *pUuid = &unlinkData->unlinkRes[(unlinkData->numOfResults)].deviceId;
 
@@ -929,7 +1097,7 @@ static void registerResultForUnlinkDevices(UnlinkData_t *unlinkData, OCStackResu
         }
         unlinkData->unlinkRes[(unlinkData->numOfResults)].res = stackresult;
         ++(unlinkData->numOfResults);
-        OC_LOG (INFO, TAG, "Out registerResultForUnlinkDevices");
+        OIC_LOG (INFO, TAG, "Out registerResultForUnlinkDevices");
     }
 }
 
@@ -938,35 +1106,35 @@ static OCStackResult SendDeleteCredentialRequest(void* ctx,
                                                  const OCProvisionDev_t* revokedDev,
                                                  const OCProvisionDev_t* destDev)
 {
-    OC_LOG(DEBUG, TAG, "IN SendDeleteCredentialRequest");
+    OIC_LOG(DEBUG, TAG, "IN SendDeleteCredentialRequest");
 
     if (NULL == ctx || NULL == respHandler || NULL == revokedDev || NULL == destDev)
     {
         return OC_STACK_INVALID_PARAM;
     }
 
-    char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(revokedDev->doxm->deviceID.id)) + 1] = {};
-    uint32_t base64Len = 0;
-    if (B64_OK != b64Encode(revokedDev->doxm->deviceID.id, sizeof(revokedDev->doxm->deviceID.id),
-                           base64Buff, sizeof(base64Buff), &base64Len))
+    char *subID = NULL;
+    OCStackResult ret = ConvertUuidToStr(&revokedDev->doxm->deviceID, &subID);
+    if(OC_STACK_OK != ret)
     {
-        OC_LOG(ERROR, TAG, "SendDeleteCredentialRequest : Failed to base64 encoding");
+        OIC_LOG(ERROR, TAG, "SendDeleteCredentialRequest : Failed to canonical UUID encoding");
         return OC_STACK_ERROR;
     }
 
     char reqBuf[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
     int snRet = 0;
-                    //coaps://0.0.0.0:5684/oic/sec/cred?sub=(BASE64 ENCODED UUID)
+                    //coaps://0.0.0.0:5684/oic/sec/cred?subjectid=(Canonical ENCODED UUID)
     snRet = snprintf(reqBuf, sizeof(reqBuf), SRP_FORM_DELETE_CREDENTIAL, destDev->endpoint.addr,
-                     destDev->securePort, OIC_RSRC_CRED_URI, OIC_JSON_SUBJECT_NAME, base64Buff);
+                     destDev->securePort, OIC_RSRC_CRED_URI, OIC_JSON_SUBJECTID_NAME, subID);
+    OICFree(subID);
     if (snRet < 0)
     {
-        OC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : Error (snprintf) %d\n", snRet);
+        OIC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : Error (snprintf) %d\n", snRet);
         return OC_STACK_ERROR;
     }
     else if ((size_t)snRet >= sizeof(reqBuf))
     {
-        OC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : Truncated (snprintf) %d\n", snRet);
+        OIC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : Truncated (snprintf) %d\n", snRet);
         return OC_STACK_ERROR;
     }
 
@@ -975,18 +1143,18 @@ static OCStackResult SendDeleteCredentialRequest(void* ctx,
     cbData.context = ctx;
     cbData.cb = respHandler;
     cbData.cd = NULL;
-    OC_LOG_V(INFO, TAG, "URI: %s",reqBuf);
+    OIC_LOG_V(INFO, TAG, "URI: %s",reqBuf);
 
-    OC_LOG(DEBUG, TAG, "Sending remove credential request to resource server");
+    OIC_LOG(DEBUG, TAG, "Sending remove credential request to resource server");
 
-    OCStackResult ret = OCDoResource(NULL, OC_REST_DELETE, reqBuf,
+    ret = OCDoResource(NULL, OC_REST_DELETE, reqBuf,
                                      &destDev->endpoint, NULL,
                                      CT_ADAPTER_IP, OC_HIGH_QOS, &cbData, NULL, 0);
     if (OC_STACK_OK != ret)
     {
-        OC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : Error in OCDoResource %d", ret);
+        OIC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : Error in OCDoResource %d", ret);
     }
-    OC_LOG(DEBUG, TAG, "OUT SendDeleteCredentialRequest");
+    OIC_LOG(DEBUG, TAG, "OUT SendDeleteCredentialRequest");
 
     return ret;
 }
@@ -1004,22 +1172,22 @@ static OCStackApplicationResult SRPUnlinkDevice2CB(void *unlinkCtx, OCDoHandle h
         OCClientResponse *clientResponse)
 {
     (void) handle;
-    OC_LOG(DEBUG, TAG, "IN SRPUnlinkDevice2CB");
+    OIC_LOG(DEBUG, TAG, "IN SRPUnlinkDevice2CB");
     VERIFY_NON_NULL(TAG, unlinkCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
     UnlinkData_t* unlinkData = (UnlinkData_t*)unlinkCtx;
 
     if (clientResponse)
     {
-        OC_LOG(DEBUG, TAG, "Valid client response for device 2");
+        OIC_LOG(DEBUG, TAG, "Valid client response for device 2");
         registerResultForUnlinkDevices(unlinkData, clientResponse->result, IDX_SECOND_DEVICE_RES);
 
         if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
         {
-            OC_LOG(DEBUG, TAG, "Credential of device2 revoked");
+            OIC_LOG(DEBUG, TAG, "Credential of device2 revoked");
         }
         else
         {
-            OC_LOG(ERROR, TAG, "Unable to delete credential information from device 2");
+            OIC_LOG(ERROR, TAG, "Unable to delete credential information from device 2");
             unlinkData->resultCallback(unlinkData->ctx,
                                        unlinkData->numOfResults, unlinkData->unlinkRes, true);
             goto error;
@@ -1031,7 +1199,7 @@ static OCStackApplicationResult SRPUnlinkDevice2CB(void *unlinkCtx, OCDoHandle h
                                        IDX_SECOND_DEVICE_RES);
         unlinkData->resultCallback(unlinkData->ctx,
                                    unlinkData->numOfResults, unlinkData->unlinkRes, true);
-        OC_LOG(ERROR, TAG, "SRPUnlinkDevice2CB received Null clientResponse");
+        OIC_LOG(ERROR, TAG, "SRPUnlinkDevice2CB received Null clientResponse");
         goto error;
     }
 
@@ -1039,7 +1207,7 @@ static OCStackApplicationResult SRPUnlinkDevice2CB(void *unlinkCtx, OCDoHandle h
     if (OC_STACK_OK != PDMUnlinkDevices(&unlinkData->unlinkDev[0].doxm->deviceID,
                                        &unlinkData->unlinkDev[1].doxm->deviceID))
     {
-        OC_LOG(FATAL, TAG, "All requests are successfully done but update provisioning DB FAILED.");
+        OIC_LOG(FATAL, TAG, "All requests are successfully done but update provisioning DB FAILED.");
         registerResultForUnlinkDevices(unlinkData, OC_STACK_INCONSISTENT_DB, IDX_DB_UPDATE_RES);
         unlinkData->resultCallback(unlinkData->ctx,
                                    unlinkData->numOfResults, unlinkData->unlinkRes, true);
@@ -1050,7 +1218,7 @@ static OCStackApplicationResult SRPUnlinkDevice2CB(void *unlinkCtx, OCDoHandle h
 
 error:
     DeleteUnlinkData_t(unlinkData);
-    OC_LOG(DEBUG, TAG, "OUT SRPUnlinkDevice2CB");
+    OIC_LOG(DEBUG, TAG, "OUT SRPUnlinkDevice2CB");
     return OC_STACK_DELETE_TRANSACTION;
 
 }
@@ -1067,28 +1235,28 @@ error:
 static OCStackApplicationResult SRPUnlinkDevice1CB(void *unlinkCtx, OCDoHandle handle,
         OCClientResponse *clientResponse)
 {
-    OC_LOG_V(INFO, TAG, "Inside SRPUnlinkDevice1CB ");
+    OIC_LOG_V(INFO, TAG, "Inside SRPUnlinkDevice1CB ");
     VERIFY_NON_NULL(TAG, unlinkCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
     UnlinkData_t* unlinkData = (UnlinkData_t*)unlinkCtx;
     (void) handle;
 
     if (clientResponse)
     {
-        OC_LOG(DEBUG, TAG, "Valid client response for device 1");
+        OIC_LOG(DEBUG, TAG, "Valid client response for device 1");
         registerResultForUnlinkDevices(unlinkData, clientResponse->result, IDX_FIRST_DEVICE_RES);
 
         if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
         {
-            OC_LOG(DEBUG, TAG, "Credential of device 1 is revoked");
+            OIC_LOG(DEBUG, TAG, "Credential of device 1 is revoked");
 
             // Second revocation request to second device.
             OCStackResult res = SendDeleteCredentialRequest((void*)unlinkData, &SRPUnlinkDevice2CB,
                                                     &unlinkData->unlinkDev[0],
                                                     &unlinkData->unlinkDev[1] /*Dest*/);
-            OC_LOG_V(DEBUG, TAG, "Credential revocation request device 2, result :: %d",res);
+            OIC_LOG_V(DEBUG, TAG, "Credential revocation request device 2, result :: %d",res);
             if (OC_STACK_OK != res)
             {
-                 OC_LOG(ERROR, TAG, "Error while sending revocation request for device 2");
+                 OIC_LOG(ERROR, TAG, "Error while sending revocation request for device 2");
                  registerResultForUnlinkDevices(unlinkData, OC_STACK_INVALID_REQUEST_HANDLE,
                                                 IDX_SECOND_DEVICE_RES);
                  unlinkData->resultCallback(unlinkData->ctx,
@@ -1097,13 +1265,13 @@ static OCStackApplicationResult SRPUnlinkDevice1CB(void *unlinkCtx, OCDoHandle h
             }
             else
             {
-                OC_LOG(DEBUG, TAG, "Request for credential revocation successfully sent");
+                OIC_LOG(DEBUG, TAG, "Request for credential revocation successfully sent");
                 return OC_STACK_DELETE_TRANSACTION;
             }
         }
         else
         {
-            OC_LOG(ERROR, TAG, "Unable to delete credential information from device 1");
+            OIC_LOG(ERROR, TAG, "Unable to delete credential information from device 1");
 
             unlinkData->resultCallback(unlinkData->ctx, unlinkData->numOfResults,
                                             unlinkData->unlinkRes, true);
@@ -1112,17 +1280,17 @@ static OCStackApplicationResult SRPUnlinkDevice1CB(void *unlinkCtx, OCDoHandle h
     }
     else
     {
-        OC_LOG(DEBUG, TAG, "Invalid response from server");
+        OIC_LOG(DEBUG, TAG, "Invalid response from server");
         registerResultForUnlinkDevices(unlinkData, OC_STACK_INVALID_REQUEST_HANDLE,
                                        IDX_FIRST_DEVICE_RES );
         unlinkData->resultCallback(unlinkData->ctx,
                                    unlinkData->numOfResults, unlinkData->unlinkRes,
                                    true);
-        OC_LOG(ERROR, TAG, "SRPUnlinkDevice1CB received Null clientResponse");
+        OIC_LOG(ERROR, TAG, "SRPUnlinkDevice1CB received Null clientResponse");
     }
 
 error:
-    OC_LOG_V(INFO, TAG, "Out SRPUnlinkDevice1CB");
+    OIC_LOG_V(INFO, TAG, "Out SRPUnlinkDevice1CB");
     DeleteUnlinkData_t(unlinkData);
     return OC_STACK_DELETE_TRANSACTION;
 }
@@ -1143,14 +1311,25 @@ OCStackResult SRPUnlinkDevices(void* ctx,
                                const OCProvisionDev_t* pTargetDev2,
                                OCProvisionResultCB resultCallback)
 {
-    OC_LOG(INFO, TAG, "IN SRPUnlinkDevices");
+    OIC_LOG(INFO, TAG, "IN SRPUnlinkDevices");
 
-    if (!pTargetDev1 || !pTargetDev2 || !resultCallback)
+    if (!pTargetDev1 || !pTargetDev2 || !pTargetDev1->doxm || !pTargetDev2->doxm)
+    {
+        OIC_LOG(INFO, TAG, "SRPUnlinkDevices : NULL parameters");
+        return OC_STACK_INVALID_PARAM;
+    }
+    if (!resultCallback)
+    {
+        OIC_LOG(INFO, TAG, "SRPUnlinkDevices : NULL Callback");
+        return OC_STACK_INVALID_CALLBACK;
+    }
+    if (0 == memcmp(&pTargetDev1->doxm->deviceID, &pTargetDev2->doxm->deviceID, sizeof(OicUuid_t)))
     {
-        OC_LOG(INFO, TAG, "SRPUnlinkDevices : NULL parameters");
+        OIC_LOG(INFO, TAG, "SRPUnlinkDevices : Same device ID");
         return OC_STACK_INVALID_PARAM;
     }
-    OC_LOG(INFO, TAG, "Unlinking following devices: ");
+
+    OIC_LOG(INFO, TAG, "Unlinking following devices: ");
     PMPrintOCProvisionDev(pTargetDev1);
     PMPrintOCProvisionDev(pTargetDev2);
 
@@ -1158,7 +1337,7 @@ OCStackResult SRPUnlinkDevices(void* ctx,
     OCStackResult res = PDMSetLinkStale(&pTargetDev1->doxm->deviceID, &pTargetDev2->doxm->deviceID);
     if (OC_STACK_OK != res)
     {
-        OC_LOG(FATAL, TAG, "unable to update DB. Try again.");
+        OIC_LOG(FATAL, TAG, "unable to update DB. Try again.");
         return res;
     }
 
@@ -1170,7 +1349,7 @@ OCStackResult SRPUnlinkDevices(void* ctx,
     unlinkData->unlinkDev = (OCProvisionDev_t*)OICCalloc(2, sizeof(OCProvisionDev_t));
     if (NULL == unlinkData->unlinkDev)
     {
-        OC_LOG(ERROR, TAG, "Memory allocation failed");
+        OIC_LOG(ERROR, TAG, "Memory allocation failed");
         res = OC_STACK_NO_MEMORY;
         goto error;
     }
@@ -1178,7 +1357,7 @@ OCStackResult SRPUnlinkDevices(void* ctx,
     unlinkData->unlinkRes = (OCProvisionResult_t*)OICCalloc(3, sizeof(OCProvisionResult_t));
     if (NULL == unlinkData->unlinkRes)
     {
-        OC_LOG(ERROR, TAG, "Memory allocation failed");
+        OIC_LOG(ERROR, TAG, "Memory allocation failed");
         res = OC_STACK_NO_MEMORY;
         goto error;
     }
@@ -1193,14 +1372,14 @@ OCStackResult SRPUnlinkDevices(void* ctx,
                                        &unlinkData->unlinkDev[1], &unlinkData->unlinkDev[0]);
     if (OC_STACK_OK != res)
     {
-        OC_LOG(ERROR, TAG, "SRPUnlinkDevices : SendDeleteCredentialRequest failed");
+        OIC_LOG(ERROR, TAG, "SRPUnlinkDevices : SendDeleteCredentialRequest failed");
         goto error;
     }
 
     return res;
 
 error:
-    OC_LOG(INFO, TAG, "OUT SRPUnlinkDevices");
+    OIC_LOG(INFO, TAG, "OUT SRPUnlinkDevices");
     DeleteUnlinkData_t(unlinkData);
     return res;
 }
@@ -1219,7 +1398,7 @@ static void DeleteRemoveData_t(RemoveData_t* pRemoveData)
 static void registerResultForRemoveDevice(RemoveData_t *removeData, OicUuid_t *pLinkedDevId,
                                           OCStackResult stackresult, bool hasError)
 {
-    OC_LOG_V(INFO, TAG, "Inside registerResultForRemoveDevice removeData->numOfResults is %d\n",
+    OIC_LOG_V(INFO, TAG, "Inside registerResultForRemoveDevice removeData->numOfResults is %zu\n",
                          removeData->numOfResults + 1);
     if (pLinkedDevId)
     {
@@ -1238,6 +1417,15 @@ static void registerResultForRemoveDevice(RemoveData_t *removeData, OicUuid_t *p
     // If we get suffcient result from linked devices, we have to call user callback and do free
     if (removeData->sizeOfResArray == removeData->numOfResults)
     {
+        if(!removeData->hasError)
+        {
+            // Remove device info from prvisioning database
+            if (OC_STACK_OK != PDMDeleteDevice(&removeData->revokeTargetDev->doxm->deviceID))
+            {
+                OIC_LOG(ERROR, TAG, "ResultForRemoveDevice : Failed to remove device in PDM.");
+                removeData->hasError = true;
+            }
+        }
         removeData->resultCallback(removeData->ctx, removeData->numOfResults, removeData->removeRes,
                                    removeData->hasError);
         DeleteRemoveData_t(removeData);
@@ -1259,52 +1447,67 @@ static OCStackApplicationResult SRPRemoveDeviceCB(void *delDevCtx, OCDoHandle ha
     //Update the delete credential into delete device context
     //Save the deleted status in delDevCtx
     (void)handle;
-    OC_LOG_V(INFO, TAG, "Inside SRPRemoveDeviceCB.");
+    OIC_LOG_V(INFO, TAG, "Inside SRPRemoveDeviceCB.");
     VERIFY_NON_NULL(TAG, delDevCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
     OCStackResult res = OC_STACK_ERROR;
 
     RemoveData_t* removeData = (RemoveData_t*)delDevCtx;
+
     if (clientResponse)
     {
-        // If we can get device's UUID from OCClientResponse, it'd be good to use it in here
-        // but OCIdentity in OCClientResponse is emtpy now.
-        // It seems that we can set identity to CAData_t *cadata in CAPrepareSendData() API
-        // but CA doesn't have deviceID yet.
-        //
-        //TODO: Get OCIdentity from OCClientResponse and use it for 'registerResultForRemoveDevice'
-        //      If we can't complete this task, Provisioning Database has always stale link status
-        //      when Remove device is called.
-
-        if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
+        OicUuid_t revDevUuid = {.id={0}};
+        if(UUID_LENGTH == clientResponse->identity.id_length)
         {
-            res = PDMUnlinkDevices(&removeData->revokeTargetDev->doxm->deviceID,
-                                   NULL /*TODO: Replace NULL to uuid from OCClientResponse*/);
-            if (OC_STACK_OK != res)
+            memcpy(revDevUuid.id, clientResponse->identity.id, sizeof(revDevUuid.id));
+            if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
             {
-                OC_LOG(FATAL, TAG, "PDMSetLinkStale() FAIL: PDB is an obsolete one.");
-                registerResultForRemoveDevice(removeData,
-                                          NULL /*TODO: Replace NULL to uuid from OCClientResponse*/,
-                                          OC_STACK_INCONSISTENT_DB, true);
-                return OC_STACK_DELETE_TRANSACTION;
+                res = PDMUnlinkDevices(&removeData->revokeTargetDev->doxm->deviceID, &revDevUuid);
+                if (OC_STACK_OK != res)
+                {
+                    OIC_LOG(ERROR, TAG, "PDMSetLinkStale() FAIL: PDB is an obsolete one.");
+                           registerResultForRemoveDevice(removeData, &revDevUuid,
+                           OC_STACK_INCONSISTENT_DB, true);
+
+                    return OC_STACK_DELETE_TRANSACTION;
+                }
+
+                registerResultForRemoveDevice(removeData, &revDevUuid,
+                                              OC_STACK_RESOURCE_DELETED, false);
+            }
+            else
+            {
+                registerResultForRemoveDevice(removeData, &revDevUuid,
+                                              clientResponse->result, true);
+                OIC_LOG(ERROR, TAG, "Unexpected result from DELETE credential request!");
             }
-            registerResultForRemoveDevice(removeData,
-                                          NULL /*TODO: Replace NULL to uuid from OCClientResponse*/,
-                                          OC_STACK_RESOURCE_DELETED, false);
         }
         else
         {
-            registerResultForRemoveDevice(removeData,
-                                          NULL /*TODO: Replace NULL to uuid from OCClientResponse*/,
-                                          clientResponse->result, true);
-            OC_LOG(ERROR, TAG, "Unexpected result from DELETE credential request!");
+            OIC_LOG_V(WARNING, TAG, "Incorrect length of device UUID was sent from %s:%d",
+                     clientResponse->devAddr.addr, clientResponse->devAddr.port);
+
+            if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
+            {
+                /**
+                  * Since server's credential was deleted,
+                  * register result as OC_STACK_INCONSISTENT_DB with NULL UUID.
+                  */
+                OIC_LOG_V(ERROR, TAG, "But server's credential was deleted.");
+                registerResultForRemoveDevice(removeData, NULL, OC_STACK_INCONSISTENT_DB, true);
+            }
+            else
+            {
+                registerResultForRemoveDevice(removeData, NULL, clientResponse->result, true);
+            }
         }
     }
     else
     {
         registerResultForRemoveDevice(removeData, NULL, OC_STACK_ERROR, true);
-        OC_LOG(ERROR, TAG, "SRPRemoveDevices received Null clientResponse");
+        OIC_LOG(ERROR, TAG, "SRPRemoveDevices received Null clientResponse");
     }
 
+
     return OC_STACK_DELETE_TRANSACTION;
 }
 
@@ -1329,7 +1532,7 @@ static OCStackResult GetListofDevToReqDeleteCred(const OCProvisionDev_t* pRevoke
         OCStackResult res = PDMSetLinkStale(&curUuid->dev, &pRevokeTargetDev->doxm->deviceID);
         if (OC_STACK_OK != res)
         {
-            OC_LOG(FATAL, TAG, "PDMSetLinkStale() FAIL: PDB is an obsolete one.");
+            OIC_LOG(FATAL, TAG, "PDMSetLinkStale() FAIL: PDB is an obsolete one.");
             return OC_STACK_INCONSISTENT_DB;
         }
 
@@ -1344,7 +1547,7 @@ static OCStackResult GetListofDevToReqDeleteCred(const OCProvisionDev_t* pRevoke
                     OCProvisionDev_t* targetDev = PMCloneOCProvisionDev(curDev);
                     if (NULL == targetDev)
                     {
-                        OC_LOG(ERROR, TAG, "SRPRemoveDevice : Cloning OCProvisionDev_t Failed.");
+                        OIC_LOG(ERROR, TAG, "SRPRemoveDevice : Cloning OCProvisionDev_t Failed.");
                         return OC_STACK_NO_MEMORY;
                     }
 
@@ -1375,13 +1578,18 @@ static OCStackResult GetListofDevToReqDeleteCred(const OCProvisionDev_t* pRevoke
 OCStackResult SRPRemoveDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery,
                              const OCProvisionDev_t* pTargetDev, OCProvisionResultCB resultCallback)
 {
-    OC_LOG(INFO, TAG, "IN SRPRemoveDevice");
+    OIC_LOG(INFO, TAG, "IN SRPRemoveDevice");
 
-    if (!pTargetDev || !resultCallback || 0 == waitTimeForOwnedDeviceDiscovery)
+    if (!pTargetDev  || 0 == waitTimeForOwnedDeviceDiscovery)
     {
-        OC_LOG(INFO, TAG, "SRPRemoveDevice : NULL parameters");
+        OIC_LOG(INFO, TAG, "SRPRemoveDevice : NULL parameters");
         return OC_STACK_INVALID_PARAM;
     }
+    if (!resultCallback)
+    {
+        OIC_LOG(INFO, TAG, "SRPRemoveDevice : NULL Callback");
+        return OC_STACK_INVALID_CALLBACK;
+    }
 
     // Declare variables in here to handle error cases with goto statement.
     OCProvisionDev_t* pOwnedDevList = NULL;
@@ -1395,13 +1603,13 @@ OCStackResult SRPRemoveDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDi
     res = PDMGetLinkedDevices(&pTargetDev->doxm->deviceID, &pLinkedUuidList, &numOfDevices);
     if (OC_STACK_OK != res)
     {
-        OC_LOG(ERROR, TAG, "SRPRemoveDevice : Failed to get linked devices information");
+        OIC_LOG(ERROR, TAG, "SRPRemoveDevice : Failed to get linked devices information");
         return res;
     }
     // if there is no related device, we can skip further process.
     if (0 == numOfDevices)
     {
-        OC_LOG(DEBUG, TAG, "SRPRemoveDevice : No linked device found.");
+        OIC_LOG(DEBUG, TAG, "SRPRemoveDevice : No linked device found.");
         res = OC_STACK_CONTINUE;
         goto error;
     }
@@ -1410,7 +1618,7 @@ OCStackResult SRPRemoveDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDi
     res = PMDeviceDiscovery(waitTimeForOwnedDeviceDiscovery, true, &pOwnedDevList);
     if (OC_STACK_OK != res)
     {
-        OC_LOG(ERROR, TAG, "SRPRemoveDevice : Failed to PMDeviceDiscovery");
+        OIC_LOG(ERROR, TAG, "SRPRemoveDevice : Failed to PMDeviceDiscovery");
         goto error;
     }
 
@@ -1421,12 +1629,12 @@ OCStackResult SRPRemoveDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDi
                                       &pLinkedDevList, &numOfLinkedDev);
     if (OC_STACK_OK != res)
     {
-        OC_LOG(ERROR, TAG, "SRPRemoveDevice : GetListofDevToReqDeleteCred() failed");
+        OIC_LOG(ERROR, TAG, "SRPRemoveDevice : GetListofDevToReqDeleteCred() failed");
         goto error;
     }
     if (0 == numOfLinkedDev) // This case means, there is linked device but it's not alive now.
     {                       // So we don't have to send request message.
-        OC_LOG(DEBUG, TAG, "SRPRemoveDevice : No alived & linked device found.");
+        OIC_LOG(DEBUG, TAG, "SRPRemoveDevice : No alived & linked device found.");
         res = OC_STACK_CONTINUE;
         goto error;
     }
@@ -1435,7 +1643,7 @@ OCStackResult SRPRemoveDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDi
     removeData = (RemoveData_t*)OICCalloc(1, sizeof(RemoveData_t));
     if (!removeData)
     {
-        OC_LOG(ERROR, TAG, "SRPRemoveDevices : Failed to memory allocation");
+        OIC_LOG(ERROR, TAG, "SRPRemoveDevices : Failed to memory allocation");
         res = OC_STACK_NO_MEMORY;
         goto error;
     }
@@ -1443,7 +1651,7 @@ OCStackResult SRPRemoveDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDi
     removeData->revokeTargetDev = PMCloneOCProvisionDev(pTargetDev);
     if (!removeData->revokeTargetDev)
     {
-        OC_LOG(ERROR, TAG, "SRPRemoveDevices : PMCloneOCProvisionDev Failed");
+        OIC_LOG(ERROR, TAG, "SRPRemoveDevices : PMCloneOCProvisionDev Failed");
         res = OC_STACK_NO_MEMORY;
         goto error;
     }
@@ -1452,7 +1660,7 @@ OCStackResult SRPRemoveDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDi
         (OCProvisionResult_t*)OICCalloc(numOfLinkedDev, sizeof(OCProvisionResult_t));
     if (!removeData->removeRes)
     {
-        OC_LOG(ERROR, TAG, "SRPRemoveDevices : Failed to memory allocation");
+        OIC_LOG(ERROR, TAG, "SRPRemoveDevices : Failed to memory allocation");
         res = OC_STACK_NO_MEMORY;
         goto error;
     }
@@ -1473,7 +1681,7 @@ OCStackResult SRPRemoveDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDi
                                            removeData->revokeTargetDev, curDev);
         if (OC_STACK_OK != res)
         {
-            OC_LOG_V(ERROR, TAG, "SRPRemoveDevice : Fail to send the DELETE credential request to\
+            OIC_LOG_V(ERROR, TAG, "SRPRemoveDevice : Fail to send the DELETE credential request to\
                      %s:%u", curDev->endpoint.addr, curDev->endpoint.port);
         }
         else
@@ -1484,7 +1692,7 @@ OCStackResult SRPRemoveDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDi
 
     PDMDestoryOicUuidLinkList(pLinkedUuidList); //TODO: Modify API name to have unified convention.
     PMDeleteDeviceList(pOwnedDevList);
-    OC_LOG(INFO, TAG, "OUT SRPRemoveDevice");
+    OIC_LOG(INFO, TAG, "OUT SRPRemoveDevice");
 
     return totalRes; // Caller of this API should wait callback if totalRes == OC_STACK_OK.
 
@@ -1498,6 +1706,6 @@ error:
         OICFree(removeData->removeRes);
         OICFree(removeData);
     }
-    OC_LOG(INFO, TAG, "OUT ERROR case SRPRemoveDevice");
+    OIC_LOG(INFO, TAG, "OUT ERROR case SRPRemoveDevice");
     return res;
 }
index 838bf30..ee406d5 100644 (file)
@@ -48,6 +48,7 @@ sptest_env.AppendUnique(LIBS = ['-lpthread','-ldl'])
 sptest_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 sptest_env.AppendUnique(LIBPATH = [src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs'])
 sptest_env.PrependUnique(LIBS = [   'ocpmapi',
+                                    'oc',
                                     'ocsrm',
                                     'octbstack',
                                     'oc_logger',
@@ -86,6 +87,6 @@ if env.get('TEST') == '1':
                sptest_env.AppendENVPath('GTEST_OUTPUT', ['xml:'+ result_dir])
                sptest_env.AppendENVPath('LD_LIBRARY_PATH', [out_dir])
                sptest_env.AppendENVPath('LD_LIBRARY_PATH', ['./extlibs/gtest/gtest-1.7.0/lib/.libs'])
-               ut = sptest_env.Command ('ut', None, out_dir + '/resource/csdk/security/unittest/unittest')
+               ut = sptest_env.Command ('ut', None, out_dir + '/resource/csdk/security/provisioning/unittest/unittest')
                AlwaysBuild ('ut')
 
index 2e38f6b..b10129a 100644 (file)
 #include "gtest/gtest.h"
 #include "ocprovisioningmanager.h"
 
+static OicSecAcl_t acl1;
+static OicSecAcl_t acl2;
+static OCProvisionDev_t pDev1;
+static OCProvisionDev_t pDev2;
+static OicSecCredType_t credType = SYMMETRIC_PAIR_WISE_KEY;
+static OicSecOxm_t oicSecDoxmJustWorks = OIC_JUST_WORKS;
+static OicSecOxm_t oicSecDoxmRandomPin = OIC_RANDOM_DEVICE_PIN;
+static OicSecDoxm_t defaultDoxm1 =
+{
+    NULL,                   /* OicUrn_t *oxmType */
+    0,                      /* size_t oxmTypeLen */
+    &oicSecDoxmJustWorks,  /* uint16_t *oxm */
+    1,                      /* size_t oxmLen */
+    OIC_JUST_WORKS,         /* uint16_t oxmSel */
+    SYMMETRIC_PAIR_WISE_KEY,/* OicSecCredType_t sct */
+    false,                  /* bool owned */
+    {{0}},            /* OicUuid_t deviceID */
+    false,                  /* bool dpc */
+    {{0}},            /* OicUuid_t owner */
+};
+
+static OicSecDoxm_t defaultDoxm2 =
+{
+    NULL,                   /* OicUrn_t *oxmType */
+    0,                      /* size_t oxmTypeLen */
+    &oicSecDoxmRandomPin,  /* uint16_t *oxm */
+    1,                      /* size_t oxmLen */
+    OIC_RANDOM_DEVICE_PIN,         /* uint16_t oxmSel */
+    SYMMETRIC_PAIR_WISE_KEY,/* OicSecCredType_t sct */
+    false,                  /* bool owned */
+    {{0}},            /* OicUuid_t deviceID */
+    false,                  /* bool dpc */
+    {{0}},            /* OicUuid_t owner */
+};
+
 static void provisioningCB (void* UNUSED1, int UNUSED2, OCProvisionResult_t *UNUSED3, bool UNUSED4)
 {
     //dummy callback
@@ -29,25 +64,70 @@ static void provisioningCB (void* UNUSED1, int UNUSED2, OCProvisionResult_t *UNU
     (void) UNUSED4;
 }
 
+TEST(OCProvisionPairwiseDevicesTest, NullDevice1)
+{
+    pDev1.doxm = &defaultDoxm1;
+    uint8_t deviceId1[] = {0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x49, 0x64};
+    memcpy(pDev1.doxm->deviceID.id, deviceId1, sizeof(deviceId1));
+
+    pDev2.doxm = &defaultDoxm2;
+    uint8_t deviceId2[] = {0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x49, 0x63};
+    memcpy(pDev2.doxm->deviceID.id, deviceId2, sizeof(deviceId2));
+
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCProvisionPairwiseDevices(NULL, credType,
+                                                              OWNER_PSK_LENGTH_128, NULL, &acl1,
+                                                              &pDev2, &acl2, &provisioningCB));
+}
+
+TEST(OCProvisionPairwiseDevicesTest, NullDevice2)
+{
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCProvisionPairwiseDevices(NULL, credType,
+                                                              OWNER_PSK_LENGTH_128, &pDev1, &acl1,
+                                                              NULL, &acl2, &provisioningCB));
+}
+
+TEST(OCProvisionPairwiseDevicesTest, SamelDeviceId)
+{
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCProvisionPairwiseDevices(NULL, credType,
+                                                              OWNER_PSK_LENGTH_128, &pDev1, &acl1,
+                                                              &pDev1, &acl2, &provisioningCB));
+}
+
+TEST(OCProvisionPairwiseDevicesTest, NullCallback)
+{
+    EXPECT_EQ(OC_STACK_INVALID_CALLBACK, OCProvisionPairwiseDevices(NULL, credType,
+                                                              OWNER_PSK_LENGTH_128, &pDev1, &acl1,
+                                                              &pDev2, &acl2, NULL));
+}
+
+TEST(OCProvisionPairwiseDevicesTest, InvalidKeySize)
+{
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCProvisionPairwiseDevices(NULL, credType,
+                                                              0, &pDev1, &acl1,
+                                                              &pDev2, &acl2 ,&provisioningCB));
+}
+
 TEST(OCUnlinkDevicesTest, NullDevice1)
 {
-    OCProvisionDev_t dev2;
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCUnlinkDevices(NULL, NULL, &dev2, provisioningCB));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCUnlinkDevices(NULL, NULL, &pDev2, provisioningCB));
 }
 
 TEST(OCUnlinkDevicesTest, NullDevice2)
 {
-    OCProvisionDev_t dev1;
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCUnlinkDevices(NULL, &dev1, NULL, provisioningCB));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCUnlinkDevices(NULL, &pDev1, NULL, provisioningCB));
 }
 
 TEST(OCUnlinkDevicesTest, NullCallback)
 {
-    OCProvisionDev_t dev1;
-    OCProvisionDev_t dev2;
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCUnlinkDevices(NULL, &dev1, &dev2, NULL));
+    EXPECT_EQ(OC_STACK_INVALID_CALLBACK, OCUnlinkDevices(NULL, &pDev1, &pDev2, NULL));
 }
 
+TEST(OCUnlinkDevicesTest, SamelDeviceId)
+{
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCUnlinkDevices(NULL,&pDev1, &pDev1, &provisioningCB));
+}
+
+
 TEST(OCRemoveDeviceTest, NullTargetDevice)
 {
     unsigned short waitTime = 10 ;
@@ -57,27 +137,35 @@ TEST(OCRemoveDeviceTest, NullTargetDevice)
 TEST(OCRemoveDeviceTest, NullResultCallback)
 {
     unsigned short waitTime = 10;
-    OCProvisionDev_t dev1;
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCRemoveDevice(NULL, waitTime, &dev1, NULL));
+    EXPECT_EQ(OC_STACK_INVALID_CALLBACK, OCRemoveDevice(NULL, waitTime, &pDev1, NULL));
 }
 
 TEST(OCRemoveDeviceTest, ZeroWaitTime)
 {
     unsigned short waitTime = 0;
-    OCProvisionDev_t dev1;
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCRemoveDevice(NULL, waitTime, &dev1, NULL));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCRemoveDevice(NULL, waitTime, &pDev1, provisioningCB));
 }
 
 TEST(OCGetDevInfoFromNetworkTest, NullUnOwnedDeviceInfo)
 {
+    unsigned short waitTime = 10;
     OCProvisionDev_t *ownedList = NULL;
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCGetDevInfoFromNetwork(0, &ownedList, NULL));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCGetDevInfoFromNetwork(waitTime, &ownedList, NULL));
 }
 
 TEST(OCGetDevInfoFromNetworkTest, NullOwnedDeviceInfo)
 {
+    unsigned short waitTime = 10;
+    OCProvisionDev_t *unownedList = NULL;
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCGetDevInfoFromNetwork(waitTime, NULL, &unownedList));
+}
+
+TEST(OCGetDevInfoFromNetworkTest, ZeroWaitTime)
+{
+    unsigned short waitTime = 0;
+    OCProvisionDev_t *ownedList = NULL;
     OCProvisionDev_t *unownedList = NULL;
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCGetDevInfoFromNetwork(0, NULL, &unownedList));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCGetDevInfoFromNetwork(waitTime, &ownedList, &unownedList));
 }
 
 TEST(OCGetLinkedStatusTest, NULLDeviceID)
index 9f69a11..f0a0eab 100644 (file)
@@ -28,10 +28,10 @@ using namespace std;
 
 TEST(JustWorksOxMTest, NullParam)
 {
-
     OTMContext_t* otmCtx = NULL;
     OCStackResult res = OC_STACK_ERROR;
-    char* payloadRes;
+    uint8_t *payloadRes = NULL;
+    size_t size = 0;
 
     //LoadSecretJustWorksCallback always returns OC_STACK_OK.
     res = LoadSecretJustWorksCallback(otmCtx);
@@ -40,11 +40,11 @@ TEST(JustWorksOxMTest, NullParam)
     res = CreateSecureSessionJustWorksCallback(otmCtx);
     EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    payloadRes = CreateJustWorksSelectOxmPayload(otmCtx);
-    EXPECT_TRUE(NULL == payloadRes);
+    res = CreateJustWorksSelectOxmPayload(otmCtx, &payloadRes, &size);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    payloadRes = CreateJustWorksOwnerTransferPayload(otmCtx);
-    EXPECT_TRUE(NULL == payloadRes);
+    res = CreateJustWorksOwnerTransferPayload(otmCtx, &payloadRes, &size);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
     OTMContext_t otmCtx2;
     otmCtx2.selectedDeviceInfo = NULL;
@@ -56,31 +56,32 @@ TEST(JustWorksOxMTest, NullParam)
     res = CreateSecureSessionJustWorksCallback(&otmCtx2);
     EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    payloadRes = CreateJustWorksSelectOxmPayload(&otmCtx2);
-    EXPECT_TRUE(NULL == payloadRes);
+    res = CreateJustWorksSelectOxmPayload(&otmCtx2, &payloadRes, &size);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    payloadRes = CreateJustWorksOwnerTransferPayload(&otmCtx2);
-    EXPECT_TRUE(NULL == payloadRes);
+    res = CreateJustWorksOwnerTransferPayload(&otmCtx2, &payloadRes, &size);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 }
 
 TEST(RandomPinOxMTest, NullParam)
 {
     OTMContext_t* otmCtx = NULL;
     OCStackResult res = OC_STACK_ERROR;
-    char* payloadRes;
+    uint8_t *payloadRes = NULL;
+    size_t size = 0;
 
     //LoadSecretJustWorksCallback always returns OC_STACK_OK.
     res = InputPinCodeCallback(otmCtx);
     EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    res = CreateSecureSessionRandomPinCallbak(otmCtx);
+    res = CreateSecureSessionRandomPinCallback(otmCtx);
     EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    payloadRes = CreatePinBasedSelectOxmPayload(otmCtx);
-    EXPECT_TRUE(NULL == payloadRes);
+    res = CreatePinBasedSelectOxmPayload(otmCtx, &payloadRes, &size);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    payloadRes = CreatePinBasedOwnerTransferPayload(otmCtx);
-    EXPECT_TRUE(NULL == payloadRes);
+    res = CreatePinBasedOwnerTransferPayload(otmCtx, &payloadRes, &size);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
     OTMContext_t otmCtx2;
     otmCtx2.selectedDeviceInfo = NULL;
@@ -89,12 +90,12 @@ TEST(RandomPinOxMTest, NullParam)
     res = InputPinCodeCallback(&otmCtx2);
     EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    res = CreateSecureSessionRandomPinCallbak(&otmCtx2);
+    res = CreateSecureSessionRandomPinCallback(&otmCtx2);
     EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    payloadRes = CreatePinBasedSelectOxmPayload(&otmCtx2);
-    EXPECT_TRUE(NULL == payloadRes);
+    res = CreatePinBasedSelectOxmPayload(&otmCtx2, &payloadRes, &size);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    payloadRes = CreatePinBasedOwnerTransferPayload(&otmCtx2);
-    EXPECT_TRUE(NULL == payloadRes);
+    res = CreatePinBasedOwnerTransferPayload(&otmCtx2, &payloadRes, &size);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 }
index 0a53e1f..92c67b7 100644 (file)
 #include "gtest/gtest.h"
 #include "provisioningdatabasemanager.h"
 
-const char ID_1[] = "1111111111111111";
-const char ID_2[] = "2111111111111111";
-const char ID_3[] = "3111111111111111";
-const char ID_4[] = "4111111111111111";
-const char ID_5[] = "5111111111111111";
-const char ID_6[] = "6111111111111111";
-const char ID_7[] = "7777777777777777";
-const char ID_8[] = "8777777777777777";
+#define DB_FILE "PDM.db"
+const char ID_1 [] = "1111111111111111";
+const char ID_2 [] = "2111111111111111";
+const char ID_3 [] = "3111111111111111";
+const char ID_4 [] = "4111111111111111";
+const char ID_5 [] = "5111111111111111";
+const char ID_6 [] = "6111111111111111";
+const char ID_7 [] = "7111111111111111";
+const char ID_8 [] = "8111111111111111";
+const char ID_9 [] = "9111111111111111";
+const char ID_10[] = "1222222222222222";
+const char ID_11[] = "2222222222222222";
+const char ID_12[] = "3222222222222222";
+const char ID_13[] = "4222222222222222";
+
 
 TEST(CallPDMAPIbeforeInit, BeforeInit)
 {
+    if (0 == access(DB_FILE, F_OK))
+    {
+        EXPECT_EQ(0, unlink(DB_FILE));
+    }
     EXPECT_EQ(OC_STACK_PDM_IS_NOT_INITIALIZED, PDMAddDevice(NULL));
     EXPECT_EQ(OC_STACK_PDM_IS_NOT_INITIALIZED, PDMIsDuplicateDevice(NULL,NULL));
     EXPECT_EQ(OC_STACK_PDM_IS_NOT_INITIALIZED, PDMLinkDevices(NULL, NULL));
@@ -264,3 +275,97 @@ TEST(PDMIsLinkExistsTest, DuplicateID)
     EXPECT_EQ(OC_STACK_OK, res);
     EXPECT_FALSE(linkExisits);
 }
+
+TEST(PDMSetDeviceStaleTest, NULLUUID)
+{
+    EXPECT_EQ(OC_STACK_OK, PDMInit(NULL));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, PDMSetDeviceStale(NULL));
+}
+
+TEST(PDMSetDeviceStaleTest, VALIDUUID)
+{
+    EXPECT_EQ(OC_STACK_OK, PDMInit(NULL));
+    OicUuid_t uid1 = {{0,}};
+    memcpy(&uid1.id, ID_9, sizeof(uid1.id));
+    EXPECT_EQ(OC_STACK_OK, PDMAddDevice(&uid1));
+    EXPECT_EQ(OC_STACK_OK,PDMSetDeviceStale(&uid1));
+}
+
+TEST(PDMSetDeviceStaleTest, StaleDeviceNotinDeviceList)
+{
+    EXPECT_EQ(OC_STACK_OK, PDMInit(NULL));
+    OicUuid_t uid1 = {{0,}};
+    memcpy(&uid1.id, ID_10, sizeof(uid1.id));
+    EXPECT_EQ(OC_STACK_OK, PDMAddDevice(&uid1));
+    EXPECT_EQ(OC_STACK_OK,PDMSetDeviceStale(&uid1));
+
+    OCUuidList_t *list = NULL;
+    size_t noOfDevcies = 0;
+    EXPECT_EQ(OC_STACK_OK, PDMGetOwnedDevices(&list, &noOfDevcies));
+
+    while (list)
+    {
+        EXPECT_FALSE(0 == memcmp(list->dev.id, uid1.id,sizeof(uid1.id)));
+        list = list->next;
+    }
+}
+
+TEST(PDMSetDeviceStaleTest, StaleDeviceNotinLinkedDevice)
+{
+    EXPECT_EQ(OC_STACK_OK, PDMInit(NULL));
+    OicUuid_t uid1 = {{0,}};
+    memcpy(&uid1.id, ID_11, sizeof(uid1.id));
+
+    OicUuid_t uid2 = {{0,}};
+    memcpy(&uid2.id, ID_12, sizeof(uid2.id));
+
+    OicUuid_t uid3 = {{0,}};
+    memcpy(&uid3.id, ID_13, sizeof(uid3.id));
+
+    EXPECT_EQ(OC_STACK_OK, PDMAddDevice(&uid1));
+    EXPECT_EQ(OC_STACK_OK, PDMAddDevice(&uid2));
+    EXPECT_EQ(OC_STACK_OK, PDMAddDevice(&uid3));
+
+    EXPECT_EQ(OC_STACK_OK, PDMLinkDevices(&uid1, &uid2));
+    EXPECT_EQ(OC_STACK_OK, PDMLinkDevices(&uid2, &uid3));
+    EXPECT_EQ(OC_STACK_OK, PDMLinkDevices(&uid1, &uid3));
+
+    EXPECT_EQ(OC_STACK_OK,PDMSetDeviceStale(&uid1));
+
+    OCUuidList_t *list1 = NULL;
+    size_t noOfDevices1 = 0;
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, PDMGetLinkedDevices(&uid1, &list1, &noOfDevices1));
+
+    OCUuidList_t *list2 = NULL;
+    size_t noOfDevices2 = 0;
+    EXPECT_EQ(OC_STACK_OK, PDMGetLinkedDevices(&uid2, &list2, &noOfDevices2));
+    OCUuidList_t *ptr = list2;
+    while(ptr)
+    {
+        EXPECT_FALSE(0 == memcmp(ptr->dev.id, uid1.id,sizeof(uid1.id)));
+        ptr = ptr->next;
+    }
+    ptr = list2;
+    while(ptr)
+    {
+        EXPECT_TRUE(0 == memcmp(ptr->dev.id, uid3.id,sizeof(uid3.id)));
+        ptr = ptr->next;
+    }
+
+    OCUuidList_t *list3 = NULL;
+    size_t noOfDevices3 = 0;
+    EXPECT_EQ(OC_STACK_OK, PDMGetLinkedDevices(&uid3, &list3, &noOfDevices3));
+    ptr = list3;
+    while(ptr)
+    {
+        EXPECT_FALSE(0 == memcmp(ptr->dev.id, uid1.id,sizeof(uid1.id)));
+        ptr = ptr->next;
+    }
+
+    ptr = list3;
+    while(ptr)
+    {
+        EXPECT_TRUE(0 == memcmp(ptr->dev.id, uid2.id,sizeof(uid2.id)));
+        ptr = ptr->next;
+    }
+}
index 25d2226..b8e3875 100644 (file)
 #include "gtest/gtest.h"
 #include "secureresourceprovider.h"
 
-
 static OicSecAcl_t acl;
 static OCProvisionDev_t pDev1;
 static OCProvisionDev_t pDev2;
-static OicSecCredType_t credType;
+static OicSecCredType_t credType = SYMMETRIC_PAIR_WISE_KEY;
+static OCProvisionDev_t selectedDeviceInfo;
+static OicSecPconf_t pconf;
+static OicSecOxm_t oicSecDoxmJustWorks = OIC_JUST_WORKS;
+static OicSecOxm_t oicSecDoxmRandomPin = OIC_RANDOM_DEVICE_PIN;
+static OicSecDoxm_t defaultDoxm1 =
+{
+    NULL,                   /* OicUrn_t *oxmType */
+    0,                      /* size_t oxmTypeLen */
+    &oicSecDoxmJustWorks,  /* uint16_t *oxm */
+    1,                      /* size_t oxmLen */
+    OIC_JUST_WORKS,         /* uint16_t oxmSel */
+    SYMMETRIC_PAIR_WISE_KEY,/* OicSecCredType_t sct */
+    false,                  /* bool owned */
+    {{0}},            /* OicUuid_t deviceID */
+    false,                  /* bool dpc */
+    {{0}},            /* OicUuid_t owner */
+};
+
+static OicSecDoxm_t defaultDoxm2 =
+{
+    NULL,                   /* OicUrn_t *oxmType */
+    0,                      /* size_t oxmTypeLen */
+    &oicSecDoxmRandomPin,  /* uint16_t *oxm */
+    1,                      /* size_t oxmLen */
+    OIC_RANDOM_DEVICE_PIN,         /* uint16_t oxmSel */
+    SYMMETRIC_PAIR_WISE_KEY,/* OicSecCredType_t sct */
+    false,                  /* bool owned */
+    {{0}},            /* OicUuid_t deviceID */
+    false,                  /* bool dpc */
+    {{0}},            /* OicUuid_t owner */
+};
 
 static void provisioningCB (void* UNUSED1, int UNUSED2, OCProvisionResult_t *UNUSED3, bool UNUSED4)
 {
@@ -37,6 +67,14 @@ static void provisioningCB (void* UNUSED1, int UNUSED2, OCProvisionResult_t *UNU
 
 TEST(SRPProvisionACLTest, NullDeviceInfo)
 {
+    pDev1.doxm = &defaultDoxm1;
+    uint8_t deviceId1[] = {0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x49, 0x64};
+    memcpy(pDev1.doxm->deviceID.id, deviceId1, sizeof(deviceId1));
+
+    pDev2.doxm = &defaultDoxm2;
+    uint8_t deviceId2[] = {0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x49, 0x63};
+    memcpy(pDev2.doxm->deviceID.id, deviceId2, sizeof(deviceId2));
+
     EXPECT_EQ(OC_STACK_INVALID_PARAM, SRPProvisionACL(NULL, NULL, &acl, &provisioningCB));
 }
 
@@ -57,6 +95,13 @@ TEST(SRPProvisionCredentialsTest, NullDevice1)
                                                               &pDev2, &provisioningCB));
 }
 
+TEST(SRPProvisionCredentialsTest, SamelDeviceId)
+{
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, SRPProvisionCredentials(NULL, credType,
+                                                              OWNER_PSK_LENGTH_128, &pDev1,
+                                                              &pDev1, &provisioningCB));
+}
+
 TEST(SRPProvisionCredentialsTest, NullCallback)
 {
     EXPECT_EQ(OC_STACK_INVALID_CALLBACK, SRPProvisionCredentials(NULL, credType,
@@ -73,21 +118,22 @@ TEST(SRPProvisionCredentialsTest, InvalidKeySize)
 
 TEST(SRPUnlinkDevicesTest, NullDevice1)
 {
-    OCProvisionDev_t dev2;
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, SRPUnlinkDevices(NULL, NULL, &dev2, provisioningCB));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, SRPUnlinkDevices(NULL, NULL, &pDev2, provisioningCB));
 }
 
 TEST(SRPUnlinkDevicesTest, NullDevice2)
 {
-    OCProvisionDev_t dev1;
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, SRPUnlinkDevices(NULL, &dev1, NULL, provisioningCB));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, SRPUnlinkDevices(NULL, &pDev1, NULL, provisioningCB));
+}
+
+TEST(SRPUnlinkDevicesTest, SamelDeviceId)
+{
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, SRPUnlinkDevices(NULL, &pDev1, &pDev1, provisioningCB));
 }
 
 TEST(SRPUnlinkDevicesTest, NullCallback)
 {
-    OCProvisionDev_t dev1;
-    OCProvisionDev_t dev2;
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, SRPUnlinkDevices(NULL, &dev1, &dev2, NULL));
+    EXPECT_EQ(OC_STACK_INVALID_CALLBACK, SRPUnlinkDevices(NULL, &pDev1, &pDev2, NULL));
 }
 
 TEST(SRPRemoveDeviceTest, NullTargetDevice)
@@ -100,7 +146,7 @@ TEST(SRPRemoveDeviceTest, NullResultCallback)
 {
     unsigned short waitTime = 10;
     OCProvisionDev_t dev1;
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, SRPRemoveDevice(NULL, waitTime, &dev1, NULL));
+    EXPECT_EQ(OC_STACK_INVALID_CALLBACK, SRPRemoveDevice(NULL, waitTime, &dev1, NULL));
 }
 
 TEST(SRPRemoveDeviceTest, ZeroWaitTime)
@@ -108,3 +154,18 @@ TEST(SRPRemoveDeviceTest, ZeroWaitTime)
     OCProvisionDev_t dev1;
     EXPECT_EQ(OC_STACK_INVALID_PARAM, SRPRemoveDevice(NULL, 0, &dev1, NULL));
 }
+
+TEST(SRPProvisionDirectPairingTest, NullselectedDeviceInfo)
+{
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, SRPProvisionDirectPairing(NULL, NULL, &pconf, &provisioningCB));
+}
+
+TEST(SRPProvisionDirectPairingTest, Nullpconf)
+{
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, SRPProvisionDirectPairing(NULL, &selectedDeviceInfo, NULL, &provisioningCB));
+}
+
+TEST(SRPProvisionDirectPairingTest, Nullcallback)
+{
+    EXPECT_EQ(OC_STACK_INVALID_CALLBACK, SRPProvisionDirectPairing(NULL, &selectedDeviceInfo, &pconf, NULL));
+}
index 6d20938..d2b9f4b 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#include <stdlib.h>
+#ifdef WITH_ARDUINO
 #include <string.h>
+#else
+#include <strings.h>
+#endif
+#include <stdlib.h>
+
 #include "ocstack.h"
-#include "logger.h"
+#include "ocserverrequest.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
-#include "cJSON.h"
-#include "base64.h"
-#include "resourcemanager.h"
-#include "aclresource.h"
-#include "psinterface.h"
+#include "ocrandom.h"
+#include "ocpayload.h"
 #include "utlist.h"
+#include "payload_logging.h"
 #include "srmresourcestrings.h"
+#include "aclresource.h"
 #include "doxmresource.h"
+#include "resourcemanager.h"
 #include "srmutility.h"
-#include "ocserverrequest.h"
-#include <stdlib.h>
-#ifdef WITH_ARDUINO
-#include <string.h>
-#else
-#include <strings.h>
-#endif
+#include "psinterface.h"
+
+#include "security_internals.h"
 
 #define TAG  "SRM-ACL"
+#define NUMBER_OF_SEC_PROV_RSCS 4
+#define NUMBER_OF_DEFAULT_SEC_RSCS 2
+
+static const uint8_t ACL_MAP_SIZE = 2;
+static const uint8_t ACL_ACLIST_MAP_SIZE = 1;
+static const uint8_t ACL_ACES_MAP_SIZE = 3;
+static const uint8_t ACL_RESOURCE_MAP_SIZE = 4;
+
+
+// CborSize is the default cbor payload size being used.
+static const uint16_t CBOR_SIZE = 2048;
 
-OicSecAcl_t               *gAcl = NULL;
-static OCResourceHandle    gAclHandle = NULL;
+static OicSecAcl_t *gAcl = NULL;
+static OCResourceHandle gAclHandle = NULL;
 
 /**
  * This function frees OicSecAcl_t object's fields and object itself.
@@ -52,9 +64,9 @@ static OCResourceHandle    gAclHandle = NULL;
 static void FreeACE(OicSecAcl_t *ace)
 {
     size_t i;
-    if(NULL == ace)
+    if (NULL == ace)
     {
-        OC_LOG (ERROR, TAG, "Invalid Parameter");
+        OIC_LOG(ERROR, TAG, "Invalid Parameter");
         return;
     }
 
@@ -66,9 +78,9 @@ static void FreeACE(OicSecAcl_t *ace)
     OICFree(ace->resources);
 
     //Clean Period
-    if(ace->periods)
+    if (ace->periods)
     {
-        for(i = 0; i < ace->prdRecrLen; i++)
+        for (i = 0; i < ace->prdRecrLen; i++)
         {
             OICFree(ace->periods[i]);
         }
@@ -76,18 +88,15 @@ static void FreeACE(OicSecAcl_t *ace)
     }
 
     //Clean Recurrence
-    if(ace->recurrences)
+    if (ace->recurrences)
     {
-        for(i = 0; i < ace->prdRecrLen; i++)
+        for (i = 0; i < ace->prdRecrLen; i++)
         {
             OICFree(ace->recurrences[i]);
         }
         OICFree(ace->recurrences);
     }
 
-    // Clean Owners
-    OICFree(ace->owners);
-
     // Clean ACL node itself
     OICFree(ace);
 }
@@ -106,356 +115,628 @@ void DeleteACLList(OicSecAcl_t* acl)
     }
 }
 
-/*
- * This internal method converts ACL data into JSON format.
- *
- * Note: Caller needs to invoke 'free' when finished done using
- * return string.
- */
-char * BinToAclJSON(const OicSecAcl_t * acl)
+static size_t OicSecAclSize(const OicSecAcl_t *secAcl)
 {
-    cJSON *jsonRoot = NULL;
-    char *jsonStr = NULL;
+    if (!secAcl)
+    {
+        return 0;
+    }
+    OicSecAcl_t *acl = (OicSecAcl_t *)secAcl;
+    size_t size = 0;
+    while (acl)
+    {
+       size++;
+       acl = acl->next;
+    }
+    return size;
+}
 
-    if (acl)
+OCStackResult AclToCBORPayload(const OicSecAcl_t *secAcl, uint8_t **payload, size_t *size)
+{
+     if (NULL == secAcl || NULL == payload || NULL != *payload || NULL == size)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCStackResult ret = OC_STACK_ERROR;
+    CborError cborEncoderResult = CborNoError;
+    OicSecAcl_t *acl = (OicSecAcl_t *)secAcl;
+    CborEncoder encoder;
+    CborEncoder aclMap;
+    CborEncoder aclListMap;
+    CborEncoder acesArray;
+    uint8_t *outPayload = NULL;
+    size_t cborLen = *size;
+    *size = 0;
+    *payload = NULL;
+
+    if (cborLen == 0)
     {
-        jsonRoot = cJSON_CreateObject();
-        VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+        cborLen = CBOR_SIZE;
+    }
+
+    outPayload = (uint8_t *)OICCalloc(1, cborLen);
+    VERIFY_NON_NULL(TAG, outPayload, ERROR);
+    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
+
+    // Create ACL Map (aclist, rownerid)
+    cborEncoderResult = cbor_encoder_create_map(&encoder, &aclMap, ACL_MAP_SIZE);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Creating ACL Map.");
+
+    cborEncoderResult = cbor_encode_text_string(&aclMap, OIC_JSON_ACLIST_NAME,
+        strlen(OIC_JSON_ACLIST_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding aclist Name Tag.");
 
-        cJSON *jsonAclArray = NULL;
-        cJSON_AddItemToObject (jsonRoot, OIC_JSON_ACL_NAME, jsonAclArray = cJSON_CreateArray());
-        VERIFY_NON_NULL(TAG, jsonAclArray, ERROR);
+    // Create ACLIST Map (aces)
+    cborEncoderResult = cbor_encoder_create_map(&aclMap, &aclListMap, ACL_ACLIST_MAP_SIZE);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Creating ACLIST Map.");
 
-        while(acl)
+    cborEncoderResult = cbor_encode_text_string(&aclListMap, OIC_JSON_ACES_NAME,
+        strlen(OIC_JSON_ACES_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ACES Name Tag.");
+
+    // Create ACES Array
+    cborEncoderResult = cbor_encoder_create_array(&aclListMap, &acesArray, OicSecAclSize(secAcl));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Creating ACES Array.");
+
+    while (acl)
+    {
+        CborEncoder oicSecAclMap;
+        // ACL Map size - Number of mandatory items
+        uint8_t aclMapSize = ACL_ACES_MAP_SIZE;
+        size_t inLen = 0;
+
+        // Create ACL Map
+        if (acl->periods)
+        {
+            ++aclMapSize;
+        }
+        if (acl->recurrences)
         {
-            char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
-            uint32_t outLen = 0;
-            size_t inLen = 0;
-            B64Result b64Ret = B64_OK;
+            ++aclMapSize;
+        }
 
-            cJSON *jsonAcl = cJSON_CreateObject();
+        cborEncoderResult = cbor_encoder_create_map(&acesArray, &oicSecAclMap, aclMapSize);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Creating ACES Map");
+
+        // Subject -- Mandatory
+        cborEncoderResult = cbor_encode_text_string(&oicSecAclMap, OIC_JSON_SUBJECTID_NAME,
+            strlen(OIC_JSON_SUBJECTID_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Subject Name Tag.");
+        inLen = (memcmp(&(acl->subject), &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)) == 0) ?
+            WILDCARD_SUBJECT_ID_LEN : sizeof(OicUuid_t);
+        if(inLen == WILDCARD_SUBJECT_ID_LEN)
+        {
+            cborEncoderResult = cbor_encode_text_string(&oicSecAclMap, WILDCARD_RESOURCE_URI,
+                strlen(WILDCARD_RESOURCE_URI));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Subject Id wildcard Value.");
+        }
+        else
+        {
+            char *subject = NULL;
+            ret = ConvertUuidToStr(&acl->subject, &subject);
+            VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
+            cborEncoderResult = cbor_encode_text_string(&oicSecAclMap, subject, strlen(subject));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Subject Id Value.");
+            OICFree(subject);
+        }
+
+        // Resources
+        {
+            CborEncoder resources;
+            cborEncoderResult = cbor_encode_text_string(&oicSecAclMap, OIC_JSON_RESOURCES_NAME,
+                strlen(OIC_JSON_RESOURCES_NAME));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Resource Name Tag.");
+
+            cborEncoderResult = cbor_encoder_create_array(&oicSecAclMap, &resources, acl->resourcesLen);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Resource Name Array.");
 
-            // Subject -- Mandatory
-            outLen = 0;
-            if (memcmp(&(acl->subject), &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)) == 0)
-            {
-                inLen = WILDCARD_SUBJECT_ID_LEN;
-            }
-            else
-            {
-                inLen =  sizeof(OicUuid_t);
-            }
-            b64Ret = b64Encode(acl->subject.id, inLen, base64Buff,
-                sizeof(base64Buff), &outLen);
-            VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
-            cJSON_AddStringToObject(jsonAcl, OIC_JSON_SUBJECT_NAME, base64Buff );
-
-            // Resources -- Mandatory
-            cJSON *jsonRsrcArray = NULL;
-            cJSON_AddItemToObject (jsonAcl, OIC_JSON_RESOURCES_NAME, jsonRsrcArray = cJSON_CreateArray());
-            VERIFY_NON_NULL(TAG, jsonRsrcArray, ERROR);
             for (size_t i = 0; i < acl->resourcesLen; i++)
             {
-                cJSON_AddItemToArray (jsonRsrcArray, cJSON_CreateString(acl->resources[i]));
+
+                CborEncoder rMap;
+                cborEncoderResult = cbor_encoder_create_map(&resources, &rMap, ACL_RESOURCE_MAP_SIZE);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Resource Map.");
+
+                cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_HREF_NAME,
+                        strlen(OIC_JSON_HREF_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding HREF Name Tag.");
+                cborEncoderResult = cbor_encode_text_string(&rMap, acl->resources[i],
+                        strlen(acl->resources[i]));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding HREF Value in Map.");
+
+                cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_REL_NAME,
+                        strlen(OIC_JSON_REL_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding REL Name Tag.");
+
+                // TODO : Need to assign real value of REL
+                cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_EMPTY_STRING,
+                        strlen(OIC_JSON_EMPTY_STRING));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding REL Value.");
+
+                cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_RT_NAME,
+                        strlen(OIC_JSON_RT_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag.");
+
+                // TODO : Need to assign real value of RT
+                cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_EMPTY_STRING,
+                        strlen(OIC_JSON_EMPTY_STRING));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
+
+                cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_IF_NAME,
+                        strlen(OIC_JSON_IF_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag.");
+
+                // TODO : Need to assign real value of IF
+                cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_EMPTY_STRING,
+                        strlen(OIC_JSON_EMPTY_STRING));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
+
+
+                cborEncoderResult = cbor_encoder_close_container(&resources, &rMap);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Resource Map.");
+
             }
+            cborEncoderResult = cbor_encoder_close_container(&oicSecAclMap, &resources);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Resource Name Array.");
+        }
 
-            // Permissions -- Mandatory
-            cJSON_AddNumberToObject (jsonAcl, OIC_JSON_PERMISSION_NAME, acl->permission);
 
-            //Period & Recurrence -- Not Mandatory
-            if(0 != acl->prdRecrLen)
+        // Permissions -- Mandatory
+        cborEncoderResult = cbor_encode_text_string(&oicSecAclMap, OIC_JSON_PERMISSION_NAME,
+            strlen(OIC_JSON_PERMISSION_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Permission Name Tag.");
+        cborEncoderResult = cbor_encode_int(&oicSecAclMap, acl->permission);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Permission Name Value.");
+
+        // Period -- Not Mandatory
+        if (acl->periods)
+        {
+
+            CborEncoder period;
+            cborEncoderResult = cbor_encode_text_string(&oicSecAclMap, OIC_JSON_PERIOD_NAME,
+                strlen(OIC_JSON_PERIOD_NAME));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Tag.");
+            cborEncoderResult = cbor_encoder_create_array(&oicSecAclMap, &period, acl->prdRecrLen);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Array.");
+            for (size_t i = 0; i < acl->prdRecrLen; i++)
             {
-                cJSON *jsonPeriodArray = NULL;
-                cJSON_AddItemToObject (jsonAcl, OIC_JSON_PERIODS_NAME,
-                        jsonPeriodArray = cJSON_CreateArray());
-                VERIFY_NON_NULL(TAG, jsonPeriodArray, ERROR);
-                for (size_t i = 0; i < acl->prdRecrLen; i++)
-                {
-                    cJSON_AddItemToArray (jsonPeriodArray,
-                            cJSON_CreateString(acl->periods[i]));
-                }
+                cborEncoderResult = cbor_encode_text_string(&period, acl->periods[i],
+                    strlen(acl->periods[i]));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Value in Array.");
             }
+            cborEncoderResult = cbor_encoder_close_container(&oicSecAclMap, &period);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Period Array.");
+        }
 
-            //Recurrence -- Not Mandatory
-            if(0 != acl->prdRecrLen && acl->recurrences)
+        // Recurrence -- Not Mandatory
+        if (acl->recurrences)
+        {
+            CborEncoder recurrences;
+            cborEncoderResult = cbor_encode_text_string(&oicSecAclMap, OIC_JSON_RECURRENCES_NAME,
+                strlen(OIC_JSON_RECURRENCES_NAME));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Recurrence Tag.");
+            cborEncoderResult = cbor_encoder_create_array(&oicSecAclMap, &recurrences, acl->prdRecrLen);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Recurrence Array.");
+
+            for (size_t i = 0; i < acl->prdRecrLen; i++)
             {
-                cJSON *jsonRecurArray  = NULL;
-                cJSON_AddItemToObject (jsonAcl, OIC_JSON_RECURRENCES_NAME,
-                        jsonRecurArray = cJSON_CreateArray());
-                VERIFY_NON_NULL(TAG, jsonRecurArray, ERROR);
-                for (size_t i = 0; i < acl->prdRecrLen; i++)
-                {
-                    cJSON_AddItemToArray (jsonRecurArray,
-                            cJSON_CreateString(acl->recurrences[i]));
-                }
+                cborEncoderResult = cbor_encode_text_string(&recurrences, acl->recurrences[i],
+                    strlen(acl->recurrences[i]));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Recurrence Array Value.");
             }
+            cborEncoderResult = cbor_encoder_close_container(&oicSecAclMap, &recurrences);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Recurrence Array");
 
-            // Owners -- Mandatory
-            cJSON *jsonOwnrArray = NULL;
-            cJSON_AddItemToObject (jsonAcl, OIC_JSON_OWNERS_NAME, jsonOwnrArray = cJSON_CreateArray());
-            VERIFY_NON_NULL(TAG, jsonOwnrArray, ERROR);
-            for (size_t i = 0; i < acl->ownersLen; i++)
-            {
-                outLen = 0;
+        }
 
-                b64Ret = b64Encode(acl->owners[i].id, sizeof(((OicUuid_t*)0)->id), base64Buff,
-                    sizeof(base64Buff), &outLen);
-                VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
 
-                cJSON_AddItemToArray (jsonOwnrArray, cJSON_CreateString(base64Buff));
-            }
+        cborEncoderResult = cbor_encoder_close_container(&acesArray, &oicSecAclMap);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing ACES Map.");
+        acl = acl->next;
+    }
 
-            // Attach current acl node to Acl Array
-            cJSON_AddItemToArray(jsonAclArray, jsonAcl);
-            acl = acl->next;
-        }
+    // Close ACES Array
+    cborEncoderResult = cbor_encoder_close_container(&aclListMap, &acesArray);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing ACES Array.");
+
+    // Close ACLIST Map
+    cborEncoderResult = cbor_encoder_close_container(&aclMap, &aclListMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing ACLIST Map.");
 
-        jsonStr = cJSON_PrintUnformatted(jsonRoot);
+    // Rownerid
+    {
+        char *rowner = NULL;
+        cborEncoderResult = cbor_encode_text_string(&aclMap, OIC_JSON_ROWNERID_NAME,
+            strlen(OIC_JSON_ROWNERID_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding rownerid Name.");
+        ret = ConvertUuidToStr(&secAcl->rownerID, &rowner);
+        VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
+        cborEncoderResult = cbor_encode_text_string(&aclMap, rowner, strlen(rowner));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding rownerid Value.");
+        OICFree(rowner);
     }
 
+    // Close ACL Map
+    cborEncoderResult = cbor_encoder_close_container(&encoder, &aclMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing ACL Map.");
+
+    if (CborNoError == cborEncoderResult)
+    {
+        OIC_LOG(DEBUG, TAG, "AclToCBORPayload Successed");
+        *size = encoder.ptr - outPayload;
+        *payload = outPayload;
+        ret = OC_STACK_OK;
+    }
 exit:
-    if (jsonRoot)
+    if (CborErrorOutOfMemory == cborEncoderResult)
     {
-        cJSON_Delete(jsonRoot);
+        OIC_LOG(DEBUG, TAG, "AclToCBORPayload:CborErrorOutOfMemory : retry with more memory");
+
+        // reallocate and try again!
+        OICFree(outPayload);
+        // Since the allocated initial memory failed, double the memory.
+        cborLen += encoder.ptr - encoder.end;
+        cborEncoderResult = CborNoError;
+        ret = AclToCBORPayload(secAcl, payload, &cborLen);
+        *size = cborLen;
     }
-    return jsonStr;
+    else if (cborEncoderResult != CborNoError)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to AclToCBORPayload");
+        OICFree(outPayload);
+        outPayload = NULL;
+        *size = 0;
+        *payload = NULL;
+        ret = OC_STACK_ERROR;
+    }
+
+    return ret;
 }
 
-/*
- * This internal method converts JSON ACL into binary ACL.
- */
-OicSecAcl_t * JSONToAclBin(const char * jsonStr)
+// This function converts CBOR format to ACL data.
+// Caller needs to invoke 'free' when done using
+// note: This function is used in unit test hence not declared static,
+OicSecAcl_t* CBORPayloadToAcl(const uint8_t *cborPayload, const size_t size)
 {
+    if (NULL == cborPayload || 0 == size)
+    {
+        return NULL;
+    }
     OCStackResult ret = OC_STACK_ERROR;
-    OicSecAcl_t * headAcl = NULL;
-    OicSecAcl_t * prevAcl = NULL;
-    cJSON *jsonRoot = NULL;
-    cJSON *jsonAclArray = NULL;
+    CborValue aclCbor = { .parser = NULL };
+    CborParser parser = { .end = NULL };
+    CborError cborFindResult = CborNoError;
+    cbor_parser_init(cborPayload, size, 0, &parser, &aclCbor);
 
-    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
+    OicSecAcl_t *headAcl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
 
-    jsonRoot = cJSON_Parse(jsonStr);
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+    // Enter ACL Map
+    CborValue aclMap = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
+    cborFindResult = cbor_value_enter_container(&aclCbor, &aclMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering ACL Map.");
 
-    jsonAclArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_ACL_NAME);
-    VERIFY_NON_NULL(TAG, jsonAclArray, ERROR);
-
-    if (cJSON_Array == jsonAclArray->type)
+    while (cbor_value_is_valid(&aclMap))
     {
-        int numAcl = cJSON_GetArraySize(jsonAclArray);
-        int idx = 0;
-
-        VERIFY_SUCCESS(TAG, numAcl > 0, INFO);
-        do
+        char* tagName = NULL;
+        size_t len = 0;
+        CborType type = cbor_value_get_type(&aclMap);
+        if (type == CborTextStringType)
         {
-            cJSON *jsonAcl = cJSON_GetArrayItem(jsonAclArray, idx);
-            VERIFY_NON_NULL(TAG, jsonAcl, ERROR);
-
-            OicSecAcl_t *acl = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t));
-            VERIFY_NON_NULL(TAG, acl, ERROR);
-
-            headAcl = (headAcl) ? headAcl : acl;
-            if (prevAcl)
+            cborFindResult = cbor_value_dup_text_string(&aclMap, &tagName, &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Name in ACL Map.");
+            cborFindResult = cbor_value_advance(&aclMap);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Value in ACL Map.");
+        }
+        if(tagName)
+        {
+            if (strcmp(tagName, OIC_JSON_ACLIST_NAME)  == 0)
             {
-                prevAcl->next = acl;
-            }
+                // Enter ACLIST Map
+                CborValue aclistMap = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
+                cborFindResult = cbor_value_enter_container(&aclMap, &aclistMap);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering ACLIST Map.");
 
-            size_t jsonObjLen = 0;
-            cJSON *jsonObj = NULL;
-
-            unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
-            uint32_t outLen = 0;
-            B64Result b64Ret = B64_OK;
-
-            // Subject -- Mandatory
-            jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_SUBJECT_NAME);
-            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-            VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
-            outLen = 0;
-            b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
-                        sizeof(base64Buff), &outLen);
-            VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(acl->subject.id)), ERROR);
-            memcpy(acl->subject.id, base64Buff, outLen);
-
-            // Resources -- Mandatory
-            jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_RESOURCES_NAME);
-            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
-
-            acl->resourcesLen = cJSON_GetArraySize(jsonObj);
-            VERIFY_SUCCESS(TAG, acl->resourcesLen > 0, ERROR);
-            acl->resources = (char**)OICCalloc(acl->resourcesLen, sizeof(char*));
-            VERIFY_NON_NULL(TAG, (acl->resources), ERROR);
-
-            size_t idxx = 0;
-            do
-            {
-                cJSON *jsonRsrc = cJSON_GetArrayItem(jsonObj, idxx);
-                VERIFY_NON_NULL(TAG, jsonRsrc, ERROR);
-
-                jsonObjLen = strlen(jsonRsrc->valuestring) + 1;
-                acl->resources[idxx] = (char*)OICMalloc(jsonObjLen);
-                VERIFY_NON_NULL(TAG, (acl->resources[idxx]), ERROR);
-                OICStrcpy(acl->resources[idxx], jsonObjLen, jsonRsrc->valuestring);
-            } while ( ++idxx < acl->resourcesLen);
-
-            // Permissions -- Mandatory
-            jsonObj = cJSON_GetObjectItem(jsonAcl,
-                                OIC_JSON_PERMISSION_NAME);
-            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-            VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
-            acl->permission = jsonObj->valueint;
-
-            //Period -- Not Mandatory
-            cJSON *jsonPeriodObj = cJSON_GetObjectItem(jsonAcl,
-                    OIC_JSON_PERIODS_NAME);
-            if(jsonPeriodObj)
-            {
-                VERIFY_SUCCESS(TAG, cJSON_Array == jsonPeriodObj->type,
-                               ERROR);
-                acl->prdRecrLen = cJSON_GetArraySize(jsonPeriodObj);
-                if(acl->prdRecrLen > 0)
-                {
-                    acl->periods = (char**)OICCalloc(acl->prdRecrLen,
-                                    sizeof(char*));
-                    VERIFY_NON_NULL(TAG, acl->periods, ERROR);
 
-                    cJSON *jsonPeriod = NULL;
-                    for(size_t i = 0; i < acl->prdRecrLen; i++)
+                while (cbor_value_is_valid(&aclistMap))
+                {
+                    char* acName = NULL;
+                    size_t acLen = 0;
+                    CborType acType = cbor_value_get_type(&aclistMap);
+                    if (acType == CborTextStringType)
                     {
-                        jsonPeriod = cJSON_GetArrayItem(jsonPeriodObj, i);
-                        VERIFY_NON_NULL(TAG, jsonPeriod, ERROR);
-
-                        jsonObjLen = strlen(jsonPeriod->valuestring) + 1;
-                        acl->periods[i] = (char*)OICMalloc(jsonObjLen);
-                        VERIFY_NON_NULL(TAG, acl->periods[i], ERROR);
-                        OICStrcpy(acl->periods[i], jsonObjLen,
-                                  jsonPeriod->valuestring);
+                        cborFindResult = cbor_value_dup_text_string(&aclistMap, &acName, &acLen, NULL);
+                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Name in ACLIST Map.");
+                        cborFindResult = cbor_value_advance(&aclistMap);
+                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Value in ACLIST Map.");
                     }
-                }
-            }
-
-            //Recurrence -- Not mandatory
-            cJSON *jsonRecurObj = cJSON_GetObjectItem(jsonAcl,
-                                        OIC_JSON_RECURRENCES_NAME);
-            if(jsonRecurObj)
-            {
-                VERIFY_SUCCESS(TAG, cJSON_Array == jsonRecurObj->type,
-                               ERROR);
+                    if(acName)
+                    {
+                        if (strcmp(acName, OIC_JSON_ACES_NAME)  == 0)
+                        {
 
-                if(acl->prdRecrLen > 0)
-                {
-                    acl->recurrences = (char**)OICCalloc(acl->prdRecrLen,
-                                             sizeof(char*));
-                    VERIFY_NON_NULL(TAG, acl->recurrences, ERROR);
+                            // Enter ACES Array
+                            CborValue aclArray = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
+                            cborFindResult = cbor_value_enter_container(&aclistMap, &aclArray);
+                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering ACL Array.");
+
+                            int acesCount = 0;
+                            while (cbor_value_is_valid(&aclArray))
+                            {
+                                acesCount++;
+
+                                CborValue aclMap = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
+                                cborFindResult = cbor_value_enter_container(&aclArray, &aclMap);
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering ACL Map.");
+                                OicSecAcl_t *acl = NULL;
+
+                                if(acesCount == 1)
+                                {
+                                    acl = headAcl;
+                                }
+                                else
+                                {
+                                    acl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
+                                    OicSecAcl_t *temp = headAcl;
+                                    while (temp->next)
+                                    {
+                                        temp = temp->next;
+                                    }
+                                    temp->next = acl;
+                                }
+                                VERIFY_NON_NULL(TAG, acl, ERROR);
+
+                                while (cbor_value_is_valid(&aclMap))
+                                {
+                                    char* name = NULL;
+                                    size_t len = 0;
+                                    CborType type = cbor_value_get_type(&aclMap);
+                                    if (type == CborTextStringType)
+                                    {
+                                        cborFindResult = cbor_value_dup_text_string(&aclMap, &name, &len, NULL);
+                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Name in ACL Map.");
+                                        cborFindResult = cbor_value_advance(&aclMap);
+                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Value in ACL Map.");
+                                    }
+                                    if (name)
+                                    {
+                                        // Subject -- Mandatory
+                                        if (strcmp(name, OIC_JSON_SUBJECTID_NAME)  == 0)
+                                        {
+                                            char *subject = NULL;
+                                            cborFindResult = cbor_value_dup_text_string(&aclMap, &subject, &len, NULL);
+                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding subject Value.");
+                                            if(strcmp(subject, WILDCARD_RESOURCE_URI) == 0)
+                                            {
+                                                acl->subject.id[0] = '*';
+                                            }
+                                            else
+                                            {
+                                                ret = ConvertStrToUuid(subject, &acl->subject);
+                                                VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
+                                            }
+                                            OICFree(subject);
+                                        }
+
+                                        // Resources -- Mandatory
+                                        if (strcmp(name, OIC_JSON_RESOURCES_NAME) == 0)
+                                        {
+                                            CborValue resources = { .parser = NULL };
+                                            cborFindResult = cbor_value_get_array_length(&aclMap, &acl->resourcesLen);
+                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Resource Array Len Value.");
+                                            cborFindResult = cbor_value_enter_container(&aclMap, &resources);
+                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering a Resource Array.");
+
+                                            acl->resources = (char **) OICMalloc(acl->resourcesLen * sizeof(char*));
+                                            VERIFY_NON_NULL(TAG, acl->resources, ERROR);
+                                            int i = 0;
+                                            while (cbor_value_is_valid(&resources))
+                                            {
+                                                // rMap
+                                                CborValue rMap = { .parser = NULL  };
+                                                cborFindResult = cbor_value_enter_container(&resources, &rMap);
+                                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Resource Map");
+
+
+                                                while(cbor_value_is_valid(&rMap))
+                                                {
+                                                    char *rMapName = NULL;
+                                                    size_t rMapNameLen = 0;
+                                                    cborFindResult = cbor_value_dup_text_string(&rMap, &rMapName, &rMapNameLen, NULL);
+                                                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding RMap Data Name Tag.");
+                                                    cborFindResult = cbor_value_advance(&rMap);
+                                                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding RMap Data Value.");
+
+                                                    // "href"
+                                                    if (0 == strcmp(OIC_JSON_HREF_NAME, rMapName))
+                                                    {
+                                                        // TODO : Need to check data structure of OicSecAcl_t based on RAML spec.
+                                                        cborFindResult = cbor_value_dup_text_string(&rMap, &acl->resources[i++], &len, NULL);
+                                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Href Value.");
+                                                    }
+                                                    // "rel"
+                                                    if (0 == strcmp(OIC_JSON_REL_NAME, rMapName))
+                                                    {
+                                                        // TODO : Need to check data structure of OicSecAcl_t based on RAML spec.
+                                                        char *relData = NULL;
+                                                        cborFindResult = cbor_value_dup_text_string(&rMap, &relData, &len, NULL);
+                                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding REL Value.");
+                                                        OICFree(relData);
+                                                    }
+                                                    // "rt"
+                                                    if (0 == strcmp(OIC_JSON_RT_NAME, rMapName))
+                                                    {
+                                                        // TODO : Need to check data structure of OicSecAcl_t and assign based on RAML spec.
+                                                        char *rtData = NULL;
+                                                        cborFindResult = cbor_value_dup_text_string(&rMap, &rtData, &len, NULL);
+                                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding RT Value.");
+                                                        OICFree(rtData);
+                                                    }
+
+                                                    // "if"
+                                                    if (0 == strcmp(OIC_JSON_IF_NAME, rMapName))
+                                                    {
+                                                        // TODO : Need to check data structure of OicSecAcl_t and assign based on RAML spec.
+                                                        char *ifData = NULL;
+                                                        cborFindResult = cbor_value_dup_text_string(&rMap, &ifData, &len, NULL);
+                                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding IF Value.");
+                                                        OICFree(ifData);
+                                                    }
+
+                                                    if (cbor_value_is_valid(&rMap))
+                                                    {
+                                                        cborFindResult = cbor_value_advance(&rMap);
+                                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Rlist Map.");
+                                                    }
+                                                    OICFree(rMapName);
+                                                }
+
+                                                if (cbor_value_is_valid(&resources))
+                                                {
+                                                    cborFindResult = cbor_value_advance(&resources);
+                                                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Resource Array.");
+                                                }
+                                            }
+                                        }
+
+                                        // Permissions -- Mandatory
+                                        if (strcmp(name, OIC_JSON_PERMISSION_NAME) == 0)
+                                        {
+                                            cborFindResult = cbor_value_get_uint64(&aclMap, (uint64_t *) &acl->permission);
+                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a PERM Value.");
+                                        }
+
+                                        // Period -- Not mandatory
+                                        if (strcmp(name, OIC_JSON_PERIOD_NAME) == 0)
+                                        {
+                                            CborValue period = { .parser = NULL };
+                                            cborFindResult = cbor_value_get_array_length(&aclMap, &acl->prdRecrLen);
+                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Period Array Len.");
+                                            cborFindResult = cbor_value_enter_container(&aclMap, &period);
+                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Period Array Map.");
+                                            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))
+                                            {
+                                                cborFindResult = cbor_value_dup_text_string(&period, &acl->periods[i++],
+                                                    &len, NULL);
+                                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Period Array Value.");
+                                                cborFindResult = cbor_value_advance(&period);
+                                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing a Period Array.");
+                                            }
+                                        }
+
+                                        // Recurrence -- Not mandatory
+                                        if (strcmp(name, OIC_JSON_RECURRENCES_NAME) == 0)
+                                        {
+                                            CborValue recurrences = { .parser = NULL };
+                                            cborFindResult = cbor_value_enter_container(&aclMap, &recurrences);
+                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Adding Recurrence Array.");
+                                            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))
+                                            {
+                                                cborFindResult = cbor_value_dup_text_string(&recurrences,
+                                                    &acl->recurrences[i++], &len, NULL);
+                                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Adding Recurrence Array Value.");
+                                                cborFindResult = cbor_value_advance(&recurrences);
+                                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Closing Recurrence Array.");
+                                            }
+                                        }
+
+                                        OICFree(name);
+                                    }
+
+                                    if (type != CborMapType && cbor_value_is_valid(&aclMap))
+                                    {
+                                        cborFindResult = cbor_value_advance(&aclMap);
+                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing the Array.");
+                                    }
+                                }
+
+                                acl->next = NULL;
+
+                                if (cbor_value_is_valid(&aclArray))
+                                {
+                                    cborFindResult = cbor_value_advance(&aclArray);
+                                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing ACL Array.");
+                                }
+                            }
+                        }
+                        OICFree(acName);
+                    }
 
-                    cJSON *jsonRecur = NULL;
-                    for(size_t i = 0; i < acl->prdRecrLen; i++)
+                    if (cbor_value_is_valid(&aclistMap))
                     {
-                        jsonRecur = cJSON_GetArrayItem(jsonRecurObj, i);
-                        VERIFY_NON_NULL(TAG, jsonRecur, ERROR);
-                        jsonObjLen = strlen(jsonRecur->valuestring) + 1;
-                        acl->recurrences[i] = (char*)OICMalloc(jsonObjLen);
-                        VERIFY_NON_NULL(TAG, acl->recurrences[i], ERROR);
-                        OICStrcpy(acl->recurrences[i], jsonObjLen,
-                              jsonRecur->valuestring);
+                        cborFindResult = cbor_value_advance(&aclistMap);
+                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing ACLIST Map.");
                     }
                 }
             }
 
-            // Owners -- Mandatory
-            jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_OWNERS_NAME);
-            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
-
-            acl->ownersLen = cJSON_GetArraySize(jsonObj);
-            VERIFY_SUCCESS(TAG, acl->ownersLen > 0, ERROR);
-            acl->owners = (OicUuid_t*)OICCalloc(acl->ownersLen, sizeof(OicUuid_t));
-            VERIFY_NON_NULL(TAG, (acl->owners), ERROR);
-
-            idxx = 0;
-            do
+            // TODO : Need to modify headAcl->owners[0].id to headAcl->rowner based on RAML spec.
+            if (strcmp(tagName, OIC_JSON_ROWNERID_NAME)  == 0)
             {
-                cJSON *jsonOwnr = cJSON_GetArrayItem(jsonObj, idxx);
-                VERIFY_NON_NULL(TAG, jsonOwnr, ERROR);
-                VERIFY_SUCCESS(TAG, cJSON_String == jsonOwnr->type, ERROR);
-
-                outLen = 0;
-                b64Ret = b64Decode(jsonOwnr->valuestring, strlen(jsonOwnr->valuestring), base64Buff,
-                            sizeof(base64Buff), &outLen);
-
-                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(acl->owners[idxx].id)),
-                                    ERROR);
-                memcpy(acl->owners[idxx].id, base64Buff, outLen);
-            } while ( ++idxx < acl->ownersLen);
-
-            prevAcl = acl;
-        } while( ++idx < numAcl);
+                char *stRowner = NULL;
+                cborFindResult = cbor_value_dup_text_string(&aclMap, &stRowner, &len, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Rownerid Value.");
+                ret = ConvertStrToUuid(stRowner, &headAcl->rownerID);
+                VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
+                OICFree(stRowner);
+            }
+            OICFree(tagName);
+        }
+        if (cbor_value_is_valid(&aclMap))
+        {
+            cborFindResult = cbor_value_advance(&aclMap);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing ACL Map.");
+        }
     }
 
-    ret = OC_STACK_OK;
-
 exit:
-    cJSON_Delete(jsonRoot);
-    if (OC_STACK_OK != ret)
+    if (cborFindResult != CborNoError)
     {
+        OIC_LOG(ERROR, TAG, "Failed to CBORPayloadToAcl");
         DeleteACLList(headAcl);
         headAcl = NULL;
     }
     return headAcl;
 }
 
-static bool UpdatePersistentStorage(const OicSecAcl_t *acl)
-{
-    // Convert ACL data into JSON for update to persistent storage
-    char *jsonStr = BinToAclJSON(acl);
-    if (jsonStr)
-    {
-        cJSON *jsonAcl = cJSON_Parse(jsonStr);
-        OICFree(jsonStr);
-
-        if ((jsonAcl) && (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_ACL_NAME, jsonAcl)))
-        {
-            return true;
-        }
-        cJSON_Delete(jsonAcl);
-    }
-    return false;
-}
-
-/*
+/**
  * This method removes ACE for the subject and resource from the ACL
  *
- * @param subject  - subject of the ACE
- * @param resource - resource of the ACE
+ * @param subject of the ACE
+ * @param resource of the ACE
  *
  * @return
- *     OC_STACK_RESOURCE_DELETED on success
- *     OC_STACK_NO_RESOURC on failure to find the appropriate ACE
- *     OC_STACK_INVALID_PARAM on invalid parameter
+ *     ::OC_STACK_RESOURCE_DELETED on success
+ *     ::OC_STACK_NO_RESOURCE on failure to find the appropriate ACE
+ *     ::OC_STACK_INVALID_PARAM on invalid parameter
  */
-static OCStackResult RemoveACE(const OicUuid_t * subject,
-                               const char * resource)
+static OCStackResult RemoveACE(const OicUuid_t * subject, const char * resource)
 {
-    OC_LOG(DEBUG, TAG, "IN RemoveACE");
+    OIC_LOG(DEBUG, TAG, "IN RemoveACE");
 
     OicSecAcl_t *acl = NULL;
     OicSecAcl_t *tempAcl = NULL;
     bool deleteFlag = false;
     OCStackResult ret = OC_STACK_NO_RESOURCE;
 
-    if(memcmp(subject->id, &WILDCARD_SUBJECT_ID, sizeof(subject->id)) == 0)
+    if (memcmp(subject->id, &WILDCARD_SUBJECT_ID, sizeof(subject->id)) == 0)
     {
-        OC_LOG_V (ERROR, TAG, "%s received invalid parameter", __func__ );
+        OIC_LOG_V(ERROR, TAG, "%s received invalid parameter", __func__ );
         return  OC_STACK_INVALID_PARAM;
     }
 
     //If resource is NULL then delete all the ACE for the subject.
-    if(NULL == resource || resource[0] == '\0')
+    if (NULL == resource || resource[0] == '\0')
     {
         LL_FOREACH_SAFE(gAcl, acl, tempAcl)
         {
-            if(memcmp(acl->subject.id, subject->id, sizeof(subject->id)) == 0)
+            if (memcmp(acl->subject.id, subject->id, sizeof(subject->id)) == 0)
             {
                 LL_DELETE(gAcl, acl);
                 FreeACE(acl);
@@ -471,9 +752,9 @@ static OCStackResult RemoveACE(const OicUuid_t * subject,
         //the resource array
         LL_FOREACH_SAFE(gAcl, acl, tempAcl)
         {
-            if(memcmp(acl->subject.id, subject->id, sizeof(subject->id)) == 0)
+            if (memcmp(acl->subject.id, subject->id, sizeof(subject->id)) == 0)
             {
-                if(1 == acl->resourcesLen && strcmp(acl->resources[0],  resource) == 0)
+                if (1 == acl->resourcesLen && strcmp(acl->resources[0], resource) == 0)
                 {
                     LL_DELETE(gAcl, acl);
                     FreeACE(acl);
@@ -482,24 +763,24 @@ static OCStackResult RemoveACE(const OicUuid_t * subject,
                 }
                 else
                 {
-                    int resPos = -1;
+                    size_t resPos = -1;
                     size_t i;
-                    for(i = 0; i < acl->resourcesLen; i++)
+                    for (i = 0; i < acl->resourcesLen; i++)
                     {
-                        if(strcmp(acl->resources[i],  resource) == 0)
+                        if (strcmp(acl->resources[i], resource) == 0)
                         {
                             resPos = i;
                             break;
                         }
                     }
-                    if((0 <= resPos))
+                    if (0 <= (int) resPos)
                     {
                         OICFree(acl->resources[resPos]);
                         acl->resources[resPos] = NULL;
                         acl->resourcesLen -= 1;
-                        for(i = resPos; i < acl->resourcesLen; i++)
+                        for (i = resPos; i < acl->resourcesLen; i++)
                         {
-                            acl->resources[i] = acl->resources[i+1];
+                            acl->resources[i] = acl->resources[i + 1];
                         }
                         deleteFlag = true;
                         break;
@@ -509,17 +790,31 @@ static OCStackResult RemoveACE(const OicUuid_t * subject,
         }
     }
 
-    if(deleteFlag)
+    if (deleteFlag)
     {
-        if(UpdatePersistentStorage(gAcl))
+        // In case of unit test do not update persistant storage.
+        if (memcmp(subject->id, &WILDCARD_SUBJECT_B64_ID, sizeof(subject->id)) == 0)
         {
             ret = OC_STACK_RESOURCE_DELETED;
         }
+        else
+        {
+            uint8_t *payload = NULL;
+            size_t size = 0;
+            if (OC_STACK_OK == AclToCBORPayload(gAcl, &payload, &size))
+            {
+                if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, payload, size))
+                {
+                    ret = OC_STACK_RESOURCE_DELETED;
+                }
+                OICFree(payload);
+            }
+        }
     }
     return ret;
 }
 
-/*
+/**
  * This method parses the query string received for REST requests and
  * retrieves the 'subject' field.
  *
@@ -530,33 +825,25 @@ static OCStackResult RemoveACE(const OicUuid_t * subject,
  */
 static bool GetSubjectFromQueryString(const char *query, OicUuid_t *subject)
 {
-    OicParseQueryIter_t parseIter = {.attrPos=NULL};
+    OicParseQueryIter_t parseIter = { .attrPos = NULL };
 
-    ParseQueryIterInit((unsigned char *)query, &parseIter);
+    ParseQueryIterInit((unsigned char *) query, &parseIter);
 
-
-    while(GetNextQuery(&parseIter))
+    while (GetNextQuery (&parseIter))
     {
-        if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBJECT_NAME, parseIter.attrLen) == 0)
+        if (strncasecmp((char *) parseIter.attrPos, OIC_JSON_SUBJECTID_NAME, parseIter.attrLen) == 0)
         {
             VERIFY_SUCCESS(TAG, 0 != parseIter.valLen, ERROR);
-            unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
-            uint32_t outLen = 0;
-            B64Result b64Ret = B64_OK;
-            b64Ret = b64Decode((char *)parseIter.valPos, parseIter.valLen, base64Buff,
-                    sizeof(base64Buff), &outLen);
-            VERIFY_SUCCESS(TAG, (B64_OK == b64Ret && outLen <= sizeof(subject->id)), ERROR);
-            memcpy(subject->id, base64Buff, outLen);
-
+            memcpy(subject->id, parseIter.valPos, parseIter.valLen);
             return true;
         }
     }
 
 exit:
-   return false;
+    return false;
 }
 
-/*
+/**
  * This method parses the query string received for REST requests and
  * retrieves the 'resource' field.
  *
@@ -568,16 +855,17 @@ exit:
  */
 static bool GetResourceFromQueryString(const char *query, char *resource, size_t resourceSize)
 {
-    OicParseQueryIter_t parseIter = {.attrPos=NULL};
+    OicParseQueryIter_t parseIter = { .attrPos = NULL };
 
-    ParseQueryIterInit((unsigned char *)query, &parseIter);
+    ParseQueryIterInit((unsigned char *) query, &parseIter);
 
-    while(GetNextQuery(&parseIter))
+    while (GetNextQuery (&parseIter))
     {
-        if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_RESOURCES_NAME, parseIter.attrLen) == 0)
+        if (strncasecmp((char *) parseIter.attrPos, OIC_JSON_RESOURCES_NAME, parseIter.attrLen)
+                == 0)
         {
             VERIFY_SUCCESS(TAG, 0 != parseIter.valLen, ERROR);
-            OICStrcpy(resource, resourceSize, (char *)parseIter.valPos);
+            OICStrcpy(resource, resourceSize, (char *) parseIter.valPos);
 
             return true;
         }
@@ -587,28 +875,26 @@ exit:
    return false;
 }
 
-
-
-static OCEntityHandlerResult HandleACLGetRequest (const OCEntityHandlerRequest * ehRequest)
+static OCEntityHandlerResult HandleACLGetRequest(const OCEntityHandlerRequest *ehRequest)
 {
-    OCEntityHandlerResult ehRet = OC_EH_ERROR;
-    char* jsonStr = NULL;
+    OIC_LOG(INFO, TAG, "HandleACLGetRequest processing the request");
+    uint8_t* payload = NULL;
+    size_t size = 0;
+    OCEntityHandlerResult ehRet;
 
     // Process the REST querystring parameters
-    if(ehRequest->query)
+    if (ehRequest->query)
     {
-        OC_LOG (DEBUG, TAG, "HandleACLGetRequest processing query");
+        OIC_LOG(DEBUG, TAG, "HandleACLGetRequest processing query");
 
-        OicUuid_t subject = {.id={0}};
-        char resource[MAX_URI_LENGTH] = {0};
+        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);
+        VERIFY_SUCCESS(TAG, true == GetSubjectFromQueryString(ehRequest->query, &subject), ERROR);
 
         GetResourceFromQueryString(ehRequest->query, resource, sizeof(resource));
 
@@ -617,7 +903,7 @@ static OCEntityHandlerResult HandleACLGetRequest (const OCEntityHandlerRequest *
          * Below code needs to be updated for scenarios when Subject have
          * multiple ACE's in ACL resource.
          */
-        while((currentAce = GetACLResourceData(&subject, &savePtr)))
+        while ((currentAce = GetACLResourceData(&subject, &savePtr)))
         {
             /*
              * If REST querystring contains a specific resource, we need
@@ -625,106 +911,138 @@ static OCEntityHandlerResult HandleACLGetRequest (const OCEntityHandlerRequest *
              */
             if (resource[0] != '\0')
             {
-                for(size_t n = 0; n < currentAce->resourcesLen; n++)
+                for (size_t n = 0; n < currentAce->resourcesLen; n++)
                 {
-                    if((currentAce->resources[n]) &&
-                            (0 == strcmp(resource, currentAce->resources[n]) ||
-                             0 == strcmp(WILDCARD_RESOURCE_URI, currentAce->resources[n])))
+                    if ((currentAce->resources[n])
+                            && (0 == strcmp(resource, currentAce->resources[n])
+                                    || 0 == strcmp(WILDCARD_RESOURCE_URI, currentAce->resources[n])))
                     {
-                        // Convert ACL data into JSON for transmission
-                        jsonStr = BinToAclJSON(currentAce);
+                        // Convert ACL data into CBOR format for transmission
+                        if (OC_STACK_OK != AclToCBORPayload(currentAce, &payload, &size))
+                        {
+                            ehRet = OC_EH_ERROR;
+                        }
                         goto exit;
                     }
                 }
             }
             else
             {
-                // Convert ACL data into JSON for transmission
-                jsonStr = BinToAclJSON(currentAce);
+                // Convert ACL data into CBOR format for transmission
+                if (OC_STACK_OK != AclToCBORPayload(currentAce, &payload, &size))
+                {
+                    ehRet = OC_EH_ERROR;
+                }
                 goto exit;
             }
         }
     }
     else
     {
-        // Convert ACL data into JSON for transmission
-        jsonStr = BinToAclJSON(gAcl);
+        // Convert ACL data into CBOR format for transmission.
+        if (OC_STACK_OK != AclToCBORPayload(gAcl, &payload, &size))
+        {
+            ehRet = OC_EH_ERROR;
+        }
     }
-
 exit:
-    ehRet = (jsonStr ? OC_EH_OK : OC_EH_ERROR);
+    // A device should always have a default acl. Therefore, payload should never be NULL.
+    ehRet = (payload ? OC_EH_OK : OC_EH_ERROR);
 
     // Send response payload to request originator
-    SendSRMResponse(ehRequest, ehRet, jsonStr);
-
-    OICFree(jsonStr);
+    if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, payload, size))
+    {
+        ehRet = OC_EH_ERROR;
+        OIC_LOG(ERROR, TAG, "SendSRMResponse failed for HandleACLGetRequest");
+    }
+    OICFree(payload);
 
-    OC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
+    OIC_LOG_V(DEBUG, TAG, "%s RetVal %d", __func__, ehRet);
     return ehRet;
 }
 
-static OCEntityHandlerResult HandleACLPostRequest (const OCEntityHandlerRequest * ehRequest)
+static OCEntityHandlerResult HandleACLPostRequest(const OCEntityHandlerRequest *ehRequest)
 {
+    OIC_LOG(INFO, TAG, "HandleACLPostRequest processing the request");
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
 
-    // Convert JSON ACL data into binary. This will also validate the ACL data received.
-    OicSecAcl_t* newAcl = JSONToAclBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
-
-    if (newAcl)
+    // Convert CBOR into ACL data and update to SVR buffers. This will also validate the ACL data received.
+    uint8_t *payload = ((OCSecurityPayload *) ehRequest->payload)->securityData;
+    size_t size = ((OCSecurityPayload *) ehRequest->payload)->payloadSize;
+    if (payload)
     {
-        // Append the new ACL to existing ACL
-        LL_APPEND(gAcl, newAcl);
-
-        if(UpdatePersistentStorage(gAcl))
+        OicSecAcl_t *newAcl = CBORPayloadToAcl(payload, size);
+        if (newAcl)
         {
-            ehRet = OC_EH_RESOURCE_CREATED;
+            // Append the new ACL to existing ACL
+            LL_APPEND(gAcl, newAcl);
+            size_t size = 0;
+            // In case of unit test do not update persistant storage.
+            if (memcmp(newAcl->subject.id, &WILDCARD_SUBJECT_ID, sizeof(newAcl->subject.id)) == 0
+                || memcmp(newAcl->subject.id, &WILDCARD_SUBJECT_B64_ID, sizeof(newAcl->subject.id)) == 0)
+            {
+                ehRet = OC_EH_RESOURCE_CREATED;
+            }
+            else
+            {
+                uint8_t *cborPayload = NULL;
+                if (OC_STACK_OK == AclToCBORPayload(gAcl, &cborPayload, &size))
+                {
+                    if (UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, cborPayload, size) == OC_STACK_OK)
+                    {
+                        ehRet = OC_EH_RESOURCE_CREATED;
+                    }
+                    OICFree(cborPayload);
+                }
+            }
         }
     }
 
     // Send payload to request originator
-    SendSRMResponse(ehRequest, ehRet, NULL);
+    if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL, 0))
+    {
+        ehRet = OC_EH_ERROR;
+        OIC_LOG(ERROR, TAG, "SendSRMResponse failed in HandleACLPostRequest");
+    }
 
-    OC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
+    OIC_LOG_V(DEBUG, TAG, "%s RetVal %d", __func__, ehRet);
     return ehRet;
 }
 
 static OCEntityHandlerResult HandleACLDeleteRequest(const OCEntityHandlerRequest *ehRequest)
 {
-    OC_LOG (DEBUG, TAG, "Processing ACLDeleteRequest");
+    OIC_LOG(DEBUG, TAG, "Processing ACLDeleteRequest");
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
-    OicUuid_t subject = {.id={0}};
-    char resource[MAX_URI_LENGTH] = {0};
+    OicUuid_t subject = { .id= { 0 } };
+    char resource[MAX_URI_LENGTH] = { 0 };
 
     VERIFY_NON_NULL(TAG, ehRequest->query, ERROR);
 
     // 'Subject' field is MUST for processing a querystring in REST request.
-    VERIFY_SUCCESS(TAG,
-            true == GetSubjectFromQueryString(ehRequest->query, &subject),
-            ERROR);
+    VERIFY_SUCCESS(TAG, true == GetSubjectFromQueryString(ehRequest->query, &subject), ERROR);
 
     GetResourceFromQueryString(ehRequest->query, resource, sizeof(resource));
 
-    if(OC_STACK_RESOURCE_DELETED == RemoveACE(&subject, resource))
+    if (OC_STACK_RESOURCE_DELETED == RemoveACE(&subject, resource))
     {
         ehRet = OC_EH_RESOURCE_DELETED;
     }
 
 exit:
     // Send payload to request originator
-    SendSRMResponse(ehRequest, ehRet, NULL);
+    if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL, 0))
+    {
+        ehRet = OC_EH_ERROR;
+        OIC_LOG(ERROR, TAG, "SendSRMResponse failed in HandleACLDeleteRequest");
+    }
 
     return ehRet;
 }
 
-/*
- * This internal method is the entity handler for ACL resources and
- * will handle REST request (GET/PUT/POST/DEL) for them.
- */
-OCEntityHandlerResult ACLEntityHandler (OCEntityHandlerFlag flag,
-                                        OCEntityHandlerRequest * ehRequest,
-                                        void* callbackParameter)
+OCEntityHandlerResult ACLEntityHandler(OCEntityHandlerFlag flag, OCEntityHandlerRequest * ehRequest,
+        void* callbackParameter)
 {
-    OC_LOG(DEBUG, TAG, "Received request ACLEntityHandler");
+    OIC_LOG(DEBUG, TAG, "Received request ACLEntityHandler");
     (void)callbackParameter;
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
 
@@ -736,7 +1054,7 @@ OCEntityHandlerResult ACLEntityHandler (OCEntityHandlerFlag flag,
     if (flag & OC_REQUEST_FLAG)
     {
         // TODO :  Handle PUT method
-        OC_LOG (DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
+        OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
         switch (ehRequest->method)
         {
             case OC_REST_GET:
@@ -753,17 +1071,17 @@ OCEntityHandlerResult ACLEntityHandler (OCEntityHandlerFlag flag,
 
             default:
                 ehRet = OC_EH_ERROR;
-                SendSRMResponse(ehRequest, ehRet, NULL);
+                SendSRMResponse(ehRequest, ehRet, NULL, 0);
         }
     }
 
     return ehRet;
 }
 
-/*
+/**
  * This internal method is used to create '/oic/sec/acl' resource.
  */
-OCStackResult CreateACLResource()
+static OCStackResult CreateACLResource()
 {
     OCStackResult ret;
 
@@ -777,23 +1095,24 @@ OCStackResult CreateACLResource()
 
     if (OC_STACK_OK != ret)
     {
-        OC_LOG (FATAL, TAG, "Unable to instantiate ACL resource");
+        OIC_LOG(FATAL, TAG, "Unable to instantiate ACL resource");
         DeInitACLResource();
     }
     return ret;
 }
 
-/*
- * This internal method is to retrieve the default ACL.
- * If SVR database in persistent storage got corrupted or
- * is not available for some reason, a default ACL is created
- * which allows user to initiate ACL provisioning again.
- */
-OCStackResult  GetDefaultACL(OicSecAcl_t** defaultAcl)
+// This function sets the default ACL and is defined for the unit test only.
+OCStackResult SetDefaultACL(OicSecAcl_t *acl)
+{
+    gAcl = acl;
+    return OC_STACK_OK;
+}
+
+OCStackResult GetDefaultACL(OicSecAcl_t** defaultAcl)
 {
     OCStackResult ret = OC_STACK_ERROR;
 
-    OicUuid_t ownerId = {.id = {0}};
+    OicUuid_t ownerId = { .id = { 0 } };
 
     /*
      * TODO In future, when new virtual resources will be added in OIC
@@ -820,22 +1139,22 @@ OCStackResult  GetDefaultACL(OicSecAcl_t** defaultAcl)
         return OC_STACK_INVALID_PARAM;
     }
 
-    OicSecAcl_t *acl = (OicSecAcl_t *)OICCalloc(1, sizeof(OicSecAcl_t));
+    OicSecAcl_t *acl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
     VERIFY_NON_NULL(TAG, acl, ERROR);
 
     // Subject -- Mandatory
     memcpy(&(acl->subject), &WILDCARD_SUBJECT_ID, sizeof(acl->subject));
 
     // Resources -- Mandatory
-    acl->resourcesLen = sizeof(rsrcs)/sizeof(rsrcs[0]);
+    acl->resourcesLen = sizeof(rsrcs) / sizeof(rsrcs[0]);
 
-    acl->resources = (char**)OICCalloc(acl->resourcesLen, sizeof(char*));
+    acl->resources = (char**) OICCalloc(acl->resourcesLen, sizeof(char*));
     VERIFY_NON_NULL(TAG, (acl->resources), ERROR);
 
-    for (size_t i = 0; i <  acl->resourcesLen; i++)
+    for (size_t i = 0; i < acl->resourcesLen; i++)
     {
         size_t len = strlen(rsrcs[i]) + 1;
-        acl->resources[i] = (char*)OICMalloc(len * sizeof(char));
+        acl->resources[i] = (char*) OICMalloc(len * sizeof(char));
         VERIFY_NON_NULL(TAG, (acl->resources[i]), ERROR);
         OICStrcpy(acl->resources[i], len, rsrcs[i]);
     }
@@ -846,13 +1165,18 @@ OCStackResult  GetDefaultACL(OicSecAcl_t** defaultAcl)
     acl->recurrences = NULL;
 
     // Device ID is the owner of this default ACL
-    ret = GetDoxmDeviceID( &ownerId);
-    VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, FATAL);
+    if (GetDoxmResourceData() != NULL)
+    {
+        ret = GetDoxmDeviceID(&ownerId);
+        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, FATAL);
+    }
+    else
+    {
+        OCRandomUuidResult rdm = OCGenerateUuid(ownerId.id);
+        VERIFY_SUCCESS(TAG, RAND_UUID_OK == rdm, FATAL);
+    }
 
-    acl->ownersLen = 1;
-    acl->owners = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
-    VERIFY_NON_NULL(TAG, (acl->owners), ERROR);
-    memcpy(acl->owners, &ownerId, sizeof(OicUuid_t));
+    memcpy(&acl->rownerID, &ownerId, sizeof(OicUuid_t));
 
     acl->next = NULL;
 
@@ -870,30 +1194,29 @@ exit:
     return ret;
 }
 
-/**
- * Initialize ACL resource by loading data from persistent storage.
- *
- * @retval  OC_STACK_OK for Success, otherwise some error value
- */
 OCStackResult InitACLResource()
 {
     OCStackResult ret = OC_STACK_ERROR;
 
-    // Read ACL resource from PS
-    char* jsonSVRDatabase = GetSVRDatabase();
-
-    if (jsonSVRDatabase)
+    uint8_t *data = NULL;
+    size_t size = 0;
+    ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_ACL_NAME, &data, &size);
+    // If database read failed
+    if (ret != OC_STACK_OK)
     {
-        // Convert JSON ACL into binary format
-        gAcl = JSONToAclBin(jsonSVRDatabase);
-        OICFree(jsonSVRDatabase);
+        OIC_LOG(DEBUG, TAG, "ReadSVDataFromPS failed");
+    }
+    if (data)
+    {
+        // Read ACL resource from PS
+        gAcl = CBORPayloadToAcl(data, size);
     }
     /*
      * If SVR database in persistent storage got corrupted or
      * is not available for some reason, a default ACL is created
      * which allows user to initiate ACL provisioning again.
      */
-    if (!jsonSVRDatabase || !gAcl)
+    if (!gAcl)
     {
         GetDefaultACL(&gAcl);
         // TODO Needs to update persistent storage
@@ -911,37 +1234,25 @@ exit:
     return ret;
 }
 
-/**
- * Perform cleanup for ACL resources.
- *
- * @retval  none
- */
-void DeInitACLResource()
+OCStackResult DeInitACLResource()
 {
-    OCDeleteResource(gAclHandle);
+    OCStackResult ret =  OCDeleteResource(gAclHandle);
     gAclHandle = NULL;
 
-    DeleteACLList(gAcl);
-    gAcl = NULL;
+    if (gAcl)
+    {
+        DeleteACLList(gAcl);
+        gAcl = NULL;
+    }
+    return ret;
 }
 
-/**
- * This method is used by PolicyEngine to retrieve ACL for a Subject.
- *
- * @param subjectId ID of the subject for which ACL is required.
- * @param savePtr is used internally by @ref GetACLResourceData to maintain index between
- *                successive calls for same subjectId.
- *
- * @retval  reference to @ref OicSecAcl_t if ACL is found, else NULL
- *
- * @note On the first call to @ref GetACLResourceData, savePtr should point to NULL
- */
 const OicSecAcl_t* GetACLResourceData(const OicUuid_t* subjectId, OicSecAcl_t **savePtr)
 {
     OicSecAcl_t *acl = NULL;
     OicSecAcl_t *begin = NULL;
 
-    if ( NULL == subjectId)
+    if (NULL == subjectId)
     {
         return NULL;
     }
@@ -985,33 +1296,217 @@ const OicSecAcl_t* GetACLResourceData(const OicUuid_t* subjectId, OicSecAcl_t **
     return NULL;
 }
 
-
-OCStackResult InstallNewACL(const char* newJsonStr)
+OCStackResult InstallNewACL(const uint8_t *cborPayload, const size_t size)
 {
     OCStackResult ret = OC_STACK_ERROR;
 
-    // Convert JSON ACL data into binary. This will also validate the ACL data received.
-    OicSecAcl_t* newAcl = JSONToAclBin(newJsonStr);
+    // Convert CBOR format to ACL data. This will also validate the ACL data received.
+    OicSecAcl_t* newAcl = CBORPayloadToAcl(cborPayload, size);
 
     if (newAcl)
     {
         // Append the new ACL to existing ACL
         LL_APPEND(gAcl, newAcl);
 
-        // Convert ACL data into JSON for update to persistent storage
-        char *jsonStr = BinToAclJSON(gAcl);
-        if (jsonStr)
+        // Update persistent storage only if it is not WILDCARD_SUBJECT_ID
+        if (memcmp(newAcl->subject.id, &WILDCARD_SUBJECT_ID, sizeof(newAcl->subject.id)) == 0
+            || memcmp(newAcl->subject.id, &WILDCARD_SUBJECT_B64_ID, sizeof(newAcl->subject.id)) == 0)
+        {
+            ret = OC_STACK_OK;
+        }
+        else
         {
-            cJSON *jsonAcl = cJSON_Parse(jsonStr);
-            OICFree(jsonStr);
+            size_t size = 0;
+            uint8_t *payload = NULL;
+            if (OC_STACK_OK == AclToCBORPayload(gAcl, &payload, &size))
+            {
+                if (UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, payload, size) == OC_STACK_OK)
+                {
+                    ret = OC_STACK_OK;
+                }
+                OICFree(payload);
+            }
+        }
+    }
 
-            if (jsonAcl)
+    return ret;
+}
+
+/**
+ * This function generates default ACL for security resource in case of owned status.
+ *
+ * @return Default ACL for security resource.
+ */
+static OicSecAcl_t* GetSecDefaultACL()
+{
+    const char *sec_rsrcs[] = {
+        OIC_RSRC_DOXM_URI,
+        OIC_RSRC_PSTAT_URI
+    };
+    OicUuid_t ownerId = {.id = {0}};
+    OCStackResult res = OC_STACK_ERROR;
+    OicSecAcl_t* newDefaultAcl = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t));
+    VERIFY_NON_NULL(TAG, newDefaultAcl, ERROR);
+
+    // Subject -- Mandatory
+    memcpy(&(newDefaultAcl->subject), &WILDCARD_SUBJECT_ID, WILDCARD_SUBJECT_ID_LEN);
+
+    // Resources -- Mandatory
+    newDefaultAcl->resourcesLen = NUMBER_OF_DEFAULT_SEC_RSCS;
+    newDefaultAcl->resources = (char**)OICCalloc(NUMBER_OF_DEFAULT_SEC_RSCS, sizeof(char*));
+    VERIFY_NON_NULL(TAG, (newDefaultAcl->resources), ERROR);
+
+    for (size_t i = 0; i <  NUMBER_OF_DEFAULT_SEC_RSCS; i++)
+    {
+        size_t len = strlen(sec_rsrcs[i]) + 1;
+        newDefaultAcl->resources[i] = (char*)OICMalloc(len * sizeof(char));
+        VERIFY_NON_NULL(TAG, (newDefaultAcl->resources[i]), ERROR);
+        OICStrcpy(newDefaultAcl->resources[i], len, sec_rsrcs[i]);
+    }
+
+    // Permissions -- Mandatory
+    newDefaultAcl->permission = PERMISSION_READ;
+
+    //Period -- Not Mandatory
+    newDefaultAcl->prdRecrLen = 0;
+    newDefaultAcl->periods = NULL;
+
+    //Recurrence -- Not Mandatory
+    newDefaultAcl->recurrences = NULL;
+
+    // Device ID is the owner of this default ACL
+    res = GetDoxmDeviceID(&ownerId);
+    VERIFY_SUCCESS(TAG, OC_STACK_OK == res, FATAL);
+
+    // Owners -- Mandatory
+    memcpy(&newDefaultAcl->rownerID, &ownerId, sizeof(OicUuid_t));
+
+    return newDefaultAcl;
+exit:
+    DeleteACLList(newDefaultAcl);
+    return NULL;
+
+}
+
+OCStackResult UpdateDefaultSecProvACL()
+{
+    OCStackResult ret = OC_STACK_OK;
+    OicSecAcl_t *acl = NULL;
+    OicSecAcl_t *tmp = NULL;
+
+    if(gAcl)
+    {
+        int matchedRsrc = 0;
+        bool isRemoved = false;
+
+        LL_FOREACH_SAFE(gAcl, acl, tmp)
+        {
+            //Find default security resource ACL
+            if(memcmp(&acl->subject, &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)) == 0 &&
+                ((PERMISSION_READ | PERMISSION_WRITE) == acl->permission))
             {
-                ret = UpdateSVRDatabase(OIC_JSON_ACL_NAME, jsonAcl);
+                matchedRsrc = 0;
+
+                for(size_t i = 0; i < acl->resourcesLen; i++)
+                {
+                    if(strncmp(acl->resources[i], OIC_RSRC_DOXM_URI,
+                               strlen(OIC_RSRC_DOXM_URI) + 1) == 0 ||
+                       strncmp(acl->resources[i], OIC_RSRC_CRED_URI,
+                               strlen(OIC_RSRC_CRED_URI) + 1) == 0 ||
+                       strncmp(acl->resources[i], OIC_RSRC_ACL_URI,
+                               strlen(OIC_RSRC_ACL_URI) + 1) == 0 ||
+                       strncmp(acl->resources[i], OIC_RSRC_PSTAT_URI,
+                               strlen(OIC_RSRC_PSTAT_URI) + 1) == 0)
+                    {
+                        matchedRsrc++;
+                    }
+                }
+
+                //If default security resource ACL is detected, delete it.
+                if(NUMBER_OF_SEC_PROV_RSCS == matchedRsrc)
+                {
+                    LL_DELETE(gAcl, acl);
+                    FreeACE(acl);
+                    isRemoved = true;
+                }
             }
-            cJSON_Delete(jsonAcl);
         }
+
+        if(isRemoved)
+        {
+            /*
+             * Generate new security resource ACL as follows :
+             *      subject : "*"
+             *      resources :  '/oic/sec/doxm', '/oic/sec/pstat'
+             *      permission : READ
+             */
+            OicSecAcl_t *newDefaultAcl = GetSecDefaultACL();
+            if (newDefaultAcl)
+            {
+                LL_APPEND(gAcl, newDefaultAcl);
+
+                size_t size = 0;
+                uint8_t *payload = NULL;
+                if (OC_STACK_OK == AclToCBORPayload(gAcl, &payload, &size))
+                {
+                    if (UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, payload, size) == OC_STACK_OK)
+                    {
+                        ret = OC_STACK_OK;
+                    }
+                    OICFree(payload);
+                }
+            }
+        }
+    }
+
+    return ret;
+}
+
+OCStackResult SetAclRownerId(const OicUuid_t* newROwner)
+{
+    OCStackResult ret = OC_STACK_ERROR;
+    uint8_t *cborPayload = NULL;
+    size_t size = 0;
+    OicUuid_t prevId = {.id={0}};
+
+    if(NULL == newROwner)
+    {
+        ret = OC_STACK_INVALID_PARAM;
+    }
+    if(NULL == gAcl)
+    {
+        ret = OC_STACK_NO_RESOURCE;
+    }
+
+    if(newROwner && gAcl)
+    {
+        memcpy(prevId.id, gAcl->rownerID.id, sizeof(prevId.id));
+        memcpy(gAcl->rownerID.id, newROwner->id, sizeof(newROwner->id));
+
+        ret = AclToCBORPayload(gAcl, &cborPayload, &size);
+        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+
+        ret = UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, cborPayload, size);
+        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+
+        OICFree(cborPayload);
     }
 
     return ret;
+
+exit:
+    OICFree(cborPayload);
+    memcpy(gAcl->rownerID.id, prevId.id, sizeof(prevId.id));
+    return ret;
+}
+
+OCStackResult GetAclRownerId(OicUuid_t *rowneruuid)
+{
+    OCStackResult retVal = OC_STACK_ERROR;
+    if (gAcl)
+    {
+        *rowneruuid = gAcl->rownerID;
+        retVal = OC_STACK_OK;
+    }
+    return retVal;
 }
index 9d1d668..be21257 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-
 #include <stdlib.h>
 #include <string.h>
-#include "ocstack.h"
-#include "logger.h"
 #include "oic_malloc.h"
-#include "oic_string.h"
-#include "cJSON.h"
-#include "base64.h"
-#include "resourcemanager.h"
+#include "ocpayload.h"
+#include "payload_logging.h"
 #include "psinterface.h"
+#include "resourcemanager.h"
 #include "utlist.h"
 #include "srmresourcestrings.h"
-#include "amaclresource.h"
 #include "srmutility.h"
-#include <stdlib.h>
-#include <string.h>
+#include "amaclresource.h"
 
 #define TAG  "SRM-AMACL"
 
-OicSecAmacl_t *gAmacl = NULL;
+/** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
+ * The value of payload size is increased until reaching belox max cbor size. */
+static const uint16_t CBOR_SIZE = 1024;
+
+/* Max cbor size payload. */
+static const uint16_t CBOR_MAX_SIZE = 4400;
+
+/** AMACL Map size - Number of mandatory items. */
+static const uint8_t AMACL_MAP_SIZE = 3;
+static const uint8_t AMACL_RSRC_MAP_SIZE = 1;
+static const uint8_t AMACL_RLIST_MAP_SIZE = 3;
+
+static OicSecAmacl_t *gAmacl = NULL;
 static OCResourceHandle gAmaclHandle = NULL;
 
 void DeleteAmaclList(OicSecAmacl_t* amacl)
@@ -48,12 +54,10 @@ void DeleteAmaclList(OicSecAmacl_t* amacl)
         OicSecAmacl_t *amaclTmp1 = NULL, *amaclTmp2 = NULL;
         LL_FOREACH_SAFE(amacl, amaclTmp1, amaclTmp2)
         {
-            unsigned int i = 0;
-
             LL_DELETE(amacl, amaclTmp1);
 
             // Clean Resources
-            for (i = 0; i < amaclTmp1->resourcesLen; i++)
+            for (size_t i = 0; i < amaclTmp1->resourcesLen; i++)
             {
                 OICFree(amaclTmp1->resources[i]);
             }
@@ -62,204 +66,403 @@ void DeleteAmaclList(OicSecAmacl_t* amacl)
             // Clean Amss
             OICFree(amaclTmp1->amss);
 
-            // Clean Owners
-            OICFree(amaclTmp1->owners);
-
             // Clean Amacl node itself
             OICFree(amaclTmp1);
         }
     }
 }
 
-/*
- * This internal method converts AMACL data into JSON format.
- *
- * Note: Caller needs to invoke 'free' when finished using the return string.
- */
-char * BinToAmaclJSON(const OicSecAmacl_t * amacl)
+static size_t OicSecAmaclCount(const OicSecAmacl_t *secAmacl)
 {
-    cJSON *jsonRoot = NULL;
-    char *jsonStr = NULL;
+    size_t size = 0;
+    for (const OicSecAmacl_t *amacl = secAmacl; amacl; amacl = amacl->next)
+    {
+        size++;
+    }
+    return size;
+}
 
-    if (amacl)
+OCStackResult AmaclToCBORPayload(const OicSecAmacl_t *amaclS, uint8_t **cborPayload,
+                                 size_t *cborSize)
+{
+    if (NULL == amaclS || NULL == cborPayload || NULL != *cborPayload || NULL == cborSize)
     {
-        jsonRoot = cJSON_CreateObject();
-        VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+        return OC_STACK_INVALID_PARAM;
+    }
 
-        cJSON *jsonAmaclArray = NULL;
-        cJSON_AddItemToObject (jsonRoot, OIC_JSON_AMACL_NAME, jsonAmaclArray = cJSON_CreateArray());
-        VERIFY_NON_NULL(TAG, jsonAmaclArray, ERROR);
+    OCStackResult ret = OC_STACK_ERROR;
+    size_t cborLen = *cborSize;
+    if (0 == cborLen)
+    {
+        cborLen = CBOR_SIZE;
+    }
 
-        while(amacl)
-        {
-            char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
-            uint32_t outLen = 0;
-            B64Result b64Ret = B64_OK;
-
-            cJSON *jsonAmacl = cJSON_CreateObject();
-
-            // Resources -- Mandatory
-            cJSON *jsonRsrcArray = NULL;
-            cJSON_AddItemToObject(jsonAmacl, OIC_JSON_RESOURCES_NAME, jsonRsrcArray =
-                    cJSON_CreateArray());
-            VERIFY_NON_NULL(TAG, jsonRsrcArray, ERROR);
-            for (unsigned int i = 0; i < amacl->resourcesLen; i++)
-            {
-                cJSON_AddItemToArray(jsonRsrcArray, cJSON_CreateString(amacl->resources[i]));
-            }
+    *cborSize = 0;
+    *cborPayload = NULL;
 
-            // Amss -- Mandatory
-            cJSON *jsonAmsArray = NULL;
-            cJSON_AddItemToObject(jsonAmacl, OIC_JSON_AMSS_NAME, jsonAmsArray =
-                    cJSON_CreateArray());
-            VERIFY_NON_NULL(TAG, jsonAmsArray, ERROR);
-            for (unsigned int i = 0; i < amacl->amssLen; i++)
-            {
-                outLen = 0;
+    CborEncoder encoder;
+    CborEncoder amaclMap;
+    int64_t cborEncoderResult = CborNoError;
+    CborEncoder rsrcMap;
+    CborEncoder rlistArray;
+    CborEncoder amss;
+    char *stRowner = NULL;
 
-                b64Ret = b64Encode(amacl->amss[i].id, sizeof(((OicUuid_t*) 0)->id), base64Buff,
-                        sizeof(base64Buff), &outLen);
-                VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
+    const OicSecAmacl_t *amacl = amaclS;
+    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
+    VERIFY_NON_NULL(TAG, outPayload, ERROR);
+    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
 
-                cJSON_AddItemToArray(jsonAmsArray, cJSON_CreateString(base64Buff));
-            }
+    // Create AMACL Map
+    cborEncoderResult = cbor_encoder_create_map(&encoder, &amaclMap, AMACL_MAP_SIZE);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding AMACL Map.");
 
-            // Owners -- Mandatory
-            cJSON *jsonOwnrArray = NULL;
-            cJSON_AddItemToObject(jsonAmacl, OIC_JSON_OWNERS_NAME, jsonOwnrArray =
-                    cJSON_CreateArray());
-            VERIFY_NON_NULL(TAG, jsonOwnrArray, ERROR);
-            for (unsigned int i = 0; i < amacl->ownersLen; i++)
-            {
-                outLen = 0;
+    // resources -- Mandatory
+    cborEncoderResult = cbor_encode_text_string(&amaclMap, OIC_JSON_RESOURCES_NAME,
+                strlen(OIC_JSON_RESOURCES_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Resource Name Tag.");
 
-                b64Ret = b64Encode(amacl->owners[i].id, sizeof(((OicUuid_t*) 0)->id), base64Buff,
-                        sizeof(base64Buff), &outLen);
-                VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
+    cborEncoderResult = cbor_encoder_create_map(&amaclMap, &rsrcMap, AMACL_RSRC_MAP_SIZE);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Resource Map.");
 
-                cJSON_AddItemToArray(jsonOwnrArray, cJSON_CreateString(base64Buff));
-            }
 
-            // Attach current amacl node to Amacl Array
-            cJSON_AddItemToArray(jsonAmaclArray, jsonAmacl);
-            amacl = amacl->next;
-        }
+    cborEncoderResult = cbor_encode_text_string(&rsrcMap, OIC_JSON_RLIST_NAME,
+                strlen(OIC_JSON_RLIST_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RLIST Name Tag.");
 
-        jsonStr = cJSON_PrintUnformatted(jsonRoot);
+    // TODO : Need to input array length by OicSecAmacl_t->resources->rlistLen based on spec.
+    cborEncoderResult = cbor_encoder_create_array(&rsrcMap, &rlistArray, amacl->resourcesLen);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RLIST Array.");
+
+    // TODO : Need to add OicSecAmacl_t->rlist as array rMap based on RAML spec.
+    for (size_t i = 0; i < amacl->resourcesLen; i++)
+    {
+        // TODO : Need to create rMap structure based on RAML spec.
+        CborEncoder rMap;
+        cborEncoderResult = cbor_encoder_create_map(&rlistArray, &rMap, AMACL_RLIST_MAP_SIZE);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RLIST Map.");
+
+        cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_HREF_NAME,
+                strlen(OIC_JSON_HREF_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding HREF Name Tag.");
+        cborEncoderResult = cbor_encode_text_string(&rMap, amacl->resources[i],
+                strlen(amacl->resources[i]));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding HREF Value in Map.");
+
+        cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_RT_NAME,
+                strlen(OIC_JSON_RT_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag.");
+
+        // TODO : Need to assign real value of RT
+        cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_EMPTY_STRING,
+                strlen(OIC_JSON_EMPTY_STRING));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
+
+        cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_IF_NAME,
+                strlen(OIC_JSON_IF_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag.");
+
+        // TODO : Need to assign real value of IF
+        cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_EMPTY_STRING,
+                strlen(OIC_JSON_EMPTY_STRING));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
+
+        cborEncoderResult = cbor_encoder_close_container(&rlistArray, &rMap);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing RLIST Array.");
     }
 
-exit:
-    if (jsonRoot)
+    cborEncoderResult = cbor_encoder_close_container(&rsrcMap, &rlistArray);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing RLIST Array.");
+
+
+    cborEncoderResult = cbor_encoder_close_container(&amaclMap, &rsrcMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Resource Map.");
+
+    // TODO : Need to modify type of OicSecAmacl_t->amss based on RAML spec.
+    // ams -- Mandatory
+    cborEncoderResult = cbor_encode_text_string(&amaclMap, OIC_JSON_AMS_NAME,
+                strlen(OIC_JSON_AMS_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding AMSS Name Tag.");
+
+    cborEncoderResult = cbor_encoder_create_array(&amaclMap, &amss, amacl->amssLen);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding AMS Name Array.");
+    for (size_t i = 0; i < amacl->amssLen; i++)
     {
-        cJSON_Delete(jsonRoot);
+        cborEncoderResult = cbor_encode_text_string(&amss, (const char *)amacl->amss[i].id,
+            sizeof(amacl->amss[i].id));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding AMS Name Value.");
     }
-    return jsonStr;
-}
+    cborEncoderResult = cbor_encoder_close_container(&amaclMap, &amss);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing AMSS Array.");
 
+    // TODO : Need to check owner property in the RAML spec.
+    // rowner -- Mandatory
+    cborEncoderResult = cbor_encode_text_string(&amaclMap, OIC_JSON_ROWNERID_NAME,
+                strlen(OIC_JSON_ROWNERID_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding ROwnerID Name Tag.");
 
+    ret = ConvertUuidToStr(&amacl->rownerID, &stRowner);
+    VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
+    cborEncoderResult = cbor_encode_text_string(&amaclMap, stRowner, strlen(stRowner));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding ROwner Value.");
+    OICFree(stRowner);
 
+    cborEncoderResult = cbor_encoder_close_container(&encoder, &amaclMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Amacl Map.");
 
-/*
- * This internal method converts JSON AMACL into binary AMACL.
- */
-OicSecAmacl_t * JSONToAmaclBin(const char * jsonStr)
+    if (CborNoError == cborEncoderResult)
+    {
+        *cborPayload = outPayload;
+        *cborSize = encoder.ptr - outPayload;
+        ret = OC_STACK_OK;
+    }
+
+exit:
+    if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
+    {
+       // reallocate and try again!
+       OICFree(outPayload);
+       outPayload = NULL;
+       // Since the allocated initial memory failed, double the memory.
+       cborLen += encoder.ptr - encoder.end;
+       cborEncoderResult = CborNoError;
+       ret = AmaclToCBORPayload(amaclS, cborPayload, &cborLen);
+       if (OC_STACK_OK == ret)
+       {
+           *cborSize = cborLen;
+           ret = OC_STACK_OK;
+       }
+    }
+
+    if (CborNoError != cborEncoderResult || ret != OC_STACK_OK)
+    {
+       OICFree(outPayload);
+       outPayload = NULL;
+       *cborSize = 0;
+       *cborPayload = NULL;
+       ret = OC_STACK_ERROR;
+    }
+
+    return ret;
+}
+
+OCStackResult CBORPayloadToAmacl(const uint8_t *cborPayload, size_t size,
+                                 OicSecAmacl_t **secAmacl)
 {
+    if (NULL == cborPayload || NULL == secAmacl || NULL != *secAmacl || 0 == size)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    *secAmacl = NULL;
+
     OCStackResult ret = OC_STACK_ERROR;
-    OicSecAmacl_t * headAmacl = NULL;
-    OicSecAmacl_t * prevAmacl = NULL;
-    cJSON *jsonRoot = NULL;
-    cJSON *jsonAmaclArray = NULL;
 
-    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
+    CborValue amaclCbor = { .parser = NULL };
+    CborParser parser = { .end = NULL };
+    CborError cborFindResult = CborNoError;
 
-    jsonRoot = cJSON_Parse(jsonStr);
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+    cbor_parser_init(cborPayload, size, 0, &parser, &amaclCbor);
+    OicSecAmacl_t *headAmacl = (OicSecAmacl_t *)OICCalloc(1, sizeof(OicSecAmacl_t));
 
-    jsonAmaclArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_AMACL_NAME);
-    VERIFY_NON_NULL(TAG, jsonAmaclArray, INFO);
+    CborValue amaclMap = { .parser = NULL };
+    cborFindResult = cbor_value_enter_container(&amaclCbor, &amaclMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Amacl Map.");
 
-    if (cJSON_Array == jsonAmaclArray->type)
+    while(cbor_value_is_valid(&amaclMap))
     {
-        int numAmacl = cJSON_GetArraySize(jsonAmaclArray);
-        int idx = 0;
+        char *name = NULL;
+        size_t len = 0;
+        cborFindResult = cbor_value_dup_text_string(&amaclMap, &name, &len, NULL);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Amacl Data Name Tag.");
+        cborFindResult = cbor_value_advance(&amaclMap);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Amacl Data Value.");
 
-        VERIFY_SUCCESS(TAG, numAmacl > 0, INFO);
-        do
-        {
-            cJSON *jsonAmacl = cJSON_GetArrayItem(jsonAmaclArray, idx);
-            VERIFY_NON_NULL(TAG, jsonAmacl, ERROR);
+        //CborType type = cbor_value_get_type(&amaclMap);
 
-            OicSecAmacl_t *amacl = (OicSecAmacl_t*)OICCalloc(1, sizeof(OicSecAmacl_t));
-            VERIFY_NON_NULL(TAG, amacl, ERROR);
+        // Resources -- Mandatory
+        if (0 == strcmp(OIC_JSON_RESOURCES_NAME, name))
+        {
+            // resource map
+            CborValue rsrcMap = { .parser = NULL  };
+            cborFindResult = cbor_value_enter_container(&amaclMap, &rsrcMap);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Resource Map");
 
-            headAmacl = (headAmacl) ? headAmacl : amacl;
-            if (prevAmacl)
+            while(cbor_value_is_valid(&rsrcMap))
             {
-                prevAmacl->next = amacl;
+                // resource name
+                char *rsrcName = NULL;
+                size_t rsrcNameLen = 0;
+                cborFindResult = cbor_value_dup_text_string(&rsrcMap, &rsrcName, &rsrcNameLen, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Resource Data Name Tag.");
+                cborFindResult = cbor_value_advance(&rsrcMap);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Resource Data Value.");
+
+                // rlist
+                if (0 == strcmp(OIC_JSON_RLIST_NAME, rsrcName))
+                {
+                    int i = 0;
+                    // TODO : Need to assign array length to OicSecAmacl_t->resources->rlistLen based of RAML spec.
+                    cborFindResult = cbor_value_get_array_length(&rsrcMap, &headAmacl->resourcesLen);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Rlist Array Len.");
+
+                    CborValue rsrcArray = { .parser = NULL  };
+
+                    // rlist array
+                    cborFindResult = cbor_value_enter_container(&rsrcMap, &rsrcArray);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Rlist Array");
+
+                    // TODO : Need to check data structure of OicSecAmacl_t based on RAML spec.
+                    headAmacl->resources = (char **) OICCalloc(headAmacl->resourcesLen, sizeof(*headAmacl->resources));
+                    VERIFY_NON_NULL(TAG, headAmacl->resources, ERROR);
+
+                    while (cbor_value_is_valid(&rsrcArray))
+                    {
+                        // rMap
+                        CborValue rMap = { .parser = NULL  };
+                        cborFindResult = cbor_value_enter_container(&rsrcArray, &rMap);
+                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Rlist Map");
+
+                        while(cbor_value_is_valid(&rMap))
+                        {
+                            char *rMapName = NULL;
+                            size_t rMapNameLen = 0;
+                            cborFindResult = cbor_value_dup_text_string(&rMap, &rMapName, &rMapNameLen, NULL);
+                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding RMap Data Name Tag.");
+                            cborFindResult = cbor_value_advance(&rMap);
+                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding RMap Data Value.");
+
+                            // "href"
+                            if (0 == strcmp(OIC_JSON_HREF_NAME, rMapName))
+                            {
+                                // TODO : Need to check data structure of OicSecAmacl_t based on RAML spec.
+                                cborFindResult = cbor_value_dup_text_string(&rMap, &headAmacl->resources[i++], &len, NULL);
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Href Value.");
+                            }
+
+                            // "rt"
+                            if (0 == strcmp(OIC_JSON_RT_NAME, rMapName))
+                            {
+                                // TODO : Need to check data structure of OicSecAmacl_t and assign based on RAML spec.
+                                char *rtData = NULL;
+                                cborFindResult = cbor_value_dup_text_string(&rMap, &rtData, &len, NULL);
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding RT Value.");
+                                OICFree(rtData);
+                            }
+
+                            // "if"
+                            if (0 == strcmp(OIC_JSON_IF_NAME, rMapName))
+                            {
+                                // TODO : Need to check data structure of OicSecAmacl_t and assign based on RAML spec.
+                                char *ifData = NULL;
+                                cborFindResult = cbor_value_dup_text_string(&rMap, &ifData, &len, NULL);
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding IF Value.");
+                                OICFree(ifData);
+                            }
+
+                            if (cbor_value_is_valid(&rMap))
+                            {
+                                cborFindResult = cbor_value_advance(&rMap);
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Rlist Map.");
+                            }
+                            OICFree(rMapName);
+                        }
+
+                        if (cbor_value_is_valid(&rsrcArray))
+                        {
+                            cborFindResult = cbor_value_advance(&rsrcArray);
+                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Resource Array.");
+                        }
+                    }
+                }
+
+                if (cbor_value_is_valid(&rsrcMap))
+                {
+                    cborFindResult = cbor_value_advance(&rsrcMap);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Resource Map.");
+                }
+                OICFree(rsrcName);
             }
 
-            size_t jsonObjLen = 0;
-            cJSON *jsonObj = NULL;
-
-            // Resources -- Mandatory
-            jsonObj = cJSON_GetObjectItem(jsonAmacl, OIC_JSON_RESOURCES_NAME);
-            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
-
-            amacl->resourcesLen = cJSON_GetArraySize(jsonObj);
-            VERIFY_SUCCESS(TAG, amacl->resourcesLen > 0, ERROR);
-            amacl->resources = (char**)OICCalloc(amacl->resourcesLen, sizeof(char*));
-            VERIFY_NON_NULL(TAG, (amacl->resources), ERROR);
+        }
 
-            size_t idxx = 0;
-            do
+        // TODO : Need to modify type of OicSecAmacl_t->amss based on RAML spec.
+         // Ams -- Mandatory
+        if (0 == strcmp(OIC_JSON_AMS_NAME, name))
+        {
+            int i = 0;
+            CborValue amsArray = { .parser = NULL };
+            cborFindResult = cbor_value_get_array_length(&amaclMap, &headAmacl->amssLen);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding AMS Array Len.");
+            cborFindResult = cbor_value_enter_container(&amaclMap, &amsArray);
+            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))
             {
-                cJSON *jsonRsrc = cJSON_GetArrayItem(jsonObj, idxx);
-                VERIFY_NON_NULL(TAG, jsonRsrc, ERROR);
-
-                jsonObjLen = strlen(jsonRsrc->valuestring) + 1;
-                amacl->resources[idxx] = (char*)OICMalloc(jsonObjLen);
-                VERIFY_NON_NULL(TAG, (amacl->resources[idxx]), ERROR);
-                OICStrcpy(amacl->resources[idxx], jsonObjLen, jsonRsrc->valuestring);
-            } while ( ++idxx < amacl->resourcesLen);
+                char *amssId = NULL;
+                cborFindResult = cbor_value_dup_text_string(&amsArray, &amssId, &len, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding AMS Id.");
+                cborFindResult = cbor_value_advance(&amsArray);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing AMS.");
+                memcpy(headAmacl->amss[i++].id, (OicUuid_t *)amssId, len);
+                OICFree(amssId);
+            }
+        }
 
-            // Amss -- Mandatory
-            VERIFY_SUCCESS( TAG, OC_STACK_OK == AddUuidArray(jsonAmacl, OIC_JSON_AMSS_NAME,
-                               &(amacl->amssLen), &(amacl->amss)), ERROR);
+        // Rowner -- Mandatory
+        if (0 == strcmp(OIC_JSON_ROWNERID_NAME, name))
+        {
+            char *stRowner = NULL;
+            cborFindResult = cbor_value_dup_text_string(&amaclMap, &stRowner, &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ROwner Value.");
 
-            // Owners -- Mandatory
-            VERIFY_SUCCESS( TAG, OC_STACK_OK == AddUuidArray(jsonAmacl, OIC_JSON_OWNERS_NAME,
-                               &(amacl->ownersLen), &(amacl->owners)), ERROR);
+            ret = ConvertStrToUuid(stRowner, &headAmacl->rownerID);
+            VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
+            OICFree(stRowner);
+        }
 
-            prevAmacl = amacl;
-        } while( ++idx < numAmacl);
+        //if (CborMapType != type && cbor_value_is_valid(&amaclMap))
+        if (cbor_value_is_valid(&amaclMap))
+        {
+            cborFindResult = cbor_value_advance(&amaclMap);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Amacl Map.");
+        }
+        OICFree(name);
     }
 
+    *secAmacl = headAmacl;
     ret = OC_STACK_OK;
 
 exit:
-    cJSON_Delete(jsonRoot);
-    if (OC_STACK_OK != ret)
+    if (CborNoError != cborFindResult)
     {
         DeleteAmaclList(headAmacl);
         headAmacl = NULL;
+        *secAmacl = NULL;
+        ret = OC_STACK_ERROR;
     }
-    return headAmacl;
+    return ret;
 }
 
 static OCEntityHandlerResult HandleAmaclGetRequest (const OCEntityHandlerRequest * ehRequest)
 {
     // Convert Amacl data into JSON for transmission
-    char* jsonStr = BinToAmaclJSON(gAmacl);
+    size_t size = 0;
+    uint8_t *cborPayload = NULL;
+    OCStackResult res = AmaclToCBORPayload(gAmacl, &cborPayload, &size);
 
-    OCEntityHandlerResult ehRet = (jsonStr ? OC_EH_OK : OC_EH_ERROR);
+    OCEntityHandlerResult ehRet = (res == OC_STACK_OK) ? OC_EH_OK : OC_EH_ERROR;
 
     // Send response payload to request originator
-    SendSRMResponse(ehRequest, ehRet, jsonStr);
-
-    OICFree(jsonStr);
+    if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, cborPayload, size))
+    {
+        ehRet = OC_EH_ERROR;
+        OIC_LOG(ERROR, TAG, "SendSRMResponse failed in HandleAmaclGetRequest");
+    }
+    OICFree(cborPayload);
 
-    OC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
+    OIC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
     return ehRet;
 }
 
@@ -267,44 +470,49 @@ static OCEntityHandlerResult HandleAmaclPostRequest (const OCEntityHandlerReques
 {
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
 
-    // Convert JSON Amacl data into binary. This will also validate the Amacl data received.
-    OicSecAmacl_t* newAmacl = JSONToAmaclBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
-
-    if (newAmacl)
+    // Convert CBOR Amacl data into binary. This will also validate the Amacl data received.
+    uint8_t *payload = ((OCSecurityPayload *) ehRequest->payload)->securityData;
+    size_t size = ((OCSecurityPayload *) ehRequest->payload)->payloadSize;
+    if (payload)
     {
-        // Append the new Amacl to existing Amacl
-        LL_APPEND(gAmacl, newAmacl);
-
-        // Convert Amacl data into JSON for update to persistent storage
-        char *jsonStr = BinToAmaclJSON(gAmacl);
-        if (jsonStr)
+        OicSecAmacl_t *newAmacl = NULL;
+        OCStackResult res = CBORPayloadToAmacl(payload, size, &newAmacl);
+        if (newAmacl && OC_STACK_OK == res)
         {
-            cJSON *jsonAmacl = cJSON_Parse(jsonStr);
-            OICFree(jsonStr);
-
-            if ((jsonAmacl) &&
-                (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_AMACL_NAME, jsonAmacl)))
+            // Append the new Amacl to existing Amacl
+            LL_APPEND(gAmacl, newAmacl);
+            size_t size = 0;
+            // Convert Amacl data into JSON for update to persistent storage.
+            uint8_t *cborPayload = NULL;
+            res = AmaclToCBORPayload(gAmacl, &cborPayload, &size);
+            if (cborPayload && (OC_STACK_OK == res) &&
+                (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_AMACL_NAME, cborPayload, size)))
             {
                 ehRet = OC_EH_RESOURCE_CREATED;
             }
-            cJSON_Delete(jsonAmacl);
+            OICFree(cborPayload);
         }
+        OICFree(payload);
     }
 
     // Send payload to request originator
-    SendSRMResponse(ehRequest, ehRet, NULL);
+    if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL, 0))
+    {
+        ehRet = OC_EH_ERROR;
+        OIC_LOG(ERROR, TAG, "SendSRMResponse failed in HandleAmaclPostRequest");
+    }
 
-    OC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
+    OIC_LOG_V(DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
     return ehRet;
 }
 
-/*
+/**
  * This internal method is the entity handler for Amacl resources and
  * will handle REST request (GET/PUT/POST/DEL) for them.
  */
-OCEntityHandlerResult AmaclEntityHandler (OCEntityHandlerFlag flag,
-                                          OCEntityHandlerRequest * ehRequest,
-                                          void* callbackParameter)
+static OCEntityHandlerResult AmaclEntityHandler (OCEntityHandlerFlag flag,
+                                                 OCEntityHandlerRequest * ehRequest,
+                                                 void* callbackParameter)
 {
     (void) callbackParameter;
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
@@ -316,7 +524,7 @@ OCEntityHandlerResult AmaclEntityHandler (OCEntityHandlerFlag flag,
 
     if (flag & OC_REQUEST_FLAG)
     {
-        OC_LOG (DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
+        OIC_LOG (DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
         switch (ehRequest->method)
         {
             case OC_REST_GET:
@@ -329,53 +537,56 @@ OCEntityHandlerResult AmaclEntityHandler (OCEntityHandlerFlag flag,
 
             default:
                 ehRet = OC_EH_ERROR;
-                SendSRMResponse(ehRequest, ehRet, NULL);
+                SendSRMResponse(ehRequest, ehRet, NULL, 0);
         }
     }
 
     return ehRet;
 }
 
-/*
+/**
  * This internal method is used to create '/oic/sec/amacl' resource.
  */
-OCStackResult CreateAmaclResource()
+static OCStackResult CreateAmaclResource()
 {
-    OCStackResult ret;
-
-    ret = OCCreateResource(&gAmaclHandle,
-                           OIC_RSRC_TYPE_SEC_AMACL,
-                           OIC_MI_DEF,
-                           OIC_RSRC_AMACL_URI,
-                           AmaclEntityHandler,
-                           NULL,
-                           OC_OBSERVABLE);
+    OCStackResult ret = OCCreateResource(&gAmaclHandle,
+                                         OIC_RSRC_TYPE_SEC_AMACL,
+                                         OIC_MI_DEF,
+                                         OIC_RSRC_AMACL_URI,
+                                         AmaclEntityHandler,
+                                         NULL,
+                                         OC_OBSERVABLE);
 
     if (OC_STACK_OK != ret)
     {
-        OC_LOG (FATAL, TAG, "Unable to instantiate Amacl resource");
+        OIC_LOG (FATAL, TAG, "Unable to instantiate Amacl resource");
         DeInitAmaclResource();
     }
     return ret;
 }
 
-/**
- * Initialize Amacl resource by loading data from persistent storage.
- *
- * @retval  OC_STACK_OK for Success, otherwise some error value
- */
 OCStackResult InitAmaclResource()
 {
     OCStackResult ret = OC_STACK_ERROR;
 
-    // Read Amacl resource from PS
-    char* jsonSVRDatabase = GetSVRDatabase();
+    uint8_t *data = NULL;
+    size_t size = 0;
+    ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_AMACL_NAME, &data, &size);
 
-    if (jsonSVRDatabase)
+    // If database read failed
+    if (OC_STACK_OK != ret)
     {
-        // Convert JSON Amacl into binary format
-        gAmacl = JSONToAmaclBin(jsonSVRDatabase);
-        OICFree(jsonSVRDatabase);
+        OIC_LOG(DEBUG, TAG, "ReadSVDataFromPS failed");
+    }
+    if (data)
+    {
+        // Read AMACL resource from PS
+        ret = CBORPayloadToAmacl(data, size, &gAmacl);
+        if (OC_STACK_OK != ret)
+        {
+            OIC_LOG(DEBUG, TAG, "ReadAMACLresourcefromPS failed");
+        }
+        OICFree(data);
     }
 
     // Instantiate 'oic/sec/amacl' resource
@@ -388,11 +599,6 @@ OCStackResult InitAmaclResource()
     return ret;
 }
 
-/**
- * Perform cleanup for Amacl resources.
- *
- * @retval  none
- */
 void DeInitAmaclResource()
 {
     OCDeleteResource(gAmaclHandle);
@@ -402,7 +608,6 @@ void DeInitAmaclResource()
     gAmacl = NULL;
 }
 
-
 OCStackResult AmaclGetAmsDeviceId(const char *resource, OicUuid_t *amsDeviceId)
 {
     OicSecAmacl_t *amacl = NULL;
@@ -414,7 +619,7 @@ OCStackResult AmaclGetAmsDeviceId(const char *resource, OicUuid_t *amsDeviceId)
     {
         for(size_t i = 0; i < amacl->resourcesLen; i++)
         {
-            if (strncmp((amacl->resources[i]), resource, strlen(amacl->resources[i])) == 0)
+            if (0 == strncmp((amacl->resources[i]), resource, strlen(amacl->resources[i])))
             {
                 //Returning the ID of the first AMS service for the resource
                 memcpy(amsDeviceId, &amacl->amss[0], sizeof(*amsDeviceId));
@@ -426,3 +631,52 @@ OCStackResult AmaclGetAmsDeviceId(const char *resource, OicUuid_t *amsDeviceId)
 exit:
     return OC_STACK_ERROR;
 }
+
+OCStackResult SetAmaclRownerId(const OicUuid_t* newROwner)
+{
+    OCStackResult ret = OC_STACK_ERROR;
+    uint8_t *cborPayload = NULL;
+    size_t size = 0;
+    OicUuid_t prevId = {.id={0}};
+
+    if(NULL == newROwner)
+    {
+        ret = OC_STACK_INVALID_PARAM;
+    }
+    if(NULL == gAmacl)
+    {
+        ret = OC_STACK_NO_RESOURCE;
+    }
+
+    if(newROwner && gAmacl)
+    {
+        memcpy(prevId.id, gAmacl->rownerID.id, sizeof(prevId.id));
+        memcpy(gAmacl->rownerID.id, newROwner->id, sizeof(newROwner->id));
+
+        ret = AmaclToCBORPayload(gAmacl, &cborPayload, &size);
+        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+
+        ret = UpdateSecureResourceInPS(OIC_JSON_AMACL_NAME, cborPayload, size);
+        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+
+        OICFree(cborPayload);
+    }
+
+    return ret;
+
+exit:
+    OICFree(cborPayload);
+    memcpy(gAmacl->rownerID.id, prevId.id, sizeof(prevId.id));
+    return ret;
+}
+
+OCStackResult GetAmaclRownerId(OicUuid_t *rowneruuid)
+{
+    OCStackResult retVal = OC_STACK_ERROR;
+    if (gAmacl)
+    {
+        *rowneruuid = gAmacl->rownerID;
+        retVal = OC_STACK_OK;
+    }
+    return retVal;
+}
index 7e4e301..9486f90 100644 (file)
@@ -18,6 +18,7 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#include <string.h>
 #include "oic_malloc.h"
 #include "amsmgr.h"
 #include "resourcemanager.h"
 #include "policyengine.h"
 #include "oic_string.h"
 #include "caremotehandler.h"
-#include <string.h>
 
 #define TAG "SRM-AMSMGR"
 
-
  //Callback for AMS service multicast discovery request.
 static OCStackApplicationResult AmsMgrDiscoveryCallback(void *ctx, OCDoHandle handle,
                          OCClientResponse * clientResponse);
@@ -51,25 +50,19 @@ static OCStackApplicationResult SecurePortDiscoveryCallback(void *ctx, OCDoHandl
 static OCStackApplicationResult AmsMgrAclReqCallback(void *ctx, OCDoHandle handle,
     OCClientResponse * clientResponse);
 
-
 OCStackResult DiscoverAmsService(PEContext_t *context)
 {
-    OC_LOG(INFO, TAG, "IN DiscoverAmsService");
+    OIC_LOG(INFO, TAG, "IN DiscoverAmsService");
 
     OCStackResult ret = OC_STACK_ERROR;
     const char DOXM_DEVICEID_QUERY_FMT[] = "%s?%s=%s";
     char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {};
     OCCallbackData cbData = {.context=NULL};
-    char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
-    uint32_t outLen = 0;
-    B64Result b64Ret;
 
     VERIFY_NON_NULL(TAG, context, ERROR);
-    b64Ret = b64Encode(context->amsMgrContext->amsDeviceId.id,
-          sizeof(context->amsMgrContext->amsDeviceId.id), base64Buff, sizeof(base64Buff), &outLen);
-    VERIFY_SUCCESS(TAG, B64_OK == b64Ret, ERROR);
     snprintf(uri, sizeof(uri), DOXM_DEVICEID_QUERY_FMT, OIC_RSRC_DOXM_URI,
-                                       OIC_JSON_DEVICE_ID_NAME, base64Buff);
+                                       OIC_JSON_DEVICE_ID_NAME,
+                                       context->amsMgrContext->amsDeviceId.id);
 
     cbData.cb = &AmsMgrDiscoveryCallback;
     cbData.context = (void*)context;
@@ -80,20 +73,19 @@ OCStackResult DiscoverAmsService(PEContext_t *context)
      * Need logic to reset the PE state and send ACCESS_DENIED response,
      * when discovery response from AMS service is not received within certain time.
      */
-    OC_LOG_V(INFO, TAG,"AMS Manager Sending Multicast Discovery with URI = %s", uri);
+    OIC_LOG_V(INFO, TAG,"AMS Manager Sending Multicast Discovery with URI = %s", uri);
     ret = OCDoResource(NULL, OC_REST_DISCOVER, uri, NULL, NULL,
                        CT_DEFAULT, OC_LOW_QOS, &cbData, NULL, 0);
 
 exit:
-    OC_LOG(INFO, TAG, "Leaving DiscoverAmsService");
+    OIC_LOG(INFO, TAG, "Leaving DiscoverAmsService");
     return ret;
 }
 
-
 static OCStackApplicationResult AmsMgrDiscoveryCallback(void *ctx, OCDoHandle handle,
                          OCClientResponse * clientResponse)
 {
-    OC_LOG_V(INFO, TAG, "%s Begin", __func__ );
+    OIC_LOG_V(INFO, TAG, "%s Begin", __func__ );
 
     if (!ctx ||
         !clientResponse ||
@@ -101,7 +93,7 @@ static OCStackApplicationResult AmsMgrDiscoveryCallback(void *ctx, OCDoHandle ha
         (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)||
         (OC_STACK_OK != clientResponse->result))
     {
-        OC_LOG_V(ERROR, TAG, "%s Invalid Response ", __func__);
+        OIC_LOG_V(ERROR, TAG, "%s Invalid Response ", __func__);
         return OC_STACK_KEEP_TRANSACTION;
     }
 
@@ -109,20 +101,22 @@ static OCStackApplicationResult AmsMgrDiscoveryCallback(void *ctx, OCDoHandle ha
     PEContext_t *context = (PEContext_t *) ctx;
     if (context->state != AWAITING_AMS_RESPONSE)
     {
-        OC_LOG_V(ERROR, TAG, "%s Invalid PE State ", __func__);
+        OIC_LOG_V(ERROR, TAG, "%s Invalid PE State ", __func__);
         return OC_STACK_DELETE_TRANSACTION;
     }
 
     OicSecDoxm_t *doxm = NULL;
-    OC_LOG_V(INFO, TAG, "Doxm DeviceId Discovery response = %s\n",
+
+    OIC_LOG_V(INFO, TAG, "Doxm DeviceId Discovery response = %s\n",
           ((OCSecurityPayload*)clientResponse->payload)->securityData);
-    doxm = JSONToDoxmBin(((OCSecurityPayload*)clientResponse->payload)->securityData);
+    uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
+    size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
 
     //As doxm is NULL amsmgr can't test if response from trusted AMS service
     //so keep the transaction.
-    if(NULL == doxm)
+    if (OC_STACK_OK == CBORPayloadToDoxm(payload, size, &doxm))
     {
-        OC_LOG_V(ERROR, TAG, "%s : Unable to convert JSON to Binary",__func__);
+        OIC_LOG_V(ERROR, TAG, "%s : Unable to convert CBOR to Binary",__func__);
         return OC_STACK_KEEP_TRANSACTION;
     }
 
@@ -136,9 +130,9 @@ static OCStackApplicationResult AmsMgrDiscoveryCallback(void *ctx, OCDoHandle ha
     if (memcmp(&context->amsMgrContext->amsDeviceId, &deviceId,
             sizeof(context->amsMgrContext->amsDeviceId)) == 0)
     {
-        OC_LOG(INFO, TAG, "AMS Manager Sending unicast discovery to get secured port info");
+        OIC_LOG(INFO, TAG, "AMS Manager Sending unicast discovery to get secured port info");
         //Sending Unicast discovery to get secure port information
-        if(OC_STACK_OK == SendUnicastSecurePortDiscovery(context, &clientResponse->devAddr,
+        if (OC_STACK_OK == SendUnicastSecurePortDiscovery(context, &clientResponse->devAddr,
                 clientResponse->connType))
         {
             context->retVal = ACCESS_WAITING_FOR_AMS;
@@ -150,11 +144,10 @@ static OCStackApplicationResult AmsMgrDiscoveryCallback(void *ctx, OCDoHandle ha
     return OC_STACK_DELETE_TRANSACTION;
 }
 
-
 OCStackResult SendUnicastSecurePortDiscovery(PEContext_t *context,OCDevAddr *devAddr,
                                       OCConnectivityType connType)
 {
-    OC_LOG(INFO, TAG, "IN SendUnicastSecurePortDiscovery");
+    OIC_LOG(INFO, TAG, "IN SendUnicastSecurePortDiscovery");
 
     const char RES_DOXM_QUERY_FMT[] = "%s?%s=%s";
     OCCallbackData cbData = {.context=NULL};
@@ -165,7 +158,7 @@ OCStackResult SendUnicastSecurePortDiscovery(PEContext_t *context,OCDevAddr *dev
     cbData.cb = &SecurePortDiscoveryCallback;
     cbData.context = context;
 
-    OC_LOG_V(INFO, TAG, "AMS Manager Sending Unicast Discovery with URI = %s", uri);
+    OIC_LOG_V(INFO, TAG, "AMS Manager Sending Unicast Discovery with URI = %s", uri);
 
     return  OCDoResource(NULL, OC_REST_DISCOVER, uri, devAddr, NULL,
                          connType, OC_LOW_QOS, &cbData, NULL, 0);
@@ -174,29 +167,31 @@ OCStackResult SendUnicastSecurePortDiscovery(PEContext_t *context,OCDevAddr *dev
 static OCStackApplicationResult SecurePortDiscoveryCallback(void *ctx, OCDoHandle handle,
                          OCClientResponse * clientResponse)
 {
-    OC_LOG(INFO, TAG, "In SecurePortDiscoveryCallback");
+    OIC_LOG(INFO, TAG, "In SecurePortDiscoveryCallback");
 
     if (!ctx ||
         !clientResponse ||
         !clientResponse->payload||
         (PAYLOAD_TYPE_DISCOVERY != clientResponse->payload->type)||
         (OC_STACK_OK != clientResponse->result))
-        {
-            OC_LOG_V(ERROR, TAG, "%s Invalid Response ", __func__);
-            SRMSendResponse(ACCESS_DENIED_AMS_SERVICE_ERROR);
-            return OC_STACK_DELETE_TRANSACTION;
-        }
+    {
+        OIC_LOG_V(ERROR, TAG, "%s Invalid Response ", __func__);
+        SRMSendResponse(ACCESS_DENIED_AMS_SERVICE_ERROR);
+        return OC_STACK_DELETE_TRANSACTION;
+    }
 
     PEContext_t *context = (PEContext_t *) ctx;
+
     (void)handle;
     if (context->state != AWAITING_AMS_RESPONSE)
     {
-        OC_LOG_V(ERROR, TAG, "%s Invalid PE State ", __func__);
+        OIC_LOG_V(ERROR, TAG, "%s Invalid PE State ", __func__);
         context->retVal = ACCESS_DENIED_AMS_SERVICE_ERROR;
         SRMSendResponse(context->retVal);
         return OC_STACK_DELETE_TRANSACTION;
     }
-    OCResourcePayload* resPayload = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
+
+    OCResourcePayload *resPayload = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
 
     //Verifying if the ID of the sender is an AMS service that this device trusts.
     if(resPayload &&
@@ -205,6 +200,7 @@ static OCStackApplicationResult SecurePortDiscoveryCallback(void *ctx, OCDoHandl
             // resPayload->sid,
                     sizeof(context->amsMgrContext->amsDeviceId.id)) != 0)
     {
+        OIC_LOG_V(ERROR, TAG, "%s Invalid AMS device", __func__);
         context->retVal = ACCESS_DENIED_AMS_SERVICE_ERROR;
         SRMSendResponse(context->retVal);
         return OC_STACK_DELETE_TRANSACTION;
@@ -218,13 +214,13 @@ static OCStackApplicationResult SecurePortDiscoveryCallback(void *ctx, OCDoHandl
             return OC_STACK_DELETE_TRANSACTION;
         }
     }
-    OC_LOG(INFO, TAG, "Can not find secure port information");
+    OIC_LOG(INFO, TAG, "Can not find secure port information");
+
     context->retVal = ACCESS_DENIED_AMS_SERVICE_ERROR;
     SRMSendResponse(context->retVal);
     return OC_STACK_DELETE_TRANSACTION;
 }
 
-
 OCStackResult SendAclReq(PEContext_t *context, OCDevAddr *devAddr, OCConnectivityType connType,
         uint16_t securedPort)
 {
@@ -236,17 +232,22 @@ OCStackResult SendAclReq(PEContext_t *context, OCDevAddr *devAddr, OCConnectivit
     OCCallbackData cbData = {.context=NULL};
     OCDevAddr destAddr = {.adapter = OC_ADAPTER_IP};
     B64Result b64Ret;
+    char *subID = NULL;
 
     VERIFY_NON_NULL(TAG, context, ERROR);
     VERIFY_NON_NULL(TAG, devAddr, ERROR);
 
-    b64Ret = b64Encode(context->subject.id, sizeof(context->subject.id),
-                       base64Buff, sizeof(base64Buff), &outLen);
-    VERIFY_SUCCESS(TAG, B64_OK == b64Ret, ERROR);
+    ret = ConvertUuidToStr(&context->subject, &subID);
+    if(OC_STACK_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "SendAclReq : Failed to canonical UUID encoding");
+        return OC_STACK_ERROR;
+    }
 
     snprintf(uri, sizeof(uri), GET_ACE_QUERY_FMT, OIC_RSRC_ACL_URI,
-                                    OIC_JSON_SUBJECT_NAME, base64Buff,
+                                    OIC_JSON_SUBJECTID_NAME, subID,
                                     OIC_JSON_RESOURCES_NAME, context->resource);
+    OICFree(subID);
 
     cbData.cb = &AmsMgrAclReqCallback;
     cbData.context = context;
@@ -256,20 +257,19 @@ OCStackResult SendAclReq(PEContext_t *context, OCDevAddr *devAddr, OCConnectivit
     destAddr.flags = (OCTransportFlags)(destAddr.flags | OC_FLAG_SECURE);
     destAddr.port = securedPort;
 
-    OC_LOG_V(INFO, TAG, "AMS Manager Sending Unicast ACL request with URI = %s", uri);
+    OIC_LOG_V(INFO, TAG, "AMS Manager Sending Unicast ACL request with URI = %s", uri);
     ret = OCDoResource(NULL, OC_REST_GET, uri, &destAddr, NULL,
             connType, OC_LOW_QOS, &cbData, NULL, 0);
 
 exit:
-    OC_LOG_V(INFO, TAG, "%s returns %d ", __func__, ret);
+    OIC_LOG_V(INFO, TAG, "%s returns %d ", __func__, ret);
     return ret;
 }
 
-
 static OCStackApplicationResult AmsMgrAclReqCallback(void *ctx, OCDoHandle handle,
     OCClientResponse * clientResponse)
 {
-    OC_LOG_V(INFO, TAG, "%s Begin", __func__ );
+    OIC_LOG_V(INFO, TAG, "%s Begin", __func__ );
 
     (void)handle;
     PEContext_t *context = (PEContext_t *) ctx;
@@ -281,13 +281,14 @@ static OCStackApplicationResult AmsMgrAclReqCallback(void *ctx, OCDoHandle handl
         (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type) ||
         (clientResponse->result != OC_STACK_OK))
     {
+        OIC_LOG_V(ERROR, TAG, "%s Invalid Response ", __func__);
         SRMSendResponse(ACCESS_DENIED_AMS_SERVICE_ERROR);
-        goto exit;
+        return OC_STACK_DELETE_TRANSACTION;
     }
 
     if (context->state != AWAITING_AMS_RESPONSE)
     {
-        OC_LOG_V(ERROR, TAG, "%s Invalid State ", __func__);
+        OIC_LOG_V(ERROR, TAG, "%s Invalid State ", __func__);
         context->retVal = ACCESS_DENIED_AMS_SERVICE_ERROR;
         SRMSendResponse(context->retVal);
         return OC_STACK_DELETE_TRANSACTION;
@@ -300,15 +301,16 @@ static OCStackApplicationResult AmsMgrAclReqCallback(void *ctx, OCDoHandle handl
         memcmp(context->amsMgrContext->amsDeviceId.id, clientResponse->identity.id,
                        sizeof(context->amsMgrContext->amsDeviceId.id)) == 0)
     {
+        size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
         OCStackResult ret =
-                InstallNewACL(((OCSecurityPayload*)clientResponse->payload)->securityData);
+                InstallNewACL(((OCSecurityPayload*)clientResponse->payload)->securityData, size);
         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
 
-        OC_LOG_V(INFO, TAG, "%s : Calling checkPermission", __func__);
+        OIC_LOG_V(INFO, TAG, "%s : Calling checkPermission", __func__);
         rsps = CheckPermission(context, &context->subject, context->resource, context->permission);
         VERIFY_SUCCESS(TAG, (true == IsAccessGranted(rsps)), ERROR);
 
-        OC_LOG_V(INFO, TAG, "%sAccess granted, Calling SRMCallCARequestHandler", __func__);
+        OIC_LOG_V(INFO, TAG, "%sAccess granted, Calling SRMCallCARequestHandler", __func__);
         context->retVal = ACCESS_GRANTED;
         SRMSendResponse(context->retVal);
         return OC_STACK_DELETE_TRANSACTION;
@@ -317,12 +319,9 @@ static OCStackApplicationResult AmsMgrAclReqCallback(void *ctx, OCDoHandle handl
 exit:
     context->retVal = ACCESS_DENIED_AMS_SERVICE_ERROR;
     SRMSendResponse(context->retVal);
-    FreeCARequestInfo(context->amsMgrContext->requestInfo);
-    OICFree(context->amsMgrContext->endpoint);
     return OC_STACK_DELETE_TRANSACTION;
 }
 
-
 OCStackResult UpdateAmsMgrContext(PEContext_t *context, const CAEndpoint_t *endpoint,
                         const CARequestInfo_t *requestInfo)
 {
@@ -330,7 +329,7 @@ OCStackResult UpdateAmsMgrContext(PEContext_t *context, const CAEndpoint_t *endp
 
     //The AmsMgr context endpoint and requestInfo will be free from ,
     //AmsMgrAclReqCallback function
-    if(context->amsMgrContext->endpoint)
+    if (context->amsMgrContext->endpoint)
     {
         OICFree(context->amsMgrContext->endpoint);
         context->amsMgrContext->endpoint = NULL;
@@ -339,7 +338,7 @@ OCStackResult UpdateAmsMgrContext(PEContext_t *context, const CAEndpoint_t *endp
     VERIFY_NON_NULL(TAG, context->amsMgrContext->endpoint, ERROR);
     *context->amsMgrContext->endpoint = *endpoint;
 
-    if(context->amsMgrContext->requestInfo)
+    if (context->amsMgrContext->requestInfo)
     {
         FreeCARequestInfo(context->amsMgrContext->requestInfo);
         context->amsMgrContext->requestInfo = NULL;
@@ -353,6 +352,11 @@ exit:
 
 void FreeCARequestInfo(CARequestInfo_t *requestInfo)
 {
+    if (NULL == requestInfo)
+    {
+        OIC_LOG_V(ERROR, TAG, "%s: Can't free memory. Received NULL requestInfo", __func__);
+        return;
+    }
     OICFree(requestInfo->info.token);
     OICFree(requestInfo->info.options);
     OICFree(requestInfo->info.payload);
@@ -365,22 +369,22 @@ void FreeCARequestInfo(CARequestInfo_t *requestInfo)
 //context->amsMgrContext->amsDeviceId with amsID of the Amacl else leaves it empty.
 bool FoundAmaclForRequest(PEContext_t *context)
 {
-    OC_LOG_V(INFO, TAG, "%s:no ACL found. Searching for AMACL",__func__);
+    OIC_LOG_V(INFO, TAG, "%s:no ACL found. Searching for AMACL",__func__);
 
     bool ret = false;
     VERIFY_NON_NULL(TAG, context, ERROR);
     memset(&context->amsMgrContext->amsDeviceId, 0, sizeof(context->amsMgrContext->amsDeviceId));
 
     //Call amacl resource function to get the AMS service deviceID for the resource
-    if(OC_STACK_OK == AmaclGetAmsDeviceId(context->resource, &context->amsMgrContext->amsDeviceId))
+    if (OC_STACK_OK == AmaclGetAmsDeviceId(context->resource, &context->amsMgrContext->amsDeviceId))
     {
-        OC_LOG_V(INFO, TAG, "%s:AMACL found for the requested resource %s",
+        OIC_LOG_V(INFO, TAG, "%s:AMACL found for the requested resource %s",
                 __func__, context->resource);
         ret = true;
     }
     else
     {
-        OC_LOG_V(INFO, TAG, "%s:AMACL found for the requested resource %s",
+        OIC_LOG_V(INFO, TAG, "%s:AMACL found for the requested resource %s",
                 __func__, context->resource);
         ret = false;
     }
@@ -389,12 +393,11 @@ bool FoundAmaclForRequest(PEContext_t *context)
      return ret;
 }
 
-
 void ProcessAMSRequest(PEContext_t *context)
 {
     OicUuid_t  emptyUuid = {.id={}};
-    OC_LOG_V(INFO, TAG, "Entering %s", __func__);
-    if(NULL != context)
+    OIC_LOG_V(INFO, TAG, "Entering %s", __func__);
+    if (NULL != context)
     {
         if((false == context->matchingAclFound) && (false == context->amsProcessing))
         {
@@ -406,6 +409,8 @@ void ProcessAMSRequest(PEContext_t *context)
                 if(OC_STACK_OK == DiscoverAmsService(context))
                 {
                     context->retVal = ACCESS_WAITING_FOR_AMS;
+                    OIC_LOG_V(INFO, TAG, "Leaving %s(WAITING_FOR_AMS)", __func__);
+                    context->state = AWAITING_AMS_RESPONSE;
                 }
                 else
                 {
@@ -416,11 +421,6 @@ void ProcessAMSRequest(PEContext_t *context)
     }
     else
     {
-        OC_LOG_V(INFO, TAG, "Leaving %s(context is NULL)", __func__);
-    }
-
-    if(ACCESS_WAITING_FOR_AMS == context->retVal )
-    {
-        OC_LOG_V(INFO, TAG, "Leaving %s(WAITING_FOR_AMS)", __func__);
+        OIC_LOG_V(INFO, TAG, "Leaving %s(context is NULL)", __func__);
     }
 }
index 3b20cf5..4c396f1 100644 (file)
@@ -1,38 +1,38 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
+//******************************************************************
+//
+// 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 "base64.h"
 
-/**< base character of Base64  */
+/** base character of Base64. */
 static const char g_b64TransTbl[] =
                 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef"\
                 "ghijklmnopqrstuvwxyz0123456789+/";
 
 /**
- * base64 block encode function
+ * base64 block encode function.
  *
- * @param[in] in  octet stream, max 3 byte
- * @param[out] out  base64 encoded stream, 4 byte
- * @param[in] len  byte-length of in
+ * @param in is the octet stream, max 3 byte.
+ * @param out is the Base64 encoded stream, 4 byte.
+ * @param len is the  byte-length of octet stream.
  *
- * @return  B64_OK for Success, otherwise some error value
+ * @return ::B64_OK for Success, otherwise some error value.
  */
 static B64Result b64EncodeBlk(const uint8_t* in, char* out, uint32_t len)
 {
@@ -43,7 +43,7 @@ static B64Result b64EncodeBlk(const uint8_t* in, char* out, uint32_t len)
 
     out[0] = g_b64TransTbl[in[0] >> 2];
 
-    if(1 == len)
+    if (1 == len)
     {
         out[1] = g_b64TransTbl[((in[0] & 0x03) << 4)];
     }
@@ -52,7 +52,7 @@ static B64Result b64EncodeBlk(const uint8_t* in, char* out, uint32_t len)
         out[1] = g_b64TransTbl[((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4)];
     }
 
-    if(2 == len)
+    if (2 == len)
     {
         out[2] = g_b64TransTbl[((in[1] & 0x0f) << 2)];
     }
@@ -77,25 +77,9 @@ static B64Result b64EncodeBlk(const uint8_t* in, char* out, uint32_t len)
     return B64_OK;
 }
 
-/**
- * Encode the plain message in base64.
- *
- * @param[in] in  Plain message
- * @param[in] inLen  Byte length of 'in'
- * @param[in,out] outBuf Output buffer
- *                Base64 encoded message will be written into 'out'
- *                NOTE : This method adds a NULL to the string configuration
- * @param[in] outBufSize Size of output buffer
- * @param[out] outLen  Byte length of encoded message
- *
- * @return  B64_OK for Success, otherwise some error value
-*/
 B64Result b64Encode(const uint8_t* in, const size_t inLen,
                char* outBuf, const size_t outBufSize, uint32_t* outLen)
 {
-    uint32_t i;
-    uint32_t minBufSize;
-
     if (NULL == in || 0 == inLen || NULL ==  outBuf || NULL == outLen )
     {
         return B64_INVALID_PARAM;
@@ -104,12 +88,13 @@ B64Result b64Encode(const uint8_t* in, const size_t inLen,
     *outLen = ((inLen / 3) * 3 == inLen) ?
               ((inLen / 3) * 4) :
               (((inLen / 3) + 1) * 4);
-    minBufSize = (*outLen + 1);
-    if(outBufSize < minBufSize)
+    uint32_t minBufSize = (*outLen + 1);
+    if (outBufSize < minBufSize)
     {
         return B64_OUTPUT_BUFFER_TOO_SMALL;
     }
 
+    uint32_t i;
     for (i = 0; i < inLen / 3; i++)
     {
         if(B64_OK != b64EncodeBlk(in + i * 3, outBuf + i * 4, 3))
@@ -118,9 +103,9 @@ B64Result b64Encode(const uint8_t* in, const size_t inLen,
         }
     }
 
-    if (i * 3 != inLen)
+    if (((size_t)i * 3) != inLen)
     {
-        if(B64_OK != b64EncodeBlk(in + i * 3, outBuf + i * 4, inLen - i * 3))
+        if (B64_OK != b64EncodeBlk(in + i * 3, outBuf + i * 4, inLen - i * 3))
         {
             return B64_INVALID_PARAM;
         }
@@ -132,11 +117,11 @@ B64Result b64Encode(const uint8_t* in, const size_t inLen,
 }
 
 /**
- * Get decoded value
+ * Get decoded value.
  *
- * @param[in] c  Base64 encoded charactor
+ * @param c is the Base64 encoded character.
  *
- * @return decoded value, 6-bit
+ * @return decoded value, 6-bit.
  */
 static uint32_t b64GetVal(char c)
 {
@@ -169,23 +154,21 @@ static uint32_t b64GetVal(char c)
 }
 
 /**
- * base64 block decode function
+ * Base64 block decode function.
  *
- * @param[in] in  Base64 encoded stream, 4 bytes
- * @param[out] out  Octet stream, 3 bytes
+ * @param in is the Base64 encoded stream, 4 bytes.
+ * @param out is the Octet stream, 3 bytes.
  *
- * @return  B64_OK for Success, otherwise some error value
+ * @return ::B64_OK for Success, otherwise some error value.
  */
 static B64Result b64DecodeBlk(const char* in, uint8_t* out)
 {
-    uint32_t val;
-
-    if(NULL == in || NULL == out)
+    if (NULL == in || NULL == out)
     {
         return B64_INVALID_PARAM;
     }
 
-    val = (b64GetVal(in[0]) << 18) | (b64GetVal(in[1]) << 12) |
+    uint32_t val = (b64GetVal(in[0]) << 18) | (b64GetVal(in[1]) << 12) |
           (b64GetVal(in[2]) << 6) | (b64GetVal(in[3]));
 
     out[0] = (val >> 16) & 0xff;
@@ -202,47 +185,32 @@ static B64Result b64DecodeBlk(const char* in, uint8_t* out)
     return B64_OK;
 }
 
-/**
- * Decode the encoded message in base64.
- *
- * @param[in] in  Base64 encoded message
- * @param[in] inLen  Byte lenth of 'in'
- * @param[in, out] outBuf  Output buffer
- *                 Base64 decoded message will be written into 'out'
- * @param[in] outBufSize Size of output buffer
- * @param[out] outLen  Byte length of decoded message
- *
- * @return  B64_OK for Success, otherwise some error value
- */
 B64Result b64Decode(const char* in, const size_t inLen,
                uint8_t* outBuf, size_t outBufSize, uint32_t* outLen)
 {
-    uint32_t i;
-    uint32_t minBufSize;
-
     if (NULL == in || 0 == inLen || 0 != (inLen & 0x03) || NULL == outBuf || NULL == outLen)
     {
         return B64_INVALID_PARAM;
     }
 
     *outLen = (inLen / 4) * 3;
-    minBufSize = (inLen / 4) * 3;
-    if('=' == in[inLen - 1])
+    uint32_t minBufSize = (inLen / 4) * 3;
+    if ('=' == in[inLen - 1])
     {
         minBufSize--;
         (*outLen)--;
     }
-    if('=' == in[inLen - 2])
+    if ('=' == in[inLen - 2])
     {
         minBufSize--;
         (*outLen)--;
     }
-    if(outBufSize < minBufSize)
+    if (outBufSize < minBufSize)
     {
         return B64_OUTPUT_BUFFER_TOO_SMALL;
     }
 
-    for (i = 0; i < inLen / 4; i++)
+    for (uint32_t i = 0; i < inLen / 4; i++)
     {
         if(B64_OK != b64DecodeBlk(in + i * 4, outBuf + i * 3))
         {
index 660164b..07bc8ea 100644 (file)
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #define __STDC_LIMIT_MACROS
-#include "ocstack.h"
-#include "logger.h"
-#include "oic_malloc.h"
-#include "cJSON.h"
-#include "resourcemanager.h"
-#include "psinterface.h"
-#include "utlist.h"
-#include "srmresourcestrings.h"
-#include "credresource.h"
-#include "ocrandom.h"
-#include "doxmresource.h"
-#include "base64.h"
-#include "srmutility.h"
-#include "cainterface.h"
-#include "pbkdf2.h"
+
 #include <stdlib.h>
-#include "iotvticalendar.h"
 #ifdef WITH_ARDUINO
 #include <string.h>
 #else
 #endif
 #include <stdint.h>
 
+#include "cainterface.h"
+#include "payload_logging.h"
+#include "ocstack.h"
+#include "ocrandom.h"
+#include "base64.h"
+#include "ocserverrequest.h"
+#include "oic_malloc.h"
+#include "ocpayload.h"
+#include "utlist.h"
+#include "credresource.h"
+#include "doxmresource.h"
+#include "pstatresource.h"
+#include "iotvticalendar.h"
+#include "pbkdf2.h"
+#include "resourcemanager.h"
+#include "srmresourcestrings.h"
+#include "srmutility.h"
+#include "psinterface.h"
+#include "pinoxmcommon.h"
+
+#ifdef __WITH_DTLS__
+#include "global.h"
+#endif
+
 #define TAG  "SRM-CREDL"
 
+/** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
+ * The value of payload size is increased until reaching belox max cbor size. */
+static const uint16_t CBOR_SIZE = 2048;
+
+/** Max cbor size payload. */
+static const uint16_t CBOR_MAX_SIZE = 4400;
+
+/** CRED size - Number of mandatory items. */
+static const uint8_t CRED_ROOT_MAP_SIZE = 2;
+static const uint8_t CRED_MAP_SIZE = 3;
+
 
 static OicSecCred_t        *gCred = NULL;
 static OCResourceHandle    gCredHandle = NULL;
@@ -56,7 +76,7 @@ static void FreeCred(OicSecCred_t *cred)
 {
     if(NULL == cred)
     {
-        OC_LOG (ERROR, TAG, "Invalid Parameter");
+        OIC_LOG(ERROR, TAG, "Invalid Parameter");
         return;
     }
     //Note: Need further clarification on roleID data type
@@ -66,7 +86,9 @@ static void FreeCred(OicSecCred_t *cred)
 #endif
 
     //Clean PublicData
+#ifdef __WITH_X509__
     OICFree(cred->publicData.data);
+#endif
 
     //Clean PrivateData
     OICFree(cred->privateData.data);
@@ -74,9 +96,6 @@ static void FreeCred(OicSecCred_t *cred)
     //Clean Period
     OICFree(cred->period);
 
-    //Clean Owners
-    OICFree(cred->owners);
-
     //Clean Cred node itself
     OICFree(cred);
 }
@@ -94,341 +113,498 @@ void DeleteCredList(OicSecCred_t* cred)
     }
 }
 
-/**
- * This function converts credential data into JSON format.
- * Caller needs to invoke 'free' when done using
- * returned string.
- * @param cred  pointer to instance of OicSecCred_t structure.
- *
- * @retval
- *      pointer to JSON credential representation - if credential for subjectId found
- *      NULL                                      - if credential for subjectId not found
- */
-char * BinToCredJSON(const OicSecCred_t * cred)
+static size_t OicSecCredCount(const OicSecCred_t *secCred)
 {
-    cJSON *jsonRoot = NULL;
-    char *jsonStr = NULL;
+    size_t size = 0;
+    for (const OicSecCred_t *cred = secCred; cred; cred = cred->next)
+    {
+        size++;
+    }
+    return size;
+}
 
-    if (cred)
+OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload,
+                                size_t *cborSize)
+{
+    if (NULL == credS || NULL == cborPayload || NULL != *cborPayload || NULL == cborSize)
     {
-        char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
-        uint32_t outLen = 0;
-        B64Result b64Ret = B64_OK;
+        return OC_STACK_INVALID_PARAM;
+    }
 
-        jsonRoot = cJSON_CreateObject();
-        VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+    OCStackResult ret = OC_STACK_ERROR;
 
-        cJSON *jsonCredArray = NULL;
-        cJSON_AddItemToObject(jsonRoot, OIC_JSON_CRED_NAME,
-                jsonCredArray = cJSON_CreateArray());
-        VERIFY_NON_NULL(TAG, jsonCredArray, ERROR);
+    CborError cborEncoderResult = CborNoError;
+    uint8_t *outPayload = NULL;
+    size_t cborLen = *cborSize;
+    *cborSize = 0;
+    *cborPayload = NULL;
+    const OicSecCred_t *cred = credS;
+    CborEncoder encoder;
+    CborEncoder credArray;
+    CborEncoder credRootMap;
+
+    if (0 == cborLen)
+    {
+        cborLen = CBOR_SIZE;
+    }
 
-        while(cred)
-        {
-            cJSON *jsonCred = cJSON_CreateObject();
-            VERIFY_NON_NULL(TAG, jsonCred, ERROR);
+    outPayload = (uint8_t *)OICCalloc(1, cborLen);
+    VERIFY_NON_NULL(TAG, outPayload, ERROR);
+    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
 
-            //CredID -- Mandatory
-            cJSON_AddNumberToObject(jsonCred, OIC_JSON_CREDID_NAME, (int)cred->credId);
+    // Create CRED Root Map (creds, rownerid)
+    cborEncoderResult = cbor_encoder_create_map(&encoder, &credRootMap, CRED_ROOT_MAP_SIZE);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Root Map");
 
-            //Subject -- Mandatory
-            outLen = 0;
-            memset(base64Buff, 0, sizeof(base64Buff));
-            b64Ret = b64Encode(cred->subject.id, sizeof(cred->subject.id), base64Buff,
-                   sizeof(base64Buff), &outLen);
-            VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
-            cJSON_AddStringToObject(jsonCred, OIC_JSON_SUBJECT_NAME, base64Buff);
+    // creds
+    cborEncoderResult = cbor_encode_text_string(&credRootMap, OIC_JSON_CREDS_NAME,
+        strlen(OIC_JSON_CREDS_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding creds Name Tag.");
 
-            //Note: Need further clarification on roleID data type
-#if 0
-            //RoleId -- Not Mandatory
-            if(cred->roleIdsLen > 0)
-            {
-                cJSON *jsonRoleIdsArray = NULL;
-                cJSON_AddItemToObject (jsonCred, OIC_JSON_ROLEIDS_NAME,
-                                         jsonRoleIdsArray = cJSON_CreateArray());
-                VERIFY_NON_NULL(TAG, jsonRoleIdsArray, ERROR);
-                for (size_t i = 0; i < cred->roleIdsLen; i++)
-                {
-                    cJSON_AddItemToArray (jsonRoleIdsArray,
-                            cJSON_CreateString((char *)cred->roleIds[i].id));
-                }
-            }
-#endif
+    // creds array
+    cborEncoderResult = cbor_encoder_create_array(&credRootMap, &credArray, OicSecCredCount(cred));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Array.");
 
-            //CredType -- Mandatory
-            cJSON_AddNumberToObject(jsonCred, OIC_JSON_CREDTYPE_NAME,(int)cred->credType);
+    while (cred)
+    {
+        CborEncoder credMap;
+        size_t mapSize = CRED_MAP_SIZE;
+        char *subject = NULL;
+        if (cred->period)
+        {
+            mapSize++;
+        }
+#ifdef __WITH_X509__
+        if (SIGNED_ASYMMETRIC_KEY == cred->credType && cred->publicData.data)
+        {
+            mapSize++;
+        }
+#endif /* __WITH_X509__ */
+        if (cred->privateData.data)
+        {
+            mapSize++;
+        }
+        cborEncoderResult = cbor_encoder_create_map(&credArray, &credMap, mapSize);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Map");
+
+        //CredID -- Mandatory
+        cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_CREDID_NAME,
+            strlen(OIC_JSON_CREDID_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Id Tag. ");
+        cborEncoderResult = cbor_encode_int(&credMap, cred->credId);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Id Value.");
+
+        //Subject -- Mandatory
+        cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_SUBJECTID_NAME,
+            strlen(OIC_JSON_SUBJECTID_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Subject Tag.");
+        ret = ConvertUuidToStr(&cred->subject, &subject);
+        VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
+        cborEncoderResult = cbor_encode_text_string(&credMap, subject, strlen(subject));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Subject Id Value.");
+        OICFree(subject);
+
+        //CredType -- Mandatory
+        cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_CREDTYPE_NAME,
+            strlen(OIC_JSON_CREDTYPE_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag.");
+        cborEncoderResult = cbor_encode_int(&credMap, cred->credType);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
 
 #ifdef __WITH_X509__
-            //PublicData -- Not Mandatory
-            if(cred->publicData.data)
-            {
-                if (SIGNED_ASYMMETRIC_KEY == cred->credType)
-                {
-                    cJSON_AddItemToObject(jsonCred, OIC_JSON_PUBLICDATA_NAME,
-                                          cJSON_Parse(cred->publicData.data));
-                }
-                else
-                {
-                cJSON_AddStringToObject(jsonCred, OIC_JSON_PUBLICDATA_NAME, cred->publicData.data);
-                }
-            }
+        //PublicData -- Not Mandatory
+        if (SIGNED_ASYMMETRIC_KEY == cred->credType && cred->publicData.data)
+        {
+            CborEncoder publicMap;
+            const size_t publicMapSize = 2;
+
+            cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_PUBLICDATA_NAME,
+                strlen(OIC_JSON_PUBLICDATA_NAME));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PublicData Tag.");
+
+            cborEncoderResult = cbor_encoder_create_map(&credMap, &publicMap, publicMapSize);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PublicData Map");
+
+            cborEncoderResult = cbor_encode_text_string(&publicMap, OIC_JSON_DATA_NAME,
+                strlen(OIC_JSON_DATA_NAME));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Pub Data Tag.");
+            cborEncoderResult = cbor_encode_byte_string(&publicMap, cred->publicData.data,
+                cred->publicData.len);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Pub Value.");
+
+            // TODO: Need to data strucure modification for OicSecCert_t.
+            cborEncoderResult = cbor_encode_text_string(&publicMap, OIC_JSON_ENCODING_NAME,
+                strlen(OIC_JSON_ENCODING_NAME));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Public Encoding Tag.");
+            cborEncoderResult = cbor_encode_text_string(&publicMap, OIC_SEC_ENCODING_RAW,
+                strlen(OIC_SEC_ENCODING_RAW));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Public Encoding Value.");
+
+            cborEncoderResult = cbor_encoder_close_container(&credMap, &publicMap);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing PublicData Map.");
+        }
 #endif /*__WITH_X509__*/
-            //PrivateData -- Not Mandatory
-            if(cred->privateData.data)
-            {
-#ifdef __WITH_X509__
-                if (SIGNED_ASYMMETRIC_KEY == cred->credType)
-                {
-                    cJSON_AddItemToObject(jsonCred, OIC_JSON_PRIVATEDATA_NAME,
-                                          cJSON_Parse(cred->privateData.data));
-                }
-                else
-                {
-                    cJSON_AddStringToObject(jsonCred, OIC_JSON_PRIVATEDATA_NAME, cred->privateData.data);
-                }
-#else
-                cJSON_AddStringToObject(jsonCred, OIC_JSON_PRIVATEDATA_NAME, cred->privateData.data);
-#endif
-            }
+        //PrivateData -- Not Mandatory
+        if(cred->privateData.data)
+        {
+            CborEncoder privateMap;
+            const size_t privateMapSize = 2;
+
+            cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_PRIVATEDATA_NAME,
+                strlen(OIC_JSON_PRIVATEDATA_NAME));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PrivateData Tag.");
+
+            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.");
+
+            cborEncoderResult = cbor_encoder_close_container(&credMap, &privateMap);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing PrivateData Map.");
+        }
 
-            //Period -- Not Mandatory
-            if(cred->period)
-            {
-                cJSON_AddStringToObject(jsonCred, OIC_JSON_PERIOD_NAME,
-                                        cred->period);
-            }
+        //Period -- Not Mandatory
+        if(cred->period)
+        {
+            cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_PERIOD_NAME,
+                strlen(OIC_JSON_PERIOD_NAME));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Name Tag.");
+            cborEncoderResult = cbor_encode_text_string(&credMap, cred->period,
+                strlen(cred->period));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Name Value.");
+        }
 
-            //Owners -- Mandatory
-            cJSON *jsonOwnrArray = NULL;
-            cJSON_AddItemToObject (jsonCred, OIC_JSON_OWNERS_NAME,
-                                             jsonOwnrArray = cJSON_CreateArray());
-            VERIFY_NON_NULL(TAG, jsonOwnrArray, ERROR);
-            for (size_t i = 0; i < cred->ownersLen; i++)
-            {
-                outLen = 0;
-                memset(base64Buff, 0, sizeof(base64Buff));
-                b64Ret = b64Encode(cred->owners[i].id, sizeof(cred->owners[i].id),
-                        base64Buff, sizeof(base64Buff), &outLen);
-                VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
-                cJSON_AddItemToArray (jsonOwnrArray,
-                                       cJSON_CreateString((char *)(base64Buff)));
-            }
 
-            /* Attach current cred node to cred Array */
-            cJSON_AddItemToArray(jsonCredArray, jsonCred);
-            cred = cred->next;
-        }
+        cborEncoderResult = cbor_encoder_close_container(&credArray, &credMap);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Cred Map.");
 
-        jsonStr = cJSON_PrintUnformatted(jsonRoot);
+        cred = cred->next;
     }
+    cborEncoderResult = cbor_encoder_close_container(&credRootMap, &credArray);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Cred Array.");
 
-exit:
-    if (jsonRoot)
+    cred = credS;
+
+    // Rownerid
     {
-        cJSON_Delete(jsonRoot);
+        char *rowner = NULL;
+        cborEncoderResult = cbor_encode_text_string(&credRootMap, OIC_JSON_ROWNERID_NAME,
+            strlen(OIC_JSON_ROWNERID_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding rownerid Name.");
+        ret = ConvertUuidToStr(&cred->rownerID, &rowner);
+        VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
+        cborEncoderResult = cbor_encode_text_string(&credRootMap, rowner, strlen(rowner));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding rownerid Value.");
+        OICFree(rowner);
     }
-    return jsonStr;
-}
 
-/*
- * This internal method converts JSON cred into binary cred.
- */
-OicSecCred_t * JSONToCredBin(const char * jsonStr)
-{
-    OCStackResult ret = OC_STACK_ERROR;
-    OicSecCred_t * headCred = NULL;
-    OicSecCred_t * prevCred = NULL;
-    cJSON *jsonCredArray = NULL;
+    // Close CRED Root Map
+    cborEncoderResult = cbor_encoder_close_container(&encoder, &credRootMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing CRED Root Map.");
 
-    cJSON *jsonRoot = cJSON_Parse(jsonStr);
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+    if (CborNoError == cborEncoderResult)
+    {
+        OIC_LOG(DEBUG, TAG, "CredToCBORPayload Successed");
+        *cborPayload = outPayload;
+        *cborSize = encoder.ptr - outPayload;
+        ret = OC_STACK_OK;
+    }
+    OIC_LOG(DEBUG, TAG, "CredToCBORPayload OUT");
+exit:
+    if (CborErrorOutOfMemory == cborEncoderResult)
+    {
+        OIC_LOG(DEBUG, TAG, "CredToCBORPayload:CborErrorOutOfMemory : retry with more memory");
+        // reallocate and try again!
+        OICFree(outPayload);
+        // Since the allocated initial memory failed, double the memory.
+        cborLen += encoder.ptr - encoder.end;
+        cborEncoderResult = CborNoError;
+        ret = CredToCBORPayload(credS, cborPayload, &cborLen);
+        *cborSize = cborLen;
+    }
 
-    jsonCredArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_CRED_NAME);
-    VERIFY_NON_NULL(TAG, jsonCredArray, ERROR);
-    if (cJSON_Array == jsonCredArray->type)
+    if (CborNoError != cborEncoderResult)
     {
-        int numCred = cJSON_GetArraySize(jsonCredArray);
-        int idx = 0;
+        OIC_LOG(ERROR, TAG, "Failed to CredToCBORPayload");
+        OICFree(outPayload);
+        outPayload = NULL;
+        *cborSize = 0;
+        *cborPayload = NULL;
+        ret = OC_STACK_ERROR;
+    }
 
-        unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
-        uint32_t outLen = 0;
-        B64Result b64Ret = B64_OK;
+    return ret;
+}
 
-        VERIFY_SUCCESS(TAG, numCred > 0, ERROR);
-        do
-        {
-            cJSON *jsonCred = cJSON_GetArrayItem(jsonCredArray, idx);
-            VERIFY_NON_NULL(TAG, jsonCred, ERROR);
+OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
+                                OicSecCred_t **secCred)
+{
+    if (NULL == cborPayload || NULL == secCred || NULL != *secCred || 0 == size)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
 
-            OicSecCred_t *cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
-            VERIFY_NON_NULL(TAG, cred, ERROR);
+    OCStackResult ret = OC_STACK_ERROR;
+    CborValue credCbor = { .parser = NULL };
+    CborParser parser = { .end = NULL };
+    CborError cborFindResult = CborNoError;
+    cbor_parser_init(cborPayload, size, 0, &parser, &credCbor);
 
-            headCred = (headCred) ? headCred : cred;
-            if (prevCred)
-            {
-                prevCred->next = cred;
-            }
-            size_t jsonObjLen = 0;
-            cJSON *jsonObj = NULL;
+    OicSecCred_t *headCred = (OicSecCred_t *) OICCalloc(1, sizeof(OicSecCred_t));
 
-            //CredId -- Mandatory
-            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_CREDID_NAME);
-            if(jsonObj)
-            {
-                VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
-                cred->credId = jsonObj->valueint;
-            }
+    // Enter CRED Root Map
+    CborValue CredRootMap = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
+    cborFindResult = cbor_value_enter_container(&credCbor, &CredRootMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering CRED Root Map.");
 
-            //subject -- Mandatory
-            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_SUBJECT_NAME);
-            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-            VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
-            outLen = 0;
-            memset(base64Buff, 0, sizeof(base64Buff));
-            b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring),
-                    base64Buff, sizeof(base64Buff), &outLen);
-            VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(cred->subject.id)),
-                           ERROR);
-            memcpy(cred->subject.id, base64Buff, outLen);
-
-            //CredType -- Mandatory
-            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_CREDTYPE_NAME);
-            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-            VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
-            cred->credType = (OicSecCredType_t)jsonObj->valueint;
-
-            //PrivateData is mandatory for some of the credential types listed below.
-            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PRIVATEDATA_NAME);
-            if ((cred->credType & SYMMETRIC_PAIR_WISE_KEY) ||
-                (cred->credType & SYMMETRIC_GROUP_KEY) ||
-                (cred->credType & PIN_PASSWORD))
-            {
-                VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-                VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
-            }
-#ifdef __WITH_X509__
-            else if (cred->credType & SIGNED_ASYMMETRIC_KEY)
-            {
-                VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-                VERIFY_SUCCESS(TAG, cJSON_Object == jsonObj->type, ERROR);
-            }
-#endif //  __WITH_X509__
-            if (NULL != jsonObj)
+    while (cbor_value_is_valid(&CredRootMap))
+    {
+        char* tagName = NULL;
+        size_t len = 0;
+        CborType type = cbor_value_get_type(&CredRootMap);
+        if (type == CborTextStringType)
+        {
+            cborFindResult = cbor_value_dup_text_string(&CredRootMap, &tagName, &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Name in CRED Root Map.");
+            cborFindResult = cbor_value_advance(&CredRootMap);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Value in CRED Root Map.");
+        }
+        if(tagName)
+        {
+            if (strcmp(tagName, OIC_JSON_CREDS_NAME)  == 0)
             {
-                if (cJSON_String == jsonObj->type)
-                {
-                    jsonObjLen = strlen(jsonObj->valuestring) + 1;
-                    cred->privateData.data = (char *)OICMalloc(jsonObjLen);
-                    VERIFY_NON_NULL(TAG, (cred->privateData.data), ERROR);
-                    strncpy((char *)cred->privateData.data, (char *)jsonObj->valuestring, jsonObjLen);
-                }
-#ifdef __WITH_X509__
-                else if (SIGNED_ASYMMETRIC_KEY == cred->credType && cJSON_Object == jsonObj->type)
+                // Enter CREDS Array
+                size_t len = 0;
+                int credCount = 0;
+                CborValue credArray = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
+                cborFindResult = cbor_value_enter_container(&CredRootMap, &credArray);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Cred Array.");
+
+                while (cbor_value_is_valid(&credArray))
                 {
-                    cred->privateData.data = cJSON_PrintUnformatted(jsonObj);
-                    VERIFY_NON_NULL(TAG, (cred->privateData.data), ERROR);
-                }
-#endif // __WITH_X509__
-            }
+                    credCount++;
+                    //CredId -- Mandatory
+                    CborValue credMap = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
+                    cborFindResult = cbor_value_enter_container(&credArray, &credMap);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Cred Map.");
+                    OicSecCred_t *cred = NULL;
+
+                    if(1 == credCount)
+                    {
+                        cred = headCred;
+                    }
+                    else
+                    {
+                        cred = (OicSecCred_t *) OICCalloc(1, sizeof(OicSecCred_t));
+                        OicSecCred_t *temp = headCred;
+                        while (temp->next)
+                        {
+                            temp = temp->next;
+                        }
+                        temp->next = cred;
+                    }
 
-            //PublicData is mandatory only for SIGNED_ASYMMETRIC_KEY credentials type.
-            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PUBLICDATA_NAME);
-#ifdef __WITH_X509__
-            if (cred->credType & SIGNED_ASYMMETRIC_KEY)
-            {
-                VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-                VERIFY_SUCCESS(TAG, cJSON_Object == jsonObj->type, ERROR);
-            }
-#endif //  __WITH_X509__
-            if (NULL != jsonObj)
-            {
-                if (cJSON_String == jsonObj->type)
-                {
-                    jsonObjLen = strlen(jsonObj->valuestring) + 1;
-                    cred->publicData.data = (char *)OICMalloc(jsonObjLen);
-                    VERIFY_NON_NULL(TAG, (cred->publicData.data), ERROR);
-                    strncpy((char *)cred->publicData.data, (char *)jsonObj->valuestring, jsonObjLen);
-                }
+                    VERIFY_NON_NULL(TAG, cred, ERROR);
+
+                    while(cbor_value_is_valid(&credMap))
+                    {
+                        char* name = NULL;
+                        CborType type = cbor_value_get_type(&credMap);
+                        if (type == CborTextStringType)
+                        {
+                            cborFindResult = cbor_value_dup_text_string(&credMap, &name, &len, NULL);
+                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Name in CRED Map.");
+                            cborFindResult = cbor_value_advance(&credMap);
+                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Value in CRED Map.");
+                        }
+                        if(name)
+                        {
+                            //credid
+                            if (strcmp(name, OIC_JSON_CREDID_NAME)  == 0)
+                            {
+                                cborFindResult = cbor_value_get_uint64(&credMap, (uint64_t *) &cred->credId);
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding CredId.");
+                            }
+                            // subjectid
+                            if (strcmp(name, OIC_JSON_SUBJECTID_NAME)  == 0)
+                            {
+                                char *subjectid = NULL;
+                                cborFindResult = cbor_value_dup_text_string(&credMap, &subjectid, &len, NULL);
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding subjectid Value.");
+                                ret = ConvertStrToUuid(subjectid, &cred->subject);
+                                VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
+                                OICFree(subjectid);
+                            }
+                            // credtype
+                            if (strcmp(name, OIC_JSON_CREDTYPE_NAME)  == 0)
+                            {
+                                cborFindResult = cbor_value_get_uint64(&credMap, (uint64_t *) &cred->credType);
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding CredType.");
+                            }
+                            // privatedata
+                            if (strcmp(name, OIC_JSON_PRIVATEDATA_NAME)  == 0)
+                            {
+                                CborValue privateMap = { .parser = NULL };
+                                cborFindResult = cbor_value_enter_container(&credMap, &privateMap);
+
+                                while (cbor_value_is_valid(&privateMap))
+                                {
+                                    char* privname = NULL;
+                                    CborType type = cbor_value_get_type(&privateMap);
+                                    if (type == CborTextStringType)
+                                    {
+                                        cborFindResult = cbor_value_dup_text_string(&privateMap, &privname,
+                                                &len, NULL);
+                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get text");
+                                        cborFindResult = cbor_value_advance(&privateMap);
+                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance value");
+                                    }
+                                    if (privname)
+                                    {
+                                        // 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);
+                                            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.
+                                        }
+                                    }
+                                    if (cbor_value_is_valid(&privateMap))
+                                    {
+                                        cborFindResult = cbor_value_advance(&privateMap);
+                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing privatedata Map.");
+                                    }
+                                    OICFree(privname);
+                                }
+
+                            }
 #ifdef __WITH_X509__
-                else if (SIGNED_ASYMMETRIC_KEY == cred->credType && cJSON_Object == jsonObj->type)
-                {
-                    cred->publicData.data = cJSON_PrintUnformatted(jsonObj);
-                    VERIFY_NON_NULL(TAG, (cred->publicData.data), ERROR);
+                            if (strcmp(name, OIC_JSON_PUBLICDATA_NAME)  == 0)
+                            {
+                                CborValue pubMap = { .parser = NULL };
+                                cborFindResult = cbor_value_enter_container(&credMap, &pubMap);
+
+                                while (cbor_value_is_valid(&pubMap))
+                                {
+                                    char* pubname = NULL;
+                                    CborType type = cbor_value_get_type(&pubMap);
+                                    if (type == CborTextStringType)
+                                    {
+                                        cborFindResult = cbor_value_dup_text_string(&pubMap, &pubname,
+                                                &len, NULL);
+                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get text");
+                                        cborFindResult = cbor_value_advance(&pubMap);
+                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance value");
+                                    }
+                                    if (pubname)
+                                    {
+                                        // PrivateData::privdata -- Mandatory
+                                        if (strcmp(pubname, OIC_JSON_DATA_NAME) == 0)
+                                        {
+                                            cborFindResult = cbor_value_dup_byte_string(&pubMap, &cred->publicData.data,
+                                                &cred->publicData.len, NULL);
+                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding PubData.");
+                                        }
+                                        // PublicData::encoding -- Mandatory
+                                        if (strcmp(pubname, OIC_JSON_ENCODING_NAME) == 0)
+                                        {
+                                            // TODO: Need to update data structure, just ignore encoding value now.
+                                        }
+                                    }
+                                    if (cbor_value_is_valid(&pubMap))
+                                    {
+                                        cborFindResult = cbor_value_advance(&pubMap);
+                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing publicdata Map.");
+                                    }
+                                    OICFree(pubname);
+                                }
+                            }
+#endif  //__WITH_X509__
+
+                            if (0 == strcmp(OIC_JSON_PERIOD_NAME, name))
+                            {
+                                cborFindResult = cbor_value_dup_text_string(&credMap, &cred->period, &len, NULL);
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Period.");
+                            }
+
+                            if (cbor_value_is_valid(&credMap))
+                            {
+                                cborFindResult = cbor_value_advance(&credMap);
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing CRED Map.");
+                            }
+                            OICFree(name);
+                        }
+                    }
+                    cred->next = NULL;
+                    if (cbor_value_is_valid(&credArray))
+                    {
+                        cborFindResult = cbor_value_advance(&credArray);
+                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing CRED Array.");
+                    }
                 }
-#endif //  __WITH_X509__
             }
 
-            //Period -- Not Mandatory
-            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PERIOD_NAME);
-            if(jsonObj && cJSON_String == jsonObj->type)
+            //ROwner -- Mandatory
+            if (strcmp(tagName, OIC_JSON_ROWNERID_NAME)  == 0)
             {
-                jsonObjLen = strlen(jsonObj->valuestring) + 1;
-                cred->period = (char *)OICMalloc(jsonObjLen);
-                VERIFY_NON_NULL(TAG, cred->period, ERROR);
-                strncpy(cred->period, jsonObj->valuestring, jsonObjLen);
-            }
+                char *stRowner = NULL;
+                cborFindResult = cbor_value_dup_text_string(&CredRootMap, &stRowner, &len, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Rownerid Value.");
 
-            //Owners -- Mandatory
-            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_OWNERS_NAME);
-            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
-            cred->ownersLen = cJSON_GetArraySize(jsonObj);
-            VERIFY_SUCCESS(TAG, cred->ownersLen > 0, ERROR);
-            cred->owners = (OicUuid_t*)OICCalloc(cred->ownersLen, sizeof(OicUuid_t));
-            VERIFY_NON_NULL(TAG, (cred->owners), ERROR);
-            for(size_t i = 0; i < cred->ownersLen; i++)
-            {
-                cJSON *jsonOwnr = cJSON_GetArrayItem(jsonObj, i);
-                VERIFY_NON_NULL(TAG, jsonOwnr, ERROR);
-                VERIFY_SUCCESS(TAG, cJSON_String == jsonOwnr->type, ERROR);
-                outLen = 0;
-                memset(base64Buff, 0, sizeof(base64Buff));
-                b64Ret = b64Decode(jsonOwnr->valuestring, strlen(jsonOwnr->valuestring),
-                         base64Buff, sizeof(base64Buff), &outLen);
-                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK &&
-                               outLen <= sizeof(cred->owners[i].id)), ERROR);
-                memcpy(cred->owners[i].id, base64Buff, outLen);
+                ret = ConvertStrToUuid(stRowner, &headCred->rownerID);
+                VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
+                OICFree(stRowner);
             }
-            prevCred = cred;
-        } while( ++idx < numCred);
+            OICFree(tagName);
+        }
+        if (cbor_value_is_valid(&CredRootMap))
+        {
+            cborFindResult = cbor_value_advance(&CredRootMap);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing CRED Root Map.");
+        }
     }
 
+    *secCred = headCred;
     ret = OC_STACK_OK;
 
 exit:
-    cJSON_Delete(jsonRoot);
-    if (OC_STACK_OK != ret)
+    if (CborNoError != cborFindResult)
     {
         DeleteCredList(headCred);
         headCred = NULL;
+        *secCred = NULL;
+        ret = OC_STACK_ERROR;
     }
-    return headCred;
+
+    return ret;
 }
 
-/**
- * This function generates the bin credential data.
- *
- * @param subject pointer to subject of this credential.
- * @param credType credential type.
- * @param publicData public data such as public key.
- * @param privateData private data such as private key.
- *        The privateData is expected in base64 encoded format.
- * @param ownersLen length of owners array
- * @param owners array of owners.
- *
- * @retval
- *      pointer to instance of OicSecCred_t  - success
- *      NULL                                 - error
- */
 OicSecCred_t * GenerateCredential(const OicUuid_t * subject, OicSecCredType_t credType,
-                                 const char * publicData, const char * privateData,
-                                 size_t ownersLen, const OicUuid_t * owners)
+                                  const OicSecCert_t * publicData, const OicSecKey_t* privateData,
+                                  const OicUuid_t * rownerID)
 {
     (void)publicData;
     OCStackResult ret = OC_STACK_ERROR;
 
-    OicSecCred_t *cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
+    OicSecCred_t *cred = (OicSecCred_t *)OICCalloc(1, sizeof(*cred));
     VERIFY_NON_NULL(TAG, cred, ERROR);
 
     //CredId is assigned before appending new cred to the existing
@@ -443,30 +619,25 @@ OicSecCred_t * GenerateCredential(const OicUuid_t * subject, OicSecCredType_t cr
     cred->credType = credType;
 
 #ifdef __WITH_X509__
-    if(publicData)
+    if (publicData && publicData->data)
     {
-        cred->publicData.data = (char *)OICMalloc(strlen(publicData)+1);
+        cred->publicData.data = (uint8_t *)OICCalloc(1, publicData->len);
         VERIFY_NON_NULL(TAG, cred->publicData.data, ERROR);
-        strncpy((char *)cred->publicData.data, publicData, strlen(publicData)+1);
+        memcpy(cred->publicData.data, publicData->data, publicData->len);
+        cred->publicData.len = publicData->len;
     }
 #endif // __WITH_X509__
 
-    if(privateData)
+    if (privateData && privateData->data)
     {
-        cred->privateData.data = (char *)OICMalloc(strlen(privateData)+1);
+        cred->privateData.data = (uint8_t *)OICCalloc(1, privateData->len);
         VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
-        strncpy((char *)cred->privateData.data, privateData, strlen(privateData)+1);
+        memcpy(cred->privateData.data, privateData->data, privateData->len);
+        cred->privateData.len = privateData->len;
     }
 
-    VERIFY_SUCCESS(TAG, ownersLen > 0, ERROR);
-    cred->ownersLen = ownersLen;
-
-    cred->owners = (OicUuid_t*)OICCalloc(cred->ownersLen, sizeof(OicUuid_t));
-    VERIFY_NON_NULL(TAG, cred->owners, ERROR);
-    for(size_t i = 0; i < cred->ownersLen; i++)
-    {
-        memcpy(cred->owners[i].id, owners[i].id, sizeof(cred->owners[i].id));
-    }
+    VERIFY_NON_NULL(TAG, rownerID, ERROR);
+    memcpy(&cred->rownerID, rownerID, sizeof(OicUuid_t));
 
     ret = OC_STACK_OK;
 exit:
@@ -483,22 +654,23 @@ static bool UpdatePersistentStorage(const OicSecCred_t *cred)
     bool ret = false;
 
     // Convert Cred data into JSON for update to persistent storage
-    char *jsonStr = BinToCredJSON(cred);
-    if (jsonStr)
+    if (cred)
     {
-        cJSON *jsonCred = cJSON_Parse(jsonStr);
-        OICFree(jsonStr);
-
-        if ((jsonCred) &&
-          (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_CRED_NAME, jsonCred)))
+        uint8_t *payload = NULL;
+        size_t size = 0;
+        OCStackResult res = CredToCBORPayload(cred, &payload, &size);
+        if ((OC_STACK_OK == res) && payload)
         {
-            ret = true;
+            if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_CRED_NAME, payload, size))
+            {
+                ret = true;
+            }
+            OICFree(payload);
         }
-        cJSON_Delete(jsonCred );
     }
     else //Empty cred list
     {
-        if (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_CRED_NAME, NULL))
+        if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_CRED_NAME, NULL, 0))
         {
             ret = true;
         }
@@ -507,23 +679,22 @@ static bool UpdatePersistentStorage(const OicSecCred_t *cred)
 }
 
 /**
- * Compare function used LL_SORT for sorting credentials
+ * Compare function used LL_SORT for sorting credentials.
  *
- * @param first   pointer to OicSecCred_t struct
- * @param second  pointer to OicSecCred_t struct
+ * @param first pointer to OicSecCred_t struct.
+ * @param second  pointer to OicSecCred_t struct.
  *
- *@retval
- *  -1    if credId of first is less than credId of second
- *   0    if credId of first is equal to credId of second
- *   1    if credId of first is greater than credId of second
+ *@return -1, if credId of first is less than credId of second.
+ * 0, if credId of first is equal to credId of second.
+ * 1, if credId of first is greater than credId of second.
  */
 static int CmpCredId(const OicSecCred_t * first, const OicSecCred_t *second)
 {
-    if(first->credId < second->credId)
+    if (first->credId < second->credId)
     {
         return -1;
     }
-    else if(first->credId > second->credId)
+    else if (first->credId > second->credId)
     {
         return 1;
     }
@@ -537,23 +708,19 @@ static int CmpCredId(const OicSecCred_t * first, const OicSecCred_t *second)
  * available due deletion of OicSecCred_t object or one more than
  * credId of last credential in the list.
  *
- * @retval
- *      next available credId  - success
- *      0                      - error
+ * @return next available credId if successful, else 0 for error.
  */
-
 static uint16_t GetCredId()
 {
     //Sorts credential list in incremental order of credId
     LL_SORT(gCred, CmpCredId);
 
-
     OicSecCred_t *currentCred = NULL, *credTmp = NULL;
     uint16_t nextCredId = 1;
 
     LL_FOREACH_SAFE(gCred, currentCred, credTmp)
     {
-        if(currentCred->credId == nextCredId)
+        if (currentCred->credId == nextCredId)
         {
             nextCredId += 1;
         }
@@ -571,38 +738,29 @@ exit:
 }
 
 /**
- * Get the default value
- * @retval  NULL for now. Update it when we finalize the default info.
+ * Get the default value.
+ *
+ * @return  NULL for now.
  */
 static OicSecCred_t* GetCredDefault()
 {
+    // TODO:Update it when we finalize the default info.
     return NULL;
 }
 
-/**
- * This function adds the new cred to the credential list.
- *
- * @param cred pointer to new credential.
- *
- * @retval
- *      OC_STACK_OK     - cred not NULL and persistent storage gets updated
- *      OC_STACK_ERROR  - cred is NULL or fails to update persistent storage
- */
 OCStackResult AddCredential(OicSecCred_t * newCred)
 {
     OCStackResult ret = OC_STACK_ERROR;
-
     VERIFY_SUCCESS(TAG, NULL != newCred, ERROR);
 
     //Assigning credId to the newCred
     newCred->credId = GetCredId();
-
     VERIFY_SUCCESS(TAG, newCred->credId != 0, ERROR);
 
     //Append the new Cred to existing list
     LL_APPEND(gCred, newCred);
 
-    if(UpdatePersistentStorage(gCred))
+    if (UpdatePersistentStorage(gCred))
     {
         ret = OC_STACK_OK;
     }
@@ -620,7 +778,7 @@ OCStackResult RemoveCredential(const OicUuid_t *subject)
 
     LL_FOREACH_SAFE(gCred, cred, tempCred)
     {
-        if(memcmp(cred->subject.id, subject->id, sizeof(subject->id)) == 0)
+        if (memcmp(cred->subject.id, subject->id, sizeof(subject->id)) == 0)
         {
             LL_DELETE(gCred, cred);
             FreeCred(cred);
@@ -628,9 +786,9 @@ OCStackResult RemoveCredential(const OicUuid_t *subject)
         }
     }
 
-    if(deleteFlag)
+    if (deleteFlag)
     {
-        if(UpdatePersistentStorage(gCred))
+        if (UpdatePersistentStorage(gCred))
         {
             ret = OC_STACK_RESOURCE_DELETED;
         }
@@ -651,21 +809,219 @@ OCStackResult RemoveAllCredentials(void)
     DeleteCredList(gCred);
     gCred = GetCredDefault();
 
-    if(!UpdatePersistentStorage(gCred))
+    if (!UpdatePersistentStorage(gCred))
     {
         return OC_STACK_ERROR;
     }
     return OC_STACK_OK;
 }
 
-static OCEntityHandlerResult HandlePostRequest(const OCEntityHandlerRequest * ehRequest)
+#ifdef __WITH_DTLS__
+/**
+ * Internal function to fill private data of owner PSK.
+ *
+ * @param receviedCred recevied owner credential from OBT(PT)
+ * @param ownerAdd address of OBT(PT)
+ * @param doxm current device's doxm resource
+ *
+ * @return
+ *     true successfully done and valid ower psk information
+ *     false Invalid owner psk information or failed to owner psk generation
+ */
+static bool FillPrivateDataOfOwnerPSK(OicSecCred_t* receviedCred, const CAEndpoint_t* ownerAddr,
+                           const OicSecDoxm_t* doxm)
+{
+    //Derive OwnerPSK locally
+    const char* oxmLabel = GetOxmString(doxm->oxmSel);
+    VERIFY_NON_NULL(TAG, oxmLabel, ERROR);
+
+    uint8_t ownerPSK[OWNER_PSK_LENGTH_128] = {0};
+    CAResult_t pskRet = CAGenerateOwnerPSK(ownerAddr,
+        (uint8_t*)oxmLabel, strlen(oxmLabel),
+        doxm->owner.id, sizeof(doxm->owner.id),
+        doxm->deviceID.id, sizeof(doxm->deviceID.id),
+        ownerPSK, OWNER_PSK_LENGTH_128);
+    VERIFY_SUCCESS(TAG, pskRet == CA_STATUS_OK, ERROR);
+
+    OIC_LOG(DEBUG, TAG, "OwnerPSK dump :");
+    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);
+
+    OIC_LOG(INFO, TAG, "PrivateData of OwnerPSK was calculated successfully");
+
+    //Verify OwnerPSK information
+    return (memcmp(&(receviedCred->subject), &(doxm->owner), sizeof(OicUuid_t)) == 0 &&
+            receviedCred->credType == SYMMETRIC_PAIR_WISE_KEY);
+exit:
+    //receviedCred->privateData.data will be deallocated when deleting credential.
+    return false;
+}
+
+#endif //__WITH_DTLS__
+
+static OCEntityHandlerResult HandlePutRequest(const OCEntityHandlerRequest * ehRequest)
 {
     OCEntityHandlerResult ret = OC_EH_ERROR;
+    OIC_LOG(DEBUG, TAG, "HandleCREDPutRequest IN");
+
+    //Get binary representation of cbor
+    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)
+    {
+#ifdef __WITH_DTLS__
+        OicUuid_t emptyUuid = {.id={0}};
+        const OicSecDoxm_t* doxm = GetDoxmResourceData();
+        if(false == doxm->owned && memcmp(&(doxm->owner), &emptyUuid, sizeof(OicUuid_t)) != 0)
+        {
+            //in case of owner PSK
+            switch(cred->credType)
+            {
+                case SYMMETRIC_PAIR_WISE_KEY:
+                {
+                    OCServerRequest *request = (OCServerRequest *)ehRequest->requestHandle;
+                    if(FillPrivateDataOfOwnerPSK(cred, (CAEndpoint_t *)&request->devAddr, doxm))
+                    {
+                        if(OC_STACK_RESOURCE_DELETED == RemoveCredential(&cred->subject))
+                        {
+                            OIC_LOG(WARNING, TAG, "The credential with the same subject ID was detected!");
+                        }
+
+                        OIC_LOG(ERROR, TAG, "OwnerPSK was generated successfully.");
+                        if(OC_STACK_OK == AddCredential(cred))
+                        {
+                            ret = OC_EH_RESOURCE_CREATED;
+                        }
+                        else
+                        {
+                            OIC_LOG(ERROR, TAG, "Failed to save the OwnerPSK as cred resource");
+                            ret = OC_EH_ERROR;
+                        }
+                    }
+                    else
+                    {
+                        OIC_LOG(ERROR, TAG, "Failed to verify receviced OwnerPKS.");
+                        ret = OC_EH_ERROR;
+                    }
+
+                    if(OC_EH_RESOURCE_CREATED == ret)
+                    {
+                        /**
+                         * in case of random PIN based OxM,
+                         * revert get_psk_info callback of tinyDTLS to use owner credential.
+                         */
+                        if(OIC_RANDOM_DEVICE_PIN == doxm->oxmSel)
+                        {
+                            OicUuid_t emptyUuid = { .id={0}};
+                            SetUuidForRandomPinOxm(&emptyUuid);
 
-    //Get binary representation of json
-    OicSecCred_t * cred  = JSONToCredBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
+                            if(CA_STATUS_OK != CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials))
+                            {
+                                OIC_LOG(ERROR, TAG, "Failed to revert DTLS credential handler.");
+                                ret = OC_EH_ERROR;
+                                break;
+                            }
+                        }
+
+                        //Select cipher suite to use owner PSK
+                        if(CA_STATUS_OK != CAEnableAnonECDHCipherSuite(false))
+                        {
+                            OIC_LOG(ERROR, TAG, "Failed to disable anonymous cipher suite");
+                            ret = OC_EH_ERROR;
+                        }
+                        else
+                        {
+                            OIC_LOG(INFO, TAG, "Anonymous cipher suite is DISABLED");
+                        }
+
+                        if(CA_STATUS_OK !=
+                           CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256))
+                        {
+                            OIC_LOG(ERROR, TAG, "Failed to select cipher suite");
+                            ret = OC_EH_ERROR;
+                        }
+                    }
 
-    if(cred)
+                    break;
+                }
+                case SYMMETRIC_GROUP_KEY:
+                case ASYMMETRIC_KEY:
+                case SIGNED_ASYMMETRIC_KEY:
+                case PIN_PASSWORD:
+                case ASYMMETRIC_ENCRYPTION_KEY:
+                {
+                    OIC_LOG(WARNING, TAG, "Unsupported credential type for owner credential.");
+                    ret = OC_EH_ERROR;
+                    break;
+                }
+                default:
+                {
+                    OIC_LOG(WARNING, TAG, "Unknow credential type for owner credential.");
+                    ret = OC_EH_ERROR;
+                    break;
+                }
+            }
+
+            if(OC_EH_RESOURCE_CREATED != ret)
+            {
+                /*
+                  * If some error is occured while ownership transfer,
+                  * ownership transfer related resource should be revert back to initial status.
+                  */
+                RestoreDoxmToInitState();
+                RestorePstatToInitState();
+            }
+        }
+        else
+        {
+            /*
+             * If the post request credential has credId, it will be
+             * discarded and the next available credId will be assigned
+             * to it before getting appended to the existing credential
+             * list and updating svr database.
+             */
+            ret = (OC_STACK_OK == AddCredential(cred))? OC_EH_RESOURCE_CREATED : OC_EH_ERROR;
+        }
+#else //not __WITH_DTLS__
+        /*
+         * If the post request credential has credId, it will be
+         * discarded and the next available credId will be assigned
+         * to it before getting appended to the existing credential
+         * list and updating svr database.
+         */
+        ret = (OC_STACK_OK == AddCredential(cred))? OC_EH_RESOURCE_CREATED : OC_EH_ERROR;
+#endif//__WITH_DTLS__
+    }
+
+    if (OC_EH_RESOURCE_CREATED != ret)
+    {
+        if(OC_STACK_OK != RemoveCredential(&cred->subject))
+        {
+            OIC_LOG(WARNING, TAG, "Failed to remove the invalid credential");
+        }
+        FreeCred(cred);
+    }
+    OIC_LOG(DEBUG, TAG, "HandleCREDPutRequest OUT");
+    return ret;
+}
+
+static OCEntityHandlerResult HandlePostRequest(const OCEntityHandlerRequest * ehRequest)
+{
+    OCEntityHandlerResult ret = OC_EH_ERROR;
+
+    //Get binary representation of CBOR
+    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 ((OC_STACK_OK == res) && cred)
     {
         //If the Post request credential has credId, it will be
         //discarded and the next available credId will be assigned
@@ -673,75 +1029,68 @@ static OCEntityHandlerResult HandlePostRequest(const OCEntityHandlerRequest * eh
         //list and updating svr database.
         ret = (OC_STACK_OK == AddCredential(cred))? OC_EH_RESOURCE_CREATED : OC_EH_ERROR;
     }
+
     return ret;
 }
 
 static OCEntityHandlerResult HandleDeleteRequest(const OCEntityHandlerRequest *ehRequest)
 {
-    OC_LOG(DEBUG, TAG, "Processing CredDeleteRequest");
+    OIC_LOG(DEBUG, TAG, "Processing CredDeleteRequest");
 
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
 
-    if(NULL == ehRequest->query)
-   {
-       return ehRet;
-   }
-
-   OicParseQueryIter_t parseIter = {.attrPos=NULL};
-   OicUuid_t subject = {.id={0}};
-
-   //Parsing REST query to get the subject
-   ParseQueryIterInit((unsigned char *)ehRequest->query, &parseIter);
-   while(GetNextQuery(&parseIter))
-   {
-       if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBJECT_NAME,
-               parseIter.attrLen) == 0)
-       {
-           unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
-           uint32_t outLen = 0;
-           B64Result b64Ret = B64_OK;
-
-           b64Ret = b64Decode((char *)parseIter.valPos, parseIter.valLen,
-                   base64Buff, sizeof(base64Buff), &outLen);
-
-           VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(subject.id)), ERROR);
-           memcpy(subject.id, base64Buff, outLen);
-       }
-   }
-
-   if(OC_STACK_RESOURCE_DELETED == RemoveCredential(&subject))
-   {
-       ehRet = OC_EH_RESOURCE_DELETED;
-   }
+    if (NULL == ehRequest->query)
+    {
+        return ehRet;
+    }
+
+    OicParseQueryIter_t parseIter = { .attrPos=NULL };
+    OicUuid_t subject = {.id={0}};
+
+    //Parsing REST query to get the subject
+    ParseQueryIterInit((unsigned char *)ehRequest->query, &parseIter);
+    while (GetNextQuery(&parseIter))
+    {
+        if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBJECTID_NAME,
+                parseIter.attrLen) == 0)
+        {
+            OCStackResult ret = ConvertStrToUuid((const char*)parseIter.valPos, &subject);
+            VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+        }
+    }
+
+    if (OC_STACK_RESOURCE_DELETED == RemoveCredential(&subject))
+    {
+        ehRet = OC_EH_RESOURCE_DELETED;
+    }
 
 exit:
     return ehRet;
 }
 
-/*
- * This internal method is the entity handler for Cred resources
- * to handle REST request (PUT/POST/DEL)
- */
-OCEntityHandlerResult CredEntityHandler (OCEntityHandlerFlag flag,
+OCEntityHandlerResult CredEntityHandler(OCEntityHandlerFlag flag,
                                         OCEntityHandlerRequest * ehRequest,
                                         void* callbackParameter)
 {
     (void)callbackParameter;
     OCEntityHandlerResult ret = OC_EH_ERROR;
 
-    if(!ehRequest)
+    if (!ehRequest)
     {
         return OC_EH_ERROR;
     }
     if (flag & OC_REQUEST_FLAG)
     {
-        OC_LOG (DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
+        OIC_LOG (DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
         //TODO :  Handle PUT/DEL methods
-        switch(ehRequest->method)
+        switch (ehRequest->method)
         {
             case OC_REST_GET:
                 ret = OC_EH_FORBIDDEN;
                 break;
+            case OC_REST_PUT:
+                ret = HandlePutRequest(ehRequest);
+                break;
             case OC_REST_POST:
                 ret = HandlePostRequest(ehRequest);
                 break;
@@ -755,78 +1104,64 @@ OCEntityHandlerResult CredEntityHandler (OCEntityHandlerFlag flag,
     }
 
     //Send payload to request originator
-    ret = (SendSRMResponse(ehRequest, ret, NULL) == OC_STACK_OK ?
-                       ret : OC_EH_ERROR);
+    ret = (SendSRMResponse(ehRequest, ret, NULL, 0) == OC_STACK_OK) ?
+                       ret : OC_EH_ERROR;
 
     return ret;
 }
 
-/*
- * This internal method is used to create '/oic/sec/Cred' resource.
- */
 OCStackResult CreateCredResource()
 {
-    OCStackResult ret;
-
-    ret = OCCreateResource(&gCredHandle,
-                           OIC_RSRC_TYPE_SEC_CRED,
-                           OIC_MI_DEF,
-                           OIC_RSRC_CRED_URI,
-                           CredEntityHandler,
-                           NULL,
-                           OC_RES_PROP_NONE);
+    OCStackResult ret = OCCreateResource(&gCredHandle,
+                                         OIC_RSRC_TYPE_SEC_CRED,
+                                         OIC_MI_DEF,
+                                         OIC_RSRC_CRED_URI,
+                                         CredEntityHandler,
+                                         NULL,
+                                         OC_RES_PROP_NONE);
 
     if (OC_STACK_OK != ret)
     {
-        OC_LOG (FATAL, TAG, "Unable to instantiate Cred resource");
+        OIC_LOG (FATAL, TAG, "Unable to instantiate Cred resource");
         DeInitCredResource();
     }
     return ret;
 }
 
-/**
- * Initialize Cred resource by loading data from persistent storage.
- *
- * @retval
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack process error
- */
 OCStackResult InitCredResource()
 {
     OCStackResult ret = OC_STACK_ERROR;
 
     //Read Cred resource from PS
-    char* jsonSVRDatabase = GetSVRDatabase();
-
-    if (jsonSVRDatabase)
+    uint8_t *data = NULL;
+    size_t size = 0;
+    ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_CRED_NAME, &data, &size);
+    // If database read failed
+    if (ret != OC_STACK_OK)
+    {
+        OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
+    }
+    if (data)
     {
-        //Convert JSON Cred into binary format
-        gCred = JSONToCredBin(jsonSVRDatabase);
+        // Read ACL resource from PS
+        ret = CBORPayloadToCred(data, size, &gCred);
     }
+
     /*
      * If SVR database in persistent storage got corrupted or
      * is not available for some reason, a default Cred is created
      * which allows user to initiate Cred provisioning again.
      */
-    if (!jsonSVRDatabase || !gCred)
+    if (ret != OC_STACK_OK || !data || !gCred)
     {
         gCred = GetCredDefault();
     }
     //Instantiate 'oic.sec.cred'
     ret = CreateCredResource();
-    OICFree(jsonSVRDatabase);
+    OICFree(data);
     return ret;
 }
 
-/**
- * Perform cleanup for Cred resources.
- *
- * @return
- *     OC_STACK_OK              - no errors
- *     OC_STACK_ERROR           - stack process error
- *     OC_STACK_NO_RESOURCE     - resource not found
- *     OC_STACK_INVALID_PARAM   - invalid param
- */
 OCStackResult DeInitCredResource()
 {
     OCStackResult result = OCDeleteResource(gCredHandle);
@@ -835,15 +1170,6 @@ OCStackResult DeInitCredResource()
     return result;
 }
 
-/**
- * This method is used by tinydtls/SRM to retrieve credential for given Subject.
- *
- * @param subject - subject for which credential is required.
- *
- * @retval
- *     reference to OicSecCred_t - if credential is found
- *     NULL                      - if credential not found
- */
 const OicSecCred_t* GetCredResourceData(const OicUuid_t* subject)
 {
     OicSecCred_t *cred = NULL;
@@ -865,22 +1191,9 @@ const OicSecCred_t* GetCredResourceData(const OicUuid_t* subject)
 
 
 #if defined(__WITH_DTLS__)
-/**
- * This internal callback is used by lower stack (i.e. CA layer) to
- * retrieve PSK credentials from RI security layer.
- *
- * @param[in]  type type of PSK data required by tinyDTLS layer during DTLS handshake.
- * @param[in]  desc Additional request information.
- * @param[in]  desc_len The actual length of desc.
- * @param[out] result  Must be filled with the requested information.
- * @param[in]  result_length  Maximum size of @p result.
- *
- * @return The number of bytes written to @p result or a value
- *         less than zero on error.
- */
-int32_t GetDtlsPskCredentials( CADtlsPskCredType_t type,
-              const unsigned char *desc, size_t desc_len,
-              unsigned char *result, size_t result_length)
+int32_t GetDtlsPskCredentials(CADtlsPskCredType_t type,
+              const uint8_t *desc, size_t desc_len,
+              uint8_t *result, size_t result_length)
 {
     int32_t ret = -1;
 
@@ -898,13 +1211,13 @@ int32_t GetDtlsPskCredentials( CADtlsPskCredType_t type,
                 // Retrieve Device ID from doxm resource
                 if ( OC_STACK_OK != GetDoxmDeviceID(&deviceID) )
                 {
-                    OC_LOG (ERROR, TAG, "Unable to retrieve doxm Device ID");
+                    OIC_LOG (ERROR, TAG, "Unable to retrieve doxm Device ID");
                     return ret;
                 }
 
                 if (result_length < sizeof(deviceID.id))
                 {
-                    OC_LOG (ERROR, TAG, "Wrong value for result_length");
+                    OIC_LOG (ERROR, TAG, "Wrong value for result_length");
                     return ret;
                 }
                 memcpy(result, deviceID.id, sizeof(deviceID.id));
@@ -933,24 +1246,16 @@ int32_t GetDtlsPskCredentials( CADtlsPskCredType_t type,
                         {
                             if(IOTVTICAL_VALID_ACCESS != IsRequestWithinValidTime(cred->period, NULL))
                             {
-                                OC_LOG (INFO, TAG, "Credentials are expired.");
+                                OIC_LOG (INFO, TAG, "Credentials are expired.");
                                 ret = -1;
                                 return ret;
                             }
                         }
 
-                        // Convert PSK from Base64 encoding to binary before copying
-                        uint32_t outLen = 0;
-                        B64Result b64Ret = b64Decode(cred->privateData.data,
-                                strlen(cred->privateData.data), result,
-                                result_length, &outLen);
-                        if (B64_OK != b64Ret)
-                        {
-                            OC_LOG (ERROR, TAG, "Base64 decoding failed.");
-                            ret = -1;
-                            return ret;
-                        }
-                        return outLen;
+                        // Copy PSK.
+                        result_length = cred->privateData.len;
+                        memcpy(result, cred->privateData.data, result_length);
+                        return result_length;
                     }
                 }
             }
@@ -958,7 +1263,7 @@ int32_t GetDtlsPskCredentials( CADtlsPskCredType_t type,
 
         default:
             {
-                OC_LOG (ERROR, TAG, "Wrong value passed for CADtlsPskCredType_t.");
+                OIC_LOG (ERROR, TAG, "Wrong value passed for CADtlsPskCredType_t.");
                 ret = -1;
             }
             break;
@@ -974,40 +1279,36 @@ int32_t GetDtlsPskCredentials( CADtlsPskCredType_t type,
  * @param[in] credType Type of credential to be added
  * @param[in] pin numeric characters
  * @param[in] pinSize length of 'pin'
- * @param[in] ownersLen Number of owners
- * @param[in] owners Array of owners
+ * @param[in] rownerID Resource owner's UUID
  * @param[out] tmpCredSubject Generated credential's subject.
  *
  * @return OC_STACK_OK for success and errorcode otherwise.
  */
 OCStackResult AddTmpPskWithPIN(const OicUuid_t* tmpSubject, OicSecCredType_t credType,
                             const char * pin, size_t pinSize,
-                            size_t ownersLen, const OicUuid_t * owners, OicUuid_t* tmpCredSubject)
+                            const OicUuid_t * rownerID, OicUuid_t* tmpCredSubject)
 {
     OCStackResult ret = OC_STACK_ERROR;
+    OIC_LOG(DEBUG, TAG, "AddTmpPskWithPIN IN");
 
-    if(tmpSubject == NULL || pin == NULL || pinSize == 0 || tmpCredSubject == NULL)
+    if(NULL == tmpSubject || NULL == pin || 0 == pinSize || NULL == tmpCredSubject)
     {
         return OC_STACK_INVALID_PARAM;
     }
 
     uint8_t privData[OWNER_PSK_LENGTH_128] = {0,};
-    int dtlsRes = DeriveCryptoKeyFromPassword((const unsigned char *)pin, pinSize, owners->id,
+    OicSecKey_t privKey = {privData, OWNER_PSK_LENGTH_128};
+    OicSecCred_t* cred = NULL;
+    int dtlsRes = DeriveCryptoKeyFromPassword((const unsigned char *)pin, pinSize, rownerID->id,
                                               UUID_LENGTH, PBKDF_ITERATIONS,
                                               OWNER_PSK_LENGTH_128, privData);
-    VERIFY_SUCCESS(TAG, (dtlsRes == 0) , ERROR);
+    VERIFY_SUCCESS(TAG, (0 == dtlsRes) , ERROR);
 
-    uint32_t outLen = 0;
-    char base64Buff[B64ENCODE_OUT_SAFESIZE(OWNER_PSK_LENGTH_128) + 1] = {};
-    B64Result b64Ret = b64Encode(privData, OWNER_PSK_LENGTH_128, base64Buff,
-                                sizeof(base64Buff), &outLen);
-    VERIFY_SUCCESS(TAG, (B64_OK == b64Ret), ERROR);
-
-    OicSecCred_t* cred = GenerateCredential(tmpSubject, credType, NULL,
-                                            base64Buff, ownersLen, owners);
+    cred = GenerateCredential(tmpSubject, credType, NULL,
+                              &privKey, rownerID);
     if(NULL == cred)
     {
-        OC_LOG(ERROR, TAG, "GeneratePskWithPIN() : Failed to generate credential");
+        OIC_LOG(ERROR, TAG, "GeneratePskWithPIN() : Failed to generate credential");
         return OC_STACK_ERROR;
     }
 
@@ -1016,8 +1317,10 @@ OCStackResult AddTmpPskWithPIN(const OicUuid_t* tmpSubject, OicSecCredType_t cre
     ret = AddCredential(cred);
     if( OC_STACK_OK != ret)
     {
-        OC_LOG(ERROR, TAG, "GeneratePskWithPIN() : Failed to add credential");
+        RemoveCredential(tmpSubject);
+        OIC_LOG(ERROR, TAG, "GeneratePskWithPIN() : Failed to add credential");
     }
+    OIC_LOG(DEBUG, TAG, "AddTmpPskWithPIN OUT");
 
 exit:
     return ret;
@@ -1032,21 +1335,12 @@ exit:
 #define CERTIFICATE ("x5c")
 #define PRIVATE_KEY ("d")
 
-
-static void WriteCertPrefix(uint8_t *prefix, uint32_t certLen)
-{
-    for (size_t i = 0; i < CERT_LEN_PREFIX; ++i)
-    {
-        prefix[i] = (certLen >> (BYTE_SIZE * (CERT_LEN_PREFIX - 1 - i))) & 0xFF;
-    }
-}
-
-static uint32_t ParseCertPrefix(uint8_t *prefix)
+static uint32_t parseCertPrefix(uint8_t *prefix)
 {
     uint32_t res = 0;
-    if(NULL != prefix)
+    if (NULL != prefix)
     {
-        for(int i=0; i < CERT_LEN_PREFIX; ++i)
+        for (int i = 0; i < CERT_LEN_PREFIX; ++i)
         {
             res |= (((uint32_t) prefix[i]) << ((CERT_LEN_PREFIX - 1 -i) * BYTE_SIZE));
         }
@@ -1054,34 +1348,16 @@ static uint32_t ParseCertPrefix(uint8_t *prefix)
     return res;
 }
 
-static uint32_t appendCert2Chain(uint8_t *appendPoint, char *cert, uint32_t max_len)
+static OCStackResult GetCAPublicKeyData(CADtlsX509Creds_t *credInfo)
 {
-    uint32_t ret = 0;
-    VERIFY_NON_NULL(TAG, appendPoint, ERROR);
-    VERIFY_NON_NULL(TAG, cert, ERROR);
-
-    uint32_t certLen;
-    VERIFY_SUCCESS(TAG, B64_OK == b64Decode(cert, strlen(cert), appendPoint + CERT_LEN_PREFIX,
-                                            max_len - CERT_LEN_PREFIX, &certLen), ERROR);
-    WriteCertPrefix(appendPoint, certLen);
-
-    ret = certLen + CERT_LEN_PREFIX;
-exit:
-    return ret;
-}
-
-static OCStackResult GetCAPublicKeyData(CADtlsX509Creds_t *credInfo){
     OCStackResult ret = OC_STACK_ERROR;
     uint8_t *ccPtr = credInfo->certificateChain;
-    for(uint32_t i =0; i < credInfo->chainLen - 1; ++i)
+    for (uint8_t i = 0; i < credInfo->chainLen - 1; ++i)
     {
-        ccPtr += CERT_LEN_PREFIX + ParseCertPrefix(ccPtr);
+        ccPtr += CERT_LEN_PREFIX + parseCertPrefix(ccPtr);
     }
 
-    ByteArray cert = {
-        .data = ccPtr + CERT_LEN_PREFIX,
-        .len = ParseCertPrefix(ccPtr)
-         };
+    ByteArray cert = { .data = ccPtr + CERT_LEN_PREFIX, .len = parseCertPrefix(ccPtr) };
     CertificateX509 certStruct;
 
     VERIFY_SUCCESS(TAG, PKI_SUCCESS == DecodeCertificate(cert, &certStruct), ERROR);
@@ -1096,86 +1372,82 @@ static OCStackResult GetCAPublicKeyData(CADtlsX509Creds_t *credInfo){
     return ret;
 }
 
-static OCStackResult GetCertCredPublicData(CADtlsX509Creds_t *credInfo, OicSecCred_t *cred)
+int GetDtlsX509Credentials(CADtlsX509Creds_t *credInfo)
 {
-    OCStackResult ret = OC_STACK_ERROR;
+    int ret = 1;
     VERIFY_NON_NULL(TAG, credInfo, ERROR);
-    VERIFY_NON_NULL(TAG, cred, ERROR);
-    VERIFY_NON_NULL(TAG, cred->publicData.data, ERROR);
-    //VERIFY_SUCCESS(TAG, NULL == credInfo->certificateChain.data, ERROR);
-    cJSON *jsonRoot = cJSON_Parse(cred->publicData.data);
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
-
-    //Get certificate chain
-    cJSON *jsonObj = cJSON_GetObjectItem(jsonRoot, CERTIFICATE);//TODO define field names constants
-    VERIFY_SUCCESS(TAG, NULL != jsonObj && cJSON_Array == jsonObj->type, ERROR);
+    if (NULL == gCred)
+    {
+        VERIFY_SUCCESS(TAG, OC_STACK_OK == InitCredResource(), ERROR);
+    }
 
-    size_t certChainLen = cJSON_GetArraySize(jsonObj);
-    credInfo->chainLen = certChainLen;
-    VERIFY_SUCCESS(TAG, MAX_CHAIN_LEN >= certChainLen, ERROR);
+    OicSecCred_t *cred = NULL;
+    LL_SEARCH_SCALAR(gCred, cred, credType, SIGNED_ASYMMETRIC_KEY);
+    VERIFY_NON_NULL(TAG, cred, ERROR);
 
-    uint32_t len = 0;
-    for (size_t i = 0; i < certChainLen; ++i)
+    if (cred->publicData.len > MAX_CERT_MESSAGE_LEN || cred->privateData.len > PRIVATE_KEY_SIZE)
     {
-        cJSON *item = cJSON_GetArrayItem(jsonObj, i);
-        VERIFY_SUCCESS(TAG, cJSON_String == item->type, ERROR);
-        uint32_t appendedLen = appendCert2Chain(credInfo->certificateChain + len, item->valuestring,
-                                              MAX_CERT_MESSAGE_LEN - len);
-        VERIFY_SUCCESS(TAG, 0 != appendedLen, ERROR);
-        len += appendedLen;
+        goto exit;
     }
-    credInfo->certificateChainLen = len;
-    VERIFY_SUCCESS(TAG, OC_STACK_OK == GetCAPublicKeyData(credInfo), ERROR);
-    ret = OC_STACK_OK;
+    credInfo->chainLen = 2;
+    memcpy(credInfo->certificateChain, cred->publicData.data, cred->publicData.len);
+    memcpy(credInfo->devicePrivateKey, cred->privateData.data, cred->privateData.len);
+    credInfo->certificateChainLen = cred->publicData.len;
+    GetCAPublicKeyData(credInfo);
+    ret = 0;
+
 exit:
-    cJSON_Delete(jsonRoot);
+
     return ret;
 }
+#undef CERT_LEN_PREFIX
+#endif /* __WITH_X509__ */
 
-static OCStackResult GetCertCredPrivateData(CADtlsX509Creds_t *credInfo, OicSecCred_t *cred)
+OCStackResult SetCredRownerId(const OicUuid_t* newROwner)
 {
     OCStackResult ret = OC_STACK_ERROR;
-    VERIFY_NON_NULL(TAG, credInfo, ERROR);
-    VERIFY_NON_NULL(TAG, cred, ERROR);
-    VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
-    cJSON *jsonRoot = cJSON_Parse(cred->privateData.data);
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+    uint8_t *cborPayload = NULL;
+    size_t size = 0;
+    OicUuid_t prevId = {.id={0}};
 
-    cJSON *jsonObj = cJSON_GetObjectItem(jsonRoot, PRIVATE_KEY);//TODO define field names constants
-    VERIFY_SUCCESS(TAG, NULL != jsonObj && cJSON_String == jsonObj->type, ERROR);
+    if(NULL == newROwner)
+    {
+        ret = OC_STACK_INVALID_PARAM;
+    }
+    if(NULL == gCred)
+    {
+        ret = OC_STACK_NO_RESOURCE;
+    }
 
-    uint32_t read = 0u;
-    VERIFY_SUCCESS(TAG, B64_OK == b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring),
-                                            credInfo->devicePrivateKey, PRIVATE_KEY_SIZE, &read)
-                   && PRIVATE_KEY_SIZE == read, ERROR);
+    if(newROwner && gCred)
+    {
+        memcpy(prevId.id, gCred->rownerID.id, sizeof(prevId.id));
+        memcpy(gCred->rownerID.id, newROwner->id, sizeof(newROwner->id));
 
-    ret = OC_STACK_OK;
+        ret = CredToCBORPayload(gCred, &cborPayload, &size);
+        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+
+        ret = UpdateSecureResourceInPS(OIC_JSON_CRED_NAME, cborPayload, size);
+        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+
+        OICFree(cborPayload);
+    }
+
+    return ret;
 
 exit:
-    cJSON_Delete(jsonRoot);
+    OICFree(cborPayload);
+    memcpy(gCred->rownerID.id, prevId.id, sizeof(prevId.id));
     return ret;
 }
 
-int GetDtlsX509Credentials(CADtlsX509Creds_t *credInfo)
+OCStackResult GetCredRownerId(OicUuid_t *rowneruuid)
 {
-    int ret = 1;
-    VERIFY_NON_NULL(TAG, credInfo, ERROR);
-    if (NULL == gCred)
+    OCStackResult retVal = OC_STACK_ERROR;
+    if (gCred)
     {
-        VERIFY_SUCCESS(TAG, OC_STACK_OK == InitCredResource(), ERROR);
+        *rowneruuid = gCred->rownerID;
+        retVal = OC_STACK_OK;
     }
-
-    OicSecCred_t *cred = NULL;
-    LL_SEARCH_SCALAR(gCred, cred, credType, SIGNED_ASYMMETRIC_KEY);
-    VERIFY_NON_NULL(TAG, cred, ERROR);
-
-    VERIFY_SUCCESS(TAG, OC_STACK_OK == GetCertCredPrivateData(credInfo, cred), ERROR);
-    VERIFY_SUCCESS(TAG, OC_STACK_OK == GetCertCredPublicData(credInfo, cred), ERROR);
-
-    ret = 0;
-exit:
-
-    return ret;
+    return retVal;
 }
-#undef CERT_LEN_PREFIX
-#endif /* __WITH_X509__ */
index c226c9d..53f2ca2 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#include <stdlib.h>
-#include <string.h>
-#include "ocstack.h"
-#include "logger.h"
-#include "oic_malloc.h"
-#include "cJSON.h"
-#include "base64.h"
-#include "resourcemanager.h"
-#include "psinterface.h"
 #include "utlist.h"
+#include "payload_logging.h"
+#include "psinterface.h"
+#include "resourcemanager.h"
 #include "srmresourcestrings.h"
-#include "doxmresource.h"
 #include "srmutility.h"
+#include "doxmresource.h"
+#include "ocpayload.h"
+#include "oic_malloc.h"
 #ifdef __WITH_X509__
 #include "crlresource.h"
 #include "crl.h"
 
 #define SEPARATOR                   ":"
 #define SEPARATOR_LEN               (1)
-#define JSON_CRL_NAME               "\"CRL\""
-#define JSON_CRL_NAME_LEN           (5)
-#define OIC_JSON_CRL_NAME           "crl"
-#define OIC_JSON_CRL_ID             "CRLId"
-#define OIC_JSON_CRL_THIS_UPDATE    "ThisUpdate"
-#define OIC_JSON_CRL_DATA           "CRLData"
-#define CRL_DEFAULT_CRL_ID           1
+#define CBOR_CRL_NAME               "\"CRL\""
+#define CBOR_CRL_NAME_LEN           (5)
+#define OIC_CBOR_CRL_NAME           "crl"
+#define OIC_CBOR_CRL_ID             "CRLId"
+#define OIC_CBOR_CRL_THIS_UPDATE    "ThisUpdate"
+#define OIC_CBOR_CRL_DATA           "CRLData"
+#define CRL_DEFAULT_CRL_ID          (1)
 #define CRL_DEFAULT_THIS_UPDATE     "150101000000Z"
 #define CRL_DEFAULT_CRL_DATA        "-"
 
 static OCResourceHandle     gCrlHandle  = NULL;
 static OicSecCrl_t         *gCrl        = NULL;
 
+/** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
+ * The value of payload size is increased until reaching below max cbor size. */
+static const uint16_t CBOR_SIZE = 1024;
+
+// Max cbor size payload.
+static const uint16_t CBOR_MAX_SIZE = 4400;
+
+// PSTAT Map size - Number of mandatory items
+static const uint8_t CRL_MAP_SIZE = 3;
 
 void DeleteCrlBinData(OicSecCrl_t *crl)
 {
@@ -69,260 +74,263 @@ void DeleteCrlBinData(OicSecCrl_t *crl)
     }
 }
 
-char *BinToCrlJSON(const OicSecCrl_t *crl)
+OCStackResult CrlToCBORPayload(const OicSecCrl_t *crl, uint8_t **payload, size_t *size)
 {
-    if (NULL == crl)
+    if (NULL == crl || NULL == payload || NULL != *payload || NULL == size)
     {
-        return NULL;
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    size_t cborLen = *size;
+    if (0 == cborLen)
+    {
+        cborLen = CBOR_SIZE;
     }
 
-    char *base64Buff = NULL;
-    uint32_t outLen = 0;
-    uint32_t base64CRLLen = 0;
-    B64Result b64Ret = B64_OK;
-    char *jsonStr = NULL;
-    cJSON *jsonRoot = cJSON_CreateObject();
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
-    cJSON *jsonCrl = cJSON_CreateObject();
-    VERIFY_NON_NULL(TAG, jsonCrl, ERROR);
+    *payload = NULL;
+    *size = 0;
 
-    cJSON_AddItemToObject(jsonRoot, OIC_JSON_CRL_NAME, jsonCrl);
+    OCStackResult ret = OC_STACK_ERROR;
+
+    CborEncoder encoder;
+    CborEncoder crlMap;
+
+    CborError cborEncoderResult = CborNoError;
+
+    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
+    VERIFY_NON_NULL(TAG, outPayload, ERROR);
+    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
+
+    cborEncoderResult = cbor_encoder_create_map(&encoder, &crlMap, CRL_MAP_SIZE);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to create CRL Map");
 
     //CRLId -- Mandatory
-    cJSON_AddNumberToObject(jsonCrl, OIC_JSON_CRL_ID, (int)crl->CrlId);
+    cborEncoderResult = cbor_encode_text_string(&crlMap, OIC_CBOR_CRL_ID,
+        strlen(OIC_CBOR_CRL_ID));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add CRL ID");
+    cborEncoderResult = cbor_encode_int(&crlMap, crl->CrlId);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add CRL Id value");
 
     //ThisUpdate -- Mandatory
-    outLen = 0;
-    base64CRLLen = B64ENCODE_OUT_SAFESIZE(crl->ThisUpdate.len);
-    base64Buff = OICMalloc(base64CRLLen);
-    b64Ret = b64Encode(crl->ThisUpdate.data, crl->ThisUpdate.len, base64Buff,
-             base64CRLLen, &outLen);
-    VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
-    cJSON_AddStringToObject(jsonCrl, OIC_JSON_CRL_THIS_UPDATE, base64Buff);
-    OICFree(base64Buff);
+    cborEncoderResult = cbor_encode_text_string(&crlMap, OIC_CBOR_CRL_THIS_UPDATE,
+        strlen(OIC_CBOR_CRL_THIS_UPDATE));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add Crl update");
+    cborEncoderResult = cbor_encode_byte_string(&crlMap, crl->ThisUpdate.data,
+                                                crl->ThisUpdate.len);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add Crl Update value");
 
     //CRLData -- Mandatory
-    outLen = 0;
-    base64CRLLen = B64ENCODE_OUT_SAFESIZE(crl->CrlData.len);
-    base64Buff = OICMalloc(base64CRLLen);
-    b64Ret = b64Encode(crl->CrlData.data, crl->CrlData.len, base64Buff,
-             base64CRLLen, &outLen);
-    VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
-    cJSON_AddStringToObject(jsonCrl, OIC_JSON_CRL_DATA, base64Buff);
-
-    jsonStr = cJSON_PrintUnformatted(jsonRoot);
+    cborEncoderResult = cbor_encode_text_string(&crlMap, OIC_CBOR_CRL_DATA,
+        strlen(OIC_CBOR_CRL_DATA));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add Crl data name");
+    cborEncoderResult = cbor_encode_byte_string(&crlMap, crl->CrlData.data,
+                                                crl->CrlData.len);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add Crl data value");
+
+    cborEncoderResult = cbor_encoder_close_container(&encoder, &crlMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add close Crl map");
+
+    *size = encoder.ptr - outPayload;
+    *payload = outPayload;
+    ret = OC_STACK_OK;
 
 exit:
-    OICFree(base64Buff);
-    if (jsonRoot)
+    if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
     {
-        cJSON_Delete(jsonRoot);
+        // reallocate and try again!
+        OICFree(outPayload);
+        // Since the allocated initial memory failed, double the memory.
+        cborLen += encoder.ptr - encoder.end;
+        cborEncoderResult = CborNoError;
+        ret = CrlToCBORPayload(crl, payload, &cborLen);
     }
-    return jsonStr;
+
+    if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
+    {
+        OICFree(outPayload);
+        outPayload = NULL;
+        *payload = NULL;
+        *size = 0;
+        ret = OC_STACK_ERROR;
+    }
+
+    return ret;
 }
 
-OicSecCrl_t *JSONToCrlBin(const char * jsonStr)
+OCStackResult CBORPayloadToCrl(const uint8_t *cborPayload, const size_t size,
+                               OicSecCrl_t **secCrl)
 {
-    if (NULL == jsonStr)
+    if (NULL == cborPayload || NULL == secCrl || NULL != *secCrl || 0 == size)
     {
-        return NULL;
+        return OC_STACK_INVALID_PARAM;
     }
 
     OCStackResult ret = OC_STACK_ERROR;
-    OicSecCrl_t *crl =  NULL;
-    cJSON *jsonCrl = NULL;
-    cJSON *jsonObj = NULL;
+    *secCrl = NULL;
 
-    unsigned char *base64Buff = NULL;
-    uint32_t base64CRLLen = 0;
-    uint32_t outLen = 0;
-    B64Result b64Ret = B64_OK;
+    CborValue crlCbor = {.parser = NULL};
+    CborParser parser = {.end = NULL};
+    CborError cborFindResult = CborNoError;
 
-    cJSON *jsonRoot = cJSON_Parse(jsonStr);
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+    cbor_parser_init(cborPayload, size, 0, &parser, &crlCbor);
+    CborValue crlMap = { .parser = NULL};
+    OicSecCrl_t *crl = NULL;
+    size_t outLen = 0;
+    cborFindResult = cbor_value_enter_container(&crlCbor, &crlMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to enter Crl map");
 
-    jsonCrl = cJSON_GetObjectItem(jsonRoot, OIC_JSON_CRL_NAME);
-    VERIFY_NON_NULL(TAG, jsonCrl, ERROR);
     crl = (OicSecCrl_t *)OICCalloc(1, sizeof(OicSecCrl_t));
     VERIFY_NON_NULL(TAG, crl, ERROR);
 
-    //CRLId -- Mandatory
-    jsonObj = cJSON_GetObjectItem(jsonCrl, OIC_JSON_CRL_ID);
-    if(jsonObj)
-    {
-        VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
-        crl->CrlId = (uint16_t)jsonObj->valueint;
-    }
-    else // PUT/POST JSON may not have CRLId so set it to the gCRList->CRLId
+    cborFindResult = cbor_value_map_find_value(&crlCbor, OIC_CBOR_CRL_ID, &crlMap);
+    if (CborNoError == cborFindResult && cbor_value_is_integer(&crlMap))
     {
-        VERIFY_NON_NULL(TAG, gCrl, ERROR);
-        crl->CrlId = gCrl->CrlId;
+        cborFindResult = cbor_value_get_int(&crlMap, (int *) &crl->CrlId);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding CrlId.");
     }
 
-    //ThisUpdate -- Mandatory
-    jsonObj = cJSON_GetObjectItem(jsonCrl, OIC_JSON_CRL_THIS_UPDATE);
-    if(jsonObj)
+    cborFindResult = cbor_value_map_find_value(&crlCbor, OIC_CBOR_CRL_THIS_UPDATE, &crlMap);
+    if (CborNoError == cborFindResult && cbor_value_is_byte_string(&crlMap))
     {
-        VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
-        if(cJSON_String == jsonObj->type)
-        {
-            //Check for empty string, in case ThisUpdate field has not been set yet
-            if (jsonObj->valuestring[0])
-            {
-                base64CRLLen = B64ENCODE_OUT_SAFESIZE(strlen(jsonObj->valuestring));
-                base64Buff = OICMalloc(base64CRLLen);
-                b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
-                        base64CRLLen, &outLen);
-                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= base64CRLLen),
-                                ERROR);
-                crl->ThisUpdate.data = OICMalloc(outLen + 1);
-                memcpy(crl->ThisUpdate.data, base64Buff, outLen);
-                crl->ThisUpdate.len = outLen;
-                OICFree(base64Buff);
-                base64Buff = NULL;
-            }
-        }
+        cborFindResult = cbor_value_dup_byte_string(&crlMap,
+            &crl->ThisUpdate.data, &crl->ThisUpdate.len, NULL);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Byte Array.");
     }
-    else // PUT/POST JSON will not have ThisUpdate so set it to the gCRList->ThisUpdate
+    cborFindResult = cbor_value_map_find_value(&crlCbor, OIC_CBOR_CRL_DATA, &crlMap);
+    if (CborNoError == cborFindResult && cbor_value_is_byte_string(&crlMap))
     {
-        VERIFY_NON_NULL(TAG, gCrl, ERROR);
-        outLen = gCrl->ThisUpdate.len;
-        crl->ThisUpdate.data = OICMalloc(outLen + 1);
-        memcpy(crl->ThisUpdate.data, gCrl->ThisUpdate.data, outLen);
-        crl->ThisUpdate.len = outLen;
+        cborFindResult = cbor_value_dup_byte_string(&crlMap,
+                         &crl->CrlData.data, &crl->CrlData.len, NULL);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Byte Array.");
     }
 
-    //CRLData -- Mandatory
-    jsonObj = cJSON_GetObjectItem(jsonCrl, OIC_JSON_CRL_DATA);
-    if(jsonObj)
+    *secCrl = crl;
+    ret = OC_STACK_OK;
+exit:
+    if (CborNoError != cborFindResult)
     {
-        VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
-        if(cJSON_String == jsonObj->type)
+        // PUT/POST CBOR may not have mandatory values set default values.
+        if (gCrl)
         {
-            //Check for empty string, in case CRLData field has not been set yet
-            if (jsonObj->valuestring[0])
+            OIC_LOG (DEBUG, TAG, "Set default values");
+            crl->CrlId = gCrl->CrlId;
+            if (crl->ThisUpdate.data)
+            {
+                OICFree(crl->ThisUpdate.data);
+            }
+            outLen = gCrl->ThisUpdate.len;
+            crl->ThisUpdate.data = (uint8_t*) OICMalloc(outLen);
+            if (crl->ThisUpdate.data)
             {
-                outLen = 0;
-                base64CRLLen = B64ENCODE_OUT_SAFESIZE(strlen(jsonObj->valuestring));
-                base64Buff = OICMalloc(base64CRLLen);
-                b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
-                        base64CRLLen, &outLen);
-                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= base64CRLLen),
-                                ERROR);
-                crl->CrlData.data = OICMalloc(outLen + 1);
-                memcpy(crl->CrlData.data, base64Buff, outLen);
+                memcpy(crl->ThisUpdate.data, gCrl->ThisUpdate.data, outLen);
+                crl->ThisUpdate.len = outLen;
+            }
+            else
+            {
+                crl->ThisUpdate.len = 0;
+                OIC_LOG(ERROR, TAG, "Set default failed");
+            }
+            if (crl->CrlData.data)
+            {
+                OICFree(crl->CrlData.data);
+            }
+            outLen = gCrl->CrlData.len;
+            crl->CrlData.data = (uint8_t*) OICMalloc(outLen);
+            if (crl->CrlData.data && gCrl->CrlData.data)
+            {
+                memcpy(crl->CrlData.data, gCrl->CrlData.data, outLen);
                 crl->CrlData.len = outLen;
-                OICFree(base64Buff);
-                base64Buff = NULL;
             }
-        }
-    }
-    else // PUT/POST JSON will not have CRLData so set it to the gCRList->CRLData
-    {
-        VERIFY_NON_NULL(TAG, gCrl, ERROR);
-        outLen = gCrl->CrlData.len;
-        crl->CrlData.data = OICMalloc(outLen + 1);
-        memcpy(crl->CrlData.data, gCrl->CrlData.data, outLen);
-        crl->CrlData.len = outLen;
-    }
+            else
+            {
+                crl->CrlData.len = 0;
+                OIC_LOG (ERROR, TAG, "Set default failed");
+            }
 
-    ret = OC_STACK_OK;
-exit:
-    cJSON_Delete(jsonRoot);
-    OICFree(base64Buff);
-    base64Buff = NULL;
-    if (OC_STACK_OK != ret)
-    {
-        DeleteCrlBinData(crl);
-        crl = NULL;
+            *secCrl = crl;
+            ret = OC_STACK_OK;
+        }
+        else
+        {
+            OIC_LOG (ERROR, TAG, "CBORPayloadToCrl failed");
+            DeleteCrlBinData(crl);
+            crl = NULL;
+            ret = OC_STACK_ERROR;
+        }
     }
-    return crl;
+    return ret;
 }
 
 OCStackResult UpdateCRLResource(const OicSecCrl_t *crl)
 {
-    char *jsonStr = NULL;
-    OCStackResult res = OC_STACK_ERROR;
+    uint8_t *payload = NULL;
+    size_t size = 0;
 
-    jsonStr = BinToCrlJSON((OicSecCrl_t *) crl);
-    if (!jsonStr)
+    OCStackResult res = CrlToCBORPayload((OicSecCrl_t *) crl, &payload, &size);
+    if (OC_STACK_OK != res)
     {
-        return OC_STACK_ERROR;
+        return res;
     }
 
-    cJSON *jsonObj = cJSON_Parse(jsonStr);
-    OICFree(jsonStr);
-
-    if (jsonObj == NULL)
-    {
-        return OC_STACK_ERROR;
-    }
-
-    res = UpdateSVRDatabase(OIC_JSON_CRL_NAME, jsonObj);
-    cJSON_Delete(jsonObj);
-
-    return res;
+    return UpdateSecureResourceInPS(OIC_CBOR_CRL_NAME, payload, size);
 }
 
 static OCEntityHandlerResult HandleCRLPostRequest(const OCEntityHandlerRequest *ehRequest)
 {
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
+    OicSecCrl_t *crl = NULL;
+    uint8_t *payload = ((OCSecurityPayload *)ehRequest->payload)->securityData;
+    size_t size = ((OCSecurityPayload *) ehRequest->payload)->payloadSize;
 
-    char *jsonCRL = (char *)(((OCSecurityPayload *)ehRequest->payload)->securityData);
-
-    if (jsonCRL)
+    if (payload)
     {
-        OC_LOG(INFO, TAG, "UpdateSVRDB...");
-        OC_LOG_V(INFO, TAG, "crl: \"%s\"", jsonCRL);
-
-        cJSON *jsonObj = cJSON_Parse(jsonCRL);
-        OicSecCrl_t *crl = NULL;
-        crl = JSONToCrlBin(jsonCRL);
-        if (!crl)
-        {
-            OC_LOG(ERROR, TAG, "Error JSONToCrlBin");
-        }
+        OIC_LOG(INFO, TAG, "UpdateSVRDB...");
+        CBORPayloadToCrl(payload, size, &crl);
+        VERIFY_NON_NULL(TAG, crl, ERROR);
 
         gCrl->CrlId = crl->CrlId;
 
         OICFree(gCrl->ThisUpdate.data);
         gCrl->ThisUpdate.data = NULL;
         gCrl->ThisUpdate.data = OICMalloc(crl->ThisUpdate.len);
+        VERIFY_NON_NULL(TAG, gCrl->ThisUpdate.data, ERROR);
         memcpy(gCrl->ThisUpdate.data, crl->ThisUpdate.data, crl->ThisUpdate.len);
         gCrl->ThisUpdate.len = crl->ThisUpdate.len;
 
         OICFree(gCrl->CrlData.data);
-        gCrl->CrlData.data = NULL;
         gCrl->CrlData.data = OICMalloc(crl->CrlData.len);
+        VERIFY_NON_NULL(TAG, gCrl->CrlData.data, ERROR);
         memcpy(gCrl->CrlData.data, crl->CrlData.data, crl->CrlData.len);
         gCrl->CrlData.len = crl->CrlData.len;
 
-        if (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_CRL_NAME, jsonObj))
+        if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_CBOR_CRL_NAME, payload, size))
         {
-            OC_LOG(INFO, TAG, "UpdateSVRDB == OK");
             ehRet = OC_EH_RESOURCE_CREATED;
         }
 
         DeleteCrlBinData(crl);
-        cJSON_Delete(jsonObj);
-
     }
 
+exit:
     // Send payload to request originator
-    SendSRMResponse(ehRequest, ehRet, NULL);
+    if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL, 0))
+    {
+        ehRet = OC_EH_ERROR;
+        OIC_LOG(ERROR, TAG, "SendSRMResponse failed in HandleCRLPostRequest");
+    }
 
-    OC_LOG_V(INFO, TAG, "%s RetVal %d", __func__, ehRet);
+    OIC_LOG_V(INFO, TAG, "%s RetVal %d", __func__, ehRet);
     return ehRet;
 }
 
 
-/*
+/**
  * This internal method is the entity handler for CRL resource and
  * will handle REST request (GET/PUT/POST/DEL) for them.
  */
-OCEntityHandlerResult CRLEntityHandler(OCEntityHandlerFlag flag,
-                                       OCEntityHandlerRequest *ehRequest,
-                                       void *callbackParameter)
+static OCEntityHandlerResult CRLEntityHandler(OCEntityHandlerFlag flag,
+                                              OCEntityHandlerRequest *ehRequest,
+                                              void *callbackParameter)
 {
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
     (void)callbackParameter;
@@ -332,16 +340,16 @@ OCEntityHandlerResult CRLEntityHandler(OCEntityHandlerFlag flag,
         return ehRet;
     }
 
-    OC_LOG(INFO, TAG, "Handle CRL resource");
+    OIC_LOG(INFO, TAG, "Handle CRL resource");
 
     if (flag & OC_REQUEST_FLAG)
     {
         // TODO :  Handle PUT and DEL methods
-        OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
+        OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
         switch (ehRequest->method)
         {
             case OC_REST_GET:
-                OC_LOG (INFO, TAG, "Not implemented request method.");
+                OIC_LOG (INFO, TAG, "Not implemented request method.");
                 //ehRet = HandleCRLGetRequest(ehRequest);
                 break;
 
@@ -351,53 +359,68 @@ OCEntityHandlerResult CRLEntityHandler(OCEntityHandlerFlag flag,
 
             default:
                 ehRet = OC_EH_ERROR;
-                SendSRMResponse(ehRequest, ehRet, NULL);
+                SendSRMResponse(ehRequest, ehRet, NULL, 0);
         }
     }
 
     return ehRet;
 }
 
-/*
+/**
  * This internal method is used to create '/oic/sec/crl' resource.
  */
-OCStackResult CreateCRLResource()
+static OCStackResult CreateCRLResource()
 {
-    OCStackResult ret;
-    ret = OCCreateResource(&gCrlHandle,
-                           OIC_RSRC_TYPE_SEC_CRL,
-                           OIC_MI_DEF,
-                           OIC_RSRC_CRL_URI,
-                           CRLEntityHandler,
-                           NULL,
-                           OC_OBSERVABLE);
+    OCStackResult ret = OCCreateResource(&gCrlHandle,
+                                         OIC_RSRC_TYPE_SEC_CRL,
+                                         OIC_MI_DEF,
+                                         OIC_RSRC_CRL_URI,
+                                         CRLEntityHandler,
+                                         NULL,
+                                         OC_OBSERVABLE);
 
     if (OC_STACK_OK != ret)
     {
-        OC_LOG(FATAL, TAG, "Unable to instantiate CRL resource");
+        OIC_LOG(FATAL, TAG, "Unable to instantiate CRL resource");
         DeInitCRLResource();
     }
     return ret;
 }
 
 /**
- * Get the default value
- * @retval  NULL for now. Update it when we finalize the default info.
+ * Get the default value.
+ * @return defaultCrl for now.
  */
 static OicSecCrl_t *GetCrlDefault()
 {
-    OicSecCrl_t *defaultCrl = NULL;
-    defaultCrl = (OicSecCrl_t *)OICCalloc(1, sizeof(OicSecCrl_t));
-
+    OicSecCrl_t *defaultCrl = (OicSecCrl_t *)OICCalloc(1, sizeof(OicSecCrl_t));
+    if (NULL == defaultCrl)
+    {
+        return NULL;
+    }
     defaultCrl->CrlId = CRL_DEFAULT_CRL_ID;
 
     defaultCrl->CrlData.len = strlen(CRL_DEFAULT_CRL_DATA);
-    defaultCrl->CrlData.data = OICMalloc(defaultCrl->CrlData.len);
-    memcpy(defaultCrl->CrlData.data, CRL_DEFAULT_CRL_DATA, defaultCrl->CrlData.len);
+    defaultCrl->CrlData.data = (uint8_t*) OICMalloc(defaultCrl->CrlData.len);
+    if (defaultCrl->CrlData.data)
+    {
+        memcpy(defaultCrl->CrlData.data, CRL_DEFAULT_CRL_DATA, defaultCrl->CrlData.len);
+    }
+    else
+    {
+        defaultCrl->CrlData.len = 0;
+    }
 
     defaultCrl->ThisUpdate.len = strlen(CRL_DEFAULT_THIS_UPDATE);
-    defaultCrl->ThisUpdate.data = OICMalloc(defaultCrl->ThisUpdate.len);
-    memcpy(defaultCrl->ThisUpdate.data, CRL_DEFAULT_THIS_UPDATE, defaultCrl->ThisUpdate.len);
+    defaultCrl->ThisUpdate.data = (uint8_t*) OICMalloc(defaultCrl->ThisUpdate.len);
+    if (defaultCrl->ThisUpdate.data)
+    {
+        memcpy(defaultCrl->ThisUpdate.data, CRL_DEFAULT_THIS_UPDATE, defaultCrl->ThisUpdate.len);
+    }
+    else
+    {
+        defaultCrl->ThisUpdate.len = 0;
+    }
 
     return defaultCrl;
 }
@@ -412,28 +435,33 @@ static OicSecCrl_t *GetCrlDefault()
 OCStackResult InitCRLResource()
 {
     OCStackResult ret = OC_STACK_ERROR;
-    char* jsonSVRDatabase;
-
-    //Read CRL resource from PS
-    jsonSVRDatabase = GetSVRDatabase();
-
-    if (jsonSVRDatabase)
+    // Read Crl resource from PS
+    uint8_t *data = NULL;
+    size_t size = 0;
+    ret = GetSecureVirtualDatabaseFromPS(OIC_CBOR_CRL_NAME, &data, &size);
+    // If database read failed
+    if (OC_STACK_OK != ret)
     {
-        //Convert JSON CRL into binary format
-        gCrl = JSONToCrlBin(jsonSVRDatabase);
+        OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
     }
+    if (data)
+    {
+        // Read ACL resource from PS
+        ret = CBORPayloadToCrl(data, size, &gCrl);
+    }
+
     /*
      * If SVR database in persistent storage got corrupted or
      * is not available for some reason, a default CrlResource is created
      * which allows user to initiate CrlResource provisioning again.
      */
-    if (!jsonSVRDatabase || !gCrl)
+    if ((OC_STACK_OK != ret) || !data || !gCrl)
     {
         gCrl = GetCrlDefault();
     }
 
     ret = CreateCRLResource();
-    OICFree(jsonSVRDatabase);
+    OICFree(data);
     return ret;
 }
 
@@ -453,58 +481,39 @@ OicSecCrl_t *GetCRLResource()
     OicSecCrl_t *crl =  NULL;
 
     //Read CRL resource from PS
-    char* jsonSVRDatabase = GetSVRDatabase();
-
-    if (jsonSVRDatabase)
+    uint8_t *data = NULL;
+    size_t size = 0;
+    OCStackResult ret = GetSecureVirtualDatabaseFromPS(OIC_CBOR_CRL_NAME, &data, &size);
+    if (data)
     {
-        //Convert JSON CRL into binary format
-        crl = JSONToCrlBin(jsonSVRDatabase);
+        //Convert CBOR CRL into binary format
+        ret = CBORPayloadToCrl(data, size, &crl);
     }
     /*
      * If SVR database in persistent storage got corrupted or
      * is not available for some reason, a default CrlResource is created
      * which allows user to initiate CrlResource provisioning again.
      */
-    if (!jsonSVRDatabase || !crl)
+    if ((OC_STACK_OK != ret) || !data || !crl)
     {
         crl = GetCrlDefault();
     }
-    OICFree(jsonSVRDatabase);
+    OICFree(data);
 
     return crl;
 }
 
-char *GetBase64CRL()
+uint8_t *GetCrl()
 {
-    cJSON *jsonCrl = NULL;
-    cJSON *jsonObj = NULL;
-    char *jsonSVRDatabase = GetSVRDatabase();
-    char* ret = NULL;
-
-    cJSON *jsonRoot = cJSON_Parse(jsonSVRDatabase);
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
-
-    jsonCrl = cJSON_GetObjectItem(jsonRoot, OIC_JSON_CRL_NAME);
-    VERIFY_NON_NULL(TAG, jsonCrl, ERROR);
-
-    //CRLData -- Mandatory
-    jsonObj = cJSON_GetObjectItem(jsonCrl, OIC_JSON_CRL_DATA);
-    if(jsonObj)
+    uint8_t *data = NULL;
+    size_t size = 0;
+    OicSecCrl_t *crl = NULL;
+    if (OC_STACK_OK == GetSecureVirtualDatabaseFromPS(OIC_CBOR_CRL_NAME, &data, &size) && data &&
+        OC_STACK_OK == CBORPayloadToCrl(data, size, &crl))
     {
-        VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
-        if(cJSON_String == jsonObj->type)
-        {
-            //Check for empty string, in case CRLData field has not been set yet
-            if (jsonObj->valuestring[0])
-            {
-                ret = jsonObj->valuestring;
-            }
-        }
+        return crl->CrlData.data;
     }
-exit:
-    OICFree(jsonSVRDatabase);
-    cJSON_Delete(jsonRoot);
-    return ret;
+    return NULL;
 }
 
 void  GetDerCrl(ByteArray crlArray)
diff --git a/resource/csdk/security/src/directpairing.c b/resource/csdk/security/src/directpairing.c
new file mode 100644 (file)
index 0000000..5606598
--- /dev/null
@@ -0,0 +1,1024 @@
+/* *****************************************************************\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
+#ifndef _POSIX_C_SOURCE\r
+#define _POSIX_C_SOURCE 200112L\r
+#endif\r
+#ifndef WITH_ARDUINO\r
+#include <unistd.h>\r
+#include <time.h>\r
+#include <sys/time.h>\r
+#endif\r
+#include <string.h>\r
+\r
+#include "ocstack.h"\r
+#include "oic_malloc.h"\r
+#include "oic_string.h"\r
+#include "logger.h"\r
+#include "cJSON.h"\r
+#include "utlist.h"\r
+#include "ocpayload.h"\r
+#include "payload_logging.h"\r
+#include "cainterface.h"\r
+\r
+#include "directpairing.h"\r
+#include "srmresourcestrings.h" //@note: SRM's internal header\r
+#include "doxmresource.h"       //@note: SRM's internal header\r
+#include "pconfresource.h"       //@note: SRM's internal header\r
+#include "dpairingresource.h"       //@note: SRM's internal header\r
+#include "credresource.h"\r
+\r
+#include "pmtypes.h"\r
+#include "pmutility.h"\r
+\r
+#include "srmutility.h"\r
+\r
+#ifdef __WITH_DTLS__\r
+#include "global.h"\r
+#endif\r
+\r
+\r
+#define TAG ("DP")\r
+static const uint16_t CBOR_SIZE = 1024;\r
+\r
+/**\r
+ * Structure to carry direct-pairing API data to callback.\r
+ */\r
+typedef struct DPairData\r
+{\r
+    OCDirectPairingDev_t        *peer;                         /**< Pointer to pairing target info.**/\r
+    char                                  pin[DP_PIN_LENGTH];  /**< PIN **/\r
+    OCDirectPairingResultCB    resultCallback;           /**< Pointer to result callback.**/\r
+} DPairData_t;\r
+\r
+static OCDirectPairingDev_t *g_dp_paired = NULL;\r
+static OCDirectPairingDev_t *g_dp_discover = NULL;\r
+static DPairData_t *g_dp_proceed_ctx = NULL;\r
+\r
+\r
+/**\r
+ * Function to search node in linked list that matches given IP and port.\r
+ *\r
+ * @param[in] pList         List of OCProvisionDev_t.\r
+ * @param[in] addr          address of target device.\r
+ * @param[in] port          port of remote server.\r
+ *\r
+ * @return pointer of OCProvisionDev_t if exist, otherwise NULL\r
+ */\r
+OCDirectPairingDev_t* getDev(OCDirectPairingDev_t **ppList, const char* addr, const uint16_t port)\r
+{\r
+    if(NULL == addr)\r
+    {\r
+        OIC_LOG_V(ERROR, TAG, "Invalid Input parameters in [%s]\n", __FUNCTION__);\r
+        return NULL;\r
+    }\r
+\r
+    OCDirectPairingDev_t *ptr = NULL;\r
+    LL_FOREACH(*ppList, ptr)\r
+    {\r
+        if( strcmp(ptr->endpoint.addr, addr) == 0 && port == ptr->endpoint.port)\r
+        {\r
+            return ptr;\r
+        }\r
+    }\r
+\r
+    return NULL;\r
+}\r
+\r
+\r
+\r
+/**\r
+ * Add device information to list.\r
+ *\r
+ * @param[in] pList         List of OCProvisionDev_t.\r
+ * @param[in] addr          address of target device.\r
+ * @param[in] port          port of remote server.\r
+ * @param[in] adapter       adapter type of endpoint.\r
+ * @param[in] doxm          pointer to doxm instance.\r
+ * @param[in] connType  connectivity type of endpoint\r
+ *\r
+ * @return OC_STACK_OK for success and errorcode otherwise.\r
+ */\r
+OCStackResult addDev(OCDirectPairingDev_t **ppList, OCDevAddr *endpoint,\r
+                                      OCConnectivityType conn, OicSecPconf_t *pconf)\r
+{\r
+    if(NULL == endpoint || NULL == pconf)\r
+    {\r
+        OIC_LOG_V(ERROR, TAG, "Invalid Input parameters in [%s]\n", __FUNCTION__);\r
+        return OC_STACK_INVALID_PARAM;\r
+    }\r
+\r
+    OCDirectPairingDev_t *ptr = getDev(ppList, endpoint->addr, endpoint->port);\r
+    if(!ptr)\r
+    {\r
+        ptr = (OCDirectPairingDev_t *)OICCalloc(1, sizeof (OCDirectPairingDev_t));\r
+        if (NULL == ptr)\r
+        {\r
+            OIC_LOG(ERROR, TAG, "Error while allocating memory for linkedlist node !!");\r
+            return OC_STACK_NO_MEMORY;\r
+        }\r
+\r
+        memcpy(&ptr->endpoint, endpoint, sizeof(OCDevAddr));\r
+        ptr->connType = conn;\r
+        ptr->securePort = DEFAULT_SECURE_PORT;\r
+        ptr->edp = pconf->edp;\r
+        ptr->prm = pconf->prm;\r
+        pconf->prm = NULL;  // to prevent free\r
+        ptr->prmLen = pconf->prmLen;\r
+        memcpy(&ptr->deviceID, &pconf->deviceID, sizeof(OicUuid_t));\r
+        memcpy(&ptr->rowner, &pconf->rownerID, sizeof(OicUuid_t));\r
+        ptr->next = NULL;\r
+\r
+        LL_PREPEND(*ppList, ptr);\r
+        OIC_LOG(INFO, TAG, "device added !");\r
+    }\r
+\r
+    return OC_STACK_OK;\r
+}\r
+\r
+\r
+/**\r
+ * Add device information to list.\r
+ *\r
+ * @param[in] ppList         List of OCProvisionDev_t.\r
+ * @param[in] pDev          target device.\r
+ *\r
+ * @return OC_STACK_OK for success and errorcode otherwise.\r
+ */\r
+OCStackResult addDev2(OCDirectPairingDev_t **ppList, OCDirectPairingDev_t *pDev)\r
+{\r
+    if(NULL == pDev)\r
+    {\r
+        OIC_LOG_V(ERROR, TAG, "Invalid Input parameters in [%s]\n", __FUNCTION__);\r
+        return OC_STACK_INVALID_PARAM;\r
+    }\r
+\r
+    OCDirectPairingDev_t *ptr = getDev(ppList, pDev->endpoint.addr, pDev->endpoint.port);\r
+    if(!ptr)\r
+    {\r
+        ptr = (OCDirectPairingDev_t *)OICCalloc(1, sizeof (OCDirectPairingDev_t));\r
+        if (NULL == ptr)\r
+        {\r
+            OIC_LOG(ERROR, TAG, "Error while allocating memory for linkedlist node !!");\r
+            return OC_STACK_NO_MEMORY;\r
+        }\r
+\r
+        memcpy(&ptr->endpoint, &pDev->endpoint, sizeof(OCDevAddr));\r
+        ptr->connType = pDev->connType;\r
+        ptr->securePort = pDev->securePort;\r
+        ptr->edp = pDev->edp;\r
+        ptr->prmLen = pDev->prmLen;\r
+        ptr->prm = (OicSecPrm_t*)OICCalloc(ptr->prmLen, sizeof (OicSecPrm_t));\r
+        if (NULL == ptr->prm)\r
+        {\r
+            OIC_LOG(ERROR, TAG, "Error while allocating memory for prm !!");\r
+            return OC_STACK_NO_MEMORY;\r
+        }\r
+        memcpy(ptr->prm, pDev->prm, sizeof(OicSecPrm_t)*ptr->prmLen);\r
+        memcpy(&ptr->deviceID, &pDev->deviceID, sizeof(OicUuid_t));\r
+        memcpy(&ptr->rowner, &pDev->rowner, sizeof(OicUuid_t));\r
+        ptr->next = NULL;\r
+\r
+        LL_PREPEND(*ppList, ptr);\r
+        OIC_LOG(INFO, TAG, "device added !");\r
+    }\r
+\r
+    return OC_STACK_OK;\r
+}\r
+\r
+\r
+\r
+/**\r
+ * This function deletes list of provision target devices\r
+ *\r
+ * @param[in] pDevicesList         List of OCProvisionDev_t.\r
+ */\r
+void delList(OCDirectPairingDev_t *pList)\r
+{\r
+    if(pList)\r
+    {\r
+        OCDirectPairingDev_t *del = NULL, *tmp = NULL;\r
+        LL_FOREACH_SAFE(pList, del, tmp)\r
+        {\r
+            LL_DELETE(pList, del);\r
+            if (del && del->prm)\r
+            {\r
+                OICFree(del->prm);\r
+            }\r
+        }\r
+    }\r
+}\r
+\r
+bool DPGenerateQuery(bool isSecure,\r
+                     const char* address, const uint16_t port,\r
+                     const OCConnectivityType connType,\r
+                     char* buffer, size_t bufferSize, const char* uri)\r
+{\r
+    if(!address || !buffer || !uri)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "DPGenerateQuery : Invalid parameters.");\r
+        return false;\r
+    }\r
+\r
+    static char QPREFIX_COAP[] =  "coap://";\r
+    static char QPREFIX_COAPS[] = "coaps://";\r
+\r
+    int snRet = 0;\r
+    char* prefix = (isSecure == true) ? QPREFIX_COAPS : QPREFIX_COAP;\r
+\r
+    switch(connType & CT_MASK_ADAPTER)\r
+    {\r
+        case CT_ADAPTER_IP:\r
+            switch(connType & CT_MASK_FLAGS & ~CT_FLAG_SECURE)\r
+            {\r
+                case CT_IP_USE_V4:\r
+                        snRet = snprintf(buffer, bufferSize, "%s%s:%d%s",\r
+                                         prefix, address, port, uri);\r
+                    break;\r
+                case CT_IP_USE_V6:\r
+                        snRet = snprintf(buffer, bufferSize, "%s[%s]:%d%s",\r
+                                         prefix, address, port, uri);\r
+                    break;\r
+                default:\r
+                    OIC_LOG(ERROR, TAG, "Unknown address format.");\r
+                    return false;\r
+            }\r
+            // snprintf return value check\r
+            if (snRet < 0)\r
+            {\r
+                OIC_LOG_V(ERROR, TAG, "DPGenerateQuery : Error (snprintf) %d\n", snRet);\r
+                return false;\r
+            }\r
+            else if ((size_t)snRet >= bufferSize)\r
+            {\r
+                OIC_LOG_V(ERROR, TAG, "DPGenerateQuery : Truncated (snprintf) %d\n", snRet);\r
+                return false;\r
+            }\r
+\r
+            break;\r
+#ifndef WITH_ARDUINO\r
+        // TODO: We need to verify tinyDTLS in below cases\r
+        case CT_ADAPTER_GATT_BTLE:\r
+        case CT_ADAPTER_RFCOMM_BTEDR:\r
+            OIC_LOG(ERROR, TAG, "Not supported connectivity adapter.");\r
+            return false;\r
+            break;\r
+#endif\r
+        default:\r
+            OIC_LOG(ERROR, TAG, "Unknown connectivity adapter.");\r
+            return false;\r
+    }\r
+\r
+    return true;\r
+}\r
+\r
+const OCDirectPairingDev_t* DPGetDiscoveredDevices()\r
+{\r
+    return g_dp_discover;\r
+}\r
+\r
+const OCDirectPairingDev_t* DPGetPairedDevices()\r
+{\r
+    return g_dp_paired;\r
+}\r
+\r
+void DPDeleteLists()\r
+{\r
+    delList(g_dp_discover);\r
+    delList(g_dp_paired);\r
+}\r
+\r
+/**\r
+ * Callback handler of FinalizeDirectPairing.\r
+ *\r
+ * @param[in] ctx             ctx value passed to callback from calling function.\r
+ * @param[in] UNUSED          handle to an invocation\r
+ * @param[in] clientResponse  Response from queries to remote servers.\r
+ * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction\r
+ *          and  OC_STACK_KEEP_TRANSACTION to keep it.\r
+ */\r
+static OCStackApplicationResult DirectPairingFinalizeHandler(void *ctx, OCDoHandle UNUSED,\r
+                                                  OCClientResponse *clientResponse)\r
+{\r
+    OIC_LOG_V(INFO, TAG, "IN DirectPairingFinalizeHandler()");\r
+    (void)UNUSED;\r
+    if(NULL == ctx)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Context is Null");\r
+        return OC_STACK_DELETE_TRANSACTION;\r
+    }\r
+\r
+    OCStackResult res;\r
+    DPairData_t *dpairData = (DPairData_t*)ctx;\r
+    OCDirectPairingDev_t *peer = dpairData->peer;\r
+    OCDirectPairingResultCB resultCallback = dpairData->resultCallback;\r
+\r
+    if (clientResponse)\r
+    {\r
+        if(OC_STACK_OK == clientResponse->result)\r
+        {\r
+            // result\r
+            OIC_LOG(INFO, TAG, "DirectPairingFinalizeHandler : success PUT"\r
+                    " request to /oic/sec/dpairing");\r
+\r
+            CAEndpoint_t endpoint;\r
+            memset(&endpoint, 0x00, sizeof(CAEndpoint_t));\r
+            OICStrcpy(endpoint.addr, MAX_ADDR_STR_SIZE_CA, peer->endpoint.addr);\r
+            endpoint.addr[MAX_ADDR_STR_SIZE_CA - 1] = '\0';\r
+            endpoint.port = peer->securePort;\r
+\r
+            OicUuid_t ptDeviceID = {.id={0}};\r
+            if (OC_STACK_OK != GetDoxmDeviceID(&ptDeviceID))\r
+            {\r
+                OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");\r
+                resultCallback(peer, OC_STACK_ERROR);\r
+                return OC_STACK_DELETE_TRANSACTION;\r
+            }\r
+\r
+#ifdef __WITH_DTLS__\r
+            res = SavePairingPSK((OCDevAddr*)&endpoint, &peer->deviceID, &ptDeviceID, false);\r
+            if(OC_STACK_OK != res)\r
+            {\r
+                OIC_LOG(ERROR, TAG, "Failed to PairingPSK generation");\r
+                resultCallback(peer, res);\r
+                return OC_STACK_DELETE_TRANSACTION;\r
+            }\r
+\r
+            //  close temporary sesion\r
+            CAResult_t caResult = CACloseDtlsSession((const CAEndpoint_t*)&endpoint);\r
+            if(CA_STATUS_OK != caResult)\r
+            {\r
+                OIC_LOG(INFO, TAG, "Fail to close temporary dtls session");\r
+            }\r
+\r
+            caResult = CASelectCipherSuite(TLS_NULL_WITH_NULL_NULL);\r
+            if(CA_STATUS_OK != caResult)\r
+            {\r
+                OIC_LOG(ERROR, TAG, "Failed to select TLS_NULL_WITH_NULL_NULL");\r
+            }\r
+#endif // __WITH_DTLS__\r
+\r
+            OIC_LOG(INFO, TAG, "Direct-Papring was successfully completed.");\r
+\r
+            // update paired list\r
+            OCDirectPairingDev_t *dev = getDev(&g_dp_discover, peer->endpoint.addr,\r
+                    peer->endpoint.port);\r
+            res = addDev2(&g_dp_paired, dev);\r
+            if (OC_STACK_OK != res)\r
+            {\r
+                OIC_LOG(ERROR, TAG, "Error while adding a device to paired list.");\r
+            }\r
+\r
+            resultCallback(peer, OC_STACK_OK);\r
+\r
+            return OC_STACK_DELETE_TRANSACTION;\r
+        }\r
+        else\r
+        {\r
+            OIC_LOG(INFO, TAG, "Direct-Papring received error response.");\r
+        }\r
+    }\r
+    else\r
+    {\r
+        OIC_LOG(ERROR, TAG, "DirectPairingFinalizeHandler received Null clientResponse");\r
+    }\r
+\r
+    resultCallback(peer, OC_STACK_ERROR);\r
+    OICFree(dpairData);\r
+    return OC_STACK_DELETE_TRANSACTION;\r
+}\r
+\r
+/**\r
+ * Finalize direct-pairing .\r
+ *\r
+ * @param[in] peer  target device to establish direct-pairing.\r
+ * @param[in] resultCallback  result event callback.\r
+ *\r
+ * @return OC_STACK_OK on success otherwise error.\r
+ */\r
+OCStackResult FinalizeDirectPairing(OCDirectPairingDev_t* peer,\r
+                                                     OCDirectPairingResultCB resultCallback)\r
+{\r
+    if(NULL == peer)\r
+    {\r
+        return OC_STACK_INVALID_PARAM;\r
+    }\r
+\r
+    OicUuid_t deviceID =   {.id={0}};\r
+    if (OC_STACK_OK != GetDoxmDeviceID(&deviceID))\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Error while retrieving device ID");\r
+        return OC_STACK_ERROR;\r
+    }\r
+\r
+    OicSecDpairing_t dpair;\r
+    memset(&dpair, 0, sizeof(OicSecDpairing_t));\r
+    dpair.spm = (OicSecPrm_t)PRM_NOT_ALLOWED;\r
+    memcpy(&dpair.pdeviceID, &deviceID, sizeof(OicUuid_t));\r
+\r
+    OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));\r
+    if(!secPayload)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Failed to memory allocation");\r
+        return OC_STACK_NO_MEMORY;\r
+    }\r
+    secPayload->base.type = PAYLOAD_TYPE_SECURITY;\r
+\r
+    OCStackResult ret = DpairingToCBORPayload(&dpair, &(secPayload->securityData),\r
+            &(secPayload->payloadSize));\r
+\r
+    if(OC_STACK_OK != ret)\r
+    {\r
+        OICFree(secPayload);\r
+        OIC_LOG(ERROR, TAG, "Failed to DpairingToCBORPayload");\r
+        return OC_STACK_NO_MEMORY;\r
+    }\r
+    OIC_LOG(INFO, TAG, "DPARING CBOR data:");\r
+    OIC_LOG_BUFFER(INFO, TAG, secPayload->securityData, secPayload->payloadSize);\r
+\r
+    char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};\r
+    if(!DPGenerateQuery(true,\r
+                        peer->endpoint.addr,\r
+                        peer->securePort,\r
+                        peer->connType,\r
+                        query, sizeof(query), OIC_RSRC_DPAIRING_URI))\r
+    {\r
+        OIC_LOG(ERROR, TAG, "DPDirectPairing : Failed to generate query");\r
+        return OC_STACK_ERROR;\r
+    }\r
+    OIC_LOG_V(DEBUG, TAG, "Query=%s", query);\r
+\r
+    DPairData_t *dpairData = (DPairData_t *) OICCalloc(1, sizeof(DPairData_t));\r
+    if (dpairData == NULL)\r
+    {\r
+        OICFree(secPayload->securityData);\r
+        OICFree(secPayload);\r
+        OIC_LOG(ERROR, TAG, "Unable to allocate memory");\r
+        return OC_STACK_NO_MEMORY;\r
+    }\r
+    dpairData->peer = peer;\r
+    dpairData->resultCallback = resultCallback;\r
+\r
+    OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};\r
+    cbData.cb = DirectPairingFinalizeHandler;\r
+    cbData.context = (void*)dpairData;\r
+    cbData.cd = NULL;\r
+\r
+    OCMethod method = OC_REST_PUT;\r
+    OCDoHandle handle = NULL;\r
+    OIC_LOG(DEBUG, TAG, "Sending DPAIRNG setting to resource server");\r
+    ret = OCDoResource(&handle, method, query,\r
+            &peer->endpoint, (OCPayload*)secPayload,\r
+            peer->connType, OC_LOW_QOS, &cbData, NULL, 0);\r
+    if(OC_STACK_OK != ret)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "error in OCDoResource");\r
+        return OC_STACK_ERROR;\r
+    }\r
+\r
+    return OC_STACK_OK;\r
+ }\r
+\r
+/**\r
+ * Function to handle the handshake result in Direct-Pairing.\r
+ * This function will be invoked after DTLS handshake\r
+ * @param   endPoint  [IN] The remote endpoint.\r
+ * @param   errorInfo [IN] Error information from the endpoint.\r
+ * @return  NONE\r
+ */\r
+void DirectPairingDTLSHandshakeCB(const CAEndpoint_t *endpoint, const CAErrorInfo_t *info)\r
+{\r
+    OIC_LOG_V(INFO, TAG, "IN DirectPairingDTLSHandshakeCB");\r
+\r
+\r
+    if(g_dp_proceed_ctx && g_dp_proceed_ctx->peer && endpoint && info)\r
+    {\r
+        OIC_LOG_V(INFO, TAG, "Received status from remote device(%s:%d) : %d",\r
+                 endpoint->addr, endpoint->port, info->result);\r
+\r
+        OCDirectPairingDev_t *peer = g_dp_proceed_ctx->peer;\r
+        OCDirectPairingResultCB resultCallback = g_dp_proceed_ctx->resultCallback;\r
+        OCStackResult res;\r
+\r
+        //Make sure the address matches.\r
+        if(strncmp(peer->endpoint.addr, endpoint->addr, sizeof(endpoint->addr)) == 0 &&\r
+                         peer->securePort == endpoint->port)\r
+        {\r
+            //In case of success, send next coaps request.\r
+            if(CA_STATUS_OK == info->result)\r
+            {\r
+                OIC_LOG(INFO, TAG, "Now, finalize Direct-Pairing procedure.");\r
+\r
+                res = FinalizeDirectPairing(peer, resultCallback);\r
+                if(OC_STACK_OK != res)\r
+                {\r
+                    OIC_LOG(ERROR, TAG, "Failed to finalize direct-pairing");\r
+                    resultCallback(peer, res);\r
+                }\r
+            }\r
+            else if(CA_DTLS_AUTHENTICATION_FAILURE == info->result)\r
+            {\r
+                OIC_LOG(INFO, TAG, "DirectPairingDTLSHandshakeCB - Authentication failed");\r
+                resultCallback(peer, OC_STACK_AUTHENTICATION_FAILURE);\r
+            }\r
+\r
+#ifdef __WITH_DTLS__\r
+            CARegisterDTLSHandshakeCallback(NULL);\r
+#endif // __WITH_DTLS__\r
+            res = RemoveCredential(&peer->deviceID);\r
+            if(OC_STACK_RESOURCE_DELETED != res)\r
+            {\r
+                OIC_LOG_V(ERROR, TAG, "Failed to remove temporal PSK : %d", res);\r
+            }\r
+\r
+            OICFree(g_dp_proceed_ctx);\r
+            g_dp_proceed_ctx = NULL;\r
+        }\r
+        else\r
+        {\r
+            OIC_LOG_V(INFO, TAG, "DirectPairingDTLSHandshakeCB - Not matched to peer address");\r
+        }\r
+    }\r
+\r
+    OIC_LOG_V(INFO, TAG, "OUT DirectPairingDTLSHandshakeCB");\r
+}\r
+\r
+/**\r
+ * Callback handler of DPDirectPairing.\r
+ *\r
+ * @param[in] ctx             ctx value passed to callback from calling function.\r
+ * @param[in] UNUSED          handle to an invocation\r
+ * @param[in] clientResponse  Response from queries to remote servers.\r
+ * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction\r
+ *          and  OC_STACK_KEEP_TRANSACTION to keep it.\r
+ */\r
+static OCStackApplicationResult DirectPairingHandler(void *ctx, OCDoHandle UNUSED,\r
+                                                  OCClientResponse *clientResponse)\r
+{\r
+    OIC_LOG_V(INFO, TAG, "IN DirectPairingHandler.");\r
+    (void)UNUSED;\r
+    if(NULL == ctx)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Context is Null");\r
+        return OC_STACK_DELETE_TRANSACTION;\r
+    }\r
+\r
+    OCStackResult res = OC_STACK_ERROR;\r
+    DPairData_t *dpairData = (DPairData_t*)ctx;\r
+    OCDirectPairingResultCB resultCallback = (OCDirectPairingResultCB)dpairData->resultCallback;\r
+    OicUuid_t subjectId = {.id={0}};\r
+\r
+    if (clientResponse)\r
+    {\r
+        if(OC_STACK_RESOURCE_CREATED == clientResponse->result)\r
+        {\r
+            // result\r
+            OIC_LOG(INFO, TAG, "DirectPairingHandler : success POST request to /oic/sec/dpairing");\r
+\r
+#ifdef __WITH_DTLS__\r
+            // Add temporary psk\r
+            res = AddTmpPskWithPIN(&dpairData->peer->deviceID,\r
+                           SYMMETRIC_PAIR_WISE_KEY,\r
+                           (char*)dpairData->pin, DP_PIN_LENGTH,\r
+                           &dpairData->peer->rowner, &subjectId);\r
+            VERIFY_SUCCESS(TAG, OC_STACK_OK == res, ERROR);\r
+\r
+\r
+            // Start to establish a secure channel with Pin-based PSK cipher suite\r
+            CAResult_t caresult;\r
+\r
+            caresult = CAEnableAnonECDHCipherSuite(false);\r
+            VERIFY_SUCCESS(TAG, CA_STATUS_OK == caresult, ERROR);\r
+\r
+            caresult = CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256);\r
+            VERIFY_SUCCESS(TAG, CA_STATUS_OK == caresult, ERROR);\r
+\r
+            //Register proceeding peer info. & DTLS event handler to catch the dtls event while handshake\r
+            g_dp_proceed_ctx = dpairData;\r
+            res = CARegisterDTLSHandshakeCallback(DirectPairingDTLSHandshakeCB);\r
+            VERIFY_SUCCESS(TAG, CA_STATUS_OK == caresult, ERROR);\r
+\r
+            // initiate dtls\r
+            CAEndpoint_t *endpoint = (CAEndpoint_t *)OICCalloc(1, sizeof (CAEndpoint_t));\r
+            VERIFY_NON_NULL(TAG, endpoint, FATAL);\r
+            memcpy(endpoint,&dpairData->peer->endpoint,sizeof(CAEndpoint_t));\r
+            endpoint->port = dpairData->peer->securePort;\r
+            OIC_LOG_V(INFO, TAG, "Initiate DTLS handshake to %s(%d)", endpoint->addr,\r
+                    endpoint->port);\r
+\r
+            caresult = CAInitiateHandshake(endpoint);\r
+            OICFree(endpoint);\r
+            VERIFY_SUCCESS(TAG, CA_STATUS_OK == caresult, ERROR);\r
+#endif // __WITH_DTLS__\r
+\r
+            res = OC_STACK_OK;\r
+        }\r
+        else\r
+        {\r
+            // result\r
+            OIC_LOG(INFO, TAG, "DirectPairingHandler : fail POST request to /oic/sec/dpairing");\r
+        }\r
+    }\r
+    else\r
+    {\r
+        OIC_LOG(ERROR, TAG, "DirectPairingHandler received Null clientResponse");\r
+    }\r
+\r
+#ifdef __WITH_DTLS__\r
+exit:\r
+#endif // __WITH_DTLS__\r
+\r
+    if (OC_STACK_OK != res)\r
+    {\r
+        if (0 < strlen((const char*)subjectId.id))\r
+        {\r
+            RemoveCredential(&dpairData->peer->deviceID);\r
+            OICFree(dpairData);\r
+            g_dp_proceed_ctx = NULL;\r
+        }\r
+\r
+        resultCallback(dpairData->peer, res);\r
+    }\r
+    OIC_LOG_V(INFO, TAG, "OUT DirectPairingHandler.");\r
+    return OC_STACK_DELETE_TRANSACTION;\r
+}\r
+\r
+/**\r
+ * Start direct-pairing .\r
+ *\r
+ * @param[in] peer  target device to establish direct-pairing.\r
+ * @param[in] pmSel  selected pairing method.\r
+ * @param[in] pinNumber  secret value for dtls connection.\r
+ *\r
+ * @return OC_STACK_OK on success otherwise error.\r
+ */\r
+OCStackResult DPDirectPairing(OCDirectPairingDev_t* peer, OicSecPrm_t pmSel, char *pinNumber,\r
+                                                     OCDirectPairingResultCB resultCallback)\r
+{\r
+    if(NULL == peer || NULL == pinNumber)\r
+    {\r
+        return OC_STACK_INVALID_PARAM;\r
+    }\r
+\r
+    OicUuid_t deviceID =   {.id={0}};\r
+    if (OC_STACK_OK != GetDoxmDeviceID(&deviceID))\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Error while retrieving device ID");\r
+        return OC_STACK_ERROR;\r
+    }\r
+\r
+    OicSecDpairing_t dpair;\r
+    memset(&dpair, 0, sizeof(OicSecDpairing_t));\r
+    dpair.spm = pmSel;\r
+    memcpy(&dpair.pdeviceID, &deviceID, sizeof(OicUuid_t));\r
+\r
+    OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));\r
+    if(!secPayload)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Failed to memory allocation");\r
+        return OC_STACK_NO_MEMORY;\r
+    }\r
+    secPayload->base.type = PAYLOAD_TYPE_SECURITY;\r
+\r
+    OCStackResult ret = DpairingToCBORPayload(&dpair, &(secPayload->securityData),\r
+            &(secPayload->payloadSize));\r
+\r
+    if(OC_STACK_OK != ret)\r
+    {\r
+        OICFree(secPayload);\r
+        OIC_LOG(ERROR, TAG, "Failed to DpairingToCBORPayload");\r
+        return OC_STACK_NO_MEMORY;\r
+    }\r
+    OIC_LOG(INFO, TAG, "DPARING CBOR data:");\r
+    OIC_LOG_BUFFER(INFO, TAG, secPayload->securityData, secPayload->payloadSize);\r
+\r
+    char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};\r
+    if(!DPGenerateQuery(false,\r
+                        peer->endpoint.addr,\r
+                        peer->endpoint.port,\r
+                        //peer->securePort,\r
+                        peer->connType,\r
+                        query, sizeof(query), OIC_RSRC_DPAIRING_URI))\r
+    {\r
+        OIC_LOG(ERROR, TAG, "DPDirectPairing : Failed to generate query");\r
+        return OC_STACK_ERROR;\r
+    }\r
+    OIC_LOG_V(DEBUG, TAG, "Query=%s", query);\r
+\r
+    DPairData_t *dpairData = (DPairData_t *) OICCalloc(1, sizeof(DPairData_t));\r
+    if (dpairData == NULL)\r
+    {\r
+        OICFree(secPayload->securityData);\r
+        OICFree(secPayload);\r
+        OIC_LOG(ERROR, TAG, "Unable to allocate memory");\r
+        return OC_STACK_NO_MEMORY;\r
+    }\r
+    dpairData->peer = peer;\r
+    memcpy(dpairData->pin, pinNumber, DP_PIN_LENGTH);\r
+    dpairData->resultCallback = resultCallback;\r
+\r
+    OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};\r
+    cbData.cb = DirectPairingHandler;\r
+    cbData.context = (void*)dpairData;\r
+    cbData.cd = NULL;\r
+\r
+    OCMethod method = OC_REST_POST;\r
+    OCDoHandle handle = NULL;\r
+    OIC_LOG(DEBUG, TAG, "Sending DPAIRNG setting to resource server");\r
+    ret = OCDoResource(&handle, method, query,\r
+            &peer->endpoint, (OCPayload*)secPayload,\r
+            peer->connType, OC_LOW_QOS, &cbData, NULL, 0);\r
+    if(OC_STACK_OK != ret)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "error in OCDoResource");\r
+        return OC_STACK_ERROR;\r
+    }\r
+\r
+    return OC_STACK_OK;\r
+\r
+ }\r
+\r
+/**\r
+ * Callback handler for getting secure port information using /oic/res discovery.\r
+ *\r
+ * @param[in] ctx             user context\r
+ * @param[in] handle          Handle for response\r
+ * @param[in] clientResponse  Response information(It will contain payload)\r
+ *\r
+ * @return OC_STACK_KEEP_TRANSACTION to keep transaction and\r
+ *         OC_STACK_DELETE_TRANSACTION to delete it.\r
+ */\r
+static OCStackApplicationResult DirectPairingPortDiscoveryHandler(void *ctx, OCDoHandle UNUSED,\r
+                                 OCClientResponse *clientResponse)\r
+{\r
+    OIC_LOG(INFO, TAG, "Callback Context for Direct-Pairing Secure Port DISCOVER "\r
+            "query recvd successfully");\r
+\r
+    (void)ctx;\r
+    (void)UNUSED;\r
+    if (clientResponse)\r
+    {\r
+        if  (NULL == clientResponse->payload)\r
+        {\r
+            OIC_LOG(INFO, TAG, "Skiping Null payload");\r
+        }\r
+        else\r
+        {\r
+            if (PAYLOAD_TYPE_DISCOVERY != clientResponse->payload->type)\r
+            {\r
+                OIC_LOG(INFO, TAG, "Wrong payload type");\r
+                return OC_STACK_DELETE_TRANSACTION;\r
+            }\r
+\r
+            uint16_t securePort = 0;\r
+            OCResourcePayload* resPayload = ((OCDiscoveryPayload*)clientResponse->payload)->resources;\r
+            OIC_LOG_PAYLOAD(INFO, clientResponse->payload);\r
+\r
+            if (resPayload && resPayload->secure)\r
+            {\r
+                securePort = resPayload->port;\r
+            }\r
+            else\r
+            {\r
+                OIC_LOG(INFO, TAG, "Can not find secure port information.");\r
+                return OC_STACK_DELETE_TRANSACTION;\r
+            }\r
+\r
+            OCDirectPairingDev_t *ptr = getDev(&g_dp_discover,\r
+                    clientResponse->devAddr.addr, clientResponse->devAddr.port);\r
+            if(!ptr)\r
+            {\r
+                OIC_LOG(ERROR, TAG, "Can not find device information in the discovery device list");\r
+                return OC_STACK_DELETE_TRANSACTION;\r
+            }\r
+            ptr->securePort = securePort;\r
+\r
+            OIC_LOG(INFO, TAG, "Exiting DirectPairingPortDiscoveryHandler.");\r
+        }\r
+\r
+        return  OC_STACK_DELETE_TRANSACTION;\r
+    }\r
+    else\r
+    {\r
+        OIC_LOG(INFO, TAG, "Skiping Null response");\r
+    }\r
+    return  OC_STACK_DELETE_TRANSACTION;\r
+}\r
+\r
+/**\r
+ * Callback handler for DPDeviceDiscovery API.\r
+ *\r
+ * @param[in] ctx             User context\r
+ * @param[in] handle          Handler for response\r
+ * @param[in] clientResponse  Response information (It will contain payload)\r
+ * @return OC_STACK_KEEP_TRANSACTION to keep transaction and\r
+ *         OC_STACK_DELETE_TRANSACTION to delete it.\r
+ */\r
+static OCStackApplicationResult DirectPairingDiscoveryHandler(void* ctx, OCDoHandle UNUSED,\r
+        OCClientResponse * clientResponse)\r
+{\r
+    OIC_LOG(INFO, TAG, "Callback Context for Direct-Pairing DISCOVER query recvd successfully");\r
+\r
+    (void)ctx;\r
+    (void)UNUSED;\r
+    if (clientResponse)\r
+    {\r
+        OIC_LOG_V(INFO, TAG, "StackResult: %d", clientResponse->result);\r
+        OIC_LOG_V(INFO, TAG,\r
+                "Device =============> Discovered @ %s:%d",\r
+                clientResponse->devAddr.addr,\r
+                clientResponse->devAddr.port);\r
+\r
+        if  (NULL == clientResponse->payload)\r
+        {\r
+            OIC_LOG(INFO, TAG, "Skiping Null payload");\r
+            return OC_STACK_KEEP_TRANSACTION;\r
+        }\r
+        if (OC_STACK_OK != clientResponse->result)\r
+        {\r
+            OIC_LOG(INFO, TAG, "Error in response");\r
+            return OC_STACK_KEEP_TRANSACTION;\r
+        }\r
+\r
+        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);\r
+        OicSecPconf_t *pconf = NULL;\r
+\r
+        OCStackResult res = CBORPayloadToPconf(\r
+                ((OCSecurityPayload*)clientResponse->payload)->securityData,\r
+                CBOR_SIZE,&pconf);\r
+        if (OC_STACK_OK != res )\r
+        {\r
+            OIC_LOG(INFO, TAG, "Ignoring malformed CBOR");\r
+            return OC_STACK_KEEP_TRANSACTION;\r
+        }\r
+        else\r
+        {\r
+            if(pconf->edp)\r
+            {\r
+                OCDevAddr endpoint;\r
+                memcpy(&endpoint, &clientResponse->devAddr, sizeof(OCDevAddr));\r
+\r
+                OCStackResult res = addDev(&g_dp_discover, &endpoint,\r
+                            clientResponse->connType, pconf);\r
+                DeletePconfBinData(pconf);\r
+                if (OC_STACK_OK != res)\r
+                {\r
+                    OIC_LOG(ERROR, TAG, "Error while adding data to linkedlist.");\r
+                    return OC_STACK_KEEP_TRANSACTION;\r
+                }\r
+\r
+\r
+                char rsrc_uri[MAX_URI_LENGTH+1] = {0};\r
+                int wr_len = snprintf(rsrc_uri, sizeof(rsrc_uri), "%s?%s=%s",\r
+                          OC_RSRVD_WELL_KNOWN_URI, OC_RSRVD_RESOURCE_TYPE, OIC_RSRC_TYPE_SEC_DPAIRING);\r
+                if(wr_len <= 0 || (size_t)wr_len >= sizeof(rsrc_uri))\r
+                {\r
+                    OIC_LOG(ERROR, TAG, "rsrc_uri_string_print failed");\r
+                    return OC_STACK_KEEP_TRANSACTION;\r
+                }\r
+\r
+                //Try to the unicast discovery to getting secure port\r
+                char query[MAX_URI_LENGTH+MAX_QUERY_LENGTH+1] = {0};\r
+                if(!DPGenerateQuery(false,\r
+                                    clientResponse->devAddr.addr, clientResponse->devAddr.port,\r
+                                    clientResponse->connType,\r
+                                    query, sizeof(query), rsrc_uri))\r
+                {\r
+                    OIC_LOG(ERROR, TAG, "DirectPairingDiscoveryHandler : Failed to generate query");\r
+                    return OC_STACK_KEEP_TRANSACTION;\r
+                }\r
+                OIC_LOG_V(DEBUG, TAG, "Query=%s", query);\r
+\r
+                OCCallbackData cbData;\r
+                cbData.cb = &DirectPairingPortDiscoveryHandler;\r
+                cbData.context = NULL;\r
+                cbData.cd = NULL;\r
+                OCStackResult ret = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,\r
+                        clientResponse->connType, OC_LOW_QOS, &cbData, NULL, 0);\r
+                if(OC_STACK_OK != ret)\r
+                {\r
+                    OIC_LOG(ERROR, TAG, "Failed to Secure Port Discovery");\r
+                    return OC_STACK_KEEP_TRANSACTION;\r
+                }\r
+                else\r
+                {\r
+                    OIC_LOG_V(INFO, TAG, "OCDoResource with [%s] Success", query);\r
+                }\r
+            }\r
+            return  OC_STACK_KEEP_TRANSACTION;\r
+        }\r
+    }\r
+    else\r
+    {\r
+        OIC_LOG(INFO, TAG, "Skiping Null response");\r
+    }\r
+\r
+    return OC_STACK_DELETE_TRANSACTION;\r
+}\r
+#ifndef WITH_ARDUINO\r
+/**\r
+ * Discover direct-pairing devices in the same IP subnet. .\r
+ *\r
+ * @param[in] waittime  Timeout in seconds.\r
+ *\r
+ * @return OC_STACK_OK on success otherwise error.\r
+ */\r
+OCStackResult DPDeviceDiscovery(unsigned short waittime)\r
+{\r
+    OIC_LOG(DEBUG, TAG, "IN DPDeviceDiscovery");\r
+\r
+    if (g_dp_discover)\r
+    {\r
+        delList(g_dp_discover);\r
+        g_dp_discover = NULL;\r
+    }\r
+\r
+    OCStackResult ret;\r
+    struct timespec startTime = {.tv_sec=0, .tv_nsec=0};\r
+    struct timespec currTime  = {.tv_sec=0, .tv_nsec=0};\r
+    struct timespec timeout;\r
+\r
+    const char DP_DISCOVERY_QUERY[] = "/oic/sec/pconf";\r
+\r
+    OCCallbackData cbData;\r
+    cbData.cb = DirectPairingDiscoveryHandler;\r
+    cbData.context = NULL;\r
+    cbData.cd = NULL;\r
+\r
+    /* Start a DP discovery query*/\r
+    OIC_LOG_V(INFO, TAG, "Initiating Direct-Pairing Discovery : %s\n", DP_DISCOVERY_QUERY);\r
+    OCDoHandle handle = NULL;\r
+    ret = OCDoResource(&handle, OC_REST_DISCOVER, DP_DISCOVERY_QUERY, 0, 0, CT_DEFAULT,\r
+                       OC_LOW_QOS, &cbData, NULL, 0);\r
+    if (ret != OC_STACK_OK)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "OCStack resource error");\r
+        return ret;\r
+    }\r
+\r
+    // wait..\r
+    timeout.tv_sec  = 0;\r
+    timeout.tv_nsec = 100000000L;\r
+\r
+    int clock_res = -1;\r
+#if defined(__ANDROID__) || _POSIX_TIMERS > 0\r
+    clock_res = clock_gettime(CLOCK_MONOTONIC, &startTime);\r
+#endif\r
+    if (0 != clock_res)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "clock error");\r
+        if(OC_STACK_OK !=  OCCancel(handle, OC_LOW_QOS, NULL, 0))\r
+        {\r
+            OIC_LOG(ERROR, TAG, "Failed to remove registered callback");\r
+        }\r
+        return OC_STACK_ERROR;\r
+    }\r
+\r
+    while (1)\r
+    {\r
+#if defined(__ANDROID__) || _POSIX_TIMERS > 0\r
+        clock_res = clock_gettime(CLOCK_MONOTONIC, &currTime);\r
+#endif\r
+        if (0 != clock_res)\r
+        {\r
+            OIC_LOG(ERROR, TAG, "clock error");\r
+            ret = OC_STACK_ERROR;\r
+            break;\r
+        }\r
+        long elapsed = (currTime.tv_sec - startTime.tv_sec);\r
+        if (elapsed > waittime)\r
+        {\r
+            break;\r
+        }\r
+        else\r
+        {\r
+            nanosleep(&timeout, NULL);\r
+        }\r
+    }\r
+\r
+    //Waiting for each response.\r
+    ret = OCCancel(handle, OC_LOW_QOS, NULL, 0);\r
+    if (OC_STACK_OK != ret)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Failed to remove registered callback");\r
+    }\r
+    OIC_LOG(DEBUG, TAG, "OUT DPDeviceDiscovery");\r
+    return ret;\r
+}\r
+#endif\r
index cb2bd37..d48c8ef 100644 (file)
 // limitations under the License.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#include <stdlib.h>
+#include <string.h>
+
+#if HAVE_STRINGS_H
+#include <strings.h>
+#endif
+
+#ifdef __WITH_DTLS__
+#include "global.h"
+#endif
 
 #include "ocstack.h"
-#include "logger.h"
 #include "oic_malloc.h"
-#include "cJSON.h"
+#include "payload_logging.h"
+#include "utlist.h"
+#include "ocrandom.h"
+#include "ocpayload.h"
+#include "cainterface.h"
+#include "ocserverrequest.h"
 #include "resourcemanager.h"
 #include "doxmresource.h"
+#include "pstatresource.h"
+#include "aclresource.h"
+#include "amaclresource.h"
+#include "pconfresource.h"
+#include "dpairingresource.h"
 #include "psinterface.h"
-#include "utlist.h"
 #include "srmresourcestrings.h"
 #include "securevirtualresourcetypes.h"
-#include "base64.h"
-#include "ocrandom.h"
-#include "cainterface.h"
 #include "credresource.h"
-#include "ocserverrequest.h"
 #include "srmutility.h"
 #include "pinoxmcommon.h"
 
-#ifdef __WITH_DTLS__
-#include "global.h"
-#endif
+#define TAG  "SRM-DOXM"
 
-#include <stdlib.h>
-#include <string.h>
+/** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
+ * The value of payload size is increased until reaching belox max cbor size. */
+static const uint16_t CBOR_SIZE = 512;
 
-#if HAVE_STRINGS_H
-#include <strings.h>
-#endif
+/** Max cbor size payload. */
+static const uint16_t CBOR_MAX_SIZE = 4400;
 
-#define TAG  "SRM-DOXM"
+/** DOXM Map size - Number of mandatory items. */
+static const uint8_t DOXM_MAP_SIZE = 7;
 
 static OicSecDoxm_t        *gDoxm = NULL;
 static OCResourceHandle    gDoxmHandle = NULL;
@@ -63,7 +76,9 @@ static OicSecDoxm_t gDefaultDoxm =
     SYMMETRIC_PAIR_WISE_KEY,/* OicSecCredType_t sct */
     false,                  /* bool owned */
     {.id = {0}},            /* OicUuid_t deviceID */
+    false,                  /* bool dpc */
     {.id = {0}},            /* OicUuid_t owner */
+    {.id = {0}},            /* OicUuid_t rownerID */
 };
 
 void DeleteDoxmBinData(OicSecDoxm_t* doxm)
@@ -85,162 +100,259 @@ void DeleteDoxmBinData(OicSecDoxm_t* doxm)
     }
 }
 
-char * BinToDoxmJSON(const OicSecDoxm_t * doxm)
+OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, size_t *size)
 {
-    if (NULL == doxm)
+    if (NULL == doxm || NULL == payload || NULL != *payload || NULL == size)
     {
-        return NULL;
+        return OC_STACK_INVALID_PARAM;
     }
+    size_t cborLen = *size;
+    if (0 == cborLen)
+    {
+        cborLen = CBOR_SIZE;
+    }
+    *payload = NULL;
+    *size = 0;
+
+    OCStackResult ret = OC_STACK_ERROR;
+
+    CborEncoder encoder;
+    CborEncoder doxmMap;
+    char* strUuid = NULL;
 
-    char *jsonStr = NULL;
-    cJSON *jsonDoxm = NULL;
-    char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
-    uint32_t outLen = 0;
-    B64Result b64Ret = B64_OK;
+    int64_t cborEncoderResult = CborNoError;
+    uint8_t mapSize = DOXM_MAP_SIZE;
+    if (doxm->oxmTypeLen > 0)
+    {
+        mapSize++;
+    }
+    if (doxm->oxmLen > 0)
+    {
+        mapSize++;
+    }
 
-    cJSON *jsonRoot = cJSON_CreateObject();
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
+    VERIFY_NON_NULL(TAG, outPayload, ERROR);
+    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
 
-    jsonDoxm = cJSON_CreateObject();
-    VERIFY_NON_NULL(TAG, jsonDoxm, ERROR);
-    cJSON_AddItemToObject(jsonRoot, OIC_JSON_DOXM_NAME, jsonDoxm );
+    cborEncoderResult = cbor_encoder_create_map(&encoder, &doxmMap, mapSize);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Map.");
 
     //OxmType -- Not Mandatory
-    if(doxm->oxmTypeLen > 0)
+    if (doxm->oxmTypeLen > 0)
     {
-        cJSON *jsonOxmTyArray = cJSON_CreateArray();
-        VERIFY_NON_NULL(TAG, jsonOxmTyArray, ERROR);
-        cJSON_AddItemToObject (jsonDoxm, OIC_JSON_OXM_TYPE_NAME, jsonOxmTyArray );
+        CborEncoder oxmType;
+        cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_TYPE_NAME,
+            strlen(OIC_JSON_OXM_TYPE_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Tag.");
+        cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxmType, doxm->oxmTypeLen);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Array.");
+
         for (size_t i = 0; i < doxm->oxmTypeLen; i++)
         {
-            cJSON_AddItemToArray (jsonOxmTyArray, cJSON_CreateString(doxm->oxmType[i]));
+            cborEncoderResult = cbor_encode_text_string(&oxmType, doxm->oxmType[i],
+                strlen(doxm->oxmType[i]));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Value.");
         }
+        cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxmType);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmType.");
     }
 
     //Oxm -- Not Mandatory
-    if(doxm->oxmLen > 0)
+    if (doxm->oxmLen > 0)
     {
-        cJSON *jsonOxmArray = cJSON_CreateArray();
-        VERIFY_NON_NULL(TAG, jsonOxmArray, ERROR);
-        cJSON_AddItemToObject (jsonDoxm, OIC_JSON_OXM_NAME,jsonOxmArray );
+        CborEncoder oxm;
+        cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXMS_NAME,
+            strlen(OIC_JSON_OXMS_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Tag.");
+        cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxm, doxm->oxmLen);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Array.");
+
         for (size_t i = 0; i < doxm->oxmLen; i++)
         {
-            cJSON_AddItemToArray (jsonOxmArray, cJSON_CreateNumber(doxm->oxm[i]));
+            cborEncoderResult = cbor_encode_int(&oxm, doxm->oxm[i]);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Value");
         }
+        cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxm);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmName.");
     }
 
     //OxmSel -- Mandatory
-    cJSON_AddNumberToObject(jsonDoxm, OIC_JSON_OXM_SEL_NAME, (int)doxm->oxmSel);
+    cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_SEL_NAME,
+        strlen(OIC_JSON_OXM_SEL_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Tag.");
+    cborEncoderResult = cbor_encode_int(&doxmMap, doxm->oxmSel);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Value.");
 
     //sct -- Mandatory
-    cJSON_AddNumberToObject(jsonDoxm, OIC_JSON_SUPPORTED_CRED_TYPE_NAME, (int)doxm->sct);
+    cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUPPORTED_CRED_TYPE_NAME,
+        strlen(OIC_JSON_SUPPORTED_CRED_TYPE_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag");
+    cborEncoderResult = cbor_encode_int(&doxmMap, doxm->sct);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
 
     //Owned -- Mandatory
-    cJSON_AddBoolToObject(jsonDoxm, OIC_JSON_OWNED_NAME, doxm->owned);
-
-    //TODO: Need more clarification on deviceIDFormat field type.
-#if 0
-    //DeviceIdFormat -- Mandatory
-    cJSON_AddNumberToObject(jsonDoxm, OIC_JSON_DEVICE_ID_FORMAT_NAME, doxm->deviceIDFormat);
-#endif
+    cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OWNED_NAME,
+        strlen(OIC_JSON_OWNED_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Tag.");
+    cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->owned);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Value.");
 
     //DeviceId -- Mandatory
-    outLen = 0;
-    b64Ret = b64Encode(doxm->deviceID.id, sizeof(doxm->deviceID.id), base64Buff,
-                    sizeof(base64Buff), &outLen);
-    VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
-    cJSON_AddStringToObject(jsonDoxm, OIC_JSON_DEVICE_ID_NAME, base64Buff);
-
-    //Owner -- Mandatory
-    outLen = 0;
-    b64Ret = b64Encode(doxm->owner.id, sizeof(doxm->owner.id), base64Buff,
-                    sizeof(base64Buff), &outLen);
-    VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
-    cJSON_AddStringToObject(jsonDoxm, OIC_JSON_OWNER_NAME, base64Buff);
-
-    jsonStr = cJSON_PrintUnformatted(jsonRoot);
-
+    cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVICE_ID_NAME,
+        strlen(OIC_JSON_DEVICE_ID_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag.");
+    ret = ConvertUuidToStr(&doxm->deviceID, &strUuid);
+    VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
+    cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value.");
+    OICFree(strUuid);
+    strUuid = NULL;
+
+    //devownerid -- Mandatory
+    cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVOWNERID_NAME,
+        strlen(OIC_JSON_DEVOWNERID_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Tag.");
+    ret = ConvertUuidToStr(&doxm->owner, &strUuid);
+    VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
+    cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Value.");
+    OICFree(strUuid);
+    strUuid = NULL;
+
+    //ROwner -- Mandatory
+    cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_ROWNERID_NAME,
+        strlen(OIC_JSON_ROWNERID_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Tag.");
+    ret = ConvertUuidToStr(&doxm->rownerID, &strUuid);
+    VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
+    cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Value.");
+    OICFree(strUuid);
+    strUuid = NULL;
+
+    //DPC -- Mandatory
+    cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DPC_NAME,
+        strlen(OIC_JSON_DPC_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Tag.");
+    cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->dpc);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Value.");
+
+    cborEncoderResult = cbor_encoder_close_container(&encoder, &doxmMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing DoxmMap.");
+
+    if (CborNoError == cborEncoderResult)
+    {
+        *size = encoder.ptr - outPayload;
+        *payload = outPayload;
+        ret = OC_STACK_OK;
+    }
 exit:
-    if (jsonRoot)
+    if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
     {
-        cJSON_Delete(jsonRoot);
+        OIC_LOG(DEBUG, TAG, "Memory getting reallocated.");
+        // reallocate and try again!
+        OICFree(outPayload);
+        // Since the allocated initial memory failed, double the memory.
+        cborLen += encoder.ptr - encoder.end;
+        OIC_LOG_V(DEBUG, TAG, "Doxm reallocation size : %zd.", cborLen);
+        cborEncoderResult = CborNoError;
+        ret = DoxmToCBORPayload(doxm, payload, &cborLen);
+        *size = cborLen;
     }
-    return jsonStr;
+
+    if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
+    {
+       OICFree(outPayload);
+       outPayload = NULL;
+       *payload = NULL;
+       *size = 0;
+       ret = OC_STACK_ERROR;
+    }
+
+    return ret;
 }
 
-OicSecDoxm_t * JSONToDoxmBin(const char * jsonStr)
+OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
+                                OicSecDoxm_t **secDoxm)
 {
-
-    if (NULL == jsonStr)
+    if (NULL == cborPayload || NULL == secDoxm || NULL != *secDoxm || 0 == size)
     {
-        return NULL;
+        return OC_STACK_INVALID_PARAM;
     }
 
     OCStackResult ret = OC_STACK_ERROR;
-    OicSecDoxm_t *doxm =  NULL;
-    cJSON *jsonDoxm = NULL;
-    cJSON *jsonObj = NULL;
-
-    size_t jsonObjLen = 0;
-    unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
-    uint32_t outLen = 0;
-    B64Result b64Ret = B64_OK;
-
-    cJSON *jsonRoot = cJSON_Parse(jsonStr);
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+    *secDoxm = NULL;
 
-    jsonDoxm = cJSON_GetObjectItem(jsonRoot, OIC_JSON_DOXM_NAME);
-    VERIFY_NON_NULL(TAG, jsonDoxm, ERROR);
+    CborParser parser;
+    CborError cborFindResult = CborNoError;
+    char* strUuid = NULL;
+    size_t len = 0;
+    CborValue doxmCbor;
 
-    doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t));
+    cbor_parser_init(cborPayload, size, 0, &parser, &doxmCbor);
+    CborValue doxmMap;
+    OicSecDoxm_t *doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(*doxm));
     VERIFY_NON_NULL(TAG, doxm, ERROR);
 
+    cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_TYPE_NAME, &doxmMap);
     //OxmType -- not Mandatory
-    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_TYPE_NAME);
-    if ((jsonObj) && (cJSON_Array == jsonObj->type))
+    if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
     {
-        doxm->oxmTypeLen = cJSON_GetArraySize(jsonObj);
-        VERIFY_SUCCESS(TAG, doxm->oxmTypeLen > 0, ERROR);
+        CborValue oxmType;
 
-        doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(char *));
-        VERIFY_NON_NULL(TAG, (doxm->oxmType), ERROR);
+        cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmTypeLen);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmTypeLen.")
+        VERIFY_SUCCESS(TAG, doxm->oxmTypeLen != 0, ERROR);
 
-        for (size_t i  = 0; i < doxm->oxmTypeLen ; i++)
-        {
-            cJSON *jsonOxmTy = cJSON_GetArrayItem(jsonObj, i);
-            VERIFY_NON_NULL(TAG, jsonOxmTy, ERROR);
+        doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(*doxm->oxmType));
+        VERIFY_NON_NULL(TAG, doxm->oxmType, ERROR);
+
+        cborFindResult = cbor_value_enter_container(&doxmMap, &oxmType);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmType Array.")
 
-            jsonObjLen = strlen(jsonOxmTy->valuestring) + 1;
-            doxm->oxmType[i] = (char*)OICMalloc(jsonObjLen);
-            VERIFY_NON_NULL(TAG, doxm->oxmType[i], ERROR);
-            strncpy((char *)doxm->oxmType[i], (char *)jsonOxmTy->valuestring, jsonObjLen);
+        int i = 0;
+        size_t len = 0;
+        while (cbor_value_is_valid(&oxmType))
+        {
+            cborFindResult = cbor_value_dup_text_string(&oxmType, &doxm->oxmType[i++],
+                                                        &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding omxType text string.")
+            cborFindResult = cbor_value_advance(&oxmType);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmType.")
         }
     }
 
+    cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXMS_NAME, &doxmMap);
     //Oxm -- not Mandatory
-    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_NAME);
-    if (jsonObj && cJSON_Array == jsonObj->type)
+    if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
     {
-        doxm->oxmLen = cJSON_GetArraySize(jsonObj);
-        VERIFY_SUCCESS(TAG, doxm->oxmLen > 0, ERROR);
+        CborValue oxm;
+        cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmLen);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName array Length.")
+        VERIFY_SUCCESS(TAG, doxm->oxmLen != 0, ERROR);
 
-        doxm->oxm = (OicSecOxm_t*)OICCalloc(doxm->oxmLen, sizeof(OicSecOxm_t));
+        doxm->oxm = (OicSecOxm_t *)OICCalloc(doxm->oxmLen, sizeof(*doxm->oxm));
         VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
 
-        for (size_t i  = 0; i < doxm->oxmLen ; i++)
+        cborFindResult = cbor_value_enter_container(&doxmMap, &oxm);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmName Array.")
+
+        int i = 0;
+        while (cbor_value_is_valid(&oxm))
         {
-            cJSON *jsonOxm = cJSON_GetArrayItem(jsonObj, i);
-            VERIFY_NON_NULL(TAG, jsonOxm, ERROR);
-            doxm->oxm[i] = (OicSecOxm_t)jsonOxm->valueint;
+            cborFindResult = cbor_value_get_int(&oxm, (int *) &doxm->oxm[i++]);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName Value")
+            cborFindResult = cbor_value_advance(&oxm);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmName.")
         }
     }
 
-    //OxmSel -- Mandatory
-    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_SEL_NAME);
-    if(jsonObj)
+    cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_SEL_NAME, &doxmMap);
+    if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
     {
-        VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
-        doxm->oxmSel = (OicSecOxm_t)jsonObj->valueint;
+        cborFindResult = cbor_value_get_int(&doxmMap, (int *) &doxm->oxmSel);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sel Name Value.")
     }
     else // PUT/POST JSON may not have oxmsel so set it to the gDoxm->oxmSel
     {
@@ -248,12 +360,11 @@ OicSecDoxm_t * JSONToDoxmBin(const char * jsonStr)
         doxm->oxmSel = gDoxm->oxmSel;
     }
 
-    //sct -- Mandatory
-    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_SUPPORTED_CRED_TYPE_NAME);
-    if(jsonObj)
+    cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUPPORTED_CRED_TYPE_NAME, &doxmMap);
+    if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
     {
-        VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
-        doxm->sct = (OicSecCredType_t)jsonObj->valueint;
+        cborFindResult = cbor_value_get_int(&doxmMap, (int *) &doxm->sct);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sct Name Value.")
     }
     else // PUT/POST JSON may not have sct so set it to the gDoxm->sct
     {
@@ -261,12 +372,11 @@ OicSecDoxm_t * JSONToDoxmBin(const char * jsonStr)
         doxm->sct = gDoxm->sct;
     }
 
-    //Owned -- Mandatory
-    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OWNED_NAME);
-    if(jsonObj)
+    cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OWNED_NAME, &doxmMap);
+    if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
     {
-        VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type), ERROR);
-        doxm->owned = jsonObj->valueint;
+        cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->owned);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owned Value.")
     }
     else // PUT/POST JSON may not have owned so set it to the gDomx->owned
     {
@@ -274,58 +384,64 @@ OicSecDoxm_t * JSONToDoxmBin(const char * jsonStr)
         doxm->owned = gDoxm->owned;
     }
 
-    //DeviceId -- Mandatory
-    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_DEVICE_ID_NAME);
-    if(jsonObj)
+    cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DPC_NAME, &doxmMap);
+    if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
     {
-        VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
-        if(cJSON_String == jsonObj->type)
-        {
-            //Check for empty string, in case DeviceId field has not been set yet
-            if (jsonObj->valuestring[0])
-            {
-                outLen = 0;
-                b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
-                        sizeof(base64Buff), &outLen);
-                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(doxm->deviceID.id)),
-                                ERROR);
-                memcpy(doxm->deviceID.id, base64Buff, outLen);
-            }
-        }
+        cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->dpc);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding DPC Value.")
     }
-    else // PUT/POST JSON will not have deviceID so set it to the gDoxm->deviceID.id
+    else // PUT/POST JSON may not have owned so set it to the gDomx->owned
     {
         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
-        memcpy((char *)doxm->deviceID.id, (char *)gDoxm->deviceID.id, sizeof(doxm->deviceID.id));
+        doxm->owned = false;
+    }
+
+    cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVICE_ID_NAME, &doxmMap);
+    if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
+    {
+        cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Device Id Value.");
+        ret = ConvertStrToUuid(strUuid , &doxm->deviceID);
+        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+        OICFree(strUuid);
+        strUuid  = NULL;
     }
 
-    //Owner -- will be empty when device status is unowned.
-    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OWNER_NAME);
-    if(true == doxm->owned)
+    cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVOWNERID_NAME, &doxmMap);
+    if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
     {
-        VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+        cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Value.");
+        ret = ConvertStrToUuid(strUuid , &doxm->owner);
+        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+        OICFree(strUuid);
+        strUuid  = NULL;
     }
-    if(jsonObj)
+
+    cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_ROWNERID_NAME, &doxmMap);
+    if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
     {
-        VERIFY_SUCCESS(TAG, (cJSON_String == jsonObj->type), ERROR);
-        outLen = 0;
-        b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
-                sizeof(base64Buff), &outLen);
-        VERIFY_SUCCESS(TAG, ((b64Ret == B64_OK) && (outLen <= sizeof(doxm->owner.id))), ERROR);
-        memcpy(doxm->owner.id, base64Buff, outLen);
+        cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ROwner Value.");
+        ret = ConvertStrToUuid(strUuid , &doxm->rownerID);
+        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+        OICFree(strUuid);
+        strUuid  = NULL;
     }
 
+    *secDoxm = doxm;
     ret = OC_STACK_OK;
 
 exit:
-    cJSON_Delete(jsonRoot);
-    if (OC_STACK_OK != ret)
+    if (CborNoError != cborFindResult)
     {
+        OIC_LOG (ERROR, TAG, "CBORPayloadToDoxm failed!!!");
         DeleteDoxmBinData(doxm);
         doxm = NULL;
+        *secDoxm = NULL;
+        ret = OC_STACK_ERROR;
     }
-
-    return doxm;
+    return ret;
 }
 
 /**
@@ -338,19 +454,22 @@ static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
 
     if (NULL != doxm)
     {
-        // Convert Doxm data into JSON for update to persistent storage
-        char *jsonStr = BinToDoxmJSON(doxm);
-        if (jsonStr)
+        // Convert Doxm data into CBOR for update to persistent storage
+        uint8_t *payload = NULL;
+        size_t size = 0;
+        OCStackResult res = DoxmToCBORPayload(doxm, &payload, &size);
+        if (payload && (OC_STACK_OK == res)
+            && (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, payload, size)))
+        {
+                bRet = true;
+        }
+        OICFree(payload);
+    }
+    else
+    {
+        if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, NULL, 0))
         {
-            cJSON *jsonDoxm = cJSON_Parse(jsonStr);
-            OICFree(jsonStr);
-
-            if (jsonDoxm &&
-                    (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_DOXM_NAME, jsonDoxm)))
-            {
                 bRet = true;
-            }
-            cJSON_Delete(jsonDoxm);
         }
     }
 
@@ -367,7 +486,7 @@ static bool ValidateQuery(const char * query)
     // access rules. Eventually, the PE and PM code will
     // not send a request to the /doxm Entity Handler at all
     // if it should not respond.
-    OC_LOG (DEBUG, TAG, "In ValidateQuery");
+    OIC_LOG (DEBUG, TAG, "In ValidateQuery");
     if(NULL == gDoxm)
     {
         return false;
@@ -382,255 +501,229 @@ static bool ValidateQuery(const char * query)
 
     ParseQueryIterInit((unsigned char*)query, &parseIter);
 
-    while(GetNextQuery(&parseIter))
+    while (GetNextQuery(&parseIter))
     {
-        if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
+        if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
         {
             bOwnedQry = true;
-            if((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
+            if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
                     (gDoxm->owned))
             {
                 bOwnedMatch = true;
             }
-            else if((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
+            else if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
                     && (!gDoxm->owned))
             {
                 bOwnedMatch = true;
             }
         }
 
-        if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_DEVICE_ID_NAME, parseIter.attrLen) == 0)
+        if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_DEVICE_ID_NAME, parseIter.attrLen) == 0)
         {
             bDeviceIDQry = true;
             OicUuid_t subject = {.id={0}};
-            unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
-            uint32_t outLen = 0;
-            B64Result b64Ret = B64_OK;
 
-            b64Ret = b64Decode((char *)parseIter.valPos, parseIter.valLen, base64Buff,
-                                           sizeof(base64Buff), &outLen);
-
-            VERIFY_SUCCESS(TAG, (B64_OK == b64Ret && outLen <= sizeof(subject.id)), ERROR);
-                       memcpy(subject.id, base64Buff, outLen);
-            if(0 == memcmp(&gDoxm->deviceID.id, &subject.id, sizeof(gDoxm->deviceID.id)))
+            memcpy(subject.id, parseIter.valPos, parseIter.valLen);
+            if (0 == memcmp(&gDoxm->deviceID.id, &subject.id, sizeof(gDoxm->deviceID.id)))
             {
                 bDeviceIDMatch = true;
             }
         }
     }
 
-exit:
     return ((bOwnedQry ? bOwnedMatch : true) && (bDeviceIDQry ? bDeviceIDMatch : true));
 }
 
 static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest)
 {
-    char* jsonStr = NULL;
     OCEntityHandlerResult ehRet = OC_EH_OK;
 
-    OC_LOG (DEBUG, TAG, "Doxm EntityHandle processing GET request");
+    OIC_LOG(DEBUG, TAG, "Doxm EntityHandle processing GET request");
 
     //Checking if Get request is a query.
-    if(ehRequest->query)
+    if (ehRequest->query)
     {
-        OC_LOG (DEBUG, TAG, "HandleDoxmGetRequest processing query");
-        if(!ValidateQuery(ehRequest->query))
+        OIC_LOG(DEBUG, TAG, "HandleDoxmGetRequest processing query");
+        if (!ValidateQuery(ehRequest->query))
         {
             ehRet = OC_EH_ERROR;
         }
     }
 
     /*
-     * For GET or Valid Query request return doxm resource json payload.
+     * For GET or Valid Query request return doxm resource CBOR payload.
      * For non-valid query return NULL json payload.
-     * A device will 'always' have a default Doxm, so BinToDoxmJSON will
+     * A device will 'always' have a default Doxm, so DoxmToCBORPayload will
      * return valid doxm resource json.
      */
+    uint8_t *payload = NULL;
+    size_t size = 0;
 
-    jsonStr = (ehRet == OC_EH_OK) ? BinToDoxmJSON(gDoxm) : NULL;
+    if (ehRet == OC_EH_OK)
+    {
+        if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size))
+        {
+            payload = NULL;
+        }
+    }
 
     // Send response payload to request originator
-    if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, jsonStr))
+    if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, payload, size))
     {
-        OC_LOG (ERROR, TAG, "SendSRMResponse failed in HandleDoxmGetRequest");
+        ehRet = OC_EH_ERROR;
+        OIC_LOG(ERROR, TAG, "SendSRMResponse failed in HandleDoxmGetRequest");
     }
 
-    OICFree(jsonStr);
+    OICFree(payload);
 
     return ehRet;
 }
 
-#ifdef __WITH_DTLS__
-/*
- * Generating new credential for provisioning tool
- *
- * PSK generated by
- */
-static OCEntityHandlerResult AddOwnerPSK(const CAEndpoint_t* endpoint,
-                    OicSecDoxm_t* ptDoxm,
-                    const uint8_t* label, const size_t labelLen)
+static OCEntityHandlerResult HandleDoxmPutRequest(const OCEntityHandlerRequest * ehRequest)
 {
-    size_t ownLen = 1;
-    uint32_t outLen = 0;
-    OicSecCred_t *cred = NULL;
-    uint8_t ownerPSK[OWNER_PSK_LENGTH_128] = {};
-
-    CAResult_t pskRet = CAGenerateOwnerPSK(endpoint,
-        label, labelLen,
-        ptDoxm->owner.id, sizeof(ptDoxm->owner.id),
-        gDoxm->deviceID.id, sizeof(gDoxm->deviceID.id),
-        ownerPSK, OWNER_PSK_LENGTH_128);
-
-    VERIFY_SUCCESS(TAG, pskRet == CA_STATUS_OK, ERROR);
-
-    char base64Buff[B64ENCODE_OUT_SAFESIZE(OWNER_PSK_LENGTH_128) + 1] = {};
-    B64Result b64Ret = b64Encode(ownerPSK, OWNER_PSK_LENGTH_128, base64Buff,
-                    sizeof(base64Buff), &outLen);
-    VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
-
-    OC_LOG (DEBUG, TAG, "Doxm EntityHandle  generating Credential");
-    cred = GenerateCredential(&ptDoxm->owner, SYMMETRIC_PAIR_WISE_KEY,
-                              NULL, base64Buff, ownLen, &ptDoxm->owner);
-    VERIFY_NON_NULL(TAG, cred, ERROR);
-
-    //Adding provisioning tool credential to cred Resource.
-    VERIFY_SUCCESS(TAG, OC_STACK_OK == AddCredential(cred), ERROR);
-
-    gDoxm->owned = true;
-    gDoxm->oxmSel = ptDoxm->oxmSel;
-    memcpy(&(gDoxm->owner), &(ptDoxm->owner), sizeof(OicUuid_t));
-
-    return OC_EH_OK;
-
-exit:
-    return OC_EH_ERROR;
-}
-#endif //__WITH_DTLS__
-
-static OCEntityHandlerResult HandleDoxmPutRequest (const OCEntityHandlerRequest * ehRequest)
-{
-    OC_LOG (DEBUG, TAG, "Doxm EntityHandle  processing PUT request");
+    OIC_LOG (DEBUG, TAG, "Doxm EntityHandle  processing PUT request");
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
-    OicUuid_t emptyOwner = {.id = {0}};
+    OicUuid_t emptyOwner = {.id = {0} };
 
     /*
-     * Convert JSON Doxm data into binary. This will also validate
+     * Convert CBOR Doxm data into binary. This will also validate
      * the Doxm data received.
      */
-    OicSecDoxm_t* newDoxm = JSONToDoxmBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
+    OicSecDoxm_t *newDoxm = NULL;
 
-    if (newDoxm)
+    if (ehRequest->payload)
     {
-        // Iotivity SRM ONLY supports OIC_JUST_WORKS now
-        if (OIC_JUST_WORKS == newDoxm->oxmSel)
-        {
-            /*
-             * If current state of the device is un-owned, enable
-             * anonymous ECDH cipher in tinyDTLS so that Provisioning
-             * tool can initiate JUST_WORKS ownership transfer process.
-             */
-            if ((false == gDoxm->owned) && (false == newDoxm->owned))
-            {
-                OC_LOG (INFO, TAG, "Doxm EntityHandle  enabling AnonECDHCipherSuite");
-#ifdef __WITH_DTLS__
-                ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
-#endif //__WITH_DTLS__
-                goto exit;
-            }
+        uint8_t *payload = ((OCSecurityPayload *)ehRequest->payload)->securityData;
+        size_t size = ((OCSecurityPayload *)ehRequest->payload)->payloadSize;
+        OCStackResult res = CBORPayloadToDoxm(payload, size, &newDoxm);
 
-            /*
-             * When current state of the device is un-owned and Provisioning
-             * Tool is attempting to change the state to 'Owned' with a
-             * qualified value for the field 'Owner'
-             */
-            if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
-                (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) != 0))
+        if (newDoxm && OC_STACK_OK == res)
+        {
+            if (OIC_JUST_WORKS == newDoxm->oxmSel)
             {
-                /*
-                 * Generate OwnerPSK and create credential for Provisioning
-                 * tool with the generated OwnerPSK.
-                 * Update persistent storage and disable anonymous ECDH cipher
-                 *
-                 */
-#ifdef __WITH_DTLS__
-                OCServerRequest *request = (OCServerRequest *)ehRequest->requestHandle;
-
-                //Generating OwnerPSK
-                OC_LOG (INFO, TAG, "Doxm EntityHandle  generating OwnerPSK");
-
-                //Generate new credential for provisioning tool
-                ehRet = AddOwnerPSK((CAEndpoint_t *)&request->devAddr, newDoxm,
-                        (uint8_t*) OXM_JUST_WORKS, strlen(OXM_JUST_WORKS));
-
-                VERIFY_SUCCESS(TAG, OC_EH_OK == ehRet, ERROR);
-
-                // Update new state in persistent storage
-                if (true == UpdatePersistentStorage(gDoxm))
-                {
-                    ehRet = OC_EH_OK;
-                }
-                else
+                if ((false == gDoxm->owned) && (false == newDoxm->owned))
                 {
-                    ehRet = OC_EH_ERROR;
-
                     /*
-                     * If persistent storage update failed, revert back the state
-                     * for global variable.
+                     * If current state of the device is un-owned, enable
+                     * anonymous ECDH cipher in tinyDTLS so that Provisioning
+                     * tool can initiate JUST_WORKS ownership transfer process.
                      */
-                    gDoxm->owned = false;
-                    gDoxm->oxmSel = 0;
-                    memset(&(gDoxm->owner), 0, sizeof(OicUuid_t));
-                }
+                    if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
+                    {
+                        OIC_LOG (INFO, TAG, "Doxm EntityHandle  enabling AnonECDHCipherSuite");
+#ifdef __WITH_DTLS__
+                        ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
+#endif //__WITH_DTLS__
+                        goto exit;
+                    }
+                    else
+                    {
+#ifdef __WITH_DTLS__
+                        //Save the owner's UUID to derive owner credential
+                        memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
+
+                        // Update new state in persistent storage
+                        if (true == UpdatePersistentStorage(gDoxm))
+                        {
+                            ehRet = OC_EH_OK;
+                        }
+                        else
+                        {
+                            OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
+                            ehRet = OC_EH_ERROR;
+                        }
+
+                        /*
+                         * Disable anonymous ECDH cipher in tinyDTLS since device is now
+                         * in owned state.
+                         */
+                        CAResult_t caRes = CA_STATUS_OK;
+                        caRes = CAEnableAnonECDHCipherSuite(false);
+                        VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
+                        OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
 
-                /*
-                 * Disable anonymous ECDH cipher in tinyDTLS since device is now
-                 * in owned state.
-                 */
-                CAEnableAnonECDHCipherSuite(false);
 #ifdef __WITH_X509__
 #define TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 0xC0AE
-                CASelectCipherSuite(TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
+                        CASelectCipherSuite(TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
 #endif //__WITH_X509__
 #endif //__WITH_DTLS__
+                    }
+                }
             }
-        }
-        else if(OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
-        {
-            //this temp Credential ID is used to track temporal Cred Id
-            static OicUuid_t tmpCredId = {.id={0}};
-            static bool tmpCredGenFlag = false;
-
-            if ((false == gDoxm->owned) && (false == newDoxm->owned))
+            else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
             {
-#ifdef __WITH_DTLS__
-                CAEnableAnonECDHCipherSuite(false);
-                OC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
-                CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256);
-
-                char ranPin[OXM_RANDOM_PIN_SIZE + 1] = {0,};
-                if(OC_STACK_OK == GeneratePin(ranPin, OXM_RANDOM_PIN_SIZE + 1))
+                if ((false == gDoxm->owned) && (false == newDoxm->owned))
                 {
-                    if(tmpCredGenFlag)
+                    /*
+                     * If current state of the device is un-owned, enable
+                     * anonymous ECDH cipher in tinyDTLS so that Provisioning
+                     * tool can initiate JUST_WORKS ownership transfer process.
+                     */
+                    if(memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
                     {
-                       OC_LOG(INFO, TAG, "Corrupted PSK is detected!!!");
-                       VERIFY_SUCCESS(TAG,
-                                      OC_STACK_RESOURCE_DELETED == RemoveCredential(&tmpCredId),
-                                      ERROR);
-                    }
-
-                    OCStackResult res = AddTmpPskWithPIN( &(newDoxm->owner), SYMMETRIC_PAIR_WISE_KEY,
-                                     ranPin, OXM_RANDOM_PIN_SIZE, 1, &(newDoxm->owner), &tmpCredId);
-                    VERIFY_SUCCESS(TAG, res == OC_STACK_OK, ERROR);
-                    tmpCredGenFlag = true;
-                    ehRet = OC_EH_OK;
-                }
-                else
-                {
-                    OC_LOG(ERROR, TAG, "Failed to generate random PIN");
-                    ehRet = OC_EH_ERROR;
-                }
+                        gDoxm->oxmSel = newDoxm->oxmSel;
+                        //Update new state in persistent storage
+                        if ((UpdatePersistentStorage(gDoxm) == true))
+                        {
+                            ehRet = OC_EH_OK;
+                        }
+                        else
+                        {
+                            OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
+                            ehRet = OC_EH_ERROR;
+                        }
 
+#ifdef __WITH_DTLS__
+                        CAResult_t caRes = CA_STATUS_OK;
+
+                        caRes = CAEnableAnonECDHCipherSuite(false);
+                        VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
+                        OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
+
+                        caRes = CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256);
+                        VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
+
+                        char ranPin[OXM_RANDOM_PIN_SIZE + 1] = {0,};
+                        if(OC_STACK_OK == GeneratePin(ranPin, OXM_RANDOM_PIN_SIZE + 1))
+                        {
+                            //Set the device id to derive temporal PSK
+                            SetUuidForRandomPinOxm(&gDoxm->deviceID);
+
+                            /**
+                             * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
+                             * Credential should not be saved into SVR.
+                             * For this reason, use a temporary get_psk_info callback to random PIN OxM.
+                             */
+                            caRes = CARegisterDTLSCredentialsHandler(GetDtlsPskForRandomPinOxm);
+                            VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
+                            ehRet = OC_EH_OK;
+                        }
+                        else
+                        {
+                            OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
+                            ehRet = OC_EH_ERROR;
+                        }
 #endif //__WITH_DTLS__
+                    }
+                    else
+                    {
+#ifdef __WITH_DTLS__
+                        //Save the owner's UUID to derive owner credential
+                        memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
+
+                        //Update new state in persistent storage
+                        if (UpdatePersistentStorage(gDoxm) == true)
+                        {
+                            ehRet = OC_EH_OK;
+                        }
+                        else
+                        {
+                            OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
+                            ehRet = OC_EH_ERROR;
+                        }
+#endif
+                    }
+                }
             }
 
             /*
@@ -639,63 +732,98 @@ static OCEntityHandlerResult HandleDoxmPutRequest (const OCEntityHandlerRequest
              * qualified value for the field 'Owner'
              */
             if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
-                (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) != 0))
+                    (memcmp(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)) == 0))
             {
-#ifdef __WITH_DTLS__
-                OCServerRequest * request = (OCServerRequest *)ehRequest->requestHandle;
-
-                //Remove Temporal Credential resource
-                if(tmpCredGenFlag)
+                //Change the SVR's resource owner as owner device.
+                OCStackResult ownerRes = SetAclRownerId(&gDoxm->owner);
+                if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
+                {
+                    ehRet = OC_EH_ERROR;
+                    goto exit;
+                }
+                ownerRes = SetAmaclRownerId(&gDoxm->owner);
+                if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
+                {
+                    ehRet = OC_EH_ERROR;
+                    goto exit;
+                }
+                ownerRes = SetCredRownerId(&gDoxm->owner);
+                if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
                 {
-                    VERIFY_SUCCESS(TAG,
-                                   OC_STACK_RESOURCE_DELETED == RemoveCredential(&tmpCredId),
-                                   ERROR);
-                    tmpCredGenFlag = false;
+                    ehRet = OC_EH_ERROR;
+                    goto exit;
+                }
+                ownerRes = SetPstatRownerId(&gDoxm->owner);
+                if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
+                {
+                    ehRet = OC_EH_ERROR;
+                    goto exit;
+                }
+                ownerRes = SetDpairingRownerId(&gDoxm->owner);
+                if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
+                {
+                    ehRet = OC_EH_ERROR;
+                    goto exit;
+                }
+                ownerRes = SetPconfRownerId(&gDoxm->owner);
+                if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
+                {
+                    ehRet = OC_EH_ERROR;
+                    goto exit;
                 }
 
-                //Generate new credential for provisioning tool
-                ehRet = AddOwnerPSK((CAEndpoint_t*)(&request->devAddr), newDoxm,
-                                    (uint8_t*)OXM_RANDOM_DEVICE_PIN, strlen(OXM_RANDOM_DEVICE_PIN));
-                VERIFY_SUCCESS(TAG, OC_EH_OK == ehRet, ERROR);
+                gDoxm->owned = true;
+                memcpy(&gDoxm->rownerID, &gDoxm->owner, sizeof(OicUuid_t));
 
-                //Update new state in persistent storage
-                if((UpdatePersistentStorage(gDoxm) == true))
+                // Update new state in persistent storage
+                if (UpdatePersistentStorage(gDoxm))
                 {
-                    ehRet = OC_EH_OK;
+                    //Update default ACL of security resource to prevent anonymous user access.
+                    if(OC_STACK_OK == UpdateDefaultSecProvACL())
+                    {
+                        ehRet = OC_EH_OK;
+                    }
+                    else
+                    {
+                        OIC_LOG(ERROR, TAG, "Failed to remove default ACL for security provisioning");
+                        ehRet = OC_EH_ERROR;
+                    }
                 }
                 else
                 {
-                    /*
-                     * If persistent storage update failed, revert back the state
-                     * for global variable.
-                     */
-                    gDoxm->owned = false;
-                    gDoxm->oxmSel = 0;
-                    memset(&(gDoxm->owner), 0, sizeof(OicUuid_t));
+                    OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
                     ehRet = OC_EH_ERROR;
-
                 }
-#endif
-             }
+            }
         }
     }
 
 exit:
+    if(OC_EH_OK != ehRet)
+    {
+        OIC_LOG(WARNING, TAG, "The operation failed during handle DOXM request,"\
+                            "DOXM will be reverted.");
+
+        /*
+         * If some error is occured while ownership transfer,
+         * ownership transfer related resource should be revert back to initial status.
+         */
+        RestoreDoxmToInitState();
+        RestorePstatToInitState();
+    }
 
     //Send payload to request originator
-    if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL))
+    if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL, 0))
     {
-        OC_LOG (ERROR, TAG, "SendSRMResponse failed in HandlePstatPostRequest");
+        ehRet = OC_EH_ERROR;
+        OIC_LOG(ERROR, TAG, "SendSRMResponse failed in HandleDoxmPostRequest");
     }
     DeleteDoxmBinData(newDoxm);
 
     return ehRet;
 }
 
-/*
- * This internal method is the entity handler for DOXM resources.
- */
-OCEntityHandlerResult DoxmEntityHandler (OCEntityHandlerFlag flag,
+OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
                                         OCEntityHandlerRequest * ehRequest,
                                         void* callbackParam)
 {
@@ -707,10 +835,10 @@ OCEntityHandlerResult DoxmEntityHandler (OCEntityHandlerFlag flag,
         return ehRet;
     }
 
-
     if (flag & OC_REQUEST_FLAG)
     {
-        OC_LOG (DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
+        OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
+
         switch (ehRequest->method)
         {
             case OC_REST_GET:
@@ -723,7 +851,7 @@ OCEntityHandlerResult DoxmEntityHandler (OCEntityHandlerFlag flag,
 
             default:
                 ehRet = OC_EH_ERROR;
-                SendSRMResponse(ehRequest, ehRet, NULL);
+                SendSRMResponse(ehRequest, ehRet, NULL, 0);
                 break;
         }
     }
@@ -731,24 +859,20 @@ OCEntityHandlerResult DoxmEntityHandler (OCEntityHandlerFlag flag,
     return ehRet;
 }
 
-/*
- * This internal method is used to create '/oic/sec/doxm' resource.
- */
 OCStackResult CreateDoxmResource()
 {
-    OCStackResult ret;
-
-    ret = OCCreateResource(&gDoxmHandle,
-                           OIC_RSRC_TYPE_SEC_DOXM,
-                           OIC_MI_DEF,
-                           OIC_RSRC_DOXM_URI,
-                           DoxmEntityHandler,
-                           NULL,
-                           OC_OBSERVABLE | OC_SECURE | OC_EXPLICIT_DISCOVERABLE);
+    OCStackResult ret = OCCreateResource(&gDoxmHandle,
+                                         OIC_RSRC_TYPE_SEC_DOXM,
+                                         OIC_MI_DEF,
+                                         OIC_RSRC_DOXM_URI,
+                                         DoxmEntityHandler,
+                                         NULL,
+                                         OC_OBSERVABLE | OC_SECURE |
+                                         OC_EXPLICIT_DISCOVERABLE);
 
     if (OC_STACK_OK != ret)
     {
-        OC_LOG (FATAL, TAG, "Unable to instantiate Doxm resource");
+        OIC_LOG (FATAL, TAG, "Unable to instantiate Doxm resource");
         DeInitDoxmResource();
     }
     return ret;
@@ -758,7 +882,6 @@ OCStackResult CreateDoxmResource()
  * Checks if DeviceID is generated during provisioning for the new device.
  * If DeviceID is NULL then generates the new DeviceID.
  * Once DeviceID is assigned to the device it does not change for the lifetime of the device.
- *
  */
 static OCStackResult CheckDeviceID()
 {
@@ -777,15 +900,15 @@ static OCStackResult CheckDeviceID()
     {
         if (OCGenerateUuid(gDoxm->deviceID.id) != RAND_UUID_OK)
         {
-            OC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
+            OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
             return ret;
         }
         ret = OC_STACK_OK;
 
-        if (UpdatePersistentStorage(gDoxm))
+        if (!UpdatePersistentStorage(gDoxm))
         {
             //TODO: After registering PSI handler in all samples, do ret = OC_STACK_OK here.
-            OC_LOG(FATAL, TAG, "UpdatePersistentStorage failed!");
+            OIC_LOG(FATAL, TAG, "UpdatePersistentStorage failed!");
         }
     }
     else
@@ -797,81 +920,80 @@ static OCStackResult CheckDeviceID()
 
 /**
  * Get the default value.
- * @retval  the gDefaultDoxm pointer;
+ *
+ * @return the default value of doxm, @ref OicSecDoxm_t.
  */
 static OicSecDoxm_t* GetDoxmDefault()
 {
-    OC_LOG (DEBUG, TAG, "GetDoxmToDefault");
+    OIC_LOG(DEBUG, TAG, "GetDoxmToDefault");
     return &gDefaultDoxm;
 }
 
-/**
- * This method is used by SRM to retrieve DOXM resource data.
- *
- * @retval  reference to @ref OicSecDoxm_t, binary format of Doxm resource data
- */
 const OicSecDoxm_t* GetDoxmResourceData()
 {
     return gDoxm;
 }
 
-/**
- * Initialize DOXM resource by loading data from persistent storage.
- *
- * @retval  OC_STACK_OK for Success, otherwise some error value
- */
 OCStackResult InitDoxmResource()
 {
     OCStackResult ret = OC_STACK_ERROR;
 
     //Read DOXM resource from PS
-    char* jsonSVRDatabase = GetSVRDatabase();
-    if(jsonSVRDatabase)
+    uint8_t *data = NULL;
+    size_t size = 0;
+    ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_DOXM_NAME, &data, &size);
+    // If database read failed
+    if (OC_STACK_OK != ret)
+    {
+       OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
+    }
+    if (data)
     {
-        //Convert JSON DOXM into binary format
-        gDoxm = JSONToDoxmBin(jsonSVRDatabase);
+       // Read DOXM resource from PS
+       ret = CBORPayloadToDoxm(data, size, &gDoxm);
     }
     /*
      * If SVR database in persistent storage got corrupted or
      * is not available for some reason, a default doxm is created
      * which allows user to initiate doxm provisioning again.
      */
-    if(!jsonSVRDatabase || !gDoxm)
+     if ((OC_STACK_OK != ret) || !data || !gDoxm)
     {
         gDoxm = GetDoxmDefault();
     }
+
+    //In case of the server is shut down unintentionally, we should initialize the owner
+    if(false == gDoxm->owned)
+    {
+        OicUuid_t emptyUuid = {.id={0}};
+        memcpy(&gDoxm->owner, &emptyUuid, sizeof(OicUuid_t));
+    }
+
     ret = CheckDeviceID();
     if (ret == OC_STACK_OK)
     {
+        OIC_LOG_V(DEBUG, TAG, "Initial Doxm Owned = %d", gDoxm->owned);
         //Instantiate 'oic.sec.doxm'
         ret = CreateDoxmResource();
     }
     else
     {
-        OC_LOG (ERROR, TAG, "CheckDeviceID failed");
+        OIC_LOG (ERROR, TAG, "CheckDeviceID failed");
     }
-    OICFree(jsonSVRDatabase);
+    OICFree(data);
     return ret;
 }
 
-/**
- * Perform cleanup for DOXM resources.
- *
- * @return
- * OC_STACK_OK    - no error
- * OC_STACK_ERROR - stack process error
- *
- */
 OCStackResult DeInitDoxmResource()
 {
     OCStackResult ret = OCDeleteResource(gDoxmHandle);
-    if(gDoxm  != &gDefaultDoxm)
+    if (gDoxm  != &gDefaultDoxm)
     {
         DeleteDoxmBinData(gDoxm);
     }
     gDoxm = NULL;
 
-    if(OC_STACK_OK == ret)
+    if (OC_STACK_OK == ret)
     {
         return OC_STACK_OK;
     }
@@ -881,15 +1003,9 @@ OCStackResult DeInitDoxmResource()
     }
 }
 
-
-/**
- * This method returns the SRM device ID for this device.
- *
- * @retval  OC_STACK_OK for Success, otherwise some error value
- */
 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
 {
-    if(deviceID && gDoxm)
+    if (deviceID && gDoxm)
     {
        *deviceID = gDoxm->deviceID;
         return OC_STACK_OK;
@@ -897,20 +1013,54 @@ OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
     return OC_STACK_ERROR;
 }
 
-/**
- * @brief Gets the OicUuid_t value for the owner of this device.
- *
- * @return OC_STACK_OK if devOwner is a valid UUID, otherwise OC_STACK_ERROR.
- */
-OCStackResult GetDoxmDevOwnerId(OicUuid_t *devOwner)
+OCStackResult GetDoxmDevOwnerId(OicUuid_t *devownerid)
 {
     OCStackResult retVal = OC_STACK_ERROR;
-    if(gDoxm)
+    if (gDoxm)
     {
-        if(gDoxm->owned) {
-            *devOwner = gDoxm->owner; // TODO change to devOwner when available
+        OIC_LOG_V(DEBUG, TAG, "GetDoxmDevOwnerId(): gDoxm owned =  %d.", \
+            gDoxm->owned);
+        if (gDoxm->owned)
+        {
+            *devownerid = gDoxm->owner;
             retVal = OC_STACK_OK;
         }
     }
     return retVal;
 }
+
+OCStackResult GetDoxmRownerId(OicUuid_t *rowneruuid)
+{
+    OCStackResult retVal = OC_STACK_ERROR;
+    if (gDoxm)
+    {
+        if( gDoxm->owned )
+        {
+            *rowneruuid = gDoxm->rownerID;
+                    retVal = OC_STACK_OK;
+        }
+    }
+    return retVal;
+}
+
+/**
+ * Function to restore doxm resurce to initial status.
+ * This function will use in case of error while ownership transfer
+ */
+void RestoreDoxmToInitState()
+{
+    if(gDoxm)
+    {
+        OIC_LOG(INFO, TAG, "DOXM resource will revert back to initial status.");
+
+        OicUuid_t emptyUuid = {.id={0}};
+        memcpy(&(gDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
+        gDoxm->owned = false;
+        gDoxm->oxmSel = OIC_JUST_WORKS;
+
+        if(!UpdatePersistentStorage(gDoxm))
+        {
+            OIC_LOG(ERROR, TAG, "Failed to revert DOXM in persistent storage");
+        }
+    }
+}
diff --git a/resource/csdk/security/src/dpairingresource.c b/resource/csdk/security/src/dpairingresource.c
new file mode 100644 (file)
index 0000000..0c5c03f
--- /dev/null
@@ -0,0 +1,762 @@
+/* *****************************************************************
+ *
+ * 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 <stdlib.h>
+#include <string.h>
+#include "ocstack.h"
+#include "logger.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+#include "cJSON.h"
+#include "base64.h"
+#include "resourcemanager.h"
+#include "dpairingresource.h"
+#include "psinterface.h"
+#include "utlist.h"
+#include "srmresourcestrings.h"
+#include "cainterface.h"
+#include "doxmresource.h"
+#include "pconfresource.h"
+#include "credresource.h"
+#include "aclresource.h"
+#include "srmutility.h"
+#include "ocserverrequest.h"
+#include "ocpayloadcbor.h"
+#include "ocpayload.h"
+#include "payload_logging.h"
+#include <stdlib.h>
+#ifdef WITH_ARDUINO
+#include <string.h>
+#else
+#include <strings.h>
+#endif
+
+#ifdef __WITH_DTLS__
+#include "global.h"
+#endif
+
+#define TAG  "SRM-DPAIRING"
+
+/** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
+ * The value of payload size is increased until reaching belox max cbor size. */
+static const uint16_t CBOR_SIZE = 1024;
+
+/** Max cbor size payload. */
+static const uint16_t CBOR_MAX_SIZE = 4400;
+
+/** DOXM Map size - Number of mandatory items. */
+static const uint8_t DPAIR_MAP_SIZE = 3;
+
+static OicSecDpairing_t     *gDpair = NULL;
+static OCResourceHandle   gDpairHandle = NULL;
+static OicSecDpairing_t      gDefaultDpair =
+{
+    PRM_NOT_ALLOWED,       /* OicSecPrm_t spm */
+    {.id = {0}},                   /* OicUuid_t pdeviceID */
+    {.id = {0}},                   /* OicUuid_t rowner */
+};
+
+void DeleteDpairingBinData(OicSecDpairing_t* dpair)
+{
+    if (dpair)
+    {
+        //Clean dpairing itself
+        OICFree(dpair);
+    }
+}
+
+/**
+ * Get the default value.
+ * @retval  the gDefaultDpair pointer;
+ */
+static OicSecDpairing_t* GetDpairingDefault()
+{
+    OIC_LOG (DEBUG, TAG, "GetDpairingDefault");
+
+    return &gDefaultDpair;
+}
+
+/**
+ * This method is used by SRM to retrieve Dpairing resource data..
+ */
+void SetDpairingResourceOwner(OicUuid_t *rowner)
+{
+    OIC_LOG (DEBUG, TAG, "SetDpairingResourceOwner");
+    if (gDpair)
+    {
+        memcpy(&gDpair->rownerID, rowner, sizeof(OicUuid_t));
+    }
+}
+
+#ifdef __WITH_DTLS__
+/**
+ * Function to save PairingPSK.
+ *
+ * @param[in] endpoint   current endpoint.
+ * @param[in] peerDevID   peer device indentitiy.
+ * @param[in] isPairingServer   indicate if it generates PairingPSK for server or client.
+ *
+ * @return  OC_STACK_OK on success
+ */
+OCStackResult SavePairingPSK(OCDevAddr *endpoint,
+            OicUuid_t *peerDevID, OicUuid_t *owner, bool isPairingServer)
+{
+    OIC_LOG(DEBUG, TAG, "IN SavePairingPSK");
+
+    if(NULL == endpoint || NULL == peerDevID || NULL == owner)
+    {
+        OIC_LOG_V(ERROR, TAG, "Invalid Input parameters in [%s]\n", __FUNCTION__);
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCStackResult res = OC_STACK_ERROR;
+
+    OicUuid_t ptDeviceID = {.id={0}};
+    if (OC_STACK_OK != GetDoxmDeviceID(&ptDeviceID))
+    {
+        OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
+        return res;
+    }
+
+    uint8_t pairingPSK[OWNER_PSK_LENGTH_128] = {0};
+    OicSecKey_t pairingKey = {pairingPSK, OWNER_PSK_LENGTH_128};
+
+    //Generating PairingPSK using OwnerPSK scheme
+    CAResult_t pskRet = CAGenerateOwnerPSK((const CAEndpoint_t *)endpoint,
+            (uint8_t *)OIC_RSRC_TYPE_SEC_DPAIRING,
+            strlen(OIC_RSRC_TYPE_SEC_DPAIRING),
+            (isPairingServer ? ptDeviceID.id : peerDevID->id), sizeof(OicUuid_t), // server
+            (isPairingServer ? peerDevID->id : ptDeviceID.id), sizeof(OicUuid_t), // client
+            pairingPSK, OWNER_PSK_LENGTH_128);
+
+    if (CA_STATUS_OK == pskRet)
+    {
+        OIC_LOG(INFO, TAG, "pairingPSK dump:\n");
+        OIC_LOG_BUFFER(INFO, TAG, pairingPSK, OWNER_PSK_LENGTH_128);
+        //Generating new credential for direct-pairing client
+
+        OicSecCred_t *cred = GenerateCredential(peerDevID,
+                SYMMETRIC_PAIR_WISE_KEY, NULL,
+                &pairingKey, owner);
+        VERIFY_NON_NULL(TAG, cred, ERROR);
+
+        res = AddCredential(cred);
+        if(res != OC_STACK_OK)
+        {
+            DeleteCredList(cred);
+            return res;
+        }
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "CAGenerateOwnerPSK failed");
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT SavePairingPSK");
+exit:
+    return res;
+}
+#endif // __WITH_DTLS__
+
+OCStackResult DpairingToCBORPayload(const OicSecDpairing_t *dpair, uint8_t **payload, size_t *size)
+{
+    if (NULL == dpair || NULL == payload || NULL != *payload || NULL == size)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    size_t cborLen = *size;
+    if (0 == cborLen)
+    {
+        cborLen = CBOR_SIZE;
+    }
+
+    *payload = NULL;
+    *size = 0;
+
+    OCStackResult ret = OC_STACK_ERROR;
+
+    CborEncoder encoder;
+    CborEncoder dpairMap;
+
+    int64_t cborEncoderResult = CborNoError;
+    uint8_t mapSize = DPAIR_MAP_SIZE;
+
+    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
+    VERIFY_NON_NULL(TAG, outPayload, ERROR);
+    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
+
+    cborEncoderResult = cbor_encoder_create_map(&encoder, &dpairMap, mapSize);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Creating DPAIRING Map");
+
+    //spm -- Mandatory
+    cborEncoderResult = cbor_encode_text_string(&dpairMap, OIC_JSON_SPM_NAME,
+        strlen(OIC_JSON_SPM_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SPM name tag");
+    cborEncoderResult = cbor_encode_int(&dpairMap, dpair->spm);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SPM value");
+
+    //PDEVICEID -- Mandatory
+    cborEncoderResult = cbor_encode_text_string(&dpairMap, OIC_JSON_PDEVICE_ID_NAME,
+        strlen(OIC_JSON_PDEVICE_ID_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PDeviceID tag");
+    {
+        char *deviceId = NULL;
+        ret = ConvertUuidToStr(&dpair->pdeviceID, &deviceId);
+        VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
+        cborEncoderResult = cbor_encode_text_string(&dpairMap, deviceId, strlen(deviceId));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to encode PDeviceID value");
+        OICFree(deviceId);
+    }
+
+    //ROWNER -- Mandatory
+    {
+        char *rowner = NULL;
+        cborEncoderResult = cbor_encode_text_string(&dpairMap, OIC_JSON_ROWNERID_NAME,
+            strlen(OIC_JSON_ROWNERID_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROWNER tag");
+        ret = ConvertUuidToStr(&dpair->rownerID, &rowner);
+        VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
+        cborEncoderResult = cbor_encode_text_string(&dpairMap, rowner, strlen(rowner));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Rowner ID value");
+        OICFree(rowner);
+    }
+
+    cborEncoderResult = cbor_encoder_close_container(&encoder, &dpairMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to close dpairMap");
+
+     if (CborNoError == cborEncoderResult)
+    {
+        *size = encoder.ptr - outPayload;
+        *payload = outPayload;
+        ret = OC_STACK_OK;
+    }
+
+exit:
+    if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
+    {
+       // reallocate and try again!
+       OICFree(outPayload);
+       // Since the allocated initial memory failed, double the memory.
+       cborLen += encoder.ptr - encoder.end;
+       cborEncoderResult = CborNoError;
+       ret = DpairingToCBORPayload(dpair, payload, &cborLen);
+       *size = cborLen;
+    }
+
+    if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
+    {
+       OICFree(outPayload);
+       outPayload = NULL;
+       *payload = NULL;
+       *size = 0;
+       ret = OC_STACK_ERROR;
+    }
+
+    return ret;
+}
+
+OCStackResult CBORPayloadToDpair(const uint8_t *cborPayload, size_t size,
+                                OicSecDpairing_t **secDpair)
+{
+    if (NULL == cborPayload || NULL == secDpair || NULL != *secDpair || 0 == size)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCStackResult ret = OC_STACK_ERROR;
+    *secDpair = NULL;
+
+    CborValue dpairCbor = { .parser = NULL };
+    CborParser parser = { .end = NULL };
+    CborError cborFindResult = CborNoError;
+
+    cbor_parser_init(cborPayload, size, 0, &parser, &dpairCbor);
+    CborValue dpairMap = { .parser = NULL };
+    OicSecDpairing_t *dpair = NULL;
+    cborFindResult = cbor_value_enter_container(&dpairCbor, &dpairMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering DPairing Map");
+
+    dpair = (OicSecDpairing_t *)OICCalloc(1, sizeof(*dpair));
+    VERIFY_NON_NULL(TAG, dpair, ERROR);
+
+    while (cbor_value_is_valid(&dpairMap))
+    {
+        char *name = NULL;
+        size_t len = 0;
+        CborType type = CborInvalidType;
+        cborFindResult = cbor_value_dup_text_string(&dpairMap, &name, &len, NULL);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding tag name");
+        cborFindResult = cbor_value_advance(&dpairMap);
+        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))
+        {
+            cborFindResult = cbor_value_get_int(&dpairMap, (int *) &dpair->spm);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SPM Value");
+        }
+
+        if (0 == strcmp(OIC_JSON_PDEVICE_ID_NAME, name))
+        {
+            char *id = NULL;
+            cborFindResult = cbor_value_dup_text_string(&dpairMap, &id, &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding PDeviceID value");
+            ret = ConvertStrToUuid(id, &dpair->pdeviceID);
+            VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
+            OICFree(id);
+        }
+
+        if (0 == strcmp(OIC_JSON_ROWNERID_NAME, name))
+        {
+            char *id = NULL;
+            cborFindResult = cbor_value_dup_text_string(&dpairMap, &id, &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding RownerID value");
+            ret = ConvertStrToUuid(id, &dpair->rownerID);
+            VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
+            OICFree(id);
+        }
+
+        if (CborMapType != type && cbor_value_is_valid(&dpairMap))
+        {
+            cborFindResult = cbor_value_advance(&dpairMap);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing the Dpair Map");
+        }
+        OICFree(name);
+    }
+
+    *secDpair = dpair;
+    ret = OC_STACK_OK;
+
+exit:
+    if (CborNoError != cborFindResult)
+    {
+        OIC_LOG (ERROR, TAG, "CBORPayloadToDoxm failed");
+        DeleteDpairingBinData(dpair);
+        dpair = NULL;
+        *secDpair = NULL;
+        ret = OC_STACK_ERROR;
+    }
+    return ret;
+}
+/**
+ * Function to handle the handshake result in Direct-Pairing.
+ * This function will be invoked after DTLS handshake
+ * @param   endPoint  [IN] The remote endpoint.
+ * @param   errorInfo [IN] Error information from the endpoint.
+ * @return  NONE
+ */
+void DPairingDTLSHandshakeCB(const CAEndpoint_t *endpoint, const CAErrorInfo_t *info)
+{
+    OIC_LOG_V(INFO, TAG, "IN DPairingDTLSHandshakeCB");
+
+    if(gDpair && endpoint && info)
+    {
+        OIC_LOG_V(INFO, TAG, "Received status from remote device(%s:%d) : %d",
+                 endpoint->addr, endpoint->port, info->result);
+
+        if(CA_STATUS_OK == info->result)
+        {
+            OIC_LOG(INFO, TAG, "DPairingDTLSHandshakeCB - Connection success.");
+        }
+        else if(CA_DTLS_AUTHENTICATION_FAILURE == info->result)
+        {
+            OIC_LOG(INFO, TAG, "DPairingDTLSHandshakeCB - Authentication failed");
+
+        }
+
+#ifdef __WITH_DTLS__
+        CARegisterDTLSHandshakeCallback(NULL);
+#endif // __WITH_DTLS__
+
+        // delete temporary key
+        RemoveCredential(&gDpair->pdeviceID);
+    }
+
+    OIC_LOG_V(INFO, TAG, "OUT DPairingDTLSHandshakeCB");
+}
+
+static OCEntityHandlerResult HandleDpairingPostRequest (const OCEntityHandlerRequest * ehRequest)
+{
+    OIC_LOG (DEBUG, TAG, "Dpairing EntityHandle  processing POST request");
+    OCEntityHandlerResult ehRet = OC_EH_ERROR;
+    OicSecDpairing_t* newDpair = NULL;
+    OCStackResult res = OC_STACK_OK;
+
+    const OicSecPconf_t *pconf = GetPconfResourceData();
+    if (true == pconf->edp)
+    {
+        uint8_t *payload = ((OCSecurityPayload*)ehRequest->payload)->securityData;
+        size_t size = ((OCSecurityPayload*)ehRequest->payload)->payloadSize;
+        if (payload)
+        {
+            res = CBORPayloadToDpair(payload, size, &newDpair);
+        }
+    }
+    else
+    {
+        OIC_LOG (DEBUG, TAG, "EDP == false : Direct-Pairing Disabled");
+        ehRet = OC_EH_ERROR;
+    }
+
+    if (OC_STACK_OK == res && newDpair && false == IsPairedDevice(&newDpair->pdeviceID))
+    {
+        // Check if valid Post request
+        bool prmMached = false;
+        for (size_t i=0; i<pconf->prmLen; i++)
+        {
+            if (newDpair->spm == pconf->prm[i])
+            {
+                prmMached = true;
+                break;
+            }
+        }
+        OIC_LOG_V(DEBUG, TAG, "Parsed spm is %s", prmMached ? "valid" :
+                "invalid, send error response");
+
+        // Update local Dpairing with new Dpairing & prepare dtls session
+        if (prmMached && '\0' != (char)newDpair->pdeviceID.id[0])
+        {
+            if(!gDpair)
+            {
+                gDpair = GetDpairingDefault();
+            }
+            gDpair->spm = newDpair->spm;
+            memcpy(&gDpair->pdeviceID, &newDpair->pdeviceID, sizeof(OicUuid_t));
+            memcpy(&gDpair->rownerID, &pconf->rownerID, sizeof(OicUuid_t));
+
+#ifdef __WITH_DTLS__
+            // Add temporary psk
+            OCStackResult res;
+            OicUuid_t subjectId = {.id={0}};
+            res = AddTmpPskWithPIN(&gDpair->pdeviceID,
+                           SYMMETRIC_PAIR_WISE_KEY,
+                           (char*)pconf->pin.val, DP_PIN_LENGTH,
+                           &gDpair->rownerID, &subjectId);
+            if(res != OC_STACK_OK ||
+                    memcmp(&gDpair->pdeviceID, &subjectId, sizeof(OicUuid_t)))
+            {
+                OIC_LOG_V(ERROR, TAG, "Failed to save the temporal PSK : %d", res);
+                goto exit;
+            }
+
+            // Prepare to establish a secure channel with Pin-based PSK cipher suite
+            if (CA_STATUS_OK != CAEnableAnonECDHCipherSuite(false) ||
+                CA_STATUS_OK != CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256))
+            {
+                OIC_LOG_V(ERROR, TAG, "Failed to select TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256");
+                goto exit;
+            }
+
+            if(CA_STATUS_OK != CARegisterDTLSHandshakeCallback(DPairingDTLSHandshakeCB))
+            {
+                OIC_LOG(WARNING, TAG, "DirectPairingHandler : Failed to register"
+                        " DTLS handshake callback.");
+                goto exit;
+            }
+#endif // __WITH_DTLS__
+
+            // should be lock /oic/sec/dpairing resource if Direct-Pairing starts normally ?
+            OIC_LOG (DEBUG, TAG, "/oic/sec/dpairing resource created");
+
+            ehRet = OC_EH_RESOURCE_CREATED;
+        }
+        else
+        {
+            OIC_LOG(ERROR, TAG, "Error in request check");
+        }
+    }
+
+
+#ifdef __WITH_DTLS__
+exit:
+#endif // __WITH_DTLS__
+
+    // Send payload to request originator
+    if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL, 0))
+    {
+        ehRet = OC_EH_ERROR;
+        OIC_LOG (ERROR, TAG, "SendSRMResponse failed in HandleDpairingPostRequest");
+    }
+
+    if (OC_EH_ERROR == ehRet && gDpair)
+    {
+        RemoveCredential(&gDpair->pdeviceID);
+        gDpair = NULL;
+    }
+
+    DeleteDpairingBinData(newDpair);
+    OIC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
+    return ehRet;
+}
+
+static OCEntityHandlerResult HandleDpairingPutRequest (const OCEntityHandlerRequest * ehRequest)
+{
+    OIC_LOG (DEBUG, TAG, "Dpairing EntityHandle  processing PUT request (Comfirmation)");
+
+    OCEntityHandlerResult ehRet = OC_EH_ERROR;
+    OicSecDpairing_t* newDpair = NULL;
+    OCStackResult res = OC_STACK_OK;
+
+    const OicSecPconf_t *pconf = GetPconfResourceData();
+    if (true == pconf->edp)
+    {
+        uint8_t *payload = ((OCSecurityPayload*)ehRequest->payload)->securityData;
+        size_t size = ((OCSecurityPayload*)ehRequest->payload)->payloadSize;
+        if (payload)
+        {
+            res = CBORPayloadToDpair(payload, size, &newDpair);
+        }
+
+    }
+    else
+    {
+        OIC_LOG (DEBUG, TAG, "EDP == false : Direct-Pairing Disabled");
+        ehRet = OC_EH_ERROR;
+    }
+
+
+    if ((OC_STACK_OK == res) && gDpair && newDpair)
+    {
+        OIC_LOG(DEBUG, TAG, "Received direct-pairing finalization request");
+
+        // Check if valid Put request
+        VERIFY_SUCCESS(TAG, PRM_NOT_ALLOWED == newDpair->spm, ERROR);
+
+        const OicSecPconf_t *pconf = GetPconfResourceData();
+        VERIFY_NON_NULL(TAG, pconf, ERROR);
+
+#ifdef __WITH_DTLS__
+        OCServerRequest * request = (OCServerRequest *)ehRequest->requestHandle;
+        VERIFY_SUCCESS(TAG, (request->devAddr.flags | OC_FLAG_SECURE), ERROR);
+
+        //Generate new credential
+        OIC_LOG_V(INFO, TAG, "SavePairingPSK for %s(%d)", request->devAddr.addr,
+                request->devAddr.port);
+        OCStackResult res = SavePairingPSK(&request->devAddr, &newDpair->pdeviceID,
+                (OicUuid_t *)&pconf->rownerID, true);
+        VERIFY_SUCCESS(TAG, OC_STACK_OK == res, ERROR);
+#endif //__WITH_DTLS__
+
+        //Generate new acl
+        OicSecPdAcl_t *pdAcl;
+        LL_FOREACH(pconf->pdacls, pdAcl)
+        {
+            OicSecAcl_t acl;
+            memset(&acl, 0, sizeof(OicSecAcl_t));
+            memcpy(&acl.subject, &gDpair->pdeviceID, sizeof(OicUuid_t));
+            acl.resources = pdAcl->resources;
+            acl.resourcesLen = pdAcl->resourcesLen;
+            memcpy(&acl.rownerID, &pconf->rownerID, sizeof(OicUuid_t));
+            acl.permission = pdAcl->permission;
+            acl.periods = pdAcl->periods;
+            acl.recurrences = pdAcl->recurrences;
+            acl.prdRecrLen = pdAcl->prdRecrLen;
+
+            size_t size = 0;
+            uint8_t *payload = NULL;
+            if (OC_STACK_OK == AclToCBORPayload(&acl, &payload, &size))
+            {
+                InstallNewACL(payload, size);
+                OICFree(payload);
+            }
+        }
+
+        //update pconf device list
+        AddPairedDevice(&newDpair->pdeviceID);
+
+        //Initialize dpairing resource
+        gDpair = NULL;
+
+        OIC_LOG (DEBUG, TAG, "/oic/sec/dpairing resource updated,"
+                "direct-pairing finalization success");
+        ehRet = OC_EH_OK;
+    }
+
+exit:
+
+    //Send payload to request originator
+    if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL, 0))
+    {
+        ehRet = OC_EH_ERROR;
+        OIC_LOG (ERROR, TAG, "SendSRMResponse failed in HandleDpairingPutRequest");
+    }
+
+    DeleteDpairingBinData(newDpair);
+    OIC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
+    return ehRet;
+}
+/*
+ * This internal method is the entity handler for Dpairing resources and
+ * will handle REST request (GET/POST) for them.
+ */
+OCEntityHandlerResult DpairingEntityHandler (OCEntityHandlerFlag flag,
+                                        OCEntityHandlerRequest * ehRequest,
+                                        void* callbackParameter)
+{
+    OIC_LOG(DEBUG, TAG, "Received request DpairingEntityHandler");
+    (void)callbackParameter;
+    OCEntityHandlerResult ehRet = OC_EH_ERROR;
+
+    if (!ehRequest)
+    {
+        return ehRet;
+    }
+
+    if (flag & OC_REQUEST_FLAG)
+    {
+        OIC_LOG (DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
+        switch (ehRequest->method)
+        {
+            case OC_REST_GET:
+                break;
+
+            case OC_REST_POST:
+                ehRet = HandleDpairingPostRequest(ehRequest);
+                break;
+
+            case OC_REST_PUT:
+                ehRet = HandleDpairingPutRequest(ehRequest);
+                break;
+
+            case OC_REST_DELETE:
+                break;
+
+            default:
+                ehRet = OC_EH_ERROR;
+                SendSRMResponse(ehRequest, ehRet, NULL, 0);
+        }
+    }
+
+    return ehRet;
+}
+
+/*
+ * This internal method is used to create '/oic/sec/dpairing' resource.
+ */
+OCStackResult CreateDpairingResource()
+{
+    OCStackResult ret;
+
+    ret = OCCreateResource(&gDpairHandle,
+                           OIC_RSRC_TYPE_SEC_DPAIRING,
+                           OIC_MI_DEF,
+                           OIC_RSRC_DPAIRING_URI,
+                           DpairingEntityHandler,
+                           NULL,
+                           OC_SECURE | OC_EXPLICIT_DISCOVERABLE);
+
+    if (OC_STACK_OK != ret)
+    {
+        OIC_LOG (ERROR, TAG, "Unable to instantiate Dpairing resource");
+        DeInitDpairingResource();
+    }
+    return ret;
+}
+
+/**
+ * Initialize Dpairing resource by loading data from persistent storage.
+ *
+ * @retval  OC_STACK_OK for Success, otherwise some error value
+ */
+OCStackResult InitDpairingResource()
+{
+    OCStackResult ret = OC_STACK_ERROR;
+
+    // Instantiate 'oic.sec.dpairing'
+    ret = CreateDpairingResource();
+    if (OC_STACK_OK != ret)
+    {
+        DeInitDpairingResource();
+    }
+    return ret;
+}
+
+/**
+ * Perform cleanup for Dpairing resources.
+ *
+ * @return
+ * OC_STACK_OK    - no error
+ * OC_STACK_ERROR - stack process error
+ *
+ */
+OCStackResult DeInitDpairingResource()
+{
+    OCStackResult ret = OCDeleteResource(gDpairHandle);
+    gDpair = NULL;
+
+    if(OC_STACK_OK == ret)
+    {
+        return OC_STACK_OK;
+    }
+    else
+    {
+        return OC_STACK_ERROR;
+    }
+}
+
+OCStackResult SetDpairingRownerId(const OicUuid_t* newROwner)
+{
+    OCStackResult ret = OC_STACK_ERROR;
+    uint8_t *cborPayload = NULL;
+    size_t size = 0;
+    OicUuid_t prevId = {.id={0}};
+
+    if(NULL == newROwner)
+    {
+        ret = OC_STACK_INVALID_PARAM;
+    }
+    if(NULL == gDpair)
+    {
+        ret = OC_STACK_NO_RESOURCE;
+    }
+
+    if(newROwner && gDpair)
+    {
+        memcpy(prevId.id, gDpair->rownerID.id, sizeof(prevId.id));
+        memcpy(gDpair->rownerID.id, newROwner->id, sizeof(newROwner->id));
+
+        ret = DpairingToCBORPayload(gDpair, &cborPayload, &size);
+        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+
+        ret = UpdateSecureResourceInPS(OIC_JSON_DPAIRING_NAME, cborPayload, size);
+        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+
+        OICFree(cborPayload);
+    }
+
+    return ret;
+
+exit:
+    OICFree(cborPayload);
+    memcpy(gDpair->rownerID.id, prevId.id, sizeof(prevId.id));
+    return ret;
+}
+
+OCStackResult GetDpairingRownerId(OicUuid_t *rowneruuid)
+{
+    OCStackResult retVal = OC_STACK_ERROR;
+    if (gDpair)
+    {
+        *rowneruuid = gDpair->rownerID;
+        retVal = OC_STACK_OK;
+    }
+    return retVal;
+}
index 8276365..d3b6cb1 100644 (file)
@@ -34,20 +34,9 @@ static const char UNTIL[] = "UNTIL";
 static const char BYDAY[] = "BYDAY";
 static const char DAILY[] = "DAILY";
 
-
-/**
- * Parses periodStr and populate struct IotvtICalPeriod_t
- *
- * @param periodStr string to be parsed.
- * @param period    IotvtICalPeriod_t struct to be populated.
- *
- * @return  IOTVTICAL_INVALID_PARAMETER -- if parameter are invalid
- *          IOTVTICAL_INVALID_PERIOD    -- if period string has invalid format
- *          IOTVTICAL_INVALID_SUCCESS   -- if no error while parsing
- */
 IotvtICalResult_t ParsePeriod(const char *periodStr, IotvtICalPeriod_t *period)
 {
-    if((NULL == periodStr) || (NULL == period))
+    if ((NULL == periodStr) || (NULL == period))
     {
         return IOTVTICAL_INVALID_PARAMETER;
     }
@@ -62,7 +51,7 @@ IotvtICalResult_t ParsePeriod(const char *periodStr, IotvtICalPeriod_t *period)
     //startDateTime and endDateTime must be same form
     //Eg: periodStr = "20150629T153050/20150630T203055"
     //    periodStr = "20150629/20150630"
-    if(NULL == (endDTPos = strchr(periodStr, '/')))
+    if (NULL == (endDTPos = strchr(periodStr, '/')))
     {
         return IOTVTICAL_INVALID_PERIOD;
     }
@@ -71,13 +60,13 @@ IotvtICalResult_t ParsePeriod(const char *periodStr, IotvtICalPeriod_t *period)
     endDTLen   = strlen(endDTPos);
 
     //Checking if both startDateTime and endDateTime are of same form
-    if(startDTLen == endDTLen)
+    if (startDTLen == endDTLen)
     {
-        if(8 == startDTLen) //YYYYmmdd
+        if (8 == startDTLen) //YYYYmmdd
         {
             fmt = dFormat;
         }
-        else if(15 == startDTLen) //YYYYmmddTHHMMSS
+        else if (15 == startDTLen) //YYYYmmddTHHMMSS
         {
             fmt = dtFormat;
         }
@@ -92,28 +81,38 @@ IotvtICalResult_t ParsePeriod(const char *periodStr, IotvtICalPeriod_t *period)
     }
 
     //Checking if startDateTime has right format
-    if(NULL != strptime(periodStr, fmt, &period->startDateTime))
+    if (NULL != strptime(periodStr, fmt, &period->startDateTime))
     {
         //Checking if endDateTime has right format
-        if(NULL != strptime(endDTPos, fmt, &period->endDateTime))
+        if (NULL != strptime(endDTPos, fmt, &period->endDateTime))
         {
             //Checking if endDateTime is after startDateTime
-            if(difftime(mktime(&period->endDateTime),
-                        mktime(&period->startDateTime)) > 0)
+            if ((period->startDateTime.tm_year > period->endDateTime.tm_year)
+                || ((period->startDateTime.tm_year == period->endDateTime.tm_year)
+                    && (period->startDateTime.tm_mon > period->endDateTime.tm_mon))
+                || ((period->startDateTime.tm_year == period->endDateTime.tm_year)
+                    && (period->startDateTime.tm_mon == period->endDateTime.tm_mon)
+                    && (period->startDateTime.tm_mday > period->endDateTime.tm_mday))
+                || (( fmt == dtFormat) && (period->startDateTime.tm_year == period->endDateTime.tm_year)
+                    && (period->startDateTime.tm_mon == period->endDateTime.tm_mon)
+                    && (period->startDateTime.tm_mday == period->endDateTime.tm_mday)
+                    && (period->startDateTime.tm_hour > period->endDateTime.tm_hour))
+                || (( fmt == dtFormat) && (period->startDateTime.tm_year == period->endDateTime.tm_year)
+                    && (period->startDateTime.tm_mon == period->endDateTime.tm_mon)
+                    && (period->startDateTime.tm_mday == period->endDateTime.tm_mday)
+                    && (period->startDateTime.tm_hour == period->endDateTime.tm_hour)
+                    && (period->startDateTime.tm_min > period->endDateTime.tm_min))
+                || (( fmt == dtFormat) && (period->startDateTime.tm_year == period->endDateTime.tm_year)
+                    && (period->startDateTime.tm_mon == period->endDateTime.tm_mon)
+                    && (period->startDateTime.tm_mday == period->endDateTime.tm_mday)
+                    && (period->startDateTime.tm_hour == period->endDateTime.tm_hour)
+                    && (period->startDateTime.tm_min == period->endDateTime.tm_min)
+                    && (period->startDateTime.tm_sec > period->endDateTime.tm_sec)))
+            {
+                return IOTVTICAL_INVALID_PERIOD;
+            }
+            else
             {
-                //mktime increases value of tm_hour by 1 if tm_isdst is set.
-                //The tm_hour value in period's startDateTime and endDatetime
-                //should remain same irrespective of daylight saving time.
-                if(period->startDateTime.tm_isdst)
-                {
-                    period->startDateTime.tm_hour =
-                   (period->startDateTime.tm_hour + TOTAL_HOURS - TM_DST_OFFSET) % TOTAL_HOURS;
-                }
-                if(period->endDateTime.tm_isdst)
-                {
-                    period->endDateTime.tm_hour =
-                   (period->endDateTime.tm_hour + TOTAL_HOURS - TM_DST_OFFSET) % TOTAL_HOURS;
-                }
                 return IOTVTICAL_SUCCESS;
             }
         }
@@ -121,29 +120,29 @@ IotvtICalResult_t ParsePeriod(const char *periodStr, IotvtICalPeriod_t *period)
     return IOTVTICAL_INVALID_PERIOD;
 }
 
-
 /**
- * Parses untilRule and populate "until" field of struct IotvtICalRecur_t
+ * Parses untilRule and populate "until" field of struct IotvtICalRecur_t.
  *
- * @param untilRule  string to be parsed.
- * @param recur      IotvtICalRecur_t struct to be populated.
+ * @param untilRule is a string to be parsed.
+ * @param recur is the reference to the @ref IotvtICalRecur_t to be populated.
  *
- * @return  IOTVTICAL_ERRRO             -- if untilRule has invalid format
- *          IOTVTICAL_INVALID_SUCCESS   -- if no error while parsing
+ * @return ::IOTVTICAL_SUCCESS is succesful, else in case of error
+ * ::IOTVTICAL_ERROR, if untilRule has invalid format or ::IOTVTICAL_INVALID_SUCCESS,
+ * if no error while parsing.
  */
 static IotvtICalResult_t ParseDate(char *untilRule, IotvtICalRecur_t *recur)
 {
     char *date = strchr(untilRule, '=');
 
-    if(NULL == date)
+    if (NULL == date)
     {
         return IOTVTICAL_ERROR;
     }
     date += 1;
 
-    if(strlen(date) == 8) //YYYYmmdd
+    if (strlen(date) == 8) //YYYYmmdd
     {
-        if(NULL != strptime(date, dFormat, &recur->until))
+        if (NULL != strptime(date, dFormat, &recur->until))
         {
             return IOTVTICAL_SUCCESS;
         }
@@ -151,49 +150,48 @@ static IotvtICalResult_t ParseDate(char *untilRule, IotvtICalRecur_t *recur)
     return IOTVTICAL_ERROR;
 }
 
-
 /**
- * Parses bydayRule and populate "byDay" field of struct IotvtICalRecur_t
+ * Parses bydayRule and populate "byDay" field of struct @ref IotvtICalRecur_t.
  *
- * @param bydayRule  string to be parsed.
- * @param recur      IotvtICalRecur_t struct to be populated.
+ * @param bydayRule is a string to be parsed.
+ * @param recur is a reference to @ref IotvtICalRecur_t struct to be populated.
  *
- * @return  IOTVTICAL_ERRRO             -- if bydayRule has empty weekday list or invalid weekdays
- *          IOTVTICAL_INVALID_SUCCESS   -- if no error while parsing
+ * @return ::IOTVTICAL_SUCCESS is succesful, else in case of error ::IOTVTICAL_ERROR,
+ * if bydayRule has empty weekday list or invalid weekdays.
  */
 static IotvtICalResult_t  ParseByday(char *bydayRule, IotvtICalRecur_t *recur)
 {
-    if(strstr(bydayRule, "SU"))
+    if (strstr(bydayRule, "SU"))
     {
         recur->byDay = recur->byDay | SUNDAY;
     }
-    if(strstr(bydayRule, "MO"))
+    if (strstr(bydayRule, "MO"))
     {
         recur->byDay = recur->byDay | MONDAY;
     }
-    if(strstr(bydayRule, "TU"))
+    if (strstr(bydayRule, "TU"))
     {
         recur->byDay = recur->byDay | TUESDAY;
     }
-    if(strstr(bydayRule, "WE"))
+    if (strstr(bydayRule, "WE"))
     {
         recur->byDay = recur->byDay | WEDNESDAY;
     }
-    if(strstr(bydayRule, "TH"))
+    if (strstr(bydayRule, "TH"))
     {
         recur->byDay = recur->byDay | THURSDAY;
     }
-    if(strstr(bydayRule, "FR"))
+    if (strstr(bydayRule, "FR"))
     {
         recur->byDay = recur->byDay | FRIDAY;
     }
-    if(strstr(bydayRule, "SA"))
+    if (strstr(bydayRule, "SA"))
     {
         recur->byDay = recur->byDay | SATURDAY;
     }
 
     //Checking if byDay list is empty or has inValid weekdays
-    if(recur->byDay == NO_WEEKDAY)
+    if (recur->byDay == NO_WEEKDAY)
     {
         return IOTVTICAL_ERROR;
     }
@@ -201,21 +199,9 @@ static IotvtICalResult_t  ParseByday(char *bydayRule, IotvtICalRecur_t *recur)
     return IOTVTICAL_SUCCESS;
 }
 
-
-/**
- * Parses recurStr and populate struct IotvtICalRecur_t
- *
- * @param recurStr string to be parsed.
- * @param recur    IotvtICalPeriod_t struct to be populated.
- *
- * @return  IOTVTICAL_INVALID_PARAMETER -- if parameter are invalid
- *          IOTVTICAL_INVALID_PERIOD    -- if period string has invalid format
- *          IOTVTICAL_INVALID_RRULE     -- if rrule string has invalid format
- */
 IotvtICalResult_t ParseRecur(const char *recurStr, IotvtICalRecur_t *recur)
 {
-
-    if((NULL == recurStr) || (NULL == recur))
+    if ((NULL == recurStr) || (NULL == recur))
     {
         return IOTVTICAL_INVALID_PARAMETER;
     }
@@ -229,17 +215,17 @@ IotvtICalResult_t ParseRecur(const char *recurStr, IotvtICalRecur_t *recur)
     startPos = recurStr;
     //Iterates though recurrence rule
     //Eg, RRULE: FREQ=DAILY; UNTIL=20150703; BYDAY=MO, WE, FR
-    while('\0' != startPos)
+    while ('\0' != startPos)
     {
         endPos = strchr(startPos, ';');
-        if(endPos)
+        if (endPos)
         {
             endPos += 1;
         }
         OICStrcpy(buf, (endPos - startPos), startPos);
-        if(NULL != strstr(buf, FREQ))
+        if (NULL != strstr(buf, FREQ))
         {
-            if(NULL != strstr(buf, DAILY))
+            if (NULL != strstr(buf, DAILY))
             {
                 recur->freq = FREQ_DAILY;
                 freqFlag = 1;
@@ -249,16 +235,16 @@ IotvtICalResult_t ParseRecur(const char *recurStr, IotvtICalRecur_t *recur)
                 return IOTVTICAL_INVALID_RRULE;
             }
         }
-        else if(NULL != strstr(buf, UNTIL))
+        else if (NULL != strstr(buf, UNTIL))
         {
-            if(IOTVTICAL_SUCCESS != ParseDate(buf, recur))
+            if (IOTVTICAL_SUCCESS != ParseDate(buf, recur))
             {
                 return IOTVTICAL_INVALID_RRULE;
             }
         }
-        else if(NULL != strstr(buf, BYDAY))
+        else if (NULL != strstr(buf, BYDAY))
         {
-            if(IOTVTICAL_SUCCESS != ParseByday(buf, recur))
+            if (IOTVTICAL_SUCCESS != ParseByday(buf, recur))
             {
                 return IOTVTICAL_INVALID_RRULE;
             };
@@ -266,7 +252,7 @@ IotvtICalResult_t ParseRecur(const char *recurStr, IotvtICalRecur_t *recur)
         startPos = endPos;
     }
 
-    if(1 != freqFlag)
+    if (1 != freqFlag)
     {
         return IOTVTICAL_INVALID_RRULE;
     }
@@ -287,12 +273,12 @@ static int DiffDays(IotvtICalDateTime_t *date1, IotvtICalDateTime_t *date2)
     int days;
     int leapDays=0;
 
-    if(date2->tm_year > date1->tm_year)
+    if (date2->tm_year > date1->tm_year)
     {
-        for(int y = date1->tm_year; y < date2->tm_year; y++)
+        for (int y = date1->tm_year; y < date2->tm_year; y++)
         {
             y += TM_YEAR_OFFSET;
-            if(y % 4 == 0 && (y % 100 != 0 || y % 400 == 0))
+            if (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0))
             {
                leapDays += 1;
             }
@@ -305,7 +291,6 @@ static int DiffDays(IotvtICalDateTime_t *date1, IotvtICalDateTime_t *date2)
     return days;
 }
 
-
 /**
  * Computes number of seconds between two time.
  *
@@ -320,27 +305,66 @@ static int DiffSecs(IotvtICalDateTime_t *time1, IotvtICalDateTime_t *time2)
            (3600 * time1->tm_hour + 60 * time1->tm_min + time1->tm_sec);
 }
 
-
 /**
- * This API is used by policy engine to checks if the
- * request to access resource is within valid time.
+ * Validates if the @param currentTime is with in allowable period.
  *
- * @param period string representing period.
- * @param recur string representing recurrence rule
+ * @param period allowable period.
+ * @param currentTime the time that need to be validated against allowable time.
  *
- * @return  IOTVTICAL_VALID_ACCESS      -- if the request is within valid time period
- *          IOTVTICAL_INVALID_ACCESS    -- if the request is not within valid time period
- *          IOTVTICAL_INVALID_PARAMETER -- if parameter are invalid
- *          IOTVTICAL_INVALID_PERIOD    -- if period string has invalid format
- *          IOTVTICAL_INVALID_RRULE     -- if rrule string has invalid format
+ * @return ::IOTVTICAL_VALID_ACCESS, if the request is within valid time period.
+ * ::IOTVTICAL_INVALID_ACCESS, if the request is not within valid time period.
+ * ::IOTVTICAL_INVALID_PARAMETER, if parameter are invalid.
  */
+static IotvtICalResult_t ValidatePeriod(IotvtICalPeriod_t *period, IotvtICalDateTime_t *currentTime)
+{
+    if (NULL == period || NULL == currentTime)
+    {
+        return IOTVTICAL_INVALID_PARAMETER;
+    }
+
+    bool validStartTime = true;
+    bool validEndTime = true;
+    bool validDay = false;
+    bool todayIsStartDay = (0 == DiffDays(&period->startDateTime, currentTime)) ? true : false;
+    bool todayIsEndDay = (0 == DiffDays(currentTime, &period->endDateTime)) ? true : false;
+
+    //If today is the start day of the allowable period then check
+    //currentTime > allowable period startTime
+    if (todayIsStartDay)
+    {
+        validStartTime = (0 <= DiffSecs(&period->startDateTime, currentTime)) ? true : false;
+    }
+
+    //If today is the end day of allowable period then check
+    //currentTime < allowable period endTime
+    if (todayIsEndDay)
+    {
+        validEndTime = (0 <= DiffSecs(currentTime, &period->endDateTime)) ? true :false;
+    }
 
-IotvtICalResult_t IsRequestWithinValidTime(char *periodStr, char *recurStr)
+    //Check if today is valid day between startDate and EndDate inclusive
+    if ((0 <= DiffDays(&period->startDateTime, currentTime)) &&
+       (0 <= DiffDays(currentTime, &period->endDateTime)))
+    {
+        validDay = true;
+    }
+
+    if (validDay && validStartTime && validEndTime)
+    {
+        return IOTVTICAL_VALID_ACCESS;
+    }
+    else
+    {
+        return IOTVTICAL_INVALID_ACCESS;
+    }
+}
+
+IotvtICalResult_t IsRequestWithinValidTime(const char *periodStr, const char *recurStr)
 {
     //NULL recur rule means no recurring patter exist.
     //Period can't be null. Period is used with or without
     //recur rule to compute allowable access time.
-    if(NULL == periodStr)
+    if (NULL == periodStr)
     {
         return IOTVTICAL_INVALID_PARAMETER;
     }
@@ -353,19 +377,15 @@ IotvtICalResult_t IsRequestWithinValidTime(char *periodStr, char *recurStr)
     IotvtICalDateTime_t *currentTime = localtime(&rawTime);
 
     ret  = ParsePeriod(periodStr, &period);
-    if(ret != IOTVTICAL_SUCCESS)
+    if (ret != IOTVTICAL_SUCCESS)
     {
         return ret;
     }
 
-    //If recur is NULL then the access time is between period's startDate and endDate
-    if(NULL == recurStr)
+    //If recur is NULL then the access time is between period's startDateTime and endDateTime
+    if (NULL == recurStr)
     {
-        if((0 <= DiffDays(&period.startDateTime, currentTime)) &&
-           (0 <= DiffDays(currentTime, &period.endDateTime)))
-        {
-            ret = IOTVTICAL_VALID_ACCESS;
-        }
+        ret = ValidatePeriod(&period, currentTime);
     }
 
     //If recur is not NULL then the access time is between period's startTime and
@@ -373,15 +393,15 @@ IotvtICalResult_t IsRequestWithinValidTime(char *periodStr, char *recurStr)
     //is computed from period's startDate and the last instance is computed from
     //"UNTIL". If "UNTIL" is not specified then the recurrence goes for forever.
     //Eg, RRULE: FREQ=DAILY; UNTIL=20150703; BYDAY=MO, WE, FR
-    if(NULL != recurStr)
+    if (NULL != recurStr)
     {
         ret = ParseRecur(recurStr, &recur);
-        if(ret != IOTVTICAL_SUCCESS)
+        if (ret != IOTVTICAL_SUCCESS)
         {
             return ret;
         }
 
-        if((0 <= DiffSecs(&period.startDateTime, currentTime))&&
+        if ((0 <= DiffSecs(&period.startDateTime, currentTime))&&
            (0 <= DiffSecs(currentTime, &period.endDateTime)) &&
            (0 <= DiffDays(&period.startDateTime, currentTime)))
         {
@@ -389,7 +409,7 @@ IotvtICalResult_t IsRequestWithinValidTime(char *periodStr, char *recurStr)
             ret = IOTVTICAL_VALID_ACCESS;
 
             //"UNTIL" is an optional parameter of RRULE, checking if until present in recur
-            if(0 != memcmp(&recur.until, &emptyDT, sizeof(IotvtICalDateTime_t)))
+            if (0 != memcmp(&recur.until, &emptyDT, sizeof(IotvtICalDateTime_t)))
             {
                 if(0 > DiffDays(currentTime, &recur.until))
                 {
@@ -398,11 +418,11 @@ IotvtICalResult_t IsRequestWithinValidTime(char *periodStr, char *recurStr)
             }
 
             //"BYDAY" is an optional parameter of RRULE, checking if byday present in recur
-            if(NO_WEEKDAY != recur.byDay)
+            if (NO_WEEKDAY != recur.byDay)
             {
 
                 int isValidWD = (0x1 << currentTime->tm_wday) & recur.byDay; //Valid weekdays
-                if(!isValidWD)
+                if (!isValidWD)
                 {
                     ret = IOTVTICAL_INVALID_ACCESS;
                 }
index 85612e9..f1354aa 100644 (file)
@@ -1,37 +1,50 @@
-/* *****************************************************************
- *
- * 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.
- *
- * *****************************************************************/
+//******************************************************************
+//
+// 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 <memory.h>
+
 #include "ocstack.h"
 #include "ocrandom.h"
 #include "logger.h"
 #include "pinoxmcommon.h"
+#include "pbkdf2.h"
+#include "securevirtualresourcetypes.h"
 
 #define TAG "PIN_OXM_COMMON"
 
 static GeneratePinCallback gGenPinCallback = NULL;
 static InputPinCallback gInputPinCallback = NULL;
 
+typedef struct PinOxmData {
+    uint8_t pinData[OXM_RANDOM_PIN_SIZE + 1];
+    OicUuid_t newDevice;
+}PinOxmData_t;
+
+static PinOxmData_t g_PinOxmData;
+
+
 void SetInputPinCB(InputPinCallback pinCB)
 {
     if(NULL == pinCB)
     {
-        OC_LOG(ERROR, TAG, "Failed to set callback for input pin.");
+        OIC_LOG(ERROR, TAG, "Failed to set callback for input pin.");
         return;
     }
 
@@ -42,7 +55,7 @@ void SetGeneratePinCB(GeneratePinCallback pinCB)
 {
     if(NULL == pinCB)
     {
-        OC_LOG(ERROR, TAG, "Failed to set callback for generate pin.");
+        OIC_LOG(ERROR, TAG, "Failed to set callback for generate pin.");
         return;
     }
 
@@ -53,19 +66,21 @@ OCStackResult GeneratePin(char* pinBuffer, size_t bufferSize)
 {
     if(!pinBuffer)
     {
-        OC_LOG(ERROR, TAG, "PIN buffer is NULL");
+        OIC_LOG(ERROR, TAG, "PIN buffer is NULL");
         return OC_STACK_INVALID_PARAM;
     }
     if(OXM_RANDOM_PIN_SIZE + 1 > bufferSize)
     {
-        OC_LOG(ERROR, TAG, "PIN buffer size is too small");
+        OIC_LOG(ERROR, TAG, "PIN buffer size is too small");
         return OC_STACK_INVALID_PARAM;
     }
     for(size_t i = 0; i < OXM_RANDOM_PIN_SIZE; i++)
     {
         pinBuffer[i] = OCGetRandomRange((uint32_t)'0', (uint32_t)'9');
+        g_PinOxmData.pinData[i] = pinBuffer[i];
     }
     pinBuffer[OXM_RANDOM_PIN_SIZE] = '\0';
+    g_PinOxmData.pinData[OXM_RANDOM_PIN_SIZE] = '\0';
 
     if(gGenPinCallback)
     {
@@ -73,8 +88,8 @@ OCStackResult GeneratePin(char* pinBuffer, size_t bufferSize)
     }
     else
     {
-        OC_LOG(ERROR, TAG, "Invoke PIN callback failed!");
-        OC_LOG(ERROR, TAG, "Callback for genrate PIN should be registered to use PIN based OxM.");
+        OIC_LOG(ERROR, TAG, "Invoke PIN callback failed!");
+        OIC_LOG(ERROR, TAG, "Callback for genrate PIN should be registered to use PIN based OxM.");
         return OC_STACK_ERROR;
     }
 
@@ -86,25 +101,106 @@ OCStackResult InputPin(char* pinBuffer, size_t bufferSize)
 {
     if(!pinBuffer)
     {
-        OC_LOG(ERROR, TAG, "PIN buffer is NULL");
+        OIC_LOG(ERROR, TAG, "PIN buffer is NULL");
         return OC_STACK_INVALID_PARAM;
     }
     if(OXM_RANDOM_PIN_SIZE + 1 > bufferSize)
     {
-        OC_LOG(ERROR, TAG, "PIN buffer size is too small");
+        OIC_LOG(ERROR, TAG, "PIN buffer size is too small");
         return OC_STACK_INVALID_PARAM;
     }
 
     if(gInputPinCallback)
     {
         gInputPinCallback(pinBuffer, OXM_RANDOM_PIN_SIZE + 1);
+        memcpy(g_PinOxmData.pinData, pinBuffer, OXM_RANDOM_PIN_SIZE);
+        g_PinOxmData.pinData[OXM_RANDOM_PIN_SIZE] = '\0';
     }
     else
     {
-        OC_LOG(ERROR, TAG, "Invoke PIN callback failed!");
-        OC_LOG(ERROR, TAG, "Callback for input PIN should be registered to use PIN based OxM.");
+        OIC_LOG(ERROR, TAG, "Invoke PIN callback failed!");
+        OIC_LOG(ERROR, TAG, "Callback for input PIN should be registered to use PIN based OxM.");
         return OC_STACK_ERROR;
     }
 
     return OC_STACK_OK;
 }
+
+#ifdef __WITH_DTLS__
+
+void SetUuidForRandomPinOxm(const OicUuid_t* uuid)
+{
+    if(NULL != uuid)
+    {
+        memcpy(g_PinOxmData.newDevice.id, uuid->id, UUID_LENGTH);
+    }
+}
+
+int32_t GetDtlsPskForRandomPinOxm( CADtlsPskCredType_t type,
+              const unsigned char *UNUSED1, size_t UNUSED2,
+              unsigned char *result, size_t result_length)
+{
+    int32_t ret = -1;
+
+    (void)UNUSED1;
+    (void)UNUSED2;
+
+    if (NULL == result || result_length < OWNER_PSK_LENGTH_128)
+    {
+        return ret;
+    }
+
+    switch (type)
+    {
+        case CA_DTLS_PSK_HINT:
+        case CA_DTLS_PSK_IDENTITY:
+            /**
+             * The server will provide PSK hint to identify PSK according to RFC 4589 and RFC 4279.
+             *
+             * At this point, The server generate random hint and
+             * provide it to client through server key exchange message.
+             */
+            OCFillRandomMem(result, result_length);
+            ret = result_length;
+
+            OIC_LOG(DEBUG, TAG, "PSK HINT : ");
+            OIC_LOG_BUFFER(DEBUG, TAG, result, result_length);
+            break;
+
+        case CA_DTLS_PSK_KEY:
+            {
+                int dtlsRes = DeriveCryptoKeyFromPassword(
+                                                          (const unsigned char *)g_PinOxmData.pinData,
+                                                          OXM_RANDOM_PIN_SIZE,
+                                                          g_PinOxmData.newDevice.id,
+                                                          UUID_LENGTH, PBKDF_ITERATIONS,
+                                                          OWNER_PSK_LENGTH_128, (uint8_t*)result);
+
+                OIC_LOG_V(DEBUG, TAG, "DeriveCryptoKeyFromPassword Completed (%d)", dtlsRes);
+                OIC_LOG_V(DEBUG, TAG, "PIN : %s", g_PinOxmData.pinData);
+                OIC_LOG(DEBUG, TAG, "UUID : ");
+                OIC_LOG_BUFFER(DEBUG, TAG, g_PinOxmData.newDevice.id, UUID_LENGTH);
+
+                if(0 == dtlsRes)
+                {
+                    ret = OWNER_PSK_LENGTH_128;
+                }
+                else
+                {
+                    OIC_LOG_V(ERROR, TAG, "Failed to derive crypto key from PIN : result=%d", dtlsRes);
+                    ret = -1;
+                }
+            }
+            break;
+
+        default:
+            {
+                OIC_LOG (ERROR, TAG, "Wrong value passed for CADtlsPskCredType_t.");
+                ret = -1;
+            }
+            break;
+    }
+
+    return ret;
+}
+#endif //__WITH_DTLS__
index 1ddabed..02c984a 100644 (file)
@@ -1,22 +1,23 @@
-/* *****************************************************************
- *
- * 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.
- *
- * *****************************************************************/
+//******************************************************************
+//
+// 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 <string.h>
 #include <math.h>
 #include "pbkdf2.h"
 
 #define TAG "PBDKF2"
 #define XOR_BUF(in, out, bufSize)\
-do{\
+do \
+{\
     size_t i=0;\
-    for(i=0; i< (bufSize); i++)\
+    for (i=0; i< (bufSize); i++)\
     {\
         (out)[i] = (in)[i] ^ (out)[i];\
     }\
-}while(0)\
-
+} while(0)\
 
 static int isLittle()
 {
@@ -86,7 +87,7 @@ int DeriveCryptoKeyFromPassword(const unsigned char *passwd, size_t pLen,
     ctx = dtls_hmac_new( (const unsigned char *)passwd, pLen);
     if (NULL == ctx)
     {
-        OC_LOG(ERROR, TAG, "DTLS HMAC Context is NULL");
+        OIC_LOG(ERROR, TAG, "DTLS HMAC Context is NULL");
         goto bail;
     }
 
@@ -109,7 +110,7 @@ int DeriveCryptoKeyFromPassword(const unsigned char *passwd, size_t pLen,
                 int len = dtls_hmac_finalize(ctx, buf);
                 if (DTLS_HMAC_DIGEST_SIZE != len)
                 {
-                    OC_LOG(ERROR, TAG, "DTLS HMAC is failed");
+                    OIC_LOG(ERROR, TAG, "DTLS HMAC is failed");
                     res = -1;
                 }
                 memcpy(uBuf, buf, DTLS_HMAC_DIGEST_SIZE);
@@ -121,7 +122,7 @@ int DeriveCryptoKeyFromPassword(const unsigned char *passwd, size_t pLen,
                 int len = dtls_hmac_finalize(ctx, buf);
                 if (DTLS_HMAC_DIGEST_SIZE != len)
                 {
-                    OC_LOG(ERROR, TAG, "DTLS HMAC is failed");
+                    OIC_LOG(ERROR, TAG, "DTLS HMAC is failed");
                     res = -1;
                 }
                 XOR_BUF(buf, uBuf, DTLS_HMAC_DIGEST_SIZE);
diff --git a/resource/csdk/security/src/pconfresource.c b/resource/csdk/security/src/pconfresource.c
new file mode 100644 (file)
index 0000000..921b249
--- /dev/null
@@ -0,0 +1,1290 @@
+/* *****************************************************************
+ *
+ * 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 <stdlib.h>
+#include <string.h>
+#include "ocstack.h"
+#include "logger.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+#include "cJSON.h"
+#include "base64.h"
+#include "ocpayload.h"
+#include "payload_logging.h"
+#include "resourcemanager.h"
+#include "pconfresource.h"
+#include "psinterface.h"
+#include "utlist.h"
+#include "srmresourcestrings.h"
+#include "doxmresource.h"
+#include "srmutility.h"
+#include "ocserverrequest.h"
+#include <stdlib.h>
+#include "psinterface.h"
+#include "security_internals.h"
+#ifdef WITH_ARDUINO
+#include <string.h>
+#else
+#include <strings.h>
+#endif
+
+#define TAG  "SRM-PCONF"
+
+static const uint16_t CBOR_SIZE = 1024;
+static const uint64_t CBOR_MAX_SIZE = 4400;
+static const uint8_t  PCONF_MAP_SIZE = 4;
+static const uint8_t  PCONF_RESOURCE_MAP_SIZE = 4;
+
+static OicSecPconf_t          *gPconf = NULL;
+static OCResourceHandle   gPconfHandle = NULL;
+static OicSecPconf_t         gDefaultPconf =
+{
+    false,                  /* bool edp */
+    NULL,                  /* OicSecPrm *prm */
+    0,                       /* size_t prmLen */
+    {.val = {0}},       /* OicDpPin_t pin */
+    NULL,                  /* OicSecPdAcl_t *pdacls */
+    NULL,                  /* OicUuid_t *pddevs */
+    0,                       /* size_t pddevLen */
+    {.id = {0}},        /* OicUuid_t deviceID */
+    {.id = {0}},        /* OicUuid_t rowner */
+};
+
+/**
+ * This function frees OicSecPdAcl_t object's fields and object itself.
+ */
+void FreePdAclList(OicSecPdAcl_t* pdacls)
+{
+    if (pdacls)
+    {
+        size_t i = 0;
+
+        //Clean pdacl objecs
+        OicSecPdAcl_t *aclTmp1 = NULL;
+        OicSecPdAcl_t *aclTmp2 = NULL;
+        LL_FOREACH_SAFE(pdacls, aclTmp1, aclTmp2)
+        {
+            LL_DELETE(pdacls, aclTmp1);
+
+            // Clean Resources
+            for (i = 0; i < aclTmp1->resourcesLen; i++)
+            {
+                OICFree(aclTmp1->resources[i]);
+            }
+            OICFree(aclTmp1->resources);
+
+            //Clean Period
+            if(aclTmp1->periods)
+            {
+                for(i = 0; i < aclTmp1->prdRecrLen; i++)
+                {
+                    OICFree(aclTmp1->periods[i]);
+                }
+                OICFree(aclTmp1->periods);
+            }
+
+            //Clean Recurrence
+            if(aclTmp1->recurrences)
+            {
+                for(i = 0; i < aclTmp1->prdRecrLen; i++)
+                {
+                    OICFree(aclTmp1->recurrences[i]);
+                }
+                OICFree(aclTmp1->recurrences);
+            }
+        }
+
+        //Clean pconf itself
+        OICFree(pdacls);
+    }
+}
+
+void DeletePconfBinData(OicSecPconf_t* pconf)
+{
+    if (pconf)
+    {
+        //Clean prm
+        OICFree(pconf->prm);
+
+        //Clean pdacl
+        if (pconf->pdacls)
+        {
+            FreePdAclList(pconf->pdacls);
+        }
+
+        //Clean pddev
+        OICFree(pconf->pddevs);
+
+        //Clean pconf itself
+        OICFree(pconf);
+    }
+}
+
+static size_t OicPdAclSize(const OicSecPdAcl_t *pdAcl)
+{
+    if (!pdAcl)
+    {
+        return 0;
+    }
+
+    OicSecPdAcl_t *tmp = (OicSecPdAcl_t *)pdAcl;
+    size_t size = 0;
+    while (tmp)
+    {
+        size++;
+        tmp = tmp->next;
+    }
+    return size;
+}
+
+OCStackResult PconfToCBORPayload(const OicSecPconf_t *pconf,uint8_t **payload,size_t *size)
+{
+    if (NULL == pconf || NULL == payload || NULL != *payload || NULL == size)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+    size_t cborLen = *size;
+    if(0 == cborLen)
+    {
+        cborLen = CBOR_SIZE;
+    }
+    *payload = NULL;
+
+    OCStackResult ret = OC_STACK_ERROR;
+    CborEncoder encoder;
+    CborEncoder pconfMap;
+
+    int64_t cborEncoderResult = CborNoError;
+    uint8_t mapSize = PCONF_MAP_SIZE;
+
+    if (pconf->prmLen > 0)
+    {
+        mapSize++;
+    }
+    if (pconf->pdacls)
+    {
+        mapSize++;
+    }
+    if (pconf->pddevs)
+    {
+        mapSize++;
+    }
+
+    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
+    VERIFY_NON_NULL(TAG, outPayload, ERROR);
+
+    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
+    cborEncoderResult = cbor_encoder_create_map(&encoder, &pconfMap, mapSize);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Creating Pconf Map.");
+
+    //edp  -- Mandatory
+    cborEncoderResult = cbor_encode_text_string(&pconfMap, OIC_JSON_EDP_NAME,
+            strlen(OIC_JSON_EDP_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Encode EDP String.");
+    cborEncoderResult = cbor_encode_boolean(&pconfMap, pconf->edp);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Convert PconfEDP value");
+
+    //PRM type -- Not Mandatory
+    if(pconf->prmLen > 0)
+    {
+        CborEncoder prm;
+        cborEncoderResult = cbor_encode_text_string(&pconfMap, OIC_JSON_PRM_NAME,
+                strlen(OIC_JSON_PRM_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Convert Pconf PRM NAME");
+        cborEncoderResult = cbor_encoder_create_array(&pconfMap, &prm, pconf->prmLen);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Convert Pconf PRM value");
+
+        for (size_t i = 0; i < pconf->prmLen; i++)
+        {
+            cborEncoderResult = cbor_encode_int(&prm, pconf->prm[i]);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Convert Pconf PRM Array");
+        }
+        cborEncoderResult = cbor_encoder_close_container(&pconfMap, &prm);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to close encode array");
+    }
+
+    //PIN -- Mandatory
+    cborEncoderResult = cbor_encode_text_string(&pconfMap, OIC_JSON_PIN_NAME,
+            strlen(OIC_JSON_PIN_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to create OIC_JSON_PIN_NAME");
+    cborEncoderResult = cbor_encode_byte_string(&pconfMap, pconf->pin.val, sizeof(pconf->pin.val));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to convert pin value");
+
+    //PDACL -- Mandatory
+    if (pconf->pdacls)
+    {
+        OicSecPdAcl_t *pdacl = pconf->pdacls;
+        CborEncoder pdAclArray;
+        cborEncoderResult = cbor_encode_text_string(&pconfMap, OIC_JSON_PDACL_NAME,
+                strlen(OIC_JSON_PDACL_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to create OIC_JSON_PDACL_NAME");
+        cborEncoderResult = cbor_encoder_create_array(&pconfMap, &pdAclArray,
+                OicPdAclSize(pconf->pdacls));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to creeate _pdacl array");
+
+        while(pdacl)
+        {
+            CborEncoder pdAclMap;
+            // PDACL Map size - Number of mandatory items
+            uint8_t aclMapSize = 2;
+
+            if (pdacl->prdRecrLen)
+            {
+                ++aclMapSize;
+            }
+            if (pdacl->recurrences)
+            {
+                ++aclMapSize;
+            }
+
+            cborEncoderResult = cbor_encoder_create_map(&pdAclArray, &pdAclMap, aclMapSize);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult,  "Failed to creeate _pdacl array");
+
+            // Resources -- Mandatory
+            cborEncoderResult = cbor_encode_text_string(&pdAclMap, OIC_JSON_RESOURCES_NAME,
+                    strlen(OIC_JSON_RESOURCES_NAME));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult,  "Failed to encode resource result");
+
+            CborEncoder resources;
+            cborEncoderResult = cbor_encoder_create_array(&pdAclMap, &resources,
+                    pdacl->resourcesLen);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult,  "Failed to create resource array");
+
+            for (size_t i = 0; i < pdacl->resourcesLen; i++)
+            {
+                CborEncoder rMap;
+                cborEncoderResult = cbor_encoder_create_map(&resources, &rMap,
+                        PCONF_RESOURCE_MAP_SIZE);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Resource Map.");
+
+                cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_HREF_NAME,
+                        strlen(OIC_JSON_HREF_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding HREF Name Tag.");
+                cborEncoderResult = cbor_encode_text_string(&rMap, pdacl->resources[i],
+                        strlen(pdacl->resources[i]));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding HREF Value in Map.");
+
+                cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_REL_NAME,
+                        strlen(OIC_JSON_REL_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding REL Name Tag.");
+
+                // TODO : Need to assign real value of REL
+                cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_EMPTY_STRING,
+                        strlen(OIC_JSON_EMPTY_STRING));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding REL Value.");
+
+                cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_RT_NAME,
+                        strlen(OIC_JSON_RT_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag.");
+
+                // TODO : Need to assign real value of RT
+                cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_EMPTY_STRING,
+                        strlen(OIC_JSON_EMPTY_STRING));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
+
+                cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_IF_NAME,
+                        strlen(OIC_JSON_IF_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag.");
+
+                // TODO : Need to assign real value of IF
+                cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_EMPTY_STRING,
+                        strlen(OIC_JSON_EMPTY_STRING));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
+
+                cborEncoderResult = cbor_encoder_close_container(&resources, &rMap);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Resource Map.");
+            }
+
+            cborEncoderResult = cbor_encoder_close_container(&pdAclMap, &resources);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult,  "Failed to close resource array");
+
+            // Permissions -- Mandatory
+            cborEncoderResult = cbor_encode_text_string(&pdAclMap, OIC_JSON_PERMISSION_NAME,
+                    strlen(OIC_JSON_PERMISSION_NAME));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult,  "Failed to create permition string");
+            cborEncoderResult = cbor_encode_int(&pdAclMap, pdacl->permission);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to encode permition calue");
+
+            // Period -- Not Mandatory
+            if (pdacl->periods)
+            {
+                CborEncoder period;
+                cborEncoderResult = cbor_encode_text_string(&pdAclMap, OIC_JSON_PERIODS_NAME,
+                        strlen(OIC_JSON_PERIODS_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to encode period value");
+                cborEncoderResult = cbor_encoder_create_array(&pdAclMap, &period,
+                        pdacl->prdRecrLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to create array");
+
+                for (size_t i = 0; i < pdacl->prdRecrLen; i++)
+                {
+                    cborEncoderResult = cbor_encode_text_string(&period, pdacl->periods[i],
+                            strlen(pdacl->periods[i]));
+                    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to encode period");
+                }
+                cborEncoderResult = cbor_encoder_close_container(&pdAclMap, &period);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult,"Failed to close period array");
+            }
+
+            // Period -- Not Mandatory
+            if(0 != pdacl->prdRecrLen && pdacl->recurrences)
+            {
+                CborEncoder recurrences;
+                cborEncoderResult = cbor_encode_text_string(&pdAclMap, OIC_JSON_RECURRENCES_NAME,
+                        strlen(OIC_JSON_RECURRENCES_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult,"Failed to encode recurrences");
+                cborEncoderResult = cbor_encoder_create_array(&pdAclMap, &recurrences,
+                        pdacl->prdRecrLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to create rec array");
+
+                for (size_t i = 0; i < pdacl->prdRecrLen; i++)
+                {
+                    cborEncoderResult = cbor_encode_text_string(&recurrences,
+                            pdacl->recurrences[i], strlen(pdacl->recurrences[i]));
+                    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to encode recurrences");
+                }
+                cborEncoderResult = cbor_encoder_close_container(&pdAclMap, &recurrences);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to close rec array");
+            }
+            cborEncoderResult = cbor_encoder_close_container(&pdAclArray, &pdAclMap);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to close acl map");
+
+            pdacl = pdacl->next;
+        }
+        //clsoe the array
+        cborEncoderResult = cbor_encoder_close_container(&pconfMap, &pdAclArray);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to close acl array");
+    }
+
+    //PDDev -- Mandatory
+    //There may not be paired devices if it did not pairing before
+    if (pconf->pddevs && 0 < pconf->pddevLen)
+    {
+        CborEncoder pddev;
+        cborEncoderResult = cbor_encode_text_string(&pconfMap, OIC_JSON_PDDEV_LIST_NAME,
+                strlen(OIC_JSON_PDDEV_LIST_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to encode pddev");
+        cborEncoderResult = cbor_encoder_create_array(&pconfMap, &pddev,  pconf->pddevLen);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to create array");
+
+        for (size_t i = 0; i < pconf->pddevLen; i++)
+        {
+            char *pddevId = NULL;
+            ret = ConvertUuidToStr(&pconf->pddevs[i], &pddevId);
+            VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
+            cborEncoderResult = cbor_encode_text_string(&pddev, pddevId, strlen(pddevId));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding pddev Id Value.");
+            OICFree(pddevId);
+        }
+        cborEncoderResult = cbor_encoder_close_container(&pconfMap, &pddev);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to close pddev array");
+    }
+
+    //DeviceId -- Mandatory
+    //There may not be devicd id if caller is provisoning tool
+    cborEncoderResult = cbor_encode_text_string(&pconfMap, OIC_JSON_DEVICE_ID_NAME,
+            strlen(OIC_JSON_DEVICE_ID_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to encode device id");
+    {
+        char *deviceId = NULL;
+        ret = ConvertUuidToStr(&pconf->deviceID, &deviceId);
+        VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
+        cborEncoderResult = cbor_encode_text_string(&pconfMap, deviceId, strlen(deviceId));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to encode deviceID value");
+        OICFree(deviceId);
+    }
+
+    //ROwner -- Mandatory
+    {
+        char *rowner = NULL;
+        cborEncoderResult = cbor_encode_text_string(&pconfMap, OIC_JSON_ROWNERID_NAME,
+                strlen(OIC_JSON_ROWNERID_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to encode rowner string");
+        ret = ConvertUuidToStr(&pconf->rownerID, &rowner);
+        VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
+        cborEncoderResult = cbor_encode_text_string(&pconfMap, rowner, strlen(rowner));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to encode rwoner value");
+        OICFree(rowner);
+    }
+
+    cborEncoderResult = cbor_encoder_close_container(&encoder, &pconfMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to close pconfMap");
+
+    *size = encoder.ptr - outPayload;
+    *payload = outPayload;
+    ret = OC_STACK_OK;
+exit:
+    if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
+    {
+        // reallocate and try again!
+        OICFree(outPayload);
+        // Since the allocated initial memory failed, double the memory.
+        cborLen += encoder.ptr - encoder.end;
+        cborEncoderResult = CborNoError;
+        ret = PconfToCBORPayload(pconf, payload, &cborLen);
+        *size = cborLen;
+    }
+    if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
+    {
+        OICFree(outPayload);
+        outPayload = NULL;
+        *payload = NULL;
+        *size = 0;
+        ret = OC_STACK_ERROR;
+    }
+    return ret;
+}
+
+OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSecPconf_t **secPconf)
+{
+    if (NULL == cborPayload || NULL == secPconf || NULL != *secPconf || 0 == size)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+    OCStackResult ret = OC_STACK_ERROR;
+    *secPconf = NULL;
+    CborValue pconfCbor = { .parser = NULL };
+    CborParser parser = { .end = NULL };
+    CborError cborFindResult = CborNoError;
+
+    cbor_parser_init(cborPayload, size, 0, &parser, &pconfCbor);
+    CborValue pconfMap = { .parser = NULL } ;
+    OicSecPconf_t *pconf = NULL;
+    cborFindResult = cbor_value_enter_container(&pconfCbor, &pconfMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to enter map");
+    pconf = (OicSecPconf_t *)OICCalloc(1, sizeof(*pconf));
+    VERIFY_NON_NULL(TAG, pconf, ERROR);
+    while (cbor_value_is_valid(&pconfMap))
+    {
+        char *name = NULL;
+        size_t len = 0;
+        CborType type = cbor_value_get_type(&pconfMap);
+        if (type == CborTextStringType)
+        {
+            cborFindResult = cbor_value_dup_text_string(&pconfMap, &name, &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get value");
+            cborFindResult = cbor_value_advance(&pconfMap);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance value");
+        }
+
+        if (name)
+        {
+            //EDP -- Mandatory
+            if(0 == strcmp(OIC_JSON_EDP_NAME, name))
+            {
+                cborFindResult = cbor_value_get_boolean(&pconfMap, &pconf->edp);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get value");
+            }
+            if (0 == strcmp(OIC_JSON_PRM_NAME, name))
+            {
+                int i = 0;
+                CborValue prm = { .parser = NULL };
+                cborFindResult = cbor_value_get_array_length(&pconfMap, &pconf->prmLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get length");
+                VERIFY_SUCCESS(TAG, pconf->prmLen != 0, ERROR);
+
+                pconf->prm = (OicSecPrm_t *)OICCalloc(pconf->prmLen, sizeof(OicSecPrm_t));
+                VERIFY_NON_NULL(TAG, pconf->prm, ERROR);
+                cborFindResult = cbor_value_enter_container(&pconfMap, &prm);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to eneter array");
+
+                while (cbor_value_is_valid(&prm))
+                {
+                    cborFindResult = cbor_value_get_int(&prm, (int *)&pconf->prm[i++]);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get value");
+                    cborFindResult = cbor_value_advance(&prm);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance value");
+                }
+            }
+            //PIN -- Mandatory
+            if (0 == strcmp(OIC_JSON_PIN_NAME, name))
+            {
+                uint8_t *pin = NULL;
+                cborFindResult = cbor_value_dup_byte_string(&pconfMap, &pin, &len, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get value");
+                memcpy(pconf->pin.val, pin, len);
+                OICFree(pin);
+            }
+
+            //PDACL -- Mandatory
+            if (0 == strcmp(OIC_JSON_PDACL_NAME, name))
+            {
+                CborValue pdAclArray = { .parser = NULL};
+                OicSecPdAcl_t *headPdacl = NULL;
+
+                cborFindResult = cbor_value_enter_container(&pconfMap, &pdAclArray);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to enter");
+
+                while (cbor_value_is_valid(&pdAclArray))
+                {
+                    CborValue pdAclMap = { .parser = NULL};
+                    OicSecPdAcl_t *pdacl = (OicSecPdAcl_t *) OICCalloc(1, sizeof(OicSecPdAcl_t));
+                    VERIFY_NON_NULL(TAG, pdacl, ERROR);
+
+                    cborFindResult = cbor_value_enter_container(&pdAclArray, &pdAclMap);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to enter");
+
+                    while (cbor_value_is_valid(&pdAclMap))
+                    {
+                        char* name = NULL;
+                        size_t len = 0;
+                        CborType type = cbor_value_get_type(&pdAclMap);
+                        if (type == CborTextStringType)
+                        {
+                            cborFindResult = cbor_value_dup_text_string(&pdAclMap, &name,
+                                    &len, NULL);
+                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get text");
+                            cborFindResult = cbor_value_advance(&pdAclMap);
+                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance value");
+                        }
+                        if (name)
+                        {
+                            // Resources -- Mandatory
+                            if (strcmp(name, OIC_JSON_RESOURCES_NAME) == 0)
+                            {
+                                int i = 0;
+                                CborValue resources = { .parser = NULL };
+                                cborFindResult = cbor_value_get_array_length(&pdAclMap,
+                                        &pdacl->resourcesLen);
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get length");
+                                cborFindResult = cbor_value_enter_container(&pdAclMap, &resources);
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to enter");
+                                pdacl->resources = (char **) OICCalloc(pdacl->resourcesLen,
+                                        sizeof(char*));
+                                VERIFY_NON_NULL(TAG, pdacl->resources, ERROR);
+
+                                while (cbor_value_is_valid(&resources))
+                                {
+                                    CborValue rMap = { .parser = NULL  };
+                                    cborFindResult = cbor_value_enter_container(&resources, &rMap);
+                                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Resource Map");
+
+                                    while(cbor_value_is_valid(&rMap))
+                                    {
+                                        char *rMapName = NULL;
+                                        size_t rMapNameLen = 0;
+                                        cborFindResult = cbor_value_dup_text_string(&rMap, &rMapName, &rMapNameLen, NULL);
+                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding RMap Data Name Tag.");
+                                        cborFindResult = cbor_value_advance(&rMap);
+                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding RMap Data Value.");
+
+                                        // "href"
+                                        if (0 == strcmp(OIC_JSON_HREF_NAME, rMapName))
+                                        {
+                                            // TODO : Need to check data structure of OicSecPdAcl_t based on RAML spec.
+                                            cborFindResult = cbor_value_dup_text_string(&rMap, &pdacl->resources[i++], &len, NULL);
+                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Href Value.");
+                                        }
+
+                                        // "rel"
+                                        if (0 == strcmp(OIC_JSON_REL_NAME, rMapName))
+                                        {
+                                            // TODO : Need to check data structure of OicSecPdAcl_t and assign based on RAML spec.
+                                            char *relData = NULL;
+                                            cborFindResult = cbor_value_dup_text_string(&rMap, &relData, &len, NULL);
+                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding REL Value.");
+                                            OICFree(relData);
+                                        }
+
+                                        // "rt"
+                                        if (0 == strcmp(OIC_JSON_RT_NAME, rMapName))
+                                        {
+                                            // TODO : Need to check data structure of OicSecPdAcl_t and assign based on RAML spec.
+                                            char *rtData = NULL;
+                                            cborFindResult = cbor_value_dup_text_string(&rMap, &rtData, &len, NULL);
+                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding RT Value.");
+                                            OICFree(rtData);
+                                        }
+
+                                        // "if"
+                                        if (0 == strcmp(OIC_JSON_IF_NAME, rMapName))
+                                        {
+                                            // TODO : Need to check data structure of OicSecPdAcl_t and assign based on RAML spec.
+                                            char *ifData = NULL;
+                                            cborFindResult = cbor_value_dup_text_string(&rMap, &ifData, &len, NULL);
+                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding IF Value.");
+                                            OICFree(ifData);
+                                        }
+
+                                        if (cbor_value_is_valid(&rMap))
+                                        {
+                                            cborFindResult = cbor_value_advance(&rMap);
+                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Rlist Map.");
+                                        }
+                                        OICFree(rMapName);
+                                    }
+
+                                    if (cbor_value_is_valid(&resources))
+                                    {
+                                        cborFindResult = cbor_value_advance(&resources);
+                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance");
+                                    }
+                                }
+                            }
+
+                            // Permissions -- Mandatory
+                            if (strcmp(name, OIC_JSON_PERMISSION_NAME) == 0)
+                            {
+                                cborFindResult = cbor_value_get_uint64(&pdAclMap,
+                                        (uint64_t *) &pdacl->permission);
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get value");
+                            }
+
+                            // Period -- Not mandatory
+                            if (strcmp(name, OIC_JSON_PERIODS_NAME) == 0)
+                            {
+                                int i = 0;
+                                CborValue period = { .parser = NULL };
+                                cborFindResult = cbor_value_get_array_length(&pdAclMap,
+                                        &pdacl->prdRecrLen);
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get length");
+                                cborFindResult = cbor_value_enter_container(&pdAclMap, &period);
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to enter");
+                                pdacl->periods = (char **) OICCalloc(pdacl->prdRecrLen, sizeof(char*));
+                                VERIFY_NON_NULL(TAG, pdacl->periods, ERROR);
+
+                                while (cbor_value_is_text_string(&period))
+                                {
+                                    cborFindResult = cbor_value_dup_text_string(&period,
+                                            &pdacl->periods[i++], &len, NULL);
+                                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get text");
+                                    cborFindResult = cbor_value_advance(&period);
+                                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance");
+                                    pdacl->prdRecrLen++;
+                                }
+                            }
+
+                            // Recurrence -- Not mandatory
+                            if (strcmp(name, OIC_JSON_RECURRENCES_NAME) == 0)
+                            {
+                                int i = 0;
+                                CborValue recurrences = { .parser = NULL };
+                                cborFindResult = cbor_value_get_array_length(&pdAclMap, &pdacl->prdRecrLen);
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get length");
+                                cborFindResult = cbor_value_enter_container(&pdAclMap, &recurrences);
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to enter");
+                                pdacl->recurrences = (char **) OICCalloc(pdacl->prdRecrLen, sizeof(char*));
+                                VERIFY_NON_NULL(TAG, pdacl->recurrences, ERROR);
+
+                                while (cbor_value_is_text_string(&recurrences))
+                                {
+                                    cborFindResult = cbor_value_dup_text_string(&recurrences,
+                                            &pdacl->recurrences[i++], &len, NULL);
+                                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get value");
+                                    cborFindResult = cbor_value_advance(&recurrences);
+                                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance");
+                                }
+                            }
+                            if (type != CborMapType && cbor_value_is_valid(&pdAclMap))
+                            {
+                                cborFindResult = cbor_value_advance(&pdAclMap);
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance");
+                            }
+                        }
+                        if (cbor_value_is_valid(&pdAclArray))
+                        {
+                            cborFindResult = cbor_value_advance(&pdAclArray);
+                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance");
+                        }
+                        OICFree(name);
+                        name = NULL;
+                    }
+                    pdacl->next = NULL;
+                    if (headPdacl == NULL)
+                    {
+                        headPdacl = pdacl;
+                    }
+                    else
+                    {
+                        OicSecPdAcl_t *temp = headPdacl;
+                        while (temp->next)
+                        {
+                            temp = temp->next;
+                        }
+                        temp->next = pdacl;
+                    }
+                }
+                pconf->pdacls = headPdacl;
+            }
+
+            //PDDev -- Mandatory
+            if (strcmp(name, OIC_JSON_PDDEV_LIST_NAME) == 0)
+            {
+                int i = 0;
+                CborValue pddevs = { .parser = NULL };
+                cborFindResult = cbor_value_get_array_length(&pconfMap, &pconf->pddevLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get length");
+                cborFindResult = cbor_value_enter_container(&pconfMap, &pddevs);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to enter");
+
+                pconf->pddevs = (OicUuid_t *)OICMalloc(pconf->pddevLen * sizeof(OicUuid_t));
+                VERIFY_NON_NULL(TAG, pconf->pddevs, ERROR);
+                while (cbor_value_is_valid(&pddevs))
+                {
+                    char *pddev = NULL;
+                    cborFindResult = cbor_value_dup_text_string(&pddevs, &pddev, &len, NULL);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get value");
+                    cborFindResult = cbor_value_advance(&pddevs);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance");
+                    ret = ConvertStrToUuid(pddev, &pconf->pddevs[i++]);
+                    VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
+                    OICFree(pddev);
+                }
+            }
+
+            //Mandatory - Device Id
+            if (0 == strcmp(OIC_JSON_DEVICE_ID_NAME, name))
+            {
+                char *deviceId = NULL;
+                cborFindResult = cbor_value_dup_text_string(&pconfMap, &deviceId, &len, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get deviceID");
+                ret = ConvertStrToUuid(deviceId, &pconf->deviceID);
+                VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
+                OICFree(deviceId);
+            }
+
+            // ROwner -- Mandatory
+            if (0 == strcmp(OIC_JSON_ROWNERID_NAME, name))
+            {
+                char *rowner = NULL;
+                cborFindResult = cbor_value_dup_text_string(&pconfMap, &rowner, &len, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get rowner");
+                ret = ConvertStrToUuid(rowner, &pconf->rownerID);
+                VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
+                OICFree(rowner);
+            }
+        }
+        if (CborMapType != type && cbor_value_is_valid(&pconfMap))
+        {
+            cborFindResult = cbor_value_advance(&pconfMap);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance");
+        }
+        OICFree(name);
+        name = NULL;
+    }
+    *secPconf=pconf;
+    ret = OC_STACK_OK;
+exit:
+    if (CborNoError != cborFindResult)
+    {
+        OIC_LOG (ERROR, TAG, "CBORPayloadToPconf failed");
+        DeletePconfBinData(pconf);
+        pconf = NULL;
+        *secPconf = NULL;
+        ret = OC_STACK_ERROR;
+    }
+    return ret;
+}
+
+static bool UpdatePersistentStorage(const OicSecPconf_t * pconf)
+{
+    bool ret = false;
+
+    // Convert PCONF data into Cborpayload for update to persistent storage
+    uint8_t *payload = NULL;
+    size_t size = 0;
+    if (OC_STACK_OK == PconfToCBORPayload(pconf, &payload, &size) && NULL !=payload)
+    {
+        if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_PCONF_NAME, payload, size))
+        {
+            ret = true;
+        }
+        OICFree(payload);
+    }
+    return ret;
+}
+
+static OCEntityHandlerResult HandlePconfGetRequest (const OCEntityHandlerRequest * ehRequest)
+{
+    uint8_t* payload = NULL;
+    size_t size = 0;
+    OCEntityHandlerResult ehRet = OC_EH_OK;
+
+    OicSecPconf_t pconf;
+    memset(&pconf, 0, sizeof(OicSecPconf_t));
+
+    OIC_LOG (DEBUG, TAG, "Pconf EntityHandle processing GET request");
+
+    if (true == GetDoxmResourceData()->dpc)
+    {
+        //Making response elements for Get request
+        if( (true == gPconf->edp) &&
+            (gPconf->prm && 0 < gPconf->prmLen) &&
+            (0 < strlen((const char*)gPconf->deviceID.id)) &&
+            (0 < strlen((const char*)gPconf->rownerID.id)))
+        {
+            pconf.edp = true;
+            pconf.prm = gPconf->prm;
+            pconf.prmLen = gPconf->prmLen;
+            memcpy(&pconf.deviceID, &gPconf->deviceID, sizeof(OicUuid_t));
+            memcpy(&pconf.rownerID, &gPconf->rownerID, sizeof(OicUuid_t));
+            OIC_LOG (DEBUG, TAG, "PCONF - direct pairing enabled");
+        }
+        else if (false == gPconf->edp)
+        {
+            pconf.edp = false;
+            memcpy(&pconf.rownerID, &gPconf->rownerID, sizeof(OicUuid_t));
+            OIC_LOG (DEBUG, TAG, "PCONF - direct pairing disable");
+        }
+        else
+        {
+            ehRet= OC_EH_ERROR;
+            OIC_LOG (DEBUG, TAG, "PCONF - error");
+        }
+    }
+    else
+    {
+        OIC_LOG (DEBUG, TAG, "DPC == false : Direct-Pairing Disabled");
+    }
+
+
+    if (OC_STACK_OK != PconfToCBORPayload(gPconf, &payload, &size))
+    {
+        ehRet = OC_EH_ERROR;
+    }
+
+    if(OC_EH_OK == ehRet)
+    {
+        ehRet = (payload ? OC_EH_OK : OC_EH_ERROR);
+    }
+    else
+    {
+        OICFree(payload);
+        payload = NULL;
+        size = 0;
+    }
+
+    // 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 HandlePconfGetRequest");
+    }
+    OIC_LOG_V(DEBUG, TAG, "%s RetVal %d", __func__, ehRet);
+
+    OICFree(payload);
+    return ehRet;
+}
+
+static OCEntityHandlerResult HandlePconfPostRequest (const OCEntityHandlerRequest * ehRequest)
+{
+    OCEntityHandlerResult ehRet = OC_EH_OK;
+    OCStackResult res=OC_STACK_OK;
+    OicSecPconf_t* newPconf = NULL;
+
+    if (true == GetDoxmResourceData()->dpc)
+    {
+        // Convert CBOR PCONF data into binary. This will also validate the PCONF data received.
+        uint8_t *payload = ((OCSecurityPayload *) ehRequest->payload)->securityData;
+        size_t size = ((OCSecurityPayload *) ehRequest->payload)->payloadSize;
+
+        if(payload){
+            res = CBORPayloadToPconf(payload, size, &newPconf);
+        }
+    }
+    else
+    {
+        OIC_LOG (DEBUG, TAG, "DPC == false : Direct-Pairing Disabled");
+        ehRet = OC_EH_ERROR;
+    }
+
+    if (newPconf && res == OC_STACK_OK)
+    {
+        // Check if valid Post request
+        if ((true == newPconf->edp) && (0 < newPconf->prmLen) &&
+                DP_PIN_LENGTH == sizeof(newPconf->pin.val))
+        {
+            OicSecPrm_t *oldPrm = gPconf->prm;
+            OicSecPdAcl_t *oldPdacl = gPconf->pdacls;
+
+            // Update local PCONF with new PCONF
+            gPconf->edp = true;
+            memcpy(&gPconf->pin, &newPconf->pin, sizeof(OicDpPin_t));
+            gPconf->prm = newPconf->prm;
+            gPconf->prmLen = newPconf->prmLen;
+            gPconf->pdacls = newPconf->pdacls;
+            memcpy(&gPconf->rownerID, &newPconf->rownerID, sizeof(OicUuid_t));
+
+            // to delete old value(prm, pdacl)
+            newPconf->prm = oldPrm;
+            newPconf->pdacls = oldPdacl;
+        }
+        else if (false == newPconf->edp)
+        {
+            gPconf->edp = false;
+        }
+        else
+        {
+            ehRet = OC_EH_ERROR;
+        }
+
+        // Update storage
+        if(OC_EH_ERROR != ehRet && true == UpdatePersistentStorage(gPconf))
+        {
+            ehRet = OC_EH_RESOURCE_CREATED;
+        }
+
+        DeletePconfBinData(newPconf);
+    }
+    else
+    {
+        ehRet = OC_EH_ERROR;
+    }
+
+    // Send payload to request originator
+    if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL, 0))
+    {
+        ehRet = OC_EH_ERROR;
+        OIC_LOG(ERROR, TAG, "SendSRMResponse failed in HandlePconfPostRequest");
+    }
+
+    OIC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
+    return ehRet;
+}
+
+/*
+ * This internal method is the entity handler for PCONF resources and
+ * will handle REST request (POST) for them.
+ */
+OCEntityHandlerResult PconfEntityHandler (OCEntityHandlerFlag flag,
+                                        OCEntityHandlerRequest * ehRequest,
+                                        void* callbackParameter)
+{
+    OIC_LOG(DEBUG, TAG, "Received request PconfEntityHandler");
+    (void)callbackParameter;
+    OCEntityHandlerResult ehRet = OC_EH_ERROR;
+
+    if (!ehRequest)
+    {
+        return ehRet;
+    }
+
+    if (flag & OC_REQUEST_FLAG)
+    {
+        OIC_LOG (DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
+        switch (ehRequest->method)
+        {
+            case OC_REST_GET:
+                ehRet = HandlePconfGetRequest(ehRequest);
+                break;
+
+            case OC_REST_POST:
+                ehRet = HandlePconfPostRequest(ehRequest);
+                break;
+
+            case OC_REST_DELETE:
+                break;
+
+            default:
+                ehRet = OC_EH_ERROR;
+                SendSRMResponse(ehRequest, ehRet, NULL, 0);
+        }
+    }
+
+    return ehRet;
+}
+
+/*
+ * This internal method is used to create '/oic/sec/pconf' resource.
+ */
+OCStackResult CreatePconfResource()
+{
+    OCStackResult ret;
+
+    ret = OCCreateResource(&gPconfHandle,
+                           OIC_RSRC_TYPE_SEC_PCONF,
+                           OIC_MI_DEF,
+                           OIC_RSRC_PCONF_URI,
+                           PconfEntityHandler,
+                           NULL,
+                           OC_SECURE | OC_EXPLICIT_DISCOVERABLE);
+
+    if (OC_STACK_OK != ret)
+    {
+        OIC_LOG (ERROR, TAG, "Unable to instantiate PCONF resource");
+        DeInitPconfResource();
+    }
+    return ret;
+}
+
+/**
+ * Get the default value.
+ * @retval  the gDefaultPconf pointer;
+ */
+static OicSecPconf_t* GetPconfDefault()
+{
+    OIC_LOG (DEBUG, TAG, "GetPconfDefault");
+
+    return &gDefaultPconf;
+}
+
+/**
+ * This method is used by SRM to retrieve PCONF resource data..
+ *
+ * @retval  reference to @ref OicSecPconf_t, binary format of Pconf resource data
+ */
+const OicSecPconf_t* GetPconfResourceData()
+{
+    return gPconf;
+}
+
+/**
+ * Initialize PCONF resource by loading data from persistent storage.
+ *
+ * @retval  OC_STACK_OK for Success, otherwise some error value
+ */
+OCStackResult InitPconfResource()
+{
+    OCStackResult ret = OC_STACK_ERROR;
+
+    uint8_t *data = NULL;
+    size_t size = 0;
+
+    ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_PCONF_NAME, &data, &size);
+    // If database read failed
+    if (ret != OC_STACK_OK)
+    {
+        OIC_LOG(DEBUG, TAG, "ReadSVDataFromPS failed");
+    }
+    if (data)
+    {
+        CBORPayloadToPconf(data, size, &gPconf);
+    }
+
+    if (!data || !gPconf)
+    {
+        gPconf = GetPconfDefault();
+
+        // device id from doxm
+        OicUuid_t deviceId = {.id = {0}};
+        OCStackResult ret = GetDoxmDeviceID( &deviceId);
+        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+        memcpy(&gPconf->deviceID, &deviceId, sizeof(OicUuid_t));
+    }
+    VERIFY_NON_NULL(TAG, gPconf, ERROR);
+
+    // Instantiate 'oic.sec.pconf'
+    ret = CreatePconfResource();
+
+exit:
+    if (OC_STACK_OK != ret)
+    {
+        DeInitPconfResource();
+    }
+    OICFree(data);
+    return ret;
+}
+
+/**
+ * Perform cleanup for PCONF resources.
+ *
+ * @return
+ * OC_STACK_OK    - no error
+ * OC_STACK_ERROR - stack process error
+ *
+ */
+OCStackResult DeInitPconfResource()
+{
+    OCStackResult ret = OCDeleteResource(gPconfHandle);
+    if(gPconf!= &gDefaultPconf)
+    {
+        DeletePconfBinData(gPconf);
+    }
+    gPconf = NULL;
+
+    if(OC_STACK_OK == ret)
+    {
+        return OC_STACK_OK;
+    }
+    else
+    {
+        return OC_STACK_ERROR;
+    }
+}
+
+/**
+ * This method might be used to add a paired device id after direct-pairing process complete.
+ *
+ * @param pdeviceId ID of the paired device.
+ *
+ * @retval  OC_STACK_OK for Success, otherwise some error value
+ */
+OCStackResult AddPairedDevice(OicUuid_t *pdeviceId)
+{
+    if (!gPconf || !pdeviceId)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+
+    OicUuid_t *prevList = gPconf->pddevs;
+    gPconf->pddevs = (OicUuid_t *)OICCalloc(gPconf->pddevLen+1, sizeof(OicUuid_t));
+    if(!gPconf->pddevs)
+    {
+        return OC_STACK_NO_MEMORY;
+    }
+    for (size_t i=0; i<gPconf->pddevLen; i++)
+    {
+        memcpy(&gPconf->pddevs[i], &prevList[i], sizeof(OicUuid_t));
+    }
+
+    // add new paired device id
+    memcpy(&gPconf->pddevs[gPconf->pddevLen], pdeviceId, sizeof(OicUuid_t));
+    gPconf->pddevLen++;
+
+    // Update storage
+    if(true != UpdatePersistentStorage(gPconf))
+    {
+        OIC_LOG (ERROR, TAG, "Fail to update pconf resource");
+        return OC_STACK_ERROR;
+    }
+
+    OIC_LOG (ERROR, TAG, "Add paired device success");
+    return OC_STACK_OK;
+}
+
+/**
+ * This method might be used by PolicyEngine to retrieve PDACL for a Subject.
+ *
+ * @param subjectId ID of the subject for which PDACL is required.
+ * @param savePtr is used internally by @ref GetACLResourceData to maintain index between
+ *                successive calls for same subjectId.
+ *
+ * @retval  reference to @ref OicSecPdAcl_t if PDACL is found, else NULL
+ */
+const OicSecPdAcl_t* GetPdAclData(const OicUuid_t* subjectId, OicSecPdAcl_t **savePtr)
+{
+    OicSecPdAcl_t *pdacl = NULL;
+
+    if ( NULL == subjectId)
+    {
+        return NULL;
+    }
+
+    /*
+     * savePtr MUST point to NULL if this is the 'first' call to retrieve PDACL for
+     * subjectID.
+     */
+    if (NULL == *savePtr)
+    {
+        pdacl = gPconf->pdacls;
+
+        // Find if 'subjectID' is in paired device list.
+        for(size_t i=0; i<gPconf->pddevLen; i++)
+        {
+            if (memcmp(&(gPconf->pddevs[i]), subjectId, sizeof(OicUuid_t)) == 0)
+            {
+                *savePtr = pdacl;
+                return pdacl;
+            }
+        }
+    }
+    else
+    {
+        OicSecPdAcl_t *temp = NULL;
+
+        /*
+         * If this is a 'successive' call, search for location pointed by
+         * savePtr and assign 'begin' to the next PDACL after it in the linked
+         * list and start searching from there.
+         */
+        LL_FOREACH(gPconf->pdacls, temp)
+        {
+            if (temp == *savePtr)
+            {
+                pdacl = temp->next;
+                *savePtr = pdacl;
+                return pdacl;
+            }
+        }
+    }
+
+    // Cleanup in case no PDACL is found
+    *savePtr = NULL;
+    return NULL;
+}
+
+/**
+ * This method return whether device is paired or not.
+ *
+ * @param pdeviceId Target device ID to find in paired list.
+ * @retval  ture if device is already paired, else false
+ */
+bool IsPairedDevice(const OicUuid_t* pdeviceId)
+{
+    // Find if 'pdeviceId' is in paired device list.
+    for(size_t i=0; i<gPconf->pddevLen; i++)
+    {
+        if (memcmp(&(gPconf->pddevs[i]), pdeviceId, sizeof(OicUuid_t)) == 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+OCStackResult SetPconfRownerId(const OicUuid_t* newROwner)
+{
+    OCStackResult ret = OC_STACK_ERROR;
+    uint8_t *cborPayload = NULL;
+    size_t size = 0;
+    OicUuid_t prevId = {.id={0}};
+
+    if(NULL == newROwner)
+    {
+        ret = OC_STACK_INVALID_PARAM;
+    }
+    if(NULL == gPconf)
+    {
+        ret = OC_STACK_NO_RESOURCE;
+    }
+
+    if(newROwner && gPconf)
+    {
+        memcpy(prevId.id, gPconf->rownerID.id, sizeof(prevId.id));
+        memcpy(gPconf->rownerID.id, newROwner->id, sizeof(newROwner->id));
+
+        ret = PconfToCBORPayload(gPconf, &cborPayload, &size);
+        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+
+        ret = UpdateSecureResourceInPS(OIC_JSON_PCONF_NAME, cborPayload, size);
+        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+
+        OICFree(cborPayload);
+    }
+
+    return ret;
+
+exit:
+    OICFree(cborPayload);
+    memcpy(gPconf->rownerID.id, prevId.id, sizeof(prevId.id));
+    return ret;
+}
+
+OCStackResult GetPconfRownerId(OicUuid_t *rowneruuid)
+{
+    OCStackResult retVal = OC_STACK_ERROR;
+    if (gPconf)
+    {
+        *rowneruuid = gPconf->rownerID;
+        retVal = OC_STACK_OK;
+    }
+    return retVal;
+}
index ef7b005..04f0fc3 100644 (file)
@@ -17,6 +17,7 @@
 // limitations under the License.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#include <string.h>
 
 #include "oic_malloc.h"
 #include "policyengine.h"
 #include "srmutility.h"
 #include "doxmresource.h"
 #include "iotvticalendar.h"
-#include <string.h>
+#include "pstatresource.h"
+#include "dpairingresource.h"
+#include "pconfresource.h"
+#include "amaclresource.h"
+#include "credresource.h"
 
 #define TAG "SRM-PE"
 
-/**
- * Return the uint16_t CRUDN permission corresponding to passed CAMethod_t.
- */
 uint16_t GetPermissionFromCAMethod_t(const CAMethod_t method)
 {
     uint16_t perm = 0;
-    switch(method)
+    switch (method)
     {
         case CA_GET:
             perm = (uint16_t)PERMISSION_READ;
@@ -59,16 +61,22 @@ uint16_t GetPermissionFromCAMethod_t(const CAMethod_t method)
 }
 
 /**
- * @brief Compares two OicUuid_t structs.
+ * Compares two OicUuid_t structs.
+ *
  * @return true if the two OicUuid_t structs are equal, else false.
  */
-bool UuidCmp(OicUuid_t *firstId, OicUuid_t *secondId)
+static bool UuidCmp(OicUuid_t *firstId, OicUuid_t *secondId)
 {
     // TODO use VERIFY macros to check for null when they are merged.
     if(NULL == firstId || NULL == secondId)
     {
         return false;
     }
+    // Check empty uuid string
+    if('\0' == firstId->id[0] || '\0' == secondId->id[0])
+    {
+        return false;
+    }
     for(int i = 0; i < UUID_LENGTH; i++)
     {
         if(firstId->id[i] != secondId->id[i])
@@ -79,12 +87,9 @@ bool UuidCmp(OicUuid_t *firstId, OicUuid_t *secondId)
     return true;
 }
 
-/**
- * Set the state and clear other stateful context vars.
- */
 void SetPolicyEngineState(PEContext_t *context, const PEState_t state)
 {
-    if(NULL == context)
+    if (NULL == context)
     {
         return;
     }
@@ -96,6 +101,9 @@ void SetPolicyEngineState(PEContext_t *context, const PEState_t state)
     context->matchingAclFound = false;
     context->amsProcessing = false;
     context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
+
+    FreeCARequestInfo(context->amsMgrContext->requestInfo);
+    OICFree(context->amsMgrContext->endpoint);
     memset(context->amsMgrContext, 0, sizeof(AmsMgrContext_t));
 
     // Set state.
@@ -103,28 +111,102 @@ void SetPolicyEngineState(PEContext_t *context, const PEState_t state)
 }
 
 /**
- * @brief Compare the request's subject to DevOwner.
+ * Compare the request's subject to DevOwner.
  *
- * @return true if context->subjectId == GetDoxmDevOwner(), else false
+ * @return true if context->subjectId == GetDoxmDevOwner(), else false.
  */
-bool IsRequestFromDevOwner(PEContext_t *context)
+static bool IsRequestFromDevOwner(PEContext_t *context)
 {
     bool retVal = false;
-    OicUuid_t owner;
+    OicUuid_t ownerid;
 
     if(NULL == context)
     {
-        return OC_STACK_ERROR;
+        return retVal;
     }
 
-    if(OC_STACK_OK == GetDoxmDevOwnerId(&owner))
+    if(OC_STACK_OK == GetDoxmDevOwnerId(&ownerid))
     {
-        retVal = UuidCmp(&context->subject, &owner);
+        retVal = UuidCmp(&context->subject, &ownerid);
     }
 
     return retVal;
 }
 
+// TODO - remove these function placeholders as they are implemented
+// in the resource entity handler code.
+// Note that because many SVRs do not have a rowner, in those cases we
+// just return "OC_STACK_ERROR" which results in a "false" return by
+// IsRequestFromResourceOwner().
+// As these SVRs are revised to have a rowner, these functions should be
+// replaced (see pstatresource.c for example of GetPstatRownerId).
+
+OCStackResult GetCrlRownerId(OicUuid_t *rowner)
+{
+    rowner = NULL;
+    return OC_STACK_ERROR;
+}
+
+OCStackResult GetSaclRownerId(OicUuid_t *rowner)
+{
+    rowner = NULL;
+    return OC_STACK_ERROR;
+}
+
+OCStackResult GetSvcRownerId(OicUuid_t *rowner)
+{
+    rowner = NULL;
+    return OC_STACK_ERROR;
+}
+
+static GetSvrRownerId_t GetSvrRownerId[OIC_SEC_SVR_TYPE_COUNT] = {
+    GetAclRownerId,
+    GetAmaclRownerId,
+    GetCredRownerId,
+    GetCrlRownerId,
+    GetDoxmRownerId,
+    GetDpairingRownerId,
+    GetPconfRownerId,
+    GetPstatRownerId,
+    GetSaclRownerId,
+    GetSvcRownerId
+};
+
+/**
+ * Compare the request's subject to resource.ROwner.
+ *
+ * @return true if context->subjectId equals SVR rowner id, else return false
+ */
+bool IsRequestFromResourceOwner(PEContext_t *context)
+{
+    bool retVal = false;
+    OicUuid_t resourceOwner;
+
+    if(NULL == context)
+    {
+        return false;
+    }
+
+    if((OIC_R_ACL_TYPE <= context->resourceType) && \
+        (OIC_SEC_SVR_TYPE_COUNT > context->resourceType))
+    {
+        if(OC_STACK_OK == GetSvrRownerId[(int)context->resourceType](&resourceOwner))
+        {
+            retVal = UuidCmp(&context->subject, &resourceOwner);
+        }
+    }
+
+    if(true == retVal)
+    {
+        OIC_LOG(INFO, TAG, "PE.IsRequestFromResourceOwner(): returning true");
+    }
+    else
+    {
+        OIC_LOG(INFO, TAG, "PE.IsRequestFromResourceOwner(): returning false");
+    }
+
+    return retVal;
+}
 
 inline static bool IsRequestSubjectEmpty(PEContext_t *context)
 {
@@ -139,17 +221,18 @@ inline static bool IsRequestSubjectEmpty(PEContext_t *context)
             true : false;
 }
 
-
 /**
  * Bitwise check to see if 'permission' contains 'request'.
- * @param   permission  The allowed CRUDN permission.
- * @param   request     The CRUDN permission being requested.
+ *
+ * @param permission is the allowed CRUDN permission.
+ * @param request is the CRUDN permission being requested.
+ *
  * @return true if 'permission' bits include all 'request' bits.
  */
 static inline bool IsPermissionAllowingRequest(const uint16_t permission,
     const uint16_t request)
 {
-    if(request == (request & permission))
+    if (request == (request & permission))
     {
         return true;
     }
@@ -161,6 +244,7 @@ static inline bool IsPermissionAllowingRequest(const uint16_t permission,
 
 /**
  * Compare the passed subject to the wildcard (aka anonymous) subjectId.
+ *
  * @return true if 'subject' is the wildcard, false if it is not.
  */
 static inline bool IsWildCardSubject(OicUuid_t *subject)
@@ -184,15 +268,14 @@ static inline bool IsWildCardSubject(OicUuid_t *subject)
 /**
  * Copy the subject, resource and permission into the context fields.
  */
-void CopyParamsToContext(
-    PEContext_t     *context,
-    const OicUuid_t *subjectId,
-    const char      *resource,
-    const uint16_t  requestedPermission)
+static void CopyParamsToContext(PEContext_t     *context,
+                                const OicUuid_t *subjectId,
+                                const char      *resource,
+                                const uint16_t  requestedPermission)
 {
     size_t length = 0;
 
-    if(NULL == context || NULL == subjectId || NULL == resource)
+    if (NULL == context || NULL == subjectId || NULL == resource)
     {
         return;
     }
@@ -201,7 +284,7 @@ void CopyParamsToContext(
 
     // Copy the resource string into context.
     length = strlen(resource) + 1;
-    if(0 < length)
+    if (0 < length)
     {
         strncpy(context->resource, resource, length);
         context->resource[length - 1] = '\0';
@@ -211,39 +294,39 @@ void CopyParamsToContext(
     context->permission = requestedPermission;
 }
 
-
 /**
  * Check whether 'resource' is getting accessed within the valid time period.
- * @param   acl         The ACL to check.
- * @return
- *      true if access is within valid time period or if the period or recurrence is not present.
- *      false if period and recurrence present and the access is not within valid time period.
+ *
+ * @param acl is the ACL to check.
+ *
+ * @return true if access is within valid time period or if the period or recurrence is not present.
+ * false if period and recurrence present and the access is not within valid time period.
  */
 static bool IsAccessWithinValidTime(const OicSecAcl_t *acl)
 {
 #ifndef WITH_ARDUINO //Period & Recurrence not supported on Arduino due
                      //lack of absolute time
-    if(NULL== acl || NULL == acl->periods || 0 == acl->prdRecrLen)
+    if (NULL== acl || NULL == acl->periods || 0 == acl->prdRecrLen)
     {
         return true;
     }
 
     //periods & recurrences rules are paired.
-    if(NULL == acl->recurrences)
+    if (NULL == acl->recurrences)
     {
         return false;
     }
 
-    for(size_t i = 0; i < acl->prdRecrLen; i++)
+    for (size_t i = 0; i < acl->prdRecrLen; i++)
     {
-        if(IOTVTICAL_VALID_ACCESS ==  IsRequestWithinValidTime(acl->periods[i],
+        if (IOTVTICAL_VALID_ACCESS ==  IsRequestWithinValidTime(acl->periods[i],
             acl->recurrences[i]))
         {
-            OC_LOG(INFO, TAG, "Access request is in allowed time period");
+            OIC_LOG(INFO, TAG, "Access request is in allowed time period");
             return true;
         }
     }
-    OC_LOG(ERROR, TAG, "Access request is in invalid time period");
+    OIC_LOG(ERROR, TAG, "Access request is in invalid time period");
     return false;
 
 #else
@@ -253,21 +336,23 @@ static bool IsAccessWithinValidTime(const OicSecAcl_t *acl)
 
 /**
  * Check whether 'resource' is in the passed ACL.
- * @param   resource    The resource to search for.
- * @param   acl         The ACL to check.
+ *
+ * @param resource is the resource being searched.
+ * @param acl is the ACL to check.
+ *
  * @return true if 'resource' found, otherwise false.
  */
- bool IsResourceInAcl(const char *resource, const OicSecAcl_t *acl)
static bool IsResourceInAcl(const char *resource, const OicSecAcl_t *acl)
 {
-    if(NULL== acl || NULL == resource)
+    if (NULL== acl || NULL == resource)
     {
         return false;
     }
 
-     for(size_t n = 0; n < acl->resourcesLen; n++)
+     for (size_t n = 0; n < acl->resourcesLen; n++)
      {
-         if(0 == strcmp(resource, acl->resources[n]) || // TODO null terms?
-                 0 == strcmp(WILDCARD_RESOURCE_URI, acl->resources[n]))
+         if (0 == strcmp(resource, acl->resources[n]) || // TODO null terms?
+             0 == strcmp(WILDCARD_RESOURCE_URI, acl->resources[n]))
          {
              return true;
          }
@@ -281,16 +366,14 @@ static bool IsAccessWithinValidTime(const OicSecAcl_t *acl)
  * Search each ACL for requested resource.
  * If resource found, check for context->permission and period validity.
  * If the ACL is not found locally and AMACL for the resource is found
- * then sends the request to AMS service for the ACL
+ * then sends the request to AMS service for the ACL.
  * Set context->retVal to result from first ACL found which contains
  * correct subject AND resource.
- *
- * @retval void
  */
-void ProcessAccessRequest(PEContext_t *context)
+static void ProcessAccessRequest(PEContext_t *context)
 {
-    OC_LOG(DEBUG, TAG, "Entering ProcessAccessRequest()");
-    if(NULL != context)
+    OIC_LOG(DEBUG, TAG, "Entering ProcessAccessRequest()");
+    if (NULL != context)
     {
         const OicSecAcl_t *currentAcl = NULL;
         OicSecAcl_t *savePtr = NULL;
@@ -302,28 +385,28 @@ void ProcessAccessRequest(PEContext_t *context)
         // ACL for this request.
         do
         {
-            OC_LOG_V(DEBUG, TAG, "%s: getting ACL..." ,__func__);
+            OIC_LOG_V(DEBUG, TAG, "%s: getting ACL..." ,__func__);
             currentAcl = GetACLResourceData(&context->subject, &savePtr);
 
-            if(NULL != currentAcl)
+            if (NULL != currentAcl)
             {
                 // Found the subject, so how about resource?
-                OC_LOG_V(DEBUG, TAG, "%s:found ACL matching subject" ,__func__);
+                OIC_LOG_V(DEBUG, TAG, "%s:found ACL matching subject" ,__func__);
 
                 // Subject was found, so err changes to Rsrc not found for now.
                 context->retVal = ACCESS_DENIED_RESOURCE_NOT_FOUND;
-                OC_LOG_V(DEBUG, TAG, "%s:Searching for resource..." ,__func__);
-                if(IsResourceInAcl(context->resource, currentAcl))
+                OIC_LOG_V(DEBUG, TAG, "%s:Searching for resource..." ,__func__);
+                if (IsResourceInAcl(context->resource, currentAcl))
                 {
-                    OC_LOG_V(INFO, TAG, "%s:found matching resource in ACL" ,__func__);
+                    OIC_LOG_V(INFO, TAG, "%s:found matching resource in ACL" ,__func__);
                     context->matchingAclFound = true;
 
                     // Found the resource, so it's down to valid period & permission.
                     context->retVal = ACCESS_DENIED_INVALID_PERIOD;
-                    if(IsAccessWithinValidTime(currentAcl))
+                    if (IsAccessWithinValidTime(currentAcl))
                     {
                         context->retVal = ACCESS_DENIED_INSUFFICIENT_PERMISSION;
-                        if(IsPermissionAllowingRequest(currentAcl->permission, context->permission))
+                        if (IsPermissionAllowingRequest(currentAcl->permission, context->permission))
                         {
                             context->retVal = ACCESS_GRANTED;
                         }
@@ -332,40 +415,29 @@ void ProcessAccessRequest(PEContext_t *context)
             }
             else
             {
-                OC_LOG_V(INFO, TAG, "%s:no ACL found matching subject for resource %s",__func__, context->resource);
+                OIC_LOG_V(INFO, TAG, "%s:no ACL found matching subject for resource %s",__func__, context->resource);
             }
-        }
-        while((NULL != currentAcl) && (false == context->matchingAclFound));
+        } while ((NULL != currentAcl) && (false == context->matchingAclFound));
 
-        if(IsAccessGranted(context->retVal))
+        if (IsAccessGranted(context->retVal))
         {
-            OC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_GRANTED)", __func__);
+            OIC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_GRANTED)", __func__);
         }
         else
         {
-            OC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_DENIED)", __func__);
+            OIC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_DENIED)", __func__);
         }
     }
     else
     {
-        OC_LOG_V(ERROR, TAG, "%s:Leaving ProcessAccessRequest(context is NULL)", __func__);
+        OIC_LOG_V(ERROR, TAG, "%s:Leaving ProcessAccessRequest(context is NULL)", __func__);
     }
 }
 
-/**
- * Check whether a request should be allowed.
- * @param   context     Pointer to (Initialized) Policy Engine context to use.
- * @param   subjectId   Pointer to Id of the requesting entity.
- * @param   resource    Pointer to URI of Resource being requested.
- * @param   permission  Requested permission.
- * @return  ACCESS_GRANTED if request should go through,
- *          otherwise some flavor of ACCESS_DENIED
- */
-SRMAccessResponse_t CheckPermission(
-    PEContext_t     *context,
-    const OicUuid_t *subjectId,
-    const char      *resource,
-    const uint16_t  requestedPermission)
+SRMAccessResponse_t CheckPermission(PEContext_t     *context,
+                                    const OicUuid_t *subjectId,
+                                    const char      *resource,
+                                    const uint16_t  requestedPermission)
 {
     SRMAccessResponse_t retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
 
@@ -376,9 +448,9 @@ SRMAccessResponse_t CheckPermission(
     // Each state machine context can only be processing one request at a time.
     // Therefore if the context is not in AWAITING_REQUEST or AWAITING_AMS_RESPONSE
     // state, return error. Otherwise, change to BUSY state and begin processing request.
-    if(AWAITING_REQUEST == context->state || AWAITING_AMS_RESPONSE == context->state)
+    if (AWAITING_REQUEST == context->state || AWAITING_AMS_RESPONSE == context->state)
     {
-        if(AWAITING_REQUEST == context->state)
+        if (AWAITING_REQUEST == context->state)
         {
             SetPolicyEngineState(context, BUSY);
             CopyParamsToContext(context, subjectId, resource, requestedPermission);
@@ -386,10 +458,16 @@ SRMAccessResponse_t CheckPermission(
 
         // Before doing any processing, check if request coming
         // from DevOwner and if so, always GRANT.
-        if(IsRequestFromDevOwner(context))
+        if (IsRequestFromDevOwner(context))
+        {
+            context->retVal = ACCESS_GRANTED;
+        }
+        // Then check if request is for a SVR and coming from rowner
+        else if (IsRequestFromResourceOwner(context))
         {
             context->retVal = ACCESS_GRANTED;
         }
+        // Else request is a "normal" request that must be tested against ACL
         else
         {
             OicUuid_t saveSubject = {.id={}};
@@ -398,7 +476,7 @@ SRMAccessResponse_t CheckPermission(
             ProcessAccessRequest(context);
 
             // If matching ACL not found, and subject != wildcard, try wildcard.
-            if((false == context->matchingAclFound) && \
+            if ((false == context->matchingAclFound) && \
               (false == IsWildCardSubject(&context->subject)))
             {
                 //Saving subject for Amacl check
@@ -415,7 +493,7 @@ SRMAccessResponse_t CheckPermission(
             }
 
             //No local ACE found for the request so checking Amacl resource
-            if(ACCESS_GRANTED != context->retVal)
+            if (ACCESS_GRANTED != context->retVal)
             {
                 //If subject is not empty then restore the original subject
                 //else keep the subject to WILDCARD_SUBJECT_ID
@@ -442,16 +520,9 @@ SRMAccessResponse_t CheckPermission(
     // Capture retVal before resetting state for next request.
     retVal = context->retVal;
 
-    //Change the state of PE to "AWAITING_AMS_RESPONSE", if waiting
-    //for response from AMS service else to "AWAITING_REQUEST"
-    if(ACCESS_WAITING_FOR_AMS == retVal)
+   if (!context->amsProcessing)
     {
-        OC_LOG(INFO, TAG, "Setting PE State to AWAITING_AMS_RESPONSE");
-        context->state = AWAITING_AMS_RESPONSE;
-    }
-    else if(!context->amsProcessing)
-    {
-        OC_LOG(INFO, TAG, "Resetting PE context and PE State to AWAITING_REQUEST");
+        OIC_LOG(INFO, TAG, "Resetting PE context and PE State to AWAITING_REQUEST");
         SetPolicyEngineState(context, AWAITING_REQUEST);
     }
 
@@ -459,30 +530,23 @@ exit:
     return retVal;
 }
 
-/**
- * Initialize the Policy Engine. Call this before calling CheckPermission().
- * @param   context     Pointer to Policy Engine context to initialize.
- * @return  OC_STACK_OK for Success, otherwise some error value
- */
 OCStackResult InitPolicyEngine(PEContext_t *context)
 {
-    if(NULL== context)
+    if(NULL == context)
     {
         return OC_STACK_ERROR;
     }
 
-    context->amsMgrContext = (AmsMgrContext_t *)OICMalloc(sizeof(AmsMgrContext_t));
-    SetPolicyEngineState(context, AWAITING_REQUEST);
+    context->amsMgrContext = (AmsMgrContext_t *)OICCalloc(1, sizeof(AmsMgrContext_t));
+    if(NULL == context->amsMgrContext)
+    {
+        return OC_STACK_ERROR;
+    }
 
+    SetPolicyEngineState(context, AWAITING_REQUEST);
     return OC_STACK_OK;
 }
 
-/**
- * De-Initialize the Policy Engine.  Call this before exiting to allow Policy
- * Engine to do cleanup on context.
- * @param   context     Pointer to Policy Engine context to de-initialize.
- * @return  none
- */
 void DeInitPolicyEngine(PEContext_t *context)
 {
     if(NULL != context)
index 992fe70..c10b097 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#include "ocstack.h"
+#ifdef WITH_ARDUINO
+#define __STDC_LIMIT_MACROS
+#endif
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "cainterface.h"
 #include "logger.h"
+#include "ocpayload.h"
+#include "ocpayloadcbor.h"
+#include "ocstack.h"
 #include "oic_malloc.h"
-#include "cJSON.h"
-#include "cainterface.h"
-#include "secureresourcemanager.h"
+#include "payload_logging.h"
 #include "resourcemanager.h"
+#include "secureresourcemanager.h"
 #include "srmresourcestrings.h"
 #include "srmutility.h"
-#include <stdlib.h>
-#include <string.h>
 
 #define TAG  "SRM-PSI"
 
 const size_t DB_FILE_SIZE_BLOCK = 1023;
 
 /**
- * Gets the Secure Virtual Database size.
+ * Gets the Secure Virtual Database size
  *
- * @param ps  pointer of OCPersistentStorage for the SVR name ("acl", "cred", "pstat" etc).
+ * @param ps - pointer of OCPersistentStorage for the Secure Virtual Resource(s)
  *
- * @retval  total size of the SVR database.
+ * @return size_t - total size of the SVR database
  */
-size_t GetSVRDatabaseSize(OCPersistentStorage* ps)
+static size_t GetSVRDatabaseSize(const OCPersistentStorage *ps)
 {
-    size_t size = 0;
     if (!ps)
     {
-        return size;
+        return 0;
     }
-    size_t bytesRead  = 0;
-    char buffer[DB_FILE_SIZE_BLOCK];
-    FILE* fp = ps->open(SVR_DB_FILE_NAME, "r");
+    size_t size = 0;
+    char buffer[DB_FILE_SIZE_BLOCK];  // can not initialize with declaration
+                                      // but maybe not needed to initialize
+    FILE *fp = ps->open(SVR_DB_DAT_FILE_NAME, "rb");
     if (fp)
     {
+        size_t bytesRead = 0;
         do
         {
             bytesRead = ps->read(buffer, 1, DB_FILE_SIZE_BLOCK, fp);
             size += bytesRead;
-        } while (bytesRead > 0);
+        } while (bytesRead);
         ps->close(fp);
     }
     return size;
 }
 
 /**
- * Reads the Secure Virtual Database from PS into dynamically allocated
- * memory buffer.
+ * Gets the Secure Virtual Database from the Persistent Storage
  *
- * @note Caller of this method MUST use OICFree() method to release memory
- *       referenced by return value.
+ * @param rsrcName - pointer of character string for the SVR name (e.g. "acl")
+ * @param data - pointer of the returned Secure Virtual Resource(s)
+ * @param size - pointer of the returned size of Secure Virtual Resource(s)
  *
- * @retval  reference to memory buffer containing SVR database.
+ * @return OCStackResult - result of getting Secure Virtual Resource(s)
  */
-char * GetSVRDatabase()
+OCStackResult GetSecureVirtualDatabaseFromPS(const char *rsrcName, uint8_t **data, size_t *size)
 {
-    char * jsonStr = NULL;
-    FILE * fp = NULL;
-    OCPersistentStorage* ps = SRMGetPersistentStorageHandler();
-    int size = GetSVRDatabaseSize(ps);
-    if (0 == size)
+    OIC_LOG(DEBUG, TAG, "GetSecureVirtualDatabaseFromPS IN");
+    if (!data || *data || !size)
     {
-        OC_LOG (ERROR, TAG, "FindSVRDatabaseSize failed");
-        return NULL;
+        return OC_STACK_INVALID_PARAM;
     }
 
-    if (ps && ps->open)
+    FILE *fp = NULL;
+    uint8_t *fsData = NULL;
+    size_t fileSize = 0;
+    OCStackResult ret = OC_STACK_ERROR;
+
+    OCPersistentStorage *ps = SRMGetPersistentStorageHandler();
+    VERIFY_NON_NULL(TAG, ps, ERROR);
+
+    fileSize = GetSVRDatabaseSize(ps);
+    OIC_LOG_V(DEBUG, TAG, "File Read Size: %zu", fileSize);
+    if (fileSize)
     {
-        // Open default SRM database file. An app could change the path for its server.
-        fp = ps->open(SVR_DB_FILE_NAME, "r");
-        if (fp)
-        {
-            jsonStr = (char*)OICMalloc(size + 1);
-            VERIFY_NON_NULL(TAG, jsonStr, FATAL);
-            size_t bytesRead = ps->read(jsonStr, 1, size, fp);
-            jsonStr[bytesRead] = '\0';
-
-            OC_LOG_V(DEBUG, TAG, "Read %d bytes from SVR database file", bytesRead);
-            ps->close(fp);
-            fp = NULL;
-        }
-        else
+        fsData = (uint8_t *) OICCalloc(1, fileSize);
+        VERIFY_NON_NULL(TAG, fsData, ERROR);
+
+        fp = ps->open(SVR_DB_DAT_FILE_NAME, "rb");
+        VERIFY_NON_NULL(TAG, fp, ERROR);
+        if (ps->read(fsData, 1, fileSize, fp) == fileSize)
         {
-            OC_LOG (ERROR, TAG, "Unable to open SVR database file!!");
+            if (rsrcName)
+            {
+                CborParser parser;  // will be initialized in |cbor_parser_init|
+                CborValue cbor;     // will be initialized in |cbor_parser_init|
+                cbor_parser_init(fsData, fileSize, 0, &parser, &cbor);
+                CborValue cborValue = {0};
+                CborError cborFindResult = cbor_value_map_find_value(&cbor, rsrcName, &cborValue);
+                if (CborNoError == cborFindResult && cbor_value_is_byte_string(&cborValue))
+                {
+                    cborFindResult = cbor_value_dup_byte_string(&cborValue, data, size, NULL);
+                    VERIFY_SUCCESS(TAG, CborNoError==cborFindResult, ERROR);
+                    ret = OC_STACK_OK;
+                }
+                // in case of |else (...)|, svr_data not found
+            }
+            // return everything in case rsrcName is NULL
+            else
+            {
+                *size = fileSize;
+                *data = (uint8_t *) OICCalloc(1, fileSize);
+                VERIFY_NON_NULL(TAG, *data, ERROR);
+                memcpy(*data, fsData, fileSize);
+                ret = OC_STACK_OK;
+            }
         }
     }
+    OIC_LOG(DEBUG, TAG, "GetSecureVirtualDatabaseFromPS OUT");
 
 exit:
-    if (ps && fp)
+    if (fp)
     {
         ps->close(fp);
     }
-    return jsonStr;
+    OICFree(fsData);
+    return ret;
 }
 
-
 /**
- * This method is used by a entity handlers of SVR's to update
- * SVR database.
+ * Updates the Secure Virtual Resource(s) into the Persistent Storage.
+ * This function stores cbor-payload of each resource by appending resource name,
+ * and empty payload implies deleting the value
  *
- * @param rsrcName string denoting the SVR name ("acl", "cred", "pstat" etc).
- * @param jsonObj JSON object containing the SVR contents.
+ * @param rsrcName - pointer of character string for the SVR name (e.g. "acl")
+ * @param psPayload - pointer of the updated Secure Virtual Resource(s)
+ * @param psSize - the updated size of Secure Virtual Resource(s)
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @return OCStackResult - result of updating Secure Virtual Resource(s)
  */
-OCStackResult UpdateSVRDatabase(const char* rsrcName, cJSON* jsonObj)
+OCStackResult UpdateSecureResourceInPS(const char *rsrcName, const uint8_t *psPayload, size_t psSize)
 {
-    OCStackResult ret = OC_STACK_ERROR;
-    cJSON *jsonSVRDb = NULL;
-    OCPersistentStorage* ps = NULL;
-
-    // Read SVR database from PS
-    char* jsonSVRDbStr = GetSVRDatabase();
-    VERIFY_NON_NULL(TAG,jsonSVRDbStr, ERROR);
+    OIC_LOG(DEBUG, TAG, "UpdateSecureResourceInPS IN");
+    if (!rsrcName)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
 
-    // Use cJSON_Parse to parse the existing SVR database
-    jsonSVRDb = cJSON_Parse(jsonSVRDbStr);
-    VERIFY_NON_NULL(TAG,jsonSVRDb, ERROR);
+    size_t dbSize = 0;
+    size_t outSize = 0;
+    uint8_t *dbData = NULL;
+    uint8_t *outPayload = NULL;
 
-    OICFree(jsonSVRDbStr);
-    jsonSVRDbStr = NULL;
+    uint8_t *aclCbor = NULL;
+    uint8_t *pstatCbor = NULL;
+    uint8_t *doxmCbor = NULL;
+    uint8_t *amaclCbor = NULL;
+    uint8_t *svcCbor = NULL;
+    uint8_t *credCbor = NULL;
+    uint8_t *pconfCbor = NULL;
 
-    //If Cred resource gets updated with empty list then delete the Cred
-    //object from database.
-    if(NULL == jsonObj && (0 == strcmp(rsrcName, OIC_JSON_CRED_NAME)))
+    int64_t cborEncoderResult = CborNoError;
+    OCStackResult ret = GetSecureVirtualDatabaseFromPS(NULL, &dbData, &dbSize);
+    if (dbData && dbSize)
     {
-        cJSON_DeleteItemFromObject(jsonSVRDb, rsrcName);
-    }
-    else if (jsonObj->child )
-    {
-        // Create a duplicate of the JSON object which was passed.
-        cJSON* jsonDuplicateObj = cJSON_Duplicate(jsonObj, 1);
-        VERIFY_NON_NULL(TAG,jsonDuplicateObj, ERROR);
-
-        cJSON* jsonObj = cJSON_GetObjectItem(jsonSVRDb, rsrcName);
-
-        /*
-         ACL, PStat & Doxm resources at least have default entries in the database but
-         Cred resource may have no entries. The first cred resource entry (for provisioning tool)
-         is created when the device is owned by provisioning tool and it's ownerpsk is generated.*/
-        if((strcmp(rsrcName, OIC_JSON_CRED_NAME) == 0 || strcmp(rsrcName, OIC_JSON_CRL_NAME) == 0)
-                                                                                    && (!jsonObj))
+        size_t aclCborLen = 0;
+        size_t pstatCborLen = 0;
+        size_t doxmCborLen = 0;
+        size_t amaclCborLen = 0;
+        size_t svcCborLen = 0;
+        size_t credCborLen = 0;
+        size_t pconfCborLen = 0;
+
+        // Gets each secure virtual resource from persistent storage
+        // this local scoping intended, for destroying large cbor instances after use
         {
-            // Add the fist cred object in existing SVR database json
-            cJSON_AddItemToObject(jsonSVRDb, rsrcName, jsonDuplicateObj->child);
+            CborParser parser;  // will be initialized in |cbor_parser_init|
+            CborValue cbor;     // will be initialized in |cbor_parser_init|
+            cbor_parser_init(dbData, dbSize, 0, &parser, &cbor);
+            CborValue curVal = {0};
+            CborError cborFindResult = CborNoError;
+
+            cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_ACL_NAME, &curVal);
+            if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal))
+            {
+                cborFindResult = cbor_value_dup_byte_string(&curVal, &aclCbor, &aclCborLen, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ACL Name Value.");
+            }
+            cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_PSTAT_NAME, &curVal);
+            if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal))
+            {
+                cborFindResult = cbor_value_dup_byte_string(&curVal, &pstatCbor, &pstatCborLen, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding PSTAT Name Value.");
+            }
+            cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_DOXM_NAME, &curVal);
+            if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal))
+            {
+                cborFindResult = cbor_value_dup_byte_string(&curVal, &doxmCbor, &doxmCborLen, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult,  "Failed Finding DOXM Name Value.");
+            }
+            cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_AMACL_NAME, &curVal);
+            if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal))
+            {
+                cborFindResult = cbor_value_dup_byte_string(&curVal, &amaclCbor, &amaclCborLen, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding AMACL Name Value.");
+            }
+            cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_SVC_NAME, &curVal);
+            if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal))
+            {
+                cborFindResult = cbor_value_dup_byte_string(&curVal, &svcCbor, &svcCborLen, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SVC Name Value.");
+            }
+            cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_CRED_NAME, &curVal);
+            if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal))
+            {
+                cborFindResult = cbor_value_dup_byte_string(&curVal, &credCbor, &credCborLen, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding CRED Name Value.");
+            }
+            cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_PCONF_NAME, &curVal);
+            if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal))
+            {
+                cborFindResult = cbor_value_dup_byte_string(&curVal, &pconfCbor, &pconfCborLen, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding PCONF Name Value.");
+            }
         }
-        else
+
+        // Updates the added |psPayload| with the existing secure virtual resource(s)
+        // this local scoping intended, for destroying large cbor instances after use
         {
-            VERIFY_NON_NULL(TAG,jsonObj, ERROR);
+            size_t size = aclCborLen + pstatCborLen + doxmCborLen + amaclCborLen
+                        + svcCborLen + credCborLen + pconfCborLen + psSize + 255;
+            // This added '255' is arbitrary value that is added to cover the name of the resource, map addition and ending
+
+            outPayload = (uint8_t *) OICCalloc(1, size);
+            VERIFY_NON_NULL(TAG, outPayload, ERROR);
+            CborEncoder encoder;  // will be initialized in |cbor_parser_init|
+            cbor_encoder_init(&encoder, outPayload, size, 0);
+            CborEncoder secRsrc;  // will be initialized in |cbor_encoder_create_map|
+            cborEncoderResult |= cbor_encoder_create_map(&encoder, &secRsrc, CborIndefiniteLength);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PS Map.");
+
+            if (psPayload && psSize)
+            {
+                cborEncoderResult |= cbor_encode_text_string(&secRsrc, rsrcName, strlen(rsrcName));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Value Tag");
+                cborEncoderResult |= cbor_encode_byte_string(&secRsrc, psPayload, psSize);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Value.");
+            }
+            if (strcmp(OIC_JSON_ACL_NAME, rsrcName) && aclCborLen)
+            {
+                cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_ACL_NAME, strlen(OIC_JSON_ACL_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ACL Name.");
+                cborEncoderResult |= cbor_encode_byte_string(&secRsrc, aclCbor, aclCborLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ACL Value.");
+            }
+            if (strcmp(OIC_JSON_PSTAT_NAME, rsrcName) && pstatCborLen)
+            {
+                cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_PSTAT_NAME, strlen(OIC_JSON_PSTAT_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PSTAT Name.");
+                cborEncoderResult |= cbor_encode_byte_string(&secRsrc, pstatCbor, pstatCborLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PSTAT Value.");
+            }
+            if (strcmp(OIC_JSON_DOXM_NAME, rsrcName) && doxmCborLen)
+            {
+                cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_DOXM_NAME, strlen(OIC_JSON_DOXM_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Name.");
+                cborEncoderResult |= cbor_encode_byte_string(&secRsrc, doxmCbor, doxmCborLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Value.");
+            }
+            if (strcmp(OIC_JSON_AMACL_NAME, rsrcName) && amaclCborLen)
+            {
+                cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_AMACL_NAME, strlen(OIC_JSON_AMACL_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Amacl Name.");
+                cborEncoderResult |= cbor_encode_byte_string(&secRsrc, amaclCbor, amaclCborLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Amacl Value.");
+            }
+            if (strcmp(OIC_JSON_SVC_NAME, rsrcName) && svcCborLen)
+            {
+                cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_SVC_NAME, strlen(OIC_JSON_SVC_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SVC Name.");
+                cborEncoderResult |= cbor_encode_byte_string(&secRsrc, svcCbor, svcCborLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SVC Value.");
+            }
+            if (strcmp(OIC_JSON_CRED_NAME, rsrcName) && credCborLen)
+            {
+                cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_CRED_NAME, strlen(OIC_JSON_CRED_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Name.");
+                cborEncoderResult |= cbor_encode_byte_string(&secRsrc, credCbor, credCborLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Value.");
+            }
+            if (strcmp(OIC_JSON_PCONF_NAME, rsrcName) && pconfCborLen)
+            {
+                cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_PCONF_NAME, strlen(OIC_JSON_PCONF_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Pconf Name.");
+                cborEncoderResult |= cbor_encode_byte_string(&secRsrc, pconfCbor, pconfCborLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Pconf Value.");
+            }
 
-            // Replace the modified json object in existing SVR database json
-            cJSON_ReplaceItemInObject(jsonSVRDb, rsrcName, jsonDuplicateObj->child);
+            cborEncoderResult |= cbor_encoder_close_container(&encoder, &secRsrc);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Array.");
+            outSize = encoder.ptr - outPayload;
         }
     }
+    else if (psPayload && psSize)
+    {
+        size_t size = psSize + 255;
+        // This added '255' is arbitrary value that is added to cover the name of the resource, map addition and ending
 
-    // Generate string representation of updated SVR database json object
-    jsonSVRDbStr = cJSON_PrintUnformatted(jsonSVRDb);
-    VERIFY_NON_NULL(TAG,jsonSVRDbStr, ERROR);
+        outPayload = (uint8_t *) OICCalloc(1, size);
+        VERIFY_NON_NULL(TAG, outPayload, ERROR);
+        CborEncoder encoder;  // will be initialized in |cbor_parser_init|
+        cbor_encoder_init(&encoder, outPayload, size, 0);
+        CborEncoder secRsrc;  // will be initialized in |cbor_encoder_create_map|
+        cborEncoderResult |= cbor_encoder_create_map(&encoder, &secRsrc, CborIndefiniteLength);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PS Map.");
 
-    // Update the persistent storage with new SVR database
-    ps = SRMGetPersistentStorageHandler();
-    if (ps && ps->open)
+        cborEncoderResult |= cbor_encode_text_string(&secRsrc, rsrcName, strlen(rsrcName));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Value Tag");
+        cborEncoderResult |= cbor_encode_byte_string(&secRsrc, psPayload, psSize);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Value.");
+
+        cborEncoderResult |= cbor_encoder_close_container(&encoder, &secRsrc);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Array.");
+        outSize = encoder.ptr - outPayload;
+    }
+
+    if (outPayload && outSize)
     {
-        FILE* fp = ps->open(SVR_DB_FILE_NAME, "w");
-        if (fp)
+        OIC_LOG_V(DEBUG, TAG, "Writting in the file: %zu", outSize);
+        OCPersistentStorage* ps = SRMGetPersistentStorageHandler();
+        if (ps)
         {
-            size_t bytesWritten = ps->write(jsonSVRDbStr, 1, strlen(jsonSVRDbStr), fp);
-            if (bytesWritten == strlen(jsonSVRDbStr))
+            FILE *fp = ps->open(SVR_DB_DAT_FILE_NAME, "wb");
+            if (fp)
             {
-                ret = OC_STACK_OK;
+                size_t numberItems = ps->write(outPayload, 1, outSize, fp);
+                if (outSize == numberItems)
+                {
+                    OIC_LOG_V(DEBUG, TAG, "Written %zu bytes into SVR database file", outSize);
+                    ret = OC_STACK_OK;
+                }
+                else
+                {
+                    OIC_LOG_V(ERROR, TAG, "Failed writing %zu in the database", numberItems);
+                }
+                ps->close(fp);
+            }
+            else
+            {
+                OIC_LOG(ERROR, TAG, "File open failed.");
             }
-            OC_LOG_V(DEBUG, TAG, "Written %d bytes into SVR database file", bytesWritten);
-            ps->close(fp);
-            fp = NULL;
-        }
-        else
-        {
-            OC_LOG (ERROR, TAG, "Unable to open SVR database file!! ");
         }
     }
 
-exit:
-    OICFree(jsonSVRDbStr);
-    cJSON_Delete(jsonSVRDb);
+    OIC_LOG(DEBUG, TAG, "UpdateSecureResourceInPS OUT");
 
+exit:
+    OICFree(dbData);
+    OICFree(outPayload);
+    OICFree(aclCbor);
+    OICFree(pstatCbor);
+    OICFree(doxmCbor);
+    OICFree(amaclCbor);
+    OICFree(svcCbor);
+    OICFree(credCbor);
+    OICFree(pconfCbor);
     return ret;
 }
index 979073c..b3e63ac 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#include <stdlib.h>
+#include <string.h>
+
 #include "ocstack.h"
-#include "logger.h"
 #include "oic_malloc.h"
-#include "cJSON.h"
+#include "ocpayload.h"
+#include "payload_logging.h"
 #include "resourcemanager.h"
 #include "pstatresource.h"
+#include "doxmresource.h"
 #include "psinterface.h"
-#include "utlist.h"
-#include "base64.h"
 #include "srmresourcestrings.h"
 #include "srmutility.h"
-#include <stdlib.h>
-#include <string.h>
 
 #define TAG  "SRM-PSTAT"
 
+/** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
+ * The value of payload size is increased until reaching below max cbor size. */
+static const uint16_t CBOR_SIZE = 512;
+
+// Max cbor size payload.
+static const uint16_t CBOR_MAX_SIZE = 4400;
+
+// PSTAT Map size - Number of mandatory items
+static const uint8_t PSTAT_MAP_SIZE = 7;
+
 static OicSecDpom_t gSm = SINGLE_SERVICE_CLIENT_DRIVEN;
 static OicSecPstat_t gDefaultPstat =
 {
-    false,                                    // bool isOwned
-    (OicSecDpm_t)(TAKE_OWNER | BOOTSTRAP_SERVICE | SECURITY_MANAGEMENT_SERVICES |
+    false,                                    // bool isop
+    (OicSecDpm_t)(BOOTSTRAP_SERVICE | SECURITY_MANAGEMENT_SERVICES |
     PROVISION_CREDENTIALS | PROVISION_ACLS),   // OicSecDpm_t cm
     (OicSecDpm_t)(TAKE_OWNER | BOOTSTRAP_SERVICE | SECURITY_MANAGEMENT_SERVICES |
     PROVISION_CREDENTIALS | PROVISION_ACLS),   // OicSecDpm_t tm
@@ -47,8 +57,11 @@ static OicSecPstat_t gDefaultPstat =
     1,                                        // the number of elts in Sms
     &gSm,                                     // OicSecDpom_t *sm
     0,                                        // uint16_t commitHash
+    {.id = {0}},                              // OicUuid_t rownerID
 };
+
 static OicSecPstat_t    *gPstat = NULL;
+
 static OCResourceHandle gPstatHandle = NULL;
 
 void DeletePstatBinData(OicSecPstat_t* pstat)
@@ -63,148 +76,271 @@ void DeletePstatBinData(OicSecPstat_t* pstat)
     }
 }
 
-char * BinToPstatJSON(const OicSecPstat_t * pstat)
+OCStackResult PstatToCBORPayload(const OicSecPstat_t *pstat, uint8_t **payload, size_t *size)
 {
-    if(NULL == pstat)
+    if (NULL == pstat || NULL == payload || NULL != *payload || NULL == size)
     {
-        return NULL;
+        return OC_STACK_INVALID_PARAM;
     }
 
-    cJSON *jsonPstat = NULL;
-    char *jsonStr = NULL;
-    cJSON *jsonSmArray = NULL;
-    char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*) 0)->id)) + 1] = {};
-    uint32_t outLen = 0;
-    B64Result b64Ret = B64_OK;
-
-    cJSON *jsonRoot = cJSON_CreateObject();
-    VERIFY_NON_NULL(TAG, jsonRoot, INFO);
-
-    cJSON_AddItemToObject(jsonRoot, OIC_JSON_PSTAT_NAME, jsonPstat=cJSON_CreateObject());
-    cJSON_AddBoolToObject(jsonPstat, OIC_JSON_ISOP_NAME, pstat->isOp);
+    size_t cborLen = *size;
+    if (0 == cborLen)
+    {
+        cborLen = CBOR_SIZE;
+    }
 
-    b64Ret = b64Encode(pstat->deviceID.id,
-            sizeof(pstat->deviceID.id), base64Buff, sizeof(base64Buff), &outLen);
-    VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
+    *payload = NULL;
+    *size = 0;
 
-    cJSON_AddStringToObject(jsonPstat, OIC_JSON_DEVICE_ID_NAME, base64Buff);
-    cJSON_AddNumberToObject(jsonPstat, OIC_JSON_COMMIT_HASH_NAME, pstat->commitHash);
-    cJSON_AddNumberToObject(jsonPstat, OIC_JSON_CM_NAME, (int)pstat->cm);
-    cJSON_AddNumberToObject(jsonPstat, OIC_JSON_TM_NAME, (int)pstat->tm);
-    cJSON_AddNumberToObject(jsonPstat, OIC_JSON_OM_NAME, (int)pstat->om);
+    OCStackResult ret = OC_STACK_ERROR;
 
-    cJSON_AddItemToObject(jsonPstat, OIC_JSON_SM_NAME, jsonSmArray = cJSON_CreateArray());
-    VERIFY_NON_NULL(TAG, jsonSmArray, INFO);
-    for (size_t i = 0; i < pstat->smLen; i++)
+    CborEncoder encoder;
+    CborEncoder pstatMap;
+    char* strUuid = NULL;
+
+    int64_t cborEncoderResult = CborNoError;
+
+    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
+    VERIFY_NON_NULL(TAG, outPayload, ERROR);
+    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
+
+    cborEncoderResult = cbor_encoder_create_map(&encoder, &pstatMap, PSTAT_MAP_SIZE);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Pstat Map.");
+
+    cborEncoderResult = cbor_encode_text_string(&pstatMap, OIC_JSON_ISOP_NAME,
+        strlen(OIC_JSON_ISOP_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ISOP Name Tag.");
+    cborEncoderResult = cbor_encode_boolean(&pstatMap, pstat->isOp);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ISOP Name Value.");
+
+    cborEncoderResult = cbor_encode_text_string(&pstatMap, OIC_JSON_DEVICE_ID_NAME,
+        strlen(OIC_JSON_DEVICE_ID_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag.");
+    ret = ConvertUuidToStr(&pstat->deviceID, &strUuid);
+    VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
+    cborEncoderResult = cbor_encode_text_string(&pstatMap, strUuid, strlen(strUuid));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value.");
+    OICFree(strUuid);
+    strUuid = NULL;
+
+    cborEncoderResult = cbor_encode_text_string(&pstatMap, OIC_JSON_CM_NAME,
+        strlen(OIC_JSON_CM_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding CM Name Tag.");
+    cborEncoderResult = cbor_encode_int(&pstatMap, pstat->cm);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding CM Name Value.");
+
+    cborEncoderResult = cbor_encode_text_string(&pstatMap, OIC_JSON_TM_NAME,
+        strlen(OIC_JSON_TM_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding TM Name Tag.");
+    cborEncoderResult = cbor_encode_int(&pstatMap, pstat->tm);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding TM Name Value.");
+
+    cborEncoderResult = cbor_encode_text_string(&pstatMap, OIC_JSON_OM_NAME,
+        strlen(OIC_JSON_OM_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding OM Name Tag.");
+    cborEncoderResult = cbor_encode_int(&pstatMap, pstat->om);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding OM Name Value.");
+
+    cborEncoderResult = cbor_encode_text_string(&pstatMap, OIC_JSON_SM_NAME,
+        strlen(OIC_JSON_SM_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SM Name Tag.");
+    cborEncoderResult = cbor_encode_int(&pstatMap, pstat->sm[0]);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SM Name Value.");
+
+    cborEncoderResult = cbor_encode_text_string(&pstatMap, OIC_JSON_ROWNERID_NAME,
+        strlen(OIC_JSON_ROWNERID_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Tag.");
+    ret = ConvertUuidToStr(&pstat->rownerID, &strUuid);
+    VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
+    cborEncoderResult = cbor_encode_text_string(&pstatMap, strUuid, strlen(strUuid));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Value.");
+    OICFree(strUuid);
+    strUuid = NULL;
+
+    cborEncoderResult = cbor_encoder_close_container(&encoder, &pstatMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Closing PSTAT Map.");
+
+    if (CborNoError == cborEncoderResult)
     {
-        cJSON_AddItemToArray(jsonSmArray, cJSON_CreateNumber((int )pstat->sm[i]));
+        *size = encoder.ptr - outPayload;
+        *payload = outPayload;
+        ret = OC_STACK_OK;
     }
-    jsonStr = cJSON_Print(jsonRoot);
-
 exit:
-    if (jsonRoot)
+    if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
     {
-        cJSON_Delete(jsonRoot);
+        // reallocate and try again!
+        OICFree(outPayload);
+        // Since the allocated initial memory failed, double the memory.
+        cborLen += encoder.ptr - encoder.end;
+        cborEncoderResult = CborNoError;
+        ret = PstatToCBORPayload(pstat, payload, &cborLen);
+        if (OC_STACK_OK == ret)
+        {
+            *size = cborLen;
+        }
     }
-    return jsonStr;
+
+    if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
+    {
+        OICFree(outPayload);
+        outPayload = NULL;
+        *payload = NULL;
+        *size = 0;
+        ret = OC_STACK_ERROR;
+    }
+
+    return ret;
 }
 
-OicSecPstat_t * JSONToPstatBin(const char * jsonStr)
+OCStackResult CBORPayloadToPstat(const uint8_t *cborPayload, const size_t size,
+                                 OicSecPstat_t **secPstat)
 {
-    if(NULL == jsonStr)
+    if (NULL == cborPayload || NULL == secPstat || NULL != *secPstat || 0 == size)
     {
-        return NULL;
+        return OC_STACK_INVALID_PARAM;
     }
 
     OCStackResult ret = OC_STACK_ERROR;
+    *secPstat = NULL;
+
+    CborValue pstatCbor;
+    CborParser parser;
+    CborError cborFindResult = CborNoError;
+    char *strUuid = NULL;
+    size_t len = 0;
+
+    cbor_parser_init(cborPayload, size, 0, &parser, &pstatCbor);
+    CborValue pstatMap = { .parser = NULL };
+
     OicSecPstat_t *pstat = NULL;
-    cJSON *jsonPstat = NULL;
-    cJSON *jsonObj = NULL;
-
-    unsigned char base64Buff[sizeof(((OicUuid_t*) 0)->id)] = {};
-    uint32_t outLen = 0;
-    B64Result b64Ret = B64_OK;
-
-    cJSON *jsonRoot = cJSON_Parse(jsonStr);
-    VERIFY_NON_NULL(TAG, jsonRoot, INFO);
-
-    jsonPstat = cJSON_GetObjectItem(jsonRoot, OIC_JSON_PSTAT_NAME);
-    VERIFY_NON_NULL(TAG, jsonPstat, INFO);
-
-    pstat = (OicSecPstat_t*)OICCalloc(1, sizeof(OicSecPstat_t));
-    VERIFY_NON_NULL(TAG, pstat, INFO);
-    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_ISOP_NAME);
-    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-    VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type) , ERROR);
-    pstat->isOp = jsonObj->valueint;
-
-    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_DEVICE_ID_NAME);
-    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-    VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
-    b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
-                sizeof(base64Buff), &outLen);
-    VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(pstat->deviceID.id)), ERROR);
-    memcpy(pstat->deviceID.id, base64Buff, outLen);
-
-    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_COMMIT_HASH_NAME);
-    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-    VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
-    pstat->commitHash  = jsonObj->valueint;
-
-    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_CM_NAME);
-    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-    VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
-    pstat->cm  = (OicSecDpm_t)jsonObj->valueint;
-
-    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_OM_NAME);
-    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-    VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
-    pstat->om  = (OicSecDpom_t)jsonObj->valueint;
-
-    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_SM_NAME);
-    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-    if (cJSON_Array == jsonObj->type)
-    {
-        pstat->smLen = cJSON_GetArraySize(jsonObj);
-        size_t idxx = 0;
-        VERIFY_SUCCESS(TAG, pstat->smLen != 0, ERROR);
+    cborFindResult = cbor_value_enter_container(&pstatCbor, &pstatMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding PSTAT Map.");
+
+    pstat = (OicSecPstat_t *)OICCalloc(1, sizeof(OicSecPstat_t));
+    VERIFY_NON_NULL(TAG, pstat, ERROR);
+
+    cborFindResult = cbor_value_map_find_value(&pstatCbor, OIC_JSON_ISOP_NAME, &pstatMap);
+    if (CborNoError == cborFindResult && cbor_value_is_boolean(&pstatMap))
+    {
+        cborFindResult = cbor_value_get_boolean(&pstatMap, &pstat->isOp);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding isOp Value.");
+    }
+
+    cborFindResult = cbor_value_map_find_value(&pstatCbor, OIC_JSON_DEVICE_ID_NAME, &pstatMap);
+    if (CborNoError == cborFindResult && cbor_value_is_text_string(&pstatMap))
+    {
+        cborFindResult = cbor_value_dup_text_string(&pstatMap, &strUuid , &len, NULL);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Device Id Value.");
+        ret = ConvertStrToUuid(strUuid , &pstat->deviceID);
+        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+        OICFree(strUuid );
+        strUuid  = NULL;
+    }
+
+    cborFindResult = cbor_value_map_find_value(&pstatCbor, OIC_JSON_CM_NAME, &pstatMap);
+    if (CborNoError == cborFindResult && cbor_value_is_integer(&pstatMap))
+    {
+        cborFindResult = cbor_value_get_int(&pstatMap, (int *) &pstat->cm);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding CM.");
+    }
+
+    cborFindResult = cbor_value_map_find_value(&pstatCbor, OIC_JSON_TM_NAME, &pstatMap);
+    if (CborNoError == cborFindResult && cbor_value_is_integer(&pstatMap))
+    {
+        cborFindResult = cbor_value_get_int(&pstatMap, (int *) &pstat->tm);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding TM.");
+    }
+
+    cborFindResult = cbor_value_map_find_value(&pstatCbor, OIC_JSON_OM_NAME, &pstatMap);
+    if (CborNoError == cborFindResult && cbor_value_is_integer(&pstatMap))
+    {
+        cborFindResult = cbor_value_get_int(&pstatMap, (int *) &pstat->om);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding OM.");
+    }
+
+    cborFindResult = cbor_value_map_find_value(&pstatCbor, OIC_JSON_SM_NAME, &pstatMap);
+    if (CborNoError == cborFindResult && cbor_value_is_integer(&pstatMap))
+    {
+        pstat->smLen = 1;
         pstat->sm = (OicSecDpom_t*)OICCalloc(pstat->smLen, sizeof(OicSecDpom_t));
-        VERIFY_NON_NULL(TAG, pstat->sm, ERROR);
-        do
-        {
-            cJSON *jsonSm = cJSON_GetArrayItem(jsonObj, idxx);
-            VERIFY_NON_NULL(TAG, jsonSm, ERROR);
-            pstat->sm[idxx] = (OicSecDpom_t)jsonSm->valueint;
-        }while ( ++idxx < pstat->smLen);
+        cborFindResult = cbor_value_get_int(&pstatMap, (int *) &pstat->sm[0]);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SM.");
+
+    }
+
+    cborFindResult = cbor_value_map_find_value(&pstatCbor, OIC_JSON_ROWNERID_NAME, &pstatMap);
+    if (CborNoError == cborFindResult && cbor_value_is_text_string(&pstatMap))
+    {
+        cborFindResult = cbor_value_dup_text_string(&pstatMap, &strUuid , &len, NULL);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ROwner Id Value.");
+        ret = ConvertStrToUuid(strUuid , &pstat->rownerID);
+        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+        OICFree(strUuid );
+        strUuid  = NULL;
     }
+
+    *secPstat = pstat;
     ret = OC_STACK_OK;
 
 exit:
-    cJSON_Delete(jsonRoot);
-    if (OC_STACK_OK != ret)
+    if (CborNoError != cborFindResult)
     {
-        OC_LOG (ERROR, TAG, "JSONToPstatBin failed");
+        OIC_LOG(ERROR, TAG, "CBORPayloadToPstat failed");
         DeletePstatBinData(pstat);
         pstat = NULL;
+        *secPstat = NULL;
+        ret = OC_STACK_ERROR;
     }
-    return pstat;
+
+    return ret;
 }
 
 /**
+ * Function to update persistent storage
+ */
+static bool UpdatePersistentStorage(OicSecPstat_t *pstat)
+{
+    bool bRet = false;
+
+    size_t size = 0;
+    uint8_t *cborPayload = NULL;
+    OCStackResult ret = PstatToCBORPayload(pstat, &cborPayload, &size);
+    if (OC_STACK_OK == ret)
+    {
+        if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_PSTAT_NAME, cborPayload, size))
+        {
+            bRet = true;
+        }
+        OICFree(cborPayload);
+    }
+
+    return bRet;
+}
+
+
+/**
  * The entity handler determines how to process a GET request.
  */
 static OCEntityHandlerResult HandlePstatGetRequest (const OCEntityHandlerRequest * ehRequest)
 {
-    OC_LOG (INFO, TAG, "HandlePstatGetRequest  processing GET request");
-   // Convert ACL data into JSON for transmission
-    char* jsonStr = BinToPstatJSON(gPstat);
+    OIC_LOG(INFO, TAG, "HandlePstatGetRequest  processing GET request");
+
+    // Convert ACL data into CBOR for transmission
+    size_t size = 0;
+    uint8_t *payload = NULL;
+    OCStackResult res = PstatToCBORPayload(gPstat, &payload, &size);
 
-    // A device should always have a default pstat. Therefore, jsonStr should never be NULL.
-    OCEntityHandlerResult ehRet = (jsonStr ? OC_EH_OK : OC_EH_ERROR);
+    // A device should always have a default pstat. Therefore, payload should never be NULL.
+    OCEntityHandlerResult ehRet = (res == OC_STACK_OK) ? OC_EH_OK : OC_EH_ERROR;
 
     // Send response payload to request originator
-    SendSRMResponse(ehRequest, ehRet, jsonStr);
-    OICFree(jsonStr);
+    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;
 }
 
@@ -217,87 +353,89 @@ static OCEntityHandlerResult HandlePstatGetRequest (const OCEntityHandlerRequest
 static OCEntityHandlerResult HandlePstatPutRequest(const OCEntityHandlerRequest *ehRequest)
 {
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
-    cJSON *postJson = NULL;
-    OC_LOG (INFO, TAG, "HandlePstatPutRequest  processing PUT request");
-
-    if (ehRequest->resource)
-    {
-        postJson = cJSON_Parse(((OCSecurityPayload*)ehRequest->payload)->securityData);
-        VERIFY_NON_NULL(TAG, postJson, INFO);
-        cJSON *jsonPstat = cJSON_GetObjectItem(postJson, OIC_JSON_PSTAT_NAME);
-        VERIFY_NON_NULL(TAG, jsonPstat, INFO);
-        cJSON *commitHashJson = cJSON_GetObjectItem(jsonPstat, OIC_JSON_COMMIT_HASH_NAME);
-        uint16_t commitHash = 0;
-        if (commitHashJson)
-        {
-            commitHash = commitHashJson->valueint;
-        }
-        cJSON *tmJson = cJSON_GetObjectItem(jsonPstat, OIC_JSON_TM_NAME);
-        if (tmJson && gPstat)
+    OIC_LOG(INFO, TAG, "HandlePstatPutRequest  processing PUT request");
+    OicSecPstat_t *pstat = NULL;
+
+    if (ehRequest->payload)
+    {
+        uint8_t *payload = ((OCSecurityPayload *) ehRequest->payload)->securityData;
+        size_t size = ((OCSecurityPayload *) ehRequest->payload)->payloadSize;
+        VERIFY_NON_NULL(TAG, payload, ERROR);
+
+        OCStackResult ret = CBORPayloadToPstat(payload, size, &pstat);
+        VERIFY_NON_NULL(TAG, pstat, ERROR);
+        if (OC_STACK_OK == ret)
         {
-            gPstat->tm = (OicSecDpm_t)tmJson->valueint;
-            if(0 == tmJson->valueint && gPstat->commitHash == commitHash)
+            if (false == (pstat->cm & TAKE_OWNER) && false == pstat->isOp)
+            {
+                gPstat->cm = pstat->cm;
+                OIC_LOG (INFO, TAG, "State changed to Ready for Provisioning");
+            }
+            else if (false == (pstat->cm & TAKE_OWNER) && true == pstat->isOp)
             {
-                gPstat->isOp = true;
-                gPstat->cm = NORMAL;
-                OC_LOG (INFO, TAG, "CommitHash is valid and isOp is TRUE");
+                gPstat->isOp =pstat->isOp;
+                OIC_LOG (INFO, TAG, "State changed to Ready for Normal Operation");
             }
             else
             {
-                OC_LOG (INFO, TAG, "CommitHash is not valid");
+                OIC_LOG(DEBUG, TAG, "Invalid Device provisionig state");
             }
-        }
-        cJSON *omJson = cJSON_GetObjectItem(jsonPstat, OIC_JSON_OM_NAME);
-        if (omJson && gPstat)
-        {
-            /*
-             * Check if the operation mode is in the supported provisioning services
-             * operation mode list.
-             */
-            for(size_t i=0; i< gPstat->smLen; i++)
+            if (pstat->om != MULTIPLE_SERVICE_SERVER_DRIVEN && gPstat)
             {
-                if(gPstat->sm[i] == (unsigned int)omJson->valueint)
+                /*
+                 * Check if the operation mode is in the supported provisioning services
+                 * operation mode list.
+                 */
+                for (size_t i=0; i< gPstat->smLen; i++)
                 {
-                    gPstat->om = (OicSecDpom_t)omJson->valueint;
-                    break;
+                    if(gPstat->sm[i] == pstat->om)
+                    {
+                        gPstat->om = pstat->om;
+                        break;
+                    }
                 }
             }
-        }
-        // Convert pstat data into JSON for update to persistent storage
-        char *jsonStr = BinToPstatJSON(gPstat);
-        if (jsonStr)
-        {
-            cJSON *jsonPstat = cJSON_Parse(jsonStr);
-            OICFree(jsonStr);
-            if (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_PSTAT_NAME, jsonPstat))
+            // Convert pstat data into CBOR for update to persistent storage
+            if (UpdatePersistentStorage(gPstat))
             {
                 ehRet = OC_EH_OK;
             }
         }
     }
  exit:
+    if(OC_EH_OK != ehRet)
+    {
+        /*
+          * If some error is occured while ownership transfer,
+          * ownership transfer related resource should be revert back to initial status.
+          */
+        RestoreDoxmToInitState();
+        RestorePstatToInitState();
+    }
+
     //Send payload to request originator
-    if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL))
+    if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL, 0))
     {
-        OC_LOG (ERROR, TAG, "SendSRMResponse failed in HandlePstatPostRequest");
+        ehRet = OC_EH_ERROR;
+        OIC_LOG (ERROR, TAG, "SendSRMResponse failed in HandlePstatPostRequest");
     }
-    cJSON_Delete(postJson);
+    DeletePstatBinData(pstat);
     return ehRet;
 }
 
 /**
  * This internal method is the entity handler for pstat resources.
  */
-OCEntityHandlerResult PstatEntityHandler(OCEntityHandlerFlag flag,
-        OCEntityHandlerRequest * ehRequest,
-        void *callbackParam)
+ OCEntityHandlerResult PstatEntityHandler(OCEntityHandlerFlag flag,
+                                          OCEntityHandlerRequest * ehRequest,
+                                          void *callbackParam)
 {
     (void)callbackParam;
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
     // This method will handle REST request (GET/POST) for /oic/sec/pstat
     if (flag & OC_REQUEST_FLAG)
     {
-        OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
+        OIC_LOG(INFO, TAG, "Flag includes OC_REQUEST_FLAG");
         switch (ehRequest->method)
         {
             case OC_REST_GET:
@@ -308,7 +446,7 @@ OCEntityHandlerResult PstatEntityHandler(OCEntityHandlerFlag flag,
                 break;
             default:
                 ehRet = OC_EH_ERROR;
-                SendSRMResponse(ehRequest, ehRet, NULL);
+                SendSRMResponse(ehRequest, ehRet, NULL, 0);
                 break;
         }
     }
@@ -318,83 +456,89 @@ OCEntityHandlerResult PstatEntityHandler(OCEntityHandlerFlag flag,
 /**
  * This internal method is used to create '/oic/sec/pstat' resource.
  */
-OCStackResult CreatePstatResource()
+ OCStackResult CreatePstatResource()
 {
-    OCStackResult ret;
-
-    ret = OCCreateResource(&gPstatHandle,
-                           OIC_RSRC_TYPE_SEC_PSTAT,
-                           OIC_MI_DEF,
-                           OIC_RSRC_PSTAT_URI,
-                           PstatEntityHandler,
-                           NULL,
-                           OC_RES_PROP_NONE);
+    OCStackResult ret = OCCreateResource(&gPstatHandle,
+                                         OIC_RSRC_TYPE_SEC_PSTAT,
+                                         OIC_MI_DEF,
+                                         OIC_RSRC_PSTAT_URI,
+                                         PstatEntityHandler,
+                                         NULL,
+                                         OC_RES_PROP_NONE);
 
-    if (ret != OC_STACK_OK)
+    if (OC_STACK_OK != ret)
     {
-        OC_LOG (FATAL, TAG, "Unable to instantiate pstat resource");
+        OIC_LOG(FATAL, TAG, "Unable to instantiate pstat resource");
         DeInitPstatResource();
     }
     return ret;
 }
 
 /**
- * Post ACL hander update the commitHash during ACL provisioning.
- */
-void SetCommitHash(uint16_t commitHash)
-{
-    gPstat->commitHash = commitHash;
-}
-
-/**
- * Get the default value
- * @retval  the gDefaultPstat pointer
+ * Get the default value.
+ *
+ * @return the gDefaultPstat pointer.
  */
 static OicSecPstat_t* GetPstatDefault()
 {
     return &gDefaultPstat;
 }
 
-/**
- * Initialize pstat resource by loading data from persistent storage.
- *
- * @retval  OC_STACK_OK for Success, otherwise some error value
- */
 OCStackResult InitPstatResource()
 {
     OCStackResult ret = OC_STACK_ERROR;
 
     // Read Pstat resource from PS
-    char* jsonSVRDatabase = GetSVRDatabase();
-    if (jsonSVRDatabase)
+    uint8_t *data = NULL;
+    size_t size = 0;
+    OicUuid_t emptyUuid = {.id={0}};
+    ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_PSTAT_NAME, &data, &size);
+    // If database read failed
+    if (OC_STACK_OK != ret)
+    {
+        OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
+    }
+    if (data)
     {
-        // Convert JSON Pstat into binary format
-        gPstat = JSONToPstatBin(jsonSVRDatabase);
+        // Read ACL resource from PS
+        ret = CBORPayloadToPstat(data, size, &gPstat);
+        OICFree(data);
     }
     /*
      * If SVR database in persistent storage got corrupted or
      * is not available for some reason, a default pstat is created
      * which allows user to initiate pstat provisioning again.
      */
-    if(!jsonSVRDatabase || !gPstat)
+    if ((OC_STACK_OK != ret) || !gPstat)
     {
         gPstat = GetPstatDefault();
     }
+    VERIFY_NON_NULL(TAG, gPstat, FATAL);
+
+    //In case of Pstat's device id is empty, fill the device id as doxm's device id.
+    if(0 == memcmp(&gPstat->deviceID, &emptyUuid, sizeof(OicUuid_t)))
+    {
+        OicUuid_t doxmUuid = {.id={0}};
+        if(OC_STACK_OK == GetDoxmDeviceID(&doxmUuid))
+        {
+            memcpy(&gPstat->deviceID, &doxmUuid, sizeof(OicUuid_t));
+        }
+    }
+
     // Instantiate 'oic.sec.pstat'
     ret = CreatePstatResource();
 
-    OICFree(jsonSVRDatabase);
+exit:
+    if (OC_STACK_OK != ret)
+    {
+        DeInitPstatResource();
+    }
     return ret;
 }
 
-/**
- * Perform cleanup for pstat resources.
- *
- * @retval  OC_STACK_OK for Success, otherwise some error value
- */
 OCStackResult DeInitPstatResource()
 {
-    if(gPstat != &gDefaultPstat)
+    if (gPstat != &gDefaultPstat)
     {
         DeletePstatBinData(gPstat);
         gPstat = NULL;
@@ -402,3 +546,86 @@ OCStackResult DeInitPstatResource()
     return OCDeleteResource(gPstatHandle);
 }
 
+/**
+ * Function to restore pstat resurce to initial status.
+ * This function will use in case of error while ownership transfer
+ */
+void RestorePstatToInitState()
+{
+    if(gPstat)
+    {
+        OIC_LOG(INFO, TAG, "PSTAT resource will revert back to initial status.");
+
+        gPstat->cm = (OicSecDpm_t)(gPstat->cm | TAKE_OWNER);
+        gPstat->tm = (OicSecDpm_t)(gPstat->tm & (~TAKE_OWNER));
+        gPstat->om = SINGLE_SERVICE_CLIENT_DRIVEN;
+        if(gPstat->sm && 0 < gPstat->smLen)
+        {
+            gPstat->sm[0] = SINGLE_SERVICE_CLIENT_DRIVEN;
+        }
+
+        if (!UpdatePersistentStorage(gPstat))
+        {
+            OIC_LOG(ERROR, TAG, "Failed to revert PSTAT in persistent storage");
+        }
+    }
+}
+
+OCStackResult SetPstatRownerId(const OicUuid_t* newROwner)
+{
+    OCStackResult ret = OC_STACK_ERROR;
+    uint8_t *cborPayload = NULL;
+    size_t size = 0;
+    OicUuid_t prevId = {.id={0}};
+
+    if(NULL == newROwner)
+    {
+        ret = OC_STACK_INVALID_PARAM;
+    }
+    if(NULL == gPstat)
+    {
+        ret = OC_STACK_NO_RESOURCE;
+    }
+
+    if(newROwner && gPstat)
+    {
+        memcpy(prevId.id, gPstat->rownerID.id, sizeof(prevId.id));
+        memcpy(gPstat->rownerID.id, newROwner->id, sizeof(newROwner->id));
+
+        ret = PstatToCBORPayload(gPstat, &cborPayload, &size);
+        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+
+        ret = UpdateSecureResourceInPS(OIC_JSON_PSTAT_NAME, cborPayload, size);
+        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+
+        OICFree(cborPayload);
+    }
+
+    return ret;
+
+exit:
+    OICFree(cborPayload);
+    memcpy(gPstat->rownerID.id, prevId.id, sizeof(prevId.id));
+    return ret;
+}
+
+/**
+ * This function returns the "isop" status of the device.
+ *
+ * @return true iff pstat.isop == 1, else false
+ */
+bool GetPstatIsop()
+{
+    return gPstat->isOp;
+}
+
+OCStackResult GetPstatRownerId(OicUuid_t *rowneruuid)
+{
+    OCStackResult retVal = OC_STACK_ERROR;
+    if (gPstat)
+    {
+        *rowneruuid = gPstat->rownerID;
+        retVal = OC_STACK_OK;
+    }
+    return retVal;
+}
index 19fb099..198b62a 100644 (file)
@@ -18,6 +18,7 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#include <string.h>
 #include "resourcemanager.h"
 #include "securevirtualresourcetypes.h"
 #include "aclresource.h"
 #include "oic_string.h"
 #include "logger.h"
 #include "utlist.h"
-#include <string.h>
+
+//#ifdef DIRECT_PAIRING
+#include "pconfresource.h"
+#include "dpairingresource.h"
+//#endif // DIRECT_PAIRING
+#include "verresource.h"
 
 #define TAG "SRM-RM"
 
 #include "crlresource.h"
 #endif // __WITH_X509__
 
-/**
- * This method is used by all secure resource modules to send responses to REST queries.
- *
- * @param ehRequest pointer to entity handler request data structure.
- * @param ehRet result code from entity handler.
- * @param rspPayload response payload in JSON.
- *
- * @retval  OC_STACK_OK for Success, otherwise some error value
- */
 OCStackResult SendSRMResponse(const OCEntityHandlerRequest *ehRequest,
-        OCEntityHandlerResult ehRet, const char *rspPayload)
+        OCEntityHandlerResult ehRet, uint8_t *cborPayload, size_t size)
 {
-    OC_LOG (DEBUG, TAG, "SRM sending SRM response");
+    OIC_LOG(DEBUG, TAG, "SRM sending SRM response");
     OCEntityHandlerResponse response = {.requestHandle = NULL};
+    OCStackResult ret = OC_STACK_ERROR;
+
     if (ehRequest)
     {
         OCSecurityPayload ocPayload = {.base = {.type = PAYLOAD_TYPE_INVALID}};
@@ -59,21 +58,17 @@ OCStackResult SendSRMResponse(const OCEntityHandlerRequest *ehRequest,
         response.requestHandle = ehRequest->requestHandle;
         response.resourceHandle = ehRequest->resource;
         response.ehResult = ehRet;
-        response.payload = (OCPayload*)(&ocPayload);
+        response.payload = (OCPayload *)(&ocPayload);
         response.payload->type = PAYLOAD_TYPE_SECURITY;
-        ((OCSecurityPayload*)response.payload)->securityData = (char *)rspPayload;
+        ((OCSecurityPayload *)response.payload)->securityData = cborPayload;
+        ((OCSecurityPayload *)response.payload)->payloadSize = size;
         response.persistentBufferFlag = 0;
 
-        return OCDoResponse(&response);
+        ret = OCDoResponse(&response);
     }
-    return OC_STACK_ERROR;
+    return ret;
 }
 
-/**
- * Initialize all secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
- *
- * @retval  OC_STACK_OK for Success, otherwise some error value
- */
 OCStackResult InitSecureResources( )
 {
     OCStackResult ret;
@@ -106,11 +101,25 @@ OCStackResult InitSecureResources( )
     if(OC_STACK_OK == ret)
     {
         ret = InitSVCResource();
-       }
-       if(OC_STACK_OK == ret)
+    }
+    if(OC_STACK_OK == ret)
     {
         ret = InitAmaclResource();
     }
+//#ifdef DIRECT_PAIRING
+    if(OC_STACK_OK == ret)
+    {
+        ret = InitPconfResource();
+    }
+    if(OC_STACK_OK == ret)
+    {
+        ret = InitDpairingResource();
+    }
+//#endif // DIRECT_PAIRING
+    if(OC_STACK_OK == ret)
+    {
+        ret = InitVerResource();
+    }
     if(OC_STACK_OK != ret)
     {
         //TODO: Update the default behavior if one of the SVR fails
@@ -119,11 +128,6 @@ OCStackResult InitSecureResources( )
     return ret;
 }
 
-/**
- * Perform cleanup for secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
- *
- * @retval  OC_STACK_OK for Success, otherwise some error value
- */
 OCStackResult DestroySecureResources( )
 {
     DeInitACLResource();
@@ -135,6 +139,11 @@ OCStackResult DestroySecureResources( )
 #endif // __WITH_X509__
     DeInitSVCResource();
     DeInitAmaclResource();
+//#ifdef DIRECT_PAIRING
+    DeInitPconfResource();
+    DeInitDpairingResource();
+//#endif // DIRECT_PAIRING
+    DeInitVerResource();
 
     return OC_STACK_OK;
 }
index 6d55727..26a9277 100644 (file)
@@ -57,7 +57,7 @@ static SPResponseCallback gSPResponseHandler = NULL;
 PEContext_t g_policyEngineContext;
 
 /**
- * @brief function to register provisoning API's response callback.
+ * Function to register provisoning API's response callback.
  * @param respHandler response handler callback.
  */
 void SRMRegisterProvisioningResponseHandler(SPResponseCallback respHandler)
@@ -65,36 +65,48 @@ void SRMRegisterProvisioningResponseHandler(SPResponseCallback respHandler)
     gSPResponseHandler = respHandler;
 }
 
+void SetResourceRequestType(PEContext_t *context, const char *resourceUri)
+{
+    context->resourceType = GetSvrTypeFromUri(resourceUri);
+}
 
 static void SRMSendUnAuthorizedAccessresponse(PEContext_t *context)
 {
     CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
+
+    if (NULL == context ||
+       NULL == context->amsMgrContext->requestInfo)
+    {
+        OIC_LOG_V(ERROR, TAG, "%s : NULL Parameter(s)",__func__);
+        return;
+    }
+
     memcpy(&responseInfo.info, &(context->amsMgrContext->requestInfo->info),
             sizeof(responseInfo.info));
     responseInfo.info.payload = NULL;
     responseInfo.result = CA_UNAUTHORIZED_REQ;
-    if (CA_STATUS_OK != CASendResponse(context->amsMgrContext->endpoint, &responseInfo))
+
+    if (CA_STATUS_OK == CASendResponse(context->amsMgrContext->endpoint, &responseInfo))
     {
-        OC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
+        OIC_LOG(DEBUG, TAG, "Succeed in sending response to a unauthorized request!");
     }
     else
     {
-        OC_LOG(INFO, TAG, "Succeed in sending response to a unauthorized request!");
+        OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
     }
 }
 
-
 void SRMSendResponse(SRMAccessResponse_t responseVal)
 {
-    OC_LOG(DEBUG, TAG, "Sending response to remote device");
+    OIC_LOG(DEBUG, TAG, "Sending response to remote device");
 
     if (IsAccessGranted(responseVal) && gRequestHandler)
     {
-        OC_LOG_V(INFO, TAG, "%s : Access granted. Passing Request to RI layer", __func__);
+        OIC_LOG_V(INFO, TAG, "%s : Access granted. Passing Request to RI layer", __func__);
         if (!g_policyEngineContext.amsMgrContext->endpoint ||
-                !g_policyEngineContext.amsMgrContext->requestInfo)
+            !g_policyEngineContext.amsMgrContext->requestInfo)
         {
-            OC_LOG_V(ERROR, TAG, "%s : Invalid arguments", __func__);
+            OIC_LOG_V(ERROR, TAG, "%s : Invalid arguments", __func__);
             SRMSendUnAuthorizedAccessresponse(&g_policyEngineContext);
             goto exit;
         }
@@ -103,29 +115,28 @@ void SRMSendResponse(SRMAccessResponse_t responseVal)
     }
     else
     {
-        OC_LOG_V(INFO, TAG, "%s : ACCESS_DENIED.", __func__);
+        OIC_LOG_V(INFO, TAG, "%s : ACCESS_DENIED.", __func__);
         SRMSendUnAuthorizedAccessresponse(&g_policyEngineContext);
     }
 
 exit:
-    //Resting PE state to AWAITING_REQUEST
+    //Resetting PE state to AWAITING_REQUEST
     SetPolicyEngineState(&g_policyEngineContext, AWAITING_REQUEST);
 }
 
-
 /**
- * @brief   Handle the request from the SRM.
- * @param   endPoint       [IN] Endpoint object from which the response is received.
- * @param   requestInfo    [IN] Information for the request.
- * @return  NONE
+ * Handle the request from the SRM.
+ *
+ * @param endPoint object from which the response is received.
+ * @param requestInfo contains information for the request.
  */
 void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requestInfo)
 {
-    OC_LOG(DEBUG, TAG, "Received request from remote device");
+    OIC_LOG(DEBUG, TAG, "Received request from remote device");
 
     if (!endPoint || !requestInfo)
     {
-        OC_LOG(ERROR, TAG, "Invalid arguments");
+        OIC_LOG(ERROR, TAG, "Invalid arguments");
         return;
     }
 
@@ -147,24 +158,26 @@ void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requ
     }
     if (MAX_URI_LENGTH < position  || 0 > position)
     {
-        OC_LOG(ERROR, TAG, "Incorrect URI length");
+        OIC_LOG(ERROR, TAG, "Incorrect URI length");
         return;
     }
     SRMAccessResponse_t response = ACCESS_DENIED;
     char newUri[MAX_URI_LENGTH + 1];
     OICStrcpyPartial(newUri, MAX_URI_LENGTH + 1, requestInfo->info.resourceUri, position);
 
+    SetResourceRequestType(&g_policyEngineContext, newUri);
+
     //New request are only processed if the policy engine state is AWAITING_REQUEST.
-    if(AWAITING_REQUEST == g_policyEngineContext.state)
+    if (AWAITING_REQUEST == g_policyEngineContext.state)
     {
-        OC_LOG_V(DEBUG, TAG, "Processing request with uri, %s for method, %d",
+        OIC_LOG_V(DEBUG, TAG, "Processing request with uri, %s for method, %d",
                 requestInfo->info.resourceUri, requestInfo->method);
         response = CheckPermission(&g_policyEngineContext, &subjectId, newUri,
                 GetPermissionFromCAMethod_t(requestInfo->method));
     }
     else
     {
-        OC_LOG_V(INFO, TAG, "PE state %d. Ignoring request with uri, %s for method, %d",
+        OIC_LOG_V(INFO, TAG, "PE state %d. Ignoring request with uri, %s for method, %d",
                 g_policyEngineContext.state, requestInfo->info.resourceUri, requestInfo->method);
     }
 
@@ -180,9 +193,9 @@ void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requ
 
     VERIFY_NON_NULL(TAG, gRequestHandler, ERROR);
 
-    if(ACCESS_WAITING_FOR_AMS == response)
+    if (ACCESS_WAITING_FOR_AMS == response)
     {
-        OC_LOG(INFO, TAG, "Sending slow response");
+        OIC_LOG(INFO, TAG, "Sending slow response");
 
         UpdateAmsMgrContext(&g_policyEngineContext, endPoint, requestInfo);
         responseInfo.result = CA_EMPTY;
@@ -195,32 +208,32 @@ void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requ
          * CA_UNAUTHORIZED_REQ or CA_FORBIDDEN_REQ depending
          * upon SRMAccessResponseReasonCode_t
          */
-        OC_LOG(INFO, TAG, "Sending for regular response");
+        OIC_LOG(INFO, TAG, "Sending for regular response");
         responseInfo.result = CA_UNAUTHORIZED_REQ;
     }
 
     if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
     {
-        OC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
+        OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
     }
     return;
 exit:
     responseInfo.result = CA_INTERNAL_SERVER_ERROR;
     if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
     {
-        OC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
+        OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
     }
 }
 
 /**
- * @brief   Handle the response from the SRM.
- * @param   endPoint     [IN] The remote endpoint.
- * @param   responseInfo [IN] Response information from the endpoint.
- * @return  NONE
+ * Handle the response from the SRM.
+ *
+ * @param endPoint points to the remote endpoint.
+ * @param responseInfo contains response information from the endpoint.
  */
 void SRMResponseHandler(const CAEndpoint_t *endPoint, const CAResponseInfo_t *responseInfo)
 {
-    OC_LOG(DEBUG, TAG, "Received response from remote device");
+    OIC_LOG(DEBUG, TAG, "Received response from remote device");
 
     // isProvResponse flag is to check whether response is catered by provisioning APIs or not.
     // When token sent by CA response matches with token generated by provisioning request,
@@ -239,16 +252,15 @@ void SRMResponseHandler(const CAEndpoint_t *endPoint, const CAResponseInfo_t *re
     }
 }
 
-
 /**
- * @brief   Handle the error from the SRM.
- * @param   endPoint  [IN] The remote endpoint.
- * @param   errorInfo [IN] Error information from the endpoint.
- * @return  NONE
+ * Handle the error from the SRM.
+ *
+ * @param endPoint is the remote endpoint.
+ * @param errorInfo contains error information from the endpoint.
  */
 void SRMErrorHandler(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
 {
-    OC_LOG_V(INFO, TAG, "Received error from remote device with result, %d for request uri, %s",
+    OIC_LOG_V(INFO, TAG, "Received error from remote device with result, %d for request uri, %s",
             errorInfo->result, errorInfo->info.resourceUri);
     if (gErrorHandler)
     {
@@ -256,24 +268,14 @@ void SRMErrorHandler(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInf
     }
 }
 
-
-/**
- * @brief   Register request and response callbacks.
- *          Requests and responses are delivered in these callbacks.
- * @param   reqHandler   [IN] Request handler callback ( for GET,PUT ..etc)
- * @param   respHandler  [IN] Response handler callback.
- * @return
- *     OC_STACK_OK    - No errors; Success
- *     OC_STACK_INVALID_PARAM - invalid parameter
- */
 OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
                                  CAResponseCallback respHandler,
                                  CAErrorCallback errHandler)
 {
-    OC_LOG(DEBUG, TAG, "SRMRegisterHandler !!");
+    OIC_LOG(DEBUG, TAG, "SRMRegisterHandler !!");
     if( !reqHandler || !respHandler || !errHandler)
     {
-        OC_LOG(ERROR, TAG, "Callback handlers are invalid");
+        OIC_LOG(ERROR, TAG, "Callback handlers are invalid");
         return OC_STACK_INVALID_PARAM;
     }
     gRequestHandler = reqHandler;
@@ -289,90 +291,60 @@ OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
     return OC_STACK_OK;
 }
 
-/**
- * @brief   Register Persistent storage callback.
- * @param   persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
- * @return
- *     OC_STACK_OK    - No errors; Success
- *     OC_STACK_INVALID_PARAM - Invalid parameter
- */
 OCStackResult SRMRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
 {
-    OC_LOG(DEBUG, TAG, "SRMRegisterPersistentStorageHandler !!");
+    OIC_LOG(DEBUG, TAG, "SRMRegisterPersistentStorageHandler !!");
     if(!persistentStorageHandler)
     {
-        OC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
+        OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
         return OC_STACK_INVALID_PARAM;
     }
     gPersistentStorageHandler = persistentStorageHandler;
     return OC_STACK_OK;
 }
 
-/**
- * @brief   Get Persistent storage handler pointer.
- * @return
- *     The pointer to Persistent Storage callback handler
- */
-
 OCPersistentStorage* SRMGetPersistentStorageHandler()
 {
     return gPersistentStorageHandler;
 }
 
-
-/**
- * @brief   Initialize all secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
- * @retval  OC_STACK_OK for Success, otherwise some error value
- */
 OCStackResult SRMInitSecureResources()
 {
     // TODO: temporarily returning OC_STACK_OK every time until default
     // behavior (for when SVR DB is missing) is settled.
     InitSecureResources();
-
+    OCStackResult ret = OC_STACK_OK;
 #if defined(__WITH_DTLS__)
-    CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials);
+    if(CA_STATUS_OK != CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials))
+    {
+        OIC_LOG(ERROR, TAG, "Failed to revert DTLS credential handler.");
+        ret = OC_STACK_ERROR;
+    }
+
 #endif // (__WITH_DTLS__)
 #if defined(__WITH_X509__)
     CARegisterDTLSX509CredentialsHandler(GetDtlsX509Credentials);
     CARegisterDTLSCrlHandler(GetDerCrl);
 #endif // (__WITH_X509__)
 
-    return OC_STACK_OK;
+    return ret;
 }
 
-/**
- * @brief   Perform cleanup for secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
- * @retval  none
- */
 void SRMDeInitSecureResources()
 {
     DestroySecureResources();
 }
 
-/**
- * @brief   Initialize Policy Engine.
- * @return  OC_STACK_OK for Success, otherwise some error value.
- */
 OCStackResult SRMInitPolicyEngine()
 {
     return InitPolicyEngine(&g_policyEngineContext);
 }
 
-/**
- * @brief   Cleanup Policy Engine.
- * @return  none
- */
 void SRMDeInitPolicyEngine()
 {
     return DeInitPolicyEngine(&g_policyEngineContext);
 }
 
-/**
- * @brief   Check the security resource URI.
- * @param   uri [IN] Pointers to security resource URI.
- * @return  true if the URI is one of security resources, otherwise false.
- */
 bool SRMIsSecurityResourceURI(const char* uri)
 {
     if (!uri)
@@ -388,6 +360,9 @@ bool SRMIsSecurityResourceURI(const char* uri)
         OIC_RSRC_ACL_URI,
         OIC_RSRC_DOXM_URI,
         OIC_RSRC_PSTAT_URI,
+        OIC_RSRC_PCONF_URI,
+        OIC_RSRC_DPAIRING_URI,
+        OIC_RSRC_VER_URI,
     };
 
     // Remove query from Uri for resource string comparison
@@ -411,3 +386,120 @@ bool SRMIsSecurityResourceURI(const char* uri)
 
     return false;
 }
+
+/**
+ * Get the Secure Virtual Resource (SVR) type from the URI.
+ * @param   uri [IN] Pointer to URI in question.
+ * @return  The OicSecSvrType_t of the URI passed (note: if not a Secure Virtual
+            Resource, e.g. /a/light, will return "NOT_A_SVR_TYPE" enum value)
+ */
+static const char URI_QUERY_CHAR = '?';
+OicSecSvrType_t GetSvrTypeFromUri(const char* uri)
+{
+    if (!uri)
+    {
+        return NOT_A_SVR_RESOURCE;
+    }
+
+    // Remove query from Uri for resource string comparison
+    size_t uriLen = strlen(uri);
+    char *query = strchr (uri, URI_QUERY_CHAR);
+    if (query)
+    {
+        uriLen = query - uri;
+    }
+
+    size_t svrLen = 0;
+
+    svrLen = strlen(OIC_RSRC_ACL_URI);
+    if(uriLen == svrLen)
+    {
+        if(0 == strncmp(uri, OIC_RSRC_ACL_URI, svrLen))
+        {
+            return OIC_R_ACL_TYPE;
+        }
+    }
+
+    svrLen = strlen(OIC_RSRC_AMACL_URI);
+    if(uriLen == svrLen)
+    {
+        if(0 == strncmp(uri, OIC_RSRC_AMACL_URI, svrLen))
+        {
+            return OIC_R_AMACL_TYPE;
+        }
+    }
+
+    svrLen = strlen(OIC_RSRC_CRED_URI);
+    if(uriLen == svrLen)
+    {
+        if(0 == strncmp(uri, OIC_RSRC_CRED_URI, svrLen))
+        {
+            return OIC_R_CRED_TYPE;
+        }
+    }
+
+    svrLen = strlen(OIC_RSRC_CRL_URI);
+    if(uriLen == svrLen)
+    {
+        if(0 == strncmp(uri, OIC_RSRC_CRL_URI, svrLen))
+        {
+            return OIC_R_CRL_TYPE;
+        }
+    }
+
+    svrLen = strlen(OIC_RSRC_DOXM_URI);
+    if(uriLen == svrLen)
+    {
+        if(0 == strncmp(uri, OIC_RSRC_DOXM_URI, svrLen))
+        {
+            return OIC_R_DOXM_TYPE;
+        }
+    }
+
+    svrLen = strlen(OIC_RSRC_DPAIRING_URI);
+    if(uriLen == svrLen)
+    {
+        if(0 == strncmp(uri, OIC_RSRC_DPAIRING_URI, svrLen))
+        {
+            return OIC_R_DPAIRING_TYPE;
+        }
+    }
+
+    svrLen = strlen(OIC_RSRC_PCONF_URI);
+    if(uriLen == svrLen)
+    {
+        if(0 == strncmp(uri, OIC_RSRC_PCONF_URI, svrLen))
+        {
+            return OIC_R_PCONF_TYPE;
+        }
+    }
+
+    svrLen = strlen(OIC_RSRC_PSTAT_URI);
+    if(uriLen == svrLen)
+    {
+        if(0 == strncmp(uri, OIC_RSRC_PSTAT_URI, svrLen))
+        {
+            return OIC_R_PSTAT_TYPE;
+        }
+    }
+
+    svrLen = strlen(OIC_RSRC_SVC_URI);
+    if(uriLen == svrLen)
+    {
+        if(0 == strncmp(uri, OIC_RSRC_SVC_URI, svrLen))
+        {
+            return OIC_R_SVC_TYPE;
+        }
+    }
+
+    svrLen = strlen(OIC_RSRC_SACL_URI);
+    if(uriLen == svrLen)
+    {
+        if(0 == strncmp(uri, OIC_RSRC_SACL_URI, svrLen))
+        {
+            return OIC_R_SACL_TYPE;
+        }
+    }
+
+    return NOT_A_SVR_RESOURCE;
+}
old mode 100755 (executable)
new mode 100644 (file)
index be72bf3..d7b3c77
@@ -22,6 +22,7 @@
 #include "securevirtualresourcetypes.h"
 
 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
@@ -33,6 +34,8 @@ const char * OIC_JSON_AMACL_NAME = "amacl";
 const char * OIC_RSRC_TYPE_SEC_ACL = "oic.sec.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";
@@ -48,49 +51,99 @@ const char * OIC_JSON_DOXM_NAME = "doxm";
 const char * OIC_RSRC_TYPE_SEC_CRED = "oic.sec.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_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_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_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_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_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_VER_URI =  "/oic/sec/ver";
+const char * OIC_JSON_VER_NAME = "ver";
 
-const char * OIC_JSON_SUBJECT_NAME = "sub";
-const char * OIC_JSON_RESOURCES_NAME = "rsrc";
+const char * OIC_JSON_SUBJECT_NAME = "subject";
+const char * OIC_JSON_RESOURCES_NAME = "resources";
 const char * OIC_JSON_AMSS_NAME = "amss";
-const char * OIC_JSON_PERMISSION_NAME = "perms";
+const char * OIC_JSON_AMS_NAME = "ams";
+const char * OIC_JSON_PERMISSION_NAME = "permission";
 const char * OIC_JSON_OWNERS_NAME = "ownrs";
 const char * OIC_JSON_OWNER_NAME = "ownr";
+const char * OIC_JSON_DEVOWNERID_NAME = "devowneruuid";
 const char * OIC_JSON_OWNED_NAME = "owned";
 const char * OIC_JSON_OXM_NAME = "oxm";
+const char * OIC_JSON_OXMS_NAME = "oxms";
 const char * OIC_JSON_OXM_TYPE_NAME = "oxmtype";
 const char * OIC_JSON_OXM_SEL_NAME = "oxmsel";
-const char * OIC_JSON_DEVICE_ID_FORMAT_NAME = "dvcidfrmt";
+const char * OIC_JSON_DEVICE_ID_FORMAT_NAME = "didformat";
 const char * OIC_JSON_ISOP_NAME = "isop";
 const char * OIC_JSON_COMMIT_HASH_NAME = "ch";
-const char * OIC_JSON_DEVICE_ID_NAME = "deviceid";
+const char * OIC_JSON_DEVICE_ID_NAME = "deviceuuid";
 const char * OIC_JSON_CM_NAME = "cm";
 const char * OIC_JSON_TM_NAME = "tm";
 const char * OIC_JSON_OM_NAME = "om";
 const char * OIC_JSON_SM_NAME = "sm";
 const char * OIC_JSON_CREDID_NAME = "credid";
-const char * OIC_JSON_SUBJECTID_NAME = "subid";
+const char * OIC_JSON_SUBJECTID_NAME = "subjectuuid";
 const char * OIC_JSON_ROLEIDS_NAME = "roleid";
-const char * OIC_JSON_CREDTYPE_NAME = "credtyp";
-const char * OIC_JSON_PUBLICDATA_NAME = "pbdata";
-const char * OIC_JSON_PRIVATEDATA_NAME = "pvdata";
+const char * OIC_JSON_CREDTYPE_NAME = "credtype";
+const char * OIC_JSON_PUBLICDATA_NAME = "publicdata";
+const char * OIC_JSON_PRIVATEDATA_NAME = "privatedata";
+const char * OIC_JSON_PUBDATA_NAME = "pubdata";
+const char * OIC_JSON_PRIVDATA_NAME = "privdata";
+const char * OIC_JSON_OPTDATA_NAME = "optdata";
 const char * OIC_JSON_SERVICE_DEVICE_ID = "svcdid";
 const char * OIC_JSON_SERVICE_TYPE = "svct";
-const char * OIC_JSON_PERIOD_NAME = "prd";
+const char * OIC_JSON_PERIOD_NAME = "period";
 const char * OIC_JSON_PERIODS_NAME = "prds";
-const char * OIC_JSON_RECURRENCES_NAME = "recurs";
+const char * OIC_JSON_CRMS_NAME = "crms";
+const char * OIC_JSON_RECURRENCES_NAME = "recurrence";
 const char * OIC_JSON_SUPPORTED_CRED_TYPE_NAME = "sct";
+const char * OIC_JSON_DPC_NAME = "dpc";
+const char * OIC_JSON_EDP_NAME = "edp";
+const char * OIC_JSON_PIN_NAME = "pin";
+const char * OIC_JSON_PDACL_NAME = "pdacl";
+const char * OIC_JSON_PDDEV_LIST_NAME = "pddev";
+const char * OIC_JSON_ROWNER_NAME = "rowner";
+const char * OIC_JSON_PRM_NAME = "prm";
+const char * OIC_JSON_SPM_NAME = "spm";
+const char * OIC_JSON_PDEVICE_ID_NAME = "pdeviceuuid";
+const char * OIC_JSON_RLIST_NAME = "rlist";
+const char * OIC_JSON_HREF_NAME = "href";
+const char * OIC_JSON_REL_NAME = "rel";
+const char * OIC_JSON_RT_NAME = "rt";
+const char * OIC_JSON_IF_NAME = "if";
+const char * OIC_JSON_ROWNERID_NAME = "rowneruuid";
+const char * OIC_JSON_ENCODING_NAME = "encoding";
+const char * OIC_JSON_DATA_NAME = "data";
+const char * OIC_JSON_SEC_V_NAME = "secv";
+
+const char * OIC_JSON_EMPTY_STRING = "";
 
 OicUuid_t WILDCARD_SUBJECT_ID = {"*"};
+OicUuid_t WILDCARD_SUBJECT_B64_ID = { .id = {'2', '2', '2', '2', '2', '2', '2', '2',
+                                             '2', '2', '2', '2', '2', '2', '2', '2' }};
 size_t WILDCARD_SUBJECT_ID_LEN = 1;
 const char * WILDCARD_RESOURCE_URI = "*";
 
@@ -99,9 +152,16 @@ const char * OXM_JUST_WORKS = "oic.sec.doxm.jw";
 const char * OXM_RANDOM_DEVICE_PIN = "oic.sec.doxm.rdp";
 const char * OXM_MANUFACTURER_CERTIFICATE = "oic.sec.doxm.mfgcert";
 
+//Credential data encoding methods
+const char * OIC_SEC_ENCODING_BASE64 = "oic.sec.encoding.base64";
+const char * OIC_SEC_ENCODING_RAW = "oic.sec.encoding.raw";
+
 const char * OIC_SEC_TRUE = "true";
 const char * OIC_SEC_FALSE = "false";
 
 const char * OIC_SEC_REST_QUERY_SEPARATOR = ";";
 char OIC_SEC_REST_QUERY_DELIMETER = '=';
 
+//Security Version
+const char * DEFAULT_SEC_VERSION = "0.0.0";
+
index af52938..1cc5694 100644 (file)
 
 #define TAG  "SRM-UTILITY"
 
-/**
- * This method initializes the OicParseQueryIter_t struct
- *
- *@param query     - REST query, to be parsed
- *@param parseIter - OicParseQueryIter_t struct, to be initialized
- *
- */
-void ParseQueryIterInit(unsigned char * query, OicParseQueryIter_t * parseIter)
+void ParseQueryIterInit(const unsigned char * query, OicParseQueryIter_t * parseIter)
 {
-    OC_LOG (INFO, TAG, "Initializing coap iterator");
-    if((NULL == query) || (NULL == parseIter))
+    OIC_LOG(INFO, TAG, "Initializing coap iterator");
+    if ((NULL == query) || (NULL == parseIter))
+    {
         return;
+    }
 
     parseIter->attrPos = NULL;
     parseIter->attrLen = 0;
     parseIter->valPos = NULL;
     parseIter->valLen = 0;
-    coap_parse_iterator_init(query, strlen((char *)query),
-          (unsigned char *)OIC_SEC_REST_QUERY_SEPARATOR, (unsigned char *) "", 0, &parseIter->pi);
+    coap_parse_iterator_init((unsigned char *)query, strlen((char *)query),
+                             (unsigned char *)OIC_SEC_REST_QUERY_SEPARATOR,
+                             (unsigned char *) "", 0, &parseIter->pi);
 }
 
-/**
- * This method fills the OicParseQueryIter_t struct with next REST query's
- * attribute's and value's information
- *
- *@param parseIter - OicParseQueryIter_t struct, has next query's attribute's & value's info
- *
- * @retval
- *     OicParseQueryIter_t *  - has parsed query info
- *     NULL                   - has no query to parse
- */
 OicParseQueryIter_t * GetNextQuery(OicParseQueryIter_t * parseIter)
 {
-    OC_LOG (INFO, TAG, "Getting Next Query");
-    if(NULL == parseIter)
+    OIC_LOG(INFO, TAG, "Getting Next Query");
+    if (NULL == parseIter)
+    {
         return NULL;
+    }
 
     unsigned char * qrySeg = NULL;
     char * delimPos;
 
-    //Get the next query. Querys are separated by OIC_SEC_REST_QUERY_SEPARATOR
+    // Get the next query. Querys are separated by OIC_SEC_REST_QUERY_SEPARATOR.
     qrySeg = coap_parse_next(&parseIter->pi);
 
-    if(qrySeg)
+    if (qrySeg)
     {
         delimPos = strchr((char *)qrySeg, OIC_SEC_REST_QUERY_DELIMETER);
-        if(delimPos)
+        if (delimPos)
         {
             parseIter->attrPos = parseIter->pi.pos;
             parseIter->attrLen = (unsigned char *)delimPos - parseIter->pi.pos;
@@ -86,19 +74,18 @@ OicParseQueryIter_t * GetNextQuery(OicParseQueryIter_t * parseIter)
     return NULL;
 }
 
-
 // TODO This functionality is replicated in all SVR's and therefore we need
 // to encapsulate it in a common method. However, this may not be the right
 // file for this method.
-OCStackResult AddUuidArray(cJSON* jsonRoot, const char* arrayItem,
-                           size_t *numUuids, OicUuid_t** uuids )
+OCStackResult AddUuidArray(const cJSON* jsonRoot, const char* arrayItem,
+                           size_t *numUuids, OicUuid_t** uuids)
 {
     size_t idxx = 0;
-    cJSON* jsonObj = cJSON_GetObjectItem(jsonRoot, arrayItem);
+    cJSON* jsonObj = cJSON_GetObjectItem((cJSON *)jsonRoot, arrayItem);
     VERIFY_NON_NULL(TAG, jsonObj, ERROR);
     VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
 
-    *numUuids = cJSON_GetArraySize(jsonObj);
+    *numUuids = (size_t)cJSON_GetArraySize(jsonObj);
     VERIFY_SUCCESS(TAG, *numUuids > 0, ERROR);
     *uuids = (OicUuid_t*)OICCalloc(*numUuids, sizeof(OicUuid_t));
     VERIFY_NON_NULL(TAG, *uuids, ERROR);
@@ -115,10 +102,10 @@ OCStackResult AddUuidArray(cJSON* jsonRoot, const char* arrayItem,
 
         outLen = 0;
         b64Ret = b64Decode(jsonOwnr->valuestring, strlen(jsonOwnr->valuestring), base64Buff,
-                sizeof(base64Buff), &outLen);
+               sizeof(base64Buff), &outLen);
 
         VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof((*uuids)[idxx].id)),
-                ERROR);
+               ERROR);
         memcpy((*uuids)[idxx].id, base64Buff, outLen);
     } while ( ++idxx < *numUuids);
 
@@ -128,3 +115,102 @@ exit:
     return OC_STACK_ERROR;
 
 }
+
+/**
+ * Function to getting string of ownership transfer method
+ *
+ * @prarm oxmType ownership transfer method
+ *
+ * @return string value of ownership transfer method
+ */
+const char* GetOxmString(OicSecOxm_t oxmType)
+{
+    switch(oxmType)
+    {
+        case OIC_JUST_WORKS:
+            return OXM_JUST_WORKS;
+        case OIC_RANDOM_DEVICE_PIN:
+            return OXM_RANDOM_DEVICE_PIN;
+        case OIC_MANUFACTURER_CERTIFICATE:
+            return OXM_MANUFACTURER_CERTIFICATE;
+        default:
+            return NULL;
+    }
+}
+
+OCStackResult ConvertUuidToStr(const OicUuid_t* uuid, char** strUuid)
+{
+    if(NULL == uuid || NULL == strUuid || NULL != *strUuid)
+    {
+        OIC_LOG(ERROR, TAG, "ConvertUuidToStr : Invalid param");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    size_t uuidIdx = 0;
+    size_t urnIdx = 0;
+    const size_t urnBufSize = (UUID_LENGTH * 2) + 4 + 1;
+    char* convertedUrn = (char*)OICCalloc(urnBufSize, sizeof(char));
+    VERIFY_NON_NULL(TAG, convertedUrn, ERROR);
+
+    for(uuidIdx=0, urnIdx=0;  uuidIdx < UUID_LENGTH && urnIdx < urnBufSize; uuidIdx++, urnIdx+=2)
+    {
+        // canonical format for UUID has '8-4-4-4-12'
+        if(uuidIdx==4 || uuidIdx==6 || uuidIdx==8 || uuidIdx==10)
+        {
+            snprintf(convertedUrn + urnIdx, 2, "%c", '-');
+            urnIdx++;
+        }
+        snprintf(convertedUrn + urnIdx, 3, "%02x", (uint8_t)(uuid->id[uuidIdx]));
+    }
+    convertedUrn[urnBufSize - 1] = '\0';
+
+    *strUuid = convertedUrn;
+    return OC_STACK_OK;
+
+exit:
+    return OC_STACK_NO_MEMORY;
+}
+
+OCStackResult ConvertStrToUuid(const char* strUuid, OicUuid_t* uuid)
+{
+    if(NULL == strUuid || NULL == uuid)
+    {
+        OIC_LOG(ERROR, TAG, "ConvertStrToUuid : Invalid param");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    size_t urnIdx = 0;
+    size_t uuidIdx = 0;
+    size_t strUuidLen = 0;
+    char convertedUuid[UUID_LENGTH * 2] = {0};
+
+    strUuidLen = strlen(strUuid);
+    if(0 == strUuidLen)
+    {
+        OIC_LOG(INFO, TAG, "The empty string detected, The UUID will be converted to "\
+                           "\"00000000-0000-0000-0000-000000000000\"");
+    }
+    else if(UUID_LENGTH * 2 + 4 == strUuidLen)
+    {
+        for(uuidIdx=0, urnIdx=0; uuidIdx < UUID_LENGTH ; uuidIdx++, urnIdx+=2)
+        {
+            if(*(strUuid + urnIdx) == '-')
+            {
+                urnIdx++;
+            }
+            sscanf(strUuid + urnIdx, "%2hhx", &convertedUuid[uuidIdx]);
+        }
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "Invalid string uuid format, Please set the uuid as correct format");
+        OIC_LOG(ERROR, TAG, "e.g) \"72616E64-5069-6E44-6576-557569643030\" (4-2-2-2-6)");
+        OIC_LOG(ERROR, TAG, "e.g) \"\"");
+
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    memcpy(uuid->id, convertedUuid, UUID_LENGTH);
+
+    return OC_STACK_OK;
+}
index 28a8c59..a1175aa 100644 (file)
 // limitations under the License.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#include <stdlib.h>
+#include <string.h>
 
 #include "ocstack.h"
-#include "logger.h"
+#include "ocpayload.h"
 #include "oic_malloc.h"
-#include "cJSON.h"
-#include "base64.h"
+#include "utlist.h"
+#include "payload_logging.h"
 #include "resourcemanager.h"
 #include "psinterface.h"
 #include "svcresource.h"
-#include "utlist.h"
 #include "srmresourcestrings.h"
 #include "srmutility.h"
-#include <stdlib.h>
-#include <string.h>
+
+#include "security_internals.h"
 
 #define TAG  "SRM-SVC"
 
-OicSecSvc_t        *gSvc = NULL;
+/** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
+ * The value of payload size is increased until reaching belox max cbor size. */
+static const uint16_t CBOR_SIZE = 512;
+
+/** Max cbor size payload. */
+static const uint16_t CBOR_MAX_SIZE = 4400;
+
+/** SVC Map size - Number of mandatory items. */
+static const uint8_t SVC_MAP_SIZE = 3;
+
+static OicSecSvc_t        *gSvc = NULL;
 static OCResourceHandle    gSvcHandle = NULL;
 
 void DeleteSVCList(OicSecSvc_t* svc)
@@ -55,236 +66,317 @@ void DeleteSVCList(OicSecSvc_t* svc)
     }
 }
 
-/*
- * This internal method converts SVC data into JSON format.
- *
- * Note: Caller needs to invoke 'free' when finished done using
- * return string.
- */
-char * BinToSvcJSON(const OicSecSvc_t * svc)
+static size_t svcElementsCount(const OicSecSvc_t *secSvc)
 {
-    cJSON *jsonRoot = NULL;
-    char *jsonStr = NULL;
+    size_t size = 0;
+    for (const OicSecSvc_t *svc = secSvc; svc; svc = svc->next)
+    {
+        size++;
+    }
+    return size;
+}
 
-    if (svc)
+OCStackResult SVCToCBORPayload(const OicSecSvc_t *svc, uint8_t **cborPayload,
+                               size_t *cborSize)
+{
+    if (NULL == svc || NULL == cborPayload || NULL != *cborPayload || NULL == cborSize)
     {
-        jsonRoot = cJSON_CreateObject();
-        VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+       return OC_STACK_INVALID_PARAM;
+    }
 
-        cJSON *jsonSvcArray = NULL;
-        cJSON_AddItemToObject (jsonRoot, OIC_JSON_SVC_NAME, jsonSvcArray = cJSON_CreateArray());
-        VERIFY_NON_NULL(TAG, jsonSvcArray, ERROR);
+    size_t cborLen = *cborSize;
+    if (0 == cborLen)
+    {
+        cborLen = CBOR_SIZE;
+    }
+    *cborPayload = NULL;
+    *cborSize = 0;
 
-        while(svc)
-        {
-            char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
-            uint32_t outLen = 0;
-            B64Result b64Ret = B64_OK;
+    int64_t cborEncoderResult = CborNoError;
+    OCStackResult ret = OC_STACK_ERROR;
+    CborEncoder encoder;
+    CborEncoder svcArray;
 
-            cJSON *jsonSvc = cJSON_CreateObject();
+    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
+    VERIFY_NON_NULL(TAG, outPayload, ERROR);
 
-            // Service Device Identity
-            outLen = 0;
-            b64Ret = b64Encode(svc->svcdid.id, sizeof(OicUuid_t), base64Buff,
-                    sizeof(base64Buff), &outLen);
-            VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
-            cJSON_AddStringToObject(jsonSvc, OIC_JSON_SERVICE_DEVICE_ID, base64Buff );
+    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
 
-            // Service Type
-            cJSON_AddNumberToObject (jsonSvc, OIC_JSON_SERVICE_TYPE, svc->svct);
+    // Create SVC Array
+    cborEncoderResult = cbor_encoder_create_array(&encoder, &svcArray, svcElementsCount(svc));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Create SVC Array.");
 
-            // Owners
-            cJSON *jsonOwnrArray = NULL;
-            cJSON_AddItemToObject (jsonSvc, OIC_JSON_OWNERS_NAME, jsonOwnrArray = cJSON_CreateArray());
-            VERIFY_NON_NULL(TAG, jsonOwnrArray, ERROR);
-            for (unsigned int i = 0; i < svc->ownersLen; i++)
-            {
-                outLen = 0;
+    while (svc)
+    {
+        CborEncoder svcMap;
+        CborEncoder owners;
+
+        cborEncoderResult = cbor_encoder_create_map(&svcArray, &svcMap, SVC_MAP_SIZE);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Create SVC Map.");
+
+        // Service Device Identity
+        cborEncoderResult = cbor_encode_text_string(&svcMap, OIC_JSON_SERVICE_DEVICE_ID,
+            strlen(OIC_JSON_SERVICE_DEVICE_ID));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Add SVC Device Id.");
+        cborEncoderResult = cbor_encode_byte_string(&svcMap, (uint8_t *)svc->svcdid.id,
+            sizeof(svc->svcdid.id));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to ");
+
+        // Service Type
+        cborEncoderResult = cbor_encode_text_string(&svcMap, OIC_JSON_SERVICE_TYPE,
+            strlen(OIC_JSON_SERVICE_TYPE));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Add SVC Serv Type Tag.");
+        cborEncoderResult = cbor_encode_int(&svcMap, svc->svct);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Add SVC Serv Type Value.");
+
+        // Owners
+        // TODO: Need to modification to single ROwner, (Currently SINGLE_SERVICE_CLIENT_DRIVEN only)
+        cborEncoderResult = cbor_encode_text_string(&svcMap, OIC_JSON_OWNERS_NAME,
+            strlen(OIC_JSON_OWNERS_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Add SVC Owners Tag.");
+        cborEncoderResult = cbor_encoder_create_array(&svcMap, &owners, svc->ownersLen);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Add SVC Array.");
+        for (size_t i = 0; i < svc->ownersLen; i++)
+        {
+            cborEncoderResult = cbor_encode_byte_string(&owners, (uint8_t *)svc->owners[i].id,
+                sizeof(svc->owners[i].id));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Add SVC Owners Value.");
+        }
+        cborEncoderResult = cbor_encoder_close_container(&svcMap, &owners);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Close SVC Array.");
 
-                b64Ret = b64Encode(svc->owners[i].id, sizeof(((OicUuid_t*)0)->id), base64Buff,
-                        sizeof(base64Buff), &outLen);
-                VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
+        cborEncoderResult = cbor_encoder_close_container(&svcArray, &svcMap);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Close SVC Map.");
 
-                cJSON_AddItemToArray (jsonOwnrArray, cJSON_CreateString(base64Buff));
-            }
+        svc = svc->next;
+    }
 
-            // Attach current svc node to Svc Array
-            cJSON_AddItemToArray(jsonSvcArray, jsonSvc);
-            svc = svc->next;
-        }
+    cborEncoderResult = cbor_encoder_close_container(&encoder, &svcArray);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Close SVC Array.");
 
-        jsonStr = cJSON_PrintUnformatted(jsonRoot);
+    if (CborNoError == cborEncoderResult)
+    {
+        *cborPayload = outPayload;
+        *cborSize = encoder.ptr - outPayload;
+        ret = OC_STACK_OK;
     }
 
 exit:
-    if (jsonRoot)
+    if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
     {
-        cJSON_Delete(jsonRoot);
+        // reallocate and try again!
+        OICFree(outPayload);
+        outPayload = NULL;
+        // Since the allocated initial memory failed, double the memory.
+        cborLen += encoder.ptr - encoder.end;
+        cborEncoderResult = CborNoError;
+        ret = SVCToCBORPayload(svc, cborPayload, &cborLen);
+        *cborSize = cborLen;
     }
-    return jsonStr;
+
+    if (CborNoError != cborEncoderResult)
+    {
+        OICFree(outPayload);
+        outPayload = NULL;
+        *cborSize = 0;
+        *cborPayload = NULL;
+        ret = OC_STACK_ERROR;
+    }
+
+    return ret;
 }
 
-/*
- * This internal method converts JSON SVC into binary SVC.
- */
-OicSecSvc_t * JSONToSvcBin(const char * jsonStr)
+OCStackResult CBORPayloadToSVC(const uint8_t *cborPayload, size_t size,
+                               OicSecSvc_t **secSvc)
 {
+    if (NULL == cborPayload || NULL == secSvc || NULL != *secSvc || 0 == size)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    *secSvc = NULL;
+
     OCStackResult ret = OC_STACK_ERROR;
-    OicSecSvc_t * headSvc = NULL;
-    OicSecSvc_t * prevSvc = NULL;
-    cJSON *jsonRoot = NULL;
-    cJSON *jsonSvcArray = NULL;
 
-    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
+    CborValue svcCbor = { .parser = NULL };
+    CborParser parser = { .end = NULL };
+    CborError cborFindResult = CborNoError;
 
-    jsonRoot = cJSON_Parse(jsonStr);
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+    cbor_parser_init(cborPayload, size, 0, &parser, &svcCbor);
+    OicSecSvc_t *headSvc = NULL;
 
-    jsonSvcArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_SVC_NAME);
-    VERIFY_NON_NULL(TAG, jsonSvcArray, INFO);
+    CborValue svcArray = { .parser = NULL };
+    cborFindResult = cbor_value_enter_container(&svcCbor, &svcArray);
+    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Enter SVC Array.");
 
-    if (cJSON_Array == jsonSvcArray->type)
+    while (cbor_value_is_valid(&svcArray))
     {
-        int numSvc = cJSON_GetArraySize(jsonSvcArray);
-        int idx = 0;
+        CborValue svcMap = { .parser = NULL };
+        OicSecSvc_t *svc = (OicSecSvc_t *) OICCalloc(1, sizeof(OicSecSvc_t));
+        VERIFY_NON_NULL(TAG, svc, ERROR);
+        cborFindResult = cbor_value_enter_container(&svcArray, &svcMap);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Enter SVC Map.");
 
-        VERIFY_SUCCESS(TAG, numSvc > 0, INFO);
-        do
+        while (cbor_value_is_valid(&svcMap))
         {
-            cJSON *jsonSvc = cJSON_GetArrayItem(jsonSvcArray, idx);
-            VERIFY_NON_NULL(TAG, jsonSvc, ERROR);
+            char* name = NULL;
+            size_t len = 0;
+            CborType type = CborInvalidType;
 
-            OicSecSvc_t *svc = (OicSecSvc_t*)OICCalloc(1, sizeof(OicSecSvc_t));
-            VERIFY_NON_NULL(TAG, svc, ERROR);
+            cborFindResult = cbor_value_dup_text_string(&svcMap, &name, &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Find Name.");
+            cborFindResult = cbor_value_advance(&svcMap);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Advance.");
 
-            headSvc = (headSvc) ? headSvc : svc;
-            if (prevSvc)
+            type = cbor_value_get_type(&svcMap);
+            // Service Device Identity
+            if (0 == strcmp(OIC_JSON_SERVICE_DEVICE_ID, name))
             {
-                prevSvc->next = svc;
+                uint8_t *subjectId = NULL;
+                cborFindResult = cbor_value_dup_byte_string(&svcMap, &subjectId, &len, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Find SubjectId.");
+                memcpy(svc->svcdid.id, subjectId, len);
+                OICFree(subjectId);
             }
-
-            cJSON *jsonObj = NULL;
-
-            unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
-            uint32_t outLen = 0;
-            B64Result b64Ret = B64_OK;
-
-            // Service Device Identity
-            jsonObj = cJSON_GetObjectItem(jsonSvc, OIC_JSON_SERVICE_DEVICE_ID);
-            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-            VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
-            outLen = 0;
-            b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
-                        sizeof(base64Buff), &outLen);
-            VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(svc->svcdid.id)), ERROR);
-            memcpy(svc->svcdid.id, base64Buff, outLen);
-
             // Service Type
-            jsonObj = cJSON_GetObjectItem(jsonSvc, OIC_JSON_SERVICE_TYPE);
-            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-            VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
-            svc->svct = (OicSecSvcType_t)jsonObj->valueint;
-
-            // Resource Owners
-            jsonObj = cJSON_GetObjectItem(jsonSvc, OIC_JSON_OWNERS_NAME);
-            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
-
-            svc->ownersLen = cJSON_GetArraySize(jsonObj);
-            VERIFY_SUCCESS(TAG, svc->ownersLen > 0, ERROR);
-            svc->owners = (OicUuid_t*)OICCalloc(svc->ownersLen, sizeof(OicUuid_t));
-            VERIFY_NON_NULL(TAG, (svc->owners), ERROR);
-
-            size_t idxx = 0;
-            do
+            if (0 == strcmp(OIC_JSON_SERVICE_TYPE, name))
             {
-                cJSON *jsonOwnr = cJSON_GetArrayItem(jsonObj, idxx);
-                VERIFY_NON_NULL(TAG, jsonOwnr, ERROR);
-                VERIFY_SUCCESS(TAG, cJSON_String == jsonOwnr->type, ERROR);
-
-                outLen = 0;
-                b64Ret = b64Decode(jsonOwnr->valuestring, strlen(jsonOwnr->valuestring), base64Buff,
-                            sizeof(base64Buff), &outLen);
+                cborFindResult = cbor_value_get_int(&svcMap, (int *) &svc->svct);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Find SVCT.");
+            }
 
-                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(svc->owners[idxx].id)),
-                                    ERROR);
-                memcpy(svc->owners[idxx].id, base64Buff, outLen);
-            } while ( ++idxx < svc->ownersLen);
+            // Owners -- Mandatory
+            if (0 == strcmp(OIC_JSON_OWNERS_NAME, name))
+            {
+                int i = 0;
+                CborValue owners = { .parser = NULL };
+
+                cborFindResult = cbor_value_get_array_length(&svcMap, &svc->ownersLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Find Owner Len.");
+                cborFindResult = cbor_value_enter_container(&svcMap, &owners);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Enter Owner Array.");
+                svc->owners = (OicUuid_t *)OICCalloc(svc->ownersLen, sizeof(*svc->owners));
+                VERIFY_NON_NULL(TAG, svc->owners, ERROR);
+
+                while (cbor_value_is_valid(&owners))
+                {
+                    uint8_t *owner = NULL;
+                    cborFindResult = cbor_value_dup_byte_string(&owners, &owner, &len, NULL);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Find Owner Array Value.");
+                    cborFindResult = cbor_value_advance(&owners);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Advance Owner Array.");
+                    memcpy(svc->owners[i++].id, owner, len);
+                    OICFree(owner);
+                }
+            }
+            if (CborMapType != type  && cbor_value_is_valid(&svcMap))
+            {
+                cborFindResult = cbor_value_advance(&svcMap);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Advance SVC.");
+            }
+            OICFree(name);
+        }
 
-            prevSvc = svc;
-        } while( ++idx < numSvc);
+        svc->next = NULL;
+        if (NULL == headSvc)
+        {
+            headSvc = svc;
+        }
+        else
+        {
+            OicSecSvc_t *temp = headSvc;
+            while (temp->next)
+            {
+                temp = temp->next;
+            }
+            temp->next = svc;
+        }
+        if (cbor_value_is_valid(&svcArray))
+        {
+            cborFindResult = cbor_value_advance(&svcArray);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Find Name.");
+        }
     }
-
+    *secSvc = headSvc;
     ret = OC_STACK_OK;
 
 exit:
-    cJSON_Delete(jsonRoot);
-    if (OC_STACK_OK != ret)
+    if (CborNoError != cborFindResult)
     {
         DeleteSVCList(headSvc);
         headSvc = NULL;
+        *secSvc = NULL;
+        ret = OC_STACK_ERROR;
     }
-    return headSvc;
+    return ret;
 }
 
-static OCEntityHandlerResult HandleSVCGetRequest (const OCEntityHandlerRequest * ehRequest)
+static OCEntityHandlerResult HandleSVCGetRequest(const OCEntityHandlerRequest * ehRequest)
 {
     // Convert SVC data into JSON for transmission
-    char* jsonStr = BinToSvcJSON(gSvc);
-
-    OCEntityHandlerResult ehRet = (jsonStr ? OC_EH_OK : OC_EH_ERROR);
+    size_t size = 0;
+    uint8_t *cborSvc = NULL;
+    OCStackResult res =  SVCToCBORPayload(gSvc, &cborSvc, &size);
+    OCEntityHandlerResult ehRet = (res == OC_STACK_OK) ? OC_EH_OK : OC_EH_ERROR;
 
     // Send response payload to request originator
-    SendSRMResponse(ehRequest, ehRet, jsonStr);
-
-    OICFree(jsonStr);
+    if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, cborSvc, size))
+    {
+        ehRet = OC_EH_ERROR;
+        OIC_LOG(ERROR, TAG, "SendSRMResponse failed in HandleSVCGetRequest");
+    }
 
-    OC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
+    OICFree(cborSvc);
+    OIC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
     return ehRet;
 }
 
-static OCEntityHandlerResult HandleSVCPostRequest (const OCEntityHandlerRequest * ehRequest)
+static OCEntityHandlerResult HandleSVCPostRequest(const OCEntityHandlerRequest * ehRequest)
 {
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
-
-    // Convert JSON SVC data into binary. This will also validate the SVC data received.
-    OicSecSvc_t* newSvc = JSONToSvcBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
-
-    if (newSvc)
+    uint8_t *payload = ((OCSecurityPayload *) ehRequest->payload)->securityData;
+    size_t size = ((OCSecurityPayload *) ehRequest->payload)->payloadSize;
+    if (payload)
     {
-        // Append the new SVC to existing SVC
-        LL_APPEND(gSvc, newSvc);
-
-        // Convert SVC data into JSON for update to persistent storage
-        char *jsonStr = BinToSvcJSON(gSvc);
-        if (jsonStr)
+        // Convert CBOR SVC data into SVC. This will also validate the SVC data received.
+        OicSecSvc_t *newSvc = NULL;
+        OCStackResult res =  CBORPayloadToSVC(payload, size, &newSvc);
+        if (newSvc && res == OC_STACK_OK)
         {
-            cJSON *jsonSvc = cJSON_Parse(jsonStr);
-            OICFree(jsonStr);
-
-            if ((jsonSvc) &&
-                (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_SVC_NAME, jsonSvc)))
+            // Append the new SVC to existing SVC
+            LL_APPEND(gSvc, newSvc);
+
+            // Convert SVC data into JSON for update to persistent storage
+            size_t size = 0;
+            uint8_t *cborPayload = NULL;
+            res = SVCToCBORPayload(gSvc, &cborPayload, &size);
+            if (cborPayload && OC_STACK_OK == res &&
+                UpdateSecureResourceInPS(OIC_JSON_SVC_NAME, cborPayload, size) == OC_STACK_OK)
             {
                 ehRet = OC_EH_RESOURCE_CREATED;
             }
-            cJSON_Delete(jsonSvc);
+            OICFree(cborPayload);
         }
     }
 
     // Send payload to request originator
-    SendSRMResponse(ehRequest, ehRet, NULL);
+    if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL, 0))
+    {
+        ehRet = OC_EH_ERROR;
+        OIC_LOG(ERROR, TAG, "SendSRMResponse failed in HandleSVCPostRequest");
+    }
 
-    OC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
+    OIC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
     return ehRet;
 }
 
-/*
+/**
  * This internal method is the entity handler for SVC resources and
  * will handle REST request (GET/PUT/POST/DEL) for them.
  */
-OCEntityHandlerResult SVCEntityHandler (OCEntityHandlerFlag flag,
-                                        OCEntityHandlerRequest * ehRequest,
-                                        void* callbackParameter)
+static OCEntityHandlerResult SVCEntityHandler(OCEntityHandlerFlag flag,
+                                              OCEntityHandlerRequest * ehRequest,
+                                              void* callbackParameter)
 {
     (void) callbackParameter;
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
@@ -308,51 +400,58 @@ OCEntityHandlerResult SVCEntityHandler (OCEntityHandlerFlag flag,
 
             default:
                 ehRet = OC_EH_ERROR;
-                SendSRMResponse(ehRequest, ehRet, NULL);
+                SendSRMResponse(ehRequest, ehRet, NULL, 0);
         }
     }
 
     return ehRet;
 }
 
-/*
+/**
  * This internal method is used to create '/oic/sec/svc' resource.
  */
-OCStackResult CreateSVCResource()
+static OCStackResult CreateSVCResource()
 {
-    OCStackResult ret;
-
-    ret = OCCreateResource(&gSvcHandle,
-                           OIC_RSRC_TYPE_SEC_SVC,
-                           OIC_MI_DEF,
-                           OIC_RSRC_SVC_URI,
-                           SVCEntityHandler,
-                           NULL,
-                           OC_OBSERVABLE);
+    OCStackResult ret = OCCreateResource(&gSvcHandle,
+                                         OIC_RSRC_TYPE_SEC_SVC,
+                                         OIC_MI_DEF,
+                                         OIC_RSRC_SVC_URI,
+                                         SVCEntityHandler,
+                                         NULL,
+                                         OC_OBSERVABLE);
 
     if (OC_STACK_OK != ret)
     {
-        OC_LOG (FATAL, TAG, "Unable to instantiate SVC resource");
+        OIC_LOG(FATAL, TAG, "Unable to instantiate SVC resource");
         DeInitSVCResource();
     }
     return ret;
 }
 
-
 OCStackResult InitSVCResource()
 {
     OCStackResult ret = OC_STACK_ERROR;
 
-    OC_LOG_V (DEBUG, TAG, "Begin %s ", __func__ );
+    OIC_LOG_V(DEBUG, TAG, "Begin %s ", __func__ );
 
-    // Read SVC resource from PS
-    char* jsonSVRDatabase = GetSVRDatabase();
+    uint8_t *data = NULL;
+    size_t size = 0;
+    ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_SVC_NAME, &data, &size);
+    // If database read failed
+    if (ret != OC_STACK_OK)
+    {
+        OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
+    }
 
-    if (jsonSVRDatabase)
+    if (data)
     {
-        // Convert JSON SVC into binary format
-        gSvc = JSONToSvcBin(jsonSVRDatabase);
-        OICFree(jsonSVRDatabase);
+        // Convert CBOR SVC into binary format
+        ret = CBORPayloadToSVC(data, size, &gSvc);
+        if (ret != OC_STACK_OK)
+        {
+            OIC_LOG (DEBUG, TAG, " ConvertCBOR SVC into binary format failed");
+        }
+        OICFree(data);
     }
 
     // Instantiate 'oic.sec.svc'
@@ -363,15 +462,10 @@ OCStackResult InitSVCResource()
         DeInitSVCResource();
     }
 
-    OC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ret);
+    OIC_LOG_V(DEBUG, TAG, "%s RetVal %d", __func__ , ret);
     return ret;
 }
 
-/**
- * Perform cleanup for SVC resources.
- *
- * @retval  none
- */
 void DeInitSVCResource()
 {
     OCDeleteResource(gSvcHandle);
@@ -380,4 +474,3 @@ void DeInitSVCResource()
     DeleteSVCList(gSvc);
     gSvc = NULL;
 }
-
diff --git a/resource/csdk/security/src/verresource.c b/resource/csdk/security/src/verresource.c
new file mode 100644 (file)
index 0000000..0bd3f75
--- /dev/null
@@ -0,0 +1,354 @@
+/* *****************************************************************
+ *
+ * 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 <stdlib.h>
+#include <string.h>
+
+#if HAVE_STRINGS_H
+#include <strings.h>
+#endif
+
+#include "ocstack.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+#include "logger.h"
+#include "payload_logging.h"
+#include "ocpayload.h"
+#include "cainterface.h"
+#include "ocserverrequest.h"
+#include "resourcemanager.h"
+#include "verresource.h"
+#include "doxmresource.h"
+#include "psinterface.h"
+#include "srmresourcestrings.h"
+#include "securevirtualresourcetypes.h"
+#include "srmutility.h"
+
+#define TAG  "SEC-VER"
+
+/** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
+ * The value of payload size is increased until reaching belox max cbor size. */
+static const uint8_t CBOR_SIZE = 255;
+
+/** Max cbor size payload. */
+static const uint16_t CBOR_MAX_SIZE = 4400;
+
+/** VER Map size - Number of mandatory items. */
+static const uint8_t VER_MAP_SIZE = 2;
+
+static OCResourceHandle    gVerHandle = NULL;
+
+/** Security version is mapped with iotivity release version */
+const char* SECURITY_VERSION = IOTIVITY_VERSION;
+
+static OicSecVer_t gVer =
+{
+    {0},                  /* char *secv */
+    {.id = {0}},         /* OicUuid_t deviceID */
+};
+
+void DeleteVerBinData(OicSecVer_t* ver)
+{
+    if (ver)
+    {
+        //Clean ver itself
+        OICFree(ver);
+    }
+}
+
+OCStackResult VerToCBORPayload(const OicSecVer_t *ver, uint8_t **payload, size_t *size)
+{
+    if (NULL == ver || NULL == payload || NULL != *payload || NULL == size)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+    size_t cborLen = *size;
+    if (0 == cborLen)
+    {
+        cborLen = CBOR_SIZE;
+    }
+    *payload = NULL;
+    *size = 0;
+
+    OCStackResult ret = OC_STACK_ERROR;
+
+    CborEncoder encoder;
+    CborEncoder verMap;
+
+    int64_t cborEncoderResult = CborNoError;
+    uint8_t mapSize = VER_MAP_SIZE;
+    char* strUuid = NULL;
+
+    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
+    VERIFY_NON_NULL(TAG, outPayload, ERROR);
+    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
+
+    cborEncoderResult |= cbor_encoder_create_map(&encoder, &verMap, mapSize);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Ver Map.");
+
+    //SecV -- Mandatory
+    cborEncoderResult |= cbor_encode_text_string(&verMap, OIC_JSON_SEC_V_NAME,
+        strlen(OIC_JSON_SEC_V_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SecV Tag.");
+    cborEncoderResult |= cbor_encode_text_string(&verMap, ver->secv, strlen(ver->secv));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SecV Value.");
+
+    //DeviceId -- Mandatory
+    cborEncoderResult = cbor_encode_text_string(&verMap, OIC_JSON_DEVICE_ID_NAME,
+        strlen(OIC_JSON_DEVICE_ID_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag.");
+    ret = ConvertUuidToStr(&ver->deviceID, &strUuid);
+    VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
+    cborEncoderResult = cbor_encode_text_string(&verMap, strUuid, strlen(strUuid));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value.");
+    OICFree(strUuid);
+    strUuid = NULL;
+
+
+    // Close ver(first) container
+    cborEncoderResult |= cbor_encoder_close_container(&encoder, &verMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing VerMap.");
+
+    if (CborNoError == cborEncoderResult)
+    {
+        *size = encoder.ptr - outPayload;
+        *payload = outPayload;
+        ret = OC_STACK_OK;
+    }
+exit:
+    if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
+    {
+        OIC_LOG(DEBUG, TAG, "Memory getting reallocated.");
+        // reallocate and try again!
+        OICFree(outPayload);
+        // Since the allocated initial memory failed, double the memory.
+        cborLen += encoder.ptr - encoder.end;
+        OIC_LOG_V(DEBUG, TAG, "Ver reallocation size : %zd.", cborLen);
+        cborEncoderResult = CborNoError;
+        ret = VerToCBORPayload(ver, payload, &cborLen);
+        *size = cborLen;
+    }
+
+    if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
+    {
+       OICFree(outPayload);
+       outPayload = NULL;
+       *payload = NULL;
+       *size = 0;
+       ret = OC_STACK_ERROR;
+    }
+
+    return ret;
+}
+
+OCStackResult CBORPayloadToVer(const uint8_t *cborPayload, size_t size,
+                                OicSecVer_t **secVer)
+{
+    if (NULL == cborPayload || NULL == secVer || NULL != *secVer || 0 == size)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCStackResult ret = OC_STACK_ERROR;
+    *secVer = NULL;
+    char *strUuid = NULL;
+
+    CborParser parser = { .end = NULL};
+    CborError cborFindResult = CborNoError;
+    size_t len = 0;
+    CborValue verCbor = { .parser = NULL };
+    cbor_parser_init(cborPayload, size, 0, &parser, &verCbor);
+    CborValue verMap = { .parser = NULL };
+    OicSecVer_t *ver = (OicSecVer_t *)OICCalloc(1, sizeof(OicSecVer_t));
+    VERIFY_NON_NULL(TAG, ver, ERROR);
+
+
+    cborFindResult = cbor_value_map_find_value(&verCbor, OIC_JSON_SEC_V_NAME, &verMap);
+    if (CborNoError == cborFindResult && cbor_value_is_text_string(&verMap))
+    {
+        char *version = NULL;
+        cborFindResult = cbor_value_dup_text_string(&verMap, &version, &len, NULL);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Security Version Value.");
+        memcpy(ver->secv, version, len);
+        OICFree(version);
+    }
+
+    cborFindResult = cbor_value_map_find_value(&verCbor, OIC_JSON_DEVICE_ID_NAME, &verMap);
+    if (CborNoError == cborFindResult && cbor_value_is_text_string(&verMap))
+    {
+        cborFindResult = cbor_value_dup_text_string(&verMap, &strUuid , &len, NULL);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Device Id Value.");
+        ret = ConvertStrToUuid(strUuid , &ver->deviceID);
+        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+        OICFree(strUuid );
+        strUuid  = NULL;
+    }
+
+    *secVer = ver;
+    ret = OC_STACK_OK;
+
+exit:
+    if (CborNoError != cborFindResult)
+    {
+        OIC_LOG (ERROR, TAG, "CBORPayloadToVer failed!!!");
+        DeleteVerBinData(ver);
+        ret = OC_STACK_ERROR;
+    }
+    return ret;
+}
+
+static OCEntityHandlerResult HandleVerGetRequest (const OCEntityHandlerRequest * ehRequest)
+{
+    OCEntityHandlerResult ehRet = OC_EH_OK;
+
+    OIC_LOG(DEBUG, TAG, "Ver EntityHandle processing GET request");
+
+    /*
+     * For GET request return ver resource CBOR payload.
+     * For non-valid query return NULL json payload.
+     * The version is static built-in information, so VerToCBORPayload will
+     * return valid ver resource json.
+     */
+    uint8_t *payload = NULL;
+    size_t size = 0;
+    if (OC_STACK_OK != VerToCBORPayload(&gVer, &payload, &size))
+    {
+        payload = NULL;
+    }
+
+    // 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 HandleVerGetRequest");
+    }
+
+    OICFree(payload);
+
+    return ehRet;
+}
+
+OCEntityHandlerResult VerEntityHandler(OCEntityHandlerFlag flag,
+                                        OCEntityHandlerRequest * ehRequest,
+                                        void* callbackParam)
+{
+    (void)callbackParam;
+    OCEntityHandlerResult ehRet = OC_EH_ERROR;
+
+    if(NULL == ehRequest)
+    {
+        return ehRet;
+    }
+
+    if (flag & OC_REQUEST_FLAG)
+    {
+        OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
+
+        switch (ehRequest->method)
+        {
+            case OC_REST_GET:
+                ehRet = HandleVerGetRequest(ehRequest);
+                break;
+
+            default:
+                ehRet = OC_EH_ERROR;
+                SendSRMResponse(ehRequest, ehRet, NULL, 0);
+                break;
+        }
+    }
+
+    return ehRet;
+}
+
+OCStackResult CreateVerResource()
+{
+    OCStackResult ret = OCCreateResource(&gVerHandle,
+                                         OIC_RSRC_TYPE_SEC_VER,
+                                         OIC_MI_DEF,
+                                         OIC_RSRC_VER_URI,
+                                         VerEntityHandler,
+                                         NULL,
+                                         OC_SECURE);
+
+    if (OC_STACK_OK != ret)
+    {
+        OIC_LOG (FATAL, TAG, "Unable to instantiate Ver resource");
+        DeInitVerResource();
+    }
+    return ret;
+}
+
+/**
+ * Get the security version.
+ *
+ * @return the version string of security.
+ */
+const char* GetSecVersion()
+{
+    OIC_LOG(DEBUG, TAG, "GetSecVersion");
+    return gVer.secv;
+}
+
+const OicSecVer_t* GetVerResourceData()
+{
+    return &gVer;
+}
+
+OCStackResult InitVerResource()
+{
+    OCStackResult ret = OC_STACK_ERROR;
+
+    OICStrcpy(gVer.secv, MAX_VERSION_LEN, SECURITY_VERSION);
+
+    //Read device id from doxm
+    OicUuid_t deviceID = {.id={0}};
+    ret = GetDoxmDeviceID(&deviceID);
+    if (OC_STACK_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "Error while retrieving doxm device ID");
+        return ret;
+    }
+    memcpy(&gVer.deviceID, &deviceID, sizeof(OicUuid_t));
+
+    //Instantiate 'oic.sec.ver'
+    ret = CreateVerResource();
+    if (OC_STACK_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "Error while creating VER resource");
+    }
+
+    return ret;
+}
+
+OCStackResult DeInitVerResource()
+{
+    OCStackResult ret = OCDeleteResource(gVerHandle);
+
+    memset(&gVer, 0, sizeof(gVer));
+
+    if (OC_STACK_OK == ret)
+    {
+        return OC_STACK_OK;
+    }
+    else
+    {
+        return OC_STACK_ERROR;
+    }
+}
diff --git a/resource/csdk/security/tool/SConscript b/resource/csdk/security/tool/SConscript
new file mode 100644 (file)
index 0000000..9bb9569
--- /dev/null
@@ -0,0 +1,50 @@
+# //******************************************************************
+# //
+# // 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.
+# //
+# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+Import('env')
+
+tools_env = env.Clone()
+src_dir = tools_env.get('SRC_DIR')
+
+######################################################################
+# Build flags
+######################################################################
+tools_env.PrependUnique(CPPPATH = ['../../../../extlibs/cjson',
+                                  '../../stack/include',
+                                  '../../stack/include/internal',
+                                  '../../logger/include',
+                                  '../../../oc_logger/include',
+                                  '../../connectivity/api',
+                                  '../include',
+                                  '../include/internal',
+                                  '../../connectivity/lib/libcoap-4.1.1',
+
+                                  ])
+tools_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-Wextra', '-std=c++0x'])
+tools_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+tools_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
+tools_env.PrependUnique(LIBS = ['oc', 'octbstack'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+json2cbor = tools_env.Program('json2cbor', ['json2cbor.c'])
+Alias("json2cbor", [json2cbor])
+env.AppendTarget('json2cbor')
diff --git a/resource/csdk/security/tool/json2cbor.c b/resource/csdk/security/tool/json2cbor.c
new file mode 100644 (file)
index 0000000..09191cb
--- /dev/null
@@ -0,0 +1,1042 @@
+//******************************************************************
+//
+// 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 <stdlib.h>
+#include <string.h>
+#include "cJSON.h"
+#include "base64.h"
+#include "cainterface.h"
+#include "ocstack.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+#include "ocpayload.h"
+#include "ocpayloadcbor.h"
+#include "payload_logging.h"
+#include "secureresourcemanager.h"
+#include "srmresourcestrings.h"
+#include "srmutility.h"
+#include "aclresource.h"
+#include "pstatresource.h"
+#include "doxmresource.h"
+#include "amaclresource.h"
+#include "credresource.h"
+#include "svcresource.h"
+#include "security_internals.h"
+
+#define TAG  "JSON2CBOR"
+#define MAX_RANGE   ((size_t)-1)
+//SVR database buffer block size
+static const size_t DB_FILE_SIZE_BLOCK = 1023;
+
+static OicSecPstat_t* JSONToPstatBin(const char * jsonStr);
+static OicSecDoxm_t* JSONToDoxmBin(const char * jsonStr);
+static OicSecAcl_t *JSONToAclBin(const char * jsonStr);
+static OicSecSvc_t* JSONToSvcBin(const char * jsonStr);
+static OicSecAmacl_t* JSONToAmaclBin(const char * jsonStr);
+static OicSecCred_t* JSONToCredBin(const char * jsonStr);
+
+static size_t GetJSONFileSize(const char *jsonFileName)
+{
+    size_t size = 0;
+    size_t bytesRead  = 0;
+    char buffer[DB_FILE_SIZE_BLOCK];
+    FILE* fp = fopen(jsonFileName, "r");
+    if (fp)
+    {
+        do
+        {
+            bytesRead = fread(buffer, 1, DB_FILE_SIZE_BLOCK, fp);
+            if (bytesRead >=(MAX_RANGE - size))
+            {
+                fclose(fp);
+                return 0;
+            }
+            size += bytesRead;
+        } while (bytesRead > 0);
+        fclose(fp);
+    }
+    return size;
+}
+
+static void ConvertJsonToCBOR(const char *jsonFileName, const char *cborFileName)
+{
+    char *jsonStr = NULL;
+    FILE *fp = NULL;
+    FILE *fp1 = NULL;
+    uint8_t *aclCbor = NULL;
+    uint8_t *pstatCbor = NULL;
+    uint8_t *doxmCbor = NULL;
+    uint8_t *amaclCbor = NULL;
+    uint8_t *svcCbor = NULL;
+    uint8_t *credCbor = NULL;
+    cJSON *jsonRoot = NULL;
+    OCStackResult ret = OC_STACK_ERROR;
+    size_t size = GetJSONFileSize(jsonFileName);
+    if (0 == size)
+    {
+        OIC_LOG (ERROR, TAG, "Failed converting to JSON");
+        return;
+    }
+
+    jsonStr = (char *)OICMalloc(size + 1);
+    VERIFY_NON_NULL(TAG, jsonStr, FATAL);
+
+    fp = fopen(jsonFileName, "r");
+    if (fp)
+    {
+        size_t bytesRead = fread(jsonStr, 1, size, fp);
+        jsonStr[bytesRead] = '\0';
+
+        OIC_LOG_V(DEBUG, TAG, "Read %zu bytes", bytesRead);
+        fclose(fp);
+        fp = NULL;
+    }
+    else
+    {
+        OIC_LOG (ERROR, TAG, "Unable to open JSON file!!");
+        goto exit;
+    }
+
+    jsonRoot = cJSON_Parse(jsonStr);
+
+    cJSON *value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_ACL_NAME);
+    //printf("ACL json : \n%s\n", cJSON_PrintUnformatted(value));
+    size_t aclCborSize = 0;
+    if (NULL != value)
+    {
+        OicSecAcl_t *acl = JSONToAclBin(jsonStr);
+        VERIFY_NON_NULL(TAG, acl, FATAL);
+        ret = AclToCBORPayload(acl, &aclCbor, &aclCborSize);
+        if(OC_STACK_OK != ret)
+        {
+            OIC_LOG (ERROR, TAG, "Failed converting Acl to Cbor Payload");
+            DeleteACLList(acl);
+            goto exit;
+        }
+        printf("ACL Cbor Size: %zd\n", aclCborSize);
+        DeleteACLList(acl);
+    }
+
+    value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_PSTAT_NAME);
+    size_t pstatCborSize = 0;
+    if (NULL != value)
+    {
+        OicSecPstat_t *pstat = JSONToPstatBin(jsonStr);
+        VERIFY_NON_NULL(TAG, pstat, FATAL);
+        ret = PstatToCBORPayload(pstat, &pstatCbor, &pstatCborSize);
+        if(OC_STACK_OK != ret)
+        {
+            OIC_LOG (ERROR, TAG, "Failed converting Pstat to Cbor Payload");
+            DeletePstatBinData(pstat);
+            goto exit;
+        }
+        printf("PSTAT Cbor Size: %zd\n", pstatCborSize);
+        DeletePstatBinData(pstat);
+    }
+    value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_DOXM_NAME);
+    size_t doxmCborSize = 0;
+    if (NULL != value)
+    {
+        OicSecDoxm_t *doxm = JSONToDoxmBin(jsonStr);
+        VERIFY_NON_NULL(TAG, doxm, FATAL);
+        ret = DoxmToCBORPayload(doxm, &doxmCbor, &doxmCborSize);
+        if(OC_STACK_OK != ret)
+        {
+            OIC_LOG (ERROR, TAG, "Failed converting Doxm to Cbor Payload");
+            DeleteDoxmBinData(doxm);
+            goto exit;
+        }
+        printf("DOXM Cbor Size: %zd\n", doxmCborSize);
+        DeleteDoxmBinData(doxm);
+    }
+    value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_AMACL_NAME);
+    size_t amaclCborSize = 0;
+    if (NULL != value)
+    {
+        OicSecAmacl_t *amacl = JSONToAmaclBin(jsonStr);
+        VERIFY_NON_NULL(TAG, amacl, FATAL);
+        ret = AmaclToCBORPayload(amacl, &amaclCbor, &amaclCborSize);
+        if(OC_STACK_OK != ret)
+        {
+            OIC_LOG (ERROR, TAG, "Failed converting Amacl to Cbor Payload");
+            DeleteAmaclList(amacl);
+            goto exit;
+        }
+        printf("AMACL Cbor Size: %zd\n", amaclCborSize);
+        DeleteAmaclList(amacl);
+    }
+    value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_SVC_NAME);
+    size_t svcCborSize = 0;
+    if (NULL != value)
+    {
+        OicSecSvc_t *svc = JSONToSvcBin(jsonStr);
+        VERIFY_NON_NULL(TAG, svc, FATAL);
+        ret = SVCToCBORPayload(svc, &svcCbor, &svcCborSize);
+        if(OC_STACK_OK != ret)
+        {
+            OIC_LOG (ERROR, TAG, "Failed converting Svc to Cbor Payload");
+            DeleteSVCList(svc);
+            goto exit;
+        }
+        printf("SVC Cbor Size: %zd\n", svcCborSize);
+        DeleteSVCList(svc);
+    }
+    value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_CRED_NAME);
+    //printf("CRED json : \n%s\n", cJSON_PrintUnformatted(value));
+    size_t credCborSize = 0;
+    if (NULL != value)
+    {
+        OicSecCred_t *cred = JSONToCredBin(jsonStr);
+        VERIFY_NON_NULL(TAG, cred, FATAL);
+        ret = CredToCBORPayload(cred, &credCbor, &credCborSize);
+        if(OC_STACK_OK != ret)
+        {
+            OIC_LOG (ERROR, TAG, "Failed converting Cred to Cbor Payload");
+            DeleteCredList(cred);
+            goto exit;
+        }
+        printf("CRED Cbor Size: %zd\n", credCborSize);
+        DeleteCredList(cred);
+    }
+
+    CborEncoder encoder;
+    size_t cborSize = aclCborSize + pstatCborSize + doxmCborSize + svcCborSize + credCborSize + amaclCborSize;
+
+    printf("Total Cbor Size : %zd\n", cborSize);
+    cborSize += 255; // buffer margin for adding map and byte string
+    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborSize);
+    VERIFY_NON_NULL(TAG, outPayload, ERROR);
+    cbor_encoder_init(&encoder, outPayload, cborSize, 0);
+    CborEncoder map;
+    CborError cborEncoderResult = cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Creating Main Map.");
+    if (aclCborSize > 0)
+    {
+        cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_ACL_NAME, strlen(OIC_JSON_ACL_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ACL Name.");
+        cborEncoderResult = cbor_encode_byte_string(&map, aclCbor, aclCborSize);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ACL Value.");
+    }
+
+    if (pstatCborSize > 0)
+    {
+        cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_PSTAT_NAME, strlen(OIC_JSON_PSTAT_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PSTAT Name.");
+        cborEncoderResult = cbor_encode_byte_string(&map, pstatCbor, pstatCborSize);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PSTAT Value.");
+    }
+    if (doxmCborSize > 0)
+    {
+        cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_DOXM_NAME, strlen(OIC_JSON_DOXM_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DOXM Name.");
+        cborEncoderResult = cbor_encode_byte_string(&map, doxmCbor, doxmCborSize);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DOXM Value.");
+    }
+    if (amaclCborSize > 0)
+    {
+        cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_AMACL_NAME, strlen(OIC_JSON_AMACL_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding AMACL Name.");
+        cborEncoderResult = cbor_encode_byte_string(&map, amaclCbor, amaclCborSize);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding AMACL Value.");
+    }
+    if (svcCborSize > 0)
+    {
+        cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_SVC_NAME, strlen(OIC_JSON_SVC_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SVC Name.");
+        cborEncoderResult = cbor_encode_byte_string(&map, svcCbor, svcCborSize);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SVC Value.");
+    }
+    if (credCborSize > 0)
+    {
+        cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_CRED_NAME, strlen(OIC_JSON_CRED_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding CRED Name.");
+        cborEncoderResult = cbor_encode_byte_string(&map, credCbor, credCborSize);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding CRED Value.");
+    }
+
+    cborEncoderResult = cbor_encoder_close_container(&encoder, &map);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Container.");
+
+    size_t s = encoder.ptr - outPayload;
+    OIC_LOG_V(DEBUG, TAG, "Payload size %zu", s);
+
+    fp1 = fopen(cborFileName, "w");
+    if (fp1)
+    {
+        size_t bytesWritten = fwrite(outPayload, 1, s, fp1);
+        if (bytesWritten == s)
+        {
+            OIC_LOG_V(DEBUG, TAG, "Written %zu bytes", bytesWritten);
+        }
+        else
+        {
+            OIC_LOG_V(ERROR, TAG, "Failed writing %zu bytes", s);
+        }
+        fclose(fp1);
+        fp1 = NULL;
+    }
+exit:
+
+    cJSON_Delete(jsonRoot);
+    OICFree(aclCbor);
+    OICFree(doxmCbor);
+    OICFree(pstatCbor);
+    OICFree(amaclCbor);
+    OICFree(svcCbor);
+    OICFree(credCbor);
+    OICFree(jsonStr);
+    return ;
+}
+
+OicSecAcl_t* JSONToAclBin(const char * jsonStr)
+{
+    OCStackResult ret = OC_STACK_ERROR;
+    OicSecAcl_t * headAcl = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t));
+    cJSON *jsonRoot = NULL;
+
+    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
+
+    jsonRoot = cJSON_Parse(jsonStr);
+    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+
+    cJSON *jsonAclMap = cJSON_GetObjectItem(jsonRoot, OIC_JSON_ACL_NAME);
+    VERIFY_NON_NULL(TAG, jsonAclMap, ERROR);
+
+    cJSON *jsonAclObj = NULL;
+
+    // aclist
+    jsonAclObj = cJSON_GetObjectItem(jsonAclMap, OIC_JSON_ACLIST_NAME);
+    VERIFY_NON_NULL(TAG, jsonAclObj, ERROR);
+
+    // aclist-aces
+    cJSON *jsonAclArray = NULL;
+    jsonAclArray = cJSON_GetObjectItem(jsonAclObj, OIC_JSON_ACES_NAME);
+    VERIFY_NON_NULL(TAG, jsonAclArray, ERROR);
+
+    if (cJSON_Array == jsonAclArray->type)
+    {
+
+        int numAcl = cJSON_GetArraySize(jsonAclArray);
+        int idx = 0;
+
+        VERIFY_SUCCESS(TAG, numAcl > 0, INFO);
+        do
+        {
+            cJSON *jsonAcl = cJSON_GetArrayItem(jsonAclArray, idx);
+            VERIFY_NON_NULL(TAG, jsonAcl, ERROR);
+
+            OicSecAcl_t *acl = NULL;
+            if(idx == 0)
+            {
+                acl = headAcl;
+            }
+            else
+            {
+                acl = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t));
+                OicSecAcl_t *temp = headAcl;
+                while (temp->next)
+                {
+                    temp = temp->next;
+                }
+                temp->next = acl;
+            }
+
+            VERIFY_NON_NULL(TAG, acl, ERROR);
+
+            size_t jsonObjLen = 0;
+            cJSON *jsonObj = NULL;
+            jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_SUBJECTID_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
+            if(strcmp(jsonObj->valuestring, WILDCARD_RESOURCE_URI) == 0)
+            {
+                acl->subject.id[0] = '*';
+            }
+            else
+            {
+                ret = ConvertStrToUuid(jsonObj->valuestring, &acl->subject);
+                VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+            }
+            // Resources -- Mandatory
+            jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_RESOURCES_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
+
+            acl->resourcesLen = (size_t)cJSON_GetArraySize(jsonObj);
+
+            VERIFY_SUCCESS(TAG, acl->resourcesLen > 0, ERROR);
+            acl->resources = (char**)OICCalloc(acl->resourcesLen, sizeof(char*));
+            VERIFY_NON_NULL(TAG, (acl->resources), ERROR);
+
+            size_t idxx = 0;
+            do
+            {
+                cJSON *jsonRsrc = cJSON_GetArrayItem(jsonObj, idxx);
+                VERIFY_NON_NULL(TAG, jsonRsrc, ERROR);
+
+                size_t jsonRsrcObjLen = 0;
+                cJSON *jsonRsrcObj = cJSON_GetObjectItem(jsonRsrc, OIC_JSON_HREF_NAME);
+                VERIFY_NON_NULL(TAG, jsonRsrcObj, ERROR);
+                VERIFY_SUCCESS(TAG, cJSON_String == jsonRsrcObj->type, ERROR);
+
+                jsonRsrcObjLen = strlen(jsonRsrcObj->valuestring) + 1;
+                acl->resources[idxx] = (char*)OICMalloc(jsonRsrcObjLen);
+
+                VERIFY_NON_NULL(TAG, (acl->resources[idxx]), ERROR);
+                OICStrcpy(acl->resources[idxx], jsonRsrcObjLen, jsonRsrcObj->valuestring);
+
+            } while ( ++idxx < acl->resourcesLen);
+
+            // Permissions -- Mandatory
+            jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_PERMISSION_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+            acl->permission = jsonObj->valueint;
+            //Period -- Not Mandatory
+            cJSON *jsonPeriodObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_PERIOD_NAME);
+            if(jsonPeriodObj)
+            {
+                VERIFY_SUCCESS(TAG, cJSON_Array == jsonPeriodObj->type, ERROR);
+                acl->prdRecrLen = (size_t)cJSON_GetArraySize(jsonPeriodObj);
+                if(acl->prdRecrLen > 0)
+                {
+                    acl->periods = (char**)OICCalloc(acl->prdRecrLen, sizeof(char*));
+                    VERIFY_NON_NULL(TAG, acl->periods, ERROR);
+
+                    cJSON *jsonPeriod = NULL;
+                    for(size_t i = 0; i < acl->prdRecrLen; i++)
+                    {
+                        jsonPeriod = cJSON_GetArrayItem(jsonPeriodObj, i);
+                        VERIFY_NON_NULL(TAG, jsonPeriod, ERROR);
+
+                        jsonObjLen = strlen(jsonPeriod->valuestring) + 1;
+                        acl->periods[i] = (char*)OICMalloc(jsonObjLen);
+                        VERIFY_NON_NULL(TAG, acl->periods[i], ERROR);
+                        OICStrcpy(acl->periods[i], jsonObjLen, jsonPeriod->valuestring);
+                    }
+                }
+            }
+            //Recurrence -- Not mandatory
+            cJSON *jsonRecurObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_RECURRENCES_NAME);
+            if(jsonRecurObj)
+            {
+
+                VERIFY_SUCCESS(TAG, cJSON_Array == jsonRecurObj->type, ERROR);
+
+                if(acl->prdRecrLen > 0)
+                {
+                    acl->recurrences = (char**)OICCalloc(acl->prdRecrLen, sizeof(char*));
+                    VERIFY_NON_NULL(TAG, acl->recurrences, ERROR);
+
+                    cJSON *jsonRecur = NULL;
+                    for(size_t i = 0; i < acl->prdRecrLen; i++)
+                    {
+                        jsonRecur = cJSON_GetArrayItem(jsonRecurObj, i);
+                        VERIFY_NON_NULL(TAG, jsonRecur, ERROR);
+                        jsonObjLen = strlen(jsonRecur->valuestring) + 1;
+                        acl->recurrences[i] = (char*)OICMalloc(jsonObjLen);
+                        VERIFY_NON_NULL(TAG, acl->recurrences[i], ERROR);
+                        OICStrcpy(acl->recurrences[i], jsonObjLen, jsonRecur->valuestring);
+                    }
+                }
+            }
+
+            acl->next = NULL;
+
+        } while( ++idx < numAcl);
+    }
+
+
+    // rownerid
+    jsonAclObj = cJSON_GetObjectItem(jsonAclMap, OIC_JSON_ROWNERID_NAME);
+    VERIFY_NON_NULL(TAG, jsonAclObj, ERROR);
+    VERIFY_SUCCESS(TAG, cJSON_String == jsonAclObj->type, ERROR);
+    ret = ConvertStrToUuid(jsonAclObj->valuestring, &headAcl->rownerID);
+    VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+
+    ret = OC_STACK_OK;
+
+exit:
+    cJSON_Delete(jsonRoot);
+    if (OC_STACK_OK != ret)
+    {
+        DeleteACLList(headAcl);
+        headAcl = NULL;
+    }
+    return headAcl;
+}
+
+OicSecDoxm_t* JSONToDoxmBin(const char * jsonStr)
+{
+    printf("IN JSONToDoxmBin\n");
+    if (NULL == jsonStr)
+    {
+        return NULL;
+    }
+
+    OCStackResult ret = OC_STACK_ERROR;
+    OicSecDoxm_t *doxm =  NULL;
+    cJSON *jsonDoxm = NULL;
+    cJSON *jsonObj = NULL;
+
+    size_t jsonObjLen = 0;
+
+    cJSON *jsonRoot = cJSON_Parse(jsonStr);
+    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+
+    jsonDoxm = cJSON_GetObjectItem(jsonRoot, OIC_JSON_DOXM_NAME);
+    VERIFY_NON_NULL(TAG, jsonDoxm, ERROR);
+
+    doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(OicSecDoxm_t));
+    VERIFY_NON_NULL(TAG, doxm, ERROR);
+
+    //OxmType -- not Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_TYPE_NAME);
+    if ((jsonObj) && (cJSON_Array == jsonObj->type))
+    {
+        doxm->oxmTypeLen = (size_t)cJSON_GetArraySize(jsonObj);
+        VERIFY_SUCCESS(TAG, doxm->oxmTypeLen > 0, ERROR);
+
+        doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(char *));
+        VERIFY_NON_NULL(TAG, (doxm->oxmType), ERROR);
+
+        for (size_t i  = 0; i < doxm->oxmTypeLen ; i++)
+        {
+            cJSON *jsonOxmTy = cJSON_GetArrayItem(jsonObj, i);
+            VERIFY_NON_NULL(TAG, jsonOxmTy, ERROR);
+
+            jsonObjLen = strlen(jsonOxmTy->valuestring) + 1;
+            doxm->oxmType[i] = (char*)OICMalloc(jsonObjLen);
+            VERIFY_NON_NULL(TAG, doxm->oxmType[i], ERROR);
+            strncpy((char *)doxm->oxmType[i], (char *)jsonOxmTy->valuestring, jsonObjLen);
+        }
+    }
+
+    //Oxm -- not Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXMS_NAME);
+    if (jsonObj && cJSON_Array == jsonObj->type)
+    {
+        doxm->oxmLen = (size_t)cJSON_GetArraySize(jsonObj);
+        VERIFY_SUCCESS(TAG, doxm->oxmLen > 0, ERROR);
+
+        doxm->oxm = (OicSecOxm_t*)OICCalloc(doxm->oxmLen, sizeof(OicSecOxm_t));
+        VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
+
+        for (size_t i  = 0; i < doxm->oxmLen ; i++)
+        {
+            cJSON *jsonOxm = cJSON_GetArrayItem(jsonObj, i);
+            VERIFY_NON_NULL(TAG, jsonOxm, ERROR);
+            doxm->oxm[i] = (OicSecOxm_t)jsonOxm->valueint;
+        }
+    }
+
+    //OxmSel -- Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_SEL_NAME);
+    if (jsonObj)
+    {
+        VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+        doxm->oxmSel = (OicSecOxm_t)jsonObj->valueint;
+    }
+
+    //sct -- Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_SUPPORTED_CRED_TYPE_NAME);
+    if (jsonObj)
+    {
+        VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+        doxm->sct = (OicSecCredType_t)jsonObj->valueint;
+    }
+
+    //Owned -- Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OWNED_NAME);
+    if (jsonObj)
+    {
+        VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type), ERROR);
+        doxm->owned = jsonObj->valueint;
+    }
+
+    //DPC -- Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_DPC_NAME);
+    if (jsonObj)
+    {
+        VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type), ERROR);
+        doxm->dpc = jsonObj->valueint;
+    }
+
+    //DeviceId -- Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_DEVICE_ID_NAME);
+    if (jsonObj)
+    {
+        VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
+        if (cJSON_String == jsonObj->type)
+        {
+            //Check for empty string, in case DeviceId field has not been set yet
+            if (jsonObj->valuestring[0])
+            {
+                ret = ConvertStrToUuid(jsonObj->valuestring, &doxm->deviceID);
+                VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+            }
+        }
+    }
+
+    //rowner -- Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_ROWNERID_NAME);
+    if (true == doxm->owned)
+    {
+        VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+    }
+    if (jsonObj)
+    {
+        ret = ConvertStrToUuid(jsonObj->valuestring, &doxm->rownerID);
+        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+    }
+
+    //Owner -- will be empty when device status is unowned.
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_DEVOWNERID_NAME);
+    if (true == doxm->owned)
+    {
+        VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+    }
+    if (jsonObj)
+    {
+        ret = ConvertStrToUuid(jsonObj->valuestring, &doxm->owner);
+                VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+    }
+
+    ret = OC_STACK_OK;
+
+exit:
+    cJSON_Delete(jsonRoot);
+    if (OC_STACK_OK != ret)
+    {
+        DeleteDoxmBinData(doxm);
+        doxm = NULL;
+    }
+    printf("OUT JSONToDoxmBin\n");
+    return doxm;
+}
+
+OicSecPstat_t* JSONToPstatBin(const char * jsonStr)
+{
+    printf("IN JSONToPstatBin\n");
+    if(NULL == jsonStr)
+    {
+        return NULL;
+    }
+
+    OCStackResult ret = OC_STACK_ERROR;
+    OicSecPstat_t *pstat = NULL;
+    cJSON *jsonPstat = NULL;
+    cJSON *jsonObj = NULL;
+
+    cJSON *jsonRoot = cJSON_Parse(jsonStr);
+    VERIFY_NON_NULL(TAG, jsonRoot, INFO);
+
+    jsonPstat = cJSON_GetObjectItem(jsonRoot, OIC_JSON_PSTAT_NAME);
+    VERIFY_NON_NULL(TAG, jsonPstat, INFO);
+
+    pstat = (OicSecPstat_t*)OICCalloc(1, sizeof(OicSecPstat_t));
+    VERIFY_NON_NULL(TAG, pstat, INFO);
+    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_ISOP_NAME);
+    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+    VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type) , ERROR);
+    pstat->isOp = jsonObj->valueint;
+
+    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_DEVICE_ID_NAME);
+    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+    VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
+    ret = ConvertStrToUuid(jsonObj->valuestring, &pstat->deviceID);
+    VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+
+    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_ROWNERID_NAME);
+    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+    VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
+    ret = ConvertStrToUuid(jsonObj->valuestring, &pstat->rownerID);
+    VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+
+    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_CM_NAME);
+    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+    VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+    pstat->cm  = (OicSecDpm_t)jsonObj->valueint;
+
+    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_TM_NAME);
+    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+    VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+    pstat->tm  = (OicSecDpm_t)jsonObj->valueint;
+
+    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_OM_NAME);
+    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+    VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+    pstat->om  = (OicSecDpom_t)jsonObj->valueint;
+
+    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_SM_NAME);
+    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+    VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+    pstat->smLen = 1;
+    pstat->sm = (OicSecDpom_t*)OICCalloc(pstat->smLen, sizeof(OicSecDpom_t));
+    pstat->sm[0] = (OicSecDpom_t)jsonObj->valueint;
+
+    ret = OC_STACK_OK;
+
+exit:
+    cJSON_Delete(jsonRoot);
+    if (OC_STACK_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "JSONToPstatBin failed");
+    }
+    printf("OUT JSONToPstatBin\n");
+    return pstat;
+}
+
+OicSecCred_t * JSONToCredBin(const char * jsonStr)
+{
+    if (NULL == jsonStr)
+    {
+        OIC_LOG(ERROR, TAG,"JSONToCredBin jsonStr in NULL");
+        return NULL;
+    }
+
+    OicSecCred_t *headCred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
+    OCStackResult ret = OC_STACK_ERROR;
+    cJSON *jsonRoot = NULL;
+    VERIFY_NON_NULL(TAG, headCred, ERROR);
+
+    jsonRoot = cJSON_Parse(jsonStr);
+    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+
+    cJSON *jsonCredMap = cJSON_GetObjectItem(jsonRoot, OIC_JSON_CRED_NAME);
+    VERIFY_NON_NULL(TAG, jsonCredMap, ERROR);
+
+    // creds
+    cJSON *jsonCredArray = NULL;
+    jsonCredArray = cJSON_GetObjectItem(jsonCredMap, OIC_JSON_CREDS_NAME);
+    VERIFY_NON_NULL(TAG, jsonCredArray, ERROR);
+
+    if (cJSON_Array == jsonCredArray->type)
+    {
+        int numCred = cJSON_GetArraySize(jsonCredArray);
+        VERIFY_SUCCESS(TAG, numCred > 0, ERROR);
+        int idx = 0;
+        size_t ownersLen = 0;
+        do
+        {
+            cJSON *jsonCred = cJSON_GetArrayItem(jsonCredArray, idx);
+            VERIFY_NON_NULL(TAG, jsonCred, ERROR);
+
+            OicSecCred_t *cred = NULL;
+            if(idx == 0)
+            {
+                cred = headCred;
+            }
+            else
+            {
+                cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
+                OicSecCred_t *temp = headCred;
+                while (temp->next)
+                {
+                    temp = temp->next;
+                }
+                temp->next = cred;
+            }
+            VERIFY_NON_NULL(TAG, cred, ERROR);
+
+            size_t jsonObjLen = 0;
+            cJSON *jsonObj = NULL;
+
+            //CredId -- Mandatory
+            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_CREDID_NAME);
+            if(jsonObj)
+            {
+                VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+                cred->credId = jsonObj->valueint;
+            }
+
+            //subject -- Mandatory
+            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_SUBJECTID_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
+            ret = ConvertStrToUuid(jsonObj->valuestring, &cred->subject);
+            VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+
+            //CredType -- Mandatory
+            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_CREDTYPE_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+            cred->credType = (OicSecCredType_t)jsonObj->valueint;
+            //PrivateData is mandatory for some of the credential types listed below.
+            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PRIVATEDATA_NAME);
+
+            if (NULL != jsonObj)
+            {
+                cJSON *jsonPriv = cJSON_GetObjectItem(jsonObj, OIC_JSON_DATA_NAME);
+                VERIFY_NON_NULL(TAG, jsonPriv, ERROR);
+                jsonObjLen = strlen(jsonPriv->valuestring);
+                cred->privateData.data = (uint8_t *)OICCalloc(1, jsonObjLen);
+                VERIFY_NON_NULL(TAG, (cred->privateData.data), ERROR);
+                memcpy(cred->privateData.data, jsonPriv->valuestring, jsonObjLen);
+                cred->privateData.len = jsonObjLen;
+            }
+#ifdef __WITH_X509__
+            //PublicData is mandatory only for SIGNED_ASYMMETRIC_KEY credentials type.
+            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PUBLICDATA_NAME);
+
+            if (NULL != jsonObj)
+            {
+                cJSON *jsonPub = cJSON_GetObjectItem(jsonObj, OIC_JSON_DATA_NAME);
+                VERIFY_NON_NULL(TAG, jsonPub, ERROR);
+                jsonObjLen = strlen(jsonPub->valuestring);
+                cred->publicData.data = (uint8_t *)OICCalloc(1, jsonObjLen);
+                VERIFY_NON_NULL(TAG, (cred->publicData.data), ERROR);
+                memcpy(cred->publicData.data, jsonPub->valuestring, jsonObjLen);
+                cred->publicData.len = jsonObjLen;
+            }
+#endif //  __WITH_X509__
+            //Period -- Not Mandatory
+            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PERIOD_NAME);
+            if(jsonObj && cJSON_String == jsonObj->type)
+            {
+                jsonObjLen = strlen(jsonObj->valuestring) + 1;
+                cred->period = (char *)OICMalloc(jsonObjLen);
+                VERIFY_NON_NULL(TAG, cred->period, ERROR);
+                strncpy(cred->period, jsonObj->valuestring, jsonObjLen);
+            }
+            cred->next = NULL;
+        } while( ++idx < numCred);
+    }
+
+    // rownerid
+    cJSON *jsonCredObj = cJSON_GetObjectItem(jsonCredMap, OIC_JSON_ROWNERID_NAME);
+    VERIFY_NON_NULL(TAG, jsonCredObj, ERROR);
+    VERIFY_SUCCESS(TAG, cJSON_String == jsonCredObj->type, ERROR);
+    ret = ConvertStrToUuid(jsonCredObj->valuestring, &headCred->rownerID);
+    VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+    ret = OC_STACK_OK;
+
+exit:
+
+    if (OC_STACK_OK != ret)
+    {
+        DeleteCredList(headCred);
+        headCred = NULL;
+    }
+    return headCred;
+}
+
+static OicSecSvc_t* JSONToSvcBin(const char * jsonStr)
+{
+    OCStackResult ret = OC_STACK_ERROR;
+    OicSecSvc_t * headSvc = NULL;
+    OicSecSvc_t * prevSvc = NULL;
+    cJSON *jsonRoot = NULL;
+    cJSON *jsonSvcArray = NULL;
+
+    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
+
+    jsonRoot = cJSON_Parse(jsonStr);
+    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+
+    jsonSvcArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_SVC_NAME);
+    VERIFY_NON_NULL(TAG, jsonSvcArray, INFO);
+
+    if (cJSON_Array == jsonSvcArray->type)
+    {
+        int numSvc = cJSON_GetArraySize(jsonSvcArray);
+        int idx = 0;
+
+        VERIFY_SUCCESS(TAG, numSvc > 0, INFO);
+        do
+        {
+            cJSON *jsonSvc = cJSON_GetArrayItem(jsonSvcArray, idx);
+            VERIFY_NON_NULL(TAG, jsonSvc, ERROR);
+
+            OicSecSvc_t *svc = (OicSecSvc_t*)OICCalloc(1, sizeof(OicSecSvc_t));
+            VERIFY_NON_NULL(TAG, svc, ERROR);
+
+            headSvc = (headSvc) ? headSvc : svc;
+            if (prevSvc)
+            {
+                prevSvc->next = svc;
+            }
+
+            cJSON *jsonObj = NULL;
+            unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
+            uint32_t outLen = 0;
+            B64Result b64Ret = B64_OK;
+
+            // Service Device Identity
+            jsonObj = cJSON_GetObjectItem(jsonSvc, OIC_JSON_SERVICE_DEVICE_ID);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
+            outLen = 0;
+            b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
+                       sizeof(base64Buff), &outLen);
+            VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(svc->svcdid.id)), ERROR);
+            memcpy(svc->svcdid.id, base64Buff, outLen);
+
+            // Service Type
+            jsonObj = cJSON_GetObjectItem(jsonSvc, OIC_JSON_SERVICE_TYPE);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+            svc->svct = (OicSecSvcType_t)jsonObj->valueint;
+
+            // Resource Owners
+            jsonObj = cJSON_GetObjectItem(jsonSvc, OIC_JSON_OWNERS_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
+
+            svc->ownersLen = (size_t)cJSON_GetArraySize(jsonObj);
+            VERIFY_SUCCESS(TAG, svc->ownersLen > 0, ERROR);
+            svc->owners = (OicUuid_t*)OICCalloc(svc->ownersLen, sizeof(OicUuid_t));
+            VERIFY_NON_NULL(TAG, (svc->owners), ERROR);
+
+            size_t idxx = 0;
+            do
+            {
+                cJSON *jsonOwnr = cJSON_GetArrayItem(jsonObj, idxx);
+                VERIFY_NON_NULL(TAG, jsonOwnr, ERROR);
+                VERIFY_SUCCESS(TAG, cJSON_String == jsonOwnr->type, ERROR);
+                outLen = 0;
+                b64Ret = b64Decode(jsonOwnr->valuestring, strlen(jsonOwnr->valuestring), base64Buff,
+                           sizeof(base64Buff), &outLen);
+
+                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(svc->owners[idxx].id)),
+                                   ERROR);
+                memcpy(svc->owners[idxx].id, base64Buff, outLen);
+            } while ( ++idxx < svc->ownersLen);
+
+            prevSvc = svc;
+        } while( ++idx < numSvc);
+    }
+
+    ret = OC_STACK_OK;
+
+exit:
+    cJSON_Delete(jsonRoot);
+    if (OC_STACK_OK != ret)
+    {
+        DeleteSVCList(headSvc);
+        headSvc = NULL;
+    }
+    return headSvc;
+}
+
+static OicSecAmacl_t* JSONToAmaclBin(const char * jsonStr)
+{
+    OCStackResult ret = OC_STACK_ERROR;
+    OicSecAmacl_t * headAmacl = (OicSecAmacl_t*)OICCalloc(1, sizeof(OicSecAmacl_t));
+
+    cJSON *jsonRoot = NULL;
+    cJSON *jsonAmacl = NULL;
+
+    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
+
+    jsonRoot = cJSON_Parse(jsonStr);
+    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+
+    jsonAmacl = cJSON_GetObjectItem(jsonRoot, OIC_JSON_AMACL_NAME);
+    VERIFY_NON_NULL(TAG, jsonAmacl, INFO);
+
+    cJSON *jsonObj = NULL;
+
+    // Resources -- Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonAmacl, OIC_JSON_RESOURCES_NAME);
+    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+
+    // Rlist
+    cJSON *jsonRlistArray = cJSON_GetObjectItem(jsonObj, OIC_JSON_RLIST_NAME);
+    VERIFY_NON_NULL(TAG, jsonRlistArray, ERROR);
+    VERIFY_SUCCESS(TAG, cJSON_Array == jsonRlistArray->type, ERROR);
+
+    headAmacl->resourcesLen = (size_t)cJSON_GetArraySize(jsonRlistArray);
+    headAmacl->resources = (char**)OICCalloc(headAmacl->resourcesLen, sizeof(char*));
+    size_t idxx = 0;
+    do
+    {
+        cJSON *jsonRsrc = cJSON_GetArrayItem(jsonRlistArray, idxx);
+        VERIFY_NON_NULL(TAG, jsonRsrc, ERROR);
+
+        cJSON *jsonRsrcObj = cJSON_GetObjectItem(jsonRsrc, OIC_JSON_HREF_NAME);
+        VERIFY_NON_NULL(TAG, jsonRsrcObj, ERROR);
+        VERIFY_SUCCESS(TAG, cJSON_String == jsonRsrcObj->type, ERROR);
+
+        size_t jsonRsrcObjLen = 0;
+        jsonRsrcObjLen = strlen(jsonRsrcObj->valuestring) + 1;
+        headAmacl->resources[idxx] = (char*)OICMalloc(jsonRsrcObjLen);
+        VERIFY_NON_NULL(TAG, (headAmacl->resources[idxx]), ERROR);
+        OICStrcpy(headAmacl->resources[idxx], jsonRsrcObjLen, jsonRsrcObj->valuestring);
+
+    } while ( ++idxx < headAmacl->resourcesLen);
+
+    // Ams -- Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonAmacl, OIC_JSON_AMS_NAME);
+    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+    VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
+
+    headAmacl->amssLen = (size_t)cJSON_GetArraySize(jsonObj);
+    VERIFY_SUCCESS(TAG, headAmacl->amssLen > 0, ERROR);
+    headAmacl->amss = (OicUuid_t*)OICCalloc(headAmacl->amssLen, sizeof(OicUuid_t));
+    VERIFY_NON_NULL(TAG, headAmacl->amss, ERROR);
+
+    idxx = 0;
+    do
+    {
+        cJSON *jsonAms = cJSON_GetArrayItem(jsonObj, idxx);
+        VERIFY_NON_NULL(TAG, jsonAms, ERROR);
+        VERIFY_SUCCESS(TAG, cJSON_String == jsonAms->type, ERROR);
+
+        memcpy(headAmacl->amss[idxx].id, (OicUuid_t *)jsonAms->valuestring, strlen(jsonAms->valuestring));
+
+    } while ( ++idxx < headAmacl->amssLen);
+
+
+    // Rowner -- Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonAmacl, OIC_JSON_ROWNERID_NAME);
+    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+    VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
+
+    ret = ConvertStrToUuid(jsonObj->valuestring, &headAmacl->rownerID);
+    VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
+
+    ret = OC_STACK_OK;
+
+exit:
+    cJSON_Delete(jsonRoot);
+    if (OC_STACK_OK != ret)
+    {
+        DeleteAmaclList(headAmacl);
+        headAmacl = NULL;
+    }
+    return headAmacl;
+}
+
+int main(int argc, char* argv[])
+{
+    if (argc == 3)
+    {
+        printf("JSON File Name: %s\n CBOR File Name: %s \n", argv[1], argv[2]);
+        ConvertJsonToCBOR(argv[1], argv[2]);
+    }
+    else
+    {
+        printf("This program requires two inputs:\n");
+        printf("1. First input is a json file tha will be converted to cbor. \n");
+        printf("2. Second input is a resulting cbor file that will store converted cbor. \n");
+        printf("\t json2cbor <json_file_name> <cbor_file_name>. \n");
+    }
+}
index be35bb3..c431d77 100644 (file)
@@ -44,9 +44,11 @@ srmtest_env.PrependUnique(CPPPATH = [
                '../../../oc_logger/include',
                '../../../../extlibs/gtest/gtest-1.7.0/include',
                '../../../../extlibs/cjson/',
+                '../provisioning/include',
 #              '../../../../extlibs/tinydtls/',
                '../include'
                ])
+
 srmtest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
 srmtest_env.AppendUnique(LIBS = ['-lpthread'])
 srmtest_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
@@ -69,6 +71,7 @@ if not env.get('RELEASE'):
 # Source files and Targets
 ######################################################################
 unittest = srmtest_env.Program('unittest', ['aclresourcetest.cpp',
+                                            'amaclresourcetest.cpp',
                                             'pstatresource.cpp',
                                             'doxmresource.cpp',
                                             'policyengine.cpp',
@@ -78,12 +81,15 @@ unittest = srmtest_env.Program('unittest', ['aclresourcetest.cpp',
                                             'iotvticalendartest.cpp',
                                             'base64tests.cpp',
                                             'svcresourcetest.cpp',
-                                            'srmtestcommon.cpp'])
+                                            'srmtestcommon.cpp',
+                                            'directpairingtest.cpp'])
 
 Alias("test", [unittest])
 
 unittest_src_dir = src_dir + '/resource/csdk/security/unittest/'
-unittest_build_dir = env.get('BUILD_DIR') +'/resource/csdk/security/unittest'
+unittest_build_dir = env.get('BUILD_DIR') + 'resource/csdk/security/unittest'
+
+srmtest_env.AppendUnique(CPPDEFINES = ['SECURITY_BUILD_UNITTEST_DIR='+unittest_build_dir])
 
 srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
     unittest_src_dir + 'oic_unittest.json'))
@@ -92,6 +98,13 @@ srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
 srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
     unittest_src_dir + 'oic_unittest_default_acl.json'))
 
+srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
+    unittest_src_dir + 'oic_unittest.dat'))
+srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
+    unittest_src_dir + 'oic_unittest_acl1.dat'))
+srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
+    unittest_src_dir + 'oic_unittest_default_acl.dat'))
+
 env.AppendTarget('test')
 if env.get('TEST') == '1':
        target_os = env.get('TARGET_OS')
@@ -105,4 +118,3 @@ if env.get('TEST') == '1':
                srmtest_env.AppendENVPath('LD_LIBRARY_PATH', ['./extlibs/gtest/gtest-1.7.0/lib/.libs'])
                ut = srmtest_env.Command ('ut', None, out_dir + '/resource/csdk/security/unittest/unittest')
                AlwaysBuild ('ut')
-
index 08e7d26..558406a 100644 (file)
 #include <linux/limits.h>
 #include <sys/stat.h>
 #include "ocstack.h"
+#include "psinterface.h"
 #include "ocpayload.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
-#include "cJSON.h"
 #include "cainterface.h"
 #include "secureresourcemanager.h"
 #include "securevirtualresourcetypes.h"
 #include "srmtestcommon.h"
 #include "srmutility.h"
 #include "logger.h"
+#include "doxmresource.h"
+#include "ocpayload.h"
+#include "ocpayloadcbor.h"
+#include "payload_logging.h"
+#include "security_internals.h"
 
 using namespace std;
 
 #define TAG  "SRM-ACL-UT"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-extern char * BinToAclJSON(const OicSecAcl_t * acl);
-extern OicSecAcl_t * JSONToAclBin(const char * jsonStr);
-extern void DeleteACLList(OicSecAcl_t* acl);
-OCStackResult  GetDefaultACL(OicSecAcl_t** defaultAcl);
-OCEntityHandlerResult ACLEntityHandler (OCEntityHandlerFlag flag,
-                                        OCEntityHandlerRequest * ehRequest);
-#ifdef __cplusplus
-}
-#endif
-
-const char* JSON_FILE_NAME = "oic_unittest.json";
-const char* DEFAULT_ACL_JSON_FILE_NAME = "oic_unittest_default_acl.json";
-const char* ACL1_JSON_FILE_NAME = "oic_unittest_acl1.json";
+// These paths match jenkins build configuration.
+const char* DEFAULT_ACL_FILE_NAME = "/oic_unittest_default_acl.dat";
+const char* ACL1_FILE_NAME = "/oic_unittest_acl1.dat";
 
-#define NUM_ACE_FOR_WILDCARD_IN_ACL1_JSON (2)
+#define NUM_ACE_FOR_WILDCARD_IN_ACL1_DAT (1)
 
-// JSON Marshalling Tests
-TEST(ACLResourceTest, JSONMarshallingTests)
+TEST(ACLResourceTest, CBORDefaultACLConversion)
 {
-    char *jsonStr1 = ReadFile(ACL1_JSON_FILE_NAME);
-    if (jsonStr1)
+    OicSecAcl_t *defaultAcl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
+    ASSERT_TRUE(defaultAcl != NULL);
+    uint8_t defaultAclSub[] = { 0x2a };
+    memcpy(defaultAcl->subject.id, defaultAclSub, sizeof(defaultAclSub));
+    defaultAcl->permission = 2;
+    const char *defaulAclRsrc[] = { "/oic/res", "/oic/d", "/oic/p", "/oic/res/types/d",
+            "/oic/ad", "/oic/sec/acl", "/oic/sec/doxm", "/oic/sec/pstat"};
+    defaultAcl->resourcesLen = 8;
+    defaultAcl->resources = (char **)OICCalloc(defaultAcl->resourcesLen, sizeof(char *));
+    ASSERT_TRUE(defaultAcl->resources != NULL);
+    for (size_t i = 0 ; i < defaultAcl->resourcesLen; i++)
     {
-        cJSON_Minify(jsonStr1);
-        /* Workaround : cJSON_Minify does not remove all the unwanted characters
-         from the end. Here is an attempt to remove those characters */
-        int len = strlen(jsonStr1);
-        while (len > 0)
-        {
-            if (jsonStr1[--len] == '}')
-            {
-                break;
-            }
-        }
-        jsonStr1[len + 1] = 0;
+        defaultAcl->resources[i] = OICStrdup(defaulAclRsrc[i]);
+        ASSERT_TRUE(defaultAcl->resources[i] != NULL);
+    }
+    uint8_t defaultAclOwnrs[] = {0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
+        0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32};
+    memcpy(defaultAcl->rownerID.id, defaultAclOwnrs, sizeof(defaultAclOwnrs));
+
+    size_t defaultAclSize = 0;
+    uint8_t *defaultPsStorage = NULL;
+    OCStackResult convRet = AclToCBORPayload(defaultAcl, &defaultPsStorage, &defaultAclSize);
+    EXPECT_EQ(OC_STACK_OK, convRet);
+    ASSERT_TRUE(defaultPsStorage != NULL);
+    EXPECT_NE(0, defaultAclSize);
+
+    OicSecAcl_t* convertedAcl = CBORPayloadToAcl(defaultPsStorage, defaultAclSize);
+    ASSERT_TRUE(convertedAcl != NULL);
+
+    EXPECT_EQ(defaultAcl->resourcesLen, convertedAcl->resourcesLen);
+    for(int i = 0; i < convertedAcl->resourcesLen; i++)
+    {
+        EXPECT_EQ(0, strcmp(defaultAcl->resources[i], convertedAcl->resources[i]));
+    }
 
-        OicSecAcl_t * acl = JSONToAclBin(jsonStr1);
-        EXPECT_TRUE(NULL != acl);
+    DeleteACLList(convertedAcl);
+    DeleteACLList(defaultAcl);
+    OICFree(defaultPsStorage);
+}
 
-        char * jsonStr2 = BinToAclJSON(acl);
-        EXPECT_TRUE(NULL != jsonStr2);
+TEST(ACLResourceTest, CBORACLConversion)
+{
+    OicSecAcl_t *secAcl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
+    ASSERT_TRUE(secAcl != NULL);
+    uint8_t subjectBytes[] = { 0x2a };
+    memcpy(secAcl->subject.id, subjectBytes, sizeof(subjectBytes));
+    secAcl->permission = 2;
+    const char *rsrc[] = { "/oic/res", "/oic/d", "/oic/p", "/oic/res/types/d",
+                           "/oic/ad", "/oic/sec/acl"};
+    secAcl->resourcesLen = 6;
+    secAcl->resources = (char **)OICCalloc(secAcl->resourcesLen, sizeof(char *));
+    ASSERT_TRUE(secAcl->resources != NULL);
+    for (size_t i = 0 ; i < secAcl->resourcesLen; i++)
+    {
+        secAcl->resources[i] = OICStrdup(rsrc[i]);
+        ASSERT_TRUE(secAcl->resources[i] != NULL);
 
-        EXPECT_STREQ(jsonStr1, jsonStr2);
+    }
 
-        OICFree(jsonStr1);
-        OICFree(jsonStr2);
-        DeleteACLList(acl);
+    uint8_t ownrs[] = {0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
+        0x32, 0x32, 0x32, 0x32, 0x32, 0x32};
+    memcpy(secAcl->rownerID.id, ownrs, sizeof(ownrs));
+
+    OicSecAcl_t *secAcl1 = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
+    ASSERT_TRUE(secAcl1 != NULL);
+    memcpy(secAcl1->subject.id, subjectBytes, sizeof(subjectBytes));
+    secAcl1->permission = 6;
+    const char *rsrc1[] = { "/oic/sec/doxm", "/oic/sec/pstat"};
+    secAcl1->resourcesLen = 2;
+    secAcl1->resources = (char **)OICCalloc(secAcl1->resourcesLen, sizeof(char *));
+    ASSERT_TRUE(secAcl1->resources != NULL);
+    for (size_t i = 0 ; i < secAcl1->resourcesLen; i++)
+    {
+        secAcl1->resources[i] = OICStrdup(rsrc1[i]);
+        ASSERT_TRUE(secAcl1->resources[i] != NULL);
+    }
+    memcpy(secAcl1->rownerID.id, ownrs, sizeof(ownrs));
+    secAcl->next = secAcl1;
+
+    OicSecAcl_t *secAcl2 = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
+    ASSERT_TRUE(secAcl2 != NULL);
+    uint8_t subjectBytes1[] = {0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
+        0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31};
+    memcpy(secAcl2->subject.id, subjectBytes1, sizeof(subjectBytes1));
+    secAcl2->permission = 255;
+    const char *rsrc2[] = {"/oic/light", "/oic/fan" };
+    secAcl2->resourcesLen = 2;
+    secAcl2->resources = (char **)OICCalloc(secAcl2->resourcesLen, sizeof(char *));
+    ASSERT_TRUE(secAcl2->resources != NULL);
+    for (size_t i = 0 ; i < secAcl2->resourcesLen; i++)
+    {
+        secAcl2->resources[i] = OICStrdup(rsrc2[i]);
+        ASSERT_TRUE(secAcl2->resources[i] != NULL);
     }
+    memcpy(secAcl2->rownerID.id, ownrs, sizeof(ownrs));
+    secAcl1->next = secAcl2;
+
+    OicSecAcl_t *secAcl3 = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
+    ASSERT_TRUE(secAcl3 != NULL);
+    uint8_t subjectBytes2[] = {0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33,
+                               0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33};
+    memcpy(secAcl3->subject.id, subjectBytes2, sizeof(subjectBytes2));
+    secAcl3->permission = 255;
+    const char *rsrc3[] = {"/oic/light", "/oic/garage" };
+    secAcl3->resourcesLen = 2;
+    secAcl3->resources = (char **)OICCalloc(secAcl3->resourcesLen, sizeof(char *));
+    ASSERT_TRUE(secAcl3->resources != NULL);
+    for (size_t i = 0 ; i < secAcl3->resourcesLen; i++)
+    {
+        secAcl3->resources[i] = OICStrdup(rsrc3[i]);
+        ASSERT_TRUE(secAcl3->resources[i] != NULL);
+    }
+    memcpy(secAcl3->rownerID.id, ownrs, sizeof(ownrs));
+    secAcl2->next = secAcl3;
+    secAcl3->next = NULL;
+
+    size_t size = 0;
+    uint8_t *psStorage = NULL;
+    EXPECT_EQ(OC_STACK_OK, AclToCBORPayload(secAcl, &psStorage, &size));
+    ASSERT_TRUE(NULL != psStorage);
+    OicSecAcl_t *acl = CBORPayloadToAcl(psStorage, size);
+    ASSERT_TRUE(NULL != acl);
+    EXPECT_EQ(2, acl->permission);
+    EXPECT_EQ(6 , acl->resourcesLen);
+    EXPECT_STREQ("/oic/res", acl->resources[0]);
+    DeleteACLList(acl);
+    OICFree(psStorage);
+    DeleteACLList(secAcl);
+}
+
+//InitResource Tests
+TEST(ACLResourceTest, InitAclResource)
+{
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, InitACLResource());
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, DeInitACLResource());
 }
 
 // Default ACL tests
 TEST(ACLResourceTest, GetDefaultACLTests)
 {
-    // Read default ACL from the file
-    char *jsonStr = ReadFile(DEFAULT_ACL_JSON_FILE_NAME);
-    if (jsonStr)
-    {
-        OicSecAcl_t * acl = JSONToAclBin(jsonStr);
-        EXPECT_TRUE(NULL != acl);
+    uint8_t *payload = NULL;
+    size_t size = 0;
 
-        // Invoke API to generate default ACL
-        OicSecAcl_t * defaultAcl = NULL;
-        OCStackResult ret = GetDefaultACL(&defaultAcl);
-        EXPECT_TRUE(NULL == defaultAcl);
+    ASSERT_TRUE(ReadCBORFile(DEFAULT_ACL_FILE_NAME, OIC_JSON_ACL_NAME, &payload, &size));
+    ASSERT_TRUE(payload != NULL);
 
-        EXPECT_TRUE(OC_STACK_ERROR == ret);
+    OicSecAcl_t *psAcl = CBORPayloadToAcl(payload, size);
+    ASSERT_TRUE(psAcl != NULL);
 
-        // Verify if the SRM generated default ACL matches with unit test default
-        if (acl && defaultAcl)
+    OicSecAcl_t *acl = NULL;
+    EXPECT_EQ(OC_STACK_OK, GetDefaultACL(&acl));
+    ASSERT_TRUE(acl != NULL);
+
+    // Verify if the SRM generated default ACL matches with unit test default
+    if (acl && psAcl)
+    {
+        EXPECT_TRUE(strcmp((char*)acl->subject.id, (char*)psAcl->subject.id) == 0);
+        EXPECT_EQ(acl->resourcesLen, psAcl->resourcesLen);
+        for (size_t i = 0; i < acl->resourcesLen; i++)
         {
-            EXPECT_TRUE(memcmp(&(acl->subject), &(defaultAcl->subject), sizeof(OicUuid_t)) == 0);
-            EXPECT_EQ(acl->resourcesLen, defaultAcl->resourcesLen);
-            for (size_t i = 0; i < acl->resourcesLen; i++)
-            {
-                EXPECT_EQ(strlen(acl->resources[i]), strlen(defaultAcl->resources[i]));
-                EXPECT_TRUE(
-                        memcmp(acl->resources[i], defaultAcl->resources[i],
-                                strlen(acl->resources[i])) == 0);
-            }
-            EXPECT_EQ(acl->permission, defaultAcl->permission);
+            EXPECT_EQ(strlen(acl->resources[i]), strlen(psAcl->resources[i]));
+            EXPECT_TRUE(memcmp(acl->resources[i], psAcl->resources[i],
+                            strlen(acl->resources[i])) == 0);
         }
-
-        // Perform cleanup
-        DeleteACLList(acl);
-        DeleteACLList(defaultAcl);
-        OICFree(jsonStr);
+        EXPECT_EQ(acl->permission, psAcl->permission);
     }
-}
 
+    DeleteACLList(psAcl);
+    DeleteACLList(acl);
+    DeInitACLResource();
+    OICFree(payload);
+}
 
 // 'POST' ACL tests
 TEST(ACLResourceTest, ACLPostTest)
 {
-    OCEntityHandlerRequest ehReq =  OCEntityHandlerRequest();
-
     // Read an ACL from the file
-    char *jsonStr = ReadFile(ACL1_JSON_FILE_NAME);
-    if (jsonStr)
-    {
-        static OCPersistentStorage ps = OCPersistentStorage();
+    uint8_t *payload = NULL;
+    size_t size = 0;
 
-        SetPersistentHandler(&ps, true);
+    ASSERT_TRUE(ReadCBORFile(ACL1_FILE_NAME, OIC_JSON_ACL_NAME, &payload, &size));
+    ASSERT_TRUE(NULL != payload);
 
-        // Create Entity Handler POST request payload
-        ehReq.method = OC_REST_POST;
-        ehReq.payload = (OCPayload*)OCSecurityPayloadCreate(jsonStr);
+    OCSecurityPayload *securityPayload = OCSecurityPayloadCreate(payload, size);
+    ASSERT_TRUE(NULL != securityPayload);
 
-        OCEntityHandlerResult ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq);
-        EXPECT_TRUE(OC_EH_ERROR == ehRet);
+    static OCPersistentStorage ps = OCPersistentStorage();
+    SetPersistentHandler(&ps, true);
 
-        // Convert JSON into OicSecAcl_t for verification
-        OicSecAcl_t * acl = JSONToAclBin(jsonStr);
-        EXPECT_TRUE(NULL != acl);
+    // Create Entity Handler POST request payload
+    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
+    ehReq.method = OC_REST_POST;
+    ehReq.payload = (OCPayload *) securityPayload;
 
-        // Verify if SRM contains ACL for the subject
-        OicSecAcl_t* savePtr = NULL;
-        const OicSecAcl_t* subjectAcl = GetACLResourceData(&(acl->subject), &savePtr);
-        EXPECT_TRUE(NULL != subjectAcl);
+    ACLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
 
-        // Perform cleanup
-        DeleteACLList(acl);
-        DeInitACLResource();
-        OCPayloadDestroy(ehReq.payload);
-        OICFree(jsonStr);
-    }
-}
+    OicSecAcl_t *acl = CBORPayloadToAcl(payload, size);
+    ASSERT_TRUE(NULL != acl);
+
+    // Verify if SRM contains ACL for the subject
+    OicSecAcl_t *savePtr = NULL;
+    const OicSecAcl_t* subjectAcl = GetACLResourceData(&(acl->subject), &savePtr);
+    ASSERT_TRUE(NULL != subjectAcl);
 
+    // Perform cleanup
+    OICFree(payload);
+    OCPayloadDestroy((OCPayload *) securityPayload);
+    DeInitACLResource();
+    DeleteACLList(acl);
+}
 
 // GetACLResource tests
 TEST(ACLResourceTest, GetACLResourceTests)
 {
-    // gAcl is a pointer to the the global ACL used by SRM
-    extern OicSecAcl_t  *gAcl;
-
     // Read an ACL from the file
-    char *jsonStr = ReadFile(ACL1_JSON_FILE_NAME);
-    if (jsonStr)
-    {
-        gAcl = JSONToAclBin(jsonStr);
-        EXPECT_TRUE(NULL != gAcl);
+    static OCPersistentStorage ps = OCPersistentStorage();
+    SetPersistentHandler(&ps, true);
 
-        // Verify that ACL file contains 2 ACE entries for 'WILDCARD' subject
-        const OicSecAcl_t* acl = NULL;
-        OicSecAcl_t* savePtr = NULL;
-        OicUuid_t subject = WILDCARD_SUBJECT_ID;
-        int count = 0;
+    uint8_t *payload = NULL;
+    size_t size = 0;
 
-        do
-        {
-            acl = GetACLResourceData(&subject, &savePtr);
-            count = (NULL != acl) ? count + 1 : count;
-        } while (acl != NULL);
+    ASSERT_TRUE(ReadCBORFile(ACL1_FILE_NAME, OIC_JSON_ACL_NAME, &payload, &size));
+    ASSERT_TRUE(payload != NULL);
 
-        EXPECT_EQ(count, NUM_ACE_FOR_WILDCARD_IN_ACL1_JSON);
+    OicSecAcl_t *defaultPsAcl = CBORPayloadToAcl(payload, size);
+    ASSERT_TRUE(defaultPsAcl != NULL);
 
-        /* Perform cleanup */
-        DeleteACLList(gAcl);
-        gAcl = NULL;
-        OICFree(jsonStr);
-    }
+    OicSecAcl_t *acl1 = NULL;
+    EXPECT_EQ(OC_STACK_OK, GetDefaultACL(&acl1));
+    ASSERT_TRUE(acl1 != NULL);
+    EXPECT_EQ(OC_STACK_OK, SetDefaultACL(acl1));
+
+    // Verify that ACL file contains 2 ACE entries for 'WILDCARD' subject
+    const OicSecAcl_t *acl = NULL;
+    OicSecAcl_t *savePtr = NULL;
+    OicUuid_t subject = WILDCARD_SUBJECT_ID;
+    int count = 0;
+
+    do
+    {
+        acl = GetACLResourceData(&subject, &savePtr);
+        count = (NULL != acl) ? count + 1 : count;
+    } while (acl != NULL);
+
+    EXPECT_EQ(count, NUM_ACE_FOR_WILDCARD_IN_ACL1_DAT);
+
+    /* Perform cleanup */
+    OICFree(payload);
+    DeleteACLList(defaultPsAcl);
+    DeInitACLResource();
 }
 
 static OCStackResult  populateAcl(OicSecAcl_t *acl,  int numRsrc)
 {
-    OCStackResult ret = OC_STACK_ERROR;
+     OCStackResult ret = OC_STACK_ERROR;
     memcpy(acl->subject.id, "2222222222222222", sizeof(acl->subject.id));
-    acl->resourcesLen = numRsrc;
+    acl->resourcesLen = (size_t)numRsrc;
     acl->resources = (char**)OICCalloc(acl->resourcesLen, sizeof(char*));
     VERIFY_NON_NULL(TAG, acl->resources, ERROR);
     acl->resources[0] = (char*)OICMalloc(strlen("/a/led")+1);
     VERIFY_NON_NULL(TAG, acl->resources[0], ERROR);
-    OICStrcpy(acl->resources[0], sizeof(acl->resources[0]), "/a/led");
+    OICStrcpy(acl->resources[0], strlen("/a/led")+1, "/a/led");
     if(numRsrc == 2)
     {
         acl->resources[1] = (char*)OICMalloc(strlen("/a/fan")+1);
         VERIFY_NON_NULL(TAG, acl->resources[1], ERROR);
-        OICStrcpy(acl->resources[1], sizeof(acl->resources[1]), "/a/fan");
+        OICStrcpy(acl->resources[1], strlen("/a/fan")+1, "/a/fan");
     }
     acl->permission = 6;
-    acl->ownersLen = 1;
-    acl->owners = (OicUuid_t*)OICCalloc(acl->ownersLen, sizeof(OicUuid_t));
-    VERIFY_NON_NULL(TAG, acl->owners, ERROR);
-    memcpy(acl->owners->id, "1111111111111111", sizeof(acl->owners->id));
+    memcpy(acl->rownerID.id, "1111111111111111", sizeof(acl->rownerID.id));
 
     ret = OC_STACK_OK;
 exit:
@@ -237,158 +334,145 @@ exit:
 //'DELETE' ACL test
 TEST(ACLResourceTest, ACLDeleteWithSingleResourceTest)
 {
-    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
-    static OCPersistentStorage ps = OCPersistentStorage();
-    char *jsonStr = NULL;
+    //Populate ACL
     OicSecAcl_t acl = OicSecAcl_t();
-    OicSecAcl_t* savePtr = NULL;
-    const OicSecAcl_t* subjectAcl1 = NULL;
-    const OicSecAcl_t* subjectAcl2 = NULL;
-    OCEntityHandlerResult ehRet = OC_EH_ERROR;
-    char query[] = "sub=MjIyMjIyMjIyMjIyMjIyMg==;rsrc=/a/led";
+    EXPECT_EQ(OC_STACK_OK, populateAcl(&acl, 1));
 
-    SetPersistentHandler(&ps, true);
+    //GET CBOR POST payload
+    size_t size = 0;
+    uint8_t  *payload = NULL;
+    EXPECT_EQ(OC_STACK_OK, AclToCBORPayload(&acl, &payload, &size));
+    ASSERT_TRUE(NULL != payload);
 
-    //Populate ACL
-    VERIFY_SUCCESS(TAG, (OC_STACK_OK == populateAcl(&acl, 1)), ERROR);
+    // Security Payload
+    OCSecurityPayload *securityPayload = OCSecurityPayloadCreate(payload, size);
+    ASSERT_TRUE(NULL != securityPayload);
 
-    //GET json POST payload
-    jsonStr = BinToAclJSON(&acl);
-    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
+    static OCPersistentStorage ps = OCPersistentStorage();
+    SetPersistentHandler(&ps, true);
 
     // Create Entity Handler POST request payload
+    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
+    ehReq.payload = (OCPayload *) securityPayload;
     ehReq.method = OC_REST_POST;
-    ehReq.payload = (OCPayload*)OCSecurityPayloadCreate(jsonStr);
-    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq);
-    EXPECT_TRUE(OC_EH_ERROR == ehRet);
+    ACLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
 
     // Verify if SRM contains ACE for the subject
-    savePtr = NULL;
-    subjectAcl1 = GetACLResourceData(&acl.subject, &savePtr);
-    EXPECT_TRUE(NULL != subjectAcl1);
+    OicSecAcl_t* savePtr = NULL;
+    const OicSecAcl_t* subjectAcl1 = GetACLResourceData(&acl.subject, &savePtr);
+    ASSERT_TRUE(NULL != subjectAcl1);
 
     // Create Entity Handler DELETE request
     ehReq.method = OC_REST_DELETE;
-    ehReq.query = (char*)OICMalloc(strlen(query)+1);
-    VERIFY_NON_NULL(TAG, ehReq.query, ERROR);
+    char query[] = "subjectuuid=2222222222222222;resources=/a/led";
+    ehReq.query = (char *)OICMalloc(strlen(query)+1);
+    ASSERT_TRUE(NULL !=  ehReq.query);
     OICStrcpy(ehReq.query, strlen(query)+1, query);
-    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq);
-    EXPECT_TRUE(OC_EH_ERROR == ehRet);
+    ACLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
 
     // Verify if SRM has deleted ACE for the subject
     savePtr = NULL;
-    subjectAcl2 = GetACLResourceData(&acl.subject, &savePtr);
-    EXPECT_TRUE(NULL == subjectAcl2);
+    const OicSecAcl_t* subjectAcl2 = GetACLResourceData(&acl.subject, &savePtr);
+    ASSERT_TRUE(NULL == subjectAcl2);
 
-exit:
     // Perform cleanup
-    if(NULL != subjectAcl1)
-    {
-        DeInitACLResource();
-    }
-    OCPayloadDestroy(ehReq.payload);
+    DeInitACLResource();
     OICFree(ehReq.query);
-    OICFree(jsonStr);
-
+    OCPayloadDestroy((OCPayload *)securityPayload);
+    OICFree(payload);
 }
 
 TEST(ACLResourceTest, ACLDeleteWithMultiResourceTest)
 {
-    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
-    static OCPersistentStorage ps = OCPersistentStorage();
+    //Populate ACL
     OicSecAcl_t acl = OicSecAcl_t();
-    char *jsonStr = NULL;
-    OicSecAcl_t* savePtr = NULL;
-    const OicSecAcl_t* subjectAcl1 = NULL;
-    const OicSecAcl_t* subjectAcl2 = NULL;
-    OCEntityHandlerResult ehRet = OC_EH_ERROR;
-    char query[] = "sub=MjIyMjIyMjIyMjIyMjIyMg==;rsrc=/a/led";
+    EXPECT_EQ(OC_STACK_OK, populateAcl(&acl, 2));
 
-    SetPersistentHandler(&ps, true);
+    //GET CBOR POST payload
+    size_t size = 0;
+    uint8_t *payload = NULL;
+    EXPECT_EQ(OC_STACK_OK, AclToCBORPayload(&acl, &payload, &size));
+    ASSERT_TRUE(NULL != payload);
 
-    //Populate ACL
-    VERIFY_SUCCESS(TAG, (OC_STACK_OK == populateAcl(&acl, 2)), ERROR);
+    // Security Payload
+    OCSecurityPayload *securityPayload = OCSecurityPayloadCreate(payload, size);
+    ASSERT_TRUE(NULL!= securityPayload);
 
-    //GET json POST payload
-    jsonStr = BinToAclJSON(&acl);
-    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
+    static OCPersistentStorage ps = OCPersistentStorage();
+    SetPersistentHandler(&ps, true);
 
     // Create Entity Handler POST request payload
+    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
     ehReq.method = OC_REST_POST;
-    ehReq.payload = (OCPayload*)OCSecurityPayloadCreate(jsonStr);
-    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq);
-    EXPECT_TRUE(OC_EH_ERROR == ehRet);
+    ehReq.payload = (OCPayload *)securityPayload;
+    ACLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
 
     // Verify if SRM contains ACE for the subject with two resources
-    savePtr = NULL;
-    subjectAcl1 = GetACLResourceData(&acl.subject, &savePtr);
-    EXPECT_TRUE(NULL != subjectAcl1);
-    EXPECT_TRUE(subjectAcl1->resourcesLen == 2);
+    OicSecAcl_t* savePtr = NULL;
+    const OicSecAcl_t* subjectAcl1 = GetACLResourceData(&acl.subject, &savePtr);
+    ASSERT_TRUE(NULL != subjectAcl1);
+    EXPECT_EQ(2, subjectAcl1->resourcesLen);
 
     // Create Entity Handler DELETE request
     ehReq.method = OC_REST_DELETE;
-    ehReq.query = (char*)OICMalloc(strlen(query)+1);
-    VERIFY_NON_NULL(TAG, ehReq.query, ERROR);
+    char query[] = "subjectuuid=2222222222222222;resources=/a/led";
+    ehReq.query = (char *)OICMalloc(strlen(query)+1);
+    ASSERT_TRUE(NULL != ehReq.query);
     OICStrcpy(ehReq.query, strlen(query)+1, query);
 
-    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq);
-    EXPECT_TRUE(OC_EH_ERROR == ehRet);
+    ACLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
 
     // Verify if SRM contains ACL for the subject but only with one resource
     savePtr = NULL;
-    subjectAcl2 = GetACLResourceData(&acl.subject, &savePtr);
-    EXPECT_TRUE(NULL != subjectAcl2);
-    EXPECT_TRUE(subjectAcl2->resourcesLen == 1);
+    const OicSecAcl_t* subjectAcl2 = GetACLResourceData(&acl.subject, &savePtr);
+    ASSERT_TRUE(NULL != subjectAcl2);
+    EXPECT_EQ(1, subjectAcl2->resourcesLen);
 
-exit:
     // Perform cleanup
-    if(NULL != subjectAcl1)
-    {
-        DeInitACLResource();
-    }
-    OCPayloadDestroy(ehReq.payload);
+    OCPayloadDestroy((OCPayload *)securityPayload);
+    DeInitACLResource();
     OICFree(ehReq.query);
-    OICFree(jsonStr);
+    OICFree(payload);
 }
 
 //'GET' with query ACL test
-
 TEST(ACLResourceTest, ACLGetWithQueryTest)
 {
-    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
-    static OCPersistentStorage ps = OCPersistentStorage();
+    //Populate ACL
     OicSecAcl_t acl = OicSecAcl_t();
-    char *jsonStr = NULL;
-    OCEntityHandlerResult ehRet = OC_EH_ERROR;
-    char query[] = "sub=MjIyMjIyMjIyMjIyMjIyMg==;rsrc=/a/led";
+    EXPECT_EQ(OC_STACK_OK, populateAcl(&acl, 1));
 
-    SetPersistentHandler(&ps, true);
+    //GET CBOR POST payload
+    size_t size = 0;
+    uint8_t *payload = NULL;
+    EXPECT_EQ(OC_STACK_OK, AclToCBORPayload(&acl, &payload, &size));
+    ASSERT_TRUE(NULL != payload);
 
-    //Populate ACL
-    VERIFY_SUCCESS(TAG, (OC_STACK_OK == populateAcl(&acl, 1)), ERROR);
+    // Security Payload
+    OCSecurityPayload *securityPayload = OCSecurityPayloadCreate(payload, size);
+    ASSERT_TRUE(NULL != securityPayload);
 
-    //GET json POST payload
-    jsonStr = BinToAclJSON(&acl);
-    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
+    static OCPersistentStorage ps = OCPersistentStorage();
+    SetPersistentHandler(&ps, true);
 
     //Create Entity Handler POST request payload
+    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
     ehReq.method = OC_REST_POST;
-    ehReq.payload = (OCPayload*)OCSecurityPayloadCreate(jsonStr);
-    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq);
-    EXPECT_TRUE(OC_EH_ERROR == ehRet);
+    ehReq.payload = (OCPayload *)securityPayload;
+    ACLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
 
     //Create Entity Handler GET request wit query
-    ehReq.method =  OC_REST_GET;
+    ehReq.method = OC_REST_GET;
+    char query[] = "subjectuuid=2222222222222222;resources=/a/led";
     ehReq.query = (char*)OICMalloc(strlen(query)+1);
-    VERIFY_NON_NULL(TAG, ehReq.query, ERROR);
+    ASSERT_TRUE(NULL != ehReq.query);
     OICStrcpy(ehReq.query, strlen(query)+1, query);
 
-    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq);
-    EXPECT_TRUE(OC_EH_OK == ehRet);
+    ACLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
 
-exit:
     // Perform cleanup
-    OCPayloadDestroy(ehReq.payload);
+    OCPayloadDestroy((OCPayload *)securityPayload);
+    DeInitACLResource();
     OICFree(ehReq.query);
-    OICFree(jsonStr);
+    OICFree(payload);
 }
diff --git a/resource/csdk/security/unittest/amaclresourcetest.cpp b/resource/csdk/security/unittest/amaclresourcetest.cpp
new file mode 100644 (file)
index 0000000..5a138ef
--- /dev/null
@@ -0,0 +1,141 @@
+//******************************************************************
+//
+// 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 "cainterface.h"
+#include "ocstack.h"
+#include "ocpayload.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+#include "payload_logging.h"
+#include "psinterface.h"
+#include "secureresourcemanager.h"
+#include "securevirtualresourcetypes.h"
+#include "srmresourcestrings.h"
+#include "srmutility.h"
+#include "amaclresource.h"
+#include "security_internals.h"
+
+using namespace std;
+
+#define TAG  "SRM-AMACL-UT"
+
+TEST(AMACLResourceTest, CBORAMACLConversion)
+{
+    OicSecAmacl_t *secAmacl = (OicSecAmacl_t *) OICCalloc(1, sizeof(*secAmacl));
+    ASSERT_TRUE(NULL != secAmacl);
+    uint8_t amss[] = {0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35,
+        0x35, 0x35, 0x35, 0x35, 0x35, 0x35};
+    uint8_t amss1[] = {0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
+        0x36, 0x36, 0x36, 0x36, 0x36, 0x36};
+    secAmacl->amssLen = 2;
+    secAmacl->amss = (OicUuid_t *)OICCalloc(secAmacl->amssLen, sizeof(*secAmacl->amss));
+    if (!secAmacl->amss)
+    {
+        DeleteAmaclList(secAmacl);
+    }
+    ASSERT_TRUE(NULL != secAmacl->amss);
+    memcpy(secAmacl->amss[0].id, amss, sizeof(amss));
+    memcpy(secAmacl->amss[1].id, amss1, sizeof(amss1));
+
+    const char *rsrc[] = { "/a/led", "/a/fan"};
+    secAmacl->resourcesLen = 2;
+    secAmacl->resources = (char **)OICCalloc(secAmacl->resourcesLen,
+                          sizeof(*secAmacl->resources));
+    if (!secAmacl->resources)
+    {
+        DeleteAmaclList(secAmacl);
+    }
+    ASSERT_TRUE(NULL != secAmacl->resources);
+    for (size_t i = 0 ; i < secAmacl->resourcesLen; i++)
+    {
+        secAmacl->resources[i] = OICStrdup(rsrc[i]);
+        ASSERT_TRUE(NULL != secAmacl->resources[i]);
+    }
+    uint8_t ownrs[] = {0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
+        0x32, 0x32, 0x32, 0x32, 0x32, 0x32};
+    memcpy(secAmacl->rownerID.id, ownrs, sizeof(ownrs));
+
+    OicSecAmacl_t *secAmacl1 = (OicSecAmacl_t *) OICCalloc(1, sizeof(*secAmacl1));
+    if (!secAmacl1)
+    {
+        DeleteAmaclList(secAmacl);
+    }
+    ASSERT_TRUE(NULL != secAmacl1);
+    secAmacl1->amssLen = 2;
+    secAmacl1->amss = (OicUuid_t *)OICCalloc(2, sizeof(*secAmacl1->amss));
+    if (!secAmacl1->amss)
+    {
+        DeleteAmaclList(secAmacl);
+        DeleteAmaclList(secAmacl1);
+    }
+    ASSERT_TRUE(NULL != secAmacl1->amss);
+    memcpy(secAmacl1->amss[0].id, amss, sizeof(amss));
+    memcpy(secAmacl1->amss[1].id, amss1, sizeof(amss1));
+
+    const char *rsrc1[] = { "/b/led", "/b/fan"};
+    secAmacl1->resourcesLen = 2;
+    secAmacl1->resources = (char **)OICCalloc(secAmacl1->resourcesLen,
+                            sizeof(*secAmacl1->resources));
+    if (!secAmacl1->resources)
+    {
+        DeleteAmaclList(secAmacl);
+        DeleteAmaclList(secAmacl1);
+    }
+    ASSERT_TRUE(NULL != secAmacl1->resources);
+    for (size_t i = 0 ; i < secAmacl1->resourcesLen; i++)
+    {
+        secAmacl1->resources[i] = OICStrdup(rsrc1[i]);
+        ASSERT_TRUE(NULL != secAmacl1->resources[i]);
+    }
+    memcpy(secAmacl1->rownerID.id, ownrs, sizeof(ownrs));
+    secAmacl1->next = NULL;
+    secAmacl->next = secAmacl1;
+
+    size_t size = 0;
+    uint8_t *psStorage = NULL;
+    EXPECT_EQ(OC_STACK_OK, AmaclToCBORPayload(secAmacl, &psStorage, &size));
+    if (!psStorage)
+    {
+        DeleteAmaclList(secAmacl);
+    }
+    ASSERT_TRUE(NULL != psStorage);
+
+    OicSecAmacl_t *amacl = NULL;
+    EXPECT_EQ(OC_STACK_OK, CBORPayloadToAmacl(psStorage, size, &amacl));
+    if (!amacl)
+    {
+        DeleteAmaclList(secAmacl);
+        OICFree(psStorage);
+    }
+    ASSERT_TRUE(NULL != amacl);
+
+    EXPECT_EQ(secAmacl->amssLen, amacl->amssLen);
+    EXPECT_EQ(sizeof(secAmacl->amss[0].id), sizeof(amacl->amss[0].id));
+    EXPECT_EQ(sizeof(secAmacl->amss[1].id), sizeof(amacl->amss[1].id));
+    EXPECT_STREQ(secAmacl->resources[0], amacl->resources[0]);
+    EXPECT_STREQ(secAmacl->resources[1], amacl->resources[1]);
+    EXPECT_EQ(secAmacl->resourcesLen, amacl->resourcesLen);
+    EXPECT_EQ(memcmp(secAmacl->rownerID.id, amacl->rownerID.id, sizeof(amacl->rownerID.id)), 0);
+
+    DeleteAmaclList(secAmacl);
+    DeleteAmaclList(amacl);
+    OICFree(psStorage);
+}
index 4cce483..68e30e2 100644 (file)
@@ -186,7 +186,7 @@ TEST(B64DeodeTest, ValidInputForDecoding)
 // Tests for base64 decode function
 TEST(B64DeodeTest, InvalidInputForDecoding)
 {
-    uint8_t buf[128];
+    uint8_t buf[128] = {0,};
     uint32_t outputLength;
     uint32_t i=0;
 
index 5421efe..fd63aa1 100644 (file)
@@ -1,3 +1,5 @@
+//******************************************************************
+//
 // Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include "gtest/gtest.h"
-#include "ocstack.h"
+#include "logger.h"
 #include "ocpayload.h"
-#include "resourcemanager.h"
-#include "securevirtualresourcetypes.h"
-#include "credresource.h"
+#include "ocstack.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
+#include "resourcemanager.h"
+#include "credresource.h"
+#include "securevirtualresourcetypes.h"
 #include "srmtestcommon.h"
 #include "srmutility.h"
-#include "logger.h"
+#include "psinterface.h"
+#include "security_internals.h"
 
 #define TAG "SRM-CRED-UT"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-//Declare Cred resource methods for testing
-OCStackResult CreateCredResource();
-OCEntityHandlerResult CredEntityHandler (OCEntityHandlerFlag flag,
-                OCEntityHandlerRequest * ehRequest);
-char * BinToCredJSON(const OicSecCred_t * pstat);
-OicSecCred_t * JSONToCredBin(const char * jsonStr);
-void InitSecCredInstance(OicSecCred_t * cred);
-void DeleteCredList(OicSecCred_t* cred);
-const OicSecCred_t* GetCredResourceData(const OicUuid_t* subject);
-
-#ifdef __cplusplus
-}
-#endif
-
-
 OicSecCred_t * getCredList()
 {
-
-    OicSecCred_t * cred = NULL;
     size_t sz = 0;
-
-    cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
+    OicSecCred_t *cred = (OicSecCred_t *)OICCalloc(1, sizeof(*cred));
     VERIFY_NON_NULL(TAG, cred, ERROR);
     cred->credId = 1234;
-    OICStrcpy((char *)cred->subject.id, sizeof(cred->subject.id), "subject1");
+    // use |memcpy| for copying full-lengthed UUID without null termination
+    memcpy(cred->subject.id, "1111111111111111", sizeof(cred->subject.id));
 
 #if 0
     cred->roleIdsLen = 2;
@@ -66,41 +49,35 @@ OicSecCred_t * getCredList()
     VERIFY_NON_NULL(TAG, cred->roleIds, ERROR);
     OICStrcpy((char *)cred->roleIds[0].id, sizeof(cred->roleIds[0].id), "role11");
     OICStrcpy((char *)cred->roleIds[1].id, sizeof(cred->roleIds[1].id), "role12");
-
 #endif
 
     cred->credType = SYMMETRIC_PAIR_WISE_KEY;
-    cred->privateData.data = (char *)OICCalloc(1, strlen("My private Key11") + 1);
+    cred->privateData.data = (uint8_t *)OICCalloc(1, strlen("My private Key11") + 1);
     VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
-    strcpy(cred->privateData.data, "My private Key11");
-    cred->ownersLen = 1;
-    cred->owners = (OicUuid_t*)OICCalloc(cred->ownersLen, sizeof(OicUuid_t));
-    VERIFY_NON_NULL(TAG, cred->owners, ERROR);
-    OICStrcpy((char *)cred->owners[0].id, sizeof(cred->owners[0].id), "ownersId11");
-
-    cred->next = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
+    OICStrcpy((char *)cred->privateData.data, strlen("My private Key11")+1,"My private Key11");
+    // use |memcpy| for copying full-lengthed UUID without null termination
+    memcpy(cred->rownerID.id, "aaaaaaaaaaaaaaaa", sizeof(cred->rownerID.id));
+    cred->next = (OicSecCred_t*)OICCalloc(1, sizeof(*cred->next));
     VERIFY_NON_NULL(TAG, cred->next, ERROR);
     cred->next->credId = 5678;
-    OICStrcpy((char *)cred->next->subject.id, sizeof(cred->next->subject.id), "subject2");
+    // use |memcpy| for copying full-lengthed UUID without null termination
+    memcpy(cred->next->subject.id, "2222222222222222", sizeof(cred->next->subject.id));
 #if 0
     cred->next->roleIdsLen = 0;
 #endif
     cred->next->credType = SYMMETRIC_PAIR_WISE_KEY;
     sz = strlen("My private Key21") + 1;
-    cred->next->privateData.data = (char *)OICCalloc(1, sz);
+    cred->next->privateData.data = (uint8_t *)OICCalloc(1, sz);
     VERIFY_NON_NULL(TAG, cred->next->privateData.data, ERROR);
-    OICStrcpy(cred->next->privateData.data, sz,"My private Key21");
+    OICStrcpy((char *)cred->next->privateData.data, sz, "My private Key21");
 #if 0
-    sz = strlen("My Public Key123") + 1
+    sz = strlen("My Public Key123") + 1;
     cred->next->publicData.data = (char *)OICCalloc(1, sz);
     VERIFY_NON_NULL(TAG, cred->next->publicData.data, ERROR);
     OICStrcpy(cred->next->publicData.data, sz,"My Public Key123");
 #endif
-    cred->next->ownersLen = 2;
-    cred->next->owners = (OicUuid_t*)OICCalloc(cred->next->ownersLen, sizeof(OicUuid_t));
-    VERIFY_NON_NULL(TAG, cred->next->owners, ERROR);
-    OICStrcpy((char *)cred->next->owners[0].id, sizeof(cred->next->owners[0].id), "ownersId21");
-    OICStrcpy((char *)cred->next->owners[1].id, sizeof(cred->next->owners[1].id), "ownersId22");
+    // use |memcpy| for copying full-lengthed UUID without null termination
+    memcpy(cred->next->rownerID.id, "bbbbbbbbbbbbbbbb", sizeof(cred->next->rownerID.id));
 
     return cred;
 
@@ -118,223 +95,259 @@ static void printCred(const OicSecCred_t * cred)
     EXPECT_TRUE(NULL != cred);
 
     const OicSecCred_t *credTmp1 = NULL;
-    for(credTmp1 = cred; credTmp1; credTmp1 = credTmp1->next)
+    for (credTmp1 = cred; credTmp1; credTmp1 = credTmp1->next)
     {
-        OC_LOG_V(INFO, TAG, "\ncred->credId = %d", credTmp1->credId);
-        OC_LOG_V(INFO, TAG, "cred->subject.id = %s", credTmp1->subject.id);
-        OC_LOG_V(INFO, TAG, "cred->credType = %d", credTmp1->credType);
+        OIC_LOG_V(INFO, TAG, "\ncred->credId = %d", credTmp1->credId);
+        OIC_LOG_V(INFO, TAG, "cred->subject.id = %s", credTmp1->subject.id);
+        OIC_LOG_V(INFO, TAG, "cred->credType = %d", credTmp1->credType);
         if(credTmp1->privateData.data)
         {
-            OC_LOG_V(INFO, TAG, "cred->privateData.data = %s", credTmp1->privateData.data);
+            OIC_LOG_V(INFO, TAG, "cred->privateData.data = %s", credTmp1->privateData.data);
         }
+#ifdef __WITH_X509__
         if(credTmp1->publicData.data)
         {
-           OC_LOG_V(INFO, TAG, "cred->publicData.data = %s", credTmp1->publicData.data);
-        }
-        OC_LOG_V(INFO, TAG, "cred->ownersLen = %zd", credTmp1->ownersLen);
-        for(size_t i = 0; i < cred->ownersLen; i++)
-        {
-            OC_LOG_V(INFO, TAG, "cred->owners[%zd].id = %s", i, credTmp1->owners[i].id);
+           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);
     }
 }
 
  //InitCredResource Tests
-TEST(InitCredResourceTest, InitCredResource)
+TEST(CredResourceTest, InitCredResource)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, InitCredResource());
 }
 
 //DeInitCredResource Tests
-TEST(DeInitCredResourceTest, DeInitCredResource)
+TEST(CredResourceTest, DeInitCredResource)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, DeInitCredResource());
 }
 
 //CreateCredResource Tests
-TEST(CreateCredResourceTest, CreateCredResource)
+TEST(CredResourceTest, CreateCredResource)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, CreateCredResource());
 }
 
  //CredEntityHandler Tests
-TEST(CredEntityHandlerTest, CredEntityHandlerWithDummyRequest)
+TEST(CredResourceTest, CredEntityHandlerWithDummyRequest)
 {
-    OCEntityHandlerRequest req;
+    OCEntityHandlerRequest req = OCEntityHandlerRequest();
     EXPECT_EQ(OC_EH_ERROR,
-            CredEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req));
+            CredEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req, NULL));
 }
 
-TEST(CredEntityHandlerTest, CredEntityHandlerWithNULLRequest)
+TEST(CredResourceTest, CredEntityHandlerWithNULLRequest)
 {
     EXPECT_EQ(OC_EH_ERROR,
-            CredEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, NULL));
+            CredEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, NULL, NULL));
 }
 
-TEST(CredEntityHandlerTest, CredEntityHandlerInvalidFlag)
+TEST(CredResourceTest, CredEntityHandlerInvalidFlag)
 {
-    OCEntityHandlerRequest req;
+    OCEntityHandlerRequest req = OCEntityHandlerRequest();
     EXPECT_EQ(OC_EH_ERROR,
-            CredEntityHandler(OCEntityHandlerFlag::OC_OBSERVE_FLAG, &req));
+            CredEntityHandler(OCEntityHandlerFlag::OC_OBSERVE_FLAG, &req, NULL));
 }
 
 //Cred DELETE request
-TEST(CredEntityHandlerTest, CredEntityHandlerDeleteTest)
+TEST(CredResourceTest, CredEntityHandlerDeleteTest)
 {
     OCEntityHandlerRequest ehReq =  OCEntityHandlerRequest();
     static OCPersistentStorage ps =  OCPersistentStorage();
     const OicSecCred_t* subjectCred1 = NULL;
     const OicSecCred_t* subjectCred2 = NULL;
-    char *jsonStr = NULL;
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
-    char query[] = "sub=c3ViamVjdDE=";
+    char query[] = "subjectuuid=31313131-3131-3131-3131-313131313131"; //canonical uuid of subject1
 
     SetPersistentHandler(&ps, true);
 
     OicSecCred_t *cred = getCredList();
-    VERIFY_NON_NULL(TAG, cred, ERROR);
-
-    jsonStr = BinToCredJSON(cred);
-    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
+    ASSERT_TRUE(NULL != cred);
+    uint8_t *payload = NULL;
+    size_t size = 0;
+    EXPECT_EQ(OC_STACK_OK, CredToCBORPayload(cred, &payload, &size));
+    if (!payload)
+    {
+        DeleteCredList(cred);
+    }
+    ASSERT_TRUE(NULL != payload);
 
     // Create Entity Handler POST request payload
     ehReq.method = OC_REST_POST;
-    ehReq.payload = (OCPayload*)OCSecurityPayloadCreate(jsonStr);
-    ehRet = CredEntityHandler(OC_REQUEST_FLAG, &ehReq);
-    EXPECT_TRUE(OC_EH_ERROR == ehRet);
+    ehReq.payload = (OCPayload *)OCSecurityPayloadCreate(payload, size);
+    if (!ehReq.payload)
+    {
+        OICFree(payload);
+        DeleteCredList(cred);
+    }
+    ASSERT_TRUE( NULL != ehReq.payload);
+    EXPECT_EQ(OC_EH_ERROR, CredEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL));
 
     // Verify if SRM contains Credential for the subject
     subjectCred1 = GetCredResourceData(&cred->subject);
     EXPECT_TRUE(NULL != subjectCred1);
 
-   // Create Entity Handler DELETE request
-   ehReq.method = OC_REST_DELETE;
-   ehReq.query = (char*)OICMalloc(strlen(query)+1);
-   VERIFY_NON_NULL(TAG, ehReq.query, ERROR);
-   OICStrcpy(ehReq.query, strlen(query)+1, query);
+    // Create Entity Handler DELETE request
+    ehReq.method = OC_REST_DELETE;
+    ehReq.query = (char *)OICCalloc(1, strlen(query)+1);
+    if (!ehReq.query)
+    {
+        OICFree(payload);
+        DeleteCredList(cred);
+    }
+    ASSERT_TRUE(NULL != ehReq.query);
+    OICStrcpy(ehReq.query, strlen(query)+1, query);
 
-   ehRet = CredEntityHandler(OC_REQUEST_FLAG, &ehReq);
-   EXPECT_TRUE(OC_EH_ERROR == ehRet);
+    ehRet = CredEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
+    EXPECT_EQ(OC_EH_ERROR, ehRet);
 
-   // Verify if SRM has deleted ACE for the subject
-   subjectCred2 = GetCredResourceData(&cred->subject);
-   EXPECT_TRUE(NULL == subjectCred2);
+    // Verify if SRM has deleted ACE for the subject
+    subjectCred2 = GetCredResourceData(&cred->subject);
+    EXPECT_TRUE(NULL == subjectCred2);
 
-exit:
-   // Perform cleanup
-   OICFree(ehReq.query);
-   OICFree(jsonStr);
-   OCPayloadDestroy(ehReq.payload);
-   if(NULL != cred)
-   {
-       DeInitCredResource();
-       DeleteCredList(cred);
-   }
+    // Perform cleanup
+    OICFree(ehReq.query);
+    OICFree(payload);
+    DeInitCredResource();
+    DeleteCredList(cred);
+    OCPayloadDestroy((OCPayload *)ehReq.payload);
 }
 
-//BinToCredJSON Tests
-TEST(BinToCredJSONTest, BinToCredJSONNullCred)
+TEST(CredResourceTest, CredToCBORPayloadNULL)
 {
-    char* value = BinToCredJSON(NULL);
-    EXPECT_TRUE(value == NULL);
+    OicSecCred_t *cred = getCredList();
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(NULL, NULL, 0));
+    size_t size = 0;
+    uint8_t *cborPayload = (uint8_t *) OICCalloc(1, 10);
+    if (!cborPayload)
+    {
+        DeleteCredList(cred);
+    }
+    ASSERT_TRUE(NULL != cborPayload);
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(cred, &cborPayload, &size));
+    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));
+    DeleteCredList(cred);
 }
 
-TEST(BinToCredJSONTest, BinToCredJSONValidCred)
+TEST(CredResourceTest, CredToCBORPayloadVALID)
 {
-    char* json = NULL;
-    OicSecCred_t * cred = getCredList();
+    uint8_t* payload = NULL;
+    size_t size = 0;
+    OicSecCred_t *cred = getCredList();
 
-    json = BinToCredJSON(cred);
+    EXPECT_EQ(OC_STACK_OK, CredToCBORPayload(cred, &payload, &size));
+    if (!payload)
+    {
+        DeleteCredList(cred);
+    }
+    ASSERT_TRUE(NULL != payload);
 
-    OC_LOG_V(INFO, TAG, "BinToCredJSON:%s\n", json);
-    EXPECT_TRUE(json != NULL);
     DeleteCredList(cred);
-    OICFree(json);
+    OICFree(payload);
 }
 
-//JSONToCredBin Tests
-TEST(JSONToCredBinTest, JSONToCredBinValidJSON)
+TEST(CredResourceTest, CBORPayloadToCredVALID)
 {
-    OicSecCred_t* cred1 = getCredList();
-    char* json = BinToCredJSON(cred1);
+    OicSecCred_t *cred1 = getCredList();
 
-    EXPECT_TRUE(json != NULL);
-    OicSecCred_t *cred2 = JSONToCredBin(json);
-    EXPECT_TRUE(cred2 != NULL);
+    uint8_t *payload = NULL;
+    size_t size = 0;
+    EXPECT_EQ(OC_STACK_OK, CredToCBORPayload(cred1, &payload, &size));
     DeleteCredList(cred1);
+    ASSERT_TRUE(NULL != payload);
+
+    OicSecCred_t *cred2 = NULL;
+    EXPECT_EQ(OC_STACK_OK, CBORPayloadToCred(payload, size, &cred2));
+    OICFree(payload);
+    ASSERT_TRUE(cred2 != NULL);
     DeleteCredList(cred2);
-    OICFree(json);
 }
 
-TEST(JSONToCredBinTest, JSONToCredBinNullJSON)
+TEST(CredResourceTest, CBORPayloadToCredNULL)
 {
-    OicSecCred_t *cred = JSONToCredBin(NULL);
-    EXPECT_TRUE(cred == NULL);
+    OicSecCred_t *cred = NULL;
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToCred(NULL, 0, NULL));
+    uint8_t *cborPayload = (uint8_t *) OICCalloc(1, 10);
+    ASSERT_TRUE(NULL != cborPayload);
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToCred(NULL, 0, &cred));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToCred(cborPayload, 0, NULL));
+    cred = getCredList();
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToCred(cborPayload, 0, &cred));
+    DeleteCredList(cred);
+    OICFree(cborPayload);
 }
 
 //GetCredResourceData Test
-TEST(CredGetResourceDataTest, GetCredResourceDataNULLSubject)
+TEST(CredResourceTest, GetCredResourceDataNULLSubject)
 {
-    EXPECT_TRUE(NULL == GetCredResourceData(NULL));
+    EXPECT_EQ(NULL, GetCredResourceData(NULL));
 }
 
-TEST(CredGenerateCredentialTest, GenerateCredentialValidInput)
+TEST(CredResourceTest, GenerateCredentialValidInput)
 {
-    OicUuid_t owners[1];
-    OICStrcpy((char *)owners[0].id, sizeof(owners[0].id), "ownersId21");
+    OicUuid_t rownerID = {{0}};
+    OICStrcpy((char *)rownerID.id, sizeof(rownerID.id), "ownersId21");
 
     OicUuid_t subject = {{0}};
     OICStrcpy((char *)subject.id, sizeof(subject.id), "subject11");
 
-    char privateKey[] = "My private Key11";
+    uint8_t privateKey[] = "My private Key11";
+    OicSecKey_t key = {privateKey, sizeof(privateKey)};
 
     OicSecCred_t * cred  = NULL;
-
     cred = GenerateCredential(&subject, SYMMETRIC_PAIR_WISE_KEY, NULL,
-                             privateKey, 1, owners);
+                              &key, &rownerID);
     printCred(cred);
 
-    EXPECT_TRUE(NULL != cred);
+    ASSERT_TRUE(NULL != cred);
     DeleteCredList(cred);
 }
 
-TEST(GenerateAndAddCredentialTest, GenerateAndAddCredentialValidInput)
+TEST(CredResourceTest, GenerateAndAddCredentialValidInput)
 {
-    OicUuid_t owners[1];
-    OICStrcpy((char *)owners[0].id, sizeof(owners[0].id), "ownersId11");
+    OicUuid_t rownerID = {{0}};
+    OICStrcpy((char *)rownerID.id, sizeof(rownerID.id), "ownersId11");
 
     OicUuid_t subject = {{0}};
     OICStrcpy((char *)subject.id, sizeof(subject.id), "subject11");
 
-    char privateKey[] = "My private Key11";
+    uint8_t privateKey[] = "My private Key11";
+    OicSecKey_t key = {privateKey, sizeof(privateKey)};
 
-    OicSecCred_t * cred1  = NULL;
-    OicSecCred_t * headCred = NULL;
+    OicSecCred_t *cred1  = NULL;
+    OicSecCred_t *headCred = NULL;
 
     cred1 = GenerateCredential(&subject, SYMMETRIC_PAIR_WISE_KEY, NULL,
-                                 privateKey, 1, owners);
+                               &key, &rownerID);
 
-    EXPECT_EQ(OC_STACK_ERROR, AddCredential(cred1));
+    EXPECT_EQ(OC_STACK_OK, AddCredential(cred1));
     headCred = cred1;
 
-    OICStrcpy((char *)owners[0].id, sizeof(owners[0].id), "ownersId22");
+    OICStrcpy((char *)rownerID.id, sizeof(rownerID.id), "ownersId22");
     OICStrcpy((char *)subject.id, sizeof(subject.id), "subject22");
     cred1 = GenerateCredential(&subject, SYMMETRIC_PAIR_WISE_KEY, NULL,
-                                     privateKey, 1, owners);
-    EXPECT_EQ(OC_STACK_ERROR, AddCredential(cred1));
+                               &key, &rownerID);
+    EXPECT_EQ(OC_STACK_OK, AddCredential(cred1));
 
-    OICStrcpy((char *)owners[0].id, sizeof(owners[0].id), "ownersId33");
+    OICStrcpy((char *)rownerID.id, sizeof(rownerID.id), "ownersId33");
     OICStrcpy((char *)subject.id, sizeof(subject.id), "subject33");
     cred1 = GenerateCredential(&subject, SYMMETRIC_PAIR_WISE_KEY, NULL,
-                                     privateKey, 1, owners);
-    EXPECT_EQ(OC_STACK_ERROR, AddCredential(cred1));
+                               &key, &rownerID);
+    EXPECT_EQ(OC_STACK_OK, AddCredential(cred1));
 
     const OicSecCred_t* credList = GetCredResourceData(&headCred->subject);
 
     printCred(credList);
 
     DeleteCredList(headCred);
-
 }
 
 #if 0
@@ -344,5 +357,3 @@ TEST(CredGetResourceDataTest, GetCredResourceDataValidSubject)
     EXPECT_TRUE(NULL != GetCredResourceData(cred->subject));
 }
 #endif
-
-
diff --git a/resource/csdk/security/unittest/directpairingtest.cpp b/resource/csdk/security/unittest/directpairingtest.cpp
new file mode 100644 (file)
index 0000000..5c49a21
--- /dev/null
@@ -0,0 +1,48 @@
+//******************************************************************
+//
+// 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 "gtest/gtest.h"
+#include "directpairing.h"
+
+using namespace std;
+
+#define TAG  "DIRECTPAIRING-UT"
+
+static OCDirectPairingDev_t peer;
+static OicSecPrm_t pmSel;
+static char pinNumber;
+
+static void ResultCB(OCDirectPairingDev_t *UNUSED1, OCStackResult UNUSED2)
+{
+    //dummy callback
+    (void) UNUSED1;
+    (void) UNUSED2;
+}
+
+TEST(DPDirectPairingTest, NullPeer)
+{
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, DPDirectPairing(NULL, pmSel, &pinNumber, &ResultCB));
+}
+
+TEST(DPDirectPairingTest, NullPinNumber)
+{
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, DPDirectPairing(&peer, pmSel, NULL, &ResultCB));
+}
+
index f2de1dd..bdab373 100644 (file)
@@ -1,3 +1,5 @@
+//******************************************************************
+//
 // Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include "gtest/gtest.h"
 #include "ocstack.h"
+#include "ocserverrequest.h"
+#include "oic_string.h"
+#include "oic_malloc.h"
 #include "resourcemanager.h"
 #include "securevirtualresourcetypes.h"
 #include "srmresourcestrings.h"
 #include "doxmresource.h"
-#include "ocserverrequest.h"
-#include "oic_string.h"
-#include "oic_malloc.h"
-#include "logger.h"
+#include "security_internals.h"
 
 #define TAG  "SRM-DOXM"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-//Declare Doxm resource methods for testing
-OCStackResult CreateDoxmResource();
-OCEntityHandlerResult DoxmEntityHandler (OCEntityHandlerFlag flag,
-                OCEntityHandlerRequest * ehRequest);
-char * BinToDoxmJSON(const OicSecDoxm_t * doxm);
-OicSecDoxm_t * JSONToDoxmBin(const char * jsonStr);
-void InitSecDoxmInstance(OicSecDoxm_t * doxm);
-OCEntityHandlerResult HandleDoxmPostRequest (const OCEntityHandlerRequest * ehRequest);
-void DeleteDoxmBinData(OicSecDoxm_t* doxm);
-OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest);
-#ifdef __cplusplus
-}
-#endif
-
-
 OicSecDoxm_t * getBinDoxm()
 {
-    OicSecDoxm_t * doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t));
-    if(!doxm)
+    OicSecDoxm_t *doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(*doxm));
+    if (!doxm)
     {
         return NULL;
     }
     doxm->oxmTypeLen =  1;
-    doxm->oxmType    = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(char *));
-    if(!doxm->oxmType)
+    doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(*doxm->oxmType));
+    if (!doxm->oxmType)
     {
         OICFree(doxm);
         return NULL;
     }
-    doxm->oxmType[0] = (char*)OICMalloc(strlen(OXM_JUST_WORKS) + 1);
-    if(!doxm->oxmType[0])
+    doxm->oxmType[0] = (char *) OICMalloc(strlen(OXM_JUST_WORKS) + 1);
+    if (!doxm->oxmType[0])
     {
         OICFree(doxm->oxmType);
         OICFree(doxm);
         return NULL;
     }
 
-    strcpy(doxm->oxmType[0], OXM_JUST_WORKS);
+    OICStrcpy(doxm->oxmType[0], strlen(OXM_JUST_WORKS) + 1, OXM_JUST_WORKS);
     doxm->oxmLen     = 1;
     doxm->oxm        = (OicSecOxm_t *)OICCalloc(doxm->oxmLen, sizeof(OicSecOxm_t));
     if(!doxm->oxm)
@@ -88,109 +70,134 @@ OicSecDoxm_t * getBinDoxm()
     doxm->owned      = true;
     //TODO: Need more clarification on deviceIDFormat field type.
     //doxm.deviceIDFormat = URN;
-    strcpy((char *) doxm->deviceID.id, "deviceId");
-    strcpy((char *)doxm->owner.id, "ownersId");
+
+    uint8_t deviceId[] = {0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x49, 0x64};
+    memcpy(doxm->deviceID.id, deviceId, sizeof(deviceId));
+    uint8_t ownerId[] = {0x6f, 0x77, 0x6e, 0x65, 0x72, 0x73, 0x49, 0x64};
+    memcpy(doxm->owner.id, ownerId, sizeof(ownerId));
     return doxm;
 }
 
  //InitDoxmResource Tests
-TEST(InitDoxmResourceTest, InitDoxmResource)
+TEST(DoxmResourceTest, InitDoxmResource)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, InitDoxmResource());
 }
 
 //DeInitDoxmResource Tests
-TEST(DeInitDoxmResourceTest, DeInitDoxmResource)
+TEST(DoxmResourceTest, DeInitDoxmResource)
 {
     EXPECT_EQ(OC_STACK_ERROR, DeInitDoxmResource());
 }
 
 //CreateDoxmResource Tests
-TEST(CreateDoxmResourceTest, CreateDoxmResource)
+TEST(DoxmResourceTest, CreateDoxmResource)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, CreateDoxmResource());
 }
 
  //DoxmEntityHandler Tests
-TEST(DoxmEntityHandlerTest, DoxmEntityHandlerWithDummyRequest)
+TEST(DoxmResourceTest, DoxmEntityHandlerWithDummyRequest)
 {
-    OCEntityHandlerRequest req;
-    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req));
+    OCEntityHandlerRequest req = OCEntityHandlerRequest();
+    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req, NULL));
 }
 
-TEST(DoxmEntityHandlerTest, DoxmEntityHandlerWithNULLRequest)
+TEST(DoxmResourceTest, DoxmEntityHandlerWithNULLRequest)
 {
-    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, NULL));
+    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, NULL, NULL));
 }
 
-TEST(DoxmEntityHandlerTest, DoxmEntityHandlerInvalidFlag)
+TEST(DoxmResourceTest, DoxmEntityHandlerInvalidFlag)
 {
-    OCEntityHandlerRequest req;
-    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_OBSERVE_FLAG, &req));
+    OCEntityHandlerRequest req = OCEntityHandlerRequest();
+    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_OBSERVE_FLAG, &req, NULL));
 }
 
-TEST(DoxmEntityHandlerTest, DoxmEntityHandlerValidRequest)
+TEST(DoxmResourceTest, DoxmEntityHandlerValidRequest)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, InitDoxmResource());
     char query[] = "oxm=0;owned=false;owner=owner1";
     OCEntityHandlerRequest req = OCEntityHandlerRequest();
     req.method = OC_REST_GET;
     req.query = OICStrdup(query);
-    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req));
+    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req, NULL));
 
     OICFree(req.query);
 }
 
-TEST(DoxmEntityHandlerTest, DoxmEntityHandlerDeviceIdQuery)
+TEST(DoxmResourceTest, DoxmEntityHandlerDeviceIdQuery)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, InitDoxmResource());
-    char query[] = "deviceid=MjIyMjIyMjIyMjIyMjIyMg==";
+    char query[] = "deviceuuid=2222222222222222";
     OCEntityHandlerRequest req = OCEntityHandlerRequest();
     req.method = OC_REST_GET;
     req.query = OICStrdup(query);
-    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req));
+    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req, NULL));
 
     OICFree(req.query);
 }
 
-//BinToDoxmJSON Tests
-TEST(BinToDoxmJSONTest, BinToDoxmJSONNullDoxm)
+TEST(DoxmResourceTest, DoxmToCBORPayloadNULL)
 {
-    char* value = BinToDoxmJSON(NULL);
-    EXPECT_TRUE(value == NULL);
+    OicSecDoxm_t *doxm =  getBinDoxm();
+    size_t size = 10;
+    uint8_t *payload = NULL;
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, DoxmToCBORPayload(NULL, NULL, 0));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, DoxmToCBORPayload(doxm, NULL, &size));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, DoxmToCBORPayload(doxm, &payload, 0));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, DoxmToCBORPayload(NULL, &payload, &size));
+    DeleteDoxmBinData(doxm);
 }
 
-TEST(BinToDoxmJSONTest, BinToDoxmJSONValidDoxm)
+TEST(DoxmResourceTest, DoxmToCBORPayloadVALID)
 {
-    OicSecDoxm_t * doxm =  getBinDoxm();
+    OicSecDoxm_t *doxm =  getBinDoxm();
 
-    char * json = BinToDoxmJSON(doxm);
-    OC_LOG_V(INFO, TAG, "BinToDoxmJSON:%s", json);
-    EXPECT_TRUE(json != NULL);
+    uint8_t *payload = NULL;
+    size_t size = 0;
+    EXPECT_EQ(OC_STACK_OK, DoxmToCBORPayload(doxm, &payload, &size));
+    EXPECT_TRUE(payload != NULL);
 
     DeleteDoxmBinData(doxm);
-    OICFree(json);
+    OICFree(payload);
 }
 
-//JSONToDoxmBin Tests
-TEST(JSONToDoxmBinTest, JSONToDoxmBinValidJSON)
+//CBORPayloadToDoxm Tests
+TEST(DoxmResourceTest, CBORPayloadToDoxmNULL)
 {
-    OicSecDoxm_t * doxm1 =  getBinDoxm();
-    char * json = BinToDoxmJSON(doxm1);
-    EXPECT_TRUE(json != NULL);
-
-    OicSecDoxm_t *doxm2 = JSONToDoxmBin(json);
-    EXPECT_TRUE(doxm2 != NULL);
-
-    DeleteDoxmBinData(doxm1);
-    DeleteDoxmBinData(doxm2);
-    OICFree(json);
+    OicSecDoxm_t *doxm = NULL;
+    uint8_t *cborPayload = (uint8_t *)OICCalloc(1, sizeof(uint8_t));
+    size_t size = 10;
+    ASSERT_TRUE(NULL != cborPayload);
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToDoxm(NULL, 0, NULL));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToDoxm(NULL, size, &doxm));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToDoxm(cborPayload, size, NULL));
+    OICFree(cborPayload);
 }
 
-TEST(JSONToDoxmBinTest, JSONToDoxmBinNullJSON)
+TEST(DoxmResourceTest, CBORPayloadToDoxmVALID)
 {
-    OicSecDoxm_t *doxm = JSONToDoxmBin(NULL);
-    EXPECT_TRUE(doxm == NULL);
+    OicSecDoxm_t *doxm =  getBinDoxm();
+    uint8_t *payload = NULL;
+    size_t size = 0;
+    EXPECT_EQ(OC_STACK_OK, DoxmToCBORPayload(doxm, &payload, &size));
+    EXPECT_TRUE(payload != NULL);
+
+    OicSecDoxm_t *doxmSec = NULL;
+    EXPECT_EQ(OC_STACK_OK, CBORPayloadToDoxm(payload, size, &doxmSec));
+    ASSERT_TRUE(doxmSec != NULL);
+    EXPECT_EQ(doxmSec->oxmTypeLen, doxm->oxmTypeLen);
+    EXPECT_STREQ(doxmSec->oxmType[0], doxm->oxmType[0]);
+    EXPECT_EQ(doxmSec->oxmLen, doxm->oxmLen);
+    EXPECT_EQ(doxmSec->oxm[0], doxm->oxm[0]);
+    EXPECT_EQ(doxmSec->oxmSel, doxm->oxmSel);
+    EXPECT_EQ(doxmSec->sct, doxm->sct);
+    EXPECT_EQ(doxmSec->owned, doxm->owned);
+
+    DeleteDoxmBinData(doxmSec);
+    DeleteDoxmBinData(doxm);
+    OICFree(payload);
 }
 
 #if 0
index 5fc0931..6c1c20d 100644 (file)
@@ -32,56 +32,56 @@ static void printPeriod(IotvtICalPeriod_t *period)
         return;
     }
 
-    OC_LOG_V(INFO, TAG, "period->startDateTime.tm_year = %d",period->startDateTime.tm_year);
-    OC_LOG_V(INFO, TAG, "period->startDateTime.tm_mon = %d",period->startDateTime.tm_mon);
-    OC_LOG_V(INFO, TAG, "period->startDateTime.tm_mday = %d",period->startDateTime.tm_mday);
-    OC_LOG_V(INFO, TAG, "period->startDateTime.tm_hour = %d",period->startDateTime.tm_hour);
-    OC_LOG_V(INFO, TAG, "period->startDateTime.tm_min = %d",period->startDateTime.tm_min);
-    OC_LOG_V(INFO, TAG, "period->startDateTime.tm_sec = %d",period->startDateTime.tm_sec);
-
-    OC_LOG_V(INFO, TAG, "period->endDateTime.tm_year = %d",period->endDateTime.tm_year);
-    OC_LOG_V(INFO, TAG, "period->endDateTime.tm_mon = %d",period->endDateTime.tm_mon);
-    OC_LOG_V(INFO, TAG, "period->endDateTime.tm_mday = %d",period->endDateTime.tm_mday);
-    OC_LOG_V(INFO, TAG, "period->endDateTime.tm_hour = %d",period->endDateTime.tm_hour);
-    OC_LOG_V(INFO, TAG, "period->endDateTime.tm_min = %d",period->endDateTime.tm_min);
-    OC_LOG_V(INFO, TAG, "period->startDateTime.tm_sec = %d",period->endDateTime.tm_sec);
+    OIC_LOG_V(INFO, TAG, "period->startDateTime.tm_year = %d",period->startDateTime.tm_year);
+    OIC_LOG_V(INFO, TAG, "period->startDateTime.tm_mon = %d",period->startDateTime.tm_mon);
+    OIC_LOG_V(INFO, TAG, "period->startDateTime.tm_mday = %d",period->startDateTime.tm_mday);
+    OIC_LOG_V(INFO, TAG, "period->startDateTime.tm_hour = %d",period->startDateTime.tm_hour);
+    OIC_LOG_V(INFO, TAG, "period->startDateTime.tm_min = %d",period->startDateTime.tm_min);
+    OIC_LOG_V(INFO, TAG, "period->startDateTime.tm_sec = %d",period->startDateTime.tm_sec);
+
+    OIC_LOG_V(INFO, TAG, "period->endDateTime.tm_year = %d",period->endDateTime.tm_year);
+    OIC_LOG_V(INFO, TAG, "period->endDateTime.tm_mon = %d",period->endDateTime.tm_mon);
+    OIC_LOG_V(INFO, TAG, "period->endDateTime.tm_mday = %d",period->endDateTime.tm_mday);
+    OIC_LOG_V(INFO, TAG, "period->endDateTime.tm_hour = %d",period->endDateTime.tm_hour);
+    OIC_LOG_V(INFO, TAG, "period->endDateTime.tm_min = %d",period->endDateTime.tm_min);
+    OIC_LOG_V(INFO, TAG, "period->startDateTime.tm_sec = %d",period->endDateTime.tm_sec);
 }
 
 
 static void printRecur(IotvtICalRecur_t *recur)
 {
-    OC_LOG_V(INFO, TAG, "recur->freq = %d", recur->freq);
-    OC_LOG_V(INFO, TAG, "recur->until.tm_year = %d", recur->until.tm_year);
-    OC_LOG_V(INFO, TAG, "recur->until.tm_mon = %d", recur->until.tm_mon);
-    OC_LOG_V(INFO, TAG, "recur->until.tm_mday = %d", recur->until.tm_mday);
+    OIC_LOG_V(INFO, TAG, "recur->freq = %d", recur->freq);
+    OIC_LOG_V(INFO, TAG, "recur->until.tm_year = %d", recur->until.tm_year);
+    OIC_LOG_V(INFO, TAG, "recur->until.tm_mon = %d", recur->until.tm_mon);
+    OIC_LOG_V(INFO, TAG, "recur->until.tm_mday = %d", recur->until.tm_mday);
 
-    if(recur->byDay & SUNDAY)
+    if(0 != (recur->byDay & SUNDAY))
     {
-        OC_LOG_V(INFO, TAG, "recur->byDay = %s", "Sunday");
+        OIC_LOG_V(INFO, TAG, "recur->byDay = %s", "Sunday");
     }
-    if(recur->byDay & MONDAY)
+    if(0 != (recur->byDay & MONDAY))
     {
-        OC_LOG_V(INFO, TAG, "recur->byDay = %s", "Monday");
+        OIC_LOG_V(INFO, TAG, "recur->byDay = %s", "Monday");
     }
-    if(recur->byDay & TUESDAY)
+    if(0 != (recur->byDay & TUESDAY))
     {
-        OC_LOG_V(INFO, TAG, "recur->byDay = %s", "Tuesday");
+        OIC_LOG_V(INFO, TAG, "recur->byDay = %s", "Tuesday");
     }
-    if(recur->byDay & WEDNESDAY)
+    if(0 != (recur->byDay & WEDNESDAY))
     {
-        OC_LOG_V(INFO, TAG, "recur->byDay = %s", "Wednesday");
+        OIC_LOG_V(INFO, TAG, "recur->byDay = %s", "Wednesday");
     }
-    if(recur->byDay & THURSDAY)
+    if(0 != (recur->byDay & THURSDAY))
     {
-        OC_LOG_V(INFO, TAG, "recur->byDay = %s", "Thursday");
+        OIC_LOG_V(INFO, TAG, "recur->byDay = %s", "Thursday");
     }
-    if(recur->byDay & FRIDAY)
+    if(0 != (recur->byDay & FRIDAY))
     {
-        OC_LOG_V(INFO, TAG, "recur->byDay = %s", "Friday");
+        OIC_LOG_V(INFO, TAG, "recur->byDay = %s", "Friday");
     }
-    if(recur->byDay & SATURDAY)
+    if(0 != (recur->byDay & SATURDAY))
     {
-        OC_LOG_V(INFO, TAG, "recur->byDay = %s", "Saturday");
+        OIC_LOG_V(INFO, TAG, "recur->byDay = %s", "Saturday");
     }
 }
 
@@ -110,8 +110,8 @@ static void checkValidityOfRequest(char *recurStr, char *periodStr,int startTime
         tzset();
         localtime_r(&rt, &t2);
 
-        OC_LOG_V(INFO, TAG, "t1 = %02d:%02d:%02d", t1.tm_hour, t1.tm_min, t1.tm_sec );
-        OC_LOG_V(INFO, TAG, "t2 = %02d:%02d:%02d", t2.tm_hour, t2.tm_min, t2.tm_sec );
+        OIC_LOG_V(INFO, TAG, "t1 = %02d:%02d:%02d", t1.tm_hour, t1.tm_min, t1.tm_sec );
+        OIC_LOG_V(INFO, TAG, "t2 = %02d:%02d:%02d", t2.tm_hour, t2.tm_min, t2.tm_sec );
     }while(t1.tm_hour != t2.tm_hour);
 
     if(byDay > 0)
diff --git a/resource/csdk/security/unittest/oic_svr_db.dat b/resource/csdk/security/unittest/oic_svr_db.dat
new file mode 100644 (file)
index 0000000..c048b16
Binary files /dev/null and b/resource/csdk/security/unittest/oic_svr_db.dat differ
index 0b0a4a6..7c86ab3 100644 (file)
 {
-    "acl": [
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/res",
-                "/oic/d",
-                "/oic/p",
-                "/oic/res/types/d",
-                "/oic/ad"
-                       ],
-                       "perms": 2,
-                       "ownrs" : [
-                               "MjIyMjIyMjIyMjIyMjIyMg=="
-                       ]
-               },
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/sec/doxm",
-                "/oic/sec/pstat",
-                "/oic/sec/acl"
-           ],
-             "perms": 6,
-             "ownrs" : [
-                 "MjIyMjIyMjIyMjIyMjIyMg=="
-             ]
-        }
-       ],
-       "pstat":        {
-               "isop": false,
-               "deviceid":     "ZGV2aWNlaWQAAAAAABhanw==",
-               "ch": 0,
-               "cm":   0,
-               "tm":   0,
-               "om":   3,
-               "sm":   [3]
-       },
-       "doxm": {
-               "oxm":  [0],
-               "oxmsel": 0,
-               "sct": 1,
-               "owned": false,
-               "deviceid":     "MjIyMjIyMjIyMjIyMjIyMg=="
-       }
-}
+    "acl": {
+        "aclist": {
+            "aces": [
+                {
+                    "subjectuuid": "*",
+                    "resources": [
+                        {
+                            "href": "/oic/res",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/d",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/p",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/res/types/d",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/ad",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        }
+                    ],
+                    "permission": 2
+                },
+                {
+                    "subjectuuid": "*",
+                    "resources": [
+                        {
+                            "href": "/oic/sec/doxm",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/sec/pstat",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/sec/acl",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        }
+                    ],
+                    "permission": 6
+                },
+                {
+                    "subjectuuid": "*",
+                    "resources": [
+                        {
+                            "href": "/oic/sec/pconf",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/sec/dpairing",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        }
+                    ],
+                    "permission": 6
+                }
+            ]
+        },
+        "rowneruuid" : "756E6B6E-6F77-6564-4465-766963654964"
+    },
+    "pstat": {
+        "isop": false,
+        "deviceuuid": "756E6B6E-6F77-6564-4465-766963654964",
+        "rowneruuid": "756E6B6E-6F77-6564-4465-766963654964",
+        "cm": 2,
+        "tm": 0,
+        "om": 3,
+        "sm": 3
+        },
+    "doxm": {
+        "oxms": [0],
+        "oxmsel": 0,
+        "sct": 1,
+        "owned": false,
+        "deviceuuid": "756E6B6E-6F77-6564-4465-766963654964",
+        "devowneruuid": "",
+        "rowneruuid": "756E6B6E-6F77-6564-4465-766963654964",
+        "dpc": true
+    }
+}
\ No newline at end of file
diff --git a/resource/csdk/security/unittest/oic_unittest.dat b/resource/csdk/security/unittest/oic_unittest.dat
new file mode 100644 (file)
index 0000000..e022892
Binary files /dev/null and b/resource/csdk/security/unittest/oic_unittest.dat differ
index 54cd36a..922be86 100644 (file)
@@ -1,77 +1,54 @@
 {
-    "acl": [
-        {
-            "sub": "MTExMTExMTExMTExMTExMQ==",
-            "rsrc": [
-                               "/oic/light",
-                               "/oic/fan"
-                       ],
-                       "perms": 255,
-                       "ownrs" : [
-                               "MjIyMjIyMjIyMjIyMjIyMg=="
-                       ]
-               },
-               {
-            "sub": "MzMzMzMzMzMzMzMzMzMzMw==",
-            "rsrc": [
-                               "/oic/light",
-                               "/oic/garage"
-                       ],
-                       "perms": 255,
-                       "ownrs" : [
-                               "MjIyMjIyMjIyMjIyMjIyMg==",
-                "NDQ0NDQ0NDQ0NDQ0NDQ0NA=="
-                       ]
-               }
-       ],
-
-       "pstat":        {
-               "isop": false,
-               "deviceid":     "ZGV2aWNlaWQAAAAAABhanw==",
-               "ch":   1234,
-               "cm":   63,
-               "tm":   48,
-               "om":   0,
-               "sm":   [3, 1]
-       },
-
-    "amacl": [
-        {
-            "rsrc": ["/a/led", "/a/fan"],
-            "amss": [
-                "NTU1NTU1NTU1NTU1NTU1NQ==", 
-                "NjY2NjY2NjY2NjY2NjY2Ng=="
-            ],
-                       "ownrs" : [
-                               "MjIyMjIyMjIyMjIyMjIyMg=="
-                       ]
-               },
-        {
-            "rsrc": ["/b/led", "/b/fan"],
-            "amss": [
-                "NTU1NTU1NTU1NTU1NTU1NQ==", 
-                "NjY2NjY2NjY2NjY2NjY2Ng=="
-            ],
-                       "ownrs" : [
-                               "MjIyMjIyMjIyMjIyMjIyMg=="
-                       ]
-               }
-       ],
-
-"svc": [
-        {
-            "svcdid": "NTU1NTU1NTU1NTU1NTU1NQ==",
-                       "svct": 1,
-                       "ownrs" : [
-                               "OTk5OTk5OTk5OTk5OTk5OQ=="
-                       ]
-               },
-        {
-            "svcdid": "NjY2NjY2NjY2NjY2NjY2Ng==",
-                       "svct": 1,
-                       "ownrs" : [
-                               "OTk5OTk5OTk5OTk5OTk5OQ=="
-                       ]
-               }
-       ]
+    "acl": {
+        "aclist": {
+            "aces": [
+                {
+                    "subjectuuid": "31313131-3131-3131-3131-313131313131",
+                    "resources": [
+                        {
+                            "href": "/oic/light",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/fan",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        }
+                    ],
+                    "permission": 31        
+                },
+                {
+                    "subjectuuid": "33333333-3333-3333-3333-333333333333",
+                    "resources": [
+                        {
+                            "href": "/oic/light",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/garage",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        }
+                    ],
+                    "permission": 31        
+                }
+            ]
+        },
+        "rowneruuid" : "32323232-3232-3232-3232-323232323232"
+    },
+    "pstat": {
+        "isop": false,
+        "deviceuuid": "756E6B6E-6F77-6564-4465-766963654964",
+        "rowneruuid": "756E6B6E-6F77-6564-4465-766963654964",
+        "cm": 63,
+        "tm": 48,
+        "om": 0,
+        "sm": 3
+    }
 }
diff --git a/resource/csdk/security/unittest/oic_unittest_acl1.dat b/resource/csdk/security/unittest/oic_unittest_acl1.dat
new file mode 100644 (file)
index 0000000..93c8370
--- /dev/null
@@ -0,0 +1 @@
+¿caclY\ 2\8b¢faclist¡daces\84£ksubjectuuida*iresources\86¤dhrefh/oic/rescrel`brt`bif`¤dhreff/oic/dcrel`brt`bif`¤dhreff/oic/pcrel`brt`bif`¤dhrefp/oic/res/types/dcrel`brt`bif`¤dhrefg/oic/adcrel`brt`bif`¤dhrefl/oic/sec/aclcrel`brt`bif`jpermission\ 2£ksubjectuuida*iresources\82¤dhrefm/oic/sec/doxmcrel`brt`bif`¤dhrefn/oic/sec/pstatcrel`brt`bif`jpermission\ 6£ksubjectuuidx$31313131-3131-3131-3131-313131313131iresources\82¤dhrefj/oic/lightcrel`brt`bif`¤dhrefh/oic/fancrel`brt`bif`jpermission\18\1f£ksubjectuuidx$33333333-3333-3333-3333-333333333333iresources\82¤dhrefj/oic/lightcrel`brt`bif`¤dhrefk/oic/garagecrel`brt`bif`jpermission\18\1fjrowneruuidx$32323232-3232-3232-3232-323232323232ÿ
\ No newline at end of file
index a179c2c..7dd810f 100644 (file)
 {
-    "acl": [
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/res",
-                "/oic/d",
-                "/oic/p",
-                "/oic/res/types/d",
-                "/oic/ad",
-                "/oic/sec/acl"
-                       ],
-                       "perms": 2,
-                       "ownrs" : [
-                               "MjIyMjIyMjIyMjIyMjIyMg=="
-                       ]
-               },
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/sec/doxm",
-                "/oic/sec/pstat"
-                       ],
-                       "perms": 6,
-                       "ownrs" : [
-                               "MjIyMjIyMjIyMjIyMjIyMg=="
-                       ]
-               },
-        {
-            "sub": "MTExMTExMTExMTExMTExMQ==",
-            "rsrc": [
-                               "/oic/light",
-                               "/oic/fan"
-                       ],
-                       "perms": 255,
-                       "ownrs" : [
-                               "MjIyMjIyMjIyMjIyMjIyMg=="
-                       ]
-               },
-               {
-            "sub": "MzMzMzMzMzMzMzMzMzMzMw==",
-            "rsrc": [
-                               "/oic/light",
-                               "/oic/garage"
-                       ],
-                       "perms": 255,
-                       "ownrs" : [
-                               "MjIyMjIyMjIyMjIyMjIyMg==",
-                "NDQ0NDQ0NDQ0NDQ0NDQ0NA=="
-                       ]
-               }
-       ]
+    "acl": {
+        "aclist": {
+            "aces": [
+                {
+                    "subjectuuid": "*",
+                    "resources": [
+                        {
+                            "href": "/oic/res",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/d",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/p",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/res/types/d",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/ad",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/sec/acl",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        }
+                    ],
+                    "permission": 2
+                },
+                {
+                    "subjectuuid": "*",
+                    "resources": [
+                        {
+                            "href": "/oic/sec/doxm",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/sec/pstat",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        }
+                    ],
+                    "permission": 6
+                },
+                {
+                    "subjectuuid": "31313131-3131-3131-3131-313131313131",
+                    "resources": [
+                        {
+                            "href": "/oic/light",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/fan",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        }
+                    ],
+                    "permission": 31        
+                },
+                {
+                    "subjectuuid": "33333333-3333-3333-3333-333333333333",
+                    "resources": [
+                        {
+                            "href": "/oic/light",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/garage",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        }
+                    ],
+                    "permission": 31        
+                }
+            ]
+        },
+        "rowneruuid" : "32323232-3232-3232-3232-323232323232"
+    }
 }
+
diff --git a/resource/csdk/security/unittest/oic_unittest_default_acl.dat b/resource/csdk/security/unittest/oic_unittest_default_acl.dat
new file mode 100644 (file)
index 0000000..e9efbb5
--- /dev/null
@@ -0,0 +1 @@
+¿caclY\ 1X¢faclist¡daces\81£ksubjectuuida*iresources\88¤dhrefh/oic/rescrel`brt`bif`¤dhreff/oic/dcrel`brt`bif`¤dhreff/oic/pcrel`brt`bif`¤dhrefp/oic/res/types/dcrel`brt`bif`¤dhrefg/oic/adcrel`brt`bif`¤dhrefl/oic/sec/aclcrel`brt`bif`¤dhrefm/oic/sec/doxmcrel`brt`bif`¤dhrefn/oic/sec/pstatcrel`brt`bif`jpermission\ 2jrowneruuidx$32323232-3232-3232-3232-323232323232ÿ
\ No newline at end of file
index 7f3d449..d624da5 100644 (file)
@@ -1,21 +1,63 @@
 {
-    "acl": [
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/res",
-                "/oic/d",
-                "/oic/p",
-                "/oic/res/types/d",
-                "/oic/ad",
-                "/oic/sec/acl",
-                "/oic/sec/doxm",
-                "/oic/sec/pstat"
-                       ],
-                       "perms": 2,
-                       "ownrs" : [
-                               "MjIyMjIyMjIyMjIyMjIyMg=="
-                       ]
-               }
-       ]
+    "acl": {
+        "aclist": {
+            "aces": [
+                {
+                    "subjectuuid": "*",
+                    "resources": [
+                        {
+                            "href": "/oic/res",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/d",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/p",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/res/types/d",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/ad",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/sec/acl",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/sec/doxm",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        },
+                        {
+                            "href": "/oic/sec/pstat",
+                            "rel": "",
+                            "rt": "",
+                            "if": ""
+                        }
+                    ],
+                    "permission": 2
+                }
+            ]
+        },
+        "rowneruuid" : "32323232-3232-3232-3232-323232323232"
+    }
 }
index 6890530..4806a96 100644 (file)
@@ -25,6 +25,7 @@
 #include "ocstack.h"
 #include "cainterface.h"
 #include "srmresourcestrings.h"
+#include "securevirtualresourcetypes.h"
 
 using namespace std;
 
@@ -50,22 +51,35 @@ OicUuid_t g_devOwner;
 char g_resource1[] = "Resource1";
 char g_resource2[] = "Resource2";
 
+extern OicSecDoxm_t *gDoxm;
+
 //Policy Engine Core Tests
 TEST(PolicyEngineCore, InitPolicyEngine)
 {
     EXPECT_EQ(OC_STACK_OK, InitPolicyEngine(&g_peContext));
 }
 
+// TODO - in order to unittest this we need InitDoxmResource() to put doxm
+// into Owned state with a known owner.  This will have to be done post v1.1.
 TEST(PolicyEngineCore, CheckPermissionNoAcls)
 {
-    EXPECT_EQ(ACCESS_DENIED_SUBJECT_NOT_FOUND,
-        CheckPermission(&g_peContext,
-                        &g_subjectIdA,
-                        g_resource1,
-                        PERMISSION_READ));
+    if(OC_STACK_OK == InitDoxmResource())
+    {
+        EXPECT_EQ(ACCESS_DENIED_SUBJECT_NOT_FOUND,
+            CheckPermission(&g_peContext,
+                            &g_subjectIdA,
+                            g_resource1,
+                            PERMISSION_READ));
+    }
+    else
+    {
+        printf("%s WARNING: InitDoxmResource() returned ERROR!\n", \
+            PE_UT_TAG);
+    }
 }
 
-//TODO This won't work until we figure out how to OcInit() or equivalent.
+// TODO - in order to unittest this we need InitDoxmResource() to put doxm
+// into Owned state with a known owner.  This will have to be done post v1.1.
 TEST(PolicyEngineCore, CheckDevOwnerRequest)
 {
     if(OC_STACK_OK == InitDoxmResource())
@@ -86,16 +100,15 @@ TEST(PolicyEngineCore, CheckDevOwnerRequest)
         }
         else
         {
-            printf("%s WARNING: InitDoxmResource() returned ERROR!\n", \
+            printf("%s WARNING: GetDoxmDevOwnerId() returned ERROR!\n", \
                 PE_UT_TAG);
         }
     }
     else
     {
-        printf("%s WARNING: GetDoxmDevOwnerId() returned ERROR!\n", PE_UT_TAG);
+        printf("%s WARNING: InitDoxmResource() returned ERROR!\n", \
+                PE_UT_TAG);
     }
-
-
 }
 
 TEST(PolicyEngineCore, DeInitPolicyEngine)
index 03c8a68..d1c9396 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#include <unistd.h>
 #include "gtest/gtest.h"
+
+#include "ocpayload.h"
 #include "ocstack.h"
-#include "resourcemanager.h"
-#include "pstatresource.h"
 #include "oic_malloc.h"
-#include "cJSON.h"
-#include "base64.h"
 #include "cainterface.h"
+#include "resourcemanager.h"
 #include "secureresourcemanager.h"
-#include "srmtestcommon.h"
-#include "ocpayload.h"
-#include <unistd.h>
-#ifdef __cplusplus
-extern "C" {
-#endif
-//Declare Provision status resource methods for testing
-OCStackResult CreatePstatResource();
-OCEntityHandlerResult PstatEntityHandler (OCEntityHandlerFlag flag,
-                                        OCEntityHandlerRequest * ehRequest);
-char * BinToPstatJSON(const OicSecPstat_t * pstat);
-OicSecPstat_t * JSONToPstatBin(const char * jsonStr);
-const char* UNIT_TEST_JSON_FILE_NAME = "oic_unittest.json";
-#ifdef __cplusplus
-}
-#endif
+#include "pstatresource.h"
+#include "security_internals.h"
 
-//InitPstatResource Tests
-TEST(InitPstatResourceTest, InitPstatResource)
+// InitPstatResource Tests
+TEST(PstatResourceTest, InitPstatResource)
 {
-    EXPECT_EQ(OC_STACK_INVALID_PARAM,  InitPstatResource());
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, InitPstatResource());
 }
 
-
-//DeInitPstatResource Tests
-TEST(DeInitPstatResourceTest, DeInitPstatResource)
+// DeInitPstatResource Tests
+TEST(PstatResourceTest, DeInitPstatResource)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, DeInitPstatResource());
 }
 
 //CreatePstatResource Tests
-TEST(CreatePstatResourceTest, CreatePstatResource)
+TEST(PstatResourceTest, CreatePstatResource)
 {
-    EXPECT_EQ(OC_STACK_INVALID_PARAM,  CreatePstatResource());
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreatePstatResource());
 }
 
 //PstatEntityHandler Tests
-TEST(PstatEntityHandlerTest, PstatEntityHandlerWithDummyRequest)
+TEST(PstatResourceTest, PstatEntityHandlerWithDummyRequest)
 {
-    OCEntityHandlerRequest req;
+    OCEntityHandlerRequest req = OCEntityHandlerRequest();
     EXPECT_EQ(OC_EH_ERROR, PstatEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req));
 }
 
-TEST(PstatEntityHandlerTest, PstatEntityHandlerWithPostRequest)
+TEST(PstatResourceTest, PstatEntityHandlerWithPostRequest)
 {
-    OCEntityHandlerRequest req;
+    OicSecPstat_t *defaultPstat = (OicSecPstat_t *) OICCalloc(1, sizeof(*defaultPstat));
+    ASSERT_TRUE(defaultPstat != NULL);
+    defaultPstat->isOp = false;
+    uint8_t deviceId[] = {0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x69, 0x64, 0x00,
+                          0x00, 0x00, 0x00, 0x00, 0x18, 0x5a, 0x9f};
+    memcpy(defaultPstat->deviceID.id, deviceId, sizeof(deviceId));
+    EXPECT_EQ(sizeof(defaultPstat->deviceID.id), sizeof(deviceId));
+    defaultPstat->commitHash = 1234;
+    defaultPstat->cm = (OicSecDpm_t) 63;
+    defaultPstat->tm = (OicSecDpm_t) 48;
+    defaultPstat->om = (OicSecDpom_t) 0;
+    defaultPstat->smLen = 1;
+    defaultPstat->sm = (OicSecDpom_t *)OICCalloc(defaultPstat->smLen, sizeof(*defaultPstat->sm));
+    ASSERT_TRUE(defaultPstat->sm != NULL);
+    defaultPstat->sm[0] = (OicSecDpom_t) 3;
+    size_t size = 0;
+    uint8_t *cbor = NULL;
+    EXPECT_EQ(OC_STACK_OK, PstatToCBORPayload(defaultPstat, &cbor, &size));
+    DeletePstatBinData(defaultPstat);
+    ASSERT_TRUE(cbor != NULL);
+
+    OCEntityHandlerRequest req = OCEntityHandlerRequest();
     req.method = OC_REST_POST;
-    req.payload = reinterpret_cast<OCPayload*>(
-            OCSecurityPayloadCreate("{ \"pstat\": { \"tm\": 0, \"om\": 3 }}"));
+    req.payload = (OCPayload *) OCSecurityPayloadCreate(cbor, size);
     EXPECT_EQ(OC_EH_ERROR, PstatEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req));
+    OICFree(cbor);
     OCPayloadDestroy(req.payload);
 }
 
-TEST(PstatEntityHandlerTest, PstatEntityHandlerInvalidRequest)
+TEST(PstatResourceTest, PstatEntityHandlerInvalidRequest)
 {
     EXPECT_EQ(OC_EH_ERROR, PstatEntityHandler(OCEntityHandlerFlag::OC_OBSERVE_FLAG, NULL));
 }
 
-//BinToJSON Tests
-TEST(BinToJSONTest, BinToNullJSON)
+TEST(PstatResourceTest, PstatToCBORPayloadNULL)
 {
-    char* value = BinToPstatJSON(NULL);
-    EXPECT_TRUE(value == NULL);
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(NULL, NULL, 0));
+    // Case when cbor payload is NULL
+    OicSecPstat_t pstat;
+    size_t size = 10;
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(&pstat, NULL, &size));
+    uint8_t *cborPayload = (uint8_t *) OICCalloc(1, size);
+    ASSERT_TRUE(NULL != cborPayload);
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(&pstat, &cborPayload, &size));
+    OICFree(cborPayload);
+    cborPayload = NULL;
+    // Case when pstat is zero.
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(NULL, &cborPayload, &size));
+    // Case when size is 0.
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(&pstat, &cborPayload, 0));
+    OICFree(cborPayload);
 }
 
-TEST(JSONToBinTest, NullJSONToBin)
+TEST(PstatResourceTest, CBORPayloadToPstat)
 {
-    OicSecPstat_t *pstat1 = JSONToPstatBin(NULL);
-    EXPECT_TRUE(pstat1 == NULL);
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToPstat(NULL, 0, NULL));
 }
 
-TEST(MarshalingAndUnMarshalingTest, BinToPstatJSONAndJSONToPstatBin)
+TEST(PstatResourceTest, PstatToCBORPayloadAndCBORPayloadToPstat)
 {
-    const char* id = "ZGV2aWNlaWQAAAAAABhanw==";
     OicSecPstat_t pstat;
     pstat.cm = NORMAL;
     pstat.commitHash = 0;
-    uint32_t outLen = 0;
-    unsigned char base64Buff[sizeof(((OicUuid_t*) 0)->id)] = {};
-    EXPECT_EQ(B64_OK, b64Decode(id, strlen(id), base64Buff, sizeof(base64Buff), &outLen));
-    memcpy(pstat.deviceID.id, base64Buff, outLen);
+    uint8_t deviceId[] = {0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x69, 0x64, 0x00,
+                          0x00, 0x00, 0x00, 0x00, 0x18, 0x5a, 0x9f};
+    memcpy(pstat.deviceID.id, deviceId, sizeof(deviceId));
     pstat.isOp = true;
     pstat.tm = NORMAL;
     pstat.om = SINGLE_SERVICE_CLIENT_DRIVEN;
-    pstat.smLen = 2;
-    pstat.sm = (OicSecDpom_t*)OICCalloc(pstat.smLen, sizeof(OicSecDpom_t));
-    if(!pstat.sm)
-    {
-        FAIL() << "Failed to allocate the pstat.sm";
-    }
+    pstat.smLen = 1;
+    pstat.sm = (OicSecDpom_t*)OICCalloc(pstat.smLen, sizeof(*pstat.sm));
+    ASSERT_TRUE(NULL != pstat.sm);
     pstat.sm[0] = SINGLE_SERVICE_CLIENT_DRIVEN;
-    pstat.sm[1] = SINGLE_SERVICE_SERVER_DRIVEN;
-    char* jsonPstat = BinToPstatJSON(&pstat);
-    if(!jsonPstat)
+
+    size_t size = 0;
+    uint8_t *cbor = NULL;
+    EXPECT_EQ(OC_STACK_OK, PstatToCBORPayload(&pstat, &cbor, &size));
+    if (!cbor)
     {
         OICFree(pstat.sm);
-        FAIL() << "Failed to convert BinToPstatJSON";
+        FAIL() << "Failed to convert PstatToCBORPayload";
         return;
     }
-    printf("BinToJSON Dump:\n%s\n\n", jsonPstat);
-    EXPECT_TRUE(jsonPstat != NULL);
-    OicSecPstat_t *pstat1 = JSONToPstatBin(jsonPstat);
-    EXPECT_TRUE(pstat1 != NULL);
-    if(pstat1)
-    {
-        OICFree(pstat1->sm);
-    }
-    OICFree(pstat1);
-    OICFree(jsonPstat);
-    OICFree(pstat.sm);
-}
-
-TEST(PstatTests, JSONMarshalliingTests)
-{
-    char *jsonStr1 = ReadFile(UNIT_TEST_JSON_FILE_NAME);
-    if (NULL != jsonStr1)
-    {
-        cJSON_Minify(jsonStr1);
-        /* Workaround : cJSON_Minify does not remove all the unwanted characters
-         from the end. Here is an attempt to remove those characters */
-        int len = strlen(jsonStr1);
-        while (len > 0)
-        {
-            if (jsonStr1[--len] == '}')
-            {
-                break;
-            }
-        }
-        jsonStr1[len + 1] = 0;
-
-        OicSecPstat_t* pstat = JSONToPstatBin(jsonStr1);
-        EXPECT_TRUE(NULL != pstat);
-
-        char* jsonStr2 = BinToPstatJSON(pstat);
-        EXPECT_STRNE(jsonStr1, jsonStr2);
+    ASSERT_TRUE(NULL != cbor);
+    OicSecPstat_t *pstat1 = NULL;
+    EXPECT_EQ(OC_STACK_OK, CBORPayloadToPstat(cbor, size, &pstat1));
+    ASSERT_TRUE(NULL != pstat1);
+    EXPECT_EQ(pstat.commitHash, pstat1->commitHash);
+    EXPECT_EQ(pstat.isOp, pstat1->isOp);
+    EXPECT_EQ(pstat.tm, pstat1->tm);
+    EXPECT_EQ(pstat.om, pstat1->om);
+    EXPECT_EQ(pstat.smLen, pstat1->smLen);
+    EXPECT_EQ(pstat.sm[0], pstat1->sm[0]);
 
-        OICFree(jsonStr1);
-        OICFree(jsonStr2);
-        OICFree(pstat);
-   }
-    else
-    {
-        printf("Please copy %s into unittest folder\n", UNIT_TEST_JSON_FILE_NAME);
-    }
+    DeletePstatBinData(pstat1);
+    OICFree(cbor);
+    OICFree(pstat.sm);
 }
index 6f51329..1435ad5 100644 (file)
 #include "gtest/gtest.h"
 #include "oic_malloc.h"
 #include "ocstack.h"
+#include <stdlib.h>
+#include "cbor.h"
 
+#define STRINGIZE2(x) #x
+#define STRINGIZE(x) STRINGIZE2(x)
+
+// TODO: Remove this, once all cbor related are completed.
 char* ReadFile(const char* filename)
 {
 
@@ -54,6 +60,89 @@ char* ReadFile(const char* filename)
     return data;
 }
 
+bool ReadCBORFile(const char* filename, const char* rsrcname, uint8_t **payload, size_t *pSize)
+{
+    bool status = false;
+    if (!payload || !pSize)
+    {
+        printf("Passed parameter are INVALID \n");
+        return status;
+    }
+    uint8_t *data = NULL;
+    size_t size = 0;
+
+    int len = strlen(STRINGIZE(SECURITY_BUILD_UNITTEST_DIR)) + strlen(filename) + 1;
+    char *filepath = (char *)OICCalloc(1, len);
+    if (!filepath)
+    {
+        printf("filepath memory allocation failed. \n");
+        return false;
+    }
+    int ret = snprintf(filepath, len, "%s%s", STRINGIZE(SECURITY_BUILD_UNITTEST_DIR), filename);
+    printf("Root build path: %s \n", filepath);
+
+    if (ret == len-1)
+    {
+        FILE *fp = fopen(filepath, "rb");
+        if (fp)
+        {
+            struct stat st;
+            if (stat(filepath, &st) == 0)
+            {
+                data = (uint8_t *)OICMalloc(st.st_size);
+                if (data)
+                {
+                    if (fread(data, 1, st.st_size, fp) != (size_t)st.st_size)
+                    {
+                        printf("Error in reading file %s\n", filename);
+                    }
+                    else
+                    {
+                        size = st.st_size;
+
+                        CborValue cbor = {0, };
+                        CborParser parser = {0, };
+                        cbor_parser_init(data, size, 0, &parser, &cbor);
+                        CborError cborFindResult = CborNoError;
+
+                        CborValue curVal = {0, };
+                        cborFindResult = cbor_value_map_find_value(&cbor, rsrcname, &curVal);
+                        if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal))
+                        {
+                            cborFindResult = cbor_value_dup_byte_string(&curVal, payload, pSize, NULL);
+                            if(CborNoError != cborFindResult)
+                            {
+                                printf("Failed to getting %s data\n", rsrcname);
+                            }
+                            else
+                            {
+                                status = true;
+                            }
+                        }
+                        else
+                        {
+                            printf("Failed to finding %s data\n", rsrcname);
+                        }
+
+                    }
+                    OICFree(data);
+                }
+            }
+            fclose(fp);
+        }
+        else
+        {
+            printf("Unable to open %s file\n", filepath);
+        }
+    }
+    else
+    {
+        printf("Filepath copy failed.\n");
+    }
+    OICFree(filepath);
+    return status;
+}
+
 void SetPersistentHandler(OCPersistentStorage *ps, bool set)
 {
     if (set)
index 1a8685e..ff5c453 100644 (file)
@@ -22,6 +22,7 @@
 #define IOTVT_SRM_TEST_COMMON_H
 
 char* ReadFile(const char* filename);
+bool ReadCBORFile(const char* filename, const char* rsrcName, uint8_t **payload, size_t *size);
 void SetPersistentHandler(OCPersistentStorage *ps, bool set);
 
 #endif //IOTVT_SRM_TEST_COMMON_H
index 5c3f75e..8d4553f 100644 (file)
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include "gtest/gtest.h"
-#include <pwd.h>
-#include <grp.h>
-#include <linux/limits.h>
-#include <sys/stat.h>
 #include "ocstack.h"
 #include "oic_malloc.h"
-#include "cJSON.h"
 #include "cainterface.h"
 #include "secureresourcemanager.h"
 #include "securevirtualresourcetypes.h"
 #include "srmresourcestrings.h"
 #include "svcresource.h"
 #include "srmtestcommon.h"
+#include "security_internals.h"
 
 using namespace std;
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-extern char * BinToSvcJSON(const OicSecSvc_t * svc);
-extern OicSecSvc_t * JSONToSvcBin(const char * jsonStr);
-extern void DeleteSVCList(OicSecSvc_t* svc);
-#ifdef __cplusplus
-}
-#endif
-
-static const char* JSON_FILE_NAME = "oic_unittest.json";
-
-#define NUM_SVC_IN_JSON_DB (2)
+#define NUM_SVC_IN_CBOR_DB (2)
 
-
-// JSON Marshalling Tests
-TEST(SVCResourceTest, JSONMarshallingTests)
+TEST(SVCResourceTest, CBORConversionTests)
 {
-    char *jsonStr1 = ReadFile(JSON_FILE_NAME);
-    if (jsonStr1)
-    {
-        OicSecSvc_t * svc = JSONToSvcBin(jsonStr1);
-        EXPECT_TRUE(NULL != svc);
+    OicSecSvc_t *svc1 = (OicSecSvc_t *) OICCalloc(1, sizeof(*svc1));
+    ASSERT_TRUE(NULL != svc1);
+    uint8_t svcdid[] = {0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35,
+                        0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35};
+    memcpy(svc1->svcdid.id, svcdid, sizeof(svcdid));
+    ASSERT_EQ(sizeof(svc1->svcdid.id), sizeof(svcdid));
 
-        int cnt = 0;
-        OicSecSvc_t * tempSvc = svc;
-        while(tempSvc)
-        {
+    svc1->svct = (OicSecSvcType_t) 1;
+    uint8_t owners[] = {0x39, 0x39, 0x39, 0x39, 0x39, 0x39, 0x39, 0x39, 0x39,
+                        0x39, 0x39, 0x39, 0x39, 0x39, 0x39, 0x39};
+    svc1->ownersLen = 1;
+    svc1->owners = (OicUuid_t *)OICCalloc(svc1->ownersLen, sizeof(*svc1->owners));
+    ASSERT_TRUE(NULL != svc1->owners);
+    memcpy(svc1->owners[0].id, owners, sizeof(owners));
+    ASSERT_EQ(sizeof(svc1->owners[0].id), sizeof(owners));
 
-            EXPECT_EQ(tempSvc->svct, ACCESS_MGMT_SERVICE);
-            cnt++;
-            tempSvc = tempSvc->next;
-        }
-        EXPECT_EQ(cnt, NUM_SVC_IN_JSON_DB);
+    svc1->next = (OicSecSvc_t *) OICCalloc(1, sizeof(*svc1->next));
+    ASSERT_TRUE(svc1->next != NULL);
+    memcpy(svc1->next->svcdid.id, svcdid, sizeof(svcdid));
+    ASSERT_EQ(sizeof(svc1->next->svcdid.id), sizeof(svcdid));
+    svc1->next->svct = (OicSecSvcType_t) 1;
+    uint8_t owners1[] = {0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
+                        0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36};
+    svc1->next->ownersLen = 1;
+    svc1->next->owners = (OicUuid_t *)OICCalloc(svc1->next->ownersLen,
+                                                sizeof(*svc1->next->owners));
+    ASSERT_TRUE(NULL != svc1->next->owners);
+    memcpy(svc1->next->owners[0].id, owners1, sizeof(owners1));
+    svc1->next->next = NULL;
 
-        char * jsonStr2 = BinToSvcJSON(svc);
-        EXPECT_TRUE(NULL != jsonStr2);
+    size_t size = 0;
+    uint8_t *psStorage = NULL;
+    EXPECT_EQ(OC_STACK_OK, SVCToCBORPayload(svc1, &psStorage, &size));
+    ASSERT_TRUE(NULL != psStorage);
 
-        OICFree(jsonStr1);
-        OICFree(jsonStr2);
-        DeleteSVCList(svc);
+    OicSecSvc_t *svc = NULL;
+    EXPECT_EQ(OC_STACK_OK, CBORPayloadToSVC(psStorage, size, &svc));
+    ASSERT_TRUE(NULL != svc);
+
+    int cnt = 0;
+    OicSecSvc_t *tempSvc = svc;
+    while (tempSvc)
+    {
+        EXPECT_EQ(ACCESS_MGMT_SERVICE, tempSvc->svct);
+        cnt++;
+        tempSvc = tempSvc->next;
     }
-}
+    EXPECT_EQ(NUM_SVC_IN_CBOR_DB, cnt);
 
+    OICFree(psStorage);
+    DeleteSVCList(svc);
+    DeleteSVCList(svc1);
+}
old mode 100644 (file)
new mode 100755 (executable)
index 0a30750..2113320
@@ -183,6 +183,13 @@ typedef struct resourceinterface_t {
     /** Future placeholder for access control and policy.*/
 } OCResourceInterface;
 
+/**
+ * Data structure for holding child resources associated with a collection
+ */
+typedef struct OCChildResource {
+    struct OCResource *rsrcResource;
+    struct OCChildResource *next;
+} OCChildResource;
 
 /**
  * Data structure for holding data type and definition for OIC resource.
@@ -207,7 +214,8 @@ typedef struct OCResource {
     /** Array of pointers to resources; can be used to represent a container of resources.
      * (i.e. hierarchies of resources) or for reference resources (i.e. for a resource collection).*/
 
-    struct OCResource *rsrcResources[MAX_CONTAINED_RESOURCES];
+    /** Child resource(s); linked list.*/
+    OCChildResource *rsrcChildResourcesHead;
 
     /** Pointer to function that handles the entity bound to the resource.
      *  This handler has to be explicitly defined by the programmer.*/
index 606350f..8b77e34 100644 (file)
@@ -174,13 +174,6 @@ OCStackResult BuildResponseRepresentation(const OCResource *resourcePtr,
                     OCRepPayload** payload);
 
 /**
- * Prepares a Payload for response.
- */
-OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
-                                           OCDiscoveryPayload* payload,
-                                           OCDevAddr *endpoint);
-
-/**
  * A helper function that Maps an @ref OCEntityHandlerResult type to an
  * @ref OCStackResult type.
  */
index 3dfc8ce..bef3e98 100644 (file)
@@ -266,19 +266,6 @@ OCStackResult BindResourceTypeToResource(OCResource* resource,
 OCStackResult CAResultToOCResult(CAResult_t caResult);
 
 /**
- * Get a byte representation of the server instance ID.
- * The memory is managed internal to this function, so freeing it externally will
- * result in a runtime error.
- *
- * Note: This will NOT seed the RNG, so it must be called after the RNG is seeded.
- * This is done automatically during the OCInit process,
- * so ensure that this call is done after that.
- *
- * @return A uint8_t representation the server instance ID.
- */
-const OicUuid_t* OCGetServerInstanceID(void);
-
-/**
  * Map OCQualityOfService to CAMessageType.
  *
  * @param qos Input qos.
old mode 100644 (file)
new mode 100755 (executable)
diff --git a/resource/csdk/stack/include/internal/oickeepalive.h b/resource/csdk/stack/include/internal/oickeepalive.h
new file mode 100644 (file)
index 0000000..c6a4d02
--- /dev/null
@@ -0,0 +1,100 @@
+/* ****************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ * This file contains the APIs for KeepAlive Mechanism.
+ * In order to ensure that the connection between an OIC Devices,
+ * when using CoAP over TCP, OIC Device should send application layer
+ * KeepAlive messages.
+ */
+#ifndef KEEP_ALIVE_H_
+#define KEEP_ALIVE_H_
+
+#include "octypes.h"
+#include "ocserverrequest.h"
+#include "ocresource.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * Name of resource type.
+ */
+#define KEEPALIVE_RESOURCE_TYPE_NAME "oic.wk.ping"
+
+/**
+ * Name of resource interface.
+ */
+#define KEEPALIVE_RESOURCE_INTF_NAME "oic.if.rw"
+
+/**
+ * URI of the resource.
+ */
+#define KEEPALIVE_RESOURCE_URI "/oic/ping"
+
+/**
+ * Initialize the KeepAlive.
+ * @param[in]   mode        Host mode of operation.
+ * @return  ::OC_STACK_OK or Appropriate error code.
+ */
+OCStackResult InitializeKeepAlive(OCMode mode);
+
+/**
+ * Terminates the KeepAlive.
+ * @param[in]   mode        Host mode of operation.
+ * @return  ::OC_STACK_OK or Appropriate error code.
+ */
+OCStackResult TerminateKeepAlive(OCMode mode);
+
+/**
+ * Process the KeepAlive timer to send ping message to OIC Server.
+ */
+void ProcessKeepAlive();
+
+/**
+ * This API will be called from RI layer whenever there is a request for KeepAlive.
+ * Virtual Resource.
+ * @param[in]   endPoint        RemoteEndpoint which sent the packet.
+ * @param[in]   requestInfo     Received coap packet.
+ * @return  ::OC_STACK_OK or Appropriate error code.
+ */
+OCStackResult HandleKeepAliveRequest(const CAEndpoint_t* endPoint,
+                                     const CARequestInfo_t* requestInfo);
+
+/**
+ * API to handle the connected device for KeepAlive.
+ * @return  Current Time.
+ */
+void HandleKeepAliveConnCB(const CAEndpoint_t *endpoint);
+
+/**
+ * API to handle the disconnected device for KeepAlive.
+ * @return  Current Time.
+ */
+void HandleKeepAliveDisconnCB(const CAEndpoint_t *endpoint);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // KEEP_ALIVE_H_
index 57e077a..c8a7cfc 100644 (file)
 #ifndef OCPAYLOAD_H_
 #define OCPAYLOAD_H_
 
+#ifndef __STDC_FORMAT_MACROS
+#define __STDC_FORMAT_MACROS
+#endif
+#ifndef __STDC_LIMIT_MACROS
+#define __STDC_LIMIT_MACROS
+#endif
 #include <stdbool.h>
 #include <inttypes.h>
 #include "octypes.h"
@@ -30,6 +36,28 @@ extern "C"
 {
 #endif
 
+/**
+ * Macro to verify the validity of cbor operation.
+ */
+#define VERIFY_CBOR_SUCCESS(log_tag, err, log_message) \
+    if ((CborNoError != (err)) && (CborErrorOutOfMemory != (err))) \
+    { \
+        if ((log_tag) && (log_message)) \
+        { \
+            OIC_LOG_V(ERROR, (log_tag), "%s with cbor error: \'%s\'.", \
+                    (log_message), (cbor_error_string(err))); \
+        } \
+        goto exit; \
+    } \
+
+#define VERIFY_PARAM_NON_NULL(log_tag, err, log_message) \
+    if (NULL == (err)) \
+    { \
+        OIC_LOG_V(FATAL, (log_tag), "%s", (log_message)); \
+        goto exit;\
+    } \
+
+
 typedef struct OCResource OCResource;
 
 void OCPayloadDestroy(OCPayload* payload);
@@ -191,29 +219,29 @@ void OCRepPayloadDestroy(OCRepPayload* payload);
 // Discovery Payload
 OCDiscoveryPayload* OCDiscoveryPayloadCreate();
 
-OCSecurityPayload* OCSecurityPayloadCreate(const char* securityData);
+OCSecurityPayload* OCSecurityPayloadCreate(const uint8_t* securityData, size_t size);
 void OCSecurityPayloadDestroy(OCSecurityPayload* payload);
 
 void OCDiscoveryPayloadAddResource(OCDiscoveryPayload* payload, const OCResource* res,
         uint16_t port);
 void OCDiscoveryPayloadAddNewResource(OCDiscoveryPayload* payload, OCResourcePayload* res);
-bool OCResourcePayloadAddResourceType(OCResourcePayload* payload, const char* resourceType);
-bool OCResourcePayloadAddInterface(OCResourcePayload* payload, const char* interface);
+bool OCResourcePayloadAddStringLL(OCStringLL **payload, const char* type);
 
 size_t OCDiscoveryPayloadGetResourceCount(OCDiscoveryPayload* payload);
 OCResourcePayload* OCDiscoveryPayloadGetResource(OCDiscoveryPayload* payload, size_t index);
 
+void OCDiscoveryResourceDestroy(OCResourcePayload* payload);
 void OCDiscoveryPayloadDestroy(OCDiscoveryPayload* payload);
 
 // Device Payload
-OCDevicePayload* OCDevicePayloadCreate(const uint8_t* sid, const char* dname,
-        const char* specVer, const char* dmVer);
+OCDevicePayload* OCDevicePayloadCreate(const char* sid, const char* dname,
+        const OCStringLL *types, const char* specVer, const char* dmVer);
 void OCDevicePayloadDestroy(OCDevicePayload* payload);
 
 // Platform Payload
 OCPlatformPayload* OCPlatformPayloadCreate(const OCPlatformInfo* platformInfo);
 OCPlatformPayload* OCPlatformPayloadCreateAsOwner(OCPlatformInfo* platformInfo);
-
+void OCPlatformInfoDestroy(OCPlatformInfo *info);
 void OCPlatformPayloadDestroy(OCPlatformPayload* payload);
 
 // Presence Payload
index 29f39b5..9eeae7e 100644 (file)
@@ -70,7 +70,7 @@ OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode);
  * @brief   Set Remote Access information for XMPP Client.
  * @param   raInfo            [IN] remote access info.
  *
- * @return  #CA_STATUS_OK
+ * @return  ::OC_STACK_OK on success, some other value upon failure.
  */
 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo);
 #endif
@@ -134,7 +134,9 @@ OCStackResult OCProcess();
  *                          well-known multicast IP address, the qos will be forced to ::OC_LOW_QOS
  *                          since it is impractical to send other QOS levels on such addresses.
  * @param cbData            Asynchronous callback function that is invoked by the stack when
- *                          discovery or resource interaction is complete.
+ *                          discovery or resource interaction is received. The discovery could be
+ *                          related to filtered/scoped/particular resource. The callback is
+ *                          generated for each response received.
  * @param options           The address of an array containing the vendor specific header options
  *                          to be sent with the request.
  * @param numOptions        Number of header options to be included.
@@ -514,6 +516,41 @@ OCNotifyListOfObservers (OCResourceHandle handle,
  */
 OCStackResult OCDoResponse(OCEntityHandlerResponse *response);
 
+//#ifdef DIRECT_PAIRING
+/**
+ * The function is responsible for discovery of direct-pairing device is current subnet. It will list
+ * all the device in subnet which support direct-pairing.
+ * Caller must NOT free returned constant pointer
+ *
+ * @param[in] timeout Timeout in seconds, value till which function will listen to responses from
+ *                    client before returning the list of devices.
+ * @return OCDirectPairingDev_t pointer in case of success and NULL otherwise.
+ */
+const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime);
+
+/**
+ * The function is responsible for return of paired device list via direct-pairing. It will list
+ * all the device which is previousely paired with client.
+ * Caller must NOT free returned constant pointer
+ *
+ * @return OCDirectPairingDev_t pointer in case of success and NULL otherwise.
+ */
+const OCDPDev_t* OCGetDirectPairedDevices();
+
+/**
+ * The function is responsible for establishment of direct-pairing. It will proceed mode negotiation
+ * and connect PIN based dtls session.
+ *
+ * @param[in] peer Target device to establish direct-pairing.
+ * @param[in] pmSel Selected mode of pairing.
+ * @param[in] pinNumber PIN number for authentication, pin lenght is defined DP_PIN_LENGTH(8).
+ * @param[in] resultCallback Callback fucntion to event status of process.
+ * @return OTM_SUCCESS in case of success and other value otherwise.
+ */
+OCStackResult OCDoDirectPairing(OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
+                                                     OCDirectPairingCB resultCallback);
+//#endif // DIRECT_PAIRING
+
 #ifdef __cplusplus
 }
 #endif // __cplusplus
index 4125f4d..c7bd0f9 100644 (file)
@@ -64,7 +64,7 @@ extern "C" {
 
 /** Resource Type.*/
 #define OC_RSRVD_RESOURCE_TYPES_URI           "/oic/res/types/d"
-#ifdef ROUTING_GATEWAY
+#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
 /** Gateway URI.*/
 #define OC_RSRVD_GATEWAY_URI                  "/oic/gateway"
 #endif
@@ -143,6 +143,9 @@ extern "C" {
 /** To represent resource type with platform.*/
 #define OC_RSRVD_RESOURCE_TYPE_PLATFORM "oic.wk.p"
 
+/** To represent resource type with RES.*/
+#define OC_RSRVD_RESOURCE_TYPE_RES    "oic.wk.res"
+
 /** To represent interface.*/
 #define OC_RSRVD_INTERFACE              "if"
 
@@ -182,9 +185,6 @@ extern "C" {
 /** To represent host name.*/
 #define OC_RSRVD_HOST_NAME              "hn"
 
-/** To represent version.*/
-#define OC_RSRVD_VERSION                "icv"
-
 /** To represent policy.*/
 #define OC_RSRVD_POLICY                 "p"
 
@@ -248,7 +248,7 @@ extern "C" {
 #define OC_RSRVD_DEVICE_NAME            "n"
 
 /** Device specification version.*/
-#define OC_RSRVD_SPEC_VERSION           "lcv"
+#define OC_RSRVD_SPEC_VERSION           "icv"
 
 /** Device data model.*/
 #define OC_RSRVD_DATA_MODEL_VERSION     "dmv"
@@ -278,12 +278,22 @@ extern "C" {
 #ifdef RA_ADAPTER
 #define MAX_ADDR_STR_SIZE (256)
 #else
-#define MAX_ADDR_STR_SIZE (40)
+/** Max Address could be "coap+tcp://[xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx]:xxxxx" */
+#define MAX_ADDR_STR_SIZE (59)
 #endif
 
+/** Length of MAC address */
+#define MAC_ADDR_STR_SIZE (17)
+
+/** Blocks of MAC address */
+#define MAC_ADDR_BLOCKS (6)
+
 /** Max identity size. */
 #define MAX_IDENTITY_SIZE (32)
 
+/** Universal unique identity size. */
+#define UUID_IDENTITY_SIZE (128/8)
+
 /** Resource Directory */
 
 /** Resource Directory URI used to Discover RD and Publish resources.*/
@@ -320,7 +330,7 @@ extern "C" {
 #define OC_RSRVD_MEDIA_TYPE              "mt"
 
 /** To represent resource type with Publish RD.*/
-#define OC_RSRVD_RESOURCE_TYPE_RDPUBLISH "oic.wk.rdPub"
+#define OC_RSRVD_RESOURCE_TYPE_RDPUBLISH "oic.wk.rdpub"
 
 /**
  * These enums (OCTransportAdapter and OCTransportFlags) must
@@ -340,14 +350,15 @@ typedef enum
 
     /** RFCOMM over Bluetooth EDR.*/
     OC_ADAPTER_RFCOMM_BTEDR = (1 << 2),
-
 #ifdef RA_ADAPTER
     /**Remote Access over XMPP.*/
     OC_ADAPTER_REMOTE_ACCESS = (1 << 3),
 #endif
     /** CoAP over TCP.*/
-    OC_ADAPTER_TCP           = (1 << 4)
+    OC_ADAPTER_TCP           = (1 << 4),
 
+    /** NFC Transport for Messaging.*/
+    OC_ADAPTER_NFC           = (1 << 5)
 } OCTransportAdapter;
 
 /**
@@ -405,6 +416,12 @@ typedef enum
 #define OC_MASK_MODS     (0x0FF0)
 #define OC_MASK_FAMS     (OC_IP_USE_V6|OC_IP_USE_V4)
 
+typedef struct OCStringLL
+{
+    struct OCStringLL *next;
+    char* value;
+} OCStringLL;
+
 /**
  * End point identity.
  */
@@ -418,6 +435,15 @@ typedef struct
 } OCIdentity;
 
 /**
+ * Universally unique identifier.
+ */
+typedef struct
+{
+    /** identitifier string.*/
+    unsigned char id[UUID_IDENTITY_SIZE];
+} OCUUIdentity;
+
+/**
  * Data structure to encapsulate IPv4/IPv6/Contiki/lwIP device addresses.
  * OCDevAddr must be the same as CAEndpoint (in CACommon.h).
  */
@@ -469,7 +495,10 @@ typedef enum
     CT_ADAPTER_REMOTE_ACCESS = (1 << 19),
 #endif
     /** CoAP over TCP.*/
-    CT_ADAPTER_TCP          = (1 << 20),
+    CT_ADAPTER_TCP     = (1 << 20),
+
+    /** NFC Transport.*/
+    CT_ADAPTER_NFC     = (1 << 21),
 
     /** Insecure transport is the default (subject to change).*/
 
@@ -705,6 +734,12 @@ typedef enum
     OC_STACK_DUPLICATE_UUID,
     OC_STACK_INCONSISTENT_DB,
 
+    /**
+     * Error code from OTM
+     * This error is pushed from DTLS interface when handshake failure happens
+     */
+    OC_STACK_AUTHENTICATION_FAILURE,
+
     /** Insert all new error codes here!.*/
     #ifdef WITH_PRESENCE
     OC_STACK_PRESENCE_STOPPED = 128,
@@ -759,6 +794,7 @@ typedef enum
  * Persistent storage handlers. An APP must provide OCPersistentStorage handler pointers
  * when it calls OCRegisterPersistentStorageHandler.
  * Persistent storage open handler points to default file path.
+ * It should check file path and whether the file is symbolic link or no.
  * Application can point to appropriate SVR database path for it's IoTivity Server.
  */
 typedef struct {
@@ -893,11 +929,17 @@ typedef struct
 {
     /** Pointer to the device name.*/
     char *deviceName;
-
+    /** Pointer to the types.*/
+    OCStringLL *types;
 } OCDeviceInfo;
 
 #ifdef RA_ADAPTER
 /**
+ * callback for bound JID
+ */
+typedef void (*jid_bound_cb)(char *jid);
+
+/**
  * CA Remote Access information for XMPP Client
  *
  */
@@ -910,6 +952,7 @@ typedef struct
     char *password;     /**< login password */
     char *resource;     /**< specific resource for login */
     char *user_jid;     /**< specific JID for login */
+    jid_bound_cb jidbound;  /**< callback when JID bound */
 } OCRAInfo_t;
 #endif  /* RA_ADAPTER */
 
@@ -917,19 +960,33 @@ typedef struct
 /** Enum to describe the type of object held by the OCPayload object.*/
 typedef enum
 {
+    /** Contents of the payload are invalid */
     PAYLOAD_TYPE_INVALID,
+    /** The payload is an OCDiscoveryPayload */
     PAYLOAD_TYPE_DISCOVERY,
+    /** The payload is an OCDevicePayload */
     PAYLOAD_TYPE_DEVICE,
+    /** The payload is an OCPlatformPayload */
     PAYLOAD_TYPE_PLATFORM,
+    /** The payload is an OCRepPayload */
     PAYLOAD_TYPE_REPRESENTATION,
+    /** The payload is an OCSecurityPayload */
     PAYLOAD_TYPE_SECURITY,
+    /** The payload is an OCPresencePayload */
     PAYLOAD_TYPE_PRESENCE,
+    /** The payload is an OCRDPayload */
     PAYLOAD_TYPE_RD
 } OCPayloadType;
 
+/**
+ * A generic struct representing a payload returned from a resource operation
+ *
+ * A pointer to OCPayLoad can be cast to a more specific struct to access members
+ * for the its type.
+ */
 typedef struct
 {
-    // The type of message that was received
+    /** The type of message that was received */
     OCPayloadType type;
 } OCPayload;
 
@@ -996,12 +1053,6 @@ typedef struct OCRepPayloadValue
 
 } OCRepPayloadValue;
 
-typedef struct OCStringLL
-{
-    struct OCStringLL *next;
-    char* value;
-} OCStringLL;
-
 // used for get/set/put/observe/etc representations
 typedef struct OCRepPayload
 {
@@ -1111,12 +1162,27 @@ typedef struct
 {
     OCPayload base;
 
-    uint8_t* sid;
+    /** Device Id */
+    char *sid;
+
+    /** A special case for handling RD address. */
+    char* baseURI;
+
+    /** Name */
+    char *name;
+
+    /** HREF */
+    char *uri;
+
+    /** Resource Type */
+    char *type;
+
+    /** Interface */
+    OCStringLL *interface;
 
     /** This structure holds the old /oic/res response. */
     OCResourcePayload *resources;
-    /** This structure holds the collection response for the /oic/res. */
-    OCResourceCollectionPayload *collectionResources;
+
 } OCDiscoveryPayload;
 
 /**
@@ -1147,10 +1213,12 @@ typedef struct
 typedef struct
 {
     OCPayload base;
-    uint8_t* sid;
+    char *sid;
     char* deviceName;
     char* specVersion;
     char* dataModelVersion;
+    OCStringLL *interfaces;
+    OCStringLL *types;
 } OCDevicePayload;
 
 typedef struct
@@ -1158,13 +1226,17 @@ typedef struct
     OCPayload base;
     char* uri;
     OCPlatformInfo info;
+    char* rt;
+    OCStringLL* interfaces;
 } OCPlatformPayload;
 
 typedef struct
 {
     OCPayload base;
-    char* securityData;
+    uint8_t* securityData;
+    size_t payloadSize;
 } OCSecurityPayload;
+
 #ifdef WITH_PRESENCE
 typedef struct
 {
@@ -1294,15 +1366,51 @@ typedef enum
 } OCEntityHandlerFlag;
 
 /**
- * Possible returned values from client application.
+ * Possible return values from client application callback
+ *
+ * A client application callback returns an OCStackApplicationResult to indicate whether
+ * the stack should continue to keep the callback registered.
  */
 typedef enum
 {
+    /** Make no more calls to the callback and call the OCClientContextDeleter for this callback */
     OC_STACK_DELETE_TRANSACTION = 0,
+    /** Keep this callback registered and call it if an apropriate event occurs */
     OC_STACK_KEEP_TRANSACTION
 } OCStackApplicationResult;
 
 
+//#ifdef DIRECT_PAIRING
+/**
+ * @brief   direct pairing Method Type.
+ *              0:  not allowed
+ *              1:  pre-configured pin
+ *              2:  random pin
+ */
+typedef enum OCPrm
+{
+    DP_NOT_ALLOWED             = 0x0,
+    DP_PRE_CONFIGURED        = (0x1 << 0),
+    DP_RANDOM_PIN               = (0x1 << 1),
+} OCPrm_t;
+
+/**
+ * Device Information of discoverd direct pairing device(s).
+ */
+typedef struct OCDPDev
+{
+    OCDevAddr               endpoint;
+    OCConnectivityType   connType;
+    uint16_t                     securePort;
+    bool                  edp;
+    OCPrm_t           *prm;
+    size_t                prmLen;
+    OCUUIdentity     deviceID;
+    OCUUIdentity     rowner;
+    struct OCDPDev *next;
+} OCDPDev_t;
+//#endif // DIRECT_PAIRING
+
 /*
  * -------------------------------------------------------------------------------------------
  * Callback function definitions
@@ -1355,6 +1463,17 @@ typedef OCEntityHandlerResult (*OCEntityHandler)
 typedef OCEntityHandlerResult (*OCDeviceEntityHandler)
 (OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest, char* uri, void* callbackParam);
 
+//#ifdef DIRECT_PAIRING
+/**
+ * Callback function definition of direct-pairing
+ *
+ * @param[OUT] peer - pairing device info.
+ * @param[OUT} result - It's returned with 'OC_STACK_XXX'. It will return 'OC_STACK_OK'
+ *                                   if D2D pairing is success without error
+ */
+typedef void (*OCDirectPairingCB)(OCDPDev_t *peer, OCStackResult result);
+//#endif // DIRECT_PAIRING
+
 #ifdef __cplusplus
 }
 #endif // __cplusplus
index 69cb45f..b695d89 100644 (file)
 #include <dlog.h>
 #endif
 
+#ifndef __STDC_FORMAT_MACROS
+#define __STDC_FORMAT_MACROS
+#endif
+#ifndef __STDC_LIMIT_MACROS
+#define __STDC_LIMIT_MACROS
+#endif
+#include <inttypes.h>
 #include "rdpayload.h"
 
 #ifdef __cplusplus
@@ -37,116 +44,115 @@ extern "C"
 #define PL_TAG "PayloadLog"
 
 #ifdef TB_LOG
-    #define OC_LOG_PAYLOAD(level, payload) OCPayloadLog((level),(payload))
+    #define OIC_LOG_PAYLOAD(level, payload) OCPayloadLog((level),(payload))
     #define UUID_SIZE (16)
-    #define UUID_LENGTH (37)
 const char *convertTriggerEnumToString(OCPresenceTrigger trigger);
 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr);
 
 static inline void OCPayloadLogRep(LogLevel level, OCRepPayload* payload)
 {
-    OC_LOG(level, (PL_TAG), "Payload Type: Representation");
+    OIC_LOG(level, (PL_TAG), "Payload Type: Representation");
     OCRepPayload* rep = payload;
     int i = 1;
     while(rep)
     {
-        OC_LOG_V(level, PL_TAG, "\tResource #%d", i);
-        OC_LOG_V(level, PL_TAG, "\tURI:%s", rep->uri);
-        OC_LOG(level, PL_TAG, "\tResource Types:");
+        OIC_LOG_V(level, PL_TAG, "\tResource #%d", i);
+        OIC_LOG_V(level, PL_TAG, "\tURI:%s", rep->uri);
+        OIC_LOG(level, PL_TAG, "\tResource Types:");
         OCStringLL* strll =  rep->types;
         while(strll)
         {
-            OC_LOG_V(level, PL_TAG, "\t\t%s", strll->value);
+            OIC_LOG_V(level, PL_TAG, "\t\t%s", strll->value);
             strll = strll->next;
         }
-        OC_LOG(level, PL_TAG, "\tInterfaces:");
+        OIC_LOG(level, PL_TAG, "\tInterfaces:");
         strll =  rep->interfaces;
         while(strll)
         {
-            OC_LOG_V(level, PL_TAG, "\t\t%s", strll->value);
+            OIC_LOG_V(level, PL_TAG, "\t\t%s", strll->value);
             strll = strll->next;
         }
 
         // TODO Finish Logging: Values
         OCRepPayloadValue* val = rep->values;
 
-        OC_LOG(level, PL_TAG, "\tValues:");
+        OIC_LOG(level, PL_TAG, "\tValues:");
 
         while(val)
         {
             switch(val->type)
             {
                 case OCREP_PROP_NULL:
-                    OC_LOG_V(level, PL_TAG, "\t\t%s: NULL", val->name);
+                    OIC_LOG_V(level, PL_TAG, "\t\t%s: NULL", val->name);
                     break;
                 case OCREP_PROP_INT:
-                    OC_LOG_V(level, PL_TAG, "\t\t%s(int):%lld", val->name, val->i);
+                    OIC_LOG_V(level, PL_TAG, "\t\t%s(int):%zd", val->name, val->i);
                     break;
                 case OCREP_PROP_DOUBLE:
-                    OC_LOG_V(level, PL_TAG, "\t\t%s(double):%f", val->name, val->d);
+                    OIC_LOG_V(level, PL_TAG, "\t\t%s(double):%f", val->name, val->d);
                     break;
                 case OCREP_PROP_BOOL:
-                    OC_LOG_V(level, PL_TAG, "\t\t%s(bool):%s", val->name, val->b ? "true" : "false");
+                    OIC_LOG_V(level, PL_TAG, "\t\t%s(bool):%s", val->name, val->b ? "true" : "false");
                     break;
                 case OCREP_PROP_STRING:
-                    OC_LOG_V(level, PL_TAG, "\t\t%s(string):%s", val->name, val->str);
+                    OIC_LOG_V(level, PL_TAG, "\t\t%s(string):%s", val->name, val->str);
                     break;
                 case OCREP_PROP_BYTE_STRING:
-                    OC_LOG_V(level, PL_TAG, "\t\t%s(binary):", val->name);
-                    OC_LOG_BUFFER(level, PL_TAG, val->ocByteStr.bytes, val->ocByteStr.len);
+                    OIC_LOG_V(level, PL_TAG, "\t\t%s(binary):", val->name);
+                    OIC_LOG_BUFFER(level, PL_TAG, val->ocByteStr.bytes, val->ocByteStr.len);
                     break;
                 case OCREP_PROP_OBJECT:
                     // Note: Only prints the URI (if available), to print further, you'll
                     // need to dig into the object better!
-                    OC_LOG_V(level, PL_TAG, "\t\t%s(OCRep):%s", val->name, val->obj->uri);
+                    OIC_LOG_V(level, PL_TAG, "\t\t%s(OCRep):%s", val->name, val->obj->uri);
                     break;
                 case OCREP_PROP_ARRAY:
                     switch(val->arr.type)
                     {
                         case OCREP_PROP_INT:
-                            OC_LOG_V(level, PL_TAG, "\t\t%s(int array):%lld x %lld x %lld",
+                            OIC_LOG_V(level, PL_TAG, "\t\t%s(int array):%zu x %zu x %zu",
                                     val->name,
                                     val->arr.dimensions[0], val->arr.dimensions[1],
                                     val->arr.dimensions[2]);
                             break;
                         case OCREP_PROP_DOUBLE:
-                            OC_LOG_V(level, PL_TAG, "\t\t%s(double array):%lld x %lld x %lld",
+                            OIC_LOG_V(level, PL_TAG, "\t\t%s(double array):%zu x %zu x %zu",
                                     val->name,
                                     val->arr.dimensions[0], val->arr.dimensions[1],
                                     val->arr.dimensions[2]);
                             break;
                         case OCREP_PROP_BOOL:
-                            OC_LOG_V(level, PL_TAG, "\t\t%s(bool array):%lld x %lld x %lld",
+                            OIC_LOG_V(level, PL_TAG, "\t\t%s(bool array):%zu x %zu x %zu",
                                     val->name,
                                     val->arr.dimensions[0], val->arr.dimensions[1],
                                     val->arr.dimensions[2]);
                             break;
                         case OCREP_PROP_STRING:
-                            OC_LOG_V(level, PL_TAG, "\t\t%s(string array):%lld x %lld x %lld",
+                            OIC_LOG_V(level, PL_TAG, "\t\t%s(string array):%zu x %zu x %zu",
                                     val->name,
                                     val->arr.dimensions[0], val->arr.dimensions[1],
                                     val->arr.dimensions[2]);
                             break;
                         case OCREP_PROP_BYTE_STRING:
-                            OC_LOG_V(level, PL_TAG, "\t\t%s(byte array):%lld x %lld x %lld",
+                            OIC_LOG_V(level, PL_TAG, "\t\t%s(byte array):%zu x %zu x %zu",
                                     val->name,
                                     val->arr.dimensions[0], val->arr.dimensions[1],
                                     val->arr.dimensions[2]);
                             break;
                         case OCREP_PROP_OBJECT:
-                            OC_LOG_V(level, PL_TAG, "\t\t%s(OCRep array):%lld x %lld x %lld",
+                            OIC_LOG_V(level, PL_TAG, "\t\t%s(OCRep array):%zu x %zu x %zu",
                                     val->name,
                                     val->arr.dimensions[0], val->arr.dimensions[1],
                                     val->arr.dimensions[2]);
                             break;
                         default:
-                            OC_LOG_V(ERROR, PL_TAG, "\t\t%s <-- Unknown/unsupported array type!",
+                            OIC_LOG_V(ERROR, PL_TAG, "\t\t%s <-- Unknown/unsupported array type!",
                                     val->name);
                             break;
                     }
                     break;
                 default:
-                    OC_LOG_V(ERROR, PL_TAG, "\t\t%s <-- Unknown type!", val->name);
+                    OIC_LOG_V(ERROR, PL_TAG, "\t\t%s <-- Unknown type!", val->name);
                     break;
             }
             val = val -> next;
@@ -160,41 +166,62 @@ static inline void OCPayloadLogRep(LogLevel level, OCRepPayload* payload)
 
 static inline void OCPayloadLogDiscovery(LogLevel level, OCDiscoveryPayload* payload)
 {
-    OC_LOG(level, PL_TAG, "Payload Type: Discovery");
+    OIC_LOG(level, PL_TAG, "Payload Type: Discovery");
     int i = 1;
 
     if(!payload->resources)
     {
-        OC_LOG(level, PL_TAG, "\tNO Resources");
+        OIC_LOG(level, PL_TAG, "\tNO Resources");
         return;
     }
-    OC_LOG(level, PL_TAG, "\tSID:");
-    OC_LOG_BUFFER(level, PL_TAG, payload->sid, UUID_SIZE);
+    OIC_LOG_V(level, PL_TAG, "\tSID: %s", payload->sid);
+    if (payload->baseURI)
+    {
+        OIC_LOG_V(level, PL_TAG, "\tBase URI:%s", payload->baseURI);
+    }
+    if (payload->name)
+    {
+        OIC_LOG_V(level, PL_TAG, "\tNAME: %s", payload->name);
+    }
+    if (payload->uri)
+    {
+        OIC_LOG_V(level, PL_TAG, "\tURI: %s", payload->uri);
+    }
+    if (payload->type)
+    {
+        OIC_LOG_V(level, PL_TAG, "\tResource Type: %s", payload->type);
+    }
+    OIC_LOG(level, PL_TAG, "\tInterface:");
+    for (OCStringLL *itf = payload->interface; itf; itf = itf->next)
+    {
+        OIC_LOG_V(level, PL_TAG, "\t\t%s", itf->value);
+    }
+
     OCResourcePayload* res = payload->resources;
 
     while(res)
     {
-        OC_LOG_V(level, PL_TAG, "\tResource #%d", i);
-        OC_LOG_V(level, PL_TAG, "\tURI:%s", res->uri);
-        OC_LOG(level, PL_TAG, "\tResource Types:");
+        OIC_LOG_V(level, PL_TAG, "\tResource #%d", i);
+        OIC_LOG_V(level, PL_TAG, "\tURI:%s", res->uri);
+        OIC_LOG(level, PL_TAG, "\tResource Types:");
         OCStringLL* strll =  res->types;
         while(strll)
         {
-            OC_LOG_V(level, PL_TAG, "\t\t%s", strll->value);
+            OIC_LOG_V(level, PL_TAG, "\t\t%s", strll->value);
             strll = strll->next;
         }
-        OC_LOG(level, PL_TAG, "\tInterfaces:");
+        OIC_LOG(level, PL_TAG, "\tInterfaces:");
         strll =  res->interfaces;
         while(strll)
         {
-            OC_LOG_V(level, PL_TAG, "\t\t%s", strll->value);
+            OIC_LOG_V(level, PL_TAG, "\t\t%s", strll->value);
             strll = strll->next;
         }
 
-        OC_LOG_V(level, PL_TAG, "\tBitmap: %u", res->bitmap);
-        OC_LOG_V(level, PL_TAG, "\tSecure?: %s", res->secure ? "true" : "false");
-        OC_LOG_V(level, PL_TAG, "\tPort: %u", res->port);
-        OC_LOG(level, PL_TAG, "");
+        OIC_LOG_V(level, PL_TAG, "\tBitmap: %u", res->bitmap);
+        OIC_LOG_V(level, PL_TAG, "\tSecure?: %s", res->secure ? "true" : "false");
+        OIC_LOG_V(level, PL_TAG, "\tPort: %u", res->port);
+        OIC_LOG(level, PL_TAG, "");
         res = res->next;
         ++i;
     }
@@ -202,44 +229,73 @@ static inline void OCPayloadLogDiscovery(LogLevel level, OCDiscoveryPayload* pay
 
 static inline void OCPayloadLogDevice(LogLevel level, OCDevicePayload* payload)
 {
-    OC_LOG(level, PL_TAG, "Payload Type: Device");
-    OC_LOG(level, PL_TAG, "\tSID:");
-    OC_LOG_BUFFER(level, PL_TAG, payload->sid, UUID_SIZE);
-    OC_LOG_V(level, PL_TAG, "\tDevice Name:%s", payload->deviceName);
-    OC_LOG_V(level, PL_TAG, "\tSpec Version%s", payload->specVersion);
-    OC_LOG_V(level, PL_TAG, "\tData Model Version:%s", payload->dataModelVersion);
+    OIC_LOG(level, PL_TAG, "Payload Type: Device");
+    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->types)
+    {
+        OIC_LOG(level, PL_TAG, "\tResource Type:");
+        for (OCStringLL *strll = payload->types; strll; strll = strll->next)
+        {
+            OIC_LOG_V(level, PL_TAG, "\t\t%s", strll->value);
+        }
+    }
+    if (payload->interfaces)
+    {
+        OIC_LOG(level, PL_TAG, "\tInterface:");
+        for (OCStringLL *strll = payload->interfaces; strll; strll = strll->next)
+        {
+            OIC_LOG_V(level, PL_TAG, "\t\t%s", strll->value);
+        }
+    }
 }
 
 static inline void OCPayloadLogPlatform(LogLevel level, OCPlatformPayload* payload)
 {
-    OC_LOG(level, PL_TAG, "Payload Type: Platform");
-    OC_LOG_V(level, PL_TAG, "\tURI:%s", payload->uri);
-    OC_LOG_V(level, PL_TAG, "\tPlatform ID:%s", payload->info.platformID);
-    OC_LOG_V(level, PL_TAG, "\tMfg Name:%s", payload->info.manufacturerName);
-    OC_LOG_V(level, PL_TAG, "\tMfg URL:%s", payload->info.manufacturerUrl);
-    OC_LOG_V(level, PL_TAG, "\tModel Number:%s", payload->info.modelNumber);
-    OC_LOG_V(level, PL_TAG, "\tDate of Mfg:%s", payload->info.dateOfManufacture);
-    OC_LOG_V(level, PL_TAG, "\tPlatform Version:%s", payload->info.platformVersion);
-    OC_LOG_V(level, PL_TAG, "\tOS Version:%s", payload->info.operatingSystemVersion);
-    OC_LOG_V(level, PL_TAG, "\tHardware Version:%s", payload->info.hardwareVersion);
-    OC_LOG_V(level, PL_TAG, "\tFirmware Version:%s", payload->info.firmwareVersion);
-    OC_LOG_V(level, PL_TAG, "\tSupport URL:%s", payload->info.supportUrl);
-    OC_LOG_V(level, PL_TAG, "\tSystem Time:%s", payload->info.systemTime);
+    OIC_LOG(level, PL_TAG, "Payload Type: Platform");
+    OIC_LOG_V(level, PL_TAG, "\tURI:%s", payload->uri);
+    OIC_LOG_V(level, PL_TAG, "\tPlatform ID:%s", payload->info.platformID);
+    OIC_LOG_V(level, PL_TAG, "\tMfg Name:%s", payload->info.manufacturerName);
+    OIC_LOG_V(level, PL_TAG, "\tMfg URL:%s", payload->info.manufacturerUrl);
+    OIC_LOG_V(level, PL_TAG, "\tModel Number:%s", payload->info.modelNumber);
+    OIC_LOG_V(level, PL_TAG, "\tDate of Mfg:%s", payload->info.dateOfManufacture);
+    OIC_LOG_V(level, PL_TAG, "\tPlatform Version:%s", payload->info.platformVersion);
+    OIC_LOG_V(level, PL_TAG, "\tOS Version:%s", payload->info.operatingSystemVersion);
+    OIC_LOG_V(level, PL_TAG, "\tHardware Version:%s", payload->info.hardwareVersion);
+    OIC_LOG_V(level, PL_TAG, "\tFirmware Version:%s", payload->info.firmwareVersion);
+    OIC_LOG_V(level, PL_TAG, "\tSupport URL:%s", payload->info.supportUrl);
+    OIC_LOG_V(level, PL_TAG, "\tSystem Time:%s", payload->info.systemTime);
+
+    if (payload->rt)
+    {
+        OIC_LOG(level, PL_TAG, "\tResource Types:");
+        OIC_LOG_V(level, PL_TAG, "\t\t%s", payload->rt);
+    }
+    if (payload->interfaces)
+    {
+        OIC_LOG(level, PL_TAG, "\tResource Interfaces:");
+        for (OCStringLL *strll = payload->interfaces; strll; strll = strll->next)
+        {
+            OIC_LOG_V(level, PL_TAG, "\t\t%s", strll->value);
+        }
+    }
 }
 
 static inline void OCPayloadLogPresence(LogLevel level, OCPresencePayload* payload)
 {
-    OC_LOG(level, PL_TAG, "Payload Type: Presence");
-    OC_LOG_V(level, PL_TAG, "\tSequence Number:%u", payload->sequenceNumber);
-    OC_LOG_V(level, PL_TAG, "\tMax Age:%d", payload->maxAge);
-    OC_LOG_V(level, PL_TAG, "\tTrigger:%s", convertTriggerEnumToString(payload->trigger));
-    OC_LOG_V(level, PL_TAG, "\tResource Type:%s", payload->resourceType);
+    OIC_LOG(level, PL_TAG, "Payload Type: Presence");
+    OIC_LOG_V(level, PL_TAG, "\tSequence Number:%u", payload->sequenceNumber);
+    OIC_LOG_V(level, PL_TAG, "\tMax Age:%d", payload->maxAge);
+    OIC_LOG_V(level, PL_TAG, "\tTrigger:%s", convertTriggerEnumToString(payload->trigger));
+    OIC_LOG_V(level, PL_TAG, "\tResource Type:%s", payload->resourceType);
 }
 
 static inline void OCPayloadLogSecurity(LogLevel level, OCSecurityPayload* payload)
 {
-    OC_LOG(level, PL_TAG, "Payload Type: Security");
-    OC_LOG_V(level, PL_TAG, "\tSecurity Data: %s", payload->securityData);
+    OIC_LOG(level, PL_TAG, "Payload Type: Security");
+    OIC_LOG_V(level, PL_TAG, "\tSecurity Data: %s", payload->securityData);
 }
 
 static inline void OCRDPayloadLog(const LogLevel level, const OCRDPayload *payload)
@@ -251,14 +307,14 @@ static inline void OCRDPayloadLog(const LogLevel level, const OCRDPayload *paylo
 
     if (payload->rdDiscovery)
     {
-        OC_LOG(level, PL_TAG, "RD Discovery");
-        OC_LOG_V(level, PL_TAG, "  Device Name : %s", payload->rdDiscovery->n.deviceName);
-        OC_LOG_V(level, PL_TAG, "  Device Identity : %s", payload->rdDiscovery->di.id);
-        OC_LOG_V(level, PL_TAG, "  Bias: %d", payload->rdDiscovery->sel);
+        OIC_LOG(level, PL_TAG, "RD Discovery");
+        OIC_LOG_V(level, PL_TAG, "  Device Name : %s", payload->rdDiscovery->n.deviceName);
+        OIC_LOG_V(level, PL_TAG, "  Device Identity : %s", payload->rdDiscovery->di.id);
+        OIC_LOG_V(level, PL_TAG, "  Bias: %d", payload->rdDiscovery->sel);
     }
     if (payload->rdPublish)
     {
-        OC_LOG(level, PL_TAG, "RD Publish");
+        OIC_LOG(level, PL_TAG, "RD Publish");
         OCResourceCollectionPayload *rdPublish = payload->rdPublish;
         OCTagsLog(level, rdPublish->tags);
         OCLinksLog(level, rdPublish->setLinks);
@@ -269,7 +325,7 @@ static inline void OCPayloadLog(LogLevel level, OCPayload* payload)
 {
     if(!payload)
     {
-        OC_LOG(level, PL_TAG, "NULL Payload");
+        OIC_LOG(level, PL_TAG, "NULL Payload");
         return;
     }
     switch(payload->type)
@@ -296,12 +352,12 @@ static inline void OCPayloadLog(LogLevel level, OCPayload* payload)
             OCRDPayloadLog(level, (OCRDPayload*)payload);
             break;
         default:
-            OC_LOG_V(level, PL_TAG, "Unknown Payload Type: %d", payload->type);
+            OIC_LOG_V(level, PL_TAG, "Unknown Payload Type: %d", payload->type);
             break;
     }
 }
 #else
-    #define OC_LOG_PAYLOAD(level, payload)
+    #define OIC_LOG_PAYLOAD(level, payload)
 #endif
 
 #ifdef __cplusplus
index 1781263..17c6417 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef _RDPAYLOAD_H_
-#define _RDPAYLOAD_H_
+#ifndef OC_RDPAYLOAD_H_
+#define OC_RDPAYLOAD_H_
 
 #include <cbor.h>
 #include "octypes.h"
@@ -38,32 +38,10 @@ extern "C" {
  * structure.
  * @param size Length of the payload.
  *
- * @return ::OC_STACK_OK returns if successful and OC_STACK_ERROR returns if
- * failed in creating CBOR.
- */
-int64_t OCRDPayloadToCbor(const OCRDPayload *rdPayload, uint8_t *outPayload, size_t *size);
-
-/**
- * Converts tags structure to the tags cbor payload.
- *
- * @param tags Allocated Tag structure
- * @param setMap The cbor map where result will be stored.
- *
- * @return ::OC_STACK_OK returns if successful and OC_STACK_ERROR returns if
+ * @return ::CborNoError returns if successful and other Cbor error in  case of error.
  * failed in creating CBOR.
  */
-OCStackResult OCTagsPayloadToCbor(OCTagsPayload *tags, CborEncoder *setMap);
-
-/**
- * Converts links structure to cbor map structure
- *
- * @param links Allocated links structure.
- * @param setMap The cbor map where result will be stored.
- *
- * @return ::OC_STACK_OK returns if successful and OC_STACK_ERROR returns if
- * failed in creating CBOR.
- */
-OCStackResult OCLinksPayloadToCbor(OCLinksPayload *rtPtr, CborEncoder *setMap);
+CborError OCRDPayloadToCbor(const OCRDPayload *rdPayload, uint8_t *outPayload, size_t *size);
 
 /**
  * Converts CBOR to OCRDPayload.
@@ -77,28 +55,6 @@ OCStackResult OCLinksPayloadToCbor(OCLinksPayload *rtPtr, CborEncoder *setMap);
 OCStackResult OCRDCborToPayload(const CborValue *cborPayload, OCPayload **outPayload);
 
 /**
- * Converts cbor map payload to OCTags payload.
- *
- * @param tagstMap CborValue holding tags structure.
- * @param tagsPayload Allocated tags payload.
- *
- * @return ::OC_STACK_OK returns if successful and OC_STACK_ERROR returns if
- * failed in creating CBOR.
- */
-OCStackResult OCTagsCborToPayload(CborValue *tagsMap, OCTagsPayload **tagsPayload);
-
-/**
- * Converts cbor map payload to OCLinks payload.
- *
- * @param tagstMap CborValue holding links structure.
- * @param tagsPayload Allocated links payload.
- *
- * @return ::OC_STACK_OK returns if successful and OC_STACK_ERROR returns if
- * failed in creating CBOR.
- */
-OCStackResult OCLinksCborToPayload(CborValue *linksArray, OCLinksPayload **linksPayload);
-
-/**
  * Initializes RD payload structure.
  *
  * @param payloadType Defines whether payload is RD_PAYLOAD_TYPE_DISCOVERY or
@@ -176,20 +132,6 @@ OCLinksPayload* OCCopyLinksResources(const char *href, OCStringLL *rt, OCStringL
 OCResourceCollectionPayload* OCCopyCollectionResource(OCTagsPayload *tags, OCLinksPayload *links);
 
 /**
- * Adds discocvery collection in discovery payload.
- *
- * @param payload Pointer to the discovery payload. It adds allocated collection resource.
- * @param tags Pointer to the tags payload.
- * @param links Pointer to the links payload.
- *
- * @return ::OC_STACK_OK returns if successful and OC_STACK_ERROR returns if
- * failed in creating CBOR.
- */
-
-OCStackResult OCDiscoveryCollectionPayloadAddResource(OCDiscoveryPayload *payload,  OCTagsPayload *tags,
-    OCLinksPayload *links);
-
-/**
  * Destroys tags payload including internal structure allocated
  *
  * @param tags - Allocated memory of the tags payload.
@@ -237,4 +179,4 @@ void OCLinksLog(const LogLevel level, const OCLinksPayload *links);
 }
 #endif // __cplusplus
 
-#endif /* OCTYPES_H_ */
+#endif /* OC_RDPAYLOAD_H_ */
index 5b551bb..829ce52 100644 (file)
@@ -21,9 +21,6 @@
 Import('env')
 
 transport = env.get('TARGET_TRANSPORT')
-if 'BLE' in transport:
-        # Only supported for ethernet and WiFi.
-        Return()
 
 arduino_simplecs_env = env.Clone()
 ######################################################################
index 22aab31..55ed42c 100644 (file)
@@ -31,7 +31,7 @@
 #include <SPI.h>
 #include <WiFi.h>
 #include <WiFiUdp.h>
-#else
+#elif defined ARDUINOETH
 // Arduino Ethernet Shield
 #include <EthernetServer.h>
 #include <Ethernet.h>
@@ -79,35 +79,35 @@ int ConnectToNetwork()
     // check for the presence of the shield:
     if (WiFi.status() == WL_NO_SHIELD)
     {
-        OC_LOG(ERROR, TAG, ("WiFi shield not present"));
+        OIC_LOG(ERROR, TAG, ("WiFi shield not present"));
         return -1;
     }
 
     // Verify that WiFi Shield is running the firmware with all UDP fixes
     fwVersion = WiFi.firmwareVersion();
-    OC_LOG_V(INFO, TAG, "WiFi Shield Firmware version %s", fwVersion);
+    OIC_LOG_V(INFO, TAG, "WiFi Shield Firmware version %s", fwVersion);
     if ( strncmp(fwVersion, ARDUINO_WIFI_SHIELD_UDP_FW_VER, sizeof(ARDUINO_WIFI_SHIELD_UDP_FW_VER)) !=0 )
     {
-        OC_LOG(DEBUG, TAG, ("!!!!! Upgrade WiFi Shield Firmware version !!!!!!"));
+        OIC_LOG(DEBUG, TAG, ("!!!!! Upgrade WiFi Shield Firmware version !!!!!!"));
         return -1;
     }
 
     // attempt to connect to Wifi network:
     while (status != WL_CONNECTED)
     {
-        OC_LOG_V(INFO, TAG, "Attempting to connect to SSID: %s", ssid);
+        OIC_LOG_V(INFO, TAG, "Attempting to connect to SSID: %s", ssid);
         status = WiFi.begin(ssid,pass);
 
         // wait 10 seconds for connection:
         delay(10000);
     }
-    OC_LOG(DEBUG, TAG, ("Connected to wifi"));
+    OIC_LOG(DEBUG, TAG, ("Connected to wifi"));
 
     IPAddress ip = WiFi.localIP();
-    OC_LOG_V(INFO, TAG, "IP Address:  %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
+    OIC_LOG_V(INFO, TAG, "IP Address:  %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
     return 0;
 }
-#else
+#elif defined ARDUINOETH
 // Arduino Ethernet Shield
 int ConnectToNetwork()
 {
@@ -116,12 +116,12 @@ int ConnectToNetwork()
     uint8_t error = Ethernet.begin(ETHERNET_MAC);
     if (error  == 0)
     {
-        OC_LOG_V(ERROR, TAG, "error is: %d", error);
+        OIC_LOG_V(ERROR, TAG, "error is: %d", error);
         return -1;
     }
 
     IPAddress ip = Ethernet.localIP();
-    OC_LOG_V(INFO, TAG, "IP Address:  %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
+    OIC_LOG_V(INFO, TAG, "IP Address:  %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
     return 0;
 }
 #endif //ARDUINOWIFI
@@ -139,8 +139,8 @@ void PrintArduinoMemoryStats()
     extern char *__brkval;
     //address of tmp gives us the current stack boundry
     int tmp;
-    OC_LOG_V(INFO, TAG, "Stack: %u         Heap: %u", (unsigned int)&tmp, (unsigned int)__brkval);
-    OC_LOG_V(INFO, TAG, "Unallocated Memory between heap and stack: %u",
+    OIC_LOG_V(INFO, TAG, "Stack: %u         Heap: %u", (unsigned int)&tmp, (unsigned int)__brkval);
+    OIC_LOG_V(INFO, TAG, "Unallocated Memory between heap and stack: %u",
             ((unsigned int)&tmp - (unsigned int)__brkval));
     #endif
 }
@@ -155,13 +155,13 @@ OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandle
     OCRepPayload* payload = OCRepPayloadCreate();
     if(!payload)
     {
-        OC_LOG(ERROR, TAG, ("Failed to allocate Payload"));
+        OIC_LOG(ERROR, TAG, ("Failed to allocate Payload"));
         return OC_EH_ERROR;
     }
 
     if(entityHandlerRequest && (flag & OC_REQUEST_FLAG))
     {
-        OC_LOG (INFO, TAG, ("Flag includes OC_REQUEST_FLAG"));
+        OIC_LOG (INFO, TAG, ("Flag includes OC_REQUEST_FLAG"));
 
         if(OC_REST_GET == entityHandlerRequest->method)
         {
@@ -194,7 +194,7 @@ OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandle
             // Send the response
             if (OCDoResponse(&response) != OC_STACK_OK)
             {
-                OC_LOG(ERROR, TAG, "Error sending response");
+                OIC_LOG(ERROR, TAG, "Error sending response");
                 ehRet = OC_EH_ERROR;
             }
         }
@@ -203,12 +203,12 @@ OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandle
     {
         if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
         {
-            OC_LOG (INFO, TAG, ("Received OC_OBSERVE_REGISTER from client"));
+            OIC_LOG (INFO, TAG, ("Received OC_OBSERVE_REGISTER from client"));
             gLightUnderObservation = 1;
         }
         else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
         {
-            OC_LOG (INFO, TAG, ("Received OC_OBSERVE_DEREGISTER from client"));
+            OIC_LOG (INFO, TAG, ("Received OC_OBSERVE_DEREGISTER from client"));
             gLightUnderObservation = 0;
         }
     }
@@ -229,7 +229,7 @@ void *ChangeLightRepresentation (void *param)
         Light.power += 5;
         if (gLightUnderObservation)
         {
-            OC_LOG_V(INFO, TAG, " =====> Notifying stack of new power level %d\n", Light.power);
+            OIC_LOG_V(INFO, TAG, " =====> Notifying stack of new power level %d\n", Light.power);
             result = OCNotifyAllObservers (Light.handle, OC_NA_QOS);
             if (OC_STACK_NO_OBSERVERS == result)
             {
@@ -245,20 +245,22 @@ void setup()
 {
     // Add your initialization code here
     // Note : This will initialize Serial port on Arduino at 115200 bauds
-    OC_LOG_INIT();
-    OC_LOG(DEBUG, TAG, ("OCServer is starting..."));
+    OIC_LOG_INIT();
+    OIC_LOG(DEBUG, TAG, ("OCServer is starting..."));
 
     // Connect to Ethernet or WiFi network
+#if defined(ARDUINOWIFI) || defined(ARDUINOETH)
     if (ConnectToNetwork() != 0)
     {
-        OC_LOG(ERROR, TAG, ("Unable to connect to network"));
+        OIC_LOG(ERROR, TAG, ("Unable to connect to network"));
         return;
     }
+#endif
 
     // Initialize the OC Stack in Server mode
     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, ("OCStack init error"));
+        OIC_LOG(ERROR, TAG, ("OCStack init error"));
         return;
     }
 
@@ -279,7 +281,7 @@ void loop()
     // Give CPU cycles to OCStack to perform send/recv and other OCStack stuff
     if (OCProcess() != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, ("OCStack process error"));
+        OIC_LOG(ERROR, TAG, ("OCStack process error"));
         return;
     }
     ChangeLightRepresentation(NULL);
@@ -295,7 +297,7 @@ void createLightResource()
             OCEntityHandlerCb,
             NULL,
             OC_DISCOVERABLE|OC_OBSERVABLE);
-    OC_LOG_V(INFO, TAG, "Created Light resource with result: %s", getResult(res));
+    OIC_LOG_V(INFO, TAG, "Created Light resource with result: %s", getResult(res));
 }
 
 const char *getResult(OCStackResult result) {
index d1ea32e..23053e7 100644 (file)
@@ -60,8 +60,6 @@ static std::string coapServerResource = "/a/light";
 
 void StripNewLineChar(char* str);
 
-// The handle for the observe registration
-OCDoHandle gObserveDoHandle;
 #ifdef WITH_PRESENCE
 // The handle for observe registration
 OCDoHandle gPresenceHandle;
@@ -101,41 +99,41 @@ OCPayload* putPayload()
 
 static void PrintUsage()
 {
-    OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1..17> -c <0|1>");
-    OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
-    OC_LOG(INFO, TAG, "-c 0 : Use Default connectivity(IP)");
-    OC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
-    OC_LOG(INFO, TAG, "-t 1  :  Discover Resources");
-    OC_LOG(INFO, TAG, "-t 2  :  Discover Resources and Initiate Nonconfirmable Get Request");
-    OC_LOG(INFO, TAG, "-t 3  :  Discover Resources and Initiate Nonconfirmable Get Request"
+    OIC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1..17> -c <0|1>");
+    OIC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
+    OIC_LOG(INFO, TAG, "-c 0 : Use Default connectivity(IP)");
+    OIC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
+    OIC_LOG(INFO, TAG, "-t 1  :  Discover Resources");
+    OIC_LOG(INFO, TAG, "-t 2  :  Discover Resources and Initiate Nonconfirmable Get Request");
+    OIC_LOG(INFO, TAG, "-t 3  :  Discover Resources and Initiate Nonconfirmable Get Request"
             " with query filter.");
-    OC_LOG(INFO, TAG, "-t 4  :  Discover Resources and Initiate Nonconfirmable Put Requests");
-    OC_LOG(INFO, TAG, "-t 5  :  Discover Resources and Initiate Nonconfirmable Post Requests");
-    OC_LOG(INFO, TAG, "-t 6  :  Discover Resources and Initiate Nonconfirmable Delete Requests");
-    OC_LOG(INFO, TAG, "-t 7  :  Discover Resources and Initiate Nonconfirmable Observe Requests");
-    OC_LOG(INFO, TAG, "-t 8  :  Discover Resources and Initiate Nonconfirmable Get Request "\
+    OIC_LOG(INFO, TAG, "-t 4  :  Discover Resources and Initiate Nonconfirmable Put Requests");
+    OIC_LOG(INFO, TAG, "-t 5  :  Discover Resources and Initiate Nonconfirmable Post Requests");
+    OIC_LOG(INFO, TAG, "-t 6  :  Discover Resources and Initiate Nonconfirmable Delete Requests");
+    OIC_LOG(INFO, TAG, "-t 7  :  Discover Resources and Initiate Nonconfirmable Observe Requests");
+    OIC_LOG(INFO, TAG, "-t 8  :  Discover Resources and Initiate Nonconfirmable Get Request "\
             "for a resource which is unavailable");
-    OC_LOG(INFO, TAG, "-t 9  :  Discover Resources and Initiate Confirmable Get Request");
-    OC_LOG(INFO, TAG, "-t 10 :  Discover Resources and Initiate Confirmable Post Request");
-    OC_LOG(INFO, TAG, "-t 11 :  Discover Resources and Initiate Confirmable Delete Requests");
-    OC_LOG(INFO, TAG, "-t 12 :  Discover Resources and Initiate Confirmable Observe Requests"\
+    OIC_LOG(INFO, TAG, "-t 9  :  Discover Resources and Initiate Confirmable Get Request");
+    OIC_LOG(INFO, TAG, "-t 10 :  Discover Resources and Initiate Confirmable Post Request");
+    OIC_LOG(INFO, TAG, "-t 11 :  Discover Resources and Initiate Confirmable Delete Requests");
+    OIC_LOG(INFO, TAG, "-t 12 :  Discover Resources and Initiate Confirmable Observe Requests"\
             " and cancel with Low QoS");
 
 #ifdef WITH_PRESENCE
-    OC_LOG(INFO, TAG, "-t 13 :  Discover Resources and Initiate Nonconfirmable presence");
-    OC_LOG(INFO, TAG, "-t 14 :  Discover Resources and Initiate Nonconfirmable presence with "\
+    OIC_LOG(INFO, TAG, "-t 13 :  Discover Resources and Initiate Nonconfirmable presence");
+    OIC_LOG(INFO, TAG, "-t 14 :  Discover Resources and Initiate Nonconfirmable presence with "\
             "filter");
-    OC_LOG(INFO, TAG, "-t 15 :  Discover Resources and Initiate Nonconfirmable presence with "\
+    OIC_LOG(INFO, TAG, "-t 15 :  Discover Resources and Initiate Nonconfirmable presence with "\
             "2 filters");
-    OC_LOG(INFO, TAG, "-t 16 :  Discover Resources and Initiate Nonconfirmable multicast presence.");
+    OIC_LOG(INFO, TAG, "-t 16 :  Discover Resources and Initiate Nonconfirmable multicast presence.");
 #endif
 
-    OC_LOG(INFO, TAG, "-t 17 :  Discover Resources and Initiate Nonconfirmable Observe Requests "\
+    OIC_LOG(INFO, TAG, "-t 17 :  Discover Resources and Initiate Nonconfirmable Observe Requests "\
             "then cancel immediately with High QOS");
-    OC_LOG(INFO, TAG, "-t 18 :  Discover Resources and Initiate Nonconfirmable Get Request and "\
+    OIC_LOG(INFO, TAG, "-t 18 :  Discover Resources and Initiate Nonconfirmable Get Request and "\
             "add  vendor specific header options");
-    OC_LOG(INFO, TAG, "-t 19 :  Discover Platform");
-    OC_LOG(INFO, TAG, "-t 20 :  Discover Devices");
+    OIC_LOG(INFO, TAG, "-t 19 :  Discover Platform");
+    OIC_LOG(INFO, TAG, "-t 20 :  Discover Devices");
 }
 
 OCStackResult InvokeOCDoResource(std::ostringstream &query,
@@ -160,11 +158,7 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query,
 
     if (ret != OC_STACK_OK)
     {
-        OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
-    }
-    else if (method == OC_REST_OBSERVE || method == OC_REST_OBSERVE_ALL)
-    {
-        gObserveDoHandle = handle;
+        OIC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
     }
 #ifdef WITH_PRESENCE
     else if (method == OC_REST_PRESENCE)
@@ -181,18 +175,18 @@ OCStackApplicationResult putReqCB(void* ctx, OCDoHandle /*handle*/,
 {
     if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
+        OIC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
     }
 
     if (clientResponse)
     {
-        OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
-        OC_LOG_PAYLOAD(INFO, clientResponse->payload);
-        OC_LOG(INFO, TAG, ("=============> Put Response"));
+        OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
+        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        OIC_LOG(INFO, TAG, ("=============> Put Response"));
     }
     else
     {
-        OC_LOG_V(INFO, TAG, "putReqCB received Null clientResponse");
+        OIC_LOG_V(INFO, TAG, "putReqCB received Null clientResponse");
     }
     return OC_STACK_DELETE_TRANSACTION;
 }
@@ -202,18 +196,18 @@ OCStackApplicationResult postReqCB(void *ctx, OCDoHandle /*handle*/,
 {
     if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
+        OIC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
     }
 
     if (clientResponse)
     {
-        OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
-        OC_LOG_PAYLOAD(INFO, clientResponse->payload);
-        OC_LOG(INFO, TAG, ("=============> Post Response"));
+        OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
+        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        OIC_LOG(INFO, TAG, ("=============> Post Response"));
     }
     else
     {
-        OC_LOG_V(INFO, TAG, "postReqCB received Null clientResponse");
+        OIC_LOG_V(INFO, TAG, "postReqCB received Null clientResponse");
     }
     return OC_STACK_DELETE_TRANSACTION;
 }
@@ -224,18 +218,18 @@ OCStackApplicationResult deleteReqCB(void *ctx,
 {
     if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "Callback Context for DELETE recvd successfully");
+        OIC_LOG(INFO, TAG, "Callback Context for DELETE recvd successfully");
     }
 
     if (clientResponse)
     {
-        OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
-        OC_LOG_PAYLOAD(INFO, clientResponse->payload);
-        OC_LOG(INFO, TAG, ("=============> Delete Response"));
+        OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
+        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        OIC_LOG(INFO, TAG, ("=============> Delete Response"));
     }
     else
     {
-        OC_LOG_V(INFO, TAG, "deleteReqCB received Null clientResponse");
+        OIC_LOG_V(INFO, TAG, "deleteReqCB received Null clientResponse");
     }
     return OC_STACK_DELETE_TRANSACTION;
 }
@@ -245,33 +239,33 @@ OCStackApplicationResult getReqCB(void* ctx, OCDoHandle /*handle*/,
 {
     if (clientResponse == NULL)
     {
-        OC_LOG(INFO, TAG, "getReqCB received NULL clientResponse");
+        OIC_LOG(INFO, TAG, "getReqCB received NULL clientResponse");
         return   OC_STACK_DELETE_TRANSACTION;
     }
 
     if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
+        OIC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
     }
 
-    OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
-    OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
-    OC_LOG_PAYLOAD(INFO, clientResponse->payload);
-    OC_LOG(INFO, TAG, ("=============> Get Response"));
+    OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
+    OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
+    OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
+    OIC_LOG(INFO, TAG, ("=============> Get Response"));
 
     if (clientResponse->numRcvdVendorSpecificHeaderOptions > 0)
     {
-        OC_LOG (INFO, TAG, "Received vendor specific options");
+        OIC_LOG (INFO, TAG, "Received vendor specific options");
         uint8_t i = 0;
         OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
         for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
         {
             if (((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
             {
-                OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
+                OIC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
                         ((OCHeaderOption)rcvdOptions[i]).optionID );
 
-                OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
+                OIC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
                     MAX_HEADER_OPTION_DATA_LENGTH);
             }
         }
@@ -279,59 +273,61 @@ OCStackApplicationResult getReqCB(void* ctx, OCDoHandle /*handle*/,
     return OC_STACK_DELETE_TRANSACTION;
 }
 
-OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle /*handle*/,
+OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle handle,
                                   OCClientResponse * clientResponse)
 {
     if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "Callback Context for OBS query recvd successfully");
+        OIC_LOG(INFO, TAG, "Callback Context for OBS query recvd successfully");
     }
 
     if (clientResponse)
     {
-        OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
-        OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
-        OC_LOG_V(INFO, TAG, "Callback Context for OBSERVE notification recvd successfully %d",
+        OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
+        OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
+        OIC_LOG_V(INFO, TAG, "Callback Context for OBSERVE notification recvd successfully %d",
                 gNumObserveNotifies);
-        OC_LOG_PAYLOAD(INFO, clientResponse->payload);
-        OC_LOG(INFO, TAG, ("=============> Obs Response"));
+        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        OIC_LOG(INFO, TAG, ("=============> Obs Response"));
         gNumObserveNotifies++;
-        if (gNumObserveNotifies == 15) //large number to test observing in DELETE case.
+        if (gNumObserveNotifies > 15) //large number to test observing in DELETE case.
         {
             if (TestCase == TEST_OBS_REQ_NON || TestCase == TEST_OBS_REQ_CON)
             {
-                if (OCCancel (gObserveDoHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK)
+                OIC_LOG(ERROR, TAG, "Cancelling with LOW QOS");
+                if (OCCancel (handle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK)
                 {
-                    OC_LOG(ERROR, TAG, "Observe cancel error");
+                    OIC_LOG(ERROR, TAG, "Observe cancel error");
                 }
                 return OC_STACK_DELETE_TRANSACTION;
             }
             else if (TestCase == TEST_OBS_REQ_NON_CANCEL_IMM)
             {
-                if (OCCancel (gObserveDoHandle, OC_HIGH_QOS, NULL, 0) != OC_STACK_OK)
+                OIC_LOG(ERROR, TAG, "Cancelling with HIGH QOS");
+                if (OCCancel (handle, OC_HIGH_QOS, NULL, 0) != OC_STACK_OK)
                 {
-                    OC_LOG(ERROR, TAG, "Observe cancel error");
+                    OIC_LOG(ERROR, TAG, "Observe cancel error");
                 }
             }
         }
         if (clientResponse->sequenceNumber == OC_OBSERVE_REGISTER)
         {
-            OC_LOG(INFO, TAG, "This also serves as a registration confirmation");
+            OIC_LOG(INFO, TAG, "This also serves as a registration confirmation");
         }
         else if (clientResponse->sequenceNumber == OC_OBSERVE_DEREGISTER)
         {
-            OC_LOG(INFO, TAG, "This also serves as a deregistration confirmation");
+            OIC_LOG(INFO, TAG, "This also serves as a deregistration confirmation");
             return OC_STACK_DELETE_TRANSACTION;
         }
         else if (clientResponse->sequenceNumber == OC_OBSERVE_NO_OPTION)
         {
-            OC_LOG(INFO, TAG, "This also tells you that registration/deregistration failed");
+            OIC_LOG(INFO, TAG, "This also tells you that registration/deregistration failed");
             return OC_STACK_DELETE_TRANSACTION;
         }
     }
     else
     {
-        OC_LOG_V(INFO, TAG, "obsReqCB received Null clientResponse");
+        OIC_LOG_V(INFO, TAG, "obsReqCB received Null clientResponse");
     }
     return OC_STACK_KEEP_TRANSACTION;
 }
@@ -341,29 +337,29 @@ OCStackApplicationResult presenceCB(void* ctx, OCDoHandle /*handle*/,
 {
     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "Callback Context for Presence recvd successfully");
+        OIC_LOG(INFO, TAG, "Callback Context for Presence recvd successfully");
     }
 
     if (clientResponse)
     {
-        OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
-        OC_LOG_V(INFO, TAG, "Callback Context for Presence notification recvd successfully %d",
+        OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
+        OIC_LOG_V(INFO, TAG, "Callback Context for Presence notification recvd successfully %d",
                 gNumPresenceNotifies);
-        OC_LOG_PAYLOAD(INFO, clientResponse->payload);
-        OC_LOG(INFO, TAG, ("=============> Presence Response"));
+        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        OIC_LOG(INFO, TAG, ("=============> Presence Response"));
         gNumPresenceNotifies++;
         if (gNumPresenceNotifies == 20)
         {
             if (OCCancel(gPresenceHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK)
             {
-                OC_LOG(ERROR, TAG, "Presence cancel error");
+                OIC_LOG(ERROR, TAG, "Presence cancel error");
             }
             return OC_STACK_DELETE_TRANSACTION;
         }
     }
     else
     {
-        OC_LOG_V(INFO, TAG, "presenceCB received Null clientResponse");
+        OIC_LOG_V(INFO, TAG, "presenceCB received Null clientResponse");
     }
     return OC_STACK_KEEP_TRANSACTION;
 }
@@ -375,24 +371,47 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
 {
     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
+        OIC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
     }
 
     if (clientResponse)
     {
-        OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
+        OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
 
         std::string connectionType = getConnectivityType (clientResponse->connType);
-        OC_LOG_V(INFO, TAG, "Discovered on %s", connectionType.c_str());
-        OC_LOG_V(INFO, TAG,
+        OIC_LOG_V(INFO, TAG, "Discovered on %s", connectionType.c_str());
+        OIC_LOG_V(INFO, TAG,
                 "Device =============> Discovered @ %s:%d",
                 clientResponse->devAddr.addr,
                 clientResponse->devAddr.port);
-        OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
 
         ConnType = clientResponse->connType;
         serverAddr = clientResponse->devAddr;
-        parseClientResponse(clientResponse);
+
+        OCDiscoveryPayload *payload = (OCDiscoveryPayload*) clientResponse->payload;
+        if (!payload)
+        {
+            return OC_STACK_DELETE_TRANSACTION;
+        }
+
+        OCResourcePayload *resource = (OCResourcePayload*) payload->resources;
+        int found = 0;
+        while (resource)
+        {
+            if(resource->uri && strcmp(resource->uri, coapServerResource.c_str()) == 0)
+            {
+                found = 1;
+                break;
+            }
+            resource = resource->next;
+        }
+
+        if(!found)
+        {
+            OIC_LOG_V (INFO, TAG, "No /a/light in payload");
+            return OC_STACK_KEEP_TRANSACTION;
+        }
 
         switch(TestCase)
         {
@@ -454,7 +473,7 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
     }
     else
     {
-        OC_LOG_V(INFO, TAG, "discoveryReqCB received Null clientResponse");
+        OIC_LOG_V(INFO, TAG, "discoveryReqCB received Null clientResponse");
     }
     return OC_STACK_KEEP_TRANSACTION;
 }
@@ -465,17 +484,17 @@ OCStackApplicationResult PlatformDiscoveryReqCB(void* ctx,
 {
     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "Callback Context for Platform DISCOVER query recvd successfully");
+        OIC_LOG(INFO, TAG, "Callback Context for Platform DISCOVER query recvd successfully");
     }
 
     if (clientResponse)
     {
-        OC_LOG(INFO, TAG, ("Discovery Response:"));
-        OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        OIC_LOG(INFO, TAG, ("Discovery Response:"));
+        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
     }
     else
     {
-        OC_LOG_V(INFO, TAG, "PlatformDiscoveryReqCB received Null clientResponse");
+        OIC_LOG_V(INFO, TAG, "PlatformDiscoveryReqCB received Null clientResponse");
     }
 
     return (UnicastDiscovery) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION;
@@ -486,17 +505,17 @@ OCStackApplicationResult DeviceDiscoveryReqCB(void* ctx, OCDoHandle /*handle*/,
 {
     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "Callback Context for Device DISCOVER query recvd successfully");
+        OIC_LOG(INFO, TAG, "Callback Context for Device DISCOVER query recvd successfully");
     }
 
     if (clientResponse)
     {
-        OC_LOG(INFO, TAG, ("Discovery Response:"));
-        OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        OIC_LOG(INFO, TAG, ("Discovery Response:"));
+        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
     }
     else
     {
-        OC_LOG_V(INFO, TAG, "PlatformDiscoveryReqCB received Null clientResponse");
+        OIC_LOG_V(INFO, TAG, "PlatformDiscoveryReqCB received Null clientResponse");
     }
 
     return (UnicastDiscovery) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION;
@@ -506,7 +525,7 @@ OCStackApplicationResult DeviceDiscoveryReqCB(void* ctx, OCDoHandle /*handle*/,
 int InitPresence()
 {
     OCStackResult result = OC_STACK_OK;
-    OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
+    OIC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
     std::ostringstream querySuffix;
     query << OC_RSRVD_PRESENCE_URI;
@@ -549,27 +568,27 @@ int InitPresence()
 
 int InitGetRequestToUnavailableResource(OCQualityOfService qos)
 {
-    OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
     query << "/SomeUnknownResource";
+    OIC_LOG_V(INFO, TAG, "\nExecuting %s with query %s", __func__, query.str().c_str());
     return (InvokeOCDoResource(query, &serverAddr, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS,
             getReqCB, NULL, 0));
 }
 
 int InitObserveRequest(OCQualityOfService qos)
 {
-    OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
     query << coapServerResource;
+    OIC_LOG_V(INFO, TAG, "\nExecuting %s with query %s", __func__, query.str().c_str());
     return (InvokeOCDoResource(query, &serverAddr, OC_REST_OBSERVE,
               (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, obsReqCB, NULL, 0));
 }
 
 int InitPutRequest(OCQualityOfService qos)
 {
-    OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
     query << coapServerResource;
+    OIC_LOG_V(INFO, TAG, "\nExecuting %s with query %s", __func__, query.str().c_str());
     return (InvokeOCDoResource(query, &serverAddr, OC_REST_PUT, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS,
             putReqCB, NULL, 0));
 }
@@ -577,10 +596,11 @@ int InitPutRequest(OCQualityOfService qos)
 int InitPostRequest(OCQualityOfService qos)
 {
     OCStackResult result;
-    OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
+
     std::ostringstream query;
     query << coapServerResource;
 
+    OIC_LOG_V(INFO, TAG, "\nExecuting %s with query %s", __func__, query.str().c_str());
     // First POST operation (to create an Light instance)
     result = InvokeOCDoResource(query, &serverAddr, OC_REST_POST,
                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
@@ -588,7 +608,7 @@ int InitPostRequest(OCQualityOfService qos)
     if (OC_STACK_OK != result)
     {
         // Error can happen if for example, network connectivity is down
-        OC_LOG(INFO, TAG, "First POST call did not succeed");
+        OIC_LOG(INFO, TAG, "First POST call did not succeed");
     }
 
     // Second POST operation (to create an Light instance)
@@ -597,7 +617,7 @@ int InitPostRequest(OCQualityOfService qos)
                                postReqCB, NULL, 0);
     if (OC_STACK_OK != result)
     {
-        OC_LOG(INFO, TAG, "Second POST call did not succeed");
+        OIC_LOG(INFO, TAG, "Second POST call did not succeed");
     }
 
     // This POST operation will update the original resourced /a/light
@@ -612,7 +632,7 @@ void* RequestDeleteDeathResourceTask(void* myqos)
     std::ostringstream query;
     query << coapServerResource;
 
-    OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
+    OIC_LOG_V(INFO, TAG, "\nExecuting %s with query %s", __func__, query.str().c_str());
 
     // Second DELETE operation to delete the resource that might have been removed already.
     OCQualityOfService qos;
@@ -631,7 +651,7 @@ void* RequestDeleteDeathResourceTask(void* myqos)
 
     if (OC_STACK_OK != result)
     {
-        OC_LOG(INFO, TAG, "Second DELETE call did not succeed");
+        OIC_LOG(INFO, TAG, "Second DELETE call did not succeed");
     }
 
     return NULL;
@@ -643,7 +663,7 @@ int InitDeleteRequest(OCQualityOfService qos)
     std::ostringstream query;
     query << coapServerResource;
 
-    OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
+    OIC_LOG_V(INFO, TAG, "\nExecuting %s with query %s", __func__, query.str().c_str());
 
     // First DELETE operation
     result = InvokeOCDoResource(query, &serverAddr, OC_REST_DELETE,
@@ -652,7 +672,7 @@ int InitDeleteRequest(OCQualityOfService qos)
     if (OC_STACK_OK != result)
     {
         // Error can happen if for example, network connectivity is down
-        OC_LOG(INFO, TAG, "First DELETE call did not succeed");
+        OIC_LOG(INFO, TAG, "First DELETE call did not succeed");
     }
     else
     {
@@ -661,7 +681,7 @@ int InitDeleteRequest(OCQualityOfService qos)
         pthread_create (&threadId, NULL, RequestDeleteDeathResourceTask, (void*)qos);
     }
 
-    OC_LOG_V(INFO, TAG, "\n\nExit  %s", __func__);
+    OIC_LOG_V(INFO, TAG, "\n\nExit  %s", __func__);
     return result;
 }
 
@@ -670,16 +690,16 @@ int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptio
 
     OCHeaderOption options[MAX_HEADER_OPTIONS];
 
-    OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
     query << coapServerResource;
 
     // ocserver is written to only process "power<X" query.
     if (getWithQuery)
     {
-        OC_LOG(INFO, TAG, "Using query power<50");
+        OIC_LOG(INFO, TAG, "Using query power<50");
         query << "?power<50";
     }
+    OIC_LOG_V(INFO, TAG, "\nExecuting %s with query %s", __func__, query.str().c_str());
 
     if (withVendorSpecificHeaderOptions)
     {
@@ -709,7 +729,7 @@ int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptio
 
 int InitPlatformDiscovery(OCQualityOfService qos)
 {
-    OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
+    OIC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
 
     OCStackResult ret;
     OCCallbackData cbData;
@@ -726,7 +746,7 @@ int InitPlatformDiscovery(OCQualityOfService qos)
                        &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack device error");
+        OIC_LOG(ERROR, TAG, "OCStack device error");
     }
 
     return ret;
@@ -734,7 +754,7 @@ int InitPlatformDiscovery(OCQualityOfService qos)
 
 int InitDeviceDiscovery(OCQualityOfService qos)
 {
-    OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
+    OIC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
 
     OCStackResult ret;
     OCCallbackData cbData;
@@ -751,7 +771,7 @@ int InitDeviceDiscovery(OCQualityOfService qos)
                        &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack device error");
+        OIC_LOG(ERROR, TAG, "OCStack device error");
     }
 
     return ret;
@@ -774,7 +794,7 @@ int InitDiscovery(OCQualityOfService qos)
                        &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack resource error");
+        OIC_LOG(ERROR, TAG, "OCStack resource error");
     }
     return ret;
 }
@@ -812,7 +832,7 @@ int main(int argc, char* argv[])
 
     if (OCInit1(OC_CLIENT, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack init error");
+        OIC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
 
@@ -825,7 +845,7 @@ int main(int argc, char* argv[])
     {
         if (OC_STACK_OK != OCProcess())
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             return 0;
         }
         usleep(SLEEP_DURATION);
@@ -837,7 +857,7 @@ int main(int argc, char* argv[])
     }
     else
     {
-        OC_LOG(INFO, TAG, "Default Connectivity type selected...");
+        OIC_LOG(INFO, TAG, "Default Connectivity type selected...");
         PrintUsage();
     }
 
@@ -845,9 +865,9 @@ int main(int argc, char* argv[])
 
     if (UnicastDiscovery)
     {
-        OC_LOG(INFO, TAG, "Enter IP address of server with optional port number");
-        OC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
-        OC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
+        OIC_LOG(INFO, TAG, "Enter IP address of server with optional port number");
+        OIC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
+        OIC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
 
         if (fgets(discoveryAddr, sizeof (discoveryAddr), stdin))
         {
@@ -856,7 +876,7 @@ int main(int argc, char* argv[])
         }
         else
         {
-            OC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
+            OIC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
             return OC_STACK_INVALID_PARAM;
         }
     }
@@ -875,25 +895,25 @@ int main(int argc, char* argv[])
     }
 
     // Break from loop with Ctrl+C
-    OC_LOG(INFO, TAG, "Entering occlient main loop...");
+    OIC_LOG(INFO, TAG, "Entering occlient main loop...");
     signal(SIGINT, handleSigInt);
     while (!gQuitFlag)
     {
 
         if (OCProcess() != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             return 0;
         }
 #ifndef ROUTING_GATEAWAY
         sleep(1);
 #endif
     }
-    OC_LOG(INFO, TAG, "Exiting occlient main loop...");
+    OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
 
     if (OCStop() != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack stop error");
+        OIC_LOG(ERROR, TAG, "OCStack stop error");
     }
 
     return 0;
@@ -922,13 +942,3 @@ std::string getConnectivityType (OCConnectivityType connType)
             return "Incorrect connectivity";
     }
 }
-
-std::string getQueryStrForGetPut(OCClientResponse * /*clientResponse*/)
-{
-    return "/a/light";
-}
-
-void parseClientResponse(OCClientResponse * clientResponse)
-{
-    coapServerResource = getQueryStrForGetPut(clientResponse);
-}
index 419593a..61622eb 100644 (file)
@@ -78,15 +78,15 @@ OCPayload* putPayload()
 
 static void PrintUsage()
 {
-    OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
-    OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
-    OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
-    OC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
+    OIC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
+    OIC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
+    OIC_LOG(INFO, TAG, "-t 1 : Discover Resources");
+    OIC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
             " Initiate Nonconfirmable Get/Put/Post Requests");
-    OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate "
+    OIC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate "
             "Confirmable Get/Put/Post Requests");
-    OC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
-    OC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
+    OIC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
+    OIC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
 }
 
 /*
@@ -117,7 +117,7 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query,
 
     if (ret != OC_STACK_OK)
     {
-        OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d",
+        OIC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d",
                  ret, method);
     }
 
@@ -129,21 +129,21 @@ OCStackApplicationResult putReqCB(void* ctx, OCDoHandle /*handle*/,
 {
     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "<====Callback Context for PUT received successfully====>");
+        OIC_LOG(INFO, TAG, "<====Callback Context for PUT received successfully====>");
     }
     else
     {
-        OC_LOG(ERROR, TAG, "<====Callback Context for PUT fail====>");
+        OIC_LOG(ERROR, TAG, "<====Callback Context for PUT fail====>");
     }
 
     if(clientResponse)
     {
-        OC_LOG_PAYLOAD(INFO, clientResponse->payload);
-        OC_LOG(INFO, TAG, ("=============> Put Response"));
+        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        OIC_LOG(INFO, TAG, ("=============> Put Response"));
     }
     else
     {
-        OC_LOG(ERROR, TAG, "<====PUT Callback fail to receive clientResponse====>\n");
+        OIC_LOG(ERROR, TAG, "<====PUT Callback fail to receive clientResponse====>\n");
     }
     return OC_STACK_DELETE_TRANSACTION;
 }
@@ -153,21 +153,21 @@ OCStackApplicationResult postReqCB(void *ctx, OCDoHandle /*handle*/,
 {
     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "<====Callback Context for POST received successfully====>");
+        OIC_LOG(INFO, TAG, "<====Callback Context for POST received successfully====>");
     }
     else
     {
-        OC_LOG(ERROR, TAG, "<====Callback Context for POST fail====>");
+        OIC_LOG(ERROR, TAG, "<====Callback Context for POST fail====>");
     }
 
     if(clientResponse)
     {
-        OC_LOG_PAYLOAD(INFO, clientResponse->payload);
-        OC_LOG(INFO, TAG, ("=============> Post Response"));
+        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        OIC_LOG(INFO, TAG, ("=============> Post Response"));
     }
     else
     {
-        OC_LOG(ERROR, TAG, "<====POST Callback fail to receive clientResponse====>\n");
+        OIC_LOG(ERROR, TAG, "<====POST Callback fail to receive clientResponse====>\n");
     }
 
     return OC_STACK_DELETE_TRANSACTION;
@@ -178,33 +178,33 @@ OCStackApplicationResult getReqCB(void* ctx, OCDoHandle /*handle*/,
 {
     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "<====Callback Context for GET received successfully====>");
+        OIC_LOG(INFO, TAG, "<====Callback Context for GET received successfully====>");
     }
     else
     {
-        OC_LOG(ERROR, TAG, "<====Callback Context for GET fail====>");
+        OIC_LOG(ERROR, TAG, "<====Callback Context for GET fail====>");
     }
 
     if (clientResponse)
     {
-        OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
-        OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
-        OC_LOG_PAYLOAD(INFO, clientResponse->payload);
-        OC_LOG(INFO, TAG, ("=============> Get Response"));
+        OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
+        OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
+        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        OIC_LOG(INFO, TAG, ("=============> Get Response"));
 
         if (clientResponse->numRcvdVendorSpecificHeaderOptions > 0 )
         {
-            OC_LOG (INFO, TAG, "Received vendor specific options");
+            OIC_LOG (INFO, TAG, "Received vendor specific options");
             uint8_t i = 0;
             OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
             for (i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
             {
                 if (((OCHeaderOption) rcvdOptions[i]).protocolID == OC_COAP_ID)
                 {
-                    OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
+                    OIC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
                             ((OCHeaderOption)rcvdOptions[i]).optionID );
 
-                    OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
+                    OIC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
                         MAX_HEADER_OPTION_DATA_LENGTH);
                 }
             }
@@ -212,7 +212,7 @@ OCStackApplicationResult getReqCB(void* ctx, OCDoHandle /*handle*/,
     }
     else
     {
-        OC_LOG(ERROR, TAG, "<====GET Callback fail to receive clientResponse====>\n");
+        OIC_LOG(ERROR, TAG, "<====GET Callback fail to receive clientResponse====>\n");
     }
     return OC_STACK_DELETE_TRANSACTION;
 }
@@ -225,27 +225,27 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
 {
     if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "\n<====Callback Context for DISCOVERY query "
+        OIC_LOG(INFO, TAG, "\n<====Callback Context for DISCOVERY query "
                "received successfully====>");
     }
     else
     {
-        OC_LOG(ERROR, TAG, "\n<====Callback Context for DISCOVERY fail====>");
+        OIC_LOG(ERROR, TAG, "\n<====Callback Context for DISCOVERY fail====>");
     }
 
     if (clientResponse)
     {
-        OC_LOG_V(INFO, TAG,
+        OIC_LOG_V(INFO, TAG,
                 "Device =============> Discovered @ %s:%d",
                 clientResponse->devAddr.addr,
                 clientResponse->devAddr.port);
-        OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
 
         collectUniqueResource(clientResponse);
     }
     else
     {
-        OC_LOG(ERROR, TAG, "<====DISCOVERY Callback fail to receive clientResponse====>\n");
+        OIC_LOG(ERROR, TAG, "<====DISCOVERY Callback fail to receive clientResponse====>\n");
     }
     return (UnicastDiscovery) ?
            OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
@@ -259,11 +259,11 @@ int InitPutRequest(OCQualityOfService qos)
 
     if(!resource)
     {
-        OC_LOG_V(ERROR, TAG, "Resource null, can't do PUT request\n");
+        OIC_LOG_V(ERROR, TAG, "Resource null, can't do PUT request\n");
         return -1;
     }
     query << resource->uri;
-    OC_LOG_V(INFO, TAG,"Executing InitPutRequest, Query: %s", query.str().c_str());
+    OIC_LOG_V(INFO, TAG,"Executing InitPutRequest, Query: %s", query.str().c_str());
 
     return (InvokeOCDoResource(query, OC_REST_PUT, &resource->endpoint,
            ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
@@ -279,12 +279,12 @@ int InitPostRequest(OCQualityOfService qos)
 
     if(!resource)
     {
-        OC_LOG_V(ERROR, TAG, "Resource null, can't do POST request\n");
+        OIC_LOG_V(ERROR, TAG, "Resource null, can't do POST request\n");
         return -1;
     }
 
     query << resource->uri;
-    OC_LOG_V(INFO, TAG,"Executing InitPostRequest, Query: %s", query.str().c_str());
+    OIC_LOG_V(INFO, TAG,"Executing InitPostRequest, Query: %s", query.str().c_str());
 
     // First POST operation (to create an LED instance)
     result = InvokeOCDoResource(query, OC_REST_POST, &resource->endpoint,
@@ -293,7 +293,7 @@ int InitPostRequest(OCQualityOfService qos)
     if (OC_STACK_OK != result)
     {
         // Error can happen if for example, network connectivity is down
-        OC_LOG(ERROR, TAG, "First POST call did not succeed");
+        OIC_LOG(ERROR, TAG, "First POST call did not succeed");
     }
 
     // Second POST operation (to create an LED instance)
@@ -302,7 +302,7 @@ int InitPostRequest(OCQualityOfService qos)
             postReqCB, NULL, 0);
     if (OC_STACK_OK != result)
     {
-        OC_LOG(ERROR, TAG, "Second POST call did not succeed");
+        OIC_LOG(ERROR, TAG, "Second POST call did not succeed");
     }
 
     // This POST operation will update the original resourced /a/led
@@ -319,11 +319,11 @@ int InitGetRequest(OCQualityOfService qos)
 
     if(!resource)
     {
-        OC_LOG_V(ERROR, TAG, "Resource null, can't do GET request\n");
+        OIC_LOG_V(ERROR, TAG, "Resource null, can't do GET request\n");
         return -1;
     }
     query << resource->uri;
-    OC_LOG_V(INFO, TAG,"Executing InitGetRequest, Query: %s", query.str().c_str());
+    OIC_LOG_V(INFO, TAG,"Executing InitGetRequest, Query: %s", query.str().c_str());
 
     return (InvokeOCDoResource(query, OC_REST_GET, &resource->endpoint,
             (qos == OC_HIGH_QOS)?OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
@@ -338,9 +338,9 @@ int InitDiscovery()
 
     if (UnicastDiscovery)
     {
-        OC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
-        OC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
-        OC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
+        OIC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
+        OIC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
+        OIC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
 
         if (fgets(ipaddr, sizeof (ipaddr), stdin))
         {
@@ -348,7 +348,7 @@ int InitDiscovery()
         }
         else
         {
-            OC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
+            OIC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
             return OC_STACK_INVALID_PARAM;
         }
     }
@@ -363,7 +363,7 @@ int InitDiscovery()
                        OC_LOW_QOS, &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack resource error");
+        OIC_LOG(ERROR, TAG, "OCStack resource error");
     }
     return ret;
 }
@@ -416,17 +416,17 @@ void collectUniqueResource(const OCClientResponse * clientResponse)
         {
             if(insertResource(sidStr, res->uri, clientResponse) == 1)
             {
-                OC_LOG_V(INFO,TAG,"%s%s%s%s\n",sidStr, ":", res->uri, " is new");
+                OIC_LOG_V(INFO,TAG,"%s%s%s%s\n",sidStr, ":", res->uri, " is new");
                 printResourceList();
                 queryResource();
             }
             else {
-                OC_LOG_V(INFO,TAG,"%s%s%s%s\n",sidStr, ":", res->uri, " is old");
+                OIC_LOG_V(INFO,TAG,"%s%s%s%s\n",sidStr, ":", res->uri, " is old");
             }
         }
         else
         {
-            OC_LOG(ERROR, TAG, "Could Not Retrieve the Server ID");
+            OIC_LOG(ERROR, TAG, "Could Not Retrieve the Server ID");
         }
 
         res = res->next;
@@ -469,7 +469,7 @@ int insertResource(const char * sid, char const * uri,
     }
     else
     {
-        OC_LOG(ERROR, TAG, "Memory not allocated to ResourceNode");
+        OIC_LOG(ERROR, TAG, "Memory not allocated to ResourceNode");
         OICFree(sid_cpy);
         OICFree(uri_cpy);
         return -1;
@@ -492,37 +492,37 @@ void printResourceList()
 {
     ResourceNode * iter;
     iter = resourceList;
-    OC_LOG(INFO, TAG, "Resource List: ");
+    OIC_LOG(INFO, TAG, "Resource List: ");
     while(iter)
     {
-        OC_LOG(INFO, TAG, "*****************************************************");
-        OC_LOG_V(INFO, TAG, "sid = %s",iter->sid);
-        OC_LOG_V(INFO, TAG, "uri = %s", iter->uri);
-        OC_LOG_V(INFO, TAG, "ip = %s", iter->endpoint.addr);
-        OC_LOG_V(INFO, TAG, "port = %d", iter->endpoint.port);
+        OIC_LOG(INFO, TAG, "*****************************************************");
+        OIC_LOG_V(INFO, TAG, "sid = %s",iter->sid);
+        OIC_LOG_V(INFO, TAG, "uri = %s", iter->uri);
+        OIC_LOG_V(INFO, TAG, "ip = %s", iter->endpoint.addr);
+        OIC_LOG_V(INFO, TAG, "port = %d", iter->endpoint.port);
         switch (iter->endpoint.adapter)
         {
             case OC_ADAPTER_IP:
-                OC_LOG(INFO, TAG, "connType = Default (IPv4)");
+                OIC_LOG(INFO, TAG, "connType = Default (IPv4)");
                 break;
             case OC_ADAPTER_GATT_BTLE:
-                OC_LOG(INFO, TAG, "connType = BLE");
+                OIC_LOG(INFO, TAG, "connType = BLE");
                 break;
             case OC_ADAPTER_RFCOMM_BTEDR:
-                OC_LOG(INFO, TAG, "connType = BT");
+                OIC_LOG(INFO, TAG, "connType = BT");
                 break;
             default:
-                OC_LOG(INFO, TAG, "connType = Invalid connType");
+                OIC_LOG(INFO, TAG, "connType = Invalid connType");
                 break;
         }
-        OC_LOG(INFO, TAG, "*****************************************************");
+        OIC_LOG(INFO, TAG, "*****************************************************");
         iter = iter->next;
     }
 }
 
 void freeResourceList()
 {
-    OC_LOG(INFO, TAG, "Freeing ResourceNode List");
+    OIC_LOG(INFO, TAG, "Freeing ResourceNode List");
     ResourceNode * temp;
     while(resourceList)
     {
@@ -570,7 +570,7 @@ int main(int argc, char* argv[])
     /* Initialize OCStack*/
     if (OCInit1(OC_CLIENT, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack init error");
+        OIC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
 
@@ -580,7 +580,7 @@ int main(int argc, char* argv[])
     }
     else
     {
-        OC_LOG(INFO, TAG, "Default Connectivity type selected");
+        OIC_LOG(INFO, TAG, "Default Connectivity type selected");
         PrintUsage();
     }
 
@@ -593,17 +593,17 @@ int main(int argc, char* argv[])
     {
         if (OCProcess() != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             return 0;
         }
         sleep(2);
     }
 
     freeResourceList();
-    OC_LOG(INFO, TAG, "Exiting occlient main loop...");
+    OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
     if (OCStop() != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack stop error");
+        OIC_LOG(ERROR, TAG, "OCStack stop error");
     }
     return 0;
 }
index ff404d9..fee8870 100644 (file)
@@ -132,26 +132,26 @@ OCPayload* putPayload()
 
 void PrintUsage()
 {
-    OC_LOG(INFO, TAG, "Usage : occlientcoll -t <Test Case> -c <CA connectivity Type>");
-    OC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
-    OC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
-    OC_LOG(INFO, TAG, "Test Case 1 : Discover Resources && Initiate GET Request on an "\
+    OIC_LOG(INFO, TAG, "Usage : occlientcoll -t <Test Case> -c <CA connectivity Type>");
+    OIC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
+    OIC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
+    OIC_LOG(INFO, TAG, "Test Case 1 : Discover Resources && Initiate GET Request on an "\
             "available resource using default interface.");
-    OC_LOG(INFO, TAG, "Test Case 2 : Discover Resources && Initiate GET Request on an "\
+    OIC_LOG(INFO, TAG, "Test Case 2 : Discover Resources && Initiate GET Request on an "\
                  "available resource using batch interface.");
-    OC_LOG(INFO, TAG, "Test Case 3 : Discover Resources && Initiate GET Request on an "\
+    OIC_LOG(INFO, TAG, "Test Case 3 : Discover Resources && Initiate GET Request on an "\
                  "available resource using link list interface.");
-    OC_LOG(INFO, TAG, "Test Case 4 : Discover Resources && Initiate GET & PUT Request on an "\
+    OIC_LOG(INFO, TAG, "Test Case 4 : Discover Resources && Initiate GET & PUT Request on an "\
                  "available resource using default interface.");
-    OC_LOG(INFO, TAG, "Test Case 5 : Discover Resources && Initiate GET & PUT Request on an "\
+    OIC_LOG(INFO, TAG, "Test Case 5 : Discover Resources && Initiate GET & PUT Request on an "\
                  "available resource using batch interface.");
-    OC_LOG(INFO, TAG, "Test Case 6 : Discover Resources && Initiate GET & PUT Request on an "\
+    OIC_LOG(INFO, TAG, "Test Case 6 : Discover Resources && Initiate GET & PUT Request on an "\
                  "available resource using link list interface.");
-    OC_LOG(INFO, TAG, "Test Case 7 : Discover Resources && Initiate GET Request on an "\
+    OIC_LOG(INFO, TAG, "Test Case 7 : Discover Resources && Initiate GET Request on an "\
                  "unavailable resource using default interface.");
-    OC_LOG(INFO, TAG, "Test Case 8 : Discover Resources && Initiate GET Request on an "\
+    OIC_LOG(INFO, TAG, "Test Case 8 : Discover Resources && Initiate GET Request on an "\
                  "unavailable resource using batch interface.");
-    OC_LOG(INFO, TAG, "Test Case 9 : Discover Resources && Initiate GET Request on an "\
+    OIC_LOG(INFO, TAG, "Test Case 9 : Discover Resources && Initiate GET Request on an "\
                  "unavailable resource using link list interface.");
 }
 
@@ -160,13 +160,13 @@ OCStackApplicationResult putReqCB(void* ctx, OCDoHandle /*handle*/,
 {
     if(clientResponse == NULL)
     {
-        OC_LOG(INFO, TAG, "The clientResponse is NULL");
+        OIC_LOG(INFO, TAG, "The clientResponse is NULL");
         return   OC_STACK_DELETE_TRANSACTION;
     }
     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG_V(INFO, TAG, "Callback Context for PUT query recvd successfully");
-        OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        OIC_LOG_V(INFO, TAG, "Callback Context for PUT query recvd successfully");
+        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
     }
 
     return OC_STACK_KEEP_TRANSACTION;
@@ -175,27 +175,27 @@ OCStackApplicationResult putReqCB(void* ctx, OCDoHandle /*handle*/,
 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle /*handle*/,
                                   OCClientResponse * clientResponse)
 {
-    OC_LOG_V(INFO, TAG, "StackResult: %s",
+    OIC_LOG_V(INFO, TAG, "StackResult: %s",
             getResult(clientResponse->result));
     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
+        OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
         if(clientResponse->sequenceNumber == 0)
         {
-            OC_LOG_V(INFO, TAG, "Callback Context for GET query recvd successfully");
-            OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+            OIC_LOG_V(INFO, TAG, "Callback Context for GET query recvd successfully");
+            OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
         }
         else
         {
-            OC_LOG_V(INFO, TAG, "Callback Context for Get recvd successfully %d",
+            OIC_LOG_V(INFO, TAG, "Callback Context for Get recvd successfully %d",
                     gNumObserveNotifies);
-            OC_LOG_PAYLOAD(INFO, clientResponse->payload);;
+            OIC_LOG_PAYLOAD(INFO, clientResponse->payload);;
             gNumObserveNotifies++;
             if (gNumObserveNotifies == 3)
             {
                 if (OCCancel (gObserveDoHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK)
                 {
-                    OC_LOG(ERROR, TAG, "Observe cancel error");
+                    OIC_LOG(ERROR, TAG, "Observe cancel error");
                 }
             }
         }
@@ -211,21 +211,21 @@ OCStackApplicationResult getReqCB(void* ctx, OCDoHandle /*handle*/,
 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
                                         OCClientResponse * clientResponse)
 {
-    OC_LOG(INFO, TAG,
+    OIC_LOG(INFO, TAG,
             "Entering discoveryReqCB (Application Layer CB)");
-    OC_LOG_V(INFO, TAG, "StackResult: %s",
+    OIC_LOG_V(INFO, TAG, "StackResult: %s",
             getResult(clientResponse->result));
 
     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG_V(INFO, TAG, "Callback Context recvd successfully");
+        OIC_LOG_V(INFO, TAG, "Callback Context recvd successfully");
     }
 
-    OC_LOG_V(INFO, TAG,
+    OIC_LOG_V(INFO, TAG,
             "Device =============> Discovered @ %s:%d",
             clientResponse->devAddr.addr,
             clientResponse->devAddr.port);
-    OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+    OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
 
     ConnType = clientResponse->connType;
 
@@ -257,7 +257,7 @@ int InitGetRequestToUnavailableResource(OCClientResponse * clientResponse)
                        &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack resource error");
+        OIC_LOG(ERROR, TAG, "OCStack resource error");
     }
     return ret;
 }
@@ -273,9 +273,9 @@ int InitObserveRequest(OCClientResponse * clientResponse)
     cbData.cb = getReqCB;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
-    OC_LOG_V(INFO, TAG, "OBSERVE payload from client =");
+    OIC_LOG_V(INFO, TAG, "OBSERVE payload from client =");
     OCPayload* payload = putPayload();
-    OC_LOG_PAYLOAD(INFO, payload);
+    OIC_LOG_PAYLOAD(INFO, payload);
     OCPayloadDestroy(payload);
 
     ret = OCDoResource(&handle, OC_REST_OBSERVE, obsReg.str().c_str(),
@@ -283,7 +283,7 @@ int InitObserveRequest(OCClientResponse * clientResponse)
                        OC_LOW_QOS, &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack resource error");
+        OIC_LOG(ERROR, TAG, "OCStack resource error");
     }
     else
     {
@@ -305,9 +305,9 @@ int InitPutRequest(OCClientResponse * clientResponse)
     cbData.cb = putReqCB;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
-    OC_LOG_V(INFO, TAG, "PUT payload from client = ");
+    OIC_LOG_V(INFO, TAG, "PUT payload from client = ");
     OCPayload* payload = putPayload();
-    OC_LOG_PAYLOAD(INFO, payload);
+    OIC_LOG_PAYLOAD(INFO, payload);
     OCPayloadDestroy(payload);
 
     ret = OCDoResource(NULL, OC_REST_PUT, getQuery.str().c_str(),
@@ -315,7 +315,7 @@ int InitPutRequest(OCClientResponse * clientResponse)
                        OC_LOW_QOS, &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack resource error");
+        OIC_LOG(ERROR, TAG, "OCStack resource error");
     }
     return ret;
 }
@@ -340,7 +340,7 @@ int InitGetRequest(OCClientResponse * clientResponse)
                        &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack resource error");
+        OIC_LOG(ERROR, TAG, "OCStack resource error");
     }
     return ret;
 }
@@ -362,7 +362,7 @@ int InitDiscovery()
             &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack resource error");
+        OIC_LOG(ERROR, TAG, "OCStack resource error");
     }
     return ret;
 }
@@ -396,7 +396,7 @@ int main(int argc, char* argv[])
     /* Initialize OCStack*/
     if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack init error");
+        OIC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
 
@@ -406,30 +406,30 @@ int main(int argc, char* argv[])
     }
     else
     {
-        OC_LOG(INFO, TAG, "Default Connectivity type selected...");
+        OIC_LOG(INFO, TAG, "Default Connectivity type selected...");
         ConnType = CT_ADAPTER_IP;
     }
 
     InitDiscovery();
 
     // Break from loop with Ctrl+C
-    OC_LOG(INFO, TAG, "Entering occlient main loop...");
+    OIC_LOG(INFO, TAG, "Entering occlient main loop...");
     signal(SIGINT, handleSigInt);
     while (!gQuitFlag)
     {
 
         if (OCProcess() != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             return 0;
         }
 
         sleep(2);
-    } OC_LOG(INFO, TAG, "Exiting occlient main loop...");
+    } OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
 
     if (OCStop() != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack stop error");
+        OIC_LOG(ERROR, TAG, "OCStack stop error");
     }
 
     return 0;
index 3a7f26e..572b9e3 100644 (file)
@@ -59,15 +59,15 @@ void handleSigInt(int signum)
 
 static void PrintUsage()
 {
-    OC_LOG(INFO, TAG, "Usage : occlient -c <0|1> -u <0|1> -t <1|2|3>");
-    OC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
-    OC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
-    OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
-    OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
-    OC_LOG(INFO, TAG, "-t 2 : Discover Resources and Initiate Nonconfirmable Get Request");
-    OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get Request");
-    OC_LOG(INFO, TAG, "-t 4 : Discover Resources and Initiate NonConfirmable Put Request");
-    OC_LOG(INFO, TAG, "-t 5 : Discover Resources and Initiate Confirmable Put Request");
+    OIC_LOG(INFO, TAG, "Usage : occlient -c <0|1> -u <0|1> -t <1|2|3>");
+    OIC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
+    OIC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
+    OIC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
+    OIC_LOG(INFO, TAG, "-t 1 : Discover Resources");
+    OIC_LOG(INFO, TAG, "-t 2 : Discover Resources and Initiate Nonconfirmable Get Request");
+    OIC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get Request");
+    OIC_LOG(INFO, TAG, "-t 4 : Discover Resources and Initiate NonConfirmable Put Request");
+    OIC_LOG(INFO, TAG, "-t 5 : Discover Resources and Initiate Confirmable Put Request");
 }
 
 OCPayload* putPayload()
@@ -103,7 +103,7 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query,
 
     if (ret != OC_STACK_OK)
     {
-        OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
+        OIC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
     }
 
     return ret;
@@ -114,33 +114,33 @@ OCStackApplicationResult getReqCB(void* ctx,
 {
     if(clientResponse == NULL)
     {
-        OC_LOG(INFO, TAG, "The clientResponse is NULL");
+        OIC_LOG(INFO, TAG, "The clientResponse is NULL");
         return   OC_STACK_DELETE_TRANSACTION;
     }
     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
+        OIC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
     }
 
-    OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
-    OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
-    OC_LOG(INFO, TAG, "Get Response =============> ");
-    OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+    OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
+    OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
+    OIC_LOG(INFO, TAG, "Get Response =============> ");
+    OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
 
     if(clientResponse->rcvdVendorSpecificHeaderOptions &&
             clientResponse->numRcvdVendorSpecificHeaderOptions)
     {
-        OC_LOG (INFO, TAG, "Received vendor specific options");
+        OIC_LOG (INFO, TAG, "Received vendor specific options");
         uint8_t i = 0;
         OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
         for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
         {
             if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
             {
-                OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
+                OIC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
                         ((OCHeaderOption)rcvdOptions[i]).optionID );
 
-                OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
+                OIC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
                     MAX_HEADER_OPTION_DATA_LENGTH);
             }
         }
@@ -154,16 +154,16 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
 {
     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
+        OIC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
     }
 
     if (clientResponse)
     {
-        OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
+        OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
 
-        OC_LOG_V(INFO, TAG, "Discovered @ %s:%u =============> ",
+        OIC_LOG_V(INFO, TAG, "Discovered @ %s:%u =============> ",
             clientResponse->devAddr.addr, clientResponse->devAddr.port);
-        OC_LOG_PAYLOAD (INFO, clientResponse->payload);
+        OIC_LOG_PAYLOAD (INFO, clientResponse->payload);
 
         endpoint = clientResponse->devAddr;
 
@@ -193,10 +193,10 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
 
 int InitGetRequest(OCQualityOfService qos)
 {
-    OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
+    OIC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
     query << coapServerResource;
-    OC_LOG_V (INFO, TAG, "Performing GET with query : %s", query.str().c_str());
+    OIC_LOG_V (INFO, TAG, "Performing GET with query : %s", query.str().c_str());
     return (InvokeOCDoResource(query, OC_REST_GET, &endpoint,
                                (qos == OC_HIGH_QOS)? OC_HIGH_QOS : OC_LOW_QOS,
                                getReqCB, NULL, 0));
@@ -204,10 +204,10 @@ int InitGetRequest(OCQualityOfService qos)
 
 int InitPutRequest(OCQualityOfService qos)
 {
-    OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
+    OIC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
     query << coapServerResource;
-    OC_LOG_V (INFO, TAG, "Performing PUT with query : %s", query.str().c_str());
+    OIC_LOG_V (INFO, TAG, "Performing PUT with query : %s", query.str().c_str());
     return (InvokeOCDoResource(query, OC_REST_PUT, &endpoint,
                                (qos == OC_HIGH_QOS)?  OC_HIGH_QOS:OC_LOW_QOS,
                                getReqCB, NULL, 0));
@@ -222,9 +222,9 @@ int InitDiscovery()
 
     if (UnicastDiscovery)
     {
-        OC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
-        OC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
-        OC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
+        OIC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
+        OIC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
+        OIC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
 
         if (fgets(ipaddr, sizeof (ipaddr), stdin))
         {
@@ -232,7 +232,7 @@ int InitDiscovery()
         }
         else
         {
-            OC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
+            OIC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
             return OC_STACK_INVALID_PARAM;
         }
     }
@@ -247,7 +247,7 @@ int InitDiscovery()
                        OC_LOW_QOS, &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack resource error");
+        OIC_LOG(ERROR, TAG, "OCStack resource error");
     }
     return ret;
 }
@@ -286,7 +286,7 @@ int main(int argc, char* argv[])
     /* Initialize OCStack*/
     if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack init error");
+        OIC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
 
@@ -296,30 +296,30 @@ int main(int argc, char* argv[])
     }
     else
     {
-        OC_LOG(INFO, TAG, "Default Connectivity type selected...");
+        OIC_LOG(INFO, TAG, "Default Connectivity type selected...");
         AdapterType = CT_ADAPTER_IP;
     }
 
     InitDiscovery();
 
     // Break from loop with Ctrl+C
-    OC_LOG(INFO, TAG, "Entering occlient main loop...");
+    OIC_LOG(INFO, TAG, "Entering occlient main loop...");
     signal(SIGINT, handleSigInt);
     while (!gQuitFlag)
     {
         if (OCProcess() != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             return 0;
         }
 
         sleep(2);
     }
-    OC_LOG(INFO, TAG, "Exiting occlient main loop...");
+    OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
 
     if (OCStop() != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack stop error");
+        OIC_LOG(ERROR, TAG, "OCStack stop error");
     }
 
     return 0;
index 918d3e0..c3a7059 100644 (file)
 #include "payload_logging.h"
 #include "ocremoteaccessclient.h"
 
+#define SET_BUT_NOT_USED(x) (void) x
 // Tracking user input
 static int TEST_CASE = 0;
 
-static const char * MULTICAST_DEVICE_DISCOVERY_QUERY = "/oic/d";
-static const char * MULTICAST_PLATFORM_DISCOVERY_QUERY = "/oic/p";
 static const char * MULTICAST_RESOURCE_DISCOVERY_QUERY = "/oic/res";
 
 static std::string coapServerIP = "255.255.255.255";
@@ -86,15 +85,15 @@ OCPayload* putPayload()
 
 static void PrintUsage()
 {
-    OC_LOG(INFO, TAG, "This sample makes all requests via the remote access adapter");
-    OC_LOG(INFO, TAG, "Usage : ocremoteaccessclient -t <number>");
-    OC_LOG(INFO, TAG, "-t 1  :  Discover Resources");
-    OC_LOG(INFO, TAG, "-t 2  :  Discover & Get");
-    OC_LOG(INFO, TAG, "-t 3  :  Discover & Put");
-    OC_LOG(INFO, TAG, "-t 4  :  Discover & Post");
-    OC_LOG(INFO, TAG, "-t 5  :  Discover & Delete");
-    OC_LOG(INFO, TAG, "-t 6  :  Discover & Observe");
-    OC_LOG(INFO, TAG, "-t 7  :  Discover & Observe then cancel immediately with High QOS");
+    OIC_LOG(INFO, TAG, "This sample makes all requests via the remote access adapter");
+    OIC_LOG(INFO, TAG, "Usage : ocremoteaccessclient -t <number>");
+    OIC_LOG(INFO, TAG, "-t 1  :  Discover Resources");
+    OIC_LOG(INFO, TAG, "-t 2  :  Discover & Get");
+    OIC_LOG(INFO, TAG, "-t 3  :  Discover & Put");
+    OIC_LOG(INFO, TAG, "-t 4  :  Discover & Post");
+    OIC_LOG(INFO, TAG, "-t 5  :  Discover & Delete");
+    OIC_LOG(INFO, TAG, "-t 6  :  Discover & Observe");
+    OIC_LOG(INFO, TAG, "-t 7  :  Discover & Observe then cancel immediately with High QOS");
 }
 
 OCStackResult InvokeOCDoResource(std::ostringstream &query,
@@ -125,7 +124,7 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query,
 
     if (ret != OC_STACK_OK)
     {
-        OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
+        OIC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
     }
     else if (method == OC_REST_OBSERVE || method == OC_REST_OBSERVE_ALL)
     {
@@ -146,22 +145,23 @@ OCStackApplicationResult restRequestCB(void* ctx,
 {
     if(clientResponse == NULL)
     {
-        OC_LOG(INFO, TAG, "Received NULL response");
+        OIC_LOG(INFO, TAG, "Received NULL response");
         return   OC_STACK_DELETE_TRANSACTION;
     }
     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "Callback Context recvd successfully");
+        OIC_LOG(INFO, TAG, "Callback Context recvd successfully");
     }
 
-    OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
-    OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
-    OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+    OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
+    OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
+    OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
 
     if(clientResponse->numRcvdVendorSpecificHeaderOptions > 0)
     {
-        OC_LOG (INFO, TAG, "Received vendor specific options. Ignoring");
+        OIC_LOG (INFO, TAG, "Received vendor specific options. Ignoring");
     }
+    SET_BUT_NOT_USED(handle);
     return OC_STACK_DELETE_TRANSACTION;
 }
 
@@ -169,23 +169,23 @@ OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle handle, OCClientResponse
 {
     if(!clientResponse)
     {
-        OC_LOG_V(INFO, TAG, "obsReqCB received NULL response");
+        OIC_LOG_V(INFO, TAG, "obsReqCB received NULL response");
     }
     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "Callback Context recvd successfully");
+        OIC_LOG(INFO, TAG, "Callback Context recvd successfully");
     }
-    OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
-    OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
-    OC_LOG_V(INFO, TAG, "OBSERVE notification %d recvd", gNumObserveNotifies);
-    OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+    OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
+    OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
+    OIC_LOG_V(INFO, TAG, "OBSERVE notification %d recvd", gNumObserveNotifies);
+    OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
 
     gNumObserveNotifies++;
     if (gNumObserveNotifies == maxNotification)
     {
         if (OCCancel (gObserveDoHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "Observe cancel error");
+            OIC_LOG(ERROR, TAG, "Observe cancel error");
         }
         return OC_STACK_DELETE_TRANSACTION;
     }
@@ -193,24 +193,25 @@ OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle handle, OCClientResponse
     {
         if (OCCancel (gObserveDoHandle, OC_HIGH_QOS, NULL, 0) != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "Observe cancel error");
+            OIC_LOG(ERROR, TAG, "Observe cancel error");
         }
     }
     if(clientResponse->sequenceNumber == OC_OBSERVE_REGISTER)
     {
-        OC_LOG(INFO, TAG, "Registration confirmed");
+        OIC_LOG(INFO, TAG, "Registration confirmed");
     }
     else if(clientResponse->sequenceNumber == OC_OBSERVE_DEREGISTER)
     {
-        OC_LOG(INFO, TAG, "de-registration confirmed");
+        OIC_LOG(INFO, TAG, "de-registration confirmed");
         return OC_STACK_DELETE_TRANSACTION;
     }
     else if(clientResponse->sequenceNumber == OC_OBSERVE_NO_OPTION)
     {
-        OC_LOG(INFO, TAG, "Registration/deregistration failed");
+        OIC_LOG(INFO, TAG, "Registration/deregistration failed");
         return OC_STACK_DELETE_TRANSACTION;
     }
 
+    SET_BUT_NOT_USED(handle);
     return OC_STACK_KEEP_TRANSACTION;
 }
 #ifdef WITH_PRESENCE
@@ -219,30 +220,31 @@ OCStackApplicationResult presenceCB(void* ctx,
 {
     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "Callback Context recvd successfully");
+        OIC_LOG(INFO, TAG, "Callback Context recvd successfully");
     }
 
     if (clientResponse)
     {
-        OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
-        OC_LOG_V(INFO, TAG, "NONCE NUMBER: %u", clientResponse->sequenceNumber);
-        OC_LOG_V(INFO, TAG, "PRESENCE notification %d recvd", gNumPresenceNotifies);
-        OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
+        OIC_LOG_V(INFO, TAG, "NONCE NUMBER: %u", clientResponse->sequenceNumber);
+        OIC_LOG_V(INFO, TAG, "PRESENCE notification %d recvd", gNumPresenceNotifies);
+        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
 
         gNumPresenceNotifies++;
         if (gNumPresenceNotifies == maxNotification)
         {
             if (OCCancel(gPresenceHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK)
             {
-                OC_LOG(ERROR, TAG, "Presence cancel error");
+                OIC_LOG(ERROR, TAG, "Presence cancel error");
             }
             return OC_STACK_DELETE_TRANSACTION;
         }
     }
     else
     {
-        OC_LOG_V(INFO, TAG, "presenceCB received Null clientResponse");
+        OIC_LOG_V(INFO, TAG, "presenceCB received Null clientResponse");
     }
+    SET_BUT_NOT_USED(handle);
     return OC_STACK_KEEP_TRANSACTION;
 }
 #endif
@@ -253,22 +255,22 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
 {
     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "DISCOVER  callback recvd");
+        OIC_LOG(INFO, TAG, "DISCOVER  callback recvd");
     }
 
     if (!clientResponse)
     {
-        OC_LOG_V(INFO, TAG, "discoveryReqCB received Null clientResponse");
+        OIC_LOG_V(INFO, TAG, "discoveryReqCB received Null clientResponse");
     }
 
-    OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
-    OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+    OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
+    OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
 
     responseAddr = clientResponse->devAddr;
 
     switch(TEST_CASE)
     {
-        OC_LOG_V(INFO, TAG, "TEST_CASE %u\n", TEST_CASE);
+        OIC_LOG_V(INFO, TAG, "TEST_CASE %u\n", TEST_CASE);
         case TEST_GET_REQ_NON:
             InitGetRequest(OC_LOW_QOS);
             break;
@@ -289,6 +291,7 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
             PrintUsage();
             break;
     }
+    SET_BUT_NOT_USED(handle);
     return OC_STACK_KEEP_TRANSACTION;
 }
 
@@ -297,18 +300,19 @@ OCStackApplicationResult PlatformDiscoveryReqCB (void* ctx, OCDoHandle handle,
 {
     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "Callback Context for Platform DISCOVER query recvd successfully");
+        OIC_LOG(INFO, TAG, "Callback Context for Platform DISCOVER query recvd successfully");
     }
 
     if(clientResponse)
     {
-        OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
     }
     else
     {
-        OC_LOG_V(INFO, TAG, "PlatformDiscoveryReqCB received Null clientResponse");
+        OIC_LOG_V(INFO, TAG, "PlatformDiscoveryReqCB received Null clientResponse");
     }
 
+    SET_BUT_NOT_USED(handle);
     return OC_STACK_DELETE_TRANSACTION;
 }
 
@@ -317,24 +321,25 @@ OCStackApplicationResult DeviceDiscoveryReqCB (void* ctx, OCDoHandle handle,
 {
     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "Callback Context for Device DISCOVER query recvd successfully");
+        OIC_LOG(INFO, TAG, "Callback Context for Device DISCOVER query recvd successfully");
     }
 
     if(clientResponse)
     {
-        OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
     }
     else
     {
-        OC_LOG_V(INFO, TAG, "PlatformDiscoveryReqCB received Null clientResponse");
+        OIC_LOG_V(INFO, TAG, "PlatformDiscoveryReqCB received Null clientResponse");
     }
 
+    SET_BUT_NOT_USED(handle);
     return OC_STACK_DELETE_TRANSACTION;
 }
 
 int InitObserveRequest(OCQualityOfService qos)
 {
-    OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
+    OIC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
     query << coapServerResource;
     return (InvokeOCDoResource(query,
@@ -343,7 +348,7 @@ int InitObserveRequest(OCQualityOfService qos)
 
 int InitPutRequest(OCQualityOfService qos)
 {
-    OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
+    OIC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
     query << coapServerResource;
     return (InvokeOCDoResource(query, OC_REST_PUT, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS,
@@ -352,7 +357,7 @@ int InitPutRequest(OCQualityOfService qos)
 
 int InitPostRequest(OCQualityOfService qos)
 {
-    OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
+    OIC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
     query << coapServerResource;
     // First POST operation (to create an Light instance)
@@ -362,7 +367,7 @@ int InitPostRequest(OCQualityOfService qos)
     if (OC_STACK_OK != result)
     {
         // Error can happen if for example, network connectivity is down
-        OC_LOG(INFO, TAG, "First POST call did not succeed");
+        OIC_LOG(INFO, TAG, "First POST call did not succeed");
     }
 
     // Second POST operation (to create an Light instance)
@@ -371,7 +376,7 @@ int InitPostRequest(OCQualityOfService qos)
                                restRequestCB, NULL, 0);
     if (OC_STACK_OK != result)
     {
-        OC_LOG(INFO, TAG, "Second POST call did not succeed");
+        OIC_LOG(INFO, TAG, "Second POST call did not succeed");
     }
 
     // This POST operation will update the original resourced /a/light
@@ -384,7 +389,7 @@ int InitDeleteRequest(OCQualityOfService qos)
 {
     std::ostringstream query;
     query << coapServerResource;
-    OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
+    OIC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
 
     // First DELETE operation
     OCStackResult result = InvokeOCDoResource(query, OC_REST_DELETE,
@@ -393,14 +398,14 @@ int InitDeleteRequest(OCQualityOfService qos)
     if (OC_STACK_OK != result)
     {
         // Error can happen if for example, network connectivity is down
-        OC_LOG(INFO, TAG, "DELETE call did not succeed");
+        OIC_LOG(INFO, TAG, "DELETE call did not succeed");
     }
     return result;
 }
 
 int InitGetRequest(OCQualityOfService qos)
 {
-    OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
+    OIC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
     query << coapServerResource;
     return (InvokeOCDoResource(query, OC_REST_GET,
@@ -433,45 +438,71 @@ int InitDiscovery(OCQualityOfService qos)
 
     if (ret != OC_STACK_OK)
     {
-        OC_LOG_V(ERROR, TAG, "Error %u in OCDoResource with discovery", ret);
+        OIC_LOG_V(ERROR, TAG, "Error %u in OCDoResource with discovery", ret);
     }
     return ret;
 }
 
-OCStackResult initRemoteAccessAdapter ()
+static void jidbound(char *jid)
 {
-    OCRAInfo_t rainfo;
-    rainfo.hostname = "localhost";
-    rainfo.port = 5222;
-    rainfo.xmpp_domain = "localhost";
-    rainfo.username = "test1";
-    rainfo.password = "intel123";
-    rainfo.resource = "";
-    rainfo.user_jid = "";
-
-    return OCSetRAInfo(&rainfo);
+    OIC_LOG_V(INFO, TAG, "\n\n    Bound JID: %s\n\n", jid);
 }
 
 int main(int argc, char* argv[])
 {
-    int opt;
+    char host[] = "localhost";
+    char user[] = "test1";
+    char pass[] = "intel123";
+    char empstr[] = "";
+    OCRAInfo_t rainfo = {};
+
+    rainfo.hostname = host;
+    rainfo.port = 5222;
+    rainfo.xmpp_domain = host;
+    rainfo.username = user;
+    rainfo.password = pass;
+    rainfo.resource = empstr;
+    rainfo.user_jid = empstr;
+    rainfo.jidbound = jidbound;
 
-    while ((opt = getopt(argc, argv, "t:")) != -1)
+    int opt = 0;
+    while ((opt = getopt(argc, argv, "t:s:p:d:u:w:r:j:")) != -1)
     {
         switch(opt)
         {
             case 't':
                 TEST_CASE = atoi(optarg);
                 break;
+            case 's':
+                rainfo.hostname = optarg;
+                break;
+            case 'p':
+                rainfo.port = atoi(optarg);
+                break;
+            case 'd':
+                rainfo.xmpp_domain = optarg;
+                break;
+            case 'u':
+                rainfo.username = optarg;
+                break;
+            case 'w':
+                rainfo.password = optarg;
+                break;
+            case 'j':
+                rainfo.user_jid = optarg;
+                break;
+            case 'r':
+                rainfo.resource = optarg;
+                break;
             default:
                 PrintUsage();
                 return -1;
         }
     }
 
-    if (initRemoteAccessAdapter() != OC_STACK_OK)
+    if (OCSetRAInfo(&rainfo) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "Error initiating remote access adapter");
+        OIC_LOG(ERROR, TAG, "Error initiating remote access adapter");
         return 0;
     }
 
@@ -483,41 +514,41 @@ int main(int argc, char* argv[])
 
     if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack init error");
+        OIC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
 
-    OC_LOG(INFO, TAG, "Enter JID of remote server");
+    OIC_LOG(INFO, TAG, "Enter JID of remote server");
     if (fgets(remoteServerJabberID, MAX_ADDR_STR_SIZE, stdin))
     {
         StripNewLineChar(remoteServerJabberID);
     }
     else
     {
-        OC_LOG(ERROR, TAG, "Bad input for jabberID");
+        OIC_LOG(ERROR, TAG, "Bad input for jabberID");
         return OC_STACK_INVALID_PARAM;
     }
 
     InitDiscovery(OC_LOW_QOS);
 
     // Break from loop with Ctrl+C
-    OC_LOG(INFO, TAG, "Press CTRL+C to stop the stack");
+    OIC_LOG(INFO, TAG, "Press CTRL+C to stop the stack");
     signal(SIGINT, handleSigInt);
     while (!gQuitFlag)
     {
         if (OCProcess() != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             return 0;
         }
 
         sleep(2);
     }
-    OC_LOG(INFO, TAG, "Exiting ocremoteaccessclient main loop...");
+    OIC_LOG(INFO, TAG, "Exiting ocremoteaccessclient main loop...");
 
     if (OCStop() != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack stop error");
+        OIC_LOG(ERROR, TAG, "OCStack stop error");
     }
 
     return 0;
index 282adc2..0df6a43 100644 (file)
@@ -46,16 +46,16 @@ void handleSigInt(int signum)
 
 int main()
 {
-    OC_LOG(DEBUG, TAG, "OCRouting sample is starting...");
+    OIC_LOG(DEBUG, TAG, "OCRouting sample is starting...");
 
     if (OCInit(NULL, 0, OC_GATEWAY) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack init error");
+        OIC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
 
     // Break from loop with Ctrl-C
-    OC_LOG(INFO, TAG, "Entering ocrouting main loop...");
+    OIC_LOG(INFO, TAG, "Entering ocrouting main loop...");
 
     signal(SIGINT, handleSigInt);
 
@@ -63,16 +63,16 @@ int main()
     {
         if (OCProcess() != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             return 0;
         }
     }
 
-    OC_LOG(INFO, TAG, "Exiting ocrouting main loop...");
+    OIC_LOG(INFO, TAG, "Exiting ocrouting main loop...");
 
     if (OCStop() != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack process error");
+        OIC_LOG(ERROR, TAG, "OCStack process error");
     }
 
     return 0;
index 42ba141..cc5e968 100644 (file)
@@ -88,7 +88,7 @@ OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
     OCRepPayload* payload = OCRepPayloadCreate();
     if(!payload)
     {
-        OC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
+        OIC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
         return nullptr;
     }
 
@@ -104,7 +104,7 @@ OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest)
 {
     if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
     {
-        OC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
+        OIC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
         return nullptr;
     }
 
@@ -163,7 +163,7 @@ bool checkIfQueryForPowerPassed(char * query)
             int powerRequested = atoi(pointerToOperator + 1);
             if (Light.power > powerRequested)
             {
-                OC_LOG_V(INFO, TAG, "Current power: %d. Requested: <%d", Light.power
+                OIC_LOG_V(INFO, TAG, "Current power: %d. Requested: <%d", Light.power
                             , powerRequested);
                 return false;
             }
@@ -177,8 +177,8 @@ bool checkIfQueryForPowerPassed(char * query)
  */
 OCEntityHandlerResult ValidateQueryParams (OCEntityHandlerRequest *entityHandlerRequest)
 {
-    OC_LOG_V(INFO, TAG, PCF("Received query %s"), entityHandlerRequest->query);
-    OC_LOG(INFO, TAG, PCF("Not processing query"));
+    OIC_LOG_V(INFO, TAG, PCF("Received query %s"), entityHandlerRequest->query);
+    OIC_LOG(INFO, TAG, PCF("Not processing query"));
     return OC_EH_OK;
 }
 
@@ -194,7 +194,7 @@ OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
         OCRepPayload *getResp = constructResponse(ehRequest);
         if(!getResp)
         {
-            OC_LOG(ERROR, TAG, "constructResponse failed");
+            OIC_LOG(ERROR, TAG, "constructResponse failed");
             return OC_EH_ERROR;
         }
 
@@ -217,7 +217,7 @@ OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
 
     if(!putResp)
     {
-        OC_LOG(ERROR, TAG, "Failed to construct Json response");
+        OIC_LOG(ERROR, TAG, "Failed to construct Json response");
         return OC_EH_ERROR;
     }
 
@@ -258,7 +258,7 @@ OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
 
             if (0 == createLightResource (newLightUri, &gLightInstance[gCurrLightInstance]))
             {
-                OC_LOG (INFO, TAG, "Created new Light instance\n");
+                OIC_LOG (INFO, TAG, "Created new Light instance\n");
                 gLightInstance[gCurrLightInstance].state = 0;
                 gLightInstance[gCurrLightInstance].power = 0;
                 gCurrLightInstance++;
@@ -301,7 +301,7 @@ OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
     }
     else
     {
-        OC_LOG(INFO, TAG, "Payload was NULL");
+        OIC_LOG(INFO, TAG, "Payload was NULL");
         ehResult = OC_EH_ERROR;
     }
 
@@ -312,12 +312,12 @@ OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest)
 {
     if(ehRequest == NULL)
     {
-        OC_LOG(INFO, TAG, "The ehRequest is NULL");
+        OIC_LOG(INFO, TAG, "The ehRequest is NULL");
         return OC_EH_ERROR;
     }
     OCEntityHandlerResult ehResult = OC_EH_OK;
 
-    OC_LOG_V(INFO, TAG, "\n\nExecuting %s for resource %d ", __func__, ehRequest->resource);
+    OIC_LOG_V(INFO, TAG, "\n\nExecuting %s for resource %p ", __func__, ehRequest->resource);
 
     /*
      * In the sample below, the application will:
@@ -335,7 +335,7 @@ OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest)
 
         if (result == OC_STACK_OK)
         {
-            OC_LOG (INFO, TAG, "\n\nDelete Resource operation succeeded.");
+            OIC_LOG (INFO, TAG, "\n\nDelete Resource operation succeeded.");
             ehResult = OC_EH_OK;
 
             //Step 2: clear observers who wanted to observe this resource at the app level.
@@ -351,12 +351,12 @@ OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest)
         }
         else if (result == OC_STACK_NO_RESOURCE)
         {
-            OC_LOG(INFO, TAG, "\n\nThe resource doesn't exist or it might have been deleted.");
+            OIC_LOG(INFO, TAG, "\n\nThe resource doesn't exist or it might have been deleted.");
             ehResult = OC_EH_RESOURCE_DELETED;
         }
         else
         {
-            OC_LOG(INFO, TAG, "\n\nEncountered error from OCDeleteResource().");
+            OIC_LOG(INFO, TAG, "\n\nEncountered error from OCDeleteResource().");
             ehResult = OC_EH_ERROR;
         }
     }
@@ -364,7 +364,7 @@ OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest)
     {
         //Let's this app not supporting DELETE on some resources so
         //consider the DELETE request is received for a non-support resource.
-        OC_LOG_V(INFO, TAG, "\n\nThe request is received for a non-support resource.");
+        OIC_LOG_V(INFO, TAG, "\n\nThe request is received for a non-support resource.");
         ehResult = OC_EH_FORBIDDEN;
     }
 
@@ -373,14 +373,14 @@ OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest)
 
 OCEntityHandlerResult ProcessNonExistingResourceRequest(OCEntityHandlerRequest * /*ehRequest*/)
 {
-    OC_LOG_V(INFO, TAG, "\n\nExecuting %s ", __func__);
+    OIC_LOG_V(INFO, TAG, "\n\nExecuting %s ", __func__);
 
     return OC_EH_RESOURCE_NOT_FOUND;
 }
 
 void ProcessObserveRegister (OCEntityHandlerRequest *ehRequest)
 {
-    OC_LOG_V (INFO, TAG, "Received observation registration request with observation Id %d",
+    OIC_LOG_V (INFO, TAG, "Received observation registration request with observation Id %d",
             ehRequest->obsInfo.obsId);
 
     if (!observeThreadStarted)
@@ -404,7 +404,7 @@ void ProcessObserveDeregister (OCEntityHandlerRequest *ehRequest)
 {
     bool clientStillObserving = false;
 
-    OC_LOG_V (INFO, TAG, "Received observation deregistration request for observation Id %d",
+    OIC_LOG_V (INFO, TAG, "Received observation deregistration request for observation Id %d",
             ehRequest->obsInfo.obsId);
     for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
     {
@@ -428,7 +428,7 @@ OCDeviceEntityHandlerCb (OCEntityHandlerFlag flag,
                          char* uri,
                          void* /*callbackParam*/)
 {
-    OC_LOG_V (INFO, TAG, "Inside device default entity handler - flags: 0x%x, uri: %s", flag, uri);
+    OIC_LOG_V (INFO, TAG, "Inside device default entity handler - flags: 0x%x, uri: %s", flag, uri);
 
     OCEntityHandlerResult ehResult = OC_EH_OK;
     OCEntityHandlerResponse response;
@@ -436,7 +436,7 @@ OCDeviceEntityHandlerCb (OCEntityHandlerFlag flag,
     // Validate pointer
     if (!entityHandlerRequest)
     {
-        OC_LOG (ERROR, TAG, "Invalid request pointer");
+        OIC_LOG (ERROR, TAG, "Invalid request pointer");
         return OC_EH_ERROR;
     }
     // Initialize certain response fields
@@ -449,31 +449,31 @@ OCDeviceEntityHandlerCb (OCEntityHandlerFlag flag,
 
     if (flag & OC_REQUEST_FLAG)
     {
-        OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
+        OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
 
         if (entityHandlerRequest->resource == NULL)
         {
-            OC_LOG (INFO, TAG, "Received request from client to a non-existing resource");
+            OIC_LOG (INFO, TAG, "Received request from client to a non-existing resource");
             ehResult = ProcessNonExistingResourceRequest(entityHandlerRequest);
         }
         else if (OC_REST_GET == entityHandlerRequest->method)
         {
-            OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
+            OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
             ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
         }
         else if (OC_REST_PUT == entityHandlerRequest->method)
         {
-            OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
+            OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
             ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
         }
         else if (OC_REST_DELETE == entityHandlerRequest->method)
         {
-            OC_LOG (INFO, TAG, "Received OC_REST_DELETE from client");
+            OIC_LOG (INFO, TAG, "Received OC_REST_DELETE from client");
             ehResult = ProcessDeleteRequest (entityHandlerRequest);
         }
         else
         {
-            OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
+            OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
                       entityHandlerRequest->method);
             ehResult = OC_EH_ERROR;
         }
@@ -491,21 +491,21 @@ OCDeviceEntityHandlerCb (OCEntityHandlerFlag flag,
             // Send the response
             if (OCDoResponse(&response) != OC_STACK_OK)
             {
-                OC_LOG(ERROR, TAG, "Error sending response");
+                OIC_LOG(ERROR, TAG, "Error sending response");
                 ehResult = OC_EH_ERROR;
             }
         }
     }
     if (flag & OC_OBSERVE_FLAG)
     {
-        OC_LOG(INFO, TAG, "Flag includes OC_OBSERVE_FLAG");
+        OIC_LOG(INFO, TAG, "Flag includes OC_OBSERVE_FLAG");
         if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
         {
-            OC_LOG (INFO, TAG, "Received OC_OBSERVE_REGISTER from client");
+            OIC_LOG (INFO, TAG, "Received OC_OBSERVE_REGISTER from client");
         }
         else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
         {
-            OC_LOG (INFO, TAG, "Received OC_OBSERVE_DEREGISTER from client");
+            OIC_LOG (INFO, TAG, "Received OC_OBSERVE_DEREGISTER from client");
         }
     }
 
@@ -526,7 +526,7 @@ OCEntityHandlerResult
 OCEntityHandlerCb (OCEntityHandlerFlag flag,
         OCEntityHandlerRequest *entityHandlerRequest, void* /*callback*/)
 {
-    OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
+    OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
 
     OCEntityHandlerResult ehResult = OC_EH_OK;
     OCEntityHandlerResponse response = { 0, 0, OC_EH_ERROR, 0, 0, { },{ 0 }, false };
@@ -534,7 +534,7 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
     // Validate pointer
     if (!entityHandlerRequest)
     {
-        OC_LOG (ERROR, TAG, "Invalid request pointer");
+        OIC_LOG (ERROR, TAG, "Invalid request pointer");
         return OC_EH_ERROR;
     }
 
@@ -547,31 +547,31 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
 
     if (flag & OC_REQUEST_FLAG)
     {
-        OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
+        OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
 
         if (OC_REST_GET == entityHandlerRequest->method)
         {
-            OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
+            OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
             ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
         }
         else if (OC_REST_PUT == entityHandlerRequest->method)
         {
-            OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
+            OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
             ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
         }
         else if (OC_REST_POST == entityHandlerRequest->method)
         {
-            OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
+            OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
             ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
         }
         else if (OC_REST_DELETE == entityHandlerRequest->method)
         {
-            OC_LOG (INFO, TAG, "Received OC_REST_DELETE from client");
+            OIC_LOG (INFO, TAG, "Received OC_REST_DELETE from client");
             ehResult = ProcessDeleteRequest (entityHandlerRequest);
         }
         else
         {
-            OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
+            OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
                       entityHandlerRequest->method);
             ehResult = OC_EH_ERROR;
         }
@@ -590,7 +590,7 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
             if(entityHandlerRequest->rcvdVendorSpecificHeaderOptions &&
                     entityHandlerRequest->numRcvdVendorSpecificHeaderOptions)
             {
-                OC_LOG (INFO, TAG, "Received vendor specific options");
+                OIC_LOG (INFO, TAG, "Received vendor specific options");
                 uint8_t i = 0;
                 OCHeaderOption * rcvdOptions =
                         entityHandlerRequest->rcvdVendorSpecificHeaderOptions;
@@ -598,10 +598,10 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
                 {
                     if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
                     {
-                        OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
+                        OIC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
                                 ((OCHeaderOption)rcvdOptions[i]).optionID );
 
-                        OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
+                        OIC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
                             MAX_HEADER_OPTION_DATA_LENGTH);
                     }
                 }
@@ -622,23 +622,23 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
             // Send the response
             if (OCDoResponse(&response) != OC_STACK_OK)
             {
-                OC_LOG(ERROR, TAG, "Error sending response");
+                OIC_LOG(ERROR, TAG, "Error sending response");
                 ehResult = OC_EH_ERROR;
             }
         }
     }
     if (flag & OC_OBSERVE_FLAG)
     {
-        OC_LOG(INFO, TAG, "Flag includes OC_OBSERVE_FLAG");
+        OIC_LOG(INFO, TAG, "Flag includes OC_OBSERVE_FLAG");
 
         if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
         {
-            OC_LOG (INFO, TAG, "Received OC_OBSERVE_REGISTER from client");
+            OIC_LOG (INFO, TAG, "Received OC_OBSERVE_REGISTER from client");
             ProcessObserveRegister (entityHandlerRequest);
         }
         else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
         {
-            OC_LOG (INFO, TAG, "Received OC_OBSERVE_DEREGISTER from client");
+            OIC_LOG (INFO, TAG, "Received OC_OBSERVE_DEREGISTER from client");
             ProcessObserveDeregister (entityHandlerRequest);
         }
     }
@@ -671,7 +671,7 @@ void *ChangeLightRepresentation (void *param)
         Light.power += 5;
         if (gLightUnderObservation)
         {
-            OC_LOG_V(INFO, TAG, " =====> Notifying stack of new power level %d\n", Light.power);
+            OIC_LOG_V(INFO, TAG, " =====> Notifying stack of new power level %d\n", Light.power);
             if (gObserveNotifyType == 1)
             {
                 // Notify list of observers. Alternate observers on the list will be notified.
@@ -696,14 +696,14 @@ void *ChangeLightRepresentation (void *param)
                 result = OCNotifyAllObservers (Light.handle, OC_NA_QOS);
                 if (OC_STACK_NO_OBSERVERS == result)
                 {
-                    OC_LOG (INFO, TAG,
+                    OIC_LOG (INFO, TAG,
                             "=======> No more observers exist, stop sending observations");
                     gLightUnderObservation = 0;
                 }
             }
             else
             {
-                OC_LOG (ERROR, TAG, "Incorrect notification type selected");
+                OIC_LOG (ERROR, TAG, "Incorrect notification type selected");
             }
         }
     }
@@ -714,7 +714,7 @@ void *ChangeLightRepresentation (void *param)
 void *presenceNotificationGenerator(void *param)
 {
     uint8_t secondsBeforePresence = 10;
-    OC_LOG_V(INFO, TAG, "Will send out presence in %u seconds", secondsBeforePresence);
+    OIC_LOG_V(INFO, TAG, "Will send out presence in %u seconds", secondsBeforePresence);
     sleep(secondsBeforePresence);
     (void)param;
     OCDoHandle presenceNotificationHandles[numPresenceResources];
@@ -742,12 +742,12 @@ void *presenceNotificationGenerator(void *param)
         }
         if(res != OC_STACK_OK)
         {
-            OC_LOG_V(ERROR, TAG, "\"Presence Notification Generator\" failed to create resource "
+            OIC_LOG_V(ERROR, TAG, "\"Presence Notification Generator\" failed to create resource "
                     "%s with result %s.", presenceNotificationResources.at(i).c_str(),
                     getResult(res));
             break;
         }
-        OC_LOG_V(INFO, TAG, PCF("Created %s for presence notification"),
+        OIC_LOG_V(INFO, TAG, PCF("Created %s for presence notification"),
                                 presenceNotificationUris[i].c_str());
     }
     sleep(5);
@@ -759,15 +759,15 @@ void *presenceNotificationGenerator(void *param)
         }
         if(res != OC_STACK_OK)
         {
-            OC_LOG_V(ERROR, TAG, "\"Presence Notification Generator\" failed to delete "\
+            OIC_LOG_V(ERROR, TAG, "\"Presence Notification Generator\" failed to delete "\
                     "resource %s.", presenceNotificationResources.at(i).c_str());
             break;
         }
-        OC_LOG_V(INFO, TAG, PCF("Deleted %s for presence notification"),
+        OIC_LOG_V(INFO, TAG, PCF("Deleted %s for presence notification"),
                                 presenceNotificationUris[i].c_str());
     }
 
-    OC_LOG(INFO, TAG, "================ stopping presence");
+    OIC_LOG(INFO, TAG, "================ stopping presence");
     OCStopPresence();
 
     return NULL;
@@ -778,7 +778,7 @@ int createLightResource (char *uri, LightResource *lightResource)
 {
     if (!uri)
     {
-        OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
+        OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
         return -1;
     }
 
@@ -791,7 +791,7 @@ int createLightResource (char *uri, LightResource *lightResource)
             OCEntityHandlerCb,
             NULL,
             OC_DISCOVERABLE|OC_OBSERVABLE);
-    OC_LOG_V(INFO, TAG, "Created Light resource with result: %s", getResult(res));
+    OIC_LOG_V(INFO, TAG, "Created Light resource with result: %s", getResult(res));
 
     return 0;
 }
@@ -928,22 +928,69 @@ OCStackResult SetDeviceInfo(const char* deviceName)
 
 static void PrintUsage()
 {
-    OC_LOG(INFO, TAG, "Usage : ocserver -o <0|1>");
-    OC_LOG(INFO, TAG, "-o 0 : Notify all observers");
-    OC_LOG(INFO, TAG, "-o 1 : Notify list of observers");
+    OIC_LOG(INFO, TAG, "Usage : ocserver -o <0|1>");
+    OIC_LOG(INFO, TAG, "-o 0 : Notify all observers");
+    OIC_LOG(INFO, TAG, "-o 1 : Notify list of observers");
 }
 
+#ifdef RA_ADAPTER
+static void jidbound(char *jid)
+{
+    OIC_LOG_V(INFO, TAG, "\n\n    Bound JID: %s\n\n", jid);
+}
+#endif
+
 int main(int argc, char* argv[])
 {
-    int opt;
 
-    while ((opt = getopt(argc, argv, "o:")) != -1)
+#ifdef RA_ADAPTER
+    char host[] = "localhost";
+    char user[] = "test1";
+    char pass[] = "intel123";
+    char empstr[] = "";
+    OCRAInfo_t rainfo = {};
+
+    rainfo.hostname = host;
+    rainfo.port = 5222;
+    rainfo.xmpp_domain = host;
+    rainfo.username = user;
+    rainfo.password = pass;
+    rainfo.resource = empstr;
+    rainfo.user_jid = empstr;
+    rainfo.jidbound = jidbound;
+#endif
+
+    int opt = 0;
+    while ((opt = getopt(argc, argv, "o:s:p:d:u:w:r:j:")) != -1)
     {
         switch(opt)
         {
             case 'o':
                 gObserveNotifyType = atoi(optarg);
                 break;
+#ifdef RA_ADAPTER
+            case 's':
+                rainfo.hostname = optarg;
+                break;
+            case 'p':
+                rainfo.port = atoi(optarg);
+                break;
+            case 'd':
+                rainfo.xmpp_domain = optarg;
+                break;
+            case 'u':
+                rainfo.username = optarg;
+                break;
+            case 'w':
+                rainfo.password = optarg;
+                break;
+            case 'j':
+                rainfo.user_jid = optarg;
+                break;
+            case 'r':
+                rainfo.resource = optarg;
+                break;
+#endif
             default:
                 PrintUsage();
                 return -1;
@@ -955,30 +1002,22 @@ int main(int argc, char* argv[])
         PrintUsage();
         return -1;
     }
-#ifdef RA_ADAPTER
-    OCRAInfo_t rainfo;
-    rainfo.hostname = "localhost";
-    rainfo.port = 5222;
-    rainfo.xmpp_domain = "localhost";
-    rainfo.username = "test1";
-    rainfo.password = "intel123";
-    rainfo.resource = "";
-    rainfo.user_jid = "";
 
+#ifdef RA_ADAPTER
     OCSetRAInfo(&rainfo);
 #endif
 
-    OC_LOG(DEBUG, TAG, "OCServer is starting...");
+    OIC_LOG(DEBUG, TAG, "OCServer is starting...");
 
     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack init error");
+        OIC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
 #ifdef WITH_PRESENCE
     if (OCStartPresence(0) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack presence/discovery error");
+        OIC_LOG(ERROR, TAG, "OCStack presence/discovery error");
         return 0;
     }
 #endif
@@ -992,7 +1031,7 @@ int main(int argc, char* argv[])
 
     if (registrationResult != OC_STACK_OK)
     {
-        OC_LOG(INFO, TAG, "Platform info setting failed locally!");
+        OIC_LOG(INFO, TAG, "Platform info setting failed locally!");
         exit (EXIT_FAILURE);
     }
 
@@ -1000,7 +1039,7 @@ int main(int argc, char* argv[])
 
     if (registrationResult != OC_STACK_OK)
     {
-        OC_LOG(INFO, TAG, "Platform Registration failed!");
+        OIC_LOG(INFO, TAG, "Platform Registration failed!");
         exit (EXIT_FAILURE);
     }
 
@@ -1008,15 +1047,17 @@ int main(int argc, char* argv[])
 
     if (registrationResult != OC_STACK_OK)
     {
-        OC_LOG(INFO, TAG, "Device info setting failed locally!");
+        OIC_LOG(INFO, TAG, "Device info setting failed locally!");
         exit (EXIT_FAILURE);
     }
 
+    OCResourcePayloadAddStringLL(&deviceInfo.types, "oic.d.tv");
+
     registrationResult = OCSetDeviceInfo(deviceInfo);
 
     if (registrationResult != OC_STACK_OK)
     {
-        OC_LOG(INFO, TAG, "Device Registration failed!");
+        OIC_LOG(INFO, TAG, "Device Registration failed!");
         exit (EXIT_FAILURE);
     }
 
@@ -1042,7 +1083,7 @@ int main(int argc, char* argv[])
     #endif
 
     // Break from loop with Ctrl-C
-    OC_LOG(INFO, TAG, "Entering ocserver main loop...");
+    OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
 
     DeletePlatformInfo();
     DeleteDeviceInfo();
@@ -1053,7 +1094,7 @@ int main(int argc, char* argv[])
     {
         if (OCProcess() != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             return 0;
         }
     }
@@ -1067,11 +1108,11 @@ int main(int argc, char* argv[])
     pthread_cancel(threadId_presence);
     pthread_join(threadId_presence, NULL);
 
-    OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
+    OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
 
     if (OCStop() != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack process error");
+        OIC_LOG(ERROR, TAG, "OCStack process error");
     }
 
     return 0;
index 2c3cfdb..9c4aef5 100644 (file)
@@ -49,7 +49,7 @@ OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
     OCRepPayload* payload = OCRepPayloadCreate();
     if(!payload)
     {
-        OC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
+        OIC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
         return nullptr;
     }
 
@@ -65,7 +65,7 @@ OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
 {
     if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
     {
-        OC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
+        OIC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
         return nullptr;
     }
 
@@ -172,7 +172,7 @@ OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
 
             if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
             {
-                OC_LOG (INFO, TAG, "Created new LED instance");
+                OIC_LOG (INFO, TAG, "Created new LED instance");
                 gLedInstance[gCurrLedInstance].state = 0;
                 gLedInstance[gCurrLedInstance].power = 0;
                 gCurrLedInstance++;
@@ -211,7 +211,7 @@ OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
     }
     else
     {
-        OC_LOG_V (INFO, TAG, "Payload was NULL");
+        OIC_LOG_V (INFO, TAG, "Payload was NULL");
         ehResult = OC_EH_ERROR;
     }
 
@@ -223,7 +223,7 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
                    OCEntityHandlerRequest *entityHandlerRequest,
                    void* /*callbackParam*/)
 {
-    OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
+    OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
 
     OCEntityHandlerResult ehResult = OC_EH_ERROR;
     OCEntityHandlerResponse response = { 0, 0, OC_EH_ERROR, 0, 0, { },{ 0 }, false };
@@ -231,7 +231,7 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
     // Validate pointer
     if (!entityHandlerRequest)
     {
-        OC_LOG (ERROR, TAG, "Invalid request pointer");
+        OIC_LOG (ERROR, TAG, "Invalid request pointer");
         return OC_EH_ERROR;
     }
 
@@ -239,27 +239,27 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
 
     if (flag & OC_REQUEST_FLAG)
     {
-        OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
+        OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
         if (entityHandlerRequest)
         {
             if (OC_REST_GET == entityHandlerRequest->method)
             {
-                OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
+                OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
                 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
             }
             else if (OC_REST_PUT == entityHandlerRequest->method)
             {
-                OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
+                OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
                 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
             }
             else if (OC_REST_POST == entityHandlerRequest->method)
             {
-                OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
+                OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
                 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
             }
             else
             {
-                OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
+                OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
                         entityHandlerRequest->method);
             }
 
@@ -279,7 +279,7 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
                 // Send the response
                 if (OCDoResponse(&response) != OC_STACK_OK)
                 {
-                    OC_LOG(ERROR, TAG, "Error sending response");
+                    OIC_LOG(ERROR, TAG, "Error sending response");
                     ehResult = OC_EH_ERROR;
                 }
             }
@@ -301,10 +301,10 @@ void handleSigInt(int signum)
 
 int main(int /*argc*/, char* /*argv*/[])
 {
-    OC_LOG(DEBUG, TAG, "OCServer is starting...");
+    OIC_LOG(DEBUG, TAG, "OCServer is starting...");
     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack init error");
+        OIC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
 
@@ -314,24 +314,24 @@ int main(int /*argc*/, char* /*argv*/[])
     createLEDResource(gResourceUri, &LED, false, 0);
 
     // Break from loop with Ctrl-C
-    OC_LOG(INFO, TAG, "Entering ocserver main loop...");
+    OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
     signal(SIGINT, handleSigInt);
     while (!gQuitFlag)
     {
         if (OCProcess() != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             return 0;
         }
 
         sleep(2);
     }
 
-    OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
+    OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
 
     if (OCStop() != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack process error");
+        OIC_LOG(ERROR, TAG, "OCStack process error");
     }
 
     return 0;
@@ -341,7 +341,7 @@ int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState,
 {
     if (!uri)
     {
-        OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
+        OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
         return -1;
     }
 
@@ -354,7 +354,7 @@ int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState,
             OCEntityHandlerCb,
             NULL,
             OC_DISCOVERABLE|OC_OBSERVABLE);
-    OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
+    OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
 
     return 0;
 }
index eca2ad1..792b7d2 100644 (file)
@@ -59,10 +59,10 @@ typedef enum
 
 void PrintUsage()
 {
-    OC_LOG(INFO, TAG, "Usage : ocservercoll -t <Test Case>");
-    OC_LOG(INFO, TAG,
+    OIC_LOG(INFO, TAG, "Usage : ocservercoll -t <Test Case>");
+    OIC_LOG(INFO, TAG,
             "Test Case 1 : Create room resource with default collection entity handler.");
-    OC_LOG(INFO, TAG,
+    OIC_LOG(INFO, TAG,
             "Test Case 2 : Create room resource with application collection entity handler.");
 }
 
@@ -99,7 +99,7 @@ PrintReceivedMsgInfo(OCEntityHandlerFlag flag, OCEntityHandlerRequest * ehReques
         typeOfMethod = "OC_REST_PUT";
     }
 
-    OC_LOG_V(INFO, TAG, "Receiving message type: %s, method %s", typeOfMessage,
+    OIC_LOG_V(INFO, TAG, "Receiving message type: %s, method %s", typeOfMessage,
             typeOfMethod);
 }
 
@@ -108,25 +108,25 @@ OCEntityHandlerResult
 OCDeviceEntityHandlerCb (OCEntityHandlerFlag flag,
         OCEntityHandlerRequest *entityHandlerRequest, char* uri, void* /*callbackParam*/)
 {
-    OC_LOG_V(INFO, TAG, "Inside device default entity handler - flags: 0x%x, uri: %s", flag, uri);
+    OIC_LOG_V(INFO, TAG, "Inside device default entity handler - flags: 0x%x, uri: %s", flag, uri);
 
     OCEntityHandlerResult ehResult = OC_EH_OK;
     OCEntityHandlerResponse response;
 
     if (!entityHandlerRequest)
     {
-        OC_LOG(ERROR, TAG, "Invalid request pointer");
+        OIC_LOG(ERROR, TAG, "Invalid request pointer");
         return OC_EH_ERROR;
     }
 
     if (entityHandlerRequest->resource == NULL)
     {
-        OC_LOG(INFO, TAG, "Received request from client to a non-existing resource");
+        OIC_LOG(INFO, TAG, "Received request from client to a non-existing resource");
         ehResult = OC_EH_RESOURCE_NOT_FOUND;
     }
     else
     {
-        OC_LOG_V(INFO, TAG, "Device Handler: Received unsupported request from client %d",
+        OIC_LOG_V(INFO, TAG, "Device Handler: Received unsupported request from client %d",
                         entityHandlerRequest->method);
         ehResult = OC_EH_ERROR;
     }
@@ -147,7 +147,7 @@ OCDeviceEntityHandlerCb (OCEntityHandlerFlag flag,
         // Send the response
         if (OCDoResponse(&response) != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "Error sending response");
+            OIC_LOG(ERROR, TAG, "Error sending response");
             ehResult = OC_EH_ERROR;
         }
     }
@@ -161,7 +161,7 @@ OCEntityHandlerResult OCEntityHandlerRoomCb(OCEntityHandlerFlag flag,
     OCEntityHandlerResult ret = OC_EH_OK;
     OCEntityHandlerResponse response;
 
-    OC_LOG_V(INFO, TAG, "Callback for Room");
+    OIC_LOG_V(INFO, TAG, "Callback for Room");
     PrintReceivedMsgInfo(flag, ehRequest );
 
     if(ehRequest && flag == OC_REQUEST_FLAG )
@@ -229,7 +229,7 @@ OCEntityHandlerResult OCEntityHandlerRoomCb(OCEntityHandlerFlag flag,
                 // Send the response
                 if (OCDoResponse(&response) != OC_STACK_OK)
                 {
-                    OC_LOG(ERROR, TAG, "Error sending response");
+                    OIC_LOG(ERROR, TAG, "Error sending response");
                     ret = OC_EH_ERROR;
                 }
             }
@@ -302,14 +302,14 @@ OCEntityHandlerResult OCEntityHandlerRoomCb(OCEntityHandlerFlag flag,
                 // Send the response
                 if (OCDoResponse(&response) != OC_STACK_OK)
                 {
-                    OC_LOG(ERROR, TAG, "Error sending response");
+                    OIC_LOG(ERROR, TAG, "Error sending response");
                     ret = OC_EH_ERROR;
                 }
             }
         }
         else
         {
-            OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
+            OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
                     ehRequest->method);
             OCRepPayloadDestroy(payload);
             ret = OC_EH_ERROR;
@@ -328,7 +328,7 @@ OCEntityHandlerResult OCEntityHandlerLightCb(OCEntityHandlerFlag flag,
     OCEntityHandlerResult ret = OC_EH_OK;
     OCEntityHandlerResponse response;
 
-    OC_LOG_V(INFO, TAG, "Callback for Light");
+    OIC_LOG_V(INFO, TAG, "Callback for Light");
     PrintReceivedMsgInfo(flag, ehRequest );
 
     if(ehRequest && flag == OC_REQUEST_FLAG)
@@ -348,7 +348,7 @@ OCEntityHandlerResult OCEntityHandlerLightCb(OCEntityHandlerFlag flag,
         }
         else
         {
-            OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
+            OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
                     ehRequest->method);
             ret = OC_EH_ERROR;
         }
@@ -370,7 +370,7 @@ OCEntityHandlerResult OCEntityHandlerLightCb(OCEntityHandlerFlag flag,
             // Send the response
             if (OCDoResponse(&response) != OC_STACK_OK)
             {
-                OC_LOG(ERROR, TAG, "Error sending response");
+                OIC_LOG(ERROR, TAG, "Error sending response");
                 ret = OC_EH_ERROR;
             }
         }
@@ -393,7 +393,7 @@ OCEntityHandlerResult OCEntityHandlerFanCb(OCEntityHandlerFlag flag,
     OCEntityHandlerResult ret = OC_EH_OK;
     OCEntityHandlerResponse response;
 
-    OC_LOG_V(INFO, TAG, "Callback for Fan");
+    OIC_LOG_V(INFO, TAG, "Callback for Fan");
     PrintReceivedMsgInfo(flag, ehRequest );
 
     if(ehRequest && flag == OC_REQUEST_FLAG)
@@ -414,7 +414,7 @@ OCEntityHandlerResult OCEntityHandlerFanCb(OCEntityHandlerFlag flag,
         }
         else
         {
-            OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
+            OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
                     ehRequest->method);
             ret = OC_EH_ERROR;
         }
@@ -436,7 +436,7 @@ OCEntityHandlerResult OCEntityHandlerFanCb(OCEntityHandlerFlag flag,
             // Send the response
             if (OCDoResponse(&response) != OC_STACK_OK)
             {
-                OC_LOG(ERROR, TAG, "Error sending response");
+                OIC_LOG(ERROR, TAG, "Error sending response");
                 ret = OC_EH_ERROR;
             }
         }
@@ -471,7 +471,7 @@ void *ChangeLightRepresentation (void *param)
         light.power += 5;
         if (gLightUnderObservation)
         {
-            OC_LOG_V(INFO, TAG,
+            OIC_LOG_V(INFO, TAG,
                 " =====> Notifying stack of new power level %d\n", light.power);
             result = OCNotifyAllObservers (light.handle, OC_NA_QOS);
             if (OC_STACK_NO_OBSERVERS == result)
@@ -506,11 +506,11 @@ int main(int argc, char* argv[])
         return -1;
     }
 
-    OC_LOG(DEBUG, TAG, "OCServer is starting...");
+    OIC_LOG(DEBUG, TAG, "OCServer is starting...");
 
     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack init error");
+        OIC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
 
@@ -527,13 +527,13 @@ int main(int argc, char* argv[])
     pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)NULL);
 
     // Break from loop with Ctrl-C
-    OC_LOG(INFO, TAG, "Entering ocserver main loop...");
+    OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
     signal(SIGINT, handleSigInt);
     while (!gQuitFlag)
     {
         if (OCProcess() != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             return 0;
         }
         sleep(2);
@@ -545,11 +545,11 @@ int main(int argc, char* argv[])
     pthread_cancel(threadId);
     pthread_join(threadId, NULL);
 
-    OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
+    OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
 
     if (OCStop() != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack process error");
+        OIC_LOG(ERROR, TAG, "OCStack process error");
     }
 
     return 0;
@@ -567,7 +567,7 @@ void createResources()
             OCEntityHandlerFanCb,
             NULL,
             OC_DISCOVERABLE|OC_OBSERVABLE);
-    OC_LOG_V(INFO, TAG, "Created fan resource with result: %s", getResult(res));
+    OIC_LOG_V(INFO, TAG, "Created fan resource with result: %s", getResult(res));
 
     OCResourceHandle light;
     res = OCCreateResource(&light,
@@ -577,7 +577,7 @@ void createResources()
             OCEntityHandlerLightCb,
             NULL,
             OC_DISCOVERABLE|OC_OBSERVABLE);
-    OC_LOG_V(INFO, TAG, "Created light resource with result: %s", getResult(res));
+    OIC_LOG_V(INFO, TAG, "Created light resource with result: %s", getResult(res));
 
     OCResourceHandle room;
 
@@ -602,14 +602,14 @@ void createResources()
                 OC_DISCOVERABLE);
     }
 
-    OC_LOG_V(INFO, TAG, "Created room resource with result: %s", getResult(res));
+    OIC_LOG_V(INFO, TAG, "Created room resource with result: %s", getResult(res));
     OCBindResourceInterfaceToResource(room, OC_RSRVD_INTERFACE_LL);
     OCBindResourceInterfaceToResource(room, OC_RSRVD_INTERFACE_DEFAULT);
 
     res = OCBindResource(room, light);
-    OC_LOG_V(INFO, TAG, "OC Bind Contained Resource to resource: %s", getResult(res));
+    OIC_LOG_V(INFO, TAG, "OC Bind Contained Resource to resource: %s", getResult(res));
 
     res = OCBindResource(room, fan);
-    OC_LOG_V(INFO, TAG, "OC Bind Contained Resource to resource: %s", getResult(res));
+    OIC_LOG_V(INFO, TAG, "OC Bind Contained Resource to resource: %s", getResult(res));
 }
 
index 3858b23..e56e144 100644 (file)
@@ -54,17 +54,17 @@ OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
 {
     LEDResource *currLEDResource = &LED;
 
-    OC_LOG(INFO, TAG, "Entering constructResponse");
+    OIC_LOG(INFO, TAG, "Entering constructResponse");
 
     if (ehRequest->resource == gLedInstance[0].handle)
     {
-        OC_LOG(INFO, TAG, "handle 0");
+        OIC_LOG(INFO, TAG, "handle 0");
         currLEDResource = &gLedInstance[0];
         gResourceUri = const_cast<char *>("a/led/0");
     }
     else if (ehRequest->resource == gLedInstance[1].handle)
     {
-        OC_LOG(INFO, TAG, "handle 1");
+        OIC_LOG(INFO, TAG, "handle 1");
         currLEDResource = &gLedInstance[1];
         gResourceUri = const_cast<char *>("a/led/1");
     }
@@ -73,7 +73,7 @@ OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
     {
         if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
         {
-            OC_LOG(ERROR, TAG, ("Incoming payload not a representation"));
+            OIC_LOG(ERROR, TAG, ("Incoming payload not a representation"));
             return nullptr;
         }
 
@@ -96,7 +96,7 @@ OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
 
     if (!response)
     {
-        OC_LOG_V(ERROR, TAG, "Memory allocation for response payload failed.");
+        OIC_LOG_V(ERROR, TAG, "Memory allocation for response payload failed.");
     }
 
     OCRepPayloadSetUri (response, gResourceUri);
@@ -108,13 +108,13 @@ OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
 
 void ProcessGetPutRequest (OCEntityHandlerRequest *ehRequest)
 {
-    OC_LOG(INFO, TAG, "Entering ProcessGetPutRequest");
+    OIC_LOG(INFO, TAG, "Entering ProcessGetPutRequest");
 
     OCRepPayload *getResp = constructResponse(ehRequest);
 
     if(!getResp)
     {
-        OC_LOG(ERROR, TAG, "Failed to construct response");
+        OIC_LOG(ERROR, TAG, "Failed to construct response");
         return;
     }
 
@@ -135,7 +135,7 @@ void ProcessGetPutRequest (OCEntityHandlerRequest *ehRequest)
     // Send the response
     if (OCDoResponse(&response) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "Error sending response");
+        OIC_LOG(ERROR, TAG, "Error sending response");
     }
 
     free(getResp);
@@ -143,7 +143,7 @@ void ProcessGetPutRequest (OCEntityHandlerRequest *ehRequest)
 
 OCEntityHandlerRequest *CopyRequest(OCEntityHandlerRequest *entityHandlerRequest)
 {
-    OC_LOG(INFO, TAG, "Copying received request for slow response");
+    OIC_LOG(INFO, TAG, "Copying received request for slow response");
 
     OCEntityHandlerRequest *copyOfRequest =
             (OCEntityHandlerRequest *)OICMalloc(sizeof(OCEntityHandlerRequest));
@@ -159,7 +159,7 @@ OCEntityHandlerRequest *CopyRequest(OCEntityHandlerRequest *entityHandlerRequest
             copyOfRequest->query = OICStrdup(entityHandlerRequest->query);
             if(!copyOfRequest->query)
             {
-                OC_LOG(ERROR, TAG, "Copy failed due to allocation failure");
+                OIC_LOG(ERROR, TAG, "Copy failed due to allocation failure");
                 OICFree(copyOfRequest);
                 return NULL;
             }
@@ -178,11 +178,11 @@ OCEntityHandlerRequest *CopyRequest(OCEntityHandlerRequest *entityHandlerRequest
 
     if (copyOfRequest)
     {
-        OC_LOG(INFO, TAG, "Copied client request");
+        OIC_LOG(INFO, TAG, "Copied client request");
     }
     else
     {
-        OC_LOG(ERROR, TAG, "Error copying client request");
+        OIC_LOG(ERROR, TAG, "Error copying client request");
     }
     return copyOfRequest;
 }
@@ -193,16 +193,16 @@ OCEntityHandlerResult OCEntityHandlerCb (OCEntityHandlerFlag flag,
     OCEntityHandlerResult result = OC_EH_ERROR;
     OCEntityHandlerRequest *request = NULL;
 
-    OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
+    OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
 
     if (flag & OC_REQUEST_FLAG)
     {
-        OC_LOG(INFO, TAG, "Flag includes OC_REQUEST_FLAG");
+        OIC_LOG(INFO, TAG, "Flag includes OC_REQUEST_FLAG");
         if (entityHandlerRequest)
         {
-            OC_LOG_V (INFO, TAG, "request query %s from client",
+            OIC_LOG_V (INFO, TAG, "request query %s from client",
                                         entityHandlerRequest->query);
-            OC_LOG_PAYLOAD (INFO, entityHandlerRequest->payload);
+            OIC_LOG_PAYLOAD (INFO, entityHandlerRequest->payload);
 
             // Make deep copy of received request and queue it for slow processing
             request = CopyRequest(entityHandlerRequest);
@@ -210,7 +210,7 @@ OCEntityHandlerResult OCEntityHandlerCb (OCEntityHandlerFlag flag,
             if (request)
             {
 
-                OC_LOG(INFO, TAG, "Scheduling slow response for received request");
+                OIC_LOG(INFO, TAG, "Scheduling slow response for received request");
                 gRequestList.push_back(request);
                 // Indicate to the stack that this is a slow response
                 result = OC_EH_SLOW;
@@ -219,14 +219,14 @@ OCEntityHandlerResult OCEntityHandlerCb (OCEntityHandlerFlag flag,
             }
             else
             {
-                OC_LOG(ERROR, TAG, "Error queuing request for slow response");
+                OIC_LOG(ERROR, TAG, "Error queuing request for slow response");
                 // Indicate to the stack that this is a slow response
                 result = OC_EH_ERROR;
             }
         }
         else
         {
-            OC_LOG(ERROR, TAG, "Invalid request");
+            OIC_LOG(ERROR, TAG, "Invalid request");
             result = OC_EH_ERROR;
         }
     }
@@ -248,10 +248,10 @@ void AlarmHandler(int sig)
 {
     if (sig == SIGALRM)
     {
-        OC_LOG (INFO, TAG, "Server starting slow response");
+        OIC_LOG (INFO, TAG, "Server starting slow response");
         if (gRequestList.empty())
         {
-            OC_LOG (INFO, TAG, "No requests to service");
+            OIC_LOG (INFO, TAG, "No requests to service");
             return;
         }
 
@@ -260,17 +260,17 @@ void AlarmHandler(int sig)
         gRequestList.pop_front();
         if (entityHandlerRequest->method == OC_REST_GET)
         {
-            OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
+            OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
             ProcessGetPutRequest (entityHandlerRequest);
         }
         else if (entityHandlerRequest->method == OC_REST_PUT)
         {
-            OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
+            OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
             ProcessGetPutRequest (entityHandlerRequest);
         }
         else
         {
-            OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
+            OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
                     entityHandlerRequest->method);
         }
         // Free the request
@@ -288,11 +288,11 @@ void AlarmHandler(int sig)
 
 int main(int /*argc*/, char** /*argv[]*/)
 {
-    OC_LOG(DEBUG, TAG, "OCServer is starting...");
+    OIC_LOG(DEBUG, TAG, "OCServer is starting...");
 
     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack init error");
+        OIC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
 
@@ -303,20 +303,20 @@ int main(int /*argc*/, char** /*argv[]*/)
     signal(SIGALRM, AlarmHandler);
 
     // Break from loop with Ctrl-C
-    OC_LOG(INFO, TAG, "Entering ocserver main loop...");
+    OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
     signal(SIGINT, handleSigInt);
 
     while (!gQuitFlag)
     {
         if (OCProcess() != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             return 0;
         }
         sleep(2);
     }
 
-    OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
+    OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
 
     // Free requests
     if (!gRequestList.empty())
@@ -332,7 +332,7 @@ int main(int /*argc*/, char** /*argv[]*/)
 
     if (OCStop() != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack process error");
+        OIC_LOG(ERROR, TAG, "OCStack process error");
     }
 
     return 0;
@@ -342,7 +342,7 @@ int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState,
 {
     if (!uri)
     {
-        OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
+        OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
         return -1;
     }
 
@@ -355,7 +355,7 @@ int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState,
             OCEntityHandlerCb,
             NULL,
             OC_DISCOVERABLE|OC_OBSERVABLE);
-    OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
+    OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
 
     return 0;
 }
index db10b49..e15ae78 100644 (file)
@@ -67,8 +67,11 @@ samples_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
 ocserverbasicops = samples_env.Program('ocserverbasicops', ['common.cpp', 'ocserverbasicops.cpp'])
 occlientbasicops = samples_env.Program('occlientbasicops', ['common.cpp', 'occlientbasicops.cpp'])
 ocamsservice = samples_env.Program('ocamsservice', ['common.cpp', 'ocamsservice.cpp'])
-
-Alias("samples", [ocserverbasicops, occlientbasicops, ocamsservice])
+if env.get('SECURED') == '1':
+       occlientdirectpairing = samples_env.Program('occlientdirectpairing', 'occlientdirectpairing.cpp')
+       Alias("samples", [ocserverbasicops, occlientbasicops, ocamsservice, occlientdirectpairing])
+else:
+       Alias("samples", [ocserverbasicops, occlientbasicops, ocamsservice])
 
 env.AppendTarget('samples')
 
@@ -82,4 +85,15 @@ samples_env.Alias("install", samples_env.Install( sec_samples_build_dir,
     sec_samples_src_dir + 'oic_svr_db_client.json'))
 samples_env.Alias("install", samples_env.Install( sec_samples_build_dir,
     sec_samples_src_dir + 'oic_amss_db.json'))
+if env.get('SECURED') == '1':
+       samples_env.Alias("install", samples_env.Install( sec_samples_build_dir,
+               sec_samples_src_dir + 'oic_svr_db_client_directpairing.json'))
+       samples_env.Alias("install", samples_env.Install( sec_samples_build_dir,
+       sec_samples_src_dir + 'oic_svr_db_client_directpairing.dat'))
 
+samples_env.Alias("install", samples_env.Install( sec_samples_build_dir,
+    sec_samples_src_dir + 'oic_svr_db_server.dat'))
+samples_env.Alias("install", samples_env.Install( sec_samples_build_dir,
+    sec_samples_src_dir + 'oic_svr_db_client.dat'))
+samples_env.Alias("install", samples_env.Install( sec_samples_build_dir,
+    sec_samples_src_dir + 'oic_amss_db.dat'))
index c22d371..4a6b14e 100644 (file)
@@ -16,7 +16,7 @@ int gQuitFlag = 0;
 
 //AMS service database, hold AMS service Identity and
 //the PSK credentials of trusted devices
-static char AMSS_DB_FILE[] = "oic_amss_db.json";
+static char AMSS_DB_FILE[] = "oic_amss_db.dat";
 
 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
 void handleSigInt(int signum)
@@ -37,7 +37,7 @@ int main(int /*argc*/, char* /*argv*/[])
 {
     struct timespec timeout;
 
-    OC_LOG(DEBUG, TAG, "OCAMS service is starting...");
+    OIC_LOG(DEBUG, TAG, "OCAMS service is starting...");
 
     // Initialize Persistent Storage for SVR database
     OCPersistentStorage ps = { service_fopen, fread, fwrite, fclose, unlink };
@@ -45,7 +45,7 @@ int main(int /*argc*/, char* /*argv*/[])
 
     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack init error");
+        OIC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
 
@@ -53,23 +53,23 @@ int main(int /*argc*/, char* /*argv*/[])
     timeout.tv_nsec = 100000000L;
 
     // Break from loop with Ctrl-C
-    OC_LOG(INFO, TAG, "Entering ocamsservice main loop...");
+    OIC_LOG(INFO, TAG, "Entering ocamsservice main loop...");
     signal(SIGINT, handleSigInt);
     while (!gQuitFlag)
     {
         if (OCProcess() != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             return 0;
         }
         nanosleep(&timeout, NULL);
     }
 
-    OC_LOG(INFO, TAG, "Exiting ocamsservice main loop...");
+    OIC_LOG(INFO, TAG, "Exiting ocamsservice main loop...");
 
     if (OCStop() != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack process error");
+        OIC_LOG(ERROR, TAG, "OCStack process error");
     }
 
     return 0;
index c72458a..0f5d93b 100644 (file)
@@ -49,7 +49,7 @@ static OCConnectivityType ocConnType;
 //Secure Virtual Resource database for Iotivity Client application
 //It contains Client's Identity and the PSK credentials
 //of other devices which the client trusts
-static char CRED_FILE[] = "oic_svr_db_client.json";
+static char CRED_FILE[] = "oic_svr_db_client.dat";
 
 
 int gQuitFlag = 0;
@@ -81,14 +81,14 @@ OCPayload* putPayload()
 
 static void PrintUsage()
 {
-    OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
-    OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
-    OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
-    OC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
+    OIC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
+    OIC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
+    OIC_LOG(INFO, TAG, "-t 1 : Discover Resources");
+    OIC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
             " Initiate Nonconfirmable Get/Put/Post Requests");
-    OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
-    OC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
-    OC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
+    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");
 }
 
 OCStackResult InvokeOCDoResource(std::ostringstream &query,
@@ -111,7 +111,7 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query,
 
     if (ret != OC_STACK_OK)
     {
-        OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
+        OIC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
     }
 
     return ret;
@@ -119,40 +119,40 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query,
 
 OCStackApplicationResult putReqCB(void*, OCDoHandle, OCClientResponse * clientResponse)
 {
-    OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
+    OIC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
 
     if(clientResponse)
     {
-        OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
-        OC_LOG_PAYLOAD(INFO, clientResponse->payload);
-        OC_LOG(INFO, TAG, ("=============> Put Response"));
+        OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
+        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        OIC_LOG(INFO, TAG, ("=============> Put Response"));
     }
     return OC_STACK_DELETE_TRANSACTION;
 }
 
 OCStackApplicationResult postReqCB(void *, OCDoHandle, OCClientResponse *clientResponse)
 {
-    OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
+    OIC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
 
     if(clientResponse)
     {
-        OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
-        OC_LOG_PAYLOAD(INFO, clientResponse->payload);
-        OC_LOG(INFO, TAG, ("=============> Post Response"));
+        OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
+        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        OIC_LOG(INFO, TAG, ("=============> Post Response"));
     }
     return OC_STACK_DELETE_TRANSACTION;
 }
 
 OCStackApplicationResult getReqCB(void*, OCDoHandle, OCClientResponse * clientResponse)
 {
-    OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
+    OIC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
 
     if(clientResponse)
     {
-        OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
-        OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
-        OC_LOG_PAYLOAD(INFO, clientResponse->payload);
-        OC_LOG(INFO, TAG, ("=============> Get Response"));
+        OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
+        OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
+        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        OIC_LOG(INFO, TAG, ("=============> Get Response"));
     }
     return OC_STACK_DELETE_TRANSACTION;
 }
@@ -161,19 +161,19 @@ OCStackApplicationResult getReqCB(void*, OCDoHandle, OCClientResponse * clientRe
 OCStackApplicationResult discoveryReqCB(void*, OCDoHandle,
         OCClientResponse * clientResponse)
 {
-    OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
+    OIC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
 
     if (clientResponse)
     {
-        OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
-        OC_LOG_V(INFO, TAG,
+        OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
+        OIC_LOG_V(INFO, TAG,
                 "Device =============> Discovered @ %s:%d",
                 clientResponse->devAddr.addr,
                 clientResponse->devAddr.port);
 
         if (clientResponse->result == OC_STACK_OK)
         {
-            OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+            OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
 
             ocConnType = clientResponse->connType;
             endpoint = clientResponse->devAddr;
@@ -203,7 +203,7 @@ OCStackApplicationResult discoveryReqCB(void*, OCDoHandle,
 
 int InitPutRequest(OCQualityOfService qos)
 {
-    OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
+    OIC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
     query << coapServerResource;
     endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
@@ -214,7 +214,7 @@ int InitPutRequest(OCQualityOfService qos)
 int InitPostRequest(OCQualityOfService qos)
 {
     OCStackResult result;
-    OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
+    OIC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
     query << coapServerResource;
     endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
@@ -226,7 +226,7 @@ int InitPostRequest(OCQualityOfService qos)
     if (OC_STACK_OK != result)
     {
         // Error can happen if for example, network connectivity is down
-        OC_LOG(INFO, TAG, "First POST call did not succeed");
+        OIC_LOG(INFO, TAG, "First POST call did not succeed");
     }
 
     // Second POST operation (to create an LED instance)
@@ -235,7 +235,7 @@ int InitPostRequest(OCQualityOfService qos)
             postReqCB, NULL, 0);
     if (OC_STACK_OK != result)
     {
-        OC_LOG(INFO, TAG, "Second POST call did not succeed");
+        OIC_LOG(INFO, TAG, "Second POST call did not succeed");
     }
 
     // This POST operation will update the original resourced /a/led
@@ -246,7 +246,7 @@ int InitPostRequest(OCQualityOfService qos)
 
 int InitGetRequest(OCQualityOfService qos)
 {
-    OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
+    OIC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
     query << coapServerResource;
     endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
@@ -265,9 +265,9 @@ int InitDiscovery()
 
     if (UnicastDiscovery)
     {
-        OC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
-        OC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
-        OC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
+        OIC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
+        OIC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
+        OIC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
 
         if (fgets(ipaddr, sizeof (ipaddr), stdin))
         {
@@ -275,7 +275,7 @@ int InitDiscovery()
         }
         else
         {
-            OC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
+            OIC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
             return OC_STACK_INVALID_PARAM;
         }
     }
@@ -286,7 +286,7 @@ int InitDiscovery()
     cbData.cd = NULL;
 
     /* Start a discovery query*/
-    OC_LOG_V(INFO, TAG, "Initiating %s Resource Discovery : %s\n",
+    OIC_LOG_V(INFO, TAG, "Initiating %s Resource Discovery : %s\n",
         (UnicastDiscovery) ? "Unicast" : "Multicast",
         queryUri);
 
@@ -294,7 +294,7 @@ int InitDiscovery()
                        OC_LOW_QOS, &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack resource error");
+        OIC_LOG(ERROR, TAG, "OCStack resource error");
     }
     return ret;
 }
@@ -344,7 +344,7 @@ int main(int argc, char* argv[])
     }
     else
     {
-        OC_LOG(INFO, TAG, "Using Default Connectivity type");
+        OIC_LOG(INFO, TAG, "Using Default Connectivity type");
         PrintUsage();
     }
 
@@ -356,7 +356,7 @@ int main(int argc, char* argv[])
     /* Initialize OCStack*/
     if (OCInit(NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack init error");
+        OIC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
 
@@ -366,23 +366,23 @@ int main(int argc, char* argv[])
     timeout.tv_nsec = 100000000L;
 
     // Break from loop with Ctrl+C
-    OC_LOG(INFO, TAG, "Entering occlient main loop...");
+    OIC_LOG(INFO, TAG, "Entering occlient main loop...");
     signal(SIGINT, handleSigInt);
     while (!gQuitFlag)
     {
         if (OCProcess() != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             return 0;
         }
 
         nanosleep(&timeout, NULL);
     }
-    OC_LOG(INFO, TAG, "Exiting occlient main loop...");
+    OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
 
     if (OCStop() != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack stop error");
+        OIC_LOG(ERROR, TAG, "OCStack stop error");
     }
 
     return 0;
@@ -399,7 +399,7 @@ int parseClientResponse(OCClientResponse * clientResponse)
     while (res)
     {
         coapServerResource.assign(res->uri);
-        OC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
+        OIC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
 
         if (res->secure)
         {
@@ -407,7 +407,7 @@ int parseClientResponse(OCClientResponse * clientResponse)
             coapSecureResource = 1;
         }
 
-        OC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
+        OIC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
 
         // If we discovered a secure resource, exit from here
         if (coapSecureResource)
diff --git a/resource/csdk/stack/samples/linux/secure/occlientdirectpairing.cpp b/resource/csdk/stack/samples/linux/secure/occlientdirectpairing.cpp
new file mode 100644 (file)
index 0000000..0979901
--- /dev/null
@@ -0,0 +1,641 @@
+//******************************************************************\r
+//\r
+// Copyright 2014 Intel Mobile Communications GmbH 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
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <string.h>\r
+#include <signal.h>\r
+#include <unistd.h>\r
+#include <pthread.h>\r
+#include <iostream>\r
+#include <sstream>\r
+#include "ocstack.h"\r
+#include "logger.h"\r
+#include "ocpayload.h"\r
+#include "payload_logging.h"\r
+#include "oic_malloc.h"\r
+#include "oic_string.h"\r
+#include "utlist.h"\r
+\r
+#define TAG "occlient-directpairing"\r
+\r
+#define BOLD_BEGIN    "\033[1m"\r
+#define RED_BEGIN      "\033[1;31m"\r
+#define GREEN_BEGIN  "\033[1;92m"\r
+#define COLOR_END      "\033[0m"\r
+#define MAX_LINE (1024)\r
+#define DP_DISCOVERY_TIMEOUT   3  // 3 sec\r
+#define DP_PIN_LENGTH 8 // 8 digit\r
+\r
+static char DISCOVERY_QUERY[] = "%s/oic/res";\r
+\r
+//Secure Virtual Resource database for Iotivity Client application\r
+//It contains Client's Identity and the PSK credentials\r
+//of other devices which the client trusts\r
+static char CRED_FILE[] = "oic_svr_db_client_directpairing.dat";\r
+\r
+static const OCDPDev_t *discoveredDevs = NULL;\r
+static const OCDPDev_t *pairedDevs = NULL;\r
+\r
+int gQuitFlag = 0;\r
+\r
+//-----------------------------------------------------------------------------\r
+// Function prototype\r
+//-----------------------------------------------------------------------------\r
+\r
+\r
+\r
+\r
+//-----------------------------------------------------------------------------\r
+// Function body\r
+//-----------------------------------------------------------------------------\r
+\r
+/* SIGINT handler: set gQuitFlag to 1 for graceful termination */\r
+void handleSigInt(int signum)\r
+{\r
+    if (signum == SIGINT)\r
+    {\r
+        gQuitFlag = 1;\r
+    }\r
+}\r
+\r
+const char *readline(const char *in, const char *defaultStr)\r
+{\r
+    static char rbuffer[MAX_LINE] = {0,};\r
+    char *cptr, *p;\r
+\r
+    size_t in_len = strlen(in);\r
+    for (size_t i=0; i<in_len; i++)\r
+    {\r
+        fprintf(stdout, "%c", in[i]);\r
+    }\r
+\r
+    if (NULL != (cptr = fgets(rbuffer, MAX_LINE, stdin)))\r
+    {\r
+        /* kill preceding whitespace but leave \n so we're guaranteed to have something */\r
+        /*while(*cptr == ' ' || *cptr == '\t')\r
+        {\r
+            cptr++;\r
+        }*/\r
+\r
+        if ( (p = strchr(cptr, '\n')) != NULL )\r
+        {\r
+            *p = '\0';\r
+        }\r
+\r
+        if (strlen(cptr)==0 && defaultStr)\r
+        {\r
+            return defaultStr;\r
+        }\r
+        return cptr;\r
+    }\r
+    else\r
+    {\r
+        return 0;\r
+    }\r
+}\r
+\r
+const char *getResult(OCStackResult result) {\r
+    switch (result) {\r
+    case OC_STACK_OK:\r
+        return "OC_STACK_OK";\r
+    case OC_STACK_RESOURCE_CREATED:\r
+        return "OC_STACK_RESOURCE_CREATED";\r
+    case OC_STACK_RESOURCE_DELETED:\r
+        return "OC_STACK_RESOURCE_DELETED";\r
+    case OC_STACK_INVALID_URI:\r
+        return "OC_STACK_INVALID_URI";\r
+    case OC_STACK_INVALID_QUERY:\r
+        return "OC_STACK_INVALID_QUERY";\r
+    case OC_STACK_INVALID_IP:\r
+        return "OC_STACK_INVALID_IP";\r
+    case OC_STACK_INVALID_PORT:\r
+        return "OC_STACK_INVALID_PORT";\r
+    case OC_STACK_INVALID_CALLBACK:\r
+        return "OC_STACK_INVALID_CALLBACK";\r
+    case OC_STACK_INVALID_METHOD:\r
+        return "OC_STACK_INVALID_METHOD";\r
+    case OC_STACK_NO_MEMORY:\r
+        return "OC_STACK_NO_MEMORY";\r
+    case OC_STACK_COMM_ERROR:\r
+        return "OC_STACK_COMM_ERROR";\r
+    case OC_STACK_INVALID_PARAM:\r
+        return "OC_STACK_INVALID_PARAM";\r
+    case OC_STACK_NOTIMPL:\r
+        return "OC_STACK_NOTIMPL";\r
+    case OC_STACK_NO_RESOURCE:\r
+        return "OC_STACK_NO_RESOURCE";\r
+    case OC_STACK_RESOURCE_ERROR:\r
+        return "OC_STACK_RESOURCE_ERROR";\r
+    case OC_STACK_SLOW_RESOURCE:\r
+        return "OC_STACK_SLOW_RESOURCE";\r
+    case OC_STACK_NO_OBSERVERS:\r
+        return "OC_STACK_NO_OBSERVERS";\r
+    #ifdef WITH_PRESENCE\r
+    case OC_STACK_PRESENCE_STOPPED:\r
+        return "OC_STACK_PRESENCE_STOPPED";\r
+    #endif\r
+    case OC_STACK_ERROR:\r
+        return "OC_STACK_ERROR";\r
+    default:\r
+        return "UNKNOWN";\r
+    }\r
+}\r
+\r
+OCDPDev_t* getDev(const OCDPDev_t* pList, const uint32_t dev_num)\r
+{\r
+    if(NULL == pList)\r
+    {\r
+        printf("     Device List is Empty..\n");\r
+        return NULL;\r
+    }\r
+\r
+    OCDPDev_t* lst =  (OCDPDev_t*)pList;\r
+    for(size_t i=0; lst; )\r
+    {\r
+        if(dev_num == ++i)\r
+        {\r
+            return lst;\r
+        }\r
+        lst = lst->next;\r
+    }\r
+\r
+    return NULL;  // in here |lst| is always |NULL|\r
+}\r
+\r
+int printList(const OCDPDev_t* pList)\r
+{\r
+    if(!pList)\r
+    {\r
+        printf("     Device List is Empty..\n\n");\r
+        return 0;\r
+    }\r
+\r
+    const OCDPDev_t* lst = pList;\r
+    int lst_cnt = 0;\r
+    for( ; lst; )\r
+    {\r
+        printf("     [%d] ", ++lst_cnt);\r
+        for(int i=0; i<UUID_IDENTITY_SIZE; i++)\r
+        {\r
+            fprintf(stdout, "%c", (char)lst->deviceID.id[i]);\r
+        }\r
+        printf("\n");\r
+        lst = lst->next;\r
+    }\r
+    printf("\n");\r
+\r
+    return lst_cnt;\r
+}\r
+\r
+bool printPairingMethod(const OCDPDev_t* pDev)\r
+{\r
+    printf("\n   * List of supported pairing method\n");\r
+\r
+    if(!pDev || false == pDev->edp)\r
+    {\r
+        printf("     Invalid device or Not support direct-pairing..\n\n");\r
+        return false;\r
+    }\r
+\r
+    if(!pDev->prm || 0 == pDev->prmLen)\r
+    {\r
+        printf("     Not exist any support method..\n\n");\r
+        return false;\r
+    }\r
+\r
+    bool bAvailable = true;\r
+    for(size_t i=0; i<pDev->prmLen; i++)\r
+    {\r
+        printf("     [%ld] ", i+1);\r
+        switch (pDev->prm[i])\r
+        {\r
+            case DP_PRE_CONFIGURED:\r
+                printf("Pre-Configured PIN");\r
+                break;\r
+            case DP_RANDOM_PIN:\r
+                printf("Random PIN");\r
+                break;\r
+            default:\r
+                printf("NOT Allowed (%d)", pDev->prm[i]);\r
+                bAvailable = false;\r
+                break;\r
+        }\r
+        printf("\n");\r
+    }\r
+    printf("\n");\r
+\r
+    return bAvailable;\r
+}\r
+\r
+// This is a function called back when a device is discovered\r
+OCStackApplicationResult discoveryReqCB(void*, OCDoHandle,\r
+        OCClientResponse * clientResponse)\r
+{\r
+    OIC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");\r
+\r
+    if (clientResponse)\r
+    {\r
+        OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));\r
+        OIC_LOG_V(INFO, TAG,\r
+                "Device =============> Discovered @ %s:%d",\r
+                clientResponse->devAddr.addr,\r
+                clientResponse->devAddr.port);\r
+\r
+        if (clientResponse->result == OC_STACK_OK)\r
+        {\r
+            OIC_LOG_PAYLOAD(INFO, clientResponse->payload);\r
+        }\r
+    }\r
+\r
+    return OC_STACK_DELETE_TRANSACTION;\r
+\r
+}\r
+\r
+// This is a function called back when direct-pairing status is changed\r
+void pairingReqCB(OCDPDev_t* peer, OCStackResult result)\r
+{\r
+    OIC_LOG(INFO, TAG, "Callback Context for Direct-Pairing establishment\n");\r
+\r
+    if (OC_STACK_OK == result)\r
+    {\r
+        OIC_LOG_V(INFO, TAG,\r
+                "Direct-Pairing SUCCESS =============> Target @ %s:%d\n",\r
+                peer->endpoint.addr,\r
+                peer->endpoint.port);\r
+    }\r
+    else\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Direct-Pairing FAILED..\n");\r
+    }\r
+}\r
+\r
+OCStackApplicationResult getReqCB(void * ctx, OCDoHandle handle, OCClientResponse *clientResponse)\r
+{\r
+    OIC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");\r
+\r
+    (void)ctx;\r
+    (void)handle;\r
+    if (clientResponse)\r
+    {\r
+        OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));\r
+        OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);\r
+        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);\r
+        if ((OCSecurityPayload*)clientResponse->payload)\r
+        {\r
+            OIC_LOG(INFO, TAG, PCF("=============> Get Response"));\r
+        }\r
+    }\r
+    return OC_STACK_DELETE_TRANSACTION;\r
+}\r
+\r
+int DeviceDiscovery()\r
+{\r
+    OCStackResult ret;\r
+    OCCallbackData cbData;\r
+    char queryUri[200];\r
+    char ipaddr[100] = { '\0' };\r
+\r
+    snprintf(queryUri, sizeof (queryUri), DISCOVERY_QUERY, ipaddr);\r
+\r
+    cbData.cb = discoveryReqCB;\r
+    cbData.context = NULL;\r
+    cbData.cd = NULL;\r
+\r
+    /* Start a discovery query*/\r
+    OIC_LOG_V(INFO, TAG, "Resource Discovery : %s\n", queryUri);\r
+\r
+    ret = OCDoResource(NULL, OC_REST_DISCOVER, queryUri, 0, 0, CT_DEFAULT,\r
+                       OC_LOW_QOS, &cbData, NULL, 0);\r
+    if (ret != OC_STACK_OK)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "OCStack resource error");\r
+    }\r
+    return ret;\r
+}\r
+\r
+OCStackResult DirectPairingDiscovery()\r
+{\r
+    // initiate direct pairing discovery\r
+    OIC_LOG(INFO, TAG, "   Discovering Only Owned Devices on Network..");\r
+    discoveredDevs = OCDiscoverDirectPairingDevices(DP_DISCOVERY_TIMEOUT);\r
+    if(NULL == discoveredDevs)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "OCDiscoverDirectPairingDevices API error");\r
+        return OC_STACK_ERROR;\r
+    }\r
+\r
+    // display the discovered unowned list\r
+    printf("   > Discovered Direct-Pairing Support Devices\n");\r
+    printList(discoveredDevs);\r
+\r
+    return OC_STACK_OK;\r
+}\r
+\r
+OCStackResult DoDirectPairing(OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber)\r
+{\r
+    if (NULL == peer || NULL == pinNumber)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "invalid parameter");\r
+        return OC_STACK_INVALID_PARAM;\r
+    }\r
+\r
+    // start direct pairing\r
+    OIC_LOG(INFO, TAG, "   Start Direct Pairing..");\r
+    if(OC_STACK_OK != OCDoDirectPairing(peer, pmSel, pinNumber, pairingReqCB))\r
+    {\r
+        OIC_LOG(ERROR, TAG, "OCDoDirectPairing API error");\r
+        return OC_STACK_ERROR;\r
+    }\r
+\r
+    return OC_STACK_OK;\r
+}\r
+\r
+OCStackResult SendGetRequest(OCDPDev_t* peer)\r
+{\r
+    OIC_LOG(INFO, TAG, "Send Get REQ to Led server");\r
+\r
+    char szQueryUri[] = "/a/led";\r
+    OCDoHandle handle;\r
+    OCCallbackData cbData;\r
+    OCDevAddr endpoint;\r
+    OCStackResult ret;\r
+\r
+    memcpy(&endpoint, &peer->endpoint, sizeof(OCDevAddr));\r
+    endpoint.port = peer->securePort;\r
+    endpoint.flags = (OCTransportFlags)(endpoint.flags | OC_SECURE);\r
+\r
+    cbData.cb = getReqCB;\r
+    cbData.context = NULL;\r
+    cbData.cd = NULL;\r
+\r
+    OIC_LOG(INFO, TAG, "Request to /a/light ");\r
+    ret = OCDoResource(&handle, OC_REST_GET, szQueryUri,\r
+               &endpoint, NULL, peer->connType, OC_LOW_QOS, &cbData, NULL, 0);\r
+    if (ret != OC_STACK_OK)\r
+    {\r
+        OIC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, OC_REST_GET);\r
+    }\r
+\r
+    return ret;\r
+}\r
+\r
+FILE* client_fopen(const char *path, const char *mode)\r
+{\r
+    (void)path;\r
+    return fopen(CRED_FILE, mode);\r
+}\r
+\r
+void *CLInterface(void *data)\r
+{\r
+    printf(RED_BEGIN"#Ready to operation ('h' for help)#\n"COLOR_END);\r
+\r
+    (void)data;\r
+    OCStackResult ret;\r
+    char query[MAX_LINE] = {0,};\r
+    const char prompt[] = BOLD_BEGIN"IoTivity-DP#"COLOR_END" ";\r
+    const char* helpmsg[6] = {\r
+            GREEN_BEGIN"# h  (or help) : show help message"COLOR_END,\r
+            GREEN_BEGIN"# dd (DP device discovery) : discover Direct-Pairing devices"COLOR_END,\r
+            GREEN_BEGIN"# dp (start Direct-Pairing) : negotiate DP method & start Direct-Pairing"COLOR_END,\r
+            GREEN_BEGIN"# sd (send data) : send data to device"COLOR_END,\r
+            GREEN_BEGIN"# ll (list all device) : list all discovered/paired devices"COLOR_END,\r
+            GREEN_BEGIN"# q  (quit) : quit test"COLOR_END,\r
+        };\r
+\r
+    for (size_t i=0; i<(sizeof(helpmsg)/sizeof(char*)); i++)\r
+    {\r
+        fprintf(stderr, "%s\n", helpmsg[i]);\r
+    }\r
+    printf("\n");\r
+\r
+    // cli\r
+    for (;;)\r
+    {\r
+        const char *input = readline(prompt, NULL);\r
+        if (!input) {\r
+            continue;\r
+        }\r
+\r
+        strncpy(query, input, MAX_LINE);\r
+        if (!strlen(query))\r
+        {\r
+            continue;\r
+        }\r
+        else if (!strcmp(query, "h") || !strcmp(query, "help"))\r
+        {\r
+            for (size_t i=0; i<(sizeof(helpmsg)/sizeof(char*)); i++)\r
+            {\r
+                fprintf(stderr, "%s\n", helpmsg[i]);\r
+            }\r
+            continue;\r
+        }\r
+        else\r
+        {\r
+            if (!strcmp(query, "dd"))\r
+            {\r
+                OIC_LOG(INFO, TAG, "- Direct-Pairing device discovery -");\r
+\r
+                ret = DirectPairingDiscovery();\r
+                if (OC_STACK_OK != ret)\r
+                {\r
+                    OIC_LOG(ERROR, TAG, "Error in DirectPairingDiscovery()");\r
+                }\r
+            }\r
+            else if (!strcmp(query, "dp"))\r
+            {\r
+                OIC_LOG(INFO, TAG, "- Negotiate DP method & Start Direct-Pairing -");\r
+\r
+                printf("\n   * List of  discovered device\n");\r
+                printList(discoveredDevs);\r
+\r
+                // target peer\r
+                OCDPDev_t *peer = NULL;\r
+                long peerIdx;\r
+                input = readline("   > Enter Peer Device Number to initiate Direct-Pairing: ", NULL);\r
+                if (!input || !strlen(input))\r
+                {\r
+                    continue;\r
+                }\r
+                char *ptr;\r
+                peerIdx = strtol(input, &ptr, 10);\r
+\r
+                peer = getDev(discoveredDevs, (uint32_t)peerIdx);\r
+                if (NULL == peer)\r
+                {\r
+                    OIC_LOG(ERROR, TAG, "Not found the peer in discovered list");\r
+                    continue;\r
+                }\r
+\r
+                // get pairing method\r
+                long pmIdx;\r
+                OCPrm_t pmSel = DP_NOT_ALLOWED;\r
+                if (false == printPairingMethod(peer))\r
+                {\r
+                    OIC_LOG(ERROR, TAG, "Target does not support the Direct-Pairing");\r
+                    continue;\r
+                }\r
+                input = readline("   > Enter pairing method: ", NULL);\r
+                if (!input || !strlen(input))\r
+                {\r
+                    continue;\r
+                }\r
+                pmIdx = strtol(input, &ptr, 10);\r
+                printf("\n");\r
+                if (0 >= pmIdx || peer->prmLen+1 < (size_t)pmIdx)\r
+                {\r
+                    OIC_LOG(ERROR, TAG, "Invalid mode selection");\r
+                    continue;\r
+                }\r
+                pmSel = peer->prm[pmIdx-1];\r
+\r
+                // get PIN\r
+                char pinNumber[DP_PIN_LENGTH+1];\r
+                input = readline("   > Enter PIN Number for authentication (ex - '00000000' [8 digit] ): ", NULL);\r
+                if (!input || DP_PIN_LENGTH != strlen(input))\r
+                {\r
+                    OIC_LOG(ERROR, TAG, "Invalid PIN");\r
+                    continue;\r
+                }\r
+                sscanf(input, "%8s", pinNumber);\r
+                printf("\n");\r
+\r
+                ret = DoDirectPairing(peer, pmSel, pinNumber);\r
+                if (OC_STACK_OK != ret)\r
+                {\r
+                    OIC_LOG(ERROR, TAG, "Error in DoDirectPairing()");\r
+                }\r
+            }\r
+            else if (!strcmp(query, "sd"))\r
+            {\r
+                OIC_LOG(INFO, TAG, "- Send data(GET Request) to device(led server) -");\r
+\r
+                //pairedDevs = OCGetDirectPairedDevices();\r
+                //printList(pairedDevs);\r
+                printList(discoveredDevs);\r
+\r
+                // target peer\r
+                OCDPDev_t *peer = NULL;\r
+                long peerIdx;\r
+                input = readline("   > Enter Peer Device Number to initiate Direct-Pairing: ", NULL);\r
+                if (!input || !strlen(input))\r
+                {\r
+                    continue;\r
+                }\r
+                char *ptr;\r
+                peerIdx = strtol(input, &ptr, 10);\r
+\r
+                //peer = getDev(pairedDevs, peerIdx);\r
+                peer = getDev(discoveredDevs, (uint32_t)peerIdx);\r
+                if (NULL == peer)\r
+                {\r
+                    OIC_LOG(ERROR, TAG, "Not found the peer in discovered list");\r
+                    continue;\r
+                }\r
+\r
+                // send Get Req\r
+                ret = SendGetRequest(peer);\r
+                if (OC_STACK_OK != ret)\r
+                {\r
+                    OIC_LOG(ERROR, TAG, "Error in SendGetRequest()");\r
+                }\r
+            }\r
+            else if (!strcmp(query, "ll"))\r
+            {\r
+                OIC_LOG(INFO, TAG, "- List all discovered and paired devices) -");\r
+\r
+                printf("  > List of discovered devices\n");\r
+                printList(discoveredDevs);\r
+                printf("\n");\r
+\r
+                printf("  > List of paired devices\n");\r
+                pairedDevs = OCGetDirectPairedDevices();\r
+                printList(pairedDevs);\r
+                printf("\n");\r
+            }\r
+            else if (!strcmp(query, "q"))\r
+            {\r
+                printf("QUIT\n");\r
+                gQuitFlag = 1;\r
+                break;\r
+            }\r
+        }\r
+    }\r
+\r
+    return 0;\r
+}\r
+\r
+int main(void)\r
+{\r
+    struct timespec timeout;\r
+\r
+    // Initialize Persistent Storage for SVR database\r
+    OCPersistentStorage ps = { client_fopen, fread, fwrite, fclose, unlink };\r
+    OCRegisterPersistentStorageHandler(&ps);\r
+\r
+    /* Initialize OCStack*/\r
+    if (OCInit(NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "OCStack init error");\r
+        return 0;\r
+    }\r
+\r
+//    DeviceDiscovery();\r
+\r
+    timeout.tv_sec  = 0;\r
+    timeout.tv_nsec = 100000000L;\r
+\r
+    // Break from loop with Ctrl+C\r
+    OIC_LOG(INFO, TAG, "Entering occlient main loop...");\r
+    signal(SIGINT, handleSigInt);\r
+\r
+    // CLI\r
+    int thr_id;\r
+    pthread_t p_thread;\r
+    thr_id = pthread_create(&p_thread, NULL, CLInterface, (void *)NULL);\r
+    if (thr_id < 0)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "create CLI Thread error");\r
+        return 0;\r
+    }\r
+\r
+    // loop\r
+    while (!gQuitFlag)\r
+    {\r
+        if (OCProcess() != OC_STACK_OK)\r
+        {\r
+            OIC_LOG(ERROR, TAG, "OCStack process error");\r
+            return 0;\r
+        }\r
+\r
+        nanosleep(&timeout, NULL);\r
+    }\r
+    OIC_LOG(INFO, TAG, "Exiting occlient main loop...");\r
+\r
+    if (OCStop() != OC_STACK_OK)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "OCStack stop error");\r
+    }\r
+\r
+    return 0;\r
+}\r
+\r
+\r
+\r
index 8db063c..22bc674 100644 (file)
@@ -45,14 +45,14 @@ char *gResourceUri= (char *)"/a/led";
 //Secure Virtual Resource database for Iotivity Server
 //It contains Server's Identity and the PSK credentials
 //of other devices which the server trusts
-static char CRED_FILE[] = "oic_svr_db_server.json";
+static char CRED_FILE[] = "oic_svr_db_server.dat";
 
 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
 {
     OCRepPayload* payload = OCRepPayloadCreate();
     if(!payload)
     {
-        OC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
+        OIC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
         return nullptr;
     }
 
@@ -68,7 +68,7 @@ OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
 {
     if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
     {
-        OC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
+        OIC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
         return nullptr;
     }
 
@@ -178,7 +178,7 @@ OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
 
             if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
             {
-                OC_LOG (INFO, TAG, "Created new LED instance");
+                OIC_LOG (INFO, TAG, "Created new LED instance");
                 gLedInstance[gCurrLedInstance].state = 0;
                 gLedInstance[gCurrLedInstance].power = 0;
                 gCurrLedInstance++;
@@ -217,7 +217,7 @@ OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
     }
     else
     {
-        OC_LOG_V (INFO, TAG, "Payload was NULL");
+        OIC_LOG_V (INFO, TAG, "Payload was NULL");
         ehResult = OC_EH_ERROR;
     }
 
@@ -229,14 +229,14 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
         OCEntityHandlerRequest *entityHandlerRequest,
         void* /*callbackParam*/)
 {
-    OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
+    OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
 
     OCEntityHandlerResult ehResult = OC_EH_ERROR;
     OCEntityHandlerResponse response = { 0, 0, OC_EH_ERROR, 0, 0, { },{ 0 }, false };
     // Validate pointer
     if (!entityHandlerRequest)
     {
-        OC_LOG (ERROR, TAG, "Invalid request pointer");
+        OIC_LOG (ERROR, TAG, "Invalid request pointer");
         return OC_EH_ERROR;
     }
 
@@ -244,27 +244,27 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
 
     if (flag & OC_REQUEST_FLAG)
     {
-        OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
+        OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
         if (entityHandlerRequest)
         {
             if (OC_REST_GET == entityHandlerRequest->method)
             {
-                OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
+                OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
                 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
             }
             else if (OC_REST_PUT == entityHandlerRequest->method)
             {
-                OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
+                OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
                 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
             }
             else if (OC_REST_POST == entityHandlerRequest->method)
             {
-                OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
+                OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
                 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
             }
             else
             {
-                OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
+                OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
                         entityHandlerRequest->method);
                 ehResult = OC_EH_ERROR;
             }
@@ -285,7 +285,7 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
                 // Send the response
                 if (OCDoResponse(&response) != OC_STACK_OK)
                 {
-                    OC_LOG(ERROR, TAG, "Error sending response");
+                    OIC_LOG(ERROR, TAG, "Error sending response");
                     ehResult = OC_EH_ERROR;
                 }
             }
@@ -315,7 +315,7 @@ int main(int /*argc*/, char* /*argv*/[])
 {
     struct timespec timeout;
 
-    OC_LOG(DEBUG, TAG, "OCServer is starting...");
+    OIC_LOG(DEBUG, TAG, "OCServer is starting...");
 
     // Initialize Persistent Storage for SVR database
     OCPersistentStorage ps = { server_fopen, fread, fwrite, fclose, unlink };
@@ -323,7 +323,7 @@ int main(int /*argc*/, char* /*argv*/[])
 
     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack init error");
+        OIC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
 
@@ -336,23 +336,23 @@ int main(int /*argc*/, char* /*argv*/[])
     timeout.tv_nsec = 100000000L;
 
     // Break from loop with Ctrl-C
-    OC_LOG(INFO, TAG, "Entering ocserver main loop...");
+    OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
     signal(SIGINT, handleSigInt);
     while (!gQuitFlag)
     {
         if (OCProcess() != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             return 0;
         }
         nanosleep(&timeout, NULL);
     }
 
-    OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
+    OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
 
     if (OCStop() != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack process error");
+        OIC_LOG(ERROR, TAG, "OCStack process error");
     }
 
     return 0;
@@ -362,7 +362,7 @@ int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState,
 {
     if (!uri)
     {
-        OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
+        OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
         return -1;
     }
 
@@ -375,7 +375,7 @@ int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState,
             OCEntityHandlerCb,
             NULL,
             OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
-    OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
+    OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
 
     return 0;
 }
diff --git a/resource/csdk/stack/samples/linux/secure/oic_amss_db.dat b/resource/csdk/stack/samples/linux/secure/oic_amss_db.dat
new file mode 100644 (file)
index 0000000..ff0932f
Binary files /dev/null and b/resource/csdk/stack/samples/linux/secure/oic_amss_db.dat differ
index 9543a87..4d958e9 100644 (file)
-{
-    "acl": [
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/res",
-                "/oic/d",
-                "/oic/p",
-                "/oic/res/types/d",
-                "/oic/ad",
-                "/oic/sec/acl",
-                "/oic/sec/amacl"
-                       ],
-                       "perms": 2,
-                       "ownrs" : ["MTExMTExMTExMTExMTExMQ=="]
-               },
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/sec/doxm",
-                "/oic/sec/pstat"
-             ],
-             "perms": 2,
-             "ownrs" : ["MTExMTExMTExMTExMTExMQ=="]
-        },
-        {
-            "sub": "MjIyMjIyMjIyMjIyMjIyMg==",
-            "rsrc": ["/oic/sec/acl",
-                      "/oic/sec/cred"],
-            "perms": 8,
-            "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-        },
-        {
-            "sub": "NDQ0NDMzMzMyMjIyMTExMQ==",
-            "rsrc": ["/a/led"],
-            "perms": 6,
-            "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-        }
-       ],
-       "pstat":        {
-               "isop": true,
-               "deviceid":     "ZGV2aWNlaWQAAAAAABhanw==",
-               "ch": 0,
-               "cm":   0,
-               "tm":   0,
-               "om":   3,
-               "sm":   [3]
-       },
-       "doxm": {
-               "oxm":  [0],
-               "oxmsel": 0,
-               "sct": 1,
-               "owned": true,
-               "deviceid":     "MTkxOTE5MTkxOTE5MTkxOQ==",
-               "ownr": "YWRtaW5EZXZpY2VVVUlEAA=="
-       },
-       "cred": [{
-               "credid": 1,
-               "sub": "MTExMTExMTExMTExMTExMQ==",
-               "credtyp": 1,
-               "pvdata": "QkJCQkJCQkJCQkJCQkJCQg==",
-        "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-       }]
-}
+{\r
+    "acl": {\r
+        "aclist": {\r
+            "aces": [\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/res",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/p",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/types/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/ad",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/acl",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/amacl",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/doxm",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        } ,\r
+                        {\r
+                            "href": "/oic/sec/pstat",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                }\r
+            ]\r
+        },\r
+        "rowneruuid" : "31393139-3139-3139-3139-313931393139"\r
+    },\r
+    "pstat": {\r
+        "isop": true,\r
+        "deviceuuid": "31393139-3139-3139-3139-313931393139",\r
+        "rowneruuid": "31393139-3139-3139-3139-313931393139",\r
+        "cm": 0,\r
+        "tm": 0,\r
+        "om": 3,\r
+        "sm": 3\r
+        },\r
+    "doxm": {\r
+        "oxms": [0],\r
+        "oxmsel": 0,\r
+        "sct": 1,\r
+        "owned": true,\r
+        "deviceuuid": "31393139-3139-3139-3139-313931393139",\r
+        "devowneruuid": "61646D69-6E44-6576-6963-655555494430",\r
+        "rowneruuid": "31393139-3139-3139-3139-313931393139",\r
+        "dpc": false\r
+    },\r
+    "cred": {\r
+        "creds": [\r
+            {\r
+                "credid": 1,\r
+                "subjectuuid": "31313131-3131-3131-3131-313131313131",\r
+                "credtype": 1,\r
+                "privatedata": {\r
+                    "data": "BBBBBBBBBBBBBBBB",\r
+                    "encoding": "oic.sec.encoding.raw"\r
+                }\r
+            }\r
+        ],\r
+        "rowneruuid": "32323232-3232-3232-3232-323232323232"\r
+    }\r
+}
\ No newline at end of file
diff --git a/resource/csdk/stack/samples/linux/secure/oic_svr_db_client.dat b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client.dat
new file mode 100644 (file)
index 0000000..7dbbb0a
Binary files /dev/null and b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client.dat differ
index ca8fed4..4b19514 100644 (file)
-{
-    "acl": [
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/res",
-                "/oic/d",
-                "/oic/p",
-                "/oic/res/types/d",
-                "/oic/ad",
-                "/oic/sec/acl",
-                "/oic/sec/amacl"
-                       ],
-                       "perms": 2,
-                       "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-               },
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/sec/doxm",
-                "/oic/sec/pstat"
-             ],
-             "perms": 2,
-             "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-        }
-       ],
-       "pstat":        {
-               "isop": true,
-               "deviceid":     "ZGV2aWNlaWQAAAAAABhanw==",
-               "ch": 0,
-               "cm":   0,
-               "tm":   0,
-               "om":   3,
-               "sm":   [3]
-       },
-       "doxm": {
-               "oxm":  [0],
-               "oxmsel": 0,
-               "sct": 1,
-               "owned": true,
-               "deviceid":     "MjIyMjIyMjIyMjIyMjIyMg==",
-               "ownr": "MjIyMjIyMjIyMjIyMjIyMg=="
-       },
-    "cred":    [{
-               "credid": 1,
-               "sub": "MTExMTExMTExMTExMTExMQ==",
-               "credtyp": 1,
-               "prd": "20150630T060000/20990920T220000",
-               "pvdata": "QUFBQUFBQUFBQUFBQUFBQQ==",
-        "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-       }]
-}
+{\r
+    "acl": {\r
+        "aclist": {\r
+            "aces": [\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/res",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/p",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/types/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/ad",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/acl",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/amacl",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/doxm",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        } ,\r
+                        {\r
+                            "href": "/oic/sec/pstat",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                }\r
+            ]\r
+        },\r
+        "rowneruuid" : "32323232-3232-3232-3232-323232323232"\r
+    },\r
+    "pstat": {\r
+        "isop": true,\r
+        "deviceuuid": "32323232-3232-3232-3232-323232323232",\r
+        "rowneruuid": "32323232-3232-3232-3232-323232323232",\r
+        "cm": 0,\r
+        "tm": 0,\r
+        "om": 3,\r
+        "sm": 3\r
+        },\r
+    "doxm": {\r
+        "oxms": [0],\r
+        "oxmsel": 0,\r
+        "sct": 1,\r
+        "owned": true,\r
+        "deviceuuid": "32323232-3232-3232-3232-323232323232",\r
+        "devowneruuid": "32323232-3232-3232-3232-323232323232",\r
+        "rowneruuid": "32323232-3232-3232-3232-323232323232",\r
+        "dpc": false\r
+    },\r
+    "cred": {\r
+        "creds": [\r
+            {\r
+                "credid": 1,\r
+                "subjectuuid": "31313131-3131-3131-3131-313131313131",\r
+                "credtype": 1,\r
+                "privatedata": {\r
+                    "data": "AAAAAAAAAAAAAAAA",\r
+                    "encoding": "oic.sec.encoding.raw"\r
+                }\r
+            }\r
+        ],\r
+        "rowneruuid": "32323232-3232-3232-3232-323232323232"\r
+    }\r
+}\r
diff --git a/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_directpairing.dat b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_directpairing.dat
new file mode 100644 (file)
index 0000000..43b7a1c
Binary files /dev/null and b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_directpairing.dat differ
diff --git a/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_directpairing.json b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_directpairing.json
new file mode 100644 (file)
index 0000000..588ac54
--- /dev/null
@@ -0,0 +1,100 @@
+{\r
+    "acl": {\r
+        "aclist": {\r
+            "aces": [\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/res",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/p",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/types/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/presence",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/doxm",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/pstat",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/acl",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/cred",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 6\r
+                }\r
+            ]\r
+        },\r
+        "rowneruuid" : "64697265-6374-7061-6972-696e67446576"\r
+    },\r
+    "pstat": {\r
+        "isop": false,\r
+        "deviceuuid": "64697265-6374-7061-6972-696e67446576",\r
+        "rowneruuid": "64697265-6374-7061-6972-696e67446576",\r
+        "cm": 2,\r
+        "tm": 0,\r
+        "om": 3,\r
+        "sm": 3\r
+        },\r
+    "doxm": {\r
+        "oxms": [0],\r
+        "oxmsel": 0,\r
+        "sct": 1,\r
+        "owned": false,\r
+        "deviceuuid": "64697265-6374-7061-6972-696e67446576",\r
+        "devowneruuid": "",\r
+        "rowneruuid": "64697265-6374-7061-6972-696e67446576",\r
+        "dpc": false\r
+    }\r
+}\r
diff --git a/resource/csdk/stack/samples/linux/secure/oic_svr_db_server.dat b/resource/csdk/stack/samples/linux/secure/oic_svr_db_server.dat
new file mode 100644 (file)
index 0000000..693c81d
Binary files /dev/null and b/resource/csdk/stack/samples/linux/secure/oic_svr_db_server.dat differ
index 9456b41..920c945 100644 (file)
-{
-    "acl": [
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/res",
-                "/oic/d",
-                "/oic/p",
-                "/oic/res/types/d",
-                "/oic/ad",
-                "/oic/sec/acl",
-                "/oic/sec/amacl"
-                       ],
-                       "perms": 2,
-                       "ownrs" : ["MTExMTExMTExMTExMTExMQ=="]
-               },
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/sec/doxm",
-                "/oic/sec/pstat"
-             ],
-             "perms": 2,
-             "ownrs" : ["MTExMTExMTExMTExMTExMQ=="]
-        },
-        {
-            "sub": "MjIyMjIyMjIyMjIyMjIyMg==",
-            "rsrc": ["/oic/sec/acl",
-                      "/oic/sec/cred"],
-            "perms": 8,
-            "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-        },
-        {
-            "sub": "MjIyMjIyMjIyMjIyMjIyMg==",
-            "rsrc": ["/a/led"],
-            "perms": 6,
-            "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-        },
-        {
-            "sub": "MTExMTIyMjIzMzMzNDQ0NA==",
-            "rsrc": ["/a/led"],
-            "perms": 6,
-            "prds" : ["20150630T060000/20150630T220000", "20150630T060000/20150630T200000"],
-            "recurs" : ["FREQ=DAILY; BYDAY=MO, WE, FR", "FREQ=DAILY; BYDAY=TU, TH; UNTIL=20160630"],
-            "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-        },
-        {
-            "sub": "Nzc3Nzc3Nzc3Nzc3Nzc3Nw==",
-            "rsrc": ["/a/led"],
-            "perms": 6,
-            "prds" : ["20150630T060000/20150630T220000"],
-            "recurs" : ["FREQ=DAILY; UNTIL=20150630"],
-            "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-        }
-       ],
-       "amacl": [{
-               "rsrc" : ["/a/led"],
-               "amss" : ["MTkxOTE5MTkxOTE5MTkxOQ=="],
-               "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-       }],
-       "pstat":        {
-               "isop": true,
-               "deviceid":     "ZGV2aWNlaWQAAAAAABhanw==",
-               "ch": 0,
-               "cm":   0,
-               "tm":   0,
-               "om":   3,
-               "sm":   [3]
-       },
-       "doxm": {
-               "oxm":  [0],
-               "oxmsel": 0,
-               "sct": 1,
-               "owned": true,
-               "deviceid":     "MTExMTExMTExMTExMTExMQ==",
-               "ownr": "YWRtaW5EZXZpY2VVVUlEAA=="
-       },
-    "cred":    [{
-               "credid": 1,
-               "sub": "MjIyMjIyMjIyMjIyMjIyMg==",
-               "credtyp": 1,
-               "pvdata": "QUFBQUFBQUFBQUFBQUFBQQ==",
-        "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-       },
-       {
-           "credid": 2,
-           "sub": "MTExMTIyMjIzMzMzNDQ0NA==",
-           "credtyp": 1,
-           "pvdata": "QUFBQUFBQUFBQUFBQUFBQQ==",
-        "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-       },
-       {
-           "credid": 3,
-           "sub": "Nzc3Nzc3Nzc3Nzc3Nzc3Nw==",
-           "credtyp": 1,
-           "pvdata": "QUFBQUFBQUFBQUFBQUFBQQ==",
-        "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-       },
-       {
-           "credid": 4,
-           "sub": "NDQ0NDMzMzMyMjIyMTExMQ==",
-           "credtyp": 1,
-           "pvdata": "QUFBQUFBQUFBQUFBQUFBQQ==",
-        "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-       },
-       {
-           "credid": 5,
-           "sub": "MTkxOTE5MTkxOTE5MTkxOQ==",
-           "credtyp": 1,
-           "pvdata": "QkJCQkJCQkJCQkJCQkJCQg==",
-        "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-       }]
-}
+{\r
+    "acl": {\r
+        "aclist": {\r
+            "aces": [\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/res",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/p",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/types/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/ad",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/acl",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/amacl",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/doxm",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        } ,\r
+                        {\r
+                            "href": "/oic/sec/pstat",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "32323232-3232-3232-3232-323232323232",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/acl",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        } ,\r
+                        {\r
+                            "href": "/oic/sec/cred",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 8\r
+                },\r
+                {\r
+                    "subjectuuid": "31313131-3232-3232-3333-333334343434",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/a/led",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 6,\r
+                    "period" : ["20150630T060000/20150630T220000", "20150630T060000/20150630T200000"],\r
+                    "recurrence" : ["FREQ=DAILY; BYDAY=MO, WE, FR", "FREQ=DAILY; BYDAY=TU, TH; UNTIL=20160630"]\r
+                },\r
+                {\r
+                    "subjectuuid": "37373737-3737-3737-3737-373737373737",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/a/led",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 6,\r
+                    "period" : ["20150630T060000/20150630T220000"],\r
+                    "recurrence" : ["FREQ=DAILY; UNTIL=20150630"]\r
+                }\r
+            ]\r
+        },\r
+        "rowneruuid" : "31313131-3131-3131-3131-313131313131"\r
+    },\r
+    "pstat": {\r
+        "isop": true,\r
+        "deviceuuid": "31313131-3131-3131-3131-313131313131",\r
+        "rowneruuid": "31313131-3131-3131-3131-313131313131",\r
+        "cm": 0,\r
+        "tm": 0,\r
+        "om": 3,\r
+        "sm": 3\r
+        },\r
+    "doxm": {\r
+        "oxms": [0],\r
+        "oxmsel": 0,\r
+        "sct": 1,\r
+        "owned": true,\r
+        "deviceuuid": "31313131-3131-3131-3131-313131313131",\r
+        "devowneruuid": "32323232-3232-3232-3232-323232323232",\r
+        "rowneruuid": "31313131-3131-3131-3131-313131313131",\r
+        "dpc": false\r
+    },\r
+    "cred": {\r
+        "creds": [\r
+            {\r
+                "credid": 1,\r
+                "subjectuuid": "32323232-3232-3232-3232-323232323232",\r
+                "credtype": 1,\r
+                "period": "20150630T060000/20990920T220000",\r
+                "privatedata": {\r
+                    "data": "AAAAAAAAAAAAAAAA",\r
+                    "encoding": "oic.sec.encoding.raw"\r
+                }\r
+            },\r
+            {\r
+                "credid": 2,\r
+                "subjectuuid": "31393139-3139-3139-3139-313931393139",\r
+                "credtype": 1,\r
+                "period": "20150630T060000/20990920T220000",\r
+                "privatedata": {\r
+                    "data": "BBBBBBBBBBBBBBBB",\r
+                    "encoding": "oic.sec.encoding.raw"\r
+                }\r
+            }\r
+        ],\r
+        "rowneruuid": "32323232-3232-3232-3232-323232323232"\r
+    }\r
+}\r
diff --git a/resource/csdk/stack/samples/linux/secure/oic_svr_db_server_justworks.dat b/resource/csdk/stack/samples/linux/secure/oic_svr_db_server_justworks.dat
new file mode 100644 (file)
index 0000000..605683a
Binary files /dev/null and b/resource/csdk/stack/samples/linux/secure/oic_svr_db_server_justworks.dat differ
diff --git a/resource/csdk/stack/samples/tizen/README.txt b/resource/csdk/stack/samples/tizen/README.txt
new file mode 100644 (file)
index 0000000..33cae04
--- /dev/null
@@ -0,0 +1,52 @@
+Prerequisites
+=============
+
+1) Clone tinycbor library using following command from the path "iotivity/extlibs/tinycbor":
+   git clone https://github.com/01org/tinycbor.git extlibs/tinycbor/tinycbor
+2) To build with SECURITY=1, download sqlite3 zip file and extract it. Copy the files 
+   sqlite3.c and sqlite3.h file to iotivity/extlibs/sqlite3/ folder.
+   Download using http://www.sqlite.org/2015/sqlite-amalgamation-3081101.zip
+
+Build Procedure
+===============
+
+1) If you are building first time, then delete GBS-ROOT-RI folder from home directory.
+   Note: Default build server URL for Tizen is set in gbs configuration file @ iotivity/tools/tizen/.gbs.conf.
+         If needed, same can be modified as per appropriate target.
+2) Go to "iotivity/" folder.
+3) Execute following command(s) to start build based on transport selection required :
+    -> Building for all transports :
+    $ scons -f resource/csdk/stack/samples/tizen/build/SConscript TARGET_OS=tizen TARGET_TRANSPORT=ALL
+
+    -> Building for a specific transport :
+    $ scons -f resource/csdk/connectivity/build/tizen/SConscript TARGET_OS=tizen TARGET_TRANSPORT=IP
+
+    -> Building for multiple transports :
+    $ scons -f resource/csdk/connectivity/build/tizen/SConscript TARGET_OS=tizen TARGET_TRANSPORT=IP,BT,BLE
+
+4) By default, above command will build csdk samples also.
+
+Note :- Upon successful execution of above command(s) RI library and sample applications will be
+        generated at path "~/GBS-ROOT-RI/local/repos/<target>/armv7l/RPMS".
+
+Procedure to Execute Sample App:
+================================
+    1) Copy the generated rpms(com-oic-ri-0.1-1.armv7l.rpm, com-oic-ri-sample-0.1-1.armv7l.rpm) to Tizen Device
+       (say /opt/usr/media/xxx/)
+    2) sdb shell
+    3) su
+    4) cd /opt/usr/media/xxx/
+    5) change-booting-mode.sh --update
+
+    6) Install the rpms using the following commands:
+               a) rpm -Uvh com-oic-ri-0.1-1.armv7l.rpm --force --nodeps
+               b) rpm -Uvh com-oic-ri-sample-0.1-1.armv7l.rpm --force --nodeps
+       7) For IP transport, apply net-config smack rules using below command:
+               a) chsmack -a "net-config" /usr/apps/com.oic.ri.sample/bin/*
+               b) chsmack -e "net-config" /usr/apps/com.oic.ri.sample/bin/*
+    7) RPM will be installed in "/usr/apps/"
+       Execute the sample app by below commands
+        i) cd /usr/apps/com.oic.ri.sample/bin
+                       a) ./ocserver -o0 [For Server sample]
+                       b) ./occlient -t2 [For client sample]
+                       c) ./ocrouting [For Gateway sample]
\ No newline at end of file
index d690cd4..a128a73 100644 (file)
@@ -232,7 +232,7 @@ OCStackApplicationResult deleteReqCB(void *ctx,
     if(clientResponse)
     {
         cout << "\nStackResult: " << getResult(clientResponse->result);
-        //OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        //OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
     }
     else
     {
@@ -257,7 +257,7 @@ OCStackApplicationResult getReqCB(void* ctx, OCDoHandle /*handle*/,
 
     cout << "\nStackResult: " << getResult(clientResponse->result);
     cout << "\nSEQUENCE NUMBER: " << clientResponse->sequenceNumber;
-    //OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
+    //OIC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
 
     if (clientResponse->numRcvdVendorSpecificHeaderOptions > 0)
     {
@@ -288,7 +288,7 @@ OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle /*handle*/,
         cout << "\nStackResult: " << getResult(clientResponse->result);
         cout << "\nSEQUENCE NUMBER: " << clientResponse->sequenceNumber;
         cout << "\nCallback Context for OBSERVE notification recvd successfully ";
-        //OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        //OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
         gNumObserveNotifies++;
         if (gNumObserveNotifies == 15) //large number to test observing in DELETE case.
         {
@@ -343,7 +343,7 @@ OCStackApplicationResult presenceCB(void* ctx, OCDoHandle /*handle*/,
         cout << "\nStackResult: " << getResult(clientResponse->result);
         cout << "\nNONCE NUMBER: " << clientResponse->sequenceNumber;
         cout << "\nCallback Context for Presence notification recvd successfully ";
-        //OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        //OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
         gNumPresenceNotifies++;
         if (gNumPresenceNotifies == 20)
         {
@@ -389,7 +389,7 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
         {
             cout << ":" << clientResponse->devAddr.port;
         }
-        //OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        //OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
         cout << "\nConnectivity type: " << clientResponse->connType;
         g_connType = clientResponse->connType;
         g_serverAddr = clientResponse->devAddr;
@@ -471,8 +471,8 @@ OCStackApplicationResult PlatformDiscoveryReqCB(void* ctx,
 
     if (clientResponse)
     {
-        //OC_LOG truncates the response as it is too long.
-        //OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+        //OIC_LOG truncates the response as it is too long.
+        //OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
     }
     else
     {
@@ -492,7 +492,7 @@ OCStackApplicationResult DeviceDiscoveryReqCB(void* ctx, OCDoHandle /*handle*/,
 
     if (clientResponse)
     {
-        //OC_LOG truncates the response as it is too long.
+        //OIC_LOG truncates the response as it is too long.
         cout << "\nDiscovery response: ";
         cout << clientResponse->payload;
     }
@@ -829,7 +829,7 @@ int main(int argc, char* argv[])
     {
         if (OCProcess() != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             return 0;
         }
         usleep(SLEEP_DURATION);
@@ -886,7 +886,7 @@ int main(int argc, char* argv[])
     }
 
     // Break from loop with Ctrl+C
-    OC_LOG(INFO, TAG, "Entering occlient main loop...");
+    OIC_LOG(INFO, TAG, "Entering occlient main loop...");
     signal(SIGINT, handleSigInt);
     while (!gQuitFlag)
     {
index 944adc2..faf5108 100644 (file)
@@ -712,7 +712,7 @@ void *ChangeLightRepresentation (void *param)
 #ifdef WITH_PRESENCE
 void *presenceNotificationGenerator(void *param)
 {
-    sleep(10);
+    sleep(20);
     (void)param;
     OCDoHandle presenceNotificationHandles[numPresenceResources];
     OCStackResult res = OC_STACK_OK;
@@ -728,7 +728,7 @@ void *presenceNotificationGenerator(void *param)
     {
         if(res == OC_STACK_OK)
         {
-            sleep(1);
+            sleep(2);
             res = OCCreateResource(&presenceNotificationHandles[i],
                     presenceNotificationResources.at(i).c_str(),
                     OC_RSRVD_INTERFACE_DEFAULT,
@@ -992,6 +992,8 @@ int main(int argc, char* argv[])
         exit (EXIT_FAILURE);
     }
 
+    OCResourcePayloadAddStringLL(&deviceInfo.types, "oic.d.tv");
+
     registrationResult = OCSetDeviceInfo(deviceInfo);
 
     if (registrationResult != OC_STACK_OK)
index 4214057..180c63d 100644 (file)
@@ -36,18 +36,27 @@ sourcedir=`pwd`
 
 echo `pwd`
 
+rm -rf ./tmp
 mkdir ./tmp
 mkdir ./tmp/extlibs/
 mkdir ./tmp/packaging
-cp -R ./extlibs/tinycbor $sourcedir/tmp/extlibs
+cp -LR ./extlibs/tinycbor $sourcedir/tmp/extlibs
+rm -rf $sourcedir/tmp/extlibs/tinycbor/tinycbor/.git
 cp -R ./extlibs/cjson $sourcedir/tmp/extlibs
 cp -R ./extlibs/tinydtls $sourcedir/tmp/extlibs
 cp -R ./extlibs/timer $sourcedir/tmp/extlibs
 cp -R ./extlibs/rapidxml $sourcedir/tmp/extlibs
+cp -LR ./extlibs/sqlite3 $sourcedir/tmp/extlibs
 cp -R ./resource/csdk/stack/samples/tizen/build/packaging/*.spec $sourcedir/tmp/packaging
 cp -R ./resource $sourcedir/tmp/
 cp -R ./build_common/external_libs.scons $sourcedir/tmp/
 
+# copy dependency RPMs and conf files for tizen build
+cp ./tools/tizen/*.rpm $sourcedir/tmp
+cp ./tools/tizen/*.rpm $sourcedir/tmp/resource/csdk/stack/samples/tizen/SimpleClientServer
+cp ./tools/tizen/.gbs.conf ./tmp
+cp ./tools/tizen/.gbs.conf ./tmp/resource/csdk/stack/samples/tizen/SimpleClientServer
+
 cd $sourcedir
 cd ./resource/csdk/stack/samples/tizen/build/
 
@@ -78,15 +87,15 @@ if [ ! -d .git ]; then
 fi
 
 echo "Calling core gbs build command"
-gbscommand="gbs build -A armv7l -B ~/GBS-ROOT-RI --include-all --define 'TARGET_TRANSPORT $1' --define 'SECURED $2' --define 'RELEASE $4' --define 'LOGGING $5' --define 'ROUTING $6' --repository ./"
+gbscommand="gbs build -A armv7l -B ~/GBS-ROOT-RI-OIC --include-all --repository ./ --define 'TARGET_TRANSPORT $1' --define 'SECURED $2' --define 'RELEASE $4' --define 'LOGGING $5' --define 'ROUTING $6'"
 echo $gbscommand
 if eval $gbscommand; then
    echo "Core build is successful"
 else
-   echo "Core build failed. Try 'sudo find . -type f -exec dos2unix {} \;' in the 'connectivity/' folder"
+   echo "Core build failed. Try 'find . -type f -exec dos2unix {} \;' in the 'connectivity/' folder"
    cd $sourcedir
    rm -rf $sourcedir/tmp
-   exit
+   exit 1
 fi
 
 if echo $BUILD_SAMPLE|grep -qi '^ON$'; then
@@ -101,18 +110,19 @@ if echo $BUILD_SAMPLE|grep -qi '^ON$'; then
       git commit -m "Initial commit"
    fi
    echo "Calling sample gbs build command"
-   gbscommand="gbs build -A armv7l -B ~/GBS-ROOT-RI --include-all --define 'TARGET_TRANSPORT $1' --define 'SECURED $2' --define 'RELEASE $4' --define 'LOGGING $5' --define 'ROUTING $6' --repository ./"
+   gbscommand="gbs build -A armv7l -B ~/GBS-ROOT-RI-OIC --include-all --repository ./ --define 'TARGET_TRANSPORT $1' --define 'SECURED $2' --define 'RELEASE $4' --define 'LOGGING $5' --define 'ROUTING $6'"
    echo $gbscommand
    if eval $gbscommand; then
       echo "Sample build is successful"
    else
-      echo "Sample build is failed. Try 'sudo find . -type f -exec dos2unix {} \;' in the 'connectivity/' folder"
+      echo "Sample build is failed. Try 'find . -type f -exec dos2unix {} \;' in the 'connectivity/' folder"
+      exit 1
    fi
 else
        echo "Sample build is not enabled"
 fi
 
-
 cd $sourcedir
 rm -rf $sourcedir/tmp
 
+exit 0
index 5919540..7e559c1 100644 (file)
@@ -16,6 +16,7 @@ BuildRequires: pkgconfig(glib-2.0)
 BuildRequires: pkgconfig(capi-network-wifi)
 BuildRequires: pkgconfig(capi-network-bluetooth)
 BuildRequires: pkgconfig(uuid)
+BuildRequires: pkgconfig(sqlite3)
 BuildRequires: boost-devel
 BuildRequires: boost-thread
 BuildRequires: boost-system
@@ -48,13 +49,14 @@ cp -f %{ROOTDIR}/resource/csdk/connectivity/src/libconnectivity_abstraction.so %
 cp -f %{ROOTDIR}/resource/csdk/connectivity/lib/libcoap-4.1.1/libcoap.a %{buildroot}/%{_libdir}
 cp /usr/lib/libuuid.so.1 %{buildroot}%{_libdir}
 if echo %{SECURED}|grep -qi '1'; then
-       cp -f %{ROOTDIR}/con/extlibs/tinydtls/libtinydtls.a %{buildroot}/%{_libdir}
+       cp -f %{ROOTDIR}/extlibs/tinydtls/libtinydtls.a %{buildroot}/%{_libdir}
 fi
 
 cp -rf %{ROOTDIR}/resource/csdk/stack/include/ocstack.h* %{DEST_INC_DIR}/
 cp -rf %{ROOTDIR}/resource/csdk/stack/include/ocstackconfig.h* %{DEST_INC_DIR}/
 cp -rf %{ROOTDIR}/resource/csdk/stack/include/octypes.h* %{DEST_INC_DIR}/
 cp -rf %{ROOTDIR}/resource/csdk/logger/include/logger.h* %{DEST_INC_DIR}/
+cp -rf %{ROOTDIR}/resource/csdk/logger/include/logger_types.h* %{DEST_INC_DIR}/
 cp resource/oc_logger/include/oc_logger.hpp %{DEST_INC_DIR}/
 cp resource/oc_logger/include/oc_log_stream.hpp %{DEST_INC_DIR}/
 cp resource/oc_logger/include/oc_logger.h %{DEST_INC_DIR}/
index 4329c39..9b3c19d 100644 (file)
@@ -36,7 +36,7 @@
 #include "cainterface.h"
 
 /// Module Name
-#define TAG "occlientcb"
+#define TAG "OIC_RI_CLIENTCB"
 
 struct ClientCB *cbList = NULL;
 static OCMulticastNode * mcPresenceNodes = NULL;
@@ -48,7 +48,7 @@ AddClientCB (ClientCB** clientCB, OCCallbackData* cbData,
              OCDevAddr *devAddr, char * requestUri,
              char * resourceTypeName, uint32_t ttl)
 {
-    if(!clientCB || !cbData || !handle || !requestUri || tokenLength > CA_MAX_TOKEN_LEN)
+    if (!clientCB || !cbData || !handle || !requestUri || tokenLength > CA_MAX_TOKEN_LEN)
     {
         return OC_STACK_INVALID_PARAM;
     }
@@ -56,24 +56,24 @@ AddClientCB (ClientCB** clientCB, OCCallbackData* cbData,
     ClientCB *cbNode = NULL;
 
 #ifdef WITH_PRESENCE
-    if(method == OC_REST_PRESENCE)
+    if (method == OC_REST_PRESENCE)
     {   // Retrieve the presence callback structure for this specific requestUri.
         cbNode = GetClientCB(NULL, 0, NULL, requestUri);
     }
-#endif // WITH_PRESENCE
 
-    if(!cbNode)// If it does not already exist, create new node.
+    if (!cbNode)// If it does not already exist, create new node.
+#endif // WITH_PRESENCE
     {
         cbNode = (ClientCB*) OICMalloc(sizeof(ClientCB));
-        if(!cbNode)
+        if (!cbNode)
         {
             *clientCB = NULL;
             goto exit;
         }
         else
         {
-            OC_LOG(INFO, TAG, "Adding client callback with token");
-            OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
+            OIC_LOG(INFO, TAG, "Adding client callback with token");
+            OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
             cbNode->callBack = cbData->cb;
             cbNode->context = cbData->context;
             cbNode->deleteCallback = cbData->cd;
@@ -84,10 +84,10 @@ AddClientCB (ClientCB** clientCB, OCCallbackData* cbData,
             cbNode->handle = *handle;
             cbNode->method = method;
             cbNode->sequenceNumber = 0;
-            #ifdef WITH_PRESENCE
+#ifdef WITH_PRESENCE
             cbNode->presence = NULL;
             cbNode->filterResourceType = NULL;
-            #endif // WITH_PRESENCE
+#endif // WITH_PRESENCE
 
             if (method == OC_REST_PRESENCE ||
                 method == OC_REST_OBSERVE  ||
@@ -101,11 +101,12 @@ AddClientCB (ClientCB** clientCB, OCCallbackData* cbData,
             }
             cbNode->requestUri = requestUri;    // I own it now
             cbNode->devAddr = devAddr;          // I own it now
-            OC_LOG_V(INFO, TAG, "Added Callback for uri : %s", requestUri);
+            OIC_LOG_V(INFO, TAG, "Added Callback for uri : %s", requestUri);
             LL_APPEND(cbList, cbNode);
             *clientCB = cbNode;
         }
     }
+#ifdef WITH_PRESENCE
     else
     {
         // Ensure that the handle the SDK hands back up to the application layer for the
@@ -124,8 +125,7 @@ AddClientCB (ClientCB** clientCB, OCCallbackData* cbData,
         *handle = cbNode->handle;
     }
 
-#ifdef WITH_PRESENCE
-    if(method == OC_REST_PRESENCE && resourceTypeName)
+    if (method == OC_REST_PRESENCE && resourceTypeName)
     {
         // Amend the found or created node by adding a new resourceType to it.
         return InsertResourceTypeFilter(cbNode,(char *)resourceTypeName);
@@ -142,33 +142,33 @@ AddClientCB (ClientCB** clientCB, OCCallbackData* cbData,
     return OC_STACK_OK;
 
 exit:
-     return OC_STACK_NO_MEMORY;
+    return OC_STACK_NO_MEMORY;
 }
 
 void DeleteClientCB(ClientCB * cbNode)
 {
-    if(cbNode)
+    if (cbNode)
     {
         LL_DELETE(cbList, cbNode);
-        OC_LOG (INFO, TAG, "Deleting token");
-        OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)cbNode->token, cbNode->tokenLength);
+        OIC_LOG (INFO, TAG, "Deleting token");
+        OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)cbNode->token, cbNode->tokenLength);
         CADestroyToken (cbNode->token);
         OICFree(cbNode->devAddr);
         OICFree(cbNode->handle);
-        OC_LOG_V (INFO, TAG, "Deleting callback with uri %s", cbNode->requestUri);
+        OIC_LOG_V (INFO, TAG, "Deleting callback with uri %s", cbNode->requestUri);
         OICFree(cbNode->requestUri);
-        if(cbNode->deleteCallback)
+        if (cbNode->deleteCallback)
         {
             cbNode->deleteCallback(cbNode->context);
         }
 
 #ifdef WITH_PRESENCE
-        if(cbNode->presence)
+        if (cbNode->presence)
         {
             OICFree(cbNode->presence->timeOut);
             OICFree(cbNode->presence);
         }
-        if(cbNode->method == OC_REST_PRESENCE)
+        if (cbNode->method == OC_REST_PRESENCE)
         {
             OCResourceType * pointer = cbNode->filterResourceType;
             OCResourceType * next = NULL;
@@ -208,7 +208,7 @@ static void CheckAndDeleteTimedOutCB(ClientCB* cbNode)
 
     if (cbNode->TTL < now)
     {
-        OC_LOG(INFO, TAG, "Deleting timed-out callback");
+        OIC_LOG(INFO, TAG, "Deleting timed-out callback");
         DeleteClientCB(cbNode);
     }
 }
@@ -216,50 +216,49 @@ static void CheckAndDeleteTimedOutCB(ClientCB* cbNode)
 ClientCB* GetClientCB(const CAToken_t token, uint8_t tokenLength,
         OCDoHandle handle, const char * requestUri)
 {
-
     ClientCB* out = NULL;
 
-    if(token && *token && tokenLength <= CA_MAX_TOKEN_LEN && tokenLength > 0)
+    if (token && *token && tokenLength <= CA_MAX_TOKEN_LEN && tokenLength > 0)
     {
-        OC_LOG (INFO, TAG,  "Looking for token");
-        OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
-        OC_LOG(INFO, TAG, "\tFound in callback list");
+        OIC_LOG (INFO, TAG,  "Looking for token");
+        OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
+        OIC_LOG(INFO, TAG, "\tFound in callback list");
         LL_FOREACH(cbList, out)
         {
-            OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)out->token, tokenLength);
+            OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)out->token, tokenLength);
 
-            if(memcmp(out->token, token, tokenLength) == 0)
+            if (memcmp(out->token, token, tokenLength) == 0)
             {
                 return out;
             }
             CheckAndDeleteTimedOutCB(out);
         }
     }
-    else if(handle)
+    else if (handle)
     {
         LL_FOREACH(cbList, out)
         {
-            if(out->handle == handle)
+            if (out->handle == handle)
             {
                 return out;
             }
             CheckAndDeleteTimedOutCB(out);
         }
     }
-    else if(requestUri)
+    else if (requestUri)
     {
-        OC_LOG_V(INFO, TAG, "Looking for uri %s", requestUri);
+        OIC_LOG_V(INFO, TAG, "Looking for uri %s", requestUri);
         LL_FOREACH(cbList, out)
         {
-            OC_LOG_V(INFO, TAG, "\tFound %s", out->requestUri);
-            if(out->requestUri && strcmp(out->requestUri, requestUri ) == 0)
+            OIC_LOG_V(INFO, TAG, "\tFound %s", out->requestUri);
+            if (out->requestUri && strcmp(out->requestUri, requestUri ) == 0)
             {
                 return out;
             }
             CheckAndDeleteTimedOutCB(out);
         }
     }
-    OC_LOG(INFO, TAG, "Callback Not found !!");
+    OIC_LOG(INFO, TAG, "Callback Not found !!");
     return NULL;
 }
 
@@ -267,11 +266,11 @@ ClientCB* GetClientCB(const CAToken_t token, uint8_t tokenLength,
 OCStackResult InsertResourceTypeFilter(ClientCB * cbNode, char * resourceTypeName)
 {
     OCResourceType * newResourceType = NULL;
-    if(cbNode && resourceTypeName)
+    if (cbNode && resourceTypeName)
     {
         // Form a new resourceType member.
         newResourceType = (OCResourceType *) OICMalloc(sizeof(OCResourceType));
-        if(!newResourceType)
+        if (!newResourceType)
         {
             return OC_STACK_NO_MEMORY;
         }
@@ -300,7 +299,7 @@ void DeleteClientCBList()
 void FindAndDeleteClientCB(ClientCB * cbNode)
 {
     ClientCB* tmp;
-    if(cbNode)
+    if (cbNode)
     {
         LL_FOREACH(cbList, tmp)
         {
@@ -315,15 +314,12 @@ void FindAndDeleteClientCB(ClientCB * cbNode)
 
 OCStackResult AddMCPresenceNode(OCMulticastNode** outnode, char* uri, uint32_t nonce)
 {
-    if(!outnode)
+    if (!outnode)
     {
         return OC_STACK_INVALID_PARAM;
     }
 
-    OCMulticastNode *node;
-
-    node = (OCMulticastNode*) OICMalloc(sizeof(OCMulticastNode));
-
+    OCMulticastNode *node = (OCMulticastNode*) OICMalloc(sizeof(*node));
     if (node)
     {
         node->nonce = nonce;
@@ -338,19 +334,17 @@ OCStackResult AddMCPresenceNode(OCMulticastNode** outnode, char* uri, uint32_t n
 
 OCMulticastNode* GetMCPresenceNode(const char * uri)
 {
-    OCMulticastNode* out = NULL;
-
-    if(uri)
+    if (uri)
     {
+        OCMulticastNode* out = NULL;
         LL_FOREACH(mcPresenceNodes, out)
         {
-            if(out->uri && strcmp(out->uri, uri) == 0)
+            if (out->uri && strcmp(out->uri, uri) == 0)
             {
                 return out;
             }
         }
     }
-    OC_LOG(INFO, TAG, "MulticastNode Not found !!");
+    OIC_LOG(INFO, TAG, "MulticastNode Not found !!");
     return NULL;
 }
-
old mode 100644 (file)
new mode 100755 (executable)
index 5684f6a..551cdd4
 
 #include "oicgroup.h"
 
-#define TAG "occollection"
+#define TAG "OIC_RI_COLLECTION"
 
 #define NUM_PARAM_IN_QUERY   2 // The expected number of parameters in a query
 #define NUM_FIELDS_IN_QUERY  2 // The expected number of fields in a query
 
 static OCStackResult CheckRTParamSupport(const OCResource* resource, const char* rtPtr)
 {
-    if(!resource || !rtPtr)
+    if (!resource || !rtPtr)
     {
         return OC_STACK_INVALID_PARAM;
     }
@@ -59,7 +59,7 @@ static OCStackResult CheckRTParamSupport(const OCResource* resource, const char*
     OCResourceType* rTPointer = resource->rsrcType;
     while (rTPointer)
     {
-        if( strcmp (rTPointer->resourcetypename, rtPtr) == 0)
+        if (strcmp(rTPointer->resourcetypename, rtPtr) == 0)
         {
             return OC_STACK_OK;
         }
@@ -71,7 +71,7 @@ static OCStackResult CheckRTParamSupport(const OCResource* resource, const char*
 
 static OCStackResult CheckIFParamSupport(const OCResource* resource, const char* ifPtr)
 {
-    if(!resource || !ifPtr)
+    if (!resource || !ifPtr)
     {
         return OC_STACK_INVALID_PARAM;
     }
@@ -79,7 +79,7 @@ static OCStackResult CheckIFParamSupport(const OCResource* resource, const char*
     OCResourceInterface* iFPointer = resource->rsrcInterface;
     while (iFPointer)
     {
-        if( strcmp (iFPointer->name, ifPtr) == 0)
+        if (strcmp(iFPointer->name, ifPtr) == 0)
         {
             return OC_STACK_OK;
         }
@@ -91,7 +91,7 @@ static OCStackResult CheckIFParamSupport(const OCResource* resource, const char*
 
 static OCStackResult
 ValidateQuery (const char *query, OCResourceHandle resource,
-                             OCStackIfTypes *ifParam, char **rtParam)
+               OCStackIfTypes *ifParam, char **rtParam)
 {
     uint8_t numFields = 0;
     uint8_t numParam;
@@ -99,14 +99,14 @@ ValidateQuery (const char *query, OCResourceHandle resource,
     //TODO: Query and URL validation is being done for virtual resource case
     // using ValidateUrlQuery function. We should be able to merge it with this
     // function.
-    OC_LOG(INFO, TAG, "Entering ValidateQuery");
+    OIC_LOG(INFO, TAG, "Entering ValidateQuery");
 
     if (!query)
     {
         return OC_STACK_ERROR;
     }
 
-    if(!ifParam || !rtParam)
+    if (!ifParam || !rtParam)
     {
         return OC_STACK_INVALID_PARAM;
     }
@@ -114,7 +114,7 @@ ValidateQuery (const char *query, OCResourceHandle resource,
     if (!(*query))
     {
         // Query string is empty
-        OC_LOG(INFO, TAG, "Empty query string, use default IF and RT");
+        OIC_LOG(INFO, TAG, "Empty query string, use default IF and RT");
         *ifParam = STACK_IF_DEFAULT;
         *rtParam = (char *) OCGetResourceTypeName (resource, 0);
         return OC_STACK_OK;
@@ -172,7 +172,7 @@ ValidateQuery (const char *query, OCResourceHandle resource,
 
     if (ifPtr)
     {
-        if(CheckIFParamSupport((OCResource *)resource, ifPtr) != OC_STACK_OK)
+        if (CheckIFParamSupport((OCResource *)resource, ifPtr) != OC_STACK_OK)
         {
             return OC_STACK_INVALID_QUERY;
         }
@@ -188,7 +188,7 @@ ValidateQuery (const char *query, OCResourceHandle resource,
         {
             *ifParam = STACK_IF_BATCH;
         }
-        else if(strcmp (ifPtr, OC_RSRVD_INTERFACE_GROUP) == 0)
+        else if (strcmp (ifPtr, OC_RSRVD_INTERFACE_GROUP) == 0)
         {
             *ifParam = STACK_IF_GROUP;
         }
@@ -219,7 +219,7 @@ ValidateQuery (const char *query, OCResourceHandle resource,
         // RT not specified in query. Use the first resource type for the resource as default.
         *rtParam = (char *) OCGetResourceTypeName (resource, 0);
     }
-    OC_LOG_V(INFO, TAG, "Query params: IF = %d, RT = %s", *ifParam, *rtParam);
+    OIC_LOG_V(INFO, TAG, "Query params: IF = %d, RT = %s", *ifParam, *rtParam);
 
     return OC_STACK_OK;
 }
@@ -231,36 +231,39 @@ HandleLinkedListInterface(OCEntityHandlerRequest *ehRequest,
 {
     (void)filterOn;
     (void)filterValue;
-    if(!ehRequest)
+    if (!ehRequest)
     {
         return OC_STACK_INVALID_PARAM;
     }
 
-    OCStackResult ret = OC_STACK_OK;
     OCResource *collResource = (OCResource *)ehRequest->resource;
-
+    OCChildResource *tempChildResource = NULL;
     OCRepPayload* payload = NULL;
 
-    if(ret == OC_STACK_OK)
+    if(!collResource)
     {
-        ret = BuildResponseRepresentation(collResource, &payload);
+        return OC_STACK_INVALID_PARAM;
     }
 
+    OCStackResult ret = BuildResponseRepresentation(collResource, &payload);
     if (ret == OC_STACK_OK)
     {
-        for  (int i = 0; i < MAX_CONTAINED_RESOURCES && ret == OC_STACK_OK; i++)
+        tempChildResource = collResource->rsrcChildResourcesHead;
+        while (tempChildResource && ret == OC_STACK_OK)
         {
-            OCResource* temp = collResource->rsrcResources[i];
+            OCResource* temp = tempChildResource->rsrcResource;
             if (temp)
             {
                 //TODO : Add resource type filtering once collections
                 // start supporting queries.
                 ret = BuildResponseRepresentation(temp, &payload);
             }
+
+            tempChildResource = tempChildResource->next;
         }
     }
 
-    if(ret == OC_STACK_OK)
+    if (ret == OC_STACK_OK)
     {
         OCEntityHandlerResponse response = {0};
         response.ehResult = OC_EH_OK;
@@ -270,6 +273,7 @@ HandleLinkedListInterface(OCEntityHandlerRequest *ehRequest,
         response.resourceHandle = (OCResourceHandle) collResource;
         ret = OCDoResponse(&response);
     }
+
     OCRepPayloadDestroy(payload);
     return ret;
 }
@@ -282,60 +286,56 @@ HandleBatchInterface(OCEntityHandlerRequest *ehRequest)
         return OC_STACK_INVALID_PARAM;
     }
 
-    OCStackResult stackRet = OC_STACK_OK;
-    OCEntityHandlerResult ehResult = OC_EH_ERROR;
     OCResource * collResource = (OCResource *) ehRequest->resource;
+    OCChildResource *tempChildResource = NULL;
 
     OCRepPayload* payload = OCRepPayloadCreate();
-    if(!payload)
+    if (!payload)
     {
-        stackRet = OC_STACK_NO_MEMORY;
+        return OC_STACK_NO_MEMORY;
     }
 
-    if(stackRet == OC_STACK_OK)
+    if (collResource)
     {
-        if (collResource)
-        {
-            OCRepPayloadSetUri(payload, collResource->uri);
-        }
+        OCRepPayloadSetUri(payload, collResource->uri);
     }
 
-    if(stackRet == OC_STACK_OK)
-    {
-        OCEntityHandlerResponse response = {0};
-        response.ehResult = OC_EH_OK;
-        response.payload = (OCPayload*)payload;
-        response.persistentBufferFlag = 0;
-        response.requestHandle = (OCRequestHandle) ehRequest->requestHandle;
-        response.resourceHandle = (OCResourceHandle) collResource;
-        stackRet = OCDoResponse(&response);
-    }
+    OCEntityHandlerResponse response = {0};
+    response.ehResult = OC_EH_OK;
+    response.payload = (OCPayload*)payload;
+    response.persistentBufferFlag = 0;
+    response.requestHandle = (OCRequestHandle) ehRequest->requestHandle;
+    response.resourceHandle = (OCResourceHandle) collResource;
+    OCStackResult stackRet = OCDoResponse(&response);
 
     if (stackRet == OC_STACK_OK)
     {
-        for  (uint8_t i = 0; i < MAX_CONTAINED_RESOURCES; i++)
+        tempChildResource = collResource->rsrcChildResourcesHead;
+
+        while(tempChildResource)
         {
-            OCResource* temp = collResource->rsrcResources[i];
-            if (temp)
+            OCResource* tempRsrcResource = tempChildResource->rsrcResource;
+
+            if (tempRsrcResource)
             {
                 // Note that all entity handlers called through a collection
                 // will get the same pointer to ehRequest, the only difference
                 // is ehRequest->resource
-                ehRequest->resource = (OCResourceHandle) temp;
+                ehRequest->resource = (OCResourceHandle) tempRsrcResource;
 
-                ehResult = temp->entityHandler(OC_REQUEST_FLAG, ehRequest,
-                                        temp->entityHandlerCallbackParam);
+                OCEntityHandlerResult ehResult = tempRsrcResource->entityHandler(OC_REQUEST_FLAG, ehRequest,
+                                                        tempRsrcResource->entityHandlerCallbackParam);
 
                 // The default collection handler is returning as OK
-                if(stackRet != OC_STACK_SLOW_RESOURCE)
+                if (stackRet != OC_STACK_SLOW_RESOURCE)
                 {
                     stackRet = OC_STACK_OK;
                 }
                 // if a single resource is slow, then entire response will be treated
                 // as slow response
-                if(ehResult == OC_EH_SLOW)
+                if (ehResult == OC_EH_SLOW)
                 {
-                    OC_LOG(INFO, TAG, "This is a slow resource");
+                    OIC_LOG(INFO, TAG, "This is a slow resource");
                     ((OCServerRequest *)ehRequest->requestHandle)->slowFlag = 1;
                     stackRet = EntityHandlerCodeToOCStackCode(ehResult);
                 }
@@ -344,7 +344,11 @@ HandleBatchInterface(OCEntityHandlerRequest *ehRequest)
             {
                 break;
             }
+
+            tempChildResource = tempChildResource->next;
+
         }
+
         ehRequest->resource = (OCResourceHandle) collResource;
     }
     return stackRet;
@@ -352,16 +356,19 @@ HandleBatchInterface(OCEntityHandlerRequest *ehRequest)
 
 uint8_t GetNumOfResourcesInCollection (OCResource *resource)
 {
-    if(resource)
+    if (resource)
     {
         uint8_t num = 0;
-        for (uint8_t i = 0; i < MAX_CONTAINED_RESOURCES; i++)
+        OCChildResource *tempChildResource = NULL;
+
+        tempChildResource = resource->rsrcChildResourcesHead;
+
+        while(tempChildResource)
         {
-            if (resource->rsrcResources[i])
-            {
-                num++;
-            }
+            num++;
+            tempChildResource = tempChildResource->next;
         }
+
         return num;
     }
     else
@@ -374,24 +381,22 @@ uint8_t GetNumOfResourcesInCollection (OCResource *resource)
 OCStackResult DefaultCollectionEntityHandler (OCEntityHandlerFlag flag,
                                               OCEntityHandlerRequest *ehRequest)
 {
-    if(!ehRequest || !ehRequest->query)
+    if (!ehRequest || !ehRequest->query)
     {
         return OC_STACK_INVALID_PARAM;
     }
 
-    OCStackResult result = OC_STACK_ERROR;
-    OCStackIfTypes ifQueryParam = STACK_IF_INVALID;
-    char *rtQueryParam = NULL;
-
-    OC_LOG_V(INFO, TAG, "DefaultCollectionEntityHandler with query %s", ehRequest->query);
+    OIC_LOG_V(INFO, TAG, "DefaultCollectionEntityHandler with query %s", ehRequest->query);
 
     if (flag != OC_REQUEST_FLAG)
     {
         return OC_STACK_ERROR;
     }
 
-    result = ValidateQuery (ehRequest->query,
-                            ehRequest->resource, &ifQueryParam, &rtQueryParam);
+    OCStackIfTypes ifQueryParam = STACK_IF_INVALID;
+    char *rtQueryParam = NULL;
+    OCStackResult result = ValidateQuery (ehRequest->query,
+                                          ehRequest->resource, &ifQueryParam, &rtQueryParam);
 
     if (result != OC_STACK_OK)
     {
@@ -407,15 +412,15 @@ OCStackResult DefaultCollectionEntityHandler (OCEntityHandlerFlag flag,
                     // Get attributes of collection resource and properties of contained resources
                     // M1 release does not support attributes for collection resource, so the GET
                     // operation is same as the GET on LL interface.
-                    OC_LOG(INFO, TAG, "STACK_IF_DEFAULT");
+                    OIC_LOG(INFO, TAG, "STACK_IF_DEFAULT");
                     return HandleLinkedListInterface(ehRequest, STACK_RES_DISCOVERY_NOFILTER, NULL);
 
                 case STACK_IF_LL:
-                    OC_LOG(INFO, TAG, "STACK_IF_LL");
+                    OIC_LOG(INFO, TAG, "STACK_IF_LL");
                     return HandleLinkedListInterface(ehRequest, STACK_RES_DISCOVERY_NOFILTER, NULL);
 
                 case STACK_IF_BATCH:
-                    OC_LOG(INFO, TAG, "STACK_IF_BATCH");
+                    OIC_LOG(INFO, TAG, "STACK_IF_BATCH");
                     ((OCServerRequest *)ehRequest->requestHandle)->ehResponseHandler =
                                                                             HandleAggregateResponse;
 
@@ -451,8 +456,8 @@ OCStackResult DefaultCollectionEntityHandler (OCEntityHandlerFlag flag,
                     return HandleBatchInterface(ehRequest);
 
                 case STACK_IF_GROUP:
-                    OC_LOG(INFO, TAG, "IF_COLLECTION PUT with request ::\n");
-                    OC_LOG_PAYLOAD(INFO, ehRequest->payload);
+                    OIC_LOG(INFO, TAG, "IF_COLLECTION PUT with request ::\n");
+                    OIC_LOG_PAYLOAD(INFO, ehRequest->payload);
                     return BuildCollectionGroupActionCBORResponse(OC_REST_PUT/*flag*/,
                             (OCResource *) ehRequest->resource, ehRequest);
 
@@ -479,8 +484,8 @@ OCStackResult DefaultCollectionEntityHandler (OCEntityHandlerFlag flag,
                     return HandleBatchInterface(ehRequest);
 
                 case STACK_IF_GROUP:
-                    OC_LOG(INFO, TAG, "IF_COLLECTION POST with request ::\n");
-                    OC_LOG_PAYLOAD(INFO, ehRequest->payload);
+                    OIC_LOG(INFO, TAG, "IF_COLLECTION POST with request ::\n");
+                    OIC_LOG_PAYLOAD(INFO, ehRequest->payload);
                     return BuildCollectionGroupActionCBORResponse(OC_REST_POST/*flag*/,
                             (OCResource *) ehRequest->resource, ehRequest);
 
index 6bcaa1c..636572a 100644 (file)
 // Module Name
 #define MOD_NAME "ocobserve"
 
-#define TAG  "OCStackObserve"
+#define TAG  "OIC_RI_OBSERVE"
 
-#define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG(FATAL, TAG, #arg " is NULL"); goto exit;} }
+#define VERIFY_NON_NULL(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL"); goto exit;} }
 
-static struct ResourceObserver * serverObsList = NULL;
+static struct ResourceObserver * g_serverObsList = NULL;
 /**
  * Determine observe QOS based on the QOS of the request.
  * The qos passed as a parameter overrides what the client requested.
@@ -57,35 +57,35 @@ static struct ResourceObserver * serverObsList = NULL;
 static OCQualityOfService DetermineObserverQoS(OCMethod method,
         ResourceObserver * resourceObserver, OCQualityOfService appQoS)
 {
-    if(!resourceObserver)
+    if (!resourceObserver)
     {
-        OC_LOG(ERROR, TAG, "DetermineObserverQoS called with invalid resourceObserver");
+        OIC_LOG(ERROR, TAG, "DetermineObserverQoS called with invalid resourceObserver");
         return OC_NA_QOS;
     }
 
     OCQualityOfService decidedQoS = appQoS;
-    if(appQoS == OC_NA_QOS)
+    if (appQoS == OC_NA_QOS)
     {
         decidedQoS = resourceObserver->qos;
     }
 
-    if(appQoS != OC_HIGH_QOS)
+    if (appQoS != OC_HIGH_QOS)
     {
-        OC_LOG_V(INFO, TAG, "Current NON count for this observer is %d",
+        OIC_LOG_V(INFO, TAG, "Current NON count for this observer is %d",
                 resourceObserver->lowQosCount);
 #ifdef WITH_PRESENCE
-        if((resourceObserver->forceHighQos \
+        if ((resourceObserver->forceHighQos \
                 || resourceObserver->lowQosCount >= MAX_OBSERVER_NON_COUNT) \
                 && method != OC_REST_PRESENCE)
 #else
-        if(resourceObserver->forceHighQos \
+        if (resourceObserver->forceHighQos \
                 || resourceObserver->lowQosCount >= MAX_OBSERVER_NON_COUNT)
 #endif
         {
             resourceObserver->lowQosCount = 0;
             // at some point we have to to send CON to check on the
             // availability of observer
-            OC_LOG(INFO, TAG, "This time we are sending the  notification as High qos");
+            OIC_LOG(INFO, TAG, "This time we are sending the  notification as High qos");
             decidedQoS = OC_HIGH_QOS;
         }
         else
@@ -104,14 +104,14 @@ OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr,
         OCQualityOfService qos)
 #endif
 {
-    OC_LOG(INFO, TAG, "Entering SendObserverNotification");
-    if(!resPtr)
+    OIC_LOG(INFO, TAG, "Entering SendObserverNotification");
+    if (!resPtr)
     {
         return OC_STACK_INVALID_PARAM;
     }
 
     OCStackResult result = OC_STACK_ERROR;
-    ResourceObserver * resourceObserver = serverObsList;
+    ResourceObserver * resourceObserver = g_serverObsList;
     uint8_t numObs = 0;
     OCServerRequest * request = NULL;
     OCEntityHandlerRequest ehRequest = {0};
@@ -125,7 +125,7 @@ OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr,
         {
             numObs++;
 #ifdef WITH_PRESENCE
-            if(method != OC_REST_PRESENCE)
+            if (method != OC_REST_PRESENCE)
             {
 #endif
                 qos = DetermineObserverQoS(method, resourceObserver, qos);
@@ -137,10 +137,10 @@ OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr,
                         resourceObserver->resUri, 0, resourceObserver->acceptFormat,
                         &resourceObserver->devAddr);
 
-                if(request)
+                if (request)
                 {
                     request->observeResult = OC_STACK_OK;
-                    if(result == OC_STACK_OK)
+                    if (result == OC_STACK_OK)
                     {
                         result = FormOCEntityHandlerRequest(
                                     &ehRequest,
@@ -156,11 +156,11 @@ OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr,
                                     request->rcvdVendorSpecificHeaderOptions,
                                     OC_OBSERVE_NO_OPTION,
                                     0);
-                        if(result == OC_STACK_OK)
+                        if (result == OC_STACK_OK)
                         {
                             ehResult = resPtr->entityHandler(OC_REQUEST_FLAG, &ehRequest,
                                                 resPtr->entityHandlerCallbackParam);
-                            if(ehResult == OC_EH_ERROR)
+                            if (ehResult == OC_EH_ERROR)
                             {
                                 FindAndDeleteServerRequest(request);
                             }
@@ -175,7 +175,7 @@ OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr,
                 OCEntityHandlerResponse ehResponse = {0};
 
                 //This is effectively the implementation for the presence entity handler.
-                OC_LOG(DEBUG, TAG, "This notification is for Presence");
+                OIC_LOG(DEBUG, TAG, "This notification is for Presence");
                 result = AddServerRequest(&request, 0, 0, 1, OC_REST_GET,
                         0, resPtr->sequenceNum, qos, resourceObserver->query,
                         NULL, NULL,
@@ -183,18 +183,18 @@ OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr,
                         resourceObserver->resUri, 0, resourceObserver->acceptFormat,
                         &resourceObserver->devAddr);
 
-                if(result == OC_STACK_OK)
+                if (result == OC_STACK_OK)
                 {
                     OCPresencePayload* presenceResBuf = OCPresencePayloadCreate(
                             resPtr->sequenceNum, maxAge, trigger,
                             resourceType ? resourceType->resourcetypename : NULL);
 
-                    if(!presenceResBuf)
+                    if (!presenceResBuf)
                     {
                         return OC_STACK_NO_MEMORY;
                     }
 
-                    if(result == OC_STACK_OK)
+                    if (result == OC_STACK_OK)
                     {
                         ehResponse.ehResult = OC_EH_OK;
                         ehResponse.payload = (OCPayload*)presenceResBuf;
@@ -222,12 +222,12 @@ OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr,
 
     if (numObs == 0)
     {
-        OC_LOG(INFO, TAG, "Resource has no observers");
+        OIC_LOG(INFO, TAG, "Resource has no observers");
         result = OC_STACK_NO_OBSERVERS;
     }
     else if (observeErrorFlag)
     {
-        OC_LOG(ERROR, TAG, "Observer notification error");
+        OIC_LOG(ERROR, TAG, "Observer notification error");
         result = OC_STACK_ERROR;
     }
     return result;
@@ -240,7 +240,7 @@ OCStackResult SendListObserverNotification (OCResource * resource,
         OCQualityOfService qos)
 {
     (void)maxAge;
-    if(!resource || !obsIdList || !payload)
+    if (!resource || !obsIdList || !payload)
     {
         return OC_STACK_INVALID_PARAM;
     }
@@ -252,11 +252,11 @@ OCStackResult SendListObserverNotification (OCResource * resource,
     OCStackResult result = OC_STACK_ERROR;
     bool observeErrorFlag = false;
 
-    OC_LOG(INFO, TAG, "Entering SendListObserverNotification");
+    OIC_LOG(INFO, TAG, "Entering SendListObserverNotification");
     while(numIds)
     {
         observer = GetObserverUsingId (*obsIdList);
-        if(observer)
+        if (observer)
         {
             // Found observer - verify if it matches the resource handle
             if (observer->resource == resource)
@@ -270,15 +270,15 @@ OCStackResult SendListObserverNotification (OCResource * resource,
                         observer->resUri, 0, observer->acceptFormat,
                         &observer->devAddr);
 
-                if(request)
+                if (request)
                 {
                     request->observeResult = OC_STACK_OK;
-                    if(result == OC_STACK_OK)
+                    if (result == OC_STACK_OK)
                     {
                         OCEntityHandlerResponse ehResponse = {0};
                         ehResponse.ehResult = OC_EH_OK;
                         ehResponse.payload = (OCPayload*)OCRepPayloadCreate();
-                        if(!ehResponse.payload)
+                        if (!ehResponse.payload)
                         {
                             FindAndDeleteServerRequest(request);
                             continue;
@@ -288,9 +288,9 @@ OCStackResult SendListObserverNotification (OCResource * resource,
                         ehResponse.requestHandle = (OCRequestHandle) request;
                         ehResponse.resourceHandle = (OCResourceHandle) resource;
                         result = OCDoResponse(&ehResponse);
-                        if(result == OC_STACK_OK)
+                        if (result == OC_STACK_OK)
                         {
-                            OC_LOG_V(INFO, TAG, "Observer id %d notified.", *obsIdList);
+                            OIC_LOG_V(INFO, TAG, "Observer id %d notified.", *obsIdList);
 
                             // Increment only if OCDoResponse is successful
                             numSentNotification++;
@@ -300,7 +300,7 @@ OCStackResult SendListObserverNotification (OCResource * resource,
                         }
                         else
                         {
-                            OC_LOG_V(INFO, TAG, "Error notifying observer id %d.", *obsIdList);
+                            OIC_LOG_V(INFO, TAG, "Error notifying observer id %d.", *obsIdList);
                         }
                     }
                     else
@@ -320,17 +320,17 @@ OCStackResult SendListObserverNotification (OCResource * resource,
         numIds--;
     }
 
-    if(numSentNotification == numberOfIds && !observeErrorFlag)
+    if (numSentNotification == numberOfIds && !observeErrorFlag)
     {
         return OC_STACK_OK;
     }
-    else if(numSentNotification == 0)
+    else if (numSentNotification == 0)
     {
         return OC_STACK_NO_OBSERVERS;
     }
     else
     {
-        OC_LOG(ERROR, TAG, "Observer notification error");
+        OIC_LOG(ERROR, TAG, "Observer notification error");
         return OC_STACK_ERROR;
     }
 }
@@ -339,7 +339,7 @@ OCStackResult GenerateObserverId (OCObservationId *observationId)
 {
     ResourceObserver *resObs = NULL;
 
-    OC_LOG(INFO, TAG, "Entering GenerateObserverId");
+    OIC_LOG(INFO, TAG, "Entering GenerateObserverId");
     VERIFY_NON_NULL (observationId);
 
     do
@@ -349,7 +349,7 @@ OCStackResult GenerateObserverId (OCObservationId *observationId)
         resObs = GetObserverUsingId (*observationId);
     } while (NULL != resObs);
 
-    OC_LOG_V(INFO, TAG, "GeneratedObservation ID is %u", *observationId);
+    OIC_LOG_V(INFO, TAG, "GeneratedObservation ID is %u", *observationId);
 
     return OC_STACK_OK;
 exit:
@@ -375,14 +375,13 @@ OCStackResult AddObserver (const char         *resUri,
     {
         return OC_STACK_RESOURCE_ERROR;
     }
-    ResourceObserver *obsNode = NULL;
 
-    if(!resUri || !token || !*token)
+    if (!resUri || !token || !*token)
     {
         return OC_STACK_INVALID_PARAM;
     }
 
-    obsNode = (ResourceObserver *) OICCalloc(1, sizeof(ResourceObserver));
+    ResourceObserver *obsNode = (ResourceObserver *) OICCalloc(1, sizeof(ResourceObserver));
     if (obsNode)
     {
         obsNode->observeId = obsId;
@@ -392,14 +391,14 @@ OCStackResult AddObserver (const char         *resUri,
 
         obsNode->qos = qos;
         obsNode->acceptFormat = acceptFormat;
-        if(query)
+        if (query)
         {
             obsNode->query = OICStrdup(query);
             VERIFY_NON_NULL (obsNode->query);
         }
         // If tokenLength is zero, the return value depends on the
         // particular library implementation (it may or may not be a null pointer).
-        if(tokenLength)
+        if (tokenLength)
         {
             obsNode->token = (CAToken_t)OICMalloc(tokenLength);
             VERIFY_NON_NULL (obsNode->token);
@@ -410,7 +409,7 @@ OCStackResult AddObserver (const char         *resUri,
         obsNode->devAddr = *devAddr;
         obsNode->resource = resHandle;
 
-        LL_APPEND (serverObsList, obsNode);
+        LL_APPEND (g_serverObsList, obsNode);
 
         return OC_STACK_OK;
     }
@@ -431,7 +430,7 @@ ResourceObserver* GetObserverUsingId (const OCObservationId observeId)
 
     if (observeId)
     {
-        LL_FOREACH (serverObsList, out)
+        LL_FOREACH (g_serverObsList, out)
         {
             if (out->observeId == observeId)
             {
@@ -439,7 +438,7 @@ ResourceObserver* GetObserverUsingId (const OCObservationId observeId)
             }
         }
     }
-    OC_LOG(INFO, TAG, "Observer node not found!!");
+    OIC_LOG(INFO, TAG, "Observer node not found!!");
     return NULL;
 }
 
@@ -447,16 +446,16 @@ ResourceObserver* GetObserverUsingToken (const CAToken_t token, uint8_t tokenLen
 {
     ResourceObserver *out = NULL;
 
-    if(token && *token)
+    if (token && *token)
     {
-        OC_LOG(INFO, TAG, "Looking for token");
-        OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
-        OC_LOG(INFO, TAG, "\tFound token:");
+        OIC_LOG(INFO, TAG, "Looking for token");
+        OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
+        OIC_LOG(INFO, TAG, "\tFound token:");
 
-        LL_FOREACH (serverObsList, out)
+        LL_FOREACH (g_serverObsList, out)
         {
-            OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)out->token, tokenLength);
-            if((memcmp(out->token, token, tokenLength) == 0))
+            OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)out->token, tokenLength);
+            if ((memcmp(out->token, token, tokenLength) == 0))
             {
                 return out;
             }
@@ -464,28 +463,26 @@ ResourceObserver* GetObserverUsingToken (const CAToken_t token, uint8_t tokenLen
     }
     else
     {
-        OC_LOG(ERROR, TAG, "Passed in NULL token");
+        OIC_LOG(ERROR, TAG, "Passed in NULL token");
     }
 
-    OC_LOG(INFO, TAG, "Observer node not found!!");
+    OIC_LOG(INFO, TAG, "Observer node not found!!");
     return NULL;
 }
 
 OCStackResult DeleteObserverUsingToken (CAToken_t token, uint8_t tokenLength)
 {
-    if(!token || !*token)
+    if (!token || !*token)
     {
         return OC_STACK_INVALID_PARAM;
     }
 
-    ResourceObserver *obsNode = NULL;
-
-    obsNode = GetObserverUsingToken (token, tokenLength);
+    ResourceObserver *obsNode = GetObserverUsingToken (token, tokenLength);
     if (obsNode)
     {
-        OC_LOG_V(INFO, TAG, "deleting observer id  %u with token", obsNode->observeId);
-        OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)obsNode->token, tokenLength);
-        LL_DELETE (serverObsList, obsNode);
+        OIC_LOG_V(INFO, TAG, "deleting observer id  %u with token", obsNode->observeId);
+        OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)obsNode->token, tokenLength);
+        LL_DELETE (g_serverObsList, obsNode);
         OICFree(obsNode->resUri);
         OICFree(obsNode->query);
         OICFree(obsNode->token);
@@ -499,14 +496,14 @@ void DeleteObserverList()
 {
     ResourceObserver *out = NULL;
     ResourceObserver *tmp = NULL;
-    LL_FOREACH_SAFE (serverObsList, out, tmp)
+    LL_FOREACH_SAFE (g_serverObsList, out, tmp)
     {
-        if(out)
+        if (out)
         {
             DeleteObserverUsingToken ((out->token), out->tokenLength);
         }
     }
-    serverObsList = NULL;
+    g_serverObsList = NULL;
 }
 
 /*
@@ -523,14 +520,14 @@ CreateObserveHeaderOption (CAHeaderOption_t **caHdrOpt,
                            uint8_t numOptions,
                            uint8_t observeFlag)
 {
-    if(!caHdrOpt)
+    if (!caHdrOpt)
     {
         return OC_STACK_INVALID_PARAM;
     }
 
     if (numOptions > 0 && !ocHdrOpt)
     {
-        OC_LOG (INFO, TAG, "options are NULL though number is non zero");
+        OIC_LOG (INFO, TAG, "options are NULL though number is non zero");
         return OC_STACK_INVALID_PARAM;
     }
 
@@ -567,20 +564,20 @@ GetObserveHeaderOption (uint32_t * observationOption,
                         CAHeaderOption_t *options,
                         uint8_t * numOptions)
 {
-    if(!observationOption)
+    if (!observationOption)
     {
         return OC_STACK_INVALID_PARAM;
     }
 
-    if(!options || !numOptions)
+    if (!options || !numOptions)
     {
-        OC_LOG (INFO, TAG, "No options present");
+        OIC_LOG (INFO, TAG, "No options present");
         return OC_STACK_OK;
     }
 
     for(uint8_t i = 0; i < *numOptions; i++)
     {
-        if(options[i].protocolID == CA_COAP_ID &&
+        if (options[i].protocolID == CA_COAP_ID &&
                 options[i].optionID == COAP_OPTION_OBSERVE)
         {
             *observationOption = options[i].optionData[0];
old mode 100755 (executable)
new mode 100644 (file)
index 485eda3..3c302a3
 #include "logger.h"
 #include "rdpayload.h"
 
-#define TAG "OCPayload"
+#define TAG "OIC_RI_PAYLOAD"
+
 static void OCFreeRepPayloadValueContents(OCRepPayloadValue* val);
-static void FreeOCDiscoveryResource(OCResourcePayload* payload);
 
 void OCPayloadDestroy(OCPayload* payload)
 {
-    if(!payload)
+    if (!payload)
     {
         return;
     }
@@ -64,7 +64,7 @@ void OCPayloadDestroy(OCPayload* payload)
            OCRDPayloadDestroy((OCRDPayload*)payload);
            break;
         default:
-            OC_LOG_V(ERROR, TAG, "Unsupported payload type in destroy: %d", payload->type);
+            OIC_LOG_V(ERROR, TAG, "Unsupported payload type in destroy: %d", payload->type);
             OICFree(payload);
             break;
     }
@@ -73,7 +73,7 @@ OCRepPayload* OCRepPayloadCreate()
 {
     OCRepPayload* payload = (OCRepPayload*)OICCalloc(1, sizeof(OCRepPayload));
 
-    if(!payload)
+    if (!payload)
     {
         return NULL;
     }
@@ -85,7 +85,7 @@ OCRepPayload* OCRepPayloadCreate()
 
 void OCRepPayloadAppend(OCRepPayload* parent, OCRepPayload* child)
 {
-    if(!parent)
+    if (!parent)
     {
         return;
     }
@@ -101,7 +101,7 @@ void OCRepPayloadAppend(OCRepPayload* parent, OCRepPayload* child)
 
 static OCRepPayloadValue* OCRepPayloadFindValue(const OCRepPayload* payload, const char* name)
 {
-    if(!payload || !name)
+    if (!payload || !name)
     {
         return NULL;
     }
@@ -109,7 +109,7 @@ static OCRepPayloadValue* OCRepPayloadFindValue(const OCRepPayload* payload, con
     OCRepPayloadValue* val = payload->values;
     while(val)
     {
-        if(0 == strcmp(val->name, name))
+        if (0 == strcmp(val->name, name))
         {
             return val;
         }
@@ -117,12 +117,11 @@ static OCRepPayloadValue* OCRepPayloadFindValue(const OCRepPayload* payload, con
     }
 
     return NULL;
-
 }
 
 static void OCCopyPropertyValueArray(OCRepPayloadValue* dest, OCRepPayloadValue* source)
 {
-    if(!dest || !source)
+    if (!dest || !source)
     {
         return;
     }
@@ -132,34 +131,49 @@ static void OCCopyPropertyValueArray(OCRepPayloadValue* dest, OCRepPayloadValue*
     {
         case OCREP_PROP_INT:
             dest->arr.iArray = (int64_t*)OICMalloc(dimTotal * sizeof(int64_t));
+            VERIFY_PARAM_NON_NULL(TAG, dest->arr.iArray, "Failed allocating memory");
             memcpy(dest->arr.iArray, source->arr.iArray, dimTotal * sizeof(int64_t));
             break;
         case OCREP_PROP_DOUBLE:
             dest->arr.dArray = (double*)OICMalloc(dimTotal * sizeof(double));
+            VERIFY_PARAM_NON_NULL(TAG, dest->arr.dArray, "Failed allocating memory");
             memcpy(dest->arr.dArray, source->arr.dArray, dimTotal * sizeof(double));
             break;
         case OCREP_PROP_BOOL:
             dest->arr.bArray = (bool*)OICMalloc(dimTotal * sizeof(bool));
+            VERIFY_PARAM_NON_NULL(TAG, dest->arr.bArray, "Failed allocating memory");
             memcpy(dest->arr.bArray, source->arr.bArray, dimTotal * sizeof(bool));
             break;
         case OCREP_PROP_STRING:
             dest->arr.strArray = (char**)OICMalloc(dimTotal * sizeof(char*));
+            VERIFY_PARAM_NON_NULL(TAG, dest->arr.strArray, "Failed allocating memory");
             for(size_t i = 0; i < dimTotal; ++i)
             {
                 dest->arr.strArray[i] = OICStrdup(source->arr.strArray[i]);
             }
             break;
+        case OCREP_PROP_OBJECT:
+            dest->arr.objArray = (OCRepPayload**)OICMalloc(dimTotal * sizeof(OCRepPayload*));
+            VERIFY_PARAM_NON_NULL(TAG, dest->arr.objArray, "Failed allocating memory");
+            for(size_t i = 0; i < dimTotal; ++i)
+            {
+                dest->arr.objArray[i] = OCRepPayloadClone(source->arr.objArray[i]);
+            }
+            break;
         case OCREP_PROP_ARRAY:
             dest->arr.objArray = (OCRepPayload**)OICMalloc(dimTotal * sizeof(OCRepPayload*));
+            VERIFY_PARAM_NON_NULL(TAG, dest->arr.objArray, "Failed allocating memory");
             for(size_t i = 0; i < dimTotal; ++i)
             {
                 dest->arr.objArray[i] = OCRepPayloadClone(source->arr.objArray[i]);
             }
             break;
         default:
-            OC_LOG(ERROR, TAG, "CopyPropertyValueArray invalid type");
+            OIC_LOG(ERROR, TAG, "CopyPropertyValueArray invalid type");
             break;
     }
+exit:
+    return;
 }
 
 static void OCCopyPropertyValue (OCRepPayloadValue *dest, OCRepPayloadValue *source)
@@ -188,16 +202,16 @@ static void OCCopyPropertyValue (OCRepPayloadValue *dest, OCRepPayloadValue *sou
 
 static void OCFreeRepPayloadValueContents(OCRepPayloadValue* val)
 {
-    if(!val)
+    if (!val)
     {
         return;
     }
 
-    if(val->type == OCREP_PROP_STRING)
+    if (val->type == OCREP_PROP_STRING)
     {
         OICFree(val->str);
     }
-    else if(val->type == OCREP_PROP_BYTE_STRING)
+    else if (val->type == OCREP_PROP_BYTE_STRING)
     {
         OICFree(val->ocByteStr.bytes);
     }
@@ -218,7 +232,7 @@ static void OCFreeRepPayloadValueContents(OCRepPayloadValue* val)
                 OICFree(val->arr.iArray);
                 break;
             case OCREP_PROP_STRING:
-                for(size_t i = 0; i< dimTotal;++i)
+                for(size_t i = 0; i< dimTotal; ++i)
                 {
                     OICFree(val->arr.strArray[i]);
                 }
@@ -231,8 +245,8 @@ static void OCFreeRepPayloadValueContents(OCRepPayloadValue* val)
                 }
                 OICFree(val->arr.ocByteStrArray);
                 break;
-            case OCREP_PROP_OBJECT:
-                for(size_t i = 0; i< dimTotal;++i)
+            case OCREP_PROP_OBJECT: // This case is the temporary fix for string input
+                for(size_t i = 0; i< dimTotal; ++i)
                 {
                     OCRepPayloadDestroy(val->arr.objArray[i]);
                 }
@@ -240,7 +254,7 @@ static void OCFreeRepPayloadValueContents(OCRepPayloadValue* val)
                 break;
             case OCREP_PROP_NULL:
             case OCREP_PROP_ARRAY:
-                OC_LOG_V(ERROR, TAG, "FreeRepPayloadValueContents: Illegal type\
+                OIC_LOG_V(ERROR, TAG, "FreeRepPayloadValueContents: Illegal type\
                         inside an array: %d", val->arr.type);
                 break;
         }
@@ -249,7 +263,7 @@ static void OCFreeRepPayloadValueContents(OCRepPayloadValue* val)
 
 static void OCFreeRepPayloadValue(OCRepPayloadValue* val)
 {
-    if(!val)
+    if (!val)
     {
         return;
     }
@@ -304,21 +318,21 @@ static OCRepPayloadValue* OCRepPayloadValueClone (OCRepPayloadValue* source)
 static OCRepPayloadValue* OCRepPayloadFindAndSetValue(OCRepPayload* payload, const char* name,
         OCRepPayloadPropType type)
 {
-    if(!payload || !name)
+    if (!payload || !name)
     {
         return NULL;
     }
 
     OCRepPayloadValue* val = payload->values;
-    if(val == NULL)
+    if (val == NULL)
     {
         payload->values = (OCRepPayloadValue*)OICCalloc(1, sizeof(OCRepPayloadValue));
-        if(!payload->values)
+        if (!payload->values)
         {
             return NULL;
         }
         payload->values->name = OICStrdup(name);
-        if(!payload->values->name)
+        if (!payload->values->name)
         {
             OICFree(payload->values);
             payload->values = NULL;
@@ -330,21 +344,21 @@ static OCRepPayloadValue* OCRepPayloadFindAndSetValue(OCRepPayload* payload, con
 
     while(val)
     {
-        if(0 == strcmp(val->name, name))
+        if (0 == strcmp(val->name, name))
         {
             OCFreeRepPayloadValueContents(val);
             val->type = type;
             return val;
         }
-        else if(val->next == NULL)
+        else if (val->next == NULL)
         {
             val->next = (OCRepPayloadValue*)OICCalloc(1, sizeof(OCRepPayloadValue));
-            if(!val->next)
+            if (!val->next)
             {
                 return NULL;
             }
             val->next->name = OICStrdup(name);
-            if(!val->next->name)
+            if (!val->next->name)
             {
                 OICFree(val->next);
                 val->next = NULL;
@@ -357,7 +371,7 @@ static OCRepPayloadValue* OCRepPayloadFindAndSetValue(OCRepPayload* payload, con
         val = val->next;
     }
 
-    OC_LOG(ERROR, TAG, "FindAndSetValue reached point after while loop, pointer corruption?");
+    OIC_LOG(ERROR, TAG, "FindAndSetValue reached point after while loop, pointer corruption?");
     return NULL;
 }
 
@@ -368,12 +382,12 @@ bool OCRepPayloadAddResourceType(OCRepPayload* payload, const char* resourceType
 
 bool OCRepPayloadAddResourceTypeAsOwner(OCRepPayload* payload, char* resourceType)
 {
-    if(!payload || !resourceType)
+    if (!payload || !resourceType)
     {
         return false;
     }
 
-    if(payload->types)
+    if (payload->types)
     {
         OCStringLL* cur = payload->types;
         while(cur->next)
@@ -382,7 +396,7 @@ bool OCRepPayloadAddResourceTypeAsOwner(OCRepPayload* payload, char* resourceTyp
         }
         cur->next = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
 
-        if(!cur->next)
+        if (!cur->next)
         {
             return false;
         }
@@ -393,7 +407,7 @@ bool OCRepPayloadAddResourceTypeAsOwner(OCRepPayload* payload, char* resourceTyp
     else
     {
         payload->types = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
-        if(!payload->types)
+        if (!payload->types)
         {
             return false;
         }
@@ -409,12 +423,12 @@ bool OCRepPayloadAddInterface(OCRepPayload* payload, const char* interface)
 
 bool OCRepPayloadAddInterfaceAsOwner(OCRepPayload* payload, char* interface)
 {
-    if(!payload || !interface)
+    if (!payload || !interface)
     {
         return false;
     }
 
-    if(payload->interfaces)
+    if (payload->interfaces)
     {
         OCStringLL* cur = payload->interfaces;
         while(cur->next)
@@ -423,7 +437,7 @@ bool OCRepPayloadAddInterfaceAsOwner(OCRepPayload* payload, char* interface)
         }
         cur->next = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
 
-        if(!cur->next)
+        if (!cur->next)
         {
             return false;
         }
@@ -433,7 +447,7 @@ bool OCRepPayloadAddInterfaceAsOwner(OCRepPayload* payload, char* interface)
     else
     {
         payload->interfaces = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
-        if(!payload->interfaces)
+        if (!payload->interfaces)
         {
             return false;
         }
@@ -444,11 +458,11 @@ bool OCRepPayloadAddInterfaceAsOwner(OCRepPayload* payload, char* interface)
 
 bool OCRepPayloadSetUri(OCRepPayload* payload, const char*  uri)
 {
-    if(!payload)
+    if (!payload)
     {
         return false;
     }
-
+    OICFree(payload->uri);
     payload->uri = OICStrdup(uri);
     return payload->uri != NULL;
 }
@@ -457,7 +471,7 @@ bool OCRepPayloadIsNull(const OCRepPayload* payload, const char* name)
 {
     OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
 
-    if(!val)
+    if (!val)
     {
         return false;
     }
@@ -469,7 +483,7 @@ static bool OCRepPayloadSetProp(OCRepPayload* payload, const char* name,
         void* value, OCRepPayloadPropType type)
 {
     OCRepPayloadValue* val = OCRepPayloadFindAndSetValue(payload, name, type);
-    if(!val)
+    if (!val)
     {
         return false;
     }
@@ -518,7 +532,7 @@ bool OCRepPayloadGetPropInt(const OCRepPayload* payload, const char* name, int64
 {
     OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
 
-    if(!val || val->type != OCREP_PROP_INT)
+    if (!val || val->type != OCREP_PROP_INT)
     {
         return false;
     }
@@ -528,7 +542,7 @@ bool OCRepPayloadGetPropInt(const OCRepPayload* payload, const char* name, int64
 }
 
 bool OCRepPayloadSetPropDouble(OCRepPayload* payload,
-        const char* name, double value)
+                               const char* name, double value)
 {
     return OCRepPayloadSetProp(payload, name, &value, OCREP_PROP_DOUBLE);
 }
@@ -537,13 +551,21 @@ bool OCRepPayloadGetPropDouble(const OCRepPayload* payload, const char* name, do
 {
     OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
 
-    if(!val || val->type != OCREP_PROP_DOUBLE)
+    if (val)
     {
-        return false;
+        if (val->type == OCREP_PROP_DOUBLE)
+        {
+            *value = val->d;
+            return true;
+        }
+        else if (val->type == OCREP_PROP_INT)
+        {
+            *value = val->i;
+            return true;
+        }
     }
 
-    *value = val->d;
-    return true;
+    return false;
 }
 
 bool OCRepPayloadSetPropString(OCRepPayload* payload, const char* name, const char* value)
@@ -551,7 +573,7 @@ bool OCRepPayloadSetPropString(OCRepPayload* payload, const char* name, const ch
     char* temp = OICStrdup(value);
     bool b = OCRepPayloadSetPropStringAsOwner(payload, name, temp);
 
-    if(!b)
+    if (!b)
     {
         OICFree(temp);
     }
@@ -567,7 +589,7 @@ bool OCRepPayloadGetPropString(const OCRepPayload* payload, const char* name, ch
 {
     OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
 
-    if(!val || val->type != OCREP_PROP_STRING)
+    if (!val || val->type != OCREP_PROP_STRING)
     {
         return false;
     }
@@ -587,7 +609,7 @@ bool OCRepPayloadSetPropByteString(OCRepPayload* payload, const char* name, OCBy
                     .bytes = (uint8_t*)OICMalloc(value.len * sizeof(uint8_t)),
                     .len = value.len };
 
-    if(!ocByteStr.bytes)
+    if (!ocByteStr.bytes)
     {
         return false;
     }
@@ -595,7 +617,7 @@ bool OCRepPayloadSetPropByteString(OCRepPayload* payload, const char* name, OCBy
 
     bool b = OCRepPayloadSetPropByteStringAsOwner(payload, name, &ocByteStr);
 
-    if(!b)
+    if (!b)
     {
         OICFree(ocByteStr.bytes);
     }
@@ -633,7 +655,7 @@ bool OCRepPayloadGetPropByteString(const OCRepPayload* payload, const char* name
 }
 
 bool OCRepPayloadSetPropBool(OCRepPayload* payload,
-        const char* name, bool value)
+                             const char* name, bool value)
 {
     return OCRepPayloadSetProp(payload, name, &value, OCREP_PROP_BOOL);
 }
@@ -642,7 +664,7 @@ bool OCRepPayloadGetPropBool(const OCRepPayload* payload, const char* name, bool
 {
     OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
 
-    if(!val || val->type != OCREP_PROP_BOOL)
+    if (!val || val->type != OCREP_PROP_BOOL)
     {
         return false;
     }
@@ -656,7 +678,7 @@ bool OCRepPayloadSetPropObject(OCRepPayload* payload, const char* name, const OC
     OCRepPayload* temp = OCRepPayloadClone(value);
     bool b = OCRepPayloadSetPropObjectAsOwner(payload, name, temp);
 
-    if(!b)
+    if (!b)
     {
         OCRepPayloadDestroy(temp);
     }
@@ -672,7 +694,7 @@ bool OCRepPayloadGetPropObject(const OCRepPayload* payload, const char* name, OC
 {
     OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
 
-    if(!val || val->type != OCREP_PROP_OBJECT)
+    if (!val || val->type != OCREP_PROP_OBJECT)
     {
         return false;
     }
@@ -683,7 +705,7 @@ bool OCRepPayloadGetPropObject(const OCRepPayload* payload, const char* name, OC
 
 size_t calcDimTotal(const size_t dimensions[MAX_REP_ARRAY_DEPTH])
 {
-    if(dimensions[0] == 0)
+    if (dimensions[0] == 0)
     {
         return 0;
     }
@@ -818,7 +840,7 @@ bool OCRepPayloadSetIntArrayAsOwner(OCRepPayload* payload, const char* name,
 {
     OCRepPayloadValue* val = OCRepPayloadFindAndSetValue(payload, name, OCREP_PROP_ARRAY);
 
-    if(!val)
+    if (!val)
     {
         return false;
     }
@@ -834,14 +856,14 @@ bool OCRepPayloadSetIntArray(OCRepPayload* payload, const char* name,
         const int64_t* array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
 {
     size_t dimTotal = calcDimTotal(dimensions);
-    if(dimTotal == 0)
+    if (dimTotal == 0)
     {
         return false;
     }
 
     int64_t* newArray = (int64_t*)OICMalloc(dimTotal * sizeof(int64_t));
 
-    if(!newArray)
+    if (!newArray)
     {
         return false;
     }
@@ -850,7 +872,7 @@ bool OCRepPayloadSetIntArray(OCRepPayload* payload, const char* name,
 
 
     bool b = OCRepPayloadSetIntArrayAsOwner(payload, name, newArray, dimensions);
-    if(!b)
+    if (!b)
     {
         OICFree(newArray);
     }
@@ -862,19 +884,19 @@ bool OCRepPayloadGetIntArray(const OCRepPayload* payload, const char* name,
 {
     OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
 
-    if(!val || val->type != OCREP_PROP_ARRAY || val->arr.type != OCREP_PROP_INT
+    if (!val || val->type != OCREP_PROP_ARRAY || val->arr.type != OCREP_PROP_INT
             || !val->arr.iArray)
     {
         return false;
     }
 
     size_t dimTotal = calcDimTotal(val->arr.dimensions);
-    if(dimTotal == 0)
+    if (dimTotal == 0)
     {
         return false;
     }
     *array = (int64_t*)OICMalloc(dimTotal * sizeof(int64_t));
-    if(!*array)
+    if (!*array)
     {
         return false;
     }
@@ -889,7 +911,7 @@ bool OCRepPayloadSetDoubleArrayAsOwner(OCRepPayload* payload, const char* name,
 {
     OCRepPayloadValue* val = OCRepPayloadFindAndSetValue(payload, name, OCREP_PROP_ARRAY);
 
-    if(!val)
+    if (!val)
     {
         return false;
     }
@@ -904,14 +926,14 @@ bool OCRepPayloadSetDoubleArray(OCRepPayload* payload, const char* name,
         const double* array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
 {
     size_t dimTotal = calcDimTotal(dimensions);
-    if(dimTotal == 0)
+    if (dimTotal == 0)
     {
         return false;
     }
 
     double* newArray = (double*)OICMalloc(dimTotal * sizeof(double));
 
-    if(!newArray)
+    if (!newArray)
     {
         return false;
     }
@@ -919,7 +941,7 @@ bool OCRepPayloadSetDoubleArray(OCRepPayload* payload, const char* name,
     memcpy(newArray, array, dimTotal * sizeof(double));
 
     bool b = OCRepPayloadSetDoubleArrayAsOwner(payload, name, newArray, dimensions);
-    if(!b)
+    if (!b)
     {
         OICFree(newArray);
     }
@@ -931,24 +953,37 @@ bool OCRepPayloadGetDoubleArray(const OCRepPayload* payload, const char* name,
 {
     OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
 
-    if(!val || val->type != OCREP_PROP_ARRAY || val->arr.type != OCREP_PROP_DOUBLE
+    if (!val || val->type != OCREP_PROP_ARRAY ||
+        (val->arr.type != OCREP_PROP_DOUBLE && val->arr.type != OCREP_PROP_INT)
             || !val->arr.dArray)
     {
         return false;
     }
 
     size_t dimTotal = calcDimTotal(val->arr.dimensions);
-    if(dimTotal == 0)
+    if (dimTotal == 0)
     {
         return false;
     }
     *array = (double*)OICMalloc(dimTotal * sizeof(double));
-    if(!*array)
+    if (!*array)
     {
         return false;
     }
 
-    memcpy(*array, val->arr.dArray, dimTotal * sizeof(double));
+    if (val->arr.type != OCREP_PROP_DOUBLE)
+    {
+        memcpy(*array, val->arr.dArray, dimTotal * sizeof(double));
+    }
+    else
+    {
+        /* need to convert from integer */
+        size_t n = 0;
+        for ( ; n < dimTotal; ++n)
+        {
+            (*array)[n] = val->arr.iArray[n];
+        }
+    }
     memcpy(dimensions, val->arr.dimensions, MAX_REP_ARRAY_DEPTH * sizeof(size_t));
     return true;
 }
@@ -958,7 +993,7 @@ bool OCRepPayloadSetStringArrayAsOwner(OCRepPayload* payload, const char* name,
 {
     OCRepPayloadValue* val = OCRepPayloadFindAndSetValue(payload, name, OCREP_PROP_ARRAY);
 
-    if(!val)
+    if (!val)
     {
         return false;
     }
@@ -973,14 +1008,14 @@ bool OCRepPayloadSetStringArray(OCRepPayload* payload, const char* name,
         const char** array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
 {
     size_t dimTotal = calcDimTotal(dimensions);
-    if(dimTotal == 0)
+    if (dimTotal == 0)
     {
         return false;
     }
 
     char** newArray = (char**)OICMalloc(dimTotal * sizeof(char*));
 
-    if(!newArray)
+    if (!newArray)
     {
         return false;
     }
@@ -992,7 +1027,7 @@ bool OCRepPayloadSetStringArray(OCRepPayload* payload, const char* name,
 
     bool b = OCRepPayloadSetStringArrayAsOwner(payload, name, newArray, dimensions);
 
-    if(!b)
+    if (!b)
     {
         for(size_t i = 0; i < dimTotal; ++i)
         {
@@ -1008,19 +1043,19 @@ bool OCRepPayloadGetStringArray(const OCRepPayload* payload, const char* name,
 {
     OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
 
-    if(!val || val->type != OCREP_PROP_ARRAY || val->arr.type != OCREP_PROP_STRING
+    if (!val || val->type != OCREP_PROP_ARRAY || val->arr.type != OCREP_PROP_STRING
             || !val->arr.strArray)
     {
         return false;
     }
 
     size_t dimTotal = calcDimTotal(val->arr.dimensions);
-    if(dimTotal == 0)
+    if (dimTotal == 0)
     {
         return false;
     }
     *array = (char**)OICMalloc(dimTotal * sizeof(char*));
-    if(!*array)
+    if (!*array)
     {
         return false;
     }
@@ -1042,7 +1077,7 @@ bool OCRepPayloadSetBoolArrayAsOwner(OCRepPayload* payload, const char* name,
 
     OCRepPayloadValue* val = OCRepPayloadFindAndSetValue(payload, name, OCREP_PROP_ARRAY);
 
-    if(!val)
+    if (!val)
     {
         return false;
     }
@@ -1057,14 +1092,14 @@ bool OCRepPayloadSetBoolArray(OCRepPayload* payload, const char* name,
         const bool* array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
 {
     size_t dimTotal = calcDimTotal(dimensions);
-    if(dimTotal == 0)
+    if (dimTotal == 0)
     {
         return false;
     }
 
     bool* newArray = (bool*)OICMalloc(dimTotal * sizeof(bool));
 
-    if(!newArray)
+    if (!newArray)
     {
         return false;
     }
@@ -1073,7 +1108,7 @@ bool OCRepPayloadSetBoolArray(OCRepPayload* payload, const char* name,
 
 
     bool b = OCRepPayloadSetBoolArrayAsOwner(payload, name, newArray, dimensions);
-    if(!b)
+    if (!b)
     {
         OICFree(newArray);
     }
@@ -1085,19 +1120,19 @@ bool OCRepPayloadGetBoolArray(const OCRepPayload* payload, const char* name,
 {
     OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
 
-    if(!val || val->type != OCREP_PROP_ARRAY || val->arr.type != OCREP_PROP_BOOL
+    if (!val || val->type != OCREP_PROP_ARRAY || val->arr.type != OCREP_PROP_BOOL
             || !val->arr.bArray)
     {
         return false;
     }
 
     size_t dimTotal = calcDimTotal(val->arr.dimensions);
-    if(dimTotal == 0)
+    if (dimTotal == 0)
     {
         return false;
     }
     *array = (bool*)OICMalloc(dimTotal * sizeof(bool));
-    if(!*array)
+    if (!*array)
     {
         return false;
     }
@@ -1112,7 +1147,7 @@ bool OCRepPayloadSetPropObjectArrayAsOwner(OCRepPayload* payload, const char* na
 {
     OCRepPayloadValue* val = OCRepPayloadFindAndSetValue(payload, name, OCREP_PROP_ARRAY);
 
-    if(!val)
+    if (!val)
     {
         return false;
     }
@@ -1128,14 +1163,14 @@ bool OCRepPayloadSetPropObjectArray(OCRepPayload* payload, const char* name,
         const OCRepPayload** array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
 {
     size_t dimTotal = calcDimTotal(dimensions);
-    if(dimTotal == 0)
+    if (dimTotal == 0)
     {
         return false;
     }
 
     OCRepPayload** newArray = (OCRepPayload**)OICMalloc(dimTotal * sizeof(OCRepPayload*));
 
-    if(!newArray)
+    if (!newArray)
     {
         return false;
     }
@@ -1147,7 +1182,7 @@ bool OCRepPayloadSetPropObjectArray(OCRepPayload* payload, const char* name,
 
     bool b = OCRepPayloadSetPropObjectArrayAsOwner(payload, name, newArray, dimensions);
 
-    if(!b)
+    if (!b)
     {
         for(size_t i = 0; i < dimTotal; ++i)
         {
@@ -1163,19 +1198,19 @@ bool OCRepPayloadGetPropObjectArray(const OCRepPayload* payload, const char* nam
 {
     OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
 
-    if(!val || val->type != OCREP_PROP_ARRAY || val->arr.type != OCREP_PROP_OBJECT
+    if (!val || val->type != OCREP_PROP_ARRAY || val->arr.type != OCREP_PROP_OBJECT
             || !val->arr.objArray)
     {
         return false;
     }
 
     size_t dimTotal = calcDimTotal(val->arr.dimensions);
-    if(dimTotal == 0)
+    if (dimTotal == 0)
     {
         return false;
     }
     *array = (OCRepPayload**)OICMalloc(dimTotal * sizeof(OCRepPayload*));
-    if(!*array)
+    if (!*array)
     {
         return false;
     }
@@ -1192,7 +1227,7 @@ bool OCRepPayloadGetPropObjectArray(const OCRepPayload* payload, const char* nam
 
 void OCFreeOCStringLL(OCStringLL* ll)
 {
-    if(!ll)
+    if (!ll)
     {
         return;
     }
@@ -1263,7 +1298,7 @@ OCRepPayload* OCRepPayloadClone (const OCRepPayload* payload)
 
 void OCRepPayloadDestroy(OCRepPayload* payload)
 {
-    if(!payload)
+    if (!payload)
     {
         return;
     }
@@ -1280,7 +1315,7 @@ OCDiscoveryPayload* OCDiscoveryPayloadCreate()
 {
     OCDiscoveryPayload* payload = (OCDiscoveryPayload*)OICCalloc(1, sizeof(OCDiscoveryPayload));
 
-    if(!payload)
+    if (!payload)
     {
         return NULL;
     }
@@ -1290,24 +1325,31 @@ OCDiscoveryPayload* OCDiscoveryPayloadCreate()
     return payload;
 }
 
-OCSecurityPayload* OCSecurityPayloadCreate(const char* securityData)
+OCSecurityPayload* OCSecurityPayloadCreate(const uint8_t* securityData, size_t size)
 {
     OCSecurityPayload* payload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
 
-    if(!payload)
+    if (!payload)
     {
         return NULL;
     }
 
     payload->base.type = PAYLOAD_TYPE_SECURITY;
-    payload->securityData = OICStrdup(securityData);
+    payload->securityData = (uint8_t *)OICCalloc(1, size);
+    if (!payload->securityData)
+    {
+        OICFree(payload);
+        return NULL;
+    }
+    memcpy(payload->securityData, (uint8_t *)securityData, size);
+    payload->payloadSize = size;
 
     return payload;
 }
 
 void OCSecurityPayloadDestroy(OCSecurityPayload* payload)
 {
-    if(!payload)
+    if (!payload)
     {
         return;
     }
@@ -1334,7 +1376,7 @@ OCResourcePayload* OCDiscoveryPayloadGetResource(OCDiscoveryPayload* payload, si
     OCResourcePayload* p = payload->resources;
     while(p)
     {
-        if(i == index)
+        if (i == index)
         {
             return p;
         }
@@ -1347,34 +1389,34 @@ OCResourcePayload* OCDiscoveryPayloadGetResource(OCDiscoveryPayload* payload, si
 static OCResourcePayload* OCCopyResource(const OCResource* res, uint16_t port)
 {
     OCResourcePayload* pl = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
-    if(!pl)
+    if (!pl)
     {
         return NULL;
     }
 
     pl->uri = OICStrdup(res->uri);
 
-    if(!pl->uri)
+    if (!pl->uri)
     {
-        FreeOCDiscoveryResource(pl);
+        OCDiscoveryResourceDestroy(pl);
         return NULL;
     }
 
     // types
     OCResourceType* typePtr = res->rsrcType;
 
-    if(typePtr != NULL)
+    if (typePtr != NULL)
     {
         pl->types = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
-        if(!pl->types)
+        if (!pl->types)
         {
-            FreeOCDiscoveryResource(pl);
+            OCDiscoveryResourceDestroy(pl);
             return NULL;
         }
         pl->types->value = OICStrdup(typePtr->resourcetypename);
-        if(!pl->types->value)
+        if (!pl->types->value)
         {
-            FreeOCDiscoveryResource(pl);
+            OCDiscoveryResourceDestroy(pl);
             return NULL;
         }
 
@@ -1383,15 +1425,15 @@ static OCResourcePayload* OCCopyResource(const OCResource* res, uint16_t port)
         while(typePtr)
         {
             cur->next = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
-            if(!cur->next)
+            if (!cur->next)
             {
-                FreeOCDiscoveryResource(pl);
+                OCDiscoveryResourceDestroy(pl);
                 return NULL;
             }
             cur->next->value = OICStrdup(typePtr->resourcetypename);
-            if(!cur->next->value)
+            if (!cur->next->value)
             {
-                FreeOCDiscoveryResource(pl);
+                OCDiscoveryResourceDestroy(pl);
                 return NULL;
             }
             cur = cur->next;
@@ -1401,18 +1443,18 @@ static OCResourcePayload* OCCopyResource(const OCResource* res, uint16_t port)
 
     // interfaces
     OCResourceInterface* ifPtr = res->rsrcInterface;
-    if(ifPtr != NULL)
+    if (ifPtr != NULL)
     {
         pl->interfaces = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
-        if(!pl->interfaces)
+        if (!pl->interfaces)
         {
-            FreeOCDiscoveryResource(pl);
+            OCDiscoveryResourceDestroy(pl);
             return NULL;
         }
         pl->interfaces->value = OICStrdup(ifPtr->name);
-        if(!pl->interfaces->value)
+        if (!pl->interfaces->value)
         {
-            FreeOCDiscoveryResource(pl);
+            OCDiscoveryResourceDestroy(pl);
             return NULL;
         }
 
@@ -1421,15 +1463,15 @@ static OCResourcePayload* OCCopyResource(const OCResource* res, uint16_t port)
         while(ifPtr && cur)
         {
             cur->next = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
-            if(!cur->next)
+            if (!cur->next)
             {
-                FreeOCDiscoveryResource(pl);
+                OCDiscoveryResourceDestroy(pl);
                 return NULL;
             }
             cur->next->value = OICStrdup(ifPtr->name);
-            if(!cur->next->value)
+            if (!cur->next->value)
             {
-                FreeOCDiscoveryResource(pl);
+                OCDiscoveryResourceDestroy(pl);
                 return NULL;
             }
             cur = cur->next;
@@ -1450,107 +1492,44 @@ void OCDiscoveryPayloadAddResource(OCDiscoveryPayload* payload, const OCResource
     OCDiscoveryPayloadAddNewResource(payload, OCCopyResource(res, port));
 }
 
-bool OCResourcePayloadAddResourceType(OCResourcePayload* payload, const char* resourceType)
+bool OCResourcePayloadAddStringLL(OCStringLL **stringLL, const char *value)
 {
-    if (!resourceType)
-    {
-        return false;
-    }
-
-    char* dup = OICStrdup(resourceType);
-
-    if (!dup)
-    {
-        return false;
-    }
+    char *dup = OICStrdup(value);
+    VERIFY_PARAM_NON_NULL(TAG, dup, "Failed copying string");
+    VERIFY_PARAM_NON_NULL(TAG, value, "Invalid Parameters");
 
-    if (!payload->types)
+    if (!*stringLL)
     {
-        payload->types = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
-
-        if (!payload->types)
-        {
-            OICFree(dup);
-            return false;
-        }
-
-        payload->types->value = dup;
+        *stringLL = (OCStringLL *)OICCalloc(1, sizeof(OCStringLL));
+        VERIFY_PARAM_NON_NULL(TAG, *stringLL, "Failed allocating memory");
+        (*stringLL)->value = dup;
         return true;
     }
-
     else
     {
-        OCStringLL* temp = payload->types;
-
+        OCStringLL *temp = *stringLL;
         while(temp->next)
         {
             temp = temp->next;
         }
-
-        temp->next = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
-        if (!temp->next)
-        {
-            OICFree(dup);
-            return false;
-        }
-
+        temp->next = (OCStringLL *)OICCalloc(1, sizeof(OCStringLL));
+        VERIFY_PARAM_NON_NULL(TAG, temp->next, "Failed allocating memory");
         temp->next->value = dup;
         return true;
     }
+exit:
+    OICFree(dup);
+    return false;
 }
 
-bool OCResourcePayloadAddInterface(OCResourcePayload* payload, const char* interface)
+void OCDiscoveryPayloadAddNewResource(OCDiscoveryPayload* payload, OCResourcePayload* res)
 {
-    if (!interface)
-    {
-        return false;
-    }
-
-    char* dup = OICStrdup(interface);
-
-    if (!dup)
-    {
-        return false;
-    }
-
-    if (!payload->interfaces)
-    {
-        payload->interfaces = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
-
-        if (!payload->interfaces)
-        {
-            OICFree(dup);
-            return false;
-        }
-
-        payload->interfaces->value = dup;
-        return true;
-    }
-
-    else
+    if (!payload)
     {
-        OCStringLL* temp = payload->interfaces;
-
-        while(temp->next)
-        {
-            temp = temp->next;
-        }
-
-        temp->next = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
-        if (!temp->next)
-        {
-            OICFree(dup);
-            return false;
-        }
-
-        temp->next->value = dup;
-        return true;
+        return;
     }
-}
 
-void OCDiscoveryPayloadAddNewResource(OCDiscoveryPayload* payload, OCResourcePayload* res)
-{
-    if(!payload->resources)
+    if (!payload->resources)
     {
         payload->resources = res;
     }
@@ -1565,9 +1544,9 @@ void OCDiscoveryPayloadAddNewResource(OCDiscoveryPayload* payload, OCResourcePay
     }
 }
 
-static void FreeOCDiscoveryResource(OCResourcePayload* payload)
+void OCDiscoveryResourceDestroy(OCResourcePayload* payload)
 {
-    if(!payload)
+    if (!payload)
     {
         return;
     }
@@ -1575,58 +1554,67 @@ static void FreeOCDiscoveryResource(OCResourcePayload* payload)
     OICFree(payload->uri);
     OCFreeOCStringLL(payload->types);
     OCFreeOCStringLL(payload->interfaces);
-    FreeOCDiscoveryResource(payload->next);
+    OCDiscoveryResourceDestroy(payload->next);
     OICFree(payload);
 
 }
 void OCDiscoveryPayloadDestroy(OCDiscoveryPayload* payload)
 {
-    if(!payload)
+    if (!payload)
     {
         return;
     }
     OICFree(payload->sid);
-    FreeOCDiscoveryResource(payload->resources);
+    OICFree(payload->baseURI);
+    OICFree(payload->uri);
+    OICFree(payload->type);
+    OICFree(payload->name);
+    OCFreeOCStringLL(payload->interface);
+    OCDiscoveryResourceDestroy(payload->resources);
     OICFree(payload);
 }
 
-OCDevicePayload* OCDevicePayloadCreate(const uint8_t* sid, const char* dname,
-        const char* specVer, const char* dmVer)
+OCDevicePayload* OCDevicePayloadCreate(const char* sid, const char* dname,
+        const OCStringLL *types, const char* specVer, const char* dmVer)
 {
 
     OCDevicePayload* payload = (OCDevicePayload*)OICCalloc(1, sizeof(OCDevicePayload));
 
-    if(!payload)
+    if (!payload)
     {
         return NULL;
     }
 
     payload->base.type = PAYLOAD_TYPE_DEVICE;
-
-    if(sid)
+    payload->sid = OICStrdup(sid);
+    if (sid && !payload->sid)
     {
-        payload->sid = (uint8_t*)OICMalloc(UUID_SIZE);
-        if(!payload->sid)
-        {
-            goto exit;
-        }
-        memcpy(payload->sid, sid, UUID_SIZE);
+        goto exit;
     }
 
     payload->deviceName = OICStrdup(dname);
-    if(dname && !payload->deviceName)
+    if (dname && !payload->deviceName)
     {
         goto exit;
     }
 
     payload->specVersion = OICStrdup(specVer);
-    if(specVer && !payload->specVersion)
+    if (specVer && !payload->specVersion)
     {
         goto exit;
     }
 
     payload->dataModelVersion = OICStrdup(dmVer);
-    if(dmVer && !payload->dataModelVersion)
+    if (dmVer && !payload->dataModelVersion)
+    {
+        goto exit;
+    }
+
+    OCResourcePayloadAddStringLL(&payload->interfaces, OC_RSRVD_INTERFACE_DEFAULT);
+    OCResourcePayloadAddStringLL(&payload->interfaces, OC_RSRVD_INTERFACE_READ);
+
+    payload->types = CloneOCStringLL((OCStringLL *)types);
+    if (types && !payload->types)
     {
         goto exit;
     }
@@ -1640,7 +1628,7 @@ exit:
 
 void OCDevicePayloadDestroy(OCDevicePayload* payload)
 {
-    if(!payload)
+    if (!payload)
     {
         return;
     }
@@ -1649,12 +1637,14 @@ void OCDevicePayloadDestroy(OCDevicePayload* payload)
     OICFree(payload->deviceName);
     OICFree(payload->specVersion);
     OICFree(payload->dataModelVersion);
+    OCFreeOCStringLL(payload->types);
+    OCFreeOCStringLL(payload->interfaces);
     OICFree(payload);
 }
 
 static void OCCopyPlatformInfo(const OCPlatformInfo* platformInfo, OCPlatformPayload* target)
 {
-    if(!platformInfo || !target)
+    if (!platformInfo || !target)
     {
         return;
     }
@@ -1675,12 +1665,13 @@ static void OCCopyPlatformInfo(const OCPlatformInfo* platformInfo, OCPlatformPay
 OCPlatformPayload* OCPlatformPayloadCreateAsOwner(OCPlatformInfo* platformInfo)
 {
     OCPlatformPayload* payload = (OCPlatformPayload*)OICCalloc(1, sizeof(OCPlatformPayload));
-    if(!payload)
+    if (!payload)
     {
         return NULL;
     }
 
     payload->base.type = PAYLOAD_TYPE_PLATFORM;
+
     payload->info = *platformInfo;
 
     return payload;
@@ -1690,35 +1681,47 @@ OCPlatformPayload* OCPlatformPayloadCreate(const OCPlatformInfo* platformInfo)
 {
     OCPlatformPayload* payload = (OCPlatformPayload*)OICCalloc(1, sizeof(OCPlatformPayload));
 
-    if(!payload)
+    if (!payload)
     {
         return NULL;
     }
 
     payload->base.type = PAYLOAD_TYPE_PLATFORM;
+
+    OCResourcePayloadAddStringLL(&payload->interfaces, OC_RSRVD_INTERFACE_DEFAULT);
+    OCResourcePayloadAddStringLL(&payload->interfaces, OC_RSRVD_INTERFACE_READ);
+
+    payload->rt = OICStrdup(OC_RSRVD_RESOURCE_TYPE_PLATFORM);
     OCCopyPlatformInfo(platformInfo, payload);
 
     return payload;
 }
 
+void OCPlatformInfoDestroy(OCPlatformInfo *info)
+{
+    OICFree(info->platformID);
+    OICFree(info->manufacturerName);
+    OICFree(info->manufacturerUrl);
+    OICFree(info->modelNumber);
+    OICFree(info->dateOfManufacture);
+    OICFree(info->platformVersion);
+    OICFree(info->operatingSystemVersion);
+    OICFree(info->hardwareVersion);
+    OICFree(info->firmwareVersion);
+    OICFree(info->supportUrl);
+    OICFree(info->systemTime);
+}
+
 void OCPlatformPayloadDestroy(OCPlatformPayload* payload)
 {
-    if(!payload)
+    if (!payload)
     {
         return;
     }
     OICFree(payload->uri);
-    OICFree(payload->info.platformID);
-    OICFree(payload->info.manufacturerName);
-    OICFree(payload->info.manufacturerUrl);
-    OICFree(payload->info.modelNumber);
-    OICFree(payload->info.dateOfManufacture);
-    OICFree(payload->info.platformVersion);
-    OICFree(payload->info.operatingSystemVersion);
-    OICFree(payload->info.hardwareVersion);
-    OICFree(payload->info.firmwareVersion);
-    OICFree(payload->info.supportUrl);
-    OICFree(payload->info.systemTime);
+    OCPlatformInfoDestroy(&payload->info);
+    OICFree(payload->rt);
+    OCFreeOCStringLL(payload->interfaces);
     OICFree(payload);
 }
 
@@ -1726,7 +1729,7 @@ OCPresencePayload* OCPresencePayloadCreate(uint32_t seqNum, uint32_t maxAge,
         OCPresenceTrigger trigger, const char* resourceType)
 {
     OCPresencePayload* payload = (OCPresencePayload*)OICCalloc(1, sizeof(OCPresencePayload));
-    if(!payload)
+    if (!payload)
     {
         return NULL;
     }
@@ -1741,7 +1744,7 @@ OCPresencePayload* OCPresencePayloadCreate(uint32_t seqNum, uint32_t maxAge,
 
 void OCPresencePayloadDestroy(OCPresencePayload* payload)
 {
-    if(!payload)
+    if (!payload)
     {
         return;
     }
index a2035cf..9f1bde6 100644 (file)
 #include "cbor.h"
 #include "rdpayload.h"
 
-#define TAG "OCPayloadConvert"
+#define TAG "OIC_RI_PAYLOADCONVERT"
+
 // Arbitrarily chosen size that seems to contain the majority of packages
 #define INIT_SIZE (255)
 
-// CBOR Array Length
-#define DISCOVERY_CBOR_ARRAY_LEN 1
-// CBOR Res Map Length
-#define DISCOVERY_CBOR_RES_MAP_LEN 2
-// CBOR Links Map Length
-#define DISCOVERY_CBOR_LINKS_MAP_LEN 4
+// Discovery Links Map Length.
+#define LINKS_MAP_LEN 4
 
 // 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,
-        size_t* size);
-static int64_t OCConvertDevicePayload(OCDevicePayload* payload, uint8_t* outPayload,
-        size_t* size);
-static int64_t OCConvertPlatformPayload(OCPlatformPayload* payload, uint8_t* outPayload,
-        size_t* size);
-static int64_t OCConvertRepPayload(OCRepPayload* payload, uint8_t* outPayload, size_t* size);
-static int64_t OCConvertRepMap(CborEncoder *map, const OCRepPayload* payload);
-static int64_t OCConvertPresencePayload(OCPresencePayload* payload, uint8_t* outPayload,
-        size_t* size);
-static int64_t OCConvertSecurityPayload(OCSecurityPayload* payload, uint8_t* outPayload,
-        size_t* size);
-static int64_t OCConvertSingleRepPayload(CborEncoder* parent, const OCRepPayload* payload);
-static int64_t OCConvertArray(CborEncoder* parent, const OCRepPayloadValueArray* valArray);
-
-static int64_t AddTextStringToMap(CborEncoder* map, const char* key, size_t keylen,
-        const char* value);
-
-static int64_t ConditionalAddTextStringToMap(CborEncoder* map, const char* key, size_t keylen,
-        const char* value);
+static int64_t OCConvertPayloadHelper(OCPayload *payload, uint8_t *outPayload, size_t *size);
+static int64_t OCConvertDiscoveryPayload(OCDiscoveryPayload *payload, uint8_t *outPayload,
+        size_t *size);
+static int64_t OCConvertDevicePayload(OCDevicePayload *payload, uint8_t *outPayload,
+        size_t *size);
+static int64_t OCConvertPlatformPayload(OCPlatformPayload *payload, uint8_t *outPayload,
+        size_t *size);
+static int64_t OCConvertRepPayload(OCRepPayload *payload, uint8_t *outPayload, size_t *size);
+static int64_t OCConvertRepMap(CborEncoder *map, const OCRepPayload *payload);
+static int64_t OCConvertPresencePayload(OCPresencePayload *payload, uint8_t *outPayload,
+        size_t *size);
+static int64_t OCConvertSecurityPayload(OCSecurityPayload *payload, uint8_t *outPayload,
+        size_t *size);
+static int64_t OCConvertSingleRepPayload(CborEncoder *parent, const OCRepPayload *payload);
+static int64_t OCConvertArray(CborEncoder *parent, const OCRepPayloadValueArray *valArray);
+
+static int64_t AddTextStringToMap(CborEncoder *map, const char *key, size_t keylen,
+        const char *value);
+static int64_t ConditionalAddTextStringToMap(CborEncoder *map, const char *key, size_t keylen,
+        const char *value);
 
 OCStackResult OCConvertPayload(OCPayload* payload, uint8_t** outPayload, size_t* size)
 {
@@ -72,66 +68,72 @@ OCStackResult OCConvertPayload(OCPayload* payload, uint8_t** outPayload, size_t*
     #define CborNeedsUpdating  (CborErrorOutOfMemory < CborErrorDataTooLarge)
     OC_STATIC_ASSERT(!CborNeedsUpdating, "tinycbor needs to be updated to at least 47a78569c0");
     #undef CborNeedsUpdating
-    if (!payload)
+
+    OCStackResult ret = OC_STACK_INVALID_PARAM;
+    int64_t err;
+    uint8_t *out = NULL;
+    size_t curSize = INIT_SIZE;
+
+    VERIFY_PARAM_NON_NULL(TAG, payload, "Input param, payload is NULL");
+    VERIFY_PARAM_NON_NULL(TAG, outPayload, "OutPayload parameter is NULL");
+    VERIFY_PARAM_NON_NULL(TAG, size, "size parameter is NULL");
+
+    OIC_LOG_V(INFO, TAG, "Converting payload of type %d", payload->type);
+    if (PAYLOAD_TYPE_SECURITY == payload->type)
     {
-        OC_LOG(ERROR, TAG, "Payload parameter NULL");
-        return OC_STACK_INVALID_PARAM;
+        size_t securityPayloadSize = ((OCSecurityPayload *)payload)->payloadSize;
+        if (securityPayloadSize > 0)
+        {
+            out = (uint8_t *)OICCalloc(1, ((OCSecurityPayload *)payload)->payloadSize);
+            VERIFY_PARAM_NON_NULL(TAG, out, "Failed to allocate security payload");
+        }
     }
-
-    if (!outPayload || !size)
+    if (out == NULL)
     {
-        OC_LOG(ERROR, TAG, "Out parameter/s parameter NULL");
-        return OC_STACK_INVALID_PARAM;
+        out = (uint8_t *)OICCalloc(1, curSize);
+        VERIFY_PARAM_NON_NULL(TAG, out, "Failed to allocate payload");
     }
-
-    OC_LOG_V(INFO, TAG, "Converting payload of type %d", payload->type);
-
-    size_t curSize = INIT_SIZE;
-    uint8_t* out = (uint8_t*)OICCalloc(1, curSize);
-    int64_t err = OCConvertPayloadHelper(payload, out, &curSize);
+    err = OCConvertPayloadHelper(payload, out, &curSize);
+    ret = OC_STACK_NO_MEMORY;
 
     if (err == CborErrorOutOfMemory)
     {
         // reallocate "out" and try again!
-        uint8_t* out2 = (uint8_t*)OICRealloc(out, curSize);
-
-        if (!out2)
-        {
-            OICFree(out);
-            return OC_STACK_NO_MEMORY;
-        }
-
+        uint8_t *out2 = (uint8_t *)OICRealloc(out, curSize);
+        VERIFY_PARAM_NON_NULL(TAG, out2, "Failed to increase payload size");
         out = out2;
         err = OCConvertPayloadHelper(payload, out, &curSize);
+        while (err == CborErrorOutOfMemory)
+        {
+            uint8_t *out2 = (uint8_t *)OICRealloc(out, curSize);
+            VERIFY_PARAM_NON_NULL(TAG, out2, "Failed to increase payload size");
+            out = out2;
+            err = OCConvertPayloadHelper(payload, out, &curSize);
+        }
     }
 
-    if (err == 0)
+    if (err == CborNoError)
     {
-        if (curSize < INIT_SIZE)
+        if (curSize < INIT_SIZE && PAYLOAD_TYPE_SECURITY != payload->type)
         {
-            uint8_t* out2 = (uint8_t*)OICRealloc(out, curSize);
-
-            if (!out2)
-            {
-                OICFree(out);
-                return OC_STACK_NO_MEMORY;
-            }
-
+            uint8_t *out2 = (uint8_t *)OICRealloc(out, curSize);
+            VERIFY_PARAM_NON_NULL(TAG, out2, "Failed to increase payload size");
             out = out2;
         }
 
         *size = curSize;
         *outPayload = out;
+        OIC_LOG_V(DEBUG, TAG, "Payload Size: %zd Payload : ", *size);
+        OIC_LOG_BUFFER(DEBUG, TAG, *outPayload, *size);
         return OC_STACK_OK;
     }
-    else if (err < 0)
-    {
-        return (OCStackResult)-err;
-    }
-    else
-    {
-        return OC_STACK_ERROR;
-    }
+
+    //TODO: Proper conversion from CborError to OCStackResult.
+    ret = (OCStackResult)-err;
+
+exit:
+    OICFree(out);
+    return ret;
 }
 
 static int64_t OCConvertPayloadHelper(OCPayload* payload, uint8_t* outPayload, size_t* size)
@@ -153,8 +155,8 @@ static int64_t OCConvertPayloadHelper(OCPayload* payload, uint8_t* outPayload, s
         case PAYLOAD_TYPE_RD:
             return OCRDPayloadToCbor((OCRDPayload*)payload, outPayload, size);
         default:
-            OC_LOG_V(INFO,TAG, "ConvertPayload default %d", payload->type);
-            return OC_STACK_NOTIMPL;
+            OIC_LOG_V(INFO,TAG, "ConvertPayload default %d", payload->type);
+            return CborErrorUnknownType;
     }
 }
 
@@ -165,123 +167,61 @@ static int64_t checkError(int64_t err, CborEncoder* encoder, uint8_t* outPayload
         *size += encoder->ptr - encoder->end;
         return err;
     }
-    else if (err != 0)
+    else if (err != CborNoError)
     {
-        OC_LOG_V(ERROR, TAG, "Convert Payload failed", err);
+        OIC_LOG_V(ERROR, TAG, "Convert Payload failed : %s", cbor_error_string(err));
         return err;
     }
     else
     {
         *size = encoder->ptr - outPayload;
-        return 0;
+        return err;
     }
 }
+
 static int64_t OCConvertSecurityPayload(OCSecurityPayload* payload, uint8_t* outPayload,
         size_t* size)
 {
-    CborEncoder encoder;
-    int64_t err = 0;
-
-    cbor_encoder_init(&encoder, outPayload, *size, 0);
-
-    CborEncoder map;
-
-    err = err | cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength);
-
-    if(payload->securityData)
-    {
-        err = err | cbor_encode_text_string(&map, payload->securityData,
-                                            strlen(payload->securityData));
-    }
-
-    err = err | cbor_encoder_close_container(&encoder, &map);
-    return checkError(err, &encoder, outPayload, size);
+    memcpy(outPayload, payload->securityData, payload->payloadSize);
+    *size = payload->payloadSize;
 
+    return CborNoError;
 }
 
-static char* OCStringLLJoin(OCStringLL* val)
+static int64_t OCStringLLJoin(CborEncoder *map, char *type, OCStringLL *val)
 {
-    OCStringLL* temp = val;
-    size_t size = strlen(temp->value);
+    uint16_t count = 0;
+    int64_t err = CborNoError;
 
-    while (temp->next)
+    for (OCStringLL *temp = val; temp; temp = temp->next)
     {
-        ++size;
-        temp = temp->next;
-        size += strlen(temp->value);
+        ++count;
     }
-
-    char* joinedStr = (char*)OICCalloc(sizeof(char), size + 1);
-
-    if (!joinedStr)
+    if (count > 0)
     {
-        return NULL;
+        CborEncoder array;
+        err |= cbor_encode_text_string(map, type, strlen(type));
+        err |= cbor_encoder_create_array(map, &array, count);
+        while (val)
+        {
+            err |= cbor_encode_text_string(&array, val->value, strlen(val->value));
+            val = val->next;
+        }
+        err |= cbor_encoder_close_container(map, &array);
     }
 
-    OICStrcat(joinedStr, size + 1, val->value);
-    while (val->next)
-    {
-        val = val->next;
-        OICStrcat(joinedStr, size + 1, " ");
-        OICStrcat(joinedStr, size + 1, val->value);
-    }
-    return joinedStr;
+    return err;
 }
 
-static int64_t OCConvertDiscoveryPayload(OCDiscoveryPayload* payload, uint8_t* outPayload,
-        size_tsize)
+static int64_t OCConvertDiscoveryPayload(OCDiscoveryPayload *payload, uint8_t *outPayload,
+        size_t *size)
 {
-    CborEncoder encoder = {0};
-    CborEncoder rootArray = {0};
-    int64_t err = 0;
+    CborEncoder encoder;
+    int64_t err = CborNoError;
 
     cbor_encoder_init(&encoder, outPayload, *size, 0);
 
-    if (payload->collectionResources)
-    {
-        CborError cborEncoderResult;
-        cborEncoderResult = cbor_encoder_create_array(&encoder, &rootArray, DISCOVERY_CBOR_ARRAY_LEN);
-        if (CborNoError != cborEncoderResult)
-        {
-            OC_LOG(ERROR, TAG, "Failed creating root array.");
-            goto cbor_error;
-        }
-
-        CborEncoder colArray;
-        cborEncoderResult = cbor_encoder_create_array(&rootArray, &colArray, CborIndefiniteLength);
-        if (CborNoError != cborEncoderResult)
-        {
-            OC_LOG(ERROR, TAG, "Failed creating collection array.");
-            goto cbor_error;
-        }
-
-        OCResourceCollectionPayload *colResources = payload->collectionResources;
-        while (colResources)
-        {
-            if (OC_STACK_OK != OCTagsPayloadToCbor(colResources->tags, &colArray))
-            {
-                goto cbor_error;
-            }
-            if (OC_STACK_OK != OCLinksPayloadToCbor(colResources->setLinks, &colArray))
-            {
-                goto cbor_error;
-            }
-            colResources = colResources->next;
-        }
-        cborEncoderResult = cbor_encoder_close_container(&rootArray, &colArray);
-        if (CborNoError != cborEncoderResult)
-        {
-            OC_LOG(ERROR, TAG, "Failed closing collection array.");
-            goto cbor_error;
-        }
-        cborEncoderResult = cbor_encoder_close_container(&encoder, &rootArray);
-        if (CborNoError != cborEncoderResult)
-        {
-            OC_LOG(ERROR, TAG, "Failed closing root array.");
-            goto cbor_error;
-        }
-    }
-    else if (payload->resources)
+    if (payload->resources)
     {
         /*
         The format for the payload is "modelled" as JSON.
@@ -289,6 +229,11 @@ static int64_t OCConvertDiscoveryPayload(OCDiscoveryPayload* payload, uint8_t* o
         [                                                       // rootArray
             {                                                   // rootMap
                 "di" : UUID,                                    // device ID
+                "href": "/oic/res"
+                "rt": "oic.wk.res"
+                "n":"MyDevice"
+                "if":"oic.if.ll oic.if.baseline"
+                "di": "0685B960-736F-46F7-BEC0-9E6CBD61ADC1",
                 links :[                                        // linksArray contains maps of resources
                             {
                                 href, rt, if, policy            // Resource 1
@@ -303,408 +248,467 @@ static int64_t OCConvertDiscoveryPayload(OCDiscoveryPayload* payload, uint8_t* o
             }
         ]
         */
-        CborEncoder rootMap = {};
-        size_t resourceCount =  OCDiscoveryPayloadGetResourceCount(payload);
-
         // Open the main root array
-        err = err | cbor_encoder_create_array(&encoder, &rootArray, 1);
+        CborEncoder rootArray;
+        size_t resourceCount =  OCDiscoveryPayloadGetResourceCount(payload);
+        err |= cbor_encoder_create_array(&encoder, &rootArray, 1);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed creating discovery root array");
 
         // Open the root map in the root array
-        err = err | cbor_encoder_create_map(&rootArray, &rootMap, DISCOVERY_CBOR_RES_MAP_LEN);
+        CborEncoder rootMap;
+        err |= cbor_encoder_create_map(&rootArray, &rootMap, CborIndefiniteLength);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed creating discovery map");
+
+        // Insert Name
+        err |= ConditionalAddTextStringToMap(&rootMap, OC_RSRVD_DEVICE_NAME,
+                sizeof(OC_RSRVD_DEVICE_NAME) - 1, payload->name);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting name");
+
+        // Insert URI
+        err |= ConditionalAddTextStringToMap(&rootMap, OC_RSRVD_HREF, sizeof(OC_RSRVD_HREF) - 1,
+                payload->uri);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting href");
 
         // Insert Device ID into the root map
-        err = err | cbor_encode_text_string(&rootMap, OC_RSRVD_DEVICE_ID,
-                sizeof(OC_RSRVD_DEVICE_ID) - 1);
-        err = err | cbor_encode_byte_string(&rootMap, payload->sid, UUID_SIZE);
+        err |= AddTextStringToMap(&rootMap, OC_RSRVD_DEVICE_ID, sizeof(OC_RSRVD_DEVICE_ID) - 1,
+                payload->sid);
+        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);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting RT");
 
+        // Insert interfaces
+        if (payload->interface)
+        {
+            err |= OCStringLLJoin(&rootMap, OC_RSRVD_INTERFACE, payload->interface);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding interface types tag/value");
+        }
+
+        // Insert baseURI if present
+        err |= ConditionalAddTextStringToMap(&rootMap, OC_RSRVD_BASE_URI,
+                                            sizeof(OC_RSRVD_BASE_URI) - 1,
+                                            payload->baseURI);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting baseURI");
 
         // Insert Links into the root map.
-        CborEncoder linkArray = {};
-        err = err | cbor_encode_text_string(&rootMap, OC_RSRVD_LINKS,
-                    sizeof(OC_RSRVD_LINKS) - 1);
-        err = err | cbor_encoder_create_array(&rootMap, &linkArray, resourceCount);
+        CborEncoder linkArray;
+        err |= cbor_encode_text_string(&rootMap, OC_RSRVD_LINKS, sizeof(OC_RSRVD_LINKS) - 1);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting links array tag");
+        err |= cbor_encoder_create_array(&rootMap, &linkArray, resourceCount);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting links array");
 
         for(size_t i = 0; i < resourceCount; ++i)
         {
-            CborEncoder resourceMapElement = {};
-            OCResourcePayload* resource = OCDiscoveryPayloadGetResource(payload, i);
-            if(!resource)
-            {
-                OICFree(outPayload);
-                return OC_STACK_INVALID_PARAM;
-            }
+            CborEncoder linkMap;
+            OCResourcePayload *resource = OCDiscoveryPayloadGetResource(payload, i);
+            VERIFY_PARAM_NON_NULL(TAG, resource, "Failed retrieving resource");
 
             // resource map inside the links array.
-            err = err | cbor_encoder_create_map(&linkArray, &resourceMapElement,
-                DISCOVERY_CBOR_LINKS_MAP_LEN);
+            err |= cbor_encoder_create_map(&linkArray, &linkMap, LINKS_MAP_LEN);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed creating links map");
 
             // Below are insertions of the resource properties into the map.
             // Uri
-            err = err | AddTextStringToMap(&resourceMapElement, OC_RSRVD_HREF,
-                        sizeof(OC_RSRVD_HREF) - 1,
-                        resource->uri);
+            err |= AddTextStringToMap(&linkMap, OC_RSRVD_HREF, sizeof(OC_RSRVD_HREF) - 1,
+                    resource->uri);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding uri to links map");
+
             // Resource Type
             if (resource->types)
             {
-                char* joinedTypes = OCStringLLJoin(resource->types);
-                if (joinedTypes)
-                {
-                    err = err | cbor_encode_text_string(&resourceMapElement, OC_RSRVD_RESOURCE_TYPE,
-                            sizeof(OC_RSRVD_RESOURCE_TYPE) - 1);
-                    err = err | cbor_encode_text_string(&resourceMapElement, joinedTypes,
-                            strlen(joinedTypes));
-                    OICFree(joinedTypes);
-                }
-                else
-                {
-                    return OC_STACK_NO_MEMORY;
-                }
+                err |= OCStringLLJoin(&linkMap, OC_RSRVD_RESOURCE_TYPE, resource->types);
+                VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding resourceType tag/value to links map");
             }
             // Interface Types
             if (resource->interfaces)
             {
-                char* joinedInterfaces = OCStringLLJoin(resource->interfaces);
-                if (joinedInterfaces)
-                {
-                    err = err | cbor_encode_text_string(&resourceMapElement, OC_RSRVD_INTERFACE,
-                            sizeof(OC_RSRVD_INTERFACE) - 1);
-                    err = err | cbor_encode_text_string(&resourceMapElement, joinedInterfaces,
-                            strlen(joinedInterfaces));
-                    OICFree(joinedInterfaces);
-                }
-                else
-                {
-                    return OC_STACK_NO_MEMORY;
-                }
+                err |= OCStringLLJoin(&linkMap, OC_RSRVD_INTERFACE, resource->interfaces);
+                VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding interfaces tag/value to links map");
             }
 
             // Policy
             CborEncoder policyMap;
-            err = err | cbor_encode_text_string(&resourceMapElement, OC_RSRVD_POLICY,
-                    sizeof(OC_RSRVD_POLICY) - 1);
-            err = err | cbor_encoder_create_map(&resourceMapElement, &policyMap, CborIndefiniteLength);
+            err |= cbor_encode_text_string(&linkMap, OC_RSRVD_POLICY, sizeof(OC_RSRVD_POLICY) - 1);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding policy tag to links map");
+            err |= cbor_encoder_create_map(&linkMap, &policyMap, CborIndefiniteLength);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding policy map to links map");
 
             // Bitmap
-            err = err | cbor_encode_text_string(&policyMap, OC_RSRVD_BITMAP,
-                    sizeof(OC_RSRVD_BITMAP) - 1);
-            err = err | cbor_encode_uint(&policyMap, resource->bitmap);
+            err |=  cbor_encode_text_string(&policyMap, OC_RSRVD_BITMAP, sizeof(OC_RSRVD_BITMAP) - 1);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding bitmap tag to policy map");
+            err |= cbor_encode_uint(&policyMap, resource->bitmap);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding bitmap value to policy map");
 
-            if(resource->secure)
+            if (resource->secure)
             {
-                err = err | cbor_encode_text_string(&policyMap, OC_RSRVD_SECURE,
+                err |= cbor_encode_text_string(&policyMap, OC_RSRVD_SECURE,
                         sizeof(OC_RSRVD_SECURE) - 1);
-                err = err | cbor_encode_boolean(&policyMap, OC_RESOURCE_SECURE);
-
-                if(resource->port != 0)
-                {
-                    err = err | cbor_encode_text_string(&policyMap, OC_RSRVD_HOSTING_PORT,
-                            sizeof(OC_RSRVD_HOSTING_PORT) - 1);
-                    err = err | cbor_encode_uint(&policyMap, resource->port);
-                }
+                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)
+            {
+                err |= cbor_encode_text_string(&policyMap, OC_RSRVD_HOSTING_PORT,
+                        sizeof(OC_RSRVD_HOSTING_PORT) - 1);
+                VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding secure port tag");
+                err |= cbor_encode_uint(&policyMap, resource->port);
+                VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding secure port value");
             }
 
-            err = err | cbor_encoder_close_container(&resourceMapElement, &policyMap);
+            err |= cbor_encoder_close_container(&linkMap, &policyMap);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed closing policy map");
 
             // Finsihed encoding a resource, close the map.
-            err = err | cbor_encoder_close_container(&linkArray, &resourceMapElement);
+            err |= cbor_encoder_close_container(&linkArray, &linkMap);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed closing link map");
         }
         // Close links array inside the root map.
-        err = err | cbor_encoder_close_container(&rootMap, &linkArray);
+        err |= cbor_encoder_close_container(&rootMap, &linkArray);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed closing link array");
         // close root map inside the root array.
-        err = err | cbor_encoder_close_container(&rootArray, &rootMap);
+        err |= cbor_encoder_close_container(&rootArray, &rootMap);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed closing root map");
         // Close the final root array.
-        err = err | cbor_encoder_close_container(&encoder, &rootArray);
+        err |= cbor_encoder_close_container(&encoder, &rootArray);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed closing root array");
     }
 
+exit:
     return checkError(err, &encoder, outPayload, size);
-cbor_error:
-    OICFree(outPayload);
-    return OC_STACK_ERROR;
 }
 
-static int64_t OCConvertDevicePayload(OCDevicePayload* payload, uint8_t* outPayload,
-        size_tsize)
+static int64_t OCConvertDevicePayload(OCDevicePayload *payload, uint8_t *outPayload,
+        size_t *size)
 {
-    CborEncoder encoder = {0};
-    int64_t err = 0;
+    if (!payload)
+    {
+        return CborUnknownError;
+    }
+    int64_t err = CborNoError;
+    CborEncoder encoder;
 
     cbor_encoder_init(&encoder, outPayload, *size, 0);
     CborEncoder repMap;
-    err = err | cbor_encoder_create_map(&encoder, &repMap, CborIndefiniteLength);
+    err |= cbor_encoder_create_map(&encoder, &repMap, CborIndefiniteLength);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed creating device map");
+
+    // Resource Type
+    if (payload->types)
+    {
+        OIC_LOG(INFO, TAG, "Payload has types");
+        err |= OCStringLLJoin(&repMap, OC_RSRVD_RESOURCE_TYPE, payload->types);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding resource type tag/value.");
+    }
+
+    if (payload->interfaces)
+    {
+        OIC_LOG(INFO, TAG, "Payload has interface");
+        err |= OCStringLLJoin(&repMap, OC_RSRVD_INTERFACE, payload->interfaces);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding interface type tag/value.");
+    }
 
     // Device ID
-    err = err | cbor_encode_text_string(&repMap, OC_RSRVD_DEVICE_ID,
-            sizeof(OC_RSRVD_DEVICE_ID) - 1);
-    err = err | cbor_encode_byte_string(&repMap, payload->sid, UUID_SIZE);
+    err |= AddTextStringToMap(&repMap, OC_RSRVD_DEVICE_ID, sizeof(OC_RSRVD_DEVICE_ID) - 1 , payload->sid);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding device id");
 
     // Device Name
-    err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_DEVICE_NAME,
-            sizeof(OC_RSRVD_DEVICE_NAME) - 1,
-            payload->deviceName);
+    err |= ConditionalAddTextStringToMap(&repMap, OC_RSRVD_DEVICE_NAME,
+            sizeof(OC_RSRVD_DEVICE_NAME) - 1, payload->deviceName);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding device name");
 
     // Device Spec Version
-    err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_SPEC_VERSION,
-            sizeof(OC_RSRVD_SPEC_VERSION) - 1,
-            payload->specVersion);
+    err |= ConditionalAddTextStringToMap(&repMap, OC_RSRVD_SPEC_VERSION,
+            sizeof(OC_RSRVD_SPEC_VERSION) - 1, payload->specVersion);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding data spec version");
 
     // Device data Model Version
-    err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_DATA_MODEL_VERSION,
-            sizeof(OC_RSRVD_DATA_MODEL_VERSION) - 1,
-            payload->dataModelVersion);
+    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");
 
-    err = err | cbor_encoder_close_container(&encoder, &repMap);
+    err |= cbor_encoder_close_container(&encoder, &repMap);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed closing device map");
 
+exit:
     return checkError(err, &encoder, outPayload, size);
 }
 
-static int64_t OCConvertPlatformPayload(OCPlatformPayload* payload, uint8_t* outPayload,
-        size_tsize)
+static int64_t OCConvertPlatformPayload(OCPlatformPayload *payload, uint8_t *outPayload,
+        size_t *size)
 {
-    CborEncoder encoder = {0};
-    int64_t err = 0;
+    int64_t err = CborNoError;
+    CborEncoder encoder;
 
     cbor_encoder_init(&encoder, outPayload, *size, 0);
+
+    CborEncoder repMap;
+    err |= cbor_encoder_create_map(&encoder, &repMap, CborIndefiniteLength);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed creating platform map");
+
+    // Platform ID
+    err |= ConditionalAddTextStringToMap(&repMap, OC_RSRVD_PLATFORM_ID,
+            sizeof(OC_RSRVD_PLATFORM_ID) - 1, payload->info.platformID);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding platform id");
+
+    // MFG Name
+    err |= ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MFG_NAME,
+        sizeof(OC_RSRVD_MFG_NAME) - 1, payload->info.manufacturerName);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding mfg name");
+
+    // MFG Url
+    err |= ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MFG_URL,
+        sizeof(OC_RSRVD_MFG_URL) - 1, payload->info.manufacturerUrl);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding mfg url");
+
+    // Model Num
+    err |= ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MODEL_NUM,
+            sizeof(OC_RSRVD_MODEL_NUM) -1, payload->info.modelNumber);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding model num");
+
+    // Date of Mfg
+    err |= ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MFG_DATE,
+            sizeof(OC_RSRVD_MFG_DATE) - 1, payload->info.dateOfManufacture);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding mfg date");
+
+    // Platform Version
+    err |= ConditionalAddTextStringToMap(&repMap, OC_RSRVD_PLATFORM_VERSION,
+            sizeof(OC_RSRVD_PLATFORM_VERSION) - 1, payload->info.platformVersion);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding platform version");
+
+    // OS Version
+    err |= ConditionalAddTextStringToMap(&repMap, OC_RSRVD_OS_VERSION,
+            sizeof(OC_RSRVD_OS_VERSION) - 1, payload->info.operatingSystemVersion);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding OS version");
+
+    // Hardware Version
+    err |= ConditionalAddTextStringToMap(&repMap, OC_RSRVD_HARDWARE_VERSION,
+            sizeof(OC_RSRVD_HARDWARE_VERSION) - 1, payload->info.hardwareVersion);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding HW version");
+
+    // Firmware Version
+    err |= ConditionalAddTextStringToMap(&repMap, OC_RSRVD_FIRMWARE_VERSION,
+            sizeof(OC_RSRVD_FIRMWARE_VERSION) - 1, payload->info.firmwareVersion);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding firmware version");
+
+    // Support URL
+    err |= ConditionalAddTextStringToMap(&repMap, OC_RSRVD_SUPPORT_URL,
+            sizeof(OC_RSRVD_SUPPORT_URL) - 1, payload->info.supportUrl);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding support url");
+
+    // System Time
+    err |= ConditionalAddTextStringToMap(&repMap, OC_RSRVD_SYSTEM_TIME,
+            sizeof(OC_RSRVD_SYSTEM_TIME) - 1, payload->info.systemTime);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding system time");
+
+    // Resource type
+    if (payload->rt)
     {
-        CborEncoder repMap;
-        err = err | cbor_encoder_create_map(&encoder, &repMap, CborIndefiniteLength);
-
-        // Platform ID
-        err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_PLATFORM_ID,
-                sizeof(OC_RSRVD_PLATFORM_ID) - 1,
-                payload->info.platformID);
-
-        // MFG Name
-        err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MFG_NAME,
-                sizeof(OC_RSRVD_MFG_NAME) - 1,
-                payload->info.manufacturerName);
-
-        // MFG Url
-        err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MFG_URL,
-                sizeof(OC_RSRVD_MFG_URL) - 1,
-                payload->info.manufacturerUrl);
-
-        // Model Num
-        err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MODEL_NUM,
-                sizeof(OC_RSRVD_MODEL_NUM) - 1,
-                payload->info.modelNumber);
-
-        // Date of Mfg
-        err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MFG_DATE,
-                sizeof(OC_RSRVD_MFG_DATE) - 1,
-                payload->info.dateOfManufacture);
-
-        // Platform Version
-        err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_PLATFORM_VERSION,
-                sizeof(OC_RSRVD_PLATFORM_VERSION) - 1,
-                payload->info.platformVersion);
-
-        // OS Version
-        err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_OS_VERSION,
-                sizeof(OC_RSRVD_OS_VERSION) - 1,
-                payload->info.operatingSystemVersion);
-
-        // Hardware Version
-        err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_HARDWARE_VERSION,
-                sizeof(OC_RSRVD_HARDWARE_VERSION) - 1,
-                payload->info.hardwareVersion);
-
-        // Firmware Version
-        err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_FIRMWARE_VERSION,
-                sizeof(OC_RSRVD_FIRMWARE_VERSION) - 1,
-                payload->info.firmwareVersion);
-
-        // Support URL
-        err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_SUPPORT_URL,
-                sizeof(OC_RSRVD_SUPPORT_URL) - 1,
-                payload->info.supportUrl);
-
-        // System Time
-        err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_SYSTEM_TIME,
-                sizeof(OC_RSRVD_SYSTEM_TIME) - 1,
-                payload->info.systemTime);
-
-        // Close Map
-        err = err | cbor_encoder_close_container(&encoder, &repMap);
+        err |= ConditionalAddTextStringToMap(&repMap, OC_RSRVD_RESOURCE_TYPE,
+                sizeof(OC_RSRVD_RESOURCE_TYPE) - 1, payload->rt);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding resource type.");
     }
 
+    // Resource interfaces
+    if (payload->interfaces)
+    {
+        err |= OCStringLLJoin(&repMap, OC_RSRVD_INTERFACE, payload->interfaces);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding platform interface type.");
+    }
+
+    // Close Map
+    err |= cbor_encoder_close_container(&encoder, &repMap);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed closing rep map");
+
+exit:
     return checkError(err, &encoder, outPayload, size);
 }
 
-static int64_t OCConvertArrayItem(CborEncoder* array, const OCRepPayloadValueArray* valArray,
+static int64_t OCConvertArrayItem(CborEncoder *array, const OCRepPayloadValueArray *valArray,
         size_t index)
 {
-    int64_t err = 0;
+    int64_t err = CborNoError;
     switch (valArray->type)
     {
         case OCREP_PROP_NULL:
-            OC_LOG(ERROR, TAG, "ConvertArray Invalid NULL");
+            OIC_LOG(ERROR, TAG, "ConvertArray Invalid NULL");
             err = CborUnknownError;
             break;
         case OCREP_PROP_INT:
-            err = err | cbor_encode_int(array, valArray->iArray[index]);
+            err |= cbor_encode_int(array, valArray->iArray[index]);
             break;
         case OCREP_PROP_DOUBLE:
-            err = err | cbor_encode_double(array, valArray->dArray[index]);
+            err |= cbor_encode_double(array, valArray->dArray[index]);
             break;
         case OCREP_PROP_BOOL:
-            err = err | cbor_encode_boolean(array, valArray->bArray[index]);
+            err |= cbor_encode_boolean(array, valArray->bArray[index]);
             break;
         case OCREP_PROP_STRING:
             if (!valArray->strArray[index])
             {
-                err = err | cbor_encode_null(array);
+                err |= cbor_encode_null(array);
             }
             else
             {
-                err = err | cbor_encode_text_string(array, valArray->strArray[index],
+                err |= cbor_encode_text_string(array, valArray->strArray[index],
                         strlen(valArray->strArray[index]));
             }
             break;
         case OCREP_PROP_BYTE_STRING:
             if (!valArray->strArray[index])
             {
-                err = err | cbor_encode_null(array);
+                err |= cbor_encode_null(array);
             }
             else
             {
-                err = err | cbor_encode_byte_string(array, valArray->ocByteStrArray[index].bytes,
+                err |= cbor_encode_byte_string(array, valArray->ocByteStrArray[index].bytes,
                         valArray->ocByteStrArray[index].len);
             }
             break;
         case OCREP_PROP_OBJECT:
             if (!valArray->objArray[index])
             {
-                err = err | cbor_encode_null(array);
+                err |= cbor_encode_null(array);
             }
             else
             {
-                err = OCConvertRepMap(array, valArray->objArray[index]);
+                err |= OCConvertRepMap(array, valArray->objArray[index]);
             }
             break;
         case OCREP_PROP_ARRAY:
-            OC_LOG(ERROR, TAG, "ConvertArray Invalid child array");
+            OIC_LOG(ERROR, TAG, "ConvertArray Invalid child array");
             err = CborUnknownError;
             break;
     }
 
     return err;
 }
-static int64_t OCConvertArray(CborEncoder* parent, const OCRepPayloadValueArray* valArray)
+
+static int64_t OCConvertArray(CborEncoder *parent, const OCRepPayloadValueArray *valArray)
 {
+    int64_t err = CborNoError;
     CborEncoder array;
-    int64_t err = 0;
-
-    err = err | cbor_encoder_create_array(parent, &array, valArray->dimensions[0]);
+    err |= cbor_encoder_create_array(parent, &array, valArray->dimensions[0]);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed creating rep array");
 
-    for (size_t i = 0; i < valArray->dimensions[0];++i)
+    for (size_t i = 0; i < valArray->dimensions[0]; ++i)
     {
-        if (valArray->dimensions[1] != 0)
+        if (0 != valArray->dimensions[1])
         {
             CborEncoder array2;
-            err = err | cbor_encoder_create_array(&array, &array2, valArray->dimensions[1]);
+            err |= cbor_encoder_create_array(&array, &array2, valArray->dimensions[1]);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed creating rep array2");
 
             for (size_t j = 0; j < valArray->dimensions[1]; ++j)
             {
-                if (valArray->dimensions[2] != 0)
+                if (0 != valArray->dimensions[2])
                 {
                     CborEncoder array3;
-                    err = err | cbor_encoder_create_array(&array2, &array3,
-                            valArray->dimensions[2]);
+                    err |= cbor_encoder_create_array(&array2, &array3, valArray->dimensions[2]);
+                    VERIFY_CBOR_SUCCESS(TAG, err, "Failed creating rep array3");
 
                     for(size_t k = 0; k < valArray->dimensions[2]; ++k)
                     {
-                        OCConvertArrayItem(&array3, valArray,
+                        err |= OCConvertArrayItem(&array3, valArray,
                             j * valArray->dimensions[2] +
                             i * valArray->dimensions[2] * valArray->dimensions[1] +
                             k);
+                        VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding rep array3 value");
                     }
-                    err = err | cbor_encoder_close_container(&array2, &array3);
+                    err |= cbor_encoder_close_container(&array2, &array3);
+                    VERIFY_CBOR_SUCCESS(TAG, err, "Failed closing rep array3");
                 }
                 else
                 {
-                    OCConvertArrayItem(&array2, valArray,
-                            i * valArray->dimensions[1] + j);
+                    err |= OCConvertArrayItem(&array2, valArray, i * valArray->dimensions[1] + j);
+                    VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding rep array2 value");
                 }
             }
-            err = err | cbor_encoder_close_container(&array, &array2);
+            err |= cbor_encoder_close_container(&array, &array2);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed closing rep array2");
         }
         else
         {
-            OCConvertArrayItem(&array, valArray, i);
+            err |= OCConvertArrayItem(&array, valArray, i);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding rep array value");
         }
     }
-    err = err | cbor_encoder_close_container(parent, &array);
+    err |= cbor_encoder_close_container(parent, &array);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed closing rep array");
+
+exit:
     return err;
 }
 
-static int64_t OCConvertRepMap(CborEncoder *map, const OCRepPayloadpayload)
+static int64_t OCConvertRepMap(CborEncoder *map, const OCRepPayload *payload)
 {
-    int64_t err = 0;
+    int64_t err = CborNoError;
     CborEncoder repMap;
-    err = err | cbor_encoder_create_map(map, &repMap, CborIndefiniteLength);
-    err = err | OCConvertSingleRepPayload(&repMap, payload);
-    err = err | cbor_encoder_close_container(map, &repMap);
+    err |= cbor_encoder_create_map(map, &repMap, CborIndefiniteLength);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed creating rep map");
+    err |= OCConvertSingleRepPayload(&repMap, payload);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed converting single rep payload");
+    err |= cbor_encoder_close_container(map, &repMap);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed closing rep map");
+exit:
     return err;
 }
 
-static int64_t OCConvertSingleRepPayload(CborEncoder* repMap, const OCRepPayload* payload)
+static int64_t OCConvertSingleRepPayload(CborEncoder *repMap, const OCRepPayload *payload)
 {
-    int64_t err = 0;
-    OCRepPayloadValuevalue = payload->values;
-    while(value)
+    int64_t err = CborNoError;
+    OCRepPayloadValue *value = payload->values;
+    while (value)
     {
-        err = err | cbor_encode_text_string(repMap,
-                value->name,
-                strlen(value->name));
-        switch(value->type)
+        err |= cbor_encode_text_string(repMap, value->name, strlen(value->name));
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding tag name");
+
+        switch (value->type)
         {
             case OCREP_PROP_NULL:
-                err = err | cbor_encode_null(repMap);
+                err |= cbor_encode_null(repMap);
                 break;
             case OCREP_PROP_INT:
-                err = err | cbor_encode_int(repMap,
-                        value->i);
+                err |= cbor_encode_int(repMap, value->i);
                 break;
             case OCREP_PROP_DOUBLE:
-                err = err | cbor_encode_double(repMap,
-                        value->d);
+                err |= cbor_encode_double(repMap, value->d);
                 break;
             case OCREP_PROP_BOOL:
-                err = err | cbor_encode_boolean(repMap,
-                        value->b);
+                err |= cbor_encode_boolean(repMap, value->b);
                 break;
             case OCREP_PROP_STRING:
-                err = err | cbor_encode_text_string(repMap,
-                        value->str, strlen(value->str));
+                err |= cbor_encode_text_string(repMap, value->str, strlen(value->str));
                 break;
             case OCREP_PROP_BYTE_STRING:
-                err = err | cbor_encode_byte_string(repMap,
-                        value->ocByteStr.bytes, value->ocByteStr.len);
+                err |= cbor_encode_byte_string(repMap, value->ocByteStr.bytes, value->ocByteStr.len);
                 break;
             case OCREP_PROP_OBJECT:
-                err = err | OCConvertRepMap(repMap, value->obj);
+                err |= OCConvertRepMap(repMap, value->obj);
                 break;
             case OCREP_PROP_ARRAY:
-                err = err | OCConvertArray(repMap, &value->arr);
+                err |= OCConvertArray(repMap, &value->arr);
                 break;
             default:
-                OC_LOG_V(ERROR, TAG, "Invalid Prop type: %d",
-                        value->type);
+                OIC_LOG_V(ERROR, TAG, "Invalid Prop type: %d", value->type);
                 break;
         }
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding single rep value");
         value = value->next;
     }
 
+exit:
     return err;
 }
 
-static int64_t OCConvertRepPayload(OCRepPayload* payload, uint8_t* outPayload, size_t* size)
+static int64_t OCConvertRepPayload(OCRepPayload *payload, uint8_t *outPayload, size_t *size)
 {
-    CborEncoder encoder = {0};
-    int64_t err = 0;
+    CborEncoder encoder;
+    int64_t err = CborNoError;
 
     cbor_encoder_init(&encoder, outPayload, *size, 0);
-    CborEncoder rootMap ;
 
     size_t arrayCount = 0;
     for (OCRepPayload *temp = payload; temp; temp = temp->next)
@@ -714,115 +718,112 @@ static int64_t OCConvertRepPayload(OCRepPayload* payload, uint8_t* outPayload, s
     CborEncoder rootArray;
     if (arrayCount > 1)
     {
-        err = err | cbor_encoder_create_array(&encoder, &rootArray, arrayCount);
+        err |= cbor_encoder_create_array(&encoder, &rootArray, arrayCount);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding rep root map");
     }
 
     while (payload != NULL && (err == CborNoError))
     {
-        err = err | cbor_encoder_create_map(((arrayCount == 1)? &encoder: &rootArray),
+        CborEncoder rootMap;
+        err |= cbor_encoder_create_map(((arrayCount == 1)? &encoder: &rootArray),
                                             &rootMap, CborIndefiniteLength);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed creating root map");
+
         // Only in case of collection href is included.
         if (arrayCount > 1 && payload->uri && strlen(payload->uri) > 0)
         {
-            OC_LOG(INFO, TAG, "Payload has uri");
-            err = err | cbor_encode_text_string(&rootMap, OC_RSRVD_HREF,
-                    strlen(OC_RSRVD_HREF));
-            err = err | cbor_encode_text_string(&rootMap, payload->uri,
-                    strlen(payload->uri));
+            OIC_LOG(INFO, TAG, "Payload has uri");
+            err |= cbor_encode_text_string(&rootMap, OC_RSRVD_HREF, strlen(OC_RSRVD_HREF));
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding rep href tag");
+            err |= cbor_encode_text_string(&rootMap, payload->uri, strlen(payload->uri));
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding rep href value");
         }
         if (payload->types)
         {
-            OC_LOG(INFO, TAG, "Payload has types");
-            char* joinedTypes = OCStringLLJoin(payload->types);
-            if (joinedTypes)
-            {
-                err = err | cbor_encode_text_string(&rootMap, OC_RSRVD_RESOURCE_TYPE,
-                        strlen(OC_RSRVD_RESOURCE_TYPE));
-                err = err | cbor_encode_text_string(&rootMap, joinedTypes,
-                        strlen(joinedTypes));
-                OICFree(joinedTypes);
-            }
-            else
-            {
-                return OC_STACK_NO_MEMORY;
-            }
+            OIC_LOG(INFO, TAG, "Payload has types");
+            err |= OCStringLLJoin(&rootMap, OC_RSRVD_RESOURCE_TYPE, payload->types);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding resource type.");
         }
         if (payload->interfaces)
         {
-            OC_LOG(INFO, TAG, "Payload has interfaces");
-            char* joinedInterfaces = OCStringLLJoin(payload->interfaces);
-            if (joinedInterfaces)
-            {
-                err = err | cbor_encode_text_string(&rootMap, OC_RSRVD_INTERFACE,
-                        strlen(OC_RSRVD_INTERFACE));
-                err = err | cbor_encode_text_string(&rootMap, joinedInterfaces,
-                        strlen(joinedInterfaces));
-                OICFree(joinedInterfaces);
-            }
-            else
-            {
-                return OC_STACK_NO_MEMORY;
-            }
+            OIC_LOG(INFO, TAG, "Payload has interfaces");
+            err |= OCStringLLJoin(&rootMap, OC_RSRVD_INTERFACE, payload->interfaces);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding platform interface type.");
         }
 
-        err = err | OCConvertSingleRepPayload(&rootMap, payload);
-        err = err | cbor_encoder_close_container(((arrayCount == 1) ? &encoder: &rootArray),
-                                                &rootMap);
+        err |= OCConvertSingleRepPayload(&rootMap, payload);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting rep payload");
+
+        // Close main array
+        err |= cbor_encoder_close_container(((arrayCount == 1) ? &encoder: &rootArray),
+                &rootMap);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed closing root map");
         payload = payload->next;
     }
     if (arrayCount > 1)
     {
-        err = err | cbor_encoder_close_container(&encoder, &rootArray);
+        err |= cbor_encoder_close_container(&encoder, &rootArray);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed closing root array");
     }
 
+exit:
     return checkError(err, &encoder, outPayload, size);
 }
 
-static int64_t OCConvertPresencePayload(OCPresencePayload* payload,
-        uint8_t* outPayload, size_t* size)
+static int64_t OCConvertPresencePayload(OCPresencePayload *payload, uint8_t *outPayload,
+        size_t *size)
 {
-    CborEncoder encoder = {0};
-    int64_t err = 0;
+    int64_t err = CborNoError;
+    CborEncoder encoder;
 
     cbor_encoder_init(&encoder, outPayload, *size, 0);
     CborEncoder map;
-    err = err | cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength);
+    err |= cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed creating presence map");
 
     // Sequence Number
-    err = err | cbor_encode_text_string(&map,
-            OC_RSRVD_NONCE,
-            sizeof(OC_RSRVD_NONCE) - 1);
-    err = err | cbor_encode_uint(&map, payload->sequenceNumber);
+    err |= cbor_encode_text_string(&map, OC_RSRVD_NONCE, sizeof(OC_RSRVD_NONCE) - 1);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding nonce tag to presence map");
+    err |= cbor_encode_uint(&map, payload->sequenceNumber);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding nonce value to presence map");
 
     // Max Age
-    err = err | cbor_encode_text_string(&map,
-            OC_RSRVD_TTL,
-            sizeof(OC_RSRVD_TTL) - 1);
-    err = err | cbor_encode_uint(&map, payload->maxAge);
+    err |= cbor_encode_text_string(&map, OC_RSRVD_TTL, sizeof(OC_RSRVD_TTL) - 1);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding ttl tag to presence map");
+    err |= cbor_encode_uint(&map, payload->maxAge);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding ttl value to presence map");
 
     // Trigger
-    const char* triggerStr = convertTriggerEnumToString(payload->trigger);
-    err = err | AddTextStringToMap(&map, OC_RSRVD_TRIGGER, sizeof(OC_RSRVD_TRIGGER) - 1,
-            triggerStr);
+    err |= cbor_encode_text_string(&map, OC_RSRVD_TRIGGER, sizeof(OC_RSRVD_TRIGGER) - 1);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding trigger tag to presence map");
+    err |= cbor_encode_simple_value(&map, payload->trigger);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding trigger value to presence map");
 
     // Resource type name
-    if(payload->trigger != OC_PRESENCE_TRIGGER_DELETE)
+    if (payload->trigger != OC_PRESENCE_TRIGGER_DELETE)
     {
-        err = err | ConditionalAddTextStringToMap(&map, OC_RSRVD_RESOURCE_TYPE,
+        err |= ConditionalAddTextStringToMap(&map, OC_RSRVD_RESOURCE_TYPE,
                 sizeof(OC_RSRVD_RESOURCE_TYPE) - 1, payload->resourceType);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding resource type to presence map");
     }
 
     // Close Map
-    err = err | cbor_encoder_close_container(&encoder, &map);
+    err |= cbor_encoder_close_container(&encoder, &map);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed closing presence map");
 
+exit:
     return checkError(err, &encoder, outPayload, size);
 }
 
 static int64_t AddTextStringToMap(CborEncoder* map, const char* key, size_t keylen,
         const char* value)
 {
-    return cbor_encode_text_string(map, key, keylen) |
-           cbor_encode_text_string(map, value, strlen(value));
+    int64_t err = cbor_encode_text_string(map, key, keylen);
+    if (CborNoError != err)
+    {
+        return err;
+    }
+    return cbor_encode_text_string(map, value, strlen(value));
 }
 
 static int64_t ConditionalAddTextStringToMap(CborEncoder* map, const char* key, size_t keylen,
index 1851d45..4763299 100644 (file)
 // Required for strok_r
 #define _POSIX_C_SOURCE 200112L
 #include <string.h>
-#include "ocpayloadcbor.h"
 #include <stdlib.h>
-#include "logger.h"
 #include "oic_string.h"
 #include "oic_malloc.h"
-#include "ocstackinternal.h"
 #include "ocpayload.h"
-#include "cbor.h"
-#include "oic_string.h"
+#include "ocpayloadcbor.h"
+#include "ocstackinternal.h"
 #include "payload_logging.h"
 #include "rdpayload.h"
 
-#define TAG "OCPayloadParse"
+#define TAG "OIC_RI_PAYLOADPARSE"
 
-static OCStackResult OCParseDiscoveryPayload(OCPayload** outPayload, CborValue* arrayVal);
-static OCStackResult OCParseDevicePayload(OCPayload** outPayload, CborValue* arrayVal);
-static OCStackResult OCParsePlatformPayload(OCPayload** outPayload, CborValue* arrayVal);
-static bool OCParseSingleRepPayload(OCRepPayload** outPayload, CborValue* repParent);
-static OCStackResult OCParseRepPayload(OCPayload** outPayload, CborValue* arrayVal);
-static OCStackResult OCParsePresencePayload(OCPayload** outPayload, CborValue* arrayVal);
-static OCStackResult OCParseSecurityPayload(OCPayload** outPayload, CborValue* arrayVal);
+static OCStackResult OCParseDiscoveryPayload(OCPayload **outPayload, CborValue *arrayVal);
+static OCStackResult OCParseDevicePayload(OCPayload **outPayload, CborValue *arrayVal);
+static OCStackResult OCParsePlatformPayload(OCPayload **outPayload, CborValue *arrayVal);
+static CborError OCParseSingleRepPayload(OCRepPayload **outPayload, CborValue *repParent, bool isRoot);
+static OCStackResult OCParseRepPayload(OCPayload **outPayload, CborValue *arrayVal);
+static OCStackResult OCParsePresencePayload(OCPayload **outPayload, CborValue *arrayVal);
+static OCStackResult OCParseSecurityPayload(OCPayload **outPayload, const uint8_t *payload, size_t size);
 
-OCStackResult OCParsePayload(OCPayload** outPayload, OCPayloadType payloadType,
-        const uint8_tpayload, size_t payloadSize)
+OCStackResult OCParsePayload(OCPayload **outPayload, OCPayloadType payloadType,
+        const uint8_t *payload, size_t payloadSize)
 {
+    OCStackResult result = OC_STACK_MALFORMED_RESPONSE;
+    CborError err;
+
+    VERIFY_PARAM_NON_NULL(TAG, outPayload, "Conversion of outPayload failed");
+    VERIFY_PARAM_NON_NULL(TAG, payload, "Invalid cbor payload value");
+
+    OIC_LOG_V(INFO, TAG, "CBOR Parsing size: %zu of Payload Type: %d, Payload:",
+            payloadSize, payloadType);
+    OIC_LOG_BUFFER(DEBUG, TAG, payload, payloadSize);
+
     CborParser parser;
     CborValue rootValue;
-    bool err = false;
 
-    OC_LOG_V(INFO, TAG, "CBOR Parsing size: %d", payloadSize);
-    if((err = cbor_parser_init(payload, payloadSize, 0, &parser, &rootValue)) != false)
-    {
-        OC_LOG_V(ERROR, TAG, "CBOR Parser init failed: %d", err);
-        return OC_STACK_ERROR;
-    }
+    err = cbor_parser_init(payload, payloadSize, 0, &parser, &rootValue);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed initializing init value")
 
-    OCStackResult result = OC_STACK_ERROR;
     switch(payloadType)
     {
         case PAYLOAD_TYPE_DISCOVERY:
@@ -82,55 +83,37 @@ OCStackResult OCParsePayload(OCPayload** outPayload, OCPayloadType payloadType,
             result = OCParsePresencePayload(outPayload, &rootValue);
             break;
         case PAYLOAD_TYPE_SECURITY:
-            result = OCParseSecurityPayload(outPayload, &rootValue);
+            result = OCParseSecurityPayload(outPayload, payload, payloadSize);
             break;
         case PAYLOAD_TYPE_RD:
             result = OCRDCborToPayload(&rootValue, outPayload);
             break;
         default:
-            OC_LOG_V(ERROR, TAG, "ParsePayload Type default: %d", payloadType);
-            result = OC_STACK_ERROR;
+            OIC_LOG_V(ERROR, TAG, "ParsePayload Type default: %d", payloadType);
+            result = OC_STACK_INVALID_PARAM;
             break;
     }
 
-    if(result != OC_STACK_OK)
-    {
-        OC_LOG_V(INFO, TAG, "Finished parse payload, result is %d", result);
-    }
+    OIC_LOG_V(INFO, TAG, "Finished parse payload, result is %d", result);
 
+exit:
     return result;
 }
 
 void OCFreeOCStringLL(OCStringLL* ll);
 
-static OCStackResult OCParseSecurityPayload(OCPayload** outPayload, CborValue* rootValue)
+static OCStackResult OCParseSecurityPayload(OCPayload** outPayload, const uint8_t *payload,
+        size_t size)
 {
-    if (!outPayload)
+    if (size > 0)
     {
-        return OC_STACK_INVALID_PARAM;
+        *outPayload = (OCPayload *)OCSecurityPayloadCreate(payload, size);
     }
-
-    bool err = false;
-    char * securityData = NULL;
-    CborValue map;
-    size_t len;
-
-    err = err || cbor_value_enter_container(rootValue, &map);
-    err = err || cbor_value_dup_text_string(&map, &securityData, &len, NULL);
-    err = err || cbor_value_leave_container(rootValue, &map);
-
-    if(err)
+    else
     {
-        OC_LOG(ERROR, TAG, "Cbor in error condition");
-        OICFree(securityData);
-        return OC_STACK_MALFORMED_RESPONSE;
+        *outPayload = NULL;
     }
-
-    *outPayload = (OCPayload*)OCSecurityPayloadCreate(securityData);
-    OICFree(securityData);
-
     return OC_STACK_OK;
-
 }
 
 static char* InPlaceStringTrim(char* str)
@@ -151,488 +134,498 @@ static char* InPlaceStringTrim(char* str)
     return str;
 }
 
-static OCStackResult OCParseDiscoveryPayload(OCPayload** outPayload, CborValue* rootValue)
+static CborError OCParseStringLL(CborValue *map, char *type, OCStringLL **resource)
 {
-    if (!outPayload)
-    {
-        return OC_STACK_INVALID_PARAM;
-    }
-
-    bool err = false;
-    OCResourcePayload* resource = NULL;
-    uint16_t resourceCount = 0;
-    CborValue resourceMap = {};
-
-    OCDiscoveryPayload* out = OCDiscoveryPayloadCreate();
-    if(!out)
-    {
-        return OC_STACK_NO_MEMORY;
-    }
-
-    // Root value is already inside the main root array
-    CborValue rootMap = {};
-
-    // Enter the main root map
-    err = err || cbor_value_enter_container(rootValue, &rootMap);
-    // Look for DI
-    CborValue curVal = {};
-    err = cbor_value_map_find_value(&rootMap, OC_RSRVD_DEVICE_ID, &curVal);
-    if (CborNoError != err)
-    {
-        OC_LOG(ERROR, TAG, "Cbor find value failed.");
-        goto malformed_cbor;
-    }
-    size_t len;
-    err = cbor_value_dup_byte_string(&curVal, &(out->sid), &len, NULL);
+    CborValue val;
+    CborError err = cbor_value_map_find_value(map, type, &val);
+    VERIFY_CBOR_SUCCESS(TAG, err, "to find StringLL TAG");
 
-    // Look for Links which will have an array as the value
-    err = cbor_value_map_find_value(&rootMap, OC_RSRVD_LINKS, &curVal);
-    if (CborNoError != err)
+    if (cbor_value_is_array(&val))
     {
-        OC_LOG(ERROR, TAG, "Cbor find value failed.");
-        goto malformed_cbor;
-    }
-
-    // Enter the links array and start iterating through the array processing
-    // each resource which shows up as a map.
-    err = err || cbor_value_enter_container(&curVal, &resourceMap);
-
-    while (cbor_value_is_map(&resourceMap))
-    {
-        resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
-        if(!resource)
-        {
-            OC_LOG(ERROR, TAG, "Memory allocation failed");
-            OCDiscoveryPayloadDestroy(out);
-            return OC_STACK_NO_MEMORY;
-        }
-
-        // Uri
-        CborValue uriVal = {};
-        err = cbor_value_map_find_value(&resourceMap, OC_RSRVD_HREF, &uriVal);
-        if (CborNoError != err)
-        {
-            OC_LOG(ERROR, TAG, "Cbor finding href type failed.");
-            goto malformed_cbor;
-        }
-        err = cbor_value_dup_text_string(&uriVal, &(resource->uri), &len, NULL);
-        if (CborNoError != err)
+        CborValue txtStr;
+        err = cbor_value_enter_container(&val, &txtStr);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to enter container");
+        while (cbor_value_is_text_string(&txtStr))
         {
-            OC_LOG(ERROR, TAG, "Cbor finding href value failed.");
-            goto malformed_cbor;
-        }
-        // ResourceTypes
-        CborValue rtVal = {};
-        err = cbor_value_map_find_value(&resourceMap, OC_RSRVD_RESOURCE_TYPE, &rtVal);
-        if (CborNoError != err)
-        {
-            OC_LOG(ERROR, TAG, "Cbor finding rt type failed.");
-            goto malformed_cbor;
-        }
-        if (cbor_value_is_text_string(&rtVal))
-        {
-            char* input = NULL;
-            char* savePtr;
-            err = cbor_value_dup_text_string(&rtVal, &input, &len, NULL);
-            if (CborNoError != err)
-            {
-                OC_LOG(ERROR, TAG, "Cbor finding rt value failed.");
-                goto malformed_cbor;
-            }
+            size_t len = 0;
+            char *input = NULL;
+            err = cbor_value_dup_text_string(&txtStr, &input, &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, err, "to find StringLL value.");
             if (input)
             {
-                char* curPtr = strtok_r(input, " ", &savePtr);
-
+                char *savePtr = NULL;
+                char *curPtr = strtok_r(input, " ", &savePtr);
                 while (curPtr)
                 {
-                    chartrimmed = InPlaceStringTrim(curPtr);
+                    char *trimmed = InPlaceStringTrim(curPtr);
                     if (trimmed[0] !='\0')
                     {
-                        if (!OCResourcePayloadAddResourceType(resource, trimmed))
+                        if (!OCResourcePayloadAddStringLL(resource, trimmed))
                         {
-                            OICFree(resource->uri);
-                            OCFreeOCStringLL(resource->types);
-                            OICFree(resource);
-                            OCDiscoveryPayloadDestroy(out);
-                            return OC_STACK_NO_MEMORY;
+                            return CborErrorOutOfMemory;
                         }
                     }
                     curPtr = strtok_r(NULL, " ", &savePtr);
                 }
                 OICFree(input);
             }
+            if (cbor_value_is_text_string(&txtStr))
+            {
+                err = cbor_value_advance(&txtStr);
+                VERIFY_CBOR_SUCCESS(TAG, err, "to advance string value");
+            }
         }
+    }
+exit:
+    return err;
+}
 
-        // Interface Types
-        CborValue ifVal = {};
-        err = cbor_value_map_find_value(&resourceMap, OC_RSRVD_INTERFACE, &ifVal);
-        if (CborNoError != err)
+static OCStackResult OCParseDiscoveryPayload(OCPayload **outPayload, CborValue *rootValue)
+{
+    OCStackResult ret = OC_STACK_INVALID_PARAM;
+    OCResourcePayload *resource = NULL;
+    OCDiscoveryPayload *out = NULL;
+    size_t len = 0;
+    CborError err = CborNoError;
+    *outPayload = NULL;
+
+    VERIFY_PARAM_NON_NULL(TAG, outPayload, "Invalid Parameter outPayload");
+    VERIFY_PARAM_NON_NULL(TAG, rootValue, "Invalid Parameter rootValue");
+    if (cbor_value_is_array(rootValue))
+    {
+        // Root value is already inside the main root array
+        CborValue rootMap;
+        ret = OC_STACK_NO_MEMORY;
+        out = OCDiscoveryPayloadCreate();
+        VERIFY_PARAM_NON_NULL(TAG, out, "Failed error initializing discovery payload");
+
+        // Enter the main root map
+        ret = OC_STACK_MALFORMED_RESPONSE;
+        err = cbor_value_enter_container(rootValue, &rootMap);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to enter root map container");
+
+        // Look for DI
+        CborValue curVal;
+        if (!cbor_value_is_map(&rootMap))
         {
-            OC_LOG(ERROR, TAG, "Cbor finding if type failed.");
-            goto malformed_cbor;
+            OIC_LOG(ERROR, TAG, "Malformed packet!!");
+            goto exit;
         }
-        if (!err && cbor_value_is_text_string(&ifVal))
+        err = cbor_value_map_find_value(&rootMap, OC_RSRVD_DEVICE_ID, &curVal);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to find device id tag");
+        if (cbor_value_is_valid(&curVal))
         {
-            char* input = NULL;
-            char* savePtr;
-            err = cbor_value_dup_text_string(&ifVal, &input, &len, NULL);
-            if (CborNoError != err)
+            if (cbor_value_is_byte_string(&curVal))
             {
-                OC_LOG(ERROR, TAG, "Cbor finding if value failed.");
-                goto malformed_cbor;
+                err = cbor_value_dup_byte_string(&curVal, (uint8_t **)&(out->sid), &len, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, err, "to copy device id value");
             }
-            if (input)
+            else if (cbor_value_is_text_string(&curVal))
             {
-                char* curPtr = strtok_r(input, " ", &savePtr);
-
-                while (curPtr)
-                {
-                    char* trimmed = InPlaceStringTrim(curPtr);
-                    if (trimmed[0] !='\0')
-                    {
-                        if (!OCResourcePayloadAddInterface(resource, trimmed))
-                        {
-                            OICFree(resource->uri);
-                            OCFreeOCStringLL(resource->types);
-                            OICFree(resource);
-                            OCDiscoveryPayloadDestroy(out);
-                            return OC_STACK_NO_MEMORY;
-                        }
-                    }
-                    curPtr = strtok_r(NULL, " ", &savePtr);
-                }
-                OICFree(input);
+                err = cbor_value_dup_text_string(&curVal, &(out->sid), &len, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, err, "to copy device id value");
             }
         }
 
-        // Policy
-        CborValue policyMap = {};
-        err = cbor_value_map_find_value(&resourceMap, OC_RSRVD_POLICY, &policyMap);
-        if (CborNoError != err)
+        // BaseURI - Not a mandatory field
+        err = cbor_value_map_find_value(&rootMap, OC_RSRVD_BASE_URI, &curVal);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to find uri tag");
+        if (cbor_value_is_valid(&curVal))
         {
-            OC_LOG(ERROR, TAG, "Cbor finding policy type failed.");
-            goto malformed_cbor;
+            err = cbor_value_dup_text_string(&curVal, &(out->baseURI), &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, err, "to find base uri value");
         }
-        // Bitmap
-        CborValue val = {};
-        err = cbor_value_map_find_value(&policyMap, OC_RSRVD_BITMAP, &val);
-        if (CborNoError != err)
+
+        // HREF - Not a mandatory field
+        err = cbor_value_map_find_value(&rootMap, OC_RSRVD_HREF, &curVal);
+        if (cbor_value_is_valid(&curVal))
         {
-            OC_LOG(ERROR, TAG, "Cbor finding bitmap type failed.");
-            goto malformed_cbor;
+            err = cbor_value_dup_text_string(&curVal, &(out->uri), &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, err, "to find uri value");
         }
-        uint64_t temp = 0;
-        err = cbor_value_get_uint64(&val, &temp);
-        if (CborNoError != err)
+
+        // RT - Not a mandatory field
+        err = cbor_value_map_find_value(&rootMap, OC_RSRVD_RESOURCE_TYPE, &curVal);
+        if (cbor_value_is_valid(&curVal))
         {
-            OC_LOG(ERROR, TAG, "Cbor finding bitmap value failed.");
-            goto malformed_cbor;
+            err = cbor_value_dup_text_string(&curVal, &(out->type), &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, err, "to find base uri value");
         }
-        resource->bitmap = (uint8_t)temp;
-        // Secure Flag
-        err = cbor_value_map_find_value(&policyMap, OC_RSRVD_SECURE, &val);
-        if (CborNoError != err)
+
+        // IF - Not a mandatory field
+        err = cbor_value_map_find_value(&rootMap, OC_RSRVD_INTERFACE, &curVal);
+        if (cbor_value_is_valid(&curVal))
         {
-            OC_LOG(ERROR, TAG, "Cbor finding secure type failed.");
-            goto malformed_cbor;
+            err =  OCParseStringLL(&rootMap, OC_RSRVD_INTERFACE, &out->interface);
         }
-        if(cbor_value_is_valid(&val))
+        if (!out->interface)
         {
-            err = cbor_value_get_boolean(&val, &(resource->secure));
-            if (CborNoError != err)
+            if (!OCResourcePayloadAddStringLL(&out->interface, OC_RSRVD_INTERFACE_LL))
             {
-                OC_LOG(ERROR, TAG, "Cbor finding secure value failed.");
-                goto malformed_cbor;
+                err = CborErrorOutOfMemory;
             }
-            // Port
-            CborValue port;
-            err = cbor_value_map_find_value(&policyMap, OC_RSRVD_HOSTING_PORT,
-                            &port);
+        }
+
+        // Name - Not a mandatory field
+        err = cbor_value_map_find_value(&rootMap, OC_RSRVD_DEVICE_NAME, &curVal);
+        if (cbor_value_is_valid(&curVal))
+        {
+            err = cbor_value_dup_text_string(&curVal, &out->name, &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, err, "to find device name");
+        }
+
+        // Look for Links which will have an array as the value
+        CborValue linkMap;
+        err = cbor_value_map_find_value(&rootMap, OC_RSRVD_LINKS, &linkMap);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to find links tag");
+
+        // Enter the links array and start iterating through the array processing
+        // each resource which shows up as a map.
+        CborValue resourceMap;
+        err = cbor_value_enter_container(&linkMap, &resourceMap);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to enter link map");
+
+        while (cbor_value_is_map(&resourceMap))
+        {
+            resource = (OCResourcePayload *)OICCalloc(1, sizeof(OCResourcePayload));
+            VERIFY_PARAM_NON_NULL(TAG, resource, "Failed allocating resource payload");
+
+            // Uri
+            err = cbor_value_map_find_value(&resourceMap, OC_RSRVD_HREF, &curVal);
+            VERIFY_CBOR_SUCCESS(TAG, err, "to find href tag");
+            err = cbor_value_dup_text_string(&curVal, &(resource->uri), &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, err, "to find href value");
+
+            // ResourceTypes
+            err =  OCParseStringLL(&resourceMap, OC_RSRVD_RESOURCE_TYPE, &resource->types);
+            VERIFY_CBOR_SUCCESS(TAG, err, "to find resource type tag/value");
+
+            // Interface Types
+            err =  OCParseStringLL(&resourceMap, OC_RSRVD_INTERFACE, &resource->interfaces);
             if (CborNoError != err)
             {
-                OC_LOG(ERROR, TAG, "Cbor finding port type failed.");
-                goto malformed_cbor;
-            }
-            if(cbor_value_is_valid(&port))
-            {
-                err = cbor_value_get_uint64(&port, &temp);
-                if (CborNoError != err)
+                if (!OCResourcePayloadAddStringLL(&resource->interfaces, OC_RSRVD_INTERFACE_LL))
                 {
-                    OC_LOG(ERROR, TAG, "Cbor finding port value failed.");
-                    goto malformed_cbor;
+                    OIC_LOG(ERROR, TAG, "Failed to add string to StringLL");
+                    goto exit;
                 }
-                resource->port = (uint16_t)temp;
             }
-        }
 
-        err = cbor_value_advance(&resourceMap);
-        if (CborNoError != err)
-        {
-            OC_LOG(ERROR, TAG, "Cbor advance value failed.");
-            goto malformed_cbor;
+            // Policy
+            CborValue policyMap;
+            err = cbor_value_map_find_value(&resourceMap, OC_RSRVD_POLICY, &policyMap);
+            VERIFY_CBOR_SUCCESS(TAG, err, "to find policy tag");
+
+            // Bitmap
+            err = cbor_value_map_find_value(&policyMap, OC_RSRVD_BITMAP, &curVal);
+            VERIFY_CBOR_SUCCESS(TAG, err, "to find bitmap tag");
+            err = cbor_value_get_int(&curVal, (int *)&resource->bitmap);
+            VERIFY_CBOR_SUCCESS(TAG, err, "to find bitmap value");
+
+            // Secure Flag
+            err = cbor_value_map_find_value(&policyMap, OC_RSRVD_SECURE, &curVal);
+            VERIFY_CBOR_SUCCESS(TAG, err, "to find secure tag");
+            if (cbor_value_is_valid(&curVal))
+            {
+                err = cbor_value_get_boolean(&curVal, &(resource->secure));
+                VERIFY_CBOR_SUCCESS(TAG, err, "to find secure value");
+            }
+
+            // Port
+            err = cbor_value_map_find_value(&policyMap, OC_RSRVD_HOSTING_PORT, &curVal);
+            VERIFY_CBOR_SUCCESS(TAG, err, "to find port tag");
+            if (cbor_value_is_valid(&curVal))
+            {
+                err = cbor_value_get_int(&curVal, (int *)&resource->port);
+                VERIFY_CBOR_SUCCESS(TAG, err, "to find port value");
+            }
+
+            err = cbor_value_advance(&resourceMap);
+            VERIFY_CBOR_SUCCESS(TAG, err, "to advance resource map");
+
+            OCDiscoveryPayloadAddNewResource(out, resource);
         }
-        ++resourceCount;
-        OCDiscoveryPayloadAddNewResource(out, resource);
-    }
 
-    err = err || cbor_value_leave_container(rootValue, &resourceMap);
+        err = cbor_value_leave_container(rootValue, &resourceMap);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to advance resource map");
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "Malformed packet ");
+        goto exit;
+    }
 
-    *outPayload = (OCPayload*)out;
+    *outPayload = (OCPayload *)out;
     return OC_STACK_OK;
 
-malformed_cbor:
-    OICFree(resource->uri);
-    OCFreeOCStringLL(resource->types);
-    OCFreeOCStringLL(resource->interfaces);
-    OICFree(resource);
+exit:
+    OCDiscoveryResourceDestroy(resource);
     OCDiscoveryPayloadDestroy(out);
-    return OC_STACK_MALFORMED_RESPONSE;
-
-cbor_error:
-    OCDiscoveryCollectionPayloadDestroy(out);
-    return OC_STACK_MALFORMED_RESPONSE;
+    return ret;
 }
 
-static OCStackResult OCParseDevicePayload(OCPayload** outPayload, CborValue* rootValue)
+static OCStackResult OCParseDevicePayload(OCPayload **outPayload, CborValue *rootValue)
 {
-    if (!outPayload)
-    {
-        return OC_STACK_INVALID_PARAM;
-    }
+    OCStackResult ret = OC_STACK_INVALID_PARAM;
+    CborError err = CborNoError;
+    OCDevicePayload *out = NULL;
+    VERIFY_PARAM_NON_NULL(TAG, outPayload, "Invalid param outPayload");
+    VERIFY_PARAM_NON_NULL(TAG, rootValue, "Invalid param rootValue");
 
-    bool err = false;
+    *outPayload = NULL;
 
-    if(cbor_value_is_map(rootValue))
+    out = (OCDevicePayload *)OICCalloc(1, sizeof(OCDevicePayload));
+    VERIFY_PARAM_NON_NULL(TAG, out, "Failed allocating device payload")
+    out->base.type = PAYLOAD_TYPE_DEVICE;
+    ret = OC_STACK_MALFORMED_RESPONSE;
+
+    if (cbor_value_is_map(rootValue))
     {
-        uint8_t* sid = NULL;
-        char* dname = NULL;
-        char* specVer = NULL;
-        char* dmVer = NULL;
+        CborValue curVal;
+        // Resource Type
+        err = cbor_value_map_find_value(rootValue, OC_RSRVD_RESOURCE_TYPE, &curVal);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to find resource type tag");
+        if (cbor_value_is_valid(&curVal))
+        {
+            err =  OCParseStringLL(rootValue, OC_RSRVD_RESOURCE_TYPE, &out->types);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed to find rt type tag/value");
+        }
 
-        CborValue repVal;
+        err = cbor_value_map_find_value(rootValue, OC_RSRVD_INTERFACE, &curVal);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to find interface tag");
+        if (cbor_value_is_valid(&curVal))
+        {
+            err =  OCParseStringLL(rootValue, OC_RSRVD_INTERFACE, &out->interfaces);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed to find interfaces tag/value");
+        }
         // Device ID
-        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_DEVICE_ID, &repVal);
-        size_t len;
-        if(cbor_value_is_valid(&repVal))
+        size_t len = 0;
+        err = cbor_value_map_find_value(rootValue, OC_RSRVD_DEVICE_ID, &curVal);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to find device id tag");
+        if (cbor_value_is_valid(&curVal))
         {
-            err = err || cbor_value_dup_byte_string(&repVal, &sid, &len, NULL);
+            if (cbor_value_is_byte_string(&curVal))
+            {
+                err = cbor_value_dup_byte_string(&curVal, (uint8_t **)&out->sid, &len, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, err, "to find device id in device payload");
+            }
+            else if (cbor_value_is_text_string(&curVal))
+            {
+                err = cbor_value_dup_text_string(&curVal, &out->sid, &len, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, err, "to find device id in device payload");
+            }
         }
         // Device Name
-        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_DEVICE_NAME, &repVal);
-        if(cbor_value_is_valid(&repVal))
+        err = cbor_value_map_find_value(rootValue, OC_RSRVD_DEVICE_NAME, &curVal);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to find device name tag");
+        if (cbor_value_is_valid(&curVal))
         {
-            err = err || cbor_value_dup_text_string(&repVal, &dname, &len, NULL);
+            err = cbor_value_dup_text_string(&curVal, &out->deviceName, &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, err, "to find device name in device payload");
         }
         // Device Spec Version
-        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_SPEC_VERSION, &repVal);
-        if(cbor_value_is_valid(&repVal))
+        err = cbor_value_map_find_value(rootValue, OC_RSRVD_SPEC_VERSION, &curVal);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to find spec ver tag");
+        if (cbor_value_is_valid(&curVal))
         {
-            err = err || cbor_value_dup_text_string(&repVal, &specVer, &len, NULL);
+            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
-        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_DATA_MODEL_VERSION, &repVal);
-        if (cbor_value_is_valid(&repVal))
+        err = cbor_value_map_find_value(rootValue, OC_RSRVD_DATA_MODEL_VERSION, &curVal);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to find data model ver tag");
+        if (cbor_value_is_valid(&curVal))
         {
-            err = err || cbor_value_dup_text_string(&repVal, &dmVer, &len, NULL);
-        }
-
-        err = err || cbor_value_advance(rootValue);
-
-        if(err)
-        {
-            OICFree(sid);
-            OICFree(dname);
-            OICFree(specVer);
-            OICFree(dmVer);
-            OC_LOG_V(ERROR, TAG, "CBOR in error condition %d", err);
-            return OC_STACK_MALFORMED_RESPONSE;
-        }
-
-        *outPayload = (OCPayload*)OCDevicePayloadCreate(sid, dname, specVer, dmVer);
-
-        OICFree(sid);
-        OICFree(dname);
-        OICFree(specVer);
-        OICFree(dmVer);
-        if(!*outPayload)
-        {
-            return OC_STACK_NO_MEMORY;
+            err = cbor_value_dup_text_string(&curVal, &out->dataModelVersion, &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, err, "to find data model version in device payload");
         }
+        err = cbor_value_advance(rootValue);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to advance device payload");
 
+        *outPayload = (OCPayload *)out;
         return OC_STACK_OK;
     }
-    else
-    {
-        OC_LOG(ERROR, TAG, "Root device node was not a map");
-        return OC_STACK_MALFORMED_RESPONSE;
-    }
 
+exit:
+    OCDevicePayloadDestroy(out);
+    return ret;
 }
 
-static OCStackResult OCParsePlatformPayload(OCPayload** outPayload, CborValue* rootValue)
+static OCStackResult OCParsePlatformPayload(OCPayload **outPayload, CborValue *rootValue)
 {
-    if (!outPayload)
-    {
-        return OC_STACK_INVALID_PARAM;
-    }
+    OCStackResult ret = OC_STACK_INVALID_PARAM;
+    CborError err = CborNoError;
+    OCPlatformInfo info = {0};
+    char* rt = NULL;
+    OCStringLL* interfaces = NULL;
+    OCPlatformPayload* out = NULL;
 
-    bool err = false;
+    VERIFY_PARAM_NON_NULL(TAG, outPayload, "Invalid Parameter outPayload");
 
-    if(cbor_value_is_map(rootValue))
+    if (cbor_value_is_map(rootValue))
     {
-        OCPlatformInfo info = {0};
-
         CborValue repVal;
-        size_t len;
-        // Platform ID
-        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_PLATFORM_ID, &repVal);
-        if(cbor_value_is_valid(&repVal))
-         {
-             err = err || cbor_value_dup_text_string(&repVal, &(info.platformID), &len, NULL);
-         }
+        size_t len = 0;
+        ret = OC_STACK_MALFORMED_RESPONSE;
 
+        // Platform ID
+        err = cbor_value_map_find_value(rootValue, OC_RSRVD_PLATFORM_ID, &repVal);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to find platform id tag");
+        if (cbor_value_is_valid(&repVal))
+        {
+            err = cbor_value_dup_text_string(&repVal, &(info.platformID), &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed to find platformID in the platform payload");
+        }
          // MFG Name
-         err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_MFG_NAME, &repVal);
-         if(cbor_value_is_valid(&repVal))
-         {
-             err = err || cbor_value_dup_text_string(&repVal, &(info.manufacturerName), &len, NULL);
-         }
-
+        err = cbor_value_map_find_value(rootValue, OC_RSRVD_MFG_NAME, &repVal);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to find mfg name tag");
+        if (cbor_value_is_valid(&repVal))
+        {
+            err = cbor_value_dup_text_string(&repVal, &(info.manufacturerName), &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed to find manufactureName in the platform payload");
+        }
         // MFG URL
-        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_MFG_URL, &repVal);
-        if(cbor_value_is_valid(&repVal))
+        err = cbor_value_map_find_value(rootValue, OC_RSRVD_MFG_URL, &repVal);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to find mfg url tag");
+        if (cbor_value_is_valid(&repVal))
         {
-             err = err || cbor_value_dup_text_string(&repVal, &(info.manufacturerUrl), &len, NULL);
+            err = cbor_value_dup_text_string(&repVal, &(info.manufacturerUrl), &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed to find manufactureUrl in the platform payload");
         }
-
         // Model Num
-        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_MODEL_NUM, &repVal);
-        if(cbor_value_is_valid(&repVal))
+        err = cbor_value_map_find_value(rootValue, OC_RSRVD_MODEL_NUM, &repVal);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to find model num tag");
+        if (cbor_value_is_valid(&repVal))
         {
-             err = err || cbor_value_dup_text_string(&repVal, &(info.modelNumber), &len, NULL);
+            err = cbor_value_dup_text_string(&repVal, &(info.modelNumber), &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed to find modelNumber in the platform payload");
         }
-
         // Date of Mfg
-        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_MFG_DATE, &repVal);
-        if(cbor_value_is_valid(&repVal))
+        err = cbor_value_map_find_value(rootValue, OC_RSRVD_MFG_DATE, &repVal);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to find mfg date tag");
+        if (cbor_value_is_valid(&repVal))
         {
-             err = err || cbor_value_dup_text_string(&repVal, &(info.dateOfManufacture), &len,
-                    NULL);
+            err = cbor_value_dup_text_string(&repVal, &(info.dateOfManufacture), &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed to find dateOfManufacture in the platform payload");
         }
-
         // Platform Version
-        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_PLATFORM_VERSION, &repVal);
-        if(cbor_value_is_valid(&repVal))
+        err = cbor_value_map_find_value(rootValue, OC_RSRVD_PLATFORM_VERSION, &repVal);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to find platform ver tag");
+        if (cbor_value_is_valid(&repVal))
         {
-             err = err || cbor_value_dup_text_string(&repVal, &(info.platformVersion), &len, NULL);
+            err = cbor_value_dup_text_string(&repVal, &(info.platformVersion), &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed to find platformVersion in the platform payload");
         }
-
         // OS Version
-        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_OS_VERSION, &repVal);
-        if(cbor_value_is_valid(&repVal))
+        err = cbor_value_map_find_value(rootValue, OC_RSRVD_OS_VERSION, &repVal);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to find os ver tag");
+        if (cbor_value_is_valid(&repVal))
         {
-             err = err || cbor_value_dup_text_string(&repVal, &(info.operatingSystemVersion),
-                    &len, NULL);
+            err = cbor_value_dup_text_string(&repVal, &(info.operatingSystemVersion), &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed to find OSVersion in the platform payload");
         }
-
         // Hardware Version
-        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_HARDWARE_VERSION, &repVal);
+        err = cbor_value_map_find_value(rootValue, OC_RSRVD_HARDWARE_VERSION, &repVal);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to find hw ver tag");
         if(cbor_value_is_valid(&repVal))
         {
-             err = err || cbor_value_dup_text_string(&repVal, &(info.hardwareVersion), &len,
-                    NULL);
+            err = cbor_value_dup_text_string(&repVal, &(info.hardwareVersion), &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed to find HWVersion in the platform payload");
         }
-
         // Firmware Version
-        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_FIRMWARE_VERSION, &repVal);
+        err = cbor_value_map_find_value(rootValue, OC_RSRVD_FIRMWARE_VERSION, &repVal);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to find fw ver tag");
         if(cbor_value_is_valid(&repVal))
         {
-             err = err || cbor_value_dup_text_string(&repVal, &(info.firmwareVersion), &len,
-                    NULL);
+            err = cbor_value_dup_text_string(&repVal, &(info.firmwareVersion), &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed to find firmwareVersion in the platform payload");
         }
-
         // Support URL
-        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_SUPPORT_URL, &repVal);
+        err = cbor_value_map_find_value(rootValue, OC_RSRVD_SUPPORT_URL, &repVal);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to find support url tag");
         if(cbor_value_is_valid(&repVal))
         {
-             err = err || cbor_value_dup_text_string(&repVal, &(info.supportUrl), &len, NULL);
+            err = cbor_value_dup_text_string(&repVal, &(info.supportUrl), &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed to find supportUrl in the platform payload");
         }
-
         // System Time
-        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_SYSTEM_TIME, &repVal);
+        err = cbor_value_map_find_value(rootValue, OC_RSRVD_SYSTEM_TIME, &repVal);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to find sys time tag");
         if(cbor_value_is_valid(&repVal))
         {
-             err = err || cbor_value_dup_text_string(&repVal, &(info.systemTime), &len, NULL);
+            err = cbor_value_dup_text_string(&repVal, &(info.systemTime), &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed to find systemTume in the platform payload");
         }
 
-        err = err || cbor_value_advance(rootValue);
-
-        if(err)
+        // Resource type
+        err = cbor_value_map_find_value(rootValue, OC_RSRVD_RESOURCE_TYPE, &repVal);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to find resource type tag");
+        if(cbor_value_is_valid(&repVal))
         {
-            OICFree(info.dateOfManufacture);
-            OICFree(info.firmwareVersion);
-            OICFree(info.hardwareVersion);
-            OICFree(info.manufacturerName);
-            OICFree(info.manufacturerUrl);
-            OICFree(info.modelNumber);
-            OICFree(info.operatingSystemVersion);
-            OICFree(info.platformID);
-            OICFree(info.platformVersion);
-            OICFree(info.supportUrl);
-            OICFree(info.systemTime);
-            OC_LOG(ERROR, TAG, "CBOR error In ParsePlatformPayload");
-            return OC_STACK_MALFORMED_RESPONSE;
+            err = cbor_value_dup_text_string(&repVal, &rt, &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed to find resource type in the platform payload");
         }
 
-        *outPayload = (OCPayload*)OCPlatformPayloadCreateAsOwner(&info);
-
-        if(!*outPayload)
+        // Interface Types
+        err = cbor_value_map_find_value(rootValue, OC_RSRVD_INTERFACE, &repVal);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to find interface tag");
+        if(cbor_value_is_valid(&repVal))
         {
-            return OC_STACK_NO_MEMORY;
+            err =  OCParseStringLL(rootValue, OC_RSRVD_INTERFACE, &interfaces);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed to find interfaces tag/value");
         }
 
-        return OC_STACK_OK;
-    }
-    else
-    {
-        OC_LOG(ERROR, TAG, "Root device node was not a map");
-        return OC_STACK_MALFORMED_RESPONSE;
+        err = cbor_value_advance(rootValue);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed to find supportUrl in the platform payload");
+
+       out = (OCPlatformPayload *)OCPlatformPayloadCreateAsOwner(&info);
+       out->rt = rt;
+       out->interfaces = interfaces;
+       *outPayload = (OCPayload *)out;
+       OIC_LOG_PAYLOAD(DEBUG, *outPayload);
+       return OC_STACK_OK;
     }
+
+exit:
+    OCPlatformInfoDestroy(&info);
+    OIC_LOG(ERROR, TAG, "CBOR error In ParsePlatformPayload");
+    return ret;
 }
 
 static OCRepPayloadPropType DecodeCborType(CborType type)
 {
     switch (type)
     {
-            case CborNullType:
-                return OCREP_PROP_NULL;
-            case CborIntegerType:
-                return OCREP_PROP_INT;
-            case CborDoubleType:
-                return OCREP_PROP_DOUBLE;
-            case CborBooleanType:
-                return OCREP_PROP_BOOL;
-            case CborTextStringType:
-                return OCREP_PROP_STRING;
-            case CborByteStringType:
-                return OCREP_PROP_BYTE_STRING;
-            case CborMapType:
-                return OCREP_PROP_OBJECT;
-            case CborArrayType:
-                return OCREP_PROP_ARRAY;
-            default:
-                return OCREP_PROP_NULL;
+        case CborNullType:
+            return OCREP_PROP_NULL;
+        case CborIntegerType:
+            return OCREP_PROP_INT;
+        case CborDoubleType:
+        case CborFloatType:
+            return OCREP_PROP_DOUBLE;
+        case CborBooleanType:
+            return OCREP_PROP_BOOL;
+        case CborTextStringType:
+            return OCREP_PROP_STRING;
+        case CborByteStringType:
+            return OCREP_PROP_BYTE_STRING;
+        case CborMapType:
+            return OCREP_PROP_OBJECT;
+        case CborArrayType:
+            return OCREP_PROP_ARRAY;
+        default:
+            return OCREP_PROP_NULL;
     }
 }
-static bool OCParseArrayFindDimensionsAndType(const CborValue* parent, size_t dimensions[MAX_REP_ARRAY_DEPTH],
-        OCRepPayloadPropType* type)
+static CborError OCParseArrayFindDimensionsAndType(const CborValue *parent,
+        size_t dimensions[MAX_REP_ARRAY_DEPTH], OCRepPayloadPropType *type)
 {
-    bool err = false;
     CborValue insideArray;
     *type = OCREP_PROP_NULL;
     dimensions[0] = dimensions[1] = dimensions[2] = 0;
 
-    err = err || cbor_value_enter_container(parent, &insideArray);
+    CborError err = cbor_value_enter_container(parent, &insideArray);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed to enter container");
 
     while (cbor_value_is_valid(&insideArray))
     {
@@ -642,21 +635,21 @@ static bool OCParseArrayFindDimensionsAndType(const CborValue* parent, size_t di
         {
             size_t subdim[MAX_REP_ARRAY_DEPTH];
             tempType = OCREP_PROP_NULL;
-            err = err || OCParseArrayFindDimensionsAndType(&insideArray, subdim, &tempType);
+            err = OCParseArrayFindDimensionsAndType(&insideArray, subdim, &tempType);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed to parse array");
 
             if (subdim[2] != 0)
             {
-                OC_LOG(ERROR, TAG, "Parse array helper, sub-array too deep");
+                OIC_LOG(ERROR, TAG, "Parse array helper, sub-array too deep");
             }
 
             dimensions[1] = dimensions[1] >= subdim[0] ? dimensions[1] : subdim[0];
             dimensions[2] = dimensions[2] >= subdim[1] ? dimensions[2] : subdim[1];
 
-            if (*type != OCREP_PROP_NULL && tempType != OCREP_PROP_NULL
-                    && *type != tempType)
+            if (*type != OCREP_PROP_NULL && tempType != OCREP_PROP_NULL && *type != tempType)
             {
-                OC_LOG(ERROR, TAG, "Array parse failed, mixed arrays not allowed (subtype)");
-                return true;
+                OIC_LOG(ERROR, TAG, "Array parse failed, mixed arrays not allowed (subtype)");
+                return CborUnknownError;
             }
             else if (*type == OCREP_PROP_NULL)
             {
@@ -673,14 +666,16 @@ static bool OCParseArrayFindDimensionsAndType(const CborValue* parent, size_t di
         else if (tempType != OCREP_PROP_NULL && *type != tempType)
         {
             // this is an invalid situation!
-            OC_LOG(ERROR, TAG, "Array parse failed, mixed arrays not allowed");
-            return true;
+            OIC_LOG(ERROR, TAG, "Array parse failed, mixed arrays not allowed");
+            return CborUnknownError;
         }
 
         ++dimensions[0];
-        cbor_value_advance(&insideArray);
+        err = cbor_value_advance(&insideArray);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed to advance array");
     }
 
+exit:
     return err;
 }
 
@@ -713,25 +708,25 @@ static size_t arrayStep(size_t dimensions[MAX_REP_ARRAY_DEPTH], size_t elementNu
         elementNum;
 }
 
-static bool OCParseArrayFillArray(const CborValue* parent, size_t dimensions[MAX_REP_ARRAY_DEPTH],
-        OCRepPayloadPropType type, void* targetArray)
+static CborError OCParseArrayFillArray(const CborValue *parent,
+        size_t dimensions[MAX_REP_ARRAY_DEPTH], OCRepPayloadPropType type, void *targetArray)
 {
-    bool err = false;
     CborValue insideArray;
 
-    err = err || cbor_value_enter_container(parent, &insideArray);
-
     size_t i = 0;
-    chartempStr = NULL;
+    char *tempStr = NULL;
     OCByteString ocByteStr = { .bytes = NULL, .len = 0};
     size_t tempLen = 0;
-    OCRepPayloadtempPl = NULL;
+    OCRepPayload *tempPl = NULL;
 
     size_t newdim[MAX_REP_ARRAY_DEPTH];
     newdim[0] = dimensions[1];
     newdim[1] = dimensions[2];
     newdim[2] = 0;
 
+    CborError err = cbor_value_enter_container(parent, &insideArray);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed to enter container");
+
     while (!err && i < dimensions[0] && cbor_value_is_valid(&insideArray))
     {
         bool noAdvance = false;
@@ -742,428 +737,395 @@ static bool OCParseArrayFillArray(const CborValue* parent, size_t dimensions[MAX
                 case OCREP_PROP_INT:
                     if (dimensions[1] == 0)
                     {
-                        err = err || cbor_value_get_int64(&insideArray,
-                                &(((int64_t*)targetArray)[i]));
+                        err = cbor_value_get_int64(&insideArray, &(((int64_t*)targetArray)[i]));
                     }
                     else
                     {
-                        err = err || OCParseArrayFillArray(&insideArray, newdim,
-                            type,
-                            &(((int64_t*)targetArray)[arrayStep(dimensions, i)])
-                            );
+                        err = OCParseArrayFillArray(&insideArray, newdim, type,
+                            &(((int64_t*)targetArray)[arrayStep(dimensions, i)]));
                     }
                     break;
                 case OCREP_PROP_DOUBLE:
                     if (dimensions[1] == 0)
                     {
-                        err = err || cbor_value_get_double(&insideArray,
-                                &(((double*)targetArray)[i]));
+                        double *d = &(((double*)targetArray)[i]);
+                        if (cbor_value_get_type(&insideArray) == CborDoubleType)
+                        {
+                            err = cbor_value_get_double(&insideArray, d);
+                        }
+                        else
+                        {
+                            /* must be float */
+                            float f;
+                            err = cbor_value_get_float(&insideArray, &f);
+                            if (!err)
+                                *d = f;
+                        }
                     }
                     else
                     {
-                        err = err || OCParseArrayFillArray(&insideArray, newdim,
-                            type,
-                            &(((double*)targetArray)[arrayStep(dimensions, i)])
-                            );
+                        err = OCParseArrayFillArray(&insideArray, newdim, type,
+                            &(((double*)targetArray)[arrayStep(dimensions, i)]));
                     }
                     break;
                 case OCREP_PROP_BOOL:
                     if (dimensions[1] == 0)
                     {
-                        err = err || cbor_value_get_boolean(&insideArray,
-                                &(((bool*)targetArray)[i]));
+                        err = cbor_value_get_boolean(&insideArray, &(((bool*)targetArray)[i]));
                     }
                     else
                     {
-                        err = err || OCParseArrayFillArray(&insideArray, newdim,
-                            type,
-                            &(((bool*)targetArray)[arrayStep(dimensions, i)])
-                            );
+                        err = OCParseArrayFillArray(&insideArray, newdim, type,
+                            &(((bool*)targetArray)[arrayStep(dimensions, i)]));
                     }
                     break;
                 case OCREP_PROP_STRING:
                     if (dimensions[1] == 0)
                     {
-                        err = err || cbor_value_dup_text_string(&insideArray,
-                                &tempStr, &tempLen, NULL);
+                        err = cbor_value_dup_text_string(&insideArray, &tempStr, &tempLen, NULL);
                         ((char**)targetArray)[i] = tempStr;
                         tempStr = NULL;
                     }
                     else
                     {
-                        err = err || OCParseArrayFillArray(&insideArray, newdim,
-                            type,
-                            &(((char**)targetArray)[arrayStep(dimensions, i)])
-                            );
+                        err = OCParseArrayFillArray(&insideArray, newdim, type,
+                            &(((char**)targetArray)[arrayStep(dimensions, i)]));
                     }
                     break;
                 case OCREP_PROP_BYTE_STRING:
                     if (dimensions[1] == 0)
                     {
-                        err = err || cbor_value_dup_byte_string(&insideArray,
-                                &(ocByteStr.bytes), &(ocByteStr.len), NULL);
+                        err = cbor_value_dup_byte_string(&insideArray, &(ocByteStr.bytes),
+                                &(ocByteStr.len), NULL);
                         ((OCByteString*)targetArray)[i] = ocByteStr;
                     }
                     else
                     {
-                        err = err || OCParseArrayFillArray(&insideArray, newdim,
-                                type,
-                                &(((OCByteString*)targetArray)[arrayStep(dimensions, i)])
-                                );
+                        err = OCParseArrayFillArray(&insideArray, newdim, type,
+                                &(((OCByteString*)targetArray)[arrayStep(dimensions, i)]));
                     }
                     break;
                 case OCREP_PROP_OBJECT:
                     if (dimensions[1] == 0)
                     {
-                        err = err || OCParseSingleRepPayload(&tempPl, &insideArray);
+                        err = OCParseSingleRepPayload(&tempPl, &insideArray, false);
                         ((OCRepPayload**)targetArray)[i] = tempPl;
                         tempPl = NULL;
                         noAdvance = true;
                     }
                     else
                     {
-                        err = err || OCParseArrayFillArray(&insideArray, newdim,
-                            type,
-                            &(((OCRepPayload**)targetArray)[arrayStep(dimensions, i)])
-                            );
+                        err = OCParseArrayFillArray(&insideArray, newdim, type,
+                            &(((OCRepPayload**)targetArray)[arrayStep(dimensions, i)]));
                     }
                     break;
                 default:
-                    OC_LOG(ERROR, TAG, "Invalid Array type in Parse Array");
-                    err = true;
+                    OIC_LOG(ERROR, TAG, "Invalid Array type in Parse Array");
+                    err = CborErrorUnknownType;
                     break;
             }
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting repPayload");
         }
         ++i;
         if (!noAdvance && cbor_value_is_valid(&insideArray))
         {
-            err = err || cbor_value_advance(&insideArray);
+            err = cbor_value_advance(&insideArray);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed advnce insideArray");
         }
     }
 
+exit:
     return err;
 }
 
-static bool OCParseArray(OCRepPayload* out, const char* name, CborValue* container)
+static CborError OCParseArray(OCRepPayload *out, const char *name, CborValue *container)
 {
+    void *arr = NULL;
     OCRepPayloadPropType type;
     size_t dimensions[MAX_REP_ARRAY_DEPTH];
-    bool err = OCParseArrayFindDimensionsAndType(container, dimensions, &type);
-
-    if (err)
-    {
-        OC_LOG(ERROR, TAG, "Array details weren't clear");
-        return err;
-    }
+    size_t dimTotal = 0;
+    size_t allocSize = 0;
+    bool res = true;
+    CborError err = OCParseArrayFindDimensionsAndType(container, dimensions, &type);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Array details weren't clear");
 
     if (type == OCREP_PROP_NULL)
     {
-        err = err || OCRepPayloadSetNull(out, name);
-        err = err || cbor_value_advance(container);
+        res = OCRepPayloadSetNull(out, name);
+        err = (CborError) !res;
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting value");
+        err = cbor_value_advance(container);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed advancing container");
         return err;
     }
 
-    size_t dimTotal = calcDimTotal(dimensions);
-    size_t allocSize = getAllocSize(type);
-    void* arr = OICCalloc(dimTotal, allocSize);
-
-    if (!arr)
-    {
-        OC_LOG(ERROR, TAG, "Array Parse allocation failed");
-        return true;
-    }
+    dimTotal = calcDimTotal(dimensions);
+    allocSize = getAllocSize(type);
+    arr = OICCalloc(dimTotal, allocSize);
+    VERIFY_PARAM_NON_NULL(TAG, arr, "Array Parse allocation failed");
 
-    err = err || OCParseArrayFillArray(container, dimensions, type, arr);
+    res = OCParseArrayFillArray(container, dimensions, type, arr);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed parse array");
 
     switch (type)
     {
         case OCREP_PROP_INT:
-            if (err || !OCRepPayloadSetIntArrayAsOwner(out, name, (int64_t*)arr, dimensions))
-            {
-                OICFree(arr);
-                err = true;
-            }
+            res = OCRepPayloadSetIntArrayAsOwner(out, name, (int64_t *)arr, dimensions);
             break;
         case OCREP_PROP_DOUBLE:
-            if (err || !OCRepPayloadSetDoubleArrayAsOwner(out, name, (double*)arr, dimensions))
-            {
-                OICFree(arr);
-                err = true;
-            }
+            res = OCRepPayloadSetDoubleArrayAsOwner(out, name, (double *)arr, dimensions);
             break;
         case OCREP_PROP_BOOL:
-            if (err || !OCRepPayloadSetBoolArrayAsOwner(out, name, (bool*)arr, dimensions))
-            {
-                OICFree(arr);
-                err = true;
-            }
+            res = OCRepPayloadSetBoolArrayAsOwner(out, name, (bool *)arr, dimensions);
             break;
         case OCREP_PROP_STRING:
-            if (err || !OCRepPayloadSetStringArrayAsOwner(out, name, (char**)arr, dimensions))
-            {
-                for(size_t i = 0; i < dimTotal; ++i)
-                {
-                    OICFree(((char**)arr)[i]);
-                }
-                OICFree(arr);
-                err = true;
-            }
+            res = OCRepPayloadSetStringArrayAsOwner(out, name, (char **)arr, dimensions);
             break;
         case OCREP_PROP_BYTE_STRING:
-            if (err || !OCRepPayloadSetByteStringArrayAsOwner(out, name, (OCByteString*)arr, dimensions))
-            {
-                for (size_t i = 0; i < dimTotal; ++i)
-                {
-                    OICFree(((OCByteString*)arr)[i].bytes);
-                }
-                OICFree(arr);
-                err = true;
-            }
+            res = OCRepPayloadSetByteStringArrayAsOwner(out, name, (OCByteString *)arr, dimensions);
             break;
         case OCREP_PROP_OBJECT:
-            if (err || !OCRepPayloadSetPropObjectArrayAsOwner(out, name, (OCRepPayload**)arr, dimensions))
-            {
-                for(size_t i = 0; i < dimTotal; ++i)
-                {
-                    OCRepPayloadDestroy(((OCRepPayload**)arr)[i]);
-                }
-                OICFree(arr);
-                err = true;
-            }
+            res = OCRepPayloadSetPropObjectArrayAsOwner(out, name, (OCRepPayload**)arr, dimensions);
             break;
         default:
-            OC_LOG(ERROR, TAG, "Invalid Array type in Parse Array");
-            err = true;
+            OIC_LOG(ERROR, TAG, "Invalid Array type in Parse Array");
             break;
     }
-
+    err = (CborError) !res;
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting array parameter");
+    return CborNoError;
+exit:
+    if (type == OCREP_PROP_STRING)
+    {
+        for(size_t i = 0; i < dimTotal; ++i)
+        {
+            OICFree(((char**)arr)[i]);
+        }
+    }
+    if (type == OCREP_PROP_BYTE_STRING)
+    {
+        for(size_t i = 0; i < dimTotal; ++i)
+        {
+            OICFree(((OCByteString*)arr)[i].bytes);
+        }
+    }
+    if (type == OCREP_PROP_OBJECT)
+    {
+        for(size_t i = 0; i < dimTotal; ++i)
+        {
+            OCRepPayloadDestroy(((OCRepPayload**)arr)[i]);
+        }
+    }
+    OICFree(arr);
     return err;
 }
 
-static bool OCParseSingleRepPayload(OCRepPayload** outPayload, CborValue *objMap)
+static CborError OCParseSingleRepPayload(OCRepPayload **outPayload, CborValue *objMap, bool isRoot)
 {
-    if (!outPayload)
-    {
-        return false;
-    }
-
-    bool err = false;
+    CborError err = CborUnknownError;
+    char *name = NULL;
+    bool res = false;
+    VERIFY_PARAM_NON_NULL(TAG, outPayload, "Invalid Parameter outPayload");
+    VERIFY_PARAM_NON_NULL(TAG, objMap, "Invalid Parameter objMap");
 
     if (cbor_value_is_map(objMap))
     {
         if (!*outPayload)
         {
             *outPayload = OCRepPayloadCreate();
-            if(!*outPayload)
+            if (!*outPayload)
             {
                 return CborErrorOutOfMemory;
             }
         }
 
-        OCRepPayload* curPayload = *outPayload;
+        OCRepPayload *curPayload = *outPayload;
+
         size_t len = 0;
-        CborValue repMap = *objMap;
-        err = err || cbor_value_enter_container(objMap, &repMap);
+        CborValue repMap;
+        err = cbor_value_enter_container(objMap, &repMap);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed entering repMap");
+
         while (!err && cbor_value_is_valid(&repMap))
         {
-            char *name = NULL;
             if (cbor_value_is_text_string(&repMap))
             {
-                err = err || cbor_value_dup_text_string(&repMap, &name, &len, NULL);
-                err = err || cbor_value_advance(&repMap);
+                err = cbor_value_dup_text_string(&repMap, &name, &len, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, err, "Failed finding tag name in the map");
+                err = cbor_value_advance(&repMap);
+                VERIFY_CBOR_SUCCESS(TAG, err, "Failed advancing rootMap");
                 if (name &&
+                    isRoot &&
                     ((0 == strcmp(OC_RSRVD_HREF, name)) ||
                      (0 == strcmp(OC_RSRVD_RESOURCE_TYPE, name)) ||
                     (0 == strcmp(OC_RSRVD_INTERFACE, name))))
                 {
-                    err = err || cbor_value_advance(&repMap);
+                    err = cbor_value_advance(&repMap);
                     OICFree(name);
                     continue;
                 }
-
             }
             CborType type = cbor_value_get_type(&repMap);
-
-            switch(type)
+            switch (type)
             {
                 case CborNullType:
-                    err = !OCRepPayloadSetNull(curPayload, name);
+                    res = OCRepPayloadSetNull(curPayload, name);
                     break;
                 case CborIntegerType:
                     {
                         int64_t intval = 0;
-                        err = err || cbor_value_get_int64(&repMap, &intval);
-                        if (!err)
-                        {
-                            err = !OCRepPayloadSetPropInt(curPayload, name, intval);
-                        }
+                        err = cbor_value_get_int64(&repMap, &intval);
+                        VERIFY_CBOR_SUCCESS(TAG, err, "Failed getting int value");
+                        res = OCRepPayloadSetPropInt(curPayload, name, intval);
                     }
                     break;
                 case CborDoubleType:
                     {
                         double doubleval = 0;
-                        err = err || cbor_value_get_double(&repMap, &doubleval);
-                        if (!err)
-                        {
-                            err = !OCRepPayloadSetPropDouble(curPayload, name, doubleval);
-                        }
+                        err = cbor_value_get_double(&repMap, &doubleval);
+                        VERIFY_CBOR_SUCCESS(TAG, err, "Failed getting double value");
+                        res = OCRepPayloadSetPropDouble(curPayload, name, doubleval);
                     }
                     break;
                 case CborBooleanType:
                     {
                         bool boolval = false;
-                        err = err || cbor_value_get_boolean(&repMap, &boolval);
-                        if (!err)
-                        {
-                            err = !OCRepPayloadSetPropBool(curPayload, name, boolval);
-                        }
+                        err = cbor_value_get_boolean(&repMap, &boolval);
+                        VERIFY_CBOR_SUCCESS(TAG, err, "Failed getting boolean value");
+                        res = OCRepPayloadSetPropBool(curPayload, name, boolval);
                     }
                     break;
                 case CborTextStringType:
                     {
-                        char* strval = NULL;
-                        err = err || cbor_value_dup_text_string(&repMap, &strval, &len, NULL);
-                        if (!err)
-                        {
-                            err = !OCRepPayloadSetPropStringAsOwner(curPayload, name, strval);
-                        }
+                        char *strval = NULL;
+                        err = cbor_value_dup_text_string(&repMap, &strval, &len, NULL);
+                        VERIFY_CBOR_SUCCESS(TAG, err, "Failed getting string value");
+                        res = OCRepPayloadSetPropStringAsOwner(curPayload, name, strval);
                     }
                     break;
                 case CborByteStringType:
                     {
                         uint8_t* bytestrval = NULL;
-                        err = err || cbor_value_dup_byte_string(&repMap, &bytestrval, &len, NULL);
-                        if (!err)
-                        {
-                            OCByteString tmp = {.bytes = bytestrval, .len = len};
-                            err = !OCRepPayloadSetPropByteStringAsOwner(curPayload, name, &tmp);
-                        }
+                        err = cbor_value_dup_byte_string(&repMap, &bytestrval, &len, NULL);
+                        VERIFY_CBOR_SUCCESS(TAG, err, "Failed getting byte string value");
+                        OCByteString tmp = {.bytes = bytestrval, .len = len};
+                        res = OCRepPayloadSetPropByteStringAsOwner(curPayload, name, &tmp);
                     }
                     break;
                 case CborMapType:
                     {
                         OCRepPayload *pl = NULL;
-                        err = err || OCParseSingleRepPayload(&pl, &repMap);
-                        if (!err)
-                        {
-                            err = !OCRepPayloadSetPropObjectAsOwner(curPayload, name, pl);
-                        }
+                        err = OCParseSingleRepPayload(&pl, &repMap, false);
+                        VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting parse single rep");
+                        res = OCRepPayloadSetPropObjectAsOwner(curPayload, name, pl);
                     }
                     break;
                 case CborArrayType:
-                    err = err || OCParseArray(curPayload, name, &repMap);
+                    err = OCParseArray(curPayload, name, &repMap);
                     break;
                 default:
-                    OC_LOG_V(ERROR, TAG, "Parsing rep property, unknown type %d", repMap.type);
-                    err = true;
+                    OIC_LOG_V(ERROR, TAG, "Parsing rep property, unknown type %d", repMap.type);
+                    res = false;
+            }
+            if (type != CborArrayType)
+            {
+                err = (CborError) !res;
             }
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting value");
 
             if (type != CborMapType && cbor_value_is_valid(&repMap))
             {
-                err = err || cbor_value_advance(&repMap);
+                err = cbor_value_advance(&repMap);
+                VERIFY_CBOR_SUCCESS(TAG, err, "Failed advance repMap");
             }
             OICFree(name);
+            name = NULL;
         }
         if (cbor_value_is_container(objMap))
         {
-            err = err || cbor_value_leave_container(objMap, &repMap);
-        }
-        if (err)
-        {
-            OCRepPayloadDestroy(*outPayload);
-            *outPayload = NULL;
+            err = cbor_value_leave_container(objMap, &repMap);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed to leave container");
         }
+        return err;
     }
 
+exit:
+    OICFree(name);
+    OCRepPayloadDestroy(*outPayload);
+    *outPayload = NULL;
     return err;
 }
 
-static OCStackResult OCParseRepPayload(OCPayload** outPayload, CborValue* root)
+static OCStackResult OCParseRepPayload(OCPayload **outPayload, CborValue *root)
 {
-    if (!outPayload)
-    {
-        return OC_STACK_INVALID_PARAM;
-    }
-
+    OCStackResult ret = OC_STACK_INVALID_PARAM;
+    CborError err;
+    OCRepPayload *temp = NULL;
     OCRepPayload *rootPayload = NULL;
     OCRepPayload *curPayload = NULL;
-
-    CborValue curVal;
-    bool err = false;
-    size_t len = 0;
     CborValue rootMap = *root;
+    VERIFY_PARAM_NON_NULL(TAG, outPayload, "Invalid Parameter outPayload");
+    VERIFY_PARAM_NON_NULL(TAG, root, "Invalid Parameter root");
+
+    *outPayload = NULL;
     if (cbor_value_is_array(root))
     {
-        cbor_value_enter_container(root, &rootMap);
+        err = cbor_value_enter_container(root, &rootMap);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed entering repMap");
     }
-    while (!err && cbor_value_is_valid(&rootMap))
+    while (cbor_value_is_valid(&rootMap))
     {
-        OCRepPayload *temp = OCRepPayloadCreate();
-        if (!temp)
-        {
-            return OC_STACK_NO_MEMORY;
+        temp = OCRepPayloadCreate();
+        ret = OC_STACK_NO_MEMORY;
+        VERIFY_PARAM_NON_NULL(TAG, temp, "Failed allocating memory");
+
+        CborValue curVal;
+        ret = OC_STACK_MALFORMED_RESPONSE;
+
+        // temporary fix to check for malformed cbor payload
+        if (!cbor_value_is_map(&rootMap) && !cbor_value_is_array(&rootMap)){
+            goto exit;
         }
-        if (!err && cbor_value_is_map(&rootMap))
+
+        if (cbor_value_is_map(&rootMap))
         {
-            err = err || cbor_value_map_find_value(&rootMap, OC_RSRVD_HREF, &curVal);
+            err = cbor_value_map_find_value(&rootMap, OC_RSRVD_HREF, &curVal);
+            VERIFY_CBOR_SUCCESS(TAG, err, "to find href tag");
             if (cbor_value_is_valid(&curVal))
             {
-                err = err || cbor_value_dup_text_string(&curVal, &temp->uri, &len, NULL);
+                size_t len = 0;
+                err = cbor_value_dup_text_string(&curVal, &temp->uri, &len, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, err, "Failed to find uri");
             }
         }
-        if (!err && cbor_value_is_map(&rootMap))
+
+        // Resource types
+        if (cbor_value_is_map(&rootMap))
         {
-            err = err || cbor_value_map_find_value(&rootMap, OC_RSRVD_RESOURCE_TYPE, &curVal);
-            if(cbor_value_is_text_string(&curVal))
+            if (CborNoError == cbor_value_map_find_value(&rootMap, OC_RSRVD_RESOURCE_TYPE, &curVal))
             {
-                char* allRt = NULL;
-                err = err || cbor_value_dup_text_string(&curVal, &allRt, &len, NULL);
-                if (allRt)
-                {
-                    char* savePtr;
-                    char* curPtr = strtok_r(allRt, " ", &savePtr);
-                    while (curPtr)
-                    {
-                        char* trimmed = InPlaceStringTrim(curPtr);
-                        if (trimmed[0] != '\0')
-                        {
-                            OCRepPayloadAddResourceType(temp, curPtr);
-                        }
-                        curPtr = strtok_r(NULL, " ", &savePtr);
-                    }
-                }
-                OICFree(allRt);
+                err =  OCParseStringLL(&rootMap, OC_RSRVD_RESOURCE_TYPE, &temp->types);
+                VERIFY_CBOR_SUCCESS(TAG, err, "Failed to find rt type tag/value");
             }
         }
-        if (!err && cbor_value_is_map(&rootMap))
+
+        // Interface Types
+        if (cbor_value_is_map(&rootMap))
         {
-            err = err || cbor_value_map_find_value(&rootMap, OC_RSRVD_INTERFACE, &curVal);
-            if(cbor_value_is_text_string(&curVal))
+            if (CborNoError == cbor_value_map_find_value(&rootMap, OC_RSRVD_INTERFACE, &curVal))
             {
-                char* allIf = NULL;
-                err = err || cbor_value_dup_text_string(&curVal, &allIf, &len, NULL);
-                if (allIf)
-                {
-                    char* savePtr;
-                    char* curPtr = strtok_r(allIf, " ", &savePtr);
-                    while (curPtr)
-                    {
-                        char* trimmed = InPlaceStringTrim(curPtr);
-                        if (trimmed[0] != '\0')
-                        {
-                            OCRepPayloadAddInterface(temp, curPtr);
-                        }
-                        curPtr = strtok_r(NULL, " ", &savePtr);
-                    }
-                }
-                OICFree(allIf);
+                err =  OCParseStringLL(&rootMap, OC_RSRVD_INTERFACE, &temp->interfaces);
+                VERIFY_CBOR_SUCCESS(TAG, err, "Failed to find interfaces tag/value");
             }
         }
-        if (!err && cbor_value_is_map(&rootMap))
+
+        if (cbor_value_is_map(&rootMap))
         {
-             err = err || OCParseSingleRepPayload(&temp, &rootMap);
+            err = OCParseSingleRepPayload(&temp, &rootMap, true);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed to parse single rep payload");
         }
-        if (rootPayload == NULL)
+
+        if(rootPayload == NULL)
         {
             rootPayload = temp;
             curPayload = temp;
@@ -1173,86 +1135,77 @@ static OCStackResult OCParseRepPayload(OCPayload** outPayload, CborValue* root)
             curPayload->next = temp;
             curPayload = curPayload->next;
         }
-        if (err)
-        {
-            OCRepPayloadDestroy(rootPayload);
-            OC_LOG(ERROR, TAG, "CBOR error in ParseRepPayload");
-            return OC_STACK_MALFORMED_RESPONSE;
-        }
+
         if (cbor_value_is_array(&rootMap))
         {
-            err = err || cbor_value_advance(&rootMap);
+            err = cbor_value_advance(&rootMap);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed to advance single rep payload");
         }
     }
     *outPayload = (OCPayload *)rootPayload;
-
     return OC_STACK_OK;
+
+exit:
+    OCRepPayloadDestroy(temp);
+    OCRepPayloadDestroy(rootPayload);
+    OIC_LOG(ERROR, TAG, "CBOR error in ParseRepPayload");
+    return ret;
 }
 
-static OCStackResult OCParsePresencePayload(OCPayload** outPayload, CborValue* rootValue)
+static OCStackResult OCParsePresencePayload(OCPayload **outPayload, CborValue *rootValue)
 {
-    if (!outPayload)
-    {
-        return OC_STACK_INVALID_PARAM;
-    }
+    OCStackResult ret = OC_STACK_INVALID_PARAM;
+    OCPresencePayload *payload = NULL;
+    VERIFY_PARAM_NON_NULL(TAG, outPayload, "Invalid Parameter outPayload");
 
-    bool err = false;
-    if(cbor_value_is_map(rootValue))
-    {
-        uint64_t seqNum = 0;
-        uint64_t maxAge = 0;
-        OCPresenceTrigger trigger = OC_PRESENCE_TRIGGER_CREATE;
-        char* tempStr = NULL;
-        size_t len = 0;
+    *outPayload = NULL;
 
+    payload = (OCPresencePayload *)OICCalloc(1, sizeof(OCPresencePayload));
+    ret = OC_STACK_NO_MEMORY;
+    VERIFY_PARAM_NON_NULL(TAG, payload, "Failed allocating presence payload");
+    payload->base.type = PAYLOAD_TYPE_PRESENCE;
+    ret = OC_STACK_MALFORMED_RESPONSE;
+
+    if (cbor_value_is_map(rootValue))
+    {
         CborValue curVal;
+
         // Sequence Number
-        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_NONCE, &curVal);
-        err = err || cbor_value_get_uint64(&curVal, &seqNum);
+        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);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed finding nonce value");
 
         // Max Age
-        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_TTL, &curVal);
-        err = err || cbor_value_get_uint64(&curVal, &maxAge);
+        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);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed finding ttl value");
 
         // Trigger
-        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_TRIGGER, &curVal);
-        err = err || cbor_value_dup_text_string(&curVal, &tempStr, &len, NULL);
-        trigger = convertTriggerStringToEnum(tempStr);
-        OICFree(tempStr);
-        tempStr = NULL;
+        err = cbor_value_map_find_value(rootValue, OC_RSRVD_TRIGGER, &curVal);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed finding trigger tag");
+        err = cbor_value_get_simple_type(&curVal, (uint8_t *)&payload->trigger);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed finding trigger value");
 
         // Resource type name
-        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_RESOURCE_TYPE, &curVal);
-        if(cbor_value_is_valid(&curVal))
-        {
-             err = err || cbor_value_dup_text_string(&curVal, &tempStr, &len, NULL);
-        }
-
-        err = err || cbor_value_advance(rootValue);
-
-        if(!err)
+        err = cbor_value_map_find_value(rootValue, OC_RSRVD_RESOURCE_TYPE, &curVal);
+        VERIFY_CBOR_SUCCESS(TAG, err, "to find res type tag");
+        if (cbor_value_is_valid(&curVal))
         {
-            *outPayload = (OCPayload*)OCPresencePayloadCreate(seqNum, maxAge, trigger, tempStr);
+            size_t len = 0;
+            err = cbor_value_dup_text_string(&curVal, &payload->resourceType, &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed finding resource type value");
         }
-        OICFree(tempStr);
 
-        if(err)
-        {
-            OCPayloadDestroy(*outPayload);
-            OC_LOG(ERROR, TAG, "CBOR error Parse Presence Payload");
-            return OC_STACK_MALFORMED_RESPONSE;
-        }
-
-        if(!*outPayload)
-        {
-            return OC_STACK_NO_MEMORY;
-        }
+        err = cbor_value_advance(rootValue);
+        VERIFY_CBOR_SUCCESS(TAG, err, "Failed advancing root value");
 
+        *outPayload = (OCPayload *)payload;
         return OC_STACK_OK;
     }
-    else
-    {
-        OC_LOG(ERROR, TAG, "Root presence node was not a map");
-        return OC_STACK_MALFORMED_RESPONSE;
-    }
+exit:
+    OIC_LOG(ERROR, TAG, "CBOR error Parse Presence Payload");
+    OCPresencePayloadDestroy(payload);
+    return ret;
 }
old mode 100644 (file)
new mode 100755 (executable)
index c77c705..d109ba3
 // For POSIX.1-2001 base specification,
 // Refer http://pubs.opengroup.org/onlinepubs/009695399/
 #define _POSIX_C_SOURCE 200112L
+
+#ifdef WITH_ARDUINO
 #include <string.h>
+#else
+#include <strings.h>
+#endif
+
 #include "ocresource.h"
 #include "ocresourcehandler.h"
 #include "ocobserve.h"
@@ -39,6 +45,7 @@
 #include "cacommon.h"
 #include "cainterface.h"
 #include "rdpayload.h"
+#include "ocpayload.h"
 
 #ifdef WITH_RD
 #include "rd_server.h"
 #endif
 
 /// Module Name
-#define TAG "ocresource"
+#define TAG "OIC_RI_RESOURCE"
+
 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
-            {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
+            {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
 
-#define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
+#define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
              TAG, #arg " is NULL"); return (retVal); } }
 
 extern OCResource *headResource;
 static OCPlatformInfo savedPlatformInfo = {0};
 static OCDeviceInfo savedDeviceInfo = {0};
 
+/**
+ * Prepares a Payload for response.
+ */
+static OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
+                                                  OCDiscoveryPayload* payload,
+                                                  OCDevAddr *endpoint,
+                                                  bool rdResponse);
+
 //-----------------------------------------------------------------------------
 // Default resource entity handler function
 //-----------------------------------------------------------------------------
@@ -113,7 +129,7 @@ static OCStackResult ExtractFiltersFromQuery(char *query, char **filterOne, char
     *filterOne = NULL;
     *filterTwo = NULL;
 
-    OC_LOG_V(INFO, TAG, "Extracting params from %s", query);
+    OIC_LOG_V(INFO, TAG, "Extracting params from %s", query);
 
     char *keyValuePair = strtok_r (query, OC_QUERY_SEPARATOR, &restOfQuery);
 
@@ -121,7 +137,7 @@ static OCStackResult ExtractFiltersFromQuery(char *query, char **filterOne, char
     {
         if (numKeyValuePairsParsed >= 2)
         {
-            OC_LOG(ERROR, TAG, "More than 2 queries params in URI.");
+            OIC_LOG(ERROR, TAG, "More than 2 queries params in URI.");
             return OC_STACK_INVALID_QUERY;
         }
 
@@ -131,17 +147,17 @@ static OCStackResult ExtractFiltersFromQuery(char *query, char **filterOne, char
         {
             return OC_STACK_INVALID_QUERY;
         }
-        else if (strcmp (key, OC_RSRVD_INTERFACE) == 0)
+        else if (strncasecmp(key, OC_RSRVD_INTERFACE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
         {
             *filterOne = value;     // if
         }
-        else if (strcmp (key, OC_RSRVD_RESOURCE_TYPE) == 0)
+        else if (strncasecmp(key, OC_RSRVD_RESOURCE_TYPE, sizeof(OC_RSRVD_INTERFACE) - 1) == 0)
         {
             *filterTwo = value;     // rt
         }
         else
         {
-            OC_LOG_V(ERROR, TAG, "Unsupported query key: %s", key);
+            OIC_LOG_V(ERROR, TAG, "Unsupported query key: %s", key);
             return OC_STACK_INVALID_QUERY;
         }
         ++numKeyValuePairsParsed;
@@ -149,7 +165,7 @@ static OCStackResult ExtractFiltersFromQuery(char *query, char **filterOne, char
         keyValuePair = strtok_r(NULL, OC_QUERY_SEPARATOR, &restOfQuery);
     }
 
-    OC_LOG_V(INFO, TAG, "Extracted params %s and %s.", *filterOne, *filterTwo);
+    OIC_LOG_V(INFO, TAG, "Extracted params if: %s and rt: %s.", *filterOne, *filterTwo);
     return OC_STACK_OK;
 }
 
@@ -201,7 +217,7 @@ static OCStackResult getQueryParamsForFiltering (OCVirtualResources uri, char *q
     if (uri == OC_PRESENCE)
     {
         //Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK.
-        OC_LOG(INFO, TAG, "OC_PRESENCE Request for virtual resource.");
+        OIC_LOG(INFO, TAG, "OC_PRESENCE Request for virtual resource.");
         return OC_STACK_OK;
     }
     #endif
@@ -269,7 +285,7 @@ OCStackResult BuildResponseRepresentation(const OCResource *resourcePtr,
 }
 
 OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
-                        OCDiscoveryPayload *payload, OCDevAddr *devAddr)
+                        OCDiscoveryPayload *payload, OCDevAddr *devAddr, bool rdResponse)
 {
     if (!resourcePtr || !payload)
     {
@@ -284,29 +300,12 @@ OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
        }
     }
 
-    OCDiscoveryPayloadAddResource(payload, resourcePtr, port);
-    return OC_STACK_OK;
-}
-
-OCStackResult BuildVirtualCollectionResourceResponse(const OCResourceCollectionPayload *resourcePtr,
-        OCDiscoveryPayload *payload, OCDevAddr *devAddr)
-{
-    if (!resourcePtr || !payload)
+    if (rdResponse)
     {
-        return OC_STACK_INVALID_PARAM;
-    }
-    if (resourcePtr->tags && (resourcePtr->tags->bitmap & OC_SECURE))
-    {
-       if (GetSecurePortInfo(devAddr, &resourcePtr->tags->port) != OC_STACK_OK)
-       {
-           OC_LOG(ERROR, TAG, "Failed setting secure port.");
-       }
-    }
-    if (resourcePtr->tags && !resourcePtr->tags->baseURI)
-    {
-        resourcePtr->tags->baseURI = OICStrdup(devAddr->addr);
+        port = devAddr->port;
     }
-    OCDiscoveryCollectionPayloadAddResource(payload, resourcePtr->tags, resourcePtr->setLinks);
+
+    OCDiscoveryPayloadAddResource(payload, resourcePtr, port);
     return OC_STACK_OK;
 }
 
@@ -317,13 +316,11 @@ uint8_t IsCollectionResource (OCResource *resource)
         return 0;
     }
 
-    for (int i = 0; i < MAX_CONTAINED_RESOURCES; i++)
+    if(resource->rsrcChildResourcesHead != NULL)
     {
-        if (resource->rsrcResources[i])
-        {
-            return 1;
-        }
+        return 1;
     }
+
     return 0;
 }
 
@@ -343,7 +340,7 @@ OCResource *FindResourceByUri(const char* resourceUri)
         }
         pointer = pointer->next;
     }
-    OC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
+    OIC_LOG_V(INFO, TAG, "Resource %s not found", resourceUri);
     return NULL;
 }
 
@@ -357,12 +354,12 @@ OCStackResult DetermineResourceHandling (const OCServerRequest *request,
         return OC_STACK_INVALID_PARAM;
     }
 
-    OC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
+    OIC_LOG_V(INFO, TAG, "DetermineResourceHandling for %s", request->resourceUrl);
 
     // Check if virtual resource
     if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
     {
-        OC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
+        OIC_LOG_V (INFO, TAG, "%s is virtual", request->resourceUrl);
         *handling = OC_RESOURCE_VIRTUAL;
         *resource = headResource;
         return OC_STACK_OK;
@@ -480,7 +477,7 @@ static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilt
         resourceTypePtr = resourceTypePtr->next;
     }
 
-    OC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
+    OIC_LOG_V(INFO, TAG, "%s does not contain rt=%s.", resource->uri, resourceTypeFilter);
     return false;
 }
 
@@ -501,14 +498,16 @@ static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
 
     while (interfacePtr)
     {
-        if (strcmp (interfacePtr->name, interfaceFilter) == 0)
+        if ((strcmp (interfacePtr->name, interfaceFilter) == 0) &&
+            (strcmp (OC_RSRVD_INTERFACE_LL, interfaceFilter) == 0 ||
+             strcmp (OC_RSRVD_INTERFACE_DEFAULT, interfaceFilter) == 0))
         {
             return true;
         }
         interfacePtr = interfacePtr->next;
     }
 
-    OC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
+    OIC_LOG_V(INFO, TAG, "%s does not contain if=%s.", resource->uri, interfaceFilter);
     return false;
 }
 
@@ -518,25 +517,24 @@ static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
  * Function will return true if all non null AND non empty filters passed in find a match.
  */
 static bool includeThisResourceInResponse(OCResource *resource,
-                                                 char *interfaceFilter,
-                                                 char *resourceTypeFilter)
+                                          char *interfaceFilter,
+                                          char *resourceTypeFilter)
 {
     if (!resource)
     {
-        OC_LOG(ERROR, TAG, "Invalid resource");
+        OIC_LOG(ERROR, TAG, "Invalid resource");
         return false;
     }
 
-    if ( resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
+    if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
     {
         /*
          * At least one valid filter should be available to
          * include the resource in discovery response
          */
-        if (!((interfaceFilter && *interfaceFilter ) ||
-              (resourceTypeFilter && *resourceTypeFilter)))
+        if (!(resourceTypeFilter && *resourceTypeFilter))
         {
-            OC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
+            OIC_LOG_V(INFO, TAG, "%s no query string for EXPLICIT_DISCOVERABLE \
                 resource", resource->uri);
             return false;
         }
@@ -544,7 +542,7 @@ static bool includeThisResourceInResponse(OCResource *resource,
     else if ( !(resource->resourceProperties & OC_ACTIVE) ||
          !(resource->resourceProperties & OC_DISCOVERABLE))
     {
-        OC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
+        OIC_LOG_V(INFO, TAG, "%s not ACTIVE or DISCOVERABLE", resource->uri);
         return false;
     }
 
@@ -569,15 +567,94 @@ OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCRes
 
 #ifdef WITH_RD
 static OCStackResult checkResourceExistsAtRD(const char *interfaceType, const char *resourceType,
-    OCResourceCollectionPayload **repPayload)
+     OCResource **payload, OCDevAddr *devAddr)
 {
-    if (OCRDCheckPublishedResource(interfaceType, resourceType, repPayload) == OC_STACK_OK)
+    OCResourceCollectionPayload *repPayload;
+    if (!payload)
     {
+        return OC_STACK_ERROR;
+    }
+    if (OCRDCheckPublishedResource(interfaceType, resourceType, &repPayload, devAddr) == OC_STACK_OK)
+    {
+        if (!repPayload)
+        {
+            return OC_STACK_ERROR;
+        }
+        OCResource *ptr = ((OCResource *) OICCalloc(1, sizeof(OCResource)));
+        if (!ptr)
+        {
+           return OC_STACK_NO_MEMORY;
+        }
+
+        ptr->uri = OICStrdup(repPayload->setLinks->href);
+        if (!ptr->uri)
+        {
+           return OC_STACK_NO_MEMORY;
+        }
+        OCStringLL *rt = repPayload->setLinks->rt;
+        while (rt)
+        {
+            OCResourceType *temp = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
+            if(!temp)
+            {
+                OICFree(ptr->uri);
+                return OC_STACK_NO_MEMORY;
+            }
+            temp->next = NULL;
+            temp->resourcetypename = OICStrdup(rt->value);
+            if (!ptr->rsrcType)
+            {
+                ptr->rsrcType = temp;
+            }
+            else
+            {
+                OCResourceType *type = ptr->rsrcType;
+                while (type->next)
+                {
+                    type = type->next;
+                }
+                type->next = temp;
+            }
+            rt = rt->next;
+        }
+
+        OCStringLL *itf = repPayload->setLinks->itf;
+        while (itf)
+        {
+            OCResourceInterface *temp = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
+            if (!temp)
+            {
+                OICFree(ptr->uri);
+
+                return OC_STACK_NO_MEMORY;
+            }
+            temp->next = NULL;
+            temp->name = OICStrdup(itf->value);
+            if (!ptr->rsrcInterface)
+            {
+                ptr->rsrcInterface = temp;
+            }
+            else
+            {
+                OCResourceInterface *type = ptr->rsrcInterface;
+                while (type->next)
+                {
+                    type = type->next;
+                }
+                type->next = temp;
+            }
+            itf = itf->next;
+        }
+
+        ptr->resourceProperties = (OCResourceProperty) repPayload->tags->bitmap;
+
+        OCFreeCollectionResource(repPayload);
+        *payload = ptr;
         return OC_STACK_OK;
     }
     else
     {
-        OC_LOG_V(ERROR, TAG, "The resource type or interface type doe not exist \
+        OIC_LOG_V(ERROR, TAG, "The resource type or interface type doe not exist \
                              on the resource directory");
     }
     return OC_STACK_ERROR;
@@ -596,59 +673,139 @@ static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource
     bool bMulticast    = false;     // Was the discovery request a multicast request?
     OCPayload* payload = NULL;
 
-    OC_LOG(INFO, TAG, "Entering HandleVirtualResource");
+    OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
 
     OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
 
     // Step 1: Generate the response to discovery request
     if (virtualUriInRequest == OC_WELL_KNOWN_URI)
     {
-        char *filterOne = NULL;
-        char *filterTwo = NULL;
+        if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
+        {
+            OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
+            return OC_STACK_UNAUTHORIZED_REQ;
+        }
+
+        char *interfaceQuery = NULL;
+        char *resourceTypeQuery = NULL;
 
         discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
-                &filterOne, &filterTwo);
+                &interfaceQuery, &resourceTypeQuery);
+        bool interfaceQueryAllocated = false;
+        if (!interfaceQuery && !resourceTypeQuery)
+        {
+            interfaceQueryAllocated = true;
+            interfaceQuery = OICStrdup(OC_RSRVD_INTERFACE_LL);
+        }
 
         if (discoveryResult == OC_STACK_OK)
         {
-            payload = (OCPayload*)OCDiscoveryPayloadCreate();
+            payload = (OCPayload *)OCDiscoveryPayloadCreate();
 
-            if(payload)
+            if (payload)
             {
-                ((OCDiscoveryPayload*)payload)->sid = (uint8_t*)OICCalloc(1, UUID_SIZE);
-                memcpy(((OCDiscoveryPayload*)payload)->sid,
-                    OCGetServerInstanceID(), UUID_SIZE);
+                OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)payload;
+                discPayload->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
+                VERIFY_NON_NULL(discPayload->sid, ERROR, OC_STACK_NO_MEMORY);
+                const char* uid = OCGetServerInstanceIDString();
+                if(uid)
+                {
+                    memcpy(discPayload->sid, uid, UUID_STRING_SIZE);
+                }
 
-                bool foundResourceAtRD = false;
-                for(;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
+                if (!resourceTypeQuery && interfaceQuery && (0 == strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
                 {
-#ifdef WITH_RD
-                    if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
+                    for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
                     {
-                        OCResourceCollectionPayload *repPayload;
-                        discoveryResult = checkResourceExistsAtRD(filterOne, filterTwo, &repPayload);
-                        if (discoveryResult != OC_STACK_OK)
+                        bool result = false;
+                        if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
+                        {
+                            if (resourceTypeQuery && resourceMatchesRTFilter(resource, resourceTypeQuery))
+                            {
+                                result = true;
+                            }
+                        }
+                        if (resource->resourceProperties & OC_DISCOVERABLE)
                         {
-                             break;
+                            result = true;
+                        }
+
+                        if (result)
+                        {
+                            discoveryResult = BuildVirtualResourceResponse(resource,
+                            discPayload, &request->devAddr, false);
                         }
-                        discoveryResult = BuildVirtualCollectionResourceResponse(repPayload,
-                                    (OCDiscoveryPayload*)payload,
-                                    &request->devAddr);
-                        foundResourceAtRD = true;
                     }
+                }
+                else
+                {
+                    if ((interfaceQuery && (0 != strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL))) ||
+                        !interfaceQuery)
+                    {
+                        discPayload->uri = OICStrdup(OC_RSRVD_WELL_KNOWN_URI);
+                        VERIFY_NON_NULL(discPayload->uri, ERROR, OC_STACK_NO_MEMORY);
+                        if (savedDeviceInfo.deviceName)
+                        {
+                            discPayload->name = OICStrdup(savedDeviceInfo.deviceName);
+                            VERIFY_NON_NULL(discPayload->name, ERROR, OC_STACK_NO_MEMORY);
+                        }
+                        discPayload->type = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
+                        VERIFY_NON_NULL(discPayload->type, ERROR, OC_STACK_NO_MEMORY);
+                        OCResourcePayloadAddStringLL(&discPayload->interface, OC_RSRVD_INTERFACE_LL);
+                        OCResourcePayloadAddStringLL(&discPayload->interface, OC_RSRVD_INTERFACE_DEFAULT);
+                        VERIFY_NON_NULL(discPayload->interface, ERROR, OC_STACK_NO_MEMORY);
+                    }
+                    bool foundResourceAtRD = false;
+                    for (;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
+                    {
+#ifdef WITH_RD
+                        if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
+                        {
+                            OCResource *resource1 = NULL;
+                            OCDevAddr devAddr;
+                            discoveryResult = checkResourceExistsAtRD(interfaceQuery,
+                                resourceTypeQuery, &resource1, &devAddr);
+                            if (discoveryResult != OC_STACK_OK)
+                            {
+                                 break;
+                            }
+                            discoveryResult = BuildVirtualResourceResponse(resource1,
+                                discPayload, &devAddr, true);
+                            if (payload)
+                            {
+                                discPayload->baseURI = OICStrdup(devAddr.addr);
+                            }
+                            OICFree(resource1->uri);
+                            for (OCResourceType *rsrcRt = resource1->rsrcType, *rsrcRtNext = NULL; rsrcRt; )
+                            {
+                                rsrcRtNext = rsrcRt->next;
+                                OICFree(rsrcRt->resourcetypename);
+                                OICFree(rsrcRt);
+                                rsrcRt = rsrcRtNext;
+                            }
+
+                            for (OCResourceInterface *rsrcPtr = resource1->rsrcInterface, *rsrcNext = NULL; rsrcPtr; )
+                            {
+                                rsrcNext = rsrcPtr->next;
+                                OICFree(rsrcPtr->name);
+                                OICFree(rsrcPtr);
+                                rsrcPtr = rsrcNext;
+                            }
+                            foundResourceAtRD = true;
+                        }
 #endif
-                    if(!foundResourceAtRD && includeThisResourceInResponse(resource, filterOne, filterTwo))
+                        if (!foundResourceAtRD && includeThisResourceInResponse(resource, interfaceQuery, resourceTypeQuery))
+                        {
+                            discoveryResult = BuildVirtualResourceResponse(resource,
+                                discPayload, &request->devAddr, false);
+                        }
+                    }
+                    // Set discoveryResult appropriately if no 'valid' resources are available
+                    if (discPayload->resources == NULL && !foundResourceAtRD)
                     {
-                        discoveryResult = BuildVirtualResourceResponse(resource,
-                                (OCDiscoveryPayload*)payload,
-                                &request->devAddr);
+                        discoveryResult = OC_STACK_NO_RESOURCE;
                     }
                 }
-                // Set discoveryResult appropriately if no 'valid' resources are available
-                if (((OCDiscoveryPayload*)payload)->resources == NULL && !foundResourceAtRD)
-                {
-                    discoveryResult = OC_STACK_NO_RESOURCE;
-                }
             }
             else
             {
@@ -657,20 +814,30 @@ static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource
         }
         else
         {
-            OC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
+            OIC_LOG_V(ERROR, TAG, "Error (%d) parsing query.", discoveryResult);
+        }
+        if (interfaceQueryAllocated)
+        {
+            OICFree(interfaceQuery);
         }
     }
     else if (virtualUriInRequest == OC_DEVICE_URI)
     {
-        const OicUuid_t* deviceId = OCGetServerInstanceID();
+        if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
+        {
+            OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
+            return OC_STACK_UNAUTHORIZED_REQ;
+        }
+
+        const char* deviceId = OCGetServerInstanceIDString();
         if (!deviceId)
         {
             discoveryResult = OC_STACK_ERROR;
         }
         else
         {
-            payload = (OCPayload*) OCDevicePayloadCreate((const uint8_t*) &deviceId->id, savedDeviceInfo.deviceName,
-                    OC_SPEC_VERSION, OC_DATA_MODEL_VERSION);
+            payload = (OCPayload*) OCDevicePayloadCreate(deviceId, savedDeviceInfo.deviceName,
+                savedDeviceInfo.types, OC_SPEC_VERSION, OC_DATA_MODEL_VERSION);
             if (!payload)
             {
                 discoveryResult = OC_STACK_NO_MEMORY;
@@ -683,6 +850,12 @@ static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource
     }
     else if (virtualUriInRequest == OC_PLATFORM_URI)
     {
+        if (request->method == OC_REST_PUT || request->method == OC_REST_POST || request->method == OC_REST_DELETE)
+        {
+            OIC_LOG_V(ERROR, TAG, "Resource : %s not permitted for method: %d", request->resourceUrl, request->method);
+            return OC_STACK_UNAUTHORIZED_REQ;
+        }
+
         payload = (OCPayload*)OCPlatformPayloadCreate(&savedPlatformInfo);
         if (!payload)
         {
@@ -697,7 +870,7 @@ static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource
     else if (OC_GATEWAY_URI == virtualUriInRequest)
     {
         // Received request for a gateway
-        OC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
+        OIC_LOG(INFO, TAG, "Request is for Gateway Virtual Request");
         discoveryResult = RMHandleGatewayRequest(request, resource);
 
     }
@@ -735,9 +908,10 @@ static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource
         {
             SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
         }
-        else if(bMulticast == false)
+        else if(bMulticast == false && (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
+               (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
         {
-            OC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d)  \
+            OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d)  \
                 discovery request", discoveryResult, virtualUriInRequest);
             SendNonPersistantDiscoveryResponse(request, resource, NULL,
                 (discoveryResult == OC_STACK_NO_RESOURCE) ? OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
@@ -745,7 +919,7 @@ static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource
         else
         {
             // Ignoring the discovery request as per RFC 7252, Section #8.2
-            OC_LOG(INFO, TAG, "Silently ignoring the request since device does not have \
+            OIC_LOG(INFO, TAG, "Silently ignoring the request since device does not have \
                 any useful data to send");
         }
     }
@@ -767,7 +941,7 @@ HandleDefaultDeviceEntityHandler (OCServerRequest *request)
     OCEntityHandlerResult ehResult = OC_EH_ERROR;
     OCEntityHandlerRequest ehRequest = {0};
 
-    OC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
+    OIC_LOG(INFO, TAG, "Entering HandleResourceWithDefaultDeviceEntityHandler");
     result = FormOCEntityHandlerRequest(&ehRequest,
                                         (OCRequestHandle) request,
                                         request->method,
@@ -787,7 +961,7 @@ HandleDefaultDeviceEntityHandler (OCServerRequest *request)
                                   (char*) request->resourceUrl, defaultDeviceHandlerCallbackParameter);
     if(ehResult == OC_EH_SLOW)
     {
-        OC_LOG(INFO, TAG, "This is a slow resource");
+        OIC_LOG(INFO, TAG, "This is a slow resource");
         request->slowFlag = 1;
     }
     else if(ehResult == OC_EH_ERROR)
@@ -817,7 +991,7 @@ HandleResourceWithEntityHandler (OCServerRequest *request,
 
     OCEntityHandlerRequest ehRequest = {0};
 
-    OC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
+    OIC_LOG(INFO, TAG, "Entering HandleResourceWithEntityHandler");
     OCPayloadType type = PAYLOAD_TYPE_REPRESENTATION;
     // check the security resource
     if (request && request->resourceUrl && SRMIsSecurityResourceURI(request->resourceUrl))
@@ -848,22 +1022,22 @@ HandleResourceWithEntityHandler (OCServerRequest *request,
 
     if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
     {
-        OC_LOG(INFO, TAG, "No observation requested");
+        OIC_LOG(INFO, TAG, "No observation requested");
         ehFlag = OC_REQUEST_FLAG;
     }
     else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
     {
-        OC_LOG(INFO, TAG, "Observation registration requested");
+        OIC_LOG(INFO, TAG, "Observation registration requested");
 
         ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
                                     request->tokenLength);
 
         if (obs)
         {
-            OC_LOG (INFO, TAG, "Observer with this token already present");
-            OC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
-            OC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
-            OC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
+            OIC_LOG (INFO, TAG, "Observer with this token already present");
+            OIC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
+            OIC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
+            OIC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
 
             // server requests are usually free'd when the response is sent out
             // for the request in ocserverrequest.c : HandleSingleResponse()
@@ -884,7 +1058,7 @@ HandleResourceWithEntityHandler (OCServerRequest *request,
 
         if(result == OC_STACK_OK)
         {
-            OC_LOG(INFO, TAG, "Added observer successfully");
+            OIC_LOG(INFO, TAG, "Added observer successfully");
             request->observeResult = OC_STACK_OK;
             ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
         }
@@ -895,7 +1069,7 @@ HandleResourceWithEntityHandler (OCServerRequest *request,
             // The error in observeResult for the request will be used when responding to this
             // request by omitting the observation option/sequence number.
             request->observeResult = OC_STACK_ERROR;
-            OC_LOG(ERROR, TAG, "Observer Addition failed");
+            OIC_LOG(ERROR, TAG, "Observer Addition failed");
             ehFlag = OC_REQUEST_FLAG;
         }
 
@@ -903,7 +1077,7 @@ HandleResourceWithEntityHandler (OCServerRequest *request,
     else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER &&
             !collectionResource)
     {
-        OC_LOG(INFO, TAG, "Deregistering observation requested");
+        OIC_LOG(INFO, TAG, "Deregistering observation requested");
 
         resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
 
@@ -921,14 +1095,14 @@ HandleResourceWithEntityHandler (OCServerRequest *request,
 
         if(result == OC_STACK_OK)
         {
-            OC_LOG(INFO, TAG, "Removed observer successfully");
+            OIC_LOG(INFO, TAG, "Removed observer successfully");
             request->observeResult = OC_STACK_OK;
         }
         else
         {
             result = OC_STACK_OK;
             request->observeResult = OC_STACK_ERROR;
-            OC_LOG(ERROR, TAG, "Observer Removal failed");
+            OIC_LOG(ERROR, TAG, "Observer Removal failed");
         }
     }
     else
@@ -940,7 +1114,7 @@ HandleResourceWithEntityHandler (OCServerRequest *request,
     ehResult = resource->entityHandler(ehFlag, &ehRequest, resource->entityHandlerCallbackParam);
     if(ehResult == OC_EH_SLOW)
     {
-        OC_LOG(INFO, TAG, "This is a slow resource");
+        OIC_LOG(INFO, TAG, "This is a slow resource");
         request->slowFlag = 1;
     }
     else if(ehResult == OC_EH_ERROR)
@@ -1006,7 +1180,7 @@ ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerReque
         }
         case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER:
         {
-            OC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
+            OIC_LOG(INFO, TAG, "OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER");
             return OC_STACK_ERROR;
         }
         case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER:
@@ -1031,7 +1205,7 @@ ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerReque
         }
         default:
         {
-            OC_LOG(INFO, TAG, "Invalid Resource Determination");
+            OIC_LOG(INFO, TAG, "Invalid Resource Determination");
             return OC_STACK_ERROR;
         }
     }
@@ -1040,7 +1214,7 @@ ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerReque
 
 void DeletePlatformInfo()
 {
-    OC_LOG(INFO, TAG, "Deleting platform info.");
+    OIC_LOG(INFO, TAG, "Deleting platform info.");
 
     OICFree(savedPlatformInfo.platformID);
     savedPlatformInfo.platformID = NULL;
@@ -1118,11 +1292,11 @@ OCStackResult SavePlatformInfo(OCPlatformInfo info)
 
     if (res != OC_STACK_OK)
     {
-        OC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
+        OIC_LOG_V(ERROR, TAG, "Failed to save platform info. errno(%d)", res);
     }
     else
     {
-        OC_LOG(INFO, TAG, "Platform info saved.");
+        OIC_LOG(INFO, TAG, "Platform info saved.");
     }
 
     return res;
@@ -1130,10 +1304,12 @@ OCStackResult SavePlatformInfo(OCPlatformInfo info)
 
 void DeleteDeviceInfo()
 {
-    OC_LOG(INFO, TAG, "Deleting device info.");
+    OIC_LOG(INFO, TAG, "Deleting device info.");
 
     OICFree(savedDeviceInfo.deviceName);
+    OCFreeOCStringLL(savedDeviceInfo.types);
     savedDeviceInfo.deviceName = NULL;
+
 }
 
 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
@@ -1146,6 +1322,15 @@ static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
         return OC_STACK_NO_MEMORY;
     }
 
+    if (info.types)
+    {
+        savedDeviceInfo.types = CloneOCStringLL(info.types);
+        if(!savedDeviceInfo.types && info.types)
+        {
+            DeleteDeviceInfo();
+            return OC_STACK_NO_MEMORY;
+        }
+    }
     return OC_STACK_OK;
 }
 
@@ -1159,14 +1344,14 @@ OCStackResult SaveDeviceInfo(OCDeviceInfo info)
 
     VERIFY_SUCCESS(res, OC_STACK_OK);
 
-    if(OCGetServerInstanceID() == NULL)
+    if (OCGetServerInstanceIDString() == NULL)
     {
-        OC_LOG(INFO, TAG, "Device ID generation failed");
+        OIC_LOG(INFO, TAG, "Device ID generation failed");
         res =  OC_STACK_ERROR;
         goto exit;
     }
 
-    OC_LOG(INFO, TAG, "Device initialized successfully.");
+    OIC_LOG(INFO, TAG, "Device initialized successfully.");
     return OC_STACK_OK;
 
 exit:
index 6e44d4c..8263100 100644 (file)
@@ -39,9 +39,9 @@
 #include "pdu.h"
 
 // Module Name
-#define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG(FATAL, TAG, #arg " is NULL"); goto exit;} }
+#define VERIFY_NON_NULL(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL"); goto exit;} }
 
-#define TAG  "ocserverrequest"
+#define TAG  "OIC_RI_SERVERREQUEST"
 
 static struct OCServerRequest * serverRequestList = NULL;
 static struct OCServerResponse * serverResponseList = NULL;
@@ -76,7 +76,7 @@ static OCStackResult AddServerResponse (OCServerResponse ** response, OCRequestH
     serverResponse->requestHandle = requestHandle;
 
     *response = serverResponse;
-    OC_LOG(INFO, TAG, "Server Response Added!!");
+    OIC_LOG(INFO, TAG, "Server Response Added!!");
     LL_APPEND (serverResponseList, serverResponse);
     return OC_STACK_OK;
 
@@ -103,7 +103,7 @@ static void DeleteServerRequest(OCServerRequest * serverRequest)
         OICFree(serverRequest->requestToken);
         OICFree(serverRequest);
         serverRequest = NULL;
-        OC_LOG(INFO, TAG, "Server Request Removed!!");
+        OIC_LOG(INFO, TAG, "Server Request Removed!!");
     }
 }
 
@@ -117,9 +117,9 @@ static void DeleteServerResponse(OCServerResponse * serverResponse)
     if(serverResponse)
     {
         LL_DELETE(serverResponseList, serverResponse);
-        OICFree(serverResponse->payload);
+        OCPayloadDestroy(serverResponse->payload);
         OICFree(serverResponse);
-        OC_LOG(INFO, TAG, "Server Response Removed!!");
+        OIC_LOG(INFO, TAG, "Server Response Removed!!");
     }
 }
 
@@ -157,11 +157,10 @@ static OCStackResult OCSendResponse(const CAEndpoint_t *object, CAResponseInfo_t
 {
 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
     // Add route info in RM option.
-    OCStackResult rmResult = RMAddInfo(object->routeData, &(responseInfo->info.options),
-                       &(responseInfo->info.numOptions));
+    OCStackResult rmResult = RMAddInfo(object->routeData, responseInfo, false, NULL);
     if(OC_STACK_OK != rmResult)
     {
-        OC_LOG(ERROR, TAG, "Add option failed");
+        OIC_LOG(ERROR, TAG, "Add option failed");
         return rmResult;
     }
 #endif
@@ -171,7 +170,7 @@ static OCStackResult OCSendResponse(const CAEndpoint_t *object, CAResponseInfo_t
     CAResult_t result = CASendResponse(object, responseInfo);
     if(CA_STATUS_OK != result)
     {
-        OC_LOG_V(ERROR, TAG, "CASendResponse failed with CA error %u", result);
+        OIC_LOG_V(ERROR, TAG, "CASendResponse failed with CA error %u", result);
         return CAResultToOCResult(result);
     }
     return OC_STACK_OK;
@@ -194,24 +193,24 @@ OCServerRequest * GetServerRequestUsingToken (const CAToken_t token, uint8_t tok
 {
     if(!token)
     {
-        OC_LOG(ERROR, TAG, "Invalid Parameter Token");
+        OIC_LOG(ERROR, TAG, "Invalid Parameter Token");
         return NULL;
     }
 
     OCServerRequest * out = NULL;
-    OC_LOG(INFO, TAG,"Get server request with token");
-    OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
+    OIC_LOG(INFO, TAG,"Get server request with token");
+    OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
 
-    OC_LOG(INFO, TAG,"Found token");
+    OIC_LOG(INFO, TAG,"Found token");
     LL_FOREACH (serverRequestList, out)
     {
-        OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)out->requestToken, tokenLength);
+        OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)out->requestToken, tokenLength);
         if(memcmp(out->requestToken, token, tokenLength) == 0)
         {
             return out;
         }
     }
-    OC_LOG(ERROR, TAG, "Server Request not found!!");
+    OIC_LOG(ERROR, TAG, "Server Request not found!!");
     return NULL;
 }
 
@@ -232,7 +231,7 @@ OCServerRequest * GetServerRequestUsingHandle (const OCServerRequest * handle)
             return out;
         }
     }
-    OC_LOG(ERROR, TAG, "Server Request not found!!");
+    OIC_LOG(ERROR, TAG, "Server Request not found!!");
     return NULL;
 }
 
@@ -254,7 +253,7 @@ OCServerResponse * GetServerResponseUsingHandle (const OCServerRequest * handle)
             return out;
         }
     }
-    OC_LOG(ERROR, TAG, "Server Response not found!!");
+    OIC_LOG(ERROR, TAG, "Server Response not found!!");
     return NULL;
 }
 
@@ -274,7 +273,7 @@ OCStackResult AddServerRequest (OCServerRequest ** request, uint16_t coapID,
 
     OCServerRequest * serverRequest = NULL;
 
-    OC_LOG_V(INFO, TAG, "addserverrequest entry!! [%s:%u]", devAddr->addr, devAddr->port);
+    OIC_LOG_V(INFO, TAG, "addserverrequest entry!! [%s:%u]", devAddr->addr, devAddr->port);
 
     serverRequest = (OCServerRequest *) OICCalloc(1, sizeof(OCServerRequest) +
         (reqTotalSize ? reqTotalSize : 1) - 1);
@@ -336,7 +335,7 @@ OCStackResult AddServerRequest (OCServerRequest ** request, uint16_t coapID,
     serverRequest->devAddr = *devAddr;
 
     *request = serverRequest;
-    OC_LOG(INFO, TAG, "Server Request Added!!");
+    OIC_LOG(INFO, TAG, "Server Request Added!!");
     LL_APPEND (serverRequestList, serverRequest);
     return OC_STACK_OK;
 
@@ -442,7 +441,7 @@ CAResponseResult_t ConvertEHResultToCAResult (OCEntityHandlerResult result, OCMe
                    // This should not happen but,
                    // give it a value just in case but output an error
                    caResult = CA_CONTENT;
-                   OC_LOG_V(ERROR, TAG, "Unexpected OC_EH_OK return code for method [d].", method);
+                   OIC_LOG_V(ERROR, TAG, "Unexpected OC_EH_OK return code for method [%d].", method);
            }
             break;
         case OC_EH_ERROR:
@@ -488,6 +487,7 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
 
     if(!ehResponse || !ehResponse->requestHandle)
     {
+        OIC_LOG(ERROR, TAG, "ehResponse/requestHandle is NULL");
         return OC_STACK_ERROR;
     }
 
@@ -522,7 +522,7 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
     }
     else
     {
-        OC_LOG(ERROR, TAG, "default responseInfo type is NON");
+        OIC_LOG(ERROR, TAG, "default responseInfo type is NON");
         responseInfo.info.type = CA_MSG_NONCONFIRM;
     }
 
@@ -550,7 +550,7 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
 
         if(!responseInfo.info.options)
         {
-            OC_LOG(FATAL, TAG, "Memory alloc for options failed");
+            OIC_LOG(FATAL, TAG, "Memory alloc for options failed");
             return OC_STACK_NO_MEMORY;
         }
 
@@ -614,7 +614,7 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
                                 &responseInfo.info.payloadSize))
                         != OC_STACK_OK)
                 {
-                    OC_LOG(ERROR, TAG, "Error converting payload");
+                    OIC_LOG(ERROR, TAG, "Error converting payload");
                     OICFree(responseInfo.info.options);
                     return result;
                 }
@@ -629,8 +629,8 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
     CATransportAdapter_t CAConnTypes[] = {
                             CA_ADAPTER_IP,
                             CA_ADAPTER_GATT_BTLE,
-                            CA_ADAPTER_RFCOMM_BTEDR
-
+                            CA_ADAPTER_RFCOMM_BTEDR,
+                            CA_ADAPTER_NFC
 #ifdef RA_ADAPTER
                             , CA_ADAPTER_REMOTE_ACCESS
 #endif
@@ -647,8 +647,8 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
             (CATransportAdapter_t)(
                 CA_ADAPTER_IP           |
                 CA_ADAPTER_GATT_BTLE    |
-                CA_ADAPTER_RFCOMM_BTEDR
-
+                CA_ADAPTER_RFCOMM_BTEDR |
+                CA_ADAPTER_NFC
 #ifdef RA_ADAP
                 | CA_ADAPTER_REMOTE_ACCESS
 #endif
@@ -675,11 +675,11 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
     }
 #else
 
-    OC_LOG(INFO, TAG, "Calling OCSendResponse with:");
-    OC_LOG_V(INFO, TAG, "\tEndpoint address: %s", responseEndpoint.addr);
-    OC_LOG_V(INFO, TAG, "\tEndpoint adapter: %s", responseEndpoint.adapter);
-    OC_LOG_V(INFO, TAG, "\tResponse result : %s", responseInfo.result);
-    OC_LOG_V(INFO, TAG, "\tResponse for uri: %s", responseInfo.info.resourceUri);
+    OIC_LOG(INFO, TAG, "Calling OCSendResponse with:");
+    OIC_LOG_V(INFO, TAG, "\tEndpoint address: %s", responseEndpoint.addr);
+    OIC_LOG_V(INFO, TAG, "\tEndpoint adapter: %s", responseEndpoint.adapter);
+    OIC_LOG_V(INFO, TAG, "\tResponse result : %s", responseInfo.result);
+    OIC_LOG_V(INFO, TAG, "\tResponse for uri: %s", responseInfo.info.resourceUri);
 
     result = OCSendResponse(&responseEndpoint, &responseInfo);
 #endif
@@ -707,11 +707,11 @@ OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
 {
     if(!ehResponse || !ehResponse->payload)
     {
-        OC_LOG(ERROR, TAG, "HandleAggregateResponse invalid parameters");
+        OIC_LOG(ERROR, TAG, "HandleAggregateResponse invalid parameters");
         return OC_STACK_INVALID_PARAM;
     }
 
-    OC_LOG(INFO, TAG, "Inside HandleAggregateResponse");
+    OIC_LOG(INFO, TAG, "Inside HandleAggregateResponse");
 
     OCServerRequest *serverRequest = GetServerRequestUsingHandle((OCServerRequest *)
                                                                  ehResponse->requestHandle);
@@ -723,11 +723,11 @@ OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
     {
         if(!serverResponse)
         {
-            OC_LOG(INFO, TAG, "This is the first response fragment");
+            OIC_LOG(INFO, TAG, "This is the first response fragment");
             stackRet = AddServerResponse(&serverResponse, ehResponse->requestHandle);
             if (OC_STACK_OK != stackRet)
             {
-                OC_LOG(ERROR, TAG, "Error adding server response");
+                OIC_LOG(ERROR, TAG, "Error adding server response");
                 return stackRet;
             }
             VERIFY_NON_NULL(serverResponse);
@@ -736,18 +736,20 @@ OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
         if(ehResponse->payload->type != PAYLOAD_TYPE_REPRESENTATION)
         {
             stackRet = OC_STACK_ERROR;
-            OC_LOG(ERROR, TAG, "Error adding payload, as it was the incorrect type");
+            OIC_LOG(ERROR, TAG, "Error adding payload, as it was the incorrect type");
             goto exit;
         }
 
+        OCRepPayload *newPayload = OCRepPayloadClone((OCRepPayload *)ehResponse->payload);
+
         if(!serverResponse->payload)
         {
-            serverResponse->payload = ehResponse->payload;
+            serverResponse->payload = (OCPayload *)newPayload;
         }
         else
         {
             OCRepPayloadAppend((OCRepPayload*)serverResponse->payload,
-                    (OCRepPayload*)ehResponse->payload);
+                    (OCRepPayload*)newPayload);
         }
 
 
@@ -755,7 +757,7 @@ OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
 
         if(serverRequest->numResponses == 0)
         {
-            OC_LOG(INFO, TAG, "This is the last response fragment");
+            OIC_LOG(INFO, TAG, "This is the last response fragment");
             ehResponse->payload = serverResponse->payload;
             stackRet = HandleSingleResponse(ehResponse);
             //Delete the request and response
@@ -764,7 +766,7 @@ OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
         }
         else
         {
-            OC_LOG(INFO, TAG, "More response fragments to come");
+            OIC_LOG(INFO, TAG, "More response fragments to come");
             stackRet = OC_STACK_OK;
         }
     }
old mode 100755 (executable)
new mode 100644 (file)
index 24486de..5ca4deb
 // For POSIX.1-2001 base specification,
 // Refer http://pubs.opengroup.org/onlinepubs/009695399/
 #define _POSIX_C_SOURCE 200112L
+#ifndef __STDC_FORMAT_MACROS
+#define __STDC_FORMAT_MACROS
+#endif
+#ifndef __STDC_LIMIT_MACROS
+#define __STDC_LIMIT_MACROS
+#endif
+#include <inttypes.h>
 #include <string.h>
 #include <ctype.h>
 
 #endif
 #endif
 
+#ifdef TCP_ADAPTER
+#include "oickeepalive.h"
+#endif
+
+//#ifdef DIRECT_PAIRING
+#include "directpairing.h"
+//#endif
+
 #ifdef WITH_ARDUINO
 #include "Time.h"
 #else
@@ -117,17 +132,21 @@ OCDeviceEntityHandler defaultDeviceHandler;
 void* defaultDeviceHandlerCallbackParameter = NULL;
 static const char COAP_TCP[] = "coap+tcp:";
 
+//#ifdef DIRECT_PAIRING
+OCDirectPairingCB gDirectpairingCallback = NULL;
+//#endif
+
 //-----------------------------------------------------------------------------
 // Macros
 //-----------------------------------------------------------------------------
-#define TAG  "OCStack"
+#define TAG  "OIC_RI_STACK"
 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
-            {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
-#define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
+            {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
+#define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
              TAG, #arg " is NULL"); return (retVal); } }
-#define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OC_LOG((logLevel), \
+#define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
              TAG, #arg " is NULL"); return; } }
-#define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG(FATAL, TAG, #arg " is NULL");\
+#define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
     goto exit;} }
 
 //TODO: we should allow the server to define this
@@ -459,11 +478,10 @@ static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *
     VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
 
 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
-    OCStackResult rmResult = RMAddInfo(object->routeData, &(requestInfo->info.options),
-                                     &(requestInfo->info.numOptions));
+    OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
     if (OC_STACK_OK != rmResult)
     {
-        OC_LOG(ERROR, TAG, "Add destination option failed");
+        OIC_LOG(ERROR, TAG, "Add destination option failed");
         return rmResult;
     }
 #endif
@@ -473,7 +491,7 @@ static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *
     CAResult_t result = CASendRequest(object, requestInfo);
     if(CA_STATUS_OK != result)
     {
-        OC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
+        OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
         return CAResultToOCResult(result);
     }
     return OC_STACK_OK;
@@ -493,7 +511,7 @@ OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t stat
     switch(status)
     {
     case OC_OBSERVER_NOT_INTERESTED:
-        OC_LOG(DEBUG, TAG, "observer not interested in our notifications");
+        OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
         observer = GetObserverUsingToken (token, tokenLength);
         if(observer)
         {
@@ -517,17 +535,17 @@ OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t stat
         result = DeleteObserverUsingToken (token, tokenLength);
         if(result == OC_STACK_OK)
         {
-            OC_LOG(DEBUG, TAG, "Removed observer successfully");
+            OIC_LOG(DEBUG, TAG, "Removed observer successfully");
         }
         else
         {
             result = OC_STACK_OK;
-            OC_LOG(DEBUG, TAG, "Observer Removal failed");
+            OIC_LOG(DEBUG, TAG, "Observer Removal failed");
         }
         break;
 
     case OC_OBSERVER_STILL_INTERESTED:
-        OC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
+        OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
         observer = GetObserverUsingToken (token, tokenLength);
         if(observer)
         {
@@ -542,7 +560,7 @@ OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t stat
         break;
 
     case OC_OBSERVER_FAILED_COMM:
-        OC_LOG(DEBUG, TAG, "observer is unreachable");
+        OIC_LOG(DEBUG, TAG, "observer is unreachable");
         observer = GetObserverUsingToken (token, tokenLength);
         if(observer)
         {
@@ -567,12 +585,12 @@ OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t stat
                 result = DeleteObserverUsingToken (token, tokenLength);
                 if(result == OC_STACK_OK)
                 {
-                    OC_LOG(DEBUG, TAG, "Removed observer successfully");
+                    OIC_LOG(DEBUG, TAG, "Removed observer successfully");
                 }
                 else
                 {
                     result = OC_STACK_OK;
-                    OC_LOG(DEBUG, TAG, "Observer Removal failed");
+                    OIC_LOG(DEBUG, TAG, "Observer Removal failed");
                 }
             }
             else
@@ -581,11 +599,11 @@ OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t stat
                 result = OC_STACK_CONTINUE;
             }
             observer->forceHighQos = 1;
-            OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
+            OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
         }
         break;
     default:
-        OC_LOG(ERROR, TAG, "Unknown status");
+        OIC_LOG(ERROR, TAG, "Unknown status");
         result = OC_STACK_ERROR;
         break;
         }
@@ -605,6 +623,7 @@ OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
             break;
         case CA_CHANGED:
         case CA_CONTENT:
+        case CA_VALID:
             ret = OC_STACK_OK;
             break;
         case CA_BAD_REQ:
@@ -652,7 +671,7 @@ CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
                    // This should not happen but,
                    // give it a value just in case but output an error
                    ret = CA_CONTENT;
-                   OC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].", method);
+                   OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].", method);
             }
             break;
         case OC_STACK_RESOURCE_CREATED:
@@ -713,7 +732,7 @@ static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
         return OC_STACK_INVALID_PARAM;
     }
 
-    OC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
+    OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
 
     cbNode->presence->TTL = maxAgeSeconds;
 
@@ -746,14 +765,14 @@ static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
 
         cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
 
-        OC_LOG_V(DEBUG, TAG, "lowerBound timeout  %d", lowerBound);
-        OC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
-        OC_LOG_V(DEBUG, TAG, "timeOut entry  %d", cbNode->presence->timeOut[index]);
+        OIC_LOG_V(DEBUG, TAG, "lowerBound timeout  %d", lowerBound);
+        OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
+        OIC_LOG_V(DEBUG, TAG, "timeOut entry  %d", cbNode->presence->timeOut[index]);
     }
 
     cbNode->presence->TTLlevel = 0;
 
-    OC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
+    OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
     return OC_STACK_OK;
 }
 
@@ -859,7 +878,7 @@ OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
 
     if (responseInfo->result != CA_CONTENT)
     {
-        OC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
+        OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
         return OC_STACK_ERROR;
     }
 
@@ -892,7 +911,7 @@ OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
 
     if (!presenceSubscribe && !multicastPresenceSubscribe)
     {
-        OC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
+        OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
         goto exit;
     }
 
@@ -911,12 +930,12 @@ OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
 
         if(result != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "Presence parse failed");
+            OIC_LOG(ERROR, TAG, "Presence parse failed");
             goto exit;
         }
         if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
         {
-            OC_LOG(ERROR, TAG, "Presence payload was wrong type");
+            OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
             result = OC_STACK_ERROR;
             goto exit;
         }
@@ -929,15 +948,15 @@ OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
     {
         if(cbNode->sequenceNumber == response.sequenceNumber)
         {
-            OC_LOG(INFO, TAG, "No presence change");
+            OIC_LOG(INFO, TAG, "No presence change");
             ResetPresenceTTL(cbNode, maxAge);
-            OC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
+            OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
             goto exit;
         }
 
         if(maxAge == 0)
         {
-            OC_LOG(INFO, TAG, "Stopping presence");
+            OIC_LOG(INFO, TAG, "Stopping presence");
             response.result = OC_STACK_PRESENCE_STOPPED;
             if(cbNode->presence)
             {
@@ -954,7 +973,7 @@ OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
 
                 if(!(cbNode->presence))
                 {
-                    OC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
+                    OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
                     result = OC_STACK_NO_MEMORY;
                     goto exit;
                 }
@@ -964,7 +983,7 @@ OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
                 cbNode->presence->timeOut = (uint32_t *)
                         OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
                 if(!(cbNode->presence->timeOut)){
-                    OC_LOG(ERROR, TAG,
+                    OIC_LOG(ERROR, TAG,
                                   "Could not allocate memory for cbNode->presence->timeOut");
                     OICFree(cbNode->presence);
                     result = OC_STACK_NO_MEMORY;
@@ -996,14 +1015,14 @@ OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
         {
             if(mcNode->nonce == response.sequenceNumber)
             {
-                OC_LOG(INFO, TAG, "No presence change (Multicast)");
+                OIC_LOG(INFO, TAG, "No presence change (Multicast)");
                 goto exit;
             }
             mcNode->nonce = response.sequenceNumber;
 
             if(maxAge == 0)
             {
-                OC_LOG(INFO, TAG, "Stopping presence");
+                OIC_LOG(INFO, TAG, "Stopping presence");
                 response.result = OC_STACK_PRESENCE_STOPPED;
             }
         }
@@ -1012,7 +1031,7 @@ OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
             char* uri = OICStrdup(presenceUri);
             if (!uri)
             {
-                OC_LOG(INFO, TAG,
+                OIC_LOG(INFO, TAG,
                     "No Memory for URI to store in the presence node");
                 result = OC_STACK_NO_MEMORY;
                 goto exit;
@@ -1021,7 +1040,7 @@ OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
             result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
             if(result == OC_STACK_NO_MEMORY)
             {
-                OC_LOG(INFO, TAG,
+                OIC_LOG(INFO, TAG,
                     "No Memory for Multicast Presence Node");
                 OICFree(uri);
                 goto exit;
@@ -1051,40 +1070,9 @@ exit:
     return result;
 }
 
-void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
+void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
 {
-    VERIFY_NON_NULL_NR(endPoint, FATAL);
-    VERIFY_NON_NULL_NR(responseInfo, FATAL);
-
-    OC_LOG(INFO, TAG, "Enter HandleCAResponses");
-
-#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
-#ifdef ROUTING_GATEWAY
-    bool needRIHandling = false;
-    /*
-     * Routing manager is going to update either of endpoint or response or both.
-     * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
-     * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
-     * destination.
-     */
-    OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
-                                         &needRIHandling);
-    if(ret != OC_STACK_OK || !needRIHandling)
-    {
-        OC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
-        return;
-    }
-#endif
-
-    /*
-     * Put source in sender endpoint so that the next packet from application can be routed to
-     * proper destination and remove "RM" coap header option before passing request / response to
-     * RI as this option will make no sense to either RI or application.
-     */
-    RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
-                 (uint8_t *) &(responseInfo->info.numOptions),
-                 (CAEndpoint_t *) endPoint);
-#endif
+    OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
 
     if(responseInfo->info.resourceUri &&
         strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
@@ -1101,23 +1089,23 @@ void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* res
 
     if(cbNode)
     {
-        OC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
+        OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
         if(responseInfo->result == CA_EMPTY)
         {
-            OC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
+            OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
             // We do not have a case for the client to receive a RESET
             if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
             {
                 //This is the case of receiving an ACK on a request to a slow resource!
-                OC_LOG(INFO, TAG, "This is a pure ACK");
+                OIC_LOG(INFO, TAG, "This is a pure ACK");
                 //TODO: should we inform the client
                 //      app that at least the request was received at the server?
             }
         }
         else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
         {
-            OC_LOG(INFO, TAG, "Receiving A Timeout for this token");
-            OC_LOG(INFO, TAG, "Calling into application address space");
+            OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
+            OIC_LOG(INFO, TAG, "Calling into application address space");
 
             OCClientResponse response =
                 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
@@ -1135,8 +1123,8 @@ void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* res
         }
         else
         {
-            OC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
-            OC_LOG(INFO, TAG, "Calling into application address space");
+            OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
+            OIC_LOG(INFO, TAG, "Calling into application address space");
 
             OCClientResponse response =
                 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
@@ -1184,9 +1172,15 @@ void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* res
                     {
                         type = PAYLOAD_TYPE_RD;
                     }
+#ifdef TCP_ADAPTER
+                    else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
+                    {
+                        type = PAYLOAD_TYPE_REPRESENTATION;
+                    }
+#endif
                     else
                     {
-                        OC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
+                        OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
                                 cbNode->method, cbNode->requestUri);
                         return;
                     }
@@ -1199,22 +1193,30 @@ void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* res
                          cbNode->method == OC_REST_DELETE)
                 {
                     char targetUri[MAX_URI_LENGTH];
-                    snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s",
-                            OC_RSRVD_RD_URI, OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
+                    snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
+                            OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
                     if (strcmp(targetUri, cbNode->requestUri) == 0)
                     {
                         type = PAYLOAD_TYPE_RD;
                     }
+                    else if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
+                    {
+                        type = PAYLOAD_TYPE_PLATFORM;
+                    }
+                    else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
+                    {
+                        type = PAYLOAD_TYPE_DEVICE;
+                    }
                     if (type == PAYLOAD_TYPE_INVALID)
                     {
-                        OC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
+                        OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
                                 cbNode->method, cbNode->requestUri);
                         type = PAYLOAD_TYPE_REPRESENTATION;
                     }
                 }
                 else
                 {
-                    OC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
+                    OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
                             cbNode->method, cbNode->requestUri);
                     return;
                 }
@@ -1224,7 +1226,7 @@ void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* res
                             responseInfo->info.payload,
                             responseInfo->info.payloadSize))
                 {
-                    OC_LOG(ERROR, TAG, "Error converting payload");
+                    OIC_LOG(ERROR, TAG, "Error converting payload");
                     OCPayloadDestroy(response.payload);
                     return;
                 }
@@ -1259,7 +1261,7 @@ void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* res
 
                 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
                 {
-                    OC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
+                    OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
                     OCPayloadDestroy(response.payload);
                     return;
                 }
@@ -1275,7 +1277,7 @@ void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* res
                 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
                 response.sequenceNumber <= cbNode->sequenceNumber)
             {
-                OC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
+                OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
                                                  response.sequenceNumber);
             }
             else
@@ -1311,26 +1313,26 @@ void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* res
 
     if(observer)
     {
-        OC_LOG(INFO, TAG, "There is an observer associated with the response token");
+        OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
         if(responseInfo->result == CA_EMPTY)
         {
-            OC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
+            OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
             if(responseInfo->info.type == CA_MSG_RESET)
             {
-                OC_LOG(INFO, TAG, "This is a RESET");
+                OIC_LOG(INFO, TAG, "This is a RESET");
                 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
                         OC_OBSERVER_NOT_INTERESTED);
             }
             else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
             {
-                OC_LOG(INFO, TAG, "This is a pure ACK");
+                OIC_LOG(INFO, TAG, "This is a pure ACK");
                 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
                         OC_OBSERVER_STILL_INTERESTED);
             }
         }
         else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
         {
-            OC_LOG(INFO, TAG, "Receiving Time Out for an observer");
+            OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
             OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
                     OC_OBSERVER_FAILED_COMM);
         }
@@ -1342,14 +1344,14 @@ void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* res
         if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
            || myStackMode == OC_GATEWAY)
         {
-            OC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
+            OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
             if(responseInfo->result == CA_EMPTY)
             {
-                OC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
+                OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
             }
             else
             {
-                OC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
+                OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
                 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
                         CA_MSG_RESET, 0, NULL, NULL, 0, NULL);
             }
@@ -1358,15 +1360,15 @@ void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* res
         if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
            || myStackMode == OC_GATEWAY)
         {
-            OC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
+            OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
             if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
             {
-                OC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
+                OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
                                             responseInfo->info.messageId);
             }
             if (responseInfo->info.type == CA_MSG_RESET)
             {
-                OC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
+                OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
                                             responseInfo->info.messageId);
             }
         }
@@ -1374,7 +1376,47 @@ void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* res
         return;
     }
 
-    OC_LOG(INFO, TAG, "Exit HandleCAResponses");
+    OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
+}
+
+void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
+{
+    VERIFY_NON_NULL_NR(endPoint, FATAL);
+    VERIFY_NON_NULL_NR(responseInfo, FATAL);
+
+    OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
+
+#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
+#ifdef ROUTING_GATEWAY
+    bool needRIHandling = false;
+    /*
+     * Routing manager is going to update either of endpoint or response or both.
+     * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
+     * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
+     * destination.
+     */
+    OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
+                                         &needRIHandling);
+    if(ret != OC_STACK_OK || !needRIHandling)
+    {
+        OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
+        return;
+    }
+#endif
+
+    /*
+     * Put source in sender endpoint so that the next packet from application can be routed to
+     * proper destination and remove "RM" coap header option before passing request / response to
+     * RI as this option will make no sense to either RI or application.
+     */
+    RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
+                 (uint8_t *) &(responseInfo->info.numOptions),
+                 (CAEndpoint_t *) endPoint);
+#endif
+
+    OCHandleResponse(endPoint, responseInfo);
+
+    OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
 }
 
 /*
@@ -1383,20 +1425,20 @@ void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* res
  */
 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errrorInfo)
 {
-    OC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
+    OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
 
     if(NULL == endPoint)
     {
-        OC_LOG(ERROR, TAG, "endPoint is NULL");
+        OIC_LOG(ERROR, TAG, "endPoint is NULL");
         return;
     }
 
     if(NULL == errrorInfo)
     {
-        OC_LOG(ERROR, TAG, "errrorInfo is NULL");
+        OIC_LOG(ERROR, TAG, "errrorInfo is NULL");
         return;
     }
-    OC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
+    OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
 }
 
 /*
@@ -1409,6 +1451,7 @@ OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16
         const uint8_t numOptions, const CAHeaderOption_t *options,
         CAToken_t token, uint8_t tokenLength, const char *resourceUri)
 {
+    OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
     CAResponseInfo_t respInfo = {
         .result = responseResult
     };
@@ -1433,72 +1476,147 @@ OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16
 
 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
     // Add the destination to route option from the endpoint->routeData.
-    OCStackResult result = RMAddInfo(endPoint->routeData,
-                                     &(respInfo.info.options),
-                                     &(respInfo.info.numOptions));
+    bool doPost = false;
+    OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
     if(OC_STACK_OK != result)
     {
-        OC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
+        OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
         return result;
     }
-#endif
-
-    CAResult_t caResult = CASendResponse(endPoint, &respInfo);
+    if (doPost)
+    {
+        OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
+        CARequestInfo_t reqInfo = {.method = CA_POST };
+        /* The following initialization is not done in a single initializer block as in
+         * arduino, .c file is compiled as .cpp and moves it from C99 to C++11.  The latter
+         * does not have designated initalizers. This is a work-around for now.
+         */
+        reqInfo.info.type = CA_MSG_NONCONFIRM;
+        reqInfo.info.messageId = coapID;
+        reqInfo.info.tokenLength = tokenLength;
+        reqInfo.info.token = token;
+        reqInfo.info.numOptions = respInfo.info.numOptions;
+        reqInfo.info.payload = NULL;
+        reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
+        if (reqInfo.info.numOptions)
+        {
+            reqInfo.info.options =
+                (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
+            if (NULL == reqInfo.info.options)
+            {
+                OIC_LOG(ERROR, TAG, "Calloc failed");
+                return OC_STACK_NO_MEMORY;
+            }
+            memcpy (reqInfo.info.options, respInfo.info.options,
+                    sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
 
-    // resourceUri in the info field is cloned in the CA layer and
-    // thus ownership is still here.
-    OICFree (respInfo.info.resourceUri);
-    OICFree (respInfo.info.options);
-    if(CA_STATUS_OK != caResult)
+        }
+        CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
+        OICFree (reqInfo.info.resourceUri);
+        OICFree (reqInfo.info.options);
+        OICFree (respInfo.info.resourceUri);
+        OICFree (respInfo.info.options);
+        if (CA_STATUS_OK != caResult)
+        {
+            OIC_LOG(ERROR, TAG, "CASendRequest error");
+            return CAResultToOCResult(caResult);
+        }
+    }
+    else
+#endif
     {
-        OC_LOG(ERROR, TAG, "CASendResponse error");
-        return CAResultToOCResult(caResult);
+        CAResult_t caResult = CASendResponse(endPoint, &respInfo);
+
+        // resourceUri in the info field is cloned in the CA layer and
+        // thus ownership is still here.
+        OICFree (respInfo.info.resourceUri);
+        OICFree (respInfo.info.options);
+        if(CA_STATUS_OK != caResult)
+        {
+            OIC_LOG(ERROR, TAG, "CASendResponse error");
+            return CAResultToOCResult(caResult);
+        }
     }
+    OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
     return OC_STACK_OK;
 }
 
-//This function will be called back by CA layer when a request is received
-void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
+OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
 {
-    OC_LOG(INFO, TAG, "Enter HandleCARequests");
-    if(!endPoint)
+    OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
+    OCStackResult result = OC_STACK_ERROR;
+    if(!protocolRequest)
     {
-        OC_LOG(ERROR, TAG, "endPoint is NULL");
-        return;
+        OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
+        return OC_STACK_INVALID_PARAM;
     }
 
-    if(!requestInfo)
+    OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
+            protocolRequest->tokenLength);
+    if(!request)
     {
-        OC_LOG(ERROR, TAG, "requestInfo is NULL");
-        return;
+        OIC_LOG(INFO, TAG, "This is a new Server Request");
+        result = AddServerRequest(&request, protocolRequest->coapID,
+                protocolRequest->delayedResNeeded, 0, protocolRequest->method,
+                protocolRequest->numRcvdVendorSpecificHeaderOptions,
+                protocolRequest->observationOption, protocolRequest->qos,
+                protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
+                protocolRequest->payload, protocolRequest->requestToken,
+                protocolRequest->tokenLength, protocolRequest->resourceUrl,
+                protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
+                &protocolRequest->devAddr);
+        if (OC_STACK_OK != result)
+        {
+            OIC_LOG(ERROR, TAG, "Error adding server request");
+            return result;
+        }
+
+        if(!request)
+        {
+            OIC_LOG(ERROR, TAG, "Out of Memory");
+            return OC_STACK_NO_MEMORY;
+        }
+
+        if(!protocolRequest->reqMorePacket)
+        {
+            request->requestComplete = 1;
+        }
+    }
+    else
+    {
+        OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
     }
 
-#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
-#ifdef ROUTING_GATEWAY
-    bool needRIHandling = false;
-    /*
-     * Routing manager is going to update either of endpoint or request or both.
-     * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
-     * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
-     * destination. It can also remove "RM" coap header option before passing request / response to
-     * RI as this option will make no sense to either RI or application.
-     */
-    OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
-                                     &needRIHandling);
-    if(OC_STACK_OK != ret || !needRIHandling)
+    if(request->requestComplete)
     {
-        OC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
-        return;
+        OIC_LOG(INFO, TAG, "This Server Request is complete");
+        ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
+        OCResource *resource = NULL;
+        result = DetermineResourceHandling (request, &resHandling, &resource);
+        if (result == OC_STACK_OK)
+        {
+            result = ProcessRequest(resHandling, resource, request);
+        }
     }
-#endif
+    else
+    {
+        OIC_LOG(INFO, TAG, "This Server Request is incomplete");
+        result = OC_STACK_CONTINUE;
+    }
+    return result;
+}
 
-    /*
-     * Put source in sender endpoint so that the next packet from application can be routed to
-     * proper destination and remove RM header option.
-     */
-    RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
-                 (uint8_t *) &(requestInfo->info.numOptions),
-                 (CAEndpoint_t *) endPoint);
+void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
+{
+    OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
+
+#ifdef TCP_ADAPTER
+    if (requestInfo->info.resourceUri &&
+            strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
+    {
+        HandleKeepAliveRequest(endPoint, requestInfo);
+        return;
+    }
 #endif
 
     OCStackResult requestResult = OC_STACK_ERROR;
@@ -1511,7 +1629,7 @@ void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* reque
 
     OCServerProtocolRequest serverRequest = {0};
 
-    OC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
+    OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
 
     char * uriWithoutQuery = NULL;
     char * query  = NULL;
@@ -1520,11 +1638,11 @@ void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* reque
 
     if (requestResult != OC_STACK_OK || !uriWithoutQuery)
     {
-        OC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
+        OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
         return;
     }
-    OC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
-    OC_LOG_V(INFO, TAG, "Query : %s", query);
+    OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
+    OIC_LOG_V(INFO, TAG, "Query : %s", query);
 
     if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
     {
@@ -1533,7 +1651,7 @@ void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* reque
     }
     else
     {
-        OC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
+        OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
         OICFree(uriWithoutQuery);
         OICFree(query);
         return;
@@ -1548,7 +1666,7 @@ void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* reque
         }
         else
         {
-            OC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
+            OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
             OICFree(query);
             return;
         }
@@ -1581,7 +1699,7 @@ void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* reque
             serverRequest.method = OC_REST_DELETE;
             break;
         default:
-            OC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
+            OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
             SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
                         requestInfo->info.type, requestInfo->info.numOptions,
                         requestInfo->info.options, requestInfo->info.token,
@@ -1590,22 +1708,26 @@ void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* reque
             return;
     }
 
-    OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
+    OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
             requestInfo->info.tokenLength);
-    serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
+
     serverRequest.tokenLength = requestInfo->info.tokenLength;
+    if (serverRequest.tokenLength) {
+        // Non empty token
+        serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
 
-    if (!serverRequest.requestToken)
-    {
-        OC_LOG(FATAL, TAG, "Allocation for token failed.");
-        SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
-                requestInfo->info.type, requestInfo->info.numOptions,
-                requestInfo->info.options, requestInfo->info.token,
-                requestInfo->info.tokenLength, requestInfo->info.resourceUri);
-        OICFree(serverRequest.payload);
-        return;
+        if (!serverRequest.requestToken)
+        {
+            OIC_LOG(FATAL, TAG, "Allocation for token failed.");
+            SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
+                    requestInfo->info.type, requestInfo->info.numOptions,
+                    requestInfo->info.options, requestInfo->info.token,
+                    requestInfo->info.tokenLength, requestInfo->info.resourceUri);
+            OICFree(serverRequest.payload);
+            return;
+        }
+        memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
     }
-    memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
 
     switch (requestInfo->info.acceptFormat)
     {
@@ -1646,7 +1768,7 @@ void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* reque
     GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
     if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
     {
-        OC_LOG(ERROR, TAG,
+        OIC_LOG(ERROR, TAG,
                 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
         SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
                 requestInfo->info.type, requestInfo->info.numOptions,
@@ -1666,14 +1788,17 @@ void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* reque
     requestResult = HandleStackRequests (&serverRequest);
 
     // Send ACK to client as precursor to slow response
-    if(requestResult == OC_STACK_SLOW_RESOURCE)
+    if (requestResult == OC_STACK_SLOW_RESOURCE)
     {
-        SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
-                    CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
+        if (requestInfo->info.type == CA_MSG_CONFIRM)
+        {
+            SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
+                                    CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
+        }
     }
     else if(requestResult != OC_STACK_OK)
     {
-        OC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
+        OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
 
         CAResponseResult_t stackResponse =
             OCToCAStackResult(requestResult, serverRequest.method);
@@ -1687,72 +1812,76 @@ void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* reque
     // The token is copied in there, and is thus still owned by this function.
     OICFree(serverRequest.payload);
     OICFree(serverRequest.requestToken);
-    OC_LOG(INFO, TAG, "Exit HandleCARequests");
+    OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
 }
 
-OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
+//This function will be called back by CA layer when a request is received
+void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
 {
-    OC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
-    OCStackResult result = OC_STACK_ERROR;
-    ResourceHandling resHandling;
-    OCResource *resource;
-    if(!protocolRequest)
+    OIC_LOG(INFO, TAG, "Enter HandleCARequests");
+    if(!endPoint)
     {
-        OC_LOG(ERROR, TAG, "protocolRequest is NULL");
-        return OC_STACK_INVALID_PARAM;
+        OIC_LOG(ERROR, TAG, "endPoint is NULL");
+        return;
     }
 
-    OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
-            protocolRequest->tokenLength);
-    if(!request)
+    if(!requestInfo)
     {
-        OC_LOG(INFO, TAG, "This is a new Server Request");
-        result = AddServerRequest(&request, protocolRequest->coapID,
-                protocolRequest->delayedResNeeded, 0, protocolRequest->method,
-                protocolRequest->numRcvdVendorSpecificHeaderOptions,
-                protocolRequest->observationOption, protocolRequest->qos,
-                protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
-                protocolRequest->payload, protocolRequest->requestToken,
-                protocolRequest->tokenLength, protocolRequest->resourceUrl,
-                protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
-                &protocolRequest->devAddr);
-        if (OC_STACK_OK != result)
-        {
-            OC_LOG(ERROR, TAG, "Error adding server request");
-            return result;
-        }
-
-        if(!request)
-        {
-            OC_LOG(ERROR, TAG, "Out of Memory");
-            return OC_STACK_NO_MEMORY;
-        }
-
-        if(!protocolRequest->reqMorePacket)
-        {
-            request->requestComplete = 1;
-        }
+        OIC_LOG(ERROR, TAG, "requestInfo is NULL");
+        return;
     }
-    else
+
+#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
+#ifdef ROUTING_GATEWAY
+    bool needRIHandling = false;
+    bool isEmptyMsg = false;
+    /*
+     * Routing manager is going to update either of endpoint or request or both.
+     * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
+     * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
+     * destination. It can also remove "RM" coap header option before passing request / response to
+     * RI as this option will make no sense to either RI or application.
+     */
+    OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
+                                        &needRIHandling, &isEmptyMsg);
+    if(OC_STACK_OK != ret || !needRIHandling)
     {
-        OC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
+        OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
+        return;
     }
+#endif
 
-    if(request->requestComplete)
-    {
-        OC_LOG(INFO, TAG, "This Server Request is complete");
-        result = DetermineResourceHandling (request, &resHandling, &resource);
-        if (result == OC_STACK_OK)
-        {
-            result = ProcessRequest(resHandling, resource, request);
-        }
+    /*
+     * Put source in sender endpoint so that the next packet from application can be routed to
+     * proper destination and remove RM header option.
+     */
+    RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
+                 (uint8_t *) &(requestInfo->info.numOptions),
+                 (CAEndpoint_t *) endPoint);
+
+#ifdef ROUTING_GATEWAY
+    if (isEmptyMsg)
+    {
+        /*
+         * In Gateways, the MSGType in route option is used to check if the actual
+         * response is EMPTY message(4 bytes CoAP Header).  In case of Client, the
+         * EMPTY response is sent in the form of POST request which need to be changed
+         * to a EMPTY response by RM.  This translation is done in this part of the code.
+         */
+        OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
+        CAResponseInfo_t respInfo = {.result = CA_EMPTY,
+                                     .info.messageId = requestInfo->info.messageId,
+                                     .info.type = CA_MSG_ACKNOWLEDGE};
+        OCHandleResponse(endPoint, &respInfo);
     }
     else
+#endif
+#endif
     {
-        OC_LOG(INFO, TAG, "This Server Request is incomplete");
-        result = OC_STACK_CONTINUE;
+        // Normal handling of the packet
+        OCHandleRequests(endPoint, requestInfo);
     }
-    return result;
+    OIC_LOG(INFO, TAG, "Exit HandleCARequests");
 }
 
 bool validatePlatformInfo(OCPlatformInfo info)
@@ -1760,7 +1889,7 @@ bool validatePlatformInfo(OCPlatformInfo info)
 
     if (!info.platformID)
     {
-        OC_LOG(ERROR, TAG, "No platform ID found.");
+        OIC_LOG(ERROR, TAG, "No platform ID found.");
         return false;
     }
 
@@ -1770,13 +1899,13 @@ bool validatePlatformInfo(OCPlatformInfo info)
 
         if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
         {
-            OC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
+            OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
             return false;
         }
     }
     else
     {
-        OC_LOG(ERROR, TAG, "No manufacturer name present");
+        OIC_LOG(ERROR, TAG, "No manufacturer name present");
         return false;
     }
 
@@ -1784,7 +1913,7 @@ bool validatePlatformInfo(OCPlatformInfo info)
     {
         if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
         {
-            OC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
+            OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
             return false;
         }
     }
@@ -1823,7 +1952,7 @@ OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlag
 {
     if(stackState == OC_STACK_INITIALIZED)
     {
-        OC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
+        OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
                 OCStop() between them are ignored.");
         return OC_STACK_OK;
     }
@@ -1831,7 +1960,7 @@ OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlag
 #ifndef ROUTING_GATEWAY
     if (OC_GATEWAY == mode)
     {
-        OC_LOG(ERROR, TAG, "Routing Manager not supported");
+        OIC_LOG(ERROR, TAG, "Routing Manager not supported");
         return OC_STACK_INVALID_PARAM;
     }
 #endif
@@ -1839,19 +1968,19 @@ OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlag
 #ifdef RA_ADAPTER
     if(!gRASetInfo)
     {
-        OC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
+        OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
         return OC_STACK_ERROR;
     }
 #endif
 
     OCStackResult result = OC_STACK_ERROR;
-    OC_LOG(INFO, TAG, "Entering OCInit");
+    OIC_LOG(INFO, TAG, "Entering OCInit");
 
     // Validate mode
     if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
         || (mode == OC_GATEWAY)))
     {
-        OC_LOG(ERROR, TAG, "Invalid mode");
+        OIC_LOG(ERROR, TAG, "Invalid mode");
         return OC_STACK_ERROR;
     }
     myStackMode = mode;
@@ -1890,12 +2019,12 @@ OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlag
         case OC_CLIENT:
             CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
             result = CAResultToOCResult(CAStartDiscoveryServer());
-            OC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
+            OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
             break;
         case OC_SERVER:
             SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
             result = CAResultToOCResult(CAStartListeningServer());
-            OC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
+            OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
             break;
         case OC_CLIENT_SERVER:
         case OC_GATEWAY:
@@ -1909,6 +2038,10 @@ OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlag
     }
     VERIFY_SUCCESS(result, OC_STACK_OK);
 
+#ifdef TCP_ADAPTER
+    CARegisterKeepAliveHandler(HandleKeepAliveConnCB, HandleKeepAliveDisconnCB);
+#endif
+
 #ifdef WITH_PRESENCE
     PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
 #endif // WITH_PRESENCE
@@ -1928,18 +2061,27 @@ OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlag
         result = SRMInitPolicyEngine();
         // TODO after BeachHead delivery: consolidate into single SRMInit()
     }
-
+#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
+    RMSetStackMode(mode);
 #ifdef ROUTING_GATEWAY
     if (OC_GATEWAY == myStackMode)
     {
         result = RMInitialize();
     }
 #endif
+#endif
+
+#ifdef TCP_ADAPTER
+    if(result == OC_STACK_OK)
+    {
+        result = InitializeKeepAlive(myStackMode);
+    }
+#endif
 
 exit:
     if(result != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "Stack initialization error");
+        OIC_LOG(ERROR, TAG, "Stack initialization error");
         deleteAllResources();
         CATerminate();
         stackState = OC_STACK_UNINITIALIZED;
@@ -1949,16 +2091,16 @@ exit:
 
 OCStackResult OCStop()
 {
-    OC_LOG(INFO, TAG, "Entering OCStop");
+    OIC_LOG(INFO, TAG, "Entering OCStop");
 
     if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
     {
-        OC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
+        OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
         return OC_STACK_OK;
     }
     else if (stackState != OC_STACK_INITIALIZED)
     {
-        OC_LOG(ERROR, TAG, "Stack not initialized");
+        OIC_LOG(ERROR, TAG, "Stack not initialized");
         return OC_STACK_ERROR;
     }
 
@@ -1977,6 +2119,10 @@ OCStackResult OCStop()
     }
 #endif
 
+#ifdef TCP_ADAPTER
+    TerminateKeepAlive(myStackMode);
+#endif
+
     // Free memory dynamically allocated for resources
     deleteAllResources();
     DeleteDeviceInfo();
@@ -2000,13 +2146,13 @@ OCStackResult OCStartMulticastServer()
 {
     if(stackState != OC_STACK_INITIALIZED)
     {
-        OC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
+        OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
         return OC_STACK_ERROR;
     }
     CAResult_t ret = CAStartListeningServer();
     if (CA_STATUS_OK != ret)
     {
-        OC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
+        OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
         return OC_STACK_ERROR;
     }
     return OC_STACK_OK;
@@ -2017,7 +2163,7 @@ OCStackResult OCStopMulticastServer()
     CAResult_t ret = CAStopListeningServer();
     if (CA_STATUS_OK != ret)
     {
-        OC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
+        OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
         return OC_STACK_ERROR;
     }
     return OC_STACK_OK;
@@ -2303,7 +2449,7 @@ OCStackResult OCDoResource(OCDoHandle *handle,
                             OCHeaderOption *options,
                             uint8_t numOptions)
 {
-    OC_LOG(INFO, TAG, "Entering OCDoResource");
+    OIC_LOG(INFO, TAG, "Entering OCDoResource");
 
     // Validate input parameters
     VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
@@ -2328,13 +2474,6 @@ OCStackResult OCDoResource(OCDoHandle *handle,
     char *resourceUri = NULL;
     char *resourceType = NULL;
 
-    // This validation is broken, but doesn't cause harm
-    size_t uriLen = strlen(requestUri );
-    if ((result = verifyUriQueryLength(requestUri , uriLen)) != OC_STACK_OK)
-    {
-        goto exit;
-    }
-
     /*
      * Support original behavior with address on resourceUri argument.
      */
@@ -2345,7 +2484,7 @@ OCStackResult OCDoResource(OCDoHandle *handle,
 
     if (result != OC_STACK_OK)
     {
-        OC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
+        OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
         goto exit;
     }
 
@@ -2396,7 +2535,7 @@ OCStackResult OCDoResource(OCDoHandle *handle,
 
     if (!devAddr && !destination)
     {
-        OC_LOG(DEBUG, TAG, "no devAddr and no destination");
+        OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
         result = OC_STACK_INVALID_PARAM;
         goto exit;
     }
@@ -2423,7 +2562,7 @@ OCStackResult OCDoResource(OCDoHandle *handle,
     caResult = CAGenerateToken(&token, tokenLength);
     if (caResult != CA_STATUS_OK)
     {
-        OC_LOG(ERROR, TAG, "CAGenerateToken error");
+        OIC_LOG(ERROR, TAG, "CAGenerateToken error");
         result= OC_STACK_ERROR;
         goto exit;
     }
@@ -2461,7 +2600,7 @@ OCStackResult OCDoResource(OCDoHandle *handle,
             OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
                 != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
+            OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
             goto exit;
         }
         requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
@@ -2475,7 +2614,7 @@ OCStackResult OCDoResource(OCDoHandle *handle,
 
     if (result != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "CACreateEndpoint error");
+        OIC_LOG(ERROR, TAG, "CACreateEndpoint error");
         goto exit;
     }
 
@@ -2524,7 +2663,7 @@ OCStackResult OCDoResource(OCDoHandle *handle,
 exit:
     if (result != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCDoResource error");
+        OIC_LOG(ERROR, TAG, "OCDoResource error");
         FindAndDeleteClientCB(clientCB);
         CADestroyToken(token);
         if (handle)
@@ -2576,7 +2715,7 @@ OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption
     ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
     if (!clientCB)
     {
-        OC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
+        OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
         return OC_STACK_ERROR;
     }
 
@@ -2585,7 +2724,7 @@ OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption
         case OC_REST_OBSERVE:
         case OC_REST_OBSERVE_ALL:
 
-            OC_LOG_V(INFO, TAG, "Canceling observation for resource %s",
+            OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s",
                                         clientCB->requestUri);
             if (qos != OC_HIGH_QOS)
             {
@@ -2593,7 +2732,7 @@ OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption
                 break;
             }
 
-            OC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
+            OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
 
             requestInfo.info.type = qualityOfServiceToMessageType(qos);
             requestInfo.info.token = clientCB->token;
@@ -2623,7 +2762,7 @@ OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption
             break;
 
         case OC_REST_DISCOVER:
-            OC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
+            OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
                                            clientCB->requestUri);
             FindAndDeleteClientCB(clientCB);
             break;
@@ -2651,10 +2790,10 @@ OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption
  */
 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
 {
-    OC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
+    OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
     if(!persistentStorageHandler)
     {
-        OC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
+        OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
         return OC_STACK_INVALID_PARAM;
     }
     else
@@ -2665,7 +2804,7 @@ OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistent
                 !persistentStorageHandler->unlink ||
                 !persistentStorageHandler->write)
         {
-            OC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
+            OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
             return OC_STACK_INVALID_PARAM;
         }
     }
@@ -2680,7 +2819,7 @@ OCStackResult OCProcessPresence()
 
     // the following line floods the log with messages that are irrelevant
     // to most purposes.  Uncomment as needed.
-    //OC_LOG(INFO, TAG, "Entering RequestPresence");
+    //OIC_LOG(INFO, TAG, "Entering RequestPresence");
     ClientCB* cbNode = NULL;
     OCClientResponse clientResponse;
     OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
@@ -2693,9 +2832,9 @@ OCStackResult OCProcessPresence()
         }
 
         uint32_t now = GetTicks(0);
-        OC_LOG_V(DEBUG, TAG, "this TTL level %d",
+        OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
                                                 cbNode->presence->TTLlevel);
-        OC_LOG_V(DEBUG, TAG, "current ticks %d", now);
+        OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
 
         if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
         {
@@ -2704,12 +2843,12 @@ OCStackResult OCProcessPresence()
 
         if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
         {
-            OC_LOG_V(DEBUG, TAG, "timeout ticks %d",
+            OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
                     cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
         }
         if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
         {
-            OC_LOG(DEBUG, TAG, "No more timeout ticks");
+            OIC_LOG(DEBUG, TAG, "No more timeout ticks");
 
             clientResponse.sequenceNumber = 0;
             clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
@@ -2720,7 +2859,7 @@ OCStackResult OCProcessPresence()
             // Increment the TTLLevel (going to a next state), so we don't keep
             // sending presence notification to client.
             cbNode->presence->TTLlevel++;
-            OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
+            OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
                                         cbNode->presence->TTLlevel);
 
             cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
@@ -2739,7 +2878,7 @@ OCStackResult OCProcessPresence()
         CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
         CARequestInfo_t requestInfo = {.method = CA_GET};
 
-        OC_LOG(DEBUG, TAG, "time to test server presence");
+        OIC_LOG(DEBUG, TAG, "time to test server presence");
 
         CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
 
@@ -2757,12 +2896,12 @@ OCStackResult OCProcessPresence()
         }
 
         cbNode->presence->TTLlevel++;
-        OC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
+        OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
     }
 exit:
     if (result != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCProcessPresence error");
+        OIC_LOG(ERROR, TAG, "OCProcessPresence error");
     }
 
     return result;
@@ -2779,6 +2918,10 @@ OCStackResult OCProcess()
 #ifdef ROUTING_GATEWAY
     RMProcess();
 #endif
+
+#ifdef TCP_ADAPTER
+    ProcessKeepAlive();
+#endif
     return OC_STACK_OK;
 }
 
@@ -2793,18 +2936,18 @@ OCStackResult OCStartPresence(const uint32_t ttl)
     if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
     {
         presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
-        OC_LOG(INFO, TAG, "Setting Presence TTL to max value");
+        OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
     }
     else if (0 == ttl)
     {
         presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
-        OC_LOG(INFO, TAG, "Setting Presence TTL to default value");
+        OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
     }
     else
     {
         presenceResource.presenceTTL = ttl;
     }
-    OC_LOG_V(DEBUG, TAG, "Presence TTL is %lu seconds", presenceResource.presenceTTL);
+    OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
 
     if (OC_PRESENCE_UNINITIALIZED == presenceState)
     {
@@ -2816,7 +2959,7 @@ OCStackResult OCStartPresence(const uint32_t ttl)
         CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
         if (caResult != CA_STATUS_OK)
         {
-            OC_LOG(ERROR, TAG, "CAGenerateToken error");
+            OIC_LOG(ERROR, TAG, "CAGenerateToken error");
             CADestroyToken(caToken);
             return OC_STACK_ERROR;
         }
@@ -2850,7 +2993,7 @@ OCStackResult OCStopPresence()
 
     if(result != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG,
+        OIC_LOG(ERROR, TAG,
                       "Changing the presence resource properties to ACTIVE not successful");
         return result;
     }
@@ -2870,7 +3013,7 @@ OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandle
 
 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
 {
-    OC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
+    OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
 
     if(myStackMode ==  OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
     {
@@ -2891,14 +3034,31 @@ OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
 
 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
 {
-    OC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
+    OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
 
     if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
     {
-        OC_LOG(ERROR, TAG, "Null or empty device name.");
+        OIC_LOG(ERROR, TAG, "Null or empty device name.");
         return OC_STACK_INVALID_PARAM;
     }
 
+    if (deviceInfo.types)
+    {
+        OCStringLL *type =  deviceInfo.types;
+        OCResource *resource = findResource((OCResource *) deviceResource);
+        if (!resource)
+        {
+            return OC_STACK_INVALID_PARAM;
+        }
+        deleteResourceType(resource->rsrcType);
+        resource->rsrcType = NULL;
+
+        while (type)
+        {
+            OCBindResourceTypeToResource(deviceResource, type->value);
+            type = type->next;
+        }
+    }
     return SaveDeviceInfo(deviceInfo);
 }
 
@@ -2913,7 +3073,7 @@ OCStackResult OCCreateResource(OCResourceHandle *handle,
     OCResource *pointer = NULL;
     OCStackResult result = OC_STACK_ERROR;
 
-    OC_LOG(INFO, TAG, "Entering OCCreateResource");
+    OIC_LOG(INFO, TAG, "Entering OCCreateResource");
 
     if(myStackMode == OC_CLIENT)
     {
@@ -2922,13 +3082,13 @@ OCStackResult OCCreateResource(OCResourceHandle *handle,
     // Validate parameters
     if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
     {
-        OC_LOG(ERROR, TAG, "URI is empty or too long");
+        OIC_LOG(ERROR, TAG, "URI is empty or too long");
         return OC_STACK_INVALID_URI;
     }
     // Is it presented during resource discovery?
     if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
     {
-        OC_LOG(ERROR, TAG, "Input parameter is NULL");
+        OIC_LOG(ERROR, TAG, "Input parameter is NULL");
         return OC_STACK_INVALID_PARAM;
     }
 
@@ -2942,7 +3102,7 @@ OCStackResult OCCreateResource(OCResourceHandle *handle,
             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
                OC_EXPLICIT_DISCOVERABLE))
     {
-        OC_LOG(ERROR, TAG, "Invalid property");
+        OIC_LOG(ERROR, TAG, "Invalid property");
         return OC_STACK_INVALID_PARAM;
     }
 
@@ -2956,7 +3116,7 @@ OCStackResult OCCreateResource(OCResourceHandle *handle,
         {
             if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
             {
-                OC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
+                OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
                 return OC_STACK_INVALID_PARAM;
             }
             pointer = pointer->next;
@@ -2989,7 +3149,7 @@ OCStackResult OCCreateResource(OCResourceHandle *handle,
     result = BindResourceTypeToResource(pointer, resourceTypeName);
     if (result != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "Error adding resourcetype");
+        OIC_LOG(ERROR, TAG, "Error adding resourcetype");
         goto exit;
     }
 
@@ -2997,7 +3157,7 @@ OCStackResult OCCreateResource(OCResourceHandle *handle,
     result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
     if (result != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "Error adding resourceinterface");
+        OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
         goto exit;
     }
 
@@ -3014,6 +3174,9 @@ OCStackResult OCCreateResource(OCResourceHandle *handle,
         pointer->entityHandlerCallbackParam = NULL;
     }
 
+    // Initialize a pointer indicating child resources in case of collection
+    pointer->rsrcChildResourcesHead = NULL;
+
     *handle = pointer;
     result = OC_STACK_OK;
 
@@ -3033,14 +3196,14 @@ exit:
     return result;
 }
 
-
 OCStackResult OCBindResource(
         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
 {
     OCResource *resource = NULL;
-    uint8_t i = 0;
+    OCChildResource *tempChildResource = NULL;
+    OCChildResource *newChildResource = NULL;
 
-    OC_LOG(INFO, TAG, "Entering OCBindResource");
+    OIC_LOG(INFO, TAG, "Entering OCBindResource");
 
     // Validate parameters
     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
@@ -3048,7 +3211,7 @@ OCStackResult OCBindResource(
     // Container cannot contain itself
     if (collectionHandle == resourceHandle)
     {
-        OC_LOG(ERROR, TAG, "Added handle equals collection handle");
+        OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
         return OC_STACK_INVALID_PARAM;
     }
 
@@ -3056,43 +3219,62 @@ OCStackResult OCBindResource(
     resource = findResource((OCResource *) collectionHandle);
     if (!resource)
     {
-        OC_LOG(ERROR, TAG, "Collection handle not found");
+        OIC_LOG(ERROR, TAG, "Collection handle not found");
         return OC_STACK_INVALID_PARAM;
     }
 
     // Look for an open slot to add add the child resource.
     // If found, add it and return success
-    for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
+
+    tempChildResource = resource->rsrcChildResourcesHead;
+
+    while(resource->rsrcChildResourcesHead && tempChildResource->next)
     {
-        if (!resource->rsrcResources[i])
-        {
-            resource->rsrcResources[i] = (OCResource *) resourceHandle;
-            OC_LOG(INFO, TAG, "resource bound");
+        // TODO: what if one of child resource was deregistered without unbinding?
+        tempChildResource = tempChildResource->next;
+    }
 
-#ifdef WITH_PRESENCE
-            if (presenceResource.handle)
-            {
-                ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
-                SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
-                        OC_PRESENCE_TRIGGER_CHANGE);
-            }
-#endif
-            return OC_STACK_OK;
+    // Do memory allocation for child resource
+    newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
+    if(!newChildResource)
+    {
+        OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
+        return OC_STACK_ERROR;
+    }
 
-        }
+    newChildResource->rsrcResource = (OCResource *) resourceHandle;
+    newChildResource->next = NULL;
+
+    if(!resource->rsrcChildResourcesHead)
+    {
+        resource->rsrcChildResourcesHead = newChildResource;
+    }
+    else {
+        tempChildResource->next = newChildResource;
     }
 
-    // Unable to add resourceHandle, so return error
-    return OC_STACK_ERROR;
+    OIC_LOG(INFO, TAG, "resource bound");
+
+#ifdef WITH_PRESENCE
+    if (presenceResource.handle)
+    {
+        ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
+        SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
+                OC_PRESENCE_TRIGGER_CHANGE);
+    }
+#endif
+
+    return OC_STACK_OK;
 }
 
 OCStackResult OCUnBindResource(
         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
 {
     OCResource *resource = NULL;
-    uint8_t i = 0;
+    OCChildResource *tempChildResource = NULL;
+    OCChildResource *tempLastChildResource = NULL;
 
-    OC_LOG(INFO, TAG, "Entering OCUnBindResource");
+    OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
 
     // Validate parameters
     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
@@ -3100,7 +3282,7 @@ OCStackResult OCUnBindResource(
     // Container cannot contain itself
     if (collectionHandle == resourceHandle)
     {
-        OC_LOG(ERROR, TAG, "removing handle equals collection handle");
+        OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
         return OC_STACK_INVALID_PARAM;
     }
 
@@ -3108,18 +3290,44 @@ OCStackResult OCUnBindResource(
     resource = findResource((OCResource *) collectionHandle);
     if (!resource)
     {
-        OC_LOG(ERROR, TAG, "Collection handle not found");
+        OIC_LOG(ERROR, TAG, "Collection handle not found");
         return OC_STACK_INVALID_PARAM;
     }
 
     // Look for an open slot to add add the child resource.
     // If found, add it and return success
-    for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
+    if(!resource->rsrcChildResourcesHead)
+    {
+        OIC_LOG(INFO, TAG, "resource not found in collection");
+
+        // Unable to add resourceHandle, so return error
+        return OC_STACK_ERROR;
+
+    }
+
+    tempChildResource = resource->rsrcChildResourcesHead;
+
+    while (tempChildResource)
     {
-        if (resourceHandle == resource->rsrcResources[i])
+        if(tempChildResource->rsrcResource == resourceHandle)
         {
-            resource->rsrcResources[i] = (OCResource *) NULL;
-            OC_LOG(INFO, TAG, "resource unbound");
+            // if resource going to be unbinded is the head one.
+            if( tempChildResource == resource->rsrcChildResourcesHead )
+            {
+                OCChildResource *temp = resource->rsrcChildResourcesHead->next;
+                OICFree(resource->rsrcChildResourcesHead);
+                resource->rsrcChildResourcesHead = temp;
+                temp = NULL;
+            }
+            else
+            {
+                OCChildResource *temp = tempChildResource->next;
+                OICFree(tempChildResource);
+                tempLastChildResource->next = temp;
+                temp = NULL;
+            }
+
+            OIC_LOG(INFO, TAG, "resource unbound");
 
             // Send notification when resource is unbounded successfully.
 #ifdef WITH_PRESENCE
@@ -3130,11 +3338,21 @@ OCStackResult OCUnBindResource(
                         OC_PRESENCE_TRIGGER_CHANGE);
             }
 #endif
+            tempChildResource = NULL;
+            tempLastChildResource = NULL;
+
             return OC_STACK_OK;
+
         }
+
+        tempLastChildResource = tempChildResource;
+        tempChildResource = tempChildResource->next;
     }
 
-    OC_LOG(INFO, TAG, "resource not found in collection");
+    OIC_LOG(INFO, TAG, "resource not found in collection");
+
+    tempChildResource = NULL;
+    tempLastChildResource = NULL;
 
     // Unable to add resourceHandle, so return error
     return OC_STACK_ERROR;
@@ -3174,7 +3392,7 @@ OCStackResult BindResourceTypeToResource(OCResource* resource,
 
     if (!ValidateResourceTypeInterface(resourceTypeName))
     {
-        OC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
+        OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
         return OC_STACK_INVALID_PARAM;
     }
 
@@ -3192,11 +3410,12 @@ OCStackResult BindResourceTypeToResource(OCResource* resource,
         goto exit;
     }
     pointer->resourcetypename = str;
+    pointer->next = NULL;
 
     insertResourceType(resource, pointer);
     result = OC_STACK_OK;
 
-    exit:
+exit:
     if (result != OC_STACK_OK)
     {
         OICFree(pointer);
@@ -3217,11 +3436,11 @@ OCStackResult BindResourceInterfaceToResource(OCResource* resource,
 
     if (!ValidateResourceTypeInterface(resourceInterfaceName))
     {
-        OC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
+        OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
         return OC_STACK_INVALID_PARAM;
     }
 
-    OC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
+    OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
 
     pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
     if (!pointer)
@@ -3263,7 +3482,7 @@ OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
     resource = findResource((OCResource *) handle);
     if (!resource)
     {
-        OC_LOG(ERROR, TAG, "Resource not found");
+        OIC_LOG(ERROR, TAG, "Resource not found");
         return OC_STACK_ERROR;
     }
 
@@ -3290,7 +3509,7 @@ OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
     resource = findResource((OCResource *) handle);
     if (!resource)
     {
-        OC_LOG(ERROR, TAG, "Resource not found");
+        OIC_LOG(ERROR, TAG, "Resource not found");
         return OC_STACK_ERROR;
     }
 
@@ -3336,20 +3555,20 @@ OCStackResult OCDeleteResource(OCResourceHandle handle)
 {
     if (!handle)
     {
-        OC_LOG(ERROR, TAG, "Invalid handle for deletion");
+        OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
         return OC_STACK_INVALID_PARAM;
     }
 
     OCResource *resource = findResource((OCResource *) handle);
     if (resource == NULL)
     {
-        OC_LOG(ERROR, TAG, "Resource not found");
+        OIC_LOG(ERROR, TAG, "Resource not found");
         return OC_STACK_NO_RESOURCE;
     }
 
     if (deleteResource((OCResource *) handle) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "Error deleting resource");
+        OIC_LOG(ERROR, TAG, "Error deleting resource");
         return OC_STACK_ERROR;
     }
 
@@ -3455,19 +3674,30 @@ OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHa
         uint8_t index)
 {
     OCResource *resource = NULL;
+    OCChildResource *tempChildResource = NULL;
+    uint8_t num = 0;
 
-    if (index >= MAX_CONTAINED_RESOURCES)
+    resource = findResource((OCResource *) collectionHandle);
+    if (!resource)
     {
         return NULL;
     }
 
-    resource = findResource((OCResource *) collectionHandle);
-    if (!resource)
+    tempChildResource = resource->rsrcChildResourcesHead;
+
+    while(tempChildResource)
     {
-        return NULL;
+        if( num == index )
+        {
+            return tempChildResource->rsrcResource;
+        }
+        num++;
+        tempChildResource = tempChildResource->next;
     }
 
-    return resource->rsrcResources[index];
+    // In this case, the number of resource handles in the collection exceeds the index
+    tempChildResource = NULL;
+    return NULL;
 }
 
 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
@@ -3483,7 +3713,7 @@ OCStackResult OCBindResourceHandler(OCResourceHandle handle,
     resource = findResource((OCResource *)handle);
     if (!resource)
     {
-        OC_LOG(ERROR, TAG, "Resource not found");
+        OIC_LOG(ERROR, TAG, "Resource not found");
         return OC_STACK_ERROR;
     }
 
@@ -3509,7 +3739,7 @@ OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
     resource = findResource((OCResource *)handle);
     if (!resource)
     {
-        OC_LOG(ERROR, TAG, "Resource not found");
+        OIC_LOG(ERROR, TAG, "Resource not found");
         return NULL;
     }
 
@@ -3579,7 +3809,7 @@ OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService q
     OCMethod method = OC_REST_NOMETHOD;
     uint32_t maxAge = 0;
 
-    OC_LOG(INFO, TAG, "Notifying all observers");
+    OIC_LOG(INFO, TAG, "Notifying all observers");
 #ifdef WITH_PRESENCE
     if(handle == presenceResource.handle)
     {
@@ -3617,7 +3847,7 @@ OCNotifyListOfObservers (OCResourceHandle handle,
                          const OCRepPayload       *payload,
                          OCQualityOfService qos)
 {
-    OC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
+    OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
 
     OCResource *resPtr = NULL;
     //TODO: we should allow the server to define this
@@ -3645,7 +3875,7 @@ OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
     OCStackResult result = OC_STACK_ERROR;
     OCServerRequest *serverRequest = NULL;
 
-    OC_LOG(INFO, TAG, "Entering OCDoResponse");
+    OIC_LOG(INFO, TAG, "Entering OCDoResponse");
 
     // Validate input parameters
     VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
@@ -3663,6 +3893,54 @@ OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
     return result;
 }
 
+//#ifdef DIRECT_PAIRING
+const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
+{
+    OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
+    if(OC_STACK_OK != DPDeviceDiscovery(waittime))
+    {
+        OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
+        return NULL;
+    }
+
+    return (const OCDPDev_t*)DPGetDiscoveredDevices();
+}
+
+const OCDPDev_t* OCGetDirectPairedDevices()
+{
+    return (const OCDPDev_t*)DPGetPairedDevices();
+}
+
+void DirectPairingCB (OCDirectPairingDev_t * peer, OCStackResult result)
+{
+    if (gDirectpairingCallback)
+    {
+        gDirectpairingCallback((OCDPDev_t*)peer, result);
+        gDirectpairingCallback = NULL;
+    }
+}
+
+OCStackResult OCDoDirectPairing(OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
+                                                     OCDirectPairingCB resultCallback)
+{
+    OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
+    if(NULL ==  peer || NULL == pinNumber)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid parameters");
+        return OC_STACK_INVALID_PARAM;
+    }
+    if(NULL == resultCallback)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid callback");
+        return OC_STACK_INVALID_CALLBACK;
+    }
+
+    gDirectpairingCallback = resultCallback;
+    return DPDirectPairing((OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
+                                           pinNumber, DirectPairingCB);
+}
+//#endif // DIRECT_PAIRING
+
 //-----------------------------------------------------------------------------
 // Private internal function definitions
 //-----------------------------------------------------------------------------
@@ -3690,7 +3968,7 @@ OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
     if (resourceProperties
             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
     {
-        OC_LOG(ERROR, TAG, "Invalid property");
+        OIC_LOG(ERROR, TAG, "Invalid property");
         return OC_STACK_INVALID_PARAM;
     }
     if(!enable)
@@ -3833,11 +4111,11 @@ OCStackResult deleteResource(OCResource *resource)
     OCResource *temp = NULL;
     if(!resource)
     {
-        OC_LOG(DEBUG,TAG,"resource is NULL");
+        OIC_LOG(DEBUG,TAG,"resource is NULL");
         return OC_STACK_INVALID_PARAM;
     }
 
-    OC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
+    OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
 
     temp = headResource;
     while (temp)
@@ -3957,7 +4235,7 @@ void insertResourceType(OCResource *resource, OCResourceType *resourceType)
         {
             if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
             {
-                OC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
+                OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
                 OICFree(resourceType->resourcetypename);
                 OICFree(resourceType);
                 return;
@@ -3969,7 +4247,7 @@ void insertResourceType(OCResource *resource, OCResourceType *resourceType)
     }
     resourceType->next = NULL;
 
-    OC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
+    OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
 }
 
 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
@@ -4035,8 +4313,27 @@ void insertResourceInterface(OCResource *resource, OCResourceInterface *newInter
 
     if (!*firstInterface)
     {
-        *firstInterface = newInterface;
+        // If first interface is not oic.if.baseline, by default add it as first interface type.
+        if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
+        {
+            *firstInterface = newInterface;
+        }
+        else
+        {
+            OCStackResult result = BindResourceInterfaceToResource(resource, OC_RSRVD_INTERFACE_DEFAULT);
+            if (result != OC_STACK_OK)
+            {
+                OICFree(newInterface->name);
+                OICFree(newInterface);
+                return;
+            }
+            if (*firstInterface)
+            {
+                (*firstInterface)->next = newInterface;
+            }
+        }
     }
+    // If once add oic.if.baseline, later too below code take care of freeing memory.
     else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
     {
         if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
@@ -4045,6 +4342,7 @@ void insertResourceInterface(OCResource *resource, OCResourceInterface *newInter
             OICFree(newInterface);
             return;
         }
+        // This code will not hit anymore, keeping
         else
         {
             newInterface->next = *firstInterface;
@@ -4161,7 +4459,7 @@ OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithout
         return OC_STACK_NO_MEMORY;
 }
 
-const OicUuid_t* OCGetServerInstanceID(void)
+static const OicUuid_t* OCGetServerInstanceID(void)
 {
     static bool generated = false;
     static OicUuid_t sid;
@@ -4170,9 +4468,9 @@ const OicUuid_t* OCGetServerInstanceID(void)
         return &sid;
     }
 
-    if (GetDoxmDeviceID(&sid) != OC_STACK_OK)
+    if (OC_STACK_OK != GetDoxmDeviceID(&sid))
     {
-        OC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
+        OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
         return NULL;
     }
     generated = true;
@@ -4189,11 +4487,10 @@ const char* OCGetServerInstanceIDString(void)
         return sidStr;
     }
 
-    const OicUuid_t* sid = OCGetServerInstanceID();
-
+    const OicUuid_t *sid = OCGetServerInstanceID();
     if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
     {
-        OC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
+        OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
         return NULL;
     }
 
@@ -4209,8 +4506,8 @@ CAResult_t OCSelectNetwork()
     CATransportAdapter_t connTypes[] = {
             CA_ADAPTER_IP,
             CA_ADAPTER_RFCOMM_BTEDR,
-            CA_ADAPTER_GATT_BTLE
-
+            CA_ADAPTER_GATT_BTLE,
+            CA_ADAPTER_NFC
 #ifdef RA_ADAPTER
             ,CA_ADAPTER_REMOTE_ACCESS
 #endif
index 20d8735..383d66a 100755 (executable)
@@ -36,7 +36,7 @@
 #include <pthread.h>
 #endif
 
-#define TAG "OICGROUP"
+#define TAG "OIC_RI_GROUP"
 
 #define DESC_DELIMITER          "\""
 #define ACTION_DELIMITER        "*"
@@ -98,7 +98,7 @@ ScheduledResourceInfo *scheduleResourceList = NULL;
 void AddScheduledResource(ScheduledResourceInfo **head,
         ScheduledResourceInfo* add)
 {
-    OC_LOG(INFO, TAG, "AddScheduledResource Entering...");
+    OIC_LOG(INFO, TAG, "AddScheduledResource Entering...");
 
 #ifndef WITH_ARDUINO
     pthread_mutex_lock(&lock);
@@ -126,7 +126,7 @@ void AddScheduledResource(ScheduledResourceInfo **head,
 
 ScheduledResourceInfo* GetScheduledResource(ScheduledResourceInfo *head)
 {
-    OC_LOG(INFO, TAG, "GetScheduledResource Entering...");
+    OIC_LOG(INFO, TAG, "GetScheduledResource Entering...");
 
 #ifndef WITH_ARDUINO
     pthread_mutex_lock(&lock);
@@ -156,7 +156,7 @@ ScheduledResourceInfo* GetScheduledResource(ScheduledResourceInfo *head)
 
             if (diffTm <= (time_t) 0)
             {
-                OC_LOG(INFO, TAG, "return Call INFO.");
+                OIC_LOG(INFO, TAG, "return Call INFO.");
                 goto exit;
             }
 
@@ -170,14 +170,14 @@ ScheduledResourceInfo* GetScheduledResource(ScheduledResourceInfo *head)
 #endif
     if (tmp == NULL)
     {
-        OC_LOG(INFO, TAG, "Cannot Find Call Info.");
+        OIC_LOG(INFO, TAG, "Cannot Find Call Info.");
     }
     return tmp;
 }
 
 ScheduledResourceInfo* GetScheduledResourceByActionSetName(ScheduledResourceInfo *head, char *setName)
 {
-    OC_LOG(INFO, TAG, "GetScheduledResourceByActionSetName Entering...");
+    OIC_LOG(INFO, TAG, "GetScheduledResourceByActionSetName Entering...");
 
 #ifndef WITH_ARDUINO
     pthread_mutex_lock(&lock);
@@ -191,7 +191,7 @@ ScheduledResourceInfo* GetScheduledResourceByActionSetName(ScheduledResourceInfo
         {
             if (strcmp(tmp->actionset->actionsetName, setName) == 0)
             {
-                OC_LOG(INFO, TAG, "return Call INFO.");
+                OIC_LOG(INFO, TAG, "return Call INFO.");
                 goto exit;
             }
             tmp = tmp->next;
@@ -204,7 +204,7 @@ exit:
 #endif
     if (tmp == NULL)
     {
-        OC_LOG(INFO, TAG, "Cannot Find Call Info.");
+        OIC_LOG(INFO, TAG, "Cannot Find Call Info.");
     }
     return tmp;
 }
@@ -215,7 +215,7 @@ void RemoveScheduledResource(ScheduledResourceInfo **head,
 #ifndef WITH_ARDUINO
     pthread_mutex_lock(&lock);
 #endif
-    OC_LOG(INFO, TAG, "RemoveScheduledResource Entering...");
+    OIC_LOG(INFO, TAG, "RemoveScheduledResource Entering...");
     ScheduledResourceInfo *tmp = NULL;
 
     if (del == NULL)
@@ -496,24 +496,6 @@ OCStackResult FindAndDeleteActionSet(OCResource **resource,
     return OC_STACK_ERROR;
 }
 
-OCStackResult DeleteActionSets(OCResource** resource)
-{
-    OCActionSet *pointer = (*resource)->actionsetHead;
-    OCActionSet *pDel = pointer;
-
-    while (pointer)
-    {
-        pDel = pointer;
-        pointer = pointer->next;
-
-        DeleteActionSet(&pDel);
-        pDel->next = NULL;
-    }
-
-    (*resource)->actionsetHead = NULL;
-    return OC_STACK_OK;
-}
-
 OCStackResult GetActionSet(const char *actionName, OCActionSet *head,
         OCActionSet** actionset)
 {
@@ -647,12 +629,13 @@ OCStackResult BuildActionSetFromString(OCActionSet **set, char* actiondesc)
     OCAction *action = NULL;
     OCCapability *capa = NULL;
 
-    OC_LOG(INFO, TAG, "Build ActionSet Instance.");
+    OIC_LOG(INFO, TAG, "Build ActionSet Instance.");
 
     *set = (OCActionSet*) OICMalloc(sizeof(OCActionSet));
     VARIFY_POINTER_NULL(*set, result, exit)
 
     iterToken = (char *) strtok_r(actiondesc, ACTION_DELIMITER, &iterTokenPtr);
+    VARIFY_POINTER_NULL(iterToken, result, exit);
 
     // ActionSet Name
     memset(*set, 0, sizeof(OCActionSet));
@@ -675,7 +658,7 @@ OCStackResult BuildActionSetFromString(OCActionSet **set, char* actiondesc)
     }
 #endif
 
-    OC_LOG_V(INFO, TAG, "ActionSet Name : %s", (*set)->actionsetName);
+    OIC_LOG_V(INFO, TAG, "ActionSet Name : %s", (*set)->actionsetName);
 
     iterToken = (char *) strtok_r(NULL, ACTION_DELIMITER, &iterTokenPtr);
     while (iterToken)
@@ -704,6 +687,7 @@ OCStackResult BuildActionSetFromString(OCActionSet **set, char* actiondesc)
 
             attrIterToken = (char *) strtok_r(NULL, ATTR_ASSIGN,
                     &attrIterTokenPtr);
+            VARIFY_POINTER_NULL(attrIterToken, result, exit);
             value = (char *) OICMalloc(strlen(attrIterToken) + 1);
             VARIFY_POINTER_NULL(value, result, exit)
             VARIFY_PARAM_NULL(attrIterToken, result, exit)
@@ -711,7 +695,7 @@ OCStackResult BuildActionSetFromString(OCActionSet **set, char* actiondesc)
 
             if (strcmp(key, "uri") == 0)
             {
-                OC_LOG(INFO, TAG, "Build OCAction Instance.");
+                OIC_LOG(INFO, TAG, "Build OCAction Instance.");
 
                 action = (OCAction*) OICMalloc(sizeof(OCAction));
                 VARIFY_POINTER_NULL(action, result, exit)
@@ -725,7 +709,7 @@ OCStackResult BuildActionSetFromString(OCActionSet **set, char* actiondesc)
             {
                 if ((key != NULL) && (value != NULL))
                 {
-                    OC_LOG(INFO, TAG, "Build OCCapability Instance.");
+                    OIC_LOG(INFO, TAG, "Build OCCapability Instance.");
 
                     capa = (OCCapability*) OICMalloc(sizeof(OCCapability));
                     VARIFY_POINTER_NULL(capa, result, exit)
@@ -785,14 +769,15 @@ OCStackResult BuildStringFromActionSet(OCActionSet* actionset, char** desc)
     char temp[1024] = { 0 };
     size_t remaining = sizeof(temp) - 1;
     OCStackResult res = OC_STACK_ERROR;
+    char* actionTypeStr = NULL;
 
     OCAction *action = actionset->head;
 
     if (remaining >= strlen(actionset->actionsetName) + 1)
     {
-        strcat(temp, actionset->actionsetName);
+        strncat(temp, actionset->actionsetName, strlen(actionset->actionsetName));
         remaining -= strlen(actionset->actionsetName);
-        strcat(temp, ACTION_DELIMITER);
+        strncat(temp, ACTION_DELIMITER, strlen(ACTION_DELIMITER));
         remaining--;
     }
     else
@@ -801,6 +786,31 @@ OCStackResult BuildStringFromActionSet(OCActionSet* actionset, char** desc)
         goto exit;
     }
 
+    actionTypeStr = (char *)malloc(1024);
+    if(actionTypeStr != NULL)
+    {
+        sprintf(actionTypeStr, "%ld %u", actionset->timesteps, actionset->type);
+        if(remaining >= strlen(actionTypeStr) + strlen(ACTION_DELIMITER) + 1)
+        {
+            strncat(temp, actionTypeStr, strlen(actionTypeStr));
+            remaining -= strlen(actionTypeStr);
+            strncat(temp, ACTION_DELIMITER, strlen(ACTION_DELIMITER));
+            remaining -= strlen(ACTION_DELIMITER);
+            free(actionTypeStr);
+        }
+        else
+        {
+            free(actionTypeStr);
+            res = OC_STACK_ERROR;
+            goto exit;
+        }
+    }
+    else
+    {
+        res = OC_STACK_ERROR;
+        goto exit;
+    }
+
     while (action != NULL)
     {
         if (remaining < (strlen("uri=") + strlen(action->resourceUri) + 1))
@@ -808,6 +818,7 @@ OCStackResult BuildStringFromActionSet(OCActionSet* actionset, char** desc)
             res = OC_STACK_ERROR;
             goto exit;
         }
+
         strcat(temp, "uri=");
         remaining -= strlen("uri=");
         strcat(temp, action->resourceUri);
@@ -841,6 +852,7 @@ OCStackResult BuildStringFromActionSet(OCActionSet* actionset, char** desc)
                     goto exit;
                 }
                 strcat(temp, "|");
+                remaining --;
             }
         }
 
@@ -872,7 +884,7 @@ OCStackApplicationResult ActionSetCB(void* context, OCDoHandle handle,
 {
     (void)context;
     (void)clientResponse;
-    OC_LOG(INFO, TAG, "Entering ActionSetCB");
+    OIC_LOG(INFO, TAG, "Entering ActionSetCB");
 
     ClientRequestInfo *info = GetClientRequestInfo(clientRequstList, handle);
 
@@ -884,7 +896,7 @@ OCStackApplicationResult ActionSetCB(void* context, OCDoHandle handle,
 
         if(NULL == clientResponse->payload)
         {
-            OC_LOG(ERROR, TAG, "Error sending response");
+            OIC_LOG(ERROR, TAG, "Error sending response");
             return OC_STACK_DELETE_TRANSACTION;
         }
 
@@ -902,7 +914,7 @@ OCStackApplicationResult ActionSetCB(void* context, OCDoHandle handle,
         // Send the response
         if (OCDoResponse(&response) != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "Error sending response");
+            OIC_LOG(ERROR, TAG, "Error sending response");
             return OC_STACK_DELETE_TRANSACTION;
         }
 
@@ -928,7 +940,7 @@ OCStackResult BuildActionJSON(OCAction* action, unsigned char* bufferPtr,
     char *jsonStr;
     uint16_t jsonLen;
 
-    OC_LOG(INFO, TAG, "Entering BuildActionJSON");
+    OIC_LOG(INFO, TAG, "Entering BuildActionJSON");
     json = cJSON_CreateObject();
 
     cJSON_AddItemToObject(json, "rep", body = cJSON_CreateObject());
@@ -946,7 +958,7 @@ OCStackResult BuildActionJSON(OCAction* action, unsigned char* bufferPtr,
     jsonLen = strlen(jsonStr);
     if (jsonLen < *remaining)
     {
-        strcat((char*) bufferPtr, jsonStr);
+        strncat((char*) bufferPtr, jsonStr, jsonLen);
         *remaining -= jsonLen;
         bufferPtr += jsonLen;
         ret = OC_STACK_OK;
@@ -964,7 +976,7 @@ OCPayload* BuildActionCBOR(OCAction* action)
 
     if (!payload)
     {
-        OC_LOG(INFO, TAG, "Failed to create put payload object");
+        OIC_LOG(INFO, TAG, "Failed to create put payload object");
         return NULL;
     }
 
@@ -1061,27 +1073,27 @@ OCStackResult DoAction(OCResource* resource, OCActionSet* actionset,
 
 void DoScheduledGroupAction()
 {
-    OC_LOG(INFO, TAG, "DoScheduledGroupAction Entering...");
+    OIC_LOG(INFO, TAG, "DoScheduledGroupAction Entering...");
     ScheduledResourceInfo* info = GetScheduledResource(scheduleResourceList);
 
     if (info == NULL)
     {
-        OC_LOG(INFO, TAG, "Target resource is NULL");
+        OIC_LOG(INFO, TAG, "Target resource is NULL");
         goto exit;
     }
     else if (info->resource == NULL)
     {
-        OC_LOG(INFO, TAG, "Target resource is NULL");
+        OIC_LOG(INFO, TAG, "Target resource is NULL");
         goto exit;
     }
     else if (info->actionset == NULL)
     {
-        OC_LOG(INFO, TAG, "Target ActionSet is NULL");
+        OIC_LOG(INFO, TAG, "Target ActionSet is NULL");
         goto exit;
     }
     else if (info->ehRequest == NULL)
     {
-        OC_LOG(INFO, TAG, "Target ActionSet is NULL");
+        OIC_LOG(INFO, TAG, "Target ActionSet is NULL");
         goto exit;
     }
 #ifndef WITH_ARDUINO
@@ -1100,7 +1112,7 @@ void DoScheduledGroupAction()
 
         if (schedule)
         {
-            OC_LOG(INFO, TAG, "Building New Call Info.");
+            OIC_LOG(INFO, TAG, "Building New Call Info.");
             memset(schedule, 0, sizeof(ScheduledResourceInfo));
 
             if (info->actionset->timesteps > 0)
@@ -1116,7 +1128,7 @@ void DoScheduledGroupAction()
                         &schedule->timer_id,
                         &DoScheduledGroupAction);
 
-                OC_LOG(INFO, TAG, "Reregisteration.");
+                OIC_LOG(INFO, TAG, "Reregisteration.");
 #ifndef WITH_ARDUINO
                 pthread_mutex_unlock(&lock);
 #endif
@@ -1142,7 +1154,7 @@ OCStackResult BuildCollectionGroupActionCBORResponse(
 {
     OCStackResult stackRet = OC_STACK_ERROR;
 
-    OC_LOG(INFO, TAG, "Group Action is requested.");
+    OIC_LOG(INFO, TAG, "Group Action is requested.");
 
     char *doWhat = NULL;
     char *details = NULL;
@@ -1151,7 +1163,7 @@ OCStackResult BuildCollectionGroupActionCBORResponse(
 
     if(stackRet != OC_STACK_OK)
     {
-        OC_LOG_V(ERROR, TAG, "ExtractKeyValueFromRequest failed: %d", stackRet);
+        OIC_LOG_V(ERROR, TAG, "ExtractKeyValueFromRequest failed: %d", stackRet);
         return stackRet;
     }
 
@@ -1159,7 +1171,7 @@ OCStackResult BuildCollectionGroupActionCBORResponse(
 
     if (method == OC_REST_PUT)
     {
-        OC_LOG(INFO, TAG, "Group Action[PUT].");
+        OIC_LOG(INFO, TAG, "Group Action[PUT].");
 
         if (strcmp(doWhat, ACTIONSET) == 0)
         {
@@ -1178,7 +1190,7 @@ OCStackResult BuildCollectionGroupActionCBORResponse(
                         {
                             DeleteActionSet( &actionSet );
                         }
-                        OC_LOG(INFO, TAG, "Duplicated ActionSet ");
+                        OIC_LOG(INFO, TAG, "Duplicated ActionSet ");
                     }
                 }
                 else
@@ -1209,7 +1221,7 @@ OCStackResult BuildCollectionGroupActionCBORResponse(
 
         if(!payload)
         {
-            OC_LOG(ERROR, TAG, "Failed to allocate Payload");
+            OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
             stackRet = OC_STACK_ERROR;
         }
         else
@@ -1236,7 +1248,7 @@ OCStackResult BuildCollectionGroupActionCBORResponse(
             // Send the response
             if (OCDoResponse(&response) != OC_STACK_OK)
             {
-                OC_LOG(ERROR, TAG, "Error sending response");
+                OIC_LOG(ERROR, TAG, "Error sending response");
                 stackRet = OC_STACK_ERROR;
             }
         }
@@ -1272,21 +1284,21 @@ OCStackResult BuildCollectionGroupActionCBORResponse(
                 if (GetActionSet(details, resource->actionsetHead,
                         &actionset) != OC_STACK_OK)
                 {
-                    OC_LOG(INFO, TAG, "ERROR");
+                    OIC_LOG(INFO, TAG, "ERROR");
                     stackRet = OC_STACK_ERROR;
                 }
 
                 if (actionset == NULL)
                 {
-                    OC_LOG(INFO, TAG, "Cannot Find ActionSet");
+                    OIC_LOG(INFO, TAG, "Cannot Find ActionSet");
                     stackRet = OC_STACK_ERROR;
                 }
                 else
                 {
-                    OC_LOG(INFO, TAG, "Group Action[POST].");
+                    OIC_LOG(INFO, TAG, "Group Action[POST].");
                     if (actionset->type == NONE)
                     {
-                        OC_LOG_V(INFO, TAG, "Execute ActionSet : %s",
+                        OIC_LOG_V(INFO, TAG, "Execute ActionSet : %s",
                                 actionset->actionsetName);
                         unsigned int num = GetNumOfTargetResource(
                                 actionset->head);
@@ -1302,7 +1314,7 @@ OCStackResult BuildCollectionGroupActionCBORResponse(
                     }
                     else
                     {
-                        OC_LOG_V(INFO, TAG, "Execute Scheduled ActionSet : %s",
+                        OIC_LOG_V(INFO, TAG, "Execute Scheduled ActionSet : %s",
                                 actionset->actionsetName);
 
                         delay =
@@ -1314,7 +1326,7 @@ OCStackResult BuildCollectionGroupActionCBORResponse(
 
                         if (schedule)
                         {
-                            OC_LOG(INFO, TAG, "Building New Call Info.");
+                            OIC_LOG(INFO, TAG, "Building New Call Info.");
                             memset(schedule, 0,
                                     sizeof(ScheduledResourceInfo));
 #ifndef WITH_ARDUINO
@@ -1329,7 +1341,7 @@ OCStackResult BuildCollectionGroupActionCBORResponse(
 #endif
                             if (delay > 0)
                             {
-                                OC_LOG_V(INFO, TAG, "delay_time is %lf seconds.",
+                                OIC_LOG_V(INFO, TAG, "delay_time is %ld seconds.",
                                         actionset->timesteps);
 #ifndef WITH_ARDUINO
                                 pthread_mutex_lock(&lock);
@@ -1392,7 +1404,7 @@ OCStackResult BuildCollectionGroupActionCBORResponse(
 
         if(!payload)
         {
-            OC_LOG(ERROR, TAG, "Failed to allocate Payload");
+            OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
             stackRet = OC_STACK_ERROR;
         }
         else
@@ -1418,7 +1430,7 @@ OCStackResult BuildCollectionGroupActionCBORResponse(
             // Send the response
             if (OCDoResponse(&response) != OC_STACK_OK)
             {
-                OC_LOG(ERROR, TAG, "Error sending response");
+                OIC_LOG(ERROR, TAG, "Error sending response");
                 stackRet = OC_STACK_ERROR;
             }
         }
diff --git a/resource/csdk/stack/src/oickeepalive.c b/resource/csdk/stack/src/oickeepalive.c
new file mode 100644 (file)
index 0000000..8063f2b
--- /dev/null
@@ -0,0 +1,746 @@
+/* ****************************************************************
+ *
+ * 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 "oickeepalive.h"
+
+#include <stdio.h>
+#include <string.h>
+#include "oic_malloc.h"
+#include "oic_string.h"
+#include "oic_time.h"
+#include "ocrandom.h"
+#include "uarraylist.h"
+#include "ocstackinternal.h"
+#include "ocpayloadcbor.h"
+#include "ocpayload.h"
+#include "ocresourcehandler.h"
+#include "logger.h"
+
+/**
+ * Logging tag for module name.
+ */
+#define TAG "OIC_RI_KEEPALIVE"
+
+static const uint64_t USECS_PER_SEC = 1000000;
+
+//-----------------------------------------------------------------------------
+// Macros
+//-----------------------------------------------------------------------------
+#define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
+            {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
+
+#define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
+             TAG, #arg " is NULL"); return (retVal); } }
+
+#define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
+             TAG, #arg " is NULL"); return; } }
+
+#define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG_V(FATAL, TAG, "%s is NULL", #arg);\
+    goto exit;} }
+
+/**
+ * The KeepAlive table entries are removed
+ * if it can't receive response message within 60 seconds.
+ */
+#define KEEPALIVE_RESPONSE_TIMEOUT_SEC 60
+
+/**
+ * The Min time interval value. (2 minutes)
+ * start from 2 minutes and increases in multiples of 2 up to a maximum of 64minutes.
+ */
+#define KEEPALIVE_MIN_INTERVAL 2
+
+/**
+ * The Max time interval value. (64 minutes)
+ */
+#define KEEPALIVE_MAX_INTERVAL 64
+
+/**
+ * Default counts of interval value.
+ */
+#define DEFAULT_INTERVAL_COUNT  6
+
+/**
+ * KeepAlive key to parser Payload Table.
+ */
+static const char INTERVAL[] = "in";
+
+/**
+ * KeepAlive key to get interval values from Payload Table.
+ */
+static const char INTERVAL_ARRAY[] = "inarray";
+
+/**
+ * To check if KeepAlive is initialized.
+ */
+static bool g_isKeepAliveInitialized = false;
+
+/**
+ * Pointer to handle of the newly created KeepAlive resource.
+ */
+static OCResourceHandle g_keepAliveHandle = NULL;
+
+/**
+ * KeepAlive table which holds connection interval.
+ */
+static u_arraylist_t *g_keepAliveConnectionTable = NULL;
+
+/**
+ * KeepAlive table entries.
+ */
+typedef struct
+{
+    OCMode mode;                    /**< host Mode of Operation. */
+    CAEndpoint_t remoteAddr;        /**< destination Address. */
+    uint32_t interval;              /**< time interval for KeepAlive. in seconds.*/
+    int32_t currIndex;              /**< current interval value index. */
+    size_t intervalSize;            /**< total interval counts. */
+    int64_t *intervalInfo;          /**< interval values for KeepAlive. */
+    bool sentPingMsg;               /**< if oic client already sent ping message. */
+    uint64_t timeStamp;             /**< last sent or received ping message. in microseconds. */
+} KeepAliveEntry_t;
+
+/**
+ * Send disconnect message to remove connection.
+ */
+static OCStackResult SendDisconnectMessage(const KeepAliveEntry_t *entry);
+
+/**
+ * Send ping message to remote endpoint.
+ */
+static OCStackResult SendPingMessage(KeepAliveEntry_t *entry);
+
+/**
+ * Increase interval value to send next ping message.
+ */
+static void IncreaseInterval(KeepAliveEntry_t *entry);
+
+/**
+ * Ping Message callback registered with RI for KeepAlive Request.
+ */
+static OCStackApplicationResult PingRequestCallback(void* ctx, OCDoHandle handle,
+                                             OCClientResponse * clientResponse);
+
+/**
+ * This function creates KeepAlive resource.
+ * @return  ::OC_STACK_OK or Appropriate error code.
+ */
+static OCStackResult CreateKeepAliveResource();
+
+/**
+ * This function deletes KeepAlive resource.
+ * @return  ::OC_STACK_OK or Appropriate error code.
+ */
+static OCStackResult DeleteKeepAliveResource();
+
+/**
+ * API to handle the GET request received for a KeepAlive resource.
+ * @param[in]   endPoint        RemoteEndpoint which sent the packet.
+ * @param[in]   requestInfo     Received coap packet.
+ * @return  ::OC_STACK_OK or Appropriate error code.
+ */
+static OCStackResult HandleKeepAliveGETRequest(const CAEndpoint_t* endPoint,
+                                        const CARequestInfo_t* requestInfo);
+
+/**
+ * API to handle the PUT request received for a KeepAlive resource.
+ * @param[in]   endPoint        RemoteEndpoint which sent the packet.
+ * @param[in]   requestInfo     Received coap packet.
+ * @return  ::OC_STACK_OK or Appropriate error code.
+ */
+static OCStackResult HandleKeepAlivePUTRequest(const CAEndpoint_t* endPoint,
+                                        const CARequestInfo_t* requestInfo);
+
+/**
+ * API to handle the Response payload.
+ * @param[in]   endpoint        RemoteEndpoint which sent the packet.
+ * @param[in]   responseCode    Received reseponse code.
+ * @param[in]   respPayload     Response payload.
+ * @return  ::OC_STACK_OK or Appropriate error code.
+ */
+OCStackResult HandleKeepAliveResponse(const CAEndpoint_t *endPoint,
+                                      OCStackResult responseCode,
+                                      const OCRepPayload *respPayload);
+/**
+ * Gets keepalive entry.
+ * @param[in]   endpoint    Remote Endpoint information (like ipaddress,
+ *                          port, reference uri and transport type) to
+ *                          which the ping message has to be sent.
+ * @param[out]  index       index of array list.
+ * @return  KeepAlive entry to send ping message.
+ */
+static KeepAliveEntry_t *GetEntryFromEndpoint(const CAEndpoint_t *endpoint, uint32_t *index);
+
+/**
+ * Add keepalive entry.
+ * @param[in]   endpoint    Remote Endpoint information (like ipaddress,
+ *                          port, reference uri and transport type).
+ * @param[in]   mode        Whether it is OIC Server or OIC Client.
+ * @param[in]   intervalArray   Received interval values from cloud server.
+ * @return  The KeepAlive entry added in KeepAlive Table.
+ */
+KeepAliveEntry_t *AddKeepAliveEntry(const CAEndpoint_t *endpoint, OCMode mode,
+                                    int64_t *intervalArray);
+
+/**
+ * Remove keepalive entry.
+ * @param[in]   endpoint    Remote Endpoint information (like ipaddress,
+ *                          port, reference uri and transport type).
+ * @return  The KeepAlive entry removed in KeepAlive Table.
+ */
+static OCStackResult RemoveKeepAliveEntry(const CAEndpoint_t *endpoint);
+
+OCStackResult InitializeKeepAlive(OCMode mode)
+{
+    OIC_LOG(DEBUG, TAG, "InitializeKeepAlive IN");
+    if (g_isKeepAliveInitialized)
+    {
+        OIC_LOG(DEBUG, TAG, "KeepAlive already initialized");
+        return OC_STACK_OK;
+    }
+
+    if (OC_CLIENT != mode)
+    {
+        // Create the KeepAlive Resource[/oic/ping].
+        OCStackResult result = CreateKeepAliveResource();
+        if (OC_STACK_OK != result)
+        {
+            OIC_LOG_V(ERROR, TAG, "CreateKeepAliveResource failed[%d]", result);
+            return result;
+        }
+    }
+
+    if (!g_keepAliveConnectionTable)
+    {
+        g_keepAliveConnectionTable = u_arraylist_create();
+        if (NULL == g_keepAliveConnectionTable)
+        {
+            OIC_LOG(ERROR, TAG, "Creating KeepAlive Table failed");
+            TerminateKeepAlive(mode);
+            return OC_STACK_ERROR;
+        }
+    }
+
+    g_isKeepAliveInitialized = true;
+
+    OIC_LOG(DEBUG, TAG, "InitializeKeepAlive OUT");
+    return OC_STACK_OK;
+}
+
+OCStackResult TerminateKeepAlive(OCMode mode)
+{
+    OIC_LOG(DEBUG, TAG, "TerminateKeepAlive IN");
+    if (!g_isKeepAliveInitialized)
+    {
+        OIC_LOG(ERROR, TAG, "KeepAlive not initialized");
+        return OC_STACK_ERROR;
+    }
+
+    if (OC_CLIENT != mode)
+    {
+        // Delete the KeepAlive Resource[/oic/ping].
+        OCStackResult result = DeleteKeepAliveResource();
+        if (OC_STACK_OK != result)
+        {
+            OIC_LOG_V(ERROR, TAG, "DeleteKeepAliveResource failed[%d]", result);
+            return result;
+        }
+    }
+
+    if (NULL != g_keepAliveConnectionTable)
+    {
+        u_arraylist_destroy(g_keepAliveConnectionTable);
+        g_keepAliveConnectionTable = NULL;
+    }
+
+    g_isKeepAliveInitialized = false;
+
+    OIC_LOG(DEBUG, TAG, "TerminateKeepAlive OUT");
+    return OC_STACK_OK;
+}
+
+OCStackResult CreateKeepAliveResource()
+{
+    OIC_LOG(DEBUG, TAG, "InitKeepAliveResource IN");
+
+    // Create a KeepAlive resource
+    OCStackResult result = OCCreateResource(&g_keepAliveHandle,
+                                            KEEPALIVE_RESOURCE_TYPE_NAME,
+                                            KEEPALIVE_RESOURCE_INTF_NAME,
+                                            KEEPALIVE_RESOURCE_URI,
+                                            NULL,
+                                            NULL,
+                                            OC_DISCOVERABLE);
+
+    if (OC_STACK_OK != result)
+    {
+        OIC_LOG_V(ERROR, TAG, "Create resource for KeepAlive failed[%d]", result);
+    }
+
+    OIC_LOG(DEBUG, TAG, "InitKeepAliveResource OUT");
+    return result;
+}
+
+OCStackResult DeleteKeepAliveResource()
+{
+    OIC_LOG(DEBUG, TAG, "DeleteKeepAliveResource IN");
+
+    // Create a KeepAlive resource
+    OCStackResult result = OCDeleteResource(g_keepAliveHandle);
+
+    if (OC_STACK_OK != result)
+    {
+        OIC_LOG_V(ERROR, TAG, "Delete resource for KeepAlive failed[%d]", result);
+    }
+
+    OIC_LOG(DEBUG, TAG, "DeleteKeepAliveResource OUT");
+    return result;
+}
+
+OCStackResult HandleKeepAliveRequest(const CAEndpoint_t* endPoint,
+                                     const CARequestInfo_t* requestInfo)
+{
+    VERIFY_NON_NULL(endPoint, FATAL, OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
+
+    OIC_LOG(DEBUG, TAG, "HandleKeepAliveRequest IN");
+
+    OCStackResult result = OC_STACK_OK;
+    if (CA_PUT == requestInfo->method)
+    {
+        result = HandleKeepAlivePUTRequest(endPoint, requestInfo);
+    }
+    else if (CA_GET == requestInfo->method)
+    {
+        result = HandleKeepAliveGETRequest(endPoint, requestInfo);
+    }
+
+    OIC_LOG(DEBUG, TAG, "HandleKeepAliveRequest OUT");
+    return result;
+}
+
+OCStackResult HandleKeepAliveGETRequest(const CAEndpoint_t* endPoint,
+                                        const CARequestInfo_t* requestInfo)
+{
+    VERIFY_NON_NULL(endPoint, FATAL, OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
+
+    OIC_LOG_V(DEBUG, TAG, "Find Ping resource [%s]", requestInfo->info.resourceUri);
+
+    CAResponseResult_t result = CA_CONTENT;
+    OCResource *resourcePtr = FindResourceByUri(requestInfo->info.resourceUri);
+    if (!resourcePtr)
+    {
+        // Resource URL not specified
+        OIC_LOG_V(DEBUG, TAG, "There is no Ping resource [%s]", requestInfo->info.resourceUri);
+        result = CA_NOT_FOUND;
+    }
+
+    SendDirectStackResponse(endPoint, requestInfo->info.messageId, result, requestInfo->info.type,
+                            requestInfo->info.numOptions, requestInfo->info.options,
+                            requestInfo->info.token, requestInfo->info.tokenLength,
+                            requestInfo->info.resourceUri);
+
+    return OC_STACK_OK;
+}
+
+OCStackResult HandleKeepAlivePUTRequest(const CAEndpoint_t* endPoint,
+                                        const CARequestInfo_t* requestInfo)
+{
+    VERIFY_NON_NULL(endPoint, FATAL, OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
+
+    // Get entry from KeepAlive table.
+    uint32_t index = 0;
+    KeepAliveEntry_t *entry = GetEntryFromEndpoint(endPoint, &index);
+    if (!entry)
+    {
+        OIC_LOG(ERROR, TAG, "Received the first keepalive message from client");
+        entry = AddKeepAliveEntry(endPoint, OC_SERVER, NULL);
+        if (!entry)
+        {
+            OIC_LOG(ERROR, TAG, "Failed to add new keepalive entry");
+            return OC_STACK_ERROR;
+        }
+    }
+
+    OCPayload *ocPayload = NULL;
+    OCParsePayload(&ocPayload, PAYLOAD_TYPE_REPRESENTATION,
+                   requestInfo->info.payload, requestInfo->info.payloadSize);
+    OCRepPayload *repPayload = (OCRepPayload *)ocPayload;
+
+    int64_t interval = 0;
+    OCRepPayloadGetPropInt(repPayload, INTERVAL, &interval);
+    entry->interval = interval;
+    OIC_LOG_V(DEBUG, TAG, "Received interval is [%d]", entry->interval);
+    entry->timeStamp = OICGetCurrentTime(TIME_IN_US);
+
+    // Send response message.
+    SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_VALID, requestInfo->info.type,
+                            requestInfo->info.numOptions, requestInfo->info.options,
+                            requestInfo->info.token, requestInfo->info.tokenLength,
+                            requestInfo->info.resourceUri);
+
+    return OC_STACK_OK;
+}
+
+OCStackResult HandleKeepAliveResponse(const CAEndpoint_t *endPoint,
+                                      OCStackResult responseCode,
+                                      const OCRepPayload *respPayload)
+{
+    VERIFY_NON_NULL(endPoint, FATAL, OC_STACK_INVALID_PARAM);
+
+    OIC_LOG(DEBUG, TAG, "HandleKeepAliveResponse IN");
+
+    // Get entry from KeepAlive table.
+    uint32_t index = 0;
+    KeepAliveEntry_t *entry = GetEntryFromEndpoint(endPoint, &index);
+    if (!entry)
+    {
+        // Receive response message about find /oic/ping request.
+        OIC_LOG(ERROR, TAG, "There is no connection info in KeepAlive table");
+
+        if (OC_STACK_NO_RESOURCE == responseCode)
+        {
+            OIC_LOG(ERROR, TAG, "Server doesn't have a ping resource");
+            return OC_STACK_ERROR;
+        }
+        else if (OC_STACK_OK == responseCode)
+        {
+            int64_t *recvInterval = NULL;
+            size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
+            OCRepPayloadGetIntArray(respPayload, INTERVAL_ARRAY, &recvInterval, dimensions);
+            size_t serverIntervalSize = calcDimTotal(dimensions);
+
+            entry = AddKeepAliveEntry(endPoint, OC_CLIENT, recvInterval);
+            if (!entry)
+            {
+                OIC_LOG(ERROR, TAG, "Failed to add new KeepAlive entry");
+                return OC_STACK_ERROR;
+            }
+
+            if (serverIntervalSize)
+            {
+                // update interval size with received size of server.
+                entry->intervalSize = serverIntervalSize;
+            }
+
+            // Send first ping message
+            return SendPingMessage(entry);
+        }
+    }
+    else
+    {
+        // Set sentPingMsg values with false.
+        entry->sentPingMsg = false;
+    }
+
+    OIC_LOG(DEBUG, TAG, "HandleKeepAliveResponse OUT");
+    return OC_STACK_OK;
+}
+
+void ProcessKeepAlive()
+{
+    if (!g_isKeepAliveInitialized)
+    {
+        OIC_LOG(ERROR, TAG, "KeepAlive not initialized");
+        return;
+    }
+
+    uint32_t len = u_arraylist_length(g_keepAliveConnectionTable);
+
+    for (uint32_t i = 0; i < len; i++)
+    {
+        KeepAliveEntry_t *entry = u_arraylist_get(g_keepAliveConnectionTable, i);
+        if (NULL == entry)
+        {
+            continue;
+        }
+
+        uint64_t currentTime = OICGetCurrentTime(TIME_IN_US);
+        if (OC_CLIENT == entry->mode)
+        {
+            if (entry->sentPingMsg)
+            {
+                /*
+                 * If an OIC Client does not receive the response within 1 minutes,
+                 * terminate the connection.
+                 * In this case the timeStamp means last time sent ping message.
+                 */
+                if ((KEEPALIVE_RESPONSE_TIMEOUT_SEC * USECS_PER_SEC) <= currentTime - entry->timeStamp)
+                {
+                    OIC_LOG(DEBUG, TAG, "Client does not receive the response within 1 minutes.");
+
+                    // Send message to disconnect session.
+                    SendDisconnectMessage(entry);
+                }
+            }
+            else
+            {
+                if ((entry->interval * KEEPALIVE_RESPONSE_TIMEOUT_SEC * USECS_PER_SEC)
+                        <= currentTime - entry->timeStamp)
+                {
+                    // Increase interval value.
+                    IncreaseInterval(entry);
+
+                    OCStackResult result = SendPingMessage(entry);
+                    if (OC_STACK_OK != result)
+                    {
+                        OIC_LOG(ERROR, TAG, "Failed to send ping request");
+                        continue;
+                    }
+                }
+            }
+        }
+        else if (OC_SERVER == entry->mode)
+        {
+            /*
+             * If an OIC Server does not receive a PUT request to ping resource
+             * within the specified interval time, terminate the connection.
+             * In this case the timeStamp means last time received ping message.
+             */
+            if ((entry->interval * KEEPALIVE_RESPONSE_TIMEOUT_SEC * USECS_PER_SEC)
+                    <= currentTime - entry->timeStamp)
+            {
+                OIC_LOG(DEBUG, TAG, "Server does not receive a PUT request.");
+                SendDisconnectMessage(entry);
+            }
+        }
+    }
+}
+
+void IncreaseInterval(KeepAliveEntry_t *entry)
+{
+    VERIFY_NON_NULL_NR(entry, FATAL);
+
+    OIC_LOG_V(DEBUG, TAG, "Total interval counts: %d", entry->intervalSize);
+    if (entry->intervalSize > entry->currIndex + 1)
+    {
+        entry->currIndex++;
+        entry->interval = entry->intervalInfo[entry->currIndex];
+        OIC_LOG_V(DEBUG, TAG, "increase interval value [%d]", entry->interval);
+    }
+}
+
+OCStackResult SendDisconnectMessage(const KeepAliveEntry_t *entry)
+{
+    VERIFY_NON_NULL(entry, FATAL, OC_STACK_INVALID_PARAM);
+
+    /*
+     * Send empty message to disconnect a connection.
+     * If CA get the empty message from RI, CA will disconnect a connection.
+     */
+    CARequestInfo_t requestInfo = { .method = CA_PUT };
+    return CASendRequest(&entry->remoteAddr, &requestInfo);
+}
+
+OCStackResult SendPingMessage(KeepAliveEntry_t *entry)
+{
+    VERIFY_NON_NULL(entry, FATAL, OC_STACK_INVALID_PARAM);
+
+    // Send ping message.
+    OCCallbackData pingData = { .cb = PingRequestCallback };
+    OCDevAddr devAddr = { .adapter = OC_ADAPTER_TCP };
+    CopyEndpointToDevAddr(&(entry->remoteAddr), &devAddr);
+
+    OCRepPayload *payload = OCRepPayloadCreate();
+    if (!payload)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
+        return OC_STACK_ERROR;
+    }
+    payload->base.type = PAYLOAD_TYPE_REPRESENTATION;
+    OCRepPayloadSetPropInt(payload, INTERVAL, entry->interval);
+
+    OCDoResource(NULL, OC_REST_PUT, KEEPALIVE_RESOURCE_URI, &devAddr,
+                 (OCPayload *) payload, CT_ADAPTER_TCP, OC_LOW_QOS, &pingData, NULL, 0);
+
+    // Update timeStamp with time sent ping message for next ping message.
+    entry->timeStamp = OICGetCurrentTime(TIME_IN_US);
+    entry->sentPingMsg = true;
+
+    OIC_LOG_V(DEBUG, TAG, "Client sent ping message, interval [%d]", entry->interval);
+
+    return OC_STACK_OK;
+}
+
+OCStackApplicationResult PingRequestCallback(void* ctx, OCDoHandle handle,
+                                             OCClientResponse *clientResponse)
+{
+    OIC_LOG(DEBUG, TAG, "PingRequestCallback IN");
+    (void) ctx;
+    (void) handle;
+    if (NULL == clientResponse)
+    {
+        OIC_LOG(ERROR, TAG, "clientResponse is NULL");
+        return OC_STACK_KEEP_TRANSACTION;
+    }
+
+    CAEndpoint_t endpoint = { .adapter = CA_ADAPTER_TCP };
+    CopyDevAddrToEndpoint(&(clientResponse->devAddr), &endpoint);
+
+    HandleKeepAliveResponse(&endpoint, clientResponse->result,
+                            (OCRepPayload *)clientResponse->payload);
+
+    OIC_LOG(DEBUG, TAG, "PingRequestCallback OUT");
+    return OC_STACK_KEEP_TRANSACTION;
+}
+
+KeepAliveEntry_t *GetEntryFromEndpoint(const CAEndpoint_t *endpoint, uint32_t *index)
+{
+    if (!g_keepAliveConnectionTable)
+    {
+        OIC_LOG(ERROR, TAG, "KeepAlive Table was not Created.");
+        return NULL;
+    }
+
+    uint32_t len = u_arraylist_length(g_keepAliveConnectionTable);
+
+    for (uint32_t i = 0; i < len; i++)
+    {
+        KeepAliveEntry_t *entry = u_arraylist_get(g_keepAliveConnectionTable, i);
+        if (NULL == entry)
+        {
+            continue;
+        }
+
+        if (!strncmp(entry->remoteAddr.addr, endpoint->addr, sizeof(entry->remoteAddr.addr))
+                && (entry->remoteAddr.port == endpoint->port))
+        {
+            OIC_LOG(DEBUG, TAG, "Connection Info found in KeepAlive table");
+            *index = i;
+            return entry;
+        }
+    }
+
+    return NULL;
+}
+
+KeepAliveEntry_t *AddKeepAliveEntry(const CAEndpoint_t *endpoint, OCMode mode,
+                                    int64_t *intervalInfo)
+{
+    if (!endpoint)
+    {
+        OIC_LOG(ERROR, TAG, "endpoint is NULL");
+        return NULL;
+    }
+
+    if (!g_keepAliveConnectionTable)
+    {
+        OIC_LOG(ERROR, TAG, "KeepAlive Table was not Created.");
+        return NULL;
+    }
+
+    KeepAliveEntry_t *entry = (KeepAliveEntry_t *) OICCalloc(1, sizeof(KeepAliveEntry_t));
+    if (NULL == entry)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to Calloc KeepAlive Entry");
+        return NULL;
+    }
+
+    entry->mode = mode;
+    entry->timeStamp = OICGetCurrentTime(TIME_IN_US);
+    entry->remoteAddr.adapter = endpoint->adapter;
+    entry->remoteAddr.flags = endpoint->flags;
+    entry->remoteAddr.interface = endpoint->interface;
+    entry->remoteAddr.port = endpoint->port;
+    strncpy(entry->remoteAddr.addr, endpoint->addr, sizeof(entry->remoteAddr.addr));
+
+    entry->intervalSize = DEFAULT_INTERVAL_COUNT;
+    entry->intervalInfo = intervalInfo;
+    if (!entry->intervalInfo)
+    {
+        entry->intervalInfo = (int64_t*) OICMalloc(entry->intervalSize * sizeof(int64_t));
+        for (size_t i = 0; i < entry->intervalSize; i++)
+        {
+            entry->intervalInfo[i] = KEEPALIVE_MIN_INTERVAL << i;
+        }
+    }
+    entry->interval = entry->intervalInfo[0];
+
+    bool result = u_arraylist_add(g_keepAliveConnectionTable, (void *)entry);
+    if (!result)
+    {
+        OIC_LOG(ERROR, TAG, "Adding node to head failed");
+        OICFree(entry->intervalInfo);
+        OICFree(entry);
+        return NULL;
+    }
+
+    return entry;
+}
+
+OCStackResult RemoveKeepAliveEntry(const CAEndpoint_t *endpoint)
+{
+    VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
+
+    uint32_t index = 0;
+    KeepAliveEntry_t *entry = GetEntryFromEndpoint(endpoint, &index);
+    if (!entry)
+    {
+        OIC_LOG(ERROR, TAG, "There is no entry in keepalive table.");
+        return OC_STACK_ERROR;
+    }
+
+    KeepAliveEntry_t *removedEntry = u_arraylist_remove(g_keepAliveConnectionTable, index);
+    if (NULL == removedEntry)
+    {
+        OIC_LOG(ERROR, TAG, "Removed Entry is NULL");
+        return OC_STACK_ERROR;
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "Remove Connection Info from KeepAlive table, "
+             "remote addr=%s port:%d", removedEntry->remoteAddr.addr,
+             removedEntry->remoteAddr.port);
+
+    OICFree(entry->intervalInfo);
+    OICFree(removedEntry);
+
+    return OC_STACK_OK;
+}
+
+void HandleKeepAliveConnCB(const CAEndpoint_t *endpoint)
+{
+    VERIFY_NON_NULL_NR(endpoint, FATAL);
+
+    OIC_LOG(DEBUG, TAG, "Received the connected device information from CA");
+
+    // Send discover message to find ping resource
+    OCCallbackData pingData = { .cb = PingRequestCallback };
+    OCDevAddr devAddr = { .adapter = OC_ADAPTER_TCP };
+    CopyEndpointToDevAddr(endpoint, &devAddr);
+
+    OCDoResource(NULL, OC_REST_DISCOVER, KEEPALIVE_RESOURCE_URI, &devAddr, NULL,
+                 OC_ADAPTER_TCP, OC_HIGH_QOS, &pingData, NULL, 0);
+}
+
+void HandleKeepAliveDisconnCB(const CAEndpoint_t *endpoint)
+{
+    VERIFY_NON_NULL_NR(endpoint, FATAL);
+
+    OIC_LOG(DEBUG, TAG, "Received the disconnected device information from CA");
+
+    OCStackResult result = RemoveKeepAliveEntry(endpoint);
+    if(result != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to remove entry");
+        return;
+    }
+}
index 5a97219..0378852 100644 (file)
 #include "ocpayload.h"
 #include "payload_logging.h"
 
-#define TAG "OCRDPayload"
+#define TAG "OIC_RI_RDPAYLOAD"
 
 #define CBOR_ROOT_ARRAY_LENGTH 1
 
-static CborError FindStringInMap(CborValue *map, char *tags, char **value);
-static CborError FindIntInMap(CborValue *map, char *tags, uint64_t *value);
-static CborError FindStringLLInMap(const CborValue *linksMap, char *tag, OCStringLL **links);
-static int64_t ConditionalAddTextStringToMap(CborEncoder* map, const char* key, size_t keylen, const char *value);
-static int64_t ConditionalAddIntToMap(CborEncoder *map, const char *tags, const size_t size, const uint64_t *value);
-static int64_t AddStringLLToMap(CborEncoder *map, char *tag, const size_t size, OCStringLL *value);
-
-int64_t OCRDPayloadToCbor(const OCRDPayload *rdPayload, uint8_t *outPayload, size_t *size)
+static CborError OCTagsPayloadToCbor(OCTagsPayload *tags, CborEncoder *setMap);
+static CborError OCLinksPayloadToCbor(OCLinksPayload *rtPtr, CborEncoder *setMap);
+static CborError OCTagsCborToPayload(CborValue *tagsMap, OCTagsPayload **tagsPayload);
+static CborError OCLinksCborToPayload(CborValue *linksArray, OCLinksPayload **linksPayload);
+static CborError FindStringInMap(const CborValue *map, const char *tags, char **value);
+static CborError FindIntInMap(const CborValue *map, const char *tags, uint64_t *value);
+static CborError FindStringLLInMap(const CborValue *linksMap, const char *tag, OCStringLL **links);
+static CborError ConditionalAddTextStringToMap(CborEncoder* map, const char* key, const char *value);
+static CborError ConditionalAddIntToMap(CborEncoder *map, const char *tags, const uint64_t *value);
+static CborError AddStringLLToMap(CborEncoder *map, const char *tag, const OCStringLL *value);
+
+CborError OCRDPayloadToCbor(const OCRDPayload *rdPayload, uint8_t *outPayload, size_t *size)
 {
-    if (!outPayload || !size)
-    {
-        OC_LOG(ERROR, TAG, "Invalid parameters.");
-        return OC_STACK_INVALID_PARAM;
-    }
-
-    CborEncoder encoder;
+    CborError cborEncoderResult = CborErrorIO;
     int flags = 0;
+    CborEncoder encoder;
+    VERIFY_PARAM_NON_NULL(TAG, rdPayload, "Invalid input parameter rdPayload");
+    VERIFY_PARAM_NON_NULL(TAG, outPayload, "Invalid input parameter outPayload");
+    VERIFY_PARAM_NON_NULL(TAG, size, "Invalid input parameter size");
+
     cbor_encoder_init(&encoder, outPayload, *size, flags);
 
-    CborError cborEncoderResult;
     if (rdPayload->rdDiscovery)
     {
         CborEncoder map;
         cborEncoderResult = cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength);
-        if (CborNoError != cborEncoderResult)
-        {
-            OC_LOG(ERROR, TAG, "Failed creating discovery map.");
-            goto cbor_error;
-        }
-        if (CborNoError != ConditionalAddTextStringToMap(&map, OC_RSRVD_DEVICE_NAME,
-                sizeof(OC_RSRVD_DEVICE_NAME) - 1, (char *)rdPayload->rdDiscovery->n.deviceName))
-        {
-            OC_LOG(ERROR, TAG, "Failed setting OC_RSRVD_DEVICE_NAME.");
-            goto cbor_error;
-        }
-        if (CborNoError != ConditionalAddTextStringToMap(&map, OC_RSRVD_DEVICE_ID,
-                sizeof(OC_RSRVD_DEVICE_ID) - 1, (char *)rdPayload->rdDiscovery->di.id))
-        {
-            OC_LOG(ERROR, TAG, "Failed setting OC_RSRVD_DEVICE_ID.");
-            goto cbor_error;
-        }
-        uint64_t sel = (uint8_t) rdPayload->rdDiscovery->sel;
-        if (CborNoError != ConditionalAddIntToMap(&map, OC_RSRVD_RD_DISCOVERY_SEL,
-            sizeof(OC_RSRVD_RD_DISCOVERY_SEL) - 1, &sel))
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to create discovery map");
+
+        cborEncoderResult = ConditionalAddTextStringToMap(&map, OC_RSRVD_DEVICE_NAME,
+            rdPayload->rdDiscovery->n.deviceName);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_DEVICE_NAME in map");
+
+        cborEncoderResult = ConditionalAddTextStringToMap(&map, OC_RSRVD_DEVICE_ID,
+            (char *)rdPayload->rdDiscovery->di.id);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_DEVICE_ID in map");
+
         {
-            OC_LOG(ERROR, TAG, "Failed setting OC_RSRVD_RD_DISCOVERY_SEL.");
-            goto cbor_error;
+            uint64_t value = rdPayload->rdDiscovery->sel;
+            cborEncoderResult = ConditionalAddIntToMap(&map, OC_RSRVD_RD_DISCOVERY_SEL, &value);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add RD_DISCOVERY_SEL in map");
         }
         cborEncoderResult = cbor_encoder_close_container(&encoder, &map);
-        if (CborNoError != cborEncoderResult)
-        {
-            OC_LOG(ERROR, TAG, "Failed closing discovery map.");
-            goto cbor_error;
-        }
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed closing discovery map");
     }
     else if (rdPayload->rdPublish)
     {
         CborEncoder colArray;
         cborEncoderResult = cbor_encoder_create_array(&encoder, &colArray, CborIndefiniteLength);
-        if (CborNoError != cborEncoderResult)
-        {
-            OC_LOG(ERROR, TAG, "Failed creating collection array.");
-            goto cbor_error;
-        }
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to create collection array");
 
         OCResourceCollectionPayload *rdPublish = rdPayload->rdPublish;
         while (rdPublish)
         {
-            if (OC_STACK_OK != OCTagsPayloadToCbor(rdPublish->tags, &colArray))
-            {
-                OC_LOG(ERROR, TAG, "Failed creating tags payload.");
-                goto cbor_error;
-            }
-            if (OC_STACK_OK != OCLinksPayloadToCbor(rdPublish->setLinks, &colArray))
-            {
-                OC_LOG(ERROR, TAG, "Failed creating links payload.");
-                goto cbor_error;
-            }
+            cborEncoderResult = OCTagsPayloadToCbor(rdPublish->tags, &colArray);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed adding tags payload");
+            cborEncoderResult = OCLinksPayloadToCbor(rdPublish->setLinks, &colArray);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed adding setLinks payload");
             rdPublish = rdPublish->next;
         }
         cborEncoderResult = cbor_encoder_close_container(&encoder, &colArray);
-        if (CborNoError != cborEncoderResult)
-        {
-            OC_LOG(ERROR, TAG, "Failed closing collection array.");
-            goto cbor_error;
-        }
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed closing collection array");
     }
     else
     {
         CborEncoder map;
         cborEncoderResult = cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength);
-        if (CborNoError != cborEncoderResult)
-        {
-            OC_LOG(ERROR, TAG, "Failed creating discovery map.");
-            goto cbor_error;
-        }
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed entering discovery map");
         cborEncoderResult = cbor_encoder_close_container(&encoder, &map);
-        if (CborNoError != cborEncoderResult)
-        {
-            OC_LOG(ERROR, TAG, "Failed creating discovery map.");
-            goto cbor_error;
-        }
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed closing discovery map");
     }
     *size = encoder.ptr - outPayload;
 
-    return OC_STACK_OK;
-cbor_error:
+    return cborEncoderResult;
+
+exit:
     OICFree(outPayload);
-    return OC_STACK_ERROR;
+    return cborEncoderResult;
 }
 
-OCStackResult OCTagsPayloadToCbor(OCTagsPayload *tags, CborEncoder *setMap)
+static CborError OCTagsPayloadToCbor(OCTagsPayload *tags, CborEncoder *setMap)
 {
     CborEncoder tagsMap;
     CborError cborEncoderResult = cbor_encoder_create_map(setMap, &tagsMap, CborIndefiniteLength);
-    if (CborNoError != cborEncoderResult)
-    {
-        OC_LOG(ERROR, TAG, "Failed creating TAGS map.");
-        return OC_STACK_ERROR;
-    }
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to create tags map");
+
+    cborEncoderResult = ConditionalAddTextStringToMap(&tagsMap, OC_RSRVD_DEVICE_NAME, tags->n.deviceName);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_DEVICE_NAME in tags map");
+
+    cborEncoderResult = ConditionalAddTextStringToMap(&tagsMap, OC_RSRVD_DEVICE_ID,
+            (char *)tags->di.id);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_DEVICE_ID in tags map");
+
+    cborEncoderResult = ConditionalAddTextStringToMap(&tagsMap, OC_RSRVD_RTS, tags->rts);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_RTS in tags map");
+
+    cborEncoderResult = ConditionalAddTextStringToMap(&tagsMap, OC_RSRVD_DREL, tags->drel);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_DREL in tags map");
+
+    cborEncoderResult = ConditionalAddTextStringToMap(&tagsMap, OC_RSRVD_BASE_URI, tags->baseURI);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_BASE_URI in tags map");
 
-    if (CborNoError != ConditionalAddTextStringToMap(&tagsMap, OC_RSRVD_DEVICE_NAME,
-            sizeof(OC_RSRVD_DEVICE_NAME) - 1, (char *)tags->n.deviceName))
-    {
-        OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_DEVICE_NAME in TAGS map.");
-        return OC_STACK_ERROR;
-    }
-    if (CborNoError != ConditionalAddTextStringToMap(&tagsMap, OC_RSRVD_DEVICE_ID,
-            sizeof(OC_RSRVD_DEVICE_ID) - 1, (char *)tags->di.id))
-    {
-        OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_DEVICE_ID in TAGS map.");
-        return OC_STACK_ERROR;
-    }
-    if (CborNoError != ConditionalAddTextStringToMap(&tagsMap, OC_RSRVD_RTS,
-            sizeof(OC_RSRVD_RTS) - 1, (char *)tags->rts))
-    {
-        OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_RTS in TAGS map.");
-        return OC_STACK_ERROR;
-    }
-    if (CborNoError != ConditionalAddTextStringToMap(&tagsMap, OC_RSRVD_DREL,
-            sizeof(OC_RSRVD_DREL) - 1, (char *)tags->drel))
-    {
-        OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_DREL in TAGS map.");
-        return OC_STACK_ERROR;
-    }
-    if (CborNoError != ConditionalAddTextStringToMap(&tagsMap, OC_RSRVD_BASE_URI,
-            sizeof(OC_RSRVD_BASE_URI) - 1, (char *)tags->baseURI))
-    {
-        OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_BASE_URI in TAGS map.");
-        return OC_STACK_ERROR;
-    }
-    uint64_t temp = (uint64_t)tags->bitmap;
-    if (CborNoError != ConditionalAddIntToMap(&tagsMap, OC_RSRVD_BITMAP,
-            sizeof(OC_RSRVD_BITMAP) - 1, &temp))
-    {
-        OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_BITMAP in TAGS map.");
-        return OC_STACK_ERROR;
-    }
-    temp = (uint64_t)tags->port;
-    if (CborNoError != ConditionalAddIntToMap(&tagsMap, OC_RSRVD_HOSTING_PORT,
-            sizeof(OC_RSRVD_HOSTING_PORT) - 1, &temp))
-    {
-        OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_HOSTING_PORT in TAGS map.");
-        return OC_STACK_ERROR;
-    }
-    temp = (uint64_t)tags->ins;
-    if (CborNoError != ConditionalAddIntToMap(&tagsMap, OC_RSRVD_INS,
-            sizeof(OC_RSRVD_INS) - 1, &temp))
-    {
-        OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_INS in TAGS map.");
-        return OC_STACK_ERROR;
-    }
-    temp = (uint64_t)tags->ttl;
-    if (CborNoError != ConditionalAddIntToMap(&tagsMap, OC_RSRVD_TTL,
-            sizeof(OC_RSRVD_TTL) - 1, &temp))
     {
-        OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_TTL in TAGS map.");
-        return OC_STACK_ERROR;
+        uint64_t value = tags->bitmap;
+        cborEncoderResult = ConditionalAddIntToMap(&tagsMap, OC_RSRVD_BITMAP, &value);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_BITMAP in tags map");
+
+        value = tags->port;
+        cborEncoderResult = ConditionalAddIntToMap(&tagsMap, OC_RSRVD_HOSTING_PORT, &value);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_HOSTING_PORT in tags map");
+
+        value = tags->ins;
+        cborEncoderResult = ConditionalAddIntToMap(&tagsMap, OC_RSRVD_INS, &value);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_INS in tags map");
+
+        value = tags->ttl;
+        cborEncoderResult = ConditionalAddIntToMap(&tagsMap, OC_RSRVD_TTL, &value);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_TTL in tags map");
     }
+
     cborEncoderResult = cbor_encoder_close_container(setMap, &tagsMap);
-    if (CborNoError != cborEncoderResult)
-    {
-        OC_LOG(ERROR, TAG, "Failed closing TAGS map.");
-        return OC_STACK_ERROR;
-    }
-    return OC_STACK_OK;
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to close container");
+
+exit:
+    return cborEncoderResult;
 }
 
-OCStackResult OCLinksPayloadToCbor(OCLinksPayload *rtPtr, CborEncoder *setMap)
+static CborError OCLinksPayloadToCbor(OCLinksPayload *rtPtr, CborEncoder *setMap)
 {
     CborEncoder linksArray;
     CborError cborEncoderResult;
 
     cborEncoderResult = cbor_encoder_create_array(setMap, &linksArray, CborIndefiniteLength);
-    if (CborNoError != cborEncoderResult)
-    {
-        OC_LOG(ERROR, TAG, "Failed creating LINKS array.");
-        return OC_STACK_ERROR;
-    }
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to create Links array");
+
     while (rtPtr)
     {
         CborEncoder linksMap;
-        cborEncoderResult = cbor_encoder_create_map(&linksArray, &linksMap,
-                CborIndefiniteLength);
-        if (CborNoError != cborEncoderResult)
-        {
-            OC_LOG(ERROR, TAG, "Failed creating LINKS map.");
-            return OC_STACK_ERROR;
-        }
-        if (CborNoError != ConditionalAddTextStringToMap(&linksMap, OC_RSRVD_HREF,
-                sizeof(OC_RSRVD_HREF) - 1, rtPtr->href))
-        {
-            OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_HREF in LINKS map.");
-            return OC_STACK_ERROR;
-        }
-        if (CborNoError != ConditionalAddTextStringToMap(&linksMap, OC_RSRVD_REL,
-                sizeof(OC_RSRVD_REL) - 1,  rtPtr->rel))
-        {
-            OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_REL in LINKS map.");
-            return OC_STACK_ERROR;
-        }
-        if (CborNoError != ConditionalAddTextStringToMap(&linksMap, OC_RSRVD_TITLE,
-                sizeof(OC_RSRVD_TITLE) - 1, rtPtr->title))
-        {
-            OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_TITLE in LINKS map.");
-            return OC_STACK_ERROR;
-        }
-        if (CborNoError != ConditionalAddTextStringToMap(&linksMap, OC_RSRVD_URI,
-                sizeof(OC_RSRVD_URI) - 1, rtPtr->uri))
-        {
-            OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_URI in LINKS map.");
-            return OC_STACK_ERROR;
-        }
-        if (CborNoError != AddStringLLToMap(&linksMap, OC_RSRVD_RESOURCE_TYPE,
-                sizeof(OC_RSRVD_RESOURCE_TYPE) - 1, rtPtr->rt))
-        {
-            OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_RESOURCE_TYPE in LINKS map.");
-            return OC_STACK_ERROR;
-        }
-        if (CborNoError != AddStringLLToMap(&linksMap, OC_RSRVD_INTERFACE,
-                sizeof(OC_RSRVD_INTERFACE) - 1, rtPtr->itf))
-        {
-            OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_INTERFACE in LINKS map.");
-            return OC_STACK_ERROR;
-        }
-        if (CborNoError != AddStringLLToMap(&linksMap, OC_RSRVD_MEDIA_TYPE,
-                sizeof(OC_RSRVD_MEDIA_TYPE) - 1, rtPtr->mt))
-        {
-            OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_MEDIA_TYPE in LINKS map.");
-            return OC_STACK_ERROR;
-        }
-        uint64_t temp = (uint64_t)rtPtr->ins;
-        if (CborNoError != ConditionalAddIntToMap(&linksMap, OC_RSRVD_INS,
-            sizeof(OC_RSRVD_INS) - 1, &temp))
+        cborEncoderResult = cbor_encoder_create_map(&linksArray, &linksMap, CborIndefiniteLength);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to create Links map");
+
+        cborEncoderResult = ConditionalAddTextStringToMap(&linksMap, OC_RSRVD_HREF, rtPtr->href);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_HREF in Links map");
+
+        cborEncoderResult = ConditionalAddTextStringToMap(&linksMap, OC_RSRVD_REL, rtPtr->rel);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_REL in Links map");
+
+        cborEncoderResult = ConditionalAddTextStringToMap(&linksMap, OC_RSRVD_TITLE, rtPtr->title);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_TITLE in Links map");
+
+        cborEncoderResult = ConditionalAddTextStringToMap(&linksMap, OC_RSRVD_URI, rtPtr->uri);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_URI in Links map");
+
+        cborEncoderResult = AddStringLLToMap(&linksMap, OC_RSRVD_RESOURCE_TYPE, rtPtr->rt);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_RT in Links map");
+
+        cborEncoderResult = AddStringLLToMap(&linksMap, OC_RSRVD_INTERFACE, rtPtr->itf);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_ITF in Links map");
+
+        cborEncoderResult = AddStringLLToMap(&linksMap, OC_RSRVD_MEDIA_TYPE, rtPtr->mt);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_MT in Links map");
+
         {
-            OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_INS in LINKS map.");
-            return OC_STACK_ERROR;
+            uint64_t value = rtPtr->ins;
+            cborEncoderResult = ConditionalAddIntToMap(&linksMap, OC_RSRVD_INS, &value);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_INS in Links map");
         }
+
         cborEncoderResult = cbor_encoder_close_container(&linksArray, &linksMap);
-        if (CborNoError != cborEncoderResult)
-        {
-            OC_LOG(ERROR, TAG, "Failed closing LINKS map.");
-            return OC_STACK_ERROR;
-        }
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed closing Links map");
+
         rtPtr = rtPtr->next;
     }
     cborEncoderResult = cbor_encoder_close_container(setMap, &linksArray);
-    if (CborNoError != cborEncoderResult)
-    {
-        OC_LOG(ERROR, TAG, "Failed closing LINKS array.");
-        return OC_STACK_ERROR;;
-    }
-    return OC_STACK_OK;
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed closing links array");
+
+exit:
+    return cborEncoderResult;
 }
 
 OCStackResult OCRDCborToPayload(const CborValue *cborPayload, OCPayload **outPayload)
 {
     CborValue *rdCBORPayload = (CborValue *)cborPayload;
+    OCStackResult ret = OC_STACK_NO_MEMORY;
     CborError cborFindResult;
 
     OCRDPayload *rdPayload = OCRDPayloadCreate();
-    if (!rdPayload)
-    {
-        goto no_memory;
-    }
+    VERIFY_PARAM_NON_NULL(TAG, rdPayload, "Failed allocating rdPayload");
+
+    ret = OC_STACK_MALFORMED_RESPONSE;
 
     if (cbor_value_is_array(rdCBORPayload))
     {
@@ -326,140 +230,100 @@ OCStackResult OCRDCborToPayload(const CborValue *cborPayload, OCPayload **outPay
             // enter tags map
             CborValue tags;
             cborFindResult = cbor_value_enter_container(rdCBORPayload, &tags);
-            if (cborFindResult != CborNoError)
-            {
-                goto cbor_error;
-            }
-            if (OC_STACK_OK != OCTagsCborToPayload(&tags, &tagsPayload))
-            {
-                OCFreeTagsResource(tagsPayload);
-                goto cbor_error;
-            }
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed entering tags container.");
+
+            cborFindResult= OCTagsCborToPayload(&tags, &tagsPayload);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed parsing tags payload.");
             OCTagsLog(DEBUG, tagsPayload);
-            if (OC_STACK_OK != OCLinksCborToPayload(&tags, &linksPayload))
-            {
-                OCFreeLinksResource(linksPayload);
-                OCFreeTagsResource(tagsPayload);
-                goto cbor_error;
-            }
+
+            cborFindResult = OCLinksCborToPayload(&tags, &linksPayload);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed parsing links payload.");
             OCLinksLog(DEBUG, linksPayload);
+
             // Move from tags payload to links array.
-            if (CborNoError != cbor_value_advance(rdCBORPayload))
-            {
-                OC_LOG(DEBUG, TAG, "Failed advancing from tags payload to links.");
-                OCFreeLinksResource(linksPayload);
-                OCFreeTagsResource(tagsPayload);
-                goto cbor_error;
-            }
+            cborFindResult = cbor_value_advance(rdCBORPayload);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed advancing rdCborPayload.");
         }
         rdPayload->rdPublish = OCCopyCollectionResource(tagsPayload, linksPayload);
-        if (!rdPayload->rdPublish)
-        {
-            goto cbor_error;
-        }
+        VERIFY_PARAM_NON_NULL(TAG, rdPayload->rdPublish, "Failed allocating rdPayload->rdPublish");
     }
     else if (cbor_value_is_map(rdCBORPayload))
     {
-        char *name = NULL;
-        if (CborNoError != FindStringInMap(rdCBORPayload, OC_RSRVD_DEVICE_NAME, &name))
-        {
-            goto cbor_error;
-        }
-        char *id = NULL;
-        if (CborNoError != FindStringInMap(rdCBORPayload, OC_RSRVD_DEVICE_ID, &id))
-        {
-            goto cbor_error;
-        }
-        uint64_t biasFactor = 0;
-        if (CborNoError != FindIntInMap(rdCBORPayload, OC_RSRVD_RD_DISCOVERY_SEL, &biasFactor))
+        rdPayload->rdDiscovery = (OCRDDiscoveryPayload *)OICCalloc(1, sizeof(OCRDDiscoveryPayload));
+        VERIFY_PARAM_NON_NULL(TAG, rdPayload->rdDiscovery, "Failed allocating discoveryPayload");
+
+        cborFindResult = FindStringInMap(rdCBORPayload, OC_RSRVD_DEVICE_NAME,
+                &rdPayload->rdDiscovery->n.deviceName);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed finding OC_RSRVD_DEVICE_NAME.");
+        char *deviceId = NULL;
+        cborFindResult = FindStringInMap(rdCBORPayload, OC_RSRVD_DEVICE_ID, &deviceId);
+        if (deviceId)
         {
-            goto cbor_error;
+            memcpy(rdPayload->rdDiscovery->di.id, deviceId, strlen(deviceId));
+            OICFree(deviceId);
         }
-        rdPayload->rdDiscovery = OCRDDiscoveryPayloadCreate(name, id, (uint8_t)biasFactor);
-        if (!rdPayload->rdDiscovery)
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed finding OC_RSRVD_DEVICE_ID.");
+
         {
-            goto no_memory;
+            uint64_t value = 0;
+            cborFindResult = FindIntInMap(rdCBORPayload, OC_RSRVD_RD_DISCOVERY_SEL, &value);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed finding OC_RSRVD_RD_DISCOVERY_SEL.");
+            rdPayload->rdDiscovery->sel = value;
         }
-        OICFree(id);
-        OICFree(name);
+
         cborFindResult =  cbor_value_advance(rdCBORPayload);
-        if (CborNoError != cborFindResult)
-        {
-            goto cbor_error;
-        }
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed advancing rdCBORPayload.");
     }
-    OC_LOG_PAYLOAD(DEBUG, (OCPayload *) rdPayload);
+    OIC_LOG_PAYLOAD(DEBUG, (OCPayload *) rdPayload);
     *outPayload = (OCPayload *)rdPayload;
     return OC_STACK_OK;
-no_memory:
-    OC_LOG(ERROR, TAG, "Failed allocating memory.");
-    OCRDPayloadDestroy(rdPayload);
-    return OC_STACK_NO_MEMORY;
 
-cbor_error:
+exit:
     OCRDPayloadDestroy(rdPayload);
-    return OC_STACK_ERROR;
+    return ret;
 }
 
-static CborError FindStringInMap(CborValue *map, char *tags, char **value)
+static CborError FindStringInMap(const CborValue *map, const char *tags, char **value)
 {
     CborValue curVal;
-    size_t len;
     CborError cborFindResult = cbor_value_map_find_value(map, tags, &curVal);
     if (CborNoError == cborFindResult && cbor_value_is_text_string(&curVal))
     {
+        size_t len = 0;
         cborFindResult = cbor_value_dup_text_string(&curVal, value, &len, NULL);
-        if (CborNoError != cborFindResult)
-        {
-            OC_LOG_V(ERROR, TAG, "Failed finding value for tag %s .", tags);
-            return cborFindResult;
-        }
     }
-    return CborNoError;
+    return cborFindResult;
 }
 
-static CborError FindIntInMap(CborValue *map, char *tags, uint64_t *value)
+static CborError FindIntInMap(const CborValue *map, const char *tags, uint64_t *value)
 {
     CborValue curVal;
     CborError cborFindResult = cbor_value_map_find_value(map, tags, &curVal);
     if (CborNoError == cborFindResult && cbor_value_is_unsigned_integer(&curVal))
     {
         cborFindResult = cbor_value_get_uint64(&curVal, value);
-        if (CborNoError != cborFindResult)
-        {
-            OC_LOG_V(ERROR, TAG, "Failed finding value for tag %s .", tags);
-            return cborFindResult;
-        }
     }
-    return CborNoError;
+    return cborFindResult;
 }
 
-static CborError FindStringLLInMap(const CborValue *linksMap, char *tag, OCStringLL **links)
+static CborError FindStringLLInMap(const CborValue *linksMap, const char *tag, OCStringLL **links)
 {
     size_t len;
-    CborError cborFindResult;
     CborValue rtArray;
-    cborFindResult = cbor_value_map_find_value(linksMap, tag, &rtArray);
-    if (CborNoError != cborFindResult)
-    {
-        return CborUnknownError;
-    }
+    OCStringLL* llPtr = *links;
+    CborError cborFindResult = cbor_value_map_find_value(linksMap, tag, &rtArray);
+    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed finding tag");
+
     CborValue rtVal;
     cborFindResult = cbor_value_enter_container(&rtArray, &rtVal);
-    if (CborNoError != cborFindResult)
-    {
-        return CborUnknownError;
-    }
-    OCStringLL* llPtr = *links;
+    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed entering container");
+
     while (cbor_value_is_text_string(&rtVal))
     {
         if (llPtr == NULL)
         {
             llPtr = (OCStringLL *)OICCalloc(1, sizeof(OCStringLL));
-            if (!llPtr)
-            {
-                return CborUnknownError;
-            }
+            VERIFY_PARAM_NON_NULL(TAG, llPtr, "Failed allocating OCStringLL");
             *links = llPtr;
         }
         else if(llPtr)
@@ -469,182 +333,113 @@ static CborError FindStringLLInMap(const CborValue *linksMap, char *tag, OCStrin
                 llPtr = llPtr->next;
             }
             llPtr->next = (OCStringLL *)OICCalloc(1, sizeof(OCStringLL));
-            if (!llPtr->next)
-            {
-                return CborUnknownError;
-            }
+            VERIFY_PARAM_NON_NULL(TAG, llPtr->next, "Failed allocating OCStringLL->next");
         }
         cborFindResult = cbor_value_dup_text_string(&rtVal, &(llPtr->value), &len, NULL);
-        if (CborNoError != cborFindResult)
-        {
-            return CborUnknownError;
-        }
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed duplicating value");
         cborFindResult = cbor_value_advance(&rtVal);
-        if (CborNoError != cborFindResult)
-        {
-            return CborUnknownError;
-        }
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed advancing OCStringLL");
     }
 
     cborFindResult = cbor_value_leave_container(&rtArray, &rtVal);
+    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed leaving container");
+
+exit:
     return cborFindResult;
 }
 
-OCStackResult OCTagsCborToPayload(CborValue *tagsMap, OCTagsPayload **tagsPayload)
+static CborError OCTagsCborToPayload(CborValue *tagsMap, OCTagsPayload **tagsPayload)
 {
+    CborError cborFindResult = CborErrorOutOfMemory;
     OCTagsPayload *tags = (OCTagsPayload *)OICCalloc(1, sizeof(OCTagsPayload));
-    if (!tags)
-    {
-        return OC_STACK_NO_MEMORY;
-    }
+    VERIFY_PARAM_NON_NULL(TAG, tags, "Failed allocating tags");
+
     if (cbor_value_is_map(tagsMap))
     {
-        if (CborNoError != FindStringInMap(tagsMap, OC_RSRVD_DEVICE_NAME, &tags->n.deviceName))
-        {
-            OCFreeTagsResource(tags);
-            return OC_STACK_ERROR;
-        }
-        if (CborNoError != FindStringInMap(tagsMap, OC_RSRVD_DREL, &tags->drel))
-        {
-            OCFreeTagsResource(tags);
-            return OC_STACK_ERROR;
-        }
-        if (CborNoError != FindStringInMap(tagsMap, OC_RSRVD_RTS, &tags->rts))
-        {
-            OCFreeTagsResource(tags);
-            return OC_STACK_ERROR;
-        }
-        if (CborNoError != FindStringInMap(tagsMap, OC_RSRVD_BASE_URI, &tags->baseURI))
-        {
-            OCFreeTagsResource(tags);
-            return OC_STACK_ERROR;
-        }
-        char *id = NULL;
-        if (CborNoError != FindStringInMap(tagsMap, OC_RSRVD_DEVICE_ID, &id))
-        {
-            OCFreeTagsResource(tags);
-            return OC_STACK_ERROR;
-        }
-        if (id)
-        {
-            OICStrcpy((char*)tags->di.id, MAX_IDENTITY_SIZE, id);
-            tags->di.id_length = MAX_IDENTITY_SIZE;
-            OICFree(id);
-        }
-        uint64_t temp;
-        if (CborNoError != FindIntInMap(tagsMap, OC_RSRVD_HOSTING_PORT, &temp))
-        {
-            OCFreeTagsResource(tags);
-            return OC_STACK_ERROR;
-        }
-        tags->port = (uint16_t) temp;
-        if (CborNoError != FindIntInMap(tagsMap, OC_RSRVD_BITMAP, &temp))
-        {
-            OCFreeTagsResource(tags);
-            return OC_STACK_ERROR;
-        }
-        tags->bitmap = (uint8_t) temp;
-        if (CborNoError != FindIntInMap(tagsMap, OC_RSRVD_INS, &temp))
-        {
-            OCFreeTagsResource(tags);
-            return OC_STACK_ERROR;
-        }
-        tags->ins = (uint8_t) temp;
-        if (CborNoError != FindIntInMap(tagsMap, OC_RSRVD_TTL, &temp))
-        {
-            OCFreeTagsResource(tags);
-            return OC_STACK_ERROR;
-        }
-        tags->ttl = (uint32_t) temp;
-
-        if (CborNoError != cbor_value_advance(tagsMap))
-        {
-            OCFreeTagsResource(tags);
-            return OC_STACK_ERROR;
-        }
+        cborFindResult = FindStringInMap(tagsMap, OC_RSRVD_DEVICE_NAME, &tags->n.deviceName);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed finding deviceName");
+        cborFindResult = FindStringInMap(tagsMap, OC_RSRVD_DREL, &tags->drel);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed finding drel");
+        cborFindResult = FindStringInMap(tagsMap, OC_RSRVD_RTS, &tags->rts);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed finding rts");
+        cborFindResult = FindStringInMap(tagsMap, OC_RSRVD_BASE_URI, &tags->baseURI);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed finding baseURI");
+        char *deviceId = NULL;
+        cborFindResult = FindStringInMap(tagsMap, OC_RSRVD_DEVICE_ID, &deviceId);
+        if (deviceId)
+        {
+            memcpy(tags->di.id, deviceId, strlen(deviceId));
+            OICFree(deviceId);
+        }
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed finding deviceId");
+        {
+            uint64_t value = 0;
+            cborFindResult = FindIntInMap(tagsMap, OC_RSRVD_HOSTING_PORT, &value);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed finding port");
+            tags->port = value;
+            value = 0;
+            cborFindResult = FindIntInMap(tagsMap, OC_RSRVD_BITMAP, &value);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed finding bitmap");
+            tags->bitmap = value;
+            value = 0;
+            cborFindResult = FindIntInMap(tagsMap, OC_RSRVD_INS, &value);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed finding ins");
+            tags->ins = value;
+            value = 0;
+            cborFindResult = FindIntInMap(tagsMap, OC_RSRVD_TTL, &value);
+            tags->ttl = value;
+        }
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed finding ttl");
+        cborFindResult = cbor_value_advance(tagsMap);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed advancing bitmap");
     }
     *tagsPayload = tags;
-    return OC_STACK_OK;
+    return cborFindResult;
+
+exit:
+    OCFreeTagsResource(tags);
+    return cborFindResult;
 }
 
-OCStackResult OCLinksCborToPayload(CborValue *linksArray, OCLinksPayload **linksPayload)
+static CborError OCLinksCborToPayload(CborValue *linksArray, OCLinksPayload **linksPayload)
 {
     CborValue linksMap;
+    OCLinksPayload *setLinks = NULL;
     CborError cborFindResult = cbor_value_enter_container(linksArray, &linksMap);
-    if (CborNoError != cborFindResult)
-    {
-        OC_LOG(ERROR, TAG, "Failed enter links map");
-        return OC_STACK_ERROR;
-    }
+    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed entering links map container");
 
     while (cbor_value_is_map(&linksMap))
     {
-        OCLinksPayload *setLinks = (OCLinksPayload *)OICCalloc(1, sizeof(OCLinksPayload));
-        if (!setLinks)
-        {
-            OC_LOG(ERROR, TAG, "Failed allocating memory.");
-            OCFreeLinksResource(*linksPayload);
-            return OC_STACK_NO_MEMORY;
-        }
+        setLinks = (OCLinksPayload *)OICCalloc(1, sizeof(OCLinksPayload));
+        VERIFY_PARAM_NON_NULL(TAG, setLinks, "Failed allocating setLinks");
+
         cborFindResult = FindStringInMap(&linksMap, OC_RSRVD_HREF, &setLinks->href);
-        if (CborNoError != cborFindResult)
-        {
-            OCFreeLinksResource(*linksPayload);
-            OCFreeLinksResource(setLinks);
-            return OC_STACK_ERROR;
-        }
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed finding href value");
+
         cborFindResult = FindStringInMap(&linksMap, OC_RSRVD_REL, &setLinks->rel);
-        if (CborNoError != cborFindResult)
-        {
-            OCFreeLinksResource(*linksPayload);
-            OCFreeLinksResource(setLinks);
-            return OC_STACK_ERROR;
-        }
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed finding rel value");
 
         cborFindResult = FindStringInMap(&linksMap, OC_RSRVD_TITLE, &setLinks->title);
-        if (CborNoError != cborFindResult)
-        {
-            OCFreeLinksResource(*linksPayload);
-            OCFreeLinksResource(setLinks);
-            return OC_STACK_ERROR;
-        }
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed finding title value");
+
         cborFindResult = FindStringInMap(&linksMap, OC_RSRVD_URI, &setLinks->uri);
-        if (CborNoError != cborFindResult)
-        {
-            OCFreeLinksResource(*linksPayload);
-            OCFreeLinksResource(setLinks);
-            return OC_STACK_ERROR;
-        }
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed finding uri value");
+
         cborFindResult = FindStringLLInMap(&linksMap, OC_RSRVD_RESOURCE_TYPE, &setLinks->rt);
-        if (CborNoError != cborFindResult)
-        {
-            OCFreeLinksResource(*linksPayload);
-            OCFreeLinksResource(setLinks);
-            return OC_STACK_ERROR;
-        }
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed finding rt value");
+
         cborFindResult = FindStringLLInMap(&linksMap, OC_RSRVD_INTERFACE, &setLinks->itf);
-        if (CborNoError != cborFindResult)
-        {
-            OCFreeLinksResource(*linksPayload);
-            OCFreeLinksResource(setLinks);
-            return OC_STACK_ERROR;
-        }
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed finding itf value");
+
         cborFindResult = FindStringLLInMap(&linksMap, OC_RSRVD_MEDIA_TYPE, &setLinks->mt);
-        if (CborNoError != cborFindResult)
-        {
-            OCFreeLinksResource(*linksPayload);
-            OCFreeLinksResource(setLinks);
-            return OC_STACK_ERROR;
-        }
-        uint64_t temp;
-        cborFindResult = FindIntInMap(&linksMap, OC_RSRVD_INS, &temp);
-        if (CborNoError != cborFindResult)
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed finding mt value");
+
         {
-            OCFreeLinksResource(*linksPayload);
-            OCFreeLinksResource(setLinks);
-            return OC_STACK_ERROR;
+            uint64_t value = 0;
+            cborFindResult = FindIntInMap(&linksMap, OC_RSRVD_INS, &value);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed finding ins value");
+            setLinks->ins = value;
         }
-        setLinks->ins = (uint8_t) temp;
 
         if (!*linksPayload)
         {
@@ -660,100 +455,84 @@ OCStackResult OCLinksCborToPayload(CborValue *linksArray, OCLinksPayload **links
             temp->next = setLinks;
         }
         cborFindResult = cbor_value_advance(&linksMap);
-        if (CborNoError != cborFindResult)
-        {
-            OC_LOG(ERROR, TAG, "Failed advancing links map");
-            OCFreeLinksResource(*linksPayload);
-            OCFreeLinksResource(setLinks);
-            return OC_STACK_ERROR;
-        }
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed advancing links map");
     }
-    return OC_STACK_OK;
+
+    return cborFindResult;
+
+exit:
+    OCFreeLinksResource(*linksPayload);
+    OCFreeLinksResource(setLinks);
+    return cborFindResult;
 }
 
-static int64_t AddTextStringToMap(CborEncoder* map, const char* key, size_t keylen,
-        const char* value)
+static CborError AddTextStringToMap(CborEncoder* map, const char* key, const char* value)
 {
-    return cbor_encode_text_string(map, key, keylen) |
-           cbor_encode_text_string(map, value, strlen(value));
+    CborError err = cbor_encode_text_string(map, key, strlen(key));
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting key value");
+    err = cbor_encode_text_string(map, value, strlen(value));
+exit:
+    return err;
 }
 
-static int64_t ConditionalAddTextStringToMap(CborEncoder* map, const char* key, size_t keylen,
-        const char* value)
+static CborError ConditionalAddTextStringToMap(CborEncoder* map, const char* key, const char* value)
 {
-    return value ? AddTextStringToMap(map, key, keylen, value) : 0;
+    return value ? AddTextStringToMap(map, key, value) : CborNoError;
 }
 
-static int64_t ConditionalAddIntToMap(CborEncoder *map, const char *tags, const size_t size,
-    const uint64_t *value)
+static CborError ConditionalAddIntToMap(CborEncoder *map, const char *tags, const uint64_t *value)
 {
-    return (*value) ? (cbor_encode_text_string(map, tags, size) |
-                     cbor_encode_uint(map, *value)): 0;
+    CborError err = CborNoError;
+    if (*value)
+    {
+        err = cbor_encode_text_string(map, tags, strlen(tags));
+        VERIFY_CBOR_SUCCESS(TAG, err, "failed setting value");
+        err = cbor_encode_uint(map, *value);
+    }
+exit:
+    return err;
 }
 
-static int64_t AddStringLLToMap(CborEncoder *map, char *tag, const size_t size, OCStringLL *value)
+static CborError AddStringLLToMap(CborEncoder *map, const char *tag, const OCStringLL *strType)
 {
     CborEncoder array;
     CborError cborEncoderResult;
-    cborEncoderResult = cbor_encode_text_string(map, tag, size);
-    if (CborNoError != cborEncoderResult)
-    {
-        return cborEncoderResult;
-    }
+    cborEncoderResult = cbor_encode_text_string(map, tag, strlen(tag));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed encoding string tag name");
     cborEncoderResult = cbor_encoder_create_array(map, &array, CborIndefiniteLength);
-    if (CborNoError != cborEncoderResult)
-    {
-        return cborEncoderResult;
-    }
-    OCStringLL *strType = value;
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed creating stringLL array");
     while (strType)
     {
         cborEncoderResult = cbor_encode_text_string(&array, strType->value, strlen(strType->value));
-        if (CborNoError != cborEncoderResult)
-        {
-            return cborEncoderResult;
-        }
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed encoding string value");
         strType = strType->next;
     }
     cborEncoderResult = cbor_encoder_close_container(map, &array);
-    if (CborNoError != cborEncoderResult)
-    {
-        return cborEncoderResult;
-    }
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed closing string array");
+exit:
     return cborEncoderResult;
 }
 
 OCRDPayload *OCRDPayloadCreate()
 {
     OCRDPayload *rdPayload = (OCRDPayload *)OICCalloc(1, sizeof(OCRDPayload));
-
-    if (!rdPayload)
-    {
-        return NULL;
-    }
-
+    VERIFY_PARAM_NON_NULL(TAG, rdPayload, "Failed allocating rdPayload");
     rdPayload->base.type = PAYLOAD_TYPE_RD;
 
+exit:
     return rdPayload;
 }
 
 OCRDDiscoveryPayload *OCRDDiscoveryPayloadCreate(const char *deviceName, const char *id, int biasFactor)
 {
     OCRDDiscoveryPayload *discoveryPayload = (OCRDDiscoveryPayload *)OICCalloc(1, sizeof(OCRDDiscoveryPayload));
-
-    if (!discoveryPayload)
-    {
-        return NULL;
-    }
+    VERIFY_PARAM_NON_NULL(TAG, discoveryPayload, "Failed allocating memory for discovery payload");
 
     if (deviceName)
     {
         discoveryPayload->n.deviceName = OICStrdup(deviceName);
-        if (!discoveryPayload->n.deviceName)
-        {
-            OICFree(discoveryPayload);
-            return NULL;
-        }
+        VERIFY_PARAM_NON_NULL(TAG, discoveryPayload->n.deviceName,
+                "Failed allocating memory for discovery device name");
     }
     if (id)
     {
@@ -761,7 +540,10 @@ OCRDDiscoveryPayload *OCRDDiscoveryPayloadCreate(const char *deviceName, const c
     }
 
     discoveryPayload->sel = biasFactor;
-
+    return discoveryPayload;
+exit:
+    OICFree(discoveryPayload);
+    discoveryPayload = NULL;
     return discoveryPayload;
 }
 
@@ -858,7 +640,7 @@ OCTagsPayload* OCCopyTagsResources(const char *deviceName, const unsigned char *
     return tags;
 
 memory_allocation_failed:
-    OC_LOG(ERROR, TAG, "Memory allocation failed.");
+    OIC_LOG(ERROR, TAG, "Memory allocation failed.");
     OCFreeTagsResource(tags);
     return NULL;
 }
@@ -869,7 +651,7 @@ OCLinksPayload* OCCopyLinksResources(const char *href, OCStringLL *rt, OCStringL
     OCLinksPayload *links = (OCLinksPayload *)OICCalloc(1, sizeof(OCLinksPayload));
     if (!links)
     {
-        OC_LOG(ERROR, TAG, "Failed allocating memory.");
+        OIC_LOG(ERROR, TAG, "Failed allocating memory.");
         return NULL;
     }
     if (href)
@@ -934,72 +716,27 @@ OCLinksPayload* OCCopyLinksResources(const char *href, OCStringLL *rt, OCStringL
     return links;
 
 memory_allocation_failed:
-    OC_LOG(ERROR, TAG, "Memory allocation failed.");
+    OIC_LOG(ERROR, TAG, "Memory allocation failed.");
     OCFreeLinksResource(links);
     return NULL;
 }
 
-void OCLinksAddResource(OCDiscoveryPayload *payload, const char *href, OCStringLL *rt,
-    OCStringLL *itf, const char *rel, bool obs, const char *title, const char *uri,
-    uint8_t ins, OCStringLL *mt)
-{
-    if(!payload->collectionResources->setLinks)
-    {
-        payload->collectionResources->setLinks =
-            OCCopyLinksResources(href, rt, itf, rel, obs, title, uri, ins, mt);
-    }
-    else
-    {
-        OCLinksPayload *p = payload->collectionResources->setLinks;
-        while (p->next)
-        {
-            p = p->next;
-        }
-        p->next = OCCopyLinksResources(href, rt, itf, rel, obs, title, uri, ins, mt);
-    }
-}
-
 OCResourceCollectionPayload* OCCopyCollectionResource(OCTagsPayload *tags, OCLinksPayload *links)
 {
-    if (!tags || !links)
-    {
-        return NULL;
-    }
-    OCResourceCollectionPayload *pl = (OCResourceCollectionPayload *)OICCalloc(1, sizeof(OCResourceCollectionPayload));
-    if(!pl)
-    {
-        OC_LOG(ERROR, TAG, "Failed allocating memory for the OCResourceCollectionPayload.");
-        return NULL;
-    }
+    OCResourceCollectionPayload *pl =  NULL;
+    VERIFY_PARAM_NON_NULL(TAG, tags, "Invalid param tags");
+    VERIFY_PARAM_NON_NULL(TAG, links, "Invalid param links");
+
+    pl = (OCResourceCollectionPayload *)OICCalloc(1, sizeof(OCResourceCollectionPayload));
+    VERIFY_PARAM_NON_NULL(TAG, pl, "Failed allocating memory for the OCResourceCollectionPayload");
+
     pl->tags = tags;
     pl->setLinks = links;
 
+exit:
     return pl;
 }
 
-OCStackResult OCDiscoveryCollectionPayloadAddResource(OCDiscoveryPayload *payload, OCTagsPayload *tags, OCLinksPayload *links)
-{
-    OCResourceCollectionPayload* res = OCCopyCollectionResource(tags, links);
-    if (res == NULL)
-    {
-        return OC_STACK_NO_MEMORY;
-    }
-    if(!payload->collectionResources)
-    {
-        payload->collectionResources = res;
-    }
-    else
-    {
-        OCResourceCollectionPayload *p = payload->collectionResources;
-        while(p->next)
-        {
-            p = p->next;
-        }
-        p->next = res;
-    }
-    return OC_STACK_OK;
-}
-
 void OCFreeLinksResource(OCLinksPayload *payload)
 {
     if (!payload)
@@ -1048,45 +785,37 @@ void OCFreeCollectionResource(OCResourceCollectionPayload *payload)
     OICFree(payload);
 }
 
-void OCDiscoveryCollectionPayloadDestroy(OCDiscoveryPayload* payload)
-{
-    if(!payload)
-    {
-        return;
-    }
-
-    OCFreeCollectionResource(payload->collectionResources);
-    OICFree(payload);
-}
-
-
 void OCTagsLog(const LogLevel level, const OCTagsPayload *tags)
 {
     if (tags)
     {
         if (tags->n.deviceName)
         {
-            OC_LOG_V(level, TAG, " Device Name : %s ",tags->n.deviceName);
+            OIC_LOG_V(level, TAG, " Device Name : %s ",tags->n.deviceName);
         }
         if (tags->baseURI)
         {
-            OC_LOG_V(level, TAG, " Base URI : %s ",tags->baseURI);
+            OIC_LOG_V(level, TAG, " Base URI : %s ",tags->baseURI);
         }
-        OC_LOG_V(level, TAG, " Device ID : %s ",tags->di.id);
-        OC_LOG_V(level, TAG, " Bitmap : %d ",tags->bitmap);
-        OC_LOG_V(level, TAG, " Port : %d ",tags->port);
-        OC_LOG_V(level, TAG, " Ins : %d ",tags->ins);
-        OC_LOG_V(level, TAG, " Ttl : %d ",tags->ttl);
+        OIC_LOG_V(level, TAG, " Device ID : %s ",tags->di.id);
+        OIC_LOG_V(level, TAG, " Bitmap : %d ",tags->bitmap);
+        OIC_LOG_V(level, TAG, " Port : %d ",tags->port);
+        OIC_LOG_V(level, TAG, " Ins : %d ",tags->ins);
+        OIC_LOG_V(level, TAG, " Ttl : %d ",tags->ttl);
 
         if (tags->rts)
         {
-            OC_LOG_V(level, TAG, " RTS : %s ",tags->rts);
+            OIC_LOG_V(level, TAG, " RTS : %s ",tags->rts);
         }
         if (tags->drel)
         {
-            OC_LOG_V(level, TAG, " DREL : %s ",tags->drel);
+            OIC_LOG_V(level, TAG, " DREL : %s ",tags->drel);
         }
     }
+    else
+    {
+        (void) level;
+    }
 }
 
 void OCLinksLog(const LogLevel level, const OCLinksPayload *links)
@@ -1095,52 +824,56 @@ void OCLinksLog(const LogLevel level, const OCLinksPayload *links)
     {
         if (links->href)
         {
-            OC_LOG_V(level, TAG, " href: %s ",links->href);
+            OIC_LOG_V(level, TAG, " href: %s ",links->href);
         }
-        OC_LOG(level, TAG, " RT: ");
+        OIC_LOG(level, TAG, " RT: ");
         OCStringLL *rt = links->rt;
         while (rt)
         {
             if (rt->value)
             {
-                OC_LOG_V(level, TAG, "   %s", rt->value);
+                OIC_LOG_V(level, TAG, "   %s", rt->value);
             }
             rt = rt->next;
         }
-        OC_LOG(level, TAG, " IF: ");
+        OIC_LOG(level, TAG, " IF: ");
         OCStringLL *itf = links->itf;
         while (itf)
         {
             if (itf->value)
             {
-                OC_LOG_V(level, TAG, "   %s", itf->value);
+                OIC_LOG_V(level, TAG, "   %s", itf->value);
             }
             itf = itf->next;
         }
-        OC_LOG(level, TAG, " MT: ");
+        OIC_LOG(level, TAG, " MT: ");
         OCStringLL *mt = links->mt;
         while (mt)
         {
             if (mt->value)
             {
-                OC_LOG_V(level, TAG, "   %s", mt->value);
+                OIC_LOG_V(level, TAG, "   %s", mt->value);
             }
             mt = mt->next;
         }
-        OC_LOG_V(level, TAG, " INS: %d", links->ins);
-        OC_LOG_V(level, TAG, " OBS: %d", links->obs);
+        OIC_LOG_V(level, TAG, " INS: %d", links->ins);
+        OIC_LOG_V(level, TAG, " OBS: %d", links->obs);
         if (links->rel)
         {
-            OC_LOG_V(level, TAG, " REL: %s", links->rel);
+            OIC_LOG_V(level, TAG, " REL: %s", links->rel);
         }
         if (links->title)
         {
-            OC_LOG_V(level, TAG, " TITLE: %s", links->title);
+            OIC_LOG_V(level, TAG, " TITLE: %s", links->title);
         }
         if (links->uri)
         {
-            OC_LOG_V(level, TAG, " URI: %s", links->uri);
+            OIC_LOG_V(level, TAG, " URI: %s", links->uri);
         }
         links = links->next;
     }
+    if (!links)
+    {
+        (void) level;
+    }
 }
index 7da8c21..7d08f04 100644 (file)
@@ -38,20 +38,24 @@ Unit Test Requirements:
 3. The unit test assumes that a network interface is available
    (e.g. "eth0", "wlan0", etc.)
    If no interface is available, the unit tests will FAIL.
+
 4. To run the unit test, first build the C OCStack.
    At the time of this writing this was done by running
 
-   root/csdk/make deepclean
-   root/csdk/make BUILD=release    *default
-   root/csdk/make BUILD=debug
+   scons -c resource/csdk/
+   scons resource/csdk/ RELEASE=1  //*default
+   scons resource/csdk/ RELEASE=0
 
 5. Next, build the ocstack
-   root/csdk/stack/test/make clean
-   root/csdk/stack/test/make BUILD=release    *default
-   root/csdk/stack/test/make BUILD=debug
+   scons -c resource/csdk/stack/test
+   scons resource/csdk/stack/test RELEASE=1  //*default
+   scons resource/csdk/stack/test RELEASE=0
 
-6. Run the unit test by
-   root/csdk/stack/test/release/stacktests
-   root/csdk/stack/test/debug/stacktests
+6. Export LD_LIBRARY_PATH before running the unit tests.
+   Example:
+   export LD_LIBRARY_PATH=/home/tester/Documents/iotivity/extlibs/gtest/gtest-1.7.0/lib/.libs/
 
+7. Run the unit test by issuing the following command from root 'iotivity' folder
+   ./out/<TARGET_OS>/<TARGET_ARCH>/<release/debug>/resource/csdk/stack/test
+   Example: ./out/linux/x86/release/resource/csdk/stack/test/stacktests
 
index 6e58afc..973edbf 100644 (file)
@@ -50,17 +50,17 @@ static OCUri SERVICE_URI = "coap://127.0.0.1:5683/";
 
 void EXPECT_EQ(int a, int b)  {
   if (a == b) {
-    OC_LOG(INFO, TAG, "PASS");
+    OIC_LOG(INFO, TAG, "PASS");
   } else {
-    OC_LOG(ERROR, TAG, "**FAIL**");
+    OIC_LOG(ERROR, TAG, "**FAIL**");
   }
 }
 
 void EXPECT_STREQ(const char *a, const char *b)  {
   if (strcmp(a, b) == 0) {
-    OC_LOG(INFO, TAG, "PASS");
+    OIC_LOG(INFO, TAG, "PASS");
   } else {
-    OC_LOG(ERROR, TAG, "**FAIL**");
+    OIC_LOG(ERROR, TAG, "**FAIL**");
   }
 }
 //-----------------------------------------------------------------------------
@@ -68,11 +68,11 @@ void EXPECT_STREQ(const char *a, const char *b)  {
 //-----------------------------------------------------------------------------
 
 extern "C" void asyncDoResourcesCallback(OCStackResult result, OCRepresentationHandle representation) {
-    OC_LOG(INFO, TAG, "Entering asyncDoResourcesCallback");
+    OIC_LOG(INFO, TAG, "Entering asyncDoResourcesCallback");
 
     EXPECT_EQ(OC_STACK_OK, result);
     OCResource *resource = (OCResource *)representation;
-    OC_LOG_V(INFO, TAG, "URI = %s", resource->uri);
+    OIC_LOG_V(INFO, TAG, "URI = %s", resource->uri);
     EXPECT_STREQ(SERVICE_URI, resource->uri);
 }
 
index dec98ac..72e9ce9 100644 (file)
@@ -45,17 +45,17 @@ PROGMEM const char multiLineMsg[] = "this is a DEBUG message\non multiple\nlines
 
 void EXPECT_EQ(int a, int b)  {
   if (a == b) {
-    OC_LOG(INFO, TAG, ("PASS"));
+    OIC_LOG(INFO, TAG, ("PASS"));
   } else {
-    OC_LOG(ERROR, TAG, ("FAIL"));
+    OIC_LOG(ERROR, TAG, ("FAIL"));
   }
 }
 
 void EXPECT_STREQ(const char *a, const char *b)  {
   if (strcmp(a, b) == 0) {
-    OC_LOG(INFO, TAG, ("PASS"));
+    OIC_LOG(INFO, TAG, ("PASS"));
   } else {
-    OC_LOG(ERROR, TAG, ("FAIL"));
+    OIC_LOG(ERROR, TAG, ("FAIL"));
   }
 }
 //-----------------------------------------------------------------------------
@@ -63,31 +63,31 @@ void EXPECT_STREQ(const char *a, const char *b)  {
 //-----------------------------------------------------------------------------
 #if 0  // Turn off logger tests
 void test0() {
-    OC_LOG(INFO, tag, msg);
+    OIC_LOG(INFO, tag, msg);
 }
 
 void test1() {
-    OC_LOG(INFO, 0, msg);
+    OIC_LOG(INFO, 0, msg);
 }
 
 void test2() {
-    OC_LOG(INFO, tag, 0);
+    OIC_LOG(INFO, tag, 0);
 }
 
 void test3() {
-    OC_LOG(INFO, 0, 0);
+    OIC_LOG(INFO, 0, 0);
 }
 
 void test4() {
-    OC_LOG(DEBUG, tag, debugMsg);
-    OC_LOG(INFO, tag, infoMsg);
-    OC_LOG(WARNING, tag, warningMsg);
-    OC_LOG(ERROR, tag, errorMsg);
-    OC_LOG(FATAL, tag, fatalMsg);
+    OIC_LOG(DEBUG, tag, debugMsg);
+    OIC_LOG(INFO, tag, infoMsg);
+    OIC_LOG(WARNING, tag, warningMsg);
+    OIC_LOG(ERROR, tag, errorMsg);
+    OIC_LOG(FATAL, tag, fatalMsg);
 }
 
 void test5() {
-    OC_LOG(DEBUG, tag, multiLineMsg);
+    OIC_LOG(DEBUG, tag, multiLineMsg);
 }
 
 
@@ -97,69 +97,69 @@ void test6() {
     for (int i = 0; i < (int)(sizeof buffer); i++) {
         buffer[i] = i;
     }
-    OC_LOG_BUFFER(DEBUG, tag, buffer, sizeof buffer);
+    OIC_LOG_BUFFER(DEBUG, tag, buffer, sizeof buffer);
 
     // Log buffer, 128 bytes is a good boundary (8 rows of 16 values)
     uint8_t buffer1[128];
     for (int i = 0; i < (int)(sizeof buffer1); i++) {
         buffer1[i] = i;
     }
-    OC_LOG_BUFFER(DEBUG, tag, buffer1, sizeof buffer1);
+    OIC_LOG_BUFFER(DEBUG, tag, buffer1, sizeof buffer1);
 
     // 1 below 128 byte boundary
     uint8_t buffer2[127];
     for (int i = 0; i < (int)(sizeof buffer2); i++) {
         buffer2[i] = i;
     }
-    OC_LOG_BUFFER(DEBUG, tag, buffer2, sizeof buffer2);
+    OIC_LOG_BUFFER(DEBUG, tag, buffer2, sizeof buffer2);
 
     // 1 above 128 byte boundary
     uint8_t buffer3[129];
     for (int i = 0; i < (int)(sizeof buffer3); i++) {
         buffer3[i] = i;
     }
-    OC_LOG_BUFFER(DEBUG, tag, buffer3, sizeof buffer3);
+    OIC_LOG_BUFFER(DEBUG, tag, buffer3, sizeof buffer3);
 }
 #endif
 
 extern "C" void asyncDoResourcesCallback(OCStackResult result, OCRepresentationHandle representation) {
-    OC_LOG(INFO, TAG, ("Entering asyncDoResourcesCallback"));
+    OIC_LOG(INFO, TAG, ("Entering asyncDoResourcesCallback"));
 
     EXPECT_EQ(OC_STACK_OK, result);
     OCResource *resource = (OCResource *)representation;
-    OC_LOG_V(INFO, TAG, "URI = %s", resource->uri);
+    OIC_LOG_V(INFO, TAG, "URI = %s", resource->uri);
     EXPECT_STREQ(SERVICE_URI, resource->uri);
 }
 
 void test0() {
-    OC_LOG(INFO, TAG, ("test0"));
+    OIC_LOG(INFO, TAG, ("test0"));
     EXPECT_EQ(OC_STACK_OK, OCInit(0, 5683, OC_SERVER));
 }
 
 void test1() {
-    OC_LOG(INFO, TAG, ("test1"));
+    OIC_LOG(INFO, TAG, ("test1"));
     EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 0, OC_SERVER));
 }
 
 void test2() {
-    OC_LOG(INFO, TAG, ("test2"));
+    OIC_LOG(INFO, TAG, ("test2"));
     EXPECT_EQ(OC_STACK_OK, OCInit(0, 0, OC_SERVER));
 }
 
 void test3() {
-    OC_LOG(INFO, TAG, ("test3"));
+    OIC_LOG(INFO, TAG, ("test3"));
     EXPECT_EQ(OC_STACK_ERROR, OCInit(0, 0, (OCMode)10));
 }
 
 void test4() {
-    OC_LOG(INFO, TAG, ("test4"));
+    OIC_LOG(INFO, TAG, ("test4"));
     EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT));
     EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_SERVER));
     EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT_SERVER));
 }
 
 void test5() {
-    OC_LOG(INFO, TAG, ("test5"));
+    OIC_LOG(INFO, TAG, ("test5"));
     EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT));
     EXPECT_EQ(OC_STACK_OK, OCDoResource(OC_REST_GET, OC_EXPLICIT_DEVICE_DISCOVERY_URI, 0, 0, asyncDoResourcesCallback), NULL, 0);
     EXPECT_EQ(OC_STACK_OK, OCUpdateResources(SERVICE_URI));
@@ -167,14 +167,14 @@ void test5() {
 }
 
 void test6() {
-    OC_LOG(INFO, TAG, ("test6"));
+    OIC_LOG(INFO, TAG, ("test6"));
     EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT));
     EXPECT_EQ(OC_STACK_OK, OCStop());
     EXPECT_EQ(OC_STACK_ERROR, OCStop());
 }
 
 void test7() {
-    OC_LOG(INFO, TAG, ("test7"));
+    OIC_LOG(INFO, TAG, ("test7"));
     EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT));
     EXPECT_EQ(OC_STACK_OK, OCDoResource(OC_REST_GET, OC_EXPLICIT_DEVICE_DISCOVERY_URI, 0, 0, asyncDoResourcesCallback), NULL, 0);
     EXPECT_EQ(OC_STACK_INVALID_URI, OCUpdateResources(0));
@@ -187,7 +187,7 @@ void test7() {
 void setup()
 {
     // Add your initialization code here
-    OC_LOG_INIT();
+    OIC_LOG_INIT();
 
     test0();
     delay(2000);
index 5ced8c9..6f9f30b 100644 (file)
@@ -9,8 +9,8 @@ static uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0F, 0x2B, 0x72 };
 #define TAG ("ocserver")
 
 void ocInitialize () {
-    OC_LOG(DEBUG, TAG, ("IP addr is:"));
-    OC_LOG_BUFFER(INFO, TAG, (uint8_t*)ipAddr, sizeof(ipAddr));
+    OIC_LOG(DEBUG, TAG, ("IP addr is:"));
+    OIC_LOG_BUFFER(INFO, TAG, (uint8_t*)ipAddr, sizeof(ipAddr));
     delay(2000);
     OCInit (NULL, 0, OC_SERVER);
 }
index fca6015..40132fd 100644 (file)
@@ -41,8 +41,8 @@ void handleSigInt(int signum) {
 // This is a function called back when a device is discovered
 OCStackApplicationResult applicationDiscoverCB(
         OCClientResponse * clientResponse) {
-    OC_LOG(INFO, TAG, "Entering applicationDiscoverCB (Application Layer CB)");
-    OC_LOG_V(INFO, TAG, "Device =============> Discovered %s @ %s:%d",
+    OIC_LOG(INFO, TAG, "Entering applicationDiscoverCB (Application Layer CB)");
+    OIC_LOG_V(INFO, TAG, "Device =============> Discovered %s @ %s:%d",
                                     clientResponse->resJSONPayload,
                                     clientResponse->devAddr.addr,
                                     clientResponse->devAddr.port);
@@ -51,11 +51,11 @@ OCStackApplicationResult applicationDiscoverCB(
 }
 
 int main() {
-    OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
+    OIC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
 
     /* Initialize OCStack*/
     if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK) {
-        OC_LOG(ERROR, TAG, "OCStack init error");
+        OIC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
 
@@ -64,25 +64,27 @@ int main() {
     strcpy(szQueryUri, OC_EXPLICIT_DEVICE_DISCOVERY_URI);
     if (OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS,
             0, 0, 0) != OC_STACK_OK) {
-        OC_LOG(ERROR, TAG, "OCStack resource error");
+        OIC_LOG(ERROR, TAG, "OCStack resource error");
         return 0;
     }
 
     // Break from loop with Ctrl+C
-    OC_LOG(INFO, TAG, "Entering occlient main loop...");
+    OIC_LOG(INFO, TAG, "Entering occlient main loop...");
     signal(SIGINT, handleSigInt);
     while (!gQuitFlag) {
 
         if (OCProcess() != OC_STACK_OK) {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             return 0;
         }
 
         sleep(1);
-    }OC_LOG(INFO, TAG, "Exiting occlient main loop...");
+    }
+
+    OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
 
     if (OCStop() != OC_STACK_OK) {
-        OC_LOG(ERROR, TAG, "OCStack stop error");
+        OIC_LOG(ERROR, TAG, "OCStack stop error");
     }
 
     return 0;
index 239f8a1..c587a0b 100644 (file)
@@ -48,9 +48,9 @@ void handleSigInt(int signum) {
 }
 
 int main() {
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
+    OIC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK) {
-        OC_LOG(ERROR, TAG, "OCStack init error");
+        OIC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
 
@@ -59,26 +59,26 @@ int main() {
      */
     if(createLightResource() != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack cannot create resource...");
+        OIC_LOG(ERROR, TAG, "OCStack cannot create resource...");
     }
 
     // Break from loop with Ctrl-C
-    OC_LOG(INFO, TAG, "Entering ocserver main loop...");
+    OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
     signal(SIGINT, handleSigInt);
     while (!gQuitFlag) {
 
         if (OCProcess() != OC_STACK_OK) {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             return 0;
         }
 
         sleep(1);
     }
 
-    OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
+    OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
 
     if (OCStop() != OC_STACK_OK) {
-        OC_LOG(ERROR, TAG, "OCStack process error");
+        OIC_LOG(ERROR, TAG, "OCStack process error");
     }
 
     return 0;
index c928982..037edcd 100644 (file)
@@ -61,6 +61,9 @@ char gDeviceUUID[] = "myDeviceUUID";
 char gManufacturerName[] = "myName";
 char gTooLongManufacturerName[] = "extremelylongmanufacturername";
 char gManufacturerUrl[] = "www.foooooooooooooooo.baaaaaaaaaaaaar";
+static OCPrm_t pmSel;
+static char pinNumber;
+static OCDPDev_t peer;
 
 std::chrono::seconds const SHORT_TEST_TIMEOUT = std::chrono::seconds(5);
 
@@ -70,14 +73,54 @@ std::chrono::seconds const SHORT_TEST_TIMEOUT = std::chrono::seconds(5);
 extern "C"  OCStackApplicationResult asyncDoResourcesCallback(void* ctx,
         OCDoHandle /*handle*/, OCClientResponse * clientResponse)
 {
-    OC_LOG(INFO, TAG, "Entering asyncDoResourcesCallback");
+    OIC_LOG(INFO, TAG, "Entering asyncDoResourcesCallback");
 
     EXPECT_EQ(OC_STACK_OK, clientResponse->result);
 
     if(ctx == (void*)DEFAULT_CONTEXT_VALUE) {
-        OC_LOG_V(INFO, TAG, "Callback Context recvd successfully");
+        OIC_LOG_V(INFO, TAG, "Callback Context recvd successfully");
     }
-    OC_LOG_V(INFO, TAG, "result = %d", clientResponse->result);
+    OIC_LOG_V(INFO, TAG, "result = %d", clientResponse->result);
+
+    return OC_STACK_KEEP_TRANSACTION;
+}
+
+static void resultCallback(OCDPDev_t *UNUSED1, OCStackResult UNUSED2)
+{
+    (void) (UNUSED1);
+    (void) (UNUSED2);
+}
+
+extern "C" OCStackApplicationResult discoveryCallback(void* ctx,
+        OCDoHandle /*handle*/, OCClientResponse * clientResponse)
+{
+    OIC_LOG(INFO, TAG, "Entering asyncDoResourcesCallback");
+
+    EXPECT_EQ(OC_STACK_OK, clientResponse->result);
+
+    if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
+    {
+        OIC_LOG_V(INFO, TAG, "Callback Context recvd successfully");
+    }
+
+    OIC_LOG_V(INFO, TAG, "result = %d", clientResponse->result);
+
+    OCDiscoveryPayload *discoveryPayload = ((OCDiscoveryPayload *) clientResponse->payload);
+    EXPECT_TRUE(discoveryPayload != NULL);
+    OCResourcePayload *res = discoveryPayload->resources;
+    size_t count = 0;
+    for (OCResourcePayload *res1 = discoveryPayload->resources; res1; res1 = res1->next)
+    {
+        count++;
+    }
+    EXPECT_EQ(3, count);
+    EXPECT_EQ("/a/led1", res->uri);
+    res = res->next;
+    EXPECT_EQ("/a/led2", res->uri);
+    res = res->next;
+    EXPECT_EQ("/a/led3", res->uri);
+    res = res->next;
+    EXPECT_TRUE(res == NULL);
 
     return OC_STACK_KEEP_TRANSACTION;
 }
@@ -89,7 +132,7 @@ OCEntityHandlerResult entityHandler(OCEntityHandlerFlag /*flag*/,
         OCEntityHandlerRequest * /*entityHandlerRequest*/,
         void* /*callbackParam*/)
 {
-    OC_LOG(INFO, TAG, "Entering entityHandler");
+    OIC_LOG(INFO, TAG, "Entering entityHandler");
 
     return OC_EH_OK;
 }
@@ -99,10 +142,10 @@ OCEntityHandlerResult entityHandler(OCEntityHandlerFlag /*flag*/,
 //-----------------------------------------------------------------------------
 void InitStack(OCMode mode)
 {
-    OC_LOG(INFO, TAG, "Entering InitStack");
+    OIC_LOG(INFO, TAG, "Entering InitStack");
 
     EXPECT_EQ(OC_STACK_OK, OCInit(NULL, 0, mode));
-    OC_LOG(INFO, TAG, "Leaving InitStack");
+    OIC_LOG(INFO, TAG, "Leaving InitStack");
 }
 
 uint8_t InitNumExpectedResources()
@@ -204,6 +247,21 @@ TEST(StackStart, SetPlatformInfoValid)
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
+TEST(StackStart, SetPlatformInfoWithClientMode)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT));
+
+    OCPlatformInfo info =
+    {
+        gDeviceUUID,
+        gManufacturerName,
+        0, 0, 0, 0, 0, 0, 0, 0, 0
+    };
+    EXPECT_EQ(OC_STACK_ERROR, OCSetPlatformInfo(info));
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
 TEST(StackStart, SetPlatformInfoWithNoPlatformID)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
@@ -289,7 +347,7 @@ TEST(StackDiscovery, DISABLED_DoResourceDeviceDiscovery)
     OCCallbackData cbData;
     OCDoHandle handle;
 
-    OC_LOG(INFO, TAG, "Starting DoResourceDeviceDiscovery test ");
+    OIC_LOG(INFO, TAG, "Starting DoResourceDeviceDiscovery test ");
     InitStack(OC_CLIENT);
 
     /* Start a discovery query*/
@@ -331,7 +389,7 @@ TEST(StackResource, DISABLED_UpdateResourceNullURI)
     OCCallbackData cbData;
     OCDoHandle handle;
 
-    OC_LOG(INFO, TAG, "Starting UpdateResourceNullURI test");
+    OIC_LOG(INFO, TAG, "Starting UpdateResourceNullURI test");
     InitStack(OC_CLIENT);
 
     /* Start a discovery query*/
@@ -356,7 +414,7 @@ TEST(StackResource, DISABLED_UpdateResourceNullURI)
 TEST(StackResource, CreateResourceBadParams)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting CreateResourceBadParams test");
+    OIC_LOG(INFO, TAG, "Starting CreateResourceBadParams test");
     InitStack(OC_SERVER);
 
     OCResourceHandle handle;
@@ -392,7 +450,7 @@ TEST(StackResource, CreateResourceBadParams)
 TEST(StackResource, CreateResourceBadUri)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting CreateResourceBadUri test");
+    OIC_LOG(INFO, TAG, "Starting CreateResourceBadUri test");
     InitStack(OC_SERVER);
 
     const char *uri65 = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKL";
@@ -429,7 +487,7 @@ TEST(StackResource, CreateResourceBadUri)
 TEST(StackResource, CreateResourceSuccess)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting CreateResourceSuccess test");
+    OIC_LOG(INFO, TAG, "Starting CreateResourceSuccess test");
     InitStack(OC_SERVER);
 
     OCResourceHandle handle;
@@ -449,7 +507,7 @@ TEST(StackResource, CreateResourceSuccess)
 TEST(StackResource, CreateResourceSuccessWithResourcePolicyPropNone)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting CreateResourceSuccessWithResourcePolicyPropNone test");
+    OIC_LOG(INFO, TAG, "Starting CreateResourceSuccessWithResourcePolicyPropNone test");
     InitStack(OC_SERVER);
 
     OCResourceHandle handle;
@@ -471,7 +529,7 @@ TEST(StackResource, CreateResourceSuccessWithResourcePolicyPropNone)
 TEST(StackResource, CreateResourceWithClientStackMode)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting CreateResourceSuccess test");
+    OIC_LOG(INFO, TAG, "Starting CreateResourceSuccess test");
     InitStack(OC_CLIENT);
 
     OCResourceHandle handle;
@@ -489,7 +547,7 @@ TEST(StackResource, CreateResourceWithClientStackMode)
 TEST(StackResource, CreateResourceFailDuplicateUri)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting CreateResourceFailDuplicateUri test");
+    OIC_LOG(INFO, TAG, "Starting CreateResourceFailDuplicateUri test");
     InitStack(OC_SERVER);
 
     OCResourceHandle handle;
@@ -517,7 +575,7 @@ TEST(StackResource, CreateResourceFailDuplicateUri)
 TEST(StackResource, CreateResourceMultipleResources)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting CreateResourceMultipleResources test");
+    OIC_LOG(INFO, TAG, "Starting CreateResourceMultipleResources test");
     InitStack(OC_SERVER);
 
     OCResourceHandle handle1;
@@ -561,7 +619,7 @@ TEST(StackResource, CreateResourceMultipleResources)
 TEST(StackResource, CreateResourceBadResoureType)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting CreateResourceBadResoureType test");
+    OIC_LOG(INFO, TAG, "Starting CreateResourceBadResoureType test");
     InitStack(OC_SERVER);
 
     OCResourceHandle handle;
@@ -588,7 +646,7 @@ TEST(StackResource, CreateResourceBadResoureType)
 TEST(StackResource, CreateResourceGoodResourceType)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting CreateResourceGoodResourceType test");
+    OIC_LOG(INFO, TAG, "Starting CreateResourceGoodResourceType test");
     InitStack(OC_SERVER);
 
     OCResourceHandle handle;
@@ -606,7 +664,7 @@ TEST(StackResource, CreateResourceGoodResourceType)
 TEST(StackResource, ResourceTypeName)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting ResourceTypeName test");
+    OIC_LOG(INFO, TAG, "Starting ResourceTypeName test");
     InitStack(OC_SERVER);
 
     OCResourceHandle handle;
@@ -637,7 +695,7 @@ TEST(StackResource, ResourceTypeName)
 TEST(StackResource, ResourceTypeAttrRepresentation)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting ResourceTypeAttrRepresentation test");
+    OIC_LOG(INFO, TAG, "Starting ResourceTypeAttrRepresentation test");
     InitStack(OC_SERVER);
 
     OCResourceHandle handle;
@@ -659,7 +717,7 @@ TEST(StackResource, ResourceTypeAttrRepresentation)
 TEST(StackResource, ResourceTypeInterface)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting ResourceTypeInterface test");
+    OIC_LOG(INFO, TAG, "Starting ResourceTypeInterface test");
     InitStack(OC_SERVER);
 
     OCResourceHandle handle;
@@ -673,12 +731,14 @@ TEST(StackResource, ResourceTypeInterface)
 
     uint8_t numResourceInterfaces;
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces));
-    EXPECT_EQ(1, numResourceInterfaces);
-    const char *resourceInterfaceName = OCGetResourceInterfaceName(handle, 0);
+    EXPECT_EQ(2, numResourceInterfaces);
+    const char *resourceInterfaceName1 = OCGetResourceInterfaceName(handle, 0);
+    EXPECT_STREQ(OC_RSRVD_INTERFACE_DEFAULT, resourceInterfaceName1);
+    const char *resourceInterfaceName = OCGetResourceInterfaceName(handle, 1);
     EXPECT_STREQ("core.rw", resourceInterfaceName);
 
     // try getting resource interface names with an invalid index
-    resourceInterfaceName = OCGetResourceInterfaceName(handle, 1);
+    resourceInterfaceName = OCGetResourceInterfaceName(handle, 2);
     EXPECT_STREQ(NULL, resourceInterfaceName);
     // try getting resource interface names with an invalid index
     resourceInterfaceName = OCGetResourceInterfaceName(handle, 10);
@@ -691,7 +751,7 @@ TEST(StackResource, ResourceDefaultInterfaceAlwaysFirst)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
 
-    OC_LOG(INFO, TAG, "Starting ResourceDefaultInterfaceAlwaysFirst test");
+    OIC_LOG(INFO, TAG, "Starting ResourceDefaultInterfaceAlwaysFirst test");
 
     InitStack(OC_SERVER);
 
@@ -722,7 +782,7 @@ TEST(StackResource, ResourceDuplicateDefaultInterfaces)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
 
-    OC_LOG(INFO, TAG, "Starting ResourceDuplicateDefaultInterfaces test");
+    OIC_LOG(INFO, TAG, "Starting ResourceDuplicateDefaultInterfaces test");
 
     InitStack(OC_SERVER);
 
@@ -754,7 +814,7 @@ TEST(StackResource, ResourceDuplicateNonDefaultInterfaces)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
 
-    OC_LOG(INFO, TAG, "Starting ResourceDuplicateInterfaces test");
+    OIC_LOG(INFO, TAG, "Starting ResourceDuplicateInterfaces test");
 
     InitStack(OC_SERVER);
 
@@ -774,7 +834,7 @@ TEST(StackResource, ResourceDuplicateNonDefaultInterfaces)
 
     uint8_t numResourceInterfaces;
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces));
-    EXPECT_EQ(1, numResourceInterfaces);
+    EXPECT_EQ(2, numResourceInterfaces);
 
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
@@ -782,7 +842,7 @@ TEST(StackResource, ResourceDuplicateNonDefaultInterfaces)
 TEST(StackResource, ResourceTypeInterfaceMethods)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting ResourceTypeInterfaceMethods test");
+    OIC_LOG(INFO, TAG, "Starting ResourceTypeInterfaceMethods test");
     InitStack(OC_SERVER);
 
     OCResourceHandle handle;
@@ -796,7 +856,7 @@ TEST(StackResource, ResourceTypeInterfaceMethods)
 
     uint8_t numResourceInterfaces;
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces));
-    EXPECT_EQ(1, numResourceInterfaces);
+    EXPECT_EQ(2, numResourceInterfaces);
 
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
@@ -804,7 +864,7 @@ TEST(StackResource, ResourceTypeInterfaceMethods)
 TEST(StackResource, GetResourceProperties)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting GetResourceProperties test");
+    OIC_LOG(INFO, TAG, "Starting GetResourceProperties test");
     InitStack(OC_SERVER);
 
     OCResourceHandle handle;
@@ -825,7 +885,7 @@ TEST(StackResource, GetResourceProperties)
 TEST(StackResource, StackTestResourceDiscoverOneResourceBad)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting StackTestResourceDiscoverOneResourceBad test");
+    OIC_LOG(INFO, TAG, "Starting StackTestResourceDiscoverOneResourceBad test");
     InitStack(OC_SERVER);
     uint8_t numResources = 0;
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
@@ -854,7 +914,7 @@ TEST(StackResource, StackTestResourceDiscoverOneResourceBad)
 TEST(StackResource, StackTestResourceDiscoverOneResource)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting StackTestResourceDiscoverOneResource test");
+    OIC_LOG(INFO, TAG, "Starting StackTestResourceDiscoverOneResource test");
     InitStack(OC_SERVER);
 
     OCResourceHandle handle;
@@ -877,7 +937,7 @@ TEST(StackResource, StackTestResourceDiscoverOneResource)
 TEST(StackResource, StackTestResourceDiscoverManyResources)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting StackTestResourceDiscoverManyResources test");
+    OIC_LOG(INFO, TAG, "Starting StackTestResourceDiscoverManyResources test");
     InitStack(OC_SERVER);
 
     OCResourceHandle handle1;
@@ -942,7 +1002,7 @@ TEST(StackResource, StackTestResourceDiscoverManyResources)
 TEST(StackBind, BindResourceTypeNameBad)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting BindResourceTypeNameBad test");
+    OIC_LOG(INFO, TAG, "Starting BindResourceTypeNameBad test");
     InitStack(OC_SERVER);
 
     OCResourceHandle handle;
@@ -968,7 +1028,7 @@ TEST(StackBind, BindResourceTypeNameBad)
 TEST(StackBind, BindResourceTypeNameGood)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting BindResourceTypeNameGood test");
+    OIC_LOG(INFO, TAG, "Starting BindResourceTypeNameGood test");
     InitStack(OC_SERVER);
 
     OCResourceHandle handle;
@@ -1004,7 +1064,7 @@ TEST(StackBind, BindResourceTypeNameGood)
 TEST(StackBind, BindResourceTypeAttribRepGood)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting BindResourceTypeAttribRepGood test");
+    OIC_LOG(INFO, TAG, "Starting BindResourceTypeAttribRepGood test");
     InitStack(OC_SERVER);
 
     OCResourceHandle handle;
@@ -1035,7 +1095,7 @@ TEST(StackBind, BindResourceTypeAttribRepGood)
 TEST(StackBind, BindResourceInterfaceNameBad)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting BindResourceInterfaceNameBad test");
+    OIC_LOG(INFO, TAG, "Starting BindResourceInterfaceNameBad test");
     InitStack(OC_SERVER);
 
     OCResourceHandle handle;
@@ -1049,8 +1109,8 @@ TEST(StackBind, BindResourceInterfaceNameBad)
 
     uint8_t numResourceInterfaces;
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces));
-    EXPECT_EQ(1, numResourceInterfaces);
-    const char *resourceInterfaceName = OCGetResourceInterfaceName(handle, 0);
+    EXPECT_EQ(2, numResourceInterfaces);
+    const char *resourceInterfaceName = OCGetResourceInterfaceName(handle, 1);
     EXPECT_STREQ("core.rw", resourceInterfaceName);
 
     EXPECT_EQ(OC_STACK_INVALID_PARAM, OCBindResourceInterfaceToResource(handle, NULL));
@@ -1061,7 +1121,7 @@ TEST(StackBind, BindResourceInterfaceNameBad)
 TEST(StackBind, BindResourceInterfaceNameGood)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting BindResourceInterfaceNameGood test");
+    OIC_LOG(INFO, TAG, "Starting BindResourceInterfaceNameGood test");
     InitStack(OC_SERVER);
 
     OCResourceHandle handle;
@@ -1075,15 +1135,15 @@ TEST(StackBind, BindResourceInterfaceNameGood)
 
     uint8_t numResourceInterfaces;
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces));
-    EXPECT_EQ(1, numResourceInterfaces);
-    const char *resourceInterfaceName = OCGetResourceInterfaceName(handle, 0);
+    EXPECT_EQ(2, numResourceInterfaces);
+    const char *resourceInterfaceName = OCGetResourceInterfaceName(handle, 1);
     EXPECT_STREQ("core.rw", resourceInterfaceName);
 
     EXPECT_EQ(OC_STACK_OK, OCBindResourceInterfaceToResource(handle, "core.r"));
 
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces));
-    EXPECT_EQ(2, numResourceInterfaces);
-    resourceInterfaceName = OCGetResourceInterfaceName(handle, 1);
+    EXPECT_EQ(3, numResourceInterfaces);
+    resourceInterfaceName = OCGetResourceInterfaceName(handle, 2);
     EXPECT_STREQ("core.r", resourceInterfaceName);
 
     EXPECT_EQ(OC_STACK_OK, OCStop());
@@ -1092,7 +1152,7 @@ TEST(StackBind, BindResourceInterfaceNameGood)
 TEST(StackBind, BindResourceInterfaceMethodsBad)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting BindResourceInterfaceMethodsBad test");
+    OIC_LOG(INFO, TAG, "Starting BindResourceInterfaceMethodsBad test");
     InitStack(OC_SERVER);
 
     OCResourceHandle handle;
@@ -1106,7 +1166,7 @@ TEST(StackBind, BindResourceInterfaceMethodsBad)
 
     uint8_t numResourceInterfaces;
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces));
-    EXPECT_EQ(1, numResourceInterfaces);
+    EXPECT_EQ(2, numResourceInterfaces);
 
     EXPECT_EQ(OC_STACK_INVALID_PARAM, OCBindResourceInterfaceToResource(handle, 0));
 
@@ -1116,7 +1176,7 @@ TEST(StackBind, BindResourceInterfaceMethodsBad)
 TEST(StackBind, BindResourceInterfaceMethodsGood)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting BindResourceInterfaceMethodsGood test");
+    OIC_LOG(INFO, TAG, "Starting BindResourceInterfaceMethodsGood test");
     InitStack(OC_SERVER);
 
     OCResourceHandle handle;
@@ -1130,12 +1190,12 @@ TEST(StackBind, BindResourceInterfaceMethodsGood)
 
     uint8_t numResourceInterfaces;
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces));
-    EXPECT_EQ(1, numResourceInterfaces);
+    EXPECT_EQ(2, numResourceInterfaces);
 
     EXPECT_EQ(OC_STACK_OK, OCBindResourceInterfaceToResource(handle, "core.r"));
 
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces));
-    EXPECT_EQ(2, numResourceInterfaces);
+    EXPECT_EQ(3, numResourceInterfaces);
 
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
@@ -1143,7 +1203,7 @@ TEST(StackBind, BindResourceInterfaceMethodsGood)
 TEST(StackBind, BindContainedResourceBad)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting BindContainedResourceBad test");
+    OIC_LOG(INFO, TAG, "Starting BindContainedResourceBad test");
     InitStack(OC_SERVER);
 
     OCResourceHandle containerHandle;
@@ -1174,7 +1234,7 @@ TEST(StackBind, BindContainedResourceBad)
 TEST(StackBind, BindContainedResourceGood)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting BindContainedResourceGood test");
+    OIC_LOG(INFO, TAG, "Starting BindContainedResourceGood test");
     InitStack(OC_SERVER);
 
     uint8_t numResources = 0;
@@ -1265,15 +1325,14 @@ TEST(StackBind, BindContainedResourceGood)
     EXPECT_EQ(OC_STACK_OK, OCBindResource(containerHandle, handle2));
     EXPECT_EQ(OC_STACK_OK, OCBindResource(containerHandle, handle3));
     EXPECT_EQ(OC_STACK_OK, OCBindResource(containerHandle, handle4));
-    EXPECT_EQ(OC_STACK_ERROR, OCBindResource(containerHandle, handle5));
+    EXPECT_EQ(OC_STACK_OK, OCBindResource(containerHandle, handle5));
 
     EXPECT_EQ(handle0, OCGetResourceHandleFromCollection(containerHandle, 0));
     EXPECT_EQ(handle1, OCGetResourceHandleFromCollection(containerHandle, 1));
     EXPECT_EQ(handle2, OCGetResourceHandleFromCollection(containerHandle, 2));
     EXPECT_EQ(handle3, OCGetResourceHandleFromCollection(containerHandle, 3));
     EXPECT_EQ(handle4, OCGetResourceHandleFromCollection(containerHandle, 4));
-
-    EXPECT_EQ(NULL, OCGetResourceHandleFromCollection(containerHandle, 5));
+    EXPECT_EQ(handle5, OCGetResourceHandleFromCollection(containerHandle, 5));
 
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
@@ -1282,7 +1341,7 @@ TEST(StackBind, BindContainedResourceGood)
 TEST(StackBind, BindEntityHandlerBad)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting BindEntityHandlerBad test");
+    OIC_LOG(INFO, TAG, "Starting BindEntityHandlerBad test");
     InitStack(OC_SERVER);
 
     OCResourceHandle handle;
@@ -1302,7 +1361,7 @@ TEST(StackBind, BindEntityHandlerBad)
 TEST(StackBind, BindEntityHandlerGood)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting BindEntityHandlerGood test");
+    OIC_LOG(INFO, TAG, "Starting BindEntityHandlerGood test");
     InitStack(OC_SERVER);
 
     OCResourceHandle handle;
@@ -1326,7 +1385,7 @@ TEST(StackBind, BindEntityHandlerGood)
 TEST(StackResourceAccess, GetResourceByIndex)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting GetResourceByIndex test");
+    OIC_LOG(INFO, TAG, "Starting GetResourceByIndex test");
     InitStack(OC_SERVER);
 
     uint8_t numResources = 0;
@@ -1426,7 +1485,7 @@ TEST(StackResourceAccess, GetResourceByIndex)
 TEST(StackResourceAccess, DeleteHeadResource)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting DeleteHeadResource test");
+    OIC_LOG(INFO, TAG, "Starting DeleteHeadResource test");
     InitStack(OC_SERVER);
 
     uint8_t numResources = 0;
@@ -1455,7 +1514,7 @@ TEST(StackResourceAccess, DeleteHeadResource)
 TEST(StackResourceAccess, DeleteHeadResource2)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting DeleteHeadResource2 test");
+    OIC_LOG(INFO, TAG, "Starting DeleteHeadResource2 test");
     InitStack(OC_SERVER);
 
     uint8_t numResources = 0;
@@ -1497,7 +1556,7 @@ TEST(StackResourceAccess, DeleteHeadResource2)
 TEST(StackResourceAccess, DeleteLastResource)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting DeleteLastResource test");
+    OIC_LOG(INFO, TAG, "Starting DeleteLastResource test");
     InitStack(OC_SERVER);
 
     uint8_t numResources = 0;
@@ -1550,7 +1609,7 @@ TEST(StackResourceAccess, DeleteLastResource)
 TEST(StackResourceAccess, DeleteMiddleResource)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
-    OC_LOG(INFO, TAG, "Starting DeleteMiddleResource test");
+    OIC_LOG(INFO, TAG, "Starting DeleteMiddleResource test");
     InitStack(OC_SERVER);
 
     uint8_t numResources = 0;
@@ -1602,8 +1661,8 @@ TEST(StackResourceAccess, DeleteMiddleResource)
     // Make sure the resource elements are still correct
     uint8_t numResourceInterfaces;
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle2, &numResourceInterfaces));
-    EXPECT_EQ(1, numResourceInterfaces);
-    const char *resourceInterfaceName = OCGetResourceInterfaceName(handle2, 0);
+    EXPECT_EQ(2, numResourceInterfaces);
+    const char *resourceInterfaceName = OCGetResourceInterfaceName(handle2, 1);
     EXPECT_STREQ("core.rw", resourceInterfaceName);
 
     EXPECT_EQ(OC_STACK_OK, OCStop());
@@ -1618,3 +1677,71 @@ TEST(PODTests, OCCallbackData)
 {
     EXPECT_TRUE(std::is_pod<OCHeaderOption>::value);
 }
+
+TEST(OCDoDirectPairingTests, Nullpeer)
+{
+    EXPECT_EQ(OC_STACK_INVALID_PARAM,OCDoDirectPairing(NULL, pmSel, &pinNumber, &resultCallback));
+}
+
+TEST(OCDoDirectPairingTests, NullCallback)
+{
+    EXPECT_EQ(OC_STACK_INVALID_CALLBACK,OCDoDirectPairing(&peer, pmSel, &pinNumber, NULL));
+}
+
+TEST(OCDoDirectPairingTests, NullpinNumber)
+{
+    EXPECT_EQ(OC_STACK_INVALID_PARAM,OCDoDirectPairing(&peer, pmSel, NULL, &resultCallback));
+}
+
+TEST(StackResource, MultipleResourcesDiscovery)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OIC_LOG(INFO, TAG, "Starting MultipleResourcesDiscovery test");
+    InitStack(OC_SERVER);
+
+    OCResourceHandle handle1;
+    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle1,
+                                            "core.led",
+                                            "core.rw",
+                                            "/a/led1",
+                                            0,
+                                            NULL,
+                                            OC_DISCOVERABLE|OC_OBSERVABLE));
+
+    OCResourceHandle handle2;
+    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle2,
+                                            "core.led",
+                                            "core.rw",
+                                            "/a/led2",
+                                            0,
+                                            NULL,
+                                            OC_DISCOVERABLE|OC_OBSERVABLE));
+    OCResourceHandle handle3;
+    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle3,
+                                            "core.led",
+                                            "core.rw",
+                                            "/a/led3",
+                                            0,
+                                            NULL,
+                                            OC_DISCOVERABLE|OC_OBSERVABLE));
+    /* Start a discovery query*/
+    char szQueryUri[256] = "/oic/res?if=oic.if.ll";
+    OCCallbackData cbData;
+    cbData.cb = discoveryCallback;
+    cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
+    cbData.cd = NULL;
+
+    OCDoHandle handle;
+    EXPECT_EQ(OC_STACK_OK, OCDoResource(&handle,
+                                        OC_REST_DISCOVER,
+                                        szQueryUri,
+                                        0,
+                                        0,
+                                        CT_ADAPTER_IP,
+                                        OC_LOW_QOS,
+                                        &cbData,
+                                        NULL,
+                                        0));
+
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
diff --git a/resource/docs/Doxyfile b/resource/docs/Doxyfile
deleted file mode 100644 (file)
index d698710..0000000
+++ /dev/null
@@ -1,1834 +0,0 @@
-# Doxyfile 1.8.2
-
-# This file describes the settings to be used by the documentation system
-# doxygen (www.doxygen.org) for a project
-#
-# All text after a hash (#) is considered a comment and will be ignored
-# The format is:
-#       TAG = value [value, ...]
-# For lists items can also be appended using:
-#       TAG += value [value, ...]
-# Values that contain spaces should be placed between quotes (" ")
-
-#---------------------------------------------------------------------------
-# Project related configuration options
-#---------------------------------------------------------------------------
-
-# This tag specifies the encoding used for all characters in the config file
-# that follow. The default is UTF-8 which is also the encoding used for all
-# text before the first occurrence of this tag. Doxygen uses libiconv (or the
-# iconv built into libc) for the transcoding. See
-# http://www.gnu.org/software/libiconv for the list of possible encodings.
-
-DOXYFILE_ENCODING      = UTF-8
-
-# The PROJECT_NAME tag is a single word (or sequence of words) that should
-# identify the project. Note that if you do not use Doxywizard you need
-# to put quotes around the project name if it contains spaces.
-
-PROJECT_NAME           = "IoTivity C++ SDK"
-
-# The PROJECT_NUMBER tag can be used to enter a project or revision number.
-# This could be handy for archiving the generated documentation or
-# if some version control system is used.
-
-PROJECT_NUMBER         = 
-
-# Using the PROJECT_BRIEF tag one can provide an optional one line description
-# for a project that appears at the top of each page and should give viewer
-# a quick idea about the purpose of the project. Keep the description short.
-
-PROJECT_BRIEF          =
-
-# With the PROJECT_LOGO tag one can specify an logo or icon that is
-# included in the documentation. The maximum height of the logo should not
-# exceed 55 pixels and the maximum width should not exceed 200 pixels.
-# Doxygen will copy the logo to the output directory.
-
-PROJECT_LOGO           =
-
-# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute)
-# base path where the generated documentation will be put.
-# If a relative path is entered, it will be relative to the location
-# where doxygen was started. If left blank the current directory will be used.
-
-OUTPUT_DIRECTORY       = docs
-
-# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create
-# 4096 sub-directories (in 2 levels) under the output directory of each output
-# format and will distribute the generated files over these directories.
-# Enabling this option can be useful when feeding doxygen a huge amount of
-# source files, where putting all generated files in the same directory would
-# otherwise cause performance problems for the file system.
-
-CREATE_SUBDIRS         = NO
-
-# The OUTPUT_LANGUAGE tag is used to specify the language in which all
-# documentation generated by doxygen is written. Doxygen will use this
-# information to generate all constant output in the proper language.
-# The default language is English, other supported languages are:
-# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional,
-# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German,
-# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English
-# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian,
-# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak,
-# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese.
-
-OUTPUT_LANGUAGE        = English
-
-# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will
-# include brief member descriptions after the members that are listed in
-# the file and class documentation (similar to JavaDoc).
-# Set to NO to disable this.
-
-BRIEF_MEMBER_DESC      = YES
-
-# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend
-# the brief description of a member or function before the detailed description.
-# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
-# brief descriptions will be completely suppressed.
-
-REPEAT_BRIEF           = YES
-
-# This tag implements a quasi-intelligent brief description abbreviator
-# that is used to form the text in various listings. Each string
-# in this list, if found as the leading text of the brief description, will be
-# stripped from the text and the result after processing the whole list, is
-# used as the annotated text. Otherwise, the brief description is used as-is.
-# If left blank, the following values are used ("$name" is automatically
-# replaced with the name of the entity): "The $name class" "The $name widget"
-# "The $name file" "is" "provides" "specifies" "contains"
-# "represents" "a" "an" "the"
-
-ABBREVIATE_BRIEF       = "The $name class" \
-                         "The $name widget" \
-                         "The $name file" \
-                         is \
-                         provides \
-                         specifies \
-                         contains \
-                         represents \
-                         a \
-                         an \
-                         the
-
-# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
-# Doxygen will generate a detailed section even if there is only a brief
-# description.
-
-ALWAYS_DETAILED_SEC    = NO
-
-# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
-# inherited members of a class in the documentation of that class as if those
-# members were ordinary class members. Constructors, destructors and assignment
-# operators of the base classes will not be shown.
-
-INLINE_INHERITED_MEMB  = NO
-
-# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full
-# path before files name in the file list and in the header files. If set
-# to NO the shortest path that makes the file name unique will be used.
-
-FULL_PATH_NAMES        = NO
-
-# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag
-# can be used to strip a user-defined part of the path. Stripping is
-# only done if one of the specified strings matches the left-hand part of
-# the path. The tag can be used to show relative paths in the file list.
-# If left blank the directory from which doxygen is run is used as the
-# path to strip. Note that you specify absolute paths here, but also
-# relative paths, which will be relative from the directory where doxygen is
-# started.
-
-STRIP_FROM_PATH        =
-
-# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of
-# the path mentioned in the documentation of a class, which tells
-# the reader which header file to include in order to use a class.
-# If left blank only the name of the header file containing the class
-# definition is used. Otherwise one should specify the include paths that
-# are normally passed to the compiler using the -I flag.
-
-STRIP_FROM_INC_PATH    =
-
-# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter
-# (but less readable) file names. This can be useful if your file system
-# doesn't support long names like on DOS, Mac, or CD-ROM.
-
-SHORT_NAMES            = NO
-
-# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen
-# will interpret the first line (until the first dot) of a JavaDoc-style
-# comment as the brief description. If set to NO, the JavaDoc
-# comments will behave just like regular Qt-style comments
-# (thus requiring an explicit @brief command for a brief description.)
-
-JAVADOC_AUTOBRIEF      = YES
-
-# If the QT_AUTOBRIEF tag is set to YES then Doxygen will
-# interpret the first line (until the first dot) of a Qt-style
-# comment as the brief description. If set to NO, the comments
-# will behave just like regular Qt-style comments (thus requiring
-# an explicit \brief command for a brief description.)
-
-QT_AUTOBRIEF           = NO
-
-# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen
-# treat a multi-line C++ special comment block (i.e. a block of //! or ///
-# comments) as a brief description. This used to be the default behaviour.
-# The new default is to treat a multi-line C++ comment block as a detailed
-# description. Set this tag to YES if you prefer the old behaviour instead.
-
-MULTILINE_CPP_IS_BRIEF = NO
-
-# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented
-# member inherits the documentation from any documented member that it
-# re-implements.
-
-INHERIT_DOCS           = YES
-
-# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce
-# a new page for each member. If set to NO, the documentation of a member will
-# be part of the file/class/namespace that contains it.
-
-SEPARATE_MEMBER_PAGES  = NO
-
-# The TAB_SIZE tag can be used to set the number of spaces in a tab.
-# Doxygen uses this value to replace tabs by spaces in code fragments.
-
-TAB_SIZE               = 8
-
-# This tag can be used to specify a number of aliases that acts
-# as commands in the documentation. An alias has the form "name=value".
-# For example adding "sideeffect=\par Side Effects:\n" will allow you to
-# put the command \sideeffect (or @sideeffect) in the documentation, which
-# will result in a user-defined paragraph with heading "Side Effects:".
-# You can put \n's in the value part of an alias to insert newlines.
-
-ALIASES                =
-
-# This tag can be used to specify a number of word-keyword mappings (TCL only).
-# A mapping has the form "name=value". For example adding
-# "class=itcl::class" will allow you to use the command class in the
-# itcl::class meaning.
-
-TCL_SUBST              =
-
-# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C
-# sources only. Doxygen will then generate output that is more tailored for C.
-# For instance, some of the names that are used will be different. The list
-# of all members will be omitted, etc.
-
-OPTIMIZE_OUTPUT_FOR_C  = NO
-
-# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java
-# sources only. Doxygen will then generate output that is more tailored for
-# Java. For instance, namespaces will be presented as packages, qualified
-# scopes will look different, etc.
-
-OPTIMIZE_OUTPUT_JAVA   = NO
-
-# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
-# sources only. Doxygen will then generate output that is more tailored for
-# Fortran.
-
-OPTIMIZE_FOR_FORTRAN   = NO
-
-# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
-# sources. Doxygen will then generate output that is tailored for
-# VHDL.
-
-OPTIMIZE_OUTPUT_VHDL   = NO
-
-# Doxygen selects the parser to use depending on the extension of the files it
-# parses. With this tag you can assign which parser to use for a given
-# extension. Doxygen has a built-in mapping, but you can override or extend it
-# using this tag. The format is ext=language, where ext is a file extension,
-# and language is one of the parsers supported by doxygen: IDL, Java,
-# Javascript, CSharp, C, C++, D, PHP, Objective-C, Python, Fortran, VHDL, C,
-# C++. For instance to make doxygen treat .inc files as Fortran files (default
-# is PHP), and .f files as C (default is Fortran), use: inc=Fortran f=C. Note
-# that for custom extensions you also need to set FILE_PATTERNS otherwise the
-# files are not read by doxygen.
-
-EXTENSION_MAPPING      =
-
-# If MARKDOWN_SUPPORT is enabled (the default) then doxygen pre-processes all
-# comments according to the Markdown format, which allows for more readable
-# documentation. See http://daringfireball.net/projects/markdown/ for details.
-# The output of markdown processing is further processed by doxygen, so you
-# can mix doxygen, HTML, and XML commands with Markdown formatting.
-# Disable only in case of backward compatibilities issues.
-
-MARKDOWN_SUPPORT       = YES
-
-# When enabled doxygen tries to link words that correspond to documented classes,
-# or namespaces to their corresponding documentation. Such a link can be
-# prevented in individual cases by by putting a % sign in front of the word or
-# globally by setting AUTOLINK_SUPPORT to NO.
-
-AUTOLINK_SUPPORT       = YES
-
-# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
-# to include (a tag file for) the STL sources as input, then you should
-# set this tag to YES in order to let doxygen match functions declarations and
-# definitions whose arguments contain STL classes (e.g. func(std::string); v.s.
-# func(std::string) {}). This also makes the inheritance and collaboration
-# diagrams that involve STL classes more complete and accurate.
-
-BUILTIN_STL_SUPPORT    = NO
-
-# If you use Microsoft's C++/CLI language, you should set this option to YES to
-# enable parsing support.
-
-CPP_CLI_SUPPORT        = NO
-
-# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only.
-# Doxygen will parse them like normal C++ but will assume all classes use public
-# instead of private inheritance when no explicit protection keyword is present.
-
-SIP_SUPPORT            = NO
-
-# For Microsoft's IDL there are propget and propput attributes to indicate
-# getter and setter methods for a property. Setting this option to YES (the
-# default) will make doxygen replace the get and set methods by a property in
-# the documentation. This will only work if the methods are indeed getting or
-# setting a simple type. If this is not the case, or you want to show the
-# methods anyway, you should set this option to NO.
-
-IDL_PROPERTY_SUPPORT   = YES
-
-# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
-# tag is set to YES, then doxygen will reuse the documentation of the first
-# member in the group (if any) for the other members of the group. By default
-# all members of a group must be documented explicitly.
-
-DISTRIBUTE_GROUP_DOC   = NO
-
-# Set the SUBGROUPING tag to YES (the default) to allow class member groups of
-# the same type (for instance a group of public functions) to be put as a
-# subgroup of that type (e.g. under the Public Functions section). Set it to
-# NO to prevent subgrouping. Alternatively, this can be done per class using
-# the \nosubgrouping command.
-
-SUBGROUPING            = YES
-
-# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and
-# unions are shown inside the group in which they are included (e.g. using
-# @ingroup) instead of on a separate page (for HTML and Man pages) or
-# section (for LaTeX and RTF).
-
-INLINE_GROUPED_CLASSES = NO
-
-# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and
-# unions with only public data fields will be shown inline in the documentation
-# of the scope in which they are defined (i.e. file, namespace, or group
-# documentation), provided this scope is documented. If set to NO (the default),
-# structs, classes, and unions are shown on a separate page (for HTML and Man
-# pages) or section (for LaTeX and RTF).
-
-INLINE_SIMPLE_STRUCTS  = NO
-
-# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum
-# is documented as struct, union, or enum with the name of the typedef. So
-# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
-# with name TypeT. When disabled the typedef will appear as a member of a file,
-# namespace, or class. And the struct will be named TypeS. This can typically
-# be useful for C code in case the coding convention dictates that all compound
-# types are typedef'ed and only the typedef is referenced, never the tag name.
-
-TYPEDEF_HIDES_STRUCT   = NO
-
-# Similar to the SYMBOL_CACHE_SIZE the size of the symbol lookup cache can be
-# set using LOOKUP_CACHE_SIZE. This cache is used to resolve symbols given
-# their name and scope. Since this can be an expensive process and often the
-# same symbol appear multiple times in the code, doxygen keeps a cache of
-# pre-resolved symbols. If the cache is too small doxygen will become slower.
-# If the cache is too large, memory is wasted. The cache size is given by this
-# formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range is 0..9, the default is 0,
-# corresponding to a cache size of 2^16 = 65536 symbols.
-
-LOOKUP_CACHE_SIZE      = 0
-
-#---------------------------------------------------------------------------
-# Build related configuration options
-#---------------------------------------------------------------------------
-
-# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
-# documentation are documented, even if no documentation was available.
-# Private class members and static file members will be hidden unless
-# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES
-
-EXTRACT_ALL            = YES
-
-# If the EXTRACT_PRIVATE tag is set to YES all private members of a class
-# will be included in the documentation.
-
-EXTRACT_PRIVATE        = NO
-
-# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal
-# scope will be included in the documentation.
-
-EXTRACT_PACKAGE        = NO
-
-# If the EXTRACT_STATIC tag is set to YES all static members of a file
-# will be included in the documentation.
-
-EXTRACT_STATIC         = NO
-
-# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs)
-# defined locally in source files will be included in the documentation.
-# If set to NO only classes defined in header files are included.
-
-EXTRACT_LOCAL_CLASSES  = YES
-
-# This flag is only useful for Objective-C code. When set to YES local
-# methods, which are defined in the implementation section but not in
-# the interface are included in the documentation.
-# If set to NO (the default) only methods in the interface are included.
-
-EXTRACT_LOCAL_METHODS  = NO
-
-# If this flag is set to YES, the members of anonymous namespaces will be
-# extracted and appear in the documentation as a namespace called
-# 'anonymous_namespace{file}', where file will be replaced with the base
-# name of the file that contains the anonymous namespace. By default
-# anonymous namespaces are hidden.
-
-EXTRACT_ANON_NSPACES   = NO
-
-# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all
-# undocumented members of documented classes, files or namespaces.
-# If set to NO (the default) these members will be included in the
-# various overviews, but no documentation section is generated.
-# This option has no effect if EXTRACT_ALL is enabled.
-
-HIDE_UNDOC_MEMBERS     = NO
-
-# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all
-# undocumented classes that are normally visible in the class hierarchy.
-# If set to NO (the default) these classes will be included in the various
-# overviews. This option has no effect if EXTRACT_ALL is enabled.
-
-HIDE_UNDOC_CLASSES     = NO
-
-# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all
-# friend (class|struct|union) declarations.
-# If set to NO (the default) these declarations will be included in the
-# documentation.
-
-HIDE_FRIEND_COMPOUNDS  = NO
-
-# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any
-# documentation blocks found inside the body of a function.
-# If set to NO (the default) these blocks will be appended to the
-# function's detailed documentation block.
-
-HIDE_IN_BODY_DOCS      = NO
-
-# The INTERNAL_DOCS tag determines if documentation
-# that is typed after a \internal command is included. If the tag is set
-# to NO (the default) then the documentation will be excluded.
-# Set it to YES to include the internal documentation.
-
-INTERNAL_DOCS          = NO
-
-# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate
-# file names in lower-case letters. If set to YES upper-case letters are also
-# allowed. This is useful if you have classes or files whose names only differ
-# in case and if your file system supports case sensitive file names. Windows
-# and Mac users are advised to set this option to NO.
-
-CASE_SENSE_NAMES       = NO
-
-# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen
-# will show members with their full class and namespace scopes in the
-# documentation. If set to YES the scope will be hidden.
-
-HIDE_SCOPE_NAMES       = NO
-
-# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen
-# will put a list of the files that are included by a file in the documentation
-# of that file.
-
-SHOW_INCLUDE_FILES     = NO
-
-# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen
-# will list include files with double quotes in the documentation
-# rather than with sharp brackets.
-
-FORCE_LOCAL_INCLUDES   = NO
-
-# If the INLINE_INFO tag is set to YES (the default) then a tag [inline]
-# is inserted in the documentation for inline members.
-
-INLINE_INFO            = YES
-
-# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen
-# will sort the (detailed) documentation of file and class members
-# alphabetically by member name. If set to NO the members will appear in
-# declaration order.
-
-SORT_MEMBER_DOCS       = YES
-
-# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the
-# brief documentation of file, namespace and class members alphabetically
-# by member name. If set to NO (the default) the members will appear in
-# declaration order.
-
-SORT_BRIEF_DOCS        = NO
-
-# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen
-# will sort the (brief and detailed) documentation of class members so that
-# constructors and destructors are listed first. If set to NO (the default)
-# the constructors will appear in the respective orders defined by
-# SORT_MEMBER_DOCS and SORT_BRIEF_DOCS.
-# This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO
-# and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO.
-
-SORT_MEMBERS_CTORS_1ST = NO
-
-# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the
-# hierarchy of group names into alphabetical order. If set to NO (the default)
-# the group names will appear in their defined order.
-
-SORT_GROUP_NAMES       = NO
-
-# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be
-# sorted by fully-qualified names, including namespaces. If set to
-# NO (the default), the class list will be sorted only by class name,
-# not including the namespace part.
-# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
-# Note: This option applies only to the class list, not to the
-# alphabetical list.
-
-SORT_BY_SCOPE_NAME     = NO
-
-# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to
-# do proper type resolution of all parameters of a function it will reject a
-# match between the prototype and the implementation of a member function even
-# if there is only one candidate or it is obvious which candidate to choose
-# by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen
-# will still accept a match between prototype and implementation in such cases.
-
-STRICT_PROTO_MATCHING  = NO
-
-# The GENERATE_TODOLIST tag can be used to enable (YES) or
-# disable (NO) the todo list. This list is created by putting \todo
-# commands in the documentation.
-
-GENERATE_TODOLIST      = YES
-
-# The GENERATE_TESTLIST tag can be used to enable (YES) or
-# disable (NO) the test list. This list is created by putting \test
-# commands in the documentation.
-
-GENERATE_TESTLIST      = YES
-
-# The GENERATE_BUGLIST tag can be used to enable (YES) or
-# disable (NO) the bug list. This list is created by putting \bug
-# commands in the documentation.
-
-GENERATE_BUGLIST       = YES
-
-# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or
-# disable (NO) the deprecated list. This list is created by putting
-# \deprecated commands in the documentation.
-
-GENERATE_DEPRECATEDLIST= YES
-
-# The ENABLED_SECTIONS tag can be used to enable conditional
-# documentation sections, marked by \if sectionname ... \endif.
-
-ENABLED_SECTIONS       =
-
-# The MAX_INITIALIZER_LINES tag determines the maximum number of lines
-# the initial value of a variable or macro consists of for it to appear in
-# the documentation. If the initializer consists of more lines than specified
-# here it will be hidden. Use a value of 0 to hide initializers completely.
-# The appearance of the initializer of individual variables and macros in the
-# documentation can be controlled using \showinitializer or \hideinitializer
-# command in the documentation regardless of this setting.
-
-MAX_INITIALIZER_LINES  = 125
-
-# Set the SHOW_USED_FILES tag to NO to disable the list of files generated
-# at the bottom of the documentation of classes and structs. If set to YES the
-# list will mention the files that were used to generate the documentation.
-
-SHOW_USED_FILES        = YES
-
-# Set the SHOW_FILES tag to NO to disable the generation of the Files page.
-# This will remove the Files entry from the Quick Index and from the
-# Folder Tree View (if specified). The default is YES.
-
-SHOW_FILES             = YES
-
-# Set the SHOW_NAMESPACES tag to NO to disable the generation of the
-# Namespaces page.  This will remove the Namespaces entry from the Quick Index
-# and from the Folder Tree View (if specified). The default is YES.
-
-SHOW_NAMESPACES        = YES
-
-# The FILE_VERSION_FILTER tag can be used to specify a program or script that
-# doxygen should invoke to get the current version for each file (typically from
-# the version control system). Doxygen will invoke the program by executing (via
-# popen()) the command <command> <input-file>, where <command> is the value of
-# the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file
-# provided by doxygen. Whatever the program writes to standard output
-# is used as the file version. See the manual for examples.
-
-FILE_VERSION_FILTER    =
-
-# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
-# by doxygen. The layout file controls the global structure of the generated
-# output files in an output format independent way. To create the layout file
-# that represents doxygen's defaults, run doxygen with the -l option.
-# You can optionally specify a file name after the option, if omitted
-# DoxygenLayout.xml will be used as the name of the layout file.
-
-LAYOUT_FILE            = doxygenLayout.xml
-
-# The CITE_BIB_FILES tag can be used to specify one or more bib files
-# containing the references data. This must be a list of .bib files. The
-# .bib extension is automatically appended if omitted. Using this command
-# requires the bibtex tool to be installed. See also
-# http://en.wikipedia.org/wiki/BibTeX for more info. For LaTeX the style
-# of the bibliography can be controlled using LATEX_BIB_STYLE. To use this
-# feature you need bibtex and perl available in the search path.
-
-CITE_BIB_FILES         =
-
-#---------------------------------------------------------------------------
-# configuration options related to warning and progress messages
-#---------------------------------------------------------------------------
-
-# The QUIET tag can be used to turn on/off the messages that are generated
-# by doxygen. Possible values are YES and NO. If left blank NO is used.
-
-QUIET                  = NO
-
-# The WARNINGS tag can be used to turn on/off the warning messages that are
-# generated by doxygen. Possible values are YES and NO. If left blank
-# NO is used.
-
-WARNINGS               = YES
-
-# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings
-# for undocumented members. If EXTRACT_ALL is set to YES then this flag will
-# automatically be disabled.
-
-WARN_IF_UNDOCUMENTED   = YES
-
-# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for
-# potential errors in the documentation, such as not documenting some
-# parameters in a documented function, or documenting parameters that
-# don't exist or using markup commands wrongly.
-
-WARN_IF_DOC_ERROR      = YES
-
-# The WARN_NO_PARAMDOC option can be enabled to get warnings for
-# functions that are documented, but have no documentation for their parameters
-# or return value. If set to NO (the default) doxygen will only warn about
-# wrong or incomplete parameter documentation, but not about the absence of
-# documentation.
-
-WARN_NO_PARAMDOC       = NO
-
-# The WARN_FORMAT tag determines the format of the warning messages that
-# doxygen can produce. The string should contain the $file, $line, and $text
-# tags, which will be replaced by the file and line number from which the
-# warning originated and the warning text. Optionally the format may contain
-# $version, which will be replaced by the version of the file (if it could
-# be obtained via FILE_VERSION_FILTER)
-
-WARN_FORMAT            = "$file:$line: $text"
-
-# The WARN_LOGFILE tag can be used to specify a file to which warning
-# and error messages should be written. If left blank the output is written
-# to stderr.
-
-WARN_LOGFILE           = ./doxygen.log
-
-#---------------------------------------------------------------------------
-# configuration options related to the input files
-#---------------------------------------------------------------------------
-
-# The INPUT tag can be used to specify the files and/or directories that contain
-# documented source files. You may enter file names like "myfile.cpp" or
-# directories like "/usr/src/myproject". Separate the files or directories
-# with spaces.
-
-INPUT                  = . \
-                         ../include/OCApi.h \
-                         ../include/OCPlatform.h \
-                         ../include/OCRepresentation.h \
-                         ../include/OCResourceRequest.h \
-                         ../include/OCResourceResponse.h \
-                         ../include/OCResource.h \
-                         ../csdk/stack/include/octypes.h \
-                         ../csdk/stack/include/ocstackconfig.h \
-                         guides \
-                         ../../service/things-manager/sdk/inc \
-                         ../../service/resource-hosting/include/hosting.h \
-                         ../../service/resource-encapsulation/include \
-                         ../../service/resource-directory/include \
-                         ../../service/easy-setup/sdk/common \
-                         ../../service/easy-setup/sdk/enrollee/api \
-
-# This tag can be used to specify the character encoding of the source files
-# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is
-# also the default input encoding. Doxygen uses libiconv (or the iconv built
-# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for
-# the list of possible encodings.
-
-INPUT_ENCODING         = UTF-8
-
-# If the value of the INPUT tag contains directories, you can use the
-# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
-# and *.h) to filter out the source-files in the directories. If left
-# blank the following patterns are tested:
-# *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh
-# *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py
-# *.f90 *.f *.for *.vhd *.vhdl
-
-FILE_PATTERNS          = *.c \
-                         *.cc \
-                         *.cxx \
-                         *.cpp \
-                         *.c++ \
-                         *.d \
-                         *.java \
-                         *.ii \
-                         *.ixx \
-                         *.ipp \
-                         *.i++ \
-                         *.inl \
-                         *.h \
-                         *.hh \
-                         *.hxx \
-                         *.hpp \
-                         *.h++ \
-                         *.idl \
-                         *.odl \
-                         *.cs \
-                         *.php \
-                         *.php3 \
-                         *.inc \
-                         *.m \
-                         *.markdown \
-                         *.md \
-                         *.mm \
-                         *.dox \
-                         *.py \
-                         *.f90 \
-                         *.f \
-                         *.for \
-                         *.vhd \
-                         *.vhdl \
-                         *.txt
-
-# The RECURSIVE tag can be used to turn specify whether or not subdirectories
-# should be searched for input files as well. Possible values are YES and NO.
-# If left blank NO is used.
-
-RECURSIVE              = NO
-
-# The EXCLUDE tag can be used to specify files and/or directories that should be
-# excluded from the INPUT source files. This way you can easily exclude a
-# subdirectory from a directory tree whose root is specified with the INPUT tag.
-# Note that relative paths are relative to the directory from which doxygen is
-# run.
-
-EXCLUDE                =
-
-# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
-# directories that are symbolic links (a Unix file system feature) are excluded
-# from the input.
-
-EXCLUDE_SYMLINKS       = NO
-
-# If the value of the INPUT tag contains directories, you can use the
-# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
-# certain files from those directories. Note that the wildcards are matched
-# against the file with absolute path, so to exclude all test directories
-# for example use the pattern */test/*
-
-EXCLUDE_PATTERNS       =
-
-# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
-# (namespaces, classes, functions, etc.) that should be excluded from the
-# output. The symbol name can be a fully qualified name, a word, or if the
-# wildcard * is used, a substring. Examples: ANamespace, AClass,
-# AClass::ANamespace, ANamespace::*Test
-
-EXCLUDE_SYMBOLS        =
-
-# The EXAMPLE_PATH tag can be used to specify one or more files or
-# directories that contain example code fragments that are included (see
-# the \include command).
-
-EXAMPLE_PATH           =
-
-# If the value of the EXAMPLE_PATH tag contains directories, you can use the
-# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
-# and *.h) to filter out the source-files in the directories. If left
-# blank all files are included.
-
-EXAMPLE_PATTERNS       = *
-
-# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
-# searched for input files to be used with the \include or \dontinclude
-# commands irrespective of the value of the RECURSIVE tag.
-# Possible values are YES and NO. If left blank NO is used.
-
-EXAMPLE_RECURSIVE      = NO
-
-# The IMAGE_PATH tag can be used to specify one or more files or
-# directories that contain image that are included in the documentation (see
-# the \image command).
-
-IMAGE_PATH             = img
-
-# The INPUT_FILTER tag can be used to specify a program that doxygen should
-# invoke to filter for each input file. Doxygen will invoke the filter program
-# by executing (via popen()) the command <filter> <input-file>, where <filter>
-# is the value of the INPUT_FILTER tag, and <input-file> is the name of an
-# input file. Doxygen will then use the output that the filter program writes
-# to standard output.  If FILTER_PATTERNS is specified, this tag will be
-# ignored.
-
-INPUT_FILTER           =
-
-# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
-# basis.  Doxygen will compare the file name with each pattern and apply the
-# filter if there is a match.  The filters are a list of the form:
-# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further
-# info on how filters are used. If FILTER_PATTERNS is empty or if
-# non of the patterns match the file name, INPUT_FILTER is applied.
-
-FILTER_PATTERNS        =
-
-# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
-# INPUT_FILTER) will be used to filter the input files when producing source
-# files to browse (i.e. when SOURCE_BROWSER is set to YES).
-
-FILTER_SOURCE_FILES    = NO
-
-# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
-# pattern. A pattern will override the setting for FILTER_PATTERN (if any)
-# and it is also possible to disable source filtering for a specific pattern
-# using *.ext= (so without naming a filter). This option only has effect when
-# FILTER_SOURCE_FILES is enabled.
-
-FILTER_SOURCE_PATTERNS =
-
-#---------------------------------------------------------------------------
-# configuration options related to source browsing
-#---------------------------------------------------------------------------
-
-# If the SOURCE_BROWSER tag is set to YES then a list of source files will
-# be generated. Documented entities will be cross-referenced with these sources.
-# Note: To get rid of all source code in the generated output, make sure also
-# VERBATIM_HEADERS is set to NO.
-
-SOURCE_BROWSER         = NO
-
-# Setting the INLINE_SOURCES tag to YES will include the body
-# of functions and classes directly in the documentation.
-
-INLINE_SOURCES         = NO
-
-# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct
-# doxygen to hide any special comment blocks from generated source code
-# fragments. Normal C, C++ and Fortran comments will always remain visible.
-
-STRIP_CODE_COMMENTS    = YES
-
-# If the REFERENCED_BY_RELATION tag is set to YES
-# then for each documented function all documented
-# functions referencing it will be listed.
-
-REFERENCED_BY_RELATION = NO
-
-# If the REFERENCES_RELATION tag is set to YES
-# then for each documented function all documented entities
-# called/used by that function will be listed.
-
-REFERENCES_RELATION    = NO
-
-# If the REFERENCES_LINK_SOURCE tag is set to YES (the default)
-# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from
-# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will
-# link to the source code.  Otherwise they will link to the documentation.
-
-REFERENCES_LINK_SOURCE = YES
-
-# If the USE_HTAGS tag is set to YES then the references to source code
-# will point to the HTML generated by the htags(1) tool instead of doxygen
-# built-in source browser. The htags tool is part of GNU's global source
-# tagging system (see http://www.gnu.org/software/global/global.html). You
-# will need version 4.8.6 or higher.
-
-USE_HTAGS              = NO
-
-# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen
-# will generate a verbatim copy of the header file for each class for
-# which an include is specified. Set to NO to disable this.
-
-VERBATIM_HEADERS       = YES
-
-#---------------------------------------------------------------------------
-# configuration options related to the alphabetical class index
-#---------------------------------------------------------------------------
-
-# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index
-# of all compounds will be generated. Enable this if the project
-# contains a lot of classes, structs, unions or interfaces.
-
-ALPHABETICAL_INDEX     = YES
-
-# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then
-# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns
-# in which this list will be split (can be a number in the range [1..20])
-
-COLS_IN_ALPHA_INDEX    = 5
-
-# In case all classes in a project start with a common prefix, all
-# classes will be put under the same header in the alphabetical index.
-# The IGNORE_PREFIX tag can be used to specify one or more prefixes that
-# should be ignored while generating the index headers.
-
-IGNORE_PREFIX          =
-
-#---------------------------------------------------------------------------
-# configuration options related to the HTML output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_HTML tag is set to YES (the default) Doxygen will
-# generate HTML output.
-
-GENERATE_HTML          = YES
-
-# The HTML_OUTPUT tag is used to specify where the HTML docs will be put.
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be
-# put in front of it. If left blank `html' will be used as the default path.
-
-HTML_OUTPUT            = html
-
-# The HTML_FILE_EXTENSION tag can be used to specify the file extension for
-# each generated HTML page (for example: .htm,.php,.asp). If it is left blank
-# doxygen will generate files with .html extension.
-
-HTML_FILE_EXTENSION    = .html
-
-# The HTML_HEADER tag can be used to specify a personal HTML header for
-# each generated HTML page. If it is left blank doxygen will generate a
-# standard header. Note that when using a custom header you are responsible
-# for the proper inclusion of any scripts and style sheets that doxygen
-# needs, which is dependent on the configuration options used.
-# It is advised to generate a default header using "doxygen -w html
-# header.html footer.html stylesheet.css YourConfigFile" and then modify
-# that header. Note that the header is subject to change so you typically
-# have to redo this when upgrading to a newer version of doxygen or when
-# changing the value of configuration settings such as GENERATE_TREEVIEW!
-
-HTML_HEADER            =
-
-# The HTML_FOOTER tag can be used to specify a personal HTML footer for
-# each generated HTML page. If it is left blank doxygen will generate a
-# standard footer.
-
-HTML_FOOTER            = html/footer.html
-
-# The HTML_STYLESHEET tag can be used to specify a user-defined cascading
-# style sheet that is used by each HTML page. It can be used to
-# fine-tune the look of the HTML output. If left blank doxygen will
-# generate a default style sheet. Note that it is recommended to use
-# HTML_EXTRA_STYLESHEET instead of this one, as it is more robust and this
-# tag will in the future become obsolete.
-
-HTML_STYLESHEET        =
-
-# The HTML_EXTRA_STYLESHEET tag can be used to specify an additional
-# user-defined cascading style sheet that is included after the standard
-# style sheets created by doxygen. Using this option one can overrule
-# certain style aspects. This is preferred over using HTML_STYLESHEET
-# since it does not replace the standard style sheet and is therefor more
-# robust against future updates. Doxygen will copy the style sheet file to
-# the output directory.
-
-HTML_EXTRA_STYLESHEET  =
-
-# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
-# other source files which should be copied to the HTML output directory. Note
-# that these files will be copied to the base HTML output directory. Use the
-# $relpath$ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
-# files. In the HTML_STYLESHEET file, use the file name only. Also note that
-# the files will be copied as-is; there are no commands or markers available.
-
-HTML_EXTRA_FILES       =
-
-# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output.
-# Doxygen will adjust the colors in the style sheet and background images
-# according to this color. Hue is specified as an angle on a colorwheel,
-# see http://en.wikipedia.org/wiki/Hue for more information.
-# For instance the value 0 represents red, 60 is yellow, 120 is green,
-# 180 is cyan, 240 is blue, 300 purple, and 360 is red again.
-# The allowed range is 0 to 359.
-
-HTML_COLORSTYLE_HUE    = 220
-
-# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of
-# the colors in the HTML output. For a value of 0 the output will use
-# grayscales only. A value of 255 will produce the most vivid colors.
-
-HTML_COLORSTYLE_SAT    = 100
-
-# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to
-# the luminance component of the colors in the HTML output. Values below
-# 100 gradually make the output lighter, whereas values above 100 make
-# the output darker. The value divided by 100 is the actual gamma applied,
-# so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2,
-# and 100 does not change the gamma.
-
-HTML_COLORSTYLE_GAMMA  = 80
-
-# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
-# page will contain the date and time when the page was generated. Setting
-# this to NO can help when comparing the output of multiple runs.
-
-HTML_TIMESTAMP         = YES
-
-# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
-# documentation will contain sections that can be hidden and shown after the
-# page has loaded.
-
-HTML_DYNAMIC_SECTIONS  = NO
-
-# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of
-# entries shown in the various tree structured indices initially; the user
-# can expand and collapse entries dynamically later on. Doxygen will expand
-# the tree to such a level that at most the specified number of entries are
-# visible (unless a fully collapsed tree already exceeds this amount).
-# So setting the number of entries 1 will produce a full collapsed tree by
-# default. 0 is a special value representing an infinite number of entries
-# and will result in a full expanded tree by default.
-
-HTML_INDEX_NUM_ENTRIES = 100
-
-# If the GENERATE_DOCSET tag is set to YES, additional index files
-# will be generated that can be used as input for Apple's Xcode 3
-# integrated development environment, introduced with OSX 10.5 (Leopard).
-# To create a documentation set, doxygen will generate a Makefile in the
-# HTML output directory. Running make will produce the docset in that
-# directory and running "make install" will install the docset in
-# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find
-# it at startup.
-# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html
-# for more information.
-
-GENERATE_DOCSET        = NO
-
-# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the
-# feed. A documentation feed provides an umbrella under which multiple
-# documentation sets from a single provider (such as a company or product suite)
-# can be grouped.
-
-DOCSET_FEEDNAME        = "Doxygen generated docs"
-
-# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that
-# should uniquely identify the documentation set bundle. This should be a
-# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen
-# will append .docset to the name.
-
-DOCSET_BUNDLE_ID       = org.doxygen.Project
-
-# When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely
-# identify the documentation publisher. This should be a reverse domain-name
-# style string, e.g. com.mycompany.MyDocSet.documentation.
-
-DOCSET_PUBLISHER_ID    = org.doxygen.Publisher
-
-# The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher.
-
-DOCSET_PUBLISHER_NAME  = Publisher
-
-# If the GENERATE_HTMLHELP tag is set to YES, additional index files
-# will be generated that can be used as input for tools like the
-# Microsoft HTML help workshop to generate a compiled HTML help file (.chm)
-# of the generated HTML documentation.
-
-GENERATE_HTMLHELP      = NO
-
-# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can
-# be used to specify the file name of the resulting .chm file. You
-# can add a path in front of the file if the result should not be
-# written to the html output directory.
-
-CHM_FILE               =
-
-# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can
-# be used to specify the location (absolute path including file name) of
-# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run
-# the HTML help compiler on the generated index.hhp.
-
-HHC_LOCATION           =
-
-# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag
-# controls if a separate .chi index file is generated (YES) or that
-# it should be included in the master .chm file (NO).
-
-GENERATE_CHI           = NO
-
-# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING
-# is used to encode HtmlHelp index (hhk), content (hhc) and project file
-# content.
-
-CHM_INDEX_ENCODING     =
-
-# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag
-# controls whether a binary table of contents is generated (YES) or a
-# normal table of contents (NO) in the .chm file.
-
-BINARY_TOC             = NO
-
-# The TOC_EXPAND flag can be set to YES to add extra items for group members
-# to the contents of the HTML help documentation and to the tree view.
-
-TOC_EXPAND             = NO
-
-# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
-# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated
-# that can be used as input for Qt's qhelpgenerator to generate a
-# Qt Compressed Help (.qch) of the generated HTML documentation.
-
-GENERATE_QHP           = NO
-
-# If the QHG_LOCATION tag is specified, the QCH_FILE tag can
-# be used to specify the file name of the resulting .qch file.
-# The path specified is relative to the HTML output folder.
-
-QCH_FILE               =
-
-# The QHP_NAMESPACE tag specifies the namespace to use when generating
-# Qt Help Project output. For more information please see
-# http://doc.trolltech.com/qthelpproject.html#namespace
-
-QHP_NAMESPACE          = org.doxygen.Project
-
-# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating
-# Qt Help Project output. For more information please see
-# http://doc.trolltech.com/qthelpproject.html#virtual-folders
-
-QHP_VIRTUAL_FOLDER     = doc
-
-# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to
-# add. For more information please see
-# http://doc.trolltech.com/qthelpproject.html#custom-filters
-
-QHP_CUST_FILTER_NAME   =
-
-# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the
-# custom filter to add. For more information please see
-# <a href="http://doc.trolltech.com/qthelpproject.html#custom-filters">
-# Qt Help Project / Custom Filters</a>.
-
-QHP_CUST_FILTER_ATTRS  =
-
-# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
-# project's
-# filter section matches.
-# <a href="http://doc.trolltech.com/qthelpproject.html#filter-attributes">
-# Qt Help Project / Filter Attributes</a>.
-
-QHP_SECT_FILTER_ATTRS  =
-
-# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can
-# be used to specify the location of Qt's qhelpgenerator.
-# If non-empty doxygen will try to run qhelpgenerator on the generated
-# .qhp file.
-
-QHG_LOCATION           =
-
-# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files
-# will be generated, which together with the HTML files, form an Eclipse help
-# plugin. To install this plugin and make it available under the help contents
-# menu in Eclipse, the contents of the directory containing the HTML and XML
-# files needs to be copied into the plugins directory of eclipse. The name of
-# the directory within the plugins directory should be the same as
-# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before
-# the help appears.
-
-GENERATE_ECLIPSEHELP   = NO
-
-# A unique identifier for the eclipse help plugin. When installing the plugin
-# the directory name containing the HTML and XML files should also have
-# this name.
-
-ECLIPSE_DOC_ID         = org.doxygen.Project
-
-# The DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs)
-# at top of each HTML page. The value NO (the default) enables the index and
-# the value YES disables it. Since the tabs have the same information as the
-# navigation tree you can set this option to NO if you already set
-# GENERATE_TREEVIEW to YES.
-
-DISABLE_INDEX          = NO
-
-# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
-# structure should be generated to display hierarchical information.
-# If the tag value is set to YES, a side panel will be generated
-# containing a tree-like index structure (just like the one that
-# is generated for HTML Help). For this to work a browser that supports
-# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser).
-# Windows users are probably better off using the HTML help feature.
-# Since the tree basically has the same information as the tab index you
-# could consider to set DISABLE_INDEX to NO when enabling this option.
-
-GENERATE_TREEVIEW      = YES
-
-# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values
-# (range [0,1..20]) that doxygen will group on one line in the generated HTML
-# documentation. Note that a value of 0 will completely suppress the enum
-# values from appearing in the overview section.
-
-ENUM_VALUES_PER_LINE   = 4
-
-# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be
-# used to set the initial width (in pixels) of the frame in which the tree
-# is shown.
-
-TREEVIEW_WIDTH         = 250
-
-# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open
-# links to external symbols imported via tag files in a separate window.
-
-EXT_LINKS_IN_WINDOW    = NO
-
-# Use this tag to change the font size of Latex formulas included
-# as images in the HTML documentation. The default is 10. Note that
-# when you change the font size after a successful doxygen run you need
-# to manually remove any form_*.png images from the HTML output directory
-# to force them to be regenerated.
-
-FORMULA_FONTSIZE       = 10
-
-# Use the FORMULA_TRANPARENT tag to determine whether or not the images
-# generated for formulas are transparent PNGs. Transparent PNGs are
-# not supported properly for IE 6.0, but are supported on all modern browsers.
-# Note that when changing this option you need to delete any form_*.png files
-# in the HTML output before the changes have effect.
-
-FORMULA_TRANSPARENT    = YES
-
-# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax
-# (see http://www.mathjax.org) which uses client side Javascript for the
-# rendering instead of using prerendered bitmaps. Use this if you do not
-# have LaTeX installed or if you want to formulas look prettier in the HTML
-# output. When enabled you may also need to install MathJax separately and
-# configure the path to it using the MATHJAX_RELPATH option.
-
-USE_MATHJAX            = NO
-
-# When MathJax is enabled you need to specify the location relative to the
-# HTML output directory using the MATHJAX_RELPATH option. The destination
-# directory should contain the MathJax.js script. For instance, if the mathjax
-# directory is located at the same level as the HTML output directory, then
-# MATHJAX_RELPATH should be ../mathjax. The default value points to
-# the MathJax Content Delivery Network so you can quickly see the result without
-# installing MathJax.  However, it is strongly recommended to install a local
-# copy of MathJax from http://www.mathjax.org before deployment.
-
-MATHJAX_RELPATH        = http://cdn.mathjax.org/mathjax/latest
-
-# The MATHJAX_EXTENSIONS tag can be used to specify one or MathJax extension
-# names that should be enabled during MathJax rendering.
-
-MATHJAX_EXTENSIONS     =
-
-# When the SEARCHENGINE tag is enabled doxygen will generate a search box
-# for the HTML output. The underlying search engine uses javascript
-# and DHTML and should work on any modern browser. Note that when using
-# HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets
-# (GENERATE_DOCSET) there is already a search function so this one should
-# typically be disabled. For large projects the javascript based search engine
-# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution.
-
-SEARCHENGINE           = YES
-
-# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
-# implemented using a PHP enabled web server instead of at the web client
-# using Javascript. Doxygen will generate the search PHP script and index
-# file to put on the web server. The advantage of the server
-# based approach is that it scales better to large projects and allows
-# full text search. The disadvantages are that it is more difficult to setup
-# and does not have live searching capabilities.
-
-SERVER_BASED_SEARCH    = NO
-
-#---------------------------------------------------------------------------
-# configuration options related to the LaTeX output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will
-# generate Latex output.
-
-GENERATE_LATEX         = NO
-
-# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put.
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be
-# put in front of it. If left blank `latex' will be used as the default path.
-
-LATEX_OUTPUT           = latex
-
-# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
-# invoked. If left blank `latex' will be used as the default command name.
-# Note that when enabling USE_PDFLATEX this option is only used for
-# generating bitmaps for formulas in the HTML output, but not in the
-# Makefile that is written to the output directory.
-
-LATEX_CMD_NAME         = latex
-
-# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to
-# generate index for LaTeX. If left blank `makeindex' will be used as the
-# default command name.
-
-MAKEINDEX_CMD_NAME     = makeindex
-
-# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact
-# LaTeX documents. This may be useful for small projects and may help to
-# save some trees in general.
-
-COMPACT_LATEX          = NO
-
-# The PAPER_TYPE tag can be used to set the paper type that is used
-# by the printer. Possible values are: a4, letter, legal and
-# executive. If left blank a4wide will be used.
-
-PAPER_TYPE             = a4
-
-# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX
-# packages that should be included in the LaTeX output.
-
-EXTRA_PACKAGES         =
-
-# The LATEX_HEADER tag can be used to specify a personal LaTeX header for
-# the generated latex document. The header should contain everything until
-# the first chapter. If it is left blank doxygen will generate a
-# standard header. Notice: only use this tag if you know what you are doing!
-
-LATEX_HEADER           =
-
-# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for
-# the generated latex document. The footer should contain everything after
-# the last chapter. If it is left blank doxygen will generate a
-# standard footer. Notice: only use this tag if you know what you are doing!
-
-LATEX_FOOTER           =
-
-# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated
-# is prepared for conversion to pdf (using ps2pdf). The pdf file will
-# contain links (just like the HTML output) instead of page references
-# This makes the output suitable for online browsing using a pdf viewer.
-
-PDF_HYPERLINKS         = YES
-
-# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of
-# plain latex in the generated Makefile. Set this option to YES to get a
-# higher quality PDF documentation.
-
-USE_PDFLATEX           = YES
-
-# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode.
-# command to the generated LaTeX files. This will instruct LaTeX to keep
-# running if errors occur, instead of asking the user for help.
-# This option is also used when generating formulas in HTML.
-
-LATEX_BATCHMODE        = NO
-
-# If LATEX_HIDE_INDICES is set to YES then doxygen will not
-# include the index chapters (such as File Index, Compound Index, etc.)
-# in the output.
-
-LATEX_HIDE_INDICES     = NO
-
-# If LATEX_SOURCE_CODE is set to YES then doxygen will include
-# source code with syntax highlighting in the LaTeX output.
-# Note that which sources are shown also depends on other settings
-# such as SOURCE_BROWSER.
-
-LATEX_SOURCE_CODE      = NO
-
-# The LATEX_BIB_STYLE tag can be used to specify the style to use for the
-# bibliography, e.g. plainnat, or ieeetr. The default style is "plain". See
-# http://en.wikipedia.org/wiki/BibTeX for more info.
-
-LATEX_BIB_STYLE        = plain
-
-#---------------------------------------------------------------------------
-# configuration options related to the RTF output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output
-# The RTF output is optimized for Word 97 and may not look very pretty with
-# other RTF readers or editors.
-
-GENERATE_RTF           = NO
-
-# The RTF_OUTPUT tag is used to specify where the RTF docs will be put.
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be
-# put in front of it. If left blank `rtf' will be used as the default path.
-
-RTF_OUTPUT             = rtf
-
-# If the COMPACT_RTF tag is set to YES Doxygen generates more compact
-# RTF documents. This may be useful for small projects and may help to
-# save some trees in general.
-
-COMPACT_RTF            = NO
-
-# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated
-# will contain hyperlink fields. The RTF file will
-# contain links (just like the HTML output) instead of page references.
-# This makes the output suitable for online browsing using WORD or other
-# programs which support those fields.
-# Note: wordpad (write) and others do not support links.
-
-RTF_HYPERLINKS         = NO
-
-# Load style sheet definitions from file. Syntax is similar to doxygen's
-# config file, i.e. a series of assignments. You only have to provide
-# replacements, missing definitions are set to their default value.
-
-RTF_STYLESHEET_FILE    =
-
-# Set optional variables used in the generation of an rtf document.
-# Syntax is similar to doxygen's config file.
-
-RTF_EXTENSIONS_FILE    =
-
-#---------------------------------------------------------------------------
-# configuration options related to the man page output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_MAN tag is set to YES (the default) Doxygen will
-# generate man pages
-
-GENERATE_MAN           = NO
-
-# The MAN_OUTPUT tag is used to specify where the man pages will be put.
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be
-# put in front of it. If left blank `man' will be used as the default path.
-
-MAN_OUTPUT             = man
-
-# The MAN_EXTENSION tag determines the extension that is added to
-# the generated man pages (default is the subroutine's section .3)
-
-MAN_EXTENSION          = .3
-
-# If the MAN_LINKS tag is set to YES and Doxygen generates man output,
-# then it will generate one additional man file for each entity
-# documented in the real man page(s). These additional files
-# only source the real man page, but without them the man command
-# would be unable to find the correct page. The default is NO.
-
-MAN_LINKS              = NO
-
-#---------------------------------------------------------------------------
-# configuration options related to the XML output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_XML tag is set to YES Doxygen will
-# generate an XML file that captures the structure of
-# the code including all documentation.
-
-GENERATE_XML           = NO
-
-# The XML_OUTPUT tag is used to specify where the XML pages will be put.
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be
-# put in front of it. If left blank `xml' will be used as the default path.
-
-XML_OUTPUT             = xml
-
-# If the XML_PROGRAMLISTING tag is set to YES Doxygen will
-# dump the program listings (including syntax highlighting
-# and cross-referencing information) to the XML output. Note that
-# enabling this will significantly increase the size of the XML output.
-
-XML_PROGRAMLISTING     = YES
-
-#---------------------------------------------------------------------------
-# configuration options for the AutoGen Definitions output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will
-# generate an AutoGen Definitions (see autogen.sf.net) file
-# that captures the structure of the code including all
-# documentation. Note that this feature is still experimental
-# and incomplete at the moment.
-
-GENERATE_AUTOGEN_DEF   = NO
-
-#---------------------------------------------------------------------------
-# configuration options related to the Perl module output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_PERLMOD tag is set to YES Doxygen will
-# generate a Perl module file that captures the structure of
-# the code including all documentation. Note that this
-# feature is still experimental and incomplete at the
-# moment.
-
-GENERATE_PERLMOD       = NO
-
-# If the PERLMOD_LATEX tag is set to YES Doxygen will generate
-# the necessary Makefile rules, Perl scripts and LaTeX code to be able
-# to generate PDF and DVI output from the Perl module output.
-
-PERLMOD_LATEX          = NO
-
-# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be
-# nicely formatted so it can be parsed by a human reader.  This is useful
-# if you want to understand what is going on.  On the other hand, if this
-# tag is set to NO the size of the Perl module output will be much smaller
-# and Perl will parse it just the same.
-
-PERLMOD_PRETTY         = YES
-
-# The names of the make variables in the generated doxyrules.make file
-# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX.
-# This is useful so different doxyrules.make files included by the same
-# Makefile don't overwrite each other's variables.
-
-PERLMOD_MAKEVAR_PREFIX =
-
-#---------------------------------------------------------------------------
-# Configuration options related to the preprocessor
-#---------------------------------------------------------------------------
-
-# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will
-# evaluate all C-preprocessor directives found in the sources and include
-# files.
-
-ENABLE_PREPROCESSING   = YES
-
-# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro
-# names in the source code. If set to NO (the default) only conditional
-# compilation will be performed. Macro expansion can be done in a controlled
-# way by setting EXPAND_ONLY_PREDEF to YES.
-
-MACRO_EXPANSION        = NO
-
-# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES
-# then the macro expansion is limited to the macros specified with the
-# PREDEFINED and EXPAND_AS_DEFINED tags.
-
-EXPAND_ONLY_PREDEF     = NO
-
-# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files
-# pointed to by INCLUDE_PATH will be searched when a #include is found.
-
-SEARCH_INCLUDES        = YES
-
-# The INCLUDE_PATH tag can be used to specify one or more directories that
-# contain include files that are not input files but should be processed by
-# the preprocessor.
-
-INCLUDE_PATH           =
-
-# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
-# patterns (like *.h and *.hpp) to filter out the header-files in the
-# directories. If left blank, the patterns specified with FILE_PATTERNS will
-# be used.
-
-INCLUDE_FILE_PATTERNS  =
-
-# The PREDEFINED tag can be used to specify one or more macro names that
-# are defined before the preprocessor is started (similar to the -D option of
-# gcc). The argument of the tag is a list of macros of the form: name
-# or name=definition (no spaces). If the definition and the = are
-# omitted =1 is assumed. To prevent a macro definition from being
-# undefined via #undef or recursively expanded use the := operator
-# instead of the = operator.
-
-PREDEFINED             =
-
-# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then
-# this tag can be used to specify a list of macro names that should be expanded.
-# The macro definition that is found in the sources will be used.
-# Use the PREDEFINED tag if you want to use a different macro definition that
-# overrules the definition found in the source code.
-
-EXPAND_AS_DEFINED      =
-
-# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then
-# doxygen's preprocessor will remove all references to function-like macros
-# that are alone on a line, have an all uppercase name, and do not end with a
-# semicolon, because these will confuse the parser if not removed.
-
-SKIP_FUNCTION_MACROS   = YES
-
-#---------------------------------------------------------------------------
-# Configuration::additions related to external references
-#---------------------------------------------------------------------------
-
-# The TAGFILES option can be used to specify one or more tagfiles. For each
-# tag file the location of the external documentation should be added. The
-# format of a tag file without this location is as follows:
-#   TAGFILES = file1 file2 ...
-# Adding location for the tag files is done as follows:
-#   TAGFILES = file1=loc1 "file2 = loc2" ...
-# where "loc1" and "loc2" can be relative or absolute paths
-# or URLs. Note that each tag file must have a unique name (where the name does
-# NOT include the path). If a tag file is not located in the directory in which
-# doxygen is run, you must also specify the path to the tagfile here.
-
-TAGFILES               =
-
-# When a file name is specified after GENERATE_TAGFILE, doxygen will create
-# a tag file that is based on the input files it reads.
-
-GENERATE_TAGFILE       =
-
-# If the ALLEXTERNALS tag is set to YES all external classes will be listed
-# in the class index. If set to NO only the inherited external classes
-# will be listed.
-
-ALLEXTERNALS           = NO
-
-# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed
-# in the modules index. If set to NO, only the current project's groups will
-# be listed.
-
-EXTERNAL_GROUPS        = YES
-
-# The PERL_PATH should be the absolute path and name of the perl script
-# interpreter (i.e. the result of `which perl').
-
-PERL_PATH              = /usr/bin/perl
-
-#---------------------------------------------------------------------------
-# Configuration options related to the dot tool
-#---------------------------------------------------------------------------
-
-# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will
-# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base
-# or super classes. Setting the tag to NO turns the diagrams off. Note that
-# this option also works with HAVE_DOT disabled, but it is recommended to
-# install and use dot, since it yields more powerful graphs.
-
-CLASS_DIAGRAMS         = NO
-
-# You can define message sequence charts within doxygen comments using the \msc
-# command. Doxygen will then run the mscgen tool (see
-# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the
-# documentation. The MSCGEN_PATH tag allows you to specify the directory where
-# the mscgen tool resides. If left empty the tool is assumed to be found in the
-# default search path.
-
-MSCGEN_PATH            =
-
-# If set to YES, the inheritance and collaboration graphs will hide
-# inheritance and usage relations if the target is undocumented
-# or is not a class.
-
-HIDE_UNDOC_RELATIONS   = YES
-
-# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
-# available from the path. This tool is part of Graphviz, a graph visualization
-# toolkit from AT&T and Lucent Bell Labs. The other options in this section
-# have no effect if this option is set to NO (the default)
-
-HAVE_DOT               = NO
-
-# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is
-# allowed to run in parallel. When set to 0 (the default) doxygen will
-# base this on the number of processors available in the system. You can set it
-# explicitly to a value larger than 0 to get control over the balance
-# between CPU load and processing speed.
-
-DOT_NUM_THREADS        = 0
-
-# By default doxygen will use the Helvetica font for all dot files that
-# doxygen generates. When you want a differently looking font you can specify
-# the font name using DOT_FONTNAME. You need to make sure dot is able to find
-# the font, which can be done by putting it in a standard location or by setting
-# the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the
-# directory containing the font.
-
-DOT_FONTNAME           = Helvetica
-
-# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs.
-# The default size is 10pt.
-
-DOT_FONTSIZE           = 10
-
-# By default doxygen will tell dot to use the Helvetica font.
-# If you specify a different font using DOT_FONTNAME you can use DOT_FONTPATH to
-# set the path where dot can find it.
-
-DOT_FONTPATH           =
-
-# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen
-# will generate a graph for each documented class showing the direct and
-# indirect inheritance relations. Setting this tag to YES will force the
-# CLASS_DIAGRAMS tag to NO.
-
-CLASS_GRAPH            = YES
-
-# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen
-# will generate a graph for each documented class showing the direct and
-# indirect implementation dependencies (inheritance, containment, and
-# class references variables) of the class with other documented classes.
-
-COLLABORATION_GRAPH    = YES
-
-# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen
-# will generate a graph for groups, showing the direct groups dependencies
-
-GROUP_GRAPHS           = YES
-
-# If the UML_LOOK tag is set to YES doxygen will generate inheritance and
-# collaboration diagrams in a style similar to the OMG's Unified Modeling
-# Language.
-
-UML_LOOK               = NO
-
-# If the UML_LOOK tag is enabled, the fields and methods are shown inside
-# the class node. If there are many fields or methods and many nodes the
-# graph may become too big to be useful. The UML_LIMIT_NUM_FIELDS
-# threshold limits the number of items for each type to make the size more
-# managable. Set this to 0 for no limit. Note that the threshold may be
-# exceeded by 50% before the limit is enforced.
-
-UML_LIMIT_NUM_FIELDS   = 10
-
-# If set to YES, the inheritance and collaboration graphs will show the
-# relations between templates and their instances.
-
-TEMPLATE_RELATIONS     = NO
-
-# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT
-# tags are set to YES then doxygen will generate a graph for each documented
-# file showing the direct and indirect include dependencies of the file with
-# other documented files.
-
-INCLUDE_GRAPH          = YES
-
-# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and
-# HAVE_DOT tags are set to YES then doxygen will generate a graph for each
-# documented header file showing the documented files that directly or
-# indirectly include this file.
-
-INCLUDED_BY_GRAPH      = YES
-
-# If the CALL_GRAPH and HAVE_DOT options are set to YES then
-# doxygen will generate a call dependency graph for every global function
-# or class method. Note that enabling this option will significantly increase
-# the time of a run. So in most cases it will be better to enable call graphs
-# for selected functions only using the \callgraph command.
-
-CALL_GRAPH             = NO
-
-# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then
-# doxygen will generate a caller dependency graph for every global function
-# or class method. Note that enabling this option will significantly increase
-# the time of a run. So in most cases it will be better to enable caller
-# graphs for selected functions only using the \callergraph command.
-
-CALLER_GRAPH           = NO
-
-# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen
-# will generate a graphical hierarchy of all classes instead of a textual one.
-
-GRAPHICAL_HIERARCHY    = YES
-
-# If the DIRECTORY_GRAPH and HAVE_DOT tags are set to YES
-# then doxygen will show the dependencies a directory has on other directories
-# in a graphical way. The dependency relations are determined by the #include
-# relations between the files in the directories.
-
-DIRECTORY_GRAPH        = YES
-
-# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
-# generated by dot. Possible values are svg, png, jpg, or gif.
-# If left blank png will be used. If you choose svg you need to set
-# HTML_FILE_EXTENSION to xhtml in order to make the SVG files
-# visible in IE 9+ (other browsers do not have this requirement).
-
-DOT_IMAGE_FORMAT       = png
-
-# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to
-# enable generation of interactive SVG images that allow zooming and panning.
-# Note that this requires a modern browser other than Internet Explorer.
-# Tested and working are Firefox, Chrome, Safari, and Opera. For IE 9+ you
-# need to set HTML_FILE_EXTENSION to xhtml in order to make the SVG files
-# visible. Older versions of IE do not have SVG support.
-
-INTERACTIVE_SVG        = NO
-
-# The tag DOT_PATH can be used to specify the path where the dot tool can be
-# found. If left blank, it is assumed the dot tool can be found in the path.
-
-DOT_PATH               =
-
-# The DOTFILE_DIRS tag can be used to specify one or more directories that
-# contain dot files that are included in the documentation (see the
-# \dotfile command).
-
-DOTFILE_DIRS           =
-
-# The MSCFILE_DIRS tag can be used to specify one or more directories that
-# contain msc files that are included in the documentation (see the
-# \mscfile command).
-
-MSCFILE_DIRS           =
-
-# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of
-# nodes that will be shown in the graph. If the number of nodes in a graph
-# becomes larger than this value, doxygen will truncate the graph, which is
-# visualized by representing a node as a red box. Note that doxygen if the
-# number of direct children of the root node in a graph is already larger than
-# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note
-# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
-
-DOT_GRAPH_MAX_NODES    = 50
-
-# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the
-# graphs generated by dot. A depth value of 3 means that only nodes reachable
-# from the root by following a path via at most 3 edges will be shown. Nodes
-# that lay further from the root node will be omitted. Note that setting this
-# option to 1 or 2 may greatly reduce the computation time needed for large
-# code bases. Also note that the size of a graph can be further restricted by
-# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
-
-MAX_DOT_GRAPH_DEPTH    = 0
-
-# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
-# background. This is disabled by default, because dot on Windows does not
-# seem to support this out of the box. Warning: Depending on the platform used,
-# enabling this option may lead to badly anti-aliased labels on the edges of
-# a graph (i.e. they become hard to read).
-
-DOT_TRANSPARENT        = NO
-
-# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output
-# files in one run (i.e. multiple -o and -T options on the command line). This
-# makes dot run faster, but since only newer versions of dot (>1.8.10)
-# support this, this feature is disabled by default.
-
-DOT_MULTI_TARGETS      = NO
-
-# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will
-# generate a legend page explaining the meaning of the various boxes and
-# arrows in the dot generated graphs.
-
-GENERATE_LEGEND        = YES
-
-# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will
-# remove the intermediate dot files that are used to generate
-# the various graphs.
-
-DOT_CLEANUP            = YES
diff --git a/resource/docs/c-doc/Doxyfile b/resource/docs/c-doc/Doxyfile
new file mode 100644 (file)
index 0000000..92144a3
--- /dev/null
@@ -0,0 +1,1844 @@
+# Doxyfile 1.8.2
+
+# This file describes the settings to be used by the documentation system
+# doxygen (www.doxygen.org) for a project
+#
+# All text after a hash (#) is considered a comment and will be ignored
+# The format is:
+#       TAG = value [value, ...]
+# For lists items can also be appended using:
+#       TAG += value [value, ...]
+# Values that contain spaces should be placed between quotes (" ")
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+
+# This tag specifies the encoding used for all characters in the config file
+# that follow. The default is UTF-8 which is also the encoding used for all
+# text before the first occurrence of this tag. Doxygen uses libiconv (or the
+# iconv built into libc) for the transcoding. See
+# http://www.gnu.org/software/libiconv for the list of possible encodings.
+
+DOXYFILE_ENCODING      = UTF-8
+
+# The PROJECT_NAME tag is a single word (or sequence of words) that should
+# identify the project. Note that if you do not use Doxywizard you need
+# to put quotes around the project name if it contains spaces.
+
+PROJECT_NAME           = "IoTivity C SDK"
+
+# The PROJECT_NUMBER tag can be used to enter a project or revision number.
+# This could be handy for archiving the generated documentation or
+# if some version control system is used.
+
+PROJECT_NUMBER         =
+
+# Using the PROJECT_BRIEF tag one can provide an optional one line description
+# for a project that appears at the top of each page and should give viewer
+# a quick idea about the purpose of the project. Keep the description short.
+
+PROJECT_BRIEF          =
+
+# With the PROJECT_LOGO tag one can specify an logo or icon that is
+# included in the documentation. The maximum height of the logo should not
+# exceed 55 pixels and the maximum width should not exceed 200 pixels.
+# Doxygen will copy the logo to the output directory.
+
+PROJECT_LOGO           =
+
+# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute)
+# base path where the generated documentation will be put.
+# If a relative path is entered, it will be relative to the location
+# where doxygen was started. If left blank the current directory will be used.
+
+OUTPUT_DIRECTORY       = docs
+
+# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create
+# 4096 sub-directories (in 2 levels) under the output directory of each output
+# format and will distribute the generated files over these directories.
+# Enabling this option can be useful when feeding doxygen a huge amount of
+# source files, where putting all generated files in the same directory would
+# otherwise cause performance problems for the file system.
+
+CREATE_SUBDIRS         = NO
+
+# The OUTPUT_LANGUAGE tag is used to specify the language in which all
+# documentation generated by doxygen is written. Doxygen will use this
+# information to generate all constant output in the proper language.
+# The default language is English, other supported languages are:
+# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional,
+# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German,
+# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English
+# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian,
+# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak,
+# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese.
+
+OUTPUT_LANGUAGE        = English
+
+# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will
+# include brief member descriptions after the members that are listed in
+# the file and class documentation (similar to JavaDoc).
+# Set to NO to disable this.
+
+BRIEF_MEMBER_DESC      = YES
+
+# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend
+# the brief description of a member or function before the detailed description.
+# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
+# brief descriptions will be completely suppressed.
+
+REPEAT_BRIEF           = YES
+
+# This tag implements a quasi-intelligent brief description abbreviator
+# that is used to form the text in various listings. Each string
+# in this list, if found as the leading text of the brief description, will be
+# stripped from the text and the result after processing the whole list, is
+# used as the annotated text. Otherwise, the brief description is used as-is.
+# If left blank, the following values are used ("$name" is automatically
+# replaced with the name of the entity): "The $name class" "The $name widget"
+# "The $name file" "is" "provides" "specifies" "contains"
+# "represents" "a" "an" "the"
+
+ABBREVIATE_BRIEF       = "The $name class" \
+                         "The $name widget" \
+                         "The $name file" \
+                         is \
+                         provides \
+                         specifies \
+                         contains \
+                         represents \
+                         a \
+                         an \
+                         the
+
+# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
+# Doxygen will generate a detailed section even if there is only a brief
+# description.
+
+ALWAYS_DETAILED_SEC    = NO
+
+# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
+# inherited members of a class in the documentation of that class as if those
+# members were ordinary class members. Constructors, destructors and assignment
+# operators of the base classes will not be shown.
+
+INLINE_INHERITED_MEMB  = NO
+
+# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full
+# path before files name in the file list and in the header files. If set
+# to NO the shortest path that makes the file name unique will be used.
+
+FULL_PATH_NAMES        = NO
+
+# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag
+# can be used to strip a user-defined part of the path. Stripping is
+# only done if one of the specified strings matches the left-hand part of
+# the path. The tag can be used to show relative paths in the file list.
+# If left blank the directory from which doxygen is run is used as the
+# path to strip. Note that you specify absolute paths here, but also
+# relative paths, which will be relative from the directory where doxygen is
+# started.
+
+STRIP_FROM_PATH        =
+
+# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of
+# the path mentioned in the documentation of a class, which tells
+# the reader which header file to include in order to use a class.
+# If left blank only the name of the header file containing the class
+# definition is used. Otherwise one should specify the include paths that
+# are normally passed to the compiler using the -I flag.
+
+STRIP_FROM_INC_PATH    =
+
+# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter
+# (but less readable) file names. This can be useful if your file system
+# doesn't support long names like on DOS, Mac, or CD-ROM.
+
+SHORT_NAMES            = NO
+
+# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen
+# will interpret the first line (until the first dot) of a JavaDoc-style
+# comment as the brief description. If set to NO, the JavaDoc
+# comments will behave just like regular Qt-style comments
+# (thus requiring an explicit @brief command for a brief description.)
+
+JAVADOC_AUTOBRIEF      = YES
+
+# If the QT_AUTOBRIEF tag is set to YES then Doxygen will
+# interpret the first line (until the first dot) of a Qt-style
+# comment as the brief description. If set to NO, the comments
+# will behave just like regular Qt-style comments (thus requiring
+# an explicit \brief command for a brief description.)
+
+QT_AUTOBRIEF           = NO
+
+# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen
+# treat a multi-line C++ special comment block (i.e. a block of //! or ///
+# comments) as a brief description. This used to be the default behaviour.
+# The new default is to treat a multi-line C++ comment block as a detailed
+# description. Set this tag to YES if you prefer the old behaviour instead.
+
+MULTILINE_CPP_IS_BRIEF = NO
+
+# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented
+# member inherits the documentation from any documented member that it
+# re-implements.
+
+INHERIT_DOCS           = YES
+
+# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce
+# a new page for each member. If set to NO, the documentation of a member will
+# be part of the file/class/namespace that contains it.
+
+SEPARATE_MEMBER_PAGES  = NO
+
+# The TAB_SIZE tag can be used to set the number of spaces in a tab.
+# Doxygen uses this value to replace tabs by spaces in code fragments.
+
+TAB_SIZE               = 8
+
+# This tag can be used to specify a number of aliases that acts
+# as commands in the documentation. An alias has the form "name=value".
+# For example adding "sideeffect=\par Side Effects:\n" will allow you to
+# put the command \sideeffect (or @sideeffect) in the documentation, which
+# will result in a user-defined paragraph with heading "Side Effects:".
+# You can put \n's in the value part of an alias to insert newlines.
+
+ALIASES                =
+
+# This tag can be used to specify a number of word-keyword mappings (TCL only).
+# A mapping has the form "name=value". For example adding
+# "class=itcl::class" will allow you to use the command class in the
+# itcl::class meaning.
+
+TCL_SUBST              =
+
+# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C
+# sources only. Doxygen will then generate output that is more tailored for C.
+# For instance, some of the names that are used will be different. The list
+# of all members will be omitted, etc.
+
+OPTIMIZE_OUTPUT_FOR_C  = NO
+
+# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java
+# sources only. Doxygen will then generate output that is more tailored for
+# Java. For instance, namespaces will be presented as packages, qualified
+# scopes will look different, etc.
+
+OPTIMIZE_OUTPUT_JAVA   = NO
+
+# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
+# sources only. Doxygen will then generate output that is more tailored for
+# Fortran.
+
+OPTIMIZE_FOR_FORTRAN   = NO
+
+# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
+# sources. Doxygen will then generate output that is tailored for
+# VHDL.
+
+OPTIMIZE_OUTPUT_VHDL   = NO
+
+# Doxygen selects the parser to use depending on the extension of the files it
+# parses. With this tag you can assign which parser to use for a given
+# extension. Doxygen has a built-in mapping, but you can override or extend it
+# using this tag. The format is ext=language, where ext is a file extension,
+# and language is one of the parsers supported by doxygen: IDL, Java,
+# Javascript, CSharp, C, C++, D, PHP, Objective-C, Python, Fortran, VHDL, C,
+# C++. For instance to make doxygen treat .inc files as Fortran files (default
+# is PHP), and .f files as C (default is Fortran), use: inc=Fortran f=C. Note
+# that for custom extensions you also need to set FILE_PATTERNS otherwise the
+# files are not read by doxygen.
+
+EXTENSION_MAPPING      =
+
+# If MARKDOWN_SUPPORT is enabled (the default) then doxygen pre-processes all
+# comments according to the Markdown format, which allows for more readable
+# documentation. See http://daringfireball.net/projects/markdown/ for details.
+# The output of markdown processing is further processed by doxygen, so you
+# can mix doxygen, HTML, and XML commands with Markdown formatting.
+# Disable only in case of backward compatibilities issues.
+
+MARKDOWN_SUPPORT       = YES
+
+# When enabled doxygen tries to link words that correspond to documented classes,
+# or namespaces to their corresponding documentation. Such a link can be
+# prevented in individual cases by by putting a % sign in front of the word or
+# globally by setting AUTOLINK_SUPPORT to NO.
+
+AUTOLINK_SUPPORT       = YES
+
+# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
+# to include (a tag file for) the STL sources as input, then you should
+# set this tag to YES in order to let doxygen match functions declarations and
+# definitions whose arguments contain STL classes (e.g. func(std::string); v.s.
+# func(std::string) {}). This also makes the inheritance and collaboration
+# diagrams that involve STL classes more complete and accurate.
+
+BUILTIN_STL_SUPPORT    = NO
+
+# If you use Microsoft's C++/CLI language, you should set this option to YES to
+# enable parsing support.
+
+CPP_CLI_SUPPORT        = NO
+
+# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only.
+# Doxygen will parse them like normal C++ but will assume all classes use public
+# instead of private inheritance when no explicit protection keyword is present.
+
+SIP_SUPPORT            = NO
+
+# For Microsoft's IDL there are propget and propput attributes to indicate
+# getter and setter methods for a property. Setting this option to YES (the
+# default) will make doxygen replace the get and set methods by a property in
+# the documentation. This will only work if the methods are indeed getting or
+# setting a simple type. If this is not the case, or you want to show the
+# methods anyway, you should set this option to NO.
+
+IDL_PROPERTY_SUPPORT   = YES
+
+# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
+# tag is set to YES, then doxygen will reuse the documentation of the first
+# member in the group (if any) for the other members of the group. By default
+# all members of a group must be documented explicitly.
+
+DISTRIBUTE_GROUP_DOC   = NO
+
+# Set the SUBGROUPING tag to YES (the default) to allow class member groups of
+# the same type (for instance a group of public functions) to be put as a
+# subgroup of that type (e.g. under the Public Functions section). Set it to
+# NO to prevent subgrouping. Alternatively, this can be done per class using
+# the \nosubgrouping command.
+
+SUBGROUPING            = YES
+
+# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and
+# unions are shown inside the group in which they are included (e.g. using
+# @ingroup) instead of on a separate page (for HTML and Man pages) or
+# section (for LaTeX and RTF).
+
+INLINE_GROUPED_CLASSES = NO
+
+# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and
+# unions with only public data fields will be shown inline in the documentation
+# of the scope in which they are defined (i.e. file, namespace, or group
+# documentation), provided this scope is documented. If set to NO (the default),
+# structs, classes, and unions are shown on a separate page (for HTML and Man
+# pages) or section (for LaTeX and RTF).
+
+INLINE_SIMPLE_STRUCTS  = NO
+
+# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum
+# is documented as struct, union, or enum with the name of the typedef. So
+# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
+# with name TypeT. When disabled the typedef will appear as a member of a file,
+# namespace, or class. And the struct will be named TypeS. This can typically
+# be useful for C code in case the coding convention dictates that all compound
+# types are typedef'ed and only the typedef is referenced, never the tag name.
+
+TYPEDEF_HIDES_STRUCT   = NO
+
+# Similar to the SYMBOL_CACHE_SIZE the size of the symbol lookup cache can be
+# set using LOOKUP_CACHE_SIZE. This cache is used to resolve symbols given
+# their name and scope. Since this can be an expensive process and often the
+# same symbol appear multiple times in the code, doxygen keeps a cache of
+# pre-resolved symbols. If the cache is too small doxygen will become slower.
+# If the cache is too large, memory is wasted. The cache size is given by this
+# formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range is 0..9, the default is 0,
+# corresponding to a cache size of 2^16 = 65536 symbols.
+
+LOOKUP_CACHE_SIZE      = 0
+
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+
+# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
+# documentation are documented, even if no documentation was available.
+# Private class members and static file members will be hidden unless
+# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES
+
+EXTRACT_ALL            = YES
+
+# If the EXTRACT_PRIVATE tag is set to YES all private members of a class
+# will be included in the documentation.
+
+EXTRACT_PRIVATE        = NO
+
+# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal
+# scope will be included in the documentation.
+
+EXTRACT_PACKAGE        = NO
+
+# If the EXTRACT_STATIC tag is set to YES all static members of a file
+# will be included in the documentation.
+
+EXTRACT_STATIC         = NO
+
+# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs)
+# defined locally in source files will be included in the documentation.
+# If set to NO only classes defined in header files are included.
+
+EXTRACT_LOCAL_CLASSES  = YES
+
+# This flag is only useful for Objective-C code. When set to YES local
+# methods, which are defined in the implementation section but not in
+# the interface are included in the documentation.
+# If set to NO (the default) only methods in the interface are included.
+
+EXTRACT_LOCAL_METHODS  = NO
+
+# If this flag is set to YES, the members of anonymous namespaces will be
+# extracted and appear in the documentation as a namespace called
+# 'anonymous_namespace{file}', where file will be replaced with the base
+# name of the file that contains the anonymous namespace. By default
+# anonymous namespaces are hidden.
+
+EXTRACT_ANON_NSPACES   = NO
+
+# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all
+# undocumented members of documented classes, files or namespaces.
+# If set to NO (the default) these members will be included in the
+# various overviews, but no documentation section is generated.
+# This option has no effect if EXTRACT_ALL is enabled.
+
+HIDE_UNDOC_MEMBERS     = NO
+
+# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all
+# undocumented classes that are normally visible in the class hierarchy.
+# If set to NO (the default) these classes will be included in the various
+# overviews. This option has no effect if EXTRACT_ALL is enabled.
+
+HIDE_UNDOC_CLASSES     = NO
+
+# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all
+# friend (class|struct|union) declarations.
+# If set to NO (the default) these declarations will be included in the
+# documentation.
+
+HIDE_FRIEND_COMPOUNDS  = NO
+
+# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any
+# documentation blocks found inside the body of a function.
+# If set to NO (the default) these blocks will be appended to the
+# function's detailed documentation block.
+
+HIDE_IN_BODY_DOCS      = NO
+
+# The INTERNAL_DOCS tag determines if documentation
+# that is typed after a \internal command is included. If the tag is set
+# to NO (the default) then the documentation will be excluded.
+# Set it to YES to include the internal documentation.
+
+INTERNAL_DOCS          = NO
+
+# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate
+# file names in lower-case letters. If set to YES upper-case letters are also
+# allowed. This is useful if you have classes or files whose names only differ
+# in case and if your file system supports case sensitive file names. Windows
+# and Mac users are advised to set this option to NO.
+
+CASE_SENSE_NAMES       = NO
+
+# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen
+# will show members with their full class and namespace scopes in the
+# documentation. If set to YES the scope will be hidden.
+
+HIDE_SCOPE_NAMES       = NO
+
+# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen
+# will put a list of the files that are included by a file in the documentation
+# of that file.
+
+SHOW_INCLUDE_FILES     = NO
+
+# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen
+# will list include files with double quotes in the documentation
+# rather than with sharp brackets.
+
+FORCE_LOCAL_INCLUDES   = NO
+
+# If the INLINE_INFO tag is set to YES (the default) then a tag [inline]
+# is inserted in the documentation for inline members.
+
+INLINE_INFO            = YES
+
+# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen
+# will sort the (detailed) documentation of file and class members
+# alphabetically by member name. If set to NO the members will appear in
+# declaration order.
+
+SORT_MEMBER_DOCS       = YES
+
+# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the
+# brief documentation of file, namespace and class members alphabetically
+# by member name. If set to NO (the default) the members will appear in
+# declaration order.
+
+SORT_BRIEF_DOCS        = NO
+
+# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen
+# will sort the (brief and detailed) documentation of class members so that
+# constructors and destructors are listed first. If set to NO (the default)
+# the constructors will appear in the respective orders defined by
+# SORT_MEMBER_DOCS and SORT_BRIEF_DOCS.
+# This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO
+# and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO.
+
+SORT_MEMBERS_CTORS_1ST = NO
+
+# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the
+# hierarchy of group names into alphabetical order. If set to NO (the default)
+# the group names will appear in their defined order.
+
+SORT_GROUP_NAMES       = NO
+
+# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be
+# sorted by fully-qualified names, including namespaces. If set to
+# NO (the default), the class list will be sorted only by class name,
+# not including the namespace part.
+# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
+# Note: This option applies only to the class list, not to the
+# alphabetical list.
+
+SORT_BY_SCOPE_NAME     = NO
+
+# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to
+# do proper type resolution of all parameters of a function it will reject a
+# match between the prototype and the implementation of a member function even
+# if there is only one candidate or it is obvious which candidate to choose
+# by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen
+# will still accept a match between prototype and implementation in such cases.
+
+STRICT_PROTO_MATCHING  = NO
+
+# The GENERATE_TODOLIST tag can be used to enable (YES) or
+# disable (NO) the todo list. This list is created by putting \todo
+# commands in the documentation.
+
+GENERATE_TODOLIST      = YES
+
+# The GENERATE_TESTLIST tag can be used to enable (YES) or
+# disable (NO) the test list. This list is created by putting \test
+# commands in the documentation.
+
+GENERATE_TESTLIST      = YES
+
+# The GENERATE_BUGLIST tag can be used to enable (YES) or
+# disable (NO) the bug list. This list is created by putting \bug
+# commands in the documentation.
+
+GENERATE_BUGLIST       = YES
+
+# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or
+# disable (NO) the deprecated list. This list is created by putting
+# \deprecated commands in the documentation.
+
+GENERATE_DEPRECATEDLIST= YES
+
+# The ENABLED_SECTIONS tag can be used to enable conditional
+# documentation sections, marked by \if sectionname ... \endif.
+
+ENABLED_SECTIONS       =
+
+# The MAX_INITIALIZER_LINES tag determines the maximum number of lines
+# the initial value of a variable or macro consists of for it to appear in
+# the documentation. If the initializer consists of more lines than specified
+# here it will be hidden. Use a value of 0 to hide initializers completely.
+# The appearance of the initializer of individual variables and macros in the
+# documentation can be controlled using \showinitializer or \hideinitializer
+# command in the documentation regardless of this setting.
+
+MAX_INITIALIZER_LINES  = 125
+
+# Set the SHOW_USED_FILES tag to NO to disable the list of files generated
+# at the bottom of the documentation of classes and structs. If set to YES the
+# list will mention the files that were used to generate the documentation.
+
+SHOW_USED_FILES        = YES
+
+# Set the SHOW_FILES tag to NO to disable the generation of the Files page.
+# This will remove the Files entry from the Quick Index and from the
+# Folder Tree View (if specified). The default is YES.
+
+SHOW_FILES             = YES
+
+# Set the SHOW_NAMESPACES tag to NO to disable the generation of the
+# Namespaces page.  This will remove the Namespaces entry from the Quick Index
+# and from the Folder Tree View (if specified). The default is YES.
+
+SHOW_NAMESPACES        = YES
+
+# The FILE_VERSION_FILTER tag can be used to specify a program or script that
+# doxygen should invoke to get the current version for each file (typically from
+# the version control system). Doxygen will invoke the program by executing (via
+# popen()) the command <command> <input-file>, where <command> is the value of
+# the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file
+# provided by doxygen. Whatever the program writes to standard output
+# is used as the file version. See the manual for examples.
+
+FILE_VERSION_FILTER    =
+
+# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
+# by doxygen. The layout file controls the global structure of the generated
+# output files in an output format independent way. To create the layout file
+# that represents doxygen's defaults, run doxygen with the -l option.
+# You can optionally specify a file name after the option, if omitted
+# DoxygenLayout.xml will be used as the name of the layout file.
+
+LAYOUT_FILE            = doxygenLayout.xml
+
+# The CITE_BIB_FILES tag can be used to specify one or more bib files
+# containing the references data. This must be a list of .bib files. The
+# .bib extension is automatically appended if omitted. Using this command
+# requires the bibtex tool to be installed. See also
+# http://en.wikipedia.org/wiki/BibTeX for more info. For LaTeX the style
+# of the bibliography can be controlled using LATEX_BIB_STYLE. To use this
+# feature you need bibtex and perl available in the search path.
+
+CITE_BIB_FILES         =
+
+#---------------------------------------------------------------------------
+# configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+
+# The QUIET tag can be used to turn on/off the messages that are generated
+# by doxygen. Possible values are YES and NO. If left blank NO is used.
+
+QUIET                  = NO
+
+# The WARNINGS tag can be used to turn on/off the warning messages that are
+# generated by doxygen. Possible values are YES and NO. If left blank
+# NO is used.
+
+WARNINGS               = YES
+
+# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings
+# for undocumented members. If EXTRACT_ALL is set to YES then this flag will
+# automatically be disabled.
+
+WARN_IF_UNDOCUMENTED   = YES
+
+# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for
+# potential errors in the documentation, such as not documenting some
+# parameters in a documented function, or documenting parameters that
+# don't exist or using markup commands wrongly.
+
+WARN_IF_DOC_ERROR      = YES
+
+# The WARN_NO_PARAMDOC option can be enabled to get warnings for
+# functions that are documented, but have no documentation for their parameters
+# or return value. If set to NO (the default) doxygen will only warn about
+# wrong or incomplete parameter documentation, but not about the absence of
+# documentation.
+
+WARN_NO_PARAMDOC       = NO
+
+# The WARN_FORMAT tag determines the format of the warning messages that
+# doxygen can produce. The string should contain the $file, $line, and $text
+# tags, which will be replaced by the file and line number from which the
+# warning originated and the warning text. Optionally the format may contain
+# $version, which will be replaced by the version of the file (if it could
+# be obtained via FILE_VERSION_FILTER)
+
+WARN_FORMAT            = "$file:$line: $text"
+
+# The WARN_LOGFILE tag can be used to specify a file to which warning
+# and error messages should be written. If left blank the output is written
+# to stderr.
+
+WARN_LOGFILE           = ./doxygen.log
+
+#---------------------------------------------------------------------------
+# configuration options related to the input files
+#---------------------------------------------------------------------------
+
+# The INPUT tag can be used to specify the files and/or directories that contain
+# documented source files. You may enter file names like "myfile.cpp" or
+# directories like "/usr/src/myproject". Separate the files or directories
+# with spaces.
+
+INPUT                  = . \
+                        ../../csdk/security/provisioning/include/ocprovisioningmanager.h \
+                        ../../csdk/security/provisioning/include/pmtypes.h \
+                        ../../csdk/security/provisioning/include/pmutility.h \
+                        ../../csdk/stack/include/ocstack.h \
+                        ../../csdk/stack/include/octypes.h \
+                        ../../csdk/stack/include/ocpayload.h \
+                        ../../csdk/stack/include/ocpresence.h \
+                        ../../csdk/stack/include/rdpayload.h \
+                        ../../csdk/stack/include/payload_logging.h \
+                         ../../csdk/stack/include/ocstackconfig.h \
+                         ../../csdk/stack/include/internal/occlientcb.h \
+                         ../../csdk/stack/include/internal/occollection.h \
+                         ../../csdk/stack/include/internal/ocobserve.h \
+                         ../../csdk/stack/include/internal/ocpayloadcbor.h \
+                         ../../csdk/stack/include/internal/ocresource.h \
+                         ../../csdk/stack/include/internal/ocresourcehandler.h \
+                         ../../csdk/stack/include/internal/ocserverrequest.h \
+                         ../../csdk/stack/include/internal/ocstackinternal.h \
+                         ../../csdk/stack/include/internal/oicgroup.h \
+                         ../../csdk/stack/include/internal/oickeepalive.h \
+                         guides \
+                         ../../../service/easy-setup/enrollee/inc \
+                         ../../../service/easy-setup/enrollee/src/softap.h \
+                         ../../../service/resource-directory/include \
+
+
+# This tag can be used to specify the character encoding of the source files
+# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is
+# also the default input encoding. Doxygen uses libiconv (or the iconv built
+# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for
+# the list of possible encodings.
+
+INPUT_ENCODING         = UTF-8
+
+# If the value of the INPUT tag contains directories, you can use the
+# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
+# and *.h) to filter out the source-files in the directories. If left
+# blank the following patterns are tested:
+# *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh
+# *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py
+# *.f90 *.f *.for *.vhd *.vhdl
+
+FILE_PATTERNS          = *.c \
+                         *.cc \
+                         *.cxx \
+                         *.cpp \
+                         *.c++ \
+                         *.d \
+                         *.java \
+                         *.ii \
+                         *.ixx \
+                         *.ipp \
+                         *.i++ \
+                         *.inl \
+                         *.h \
+                         *.hh \
+                         *.hxx \
+                         *.hpp \
+                         *.h++ \
+                         *.idl \
+                         *.odl \
+                         *.cs \
+                         *.php \
+                         *.php3 \
+                         *.inc \
+                         *.m \
+                         *.markdown \
+                         *.md \
+                         *.mm \
+                         *.dox \
+                         *.py \
+                         *.f90 \
+                         *.f \
+                         *.for \
+                         *.vhd \
+                         *.vhdl \
+                         *.txt
+
+# The RECURSIVE tag can be used to turn specify whether or not subdirectories
+# should be searched for input files as well. Possible values are YES and NO.
+# If left blank NO is used.
+
+RECURSIVE              = NO
+
+# The EXCLUDE tag can be used to specify files and/or directories that should be
+# excluded from the INPUT source files. This way you can easily exclude a
+# subdirectory from a directory tree whose root is specified with the INPUT tag.
+# Note that relative paths are relative to the directory from which doxygen is
+# run.
+
+EXCLUDE                =
+
+# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
+# directories that are symbolic links (a Unix file system feature) are excluded
+# from the input.
+
+EXCLUDE_SYMLINKS       = NO
+
+# If the value of the INPUT tag contains directories, you can use the
+# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
+# certain files from those directories. Note that the wildcards are matched
+# against the file with absolute path, so to exclude all test directories
+# for example use the pattern */test/*
+
+EXCLUDE_PATTERNS       =
+
+# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
+# (namespaces, classes, functions, etc.) that should be excluded from the
+# output. The symbol name can be a fully qualified name, a word, or if the
+# wildcard * is used, a substring. Examples: ANamespace, AClass,
+# AClass::ANamespace, ANamespace::*Test
+
+EXCLUDE_SYMBOLS        =
+
+# The EXAMPLE_PATH tag can be used to specify one or more files or
+# directories that contain example code fragments that are included (see
+# the \include command).
+
+EXAMPLE_PATH           =
+
+# If the value of the EXAMPLE_PATH tag contains directories, you can use the
+# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
+# and *.h) to filter out the source-files in the directories. If left
+# blank all files are included.
+
+EXAMPLE_PATTERNS       = *
+
+# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
+# searched for input files to be used with the \include or \dontinclude
+# commands irrespective of the value of the RECURSIVE tag.
+# Possible values are YES and NO. If left blank NO is used.
+
+EXAMPLE_RECURSIVE      = NO
+
+# The IMAGE_PATH tag can be used to specify one or more files or
+# directories that contain image that are included in the documentation (see
+# the \image command).
+
+IMAGE_PATH             = img
+
+# The INPUT_FILTER tag can be used to specify a program that doxygen should
+# invoke to filter for each input file. Doxygen will invoke the filter program
+# by executing (via popen()) the command <filter> <input-file>, where <filter>
+# is the value of the INPUT_FILTER tag, and <input-file> is the name of an
+# input file. Doxygen will then use the output that the filter program writes
+# to standard output.  If FILTER_PATTERNS is specified, this tag will be
+# ignored.
+
+INPUT_FILTER           =
+
+# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
+# basis.  Doxygen will compare the file name with each pattern and apply the
+# filter if there is a match.  The filters are a list of the form:
+# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further
+# info on how filters are used. If FILTER_PATTERNS is empty or if
+# non of the patterns match the file name, INPUT_FILTER is applied.
+
+FILTER_PATTERNS        =
+
+# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
+# INPUT_FILTER) will be used to filter the input files when producing source
+# files to browse (i.e. when SOURCE_BROWSER is set to YES).
+
+FILTER_SOURCE_FILES    = NO
+
+# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
+# pattern. A pattern will override the setting for FILTER_PATTERN (if any)
+# and it is also possible to disable source filtering for a specific pattern
+# using *.ext= (so without naming a filter). This option only has effect when
+# FILTER_SOURCE_FILES is enabled.
+
+FILTER_SOURCE_PATTERNS =
+
+#---------------------------------------------------------------------------
+# configuration options related to source browsing
+#---------------------------------------------------------------------------
+
+# If the SOURCE_BROWSER tag is set to YES then a list of source files will
+# be generated. Documented entities will be cross-referenced with these sources.
+# Note: To get rid of all source code in the generated output, make sure also
+# VERBATIM_HEADERS is set to NO.
+
+SOURCE_BROWSER         = NO
+
+# Setting the INLINE_SOURCES tag to YES will include the body
+# of functions and classes directly in the documentation.
+
+INLINE_SOURCES         = NO
+
+# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct
+# doxygen to hide any special comment blocks from generated source code
+# fragments. Normal C, C++ and Fortran comments will always remain visible.
+
+STRIP_CODE_COMMENTS    = YES
+
+# If the REFERENCED_BY_RELATION tag is set to YES
+# then for each documented function all documented
+# functions referencing it will be listed.
+
+REFERENCED_BY_RELATION = NO
+
+# If the REFERENCES_RELATION tag is set to YES
+# then for each documented function all documented entities
+# called/used by that function will be listed.
+
+REFERENCES_RELATION    = NO
+
+# If the REFERENCES_LINK_SOURCE tag is set to YES (the default)
+# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from
+# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will
+# link to the source code.  Otherwise they will link to the documentation.
+
+REFERENCES_LINK_SOURCE = YES
+
+# If the USE_HTAGS tag is set to YES then the references to source code
+# will point to the HTML generated by the htags(1) tool instead of doxygen
+# built-in source browser. The htags tool is part of GNU's global source
+# tagging system (see http://www.gnu.org/software/global/global.html). You
+# will need version 4.8.6 or higher.
+
+USE_HTAGS              = NO
+
+# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen
+# will generate a verbatim copy of the header file for each class for
+# which an include is specified. Set to NO to disable this.
+
+VERBATIM_HEADERS       = YES
+
+#---------------------------------------------------------------------------
+# configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+
+# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index
+# of all compounds will be generated. Enable this if the project
+# contains a lot of classes, structs, unions or interfaces.
+
+ALPHABETICAL_INDEX     = YES
+
+# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then
+# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns
+# in which this list will be split (can be a number in the range [1..20])
+
+COLS_IN_ALPHA_INDEX    = 5
+
+# In case all classes in a project start with a common prefix, all
+# classes will be put under the same header in the alphabetical index.
+# The IGNORE_PREFIX tag can be used to specify one or more prefixes that
+# should be ignored while generating the index headers.
+
+IGNORE_PREFIX          =
+
+#---------------------------------------------------------------------------
+# configuration options related to the HTML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_HTML tag is set to YES (the default) Doxygen will
+# generate HTML output.
+
+GENERATE_HTML          = YES
+
+# The HTML_OUTPUT tag is used to specify where the HTML docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `html' will be used as the default path.
+
+HTML_OUTPUT            = html
+
+# The HTML_FILE_EXTENSION tag can be used to specify the file extension for
+# each generated HTML page (for example: .htm,.php,.asp). If it is left blank
+# doxygen will generate files with .html extension.
+
+HTML_FILE_EXTENSION    = .html
+
+# The HTML_HEADER tag can be used to specify a personal HTML header for
+# each generated HTML page. If it is left blank doxygen will generate a
+# standard header. Note that when using a custom header you are responsible
+# for the proper inclusion of any scripts and style sheets that doxygen
+# needs, which is dependent on the configuration options used.
+# It is advised to generate a default header using "doxygen -w html
+# header.html footer.html stylesheet.css YourConfigFile" and then modify
+# that header. Note that the header is subject to change so you typically
+# have to redo this when upgrading to a newer version of doxygen or when
+# changing the value of configuration settings such as GENERATE_TREEVIEW!
+
+HTML_HEADER            =
+
+# The HTML_FOOTER tag can be used to specify a personal HTML footer for
+# each generated HTML page. If it is left blank doxygen will generate a
+# standard footer.
+
+HTML_FOOTER            = html/footer.html
+
+# The HTML_STYLESHEET tag can be used to specify a user-defined cascading
+# style sheet that is used by each HTML page. It can be used to
+# fine-tune the look of the HTML output. If left blank doxygen will
+# generate a default style sheet. Note that it is recommended to use
+# HTML_EXTRA_STYLESHEET instead of this one, as it is more robust and this
+# tag will in the future become obsolete.
+
+HTML_STYLESHEET        =
+
+# The HTML_EXTRA_STYLESHEET tag can be used to specify an additional
+# user-defined cascading style sheet that is included after the standard
+# style sheets created by doxygen. Using this option one can overrule
+# certain style aspects. This is preferred over using HTML_STYLESHEET
+# since it does not replace the standard style sheet and is therefor more
+# robust against future updates. Doxygen will copy the style sheet file to
+# the output directory.
+
+HTML_EXTRA_STYLESHEET  =
+
+# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
+# other source files which should be copied to the HTML output directory. Note
+# that these files will be copied to the base HTML output directory. Use the
+# $relpath$ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
+# files. In the HTML_STYLESHEET file, use the file name only. Also note that
+# the files will be copied as-is; there are no commands or markers available.
+
+HTML_EXTRA_FILES       =
+
+# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output.
+# Doxygen will adjust the colors in the style sheet and background images
+# according to this color. Hue is specified as an angle on a colorwheel,
+# see http://en.wikipedia.org/wiki/Hue for more information.
+# For instance the value 0 represents red, 60 is yellow, 120 is green,
+# 180 is cyan, 240 is blue, 300 purple, and 360 is red again.
+# The allowed range is 0 to 359.
+
+HTML_COLORSTYLE_HUE    = 220
+
+# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of
+# the colors in the HTML output. For a value of 0 the output will use
+# grayscales only. A value of 255 will produce the most vivid colors.
+
+HTML_COLORSTYLE_SAT    = 100
+
+# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to
+# the luminance component of the colors in the HTML output. Values below
+# 100 gradually make the output lighter, whereas values above 100 make
+# the output darker. The value divided by 100 is the actual gamma applied,
+# so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2,
+# and 100 does not change the gamma.
+
+HTML_COLORSTYLE_GAMMA  = 80
+
+# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
+# page will contain the date and time when the page was generated. Setting
+# this to NO can help when comparing the output of multiple runs.
+
+HTML_TIMESTAMP         = YES
+
+# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
+# documentation will contain sections that can be hidden and shown after the
+# page has loaded.
+
+HTML_DYNAMIC_SECTIONS  = NO
+
+# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of
+# entries shown in the various tree structured indices initially; the user
+# can expand and collapse entries dynamically later on. Doxygen will expand
+# the tree to such a level that at most the specified number of entries are
+# visible (unless a fully collapsed tree already exceeds this amount).
+# So setting the number of entries 1 will produce a full collapsed tree by
+# default. 0 is a special value representing an infinite number of entries
+# and will result in a full expanded tree by default.
+
+HTML_INDEX_NUM_ENTRIES = 100
+
+# If the GENERATE_DOCSET tag is set to YES, additional index files
+# will be generated that can be used as input for Apple's Xcode 3
+# integrated development environment, introduced with OSX 10.5 (Leopard).
+# To create a documentation set, doxygen will generate a Makefile in the
+# HTML output directory. Running make will produce the docset in that
+# directory and running "make install" will install the docset in
+# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find
+# it at startup.
+# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html
+# for more information.
+
+GENERATE_DOCSET        = NO
+
+# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the
+# feed. A documentation feed provides an umbrella under which multiple
+# documentation sets from a single provider (such as a company or product suite)
+# can be grouped.
+
+DOCSET_FEEDNAME        = "Doxygen generated docs"
+
+# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that
+# should uniquely identify the documentation set bundle. This should be a
+# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen
+# will append .docset to the name.
+
+DOCSET_BUNDLE_ID       = org.doxygen.Project
+
+# When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely
+# identify the documentation publisher. This should be a reverse domain-name
+# style string, e.g. com.mycompany.MyDocSet.documentation.
+
+DOCSET_PUBLISHER_ID    = org.doxygen.Publisher
+
+# The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher.
+
+DOCSET_PUBLISHER_NAME  = Publisher
+
+# If the GENERATE_HTMLHELP tag is set to YES, additional index files
+# will be generated that can be used as input for tools like the
+# Microsoft HTML help workshop to generate a compiled HTML help file (.chm)
+# of the generated HTML documentation.
+
+GENERATE_HTMLHELP      = NO
+
+# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can
+# be used to specify the file name of the resulting .chm file. You
+# can add a path in front of the file if the result should not be
+# written to the html output directory.
+
+CHM_FILE               =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can
+# be used to specify the location (absolute path including file name) of
+# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run
+# the HTML help compiler on the generated index.hhp.
+
+HHC_LOCATION           =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag
+# controls if a separate .chi index file is generated (YES) or that
+# it should be included in the master .chm file (NO).
+
+GENERATE_CHI           = NO
+
+# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING
+# is used to encode HtmlHelp index (hhk), content (hhc) and project file
+# content.
+
+CHM_INDEX_ENCODING     =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag
+# controls whether a binary table of contents is generated (YES) or a
+# normal table of contents (NO) in the .chm file.
+
+BINARY_TOC             = NO
+
+# The TOC_EXPAND flag can be set to YES to add extra items for group members
+# to the contents of the HTML help documentation and to the tree view.
+
+TOC_EXPAND             = NO
+
+# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
+# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated
+# that can be used as input for Qt's qhelpgenerator to generate a
+# Qt Compressed Help (.qch) of the generated HTML documentation.
+
+GENERATE_QHP           = NO
+
+# If the QHG_LOCATION tag is specified, the QCH_FILE tag can
+# be used to specify the file name of the resulting .qch file.
+# The path specified is relative to the HTML output folder.
+
+QCH_FILE               =
+
+# The QHP_NAMESPACE tag specifies the namespace to use when generating
+# Qt Help Project output. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#namespace
+
+QHP_NAMESPACE          = org.doxygen.Project
+
+# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating
+# Qt Help Project output. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#virtual-folders
+
+QHP_VIRTUAL_FOLDER     = doc
+
+# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to
+# add. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#custom-filters
+
+QHP_CUST_FILTER_NAME   =
+
+# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the
+# custom filter to add. For more information please see
+# <a href="http://doc.trolltech.com/qthelpproject.html#custom-filters">
+# Qt Help Project / Custom Filters</a>.
+
+QHP_CUST_FILTER_ATTRS  =
+
+# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
+# project's
+# filter section matches.
+# <a href="http://doc.trolltech.com/qthelpproject.html#filter-attributes">
+# Qt Help Project / Filter Attributes</a>.
+
+QHP_SECT_FILTER_ATTRS  =
+
+# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can
+# be used to specify the location of Qt's qhelpgenerator.
+# If non-empty doxygen will try to run qhelpgenerator on the generated
+# .qhp file.
+
+QHG_LOCATION           =
+
+# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files
+# will be generated, which together with the HTML files, form an Eclipse help
+# plugin. To install this plugin and make it available under the help contents
+# menu in Eclipse, the contents of the directory containing the HTML and XML
+# files needs to be copied into the plugins directory of eclipse. The name of
+# the directory within the plugins directory should be the same as
+# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before
+# the help appears.
+
+GENERATE_ECLIPSEHELP   = NO
+
+# A unique identifier for the eclipse help plugin. When installing the plugin
+# the directory name containing the HTML and XML files should also have
+# this name.
+
+ECLIPSE_DOC_ID         = org.doxygen.Project
+
+# The DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs)
+# at top of each HTML page. The value NO (the default) enables the index and
+# the value YES disables it. Since the tabs have the same information as the
+# navigation tree you can set this option to NO if you already set
+# GENERATE_TREEVIEW to YES.
+
+DISABLE_INDEX          = NO
+
+# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
+# structure should be generated to display hierarchical information.
+# If the tag value is set to YES, a side panel will be generated
+# containing a tree-like index structure (just like the one that
+# is generated for HTML Help). For this to work a browser that supports
+# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser).
+# Windows users are probably better off using the HTML help feature.
+# Since the tree basically has the same information as the tab index you
+# could consider to set DISABLE_INDEX to NO when enabling this option.
+
+GENERATE_TREEVIEW      = YES
+
+# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values
+# (range [0,1..20]) that doxygen will group on one line in the generated HTML
+# documentation. Note that a value of 0 will completely suppress the enum
+# values from appearing in the overview section.
+
+ENUM_VALUES_PER_LINE   = 4
+
+# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be
+# used to set the initial width (in pixels) of the frame in which the tree
+# is shown.
+
+TREEVIEW_WIDTH         = 250
+
+# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open
+# links to external symbols imported via tag files in a separate window.
+
+EXT_LINKS_IN_WINDOW    = NO
+
+# Use this tag to change the font size of Latex formulas included
+# as images in the HTML documentation. The default is 10. Note that
+# when you change the font size after a successful doxygen run you need
+# to manually remove any form_*.png images from the HTML output directory
+# to force them to be regenerated.
+
+FORMULA_FONTSIZE       = 10
+
+# Use the FORMULA_TRANPARENT tag to determine whether or not the images
+# generated for formulas are transparent PNGs. Transparent PNGs are
+# not supported properly for IE 6.0, but are supported on all modern browsers.
+# Note that when changing this option you need to delete any form_*.png files
+# in the HTML output before the changes have effect.
+
+FORMULA_TRANSPARENT    = YES
+
+# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax
+# (see http://www.mathjax.org) which uses client side Javascript for the
+# rendering instead of using prerendered bitmaps. Use this if you do not
+# have LaTeX installed or if you want to formulas look prettier in the HTML
+# output. When enabled you may also need to install MathJax separately and
+# configure the path to it using the MATHJAX_RELPATH option.
+
+USE_MATHJAX            = NO
+
+# When MathJax is enabled you need to specify the location relative to the
+# HTML output directory using the MATHJAX_RELPATH option. The destination
+# directory should contain the MathJax.js script. For instance, if the mathjax
+# directory is located at the same level as the HTML output directory, then
+# MATHJAX_RELPATH should be ../mathjax. The default value points to
+# the MathJax Content Delivery Network so you can quickly see the result without
+# installing MathJax.  However, it is strongly recommended to install a local
+# copy of MathJax from http://www.mathjax.org before deployment.
+
+MATHJAX_RELPATH        = http://cdn.mathjax.org/mathjax/latest
+
+# The MATHJAX_EXTENSIONS tag can be used to specify one or MathJax extension
+# names that should be enabled during MathJax rendering.
+
+MATHJAX_EXTENSIONS     =
+
+# When the SEARCHENGINE tag is enabled doxygen will generate a search box
+# for the HTML output. The underlying search engine uses javascript
+# and DHTML and should work on any modern browser. Note that when using
+# HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets
+# (GENERATE_DOCSET) there is already a search function so this one should
+# typically be disabled. For large projects the javascript based search engine
+# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution.
+
+SEARCHENGINE           = YES
+
+# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
+# implemented using a PHP enabled web server instead of at the web client
+# using Javascript. Doxygen will generate the search PHP script and index
+# file to put on the web server. The advantage of the server
+# based approach is that it scales better to large projects and allows
+# full text search. The disadvantages are that it is more difficult to setup
+# and does not have live searching capabilities.
+
+SERVER_BASED_SEARCH    = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will
+# generate Latex output.
+
+GENERATE_LATEX         = NO
+
+# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `latex' will be used as the default path.
+
+LATEX_OUTPUT           = latex
+
+# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
+# invoked. If left blank `latex' will be used as the default command name.
+# Note that when enabling USE_PDFLATEX this option is only used for
+# generating bitmaps for formulas in the HTML output, but not in the
+# Makefile that is written to the output directory.
+
+LATEX_CMD_NAME         = latex
+
+# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to
+# generate index for LaTeX. If left blank `makeindex' will be used as the
+# default command name.
+
+MAKEINDEX_CMD_NAME     = makeindex
+
+# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact
+# LaTeX documents. This may be useful for small projects and may help to
+# save some trees in general.
+
+COMPACT_LATEX          = NO
+
+# The PAPER_TYPE tag can be used to set the paper type that is used
+# by the printer. Possible values are: a4, letter, legal and
+# executive. If left blank a4wide will be used.
+
+PAPER_TYPE             = a4
+
+# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX
+# packages that should be included in the LaTeX output.
+
+EXTRA_PACKAGES         =
+
+# The LATEX_HEADER tag can be used to specify a personal LaTeX header for
+# the generated latex document. The header should contain everything until
+# the first chapter. If it is left blank doxygen will generate a
+# standard header. Notice: only use this tag if you know what you are doing!
+
+LATEX_HEADER           =
+
+# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for
+# the generated latex document. The footer should contain everything after
+# the last chapter. If it is left blank doxygen will generate a
+# standard footer. Notice: only use this tag if you know what you are doing!
+
+LATEX_FOOTER           =
+
+# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated
+# is prepared for conversion to pdf (using ps2pdf). The pdf file will
+# contain links (just like the HTML output) instead of page references
+# This makes the output suitable for online browsing using a pdf viewer.
+
+PDF_HYPERLINKS         = YES
+
+# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of
+# plain latex in the generated Makefile. Set this option to YES to get a
+# higher quality PDF documentation.
+
+USE_PDFLATEX           = YES
+
+# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode.
+# command to the generated LaTeX files. This will instruct LaTeX to keep
+# running if errors occur, instead of asking the user for help.
+# This option is also used when generating formulas in HTML.
+
+LATEX_BATCHMODE        = NO
+
+# If LATEX_HIDE_INDICES is set to YES then doxygen will not
+# include the index chapters (such as File Index, Compound Index, etc.)
+# in the output.
+
+LATEX_HIDE_INDICES     = NO
+
+# If LATEX_SOURCE_CODE is set to YES then doxygen will include
+# source code with syntax highlighting in the LaTeX output.
+# Note that which sources are shown also depends on other settings
+# such as SOURCE_BROWSER.
+
+LATEX_SOURCE_CODE      = NO
+
+# The LATEX_BIB_STYLE tag can be used to specify the style to use for the
+# bibliography, e.g. plainnat, or ieeetr. The default style is "plain". See
+# http://en.wikipedia.org/wiki/BibTeX for more info.
+
+LATEX_BIB_STYLE        = plain
+
+#---------------------------------------------------------------------------
+# configuration options related to the RTF output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output
+# The RTF output is optimized for Word 97 and may not look very pretty with
+# other RTF readers or editors.
+
+GENERATE_RTF           = NO
+
+# The RTF_OUTPUT tag is used to specify where the RTF docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `rtf' will be used as the default path.
+
+RTF_OUTPUT             = rtf
+
+# If the COMPACT_RTF tag is set to YES Doxygen generates more compact
+# RTF documents. This may be useful for small projects and may help to
+# save some trees in general.
+
+COMPACT_RTF            = NO
+
+# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated
+# will contain hyperlink fields. The RTF file will
+# contain links (just like the HTML output) instead of page references.
+# This makes the output suitable for online browsing using WORD or other
+# programs which support those fields.
+# Note: wordpad (write) and others do not support links.
+
+RTF_HYPERLINKS         = NO
+
+# Load style sheet definitions from file. Syntax is similar to doxygen's
+# config file, i.e. a series of assignments. You only have to provide
+# replacements, missing definitions are set to their default value.
+
+RTF_STYLESHEET_FILE    =
+
+# Set optional variables used in the generation of an rtf document.
+# Syntax is similar to doxygen's config file.
+
+RTF_EXTENSIONS_FILE    =
+
+#---------------------------------------------------------------------------
+# configuration options related to the man page output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_MAN tag is set to YES (the default) Doxygen will
+# generate man pages
+
+GENERATE_MAN           = NO
+
+# The MAN_OUTPUT tag is used to specify where the man pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `man' will be used as the default path.
+
+MAN_OUTPUT             = man
+
+# The MAN_EXTENSION tag determines the extension that is added to
+# the generated man pages (default is the subroutine's section .3)
+
+MAN_EXTENSION          = .3
+
+# If the MAN_LINKS tag is set to YES and Doxygen generates man output,
+# then it will generate one additional man file for each entity
+# documented in the real man page(s). These additional files
+# only source the real man page, but without them the man command
+# would be unable to find the correct page. The default is NO.
+
+MAN_LINKS              = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the XML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_XML tag is set to YES Doxygen will
+# generate an XML file that captures the structure of
+# the code including all documentation.
+
+GENERATE_XML           = NO
+
+# The XML_OUTPUT tag is used to specify where the XML pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `xml' will be used as the default path.
+
+XML_OUTPUT             = xml
+
+# If the XML_PROGRAMLISTING tag is set to YES Doxygen will
+# dump the program listings (including syntax highlighting
+# and cross-referencing information) to the XML output. Note that
+# enabling this will significantly increase the size of the XML output.
+
+XML_PROGRAMLISTING     = YES
+
+#---------------------------------------------------------------------------
+# configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will
+# generate an AutoGen Definitions (see autogen.sf.net) file
+# that captures the structure of the code including all
+# documentation. Note that this feature is still experimental
+# and incomplete at the moment.
+
+GENERATE_AUTOGEN_DEF   = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_PERLMOD tag is set to YES Doxygen will
+# generate a Perl module file that captures the structure of
+# the code including all documentation. Note that this
+# feature is still experimental and incomplete at the
+# moment.
+
+GENERATE_PERLMOD       = NO
+
+# If the PERLMOD_LATEX tag is set to YES Doxygen will generate
+# the necessary Makefile rules, Perl scripts and LaTeX code to be able
+# to generate PDF and DVI output from the Perl module output.
+
+PERLMOD_LATEX          = NO
+
+# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be
+# nicely formatted so it can be parsed by a human reader.  This is useful
+# if you want to understand what is going on.  On the other hand, if this
+# tag is set to NO the size of the Perl module output will be much smaller
+# and Perl will parse it just the same.
+
+PERLMOD_PRETTY         = YES
+
+# The names of the make variables in the generated doxyrules.make file
+# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX.
+# This is useful so different doxyrules.make files included by the same
+# Makefile don't overwrite each other's variables.
+
+PERLMOD_MAKEVAR_PREFIX =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+
+# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will
+# evaluate all C-preprocessor directives found in the sources and include
+# files.
+
+ENABLE_PREPROCESSING   = YES
+
+# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro
+# names in the source code. If set to NO (the default) only conditional
+# compilation will be performed. Macro expansion can be done in a controlled
+# way by setting EXPAND_ONLY_PREDEF to YES.
+
+MACRO_EXPANSION        = NO
+
+# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES
+# then the macro expansion is limited to the macros specified with the
+# PREDEFINED and EXPAND_AS_DEFINED tags.
+
+EXPAND_ONLY_PREDEF     = NO
+
+# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files
+# pointed to by INCLUDE_PATH will be searched when a #include is found.
+
+SEARCH_INCLUDES        = YES
+
+# The INCLUDE_PATH tag can be used to specify one or more directories that
+# contain include files that are not input files but should be processed by
+# the preprocessor.
+
+INCLUDE_PATH           =
+
+# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
+# patterns (like *.h and *.hpp) to filter out the header-files in the
+# directories. If left blank, the patterns specified with FILE_PATTERNS will
+# be used.
+
+INCLUDE_FILE_PATTERNS  =
+
+# The PREDEFINED tag can be used to specify one or more macro names that
+# are defined before the preprocessor is started (similar to the -D option of
+# gcc). The argument of the tag is a list of macros of the form: name
+# or name=definition (no spaces). If the definition and the = are
+# omitted =1 is assumed. To prevent a macro definition from being
+# undefined via #undef or recursively expanded use the := operator
+# instead of the = operator.
+
+PREDEFINED             =
+
+# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then
+# this tag can be used to specify a list of macro names that should be expanded.
+# The macro definition that is found in the sources will be used.
+# Use the PREDEFINED tag if you want to use a different macro definition that
+# overrules the definition found in the source code.
+
+EXPAND_AS_DEFINED      =
+
+# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then
+# doxygen's preprocessor will remove all references to function-like macros
+# that are alone on a line, have an all uppercase name, and do not end with a
+# semicolon, because these will confuse the parser if not removed.
+
+SKIP_FUNCTION_MACROS   = YES
+
+#---------------------------------------------------------------------------
+# Configuration::additions related to external references
+#---------------------------------------------------------------------------
+
+# The TAGFILES option can be used to specify one or more tagfiles. For each
+# tag file the location of the external documentation should be added. The
+# format of a tag file without this location is as follows:
+#   TAGFILES = file1 file2 ...
+# Adding location for the tag files is done as follows:
+#   TAGFILES = file1=loc1 "file2 = loc2" ...
+# where "loc1" and "loc2" can be relative or absolute paths
+# or URLs. Note that each tag file must have a unique name (where the name does
+# NOT include the path). If a tag file is not located in the directory in which
+# doxygen is run, you must also specify the path to the tagfile here.
+
+TAGFILES               =
+
+# When a file name is specified after GENERATE_TAGFILE, doxygen will create
+# a tag file that is based on the input files it reads.
+
+GENERATE_TAGFILE       =
+
+# If the ALLEXTERNALS tag is set to YES all external classes will be listed
+# in the class index. If set to NO only the inherited external classes
+# will be listed.
+
+ALLEXTERNALS           = NO
+
+# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed
+# in the modules index. If set to NO, only the current project's groups will
+# be listed.
+
+EXTERNAL_GROUPS        = YES
+
+# The PERL_PATH should be the absolute path and name of the perl script
+# interpreter (i.e. the result of `which perl').
+
+PERL_PATH              = /usr/bin/perl
+
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+
+# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will
+# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base
+# or super classes. Setting the tag to NO turns the diagrams off. Note that
+# this option also works with HAVE_DOT disabled, but it is recommended to
+# install and use dot, since it yields more powerful graphs.
+
+CLASS_DIAGRAMS         = NO
+
+# You can define message sequence charts within doxygen comments using the \msc
+# command. Doxygen will then run the mscgen tool (see
+# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the
+# documentation. The MSCGEN_PATH tag allows you to specify the directory where
+# the mscgen tool resides. If left empty the tool is assumed to be found in the
+# default search path.
+
+MSCGEN_PATH            =
+
+# If set to YES, the inheritance and collaboration graphs will hide
+# inheritance and usage relations if the target is undocumented
+# or is not a class.
+
+HIDE_UNDOC_RELATIONS   = YES
+
+# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
+# available from the path. This tool is part of Graphviz, a graph visualization
+# toolkit from AT&T and Lucent Bell Labs. The other options in this section
+# have no effect if this option is set to NO (the default)
+
+HAVE_DOT               = NO
+
+# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is
+# allowed to run in parallel. When set to 0 (the default) doxygen will
+# base this on the number of processors available in the system. You can set it
+# explicitly to a value larger than 0 to get control over the balance
+# between CPU load and processing speed.
+
+DOT_NUM_THREADS        = 0
+
+# By default doxygen will use the Helvetica font for all dot files that
+# doxygen generates. When you want a differently looking font you can specify
+# the font name using DOT_FONTNAME. You need to make sure dot is able to find
+# the font, which can be done by putting it in a standard location or by setting
+# the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the
+# directory containing the font.
+
+DOT_FONTNAME           = Helvetica
+
+# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs.
+# The default size is 10pt.
+
+DOT_FONTSIZE           = 10
+
+# By default doxygen will tell dot to use the Helvetica font.
+# If you specify a different font using DOT_FONTNAME you can use DOT_FONTPATH to
+# set the path where dot can find it.
+
+DOT_FONTPATH           =
+
+# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for each documented class showing the direct and
+# indirect inheritance relations. Setting this tag to YES will force the
+# CLASS_DIAGRAMS tag to NO.
+
+CLASS_GRAPH            = YES
+
+# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for each documented class showing the direct and
+# indirect implementation dependencies (inheritance, containment, and
+# class references variables) of the class with other documented classes.
+
+COLLABORATION_GRAPH    = YES
+
+# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for groups, showing the direct groups dependencies
+
+GROUP_GRAPHS           = YES
+
+# If the UML_LOOK tag is set to YES doxygen will generate inheritance and
+# collaboration diagrams in a style similar to the OMG's Unified Modeling
+# Language.
+
+UML_LOOK               = NO
+
+# If the UML_LOOK tag is enabled, the fields and methods are shown inside
+# the class node. If there are many fields or methods and many nodes the
+# graph may become too big to be useful. The UML_LIMIT_NUM_FIELDS
+# threshold limits the number of items for each type to make the size more
+# managable. Set this to 0 for no limit. Note that the threshold may be
+# exceeded by 50% before the limit is enforced.
+
+UML_LIMIT_NUM_FIELDS   = 10
+
+# If set to YES, the inheritance and collaboration graphs will show the
+# relations between templates and their instances.
+
+TEMPLATE_RELATIONS     = NO
+
+# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT
+# tags are set to YES then doxygen will generate a graph for each documented
+# file showing the direct and indirect include dependencies of the file with
+# other documented files.
+
+INCLUDE_GRAPH          = YES
+
+# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and
+# HAVE_DOT tags are set to YES then doxygen will generate a graph for each
+# documented header file showing the documented files that directly or
+# indirectly include this file.
+
+INCLUDED_BY_GRAPH      = YES
+
+# If the CALL_GRAPH and HAVE_DOT options are set to YES then
+# doxygen will generate a call dependency graph for every global function
+# or class method. Note that enabling this option will significantly increase
+# the time of a run. So in most cases it will be better to enable call graphs
+# for selected functions only using the \callgraph command.
+
+CALL_GRAPH             = NO
+
+# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then
+# doxygen will generate a caller dependency graph for every global function
+# or class method. Note that enabling this option will significantly increase
+# the time of a run. So in most cases it will be better to enable caller
+# graphs for selected functions only using the \callergraph command.
+
+CALLER_GRAPH           = NO
+
+# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen
+# will generate a graphical hierarchy of all classes instead of a textual one.
+
+GRAPHICAL_HIERARCHY    = YES
+
+# If the DIRECTORY_GRAPH and HAVE_DOT tags are set to YES
+# then doxygen will show the dependencies a directory has on other directories
+# in a graphical way. The dependency relations are determined by the #include
+# relations between the files in the directories.
+
+DIRECTORY_GRAPH        = YES
+
+# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
+# generated by dot. Possible values are svg, png, jpg, or gif.
+# If left blank png will be used. If you choose svg you need to set
+# HTML_FILE_EXTENSION to xhtml in order to make the SVG files
+# visible in IE 9+ (other browsers do not have this requirement).
+
+DOT_IMAGE_FORMAT       = png
+
+# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to
+# enable generation of interactive SVG images that allow zooming and panning.
+# Note that this requires a modern browser other than Internet Explorer.
+# Tested and working are Firefox, Chrome, Safari, and Opera. For IE 9+ you
+# need to set HTML_FILE_EXTENSION to xhtml in order to make the SVG files
+# visible. Older versions of IE do not have SVG support.
+
+INTERACTIVE_SVG        = NO
+
+# The tag DOT_PATH can be used to specify the path where the dot tool can be
+# found. If left blank, it is assumed the dot tool can be found in the path.
+
+DOT_PATH               =
+
+# The DOTFILE_DIRS tag can be used to specify one or more directories that
+# contain dot files that are included in the documentation (see the
+# \dotfile command).
+
+DOTFILE_DIRS           =
+
+# The MSCFILE_DIRS tag can be used to specify one or more directories that
+# contain msc files that are included in the documentation (see the
+# \mscfile command).
+
+MSCFILE_DIRS           =
+
+# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of
+# nodes that will be shown in the graph. If the number of nodes in a graph
+# becomes larger than this value, doxygen will truncate the graph, which is
+# visualized by representing a node as a red box. Note that doxygen if the
+# number of direct children of the root node in a graph is already larger than
+# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note
+# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
+
+DOT_GRAPH_MAX_NODES    = 50
+
+# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the
+# graphs generated by dot. A depth value of 3 means that only nodes reachable
+# from the root by following a path via at most 3 edges will be shown. Nodes
+# that lay further from the root node will be omitted. Note that setting this
+# option to 1 or 2 may greatly reduce the computation time needed for large
+# code bases. Also note that the size of a graph can be further restricted by
+# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
+
+MAX_DOT_GRAPH_DEPTH    = 0
+
+# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
+# background. This is disabled by default, because dot on Windows does not
+# seem to support this out of the box. Warning: Depending on the platform used,
+# enabling this option may lead to badly anti-aliased labels on the edges of
+# a graph (i.e. they become hard to read).
+
+DOT_TRANSPARENT        = NO
+
+# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output
+# files in one run (i.e. multiple -o and -T options on the command line). This
+# makes dot run faster, but since only newer versions of dot (>1.8.10)
+# support this, this feature is disabled by default.
+
+DOT_MULTI_TARGETS      = NO
+
+# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will
+# generate a legend page explaining the meaning of the various boxes and
+# arrows in the dot generated graphs.
+
+GENERATE_LEGEND        = YES
+
+# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will
+# remove the intermediate dot files that are used to generate
+# the various graphs.
+
+DOT_CLEANUP            = YES
diff --git a/resource/docs/cpp-doc/Doxyfile b/resource/docs/cpp-doc/Doxyfile
new file mode 100644 (file)
index 0000000..112c4b3
--- /dev/null
@@ -0,0 +1,1839 @@
+# Doxyfile 1.8.2
+
+# This file describes the settings to be used by the documentation system
+# doxygen (www.doxygen.org) for a project
+#
+# All text after a hash (#) is considered a comment and will be ignored
+# The format is:
+#       TAG = value [value, ...]
+# For lists items can also be appended using:
+#       TAG += value [value, ...]
+# Values that contain spaces should be placed between quotes (" ")
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+
+# This tag specifies the encoding used for all characters in the config file
+# that follow. The default is UTF-8 which is also the encoding used for all
+# text before the first occurrence of this tag. Doxygen uses libiconv (or the
+# iconv built into libc) for the transcoding. See
+# http://www.gnu.org/software/libiconv for the list of possible encodings.
+
+DOXYFILE_ENCODING      = UTF-8
+
+# The PROJECT_NAME tag is a single word (or sequence of words) that should
+# identify the project. Note that if you do not use Doxywizard you need
+# to put quotes around the project name if it contains spaces.
+
+PROJECT_NAME           = "IoTivity C++ SDK"
+
+# The PROJECT_NUMBER tag can be used to enter a project or revision number.
+# This could be handy for archiving the generated documentation or
+# if some version control system is used.
+
+PROJECT_NUMBER         =
+
+# Using the PROJECT_BRIEF tag one can provide an optional one line description
+# for a project that appears at the top of each page and should give viewer
+# a quick idea about the purpose of the project. Keep the description short.
+
+PROJECT_BRIEF          =
+
+# With the PROJECT_LOGO tag one can specify an logo or icon that is
+# included in the documentation. The maximum height of the logo should not
+# exceed 55 pixels and the maximum width should not exceed 200 pixels.
+# Doxygen will copy the logo to the output directory.
+
+PROJECT_LOGO           =
+
+# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute)
+# base path where the generated documentation will be put.
+# If a relative path is entered, it will be relative to the location
+# where doxygen was started. If left blank the current directory will be used.
+
+OUTPUT_DIRECTORY       = docs
+
+# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create
+# 4096 sub-directories (in 2 levels) under the output directory of each output
+# format and will distribute the generated files over these directories.
+# Enabling this option can be useful when feeding doxygen a huge amount of
+# source files, where putting all generated files in the same directory would
+# otherwise cause performance problems for the file system.
+
+CREATE_SUBDIRS         = NO
+
+# The OUTPUT_LANGUAGE tag is used to specify the language in which all
+# documentation generated by doxygen is written. Doxygen will use this
+# information to generate all constant output in the proper language.
+# The default language is English, other supported languages are:
+# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional,
+# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German,
+# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English
+# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian,
+# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak,
+# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese.
+
+OUTPUT_LANGUAGE        = English
+
+# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will
+# include brief member descriptions after the members that are listed in
+# the file and class documentation (similar to JavaDoc).
+# Set to NO to disable this.
+
+BRIEF_MEMBER_DESC      = YES
+
+# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend
+# the brief description of a member or function before the detailed description.
+# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
+# brief descriptions will be completely suppressed.
+
+REPEAT_BRIEF           = YES
+
+# This tag implements a quasi-intelligent brief description abbreviator
+# that is used to form the text in various listings. Each string
+# in this list, if found as the leading text of the brief description, will be
+# stripped from the text and the result after processing the whole list, is
+# used as the annotated text. Otherwise, the brief description is used as-is.
+# If left blank, the following values are used ("$name" is automatically
+# replaced with the name of the entity): "The $name class" "The $name widget"
+# "The $name file" "is" "provides" "specifies" "contains"
+# "represents" "a" "an" "the"
+
+ABBREVIATE_BRIEF       = "The $name class" \
+                         "The $name widget" \
+                         "The $name file" \
+                         is \
+                         provides \
+                         specifies \
+                         contains \
+                         represents \
+                         a \
+                         an \
+                         the
+
+# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
+# Doxygen will generate a detailed section even if there is only a brief
+# description.
+
+ALWAYS_DETAILED_SEC    = NO
+
+# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
+# inherited members of a class in the documentation of that class as if those
+# members were ordinary class members. Constructors, destructors and assignment
+# operators of the base classes will not be shown.
+
+INLINE_INHERITED_MEMB  = NO
+
+# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full
+# path before files name in the file list and in the header files. If set
+# to NO the shortest path that makes the file name unique will be used.
+
+FULL_PATH_NAMES        = NO
+
+# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag
+# can be used to strip a user-defined part of the path. Stripping is
+# only done if one of the specified strings matches the left-hand part of
+# the path. The tag can be used to show relative paths in the file list.
+# If left blank the directory from which doxygen is run is used as the
+# path to strip. Note that you specify absolute paths here, but also
+# relative paths, which will be relative from the directory where doxygen is
+# started.
+
+STRIP_FROM_PATH        =
+
+# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of
+# the path mentioned in the documentation of a class, which tells
+# the reader which header file to include in order to use a class.
+# If left blank only the name of the header file containing the class
+# definition is used. Otherwise one should specify the include paths that
+# are normally passed to the compiler using the -I flag.
+
+STRIP_FROM_INC_PATH    =
+
+# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter
+# (but less readable) file names. This can be useful if your file system
+# doesn't support long names like on DOS, Mac, or CD-ROM.
+
+SHORT_NAMES            = NO
+
+# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen
+# will interpret the first line (until the first dot) of a JavaDoc-style
+# comment as the brief description. If set to NO, the JavaDoc
+# comments will behave just like regular Qt-style comments
+# (thus requiring an explicit @brief command for a brief description.)
+
+JAVADOC_AUTOBRIEF      = YES
+
+# If the QT_AUTOBRIEF tag is set to YES then Doxygen will
+# interpret the first line (until the first dot) of a Qt-style
+# comment as the brief description. If set to NO, the comments
+# will behave just like regular Qt-style comments (thus requiring
+# an explicit \brief command for a brief description.)
+
+QT_AUTOBRIEF           = NO
+
+# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen
+# treat a multi-line C++ special comment block (i.e. a block of //! or ///
+# comments) as a brief description. This used to be the default behaviour.
+# The new default is to treat a multi-line C++ comment block as a detailed
+# description. Set this tag to YES if you prefer the old behaviour instead.
+
+MULTILINE_CPP_IS_BRIEF = NO
+
+# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented
+# member inherits the documentation from any documented member that it
+# re-implements.
+
+INHERIT_DOCS           = YES
+
+# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce
+# a new page for each member. If set to NO, the documentation of a member will
+# be part of the file/class/namespace that contains it.
+
+SEPARATE_MEMBER_PAGES  = NO
+
+# The TAB_SIZE tag can be used to set the number of spaces in a tab.
+# Doxygen uses this value to replace tabs by spaces in code fragments.
+
+TAB_SIZE               = 8
+
+# This tag can be used to specify a number of aliases that acts
+# as commands in the documentation. An alias has the form "name=value".
+# For example adding "sideeffect=\par Side Effects:\n" will allow you to
+# put the command \sideeffect (or @sideeffect) in the documentation, which
+# will result in a user-defined paragraph with heading "Side Effects:".
+# You can put \n's in the value part of an alias to insert newlines.
+
+ALIASES                =
+
+# This tag can be used to specify a number of word-keyword mappings (TCL only).
+# A mapping has the form "name=value". For example adding
+# "class=itcl::class" will allow you to use the command class in the
+# itcl::class meaning.
+
+TCL_SUBST              =
+
+# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C
+# sources only. Doxygen will then generate output that is more tailored for C.
+# For instance, some of the names that are used will be different. The list
+# of all members will be omitted, etc.
+
+OPTIMIZE_OUTPUT_FOR_C  = NO
+
+# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java
+# sources only. Doxygen will then generate output that is more tailored for
+# Java. For instance, namespaces will be presented as packages, qualified
+# scopes will look different, etc.
+
+OPTIMIZE_OUTPUT_JAVA   = NO
+
+# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
+# sources only. Doxygen will then generate output that is more tailored for
+# Fortran.
+
+OPTIMIZE_FOR_FORTRAN   = NO
+
+# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
+# sources. Doxygen will then generate output that is tailored for
+# VHDL.
+
+OPTIMIZE_OUTPUT_VHDL   = NO
+
+# Doxygen selects the parser to use depending on the extension of the files it
+# parses. With this tag you can assign which parser to use for a given
+# extension. Doxygen has a built-in mapping, but you can override or extend it
+# using this tag. The format is ext=language, where ext is a file extension,
+# and language is one of the parsers supported by doxygen: IDL, Java,
+# Javascript, CSharp, C, C++, D, PHP, Objective-C, Python, Fortran, VHDL, C,
+# C++. For instance to make doxygen treat .inc files as Fortran files (default
+# is PHP), and .f files as C (default is Fortran), use: inc=Fortran f=C. Note
+# that for custom extensions you also need to set FILE_PATTERNS otherwise the
+# files are not read by doxygen.
+
+EXTENSION_MAPPING      =
+
+# If MARKDOWN_SUPPORT is enabled (the default) then doxygen pre-processes all
+# comments according to the Markdown format, which allows for more readable
+# documentation. See http://daringfireball.net/projects/markdown/ for details.
+# The output of markdown processing is further processed by doxygen, so you
+# can mix doxygen, HTML, and XML commands with Markdown formatting.
+# Disable only in case of backward compatibilities issues.
+
+MARKDOWN_SUPPORT       = YES
+
+# When enabled doxygen tries to link words that correspond to documented classes,
+# or namespaces to their corresponding documentation. Such a link can be
+# prevented in individual cases by by putting a % sign in front of the word or
+# globally by setting AUTOLINK_SUPPORT to NO.
+
+AUTOLINK_SUPPORT       = YES
+
+# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
+# to include (a tag file for) the STL sources as input, then you should
+# set this tag to YES in order to let doxygen match functions declarations and
+# definitions whose arguments contain STL classes (e.g. func(std::string); v.s.
+# func(std::string) {}). This also makes the inheritance and collaboration
+# diagrams that involve STL classes more complete and accurate.
+
+BUILTIN_STL_SUPPORT    = NO
+
+# If you use Microsoft's C++/CLI language, you should set this option to YES to
+# enable parsing support.
+
+CPP_CLI_SUPPORT        = NO
+
+# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only.
+# Doxygen will parse them like normal C++ but will assume all classes use public
+# instead of private inheritance when no explicit protection keyword is present.
+
+SIP_SUPPORT            = NO
+
+# For Microsoft's IDL there are propget and propput attributes to indicate
+# getter and setter methods for a property. Setting this option to YES (the
+# default) will make doxygen replace the get and set methods by a property in
+# the documentation. This will only work if the methods are indeed getting or
+# setting a simple type. If this is not the case, or you want to show the
+# methods anyway, you should set this option to NO.
+
+IDL_PROPERTY_SUPPORT   = YES
+
+# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
+# tag is set to YES, then doxygen will reuse the documentation of the first
+# member in the group (if any) for the other members of the group. By default
+# all members of a group must be documented explicitly.
+
+DISTRIBUTE_GROUP_DOC   = NO
+
+# Set the SUBGROUPING tag to YES (the default) to allow class member groups of
+# the same type (for instance a group of public functions) to be put as a
+# subgroup of that type (e.g. under the Public Functions section). Set it to
+# NO to prevent subgrouping. Alternatively, this can be done per class using
+# the \nosubgrouping command.
+
+SUBGROUPING            = YES
+
+# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and
+# unions are shown inside the group in which they are included (e.g. using
+# @ingroup) instead of on a separate page (for HTML and Man pages) or
+# section (for LaTeX and RTF).
+
+INLINE_GROUPED_CLASSES = NO
+
+# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and
+# unions with only public data fields will be shown inline in the documentation
+# of the scope in which they are defined (i.e. file, namespace, or group
+# documentation), provided this scope is documented. If set to NO (the default),
+# structs, classes, and unions are shown on a separate page (for HTML and Man
+# pages) or section (for LaTeX and RTF).
+
+INLINE_SIMPLE_STRUCTS  = NO
+
+# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum
+# is documented as struct, union, or enum with the name of the typedef. So
+# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
+# with name TypeT. When disabled the typedef will appear as a member of a file,
+# namespace, or class. And the struct will be named TypeS. This can typically
+# be useful for C code in case the coding convention dictates that all compound
+# types are typedef'ed and only the typedef is referenced, never the tag name.
+
+TYPEDEF_HIDES_STRUCT   = NO
+
+# Similar to the SYMBOL_CACHE_SIZE the size of the symbol lookup cache can be
+# set using LOOKUP_CACHE_SIZE. This cache is used to resolve symbols given
+# their name and scope. Since this can be an expensive process and often the
+# same symbol appear multiple times in the code, doxygen keeps a cache of
+# pre-resolved symbols. If the cache is too small doxygen will become slower.
+# If the cache is too large, memory is wasted. The cache size is given by this
+# formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range is 0..9, the default is 0,
+# corresponding to a cache size of 2^16 = 65536 symbols.
+
+LOOKUP_CACHE_SIZE      = 0
+
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+
+# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
+# documentation are documented, even if no documentation was available.
+# Private class members and static file members will be hidden unless
+# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES
+
+EXTRACT_ALL            = YES
+
+# If the EXTRACT_PRIVATE tag is set to YES all private members of a class
+# will be included in the documentation.
+
+EXTRACT_PRIVATE        = NO
+
+# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal
+# scope will be included in the documentation.
+
+EXTRACT_PACKAGE        = NO
+
+# If the EXTRACT_STATIC tag is set to YES all static members of a file
+# will be included in the documentation.
+
+EXTRACT_STATIC         = NO
+
+# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs)
+# defined locally in source files will be included in the documentation.
+# If set to NO only classes defined in header files are included.
+
+EXTRACT_LOCAL_CLASSES  = YES
+
+# This flag is only useful for Objective-C code. When set to YES local
+# methods, which are defined in the implementation section but not in
+# the interface are included in the documentation.
+# If set to NO (the default) only methods in the interface are included.
+
+EXTRACT_LOCAL_METHODS  = NO
+
+# If this flag is set to YES, the members of anonymous namespaces will be
+# extracted and appear in the documentation as a namespace called
+# 'anonymous_namespace{file}', where file will be replaced with the base
+# name of the file that contains the anonymous namespace. By default
+# anonymous namespaces are hidden.
+
+EXTRACT_ANON_NSPACES   = NO
+
+# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all
+# undocumented members of documented classes, files or namespaces.
+# If set to NO (the default) these members will be included in the
+# various overviews, but no documentation section is generated.
+# This option has no effect if EXTRACT_ALL is enabled.
+
+HIDE_UNDOC_MEMBERS     = NO
+
+# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all
+# undocumented classes that are normally visible in the class hierarchy.
+# If set to NO (the default) these classes will be included in the various
+# overviews. This option has no effect if EXTRACT_ALL is enabled.
+
+HIDE_UNDOC_CLASSES     = NO
+
+# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all
+# friend (class|struct|union) declarations.
+# If set to NO (the default) these declarations will be included in the
+# documentation.
+
+HIDE_FRIEND_COMPOUNDS  = NO
+
+# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any
+# documentation blocks found inside the body of a function.
+# If set to NO (the default) these blocks will be appended to the
+# function's detailed documentation block.
+
+HIDE_IN_BODY_DOCS      = NO
+
+# The INTERNAL_DOCS tag determines if documentation
+# that is typed after a \internal command is included. If the tag is set
+# to NO (the default) then the documentation will be excluded.
+# Set it to YES to include the internal documentation.
+
+INTERNAL_DOCS          = NO
+
+# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate
+# file names in lower-case letters. If set to YES upper-case letters are also
+# allowed. This is useful if you have classes or files whose names only differ
+# in case and if your file system supports case sensitive file names. Windows
+# and Mac users are advised to set this option to NO.
+
+CASE_SENSE_NAMES       = NO
+
+# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen
+# will show members with their full class and namespace scopes in the
+# documentation. If set to YES the scope will be hidden.
+
+HIDE_SCOPE_NAMES       = NO
+
+# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen
+# will put a list of the files that are included by a file in the documentation
+# of that file.
+
+SHOW_INCLUDE_FILES     = NO
+
+# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen
+# will list include files with double quotes in the documentation
+# rather than with sharp brackets.
+
+FORCE_LOCAL_INCLUDES   = NO
+
+# If the INLINE_INFO tag is set to YES (the default) then a tag [inline]
+# is inserted in the documentation for inline members.
+
+INLINE_INFO            = YES
+
+# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen
+# will sort the (detailed) documentation of file and class members
+# alphabetically by member name. If set to NO the members will appear in
+# declaration order.
+
+SORT_MEMBER_DOCS       = YES
+
+# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the
+# brief documentation of file, namespace and class members alphabetically
+# by member name. If set to NO (the default) the members will appear in
+# declaration order.
+
+SORT_BRIEF_DOCS        = NO
+
+# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen
+# will sort the (brief and detailed) documentation of class members so that
+# constructors and destructors are listed first. If set to NO (the default)
+# the constructors will appear in the respective orders defined by
+# SORT_MEMBER_DOCS and SORT_BRIEF_DOCS.
+# This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO
+# and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO.
+
+SORT_MEMBERS_CTORS_1ST = NO
+
+# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the
+# hierarchy of group names into alphabetical order. If set to NO (the default)
+# the group names will appear in their defined order.
+
+SORT_GROUP_NAMES       = NO
+
+# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be
+# sorted by fully-qualified names, including namespaces. If set to
+# NO (the default), the class list will be sorted only by class name,
+# not including the namespace part.
+# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
+# Note: This option applies only to the class list, not to the
+# alphabetical list.
+
+SORT_BY_SCOPE_NAME     = NO
+
+# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to
+# do proper type resolution of all parameters of a function it will reject a
+# match between the prototype and the implementation of a member function even
+# if there is only one candidate or it is obvious which candidate to choose
+# by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen
+# will still accept a match between prototype and implementation in such cases.
+
+STRICT_PROTO_MATCHING  = NO
+
+# The GENERATE_TODOLIST tag can be used to enable (YES) or
+# disable (NO) the todo list. This list is created by putting \todo
+# commands in the documentation.
+
+GENERATE_TODOLIST      = YES
+
+# The GENERATE_TESTLIST tag can be used to enable (YES) or
+# disable (NO) the test list. This list is created by putting \test
+# commands in the documentation.
+
+GENERATE_TESTLIST      = YES
+
+# The GENERATE_BUGLIST tag can be used to enable (YES) or
+# disable (NO) the bug list. This list is created by putting \bug
+# commands in the documentation.
+
+GENERATE_BUGLIST       = YES
+
+# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or
+# disable (NO) the deprecated list. This list is created by putting
+# \deprecated commands in the documentation.
+
+GENERATE_DEPRECATEDLIST= YES
+
+# The ENABLED_SECTIONS tag can be used to enable conditional
+# documentation sections, marked by \if sectionname ... \endif.
+
+ENABLED_SECTIONS       =
+
+# The MAX_INITIALIZER_LINES tag determines the maximum number of lines
+# the initial value of a variable or macro consists of for it to appear in
+# the documentation. If the initializer consists of more lines than specified
+# here it will be hidden. Use a value of 0 to hide initializers completely.
+# The appearance of the initializer of individual variables and macros in the
+# documentation can be controlled using \showinitializer or \hideinitializer
+# command in the documentation regardless of this setting.
+
+MAX_INITIALIZER_LINES  = 125
+
+# Set the SHOW_USED_FILES tag to NO to disable the list of files generated
+# at the bottom of the documentation of classes and structs. If set to YES the
+# list will mention the files that were used to generate the documentation.
+
+SHOW_USED_FILES        = YES
+
+# Set the SHOW_FILES tag to NO to disable the generation of the Files page.
+# This will remove the Files entry from the Quick Index and from the
+# Folder Tree View (if specified). The default is YES.
+
+SHOW_FILES             = YES
+
+# Set the SHOW_NAMESPACES tag to NO to disable the generation of the
+# Namespaces page.  This will remove the Namespaces entry from the Quick Index
+# and from the Folder Tree View (if specified). The default is YES.
+
+SHOW_NAMESPACES        = YES
+
+# The FILE_VERSION_FILTER tag can be used to specify a program or script that
+# doxygen should invoke to get the current version for each file (typically from
+# the version control system). Doxygen will invoke the program by executing (via
+# popen()) the command <command> <input-file>, where <command> is the value of
+# the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file
+# provided by doxygen. Whatever the program writes to standard output
+# is used as the file version. See the manual for examples.
+
+FILE_VERSION_FILTER    =
+
+# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
+# by doxygen. The layout file controls the global structure of the generated
+# output files in an output format independent way. To create the layout file
+# that represents doxygen's defaults, run doxygen with the -l option.
+# You can optionally specify a file name after the option, if omitted
+# DoxygenLayout.xml will be used as the name of the layout file.
+
+LAYOUT_FILE            = doxygenLayout.xml
+
+# The CITE_BIB_FILES tag can be used to specify one or more bib files
+# containing the references data. This must be a list of .bib files. The
+# .bib extension is automatically appended if omitted. Using this command
+# requires the bibtex tool to be installed. See also
+# http://en.wikipedia.org/wiki/BibTeX for more info. For LaTeX the style
+# of the bibliography can be controlled using LATEX_BIB_STYLE. To use this
+# feature you need bibtex and perl available in the search path.
+
+CITE_BIB_FILES         =
+
+#---------------------------------------------------------------------------
+# configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+
+# The QUIET tag can be used to turn on/off the messages that are generated
+# by doxygen. Possible values are YES and NO. If left blank NO is used.
+
+QUIET                  = NO
+
+# The WARNINGS tag can be used to turn on/off the warning messages that are
+# generated by doxygen. Possible values are YES and NO. If left blank
+# NO is used.
+
+WARNINGS               = YES
+
+# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings
+# for undocumented members. If EXTRACT_ALL is set to YES then this flag will
+# automatically be disabled.
+
+WARN_IF_UNDOCUMENTED   = YES
+
+# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for
+# potential errors in the documentation, such as not documenting some
+# parameters in a documented function, or documenting parameters that
+# don't exist or using markup commands wrongly.
+
+WARN_IF_DOC_ERROR      = YES
+
+# The WARN_NO_PARAMDOC option can be enabled to get warnings for
+# functions that are documented, but have no documentation for their parameters
+# or return value. If set to NO (the default) doxygen will only warn about
+# wrong or incomplete parameter documentation, but not about the absence of
+# documentation.
+
+WARN_NO_PARAMDOC       = NO
+
+# The WARN_FORMAT tag determines the format of the warning messages that
+# doxygen can produce. The string should contain the $file, $line, and $text
+# tags, which will be replaced by the file and line number from which the
+# warning originated and the warning text. Optionally the format may contain
+# $version, which will be replaced by the version of the file (if it could
+# be obtained via FILE_VERSION_FILTER)
+
+WARN_FORMAT            = "$file:$line: $text"
+
+# The WARN_LOGFILE tag can be used to specify a file to which warning
+# and error messages should be written. If left blank the output is written
+# to stderr.
+
+WARN_LOGFILE           = ./doxygen.log
+
+#---------------------------------------------------------------------------
+# configuration options related to the input files
+#---------------------------------------------------------------------------
+
+# The INPUT tag can be used to specify the files and/or directories that contain
+# documented source files. You may enter file names like "myfile.cpp" or
+# directories like "/usr/src/myproject". Separate the files or directories
+# with spaces.
+
+INPUT                  = . \
+                         ../../include/OCApi.h \
+                         ../../include/OCPlatform.h \
+                         ../../include/OCRepresentation.h \
+                         ../../include/OCResourceRequest.h \
+                         ../../include/OCResourceResponse.h \
+                         ../../include/OCResource.h \
+                         ../../include/OCProvisioningManager.h \
+                         ../../csdk/stack/include/octypes.h \
+                         ../../csdk/stack/include/ocstackconfig.h \
+                         guides \
+                         ../../../service/resource-encapsulation/include \
+                         ../../../service/resource-hosting/include \
+                         ../../../service/resource-container/include \
+                         ../../../service/resource-container/bundle-api/include \
+                         ../../../service/things-manager/sdk/inc/ThingsConfiguration.h \
+                         ../../../service/things-manager/sdk/inc/ThingsMaintenance.h \
+                         ../../../service/easy-setup/mediator/richsdk/inc/ \
+                         ../../../service/easy-setup/inc \
+                         ../../../service/scene-manager/include \
+
+
+# This tag can be used to specify the character encoding of the source files
+# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is
+# also the default input encoding. Doxygen uses libiconv (or the iconv built
+# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for
+# the list of possible encodings.
+
+INPUT_ENCODING         = UTF-8
+
+# If the value of the INPUT tag contains directories, you can use the
+# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
+# and *.h) to filter out the source-files in the directories. If left
+# blank the following patterns are tested:
+# *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh
+# *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py
+# *.f90 *.f *.for *.vhd *.vhdl
+
+FILE_PATTERNS          = *.c \
+                         *.cc \
+                         *.cxx \
+                         *.cpp \
+                         *.c++ \
+                         *.d \
+                         *.java \
+                         *.ii \
+                         *.ixx \
+                         *.ipp \
+                         *.i++ \
+                         *.inl \
+                         *.h \
+                         *.hh \
+                         *.hxx \
+                         *.hpp \
+                         *.h++ \
+                         *.idl \
+                         *.odl \
+                         *.cs \
+                         *.php \
+                         *.php3 \
+                         *.inc \
+                         *.m \
+                         *.markdown \
+                         *.md \
+                         *.mm \
+                         *.dox \
+                         *.py \
+                         *.f90 \
+                         *.f \
+                         *.for \
+                         *.vhd \
+                         *.vhdl \
+                         *.txt
+
+# The RECURSIVE tag can be used to turn specify whether or not subdirectories
+# should be searched for input files as well. Possible values are YES and NO.
+# If left blank NO is used.
+
+RECURSIVE              = NO
+
+# The EXCLUDE tag can be used to specify files and/or directories that should be
+# excluded from the INPUT source files. This way you can easily exclude a
+# subdirectory from a directory tree whose root is specified with the INPUT tag.
+# Note that relative paths are relative to the directory from which doxygen is
+# run.
+
+EXCLUDE                =
+
+# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
+# directories that are symbolic links (a Unix file system feature) are excluded
+# from the input.
+
+EXCLUDE_SYMLINKS       = NO
+
+# If the value of the INPUT tag contains directories, you can use the
+# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
+# certain files from those directories. Note that the wildcards are matched
+# against the file with absolute path, so to exclude all test directories
+# for example use the pattern */test/*
+
+EXCLUDE_PATTERNS       =
+
+# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
+# (namespaces, classes, functions, etc.) that should be excluded from the
+# output. The symbol name can be a fully qualified name, a word, or if the
+# wildcard * is used, a substring. Examples: ANamespace, AClass,
+# AClass::ANamespace, ANamespace::*Test
+
+EXCLUDE_SYMBOLS        =
+
+# The EXAMPLE_PATH tag can be used to specify one or more files or
+# directories that contain example code fragments that are included (see
+# the \include command).
+
+EXAMPLE_PATH           =
+
+# If the value of the EXAMPLE_PATH tag contains directories, you can use the
+# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
+# and *.h) to filter out the source-files in the directories. If left
+# blank all files are included.
+
+EXAMPLE_PATTERNS       = *
+
+# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
+# searched for input files to be used with the \include or \dontinclude
+# commands irrespective of the value of the RECURSIVE tag.
+# Possible values are YES and NO. If left blank NO is used.
+
+EXAMPLE_RECURSIVE      = NO
+
+# The IMAGE_PATH tag can be used to specify one or more files or
+# directories that contain image that are included in the documentation (see
+# the \image command).
+
+IMAGE_PATH             = img
+
+# The INPUT_FILTER tag can be used to specify a program that doxygen should
+# invoke to filter for each input file. Doxygen will invoke the filter program
+# by executing (via popen()) the command <filter> <input-file>, where <filter>
+# is the value of the INPUT_FILTER tag, and <input-file> is the name of an
+# input file. Doxygen will then use the output that the filter program writes
+# to standard output.  If FILTER_PATTERNS is specified, this tag will be
+# ignored.
+
+INPUT_FILTER           =
+
+# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
+# basis.  Doxygen will compare the file name with each pattern and apply the
+# filter if there is a match.  The filters are a list of the form:
+# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further
+# info on how filters are used. If FILTER_PATTERNS is empty or if
+# non of the patterns match the file name, INPUT_FILTER is applied.
+
+FILTER_PATTERNS        =
+
+# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
+# INPUT_FILTER) will be used to filter the input files when producing source
+# files to browse (i.e. when SOURCE_BROWSER is set to YES).
+
+FILTER_SOURCE_FILES    = NO
+
+# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
+# pattern. A pattern will override the setting for FILTER_PATTERN (if any)
+# and it is also possible to disable source filtering for a specific pattern
+# using *.ext= (so without naming a filter). This option only has effect when
+# FILTER_SOURCE_FILES is enabled.
+
+FILTER_SOURCE_PATTERNS =
+
+#---------------------------------------------------------------------------
+# configuration options related to source browsing
+#---------------------------------------------------------------------------
+
+# If the SOURCE_BROWSER tag is set to YES then a list of source files will
+# be generated. Documented entities will be cross-referenced with these sources.
+# Note: To get rid of all source code in the generated output, make sure also
+# VERBATIM_HEADERS is set to NO.
+
+SOURCE_BROWSER         = NO
+
+# Setting the INLINE_SOURCES tag to YES will include the body
+# of functions and classes directly in the documentation.
+
+INLINE_SOURCES         = NO
+
+# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct
+# doxygen to hide any special comment blocks from generated source code
+# fragments. Normal C, C++ and Fortran comments will always remain visible.
+
+STRIP_CODE_COMMENTS    = YES
+
+# If the REFERENCED_BY_RELATION tag is set to YES
+# then for each documented function all documented
+# functions referencing it will be listed.
+
+REFERENCED_BY_RELATION = NO
+
+# If the REFERENCES_RELATION tag is set to YES
+# then for each documented function all documented entities
+# called/used by that function will be listed.
+
+REFERENCES_RELATION    = NO
+
+# If the REFERENCES_LINK_SOURCE tag is set to YES (the default)
+# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from
+# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will
+# link to the source code.  Otherwise they will link to the documentation.
+
+REFERENCES_LINK_SOURCE = YES
+
+# If the USE_HTAGS tag is set to YES then the references to source code
+# will point to the HTML generated by the htags(1) tool instead of doxygen
+# built-in source browser. The htags tool is part of GNU's global source
+# tagging system (see http://www.gnu.org/software/global/global.html). You
+# will need version 4.8.6 or higher.
+
+USE_HTAGS              = NO
+
+# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen
+# will generate a verbatim copy of the header file for each class for
+# which an include is specified. Set to NO to disable this.
+
+VERBATIM_HEADERS       = YES
+
+#---------------------------------------------------------------------------
+# configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+
+# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index
+# of all compounds will be generated. Enable this if the project
+# contains a lot of classes, structs, unions or interfaces.
+
+ALPHABETICAL_INDEX     = YES
+
+# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then
+# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns
+# in which this list will be split (can be a number in the range [1..20])
+
+COLS_IN_ALPHA_INDEX    = 5
+
+# In case all classes in a project start with a common prefix, all
+# classes will be put under the same header in the alphabetical index.
+# The IGNORE_PREFIX tag can be used to specify one or more prefixes that
+# should be ignored while generating the index headers.
+
+IGNORE_PREFIX          =
+
+#---------------------------------------------------------------------------
+# configuration options related to the HTML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_HTML tag is set to YES (the default) Doxygen will
+# generate HTML output.
+
+GENERATE_HTML          = YES
+
+# The HTML_OUTPUT tag is used to specify where the HTML docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `html' will be used as the default path.
+
+HTML_OUTPUT            = html
+
+# The HTML_FILE_EXTENSION tag can be used to specify the file extension for
+# each generated HTML page (for example: .htm,.php,.asp). If it is left blank
+# doxygen will generate files with .html extension.
+
+HTML_FILE_EXTENSION    = .html
+
+# The HTML_HEADER tag can be used to specify a personal HTML header for
+# each generated HTML page. If it is left blank doxygen will generate a
+# standard header. Note that when using a custom header you are responsible
+# for the proper inclusion of any scripts and style sheets that doxygen
+# needs, which is dependent on the configuration options used.
+# It is advised to generate a default header using "doxygen -w html
+# header.html footer.html stylesheet.css YourConfigFile" and then modify
+# that header. Note that the header is subject to change so you typically
+# have to redo this when upgrading to a newer version of doxygen or when
+# changing the value of configuration settings such as GENERATE_TREEVIEW!
+
+HTML_HEADER            =
+
+# The HTML_FOOTER tag can be used to specify a personal HTML footer for
+# each generated HTML page. If it is left blank doxygen will generate a
+# standard footer.
+
+HTML_FOOTER            = html/footer.html
+
+# The HTML_STYLESHEET tag can be used to specify a user-defined cascading
+# style sheet that is used by each HTML page. It can be used to
+# fine-tune the look of the HTML output. If left blank doxygen will
+# generate a default style sheet. Note that it is recommended to use
+# HTML_EXTRA_STYLESHEET instead of this one, as it is more robust and this
+# tag will in the future become obsolete.
+
+HTML_STYLESHEET        =
+
+# The HTML_EXTRA_STYLESHEET tag can be used to specify an additional
+# user-defined cascading style sheet that is included after the standard
+# style sheets created by doxygen. Using this option one can overrule
+# certain style aspects. This is preferred over using HTML_STYLESHEET
+# since it does not replace the standard style sheet and is therefor more
+# robust against future updates. Doxygen will copy the style sheet file to
+# the output directory.
+
+HTML_EXTRA_STYLESHEET  =
+
+# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
+# other source files which should be copied to the HTML output directory. Note
+# that these files will be copied to the base HTML output directory. Use the
+# $relpath$ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
+# files. In the HTML_STYLESHEET file, use the file name only. Also note that
+# the files will be copied as-is; there are no commands or markers available.
+
+HTML_EXTRA_FILES       =
+
+# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output.
+# Doxygen will adjust the colors in the style sheet and background images
+# according to this color. Hue is specified as an angle on a colorwheel,
+# see http://en.wikipedia.org/wiki/Hue for more information.
+# For instance the value 0 represents red, 60 is yellow, 120 is green,
+# 180 is cyan, 240 is blue, 300 purple, and 360 is red again.
+# The allowed range is 0 to 359.
+
+HTML_COLORSTYLE_HUE    = 220
+
+# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of
+# the colors in the HTML output. For a value of 0 the output will use
+# grayscales only. A value of 255 will produce the most vivid colors.
+
+HTML_COLORSTYLE_SAT    = 100
+
+# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to
+# the luminance component of the colors in the HTML output. Values below
+# 100 gradually make the output lighter, whereas values above 100 make
+# the output darker. The value divided by 100 is the actual gamma applied,
+# so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2,
+# and 100 does not change the gamma.
+
+HTML_COLORSTYLE_GAMMA  = 80
+
+# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
+# page will contain the date and time when the page was generated. Setting
+# this to NO can help when comparing the output of multiple runs.
+
+HTML_TIMESTAMP         = YES
+
+# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
+# documentation will contain sections that can be hidden and shown after the
+# page has loaded.
+
+HTML_DYNAMIC_SECTIONS  = NO
+
+# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of
+# entries shown in the various tree structured indices initially; the user
+# can expand and collapse entries dynamically later on. Doxygen will expand
+# the tree to such a level that at most the specified number of entries are
+# visible (unless a fully collapsed tree already exceeds this amount).
+# So setting the number of entries 1 will produce a full collapsed tree by
+# default. 0 is a special value representing an infinite number of entries
+# and will result in a full expanded tree by default.
+
+HTML_INDEX_NUM_ENTRIES = 100
+
+# If the GENERATE_DOCSET tag is set to YES, additional index files
+# will be generated that can be used as input for Apple's Xcode 3
+# integrated development environment, introduced with OSX 10.5 (Leopard).
+# To create a documentation set, doxygen will generate a Makefile in the
+# HTML output directory. Running make will produce the docset in that
+# directory and running "make install" will install the docset in
+# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find
+# it at startup.
+# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html
+# for more information.
+
+GENERATE_DOCSET        = NO
+
+# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the
+# feed. A documentation feed provides an umbrella under which multiple
+# documentation sets from a single provider (such as a company or product suite)
+# can be grouped.
+
+DOCSET_FEEDNAME        = "Doxygen generated docs"
+
+# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that
+# should uniquely identify the documentation set bundle. This should be a
+# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen
+# will append .docset to the name.
+
+DOCSET_BUNDLE_ID       = org.doxygen.Project
+
+# When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely
+# identify the documentation publisher. This should be a reverse domain-name
+# style string, e.g. com.mycompany.MyDocSet.documentation.
+
+DOCSET_PUBLISHER_ID    = org.doxygen.Publisher
+
+# The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher.
+
+DOCSET_PUBLISHER_NAME  = Publisher
+
+# If the GENERATE_HTMLHELP tag is set to YES, additional index files
+# will be generated that can be used as input for tools like the
+# Microsoft HTML help workshop to generate a compiled HTML help file (.chm)
+# of the generated HTML documentation.
+
+GENERATE_HTMLHELP      = NO
+
+# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can
+# be used to specify the file name of the resulting .chm file. You
+# can add a path in front of the file if the result should not be
+# written to the html output directory.
+
+CHM_FILE               =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can
+# be used to specify the location (absolute path including file name) of
+# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run
+# the HTML help compiler on the generated index.hhp.
+
+HHC_LOCATION           =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag
+# controls if a separate .chi index file is generated (YES) or that
+# it should be included in the master .chm file (NO).
+
+GENERATE_CHI           = NO
+
+# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING
+# is used to encode HtmlHelp index (hhk), content (hhc) and project file
+# content.
+
+CHM_INDEX_ENCODING     =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag
+# controls whether a binary table of contents is generated (YES) or a
+# normal table of contents (NO) in the .chm file.
+
+BINARY_TOC             = NO
+
+# The TOC_EXPAND flag can be set to YES to add extra items for group members
+# to the contents of the HTML help documentation and to the tree view.
+
+TOC_EXPAND             = NO
+
+# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
+# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated
+# that can be used as input for Qt's qhelpgenerator to generate a
+# Qt Compressed Help (.qch) of the generated HTML documentation.
+
+GENERATE_QHP           = NO
+
+# If the QHG_LOCATION tag is specified, the QCH_FILE tag can
+# be used to specify the file name of the resulting .qch file.
+# The path specified is relative to the HTML output folder.
+
+QCH_FILE               =
+
+# The QHP_NAMESPACE tag specifies the namespace to use when generating
+# Qt Help Project output. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#namespace
+
+QHP_NAMESPACE          = org.doxygen.Project
+
+# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating
+# Qt Help Project output. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#virtual-folders
+
+QHP_VIRTUAL_FOLDER     = doc
+
+# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to
+# add. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#custom-filters
+
+QHP_CUST_FILTER_NAME   =
+
+# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the
+# custom filter to add. For more information please see
+# <a href="http://doc.trolltech.com/qthelpproject.html#custom-filters">
+# Qt Help Project / Custom Filters</a>.
+
+QHP_CUST_FILTER_ATTRS  =
+
+# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
+# project's
+# filter section matches.
+# <a href="http://doc.trolltech.com/qthelpproject.html#filter-attributes">
+# Qt Help Project / Filter Attributes</a>.
+
+QHP_SECT_FILTER_ATTRS  =
+
+# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can
+# be used to specify the location of Qt's qhelpgenerator.
+# If non-empty doxygen will try to run qhelpgenerator on the generated
+# .qhp file.
+
+QHG_LOCATION           =
+
+# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files
+# will be generated, which together with the HTML files, form an Eclipse help
+# plugin. To install this plugin and make it available under the help contents
+# menu in Eclipse, the contents of the directory containing the HTML and XML
+# files needs to be copied into the plugins directory of eclipse. The name of
+# the directory within the plugins directory should be the same as
+# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before
+# the help appears.
+
+GENERATE_ECLIPSEHELP   = NO
+
+# A unique identifier for the eclipse help plugin. When installing the plugin
+# the directory name containing the HTML and XML files should also have
+# this name.
+
+ECLIPSE_DOC_ID         = org.doxygen.Project
+
+# The DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs)
+# at top of each HTML page. The value NO (the default) enables the index and
+# the value YES disables it. Since the tabs have the same information as the
+# navigation tree you can set this option to NO if you already set
+# GENERATE_TREEVIEW to YES.
+
+DISABLE_INDEX          = NO
+
+# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
+# structure should be generated to display hierarchical information.
+# If the tag value is set to YES, a side panel will be generated
+# containing a tree-like index structure (just like the one that
+# is generated for HTML Help). For this to work a browser that supports
+# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser).
+# Windows users are probably better off using the HTML help feature.
+# Since the tree basically has the same information as the tab index you
+# could consider to set DISABLE_INDEX to NO when enabling this option.
+
+GENERATE_TREEVIEW      = YES
+
+# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values
+# (range [0,1..20]) that doxygen will group on one line in the generated HTML
+# documentation. Note that a value of 0 will completely suppress the enum
+# values from appearing in the overview section.
+
+ENUM_VALUES_PER_LINE   = 4
+
+# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be
+# used to set the initial width (in pixels) of the frame in which the tree
+# is shown.
+
+TREEVIEW_WIDTH         = 250
+
+# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open
+# links to external symbols imported via tag files in a separate window.
+
+EXT_LINKS_IN_WINDOW    = NO
+
+# Use this tag to change the font size of Latex formulas included
+# as images in the HTML documentation. The default is 10. Note that
+# when you change the font size after a successful doxygen run you need
+# to manually remove any form_*.png images from the HTML output directory
+# to force them to be regenerated.
+
+FORMULA_FONTSIZE       = 10
+
+# Use the FORMULA_TRANPARENT tag to determine whether or not the images
+# generated for formulas are transparent PNGs. Transparent PNGs are
+# not supported properly for IE 6.0, but are supported on all modern browsers.
+# Note that when changing this option you need to delete any form_*.png files
+# in the HTML output before the changes have effect.
+
+FORMULA_TRANSPARENT    = YES
+
+# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax
+# (see http://www.mathjax.org) which uses client side Javascript for the
+# rendering instead of using prerendered bitmaps. Use this if you do not
+# have LaTeX installed or if you want to formulas look prettier in the HTML
+# output. When enabled you may also need to install MathJax separately and
+# configure the path to it using the MATHJAX_RELPATH option.
+
+USE_MATHJAX            = NO
+
+# When MathJax is enabled you need to specify the location relative to the
+# HTML output directory using the MATHJAX_RELPATH option. The destination
+# directory should contain the MathJax.js script. For instance, if the mathjax
+# directory is located at the same level as the HTML output directory, then
+# MATHJAX_RELPATH should be ../mathjax. The default value points to
+# the MathJax Content Delivery Network so you can quickly see the result without
+# installing MathJax.  However, it is strongly recommended to install a local
+# copy of MathJax from http://www.mathjax.org before deployment.
+
+MATHJAX_RELPATH        = http://cdn.mathjax.org/mathjax/latest
+
+# The MATHJAX_EXTENSIONS tag can be used to specify one or MathJax extension
+# names that should be enabled during MathJax rendering.
+
+MATHJAX_EXTENSIONS     =
+
+# When the SEARCHENGINE tag is enabled doxygen will generate a search box
+# for the HTML output. The underlying search engine uses javascript
+# and DHTML and should work on any modern browser. Note that when using
+# HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets
+# (GENERATE_DOCSET) there is already a search function so this one should
+# typically be disabled. For large projects the javascript based search engine
+# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution.
+
+SEARCHENGINE           = YES
+
+# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
+# implemented using a PHP enabled web server instead of at the web client
+# using Javascript. Doxygen will generate the search PHP script and index
+# file to put on the web server. The advantage of the server
+# based approach is that it scales better to large projects and allows
+# full text search. The disadvantages are that it is more difficult to setup
+# and does not have live searching capabilities.
+
+SERVER_BASED_SEARCH    = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will
+# generate Latex output.
+
+GENERATE_LATEX         = NO
+
+# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `latex' will be used as the default path.
+
+LATEX_OUTPUT           = latex
+
+# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
+# invoked. If left blank `latex' will be used as the default command name.
+# Note that when enabling USE_PDFLATEX this option is only used for
+# generating bitmaps for formulas in the HTML output, but not in the
+# Makefile that is written to the output directory.
+
+LATEX_CMD_NAME         = latex
+
+# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to
+# generate index for LaTeX. If left blank `makeindex' will be used as the
+# default command name.
+
+MAKEINDEX_CMD_NAME     = makeindex
+
+# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact
+# LaTeX documents. This may be useful for small projects and may help to
+# save some trees in general.
+
+COMPACT_LATEX          = NO
+
+# The PAPER_TYPE tag can be used to set the paper type that is used
+# by the printer. Possible values are: a4, letter, legal and
+# executive. If left blank a4wide will be used.
+
+PAPER_TYPE             = a4
+
+# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX
+# packages that should be included in the LaTeX output.
+
+EXTRA_PACKAGES         =
+
+# The LATEX_HEADER tag can be used to specify a personal LaTeX header for
+# the generated latex document. The header should contain everything until
+# the first chapter. If it is left blank doxygen will generate a
+# standard header. Notice: only use this tag if you know what you are doing!
+
+LATEX_HEADER           =
+
+# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for
+# the generated latex document. The footer should contain everything after
+# the last chapter. If it is left blank doxygen will generate a
+# standard footer. Notice: only use this tag if you know what you are doing!
+
+LATEX_FOOTER           =
+
+# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated
+# is prepared for conversion to pdf (using ps2pdf). The pdf file will
+# contain links (just like the HTML output) instead of page references
+# This makes the output suitable for online browsing using a pdf viewer.
+
+PDF_HYPERLINKS         = YES
+
+# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of
+# plain latex in the generated Makefile. Set this option to YES to get a
+# higher quality PDF documentation.
+
+USE_PDFLATEX           = YES
+
+# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode.
+# command to the generated LaTeX files. This will instruct LaTeX to keep
+# running if errors occur, instead of asking the user for help.
+# This option is also used when generating formulas in HTML.
+
+LATEX_BATCHMODE        = NO
+
+# If LATEX_HIDE_INDICES is set to YES then doxygen will not
+# include the index chapters (such as File Index, Compound Index, etc.)
+# in the output.
+
+LATEX_HIDE_INDICES     = NO
+
+# If LATEX_SOURCE_CODE is set to YES then doxygen will include
+# source code with syntax highlighting in the LaTeX output.
+# Note that which sources are shown also depends on other settings
+# such as SOURCE_BROWSER.
+
+LATEX_SOURCE_CODE      = NO
+
+# The LATEX_BIB_STYLE tag can be used to specify the style to use for the
+# bibliography, e.g. plainnat, or ieeetr. The default style is "plain". See
+# http://en.wikipedia.org/wiki/BibTeX for more info.
+
+LATEX_BIB_STYLE        = plain
+
+#---------------------------------------------------------------------------
+# configuration options related to the RTF output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output
+# The RTF output is optimized for Word 97 and may not look very pretty with
+# other RTF readers or editors.
+
+GENERATE_RTF           = NO
+
+# The RTF_OUTPUT tag is used to specify where the RTF docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `rtf' will be used as the default path.
+
+RTF_OUTPUT             = rtf
+
+# If the COMPACT_RTF tag is set to YES Doxygen generates more compact
+# RTF documents. This may be useful for small projects and may help to
+# save some trees in general.
+
+COMPACT_RTF            = NO
+
+# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated
+# will contain hyperlink fields. The RTF file will
+# contain links (just like the HTML output) instead of page references.
+# This makes the output suitable for online browsing using WORD or other
+# programs which support those fields.
+# Note: wordpad (write) and others do not support links.
+
+RTF_HYPERLINKS         = NO
+
+# Load style sheet definitions from file. Syntax is similar to doxygen's
+# config file, i.e. a series of assignments. You only have to provide
+# replacements, missing definitions are set to their default value.
+
+RTF_STYLESHEET_FILE    =
+
+# Set optional variables used in the generation of an rtf document.
+# Syntax is similar to doxygen's config file.
+
+RTF_EXTENSIONS_FILE    =
+
+#---------------------------------------------------------------------------
+# configuration options related to the man page output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_MAN tag is set to YES (the default) Doxygen will
+# generate man pages
+
+GENERATE_MAN           = NO
+
+# The MAN_OUTPUT tag is used to specify where the man pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `man' will be used as the default path.
+
+MAN_OUTPUT             = man
+
+# The MAN_EXTENSION tag determines the extension that is added to
+# the generated man pages (default is the subroutine's section .3)
+
+MAN_EXTENSION          = .3
+
+# If the MAN_LINKS tag is set to YES and Doxygen generates man output,
+# then it will generate one additional man file for each entity
+# documented in the real man page(s). These additional files
+# only source the real man page, but without them the man command
+# would be unable to find the correct page. The default is NO.
+
+MAN_LINKS              = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the XML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_XML tag is set to YES Doxygen will
+# generate an XML file that captures the structure of
+# the code including all documentation.
+
+GENERATE_XML           = NO
+
+# The XML_OUTPUT tag is used to specify where the XML pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `xml' will be used as the default path.
+
+XML_OUTPUT             = xml
+
+# If the XML_PROGRAMLISTING tag is set to YES Doxygen will
+# dump the program listings (including syntax highlighting
+# and cross-referencing information) to the XML output. Note that
+# enabling this will significantly increase the size of the XML output.
+
+XML_PROGRAMLISTING     = YES
+
+#---------------------------------------------------------------------------
+# configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will
+# generate an AutoGen Definitions (see autogen.sf.net) file
+# that captures the structure of the code including all
+# documentation. Note that this feature is still experimental
+# and incomplete at the moment.
+
+GENERATE_AUTOGEN_DEF   = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_PERLMOD tag is set to YES Doxygen will
+# generate a Perl module file that captures the structure of
+# the code including all documentation. Note that this
+# feature is still experimental and incomplete at the
+# moment.
+
+GENERATE_PERLMOD       = NO
+
+# If the PERLMOD_LATEX tag is set to YES Doxygen will generate
+# the necessary Makefile rules, Perl scripts and LaTeX code to be able
+# to generate PDF and DVI output from the Perl module output.
+
+PERLMOD_LATEX          = NO
+
+# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be
+# nicely formatted so it can be parsed by a human reader.  This is useful
+# if you want to understand what is going on.  On the other hand, if this
+# tag is set to NO the size of the Perl module output will be much smaller
+# and Perl will parse it just the same.
+
+PERLMOD_PRETTY         = YES
+
+# The names of the make variables in the generated doxyrules.make file
+# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX.
+# This is useful so different doxyrules.make files included by the same
+# Makefile don't overwrite each other's variables.
+
+PERLMOD_MAKEVAR_PREFIX =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+
+# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will
+# evaluate all C-preprocessor directives found in the sources and include
+# files.
+
+ENABLE_PREPROCESSING   = YES
+
+# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro
+# names in the source code. If set to NO (the default) only conditional
+# compilation will be performed. Macro expansion can be done in a controlled
+# way by setting EXPAND_ONLY_PREDEF to YES.
+
+MACRO_EXPANSION        = NO
+
+# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES
+# then the macro expansion is limited to the macros specified with the
+# PREDEFINED and EXPAND_AS_DEFINED tags.
+
+EXPAND_ONLY_PREDEF     = NO
+
+# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files
+# pointed to by INCLUDE_PATH will be searched when a #include is found.
+
+SEARCH_INCLUDES        = YES
+
+# The INCLUDE_PATH tag can be used to specify one or more directories that
+# contain include files that are not input files but should be processed by
+# the preprocessor.
+
+INCLUDE_PATH           =
+
+# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
+# patterns (like *.h and *.hpp) to filter out the header-files in the
+# directories. If left blank, the patterns specified with FILE_PATTERNS will
+# be used.
+
+INCLUDE_FILE_PATTERNS  =
+
+# The PREDEFINED tag can be used to specify one or more macro names that
+# are defined before the preprocessor is started (similar to the -D option of
+# gcc). The argument of the tag is a list of macros of the form: name
+# or name=definition (no spaces). If the definition and the = are
+# omitted =1 is assumed. To prevent a macro definition from being
+# undefined via #undef or recursively expanded use the := operator
+# instead of the = operator.
+
+PREDEFINED             =
+
+# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then
+# this tag can be used to specify a list of macro names that should be expanded.
+# The macro definition that is found in the sources will be used.
+# Use the PREDEFINED tag if you want to use a different macro definition that
+# overrules the definition found in the source code.
+
+EXPAND_AS_DEFINED      =
+
+# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then
+# doxygen's preprocessor will remove all references to function-like macros
+# that are alone on a line, have an all uppercase name, and do not end with a
+# semicolon, because these will confuse the parser if not removed.
+
+SKIP_FUNCTION_MACROS   = YES
+
+#---------------------------------------------------------------------------
+# Configuration::additions related to external references
+#---------------------------------------------------------------------------
+
+# The TAGFILES option can be used to specify one or more tagfiles. For each
+# tag file the location of the external documentation should be added. The
+# format of a tag file without this location is as follows:
+#   TAGFILES = file1 file2 ...
+# Adding location for the tag files is done as follows:
+#   TAGFILES = file1=loc1 "file2 = loc2" ...
+# where "loc1" and "loc2" can be relative or absolute paths
+# or URLs. Note that each tag file must have a unique name (where the name does
+# NOT include the path). If a tag file is not located in the directory in which
+# doxygen is run, you must also specify the path to the tagfile here.
+
+TAGFILES               =
+
+# When a file name is specified after GENERATE_TAGFILE, doxygen will create
+# a tag file that is based on the input files it reads.
+
+GENERATE_TAGFILE       =
+
+# If the ALLEXTERNALS tag is set to YES all external classes will be listed
+# in the class index. If set to NO only the inherited external classes
+# will be listed.
+
+ALLEXTERNALS           = NO
+
+# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed
+# in the modules index. If set to NO, only the current project's groups will
+# be listed.
+
+EXTERNAL_GROUPS        = YES
+
+# The PERL_PATH should be the absolute path and name of the perl script
+# interpreter (i.e. the result of `which perl').
+
+PERL_PATH              = /usr/bin/perl
+
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+
+# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will
+# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base
+# or super classes. Setting the tag to NO turns the diagrams off. Note that
+# this option also works with HAVE_DOT disabled, but it is recommended to
+# install and use dot, since it yields more powerful graphs.
+
+CLASS_DIAGRAMS         = NO
+
+# You can define message sequence charts within doxygen comments using the \msc
+# command. Doxygen will then run the mscgen tool (see
+# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the
+# documentation. The MSCGEN_PATH tag allows you to specify the directory where
+# the mscgen tool resides. If left empty the tool is assumed to be found in the
+# default search path.
+
+MSCGEN_PATH            =
+
+# If set to YES, the inheritance and collaboration graphs will hide
+# inheritance and usage relations if the target is undocumented
+# or is not a class.
+
+HIDE_UNDOC_RELATIONS   = YES
+
+# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
+# available from the path. This tool is part of Graphviz, a graph visualization
+# toolkit from AT&T and Lucent Bell Labs. The other options in this section
+# have no effect if this option is set to NO (the default)
+
+HAVE_DOT               = NO
+
+# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is
+# allowed to run in parallel. When set to 0 (the default) doxygen will
+# base this on the number of processors available in the system. You can set it
+# explicitly to a value larger than 0 to get control over the balance
+# between CPU load and processing speed.
+
+DOT_NUM_THREADS        = 0
+
+# By default doxygen will use the Helvetica font for all dot files that
+# doxygen generates. When you want a differently looking font you can specify
+# the font name using DOT_FONTNAME. You need to make sure dot is able to find
+# the font, which can be done by putting it in a standard location or by setting
+# the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the
+# directory containing the font.
+
+DOT_FONTNAME           = Helvetica
+
+# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs.
+# The default size is 10pt.
+
+DOT_FONTSIZE           = 10
+
+# By default doxygen will tell dot to use the Helvetica font.
+# If you specify a different font using DOT_FONTNAME you can use DOT_FONTPATH to
+# set the path where dot can find it.
+
+DOT_FONTPATH           =
+
+# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for each documented class showing the direct and
+# indirect inheritance relations. Setting this tag to YES will force the
+# CLASS_DIAGRAMS tag to NO.
+
+CLASS_GRAPH            = YES
+
+# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for each documented class showing the direct and
+# indirect implementation dependencies (inheritance, containment, and
+# class references variables) of the class with other documented classes.
+
+COLLABORATION_GRAPH    = YES
+
+# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for groups, showing the direct groups dependencies
+
+GROUP_GRAPHS           = YES
+
+# If the UML_LOOK tag is set to YES doxygen will generate inheritance and
+# collaboration diagrams in a style similar to the OMG's Unified Modeling
+# Language.
+
+UML_LOOK               = NO
+
+# If the UML_LOOK tag is enabled, the fields and methods are shown inside
+# the class node. If there are many fields or methods and many nodes the
+# graph may become too big to be useful. The UML_LIMIT_NUM_FIELDS
+# threshold limits the number of items for each type to make the size more
+# managable. Set this to 0 for no limit. Note that the threshold may be
+# exceeded by 50% before the limit is enforced.
+
+UML_LIMIT_NUM_FIELDS   = 10
+
+# If set to YES, the inheritance and collaboration graphs will show the
+# relations between templates and their instances.
+
+TEMPLATE_RELATIONS     = NO
+
+# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT
+# tags are set to YES then doxygen will generate a graph for each documented
+# file showing the direct and indirect include dependencies of the file with
+# other documented files.
+
+INCLUDE_GRAPH          = YES
+
+# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and
+# HAVE_DOT tags are set to YES then doxygen will generate a graph for each
+# documented header file showing the documented files that directly or
+# indirectly include this file.
+
+INCLUDED_BY_GRAPH      = YES
+
+# If the CALL_GRAPH and HAVE_DOT options are set to YES then
+# doxygen will generate a call dependency graph for every global function
+# or class method. Note that enabling this option will significantly increase
+# the time of a run. So in most cases it will be better to enable call graphs
+# for selected functions only using the \callgraph command.
+
+CALL_GRAPH             = NO
+
+# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then
+# doxygen will generate a caller dependency graph for every global function
+# or class method. Note that enabling this option will significantly increase
+# the time of a run. So in most cases it will be better to enable caller
+# graphs for selected functions only using the \callergraph command.
+
+CALLER_GRAPH           = NO
+
+# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen
+# will generate a graphical hierarchy of all classes instead of a textual one.
+
+GRAPHICAL_HIERARCHY    = YES
+
+# If the DIRECTORY_GRAPH and HAVE_DOT tags are set to YES
+# then doxygen will show the dependencies a directory has on other directories
+# in a graphical way. The dependency relations are determined by the #include
+# relations between the files in the directories.
+
+DIRECTORY_GRAPH        = YES
+
+# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
+# generated by dot. Possible values are svg, png, jpg, or gif.
+# If left blank png will be used. If you choose svg you need to set
+# HTML_FILE_EXTENSION to xhtml in order to make the SVG files
+# visible in IE 9+ (other browsers do not have this requirement).
+
+DOT_IMAGE_FORMAT       = png
+
+# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to
+# enable generation of interactive SVG images that allow zooming and panning.
+# Note that this requires a modern browser other than Internet Explorer.
+# Tested and working are Firefox, Chrome, Safari, and Opera. For IE 9+ you
+# need to set HTML_FILE_EXTENSION to xhtml in order to make the SVG files
+# visible. Older versions of IE do not have SVG support.
+
+INTERACTIVE_SVG        = NO
+
+# The tag DOT_PATH can be used to specify the path where the dot tool can be
+# found. If left blank, it is assumed the dot tool can be found in the path.
+
+DOT_PATH               =
+
+# The DOTFILE_DIRS tag can be used to specify one or more directories that
+# contain dot files that are included in the documentation (see the
+# \dotfile command).
+
+DOTFILE_DIRS           =
+
+# The MSCFILE_DIRS tag can be used to specify one or more directories that
+# contain msc files that are included in the documentation (see the
+# \mscfile command).
+
+MSCFILE_DIRS           =
+
+# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of
+# nodes that will be shown in the graph. If the number of nodes in a graph
+# becomes larger than this value, doxygen will truncate the graph, which is
+# visualized by representing a node as a red box. Note that doxygen if the
+# number of direct children of the root node in a graph is already larger than
+# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note
+# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
+
+DOT_GRAPH_MAX_NODES    = 50
+
+# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the
+# graphs generated by dot. A depth value of 3 means that only nodes reachable
+# from the root by following a path via at most 3 edges will be shown. Nodes
+# that lay further from the root node will be omitted. Note that setting this
+# option to 1 or 2 may greatly reduce the computation time needed for large
+# code bases. Also note that the size of a graph can be further restricted by
+# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
+
+MAX_DOT_GRAPH_DEPTH    = 0
+
+# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
+# background. This is disabled by default, because dot on Windows does not
+# seem to support this out of the box. Warning: Depending on the platform used,
+# enabling this option may lead to badly anti-aliased labels on the edges of
+# a graph (i.e. they become hard to read).
+
+DOT_TRANSPARENT        = NO
+
+# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output
+# files in one run (i.e. multiple -o and -T options on the command line). This
+# makes dot run faster, but since only newer versions of dot (>1.8.10)
+# support this, this feature is disabled by default.
+
+DOT_MULTI_TARGETS      = NO
+
+# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will
+# generate a legend page explaining the meaning of the various boxes and
+# arrows in the dot generated graphs.
+
+GENERATE_LEGEND        = YES
+
+# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will
+# remove the intermediate dot files that are used to generate
+# the various graphs.
+
+DOT_CLEANUP            = YES
diff --git a/resource/docs/cpp-doc/devdocs.doxyfile b/resource/docs/cpp-doc/devdocs.doxyfile
new file mode 100644 (file)
index 0000000..8d38f28
--- /dev/null
@@ -0,0 +1,332 @@
+# Doxyfile 1.8.8
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+DOXYFILE_ENCODING      = UTF-8
+PROJECT_NAME           = "IoTivity Internals Documentation"
+PROJECT_NUMBER         =
+PROJECT_BRIEF          =
+PROJECT_LOGO           =
+OUTPUT_DIRECTORY       = devdocs
+CREATE_SUBDIRS         = NO
+ALLOW_UNICODE_NAMES    = NO
+OUTPUT_LANGUAGE        = English
+BRIEF_MEMBER_DESC      = YES
+REPEAT_BRIEF           = YES
+ABBREVIATE_BRIEF       =
+ALWAYS_DETAILED_SEC    = NO
+INLINE_INHERITED_MEMB  = NO
+FULL_PATH_NAMES        = NO
+STRIP_FROM_PATH        =
+STRIP_FROM_INC_PATH    =
+SHORT_NAMES            = NO
+JAVADOC_AUTOBRIEF      = YES
+QT_AUTOBRIEF           = NO
+MULTILINE_CPP_IS_BRIEF = NO
+INHERIT_DOCS           = YES
+SEPARATE_MEMBER_PAGES  = NO
+TAB_SIZE               = 4
+ALIASES                =
+TCL_SUBST              =
+OPTIMIZE_OUTPUT_FOR_C  = NO
+OPTIMIZE_OUTPUT_JAVA   = NO
+OPTIMIZE_FOR_FORTRAN   = NO
+OPTIMIZE_OUTPUT_VHDL   = NO
+EXTENSION_MAPPING      =
+MARKDOWN_SUPPORT       = YES
+AUTOLINK_SUPPORT       = YES
+BUILTIN_STL_SUPPORT    = NO
+CPP_CLI_SUPPORT        = NO
+SIP_SUPPORT            = NO
+IDL_PROPERTY_SUPPORT   = YES
+DISTRIBUTE_GROUP_DOC   = NO
+SUBGROUPING            = YES
+INLINE_GROUPED_CLASSES = NO
+INLINE_SIMPLE_STRUCTS  = NO
+TYPEDEF_HIDES_STRUCT   = NO
+LOOKUP_CACHE_SIZE      = 0
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+EXTRACT_ALL            = YES
+EXTRACT_PRIVATE        = YES
+EXTRACT_PACKAGE        = YES
+EXTRACT_STATIC         = YES
+EXTRACT_LOCAL_CLASSES  = YES
+EXTRACT_LOCAL_METHODS  = NO
+EXTRACT_ANON_NSPACES   = NO
+HIDE_UNDOC_MEMBERS     = NO
+HIDE_UNDOC_CLASSES     = NO
+HIDE_FRIEND_COMPOUNDS  = NO
+HIDE_IN_BODY_DOCS      = NO
+INTERNAL_DOCS          = YES
+CASE_SENSE_NAMES       = YES
+HIDE_SCOPE_NAMES       = NO
+SHOW_INCLUDE_FILES     = YES
+SHOW_GROUPED_MEMB_INC  = NO
+FORCE_LOCAL_INCLUDES   = NO
+INLINE_INFO            = YES
+SORT_MEMBER_DOCS       = YES
+SORT_BRIEF_DOCS        = NO
+SORT_MEMBERS_CTORS_1ST = NO
+SORT_GROUP_NAMES       = NO
+SORT_BY_SCOPE_NAME     = NO
+STRICT_PROTO_MATCHING  = NO
+GENERATE_TODOLIST      = YES
+GENERATE_TESTLIST      = YES
+GENERATE_BUGLIST       = YES
+GENERATE_DEPRECATEDLIST= YES
+ENABLED_SECTIONS       =
+MAX_INITIALIZER_LINES  = 30
+SHOW_USED_FILES        = YES
+SHOW_FILES             = YES
+SHOW_NAMESPACES        = YES
+FILE_VERSION_FILTER    =
+LAYOUT_FILE            =
+CITE_BIB_FILES         =
+#---------------------------------------------------------------------------
+# Configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+QUIET                  = NO
+WARNINGS               = YES
+WARN_IF_UNDOCUMENTED   = YES
+WARN_IF_DOC_ERROR      = YES
+WARN_NO_PARAMDOC       = NO
+WARN_FORMAT            = "$file:$line: $text"
+WARN_LOGFILE           =
+#---------------------------------------------------------------------------
+# Configuration options related to the input files
+#---------------------------------------------------------------------------
+INPUT                  = devdox \
+                         ../include \
+                         ../src \
+                         ../csdk/connectivity/api \
+                         ../csdk/connectivity/common/inc \
+                         ../csdk/connectivity/common/src \
+                         ../csdk/connectivity/inc \
+                         ../csdk/connectivity/src \
+                         ../csdk/logger/include \
+                         ../csdk/logger/src \
+                         ../csdk/ocrandom/include \
+                         ../csdk/ocrandom/src \
+                         ../csdk/security/include \
+                         ../csdk/security/src \
+                         ../csdk/stack/include \
+                         ../csdk/stack/src \
+                         ../c_common/oic_malloc/include \
+                         ../c_common/oic_malloc/src \
+                         ../c_common/oic_string/include \
+                         ../c_common/oic_string/src
+
+INPUT_ENCODING         = UTF-8
+FILE_PATTERNS          =
+RECURSIVE              = YES
+EXCLUDE                =
+EXCLUDE_SYMLINKS       = NO
+EXCLUDE_PATTERNS       =
+EXCLUDE_SYMBOLS        =
+EXAMPLE_PATH           =
+EXAMPLE_PATTERNS       =
+EXAMPLE_RECURSIVE      = NO
+IMAGE_PATH             =
+INPUT_FILTER           =
+FILTER_PATTERNS        =
+FILTER_SOURCE_FILES    = NO
+FILTER_SOURCE_PATTERNS =
+USE_MDFILE_AS_MAINPAGE =
+#---------------------------------------------------------------------------
+# Configuration options related to source browsing
+#---------------------------------------------------------------------------
+SOURCE_BROWSER         = NO
+INLINE_SOURCES         = NO
+STRIP_CODE_COMMENTS    = YES
+REFERENCED_BY_RELATION = NO
+REFERENCES_RELATION    = NO
+REFERENCES_LINK_SOURCE = YES
+SOURCE_TOOLTIPS        = YES
+USE_HTAGS              = NO
+VERBATIM_HEADERS       = YES
+CLANG_ASSISTED_PARSING = NO
+CLANG_OPTIONS          =
+#---------------------------------------------------------------------------
+# Configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+ALPHABETICAL_INDEX     = YES
+COLS_IN_ALPHA_INDEX    = 5
+IGNORE_PREFIX          =
+#---------------------------------------------------------------------------
+# Configuration options related to the HTML output
+#---------------------------------------------------------------------------
+GENERATE_HTML          = YES
+HTML_OUTPUT            = html
+HTML_FILE_EXTENSION    = .html
+HTML_HEADER            =
+HTML_FOOTER            =
+HTML_STYLESHEET        =
+HTML_EXTRA_STYLESHEET  =
+HTML_EXTRA_FILES       =
+HTML_COLORSTYLE_HUE    = 220
+HTML_COLORSTYLE_SAT    = 100
+HTML_COLORSTYLE_GAMMA  = 80
+HTML_TIMESTAMP         = YES
+HTML_DYNAMIC_SECTIONS  = NO
+HTML_INDEX_NUM_ENTRIES = 100
+GENERATE_DOCSET        = NO
+DOCSET_FEEDNAME        = "Doxygen generated docs"
+DOCSET_BUNDLE_ID       = org.doxygen.Project
+DOCSET_PUBLISHER_ID    = org.doxygen.Publisher
+DOCSET_PUBLISHER_NAME  = Publisher
+GENERATE_HTMLHELP      = NO
+CHM_FILE               =
+HHC_LOCATION           =
+GENERATE_CHI           = NO
+CHM_INDEX_ENCODING     =
+BINARY_TOC             = NO
+TOC_EXPAND             = NO
+GENERATE_QHP           = NO
+QCH_FILE               =
+QHP_NAMESPACE          = org.doxygen.Project
+QHP_VIRTUAL_FOLDER     = doc
+QHP_CUST_FILTER_NAME   =
+QHP_CUST_FILTER_ATTRS  =
+QHP_SECT_FILTER_ATTRS  =
+QHG_LOCATION           =
+GENERATE_ECLIPSEHELP   = NO
+ECLIPSE_DOC_ID         = org.doxygen.Project
+DISABLE_INDEX          = NO
+GENERATE_TREEVIEW      = NO
+ENUM_VALUES_PER_LINE   = 4
+TREEVIEW_WIDTH         = 250
+EXT_LINKS_IN_WINDOW    = NO
+FORMULA_FONTSIZE       = 10
+FORMULA_TRANSPARENT    = YES
+USE_MATHJAX            = NO
+MATHJAX_FORMAT         = HTML-CSS
+MATHJAX_RELPATH        = http://cdn.mathjax.org/mathjax/latest
+MATHJAX_EXTENSIONS     =
+MATHJAX_CODEFILE       =
+SEARCHENGINE           = YES
+SERVER_BASED_SEARCH    = NO
+EXTERNAL_SEARCH        = NO
+SEARCHENGINE_URL       =
+SEARCHDATA_FILE        = searchdata.xml
+EXTERNAL_SEARCH_ID     =
+EXTRA_SEARCH_MAPPINGS  =
+#---------------------------------------------------------------------------
+# Configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+GENERATE_LATEX         = YES
+LATEX_OUTPUT           = latex
+LATEX_CMD_NAME         = latex
+MAKEINDEX_CMD_NAME     = makeindex
+COMPACT_LATEX          = NO
+PAPER_TYPE             = a4
+EXTRA_PACKAGES         =
+LATEX_HEADER           =
+LATEX_FOOTER           =
+LATEX_EXTRA_FILES      =
+PDF_HYPERLINKS         = YES
+USE_PDFLATEX           = YES
+LATEX_BATCHMODE        = NO
+LATEX_HIDE_INDICES     = NO
+LATEX_SOURCE_CODE      = NO
+LATEX_BIB_STYLE        = plain
+#---------------------------------------------------------------------------
+# Configuration options related to the RTF output
+#---------------------------------------------------------------------------
+GENERATE_RTF           = NO
+RTF_OUTPUT             = rtf
+COMPACT_RTF            = NO
+RTF_HYPERLINKS         = NO
+RTF_STYLESHEET_FILE    =
+RTF_EXTENSIONS_FILE    =
+#---------------------------------------------------------------------------
+# Configuration options related to the man page output
+#---------------------------------------------------------------------------
+GENERATE_MAN           = NO
+MAN_OUTPUT             = man
+MAN_EXTENSION          = .3
+MAN_SUBDIR             =
+MAN_LINKS              = NO
+#---------------------------------------------------------------------------
+# Configuration options related to the XML output
+#---------------------------------------------------------------------------
+GENERATE_XML           = NO
+XML_OUTPUT             = xml
+XML_PROGRAMLISTING     = YES
+#---------------------------------------------------------------------------
+# Configuration options related to the DOCBOOK output
+#---------------------------------------------------------------------------
+GENERATE_DOCBOOK       = NO
+DOCBOOK_OUTPUT         = docbook
+DOCBOOK_PROGRAMLISTING = NO
+#---------------------------------------------------------------------------
+# Configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+GENERATE_AUTOGEN_DEF   = NO
+#---------------------------------------------------------------------------
+# Configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+GENERATE_PERLMOD       = NO
+PERLMOD_LATEX          = NO
+PERLMOD_PRETTY         = YES
+PERLMOD_MAKEVAR_PREFIX =
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+ENABLE_PREPROCESSING   = YES
+MACRO_EXPANSION        = NO
+EXPAND_ONLY_PREDEF     = NO
+SEARCH_INCLUDES        = YES
+INCLUDE_PATH           =
+INCLUDE_FILE_PATTERNS  =
+PREDEFINED             =
+EXPAND_AS_DEFINED      =
+SKIP_FUNCTION_MACROS   = YES
+#---------------------------------------------------------------------------
+# Configuration options related to external references
+#---------------------------------------------------------------------------
+TAGFILES               =
+GENERATE_TAGFILE       =
+ALLEXTERNALS           = NO
+EXTERNAL_GROUPS        = YES
+EXTERNAL_PAGES         = YES
+PERL_PATH              = /usr/bin/perl
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+CLASS_DIAGRAMS         = YES
+MSCGEN_PATH            =
+DIA_PATH               =
+HIDE_UNDOC_RELATIONS   = YES
+HAVE_DOT               = YES
+DOT_NUM_THREADS        = 0
+DOT_FONTNAME           = Helvetica
+DOT_FONTSIZE           = 10
+DOT_FONTPATH           =
+CLASS_GRAPH            = YES
+COLLABORATION_GRAPH    = YES
+GROUP_GRAPHS           = YES
+UML_LOOK               = NO
+UML_LIMIT_NUM_FIELDS   = 10
+TEMPLATE_RELATIONS     = NO
+INCLUDE_GRAPH          = YES
+INCLUDED_BY_GRAPH      = YES
+CALL_GRAPH             = NO
+CALLER_GRAPH           = NO
+GRAPHICAL_HIERARCHY    = YES
+DIRECTORY_GRAPH        = YES
+DOT_IMAGE_FORMAT       = png
+INTERACTIVE_SVG        = NO
+DOT_PATH               =
+DOTFILE_DIRS           = devdox/dot
+MSCFILE_DIRS           =
+DIAFILE_DIRS           =
+PLANTUML_JAR_PATH      =
+DOT_GRAPH_MAX_NODES    = 50
+MAX_DOT_GRAPH_DEPTH    = 0
+DOT_TRANSPARENT        = NO
+DOT_MULTI_TARGETS      = NO
+GENERATE_LEGEND        = YES
+DOT_CLEANUP            = YES
diff --git a/resource/docs/cpp-doc/devdox/ca_functional.dox b/resource/docs/cpp-doc/devdox/ca_functional.dox
new file mode 100644 (file)
index 0000000..c469fe0
--- /dev/null
@@ -0,0 +1,89 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/**
+@page ca_functional CA Functional design/implementation
+
+- @ref caf_overview
+  - @ref caf_ovr_communication
+    - @ref caf_ovr_comm_netinterface
+      - @ref caf_ovr_comm_netinterface_msg
+      - @ref caf_ovr_comm_netinterface_control
+      - @ref caf_ovr_comm_netinterface_eth
+      - @ref caf_ovr_comm_netinterface_wifi
+      - @ref caf_ovr_comm_netinterface_edr
+      - @ref caf_ovr_comm_netinterface_le
+      - @ref caf_ovr_comm_netinterface_detail
+
+<hr>
+
+@section caf_overview Overview
+
+The following are assorted implementation notes/references in regards to
+@ref ca_overview
+
+@subsection caf_ovr_communication Communication Adapters
+
+@subsubsection caf_ovr_comm_netinterface Network Interface Creation
+
+Interface connections are created at program startup. A Message Handler is
+started by invoking the CAInitialize() command. This in turn establishes
+the needed data structures and callbacks.
+
+@dotfile ca_arch_sketch.gv
+
+@paragraph caf_ovr_comm_netinterface_msg Message Handler
+
+The message handler owns athread pool and send and reive queue.
+
+@paragraph caf_ovr_comm_netinterface_control Interface controller
+
+This directly controls the individual adapters. Calling CAInitializeAdapters(ca_thread_pool_t handle)
+will invoke whatever config had been established by compile-time flags.
+
+@paragraph caf_ovr_comm_netinterface_eth Ethernet Adapter
+
+An interface adapter implemented to support Ethernet connections. It is
+created by calling CAInitializeEthernet()
+
+@paragraph caf_ovr_comm_netinterface_wifi WiFi Adapter
+
+An interface adapter implemented to support WiFi connections. It is created
+by calling CAInitializeWifi()
+
+@paragraph caf_ovr_comm_netinterface_edr EDR Adapter
+
+An interface adapter implemented to support EDR connections. It is created
+by calling CAInitializeEDR()
+
+@paragraph caf_ovr_comm_netinterface_le LE Adapter
+
+An interface adapter implemented to support LE connections. It is created
+by calling CAInitializeLE()
+
+@paragraph caf_ovr_comm_netinterface_detail Detailed Structure
+
+The following is a more detailed breakdown on the main types involved.
+Several structs and function details are present. However the diagram
+is more of a sketch and is not 100% complete.
+
+@dotfile ca_arch.gv
+
+*/
diff --git a/resource/docs/cpp-doc/devdox/ca_overview.dox b/resource/docs/cpp-doc/devdox/ca_overview.dox
new file mode 100644 (file)
index 0000000..626a973
--- /dev/null
@@ -0,0 +1,501 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/**
+@page ca_overview CA Overview
+
+- @ref cao_overview
+- @ref cao_ddoc
+    - @ref cao_ddoc_freqs
+        - @ref cao_ddoc_freqs_discovery
+            - @ref cao_ddoc_fr1101
+            - @ref cao_ddoc_fr1102
+            - @ref cao_ddoc_fr1103
+            - @ref cao_ddoc_fr1104
+            - @ref cao_ddoc_fr1105
+            - @ref cao_ddoc_fr1106
+            - @ref cao_ddoc_fr1107
+            - @ref cao_ddoc_fr1108
+            - @ref cao_ddoc_fr1109
+        - @ref cao_ddoc_freqs_msg
+            - @ref cao_ddoc_fr1201
+            - @ref cao_ddoc_fr1202
+            - @ref cao_ddoc_fr1203
+            - @ref cao_ddoc_fr1204
+        - @ref cao_ddoc_freqs_obs
+            - @ref cao_ddoc_fr1301
+            - @ref cao_ddoc_fr1302
+            - @ref cao_ddoc_fr1303
+            - @ref cao_ddoc_fr1304
+        - @ref cao_ddoc_freqs_netconfig
+            - @ref cao_ddoc_fr1401
+            - @ref cao_ddoc_fr1402
+            - @ref cao_ddoc_fr1403
+        - @ref cao_ddoc_freqs_control_ip
+            - @ref cao_ddoc_fr2101
+            - @ref cao_ddoc_fr2102
+            - @ref cao_ddoc_fr2103
+            - @ref cao_ddoc_fr2104
+            - @ref cao_ddoc_fr2105
+            - @ref cao_ddoc_fr2106
+        - @ref cao_ddoc_freqs_control_bt
+            - @ref cao_ddoc_fr2201
+            - @ref cao_ddoc_fr2202
+            - @ref cao_ddoc_fr2203
+            - @ref cao_ddoc_fr2204
+            - @ref cao_ddoc_fr2205
+            - @ref cao_ddoc_fr2206
+        - @ref cao_ddoc_freqs_control_ble
+            - @ref cao_ddoc_fr2301
+            - @ref cao_ddoc_fr2302
+            - @ref cao_ddoc_fr2303
+            - @ref cao_ddoc_fr2304
+            - @ref cao_ddoc_fr2305
+            - @ref cao_ddoc_fr2306
+            - @ref cao_ddoc_fr2307
+        - @ref cao_ddoc_freqs_control_zigbee
+            - @ref cao_ddoc_fr2401
+            - @ref cao_ddoc_fr2402
+            - @ref cao_ddoc_fr2403
+            - @ref cao_ddoc_fr2404
+            - @ref cao_ddoc_fr2405
+            - @ref cao_ddoc_fr2406
+        - @ref cao_ddoc_freqs_control_zwave
+            - @ref cao_ddoc_fr2501
+            - @ref cao_ddoc_fr2502
+            - @ref cao_ddoc_fr2503
+            - @ref cao_ddoc_fr2504
+            - @ref cao_ddoc_fr2505
+            - @ref cao_ddoc_fr2506
+    - @ref cao_ddoc_qattr
+        - @ref cao_ddoc_qattr_reliability
+            - @ref cao_ddoc_nfr201
+            - @ref cao_ddoc_nfr202
+        - @ref cao_ddoc_qattr_security
+            - @ref cao_ddoc_nfr301
+            - @ref cao_ddoc_nfr302
+        - @ref cao_ddoc_qattr_maintenance
+            - @ref cao_ddoc_nfr501
+        - @ref cao_ddoc_qattr_portability
+            - @ref cao_ddoc_nfr601
+            - @ref cao_ddoc_nfr602
+            - @ref cao_ddoc_nfr603
+            - @ref cao_ddoc_nfr604
+            - @ref cao_ddoc_nfr605
+        - @ref cao_ddoc_qattr_extensibility
+            - @ref cao_ddoc_nfr701
+    - @ref cao_ddoc_constraints
+        - @ref cao_ddoc_constraints_licence
+            - @ref cao_ddoc_con101
+<hr>
+
+@section cao_overview Overview
+
+The original Connectivity Abstraction design overview diagram was from a presentation format. A similar version has been recreated in dot.
+
+@dotfile ca_overview.gv
+
+
+@section cao_ddoc Design doc info
+
+
+@subsection cao_ddoc_freqs Functional Requirements
+
+
+@subsubsection cao_ddoc_freqs_discovery Discovery
+
+
+@paragraph cao_ddoc_fr1101 FR.1101
+Client can find all resources on the reachable networks.
+- CA should provide the way to discover all resources on the WiFi/Ethernet/BLE/BT network.
+- Resources should be represented by dedicated URI.
+- Add ZigBee and ZWave to supported network. ( 2015.01 ) : TBD
+
+@paragraph cao_ddoc_fr1102 FR.1102
+Client can find all resources on the specific network.
+- CA should provide the way to discover all resources on the specified network.
+- The specified network can be the one of or those of WiFi/Ethernet/BLE/BT network.
+- Resources should be represented by dedicated URI.
+- Add ZigBee and ZWave to supported network. ( 2015.01 ) : TBD
+
+@paragraph cao_ddoc_fr1103 FR.1103
+Client can find specific resource on the reachable networks.
+- CA should provide discovery method to find specific resource on the WiFi/Ethernet/BLE/BT network.
+- Resource should be represented by URI.
+- Add ZigBee and ZWave to supported network. ( 2015.01 ) : TBD
+
+@paragraph cao_ddoc_fr1104 FR.1104
+Client can find specific resource on the specific network.
+- CA should provide discovery method to find specific resource on the specific network.
+- The specified network can be the one of or those of WiFi/Ethernet/BLE/BT network.
+- Resources should be represented by dedicated URI.
+- Add ZigBee and ZWave to supported network. ( 2015.01 ) : TBD
+
+@paragraph cao_ddoc_fr1105 FR.1105
+Server can advertise single resource on the reachable network.
+- CA should provide advertising method to notify the resource on the WiFi/Ethernet/BLE/BT network.
+- Resource should be represented by URI
+- Advertising can include 'alive' or 'disappear'.
+- Add ZigBee and ZWave to supported network. ( 2015.01 ) : TBD
+
+@paragraph cao_ddoc_fr1106 FR.1106
+Server can advertise single resource on the specific network.
+- CA should provide advertising method to notify the resource on the specified network.
+- The spefied network can be the on of or those of WiFi/Ethernet/BLE/BT network
+- Resource should be represented by URI
+- Advertising can include 'alive' or 'disappear'.
+- Add ZigBee and ZWave to supported network. ( 2015.01 ) : TBD
+
+@paragraph cao_ddoc_fr1107 FR.1107
+Server can advertise all resources at a time on the reachable network.
+- CA should provide advertising method to notify the all resources on the WiFi/Ethernet/BLE/BT network.
+- Resource should be represented by URI
+- Advertising can include 'alive' or 'disappear'.
+- Add ZigBee and ZWave to supported network. ( 2015.01 ) : TBD
+
+@paragraph cao_ddoc_fr1108 FR.1108
+Server can advertise all resource  at a time on the specific network.
+- CA should provide advertising method to notify the all resources on the specified network.
+- The spefied network can be the on of or those of WiFi/Ethernet/BLE/BT network
+- Resource should be represented by URI
+- Advertising can include 'alive' or 'disappear'.
+- Add ZigBee and ZWave to supported network. ( 2015.01 ) : TBD
+
+@paragraph cao_ddoc_fr1109 FR.1109
+Client can send periodic hearbeat request on the specific resource.
+- CA should check the status of discovered resource periodically.
+- Heartbeat policy can be followed by IoTivity specification.
+
+
+@subsubsection cao_ddoc_freqs_msg Messaging
+
+
+@paragraph cao_ddoc_fr1201 FR.1201
+Client can send request message to server
+- CA should provide the way to send request message to server on the supported network.
+- CA should notify the event to server when the request message arrives from client.
+
+@paragraph cao_ddoc_fr1202 FR.1202
+Server can send response message to client
+- CA should provide the way to send response messate to client on the supported network.
+- CA should notify the event to client when the response message arrives from server.
+
+@paragraph cao_ddoc_fr1203 FR.1203
+Client and Server can select QoS level for each message
+- CA should provide the way to select message QoS level to the server and client.
+- QoS level policy can follow CoAP guideline ( CON / NON / ACK / RESET )
+
+@paragraph cao_ddoc_fr1204 FR.1204
+Message can be re-sent if acknowledgement didn't received.
+- CA should send high QoS level message repeatly until the acknowledgement arrive.
+- Retransmission policy can follows CoAP guideline.
+
+
+@subsubsection cao_ddoc_freqs_obs Observation
+
+
+@paragraph cao_ddoc_fr1301 FR.1301
+Client can send observation request message to server 
+- CA should provide the way to send observation request message to server on the supported network.
+
+@paragraph cao_ddoc_fr1302 FR.1302
+Server can send observation message 
+- CA should provider the way to send observation event to the clients which request observation on the supported network.
+
+@paragraph cao_ddoc_fr1303 FR.1303
+Client can send observation cancel request message to server
+- CA should provide the way to send observation cancel request message to server on the supported network.
+
+@paragraph cao_ddoc_fr1304 FR.1304
+Server can cancel observation
+- CA should provide the way to send observation cancel event to the clients which request observation on the supported network.
+
+
+@subsubsection cao_ddoc_freqs_netconfig Network Configuration
+
+
+@paragraph cao_ddoc_fr1401 FR.1401
+Server / Client can select the network interfaces to use.
+- CA should provide the way to select network interfaces to use for communication.
+
+@paragraph cao_ddoc_fr1402 FR.1402
+Server / Client can unselect the network interfaces
+- CA should provide the way to unselect network interfaces to use for communication.
+
+@paragraph cao_ddoc_fr1403 FR.1403
+Server / Client can receive the status changes of network interface
+- CA should notify whenever the network interface status changes.
+
+
+@subsubsection cao_ddoc_freqs_control_ip Connectivity Control - Wifi/Ethernet
+
+
+@paragraph cao_ddoc_fr2101 FR.2101
+Server / client can listen multicast message
+- CA should bind multicast port
+- Multicast IP address and port policy can be followed by IoTivity specification.
+
+@paragraph cao_ddoc_fr2102 FR.2102
+Server / client can send multicast message
+- CA should bind multicast port
+- Multicast IP address and port policy can be followed by IoTivity specification.
+
+@paragraph cao_ddoc_fr2103 FR.2103
+Serve / client can listen unicast message
+- CA should bind unicast port
+- Unicast IP address and port policy can be followed by IoTivity specification.
+
+@paragraph cao_ddoc_fr2104 FR.2104
+Server / client can send unicast message
+- CA should bind unicast port
+- Unicast IP address and port policy can be followed by IoTivity specification.
+
+@paragraph cao_ddoc_fr2105 FR.2105
+Server / client can monitor the interface status.
+- CA should notify the status of interface whenever change the status
+
+@paragraph cao_ddoc_fr2106 FR.2106
+Server / client can communicate in secured way
+- CA should provde the way to send / receive data in secure way
+- DTLS should be supported as a secure transfer
+
+
+@subsubsection cao_ddoc_freqs_control_bt Connectivity Control - Bluetooth
+
+
+@paragraph cao_ddoc_fr2201 FR.2201
+Client can discover the device has IoTivity server when inquiry time.
+- CA should scan the device using the specific UUID.
+- The specific UUID should represent IoTivity service and be unique
+
+@paragraph cao_ddoc_fr2202 FR.2202
+Server can register IoTivity service which can be found when inquiry scan time
+- CA should register the specific UUID to BT service.
+- The specific UUID should represent IoTivity service and be unique
+
+@paragraph cao_ddoc_fr2203 FR.2203
+Client can request bonding to the device has IoTivity server.
+- CA should request bonding to the device.
+- CA should delegate the bonding procedure to the platform
+
+@paragraph cao_ddoc_fr2204 FR.2204
+Server can accept / deny the bonding request from client device
+- CA should deletage the bonding procedure to the platform
+
+@paragraph cao_ddoc_fr2205 FR.2205
+Server / client can get the bonded device list from BT service
+
+@paragraph cao_ddoc_fr2206 FR.2206
+Server / client can communicate throuth the RFCOMM
+- Serial Port Profile( SPP ) should be provided by platform.
+- Platform should provide the fundamental operation functions to CA.
+  : connect(), accept(), disconnect(), send(), recv()
+
+@subsubsection cao_ddoc_freqs_control_ble Connectivity Control - BLE
+
+
+@paragraph cao_ddoc_fr2301 FR.2301
+Client can discover the device has IoTivity server when scan time.
+- CA should scan the device using the specific UUID
+- The specific UUID should represent IoTivity service ahd be unique
+
+@paragraph cao_ddoc_fr2302 FR.2302
+Server can register IoTivity service which can be found when
+advertising time
+- CA should register the specific UUID to BT service.
+- The specific UUID should represent IoTivity service and be unique
+
+@paragraph cao_ddoc_fr2303 FR.2303
+Client can request bonding to the device has IoTivity server.
+- CA should request bonding to the device.
+- CA should delegate the bonding procedure to the platform
+
+@paragraph cao_ddoc_fr2304 FR.2304
+Server can accept / deny the bonding request from client device
+- CA should deletage the bonding procedure to the platform
+
+@paragraph cao_ddoc_fr2305 FR.2305
+Server / client can get the bonded device list from BT service
+
+@paragraph cao_ddoc_fr2306 FR.2306
+Server / client can communicate throuth the RFCOMM
+- General Attribute Profile( GATT ) should be provided by platform.
+- Platform should provide the fundamental operation functions to CA.
+  : connect(), accept(), disconnect(), send(), recv()
+
+@paragraph cao_ddoc_fr2307 FR.2307
+Server / client can send more lager data than 23 bytes
+- (Optional) Platform may provide 'read long' and 'write long' feature of BLE
+- CA should fragment and reassemble the lager data
+
+
+@subsubsection cao_ddoc_freqs_control_zigbee Connectivity Control - ZigBee
+
+
+@paragraph cao_ddoc_fr2401 FR.2401
+Client can start forming the ZigBee network
+- Client means ZigBee coordinator device
+- ZigBee service should provide the way to start ZigBee network forming
+
+@paragraph cao_ddoc_fr2402 FR.2402
+Client can finish the formed ZigBee network
+- Client means ZigBee coordinator device
+- ZigBee service should provide the way to finish ZigBee network forming
+
+@paragraph cao_ddoc_fr2403 FR.2403
+Client can receive the event whenever the ZigBee end-device joins and leaves
+- CA should know the identifier of ZigBee end-device when joins and leaves.
+- CA should know the identifier of ZigBee end-device joined through ZigBee router when joins and leaves.
+- CA could select the ZigBee end-device to join
+
+@paragraph cao_ddoc_fr2404 FR.2404
+Client can convert common ZigBee cluster to IoTivity URI.
+- CA should convert the common ZigBee cluster to URI.
+- The common ZigBee cluster can be one of the clusters announced by ZigBee alliance.
+  : eg. Home Automation Profile, Smart Energy Profile, and so on.
+
+@paragraph cao_ddoc_fr2405 FR.2405
+Client can convert common ZigBee cluster attributes to IoTivity attributes
+- CA should convert the common ZigBee cluster to attribute of the URI.
+- The common ZigBee profile can be one of the clusters announced by ZigBee alliance.
+
+@paragraph cao_ddoc_fr2406 FR.2406
+Client can convert CoAP message to ZCL command
+- CA should convert CoAP message to ZCL command to send ZigBee end-device
+
+
+@subsubsection cao_ddoc_freqs_control_zwave Connectivity Control - ZWave
+
+
+@paragraph cao_ddoc_fr2501 FR.2501
+Client can start creating PAN ( ZWave network )
+- Client means ZWave controller device
+- ZWave service should provide the way to start ZWave network creation
+
+@paragraph cao_ddoc_fr2502 FR.2502
+Client can finish the created PAN ( ZWave network )
+- Client means ZWave controller device
+- ZWave service should provide the way to finish created ZWave network
+
+@paragraph cao_ddoc_fr2503 FR.2503
+Client can receive the event whenever the ZWave slave joins and leaves
+- CA should know the identifier of ZWave slave when joins and leaves.
+- CA should know the identifier of ZWave slave joined through ZWave router when joins and leaves.
+- CA could select the ZWave slave to join
+
+@paragraph cao_ddoc_fr2504 FR.2504
+Client can convert common ZWave device class to IoTivity URI
+- CA should convert the common ZWave device class to URI.
+- The common ZWave device class can be one of the device classes announced by ZWave alliance.
+
+@paragraph cao_ddoc_fr2505 FR.2505
+Client can convert common ZWave command class to IoTivity attribute
+- CA should convert the common ZWave command class to attribute of the URI.
+- The common ZWave command class can be one of the command classes announced by ZWave alliance.
+
+@paragraph cao_ddoc_fr2506 FR.2506
+Client can convert CoAP message to ZWave command
+- CA should convert CoAP message to command class to send ZWave slave
+
+
+@subsection cao_ddoc_qattr Quality Attributes
+
+
+@subsubsection cao_ddoc_qattr_reliability Reliability
+
+
+@paragraph cao_ddoc_nfr201 NFR.201
+Network availability detection
+- Maxinum number of messaging failure is 3 during 10 minutes in available network .
+- Terminate the connection when the number is over the maximum value.
+
+@paragraph cao_ddoc_nfr202 NFR.202
+Messaging
+- The transmitted message from source has to be deliverd to the destination completely.
+
+@subsubsection cao_ddoc_qattr_security Security
+
+
+@paragraph cao_ddoc_nfr301 NFR.301
+Transfer Channel Protection
+- should protect the transfer channel using DTLS in CoaP , authentication in BT and other mechanisms in connectivities
+
+@paragraph cao_ddoc_nfr302 NFR.302
+Message Protection ( TBD )
+- should be able to encrypt the message to protect using RSA??
+
+
+@subsubsection cao_ddoc_qattr_maintenance Maintenance
+
+
+@paragraph cao_ddoc_nfr501 NFR.501
+Modularization for connectivities
+- One connectivity module change shouldn't have an effect on the other connectivity module.
+
+@subsubsection cao_ddoc_qattr_portability Portability
+
+
+@paragraph cao_ddoc_nfr601 NFR.601
+Support on Ubuntu 12.04
+- The software should be ported on Ubuntu (12.04) without change.
+- The platform specific portion should be controlled by build configurations.
+
+@paragraph cao_ddoc_nfr602 NFR.602
+Support on Android 4.4 / 5.0 and higher
+- The software should be ported on Android v5.0 and higher without change.
+- The platform specific portion should be controlled by build configurations.
+- JNI block can be added
+
+@paragraph cao_ddoc_nfr603 NFR.603
+Support on Tizen v2.3 and higher
+- The software should be ported on Tizen v2.3 and higher without change.
+- The platform specific portion should be controlled by build configurations.
+
+@paragraph cao_ddoc_nfr604 NFR.604
+Support on Arduino Mega
+- The software should be ported on Arduino Mega without change.
+- Connectivity function can be supported through the various shields.
+- The platform specific portion should be controlled by build configurations.
+
+@paragraph cao_ddoc_nfr605 NFR.605
+Support on Arduino Due
+- The software should be ported on Arduino Due without change.
+- Connectivity function can be supported through the various shields.
+- The platform specific portion should be controlled by build configurations.
+
+
+@subsubsection cao_ddoc_qattr_extensibility Extensibility
+
+@paragraph cao_ddoc_nfr701 NFR.701
+Connectivity Extension
+- The Architecture change has to be minimized when expanding Connectivities.
+
+
+@subsection cao_ddoc_constraints Constraints
+
+
+@subsubsection cao_ddoc_constraints_licence License
+
+
+@paragraph cao_ddoc_con101 CON.101
+Open source license
+- All source codes should be released under Apache License v2 or compatible.
+
+*/
diff --git a/resource/docs/cpp-doc/devdox/dot/ca_arch.gv b/resource/docs/cpp-doc/devdox/dot/ca_arch.gv
new file mode 100644 (file)
index 0000000..05b7982
--- /dev/null
@@ -0,0 +1,283 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+digraph G {
+    label = "Network Interface Creation";
+    fontsize = 10;
+
+    edge [
+        fontsize = 10
+    ]
+
+    node [
+        fontsize = 10,
+    ]
+
+ // ----
+
+    msg_handler [
+        shape = none
+        margin = 0
+        label = <<table border="1" cellspacing="0" cellborder="0">
+                    <tr><td port="a" tooltip="Message Handler" bgcolor="gray">Message Handler</td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref g_threadPoolHandle" tooltip="-g_threadPoolHandle: ca_thread_pool_t">-g_threadPoolHandle: ca_thread_pool_t</td></tr>
+                    <tr><td align="left" href="\ref g_sendThread" tooltip="-g_sendThread: CAQueueingThread_t">-g_sendThread: CAQueueingThread_t</td></tr>
+                    <tr><td align="left" href="\ref g_receiveThread" tooltip="-g_receiveThread: CAQueueingThread_t">-g_receiveThread: CAQueueingThread_t</td></tr>
+                    <tr><td align="left" href="\ref g_retransmissionContext" tooltip="-g_retransmissionContext: CARetransmission_t">-g_retransmissionContext: CARetransmission_t</td></tr>
+                    <tr><td align="left" href="\ref g_requestHandler" tooltip="-g_requestHandler: CARequestCallback">-g_requestHandler: CARequestCallback</td></tr>
+                    <tr><td align="left" href="\ref g_responseHandler" tooltip="-g_responseHandler: CAResponseCallback">-g_responseHandler: CAResponseCallback</td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref CAInitializeMessageHandler()" tooltip="+CAInitializeMessageHandler">+CAInitializeMessageHandler</td></tr>
+                    <tr><td align="left" href="\ref CATerminateMessageHandler()" tooltip="+CATerminateMessageHandler">+CATerminateMessageHandler</td></tr>
+                </table>>
+    ]
+
+    threadpool [
+        shape = none
+        margin = 0
+        label = <<table border="1" cellspacing="0" cellborder="0">
+                    <tr><td href="\ref ca_thread_pool_t" tooltip="ca_threadpool_t" bgcolor="gray">ca_threadpool_t</td></tr>
+                    <hr/>
+                    <tr><td> </td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref ca_thread_pool_init()" tooltip="+ca_thread_pool_init">+ca_thread_pool_init</td></tr>
+                    <tr><td align="left" href="\ref ca_thread_pool_free()" tooltip="+ca_thread_pool_free">+ca_thread_pool_free</td></tr>
+                    <tr><td align="left" href="\ref ca_thread_pool_add_task()" tooltip="+ca_thread_pool_add_task">+ca_thread_pool_add_task</td></tr>
+                </table>>
+    ]
+
+
+    thread_out [
+        shape = none
+        margin = 0
+        label = <<table border="1" cellspacing="0" cellborder="0">
+                    <tr><td href="\ref CASendThreadProcess()" tooltip="Send Thread" bgcolor="gray">Send Thread</td></tr>
+                    <hr/>
+                    <tr><td> </td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref CASendThreadProcess()" tooltip="+CASendThreadProcess">+CASendThreadProcess</td></tr>
+                </table>>
+    ]
+
+    thread_in [
+        shape = none
+        margin = 0
+        label = <<table border="1" cellspacing="0" cellborder="0">
+                    <tr><td href="\ref CAReceiveThreadProcess()" tooltip="Receive Thread" bgcolor="gray">Receive Thread</td></tr>
+                    <hr/>
+                    <tr><td> </td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref CAReceiveThreadProcess()" tooltip="+CAReceiveThreadProcess">+CAReceiveThreadProcess</td></tr>
+                </table>>
+    ]
+
+    thread_retrans [
+        shape = none
+        margin = 0
+        label = <<table border="1" cellspacing="0" cellborder="0">
+                    <tr><td href="\ref CASendUnicastData()" tooltip="Retransmit Thread" bgcolor="gray">Retransmit Thread</td></tr>
+                    <hr/>
+                    <tr><td> </td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref CASendUnicastData()" tooltip="+CASendUnicastData">+CASendUnicastData</td></tr>
+                </table>>
+    ]
+
+    control [
+        tooltip = "Interface Controller",
+        label = "{Interface Controller| +CAInitializeAdapters()\l\n \n }",
+        URL = "\ref CAInitializeAdapters()"
+
+
+        shape = none
+        margin = 0
+        label = <<table border="1" cellspacing="0" cellborder="0">
+                    <tr><td href="\ref CAInitializeAdapters()" tooltip="Interface Controller" bgcolor="gray">Interface Controller</td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref g_adapterHandler" tooltip="-g_adapterHandler: CAConnectivityHandler_t[]">-g_adapterHandler: CAConnectivityHandler_t[]</td></tr>
+                    <tr><td align="left" href="\ref g_networkPacketReceivedCallback" tooltip="-g_networkPacketReceivedCallback: CANetworkPacketReceivedCallback">-g_networkPacketReceivedCallback: CANetworkPacketReceivedCallback</td></tr>
+
+                    <tr><td align="left" href="\ref g_networkChangeCallback" tooltip="-g_networkChangeCallback: CANetworkChangeCallback">-g_networkChangeCallback: CANetworkChangeCallback</td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref CAInitializeAdapters()" tooltip="+CAInitializeAdapters">+CAInitializeAdapters</td></tr>
+                    <tr><td align="left" href="\ref CATerminateAdapters()" tooltip="+CATerminateAdapters">+CATerminateAdapters</td></tr>
+                    <tr><td align="left" href="\ref CAStartAdapter()" tooltip="+CAStartAdapter">+CAStartAdapter</td></tr>
+                    <tr><td align="left" href="\ref CAStopAdapter()" tooltip="+CAStopAdapter">+CAStopAdapter</td></tr>
+                    <tr><td align="left" href="\ref CAGetNetworkInfo()" tooltip="+CAGetNetworkInfo">+CAGetNetworkInfo</td></tr>
+                    <tr><td align="left" href="\ref CAStartListeningServerAdapters()" tooltip="+CAStartListeningServerAdapters">+CAStartListeningServerAdapters</td></tr>
+                    <tr><td align="left" href="\ref CAStartDiscoveryServerAdapters()" tooltip="+CAStartDiscoveryServerAdapters">+CAStartDiscoveryServerAdapters</td></tr>
+                </table>>
+    ]
+
+
+    conn_handler [
+        shape = none
+        margin = 0
+        label = <<table border="1" cellspacing="0" cellborder="0">
+                    <tr><td href="\ref CAConnectivityHandler_t" tooltip="CAConnectivityHandler_t" bgcolor="gray">CAConnectivityHandler_t</td></tr>
+                    <hr/>
+                    <tr><td> </td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref CAConnectivityHandler_t::startAdapter" tooltip="+startAdapter: CAAdapterStart">+startAdapter: CAAdapterStart</td></tr>
+                    <tr><td align="left" href="\ref CAConnectivityHandler_t::startListenServer" tooltip="+startListenServer: CAAdapterStartListeningServer">+startListenServer: CAAdapterStartListeningServer</td></tr>
+                    <tr><td align="left" href="\ref CAConnectivityHandler_t::startDiscoveryServer" tooltip="+startDiscoveryServer: CAAdapterStartDiscoveryServer">+startDiscoveryServer: CAAdapterStartDiscoveryServer</td></tr>
+                    <tr><td align="left" href="\ref CAConnectivityHandler_t::sendData" tooltip="+sendData: CAAdapterSendUnicastData">+sendData: CAAdapterSendUnicastData</td></tr>
+                    <tr><td align="left" href="\ref CAConnectivityHandler_t::sendDataToAll" tooltip="+sendDataToAll: CAAdapterSendMulticastData">+sendDataToAll: CAAdapterSendMulticastData</td></tr>
+                    <tr><td align="left" href="\ref CAConnectivityHandler_t::GetnetInfo" tooltip="+GetnetInfo: CAAdapterGetNetworkInfo">+GetnetInfo: CAAdapterGetNetworkInfo</td></tr>
+                    <tr><td align="left" href="\ref CAConnectivityHandler_t::readData" tooltip="+readData: CAAdapterReadData">+readData: CAAdapterReadData</td></tr>
+                    <tr><td align="left" href="\ref CAConnectivityHandler_t::stopAdapter" tooltip="+stopAdapter: CAAdapterStop">+stopAdapter: CAAdapterStop</td></tr>
+                    <tr><td align="left" href="\ref CAConnectivityHandler_t::terminate" tooltip="+terminate: CAAdapterTerminate">+terminate: CAAdapterTerminate</td></tr>
+                </table>>
+
+
+    ]
+
+    adapt01 [
+        shape = none
+        margin = 0
+        label = <<table border="1" cellspacing="0" cellborder="0">
+                    <tr><td href="\ref CAInitializeEthernet" tooltip="Ethernet Adapter" bgcolor="gray">Ethernet Adapter</td></tr>
+                    <hr/>
+                    <tr><td> </td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref CAInitializeEthernet" tooltip="+CAInitializeEthernet">+CAInitializeEthernet</td></tr>
+                    <tr><td align="left" href="\ref CATerminateEthernet()" tooltip="+CATerminateEthernet">+CATerminateEthernet</td></tr>
+                    <tr><td align="left" href="\ref CAStartEthernet()" tooltip="+CAStartEthernet">+CAStartEthernet</td></tr>
+                    <tr><td align="left" href="\ref CAStopEthernet()" tooltip="+CAStopEthernet">+CAStopEthernet</td></tr>
+                    <tr><td align="left" href="\ref CAStartEthernetListeningServer()" tooltip="+CAStartEthernetListeningServer">+CAStartEthernetListeningServer</td></tr>
+                    <tr><td align="left" href="\ref CAStartEthernetDiscoveryServer()" tooltip="+CAStartEthernetDiscoveryServer">+CAStartEthernetDiscoveryServer</td></tr>
+                    <tr><td align="left" href="\ref CAGetEthernetInterfaceInformation" tooltip="+CAGetEthernetInterfaceInformation">+CAGetEthernetInterfaceInformation</td></tr>
+                    <tr><td align="left" href="\ref CASendEthernetUnicastData()" tooltip="+CASendEthernetUnicastData">+CASendEthernetUnicastData</td></tr>
+                    <tr><td align="left" href="\ref CASendEthernetMulticastData()" tooltip="+CASendEthernetMulticastData">+CASendEthernetMulticastData</td></tr>
+                    <tr><td align="left" href="\ref CAReadEthernetData()" tooltip="+CAReadEthernetData">+CAReadEthernetData</td></tr>
+                </table>>
+    ]
+
+    adapt02 [
+        tooltip = "WiFi Adapter",
+        label = "{WiFi Adapter| +CAInitializeWifi()\l\n \n }",
+        URL = "\ref CAInitializeWifi()"
+
+        shape = none
+        margin = 0
+        label = <<table border="1" cellspacing="0" cellborder="0">
+                    <tr><td href="\ref CAInitializeWifi" tooltip="WiFi Adapter" bgcolor="gray">WiFi Adapter</td></tr>
+                    <hr/>
+                    <tr><td> </td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref CAInitializeWifi()" tooltip="+CAInitializeWifi">+CAInitializeWifi</td></tr>
+                    <tr><td align="left" href="\ref CATerminateWIFI()" tooltip="+CATerminateWIFI">+CATerminateWIFI</td></tr>
+                    <tr><td align="left" href="\ref CAStartWIFI()" tooltip="+CAStartWIFI">+CAStartWIFI</td></tr>
+                    <tr><td align="left" href="\ref CAStopWIFI()" tooltip="+CAStopWIFI">+CAStopWIFI</td></tr>
+                    <tr><td align="left" href="\ref CAStartWIFIListeningServer()" tooltip="+CAStartWIFIListeningServer">+CAStartWIFIListeningServer</td></tr>
+                    <tr><td align="left" href="\ref CAStartWIFIDiscoveryServer()" tooltip="+CAStartWIFIDiscoveryServer">+CAStartWIFIDiscoveryServer</td></tr>
+                    <tr><td align="left" href="\ref CAGetWIFIInterfaceInformation()" tooltip="+CAGetWIFIInterfaceInformation">+CAGetWIFIInterfaceInformation</td></tr>
+                    <tr><td align="left" href="\ref CASendWIFIUnicastData()" tooltip="+CASendWIFIUnicastData">+CASendWIFIUnicastData</td></tr>
+                    <tr><td align="left" href="\ref CASendWIFIMulticastData()" tooltip="+CASendWIFIMulticastData">+CASendWIFIMulticastData</td></tr>
+                    <tr><td align="left" href="\ref CAReadWIFIData()" tooltip="+CAReadWIFIData">+CAReadWIFIData</td></tr>
+                </table>>
+    ]
+
+    adapt03 [
+        tooltip = "EDR Adapter",
+        label = "{EDR Adapter| +CAInitializeEDR()\l\n \n }",
+        URL = "\ref CAInitializeEDR()"
+
+        shape = none
+        margin = 0
+        label = <<table border="1" cellspacing="0" cellborder="0">
+                    <tr><td href="\ref CAInitializeEDR" tooltip="EDR Adapter" bgcolor="gray">EDR Adapter</td></tr>
+                    <hr/>
+                    <tr><td> </td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref CAInitializeEDR" tooltip="+CAInitializeEDR">+CAInitializeEDR</td></tr>
+                    <tr><td align="left" href="\ref CATerminateEDR()" tooltip="+CATerminateEDR">+CATerminateEDR</td></tr>
+                    <tr><td align="left" href="\ref CAStartEDR()" tooltip="+CAStartEDR">+CAStartEDR</td></tr>
+                    <tr><td align="left" href="\ref CAStopEDR()" tooltip="+CAStopEDR">+CAStopEDR</td></tr>
+                    <tr><td align="left" href="\ref CAStartEDRListeningServer()" tooltip="+CAStartEDRListeningServer">+CAStartEDRListeningServer</td></tr>
+                    <tr><td align="left" href="\ref CAStartEDRDiscoveryServer()" tooltip="+CAStartEDRDiscoveryServer">+CAStartEDRDiscoveryServer</td></tr>
+                    <tr><td align="left" href="\ref CAGetEDRInterfaceInformation" tooltip="+CAGetEDRInterfaceInformation">+CAGetEDRInterfaceInformation</td></tr>
+                    <tr><td align="left" href="\ref CASendEDRUnicastData()" tooltip="+CASendEDRUnicastData">+CASendEDRUnicastData</td></tr>
+                    <tr><td align="left" href="\ref CASendEDRMulticastData()" tooltip="+CASendEDRMulticastData">+CASendEDRMulticastData</td></tr>
+                    <tr><td align="left" href="\ref CAReadEDRData()" tooltip="+CAReadEDRData">+CAReadEDRData</td></tr>
+                </table>>
+    ]
+
+    adapt04 [
+        tooltip = "LE Adapter",
+        label = "{LE Adapter| +CAInitializeLE()\l\n \n }",
+        URL = "\ref CAInitializeLE()"
+
+        shape = none
+        margin = 0
+        label = <<table border="1" cellspacing="0" cellborder="0">
+                    <tr><td href="\ref CAInitializeLE" tooltip="LE Adapter" bgcolor="gray">LE Adapter</td></tr>
+                    <hr/>
+                    <tr><td> </td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref CAInitializeLE()" tooltip="+CAInitializeLE">+CAInitializeLE</td></tr>
+                    <tr><td align="left" href="\ref CATerminateLE()" tooltip="+CATerminateLE">+CATerminateLE</td></tr>
+                    <tr><td align="left" href="\ref CAStartLE()" tooltip="+CAStartLE">+CAStartLE</td></tr>
+                    <tr><td align="left" href="\ref CAStopLE" tooltip="+CAStopLE">+CAStopLE</td></tr>
+                    <tr><td align="left" href="\ref CAStartLEListeningServer()" tooltip="+CAStartLEListeningServer">+CAStartLEListeningServer</td></tr>
+                    <tr><td align="left" href="\ref CAStartLEDiscoveryServer()" tooltip="+CAStartLEDiscoveryServer">+CAStartLEDiscoveryServer</td></tr>
+                    <tr><td align="left" href="\ref CAGetLEInterfaceInformation()" tooltip="+CAGetLEInterfaceInformation">+CAGetLEInterfaceInformation</td></tr>
+                    <tr><td align="left" href="\ref CASendLEUnicastData()" tooltip="+CASendLEUnicastData">+CASendLEUnicastData</td></tr>
+                    <tr><td align="left" href="\ref CASendLEMulticastData()" tooltip="+CASendLEMulticastData">+CASendLEMulticastData</td></tr>
+                    <tr><td align="left" href="\ref CAReadLEData()" tooltip="+CAReadLEData">+CAReadLEData</td></tr>
+                </table>>
+    ]
+
+
+    // UML Inheritance relationships
+    edge [
+        arrowtail = open,
+        dir = back
+    ]
+
+    {
+        conn_handler -> adapt01
+        conn_handler -> adapt02
+        conn_handler -> adapt03
+        conn_handler -> adapt04
+    }
+
+    // UML Aggregation relationships
+    edge [
+        arrowtail = odiamond,
+        dir = back
+    ]
+
+    msg_handler -> control
+    msg_handler -> threadpool
+    msg_handler -> thread_out
+    msg_handler -> thread_in
+    msg_handler -> thread_retrans
+    control -> conn_handler
+
+
+    // Additional 'layout' tweaks
+    {rank = same control threadpool thread_out thread_in thread_retrans}
+    edge [
+        style = invis
+    ]
+    threadpool -> thread_out -> control -> thread_in -> thread_retrans
+}
diff --git a/resource/docs/cpp-doc/devdox/dot/ca_arch_sketch.gv b/resource/docs/cpp-doc/devdox/dot/ca_arch_sketch.gv
new file mode 100644 (file)
index 0000000..fd6f322
--- /dev/null
@@ -0,0 +1,90 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+digraph G {
+    label = "Network Interface Creation";
+    fontsize = 10;
+
+    edge [
+        fontsize = 10
+    ]
+
+    node [
+        fontsize = 10,
+        shape = "record"
+    ]
+
+ // ----
+
+    msg_handler [
+        label = "{Message Handler| | }",
+        tooltip = "Message Handler",
+        URL = "\ref caf_ovr_comm_netinterface_msg"
+    ]
+
+    control [
+        label = "{Interface controller| | }",
+        tooltip = "Interface controller",
+        URL = "\ref caf_ovr_comm_netinterface_control"
+    ]
+
+    adapt01 [
+        label = "{Ethernet Adapter| | }",
+        tooltip = "Ethernet Adapter",
+        URL = "\ref caf_ovr_comm_netinterface_eth"
+    ]
+
+    adapt02 [
+        label = "{WiFi Adapter| | }",
+        tooltip = "WiFi Adapter",
+        URL = "\ref caf_ovr_comm_netinterface_wifi"
+    ]
+
+    adapt03 [
+        label = "{EDR Adapter| | }",
+        tooltip = "EDR Adapter",
+        URL = "\ref caf_ovr_comm_netinterface_edr"
+    ]
+
+    adapt04 [
+        label = "{LE Adapter| | }"
+        tooltip = "LE Adapter",
+        URL = "\ref caf_ovr_comm_netinterface_le"
+    ]
+
+    // UML Aggregation relationships
+    edge [
+        arrowtail = odiamond,
+        dir = back
+    ]
+
+    msg_handler -> control
+
+    // UML Composition relationships
+    edge [
+        arrowtail = diamond,
+        dir = back
+    ]
+
+    control -> adapt01
+    control -> adapt02
+    control -> adapt03
+    control -> adapt04
+}
diff --git a/resource/docs/cpp-doc/devdox/dot/ca_overview.gv b/resource/docs/cpp-doc/devdox/dot/ca_overview.gv
new file mode 100644 (file)
index 0000000..2ac92d7
--- /dev/null
@@ -0,0 +1,197 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+// Note that this diagram is not the best example of efficient
+// graphviz/doxygen use. It was recreating the look of an existing
+// graphic and thus is focused too much on appearance over
+// functionality.
+//
+
+digraph G {
+    label = "Abstracted Architecture";
+
+    z [
+        label = "Resource Introspection",
+        shape = box,
+        style = filled,
+        fillcolor="#efefef:#bdbdbd",
+        gradientangle=270,
+        width=8
+    ];
+
+    subgraph cluster_0 {
+        label = "Connectivity Framework";
+        labeljust="l";
+
+        yy [
+            label = "Connectivity API",
+            shape = box,
+            style = filled,
+            color = "#4a7bbd",
+            fillcolor="#e6efff:#a5c5ff",
+            gradientangle=270,
+            width=8
+        ];
+
+        subgraph cluster_1 {
+            label = "Control layer";
+            style=filled;
+            color = "#4a7bbd";
+            fillcolor="#e6efff:#a5c5ff";
+            gradientangle=270;
+
+            node [
+                style=filled,
+                color="#9cbd52",
+                fillcolor="#f7ffe6:#deffad",
+                gradientangle=270,
+                shape=box
+            ];
+
+            a0 [label="Network\nConfiguration"];
+            a1 [label="CoAP\nProtocol"];
+            a2 [label="Interface\nController"];
+
+            {rank = same a0 a1 a2}
+        }
+
+        subgraph cluster_2 {
+            label = "Transport Adapter";
+            style=filled;
+            color = "#4a7bbd"
+            fillcolor="#e6efff:#a5c5ff";
+            gradientangle=270;
+            node [
+                style=filled,
+                color="#9cbd52",
+                fillcolor="#f7ffe6:#deffad",
+                gradientangle=270,
+                shape=box
+            ];
+
+            bb [label = "Common Adapter Interface", width=5];
+
+            b0 [label="IP\nAdapter"];
+            b1 [label="LE GATT\nAdapter"];
+            b2 [label="BT SPP\nAdapter"];
+            b3 [label="XXX\nAdapter"];
+
+            {rank = same b0 b1 b2 b3}
+        }
+
+        subgraph cluster_3 {
+            label = "Platform Adapter";
+            style=filled;
+            color = "#4a7bbd"
+            fillcolor="#e6efff:#a5c5ff";
+            gradientangle=270;
+            node [
+                style=filled
+                color="#7b5aa5"
+                fillcolor="#f7e6f7:#c5b5ef";
+                gradientangle=270;
+                shape=box
+            ];
+
+            c0 [label="Ubuntu\nAdapter\n(ETH/WIFI/BT)"];
+            c1 [label="Android\nAdapter\n(WIFI/BLE/BT)"];
+            c2 [label="Tizen\nAdapter\n(WIFI/BLE/BT)"];
+            c3 [label="Arduino\nAdapter\n(ETH/WIFI/BLE)"];
+            c4 [label="Platform\n(6loWPAN)\n ", color="#f7e6f7"];
+
+            {rank = same c0 c1 c2 c3 c4}
+        }
+    }
+
+    {
+        node [
+            style = filled,
+            fillcolor="#efefef:#bdbdbd",
+            gradientangle=270,
+            shape=box
+        ];
+
+        d0 [label="Ubuntu"];
+        d1 [label="Android"];
+        d2 [label="Tizen"];
+        d3 [label="Arduino"];
+        d4 [label="????"];
+
+        {rank = same d0 d1 d2 d3 d4}
+    }
+
+    subgraph cluster_lgd {
+        label = "Legend";
+
+        node [
+            style = filled,
+            width=0.25,
+            height=0.25,
+            fixedsize=true,
+            shape=box,
+            gradientangle=270
+        ];
+
+        e0 [label=" ", color="#4a7bbd", fillcolor="#e6efff:#a5c5ff"];
+        e1 [label=" ", color="#9cbd52", fillcolor="#f7ffe6:#deffad"];
+        e2 [label=" ", color="#7b5aa5", fillcolor="#f7e6f7:#c5b5ef"];
+        e3 [label=" ", fillcolor="#efefef:#bdbdbd"];
+        e_dummy[shape=point, style=invis];
+
+        edge [penwidth=0,
+              arrowhead=none,
+              fontsize=10];
+        e0 -> e1 [label="CA Component    "];
+        e1 -> e2 [label="CA Module-platform independent    "];
+        e2 -> e3 [label="CA Module-platform specific    "];
+        e3 -> e_dummy [label="External"];
+
+        {rank = same e0 e1 e2 e3 e_dummy}
+    }
+
+    // In order to control placement of the sets of items in a
+    // top-to-bottom placement, invisible edges/arrows are used.
+    // This gives a logcial control for the physical appearance we want.
+    {
+        edge[style = invis];
+
+        // order groups to get top-to-bottom
+        z -> yy
+        yy -> {a0 a2}
+        a1 -> bb
+        {a0 a2} -> {b1 b2}
+        bb -> {b1 b2}
+        {b0 b1 b2 b3} -> c2
+        c0 -> d0
+        c1 -> d1
+        c2 -> d2
+        c3 -> d3
+        d0 -> e0
+        {d2} -> {e1 e2}
+        d4 -> e3
+
+        // order nodes left-to-right
+        a0 -> a1 -> a2
+        b0 -> b1 -> b2 -> b3
+        c0 -> c1 -> c2 -> c3 -> c4
+        d0 -> d1 -> d2 -> d3 -> d4
+        e0 -> e1 -> e2 -> e3
+    }
+}
diff --git a/resource/docs/cpp-doc/devdox/mainpage.dox b/resource/docs/cpp-doc/devdox/mainpage.dox
new file mode 100644 (file)
index 0000000..b2dc361
--- /dev/null
@@ -0,0 +1,43 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/**
+@mainpage
+
+This is documentation intended for internal use of developers actually
+working on the implementation code itself. At the moment this specific page
+is just a simplified placeholder.
+
+<hr>
+
+Quick starting points:
+
+- @ref ca_overview which replicates an existing requirements doc.
+  - An overview diagram in that document: @ref cao_overview
+- @ref ca_functional Minimal sample showing how diagrams and code doc can be
+  integrated.
+  - @ref caf_ovr_comm_netinterface a section with a minimal UML sketch
+  - @ref caf_ovr_comm_netinterface_detail a more detailed UML diagram
+- The 'Related Pages' tab
+
+Then see CAEthernetInitializeServer() for...
+- CAInitializeEthernet()
+- other
+*/
\ No newline at end of file
diff --git a/resource/docs/cpp-doc/doxygenLayout.xml b/resource/docs/cpp-doc/doxygenLayout.xml
new file mode 100644 (file)
index 0000000..330cb9a
--- /dev/null
@@ -0,0 +1,14 @@
+<doxygenlayout version="1.0">
+    <navindex>
+        <tab type="mainpage" visible="yes" title="Home"/>
+        <tab type="classes" visible="yes" title="API Reference">
+            <tab type="classlist" visible="yes" title=""/>
+            <tab type="hierarchy" visible="yes" title="" intro=""/>
+            <tab type="classmembers" visible="yes" title="" intro=""/>
+        </tab>
+        <tab type="files" visible="yes" title="">
+          <tab type="filelist" visible="yes" title="" intro=""/>
+          <tab type="globals" visible="yes" title="" intro=""/>
+        </tab>
+    </navindex>
+</doxygenlayout>
diff --git a/resource/docs/cpp-doc/guides/Home.txt b/resource/docs/cpp-doc/guides/Home.txt
new file mode 100644 (file)
index 0000000..4131aff
--- /dev/null
@@ -0,0 +1,13 @@
+/*!
+
+@mainpage Welcome
+
+IoTivity is an open source software framework enabling seamless device-to-device connectivity to address the emerging needs of the Internet of Things. These API references are for any developer trying to utilize the IoTivity project for building applications.
+
+\li <a href="annotated.html"><strong>API References</strong></a><br />Provides a reference to all public APIs available to utilize the power of IoTivity.
+
+\li <a href="https://www.iotivity.org/documentation"><strong>Getting Started Guides and Tutorials</strong></a><br />Detailed getting started guides and tutorials can be found on the iotivity.org website.
+
+\li <a href="https://wiki.iotivity.org"><strong>Wiki</strong></a><br />Additional documentation can be found on the IoTivity Wiki.
+
+*/
diff --git a/resource/docs/cpp-doc/html/footer.html b/resource/docs/cpp-doc/html/footer.html
new file mode 100644 (file)
index 0000000..f392185
--- /dev/null
@@ -0,0 +1,7 @@
+<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
+    <ul>
+        <li class="footer">Generated on $datetime</li>
+    </ul>
+</div>
+</body>
+</html>
\ No newline at end of file
diff --git a/resource/docs/cpp-doc/img/seq_find_resource.png b/resource/docs/cpp-doc/img/seq_find_resource.png
new file mode 100644 (file)
index 0000000..4bef8a9
Binary files /dev/null and b/resource/docs/cpp-doc/img/seq_find_resource.png differ
diff --git a/resource/docs/cpp-doc/img/seq_find_resource_2.png b/resource/docs/cpp-doc/img/seq_find_resource_2.png
new file mode 100644 (file)
index 0000000..671cb17
Binary files /dev/null and b/resource/docs/cpp-doc/img/seq_find_resource_2.png differ
diff --git a/resource/docs/cpp-doc/img/seq_find_resource_3.png b/resource/docs/cpp-doc/img/seq_find_resource_3.png
new file mode 100644 (file)
index 0000000..0e1cd33
Binary files /dev/null and b/resource/docs/cpp-doc/img/seq_find_resource_3.png differ
diff --git a/resource/docs/cpp-doc/img/seq_find_resource_4.png b/resource/docs/cpp-doc/img/seq_find_resource_4.png
new file mode 100644 (file)
index 0000000..55daccb
Binary files /dev/null and b/resource/docs/cpp-doc/img/seq_find_resource_4.png differ
diff --git a/resource/docs/cpp-doc/img/seq_get.png b/resource/docs/cpp-doc/img/seq_get.png
new file mode 100644 (file)
index 0000000..f905bb3
Binary files /dev/null and b/resource/docs/cpp-doc/img/seq_get.png differ
diff --git a/resource/docs/cpp-doc/img/seq_observe.png b/resource/docs/cpp-doc/img/seq_observe.png
new file mode 100644 (file)
index 0000000..82046fc
Binary files /dev/null and b/resource/docs/cpp-doc/img/seq_observe.png differ
diff --git a/resource/docs/cpp-doc/img/seq_put.png b/resource/docs/cpp-doc/img/seq_put.png
new file mode 100644 (file)
index 0000000..f2c82ca
Binary files /dev/null and b/resource/docs/cpp-doc/img/seq_put.png differ
diff --git a/resource/docs/cpp-doc/img/seq_register_resource.png b/resource/docs/cpp-doc/img/seq_register_resource.png
new file mode 100644 (file)
index 0000000..ef2c95d
Binary files /dev/null and b/resource/docs/cpp-doc/img/seq_register_resource.png differ
diff --git a/resource/docs/cpp-doc/img/seq_register_resource_2.png b/resource/docs/cpp-doc/img/seq_register_resource_2.png
new file mode 100644 (file)
index 0000000..25c4523
Binary files /dev/null and b/resource/docs/cpp-doc/img/seq_register_resource_2.png differ
diff --git a/resource/docs/cpp-doc/img/seq_stack_init.png b/resource/docs/cpp-doc/img/seq_stack_init.png
new file mode 100644 (file)
index 0000000..aa15e68
Binary files /dev/null and b/resource/docs/cpp-doc/img/seq_stack_init.png differ
diff --git a/resource/docs/cpp-doc/img/stack_diagram.png b/resource/docs/cpp-doc/img/stack_diagram.png
new file mode 100644 (file)
index 0000000..2d2ae09
Binary files /dev/null and b/resource/docs/cpp-doc/img/stack_diagram.png differ
index a18252a..b8885d7 100755 (executable)
@@ -1,5 +1,5 @@
 #******************************************************************
-# JAVA API generation 
+# JAVA API generation
 #
 # BASE
 #
@@ -24,24 +24,24 @@ RE_COMMON_PKG=org.iotivity.service
 RE_CLINET_PKG=org.iotivity.service.client
 RE_SERVER_PKG=org.iotivity.service.server
 
-TM_PATH="../../service/things-manager/sdk/java/src/"
+TM_SRCS="../../service/things-manager/sdk/java/src/org/iotivity/service/tm/ThingsConfiguration.java \
+         ../../service/things-manager/sdk/java/src/org/iotivity/service/tm/ThingsMaintenance.java"
 TM_PKG=org.iotivity.service.tm
 
 RH_PATH="../../service/resource-hosting/android/resource_hosting/src/"
 RH_PKG=org.iotivity.ResourceHosting
 
 
-EASYSETUP_PATH="../../service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/"
+EASYSETUP_PATH="../../service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/"
 EASYSETUP_PKG=org.iotivity.service.easysetup.mediator
 
-SIMULATOR_PATH="../../service/simulator/java/sdk/src/"
-SIMULATOR_COMMON_PKG=org.oic.simulator
-SIMULATOR_CLIENT_PKG=org.oic.simulator.clientcontroller
-SIMULATOR_SERVER_PKG=org.oic.simulator.serviceprovider
+
+RESOURCECONTAINER_PATH="../../service/resource-container/android/resource-container/src/main/java/"
+RESOURCECONTAINER_PKG=org.iotivity.service.resourcecontainer
 
 javadoc -public -splitindex -d ./Java_API -sourcepath \
-    $BASE_PATH:$RE_PATH:$TM_PATH:$RH_PATH:$EASYSETUP_PATH:$SIMULATOR_PATH \
-    $BASE_PKG $RE_COMMON_PKG  $RE_CLINET_PKG $RE_SERVER_PKG $TM_PKG $RH_PKG $EASYSETUP_PKG \
-    $SIMULATOR_COMMON_PKG  $SIMULATOR_CLIENT_PKG $SIMULATOR_SERVER_PKG
+    $BASE_PATH:$RE_PATH:$RH_PATH:$EASYSETUP_PATH:$RESOURCECONTAINER_PATH \
+    $BASE_PKG $RE_COMMON_PKG  $RE_CLINET_PKG $RE_SERVER_PKG $TM_SRCS $TM_PKG $RH_PKG $EASYSETUP_PKG \
+    $RESOURCECONTAINER_PKG 
 
 
index 9b61cc1..9fad828 100644 (file)
@@ -88,9 +88,9 @@ devicediscoveryclient = examples_env.Program('devicediscoveryclient', 'devicedis
 threadingsample = examples_env.Program('threadingsample', 'threadingsample.cpp')
 
 clientjson = examples_env.Install(env.get('BUILD_DIR') + '/resource/examples/',
-                               env.get('SRC_DIR') + '/resource/examples/' + 'oic_svr_db_client.json')
+                               env.get('SRC_DIR') + '/resource/examples/' + 'oic_svr_db_client.dat')
 serverjson = examples_env.Install(env.get('BUILD_DIR') + '/resource/examples/',
-                               env.get('SRC_DIR') + '/resource/examples/' + 'oic_svr_db_server.json')
+                               env.get('SRC_DIR') + '/resource/examples/' + 'oic_svr_db_server.dat')
 Alias("examples", [simpleserver, simpleclient,
                simpleserverHQ, simpleclientHQ,
                fridgeserver, fridgeclient,
@@ -103,4 +103,4 @@ Alias("examples", [simpleserver, simpleclient,
                threadingsample,
                serverjson, clientjson
      ])
-env.AppendTarget('examples')
\ No newline at end of file
+env.AppendTarget('examples')
index 8f9ec9b..2112ae6 100644 (file)
@@ -29,6 +29,7 @@
 
 #include "OCPlatform.h"
 #include "OCApi.h"
+#include "ocpayload.h"
 
 using namespace OC;
 
@@ -137,6 +138,8 @@ int main()
 
 
     result = SetDeviceInfo(deviceName);
+    OCResourcePayloadAddStringLL(&deviceInfo.types, "oic.wk.d");
+    OCResourcePayloadAddStringLL(&deviceInfo.types, "oic.d.tv");
 
     result = OCPlatform::registerDeviceInfo(deviceInfo);
 
@@ -164,7 +167,3 @@ int main()
     return 0;
 
 }
-
-
-
-
index 0c7075a..bbbc748 100644 (file)
@@ -187,6 +187,7 @@ class ClientFridge
         std::cout << "Got a response from get from the " << resourceName << std::endl;
         std::cout << "Get ID is "<<getId<<" and resource URI is " << resource->uri() << std::endl;
         std::cout << "Get eCode is "<< eCode << std::endl;
+        std::cout << "OCRepresentation uri is " << rep.getUri() << std::endl;
 
         printHeaderOptions(headerOptions);
 
old mode 100644 (file)
new mode 100755 (executable)
index e1ec55a..f4b5e4d
@@ -60,7 +60,7 @@ void foundResource(std::shared_ptr< OCResource > resource)
             cout << "\tResource Type : " << resource->getResourceTypes().front() << endl;
             if (resourceURI == "/a/light" || resourceURI == "/a/fan")
             {
-                OCResourceHandle foundResourceHandle;
+                OCResourceHandle foundResourceHandle = nullptr;
                 OCStackResult result = OCPlatform::registerResource(foundResourceHandle, resource);
                 cout << "\tresource registed!" << endl;
                 if (result == OC_STACK_OK)
diff --git a/resource/examples/oic_svr_db_client.dat b/resource/examples/oic_svr_db_client.dat
new file mode 100644 (file)
index 0000000..6feb473
Binary files /dev/null and b/resource/examples/oic_svr_db_client.dat differ
index c16acb8..5052bd1 100644 (file)
-{
-    "acl": [
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/res",
-                "/oic/d",
-                "/oic/p",
-                "/oic/res/types/d",
-                "/oic/ad",
-                "/oic/sec/acl"
-                       ],
-                       "perms": 2,
-                       "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-               },
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/sec/doxm",
-                "/oic/sec/pstat"
-             ],
-             "perms": 2,
-             "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-        }
-       ],
-       "pstat":        {
-               "isop": true,
-               "deviceid":     "ZGV2aWNlaWQAAAAAABhanw==",
-               "ch": 0,
-               "cm":   0,
-               "tm":   0,
-               "om":   3,
-               "sm":   [3]
-       },
-       "doxm": {
-               "oxm":  [0],
-               "oxmsel": 0,
-               "sct": 1,
-               "owned": true,
-               "deviceid":     "MjIyMjIyMjIyMjIyMjIyMg==",
-               "ownr": "MjIyMjIyMjIyMjIyMjIyMg=="
-       },
-    "cred":    [{
-               "credid": 1,
-               "sub": "MTExMTExMTExMTExMTExMQ==",
-               "credtyp": 1,
-               "pvdata": "QUFBQUFBQUFBQUFBQUFBQQ==",
-        "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-       }]
-}
+{\r
+    "acl": {\r
+        "aclist": {\r
+            "aces": [\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/res",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/p",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/types/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/ad",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/acl",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/doxm",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        } ,\r
+                        {\r
+                            "href": "/oic/sec/pstat",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                }\r
+            ]\r
+        },\r
+        "rowneruuid" : "32323232-3232-3232-3232-323232323232"\r
+    },\r
+    "pstat": {\r
+        "isop": true,\r
+        "deviceuuid": "32323232-3232-3232-3232-323232323232",\r
+        "rowneruuid": "32323232-3232-3232-3232-323232323232",\r
+        "cm": 0,\r
+        "tm": 0,\r
+        "om": 3,\r
+        "sm": 3\r
+        },\r
+    "doxm": {\r
+        "oxms": [0],\r
+        "oxmsel": 0,\r
+        "sct": 1,\r
+        "owned": true,\r
+        "deviceuuid": "32323232-3232-3232-3232-323232323232",\r
+        "devowneruuid": "32323232-3232-3232-3232-323232323232",\r
+        "rowneruuid": "32323232-3232-3232-3232-323232323232",\r
+        "dpc": false\r
+    },\r
+    "cred": {\r
+        "creds": [\r
+            {\r
+                "credid": 1,\r
+                "subjectuuid": "31313131-3131-3131-3131-313131313131",\r
+                "credtype": 1,\r
+                "privatedata": {\r
+                    "data": "AAAAAAAAAAAAAAAA",\r
+                    "encoding": "oic.sec.encoding.raw"\r
+                }\r
+            }\r
+        ],\r
+        "rowneruuid": "32323232-3232-3232-3232-323232323232"\r
+    }\r
+}
\ No newline at end of file
diff --git a/resource/examples/oic_svr_db_server.dat b/resource/examples/oic_svr_db_server.dat
new file mode 100644 (file)
index 0000000..6834a79
Binary files /dev/null and b/resource/examples/oic_svr_db_server.dat differ
index b6bb1eb..921cc9d 100644 (file)
-{
-    "acl": [
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/res",
-                "/oic/d",
-                "/oic/p",
-                "/oic/res/types/d",
-                "/oic/ad",
-                "/oic/sec/acl"
-                       ],
-                       "perms": 2,
-                       "ownrs" : ["MTExMTExMTExMTExMTExMQ=="]
-               },
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/sec/doxm",
-                "/oic/sec/pstat"
-             ],
-             "perms": 2,
-             "ownrs" : ["MTExMTExMTExMTExMTExMQ=="]
-        },
-        {
-            "sub": "Kg==",
-            "rsrc": ["/a/light"],
-            "perms": 6,
-            "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-        }
-       ],
-       "pstat":        {
-               "isop": true,
-               "deviceid":     "ZGV2aWNlaWQAAAAAABhanw==",
-               "ch": 0,
-               "cm":   0,
-               "tm":   0,
-               "om":   3,
-               "sm":   [3]
-       },
-       "doxm": {
-               "oxm":  [0],
-               "oxmsel": 0,
-               "sct": 1,
-               "owned": true,
-               "deviceid":     "MTExMTExMTExMTExMTExMQ==",
-               "ownr": "MjIyMjIyMjIyMjIyMjIyMg=="
-       },
-    "cred":    [{
-               "credid": 1,
-               "sub": "MjIyMjIyMjIyMjIyMjIyMg==",
-               "credtyp": 1,
-               "pvdata": "QUFBQUFBQUFBQUFBQUFBQQ==",
-        "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
-       }]
-}
+{\r
+    "acl": {\r
+        "aclist": {\r
+            "aces": [\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/res",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/p",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/types/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/ad",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/acl",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/doxm",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        } ,\r
+                        {\r
+                            "href": "/oic/sec/pstat",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/a/light",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 6\r
+                }\r
+            ]\r
+        },\r
+        "rowneruuid" : "31313131-3131-3131-3131-313131313131"\r
+    },\r
+    "pstat": {\r
+        "isop": true,\r
+        "deviceuuid": "31313131-3131-3131-3131-313131313131",\r
+        "rowneruuid": "31313131-3131-3131-3131-313131313131",\r
+        "cm": 0,\r
+        "tm": 0,\r
+        "om": 3,\r
+        "sm": 3\r
+        },\r
+    "doxm": {\r
+        "oxms": [0],\r
+        "oxmsel": 0,\r
+        "sct": 1,\r
+        "owned": true,\r
+        "deviceuuid": "31313131-3131-3131-3131-313131313131",\r
+        "devowneruuid": "32323232-3232-3232-3232-323232323232",\r
+        "rowneruuid": "31313131-3131-3131-3131-313131313131",\r
+        "dpc": false\r
+    },\r
+    "cred": {\r
+        "creds": [\r
+            {\r
+                "credid": 1,\r
+                "subjectuuid": "32323232-3232-3232-3232-323232323232",\r
+                "credtype": 1,\r
+                "privatedata": {\r
+                    "data": "AAAAAAAAAAAAAAAA",\r
+                    "encoding": "oic.sec.encoding.raw"\r
+                }\r
+            }\r
+        ],\r
+        "rowneruuid": "31313131-3131-3131-3131-313131313131"\r
+    }\r
+}
\ No newline at end of file
index e43618a..07d55f0 100644 (file)
@@ -31,6 +31,7 @@
 
 using namespace OC;
 
+static const char* SVR_DB_FILE_NAME = "./oic_svr_db_client.dat";
 typedef std::map<OCResourceIdentifier, std::shared_ptr<OCResource>> DiscoveredResourceMap;
 
 DiscoveredResourceMap discoveredResources;
@@ -432,7 +433,7 @@ void checkObserverValue(int value)
 
 static FILE* client_open(const char* /*path*/, const char *mode)
 {
-    return fopen("./oic_svr_db_client.json", mode);
+    return fopen(SVR_DB_FILE_NAME, mode);
 }
 
 int main(int argc, char* argv[]) {
index e98be52..97a6074 100644 (file)
@@ -36,6 +36,7 @@ using namespace OC;
 using namespace std;
 namespace PH = std::placeholders;
 
+static const char* SVR_DB_FILE_NAME = "./oic_svr_db_server.dat";
 int gObservation = 0;
 void * ChangeLightRepresentation (void *param);
 void * handleSlowResponse (void *param, std::shared_ptr<OCResourceRequest> pRequest);
@@ -484,7 +485,7 @@ void PrintUsage()
 
 static FILE* client_open(const char* /*path*/, const char *mode)
 {
-    return fopen("./oic_svr_db_server.json", mode);
+    return fopen(SVR_DB_FILE_NAME, mode);
 }
 
 int main(int argc, char* argv[])
index 327bf13..0506e0f 100644 (file)
@@ -25,8 +25,8 @@
  * AttributeValue.
  */
 
-#ifndef __ATTRIBUTEVALUE_H
-#define __ATTRIBUTEVALUE_H
+#ifndef OC_ATTRIBUTEVALUE_H_
+#define OC_ATTRIBUTEVALUE_H_
 
 // These defines are required to get the boost::variant to hold more than 20 items.
 // documentation requires that you use a power of 10
@@ -131,4 +131,4 @@ namespace OC
 
     std::ostream& operator << (std::ostream& os, const AttributeType at);
 }
-#endif // __ATTRIBUTEVALUE_H
+#endif // OC_ATTRIBUTEVALUE_H_
diff --git a/resource/include/CAManager.h b/resource/include/CAManager.h
new file mode 100644 (file)
index 0000000..0a69743
--- /dev/null
@@ -0,0 +1,58 @@
+/* ****************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef CA_MANAGER_H_
+#define CA_MANAGER_H_
+
+#include <OCApi.h>
+
+namespace OC
+{
+    /**
+    * This namespace contains the main entrance/functionality to monitoring network changes.
+    * It may be used with OC::CAManager::functionName. To set a custom callback function,
+    * the implementer must make a call to CAManager::setNetworkMonitorHandler.
+    */
+    namespace CAManager
+    {
+        // typedef to get adapter status changes from CA.
+        typedef std::function<void(OCTransportAdapter,
+                                   const std::string&, bool)> ConnectionChangedCallback;
+
+        // typedef to get connection status changes from CA.
+        typedef std::function<void(OCTransportAdapter, bool)> AdapterChangedCallback;
+
+        /**
+        * Set network monitoring handler.
+        * @param adapterHandler adapter state change handler to handle changes for
+        *                       any transport types.
+        * @param connectionHandler connection state change handler to handle changes for
+        *                          connection with remote devices.
+        * @return Returns ::OC_STACK_OK if success.
+        */
+        OCStackResult setNetworkMonitorHandler(AdapterChangedCallback adapterHandler,
+                                               ConnectionChangedCallback connectionHandler);
+    }
+}
+
+#endif // CA_MANAGER_H_
+
+
+
index 272cd44..bfbb00f 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef _I_CLIENT_WRAPPER_H_
-#define _I_CLIENT_WRAPPER_H_
+#ifndef OC_I_CLIENT_WRAPPER_H_
+#define OC_I_CLIENT_WRAPPER_H_
 
 #include <memory>
 #include <string>
index 66f2007..62f878a 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef _I_SERVER_WRAPPER_H_
-#define _I_SERVER_WRAPPER_H_
+#ifndef OC_I_SERVER_WRAPPER_H_
+#define OC_I_SERVER_WRAPPER_H_
 
 #include <memory>
 #include <string>
index f6b7764..62830d5 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef _IN_PROC_CLIENT_WRAPPER_H_
-#define _IN_PROC_CLIENT_WRAPPER_H_
+#ifndef OC_IN_PROC_CLIENT_WRAPPER_H_
+#define OC_IN_PROC_CLIENT_WRAPPER_H_
 
 #include <thread>
 #include <mutex>
index 8eb78e3..2e04e58 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef _IN_PROC_SERVER_WRAPPER_H_
-#define _IN_PROC_SERVER_WRAPPER_H_
+#ifndef OC_IN_PROC_SERVER_WRAPPER_H_
+#define OC_IN_PROC_SERVER_WRAPPER_H_
 
 #include <thread>
 #include <mutex>
index bc5a3d2..ab5282f 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef _INITIALIZE_EXCEPTION_H_
-#define _INITIALIZE_EXCEPTION_H_
+#ifndef OC_INITIALIZE_EXCEPTION_H_
+#define OC_INITIALIZE_EXCEPTION_H_
 
 #include <stdexcept>
 #include "StringConstants.h"
index 2e7f7f7..2691007 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef _OCANDROID_H_
-#define _OCANDROID_H_
+#ifndef OC_ANDROID_H_
+#define OC_ANDROID_H_
 
 #ifdef __ANDROID__
 #include <string>
index ef27844..c0fdf93 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef __INTEL_OCAPI_H_2014_07_10
-#define __INTEL_OCAPI_H_2014_07_10
+#ifndef OC_OCAPI_H_
+#define OC_OCAPI_H_
 
 #include <string>
 #include <sstream>
index 849bacd..1d70e7d 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef __INTEL_OCEXCEPTION_H_2014_07_10
- #define __INTEL_OCEXCEPTION_H_2014_07_10
+#ifndef OC_EXCEPTION_H_
+#define OC_EXCEPTION_H_
 
 #include <stdexcept>
 #include <string>
index c70ecc0..65ec176 100644 (file)
@@ -25,8 +25,8 @@
  * OCHeaderOption.
  */
 
-#ifndef __OCHEADEROPTION_H
-#define __OCHEADEROPTION_H
+#ifndef OC_HEADEROPTION_H_
+#define OC_HEADEROPTION_H_
 
 #include <OCException.h>
 #include <StringConstants.h>
@@ -97,4 +97,4 @@ namespace OC
     } // namespace HeaderOption
 } // namespace OC
 
-#endif //__OCHEADEROPTION_H
+#endif // OC_HEADEROPTION_H_
index 04a1848..fefeb35 100644 (file)
@@ -25,8 +25,8 @@
  * OCPlatform.
  */
 
-#ifndef __OCPLATFORM_H
-#define __OCPLATFORM_H
+#ifndef OC_PLATFORM_H_
+#define OC_PLATFORM_H_
 #include <OCApi.h>
 #include <OCPlatform_impl.h>
 namespace OC
@@ -50,40 +50,57 @@ namespace OC
         typedef OCDoHandle OCPresenceHandle;
 
         /**
-        * API for notifying base that resource's attributes have changed.
-        *
-        * @param OCResourceHandle resource handle of the resource
-        * @param QualityOfService the quality of communication
-        *
-        * @return Returns ::OC_STACK_OK if success.
-        * @note This API is for server side only.
-        * @note OCResourceHandle is defined in ocstack.h
-        * @note OCStackResult is defined in ocstack.h.
-        * @see notifyAllObservers(OCResourceHandle)
-        * @see notifyAllObservers(OCResourceHandle, QualityOfService)
-        */
+         * API for notifying base that resource's attributes have changed.
+         *
+         * @param resourceHandle resource handle of the resource
+         *
+         * @return Returns ::OC_STACK_OK if success.
+         * @note This API is for server side only.
+         * @note OCResourceHandle is defined in ocstack.h
+         * @note OCStackResult is defined in ocstack.h.
+         * @see notifyAllObservers(OCResourceHandle, QualityOfService)
+         */
         OCStackResult notifyAllObservers(OCResourceHandle resourceHandle);
+
+        /**
+         * @overload
+         *
+         * @param resourceHandle resource handle of the resource
+         * @param QoS the quality of communication
+         * @see notifyAllObservers(OCResourceHandle)
+         */
         OCStackResult notifyAllObservers(OCResourceHandle resourceHandle, QualityOfService QoS);
 
         /**
-        * API for notifying only specific clients that resource's attributes have changed.
-        *
-        * @param OCResourceHandle resource handle of the resource
-        * @param observationIds std vector of observationIds. These set of ids are ones which
-        * which will be notified upon resource change.
-        * @param responsePtr OCResourceResponse pointer used by app to fill the response for this
-        * resource change.
-        * @param QualityOfService the quality of communication
-        *
-        * @return Returns ::OC_STACK_OK if success.
-        * @note This API is for server side only.
-        * @note OCResourceHandle is defined in ocstack.h.
-        * @note OCStackResult is defined in ocstack.h.
-        */
+         * API for notifying only specific clients that resource's attributes have changed.
+         *
+         * @param resourceHandle resource handle of the resource
+         * @param observationIds std vector of observationIds. These set of ids are ones which
+         * which will be notified upon resource change.
+         * @param responsePtr OCResourceResponse pointer used by app to fill the response for this
+         * resource change.
+         *
+         * @return Returns ::OC_STACK_OK if success.
+         * @note This API is for server side only.
+         * @note OCResourceHandle is defined in ocstack.h.
+         * @note OCStackResult is defined in ocstack.h.
+         * @see notifyListOfObservers(OCResourceHandle, ObservationIds&, const std::shared_ptr<OCResourceResponse>, QualityOfService)
+         */
         OCStackResult notifyListOfObservers(
                     OCResourceHandle resourceHandle,
                     ObservationIds& observationIds,
                     const std::shared_ptr<OCResourceResponse> responsePtr);
+        /**
+         * @overload
+         *
+         * @param resourceHandle resource handle of the resource
+         * @param observationIds std vector of observationIds. These set of ids are ones which
+         * which will be notified upon resource change.
+         * @param responsePtr OCResourceResponse pointer used by app to fill the response for this
+         * resource change.
+         * @param QoS the quality of communication
+         * @see notifyListOfObservers(OCResourceHandle, ObservationIds&, const std::shared_ptr<OCResourceResponse>)
+         */
         OCStackResult notifyListOfObservers(
                     OCResourceHandle resourceHandle,
                     ObservationIds& observationIds,
@@ -91,78 +108,126 @@ namespace OC
                     QualityOfService QoS);
 
         /**
-        * API for Service and Resource Discovery.
-        * @note This API applies to client side only.
-        *
-        * @param host Host IP Address of a service to direct resource discovery query. If null or
-        *        empty, performs multicast resource discovery query
-        * @param resourceURI name of the resource. If null or empty, performs search for all
-        *       resource names
-        * @param connectivityType ::OCConnectivityType type of connectivity indicating the
-        *                           interface. Example: OC_WIFI, OC_ETHERNET, OC_ALL
-        * @param resourceHandler Handles callbacks, success states and failure states.
-        *
-        *        Four modes of discovery defined as follows:
-        *        (NULL/Empty, NULL/Empty) - Performs ALL service discovery AND ALL resource
-        *           discovery.
-        *        (NULL/Empty, Not Empty) - Performs query for a filtered/scoped/particular
-        *                                   resource(s) from ALL services.
-        *        (Not Empty, NULL/Empty) - Performs ALL resource discovery on a particular service.
-        *        (Not Empty, Not Empty) - Performs query for a filtered/scoped/particular
-        *                                   resource(s)
-        *                                  from a particular service.
-        * @param QualityOfService the quality of communication
-        *
-        * @return Returns ::OC_STACK_OK if success.
-        * @note First parameter 'host' currently represents an IP address. This will change in
-        * future and will refer to endpoint interface so that we can refer to other transports such
-        * as BTH etc.
-        * @note OCStackResult is defined in ocstack.h.
-        */
+         * API for Service and Resource Discovery.
+         * @note This API applies to client side only.
+         *
+         * @param host Host IP Address of a service to direct resource discovery query. If null or
+         *        empty, performs multicast resource discovery query
+         * @param resourceURI name of the resource. If null or empty, performs search for all
+         *       resource names
+         * @param connectivityType ::OCConnectivityType type of connectivity indicating the
+         *                           interface. Example: OC_WIFI, OC_ETHERNET, OC_ALL
+         * @param resourceHandler Handles callbacks, success states and failure states.
+         *
+         *        Four modes of discovery defined as follows:
+         *        (NULL/Empty, NULL/Empty) - Performs ALL service discovery AND ALL resource
+         *           discovery.
+         *        (NULL/Empty, Not Empty) - Performs query for a filtered/scoped/particular
+         *                                   resource(s) from ALL services.
+         *        (Not Empty, NULL/Empty) - Performs ALL resource discovery on a particular service.
+         *        (Not Empty, Not Empty) - Performs query for a filtered/scoped/particular
+         *                                   resource(s)
+         *                                  from a particular service.
+         *
+         * @return Returns ::OC_STACK_OK if success.
+         * @note First parameter 'host' currently represents an IP address. This will change in
+         * future and will refer to endpoint interface so that we can refer to other transports such
+         * as BTH etc.
+         * @note OCStackResult is defined in ocstack.h.
+         * @see findResource(const std::string&, const std::string&, OCConnectivityType, FindCallback, QualityOfService)
+         */
         OCStackResult findResource(const std::string& host, const std::string& resourceURI,
                     OCConnectivityType connectivityType, FindCallback resourceHandler);
+        /**
+         * @overload
+         *
+         * @param host Host IP Address of a service to direct resource discovery query. If null or
+         *        empty, performs multicast resource discovery query
+         * @param resourceURI name of the resource. If null or empty, performs search for all
+         *       resource names
+         * @param connectivityType ::OCConnectivityType type of connectivity indicating the
+         *                           interface. Example: OC_WIFI, OC_ETHERNET, OC_ALL
+         * @param resourceHandler Handles callbacks, success states and failure states.
+         *
+         *        Four modes of discovery defined as follows:
+         *        (NULL/Empty, NULL/Empty) - Performs ALL service discovery AND ALL resource
+         *           discovery.
+         *        (NULL/Empty, Not Empty) - Performs query for a filtered/scoped/particular
+         *                                   resource(s) from ALL services.
+         *        (Not Empty, NULL/Empty) - Performs ALL resource discovery on a particular service.
+         *        (Not Empty, Not Empty) - Performs query for a filtered/scoped/particular
+         *                                   resource(s)
+         *                                  from a particular service.
+         * @param QoS QualityOfService the quality of communication
+         * @see findResource(const std::string&, const std::string&, OCConnectivityType, FindCallback)
+         */
         OCStackResult findResource(const std::string& host, const std::string& resourceURI,
                     OCConnectivityType connectivityType, FindCallback resourceHandler,
                     QualityOfService QoS);
 
         /**
-        * API for Device Discovery
-        *
-        *
-        * @param host Host IP Address. If null or empty, Multicast is performed.
-        * @param deviceURI Uri containing address to the virtual device in C Stack
+         * API for Device Discovery
+         *
+         *
+         * @param host Host IP Address. If null or empty, Multicast is performed.
+         * @param deviceURI Uri containing address to the virtual device in C Stack
                                 ("/oic/d")
-        * @param connectivityType ::OCConnectivityType type of connectivity indicating the
-        *                           interface. Example: OC_WIFI, OC_ETHERNET, OC_ALL
-        * @param deviceInfoHandler device discovery callback
-        * @param QoS the quality of communication
-        *
-        * @return Returns ::OC_STACK_OK if success.
-        * @note OCStackResult is defined in ocstack.h.
-        */
+         * @param connectivityType ::OCConnectivityType type of connectivity indicating the
+         *                           interface. Example: OC_WIFI, OC_ETHERNET, OC_ALL
+         * @param deviceInfoHandler device discovery callback
+         *
+         * @return Returns ::OC_STACK_OK if success.
+         * @note OCStackResult is defined in ocstack.h.
+         * @see getDeviceInfo(const std::string&, const std::string&, OCConnectivityType, FindDeviceCallback, QualityOfService)
+         */
         OCStackResult getDeviceInfo(const std::string& host, const std::string& deviceURI,
                     OCConnectivityType connectivityType, FindDeviceCallback deviceInfoHandler);
+        /**
+         * @overload
+         *
+         * @param host Host IP Address. If null or empty, Multicast is performed.
+         * @param deviceURI Uri containing address to the virtual device in C Stack
+                                ("/oic/d")
+         * @param connectivityType ::OCConnectivityType type of connectivity indicating the
+         *                           interface. Example: OC_WIFI, OC_ETHERNET, OC_ALL
+         * @param deviceInfoHandler device discovery callback
+         * @param QoS the quality of communication
+         * @see getDeviceInfo(const std::string&, const std::string&, OCConnectivityType, FindDeviceCallback)
+         */
         OCStackResult getDeviceInfo(const std::string& host, const std::string& deviceURI,
                     OCConnectivityType connectivityType, FindDeviceCallback deviceInfoHandler,
                     QualityOfService QoS);
 
         /**
-        * API for Platform Discovery
-        *
-        *
-        * @param host Host IP Address. If null or empty, Multicast is performed.
-        * @param platformURI Uri containing address to the virtual platform in C Stack
+         * API for Platform Discovery
+         *
+         *
+         * @param host Host IP Address. If null or empty, Multicast is performed.
+         * @param platformURI Uri containing address to the virtual platform in C Stack
                                 ("/oic/p")
-        * @param connectivityType ::OCConnectivityType type of connectivity indicating the
-        *                           interface. Example: OC_WIFI, OC_ETHERNET, OC_ALL
-        * @param platformInfoHandler platform discovery callback
-        * @param QoS the quality of communication
-        *
-        * @return Returns ::OC_STACK_OK if success.
-        * @note OCStackResult is defined in ocstack.h.
-        */
+         * @param connectivityType ::OCConnectivityType type of connectivity indicating the
+         *                           interface. Example: OC_WIFI, OC_ETHERNET, OC_ALL
+         * @param platformInfoHandler platform discovery callback
+         *
+         * @return Returns ::OC_STACK_OK if success.
+         *
+         * @note OCStackResult is defined in ocstack.h.
+         * @see getPlatformInfo(const std::string&, const std::string&, OCConnectivityType, FindPlatformCallback, QualityOfService)
+         */
         OCStackResult getPlatformInfo(const std::string& host, const std::string& platformURI,
                     OCConnectivityType connectivityType, FindPlatformCallback platformInfoHandler);
+        /**
+         * @overload
+         *
+         * @param host Host IP Address. If null or empty, Multicast is performed.
+         * @param platformURI Uri containing address to the virtual platform in C Stack
+                                ("/oic/p")
+         * @param connectivityType ::OCConnectivityType type of connectivity indicating the
+         *                           interface. Example: OC_WIFI, OC_ETHERNET, OC_ALL
+         * @param platformInfoHandler platform discovery callback
+         * @param QoS the quality of communication
+         * @see getPlatformInfo(const std::string&, const std::string&, OCConnectivityType, FindPlatformCallback)
+         */
         OCStackResult getPlatformInfo(const std::string& host, const std::string& platformURI,
                     OCConnectivityType connectivityType, FindPlatformCallback platformInfoHandler,
                     QualityOfService QoS);
@@ -202,15 +267,15 @@ namespace OC
                         uint8_t resourceProperty);
 
         /**
-        * This API registers a resource with the server
-        * @note This API applies to server & client side.
-
-        * @param resourceHandle Upon successful registration, resourceHandle will be filled
-        * @param OCResource The instance of OCResource that all data filled.
-        *
-        * @return Returns ::OC_STACK_OK if success.
-        * @note OCStackResult is defined in ocstack.h.
-        */
+         * This API registers a resource with the server
+         * @note This API applies to server & client side.
+         *
+         * @param resourceHandle Upon successful registration, resourceHandle will be filled
+         * @param resource The instance of OCResource that all data filled.
+         *
+         * @return Returns ::OC_STACK_OK if success.
+         * @note OCStackResult is defined in ocstack.h.
+         */
         OCStackResult registerResource(OCResourceHandle& resourceHandle,
                         const std::shared_ptr< OCResource > resource);
 
@@ -411,25 +476,40 @@ namespace OC
         OCStackResult stopPresence();
 
         /**
-        * subscribes to a server's presence change events.  By making this subscription,
-        * every time a server adds/removes/alters a resource, starts or is intentionally
-        * stopped (potentially more to be added later).
-        *
-        * @param presenceHandle a handle object that can be used to identify this subscription
-        *               request.  It can be used to unsubscribe from these events in the future.
-        *               It will be set upon successful return of this method.
-        * @param host The IP address/addressable name of the server to subscribe to.
-        *               This should be in the format coap://address:port
-        * @param connectivityType ::OCConnectivityType type of connectivity indicating the
-        *                           interface. Example: OC_WIFI, OC_ETHERNET, OC_ALL
-        * @param resourceType a resource type specified as a filter for subscription callbacks.
-        * @param presenceHandler callback function that will receive notifications/subscription
-        *               events
-        *
-        * @return Returns ::OC_STACK_OK if success.
-        */
+         * subscribes to a server's presence change events.  By making this subscription,
+         * every time a server adds/removes/alters a resource, starts or is intentionally
+         * stopped (potentially more to be added later).
+         *
+         * @param presenceHandle a handle object that can be used to identify this subscription
+         *               request.  It can be used to unsubscribe from these events in the future.
+         *               It will be set upon successful return of this method.
+         * @param host The IP address/addressable name of the server to subscribe to.
+         *               This should be in the format coap://address:port
+         * @param connectivityType ::OCConnectivityType type of connectivity indicating the
+         *                           interface. Example: OC_WIFI, OC_ETHERNET, OC_ALL
+         * @param presenceHandler callback function that will receive notifications/subscription
+         *               events
+         *
+         * @return Returns ::OC_STACK_OK if success.
+         * @copydoc subscribePresence(OCPresenceHandle&, const std::string&, resourceType, OCConnectivityType, SubscribeCallback)
+         */
         OCStackResult subscribePresence(OCPresenceHandle& presenceHandle, const std::string& host,
                         OCConnectivityType connectivityType, SubscribeCallback presenceHandler);
+        /**
+         * @overload
+         *
+         * @param presenceHandle a handle object that can be used to identify this subscription
+         *               request.  It can be used to unsubscribe from these events in the future.
+         *               It will be set upon successful return of this method.
+         * @param host The IP address/addressable name of the server to subscribe to.
+         *               This should be in the format coap://address:port
+         * @param resourceType a resource type specified as a filter for subscription callbacks.
+         * @param connectivityType ::OCConnectivityType type of connectivity indicating the
+         *                           interface. Example: OC_WIFI, OC_ETHERNET, OC_ALL
+         * @param presenceHandler callback function that will receive notifications/subscription
+         *               events
+         * @see subscribePresence(OCPresenceHandle&, const std::string&, OCConnectivityType, SubscribeCallback)
+         */
         OCStackResult subscribePresence(OCPresenceHandle& presenceHandle, const std::string& host,
                         const std::string& resourceType, OCConnectivityType connectivityType,
                         SubscribeCallback presenceHandler);
@@ -492,7 +572,7 @@ namespace OC
     }
 }
 
-#endif //__OCPLATFORM_H
+#endif // OC_PLATFORM_H_
 
 
 
index fd221bb..6ad03d3 100644 (file)
@@ -26,8 +26,8 @@
  * central entrance to the stack.
  */
 
-#ifndef __OCPLATFORM_IMPL_H
-#define __OCPLATFORM_IMPL_H
+#ifndef OC_PLATFORM_IMPL_H_
+#define OC_PLATFORM_IMPL_H_
 
 #include <map>
 
index adecd89..0a949e3 100644 (file)
@@ -1,25 +1,25 @@
-/* *****************************************************************
- *
- * 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.
- *
- * *****************************************************************/
-
-#ifndef _OCPROVISIONINGMANAGER_CXX_H
-#define _OCPROVISIONINGMANAGER_CXX_H
+//****************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef OC_PROVISIONINGMANAGER_CXX_H_
+#define OC_PROVISIONINGMANAGER_CXX_H_
 
 #include <thread>
 
@@ -44,7 +44,7 @@ namespace OC
     };
 
     /**
-     * @brief: This class is for credential's to be set to devices.
+     * This class is for credential's to be set to devices.
      * The types supported are
      *              0:  no security mode
      *              1:  symmetric pair-wise key
@@ -62,21 +62,44 @@ namespace OC
             Credential(OicSecCredType_t type, size_t size) : type(type), keySize(size)
             {}
 
+            /**
+             * API to get credential type of device.
+             * @return credential type of device.
+             */
             OicSecCredType_t getCredentialType() const
             {
                 return type;
             }
 
+            /**
+             * API to get size of credential key type.
+             * @return size of credential key type.
+             */
             size_t getCredentialKeySize() const
             {
                 return keySize;
             }
 
+            /**
+             * API to set credential type of device.
+             * Device can have following credential types
+             *  - symmetric pair-wise key
+             *  - symmetric group key
+             *  - asymmetric key
+             *  - signed asymmetric key (aka certificate)
+             *  - PIN /password
+             * @param type credential type.
+             */
             void setCredentialType(OicSecCredType_t type)
             {
                 this->type = type;
             }
 
+            /**
+             * API to set size of credential key type.
+             * @param keySize credential key size.
+             * @note can be either 128 or 256 for symmetric pair-wise key
+             */
             void setCredentialKeySize(size_t keySize)
             {
                 this->keySize = keySize;
@@ -87,12 +110,12 @@ namespace OC
     {
         public:
             /**
-             * The API is responsible for initializaton of the provisioning manager. It will load
+             * The API is responsible for initialization of the provisioning manager. It will load
              * provisioning database which have owned device's list and their linked status.
              *
-             * @param[in] dbPath file path of the sqlite3 db
+             * @param dbPath file path of the sqlite3 database.
              *
-             * @return OC_STACK_OK in case of success and other value otherwise.
+             * @return ::OC_STACK_OK in case of success and other value otherwise.
              */
             static OCStackResult provisionInit(const std::string& dbPath);
 
@@ -100,49 +123,49 @@ namespace OC
              * API is responsible for discovery of devices in it's subnet. It will list
              * all the device in subnet which are not yet owned.
              *
-             * @param[in] timeout Timeout in seconds, time util which function will listen to
-             *                    responses from client before returning the list of devices.
-             * @param[out] list List of candidate devices to be provisioned
-             * @return OC_STACK_OK in case of success and other value otherwise.
+             * @param timeout Timeout in seconds, time until which function will listen to
+             *                    responses from server before returning the list of devices.
+             * @param list List of candidate devices to be provisioned.
+             * @return ::OC_STACK_OK in case of success and other value otherwise.
              */
             static OCStackResult discoverUnownedDevices(unsigned short timeout,
                     DeviceList_t &list);
 
             /**
              * API is responsible for discovery of devices in it's subnet. It will list
-             * all the device in subnet which are already owned by calling provioning client
+             * all the device in subnet which are already owned by calling provisioning client.
              *
-             * @param[in] timeout Timeout in seconds, time util which function will listen to
-             *                    responses from client before returning the list of devices.
-             * @param[out] list List of owned devices
-             * @return OC_STACK_OK in case of success and other value otherwise.
+             * @param timeout Timeout in seconds, time until which function will listen to
+             *                    responses from server before returning the list of devices.
+             * @param list List of owned devices.
+             * @return ::OC_STACK_OK in case of success and other value otherwise.
              */
             static OCStackResult discoverOwnedDevices(unsigned short timeout,
                     DeviceList_t &list);
 
             /**
-             * API for registering Ownershipt transfer methods for a particular transfer Type
+             * API for registering Ownership transfer methods for a particular transfer Type.
              *
-             * @param[in] oxm Ownership transfer method
-             * @param[in] callbackData Methods for ownership transfer
-             * @param[in] InputPinCallback Method to input pin for verification
-             * @return OC_STACK_OK in case of success and other value otherwise.
+             * @param oxm Ownership transfer method.
+             * @param callbackData CallbackData Methods for ownership transfer.
+             * @param inputPin Callback method to input pin for verification.
+             * @return ::OC_STACK_OK in case of success and other value otherwise.
              */
             static OCStackResult setOwnerTransferCallbackData(OicSecOxm_t oxm,
                     OTMCallbackData_t* callbackData, InputPinCallback inputPin);
 
             /**
              * API to get status of all the devices in current subnet. The status include endpoint
-             * information and doxm information which can be extracted duing owned and unowned
+             * information and doxm information which can be extracted during owned and unowned
              * discovery. Along with this information, API will provide information about
              * devices' status.
              * Device can have following states
              *  - ON/OFF: Device is switched on or off.
              *
-             * @param[in] timeout waitime for the API.
-             * @param[out] pOwnedDevList  list of owned devices.
-             * @param[out] pUnownedDevList  list of unowned devices.
-             * @return OC_STACK_OK in case of success and other value otherwise.
+             * @param timeout Wait time for the API.
+             * @param ownedDevList  List of owned devices.
+             * @param unownedDevList  List of unowned devices.
+             * @return ::OC_STACK_OK in case of success and other value otherwise.
              */
             static OCStackResult getDevInfoFromNetwork(unsigned short timeout,
                     DeviceList_t &ownedDevList,
@@ -150,14 +173,14 @@ namespace OC
             /**
              * Server API to register callback to display stack generated PIN.
              *
-             * @param[in] GeneratePinCallback Method to display generated PIN.
-             * @return OC_STACK_OK in case of success and other value otherwise.
+             * @param displayPin Callback Method to Display generated PIN.
+             * @return ::OC_STACK_OK in case of success and other value otherwise.
              */
-            static OCStackResult setDisplayPinCB(GeneratePinCallback);
+            static OCStackResult setDisplayPinCB(GeneratePinCallback displayPin);
     };
 
     /**
-     * This class represents a Secure virtual Device, which can be provisioned by the
+     * This class represents a secure virtual device, which can be provisioned by the
      * provisioning client.
      */
     class OCSecureResource
@@ -176,13 +199,13 @@ namespace OC
              * API to provision credentials between two devices and ACLs for the devices who
              * act as a server.
              *
-             * @param[in] cred  Type of credentials & key size to be provisioned to the device.
-             * @param[in] acl1  ACL for device 1. If this is not required set NULL.
-             * @param[in] device2  Second device to be provsioned.
-             * @param[in] acl2  ACL for device 2. If this is not required set NULL.
-             * @param[in] resultCallback Callback will be called when provisioning request recieves
+             * @param cred  Type of credentials & key size to be provisioned to the device.
+             * @param acl1  ACL for device 1. If this is not required set NULL.
+             * @param device2  Second device to be provisioned.
+             * @param acl2  ACL for device 2. If this is not required set NULL.
+             * @param resultCallback Callback will be called when provisioning request receives
              *                           a response from first resource server.
-             * @return  OC_STACK_OK in case of success and other value otherwise.
+             * @return  ::OC_STACK_OK in case of success and other value otherwise.
              */
             OCStackResult provisionPairwiseDevices(const Credential &cred, const OicSecAcl_t* acl1,
                     const OCSecureResource &device2, const OicSecAcl_t* acl2,
@@ -191,19 +214,19 @@ namespace OC
             /**
              * API to do ownership transfer for un-owned device.
              *
-             * @param[in] resultCallback Result callback function to be invoked when
+             * @param resultCallback Result callback function to be invoked when
              *                           ownership transfer finished.
-             * @return OC_STACK_OK in case of success and other value otherwise.
+             * @return ::OC_STACK_OK in case of success and other value otherwise.
              */
             OCStackResult doOwnershipTransfer(ResultCallBack resultCallback);
 
             /**
              * API to send ACL information to resource.
              *
-             * @param[in] acl ACL to provision.
-             * @param[in] resultCallback 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.
+             * @param acl ACL to provision.
+             * @param resultCallback Callback will be called when provisioning request
+             *                           receives a response from resource server.
+             * @return  ::OC_STACK_OK in case of success and other value otherwise.
              */
             OCStackResult provisionACL(const OicSecAcl_t* acl,
                     ResultCallBack resultCallback);
@@ -211,35 +234,35 @@ namespace OC
             /**
              * API to provision credential to devices.
              *
-             * @param[in] cred Type of credentials to be provisioned to the device.
-             * @param[in] device2 Second device' instance,respresenting resourceto be provsioned.
-             * @param[in] resultCallback callback will be called when provisioning request recieves
+             * @param cred Type of credentials to be provisioned to the device.
+             * @param device2 Second device' instance, representing resource to be provisioned.
+             * @param resultCallback Callback will be called when provisioning request receives
              *                           a response from first resource server.
-             * @return  OC_STACK_OK in case of success and other value otherwise.
+             * @return  ::OC_STACK_OK in case of success and other value otherwise.
              */
             OCStackResult provisionCredentials(const Credential &cred,
                     const OCSecureResource &device2,
                     ResultCallBack resultCallback);
 
-            /*
-            * API to remove the credential & relasionship between the two devices.
+           /**
+            * API to remove the credential & relationship between the two devices.
             *
-            * @param[in] pTargetDev2 second device information to be unlinked.
-            * @param[in] resultCallback callback provided by API user, callback will be called when
+            * @param device2 Second device information to be unlinked.
+            * @param resultCallback Callback provided by API user, callback will be called when
             *            device unlink is finished.
-             * @return  OC_STACK_OK in case of success and other value otherwise.
+            * @return  ::OC_STACK_OK in case of success and other value otherwise.
             */
             OCStackResult unlinkDevices(const OCSecureResource &device2,
                     ResultCallBack resultCallback);
 
-            /*
+            /**
              * API to remove device credential from all devices in subnet.
              *
-             * @param[in] resultCallback callback provided by API user, callback will be called when
+             * @param resultCallback Callback provided by API user, callback will be called when
              *            credential revocation is finished.
-             * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device
-             *            discovery.(seconds)
-             * @return  OC_STACK_OK in case of success and other value otherwise.
+             * @param waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device
+             *            discovery in seconds.
+             * @return  ::OC_STACK_OK in case of success and other value otherwise.
              */
             OCStackResult removeDevice(unsigned short waitTimeForOwnedDeviceDiscovery,
                     ResultCallBack resultCallback);
@@ -247,31 +270,38 @@ namespace OC
             /**
              * This method is used to get linked devices' IDs.
              *
-             * @param[out] uuidList information about the list of linked devices' uuids.
-             * @param[out] numOfDevices total number of linked devices.
-             * @return  OC_STACK_OK in case of success and other value otherwise.
+             * @param uuidList Information about the list of linked devices uuids.
+             * @return  ::OC_STACK_OK in case of success and other value otherwise.
              */
             OCStackResult getLinkedDevices(UuidList_t &uuidList);
 
             /**
-             * API to get the DeviceID of this resource
+             * API to get the device ID of this resource.
+             * @return device ID.
              */
             std::string getDeviceID();
 
+            /**
+             * API to get the information of device for provisioning.
+             * @return  @ref OCProvisionDev_t Reference provides information of device for provisioning.
+             */
             OCProvisionDev_t* getDevPtr()const;
 
             /**
-             * This function returns the Device's IP addr.
+             * This function returns the device's IP address.
+             * @return device address.
              */
             std::string getDevAddr();
 
             /**
-             * This function returns the Device's Status
+             * This function returns the device's Status.
+             * @return Device status (1 = ON and 2 = OFF).
              */
             int getDeviceStatus();
 
             /**
-             * This function provides the OWNED status of the device.
+             * This function provides the owned status of the device.
+             * @return Device owned status.
              */
             bool getOwnedStatus();
 
@@ -286,4 +316,4 @@ namespace OC
     };
 
 }
-#endif //_OCPROVISIONINGMANAGER_CXX_H
+#endif // OC_PROVISIONINGMANAGER_CXX_H_
index e7bbccb..4d1d24a 100644 (file)
@@ -25,8 +25,8 @@
  * to OCRepresentation.
  */
 
-#ifndef __OCREPRESENTATION_H
-#define __OCREPRESENTATION_H
+#ifndef OC_REPRESENTATION_H_
+#define OC_REPRESENTATION_H_
 
 
 #include <string>
@@ -296,27 +296,10 @@ namespace OC
                     // ambigious conversions in the case where conversions can include a number of
                     // types, such as the string constructor.
                     template<typename T, typename std::enable_if<
-                     std::is_same<T, int>::value ||
-                     std::is_same<T, double>::value ||
-                     std::is_same<T, bool>::value ||
-                     std::is_same<T, std::string>::value ||
-                     std::is_same<T, OCRepresentation>::value ||
-                     std::is_same<T, std::vector<int>>::value ||
-                     std::is_same<T, std::vector<std::vector<int>>>::value ||
-                     std::is_same<T, std::vector<std::vector<std::vector<int>>>>::value ||
-                     std::is_same<T, std::vector<double>>::value ||
-                     std::is_same<T, std::vector<std::vector<double>>>::value ||
-                     std::is_same<T, std::vector<std::vector<std::vector<double>>>>::value ||
-                     std::is_same<T, std::vector<bool>>::value ||
-                     std::is_same<T, std::vector<std::vector<bool>>>::value ||
-                     std::is_same<T, std::vector<std::vector<std::vector<bool>>>>::value ||
-                     std::is_same<T, std::vector<std::string>>::value ||
-                     std::is_same<T, std::vector<std::vector<std::string>>>::value ||
-                     std::is_same<T, std::vector<std::vector<std::vector<std::string>>>>::value ||
-                     std::is_same<T, std::vector<OCRepresentation>>::value ||
-                     std::is_same<T, std::vector<std::vector<OCRepresentation>>>::value ||
-                     std::is_same<T, std::vector<std::vector<std::vector<OCRepresentation>>>>::value
-                     , int>::type = 0// enable_if
+                        is_component<T,
+                            remove_first<AttributeValue>::type
+                            >::value
+                        , int>::type = 0
                     >
                     operator T() const
                     {
@@ -470,5 +453,5 @@ namespace OC
 } // namespace OC
 
 
-#endif //__OCREPRESENTATION_H
+#endif // OC_REPRESENTATION_H_
 
index c2754a2..3fe3a68 100644 (file)
@@ -25,8 +25,8 @@
  * Resource.
  */
 
-#ifndef __OCRESOURCE_H
-#define __OCRESOURCE_H
+#ifndef OC_RESOURCE_H_
+#define OC_RESOURCE_H_
 
 #include <memory>
 #include <random>
@@ -548,5 +548,5 @@ namespace OC
 
 } // namespace OC
 
-#endif //__OCRESOURCE_H
+#endif // OC_RESOURCE_H
 
index 962ddb2..e17e3a6 100644 (file)
@@ -25,8 +25,8 @@
  * ResourceRequest.
  */
 
-#ifndef __OCRESOURCEREQUEST_H
-#define __OCRESOURCEREQUEST_H
+#ifndef OC_RESOURCEREQUEST_H_
+#define OC_RESOURCEREQUEST_H_
 
 #include "OCApi.h"
 #include "OCRepresentation.h"
@@ -219,4 +219,4 @@ namespace OC
     };
  }// namespace OC
 
-#endif //__OCRESOURCEREQUEST_H
+#endif // OC_RESOURCEREQUEST_H_
index fbdd2c9..474e90a 100644 (file)
@@ -25,8 +25,8 @@
  * ResourceResponse.
  */
 
-#ifndef __OCRESOURCERESPONSE_H
-#define __OCRESOURCERESPONSE_H
+#ifndef OC_RESOURCERESPONSE_H_
+#define OC_RESOURCERESPONSE_H_
 
 #include "OCApi.h"
 #include <IServerWrapper.h>
@@ -275,4 +275,4 @@ namespace OC
 
 } // namespace OC
 
-#endif //__OCRESOURCERESPONSE_H
+#endif // OC_RESOURCERESPONSE_H_
index b681eee..c9526f1 100644 (file)
@@ -45,17 +45,10 @@ namespace OC
                     : m_clientWrapper(cw), m_devAddr(devAddr)
             {
                 OCResourcePayload* res = payload->resources;
-                OCResourceCollectionPayload* colRes = payload->collectionResources;
                 if (res)
                 {
                     while(res)
                     {
-                        char uuidString[UUID_STRING_SIZE];
-                        if(OCConvertUuidToString(payload->sid, uuidString) != RAND_UUID_OK)
-                        {
-                            uuidString[0]= '\0';
-                        }
-
                         if (res->secure)
                         {
                             m_devAddr.flags =
@@ -66,52 +59,32 @@ namespace OC
                         {
                              m_devAddr.port = res->port;
                         }
-
-                        m_resources.push_back(std::shared_ptr<OC::OCResource>(
+                        if (payload->baseURI)
+                        {
+                            OCDevAddr rdPubAddr = m_devAddr;
+                            OICStrcpy(rdPubAddr.addr, sizeof(rdPubAddr.addr), payload->baseURI);
+                            rdPubAddr.port = res->port;
+                            m_resources.push_back(std::shared_ptr<OC::OCResource>(
+                                        new OC::OCResource(m_clientWrapper, rdPubAddr,
+                                            std::string(res->uri),
+                                            std::string(payload->sid),
+                                            (res->bitmap & OC_OBSERVABLE) == OC_OBSERVABLE,
+                                            StringLLToVector(res->types),
+                                            StringLLToVector(res->interfaces)
+                                            )));
+                        }
+                        else
+                        {
+                            m_resources.push_back(std::shared_ptr<OC::OCResource>(
                                     new OC::OCResource(m_clientWrapper, m_devAddr,
                                         std::string(res->uri),
-                                        std::string(uuidString),
+                                        std::string(payload->sid),
                                         (res->bitmap & OC_OBSERVABLE) == OC_OBSERVABLE,
                                         StringLLToVector(res->types),
                                         StringLLToVector(res->interfaces)
                                         )));
-                        res = res->next;
-                    }
-                }
-                else if (colRes)
-                {
-                    while(colRes)
-                    {
-                        // currently support for ipv4 is provided.
-                        OCDevAddr colAddr;
-                        colAddr.adapter = OC_ADAPTER_IP;
-                        colAddr.flags   = OC_IP_USE_V4;
-                        char *ptr = strtok(colRes->tags->baseURI, ":");
-                        OICStrcpy(colAddr.addr, sizeof(colAddr.addr), ptr);
-
-                        if (colRes->tags->bitmap & OC_SECURE)
-                        {
-                            colAddr.flags =
-                                  (OCTransportFlags)(OC_FLAG_SECURE | m_devAddr.flags);
-                        }
-                        if (colRes->tags->port != 0)
-                        {
-                             colAddr.port = colRes->tags->port;
                         }
-                        else
-                        {
-                            colAddr.port = atoi(ptr+1);
-                        }
-
-                        m_resources.push_back(std::shared_ptr<OC::OCResource>(
-                                    new OC::OCResource(m_clientWrapper, colAddr,
-                                        std::string(colRes->setLinks->href),
-                                        std::string((char*)colRes->tags->di.id),
-                                        (colRes->tags->bitmap & OC_OBSERVABLE) == OC_OBSERVABLE,
-                                        StringLLToVector(colRes->setLinks->rt),
-                                        StringLLToVector(colRes->setLinks->itf)
-                                        )));
-                        colRes = colRes->next;
+                        res = res->next;
                     }
                 }
             }
index 87bdf35..1c17c10 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef _INTEL_OCUTILITIES_H_
-#define _INTEL_OCUTILITIES_H_
+#ifndef OC_UTILITIES_H_
+#define OC_UTILITIES_H_
 
 #include <map>
 #include <vector>
@@ -106,12 +106,42 @@ namespace OC
     template<typename T>
     struct is_vector<T,
         typename std::enable_if<
-            std::is_same<T, std::vector<typename T::value_type, typename T::allocator_type>>::value
+            std::is_same<T, std::vector<typename T::value_type, typename T::allocator_type> >::value
         >::type
     >
     {
         constexpr static bool value = true;
     };
+
+    // type trait to remove the first type from a parameter-packed list
+    template <typename T>
+    struct remove_first;
+
+    // specialization that does all the work
+    template<template <typename...> class Base, typename T, typename ...Rest>
+    struct remove_first< Base<T, Rest...> >
+    {
+        typedef Base<Rest...> type;
+    };
+
+    // type trait that will only pass if ToTest is in the parameter pack of T2
+    template<typename ToTest, typename T2>
+    struct is_component;
+
+    // specialization to handle the single-item case
+    template<typename ToTest, template <typename...> class Base, typename T>
+    struct is_component<ToTest, Base<T> >
+    {
+        static constexpr bool value = std::is_same<ToTest, T>::value;
+    };
+
+    // Recursive specialization to handle cases with multiple values
+    template<typename ToTest, template <typename...> class Base, typename T, typename ...Rest>
+    struct is_component<ToTest, Base<T, Rest...> >
+    {
+        static constexpr bool value = std::is_same<ToTest, T>::value
+            || is_component<ToTest, Base<Rest...> >::value;
+    };
 } // namespace OC
 
 #endif
index b8f63de..a6fd165 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef _OUT_OF_PROC_CLIENT_WRAPPER_H_
-#define _OUT_OF_PROC_CLIENT_WRAPPER_H_
+#ifndef OC_OUT_OF_PROC_CLIENT_WRAPPER_H_
+#define OC_OUT_OF_PROC_CLIENT_WRAPPER_H_
 
 #include <OCApi.h>
 
index 744a14c..05d79e4 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef _OUT_OF_PROC_SERVER_WRAPPER_H_
-#define _OUT_OF_PROC_SERVER_WRAPPER_H_
+#ifndef OC_OUT_OF_PROC_SERVER_WRAPPER_H_
+#define OC_OUT_OF_PROC_SERVER_WRAPPER_H_
 
 #include <OCApi.h>
 
index 9794e42..33cb27d 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef _RESOURCE_INIT_EXCEPTION_H_
-#define _RESOURCE_INIT_EXCEPTION_H_
+#ifndef OC_RESOURCE_INIT_EXCEPTION_H_
+#define OC_RESOURCE_INIT_EXCEPTION_H_
 
 #include <stdexcept>
 #include "StringConstants.h"
index d6fd818..526a0b9 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef _STRING_CONSTANTS_H_
-#define _STRING_CONSTANTS_H_
+#ifndef OC_STRING_CONSTANTS_H_
+#define OC_STRING_CONSTANTS_H_
 
 #include <string>
 
@@ -108,7 +108,7 @@ namespace OC
         static const char PDM_DB_NOT_INITIALIZED[]     = "Provisioning DB is not initialized";
         static const char DUPLICATE_UUID[]             = "Duplicate UUID in DB";
         static const char INCONSISTENT_DB[]            = "Data in provisioning DB is inconsistent";
-
+        static const char AUTHENTICATION_FAILURE[]     = "Authentication failure";
     }
 
     namespace Error
@@ -143,5 +143,5 @@ namespace OC
 
 }
 
-#endif // _STRING_CONSTANTS_H_
+#endif // OC_STRING_CONSTANTS_H_
 
index 2f15b80..1b31142 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef _WRAPPER_FACTORY_H_
-#define _WRAPPER_FACTORY_H_
+#ifndef OC_WRAPPER_FACTORY_H_
+#define OC_WRAPPER_FACTORY_H_
 
 #include <memory>
 #include <OCApi.h>
index 1fc1a85..35ae31c 100644 (file)
@@ -54,6 +54,12 @@ liboc_logger = liboc_logger_env.SharedLibrary('oc_logger',
 
 liboc_logger_env.InstallTarget([liboc_logger_core, liboc_logger], 'liboc_logger')
 liboc_logger_env.UserInstallTargetLib([liboc_logger_core, liboc_logger], 'liboc_logger')
+liboc_logger_env.UserInstallTargetHeader('include/oc_logger.hpp', 'resource', 'oc_logger.hpp')
+liboc_logger_env.UserInstallTargetHeader('include/oc_logger.h', 'resource', 'oc_logger.h')
+liboc_logger_env.UserInstallTargetHeader('include/oc_logger_types.h', 'resource', 'oc_logger_types.h')
+liboc_logger_env.UserInstallTargetHeader('include/oc_log_stream.hpp', 'resource', 'oc_log_stream.hpp')
+liboc_logger_env.UserInstallTargetHeader('include/targets/oc_console_logger.h', 'resource/targets', 'oc_console_logger.h')
+liboc_logger_env.UserInstallTargetHeader('include/targets/oc_ostream_logger.h', 'resource/targets', 'oc_ostream_logger.h')
 
 if target_os not in ['ios', 'android']:
        SConscript('examples/SConscript')
index 02adb4f..b8b738f 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef __OC_CONSOLE_LOGGER_H_2014_09_5
- #define __OC_CONSOLE_LOGGER_H_2014_09_5
+#ifndef OC_CONSOLE_LOGGER_H_
+#define OC_CONSOLE_LOGGER_H_
 
 #include "oc_logger_types.h"
 
index dd145dd..6e92930 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef __OC_LOG_HPP_20140910
- #define __OC_LOG_HPP_20140910
+#ifndef OC_LOG_HPP_
+#define OC_LOG_HPP_
 
 #include "oc_ostream_logger.hpp"
 #include "oc_log_stream.hpp"
index bafa141..f2e01ac 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef __OC_LOG_STREAM_HPP_20140910
- #define __OC_LOG_STREAM_HPP_20140910
+#ifndef OC_LOG_STREAM_HPP_
+#define OC_LOG_STREAM_HPP_
 
 #include <iosfwd>
 #include <memory>
index 8368db0..9fd3878 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef __OC_LOGGER_H_2014_09_5
- #define __OC_LOGGER_H_2014_09_5
+#ifndef OC_LOGGER_H_
+#define OC_LOGGER_H_
 
 #include "oc_logger_types.h"
 
index 2d0df21..3ddb762 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef __OC_LOG_HPP_20140910
- #define __OC_LOG_HPP_20140910
+#ifndef OC_LOGGER_HPP_
+#define OC_LOGGER_HPP_
 
 #include "oc_logger.h"
 
index 2c807c7..83b6b3e 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef __OC_LOGGER_TYPES_H_2024_09_5
- #define __OC_LOGGER_TYPES_H_2024_09_5
+#ifndef OC_LOGGER_TYPES_H_
+#define OC_LOGGER_TYPES_H_
 
 #include <stddef.h>
 
index 02adb4f..b8b738f 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef __OC_CONSOLE_LOGGER_H_2014_09_5
- #define __OC_CONSOLE_LOGGER_H_2014_09_5
+#ifndef OC_CONSOLE_LOGGER_H_
+#define OC_CONSOLE_LOGGER_H_
 
 #include "oc_logger_types.h"
 
index 0431469..2fa7930 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef __OC_OSTREAM_LOGGER_H_2014_09_5
- #define __OC_OSTREAM_LOGGER_H_2014_09_5
+#ifndef OC_OSTREAM_LOGGER_H_
+#define OC_OSTREAM_LOGGER_H_
 
 #include "oc_logger_types.h"
 
diff --git a/resource/oc_logger/samples/linux/README b/resource/oc_logger/samples/linux/README
deleted file mode 100644 (file)
index aa8683e..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
--------------------------------------------------------------------------------
-  NOTICE - Transition to SCONS
--------------------------------------------------------------------------------
-
-The IoTivity build system is transitioning to SCONS. Although the
-makefiles are still available (until v1.0) and some developers are
-still using them, they are currently no longer supported. To learn more
-about building using SCONS see Readme.scons.txt in the repository root
-directory. The build steps used in continuous integration can be found
-in auto_build.sh which is also in the the repository root directory.
-
--------------------------------------------------------------------------------
-
-To run the oc_logger C sample app, first build liboctbstack.a
-
-cd <root>/csdk
-
-To enable logging
-make BUILD=debug
-else
-make BUILD=release
-
-Next, build the oc_logger C sample app
-
-cd <root>/oc_logger/samples/linux
-
-To enable logging
-make BUILD=debug
-else
-make BUILD=release
-
-The logger sample has two options, default logging or
-a custom logger that can be supplied by the user application
-
-To run the application with the default logger, run
-
-./debug/test_logging -c 0
-
-To run the application using a built in custom console logger, run
-
-./debug/test_logging -c 1
-
-
-
diff --git a/resource/oc_logger/samples/linux/test_logging.c b/resource/oc_logger/samples/linux/test_logging.c
deleted file mode 100644 (file)
index 533a59a..0000000
+++ /dev/null
@@ -1,80 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH 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 "logger.h"
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-#define TAG  ("MAIN")
-
-static int customLogger = 0;
-
-static void PrintUsage()
-{
-    OC_LOG(INFO, TAG, "Usage : test_logging -c <0|1>");
-    OC_LOG(INFO, TAG, "-u <0|1> : 0 - default logging, 1 - custom console logging");
-}
-
-int main(int argc, char* argv[])
-{
-    int opt;
-
-    while ((opt = getopt(argc, argv, "c:")) != -1)
-    {
-        switch(opt)
-        {
-            case 'c':
-                customLogger = atoi(optarg);
-                break;
-            default:
-                PrintUsage();
-                return -1;
-        }
-    }
-
-    if (customLogger == 0)
-    {
-        // Default logger
-        OC_LOG(DEBUG, TAG, "This is a DEBUG");
-        OC_LOG(INFO, TAG, "This is a INFO");
-        OC_LOG(WARNING, TAG, "This is a WARNING");
-        OC_LOG(ERROR, TAG, "This is a ERROR");
-        OC_LOG(FATAL, TAG, "This is a FATAL");
-    }
-    else
-    {
-        // Custom logger, in this case, the console logger
-        oc_log_ctx_t *log = oc_make_console_logger();
-
-        OC_LOG_CONFIG(log);
-
-        OC_LOG(DEBUG, TAG, "This is a DEBUG");
-        OC_LOG(INFO, TAG, "This is a INFO");
-        OC_LOG(WARNING, TAG, "This is a WARNING");
-        OC_LOG(ERROR, TAG, "This is a ERROR");
-        OC_LOG(FATAL, TAG, "This is a FATAL");
-        OC_LOG_SHUTDOWN();
-    }
-
-
-    return 0;
-}
index 0f2afa5..05186c1 100644 (file)
@@ -27,13 +27,16 @@ ocprovision_env = env.Clone()
 ######################################################################
 ocprovision_env.AppendUnique(CPPPATH = [
                '../include/',
-        '../csdk/stack/include',
-        '../csdk/logger/include',
-        '../oc_logger/include',
+               '../csdk/stack/include',
+               '../csdk/logger/include',
+               '../oc_logger/include',
+               '../csdk/connectivity/api',
                '../csdk/security/include',
                '../csdk/security/provisioning/include',
                '../csdk/security/provisioning/include/oxm',
-               '../csdk/security/provisioning/include/internal'
+               '../csdk/security/provisioning/include/internal',
+        '../csdk/connectivity/lib/libcoap-4.1.1/',
+        '../../extlibs/cjson/'
                ])
 
 target_os = env.get('TARGET_OS')
@@ -43,7 +46,11 @@ if target_os not in ['windows', 'winrt']:
 if target_os == 'android':
        ocprovision_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
        ocprovision_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-       ocprovision_env.AppendUnique(LIBS = ['ocspapi', 'octbstack', 'oc_logger', 'boost_thread', 'gnustl_shared', 'log'])
+       ocprovision_env.AppendUnique(LIBS = ['oc', 'octbstack', 'ocpmapi', 'oc_logger', 'boost_thread', 'gnustl_shared', 'log'])
+
+if target_os in ['linux', 'tizen']:
+       ocprovision_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+        ocprovision_env.AppendUnique(LIBS = ['oc', 'octbstack', 'ocpmapi', 'oc_logger', 'boost_thread'])
 
 if target_os in ['darwin', 'ios']:
        ocprovision_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
@@ -56,8 +63,9 @@ ocprovision_src = [
                'src/OCProvisioningManager.cpp'
        ]
 
-ocprovision = ocprovision_env.StaticLibrary('ocprovision', ocprovision_src)
+ocprovision = ocprovision_env.SharedLibrary('ocprovision', ocprovision_src)
 ocprovision_env.InstallTarget(ocprovision, 'libocprovision')
+ocprovision_env.UserInstallTargetLib(ocprovision, 'libocprovision')
 
-if target_os in ['linux', 'tizen']:
+if target_os in ['linux']:
     SConscript('examples/SConscript')
diff --git a/resource/provisioning/examples/README-Provisioning-Tool-CPP.txt b/resource/provisioning/examples/README-Provisioning-Tool-CPP.txt
new file mode 100644 (file)
index 0000000..1678bdb
--- /dev/null
@@ -0,0 +1,64 @@
+LAST UPDATED 3/28/2016
+
+To execute Provisioning Tool sample:
+
+1) Build IoTivity with security enabled:
+
+    $ cd <iotivity-base>
+       $ scons resource SECURED=1
+
+2) Verify Provisioning Tool functionality using secure sample apps:
+
+    Run Resource Server Device which needs to be 'provisioned' in the directory
+    <iotivity-base>/out/<...>/resource/csdk/security/provisioning/samples:
+    $ <...>/sampleserver_justworks (Just Works)
+       or
+       $ <...>/sampleserver_randompin (Random Pin)
+
+    Run Provisioning Tool Device:
+    $ ./provisioningclient
+
+    Provisioning Tool will provide prompts for discovery, ownership transfer, and provisioning.
+
+    Enter 1 (UnOwned Device discovery)
+    and you should see the list of discovered unowned devices.
+
+    Then enter 3 (Ownership transfer) and the number of device
+    you want to perform ownership transfer between the Server device and
+    the Provisioning Tool device.
+
+    If the random pin server is running, you must enter the PIN code that
+    appears on the server terminal to finish ownership transfer.
+
+    Enter 2 (Owned Device discovery) to confirm that
+    ownership transfer succeeded. If successful,
+    you should find the Server device on the Owned device list.
+
+ 3) Verify Ownership Transfer using sample apps:
+
+    If you would like to check whether ownership transfer successfully
+    created credentials, replace the server and client sample DAT files
+    with oic_svr_db_client.dat and oic_svr_db_server.dat files from the
+    ownership transfer as follows:
+    $ cp ./oic_svr_db_client.dat <iotivity-base>/out/<...>/release/resource/csdk/stack/samples/linux/secure/oic_svr_db.client.dat
+    $ cp <iotivity-base>/out/release/resource/csdk/security/provisioning/samples/oic_svr_db_server_<...>.dat <iotivity-base>/out/<...>/release/resource/csdk/stack/samples/linux/secure/oic_svr_db.server.dat
+
+    Then move to the sample app directory
+    and execute the server and client apps:
+    $ cd <iotivity-base>/out/release/resource/csdk/stack/samples/linux/secure/
+    $ export LD_LIBRARY_PATH=<iotivity-base>/out/<...>/release/
+    $ ./ocserverbasicops
+    $ ./occlientbasicops -u 0 -t 3
+
+    If successful, the client and server should successfully send and receive payloads.
+
+    All security functionality operate using CBOR data (DAT files).
+    JSON files are for reference only as they are human-readable.
+    JSON files are not used by security-related functions.
+
+    If you wish to test functionality with data file
+    different from the provided default DAT file, modify the JSON files
+    (oic_svr_db_server_justworks.json, oic_svr_db_server_randompin.json)
+    and then use the JSON-to-CBOR conversion tool
+    (<iotivity-base>/out/<...>/release/resource/csdk/security/tool/json2cbor)
+    to create a new DAT file.
index e6813c5..ceb52bf 100644 (file)
@@ -26,6 +26,9 @@ Import('env')
 lib_env = env.Clone()
 SConscript(env.get('SRC_DIR') + '/resource/third_party_libs.scons', 'lib_env')
 
+with_ra = env.get('WITH_RA')
+with_ra_ibb = env.get('WITH_RA_IBB')
+
 examples_env = lib_env.Clone()
 
 ######################################################################
@@ -36,6 +39,7 @@ examples_env.AppendUnique(CPPPATH = [
         '../../csdk/stack/include',
         '../../csdk/logger/include',
         '../../oc_logger/include',
+        '../../csdk/connectivity/api',
         '../../csdk/security/include',
         '../../csdk/security/provisioning/include',
         '../../csdk/security/provisioning/include/oxm',
@@ -55,8 +59,19 @@ examples_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 examples_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
 examples_env.PrependUnique(LIBS = ['ocprovision', 'oc', 'ocpmapi', 'octbstack',
                                     'oc_logger', 'connectivity_abstraction', 'coap'])
+if with_ra_ibb:
+       examples_env.AppendUnique(LIBS = examples_env['RALIBS'], LIBPATH = examples_env['RALIBPATH'], RPATH = examples_env['RARPATH'])
+       print "RALIBS = %s" % examples_env['RALIBS']
+       print "RALIBPATH = %s" % examples_env['RALIBPATH']
+       print "RARPATH = %s" % examples_env['RARPATH']
+       examples_env.AppendUnique(LIBS = 'wksxmppxep')
+else :
+       if with_ra:
+               examples_env.AppendUnique(LIBS = ['ra_xmpp'])
+
 if env.get('SECURED') == '1':
     examples_env.AppendUnique(LIBS = ['tinydtls'])
+    examples_env.AppendUnique(LIBS = ['timer'])
 if env.get('DTLS_WITH_X509') == '1':
        examples_env.AppendUnique(LIBS = ['CKManager'])
        examples_env.AppendUnique(LIBS = ['asn1'])
@@ -71,16 +86,18 @@ if target_os == 'android':
 if target_os in ['darwin', 'ios']:
        examples_env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
 
-if target_os == 'tizen':
-       examples_env.ParseConfig('pkg-config --libs sqlite3')
-
 ######################################################################
 # Source files and Targets
 ######################################################################
 provisioningclient = examples_env.Program('provisioningclient', 'provisioningclient.cpp')
 
-clientjson = examples_env.Install(env.get('BUILD_DIR') + '/resource/provisioning/examples/',
-                               env.get('SRC_DIR') + '/resource/provisioning/examples/' + 'oic_svr_db_client.json')
+src_dir = examples_env.get('SRC_DIR')
+svr_db_src_dir = src_dir + '/resource/provisioning/examples/'
+svr_db_build_dir = env.get('BUILD_DIR') +'/resource/provisioning/examples/'
 
-Alias("examples", [provisioningclient, clientjson])
+clientjson = examples_env.Install(svr_db_build_dir, svr_db_src_dir + 'oic_svr_db_client.json')
+clientdat = examples_env.Install(svr_db_build_dir, svr_db_src_dir + 'oic_svr_db_client.dat')
+
+Alias("examples", [provisioningclient, clientjson,clientdat])
 env.AppendTarget('examples')
+
diff --git a/resource/provisioning/examples/oic_svr_db_client.dat b/resource/provisioning/examples/oic_svr_db_client.dat
new file mode 100644 (file)
index 0000000..781f654
Binary files /dev/null and b/resource/provisioning/examples/oic_svr_db_client.dat differ
index 1219d6a..fb3c609 100644 (file)
@@ -1,43 +1,88 @@
-{
-    "acl": [
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/res",
-                "/oic/d",
-                "/oic/p",
-                "/oic/res/types/d",
-                "/oic/ad",
-                "/oic/sec/amacl"
-                       ],
-                       "perms": 2,
-                       "ownrs" : ["YWRtaW5EZXZpY2VVVUlEMA=="]
-               },
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/sec/doxm",
-                "/oic/sec/pstat"
-             ],
-             "perms": 2,
-             "ownrs" : ["YWRtaW5EZXZpY2VVVUlEMA=="]
-        }
-       ],
-       "pstat":        {
-               "isop": true,
-               "deviceid":     "YWRtaW5EZXZpY2VVVUlEMA==",
-               "ch": 0,
-               "cm":   0,
-               "tm":   0,
-               "om":   3,
-               "sm":   [3]
-       },
-       "doxm": {
-               "oxm":  [0],
-               "oxmsel": 0,
-               "sct": 1,
-               "owned": true,
-               "deviceid":     "YWRtaW5EZXZpY2VVVUlEMA==",
-               "ownr": "YWRtaW5EZXZpY2VVVUlEMA=="
-       }
-}
+{\r
+    "acl": {\r
+        "aclist": {\r
+            "aces": [\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/res",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/p",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/types/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/ad",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/amacl",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/doxm",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/pstat",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }                  \r
+                    ],\r
+                    "permission": 2\r
+                }\r
+            ]\r
+        },\r
+        "rowneruuid" : "61646D69-6E44-6576-6963-655575696430"\r
+    },    \r
+    "pstat": {\r
+        "isop": true,\r
+        "cm": 0,\r
+        "tm": 0,\r
+        "om": 3,\r
+        "sm": 3,\r
+        "deviceuuid": "61646D69-6E44-6576-6963-655575696430",\r
+        "rowneruuid": "61646D69-6E44-6576-6963-655575696430"\r
+    },\r
+    "doxm": {\r
+        "oxms": [0],\r
+        "oxmsel": 0,\r
+        "sct": 1,\r
+        "owned": true,\r
+        "deviceuuid": "61646D69-6E44-6576-6963-655575696430",\r
+        "dpc": false,\r
+        "devowneruuid": "61646D69-6E44-6576-6963-655575696430",\r
+        "rowneruuid": "61646D69-6E44-6576-6963-655575696430"\r
+    }\r
+}\r
index 5ed14fa..b2c9825 100644 (file)
@@ -50,6 +50,7 @@
 #define TAG  "provisioningclient"
 
 #define JSON_DB_PATH "./oic_svr_db_client.json"
+#define DAT_DB_PATH "./oic_svr_db_client.dat"
 #define DEV_STATUS_ON "DEV_STATUS_ON"
 #define DEV_STATUS_OFF "DEV_STATUS_OFF"
 
@@ -63,7 +64,7 @@ static int transferDevIdx, ask = 1;
 static FILE* client_open(const char *UNUSED_PARAM, const char *mode)
 {
     (void)UNUSED_PARAM;
-    return fopen(JSON_DB_PATH, mode);
+    return fopen(DAT_DB_PATH, mode);
 }
 
 void printMenu()
@@ -271,9 +272,6 @@ static void deleteACL(OicSecAcl_t *acl)
         }
         OICFree((acl)->resources);
 
-        /* Clean Owners */
-        OICFree((acl)->owners);
-
         /* Clean ACL node itself */
         /* Required only if acl was created in heap */
         OICFree((acl));
@@ -382,12 +380,17 @@ static int InputACL(OicSecAcl_t *acl)
     //Set Resource.
     printf("Num. of Resource : ");
     ret = scanf("%zu", &acl->resourcesLen);
+    if ((1 != ret) || (acl->resourcesLen <= 0 || acl->resourcesLen > 50))
+    {
+        printf("Error while input\n");
+        return -1;
+    }
     printf("-URI of resource\n");
     printf("ex)/oic/sh/temp/0 (Max_URI_Length: 64 Byte )\n");
     acl->resources = (char **)OICCalloc(acl->resourcesLen, sizeof(char *));
     if (NULL == acl->resources)
     {
-        OC_LOG(ERROR, TAG, "Error while memory allocation");
+        OIC_LOG(ERROR, TAG, "Error while memory allocation");
         return -1;
     }
     for (size_t i = 0; i < acl->resourcesLen; i++)
@@ -404,7 +407,7 @@ static int InputACL(OicSecAcl_t *acl)
         OICFree(temp_rsc);
         if (NULL == acl->resources[i])
         {
-            OC_LOG(ERROR, TAG, "Error while memory allocation");
+            OIC_LOG(ERROR, TAG, "Error while memory allocation");
             return -1;
         }
     }
@@ -425,35 +428,26 @@ static int InputACL(OicSecAcl_t *acl)
     } while (0 != ret );
 
     // Set Rowner
-    printf("Num. of Rowner : ");
-    ret = scanf("%zu", &acl->ownersLen);
     printf("-URN identifying the rowner\n");
     printf("ex) 1111-1111-1111-1111 (16 Numbers except to '-')\n");
-    acl->owners = (OicUuid_t *)OICCalloc(acl->ownersLen, sizeof(OicUuid_t));
-    if (NULL == acl->owners)
+
+    printf("Rowner : ");
+    ret = scanf("%19ms", &temp_id);
+    if (1 != ret)
     {
-        OC_LOG(ERROR, TAG, "Error while memory allocation");
+        printf("Error while input\n");
         return -1;
     }
-    for (size_t i = 0; i < acl->ownersLen; i++)
-    {
-        printf("[%zu]Rowner : ", i + 1);
-        ret = scanf("%19ms", &temp_id);
-        if (1 != ret)
-        {
-            printf("Error while input\n");
-            return -1;
-        }
 
-        for (int k = 0, j = 0; temp_id[k] != '\0'; k++)
+    for (int k = 0, j = 0; temp_id[k] != '\0'; k++)
+    {
+        if (DASH != temp_id[k])
         {
-            if (DASH != temp_id[k])
-            {
-                acl->owners[i].id[j++] = temp_id[k];
-            }
+            acl->rownerID.id[j++] = temp_id[k];
         }
-        OICFree(temp_id);
     }
+    OICFree(temp_id);
+
     return 0;
 }
 
@@ -649,7 +643,7 @@ int main(void)
                             OTMCallbackData_t pinBasedCBData;
                             pinBasedCBData.loadSecretCB = InputPinCodeCallback;
                             pinBasedCBData.createSecureSessionCB =
-                                CreateSecureSessionRandomPinCallbak;
+                                CreateSecureSessionRandomPinCallback;
                             pinBasedCBData.createSelectOxmPayloadCB =
                                 CreatePinBasedSelectOxmPayload;
                             pinBasedCBData.createOwnerTransferPayloadCB =
@@ -681,7 +675,7 @@ int main(void)
                         acl1 = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
                         if (NULL == acl1)
                         {
-                            OC_LOG(ERROR, TAG, "Error while memory allocation");
+                            OIC_LOG(ERROR, TAG, "Error while memory allocation");
                             break;
                         }
 
@@ -749,7 +743,7 @@ int main(void)
                         acl1 = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
                         if (NULL == acl1)
                         {
-                            OC_LOG(ERROR, TAG, "Error while memory allocation");
+                            OIC_LOG(ERROR, TAG, "Error while memory allocation");
                             break;
                         }
 
@@ -762,7 +756,7 @@ int main(void)
                         acl2 = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
                         if (NULL == acl2)
                         {
-                            OC_LOG(ERROR, TAG, "Error while memory allocation");
+                            OIC_LOG(ERROR, TAG, "Error while memory allocation");
                             break;
                         }
 
index 8040a99..8a2c076 100644 (file)
@@ -19,6 +19,7 @@
  * *****************************************************************/
 
 #include "ocstack.h"
+#include "srmutility.h"
 #include "base64.h"
 #include "OCProvisioningManager.h"
 
@@ -142,7 +143,7 @@ namespace OC
         {
             std::lock_guard<std::recursive_mutex> lock(*cLock);
             result = OCSetOwnerTransferCallbackData(oxm, callbackData);
-            if(result == OC_STACK_OK && (OIC_RANDOM_DEVICE_PIN & oxm))
+            if(result == OC_STACK_OK && (OIC_RANDOM_DEVICE_PIN == oxm))
             {
                 SetInputPinCB(inputPin);
             }
@@ -234,7 +235,16 @@ namespace OC
         PMResultList_t *results = nullptr;
         ProvisionContext* context = static_cast<ProvisionContext*>(ctx);
 
-        results = new PMResultList_t;
+        try
+        {
+            results = new PMResultList_t;
+        }
+        catch (std::bad_alloc& e)
+        {
+            oclog() <<"Bad alloc exception";
+            return;
+        }
+
         for (int i = 0; i < nOfRes; i++)
         {
             results->push_back(arr[i]);
@@ -270,7 +280,7 @@ namespace OC
         if(!resultCallback)
         {
             oclog() <<"Result callback can't be null";
-            return OC_STACK_INVALID_PARAM;
+            return OC_STACK_INVALID_CALLBACK;
         }
 
         OCStackResult result;
@@ -295,11 +305,16 @@ namespace OC
     OCStackResult OCSecureResource::provisionACL( const OicSecAcl_t* acl,
             ResultCallBack resultCallback)
     {
-        if(!resultCallback || !acl)
+        if(!acl)
         {
-            oclog() <<"Result callback or ACL can't be null";
+            oclog() <<"ACL can't be null";
             return OC_STACK_INVALID_PARAM;
         }
+        if(!resultCallback)
+        {
+            oclog() <<"result callback can not be null";
+            return OC_STACK_INVALID_CALLBACK;
+        }
 
         OCStackResult result;
         auto cLock = m_csdkLock.lock();
@@ -327,7 +342,7 @@ namespace OC
         if(!resultCallback)
         {
             oclog() << "Result calback can't be null";
-            return OC_STACK_INVALID_PARAM;
+            return OC_STACK_INVALID_CALLBACK;
         }
 
         OCStackResult result;
@@ -358,8 +373,8 @@ namespace OC
     {
         if(!resultCallback)
         {
-            oclog() << "Result calback can't be null";
-            return OC_STACK_INVALID_PARAM;
+            oclog() << "Result callback can not be null";
+            return OC_STACK_INVALID_CALLBACK;
         }
 
         OCStackResult result;
@@ -391,7 +406,7 @@ namespace OC
         if(!resultCallback)
         {
             oclog() << "Result calback can't be null";
-            return OC_STACK_INVALID_PARAM;
+            return OC_STACK_INVALID_CALLBACK;
         }
 
         OCStackResult result;
@@ -420,7 +435,7 @@ namespace OC
         if(!resultCallback)
         {
             oclog() << "Result calback can't be null";
-            return OC_STACK_INVALID_PARAM;
+            return OC_STACK_INVALID_CALLBACK;
         }
 
         OCStackResult result;
@@ -475,18 +490,18 @@ namespace OC
 
     std::string OCSecureResource::getDeviceID()
     {
-        char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {0,};
-        uint32_t outLen = 0;
-        B64Result b64Ret = B64_OK;
         std::ostringstream deviceId("");
+        char *devID = nullptr;
 
         validateSecureResource();
-        b64Ret = b64Encode(devPtr->doxm->deviceID.id, sizeof(devPtr->doxm->deviceID.id), base64Buff,
-                sizeof(base64Buff), &outLen);
 
-        if (B64_OK == b64Ret)
+        if (OC_STACK_OK == ConvertUuidToStr(&(devPtr->doxm->deviceID), &devID))
+        {
+            deviceId << devID;
+        }
+        else
         {
-            deviceId << base64Buff;
+            oclog() <<"Can not convert uuid to struuid";
         }
         return deviceId.str();
     }
index cbbc9bc..38e27bf 100644 (file)
@@ -60,7 +60,7 @@ namespace OCProvisioningTest
     TEST(DiscoveryTest, UnownedDevicesZeroTimeout)
     {
         DeviceList_t list;
-        EXPECT_EQ(OC_STACK_OK, OCSecure::discoverUnownedDevices(0, list));
+        EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::discoverUnownedDevices(0, list));
     }
 
     TEST(DiscoveryTest, OwnedDevices)
@@ -72,7 +72,7 @@ namespace OCProvisioningTest
     TEST(DiscoveryTest, OwnedDevicesZeroTimeout)
     {
         DeviceList_t list;
-        EXPECT_EQ(OC_STACK_OK, OCSecure::discoverOwnedDevices(0, list));
+        EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::discoverOwnedDevices(0, list));
     }
 
     TEST(OwnershipTest, SetOwnershipTransferCBDataNull)
@@ -107,7 +107,7 @@ namespace OCProvisioningTest
     {
         OTMCallbackData_t pinBasedCBData;
         pinBasedCBData.loadSecretCB = InputPinCodeCallback;
-        pinBasedCBData.createSecureSessionCB = CreateSecureSessionRandomPinCallbak;
+        pinBasedCBData.createSecureSessionCB = CreateSecureSessionRandomPinCallback;
         pinBasedCBData.createSelectOxmPayloadCB = CreatePinBasedSelectOxmPayload;
         pinBasedCBData.createOwnerTransferPayloadCB = CreatePinBasedOwnerTransferPayload;
         OTMSetOwnershipTransferCallbackData(OIC_RANDOM_DEVICE_PIN, &pinBasedCBData);
@@ -119,7 +119,7 @@ namespace OCProvisioningTest
     TEST(OwnershipTest, OwnershipTransferNullCallback)
     {
         OCSecureResource device;
-        EXPECT_EQ(OC_STACK_INVALID_PARAM, device.doOwnershipTransfer(nullptr));
+        EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.doOwnershipTransfer(nullptr));
     }
 
     TEST(DeviceInfoTest, DevInfoFromNetwork)
@@ -144,7 +144,7 @@ namespace OCProvisioningTest
     {
         OCSecureResource device;
         OicSecAcl_t *acl = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
-        EXPECT_EQ(OC_STACK_INVALID_PARAM, device.provisionACL(acl, nullptr));
+        EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.provisionACL(acl, nullptr));
         OICFree(acl);
     }
 
@@ -158,7 +158,7 @@ namespace OCProvisioningTest
     {
         OCSecureResource device, dev2;
         Credential cred;
-        EXPECT_EQ(OC_STACK_INVALID_PARAM, device.provisionCredentials(cred, dev2, nullptr));
+        EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.provisionCredentials(cred, dev2, nullptr));
     }
 
     TEST(ProvisionPairwiseTest, ProvisionPairwiseTestNullCallback)
@@ -167,7 +167,7 @@ namespace OCProvisioningTest
         Credential cred;
         OicSecAcl_t *acl1 = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
         OicSecAcl_t *acl2 = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
-        EXPECT_EQ(OC_STACK_INVALID_PARAM, device.provisionPairwiseDevices(cred, acl1,
+        EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.provisionPairwiseDevices(cred, acl1,
                     dev2, acl2, nullptr));
         OICFree(acl1);
         OICFree(acl2);
old mode 100644 (file)
new mode 100755 (executable)
index 20f2a19..3582960
@@ -24,6 +24,8 @@ import os.path
 provisiontests_env = env.Clone()
 
 src_dir = provisiontests_env.get('SRC_DIR')
+with_ra = env.get('WITH_RA')
+with_ra_ibb = env.get('WITH_RA_IBB')
 ######################################################################
 # Build flags
 ######################################################################
@@ -62,8 +64,18 @@ provisiontests_env.PrependUnique(LIBS = [
                'gtest_main',
                ])
 
+if with_ra_ibb:
+       provisiontests_env.AppendUnique(LIBS = provisiontests_env['RALIBS'], LIBPATH = provisiontests_env['RALIBPATH'], RPATH = provisiontests_env['RARPATH'])
+       print "RALIBS = %s" % provisiontests_env['RALIBS']
+       print "RALIBPATH = %s" % provisiontests_env['RALIBPATH']
+       print "RARPATH = %s" % provisiontests_env['RARPATH']
+else :
+       if with_ra:
+               provisiontests_env.AppendUnique(LIBS = ['ra_xmpp'])
+
 if env.get('SECURED') == '1':
     provisiontests_env.AppendUnique(LIBS = ['tinydtls'])
+    provisiontests_env.AppendUnique(LIBS = ['timer'])
 if env.get('DTLS_WITH_X509') == '1':
        provisiontests_env.AppendUnique(LIBS = ['CKManager'])
        provisiontests_env.AppendUnique(LIBS = ['asn1'])
diff --git a/resource/src/CAManager.cpp b/resource/src/CAManager.cpp
new file mode 100644 (file)
index 0000000..cafcfa9
--- /dev/null
@@ -0,0 +1,75 @@
+/* ****************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ *
+ * This file contains the implementation of classes and its members related
+ * to CAManager. Network changes status will be passed from CA to application.
+ */
+
+#include "OCApi.h"
+#include "CAManager.h"
+#include "cautilinterface.h"
+
+using namespace OC;
+
+namespace
+{
+        CAManager::AdapterChangedCallback g_adapterHandler = NULL;
+        CAManager::ConnectionChangedCallback g_connectionHandler = NULL;
+}
+
+void DefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
+{
+    if (g_adapterHandler)
+    {
+        g_adapterHandler((OCTransportAdapter) adapter, enabled);
+    }
+}
+
+void DefaultConnectionStateChangedHandler(CATransportAdapter_t adapter,
+                                          const char *remote_address, bool connected)
+{
+    if (g_connectionHandler)
+    {
+        g_connectionHandler((OCTransportAdapter) adapter, remote_address, connected);
+    }
+}
+
+OCStackResult CAManager::setNetworkMonitorHandler(AdapterChangedCallback adapterHandler,
+                                                  ConnectionChangedCallback connectionHandler)
+{
+    g_adapterHandler = adapterHandler;
+    g_connectionHandler = connectionHandler;
+
+    CAResult_t ret = CARegisterNetworkMonitorHandler(DefaultAdapterStateChangedHandler,
+                                                     DefaultConnectionStateChangedHandler);
+
+    switch (ret)
+    {
+        case CA_STATUS_OK:
+            return OC_STACK_OK;
+        case CA_NOT_SUPPORTED:
+            return OC_STACK_NOTIMPL;
+        default:
+            return OC_STACK_ERROR;
+    }
+}
index f441ca9..32293f8 100644 (file)
@@ -124,6 +124,7 @@ namespace OC
         // first one is considered the root, everything else is considered a child of this one.
         OCRepresentation root = *it;
         root.setDevAddr(clientResponse->devAddr);
+        root.setUri(clientResponse->resourceUri);
         ++it;
 
         std::for_each(it, oc.representations().end(),
@@ -164,13 +165,19 @@ namespace OC
             return OC_STACK_KEEP_TRANSACTION;
         }
 
-        ListenOCContainer container(clientWrapper, clientResponse->devAddr,
-                                reinterpret_cast<OCDiscoveryPayload*>(clientResponse->payload));
-        // loop to ensure valid construction of all resources
-        for(auto resource : container.Resources())
-        {
-            std::thread exec(context->callback, resource);
-            exec.detach();
+        try{
+            ListenOCContainer container(clientWrapper, clientResponse->devAddr,
+                                    reinterpret_cast<OCDiscoveryPayload*>(clientResponse->payload));
+            // loop to ensure valid construction of all resources
+            for(auto resource : container.Resources())
+            {
+                std::thread exec(context->callback, resource);
+                exec.detach();
+            }
+        }
+        catch (std::exception &e){
+            oclog() << "Exception in listCallback, ignoring response: "
+                    << e.what() << std::flush;
         }
 
 
@@ -447,6 +454,11 @@ namespace OC
     {
         MessageContainer ocInfo;
         ocInfo.addRepresentation(rep);
+        for(const OCRepresentation& r : rep.getChildren())
+        {
+            ocInfo.addRepresentation(r);
+        }
+
         return reinterpret_cast<OCPayload*>(ocInfo.getPayload());
     }
 
index 4d0b4a2..cdbb0e7 100644 (file)
@@ -103,6 +103,8 @@ std::string OC::OCException::reason(const OCStackResult sr)
             return OC::Exception::DUPLICATE_UUID;
         case OC_STACK_INCONSISTENT_DB:
             return OC::Exception::INCONSISTENT_DB;
+        case OC_STACK_AUTHENTICATION_FAILURE:
+            return OC::Exception::AUTHENTICATION_FAILURE;
     }
 
     return OC::Exception::UNKNOWN_ERROR;
index 2c91437..47dce71 100644 (file)
@@ -43,6 +43,11 @@ namespace OC
 
     void MessageContainer::setPayload(const OCPayload* rep)
     {
+        if (rep == nullptr)
+        {
+            return;
+        }
+
         switch(rep->type)
         {
             case PAYLOAD_TYPE_REPRESENTATION:
@@ -62,16 +67,15 @@ namespace OC
 
     void MessageContainer::setPayload(const OCDevicePayload* payload)
     {
-        OCRepresentation rep;
-        char uuidString[UUID_STRING_SIZE];
-        if(payload->sid && RAND_UUID_OK == OCConvertUuidToString(payload->sid, uuidString))
+        if (payload == nullptr)
         {
-            rep[OC_RSRVD_DEVICE_ID] = std::string(uuidString);
-        }
-        else
-        {
-            rep[OC_RSRVD_DEVICE_ID] = std::string();
+            return;
         }
+
+        OCRepresentation rep;
+        rep[OC_RSRVD_DEVICE_ID] = (payload->sid) ?
+            std::string(payload->sid) :
+            std::string();
         rep[OC_RSRVD_DEVICE_NAME] = payload->deviceName ?
             std::string(payload->deviceName) :
             std::string();
@@ -81,11 +85,20 @@ namespace OC
         rep[OC_RSRVD_DATA_MODEL_VERSION] = payload->dataModelVersion ?
             std::string(payload->dataModelVersion) :
             std::string();
+        for (OCStringLL *strll = payload->types; strll; strll = strll->next)
+        {
+           rep.addResourceType(strll->value);
+        }
         m_reps.push_back(std::move(rep));
     }
 
     void MessageContainer::setPayload(const OCPlatformPayload* payload)
     {
+        if (payload == nullptr)
+        {
+            return;
+        }
+
         OCRepresentation rep;
         rep[OC_RSRVD_PLATFORM_ID] = payload->info.platformID ?
             std::string(payload->info.platformID) :
@@ -121,6 +134,15 @@ namespace OC
             std::string(payload->info.systemTime) :
             std::string();
 
+        if (payload->rt)
+        {
+            rep.addResourceType(payload->rt);
+        }
+        for (OCStringLL *strll = payload->interfaces; strll; strll = strll->next)
+        {
+            rep.addResourceInterface(strll->value);
+        }
+
         m_reps.push_back(std::move(rep));
     }
 
@@ -142,7 +164,7 @@ namespace OC
         OCRepPayload* root = nullptr;
         for(const auto& r : representations())
         {
-            if(!root)
+            if (!root)
             {
                 root = r.getPayload();
             }
@@ -364,7 +386,7 @@ namespace OC
     OCRepPayload* OCRepresentation::getPayload() const
     {
         OCRepPayload* root = OCRepPayloadCreate();
-        if(!root)
+        if (!root)
         {
             throw std::bad_alloc();
         }
@@ -421,11 +443,11 @@ namespace OC
 
     size_t calcArrayDepth(const size_t dimensions[MAX_REP_ARRAY_DEPTH])
     {
-        if(dimensions[0] == 0)
+        if (dimensions[0] == 0)
         {
             throw std::logic_error("invalid calcArrayDepth");
         }
-        else if(dimensions[1] == 0)
+        else if (dimensions[1] == 0)
         {
             return 1;
         }
@@ -487,7 +509,7 @@ namespace OC
     template<typename T>
     void OCRepresentation::payload_array_helper(const OCRepPayloadValue* pl, size_t depth)
     {
-        if(depth == 1)
+        if (depth == 1)
         {
             std::vector<T> val(pl->arr.dimensions[0]);
 
@@ -735,7 +757,7 @@ namespace OC
         // child of a default or link item.
         // Our values array is only printed in the if we are the child of a Batch resource,
         // the parent in a 'default' situation, or not in a child/parent relationship.
-        if(!m_uri.empty())
+        if (!m_uri.empty())
         {
             return false;
         }
@@ -746,7 +768,7 @@ namespace OC
         {
             return false;
         }
-        else if((m_interfaceType == InterfaceType::None
+        else if ((m_interfaceType == InterfaceType::None
                         || m_interfaceType == InterfaceType::BatchChild
                         || m_interfaceType == InterfaceType::DefaultParent)
                     && m_values.size()>0)
@@ -754,7 +776,7 @@ namespace OC
             return false;
         }
 
-        if(m_children.size() > 0)
+        if (m_children.size() > 0)
         {
             return false;
         }
@@ -781,7 +803,7 @@ namespace OC
     {
         auto x = m_values.find(str);
 
-        if(m_values.end() != x)
+        if (m_values.end() != x)
         {
             return x->second.which() == AttributeValueNullIndex;
         }
@@ -1003,7 +1025,7 @@ namespace OC
     OCRepresentation::iterator& OCRepresentation::iterator::operator++()
     {
         m_iterator++;
-        if(m_iterator != m_item.m_values.end())
+        if (m_iterator != m_item.m_values.end())
         {
             m_item.m_attrName = m_iterator->first;
         }
@@ -1017,7 +1039,7 @@ namespace OC
     OCRepresentation::const_iterator& OCRepresentation::const_iterator::operator++()
     {
         m_iterator++;
-        if(m_iterator != m_item.m_values.end())
+        if (m_iterator != m_item.m_values.end())
         {
             m_item.m_attrName = m_iterator->first;
         }
@@ -1095,7 +1117,7 @@ namespace OC
     std::string OCRepresentation::getValueToString(const std::string& key) const
     {
         auto x = m_values.find(key);
-        if(x != m_values.end())
+        if (x != m_values.end())
         {
             to_string_visitor vis;
             boost::apply_visitor(vis, x->second);
@@ -1118,4 +1140,3 @@ namespace OC
         return os;
     }
 }
-
index 2d11e46..a3c8ec8 100644 (file)
@@ -23,6 +23,7 @@
 
 #include <boost/lexical_cast.hpp>
 #include <sstream>
+#include <arpa/inet.h>
 
 namespace OC {
 
@@ -66,7 +67,11 @@ OCResource::OCResource(std::weak_ptr<IClientWrapper> clientWrapper,
                         const std::vector<std::string>& interfaces)
  :  m_clientWrapper(clientWrapper), m_uri(uri),
     m_resourceId(serverId, m_uri),
-    m_devAddr{ OC_DEFAULT_ADAPTER, OC_DEFAULT_FLAGS, 0, {0}, 0 },
+    m_devAddr{ OC_DEFAULT_ADAPTER, OC_DEFAULT_FLAGS, 0, {0}, 0
+#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
+    , {0}
+#endif
+    },
     m_isObservable(observable), m_isCollection(false),
     m_resourceTypes(resourceTypes), m_interfaces(interfaces),
     m_observeHandle(nullptr)
@@ -98,11 +103,6 @@ OCResource::OCResource(std::weak_ptr<IClientWrapper> clientWrapper,
     // construct the devAddr from the pieces we have
     m_devAddr.adapter = static_cast<OCTransportAdapter>(connectivityType >> CT_ADAPTER_SHIFT);
     m_devAddr.flags = static_cast<OCTransportFlags>(connectivityType & CT_MASK_FLAGS);
-    size_t len = host.length();
-    if (len >= MAX_ADDR_STR_SIZE)
-    {
-        throw std::length_error("host address is too long.");
-    }
 
     this->setHost(host);
 }
@@ -127,7 +127,6 @@ void OCResource::setHost(const std::string& host)
     else if (host.compare(0, sizeof(COAP_TCP) - 1, COAP_TCP) == 0)
     {
         prefix_len = sizeof(COAP_TCP) - 1;
-        m_devAddr.adapter = static_cast<OCTransportAdapter>(m_devAddr.adapter & OC_ADAPTER_TCP);
     }
     else
     {
@@ -135,54 +134,126 @@ void OCResource::setHost(const std::string& host)
             m_interfaces.empty(), m_clientWrapper.expired(), false, false);
     }
 
-    // removed coap:// or coaps:// or coap+tcp://
+    // remove 'coap://' or 'coaps://' or 'coap+tcp://'
     std::string host_token = host.substr(prefix_len);
 
-    if(host_token[0] == '[')
+    if(host_token[0] == '[') // IPv6
     {
-        m_devAddr.flags = static_cast<OCTransportFlags>(m_devAddr.flags & OC_IP_USE_V6);
+        size_t bracket = host_token.find(']');
 
-        size_t found = host_token.find(']');
+        if(bracket == std::string::npos || bracket == 0)
+        {
+            throw ResourceInitException(m_uri.empty(), m_resourceTypes.empty(),
+                m_interfaces.empty(), m_clientWrapper.expired(), false, false);
+        }
+        // extract the ipv6 address
+        std::string ip6Addr = host_token.substr(1, bracket - 1);
 
-        if(found == std::string::npos || found == 0)
+        // address validity check
+        struct in6_addr buf;
+        const char *cAddr = ip6Addr.c_str();
+        if(0 == inet_pton(AF_INET6, cAddr, &buf))
         {
             throw ResourceInitException(m_uri.empty(), m_resourceTypes.empty(),
                 m_interfaces.empty(), m_clientWrapper.expired(), false, false);
         }
-        // extract the ipaddress
-        std::string ip6Addr = host_token.substr(1, found-1);
-        ip6Addr.copy(m_devAddr.addr, sizeof(m_devAddr.addr));
-        m_devAddr.addr[ip6Addr.length()] = '\0';
+
         //skip ']' and ':' characters in host string
-        host_token = host_token.substr(found + 2);
-    }
-    else
-    {
-        size_t found = host_token.find(':');
+        host_token = host_token.substr(bracket + 2);
+        int port = std::stoi(host_token);
 
-        if(found == std::string::npos || found == 0)
+        if (0 > port || UINT16_MAX < port)
         {
             throw ResourceInitException(m_uri.empty(), m_resourceTypes.empty(),
                 m_interfaces.empty(), m_clientWrapper.expired(), false, false);
         }
 
-        std::string addrPart = host_token.substr(0, found);
-        addrPart.copy(m_devAddr.addr, sizeof(m_devAddr.addr));
-        m_devAddr.addr[addrPart.length()] = '\0';
-        //skip ':' character in host string
-        host_token = host_token.substr(found + 1);
+        ip6Addr.copy(m_devAddr.addr, sizeof(m_devAddr.addr));
+        m_devAddr.addr[ip6Addr.length()] = '\0';
+        m_devAddr.port = static_cast<uint16_t>(port);
+        m_devAddr.flags = static_cast<OCTransportFlags>(m_devAddr.flags & OC_IP_USE_V6);
     }
-
-    int port = std::stoi(host_token);
-
-    if( port < 0 || port > UINT16_MAX )
+    else if (host_token[0] == ':')
     {
         throw ResourceInitException(m_uri.empty(), m_resourceTypes.empty(),
             m_interfaces.empty(), m_clientWrapper.expired(), false, false);
     }
-
-    m_devAddr.port = static_cast<uint16_t>(port);
-
+    else
+    {
+        size_t dot = host_token.find('.');
+        if (std::string::npos == dot) // MAC
+        {
+            std::string macAddr = host_token;
+
+            // address validity check
+            if (MAC_ADDR_STR_SIZE != macAddr.length())
+            {
+                throw ResourceInitException(m_uri.empty(), m_resourceTypes.empty(),
+                    m_interfaces.empty(), m_clientWrapper.expired(), false, false);
+            }
+
+            for (size_t blockCnt = 0; blockCnt < MAC_ADDR_BLOCKS; blockCnt++)
+            {
+                std::string block = macAddr.substr(blockCnt * 3, 2);
+
+                if (std::string::npos != block.find_first_not_of("0123456789ABCDEFabcdef"))
+                {
+                    throw ResourceInitException(m_uri.empty(), m_resourceTypes.empty(),
+                        m_interfaces.empty(), m_clientWrapper.expired(), false, false);
+                }
+
+                if (MAC_ADDR_BLOCKS - 1 > blockCnt)
+                {
+                    char delimiter = macAddr[blockCnt * 3 + 2];
+
+                    if (':' != delimiter)
+                    {
+                        throw ResourceInitException(m_uri.empty(), m_resourceTypes.empty(),
+                            m_interfaces.empty(), m_clientWrapper.expired(), false, false);
+                    }
+                }
+            }
+
+            macAddr.copy(m_devAddr.addr, sizeof(m_devAddr.addr));
+            m_devAddr.addr[MAC_ADDR_STR_SIZE] = '\0';
+        }
+        else // IPv4
+        {
+            size_t colon = host_token.find(':');
+
+            if (colon == std::string::npos || colon == 0)
+            {
+                throw ResourceInitException(m_uri.empty(), m_resourceTypes.empty(),
+                    m_interfaces.empty(), m_clientWrapper.expired(), false, false);
+            }
+
+            // extract the ipv4 address
+            std::string ip4Addr = host_token.substr(0, colon);
+
+            // address validity check
+            struct in_addr buf;
+            const char *cAddr = ip4Addr.c_str();
+            if(0 == inet_pton(AF_INET, cAddr, &buf))
+            {
+                throw ResourceInitException(m_uri.empty(), m_resourceTypes.empty(),
+                    m_interfaces.empty(), m_clientWrapper.expired(), false, false);
+            }
+
+            //skip ':' characters in host string
+            host_token = host_token.substr(colon + 1);
+            int port = std::stoi(host_token);
+
+            if (0 > port || UINT16_MAX < port)
+            {
+                throw ResourceInitException(m_uri.empty(), m_resourceTypes.empty(),
+                    m_interfaces.empty(), m_clientWrapper.expired(), false, false);
+            }
+
+            ip4Addr.copy(m_devAddr.addr, sizeof(m_devAddr.addr));
+            m_devAddr.addr[ip4Addr.length()] = '\0';
+            m_devAddr.port = static_cast<uint16_t>(port);
+        }
+    }
 }
 
 OCStackResult OCResource::get(const QueryParamsMap& queryParametersMap,
@@ -412,7 +483,9 @@ std::string OCResource::host() const
     {
         ss << COAPS;
     }
-    else if (m_devAddr.adapter & OC_ADAPTER_TCP)
+    else if ((m_devAddr.adapter & OC_ADAPTER_TCP)
+            || (m_devAddr.adapter & OC_ADAPTER_GATT_BTLE)
+            || (m_devAddr.adapter & OC_ADAPTER_RFCOMM_BTEDR))
     {
         ss << COAP_TCP;
     }
@@ -548,4 +621,3 @@ bool OCResourceIdentifier::operator>=(const OCResourceIdentifier &other) const
 }
 
 } // namespace OC
-
index f0e606e..a2dd893 100644 (file)
@@ -18,9 +18,9 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#include <OCApi.h>
+#include "OCApi.h"
 
-#include <OCUtilities.h>
+#include "OCUtilities.h"
 
 #include <boost/algorithm/string.hpp>
 
index 7d6df06..de1e678 100644 (file)
@@ -37,12 +37,14 @@ oclib_env.AppendUnique(CPPPATH = [
                '../c_common/ocrandom/include',
                '../csdk/logger/include',
                '../oc_logger/include',
-               '../csdk/connectivity/lib/libcoap-4.1.1'
+               '../csdk/connectivity/lib/libcoap-4.1.1',
+               '../csdk/connectivity/api'
                ])
 
 oclib_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 
 oclib_env.AppendUnique(LIBS = ['octbstack', 'oc_logger'])
+oclib_env.AppendUnique(LIBS = ['connectivity_abstraction'])
 
 target_os = env.get('TARGET_OS')
 if target_os == 'linux':
@@ -61,6 +63,9 @@ if target_os == 'android':
 if target_os == 'tizen':
        oclib_env.AppendUnique(CPPDEFINES = ['__TIZEN__'])
 
+if target_os in ['linux'] and env.get('SIMULATOR', False):
+    oclib_env.Append( RPATH = env.Literal('\\$$ORIGIN'))
+
 ######################################################################
 # Source files and Targets
 ######################################################################
@@ -73,21 +78,42 @@ oclib_src = [
                'OCRepresentation.cpp',
                'InProcServerWrapper.cpp',
                'InProcClientWrapper.cpp',
-               'OCResourceRequest.cpp'
+               'OCResourceRequest.cpp',
+               'CAManager.cpp'
        ]
 
 oclib = oclib_env.SharedLibrary('oc', oclib_src)
 oclib_env.InstallTarget(oclib, 'liboc')
 oclib_env.UserInstallTargetLib(oclib, 'liboc')
 
-src_dir = env.get('SRC_DIR')
+header_dir = env.get('SRC_DIR') + '/resource/include/'
+
+oclib_env.UserInstallTargetHeader(header_dir + 'OCApi.h', 'resource', 'OCApi.h')
+oclib_env.UserInstallTargetHeader(header_dir + 'OCHeaderOption.h', 'resource', 'OCHeaderOption.h')
+oclib_env.UserInstallTargetHeader(header_dir + 'OCException.h', 'resource', 'OCException.h')
+oclib_env.UserInstallTargetHeader(header_dir + 'StringConstants.h', 'resource', 'StringConstants.h')
+
+oclib_env.UserInstallTargetHeader(header_dir + 'OCPlatform.h', 'resource', 'OCPlatform.h')
+oclib_env.UserInstallTargetHeader(header_dir + 'OCPlatform_impl.h', 'resource', 'OCPlatform_impl.h')
+oclib_env.UserInstallTargetHeader(header_dir + 'WrapperFactory.h', 'resource', 'WrapperFactory.h')
+oclib_env.UserInstallTargetHeader(header_dir + 'IClientWrapper.h', 'resource', 'IClientWrapper.h')
+oclib_env.UserInstallTargetHeader(header_dir + 'IServerWrapper.h', 'resource', 'IServerWrapper.h')
+oclib_env.UserInstallTargetHeader(header_dir + 'OutOfProcClientWrapper.h', 'resource', 'OutOfProcClientWrapper.h')
+oclib_env.UserInstallTargetHeader(header_dir + 'OutOfProcServerWrapper.h', 'resource', 'OutOfProcServerWrapper.h')
+oclib_env.UserInstallTargetHeader(header_dir + 'InProcClientWrapper.h', 'resource', 'InProcClientWrapper.h')
+oclib_env.UserInstallTargetHeader(header_dir + 'InProcServerWrapper.h', 'resource', 'InProcServerWrapper.h')
+oclib_env.UserInstallTargetHeader(header_dir + 'InitializeException.h', 'resource', 'InitializeException.h')
+oclib_env.UserInstallTargetHeader(header_dir + 'ResourceInitException.h', 'resource', 'ResourceInitException.h')
+
+oclib_env.UserInstallTargetHeader(header_dir + 'OCRepresentation.h', 'resource', 'OCRepresentation.h')
+oclib_env.UserInstallTargetHeader(header_dir + 'AttributeValue.h', 'resource', 'AttributeValue.h')
+
+oclib_env.UserInstallTargetHeader(header_dir + 'OCResource.h', 'resource', 'OCResource.h')
+oclib_env.UserInstallTargetHeader(header_dir + 'OCResourceRequest.h', 'resource', 'OCResourceRequest.h')
+oclib_env.UserInstallTargetHeader(header_dir + 'OCResourceResponse.h', 'resource', 'OCResourceResponse.h')
+oclib_env.UserInstallTargetHeader(header_dir + 'OCUtilities.h', 'resource', 'OCUtilities.h')
 
-oclib_env.UserInstallTargetHeader(src_dir + '/resource/include/OCApi.h', 'resource', 'OCApi.h')
-oclib_env.UserInstallTargetHeader(src_dir + '/resource/include/OCPlatform.h', 'resource', 'OCPlatform.h')
-oclib_env.UserInstallTargetHeader(src_dir + '/resource/include/OCRepresentation.h', 'resource', 'OCRepresentation.h')
-oclib_env.UserInstallTargetHeader(src_dir + '/resource/include/OCResource.h', 'resource', 'OCResource.h')
-oclib_env.UserInstallTargetHeader(src_dir + '/resource/include/OCResourceRequest.h', 'resource', 'OCResourceRequest.h')
-oclib_env.UserInstallTargetHeader(src_dir + '/resource/include/OCResourceResponse.h', 'resource', 'OCResourceResponse.h')
+oclib_env.UserInstallTargetHeader(header_dir + 'CAManager.h', 'resource', 'CAManager.h')
 
 # Add Provisioning library
 if target_os in ['linux', 'android', 'tizen'] and env.get('SECURED') == '1':
index a638e4b..08a9ffb 100644 (file)
@@ -41,6 +41,7 @@ if target_os == 'linux':
     # Build Common unit tests
        SConscript('c_common/oic_string/test/SConscript')
        SConscript('c_common/oic_malloc/test/SConscript')
+       SConscript('c_common/oic_time/test/SConscript')
        SConscript('c_common/ocrandom/test/SConscript')
 
        # Build C unit tests
index 39436cd..efe51dd 100644 (file)
@@ -70,7 +70,8 @@ namespace OC
                 OC_STACK_ERROR,
                 OC_STACK_PDM_IS_NOT_INITIALIZED,
                 OC_STACK_DUPLICATE_UUID,
-                OC_STACK_INCONSISTENT_DB
+                OC_STACK_INCONSISTENT_DB,
+                OC_STACK_AUTHENTICATION_FAILURE
             };
 
             std::string resultMessages[]=
@@ -112,7 +113,8 @@ namespace OC
                 OC::Exception::GENERAL_FAULT,
                 OC::Exception::PDM_DB_NOT_INITIALIZED,
                 OC::Exception::DUPLICATE_UUID,
-                OC::Exception::INCONSISTENT_DB
+                OC::Exception::INCONSISTENT_DB,
+                OC::Exception::AUTHENTICATION_FAILURE
             };
             TEST(OCExceptionTest, ReasonCodeMatches)
             {
index 078aa89..f2db5df 100644 (file)
 
 #include <OCPlatform.h>
 #include <OCApi.h>
+#include <oic_malloc.h>
 #include <gtest/gtest.h>
 
 namespace OCPlatformTest
 {
     using namespace OC;
 
+    static const char* SVR_DB_FILE_NAME = "./oic_svr_db_server.dat";
     const OCResourceHandle HANDLE_ZERO = 0;
     const std::string gResourceTypeName = "core.res";
     const std::string gResourceInterface = DEFAULT_INTERFACE;
@@ -35,9 +37,9 @@ namespace OCPlatformTest
     //OCPersistent Storage Handlers
     static FILE* client_open(const char * /*path*/, const char *mode)
     {
-        std::cout << "<===Opening SVR DB file = './oic_svr_db_client.json' with mode = '" << mode
+        std::cout << "<===Opening SVR DB file = './oic_svr_db_client.dat' with mode = '" << mode
                 << "' " << std::endl;
-        return fopen("./oic_svr_db_client.json", mode);
+        return fopen(SVR_DB_FILE_NAME, mode);
     }
     OCPersistentStorage gps {client_open, fread, fwrite, fclose, unlink };
 
@@ -61,9 +63,22 @@ namespace OCPlatformTest
     }
 
     //Helper methods
+    void DeleteStringLL(OCStringLL* ll)
+    {
+        if (!ll)
+        {
+            return;
+        }
+
+        DeleteStringLL(ll->next);
+        delete[] ll->value;
+        OICFree(ll);
+    }
+
     void DeleteDeviceInfo(OCDeviceInfo deviceInfo)
     {
         delete[] deviceInfo.deviceName;
+        DeleteStringLL(deviceInfo.types);
 
     }
 
@@ -73,6 +88,30 @@ namespace OCPlatformTest
         strncpy(*targetString, sourceString.c_str(), (sourceString.length() + 1));
     }
 
+    bool OCResourcePayloadAddStringLL(OCStringLL **stringLL, std::string value)
+    {
+        char *dup = NULL;
+        DuplicateString(&dup, value);
+        if (!*stringLL)
+        {
+            *stringLL = (OCStringLL *)OICCalloc(1, sizeof(OCStringLL));
+            (*stringLL)->value = dup;
+            return true;
+        }
+        else
+        {
+            OCStringLL *temp = *stringLL;
+            while(temp->next)
+            {
+                temp = temp->next;
+            }
+            temp->next = (OCStringLL *)OICCalloc(1, sizeof(OCStringLL));
+            temp->next->value = dup;
+            return true;
+        }
+        return false;
+    }
+
     OCResourceHandle RegisterResource(std::string uri, std::string type, std::string iface)
     {
         PlatformConfig cfg
@@ -697,15 +736,17 @@ namespace OCPlatformTest
     TEST(RegisterDeviceInfoTest, RegisterDeviceInfoWithValidParameters)
     {
         OCDeviceInfo deviceInfo;
-
         DuplicateString(&deviceInfo.deviceName, "myDeviceName");
+        deviceInfo.types = NULL;
+        OCResourcePayloadAddStringLL(&deviceInfo.types, "oic.wk.d");
+        OCResourcePayloadAddStringLL(&deviceInfo.types, "oic.d.tv");
         EXPECT_EQ(OC_STACK_OK, OCPlatform::registerDeviceInfo(deviceInfo));
         EXPECT_NO_THROW(DeleteDeviceInfo(deviceInfo));
     }
 
     TEST(RegisterDeviceInfoTest, RegisterDeviceInfoWithEmptyObject)
     {
-        OCDeviceInfo di = {0};
+        OCDeviceInfo di = {0, 0};
         EXPECT_ANY_THROW(OCPlatform::registerDeviceInfo(di));
     }
 
index edf695f..a1ca196 100644 (file)
 #include <OCApi.h>
 #include <OCRepresentation.h>
 #include <octypes.h>
+#include <ocstack.h>
 #include <ocpayload.h>
 #include <ocpayloadcbor.h>
 #include <oic_malloc.h>
 #include <oic_string.h>
+#include "payload_logging.h"
 
 namespace OC
 {
@@ -47,28 +49,30 @@ namespace OC
 // CBOR->OCPayload and OCPayload->OCRepresentation conversions
 namespace OCRepresentationEncodingTest
 {
-    static const uint8_t sid1[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
+    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 OCStringLL *types = NULL;
     // Device Payloads
     TEST(DeviceDiscoveryEncoding, Normal)
     {
+        OCResourcePayloadAddStringLL(&types, "oic.wk.d");
+        OCResourcePayloadAddStringLL(&types, "oic.d.tv");
+
         OCDevicePayload* device = OCDevicePayloadCreate(
                 sid1,
                 devicename1,
+                types,
                 specver1,
                 dmver1);
-
+        EXPECT_STREQ(sid1, device->sid);
         EXPECT_STREQ(devicename1, device->deviceName);
         EXPECT_STREQ(specver1, device->specVersion);
         EXPECT_STREQ(dmver1, device->dataModelVersion);
         EXPECT_EQ(PAYLOAD_TYPE_DEVICE, ((OCPayload*)device)->type);
-
-        for (uint8_t i = 1; i <= sizeof(sid1); ++i)
-        {
-            EXPECT_EQ(i, sid1[i - 1]);
-        }
+        EXPECT_STREQ("oic.wk.d", device->types->value);
+        EXPECT_STREQ("oic.d.tv", device->types->next->value);
 
         uint8_t* cborData;
         size_t cborSize;
@@ -78,9 +82,12 @@ namespace OCRepresentationEncodingTest
                     cborData, cborSize));
         OICFree(cborData);
 
+        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("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);
 
         OCPayloadDestroy((OCPayload*)device);
@@ -89,6 +96,7 @@ namespace OCRepresentationEncodingTest
         mc.setPayload(parsedDevice);
         EXPECT_EQ(1u, mc.representations().size());
         const OC::OCRepresentation& r = mc.representations()[0];
+        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());
@@ -127,6 +135,9 @@ namespace OCRepresentationEncodingTest
         EXPECT_STREQ(fwver1, platform->info.firmwareVersion);
         EXPECT_STREQ(url1, platform->info.supportUrl);
         EXPECT_STREQ(time1, platform->info.systemTime);
+        EXPECT_STREQ(OC_RSRVD_INTERFACE_DEFAULT, platform->interfaces->value);
+        EXPECT_STREQ(OC_RSRVD_INTERFACE_READ, platform->interfaces->next->value);
+        EXPECT_STREQ(OC_RSRVD_RESOURCE_TYPE_PLATFORM, platform->rt);
 
         uint8_t* cborData;
         size_t cborSize;
@@ -149,6 +160,8 @@ namespace OCRepresentationEncodingTest
         EXPECT_STREQ(platform->info.firmwareVersion, platform->info.firmwareVersion);
         EXPECT_STREQ(platform->info.supportUrl, platform->info.supportUrl);
         EXPECT_STREQ(platform->info.systemTime, platform2->info.systemTime);
+        EXPECT_STREQ(platform->interfaces->value, platform2->interfaces->value);
+        EXPECT_STREQ(platform->rt, platform2->rt);
 
         OCPayloadDestroy((OCPayload*)platform);
 
@@ -679,11 +692,12 @@ namespace OCRepresentationEncodingTest
     {
         OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
         OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
-        payload->sid = (uint8_t*)OICMalloc(16);
+        payload->sid = OICStrdup(sid1);
         payload->resources = resource;
 
-        OCResourcePayloadAddResourceType(resource, "rt.singleitem");
-        OCResourcePayloadAddInterface(resource, "if.singleitem");
+        EXPECT_TRUE(OCResourcePayloadAddStringLL(&resource->types, "rt.singleitem"));
+        EXPECT_TRUE(OCResourcePayloadAddStringLL(&resource->interfaces, "if.singleitem"));
+
         resource->uri = OICStrdup("/uri/thing");
 
         uint8_t* cborData;
@@ -697,10 +711,10 @@ namespace OCRepresentationEncodingTest
         EXPECT_EQ(1u, OCDiscoveryPayloadGetResourceCount((OCDiscoveryPayload*)cparsed));
         OCResourcePayload* parsedResource = ((OCDiscoveryPayload*)cparsed)->resources;
 
+        EXPECT_STREQ(sid1, ((OCDiscoveryPayload*)cparsed)->sid);
         EXPECT_EQ(NULL, parsedResource->next);
-
-        EXPECT_EQ(NULL, parsedResource->types->next);
         EXPECT_STREQ("rt.singleitem", parsedResource->types->value);
+        EXPECT_EQ(NULL, parsedResource->types->next);
         EXPECT_EQ(NULL, parsedResource->interfaces->next);
         EXPECT_STREQ("if.singleitem", parsedResource->interfaces->value);
 
@@ -712,12 +726,12 @@ namespace OCRepresentationEncodingTest
     TEST(DiscoveryRTandIF, SingleItemFrontTrim)
     {
         OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
-        payload->sid = (uint8_t*)OICMalloc(16);
+        payload->sid = OICStrdup(sid1);
         OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
         payload->resources = resource;
 
-        OCResourcePayloadAddResourceType(resource, "    rt.singleitem");
-        OCResourcePayloadAddInterface(resource, "    if.singleitem");
+        EXPECT_TRUE(OCResourcePayloadAddStringLL(&resource->types, "    rt.singleitem"));
+        EXPECT_TRUE(OCResourcePayloadAddStringLL(&resource->interfaces, "    if.singleitem"));
         resource->uri = OICStrdup("/uri/thing");
 
         uint8_t* cborData;
@@ -732,7 +746,7 @@ namespace OCRepresentationEncodingTest
         OCResourcePayload* parsedResource = ((OCDiscoveryPayload*)cparsed)->resources;
 
         EXPECT_EQ(NULL, parsedResource->next);
-
+        EXPECT_STREQ(sid1, ((OCDiscoveryPayload*)cparsed)->sid);
         EXPECT_EQ(NULL, parsedResource->types->next);
         EXPECT_STREQ("rt.singleitem", parsedResource->types->value);
         EXPECT_EQ(NULL, parsedResource->interfaces->next);
@@ -742,15 +756,16 @@ namespace OCRepresentationEncodingTest
         OCPayloadDestroy(cparsed);
         OCDiscoveryPayloadDestroy(payload);
     }
+
     TEST(DiscoveryRTandIF, SingleItemBackTrim)
     {
         OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
-        payload->sid = (uint8_t*)OICMalloc(16);
+        payload->sid = OICStrdup(sid1);
         OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
         payload->resources = resource;
 
-        OCResourcePayloadAddResourceType(resource, "rt.singleitem    ");
-        OCResourcePayloadAddInterface(resource, "if.singleitem    ");
+        OCResourcePayloadAddStringLL(&resource->types, "rt.singleitem    ");
+        OCResourcePayloadAddStringLL(&resource->interfaces, "if.singleitem    ");
         resource->uri = OICStrdup("/uri/thing");
 
         uint8_t* cborData;
@@ -765,7 +780,7 @@ namespace OCRepresentationEncodingTest
         OCResourcePayload* parsedResource = ((OCDiscoveryPayload*)cparsed)->resources;
 
         EXPECT_EQ(NULL, parsedResource->next);
-
+        EXPECT_STREQ(sid1, ((OCDiscoveryPayload*)cparsed)->sid);
         EXPECT_EQ(NULL, parsedResource->types->next);
         EXPECT_STREQ("rt.singleitem", parsedResource->types->value);
         EXPECT_EQ(NULL, parsedResource->interfaces->next);
@@ -778,12 +793,12 @@ namespace OCRepresentationEncodingTest
     TEST(DiscoveryRTandIF, SingleItemBothTrim)
     {
         OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
-        payload->sid = (uint8_t*)OICMalloc(16);
+        payload->sid = OICStrdup(sid1);
         OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
         payload->resources = resource;
 
-        OCResourcePayloadAddResourceType(resource, "    rt.singleitem    ");
-        OCResourcePayloadAddInterface(resource, "    if.singleitem     ");
+        OCResourcePayloadAddStringLL(&resource->types, "    rt.singleitem    ");
+        OCResourcePayloadAddStringLL(&resource->interfaces, "    if.singleitem     ");
         resource->uri = OICStrdup("/uri/thing");
 
         uint8_t* cborData;
@@ -798,7 +813,7 @@ namespace OCRepresentationEncodingTest
         OCResourcePayload* parsedResource = ((OCDiscoveryPayload*)cparsed)->resources;
 
         EXPECT_EQ(NULL, parsedResource->next);
-
+        EXPECT_STREQ(sid1, ((OCDiscoveryPayload*)cparsed)->sid);
         EXPECT_EQ(NULL, parsedResource->types->next);
         EXPECT_STREQ("rt.singleitem", parsedResource->types->value);
         EXPECT_EQ(NULL, parsedResource->interfaces->next);
@@ -811,14 +826,14 @@ namespace OCRepresentationEncodingTest
     TEST(DiscoveryRTandIF, MultiItemsNormal)
     {
         OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
-        payload->sid = (uint8_t*)OICMalloc(16);
+        payload->sid = OICStrdup(sid1);
         OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
         payload->resources = resource;
 
-        OCResourcePayloadAddResourceType(resource, "rt.firstitem");
-        OCResourcePayloadAddResourceType(resource, "rt.seconditem");
-        OCResourcePayloadAddInterface(resource, "if.firstitem");
-        OCResourcePayloadAddInterface(resource, "if.seconditem");
+        OCResourcePayloadAddStringLL(&resource->types, "rt.firstitem");
+        OCResourcePayloadAddStringLL(&resource->types, "rt.seconditem");
+        OCResourcePayloadAddStringLL(&resource->interfaces, "if.firstitem");
+        OCResourcePayloadAddStringLL(&resource->interfaces, "if.seconditem");
         resource->uri = OICStrdup("/uri/thing");
 
         uint8_t* cborData;
@@ -833,7 +848,7 @@ namespace OCRepresentationEncodingTest
         OCResourcePayload* parsedResource = ((OCDiscoveryPayload*)cparsed)->resources;
 
         EXPECT_EQ(NULL, parsedResource->next);
-
+        EXPECT_STREQ(sid1, ((OCDiscoveryPayload*)cparsed)->sid);
         EXPECT_EQ(NULL, parsedResource->types->next->next);
         EXPECT_STREQ("rt.firstitem", parsedResource->types->value);
         EXPECT_STREQ("rt.seconditem", parsedResource->types->next->value);
@@ -848,14 +863,14 @@ namespace OCRepresentationEncodingTest
     TEST(DiscoveryRTandIF, MultiItemExtraLeadSpaces)
     {
         OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
-        payload->sid = (uint8_t*)OICMalloc(16);
+        payload->sid = OICStrdup(sid1);
         OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
         payload->resources = resource;
 
-        OCResourcePayloadAddResourceType(resource, "  rt.firstitem");
-        OCResourcePayloadAddResourceType(resource, "  rt.seconditem");
-        OCResourcePayloadAddInterface(resource, "  if.firstitem");
-        OCResourcePayloadAddInterface(resource, "  if.seconditem");
+        OCResourcePayloadAddStringLL(&resource->types, "  rt.firstitem");
+        OCResourcePayloadAddStringLL(&resource->types, "  rt.seconditem");
+        OCResourcePayloadAddStringLL(&resource->interfaces, "  if.firstitem");
+        OCResourcePayloadAddStringLL(&resource->interfaces, "  if.seconditem");
         resource->uri = OICStrdup("/uri/thing");
 
         uint8_t* cborData;
@@ -870,7 +885,7 @@ namespace OCRepresentationEncodingTest
         OCResourcePayload* parsedResource = ((OCDiscoveryPayload*)cparsed)->resources;
 
         EXPECT_EQ(NULL, parsedResource->next);
-
+        EXPECT_STREQ(sid1, ((OCDiscoveryPayload*)cparsed)->sid);
         EXPECT_EQ(NULL, parsedResource->types->next->next);
         EXPECT_STREQ("rt.firstitem", parsedResource->types->value);
         EXPECT_STREQ("rt.seconditem", parsedResource->types->next->value);
@@ -885,14 +900,14 @@ namespace OCRepresentationEncodingTest
     TEST(DiscoveryRTandIF, MultiItemExtraTrailSpaces)
     {
         OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
-        payload->sid = (uint8_t*)OICMalloc(16);
+        payload->sid = OICStrdup(sid1);
         OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
         payload->resources = resource;
 
-        OCResourcePayloadAddResourceType(resource, "rt.firstitem  ");
-        OCResourcePayloadAddResourceType(resource, "rt.seconditem  ");
-        OCResourcePayloadAddInterface(resource, "if.firstitem  ");
-        OCResourcePayloadAddInterface(resource, "if.seconditem  ");
+        OCResourcePayloadAddStringLL(&resource->types, "rt.firstitem  ");
+        OCResourcePayloadAddStringLL(&resource->types, "rt.seconditem  ");
+        OCResourcePayloadAddStringLL(&resource->interfaces, "if.firstitem  ");
+        OCResourcePayloadAddStringLL(&resource->interfaces, "if.seconditem  ");
         resource->uri = OICStrdup("/uri/thing");
 
         uint8_t* cborData;
@@ -907,7 +922,7 @@ namespace OCRepresentationEncodingTest
         OCResourcePayload* parsedResource = ((OCDiscoveryPayload*)cparsed)->resources;
 
         EXPECT_EQ(NULL, parsedResource->next);
-
+        EXPECT_STREQ(sid1, ((OCDiscoveryPayload*)cparsed)->sid);
         EXPECT_EQ(NULL, parsedResource->types->next->next);
         EXPECT_STREQ("rt.firstitem", parsedResource->types->value);
         EXPECT_STREQ("rt.seconditem", parsedResource->types->next->value);
@@ -922,14 +937,14 @@ namespace OCRepresentationEncodingTest
     TEST(DiscoveryRTandIF, MultiItemBothSpaces)
     {
         OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
-        payload->sid = (uint8_t*)OICMalloc(16);
+        payload->sid = OICStrdup(sid1);
         OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
         payload->resources = resource;
 
-        OCResourcePayloadAddResourceType(resource, "  rt.firstitem  ");
-        OCResourcePayloadAddResourceType(resource, "  rt.seconditem  ");
-        OCResourcePayloadAddInterface(resource, "  if.firstitem  ");
-        OCResourcePayloadAddInterface(resource, "  if.seconditem  ");
+        OCResourcePayloadAddStringLL(&resource->types, "  rt.firstitem  ");
+        OCResourcePayloadAddStringLL(&resource->types, "  rt.seconditem  ");
+        OCResourcePayloadAddStringLL(&resource->interfaces, "  if.firstitem  ");
+        OCResourcePayloadAddStringLL(&resource->interfaces, "  if.seconditem  ");
         resource->uri = OICStrdup("/uri/thing");
 
         uint8_t* cborData;
@@ -944,7 +959,7 @@ namespace OCRepresentationEncodingTest
         OCResourcePayload* parsedResource = ((OCDiscoveryPayload*)cparsed)->resources;
 
         EXPECT_EQ(NULL, parsedResource->next);
-
+        EXPECT_STREQ(sid1, ((OCDiscoveryPayload*)cparsed)->sid);
         EXPECT_EQ(NULL, parsedResource->types->next->next);
         EXPECT_STREQ("rt.firstitem", parsedResource->types->value);
         EXPECT_STREQ("rt.seconditem", parsedResource->types->next->value);
@@ -977,7 +992,6 @@ namespace OCRepresentationEncodingTest
         EXPECT_STREQ("if.firstitem", parsedPayload->interfaces->value);
         EXPECT_EQ(NULL, parsedPayload->interfaces->next);
 
-
         OICFree(cborData);
         OCRepPayloadDestroy(payload);
         OCPayloadDestroy(cparsed);
index 5f2403e..c4db98c 100644 (file)
@@ -25,6 +25,8 @@
 #include <string>
 #include <map>
 
+static char gLongHostAddress[] = "111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111:5000";
+
 namespace OCResourceTest
 {
     using namespace OC;
@@ -81,6 +83,16 @@ namespace OCResourceTest
         EXPECT_ANY_THROW(ConstructResourceObject("coap://192.168.1.2", "/resource"));
     }
 
+    TEST(ConstructResourceTest, ConstructResourceObjectWithoutPortNumber2)
+    {
+        EXPECT_ANY_THROW(ConstructResourceObject("coap://192.168.1.2:", "/resource"));
+    }
+
+    TEST(ConstructResourceTest, ConstructResourceObjectWithLongHostAddress)
+    {
+        EXPECT_ANY_THROW(ConstructResourceObject(gLongHostAddress, "/resource"));
+    }
+
     TEST(ConstructResourceTest, ConstructResourceObjectInvalidHost)
     {
         EXPECT_ANY_THROW(ConstructResourceObject("192.168.1.2:5000", "/resource"));
index 65b0921..bb02198 100644 (file)
@@ -92,4 +92,4 @@ svr_db_build_dir = os.path.join(env.get('BUILD_DIR'), 'resource/unittests/')
 unittests_env.Alias("install",
                     unittests_env.Install(svr_db_build_dir,
                                           os.path.join(svr_db_src_dir,
-                                                       'oic_svr_db_client.json')))
+                                                       'oic_svr_db_client.dat')))
index 4e34cc2..832cc76 100644 (file)
@@ -227,7 +227,7 @@ need restrictly follow it.
 
 ==== The content of a typical script ====
 
-After run the scripts in build_common (usally it's done at the beginning of
+After run the scripts in build_common (usually it's done at the beginning of
 SConstruct), an global environment 'env' is exported, 'env' has include the
 default configuration of the target OS and arch. 'env' is used in all projects,
 should avoid to change its keys. To avoid change 'env', usually clone 'env' and
@@ -235,13 +235,13 @@ update it accroding to the requirement of current sub project. Then specify the
 target(usually binary) to build.
 
 Below is an example:
-       # import the global enviroment 'env'
+       # import the global environment 'env'
        Import('env')
 
-       # Clone a new enviroment from 'env'
+       # Clone a new environment from 'env'
        new_env = env.Clone()
 
-       # Update the new enviroment, usally include add header file paths,
+       # Update the new environment, usually include add header file paths,
        # library path, libs to link and other compiler flags. This part is
        # optional.
        new_env.AppeneUnique(xxx = [ .... ])
old mode 100644 (file)
new mode 100755 (executable)
index b8dc0eb..da5062e
@@ -26,7 +26,7 @@ Import('env')
 
 target_os = env.get('TARGET_OS')
 
-if target_os not in ['arduino','darwin']:
+if target_os not in ['arduino','darwin', 'ios']:
     # Build things manager project
     SConscript('things-manager/SConscript')
 
@@ -39,15 +39,19 @@ if target_os not in ['arduino','darwin']:
     # Build resource-container project
     SConscript('resource-container/SConscript')
 
+    # Build scene-manager project
+    if target_os in ['linux']:
+        SConscript('scene-manager/SConscript')
+
     # Build simulator module
     if target_os in ['linux'] and env.get('SIMULATOR', False):
-        SConscript('simulator/SConscript')     
-    
+        SConscript('simulator/SConscript')
+
     # Build resource directory project
     if env.get('WITH_RD') == '1':
         SConscript('resource-directory/SConscript')
 
 # Build EasySetup module
-if target_os in ['arduino','android', 'linux']:
+if target_os in ['arduino', 'android', 'linux','tizen']:
     SConscript('easy-setup/SConscript')
 
old mode 100755 (executable)
new mode 100644 (file)
index 3f761ef..80bfd14
@@ -1,6 +1,6 @@
 #******************************************************************
 #
-# Copyright 2015 Samsung Electronics All Rights Reserved.
+# Copyright 2016 Samsung Electronics All Rights Reserved.
 #
 #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 #
@@ -43,19 +43,26 @@ Steps to build and deploy Easysetup Mediator in Android platform
         export ANDROID_NDK=<ANDROID_NDK>
 
     a) In the IoTivity root source folder execute
-         scons TARGET_OS=android TARGET_ARCH=armeabi TARGET_TRANSPORT=IP RELEASE=0
+         scons TARGET_OS=android TARGET_ARCH=armeabi TARGET_TRANSPORT=IP ES_ROLE=mediator ES_TARGET_ENROLLEE={Platform} RELEASE=0
+                Note : {Platform} can be -> arduino , linux, tizen
 
     b) If the project is setup correctly, you should see a BUILD SUCCESSFUL message on the terminal
         You should see the .aar files generated inside of '<iotivity>/android/android_api/base/build/outputs/aar' directory. The .aar files contain jni directory and also a .jar file
 
     c) Now navigate to the Easysetup NDK folder
-        <iotivity-root>/service/easy-setup/sdk/mediator/android
+        <iotivity-root>/service/easy-setup/mediator/richsdk/android
 
     d) Execute NDK-Build with the following command to cross compiled Easysetup JNI .so files
        <iotivity>/extlibs/android/ndk/android-ndk-r10d/ndk-build
 
     e) Step (d) will generate cross compiled Easysetup JNI .so files in the following folder
-       <iotivity>/service/easy-setup/sdk/mediator/android/libs/armeabi
+       <iotivity>/service/easy-setup/mediator/richsdk/android/libs/armeabi
+
+NOTE: If you are going to use the SECURITY feature :
+
+      (a) please remove the "oic_svr_db_client.dat" file from the application (EasySetup/app/src/main/assets/)
+
+      (b) Copy the same file in the same folder from : <iotivity>/resource/csdk/security/provisioning/sample/oic_svr_db_client.dat
 
 2) Compilation using Android Studio
 
@@ -63,8 +70,8 @@ Steps to build and deploy Easysetup Mediator in Android platform
         Install Android Studio and use the Android SDK manager to update the Android API to 21
 
     a) Import following projects to the Studio using the "File->New->Import Project"
-        - service\easy-setup\sdk\android\EasySetupCore
-        - service\easy-setup\sampleapp\android\EasySetup
+        - service/easy-setup/mediator/richsdk/android/EasySetupCore
+        - service/easy-setup/sampleapp/android/EasySetup
 
     b) EasySetupCore is dependent on the .aar files generated in 1.b
         1) To add an .aar file to the 'EasySetupCore' project,
@@ -76,11 +83,12 @@ Steps to build and deploy Easysetup Mediator in Android platform
     c)    Build EasySetupCore project using "Android Studio->Build->Make Module "easySetupCore"
         If the project is setup correctly, you should see a BUILD SUCCESSFUL in the Android Studio Gradle Build terminal
             You should see the .aar file generated inside of
-            'iotivity\service\easy-setup\sdk\mediator\android\easySetupCore\build\outputs\aar'
+            'iotivity/service/easy-setup/mediator/richsdk/android/easySetupCore/build/outputs/aar'
 
     d) EasySetup application is also dependent on the .so files generated in 1.d step
-        1) Drag and drop the following .so files in to the EasySetup\app\src\main\jniLibs\armeabi folder
-            - libeasysetup-jni.so [Easy Setup file]
+        1) Drag and drop the following .so files in to the EasySetup/app/src/main/jniLibs/armeabi folder
+            - libeasysetup-jni.so [Easy Setup JNI library]
+                       - libESMediatorRich.so [Easy Setup Mediator library]
 
     e) EasySetup is also dependent on the .aar files generated in 1.b and 2.c steps
         1) To add an .aar file to the 'EasySetup' project,
@@ -111,11 +119,11 @@ Steps to build and deploy Easysetup Mediator in Arduino platform
         NOTE: 1) BOARD=arduino_due_x_dbg|arduino_due_x. Default is arduino_due_x_dbg.
               2) For Mega board, please use the following options. BOARD=mega & TARGET_ARCH=avr
 
-       Possible values for <transport> are:
+       Possible values for <transport> are: [Only ip is currently supported]
         -> IP :
-        $ scons service TARGET_OS=arduino BOARD=arduino_due_x_dbg TARGET_ARCH=arm SHIELD=WIFI RELEASE=0
+        $ scons service TARGET_OS=arduino BOARD=arduino_due_x_dbg TARGET_ARCH=arm SHIELD=WIFI ES_ROLE=enrollee RELEASE=0
         -> BLE :
-        $ scons service TARGET_OS=arduino BOARD=arduino_due_x_dbg TARGET_ARCH=arm SHIELD=BLE RELEASE=0
+        $ scons service TARGET_OS=arduino BOARD=arduino_due_x_dbg TARGET_ARCH=arm SHIELD=BLE RELEASE=0 [Currently not supporting]
 
         Note :- Only single transport can be built at a time for Arduino
     f) The above command will build sample. The "enrollee.hex" can be found at "out/arduino/arm/release/service/easy-setup/sampleapp/enrollee/arduino"
@@ -132,22 +140,38 @@ Steps to build and deploy Easysetup Mediator in Arduino platform
 
 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 Folder structure:
-++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++        
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 
 iotivity/
 â””── service
     â””── easy-setup/
         â”‚── SConscript
-        â”‚── sdk
+        â”‚── enrollee
         â”‚    â””── inc
         â”‚    â””── src
-        â”‚    â””── android
-        â”‚    â””── arduino
-        â”‚        â””──wifi
-        â”‚            â””──inc
-        â”‚            â””──src
+        â”‚    â””── arduino/wifi
+        â”‚    â””── linux/wifi
+        â”‚    â””── tizen/wifi
+        â”‚    â””── SConscript
+        â”‚
+        â”‚── mediator
+        â”‚    â””── csdk
+        â”‚        â””──inc
+        â”‚        â””──src
+        â”‚        â””──SConscript
+        â”‚    â””── richsdk
+        â”‚        â””──android
+        â”‚        â””──inc
+        â”‚        â””──src
+        â”‚        â””──SConscript
+        â”‚    â””── SConscript
+        â”‚
         â”‚── sampleapp
         â”‚    â””──mediator/android
         â”‚    â””──mediator/linux
         â”‚    â””──enrollee/arduino
+        â”‚    â””──enrollee/linux
+        â”‚    â””──enrollee/tizen
+        â”‚    â””──enrollee/tizen-sdb
+        â”‚
         â””── Build_Instructions_Android_Arduino.txt - You are reading this.
old mode 100644 (file)
new mode 100755 (executable)
index 4b4446a..3028c08
@@ -1,6 +1,6 @@
 #******************************************************************
 #
-# Copyright 2015 Samsung Electronics All Rights Reserved.
+# Copyright 2016 Samsung Electronics All Rights Reserved.
 #
 #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 #
 #
 #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-##
-# easy-setup project build script
-##
-
-import os
-
-Import('env')
-
-transport = env.get('TARGET_TRANSPORT')
-
-env.AppendUnique(CPPDEFINES = ['EASY_SETUP_CA_INIT'])
-
-easy_setup_env = env.Clone()
-#
-target_os = env.get('TARGET_OS')
-
-lib_env = env.Clone()
-if target_os == 'android':
-       SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', exports = 'lib_env')
-
 ######################################################################
-# Build flags
-######################################################################
-easy_setup_env.AppendUnique(CPPPATH = ['sdk/inc', 'sdk/src', 'sdk/common'])
-
-if target_os not in ['windows', 'winrt']:
-    easy_setup_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
-    if target_os not in ['android', 'arduino']:
-        easy_setup_env.AppendUnique(CXXFLAGS = ['-pthread'])
-
-if target_os in ['android', 'linux']:
-       easy_setup_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-       easy_setup_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
-       easy_setup_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
-       if target_os not in ['linux', 'arduino']:
-               easy_setup_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'gnustl_shared'])      
-               if not env.get('RELEASE'):
-                       easy_setup_env.AppendUnique(LIBS = ['log'])
-       else:
-               easy_setup_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'pthread', 'connectivity_abstraction'])
-if target_os == 'arduino':
-       easy_setup_env.AppendUnique(CPPPATH = [
-                              '../../resource/oc_logger/include',
-                              '../../resource/csdk/logger/include',
-                              '../../resource/csdk/stack/include',
-                              '../../extlibs/cjson',
-                                  'sdk/enrollee/arduino/wifi',
-                                  'sdk/enrollee/api',
-                                  'sdk/enrollee/src',
-                              'sdk/enrollee/inc'])
-       easy_setup_env.AppendUnique(CPPDEFINES = ['TB_LOG', 'ESWIFI'])
-if target_os in ['android','linux']:                                      
-       easy_setup_env.PrependUnique(CPPPATH = [
-               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',
-        env.get('SRC_DIR') + '/resource/csdk/logger/include',
-               env.get('SRC_DIR') + '/resource/csdk/security/include',
-               env.get('SRC_DIR') + '/extlibs/cjson',
-               'sdk/common',
-               'sdk/mediator/inc'])
-
-######################################################################
-# Source files and Targets
+# easy-setup project build script
 ######################################################################
+Import('env')
 
-if target_os == 'arduino':
-       es_sdk_static = easy_setup_env.StaticLibrary('ESSDKLibrary',
-                                       ['sdk/enrollee/src/easysetup.cpp',
-                                       'sdk/enrollee/src/resourceHandler.cpp',
-                                       'sdk/enrollee/arduino/wifi/networkHandler.cpp'])
-       easy_setup_env.InstallTarget(es_sdk_static, 'libESSDK')
-
-if target_os == 'android':
-       es_sdk_shared = easy_setup_env.StaticLibrary('libESSDK',
-                                       ['sdk/mediator/src/prov_adapter.cpp',
-                                       'sdk/mediator/src/wifi_provisioning.cpp',
-                                        'sdk/mediator/src/provisioning.cpp'])
-       easy_setup_env.InstallTarget(es_sdk_shared, 'libESSDK')
+es_target = env.get ('TARGET_OS')
+es_role = env.get('ES_ROLE')
+es_target_enrollee = env.get('ES_TARGET_ENROLLEE')
 
-if target_os == 'linux':
-       es_sdk_shared = easy_setup_env.SharedLibrary('ESSDKLibrary',
-                                       ['sdk/mediator/src/prov_adapter.cpp',
-                                       'sdk/mediator/src/wifi_provisioning.cpp',
-                                        'sdk/mediator/src/provisioning.cpp'])
-       easy_setup_env.InstallTarget(es_sdk_shared, 'libESSDK')
+print "************************************************************************************"
+print "Easysetup device role --> %s " % es_role
+print "Target Platform --> %s " % es_target
+print "Target Enrollee platform --> %s " % es_target_enrollee
+print "************************************************************************************"
 
 #Go to build sample apps
-SConscript('sampleapp/SConscript')
+if ('mediator' in es_role) :
+       print "Building Easysetup mediator SDKs [CSDK & RichSDK]"
+
+       if es_target in ['linux','android']:
+               SConscript('mediator/SConscript')
+       else :
+               print "****************************Mediator supports Linux and Android platform****************************"
 
+if ('enrollee' in es_role) :
+       print "Building Easysetup enrollee SDK"
 
+       if es_target in ['linux', 'arduino', 'tizen']:
+               SConscript('enrollee/SConscript')
+       else :
+               print "****************************Enrollee supports linux, tizen and arduino platform****************************"
\ No newline at end of file
diff --git a/service/easy-setup/enrollee/SConscript b/service/easy-setup/enrollee/SConscript
new file mode 100644 (file)
index 0000000..f129242
--- /dev/null
@@ -0,0 +1,156 @@
+#######################################################################
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+######################################################################
+# Easy-setup Enrollee SDK build script
+######################################################################
+Import('env')
+
+enrollee_env = env.Clone()
+
+target_os = enrollee_env.get('TARGET_OS')
+
+if enrollee_env.get('RELEASE'):
+    enrollee_env.AppendUnique(CCFLAGS = ['-Os'])
+    enrollee_env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+else:
+    enrollee_env.AppendUnique(CCFLAGS = ['-g'])
+
+if enrollee_env.get('LOGGING'):
+    enrollee_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+# Enrollees are implemented for IP transport only.
+if 'IP' in enrollee_env.get('TARGET_TRANSPORT'):
+       print "Enrollees are implemented for IP transport only"
+       enrollee_env.AppendUnique(CPPDEFINES = ['ESWIFI'])
+
+if enrollee_env.get('ES_SOFTAP_MODE') == 'ENROLLEE_SOFTAP':
+       enrollee_env.AppendUnique(CPPDEFINES = ['ENROLLEE_SOFTAP'])
+
+######################################################################
+# Build flags
+######################################################################
+enrollee_env.PrependUnique(CPPPATH = [
+               enrollee_env.get('SRC_DIR') + '/resource/c_common/oic_malloc/include',
+               enrollee_env.get('SRC_DIR') + '/resource/include',
+               enrollee_env.get('SRC_DIR') + '/resource/csdk/logger/include',
+               enrollee_env.get('SRC_DIR') + '/resource/oc_logger/include',
+       enrollee_env.get('SRC_DIR') + '/resource/csdk/stack/include',
+        enrollee_env.get('SRC_DIR') + '/resource/csdk/logger/include',
+               enrollee_env.get('SRC_DIR') + '/resource/csdk/security/include',
+               enrollee_env.get('SRC_DIR') + '/extlibs/cjson',
+               enrollee_env.get('SRC_DIR') + '/extlibs/sqlite3',
+               enrollee_env.get('SRC_DIR') + '/service/easy-setup/inc',
+               enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/linux/wifi',
+               enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/inc',
+               enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/src',
+               enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/arduino'])
+
+if enrollee_env.get('SECURED') == '1':
+       enrollee_env.AppendUnique(CPPPATH = [
+               enrollee_env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include',
+               enrollee_env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include/internal',
+               enrollee_env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include/oxm'])
+
+if target_os not in ['windows', 'winrt']:
+       enrollee_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x'])
+
+######################################################################
+# Linux Enrollee
+######################################################################
+if target_os == 'linux':
+       enrollee_env.PrependUnique(CPPPATH = [
+               enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/linux/wifi'])
+
+       enrollee_env.AppendUnique(LIBS = ['pthread', 'dl'])
+       enrollee_env.AppendUnique(LIBPATH = [enrollee_env.get('BUILD_DIR')])
+       enrollee_env.AppendUnique(RPATH = [enrollee_env.get('BUILD_DIR')])
+       enrollee_env.AppendUnique(CXXFLAGS = ['-pthread'])
+       enrollee_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'pthread', 'connectivity_abstraction'])
+       if enrollee_env.get('SECURED') == '1':
+               enrollee_env.PrependUnique(LIBS = ['ocprovision', 'ocpmapi'])
+
+######################################################################
+# Tizen Enrollee
+######################################################################
+if target_os == 'tizen':
+       enrollee_env.AppendUnique(LIBPATH = [enrollee_env.get('BUILD_DIR')])
+       enrollee_env.AppendUnique(RPATH = [enrollee_env.get('BUILD_DIR')])
+       enrollee_env.AppendUnique(CXXFLAGS = ['-pthread'])
+       enrollee_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'pthread', 'connectivity_abstraction'])
+       enrollee_env.AppendUnique(CPPPATH = [
+                              enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/tizen/wifi'])
+
+######################################################################
+# Arduino Enrollee
+######################################################################
+if target_os == 'arduino':
+       enrollee_env.AppendUnique(LIBPATH = [enrollee_env.get('BUILD_DIR')])
+       enrollee_env.AppendUnique(RPATH = [enrollee_env.get('BUILD_DIR')])
+       enrollee_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'pthread', 'connectivity_abstraction'])
+       enrollee_env.AppendUnique(CPPPATH = [
+                      enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/arduino/wifi'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+es_enrollee_src = None
+
+if target_os == 'linux':
+       es_enrollee_common_src =        [enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/src/easysetup.c',
+               enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/src/onboarding.c',
+               enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/src/resourcehandler.c',
+               enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/src/softap.c',
+               enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/linux/wifi/softapnative.c',
+               enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/linux/wifi/networkhandler.c']
+
+       enrollee_env.AppendUnique(es_enrollee_src = es_enrollee_common_src)
+
+       enrollee_sdk_shared = enrollee_env.SharedLibrary('ESEnrolleeSDK', enrollee_env.get('es_enrollee_src'))
+       enrollee_env.InstallTarget(enrollee_sdk_shared, 'libESEnrollee')
+
+if target_os == 'tizen':
+       enrollee_sdk_shared = enrollee_env.SharedLibrary('ESEnrolleeSDK', [
+               enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/src/easysetup.c',
+               enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/src/onboarding.c',
+               enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/src/softap.c',
+               enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/src/resourcehandler.c',
+               enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/tizen/wifi/networkhandler.c',
+               enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/tizen/wifi/softapnative.c'])
+       enrollee_env.InstallTarget(enrollee_sdk_shared, 'libESEnrolleeSDK')
+       enrollee_env.UserInstallTargetLib(enrollee_sdk_shared, 'libESEnrolleeSDK')
+
+if target_os == 'arduino':
+       es_sdk_static = enrollee_env.StaticLibrary('ESEnrolleeSDK', [
+               enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/arduino/easysetup.cpp',
+               enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/arduino/onboarding.cpp',
+               enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/arduino/softap.cpp',
+               enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/arduino/resourcehandler.cpp',
+               enrollee_env.get('SRC_DIR') + '/service/easy-setup/enrollee/arduino/wifi/networkhandler.cpp'])
+       enrollee_env.InstallTarget(es_sdk_static, 'libESEnrolleeSDK')
+
+#Go to build sample apps
+if target_os == 'arduino':
+       SConscript('../sampleapp/enrollee/arduino/SConscript')
+
+if target_os == 'linux':
+       SConscript('../sampleapp/enrollee/linux/SConscript')
+       #Build UnitTestcases for Enrollee
+       SConscript('../enrollee/unittests/SConscript')
+
diff --git a/service/easy-setup/enrollee/arduino/easysetup.cpp b/service/easy-setup/enrollee/arduino/easysetup.cpp
new file mode 100644 (file)
index 0000000..b3f0aff
--- /dev/null
@@ -0,0 +1,207 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/**
+ * @file
+ *
+ * This file contains the implementation for EasySetup Enrollee device
+ */
+
+#include "easysetup.h"
+#include "softap.h"
+#include "onboarding.h"
+#include "logger.h"
+#include "resourcehandler.h"
+
+/**
+ * @var ES_ENROLLEE_TAG
+ * @brief Logging tag for module name.
+ */
+#define ES_ENROLLEE_TAG "ES"
+
+//-----------------------------------------------------------------------------
+// Private variables
+//-----------------------------------------------------------------------------
+
+/**
+ * @var gTargetSsid
+ * @brief Target SSID of the Soft Access point to which the device has to connect
+ */
+static char gTargetSsid[MAXSSIDLEN];
+
+/**
+ * @var gTargetPass
+ * @brief Password of the target access point to which the device has to connect
+ */
+static char gTargetPass[MAXNETCREDLEN];
+
+/**
+ * @var gEnrolleeStatusCb
+ * @brief Fucntion pointer holding the callback for intimation of EasySetup Enrollee status callback
+ */
+static ESEnrolleeEventCallback gEnrolleeStatusCb = NULL;
+
+/**
+ * @var gIsSecured
+ * @brief Variable to check if secure mode is enabled or not.
+ */
+static bool gIsSecured = false;
+
+//-----------------------------------------------------------------------------
+// Private internal function prototypes
+//-----------------------------------------------------------------------------
+void ESOnboardingCallback(ESResult esResult);
+void ESProvisioningCallback(ESResult esResult);
+void ESOnboardingCallbackTargetNet(ESResult esResult);
+static bool ESEnrolleeValidateParam(OCConnectivityType networkType, const char *ssid,
+                                                const char *passwd, ESEnrolleeEventCallback cb);
+
+
+void ESOnboardingCallback(ESResult esResult)
+{
+        OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "ESOnboardingCallback with  result = %d", esResult);
+        if(esResult == ES_OK)
+        {
+            gEnrolleeStatusCb(esResult, ES_ON_BOARDED_STATE);
+        }
+        else
+        {
+            OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG,
+                        "Onboarding is failed callback result is = %d", esResult);
+            gEnrolleeStatusCb(esResult, ES_INIT_STATE);
+        }
+}
+
+void ESProvisioningCallback(ESResult esResult)
+{
+    OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "ESProvisioningCallback with  result = %d", esResult);
+
+    if (esResult == ES_RECVTRIGGEROFPROVRES)
+    {
+        GetTargetNetworkInfoFromProvResource(gTargetSsid, gTargetPass);
+        gEnrolleeStatusCb(ES_OK, ES_PROVISIONED_STATE);
+        OIC_LOG(DEBUG, ES_ENROLLEE_TAG, "Connecting with target network");
+
+        // Connecting/onboarding to target network
+        ConnectToWiFiNetwork(gTargetSsid, gTargetPass, ESOnboardingCallbackTargetNet);
+    }
+    else
+    {
+       OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "Provisioning is failed callback result is = %d", esResult);
+       // Resetting Enrollee to ONBOARDED_STATE as Enrollee is alreday onboarded in previous step
+       gEnrolleeStatusCb(ES_OK, ES_ON_BOARDED_STATE);
+    }
+}
+
+void ESOnboardingCallbackTargetNet(ESResult esResult)
+{
+    OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "ESOnboardingCallback on target network with result = %d",
+                                                                                        esResult);
+    if(esResult == ES_OK)
+    {
+        gEnrolleeStatusCb(esResult, ES_ON_BOARDED_TARGET_NETWORK_STATE);
+    }
+    else
+    {
+        OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG,
+                    "Onboarding is failed on target network and callback result is = %d", esResult);
+        // Resetting Enrollee state to the ES_PROVISIONED_STATE
+        // as device is already being provisioned with target network creds.
+        gEnrolleeStatusCb(esResult, ES_PROVISIONED_STATE);
+    }
+}
+
+ESResult ESInitEnrollee(OCConnectivityType networkType, const char *ssid, const char *passwd,
+        bool isSecured,
+        ESEnrolleeEventCallback cb)
+{
+    OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitEnrollee IN");
+    if(!ESEnrolleeValidateParam(networkType,ssid,passwd,cb))
+    {
+        OIC_LOG(ERROR, ES_ENROLLEE_TAG,
+                            "ESInitEnrollee::Stopping Easy setup due to invalid parameters");
+        return ES_ERROR;
+    }
+
+    //Init callback
+    gEnrolleeStatusCb = cb;
+
+    gIsSecured = isSecured;
+
+    // TODO : This onboarding state has to be set by lower layer, as they better
+    // knows when actually on-boarding started.
+    cb(ES_ERROR,ES_ON_BOARDING_STATE);
+
+    OIC_LOG(INFO, ES_ENROLLEE_TAG, "received callback");
+    OIC_LOG(INFO, ES_ENROLLEE_TAG, "onboarding now..");
+
+    if(!ESOnboard(ssid, passwd, ESOnboardingCallback))
+    {
+        OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESInitEnrollee::On-boarding failed");
+        cb(ES_ERROR, ES_INIT_STATE);
+        return ES_ERROR;
+    }
+
+    OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitEnrollee OUT");
+    return ES_OK;
+}
+
+ESResult ESTerminateEnrollee()
+{
+    UnRegisterResourceEventCallBack();
+
+    //Delete Prov resource
+    if (DeleteProvisioningResource() != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, ES_ENROLLEE_TAG, "Deleting prov resource error!!");
+        return ES_ERROR;
+    }
+
+    OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESTerminateEnrollee success");
+    return ES_OK;
+}
+
+ESResult ESInitProvisioning()
+{
+    OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitProvisioning <<IN>>");
+
+    if (CreateProvisioningResource(gIsSecured) != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, ES_ENROLLEE_TAG, "CreateProvisioningResource error");
+        return ES_ERROR;
+    }
+
+    RegisterResourceEventCallBack(ESProvisioningCallback);
+
+    OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitProvisioning <<OUT>>");
+    return ES_RESOURCECREATED;
+}
+
+static bool ESEnrolleeValidateParam(OCConnectivityType /*networkType*/, const char *ssid,
+                                                const char *passwd, ESEnrolleeEventCallback cb)
+{
+    if (!ssid || !passwd || !cb)
+    {
+        OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESEnrolleeValidateParam - Invalid parameters");
+        return false;
+    }
+    return true;
+}
+
diff --git a/service/easy-setup/enrollee/arduino/onboarding.cpp b/service/easy-setup/enrollee/arduino/onboarding.cpp
new file mode 100644 (file)
index 0000000..aaf1509
--- /dev/null
@@ -0,0 +1,86 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/**
+ * @file
+ *
+ * This file has methods for on-boarding the Enrollee device.
+ * This will contain template methods that will have core business logic & negotiation algorithm
+ * on various on-boarding methods.
+ */
+
+#include "easysetup.h"
+#include "softap.h"
+#include "onboarding.h"
+
+#include "logger.h"
+#include "resourcehandler.h"
+
+/**
+ * @var ES_ENROLLEE_TAG
+ * @brief Logging tag for module name.
+ */
+#define ES_ENROLLEE_TAG "ES_SOFTAP"
+
+/**
+ * It will return true on-boarding type is soft AP
+ */
+bool ESSoftapOnboarding()
+{
+    // TODO: To be changed based on user config. Current version, hardcoded to SoftAp onboarding
+    return true;
+}
+
+/**
+ * It will return true on-boarding type is BLE
+ */
+bool ESBleOnboarding()
+{
+    //BLE onboarding is not supported with current version.
+    return false;
+}
+
+/**
+ * It will do onboarding based on the user's configuration.
+ */
+bool ESOnboard(const char * ssid, const char* passwd, ESEnrolleeNetworkEventCallback cb)
+{
+    OIC_LOG(DEBUG, ES_ENROLLEE_TAG, "ESOnboard IN");
+
+    if (ESSoftapOnboarding())
+    {
+        OIC_LOG(DEBUG, ES_ENROLLEE_TAG, "Connecting to Mediator SoftAp");
+        ConnectToWiFiNetwork(ssid, passwd, cb);
+        return true;
+    }
+    else if (ESBleOnboarding())
+    {
+        OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESOnboard::Ble onboarding is not supported");
+        // TODO:
+        return false;
+    }
+    else
+    {
+        // TODO:
+        OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESOnboard::Invalid onboarding option");
+        return false;
+    }
+}
+
diff --git a/service/easy-setup/enrollee/arduino/resourcehandler.cpp b/service/easy-setup/enrollee/arduino/resourcehandler.cpp
new file mode 100644 (file)
index 0000000..6168606
--- /dev/null
@@ -0,0 +1,396 @@
+//******************************************************************
+//
+// 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 "resourcehandler.h"
+
+#include <stdio.h>
+
+#include "ocpayload.h"
+#include "oic_string.h"
+
+/**
+ * @var ES_RH_TAG
+ * @brief Logging tag for module name.
+ */
+#define ES_RH_TAG "ES_RH"
+//-----------------------------------------------------------------------------
+// Private variables
+//-----------------------------------------------------------------------------
+
+/**
+ * @var gProvResource
+ * @brief Structure for holding the Provisioning status and target information required to
+ * connect to the target network
+ */
+static ProvResource gProvResource;
+
+/**
+ * @var gNetResource
+ * @brief Structure forr holding the Provisioning status of network information
+ */
+static NetResource gNetResource;
+
+//-----------------------------------------------------------------------------
+// Private internal function prototypes
+//-----------------------------------------------------------------------------
+OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest *ehRequest,
+        void *callback);
+const char *getResult(OCStackResult result);
+OCEntityHandlerResult ProcessGetRequest(OCEntityHandlerRequest *ehRequest, OCRepPayload** payload);
+OCEntityHandlerResult ProcessPutRequest(OCEntityHandlerRequest *ehRequest, OCRepPayload** payload);
+OCEntityHandlerResult ProcessPostRequest(OCEntityHandlerRequest *ehRequest, OCRepPayload** payload);
+OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest);
+
+ESEnrolleeResourceEventCallback gNetworkInfoProvEventCb = NULL;
+
+void RegisterResourceEventCallBack(ESEnrolleeResourceEventCallback cb)
+{
+    gNetworkInfoProvEventCb = cb;
+}
+
+void UnRegisterResourceEventCallBack()
+{
+    if (gNetworkInfoProvEventCb)
+    {
+        gNetworkInfoProvEventCb = NULL;
+    }
+}
+
+void GetTargetNetworkInfoFromProvResource(char *name, char *pass)
+{
+    if (name != NULL && pass != NULL)
+    {
+        OICStrcpy(name, MAXSSIDLEN, gProvResource.tnn);
+        OICStrcpy(pass, MAXNETCREDLEN, gProvResource.cd);
+    }
+}
+
+OCStackResult CreateProvisioningResource(bool isSecured)
+{
+    gProvResource.ps = ES_PS_NEED_PROVISIONING;
+    gProvResource.tr = ES_PS_TRIGGER_INIT_VALUE;
+
+    gProvResource.tnt = CT_ADAPTER_IP;
+    OICStrcpy(gProvResource.tnn, sizeof(gProvResource.tnn), "Unknown");
+    OICStrcpy(gProvResource.cd, sizeof(gProvResource.cd), "Unknown");
+
+    OCStackResult res = OC_STACK_ERROR;
+    if (isSecured)
+    {
+        res = OCCreateResource(&gProvResource.handle, OC_RSRVD_ES_PROV_RES_TYPE,
+        OC_RSRVD_INTERFACE_DEFAULT,
+        OC_RSRVD_ES_URI_PROV, OCEntityHandlerCb,
+        NULL, OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE);
+    }
+    else
+    {
+        res = OCCreateResource(&gProvResource.handle, OC_RSRVD_ES_PROV_RES_TYPE,
+        OC_RSRVD_INTERFACE_DEFAULT,
+        OC_RSRVD_ES_URI_PROV, OCEntityHandlerCb,
+        NULL, OC_DISCOVERABLE | OC_OBSERVABLE);
+    }
+
+    OIC_LOG_V(INFO, ES_RH_TAG, "Created Prov resource with result: %s", getResult(res));
+    return res;
+}
+
+OCStackResult DeleteProvisioningResource()
+{
+    OCStackResult res = OCDeleteResource(gProvResource.handle);
+    if (res != OC_STACK_OK)
+    {
+        OIC_LOG_V(INFO, ES_RH_TAG, "Deleting Prov resource error with result: %s", getResult(res));
+    }
+
+    return res;
+}
+
+OCEntityHandlerResult ProcessGetRequest(OCEntityHandlerRequest *ehRequest, OCRepPayload **payload)
+{
+    OCEntityHandlerResult ehResult = OC_EH_ERROR;
+    if (!ehRequest)
+    {
+        OIC_LOG(ERROR, ES_RH_TAG, "Request is Null");
+        return ehResult;
+    }
+    if (ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
+    {
+        OIC_LOG(ERROR, ES_RH_TAG, "Incoming payload not a representation");
+        return ehResult;
+    }
+
+    OCRepPayload *getResp = constructResponse(ehRequest);
+    if (!getResp)
+    {
+        OIC_LOG(ERROR, ES_RH_TAG, "constructResponse failed");
+        return OC_EH_ERROR;
+    }
+
+    *payload = getResp;
+    ehResult = OC_EH_OK;
+
+    return ehResult;
+}
+
+OCEntityHandlerResult ProcessPostRequest(OCEntityHandlerRequest *ehRequest, OCRepPayload** payload)
+{
+    OIC_LOG(INFO, ES_RH_TAG, "ProcessPostRequest enter");
+    OCEntityHandlerResult ehResult = OC_EH_ERROR;
+    if (ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
+    {
+        OIC_LOG(ERROR, ES_RH_TAG, "Incoming payload not a representation");
+        return ehResult;
+    }
+
+    OCRepPayload* input = (OCRepPayload*) (ehRequest->payload);
+    if (!input)
+    {
+        OIC_LOG(ERROR, ES_RH_TAG, "Failed to parse");
+        return ehResult;
+    }
+
+    int64_t tr;
+    if (OCRepPayloadGetPropInt(input, OC_RSRVD_ES_TR, &tr))
+    {
+        // Triggering
+        gProvResource.tr = tr;
+    }
+
+    //ES_PS_PROVISIONING_COMPLETED state indicates that already provisioning is completed.
+    // A new request for provisioning means overriding existing network provisioning information.
+    if (gProvResource.ps == ES_PS_PROVISIONING_COMPLETED && tr == ES_PS_TRIGGER_CONNECTION)
+    {
+        OIC_LOG(DEBUG, ES_RH_TAG, "Provisioning already completed."
+                "Tiggering the network connection");
+
+        if (gNetworkInfoProvEventCb)
+        {
+            gNetworkInfoProvEventCb(ES_RECVTRIGGEROFPROVRES);
+            ehResult = OC_EH_OK;
+        }
+        else
+        {
+            OIC_LOG(ERROR, ES_RH_TAG, "gNetworkInfoProvEventCb is NULL."
+                    "Network handler not registered. Failed to connect to the network");
+            ehResult = OC_EH_ERROR;
+        }
+
+        return ehResult;
+    }
+    else if (gProvResource.ps == ES_PS_PROVISIONING_COMPLETED)
+    {
+        OIC_LOG(DEBUG, ES_RH_TAG, "Provisioning already completed. "
+                "This a request to override the existing the network provisioning information");
+    }
+    else
+    {
+        OIC_LOG(DEBUG, ES_RH_TAG, "Provisioning the network information to the Enrollee.");
+    }
+
+    OICStrcpy(gProvResource.tnn, sizeof(gProvResource.tnn), "");
+    OICStrcpy(gProvResource.cd, sizeof(gProvResource.cd), "");
+
+    char* tnn;
+    if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_TNN, &tnn))
+    {
+        OICStrcpy(gProvResource.tnn, sizeof(gProvResource.tnn), tnn);
+        OIC_LOG(INFO, ES_RH_TAG, "got ssid");
+    }
+
+    OIC_LOG_V(INFO, ES_RH_TAG, "gProvResource.tnn %s", gProvResource.tnn);
+
+    char* cd;
+    if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_CD, &cd))
+    {
+        OICStrcpy(gProvResource.cd, sizeof(gProvResource.cd), cd);
+        OIC_LOG(INFO, ES_RH_TAG, "got password");
+    }OIC_LOG_V(INFO, ES_RH_TAG, "gProvResource.cd %s", gProvResource.cd);
+
+    gProvResource.ps = ES_PS_PROVISIONING_COMPLETED;
+
+    OIC_LOG_V(INFO, ES_RH_TAG, "gProvResource.ps %lld", gProvResource.ps);
+
+    OCRepPayload *getResp = constructResponse(ehRequest);
+    if (!getResp)
+    {
+        OIC_LOG(ERROR, ES_RH_TAG, "constructResponse failed");
+        return OC_EH_ERROR;
+    }
+
+    *payload = getResp;
+    ehResult = OC_EH_OK;
+
+    return ehResult;
+}
+
+OCEntityHandlerResult ProcessPutRequest(OCEntityHandlerRequest * /*ehRequest*/,
+        OCRepPayload** /*payload*/)
+{
+    OCEntityHandlerResult ehResult = OC_EH_ERROR;
+
+    return ehResult;
+}
+
+OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest)
+{
+    OCRepPayload* payload = OCRepPayloadCreate();
+    if (!payload)
+    {
+        OIC_LOG(ERROR, ES_RH_TAG, "Failed to allocate Payload");
+        return NULL;
+    }
+
+    if (ehRequest->resource == gProvResource.handle)
+    {
+        OIC_LOG(INFO, ES_RH_TAG, "constructResponse prov res");
+        OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_PROV);
+        OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_PS, gProvResource.ps);
+        OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_TNT, gProvResource.tnt);
+    }
+    else if (ehRequest->requestHandle == gNetResource.handle)
+    {
+
+        OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_NET);
+        OCRepPayloadSetPropInt(payload, "ant", gNetResource.ant[0]);
+    }
+    return payload;
+}
+
+/**
+ * This is the entity handler for the registered resource.
+ * This is invoked by OCStack whenever it recevies a request for this resource.
+ */
+OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag,
+        OCEntityHandlerRequest* entityHandlerRequest, void *callback)
+{
+    (void) callback;
+    OCEntityHandlerResult ehRet = OC_EH_OK;
+    OCEntityHandlerResponse response =
+    { 0, 0, OC_EH_ERROR, 0, 0,
+    { },
+    { 0 }, false };
+    OCRepPayload* payload = NULL;
+
+    if (entityHandlerRequest && (flag & OC_REQUEST_FLAG))
+    {
+        if (OC_REST_GET == entityHandlerRequest->method)
+        {
+            OIC_LOG(INFO, ES_RH_TAG, "Received GET request");
+            ehRet = ProcessGetRequest(entityHandlerRequest, &payload);
+        }
+        else if (OC_REST_PUT == entityHandlerRequest->method)
+        {
+            OIC_LOG(INFO, ES_RH_TAG, "Received PUT request");
+
+            //PUT request will be handled in the internal implementation
+            if (gProvResource.handle != NULL
+                    && entityHandlerRequest->resource == gProvResource.handle)
+            {
+                ehRet = ProcessPutRequest(entityHandlerRequest, &payload);
+            }
+            else
+            {
+                OIC_LOG(ERROR, ES_RH_TAG, "Cannot process put");
+                ehRet = OC_EH_ERROR;
+            }
+        }
+        else if (OC_REST_POST == entityHandlerRequest->method)
+        {
+            OIC_LOG(INFO, ES_RH_TAG, "Received OC_REST_POST from client");
+            if (gProvResource.handle != NULL
+                    && entityHandlerRequest->resource == gProvResource.handle)
+            {
+                ehRet = ProcessPostRequest(entityHandlerRequest, &payload);
+            }
+            else
+            {
+                OIC_LOG(ERROR, ES_RH_TAG, "Cannot process put");
+                ehRet = OC_EH_ERROR;
+            }
+        }
+
+        if (ehRet == OC_EH_OK)
+        {
+            // Format the response.  Note this requires some info about the request
+            response.requestHandle = entityHandlerRequest->requestHandle;
+            response.resourceHandle = entityHandlerRequest->resource;
+            response.ehResult = ehRet;
+            //response uses OCPaylod while all get,put methodes use OCRepPayload
+            response.payload = (OCPayload*) (payload);
+            response.numSendVendorSpecificHeaderOptions = 0;
+            memset(response.sendVendorSpecificHeaderOptions, 0,
+                    sizeof(response.sendVendorSpecificHeaderOptions));
+            memset(response.resourceUri, 0, sizeof(response.resourceUri));
+            // Indicate that response is NOT in a persistent buffer
+            response.persistentBufferFlag = 0;
+
+            // Send the response
+            if (OCDoResponse(&response) != OC_STACK_OK)
+            {
+                OIC_LOG(ERROR, ES_RH_TAG, "Error sending response");
+                ehRet = OC_EH_ERROR;
+            }
+        }
+    }
+
+    return ehRet;
+}
+
+const char *getResult(OCStackResult result)
+{
+    switch (result)
+    {
+        case OC_STACK_OK:
+            return "OC_STACK_OK";
+        case OC_STACK_INVALID_URI:
+            return "OC_STACK_INVALID_URI";
+        case OC_STACK_INVALID_QUERY:
+            return "OC_STACK_INVALID_QUERY";
+        case OC_STACK_INVALID_IP:
+            return "OC_STACK_INVALID_IP";
+        case OC_STACK_INVALID_PORT:
+            return "OC_STACK_INVALID_PORT";
+        case OC_STACK_INVALID_CALLBACK:
+            return "OC_STACK_INVALID_CALLBACK";
+        case OC_STACK_INVALID_METHOD:
+            return "OC_STACK_INVALID_METHOD";
+        case OC_STACK_NO_MEMORY:
+            return "OC_STACK_NO_MEMORY";
+        case OC_STACK_COMM_ERROR:
+            return "OC_STACK_COMM_ERROR";
+        case OC_STACK_INVALID_PARAM:
+            return "OC_STACK_INVALID_PARAM";
+        case OC_STACK_NOTIMPL:
+            return "OC_STACK_NOTIMPL";
+        case OC_STACK_NO_RESOURCE:
+            return "OC_STACK_NO_RESOURCE";
+        case OC_STACK_RESOURCE_ERROR:
+            return "OC_STACK_RESOURCE_ERROR";
+        case OC_STACK_SLOW_RESOURCE:
+            return "OC_STACK_SLOW_RESOURCE";
+        case OC_STACK_NO_OBSERVERS:
+            return "OC_STACK_NO_OBSERVERS";
+        case OC_STACK_ERROR:
+            return "OC_STACK_ERROR";
+        default:
+            return "UNKNOWN";
+    }
+}
+
diff --git a/service/easy-setup/enrollee/arduino/softap.cpp b/service/easy-setup/enrollee/arduino/softap.cpp
new file mode 100644 (file)
index 0000000..4199e9a
--- /dev/null
@@ -0,0 +1,89 @@
+//      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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/**
+ * These are adapter APIs will make caller modules agnostic to platform.
+ */
+
+#include "softapnative.h"
+#include "easysetup.h"
+#include "softap.h"
+#include "networkhandler.h"
+
+void ESCreateSoftapCallback(int result, const char *ip, const char* mac_addr,
+                                                            const char* device_name );
+
+ESEnrolleeNetworkEventCallback gCallback;
+
+/**
+ * It will return Device which is creating Soft AP.
+ * i.e.Enrollee or Mediator.
+ * This decesion is based on, what is the value set for ES_SOFTAP_MODE in build command as well as 
+ * in iotivity.spec file.
+ */
+DeviceRole ESSoftapHost()
+{
+#ifdef ENROLLEE_SOFTAP
+    //SoftAp at enrollee
+    return ENROLLEE;
+#else
+    //SoftAp at mediator
+    return MEDIATOR;
+#endif
+}
+
+/**
+ * It will return true if the Soft AP is created at Enrollee device
+ */
+bool ESSoftapAtEnrollee()
+{
+    return ( ESSoftapHost() == ENROLLEE) ? true : false;
+}
+
+/**
+ * It will return true if the Soft AP is created at Mediator device
+ */
+bool ESSoftapAtMediator()
+{
+    return (ESSoftapHost() == MEDIATOR) ? true : false;
+}
+
+/**
+ * This API will map result returned from the native to the caller.
+ * Callback API's signature needs to be modified under build switch according
+ * to the underline platform.
+ */
+void ESCreateSoftapCallback(int result, const char *ip, const char* mac_addr,
+                                                                const char* device_name)
+{
+    if(SOFTAP_SUCCESS ==  result) //on Success
+    {
+        gCallback(ES_OK);
+    }
+    else //on Failure
+    {
+        gCallback(ES_ERROR);
+    }
+}
+
+/**
+ * This API will create the softap at enrollee
+ */
+void ESCreateSoftap(const char * ssid, const char* passwd, ESEnrolleeNetworkEventCallback cb)
+{
+    gCallback = cb;
+
+    // TODO: To be implemented
+    // Create Soft AP through native APIs -- start
+    // native API call by and pass ESCreateSoftapCallback() as callback
+    ESCreateSoftapNative(ssid, passwd,ESCreateSoftapCallback);
+    // Create Soft AP through native APIs -- end
+}
+
diff --git a/service/easy-setup/enrollee/arduino/wifi/networkhandler.cpp b/service/easy-setup/enrollee/arduino/wifi/networkhandler.cpp
new file mode 100644 (file)
index 0000000..fae1fd5
--- /dev/null
@@ -0,0 +1,249 @@
+//******************************************************************
+//
+// 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 "networkhandler.h"
+
+// Arduino WiFi Shield includes
+#include <SPI.h>
+#include <WiFi.h>
+#include <WiFiUdp.h>
+
+#include <string.h>
+
+#include "logger.h"
+
+/**
+ * @var ES_NH_TAG
+ * @brief Logging tag for module name.
+ */
+#define ES_NH_TAG "ES_NH"
+
+//-----------------------------------------------------------------------------
+// Defines
+//-----------------------------------------------------------------------------
+/**
+ *  ES_MAX_NETWORK_RETRY sets the default number of retry count for network connection.
+ */
+#define ES_MAX_NETWORK_RETRY (5)
+
+//-----------------------------------------------------------------------------
+// Private variables
+//-----------------------------------------------------------------------------
+static IPAddress enrolleeIP;
+
+/**
+ * @var g_retryCounter
+ * @brief Retry counter for cancelling network retry. Currently network retry is
+ *          limited to 5 attempts
+ */
+static uint16_t g_retryCounter = 0;
+
+
+
+//-----------------------------------------------------------------------------
+// Private internal function prototypes
+//-----------------------------------------------------------------------------
+int findNetwork(const char *ssid);
+int ConnectToNetwork(const char *ssid, const char *pass);
+void printEncryptionType(int thisType);
+
+// Arduino WiFi Shield
+// Note : Arduino WiFi Shield currently does NOT support multicast and therefore
+// this server will NOT be listening on 224.0.1.187 multicast address.
+static const char ARDUINO_WIFI_SHIELD_UDP_FW_VER[] = "1.1.0";
+
+ESResult ConnectToWiFiNetwork(const char *ssid, const char *pass,
+                                                            ESEnrolleeNetworkEventCallback cb)
+{
+    char *fwVersion;
+    int status = WL_IDLE_STATUS;
+    int res;
+
+    // check for the presence of the shield:
+    if (WiFi.status() == WL_NO_SHIELD)
+    {
+        OIC_LOG(ERROR, ES_NH_TAG, "WiFi shield not present");
+        return ES_ERROR;
+    }
+
+    // Verify that WiFi Shield is running the firmware with all UDP fixes
+    fwVersion = WiFi.firmwareVersion();
+    OIC_LOG_V(INFO, ES_NH_TAG, "WiFi Shield Firmware version %s", fwVersion);
+    if (strncmp(fwVersion, ARDUINO_WIFI_SHIELD_UDP_FW_VER, sizeof(ARDUINO_WIFI_SHIELD_UDP_FW_VER))
+            != 0)
+    {
+        OIC_LOG(DEBUG, ES_NH_TAG, "!!!!! Upgrade WiFi Shield Firmware version !!!!!!");
+        return ES_ERROR;
+    }
+
+    //Retry counter is reset everytime the ConnectToWiFiNetwork is invoked
+    g_retryCounter = 0;
+
+    OIC_LOG_V(INFO, ES_NH_TAG, "Finding SSID: %s", ssid);
+
+    while ((findNetwork(ssid) == 0) && g_retryCounter < ES_MAX_NETWORK_RETRY) // found
+    {
+        delay(1000);
+        g_retryCounter++;
+    }
+
+    if(g_retryCounter == ES_MAX_NETWORK_RETRY){
+        OIC_LOG_V(ERROR, ES_NH_TAG, "Connection to network failed after %d attempts",
+                  g_retryCounter);
+        return ES_ERROR;
+    }
+
+    if (cb != NULL)
+    {
+        cb(ES_OK);
+    }
+
+    if (WiFi.status() == WL_CONNECTED)
+        WiFi.disconnect();
+
+    //Retry counter is reset everytime the ConnectToWiFiNetwork is invoked
+    g_retryCounter = 0;
+
+    res = ConnectToNetwork(ssid, pass);
+
+    if (res == 0)
+    {
+        return ES_NETWORKCONNECTED;
+    }
+    else
+    {
+        return ES_NETWORKNOTCONNECTED;
+    }
+}
+
+int findNetwork(const char *ssid)
+{
+    int res = 0;
+    // scan for nearby networks:
+    Serial.println("** Scan Networks **");
+    int numSsid = WiFi.scanNetworks();
+    if (numSsid == -1)
+    {
+        Serial.println("Couldn't get a wifi connection");
+
+        return res;
+    }
+
+    // print the list of networks seen:
+    Serial.print("number of available networks:");
+    Serial.println(numSsid);
+
+    // print the network number and name for each network found:
+    for (int thisNet = 0; thisNet < numSsid; thisNet++)
+    {
+        Serial.print(thisNet);
+        Serial.print(") ");
+        Serial.print(WiFi.SSID(thisNet));
+        Serial.print("\tEncryption: ");
+        printEncryptionType(WiFi.encryptionType(thisNet));
+
+        if (strcmp(WiFi.SSID(thisNet), ssid) == 0)
+        {
+            res = 1;
+        }
+    }
+
+    return res;
+}
+
+int ConnectToNetwork(const char *ssid, const char *pass)
+{
+    int status = WL_IDLE_STATUS;
+
+    // attempt to connect to Wifi network:
+    while (status != WL_CONNECTED && g_retryCounter < ES_MAX_NETWORK_RETRY)
+    {
+        OIC_LOG_V(INFO, ES_NH_TAG, "Attempting to connect to SSID: %s", ssid);
+
+        status = WiFi.begin((char *) ssid, (char *) pass);
+
+        // wait 10 seconds for connection:
+        delay(10000);
+
+        g_retryCounter++;
+    }
+
+    if(g_retryCounter == ES_MAX_NETWORK_RETRY){
+        OIC_LOG_V(ERROR, ES_NH_TAG, "Connection to network failed after %d attempts",
+                  g_retryCounter);
+        return ES_ERROR;
+    }
+
+    OIC_LOG(DEBUG, ES_NH_TAG, "Connected to wifi");
+
+    enrolleeIP = WiFi.localIP();
+    OIC_LOG_V(INFO, ES_NH_TAG, "IP Address:  %d.%d.%d.%d", enrolleeIP[0], enrolleeIP[1],
+                                                           enrolleeIP[2], enrolleeIP[3]);
+
+    char buf[50];
+    sprintf(buf, "IP Address:  %d.%d.%d.%d", enrolleeIP[0], enrolleeIP[1],
+                                             enrolleeIP[2], enrolleeIP[3]);
+    Serial.println(buf);
+
+    return 0;
+}
+
+ESResult getCurrentNetworkInfo(OCConnectivityType targetType, NetworkInfo *info)
+{
+    if (targetType == CT_ADAPTER_IP && WiFi.status() == WL_CONNECTED)
+    {
+        info->type = CT_ADAPTER_IP;
+        info->ipaddr = WiFi.localIP();
+        if((sizeof(info->ssid) >= MAXSSIDLEN) && (strlen(WiFi.SSID()) <= MAXSSIDLEN))
+        {
+            strcpy(info->ssid, WiFi.SSID());
+            return ES_OK;
+        }
+        else
+        {
+            return ES_ERROR;
+        }
+    }
+
+    return ES_ERROR;
+}
+
+void printEncryptionType(int thisType)
+{
+    // read the encryption type and print out the name:
+    switch (thisType)
+    {
+        case ENC_TYPE_WEP:
+            Serial.println("WEP");
+            break;
+        case ENC_TYPE_TKIP:
+            Serial.println("WPA");
+            break;
+        case ENC_TYPE_CCMP:
+            Serial.println("WPA2");
+            break;
+        case ENC_TYPE_NONE:
+            Serial.println("None");
+            break;
+        case ENC_TYPE_AUTO:
+            Serial.println("Auto");
+            break;
+    }
+}
diff --git a/service/easy-setup/enrollee/arduino/wifi/networkhandler.h b/service/easy-setup/enrollee/arduino/wifi/networkhandler.h
new file mode 100644 (file)
index 0000000..f1503e1
--- /dev/null
@@ -0,0 +1,68 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/**
+ * @file
+ *
+ * This file contains IP network handling functionality for Enrollee device
+ */
+
+#ifndef ES_NETWORK_HANDLER_H_
+#define ES_NETWORK_HANDLER_H_
+
+// Do not remove the include below
+#include "Arduino.h"
+
+// Arduino WiFi Shield includes
+#include <SPI.h>
+#include <WiFi.h>
+#include <WiFiUdp.h>
+
+#include <string.h>
+#include "logger.h"
+#include "escommon.h"
+
+#define MAXSSIDLEN 33
+#define MAXNETCREDLEN 20
+#define MAXNUMTYPE 5
+#define MAXADDRLEN 15
+
+/*
+ * Callback function for updating the Network status to the subscribers
+ *
+ * @param esResult ESResult provides the current state of the network connection status
+ */
+typedef void (*ESEnrolleeNetworkEventCallback)(ESResult esResult);
+
+typedef struct
+{
+    OCConnectivityType type;
+    // for WiFI
+    IPAddress ipaddr;
+    char ssid[MAXSSIDLEN];
+    // for BT, BLE
+    byte mac[6];
+} NetworkInfo;
+
+ESResult ConnectToWiFiNetwork(const char *ssid, const char *pass,
+                                                            ESEnrolleeNetworkEventCallback);
+ESResult getCurrentNetworkInfo(OCConnectivityType targetType, NetworkInfo *info);
+
+#endif
diff --git a/service/easy-setup/enrollee/inc/easysetup.h b/service/easy-setup/enrollee/inc/easysetup.h
new file mode 100755 (executable)
index 0000000..00102a9
--- /dev/null
@@ -0,0 +1,81 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+
+#ifndef EASYSETUP_ENROLLEE_H__
+#define EASYSETUP_ENROLLEE_H__
+
+#include "escommon.h"
+
+/**
+ * @file
+ *
+ * This file contains Enrollee APIs
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+/*
+ * Callback function for updating the Enrollee OnBoarding and Provisioning status result
+ * to the application
+ *
+ * @param esResult ESResult provides the current state of the Enrollee Device
+ */
+typedef void (*ESEnrolleeEventCallback)(ESResult esResult, ESEnrolleeState enrolleeState);
+
+/**
+ * This function Initializes the EasySetup. This API must be called prior to invoking any other API
+ *
+ * @param networkType       NetworkType on which OnBoarding has to be performed.
+ * @param ssid              SSID of the target SoftAP network to which the Enrollee is connecting.
+ * @param passwd            Password of the target SoftAP network to which the Enrollee is
+ *                          connecting
+ * @param isSecured         True if the Enrollee is operating in secured mode.
+ * @param eventCallback     ESEnrolleeEventCallback for for updating the Enrollee OnBoarding status
+ *                          result to the application
+ * @return ::ES_OK on success, some other value upon failure.
+ */
+ESResult ESInitEnrollee(OCConnectivityType networkType, const char *ssid, const char *passwd,
+                                bool isSecured, ESEnrolleeEventCallback eventCallback);
+
+/**
+ * This function performs initialization of Provisioning and Network resources needed for EasySetup
+ * process.
+ * @return ::ES_OK on success, some other value upon failure.
+ */
+ESResult ESInitProvisioning();
+
+/**
+ * This function performs termination of Provisioning and Network resources.
+ * Also terminates the IoTivity core stack.
+ *
+ * @return ::ES_OK on success, some other value upon failure.
+ */
+ESResult ESTerminateEnrollee();
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+
+#endif /* EASYSETUP_ENROLLEE_H__ */
+
diff --git a/service/easy-setup/enrollee/linux/wifi/networkhandler.c b/service/easy-setup/enrollee/linux/wifi/networkhandler.c
new file mode 100644 (file)
index 0000000..24b7dea
--- /dev/null
@@ -0,0 +1,80 @@
+/******************************************************************
+ *
+ * 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 "networkhandler.h"
+
+#include <unistd.h>
+
+#include "logger.h"
+#include "easysetup.h"
+#include "oic_string.h"
+
+#define LOG_TAG "LINUX ES"
+
+const char *gSsid = "DLNA_LISMORE1";
+const char *gPass = "dlna@010203";
+char *gIpAddress;
+ESEnrolleeNetworkEventCallback gNetworkEventCb;
+
+/*
+ * All the functions defined in this file are stub functions to be implemented by the end user of
+ * Easysetup Enrollee applications.
+ */
+static void ESActivateWifi()
+{
+
+}
+
+static void start()
+{
+    OIC_LOG(INFO, LOG_TAG, "START");
+    ESActivateWifi();
+}
+
+void ConnectToWiFiNetwork(const char *ssid, const char *pass,
+                                                        ESEnrolleeNetworkEventCallback cb)
+{
+    OIC_LOG_V(INFO, LOG_TAG, "ConnectToWiFiNetwork %s %s",ssid,pass);
+    gPass = pass;
+    gSsid = ssid;
+    gNetworkEventCb = cb;
+    start();
+}
+
+ESResult getCurrentNetworkInfo(OCConnectivityType targetType, NetworkInfo *info)
+{
+    if (targetType == CT_ADAPTER_IP)
+    {
+        info->type = CT_ADAPTER_IP;
+        info->ipaddr = gIpAddress;
+        if (strlen(gSsid) <= MAXSSIDLEN)
+        {
+            OICStrcpy(info->ssid, sizeof(info->ssid), gSsid);
+            return ES_OK;
+        }
+        else
+        {
+            return ES_ERROR;
+        }
+    }
+
+    return ES_ERROR;
+}
+
diff --git a/service/easy-setup/enrollee/linux/wifi/networkhandler.h b/service/easy-setup/enrollee/linux/wifi/networkhandler.h
new file mode 100644 (file)
index 0000000..b70be01
--- /dev/null
@@ -0,0 +1,63 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/**
+ * @file
+ *
+ * This file contains IP network handling functionality for Enrollee device
+ */
+
+#ifndef ES_NETWORK_HANDLER_H_
+#define ES_NETWORK_HANDLER_H_
+
+
+#include <string.h>
+#include "easysetup.h"
+#include "logger.h"
+#include "escommon.h"
+
+#define MAXSSIDLEN 33
+#define MAXNETCREDLEN 20
+#define MAXNUMTYPE 5
+#define MAXADDRLEN 15
+
+/*
+ * Callback function for updating the Network status to the subscribers
+ *
+ * @param esResult ESResult provides the current state of the network connection status
+ */
+typedef void (*ESEnrolleeNetworkEventCallback)(ESResult esResult);
+
+typedef struct
+{
+    OCConnectivityType type;
+    // for WiFI
+    //IPAddress ipaddr;
+    char *ipaddr;
+    char ssid[MAXSSIDLEN];
+    // for BT, BLE
+    //byte mac[6];
+} NetworkInfo;
+
+void ConnectToWiFiNetwork(const char *ssid, const char *pass,
+                                                            ESEnrolleeNetworkEventCallback);
+ESResult getCurrentNetworkInfo(OCConnectivityType targetType, NetworkInfo *info);
+
+#endif
diff --git a/service/easy-setup/enrollee/linux/wifi/softapnative.c b/service/easy-setup/enrollee/linux/wifi/softapnative.c
new file mode 100644 (file)
index 0000000..d6861a0
--- /dev/null
@@ -0,0 +1,38 @@
+//******************************************************************
+//
+// 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 "softapnative.h"
+
+/**
+ * This API will create the Soft AP at Enrollee device. 
+ */
+void ESCreateSoftapNative(const char * ssid, const char* passwd, SoftAPCallbackNative cb)
+{
+    const char *ip, *macaddr, *devicename;
+
+    // Soft is created successfully. This callback may be send from other cascaded callbacks
+    cb(SOFTAP_SUCCESS, ip, macaddr, devicename);
+
+    // TODO: Use below code to indicate failed on-boarding / softap creation
+    // Soft creation is failed. This callback may be send from other cascaded callbacks 
+    //cb(SOFTAP_FAILED, nullptr,nullptr,nullptr);
+}
+
diff --git a/service/easy-setup/enrollee/linux/wifi/softapnative.h b/service/easy-setup/enrollee/linux/wifi/softapnative.h
new file mode 100644 (file)
index 0000000..35c3773
--- /dev/null
@@ -0,0 +1,53 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/**
+ * @file
+ *
+ * This file contains the API declaration for creating & configuration for SoftAP 
+ */
+
+#ifndef EASYSETUP_ENROLLEE_SOFTAP_H__
+#define EASYSETUP_ENROLLEE_SOFTAP_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+
+#define SOFTAP_SUCCESS  1
+#define SOFTAP_FAILED   0
+
+
+//This callback signagure may get changed as per the native implementation.
+typedef void (*SoftAPCallbackNative)(int result, const char *ip, const char* mac_addr,
+                                                                        const char*device_name);
+
+void ESCreateSoftapNative(const char * ssid, const char* passwd, SoftAPCallbackNative cb);
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+
+#endif /* EASYSETUP_ENROLLEE_SOFTAP_H__ */
+
+
+
diff --git a/service/easy-setup/enrollee/src/easysetup.c b/service/easy-setup/enrollee/src/easysetup.c
new file mode 100644 (file)
index 0000000..cb6d260
--- /dev/null
@@ -0,0 +1,198 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/**
+ * @file
+ *
+ * This file contains the implementation for EasySetup Enrollee device
+ */
+
+#include "easysetup.h"
+#include "softap.h"
+#include "onboarding.h"
+#include "logger.h"
+#include "resourcehandler.h"
+#include "easysetupcallbacks.h"
+
+/**
+ * @var ES_ENROLLEE_TAG
+ * @brief Logging tag for module name.
+ */
+#define ES_ENROLLEE_TAG "ES"
+
+//-----------------------------------------------------------------------------
+// Private variables
+//-----------------------------------------------------------------------------
+
+/**
+ * @var gTargetSsid
+ * @brief Target SSID of the Soft Access point to which the device has to connect
+ */
+static char gTargetSsid[MAXSSIDLEN];
+
+/**
+ * @var gTargetPass
+ * @brief Password of the target access point to which the device has to connect
+ */
+static char gTargetPass[MAXNETCREDLEN];
+
+/**
+ * @var gEnrolleeStatusCb
+ * @brief Fucntion pointer holding the callback for intimation of EasySetup Enrollee status callback
+ */
+static ESEnrolleeEventCallback gEnrolleeStatusCb = NULL;
+
+/**
+ * @var gIsSecured
+ * @brief Variable to check if secure mode is enabled or not.
+ */
+static bool gIsSecured = false;
+
+void ESOnboardingCallback(ESResult esResult)
+{
+        OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "ESOnboardingCallback with  result = %d", esResult);
+        if(esResult == ES_OK)
+        {
+            gEnrolleeStatusCb(esResult, ES_ON_BOARDED_STATE);
+        }
+        else
+        {
+            OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG,
+                        "Onboarding is failed callback result is = %d", esResult);
+            gEnrolleeStatusCb(esResult, ES_INIT_STATE);
+        }
+}
+
+void ESProvisioningCallback(ESResult esResult)
+{
+    OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "ESProvisioningCallback with  result = %d", esResult);
+
+    if (esResult == ES_RECVTRIGGEROFPROVRES)
+    {
+        GetTargetNetworkInfoFromProvResource(gTargetSsid, gTargetPass);
+        gEnrolleeStatusCb(ES_OK, ES_PROVISIONED_STATE);
+        OIC_LOG(DEBUG, ES_ENROLLEE_TAG, "Connecting with target network");
+
+        // Connecting/onboarding to target network
+        ConnectToWiFiNetwork(gTargetSsid, gTargetPass, ESOnboardingCallbackTargetNet);
+    }
+    else
+    {
+       OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "Provisioning is failed callback result is = %d", esResult);
+       // Resetting Enrollee to ONBOARDED_STATE as Enrollee is alreday onboarded in previous step
+       gEnrolleeStatusCb(ES_OK, ES_ON_BOARDED_STATE);
+    }
+}
+
+void ESOnboardingCallbackTargetNet(ESResult esResult)
+{
+    OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "ESOnboardingCallback on target network with result = %d",
+                                                                                        esResult);
+    if(esResult == ES_OK)
+    {
+        gEnrolleeStatusCb(esResult, ES_ON_BOARDED_TARGET_NETWORK_STATE);
+    }
+    else
+    {
+        OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG,
+                    "Onboarding is failed on target network and callback result is = %d", esResult);
+        // Resetting Enrollee state to the ES_PROVISIONED_STATE
+        // as device is already being provisioned with target network creds.
+        gEnrolleeStatusCb(esResult, ES_PROVISIONED_STATE);
+    }
+}
+
+ESResult ESInitEnrollee(OCConnectivityType networkType, const char *ssid, const char *passwd,
+        bool isSecured,
+        ESEnrolleeEventCallback cb)
+{
+    OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitEnrollee IN");
+    if(!ESEnrolleeValidateParam(networkType,ssid,passwd,cb))
+    {
+        OIC_LOG(ERROR, ES_ENROLLEE_TAG,
+                            "ESInitEnrollee::Stopping Easy setup due to invalid parameters");
+        return ES_ERROR;
+    }
+
+    //Init callback
+    gEnrolleeStatusCb = cb;
+
+    gIsSecured = isSecured;
+
+    // TODO : This onboarding state has to be set by lower layer, as they better
+    // knows when actually on-boarding started.
+    cb(ES_ERROR,ES_ON_BOARDING_STATE);
+
+    OIC_LOG(INFO, ES_ENROLLEE_TAG, "received callback");
+    OIC_LOG(INFO, ES_ENROLLEE_TAG, "onboarding now..");
+
+    if(!ESOnboard(ssid, passwd, ESOnboardingCallback))
+    {
+        OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESInitEnrollee::On-boarding failed");
+        cb(ES_ERROR, ES_INIT_STATE);
+        return ES_ERROR;
+    }
+
+    OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitEnrollee OUT");
+    return ES_OK;
+}
+
+ESResult ESTerminateEnrollee()
+{
+    UnRegisterResourceEventCallBack();
+
+    //Delete Prov resource
+    if (DeleteProvisioningResource() != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, ES_ENROLLEE_TAG, "Deleting prov resource error!!");
+        return ES_ERROR;
+    }
+
+    OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESTerminateEnrollee success");
+    return ES_OK;
+}
+
+ESResult ESInitProvisioning()
+{
+    OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitProvisioning <<IN>>");
+
+    if (CreateProvisioningResource(gIsSecured) != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, ES_ENROLLEE_TAG, "CreateProvisioningResource error");
+        return ES_ERROR;
+    }
+
+    RegisterResourceEventCallBack(ESProvisioningCallback);
+
+    OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitProvisioning <<OUT>>");
+    return ES_RESOURCECREATED;
+}
+
+static bool ESEnrolleeValidateParam(OCConnectivityType networkType, const char *ssid,
+                                                const char *passwd, ESEnrolleeEventCallback cb)
+{
+    if (!ssid || !passwd || !cb)
+    {
+        OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESEnrolleeValidateParam - Invalid parameters");
+        return false;
+    }
+    return true;
+}
+
diff --git a/service/easy-setup/enrollee/src/easysetupcallbacks.h b/service/easy-setup/enrollee/src/easysetupcallbacks.h
new file mode 100644 (file)
index 0000000..f21c1e1
--- /dev/null
@@ -0,0 +1,69 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/**
+ * @file
+ *
+ * This file contains private internal callback function 
+ * prototypes for Easy setup [Enrollee]
+ */
+
+#ifndef EASYSETUP_ENROLLEE_CALLBACKS_H__
+#define EASYSETUP_ENROLLEE_CALLBACKS_H__
+
+#include "escommon.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+//-----------------------------------------------------------------------------
+// Private internal callback function prototypes for Easy setup [Enrollee]
+//-----------------------------------------------------------------------------
+
+ /*
+ * Callback for on boarding
+ */
+void ESOnboardingCallback(ESResult esResult);
+
+ /*
+ * Callback for provisioning
+ */
+void ESProvisioningCallback(ESResult SSSS);
+
+ /*
+ * Callback for on boarding target Network
+ */
+void ESOnboardingCallbackTargetNet(ESResult esResult);
+
+ /*
+ * Function for validating the parameter for ESInitEnrollee API
+ */
+static bool ESEnrolleeValidateParam(OCConnectivityType networkType, const char *ssid,
+                                                const char *passwd, ESEnrolleeEventCallback cb);
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+
+#endif /* EASYSETUP_ENROLLEE_CALLBACKS_H__ */
+
+
diff --git a/service/easy-setup/enrollee/src/onboarding.c b/service/easy-setup/enrollee/src/onboarding.c
new file mode 100644 (file)
index 0000000..da9acaa
--- /dev/null
@@ -0,0 +1,94 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/**
+ * @file
+ *
+ * This file has methods for on-boarding the Enrollee device.
+ * This will contain template methods that will have core business logic & negotiation algorithm
+ * on various on-boarding methods.
+ */
+
+#include "easysetup.h"
+#include "softap.h"
+#include "onboarding.h"
+
+#include "logger.h"
+#include "resourcehandler.h"
+
+/**
+ * @var ES_ENROLLEE_TAG
+ * @brief Logging tag for module name.
+ */
+#define ES_ENROLLEE_TAG "ES_SOFTAP"
+
+/**
+ * It will return true on-boarding type is soft AP
+ */
+bool ESSoftapOnboarding()
+{
+    // TODO: To be changed based on user config. Current version, hardcoded to SoftAp onboarding
+    return true;
+}
+
+/**
+ * It will return true on-boarding type is BLE
+ */
+bool ESBleOnboarding()
+{
+    //BLE onboarding is not supported with current version.
+    return false;
+}
+
+/**
+ * It will do onboarding based on the user's configuration.
+ */
+bool ESOnboard(const char * ssid, const char* passwd, ESEnrolleeNetworkEventCallback cb)
+{
+    OIC_LOG(DEBUG, ES_ENROLLEE_TAG, "ESOnboard IN");
+
+    if (ESSoftapOnboarding())
+    {
+        if (ESSoftapAtEnrollee())
+        {
+            OIC_LOG(DEBUG, ES_ENROLLEE_TAG, "Create SoftAp at enrollee");
+            ESCreateSoftap(ssid, passwd, cb);
+        }
+        else
+        {
+            OIC_LOG(DEBUG, ES_ENROLLEE_TAG, "Connecting to Mediator SoftAp");
+            ConnectToWiFiNetwork(ssid, passwd, cb);
+        }
+        return true;
+    }
+    else if (ESBleOnboarding())
+    {
+        OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESOnboard::Ble onboarding is not supported");
+        // TODO:
+        return false;
+    }
+    else
+    {
+        // TODO:
+        OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESOnboard::Invalid onboarding option");
+        return false;
+    }
+}
+
diff --git a/service/easy-setup/enrollee/src/onboarding.h b/service/easy-setup/enrollee/src/onboarding.h
new file mode 100644 (file)
index 0000000..dc0ecd6
--- /dev/null
@@ -0,0 +1,70 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+
+#ifndef EASYSETUP_ENROLLEE_ONBOARDING_H__
+#define EASYSETUP_ENROLLEE_ONBOARDING_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus:$
+
+#include "networkhandler.h"
+
+/**
+ * @file
+ *
+ * This file contains APIs to on-board ( connect ) Enrollee device into Ad-hoc network
+ * @Note :  Some of the APIs of this file need to be modified by the OEM according to the
+ *          device configuration
+ */
+
+/**
+ * This function on-board Enrollee device onto ad-hoc network.
+ * @param ssid                              SSID of the target SoftAP network to which the Enrollee
+ *                                          is connecting.
+ * @param passwd                            Password of the target SoftAP network to which the
+ *                                          Enrollee is connecting.
+ * @param ESEnrolleeNetworkEventCallback    Callback function for result update
+ * @return ::True, if on-boarding is successful.
+ */
+
+bool ESOnboard(const char * ssid, const char* passwd, ESEnrolleeNetworkEventCallback cb);
+
+/**
+ * This function verify if the on-boarding is through SoftAP.
+ * @return ::True, if Soft AP on-boarding enabled.
+ * @Note : This API to be modified by the OEM according to the device configuration
+ */
+bool ESSoftapOnboarding();
+
+/**
+ * This function verify if the on-boarding is through Ble beacons.
+ * @return ::True, if Ble beacons enabled.
+ * @Note : This API to be modified by the OEM according to the device configuration
+ */
+bool ESBleOnboarding();
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+
+#endif /* EASYSETUP_ENROLLEE_ONBOARDING_H__ */
diff --git a/service/easy-setup/enrollee/src/resourcehandler.c b/service/easy-setup/enrollee/src/resourcehandler.c
new file mode 100644 (file)
index 0000000..833e31e
--- /dev/null
@@ -0,0 +1,396 @@
+//******************************************************************
+//
+// 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 "resourcehandler.h"
+
+#include <stdio.h>
+
+#include "ocpayload.h"
+#include "oic_string.h"
+
+/**
+ * @var ES_RH_TAG
+ * @brief Logging tag for module name.
+ */
+#define ES_RH_TAG "ES_RH"
+//-----------------------------------------------------------------------------
+// Private variables
+//-----------------------------------------------------------------------------
+
+/**
+ * @var gProvResource
+ * @brief Structure for holding the Provisioning status and target information required to
+ * connect to the target network
+ */
+static ProvResource gProvResource;
+
+/**
+ * @var gNetResource
+ * @brief Structure forr holding the Provisioning status of network information
+ */
+static NetResource gNetResource;
+
+//-----------------------------------------------------------------------------
+// Private internal function prototypes
+//-----------------------------------------------------------------------------
+OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest *ehRequest,
+        void *callback);
+const char *getResult(OCStackResult result);
+OCEntityHandlerResult ProcessGetRequest(OCEntityHandlerRequest *ehRequest, OCRepPayload** payload);
+OCEntityHandlerResult ProcessPutRequest(OCEntityHandlerRequest *ehRequest, OCRepPayload** payload);
+OCEntityHandlerResult ProcessPostRequest(OCEntityHandlerRequest *ehRequest, OCRepPayload** payload);
+OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest);
+
+ESEnrolleeResourceEventCallback gNetworkInfoProvEventCb = NULL;
+
+void RegisterResourceEventCallBack(ESEnrolleeResourceEventCallback cb)
+{
+    gNetworkInfoProvEventCb = cb;
+}
+
+void UnRegisterResourceEventCallBack()
+{
+    if (gNetworkInfoProvEventCb)
+    {
+        gNetworkInfoProvEventCb = NULL;
+    }
+}
+
+void GetTargetNetworkInfoFromProvResource(char *name, char *pass)
+{
+    if (name != NULL && pass != NULL)
+    {
+        OICStrcpy(name, MAXSSIDLEN, gProvResource.tnn);
+        OICStrcpy(pass, MAXNETCREDLEN, gProvResource.cd);
+    }
+}
+
+OCStackResult CreateProvisioningResource(bool isSecured)
+{
+    gProvResource.ps = ES_PS_NEED_PROVISIONING;
+    gProvResource.tr = ES_PS_TRIGGER_INIT_VALUE;
+
+    gProvResource.tnt = CT_ADAPTER_IP;
+    OICStrcpy(gProvResource.tnn, sizeof(gProvResource.tnn), "Unknown");
+    OICStrcpy(gProvResource.cd, sizeof(gProvResource.cd), "Unknown");
+
+    OCStackResult res = OC_STACK_ERROR;
+    if (isSecured)
+    {
+        res = OCCreateResource(&gProvResource.handle, OC_RSRVD_ES_PROV_RES_TYPE,
+        OC_RSRVD_INTERFACE_DEFAULT,
+        OC_RSRVD_ES_URI_PROV, OCEntityHandlerCb,
+        NULL, OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE);
+    }
+    else
+    {
+        res = OCCreateResource(&gProvResource.handle, OC_RSRVD_ES_PROV_RES_TYPE,
+        OC_RSRVD_INTERFACE_DEFAULT,
+        OC_RSRVD_ES_URI_PROV, OCEntityHandlerCb,
+        NULL, OC_DISCOVERABLE | OC_OBSERVABLE);
+    }
+
+    OIC_LOG_V(INFO, ES_RH_TAG, "Created Prov resource with result: %s", getResult(res));
+    return res;
+}
+
+OCStackResult DeleteProvisioningResource()
+{
+    OCStackResult res = OCDeleteResource(gProvResource.handle);
+    if (res != OC_STACK_OK)
+    {
+        OIC_LOG_V(INFO, ES_RH_TAG, "Deleting Prov resource error with result: %s", getResult(res));
+    }
+
+    return res;
+}
+
+OCEntityHandlerResult ProcessGetRequest(OCEntityHandlerRequest *ehRequest, OCRepPayload **payload)
+{
+    OCEntityHandlerResult ehResult = OC_EH_ERROR;
+    if (!ehRequest)
+    {
+        OIC_LOG(ERROR, ES_RH_TAG, "Request is Null");
+        return ehResult;
+    }
+    if (ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
+    {
+        OIC_LOG(ERROR, ES_RH_TAG, "Incoming payload not a representation");
+        return ehResult;
+    }
+
+    OCRepPayload *getResp = constructResponse(ehRequest);
+    if (!getResp)
+    {
+        OIC_LOG(ERROR, ES_RH_TAG, "constructResponse failed");
+        return OC_EH_ERROR;
+    }
+
+    *payload = getResp;
+    ehResult = OC_EH_OK;
+
+    return ehResult;
+}
+
+OCEntityHandlerResult ProcessPostRequest(OCEntityHandlerRequest *ehRequest, OCRepPayload** payload)
+{
+    OIC_LOG(INFO, ES_RH_TAG, "ProcessPostRequest enter");
+    OCEntityHandlerResult ehResult = OC_EH_ERROR;
+    if (ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
+    {
+        OIC_LOG(ERROR, ES_RH_TAG, "Incoming payload not a representation");
+        return ehResult;
+    }
+
+    OCRepPayload* input = (OCRepPayload*) (ehRequest->payload);
+    if (!input)
+    {
+        OIC_LOG(ERROR, ES_RH_TAG, "Failed to parse");
+        return ehResult;
+    }
+
+    int64_t tr;
+    if (OCRepPayloadGetPropInt(input, OC_RSRVD_ES_TR, &tr))
+    {
+        // Triggering
+        gProvResource.tr = tr;
+    }
+
+    //ES_PS_PROVISIONING_COMPLETED state indicates that already provisioning is completed.
+    // A new request for provisioning means overriding existing network provisioning information.
+    if (gProvResource.ps == ES_PS_PROVISIONING_COMPLETED && tr == ES_PS_TRIGGER_CONNECTION)
+    {
+        OIC_LOG(DEBUG, ES_RH_TAG, "Provisioning already completed."
+                "Tiggering the network connection");
+
+        if (gNetworkInfoProvEventCb)
+        {
+            gNetworkInfoProvEventCb(ES_RECVTRIGGEROFPROVRES);
+            ehResult = OC_EH_OK;
+        }
+        else
+        {
+            OIC_LOG(ERROR, ES_RH_TAG, "gNetworkInfoProvEventCb is NULL."
+                    "Network handler not registered. Failed to connect to the network");
+            ehResult = OC_EH_ERROR;
+        }
+
+        return ehResult;
+    }
+    else if (gProvResource.ps == ES_PS_PROVISIONING_COMPLETED)
+    {
+        OIC_LOG(DEBUG, ES_RH_TAG, "Provisioning already completed. "
+                "This a request to override the existing the network provisioning information");
+    }
+    else
+    {
+        OIC_LOG(DEBUG, ES_RH_TAG, "Provisioning the network information to the Enrollee.");
+    }
+
+    OICStrcpy(gProvResource.tnn, sizeof(gProvResource.tnn), "");
+    OICStrcpy(gProvResource.cd, sizeof(gProvResource.cd), "");
+
+    char* tnn;
+    if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_TNN, &tnn))
+    {
+        OICStrcpy(gProvResource.tnn, sizeof(gProvResource.tnn), tnn);
+        OIC_LOG(INFO, ES_RH_TAG, "got ssid");
+    }
+
+    OIC_LOG_V(INFO, ES_RH_TAG, "gProvResource.tnn %s", gProvResource.tnn);
+
+    char* cd;
+    if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_CD, &cd))
+    {
+        OICStrcpy(gProvResource.cd, sizeof(gProvResource.cd), cd);
+        OIC_LOG(INFO, ES_RH_TAG, "got password");
+    }OIC_LOG_V(INFO, ES_RH_TAG, "gProvResource.cd %s", gProvResource.cd);
+
+    gProvResource.ps = ES_PS_PROVISIONING_COMPLETED;
+
+    OIC_LOG_V(INFO, ES_RH_TAG, "gProvResource.ps %lld", gProvResource.ps);
+
+    OCRepPayload *getResp = constructResponse(ehRequest);
+    if (!getResp)
+    {
+        OIC_LOG(ERROR, ES_RH_TAG, "constructResponse failed");
+        return OC_EH_ERROR;
+    }
+
+    *payload = getResp;
+    ehResult = OC_EH_OK;
+
+    return ehResult;
+}
+
+OCEntityHandlerResult ProcessPutRequest(OCEntityHandlerRequest * ehRequest,
+        OCRepPayload** payload)
+{
+    OCEntityHandlerResult ehResult = OC_EH_ERROR;
+
+    return ehResult;
+}
+
+OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest)
+{
+    OCRepPayload* payload = OCRepPayloadCreate();
+    if (!payload)
+    {
+        OIC_LOG(ERROR, ES_RH_TAG, "Failed to allocate Payload");
+        return NULL;
+    }
+
+    if (ehRequest->resource == gProvResource.handle)
+    {
+        OIC_LOG(INFO, ES_RH_TAG, "constructResponse prov res");
+        OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_PROV);
+        OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_PS, gProvResource.ps);
+        OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_TNT, gProvResource.tnt);
+    }
+    else if (ehRequest->requestHandle == gNetResource.handle)
+    {
+
+        OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_NET);
+        OCRepPayloadSetPropInt(payload, "ant", gNetResource.ant[0]);
+    }
+    return payload;
+}
+
+/**
+ * This is the entity handler for the registered resource.
+ * This is invoked by OCStack whenever it recevies a request for this resource.
+ */
+OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag,
+        OCEntityHandlerRequest* entityHandlerRequest, void *callback)
+{
+    (void) callback;
+    OCEntityHandlerResult ehRet = OC_EH_OK;
+    OCEntityHandlerResponse response =
+    { 0, 0, OC_EH_ERROR, 0, 0,
+    { },
+    { 0 }, false };
+    OCRepPayload* payload = NULL;
+
+    if (entityHandlerRequest && (flag & OC_REQUEST_FLAG))
+    {
+        if (OC_REST_GET == entityHandlerRequest->method)
+        {
+            OIC_LOG(INFO, ES_RH_TAG, "Received GET request");
+            ehRet = ProcessGetRequest(entityHandlerRequest, &payload);
+        }
+        else if (OC_REST_PUT == entityHandlerRequest->method)
+        {
+            OIC_LOG(INFO, ES_RH_TAG, "Received PUT request");
+
+            //PUT request will be handled in the internal implementation
+            if (gProvResource.handle != NULL
+                    && entityHandlerRequest->resource == gProvResource.handle)
+            {
+                ehRet = ProcessPutRequest(entityHandlerRequest, &payload);
+            }
+            else
+            {
+                OIC_LOG(ERROR, ES_RH_TAG, "Cannot process put");
+                ehRet = OC_EH_ERROR;
+            }
+        }
+        else if (OC_REST_POST == entityHandlerRequest->method)
+        {
+            OIC_LOG(INFO, ES_RH_TAG, "Received OC_REST_POST from client");
+            if (gProvResource.handle != NULL
+                    && entityHandlerRequest->resource == gProvResource.handle)
+            {
+                ehRet = ProcessPostRequest(entityHandlerRequest, &payload);
+            }
+            else
+            {
+                OIC_LOG(ERROR, ES_RH_TAG, "Cannot process put");
+                ehRet = OC_EH_ERROR;
+            }
+        }
+
+        if (ehRet == OC_EH_OK)
+        {
+            // Format the response.  Note this requires some info about the request
+            response.requestHandle = entityHandlerRequest->requestHandle;
+            response.resourceHandle = entityHandlerRequest->resource;
+            response.ehResult = ehRet;
+            //response uses OCPaylod while all get,put methodes use OCRepPayload
+            response.payload = (OCPayload*) (payload);
+            response.numSendVendorSpecificHeaderOptions = 0;
+            memset(response.sendVendorSpecificHeaderOptions, 0,
+                    sizeof(response.sendVendorSpecificHeaderOptions));
+            memset(response.resourceUri, 0, sizeof(response.resourceUri));
+            // Indicate that response is NOT in a persistent buffer
+            response.persistentBufferFlag = 0;
+
+            // Send the response
+            if (OCDoResponse(&response) != OC_STACK_OK)
+            {
+                OIC_LOG(ERROR, ES_RH_TAG, "Error sending response");
+                ehRet = OC_EH_ERROR;
+            }
+        }
+    }
+
+    return ehRet;
+}
+
+const char *getResult(OCStackResult result)
+{
+    switch (result)
+    {
+        case OC_STACK_OK:
+            return "OC_STACK_OK";
+        case OC_STACK_INVALID_URI:
+            return "OC_STACK_INVALID_URI";
+        case OC_STACK_INVALID_QUERY:
+            return "OC_STACK_INVALID_QUERY";
+        case OC_STACK_INVALID_IP:
+            return "OC_STACK_INVALID_IP";
+        case OC_STACK_INVALID_PORT:
+            return "OC_STACK_INVALID_PORT";
+        case OC_STACK_INVALID_CALLBACK:
+            return "OC_STACK_INVALID_CALLBACK";
+        case OC_STACK_INVALID_METHOD:
+            return "OC_STACK_INVALID_METHOD";
+        case OC_STACK_NO_MEMORY:
+            return "OC_STACK_NO_MEMORY";
+        case OC_STACK_COMM_ERROR:
+            return "OC_STACK_COMM_ERROR";
+        case OC_STACK_INVALID_PARAM:
+            return "OC_STACK_INVALID_PARAM";
+        case OC_STACK_NOTIMPL:
+            return "OC_STACK_NOTIMPL";
+        case OC_STACK_NO_RESOURCE:
+            return "OC_STACK_NO_RESOURCE";
+        case OC_STACK_RESOURCE_ERROR:
+            return "OC_STACK_RESOURCE_ERROR";
+        case OC_STACK_SLOW_RESOURCE:
+            return "OC_STACK_SLOW_RESOURCE";
+        case OC_STACK_NO_OBSERVERS:
+            return "OC_STACK_NO_OBSERVERS";
+        case OC_STACK_ERROR:
+            return "OC_STACK_ERROR";
+        default:
+            return "UNKNOWN";
+    }
+}
+
diff --git a/service/easy-setup/enrollee/src/resourcehandler.h b/service/easy-setup/enrollee/src/resourcehandler.h
new file mode 100644 (file)
index 0000000..ad470dc
--- /dev/null
@@ -0,0 +1,71 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+// Do not remove the include below
+
+#include <string.h>
+#include "logger.h"
+#include "ocstack.h"
+#include "escommon.h"
+#include "networkhandler.h"
+#include "octypes.h"
+
+#ifndef ES_RESOURCE_HANDLER_H_
+#define ES_RESOURCE_HANDLER_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef void (*ESEnrolleeResourceEventCallback)(ESResult);
+
+/* Structure to represent a Light resource */
+typedef struct PROVRESOURCE
+{
+    OCResourceHandle handle;
+    int64_t ps; // provisiong status, 1 : need to provisioning, 2 : Connected to Enroller.
+    int64_t tr; // Trigger network connection, 0 : Init value, 1 : Connected to the target network.
+    int64_t tnt; // target network type, 1: WLAN, 2: BT, 3: BLE, 4: Zigbee.
+    char tnn[MAXSSIDLEN]; // target network name, i.e. SSID for WLAN, MAC address for BT.
+    char cd[MAXNETCREDLEN]; // credential information.
+} ProvResource;
+
+/* Structure to represent a Light resource */
+typedef struct NETRESOURCE
+{
+    OCResourceHandle handle;
+    int64_t cnt; // current network type, 1: WLAN, 2: BT, 3: BLE, 4: Zigbee.
+    int64_t ant[MAXNUMTYPE]; // available network type, 1: WLAN, 2: BT, 3: BLE, 4: Zigbee.
+    char ipaddr[MAXADDRLEN]; // ip address.
+    char cnn[MAXSSIDLEN]; // current network name.
+} NetResource;
+
+OCStackResult CreateProvisioningResource(bool isSecured);
+OCStackResult DeleteProvisioningResource();
+
+void GetTargetNetworkInfoFromProvResource(char *, char *);
+void RegisterResourceEventCallBack(ESEnrolleeResourceEventCallback);
+void UnRegisterResourceEventCallBack(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //ES_RESOURCE_HANDLER_H_
\ No newline at end of file
diff --git a/service/easy-setup/enrollee/src/softap.c b/service/easy-setup/enrollee/src/softap.c
new file mode 100644 (file)
index 0000000..4199e9a
--- /dev/null
@@ -0,0 +1,89 @@
+//      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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/**
+ * These are adapter APIs will make caller modules agnostic to platform.
+ */
+
+#include "softapnative.h"
+#include "easysetup.h"
+#include "softap.h"
+#include "networkhandler.h"
+
+void ESCreateSoftapCallback(int result, const char *ip, const char* mac_addr,
+                                                            const char* device_name );
+
+ESEnrolleeNetworkEventCallback gCallback;
+
+/**
+ * It will return Device which is creating Soft AP.
+ * i.e.Enrollee or Mediator.
+ * This decesion is based on, what is the value set for ES_SOFTAP_MODE in build command as well as 
+ * in iotivity.spec file.
+ */
+DeviceRole ESSoftapHost()
+{
+#ifdef ENROLLEE_SOFTAP
+    //SoftAp at enrollee
+    return ENROLLEE;
+#else
+    //SoftAp at mediator
+    return MEDIATOR;
+#endif
+}
+
+/**
+ * It will return true if the Soft AP is created at Enrollee device
+ */
+bool ESSoftapAtEnrollee()
+{
+    return ( ESSoftapHost() == ENROLLEE) ? true : false;
+}
+
+/**
+ * It will return true if the Soft AP is created at Mediator device
+ */
+bool ESSoftapAtMediator()
+{
+    return (ESSoftapHost() == MEDIATOR) ? true : false;
+}
+
+/**
+ * This API will map result returned from the native to the caller.
+ * Callback API's signature needs to be modified under build switch according
+ * to the underline platform.
+ */
+void ESCreateSoftapCallback(int result, const char *ip, const char* mac_addr,
+                                                                const char* device_name)
+{
+    if(SOFTAP_SUCCESS ==  result) //on Success
+    {
+        gCallback(ES_OK);
+    }
+    else //on Failure
+    {
+        gCallback(ES_ERROR);
+    }
+}
+
+/**
+ * This API will create the softap at enrollee
+ */
+void ESCreateSoftap(const char * ssid, const char* passwd, ESEnrolleeNetworkEventCallback cb)
+{
+    gCallback = cb;
+
+    // TODO: To be implemented
+    // Create Soft AP through native APIs -- start
+    // native API call by and pass ESCreateSoftapCallback() as callback
+    ESCreateSoftapNative(ssid, passwd,ESCreateSoftapCallback);
+    // Create Soft AP through native APIs -- end
+}
+
diff --git a/service/easy-setup/enrollee/src/softap.h b/service/easy-setup/enrollee/src/softap.h
new file mode 100644 (file)
index 0000000..df532de
--- /dev/null
@@ -0,0 +1,85 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+
+#ifndef EASYSETUP_ENROLLEE_SOFTAP_H__
+#define EASYSETUP_ENROLLEE_SOFTAP_H__
+
+#include "escommon.h"
+#include "networkhandler.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @file
+ *
+ * This file contains platform agnostic API for creation of Soft AP
+ * @Note :  Some of the APIs of this file need to be modified by the OEM according to the device
+ *          configuration
+ */
+
+/**
+ * This function verify if the Soft AP is created at Enrollee device.
+ * @return ::True, if Soft AP is created at Enrollee device.
+ * @Note : This API needs to be modified by the OEM according to the device configuration
+ */
+
+bool ESSoftapAtEnrollee();
+
+/**
+ * This function verify if the Soft AP is created at Mediator device.
+ * @return ::True, if Soft AP is created at Mediator device.
+ * @Note : This API needs to be modified by the OEM according to the device configuration
+ */
+
+bool ESSoftapAtMediator();
+
+
+/**
+ * This function finds which Device (Enrollee or Mediator) is creating Soft AP.
+ * @return ::DeviceRole (ENROLLEE or MEDIATOR)
+ * @Note : This API needs to be modified by the OEM according to the device configuration
+ */
+
+DeviceRole ESSoftapHost();
+
+/**
+ * This function Initializes the EasySetup. This API must be called prior to invoking any other API
+ *
+ * @param ssid                  SSID of the target SoftAP network to which the Enrollee is
+ *                              connecting.
+ * @param passwd                Password of the target SoftAP network to which the Enrollee is
+ *                              connecting
+ * @param ESEnrolleeNetworkEventCallback Callback function for result update
+ * @return ::void.
+ */
+void ESCreateSoftap(const char * ssid, const char* passwd, ESEnrolleeNetworkEventCallback cb);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EASYSETUP_ENROLLEE_SOFTAP_H__ */
+
+
+
diff --git a/service/easy-setup/enrollee/tizen/wifi/networkhandler.c b/service/easy-setup/enrollee/tizen/wifi/networkhandler.c
new file mode 100644 (file)
index 0000000..ef83e92
--- /dev/null
@@ -0,0 +1,184 @@
+/******************************************************************
+ *
+ * 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 "networkhandler.h"
+
+#include <wifi.h>
+#include <unistd.h>
+
+#include "logger.h"
+#include "easysetup.h"
+#include "oic_string.h"
+
+#define LOG_TAG "TIZEN ES"
+
+const char *gSsid = "DLNA_LISMORE1";
+const char *gPass = "dlna@010203";
+char *gIpAddress = NULL;
+wifi_ap_h connectedWifi;
+ESEnrolleeNetworkEventCallback gNetworkEventCb;
+static void ESActivateWifi();
+
+static const char*
+print_state(wifi_connection_state_e state)
+{
+    switch (state)
+    {
+        case WIFI_CONNECTION_STATE_DISCONNECTED:
+            return "Disconnected";
+        case WIFI_CONNECTION_STATE_ASSOCIATION:
+            return "Association";
+        case WIFI_CONNECTION_STATE_CONNECTED:
+            return "Connected";
+        case WIFI_CONNECTION_STATE_CONFIGURATION:
+            return "Configuration";
+    }
+}
+
+void __wifi_connected_cb(wifi_error_e error_code, void *user_data)
+{
+    OIC_LOG(INFO,LOG_TAG,"#### __connected ");
+
+    if (gIpAddress)
+        free(gIpAddress);
+
+    wifi_ap_get_ip_address(connectedWifi, WIFI_ADDRESS_FAMILY_IPV4, &gIpAddress);
+    OIC_LOG_V(INFO,LOG_TAG,"#### __connected, Ipaddress=%s", gIpAddress);
+    gNetworkEventCb(ES_OK);
+
+}
+
+bool __wifi_found_ap_cb(wifi_ap_h ap, void *user_data)
+{
+    OIC_LOG(INFO,LOG_TAG,"#### __wifi_found_ap_cb received ");
+
+    int error_code = 0;
+    char *ap_name = NULL;
+    wifi_connection_state_e state;
+
+    error_code = wifi_ap_get_essid(ap, &ap_name);
+    if (error_code != WIFI_ERROR_NONE)
+    {
+        OIC_LOG(ERROR,LOG_TAG,"#### Fail to get AP name.");
+
+        return false;
+    }
+    error_code = wifi_ap_get_connection_state(ap, &state);
+    if (error_code != WIFI_ERROR_NONE)
+    {
+        OIC_LOG(ERROR,LOG_TAG,"#### Fail to get state.");
+        free(ap_name);
+
+        return false;
+    }
+    OIC_LOG_V(INFO,LOG_TAG,"#### AP name : %s, state : %s", ap_name, print_state(state));
+
+    if (strcmp(ap_name, gSsid) == 0)
+    {
+        OIC_LOG(INFO,LOG_TAG,"#### network found");
+        wifi_ap_set_passphrase(ap, gPass);
+        connectedWifi = ap;
+        error_code = wifi_connect(ap, __wifi_connected_cb, NULL);
+        OIC_LOG_V(INFO,LOG_TAG,"Code=%d", error_code);
+    }
+    OIC_LOG(INFO,LOG_TAG,"#### __wifi_found_ap_cb received ");
+    free(ap_name);
+    return true;
+}
+void __scan_request_cb(wifi_error_e error_code, void *user_data)
+{
+    OIC_LOG(INFO, LOG_TAG, "__scan_request_cb");
+    int error_code1;
+    error_code1 = wifi_foreach_found_aps(__wifi_found_ap_cb, NULL);
+    if (error_code1 != WIFI_ERROR_NONE)
+        OIC_LOG(INFO,LOG_TAG,"#### Fail to scan");
+
+    OIC_LOG(INFO, LOG_TAG,"#### __scan_request_cb exit ");
+}
+
+static void __wifi_activated_cb(wifi_error_e result, void *user_data)
+{
+    OIC_LOG(INFO, LOG_TAG, "__wifi_activated_cb");
+    if (result == WIFI_ERROR_NONE)
+    {
+        OIC_LOG(INFO,LOG_TAG,"#### Success to activate Wi-Fi device!");
+    }
+    wifi_scan(__scan_request_cb, NULL);
+
+}
+static void ESActivateWifi()
+{
+    int error_code;
+    error_code = wifi_initialize();
+    OIC_LOG_V(INFO,LOG_TAG,"#### WIFI INITIALIZED WITH STATUS :%d", error_code);
+
+    error_code = wifi_activate(__wifi_activated_cb, NULL);
+    OIC_LOG_V(INFO,LOG_TAG,"#### WIFI ACTIVATED WITH STATUS :%d", error_code);
+
+    bool wifi_activated = false;
+    wifi_is_activated(&wifi_activated);
+    if (wifi_activated)
+    {
+        OIC_LOG(INFO,LOG_TAG,"#### Success to get Wi-Fi device state.");
+        int scan_result = wifi_scan(__scan_request_cb, NULL);
+        OIC_LOG_V(INFO,LOG_TAG,"#### Wifi scan result:%d", scan_result);
+    }
+    else
+    {
+        OIC_LOG(ERROR,LOG_TAG, "#### Fail to get Wi-Fi device state.");
+    }
+}
+
+static void start()
+{
+    OIC_LOG(INFO, LOG_TAG, "START");
+    ESActivateWifi();
+}
+
+void ConnectToWiFiNetwork(const char *ssid, const char *pass,
+                                                            ESEnrolleeNetworkEventCallback cb)
+{
+    OIC_LOG_V(INFO, LOG_TAG, "ConnectToWiFiNetwork %s %s",ssid,pass);
+    gPass = pass;
+    gSsid = ssid;
+    gNetworkEventCb = cb;
+    start();
+}
+
+ESResult getCurrentNetworkInfo(OCConnectivityType targetType, NetworkInfo *info)
+{
+    if (targetType == CT_ADAPTER_IP)
+    {
+        info->type = CT_ADAPTER_IP;
+        info->ipaddr = gIpAddress;
+        if (strlen(gSsid) <= MAXSSIDLEN)
+        {
+            OICStrcpy(info->ssid, sizeof(info->ssid), gSsid);
+            return ES_OK;
+        }
+        else
+        {
+            return ES_ERROR;
+        }
+    }
+
+    return ES_ERROR;
+}
+
diff --git a/service/easy-setup/enrollee/tizen/wifi/networkhandler.h b/service/easy-setup/enrollee/tizen/wifi/networkhandler.h
new file mode 100644 (file)
index 0000000..410b665
--- /dev/null
@@ -0,0 +1,63 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/**
+ * @file
+ *
+ * This file contains IP network handling functionality for Enrollee device
+ */
+
+#ifndef ES_NETWORK_HANDLER_H_
+#define ES_NETWORK_HANDLER_H_
+
+
+#include <string.h>
+#include "easysetup.h"
+#include "logger.h"
+#include "escommon.h"
+
+#define MAXSSIDLEN 33
+#define MAXNETCREDLEN 20
+#define MAXNUMTYPE 5
+#define MAXADDRLEN 15
+
+/*
+ * Callback function for updating the Network status to the subscribers
+ *
+ * @param esResult ESResult provides the current state of the network connection status
+ */
+typedef void (*ESEnrolleeNetworkEventCallback)(ESResult esResult);
+
+typedef struct
+{
+    OCConnectivityType type;
+    // for WiFI
+    //IPAddress ipaddr;
+    char *ipaddr;
+    char ssid[MAXSSIDLEN];
+    // for BT, BLE
+    //byte mac[6];
+} NetworkInfo;
+
+void ConnectToWiFiNetwork(const char *ssid, const char *pass,
+                                                                ESEnrolleeNetworkEventCallback);
+ESResult getCurrentNetworkInfo(OCConnectivityType targetType, NetworkInfo *info);
+
+#endif
diff --git a/service/easy-setup/enrollee/tizen/wifi/softapnative.c b/service/easy-setup/enrollee/tizen/wifi/softapnative.c
new file mode 100644 (file)
index 0000000..ae47dda
--- /dev/null
@@ -0,0 +1,42 @@
+//******************************************************************
+//
+// 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 "softapnative.h"
+
+/**
+ * This API will create the Soft AP at Enrollee device. 
+ */
+void ESCreateSoftapNative(const char * ssid, const char* passwd, SoftAPCallbackNative cb)
+{
+    // TODO: Assign proper values after hardware integration is supported to create SoftAp
+    //We are not using this now. Assiging NULL to remove SVACE error
+    const char *ip = (char *)0;
+    const char *macaddr = (char *)0;
+    const char *devicename = (char *)0;
+
+    // Soft is created successfully. This callback may be send from other cascaded callbacks
+    cb(SOFTAP_SUCCESS, ip, macaddr, devicename);
+
+    // TODO: Use below code to indicate failed on-boarding / softap creation
+    // Soft creation is failed. This callback may be send from other cascaded callbacks 
+    //cb(SOFTAP_FAILED, nullptr,nullptr,nullptr);
+}
+
diff --git a/service/easy-setup/enrollee/tizen/wifi/softapnative.h b/service/easy-setup/enrollee/tizen/wifi/softapnative.h
new file mode 100644 (file)
index 0000000..10774ed
--- /dev/null
@@ -0,0 +1,66 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+
+
+#ifndef EASYSETUP_ENROLLEE_SOFTAP_H__
+#define EASYSETUP_ENROLLEE_SOFTAP_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+
+#define SOFTAP_SUCCESS  1
+#define SOFTAP_FAILED   0
+
+/**
+ * @file
+ *
+ * This file contains the API declaration for creating & configuration for SoftAP
+ */
+
+//This callback signagure may get changed as per the native implementation.
+typedef void (*SoftAPCallbackNative)(int result, const char *ip, const char* mac_addr,
+                                                                        const char*device_name);
+/**
+ * This API creats the Soft AP using the platform specific native system calls.
+ * @Note This API to be implemented by the OEM if Enrollee device SoC supports SoftAP
+ *
+ * @param networkType           NetworkType on which OnBoarding has to be performed.
+ * @param ssid                  SSID of the target SoftAP network to which the Enrollee is
+ *                              connecting.
+ * @param passwd                Password of the target SoftAP network to which the Enrollee is
+ *                              connecting
+ * @param SoftAPCallbackNative  EventCallback for for updating the Enrollee OnBoarding status
+ *                              result to the application
+ */
+
+void ESCreateSoftapNative(const char * ssid, const char* passwd, SoftAPCallbackNative cb);
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+
+#endif /* EASYSETUP_ENROLLEE_SOFTAP_H__ */
+
+
+
diff --git a/service/easy-setup/enrollee/unittests/SConscript b/service/easy-setup/enrollee/unittests/SConscript
new file mode 100644 (file)
index 0000000..6dc60e1
--- /dev/null
@@ -0,0 +1,94 @@
+#######################################################################
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+Import('env')
+import os
+import os.path
+enrollee_test_env = env.Clone()
+
+src_dir = enrollee_test_env.get('SRC_DIR')
+
+######################################################################
+# Build flags
+######################################################################
+
+enrollee_test_env.PrependUnique(CPPPATH = [
+               enrollee_test_env.get('SRC_DIR') + '/extlibs/gtest/gtest-1.7.0/include',
+               enrollee_test_env.get('SRC_DIR') + '/resource/c_common/ocrandom/include',
+               enrollee_test_env.get('SRC_DIR') + '/resource/csdk/stack/include/internal',
+               enrollee_test_env.get('SRC_DIR') + '/resource/csdk/connectivity/api',
+               enrollee_test_env.get('SRC_DIR') + '/resource/c_common/oic_malloc/include',
+               enrollee_test_env.get('SRC_DIR') + '/resource/include',
+               enrollee_test_env.get('SRC_DIR') + '/resource/csdk/logger/include',
+               enrollee_test_env.get('SRC_DIR') + '/resource/oc_logger/include',
+       enrollee_test_env.get('SRC_DIR') + '/resource/csdk/stack/include',
+               enrollee_test_env.get('SRC_DIR') + '/resource/csdk/stack/include/internal',
+        enrollee_test_env.get('SRC_DIR') + '/resource/csdk/logger/include',
+               enrollee_test_env.get('SRC_DIR') + '/resource/csdk/security/include',
+               enrollee_test_env.get('SRC_DIR') + '/extlibs/cjson',
+               enrollee_test_env.get('SRC_DIR') + '/extlibs/sqlite3',
+               enrollee_test_env.get('SRC_DIR') + '/service/easy-setup/inc',
+               enrollee_test_env.get('SRC_DIR') + '/service/easy-setup/enrollee/linux/wifi',
+               enrollee_test_env.get('SRC_DIR') + '/service/easy-setup/enrollee/inc',
+               enrollee_test_env.get('SRC_DIR') + '/service/easy-setup/enrollee/src'])
+
+enrollee_test_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
+enrollee_test_env.AppendUnique(LIBS = ['-lpthread'])
+enrollee_test_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+enrollee_test_env.AppendUnique(LIBPATH = [src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs'])
+enrollee_test_env.PrependUnique(LIBS = ['m',
+                                    'octbstack',
+                                    'ocsrm',
+                                    'connectivity_abstraction',
+                                    'coap',
+                                    'gtest',
+                                    'gtest_main'])
+
+target_os = env.get('TARGET_OS')
+if target_os != 'darwin':
+    enrollee_test_env.PrependUnique(LIBS = ['oc_logger'])
+
+if env.get('SECURED') == '1':
+    enrollee_test_env.AppendUnique(LIBS = ['tinydtls'])
+
+if env.get('LOGGING'):
+       enrollee_test_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+if env.get('ES_SOFTAP_MODE') == 'ENROLLEE_SOFTAP':
+       print "ES_SOFTAP_MODE == ENROLLEE_SOFTAP"
+       enrollee_test_env.AppendUnique(CPPDEFINES = ['ENROLLEE_SOFTAP'])
+
+enrollee_test_env.PrependUnique(LIBS = ['ESEnrolleeSDK'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+enrolleetests = enrollee_test_env.Program('enrolleetests', ['enrolleetests.cpp'])
+
+Alias("test", [enrolleetests])
+
+env.AppendTarget('test')
+if env.get('TEST') == '1':
+       target_os = env.get('TARGET_OS')
+       if target_os == 'linux':
+                from tools.scons.RunTest import *
+                run_test(enrollee_test_env,
+                         '',
+                         'service/easy-setup/enrollee/unittests/enrolleetests')
+
diff --git a/service/easy-setup/enrollee/unittests/enrolleetests.cpp b/service/easy-setup/enrollee/unittests/enrolleetests.cpp
new file mode 100644 (file)
index 0000000..9732b20
--- /dev/null
@@ -0,0 +1,303 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/**
+ * @file
+ *
+ * This file contains the implementation for EasySetup Enrollee testcases
+ */
+
+#include "gtest/gtest.h"
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <stdlib.h>
+
+//-----------------------------------------------------------------------------
+// Includes
+//-----------------------------------------------------------------------------
+#include <stdio.h>
+#include <string.h>
+
+#include <iostream>
+#include <stdint.h>
+
+#include "ocstack.h"
+#include "logger.h"
+#include "oic_malloc.h"
+#include "escommon.h"
+#include "easysetup.h"
+#include "onboarding.h"
+#include "resourcehandler.h"
+#include "softap.h"
+#include "easysetupcallbacks.h"
+
+#include "gtesthelper.h"
+
+using namespace std;
+
+namespace itst = iotivity::test;
+
+#define DEFAULT_CONTEXT_VALUE 0x99
+
+//-----------------------------------------------------------------------------
+// Private variables
+//-----------------------------------------------------------------------------
+static const char TAG[] = "TestHarness";
+
+char ssid[] = "EasySetup123";
+char passwd[] = "EasySetup123";
+
+//-----------------------------------------------------------------------------
+// Callback functions
+//-----------------------------------------------------------------------------
+extern "C"  void EventCallbackInApplication(ESResult esResult,
+                                                                    ESEnrolleeState enrolleeState)
+{
+    OIC_LOG(INFO, TAG, "Entering EventCallbackInApplication");
+
+    if(esResult != ES_OK)
+    {
+        cout<<"Easy stup is failed at Enrollee state = "<<enrolleeState<<endl;
+    }
+    else
+    {
+        if(enrolleeState == ES_ON_BOARDED_STATE)
+        {
+            cout<<"Device is successfully OnBoared on Adhoc network"<<endl;
+        }
+        else if (enrolleeState == ES_PROVISIONED_STATE)
+        {
+            cout<<"Device is provisioned with target network's credentials"<<endl;
+        }
+        else if (enrolleeState == ES_ON_BOARDED_TARGET_NETWORK_STATE)
+        {
+            cout<<"Device is onboarded/connected with target network"<<endl;
+        }
+        else
+        {
+            cout<<"Wrong state !! Easy setup is failed at Enrollee state = "<<enrolleeState<<endl;
+        }
+    }
+}
+
+//-----------------------------------------------------------------------------
+//  Local functions
+//-----------------------------------------------------------------------------
+
+void InitESEnrollee()
+{
+    OIC_LOG(INFO, TAG, "Entering InitESEnrollee");
+
+    EXPECT_EQ(ES_OK, ESInitEnrollee(CT_ADAPTER_IP,
+                                    "EasySetup123",
+                                    "EasySetup123",
+                                    0,
+                                    EventCallbackInApplication));
+    OIC_LOG(INFO, TAG, "Leaving InitESEnrollee");
+}
+
+//-----------------------------------------------------------------------------
+// Tests
+//-----------------------------------------------------------------------------
+
+TEST(ESEnrolleeInit, ESEnrolleeInitNullSSID)
+{
+    EXPECT_EQ(ES_ERROR, ESInitEnrollee(CT_ADAPTER_IP, 0, passwd, 0, EventCallbackInApplication));
+}
+
+TEST(ESEnrolleeInit, ESEnrolleeInitNullPassword)
+{
+    EXPECT_EQ(ES_ERROR, ESInitEnrollee(CT_ADAPTER_IP, ssid, 0, 0, EventCallbackInApplication));
+}
+
+TEST(ESEnrolleeInit, ESEnrolleeInitNullCb)
+{
+    EXPECT_EQ(ES_ERROR, ESInitEnrollee(CT_ADAPTER_IP, ssid, passwd, 0, 0));
+}
+
+TEST(ESEnrolleeInit, ESEnrolleeESInitEnrolleeSuccess)
+{
+    EXPECT_EQ(ES_OK, ESInitEnrollee(CT_ADAPTER_IP,
+                                    ssid,
+                                    passwd,
+                                    0,
+                                    EventCallbackInApplication));
+}
+
+TEST(ESEnrolleeInit, ESEnrolleeBleOnboarding)
+{
+    EXPECT_EQ(0, ESBleOnboarding());
+}
+
+TEST(ESEnrolleeInit, ESEnrolleeSoftapOnboarding)
+{
+    EXPECT_EQ(true, ESSoftapOnboarding());
+}
+
+TEST(ESOCInit, ESOCInitNullIPAddr)
+{
+    EXPECT_EQ(OC_STACK_OK, OCInit(0, 5683, OC_SERVER));
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+TEST(ESOCInit, ESOCInitNullPort)
+{
+    EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 0, OC_SERVER));
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+TEST(ESOCInit, ESOCInitNullAddrAndPort)
+{
+    EXPECT_EQ(OC_STACK_OK, OCInit(0, 0, OC_SERVER));
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+TEST(ESOCInit, ESOCInitInvalidMode)
+{
+    EXPECT_EQ(OC_STACK_ERROR, OCInit(0, 0, (OCMode)10));
+    EXPECT_EQ(OC_STACK_ERROR, OCStop());
+}
+
+TEST(ESProvisioning, ESInitProvisioningResource)
+{
+    EXPECT_EQ(ES_RESOURCECREATED, ESInitProvisioning());
+}
+
+TEST(ESProvisioning, ESInitProvisioningWithOCStackClientMode)
+{
+    EXPECT_EQ(OC_STACK_OK, OCInit(NULL, 0, OC_CLIENT));
+    EXPECT_EQ(ES_ERROR, ESInitProvisioning());
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+TEST(ESProvisioningResource, ESCreateProvisioningResourceSecurityDisabled)
+{
+    EXPECT_EQ(OC_STACK_OK, OCInit(0, 0, OC_SERVER));
+    EXPECT_EQ(OC_STACK_OK, CreateProvisioningResource(0));
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+TEST(ESProvisioningResource, ESCreateProvisioningResourceSecurityEnabled)
+{
+    EXPECT_EQ(OC_STACK_OK, OCInit(0, 0, OC_SERVER));
+    EXPECT_EQ(OC_STACK_OK, CreateProvisioningResource(1));
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+TEST(ESProvisioningResource, ESDeleteProvisioningResource)
+{
+    EXPECT_EQ(OC_STACK_OK, OCInit(0, 0, OC_SERVER));
+    EXPECT_EQ(OC_STACK_OK, CreateProvisioningResource(0));
+    EXPECT_EQ(OC_STACK_OK, DeleteProvisioningResource());
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+TEST(ESProvisioningResource, ESDeleteProvisioningResourceWithoutCreating)
+{
+    EXPECT_EQ(OC_STACK_OK, OCInit(0, 0, OC_SERVER));
+    EXPECT_EQ(OC_STACK_NO_RESOURCE, DeleteProvisioningResource());
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+TEST(ESOnboarding, ESOnboardingSoftAp)
+{
+    EXPECT_EQ(1, ESOnboard(ssid, passwd, ESOnboardingCallback));
+}
+
+TEST(ESOnboarding, ESOnboardingSoftApEnrollee)
+{
+#ifdef ENROLLEE_SOFTAP
+    EXPECT_EQ(1, ESSoftapAtEnrollee());
+    EXPECT_EQ(0, ESSoftapAtMediator());
+#endif
+}
+
+TEST(ESOnboarding, ESOnboardingSoftApMediator)
+{
+#ifndef ENROLLEE_SOFTAP
+    EXPECT_EQ(0, ESSoftapAtEnrollee());
+    EXPECT_EQ(1, ESSoftapAtMediator());
+#endif
+}
+
+TEST(ESOnboarding, ESOnboardingSoftApHost)
+{
+#ifdef ENROLLEE_SOFTAP
+    EXPECT_EQ(ENROLLEE, ESSoftapHost());
+#else
+    EXPECT_EQ(MEDIATOR, ESSoftapHost());
+#endif
+}
+
+TEST(ESStop, ESTerminateEasysetupWithoutESInit)
+{
+    EXPECT_EQ(ES_ERROR, ESTerminateEnrollee());
+}
+
+TEST(ESStop, ESTerminateEasysetupWithoutOCStack)
+{
+    EXPECT_EQ(ES_OK, ESInitEnrollee(CT_ADAPTER_IP,
+                                    ssid,
+                                    passwd,
+                                    0,
+                                    EventCallbackInApplication));
+    EXPECT_EQ(ES_ERROR, ESTerminateEnrollee());
+}
+
+TEST(ESStop, ESTerminateEasysetupWithOutCreateProvisioningResource)
+{
+    EXPECT_EQ(ES_OK, ESInitEnrollee(CT_ADAPTER_IP,
+                                    ssid,
+                                    passwd,
+                                    0,
+                                    EventCallbackInApplication));
+    EXPECT_EQ(OC_STACK_OK, OCInit(0, 0, OC_SERVER));
+    EXPECT_EQ(ES_ERROR, ESTerminateEnrollee());
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+TEST(ESStop, ESTerminateEasysetupWithoutProviosioningResource)
+{
+    EXPECT_EQ(ES_OK, ESInitEnrollee(CT_ADAPTER_IP,
+                                    ssid,
+                                    passwd,
+                                    0,
+                                    EventCallbackInApplication));
+    EXPECT_EQ(OC_STACK_OK, OCInit(NULL, 0, OC_SERVER));
+    EXPECT_EQ(ES_ERROR, ESTerminateEnrollee());
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+TEST(ESStop, ESTerminateEasysetupSuccess)
+{
+    EXPECT_EQ(ES_OK, ESInitEnrollee(CT_ADAPTER_IP,
+                                    ssid,
+                                    passwd,
+                                    0,
+                                    EventCallbackInApplication));
+    EXPECT_EQ(OC_STACK_OK, OCInit(NULL, 0, OC_SERVER));
+    EXPECT_EQ(ES_RESOURCECREATED, ESInitProvisioning());
+    EXPECT_EQ(ES_OK, ESTerminateEnrollee());
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
diff --git a/service/easy-setup/enrollee/unittests/gtesthelper.h b/service/easy-setup/enrollee/unittests/gtesthelper.h
new file mode 100644 (file)
index 0000000..4de59eb
--- /dev/null
@@ -0,0 +1,151 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef IOTY_GTEST_HELPER_H
+#define IOTY_GTEST_HELPER_H
+
+#include <atomic>
+#include <chrono>
+#include <condition_variable>
+#include <future>
+#include <mutex>
+#include <thread>
+
+namespace iotivity
+{
+    namespace test
+    {
+        /**
+         * Simple implementation of a deadman's timer that can be used to
+         * terminate a test that hangs.
+         *
+         * Since there is no standard way to terminate an individual thread,
+         * the entire process will be killed once time has been exceeded.
+         *
+         * @note provisions for watchdog thread cleanup are not currently added.
+         * Testing has not yet shown any need for such complexity.
+         */
+        class DeadmanTimer
+        {
+        public:
+
+            /**
+             * Creates an instance of a timer set to kill the running process
+             * after the specified timeout.
+             *
+             * If the destructor is invoked before time is up (aka this instance
+             * goes out of scope) the timeout will not cause the program to be
+             * terminated.
+             *
+             * @param time to wait before assuming the process is hung and must be
+             * killed.
+             * Examples of values that can be passed include
+             * std::chrono::milliseconds(250), std::chrono::seconds(5),
+             * std::chrono::minutes(3).
+             */
+            DeadmanTimer(std::chrono::milliseconds timeout) :
+                m_ctx(new DeadmanCtx(timeout)),
+                m_thread()
+                {
+                    m_thread = std::thread([this](){run(m_ctx);});
+                    {
+                        std::unique_lock<std::mutex> lock(m_ctx->m_mutex);
+                        while (!m_ctx->m_isArmed)
+                        {
+                            m_ctx->m_cond.wait(lock);
+                        }
+                    }
+                    // Now that the thread is live, we can stop tracking it.
+                    m_thread.detach();
+                }
+
+            /**
+             * Destructor that also will cancel the termination of the
+             * running process.
+             */
+            ~DeadmanTimer()
+            {
+                std::unique_lock<std::mutex> lock(m_ctx->m_mutex);
+                m_ctx->m_isArmed = false;
+            }
+
+        private:
+
+            /**
+             * Shared data that main and child thread might both need to
+             * access.
+             *
+             * Avoids referencing data in class instances that have been
+             * deleted.
+             */
+            class DeadmanCtx
+            {
+            public:
+
+                DeadmanCtx(std::chrono::milliseconds timeout) :
+                    m_mutex(),
+                    m_cond(),
+                    m_isArmed(false),
+                    m_timeout(timeout)
+                    {
+                    }
+
+                std::mutex m_mutex;
+                std::condition_variable m_cond;
+                bool m_isArmed;
+                std::chrono::milliseconds m_timeout;
+            };
+
+            // Explicitly block assignment and copy ctor
+            DeadmanTimer &operator=(const DeadmanTimer &rhs);
+            DeadmanTimer(const iotivity::test::DeadmanTimer &rhs);
+
+            std::shared_ptr<DeadmanCtx> m_ctx;
+            std::thread m_thread;
+
+
+            static void run(std::shared_ptr<DeadmanCtx> ctx)
+            {
+                // Let the calling thread know it can stop waiting:
+                {
+                    std::unique_lock<std::mutex> lock(ctx->m_mutex);
+                    ctx->m_isArmed = true;
+                    ctx->m_cond.notify_all();
+                }
+
+                std::this_thread::sleep_for(ctx->m_timeout);
+
+                std::unique_lock<std::mutex> lock(ctx->m_mutex);
+                if (ctx->m_isArmed)
+                {
+                    try {
+                        throw std::runtime_error("deadman timer expired");
+                    }
+                    catch (std::exception&)
+                    {
+                        std::terminate();
+                    }
+                }
+            }
+        };
+    } // namespace test
+} // namespace iotivity
+
+#endif // IOTY_GTEST_HELPER_H
diff --git a/service/easy-setup/inc/escommon.h b/service/easy-setup/inc/escommon.h
new file mode 100755 (executable)
index 0000000..17ec815
--- /dev/null
@@ -0,0 +1,249 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef ES_COMMON_H_
+#define ES_COMMON_H_
+
+#include "ocstack.h"
+#include "octypes.h"
+
+// Defines
+#define OIC_STRING_MAX_VALUE    100
+#define IPV4_ADDR_SIZE          16
+#define IP_PORT                 55555
+#define NET_WIFI_SSID_SIZE      100
+#define NET_WIFI_PWD_SIZE       100
+
+/**
+ * @brief Mac address length for BT port
+ */
+#define NET_MACADDR_SIZE 18
+
+/**
+ * Attributes used to form a proper easysetup conforming JSON message.
+ */
+#define OC_RSRVD_ES_PS                     "ps"
+#define OC_RSRVD_ES_TNN                    "tnn"
+#define OC_RSRVD_ES_CD                     "cd"
+#define OC_RSRVD_ES_TR                     "tr"
+#define OC_RSRVD_ES_TNT                    "tnt"
+#define OC_RSRVD_ES_ANT                    "ant"
+
+/**
+ * Easysetup defined resoruce types and uris.
+ */
+#define OC_RSRVD_ES_PROV_RES_TYPE           "oic.r.prov"
+#define OC_RSRVD_ES_URI_PROV               "/oic/prov"
+#define OC_RSRVD_ES_URI_NET                "/oic/net"
+
+/**
+ * @brief Defines for Provisioning status accepted values
+ */
+#define ES_PS_NEED_PROVISIONING         1
+#define ES_PS_PROVISIONING_COMPLETED    2
+#define ES_PS_TRIGGER_INIT_VALUE        0
+#define ES_PS_TRIGGER_CONNECTION        1
+
+
+/**
+* Device Roles defined for each device type used in easy setup
+*/
+typedef enum
+{
+    ENROLLEE,
+    MEDIATOR,
+    ENROLLER,
+} DeviceRole;
+
+/**
+* On-boarding connection to create Adhoc network.
+*/
+typedef enum
+{
+    SOFTAP,
+    BLE,
+} OBConnection;
+
+typedef enum
+{
+    ES_ERROR = -1,
+    ES_OK = 0,
+    ES_NETWORKFOUND = 1,
+    ES_NETWORKCONNECTED,
+    ES_NETWORKNOTCONNECTED,
+    ES_RESOURCECREATED = 11,
+    ES_RECVREQOFPROVRES = 21,
+    ES_RECVREQOFNETRES,
+    ES_RECVUPDATEOFPROVRES,
+    ES_RECVTRIGGEROFPROVRES,
+} ESResult;
+
+typedef enum
+{
+    /**
+     * Default state of the device
+     */
+    ES_INIT_STATE,
+
+    /**
+     * Device will move to this state once the on boarding begins
+     */
+    ES_ON_BOARDING_STATE,
+
+    /**
+     * Device will move to this state after successful on-boarding of the device
+     */
+    ES_ON_BOARDED_STATE,
+
+    /**
+     * Device will move to this state once the on boarding is done
+     */
+    ES_PROVISIONING_STATE,
+
+    /**
+     * Easy setup process is successful.
+     */
+    ES_PROVISIONED_STATE,
+
+    /**
+     * This state is arbitrary one, any time device can come into this state
+     * Device will move to this state if the ownership transfer initiated  by the Application
+     */
+    ES_OWNERSHIP_TRANSFERRING_STATE,
+
+    /**
+     * This state is arbitrary one, any time device can come into this state
+     * Device will move to this state if the ownership transfer is completed
+     */
+    ES_OWNERSHIP_TRANSFERRED_STATE,
+
+    /**
+     * This state is arbitrary one, any time device can come into this state
+     * Device will move to this state once the Application factory reset the device
+     */
+    ES_FACTORY_RESET_STATE,
+
+    /**
+     * Enrollee moves to this state after connecting to target network
+     */
+    ES_ON_BOARDED_TARGET_NETWORK_STATE,
+}ESEnrolleeState;
+
+/**
+ * Provisioning Device Status
+ */
+typedef struct
+{
+    // Address of remote server
+    OCDevAddr * addr;
+    // Indicates adaptor type on which the response was received
+    OCConnectivityType connType;
+} EasySetupDeviceInfo;
+
+/**
+ * Provosioning Status
+ */
+typedef enum
+{
+    DEVICE_PROVISIONED = 0,
+    DEVICE_NOT_PROVISIONED,
+    DEVICE_OWNED,
+    DEVICE_NOT_OWNED
+} EasySetupState, ProvStatus;
+
+/**
+ * Response from queries to remote servers.
+ */
+typedef struct
+{
+    // EasySetup Status
+    EasySetupState provStatus;
+    // EasySetup Device Info
+    EasySetupDeviceInfo provDeviceInfo;
+} EasySetupInfo, ProvisioningInfo;
+
+/**
+ * @brief  Network information of the Enroller
+ */
+typedef union
+{
+    /**
+     * @brief BT Mac Information
+     */
+    struct
+    {
+        char btMacAddress[NET_MACADDR_SIZE];   /**< BT mac address **/
+    } BT;
+
+    /**
+     * @brief LE MAC Information
+     */
+    struct
+    {
+        char leMacAddress[NET_MACADDR_SIZE];   /**< BLE mac address **/
+    } LE;
+
+    /**
+     * @brief IP Information
+     */
+    struct
+    {
+        char ssid[NET_WIFI_SSID_SIZE]; /**< ssid of the Enroller**/
+        char pwd[NET_WIFI_PWD_SIZE]; /**< pwd of the Enroller**/
+    } WIFI;
+} ProvData;
+
+/**
+ * @brief Network Information
+ */
+typedef struct
+{
+    ProvData provData;    /**< Enroller Network Info**/
+    OCConnectivityType connType;    /**< Connectivity Type**/
+} ProvConfig;
+
+/**
+ * Client applications implement this callback to consume responses received from Servers.
+ */
+typedef void (*OCProvisioningStatusCB)(EasySetupInfo *easySetupInfo);
+
+/**
+ * @brief This structure represent configuration information to create wifi onboarding SoftAP or connection.
+*/
+
+
+// Note : Below structure is not currently used but added for future purpose.
+typedef struct {
+    char ssid[NET_WIFI_SSID_SIZE]; /**< ssid of the onboarding Adhoc Wifi network**/
+    char pwd[NET_WIFI_PWD_SIZE]; /**< pwd of the onboarding Adhoc wifi network**/
+    bool isSecured;                 /**< Secure connection**/
+}WiFiOnboardingConfig;
+
+/**
+ * @brief This structure represent onboarding connection instance.
+*/
+typedef struct {
+ /*Actual use of ipAddress is for unicast discovery, but also used to identify the Enrollee device as of now,
+    device identification should be based on DeviceID in next release.*/
+   char ipAddress[IPV4_ADDR_SIZE]; /**< IP Address of the Enrollee **/
+   bool isSecured;                 /**< Secure connection**/
+}WiFiOnboadingConnection;
+
+#endif //ES_COMMON_H_
diff --git a/service/easy-setup/mediator/SConscript b/service/easy-setup/mediator/SConscript
new file mode 100644 (file)
index 0000000..0e35382
--- /dev/null
@@ -0,0 +1,34 @@
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+######################################################################
+# easy-setup Mediator SDKs build script
+######################################################################
+Import('env')
+
+target_os = env.get('TARGET_OS')
+
+# Build easy-setup Mediator C SDK
+SConscript('csdk/SConscript')
+
+# Build easy-setup Mediator Rich [C++] SDK
+SConscript('richsdk/SConscript')
+
+
diff --git a/service/easy-setup/mediator/csdk/SConscript b/service/easy-setup/mediator/csdk/SConscript
new file mode 100644 (file)
index 0000000..675ab6b
--- /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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+######################################################################
+# easy-setup Mediator CSDK build script
+######################################################################
+
+import os
+
+Import('env')
+
+env.AppendUnique(CPPDEFINES = ['EASY_SETUP_CA_INIT'])
+
+if env.get('RELEASE'):
+    env.AppendUnique(CCFLAGS = ['-Os'])
+    env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+else:
+    env.AppendUnique(CCFLAGS = ['-g'])
+
+if env.get('LOGGING'):
+    env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+# Easysetup provides reference implemenation of Arduino Enrollee.
+# Mediator applications developed on different platforms will be default defining the
+# flag 'REMOTE_ARDUINO_ENROLEE'. If the target Enrollee is not Arduino, the below commented
+# modifications must be enabled instead (and the existing define must be commented).
+#
+##### The following lines must be uncommented, if target Enrollee is not Arduino
+target_enrollee = env.get('ES_TARGET_ENROLLEE')
+if target_enrollee == 'arduino':
+       print "REMOTE_ARDUINO_ENROLEE flag is defined."
+       print "The Mediator application will be working only with Arduino Enrollee."
+       env.AppendUnique(CPPDEFINES = ['REMOTE_ARDUINO_ENROLEE'])
+
+lib_env = env.Clone()
+easy_setup_env = env.Clone()
+
+target_os = env.get('TARGET_OS')
+
+if target_os in ['android']:
+       # Add third party libraries
+       SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+
+######################################################################
+# Build flags
+######################################################################
+
+easy_setup_env.AppendUnique(CPPPATH = ['inc',  'src','../../inc'])
+easy_setup_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
+if target_os == 'linux':
+       easy_setup_env.AppendUnique(LIBS = ['pthread', 'dl'])
+
+
+######################################################################
+# Linux Mediator
+######################################################################
+if target_os == 'linux':
+       easy_setup_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+       easy_setup_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
+       easy_setup_env.AppendUnique(CXXFLAGS = ['-pthread'])
+       easy_setup_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'pthread', 'connectivity_abstraction'])
+
+######################################################################
+# Android Mediator
+######################################################################
+if target_os == 'android':
+       easy_setup_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+       easy_setup_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
+       easy_setup_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
+       easy_setup_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'gnustl_shared'])
+       if not env.get('RELEASE'):
+               easy_setup_env.AppendUnique(LIBS = ['log'])
+
+
+if target_os in ['android','linux']:
+       easy_setup_env.PrependUnique(CPPPATH = [
+               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',
+               env.get('SRC_DIR') + '/resource/csdk/security/include',
+               env.get('SRC_DIR') + '/extlibs/cjson',
+               env.get('SRC_DIR') + '/service/easy-setup/inc',
+               'inc'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+
+if target_os == 'android':
+       es_m_csdk_static = easy_setup_env.StaticLibrary('libESMediatorCSDK',
+                                       ['src/provisioningapi.cpp',
+                                       'src/wifiprovisioning.cpp',
+                    'src/provisioning.cpp'])
+       easy_setup_env.InstallTarget(es_m_csdk_static, 'libESMediatorCSDK')
+
+if target_os == 'linux':
+       es_m_csdk_shared = easy_setup_env.SharedLibrary('ESMediatorCSDK',
+                                       ['src/provisioningapi.cpp',
+                                       'src/wifiprovisioning.cpp',
+                    'src/provisioning.cpp'])
+       easy_setup_env.InstallTarget(es_m_csdk_shared, 'libESMediatorCSDK')
+
+       #Go to build sample apps
+       SConscript('../../sampleapp/mediator/linux/csdk_sample/SConscript')
+
+######################################################################
+#Build UnitTestcases for Mediator[CSDK]
+################################################ ######################
+if target_os == 'linux':
+    SConscript('unittests/SConscript')
+
+
+
+
+
+
+
+
+
diff --git a/service/easy-setup/mediator/csdk/inc/provisioning.h b/service/easy-setup/mediator/csdk/inc/provisioning.h
new file mode 100755 (executable)
index 0000000..f9a6d61
--- /dev/null
@@ -0,0 +1,119 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef __ES_PROVISIONING_HANDLER_H_
+#define __ES_PROVISIONING_HANDLER_H_
+
+#include "octypes.h"
+
+#include "logger.h"
+#include "ocstack.h"
+#include "escommon.h"
+
+//-----------------------------------------------------------------------------
+// Defines
+//-----------------------------------------------------------------------------
+#define EASY_SETUP_DEFAULT_CONTEXT_VALUE 0x99
+
+/**
+ * List of methods that can be inititated from the client
+ */
+OCStackResult InitProvisioningHandler();
+
+OCStackResult TerminateProvisioningHandler();
+
+OCStackResult GetProvisioningStatus(OCQualityOfService qos, const char *query,
+        const OCDevAddr *destination);
+
+OCStackResult StartProvisioningProcess(const ProvConfig *netInfo,
+        WiFiOnboadingConnection *onboardConn, OCProvisioningStatusCB provisioningStatusCallback,
+        char *findResQuery);
+
+void StopProvisioningProcess();
+
+/**
+ * Internal worker functions.
+ */
+OCStackResult TriggerNetworkConnection(OCQualityOfService qos, const char *query,
+        const char *resUri, OCDevAddr *destination, int /*pauseBeforeStart*/);
+
+OCStackApplicationResult TriggerNetworkConnectionResponse(void *ctx, OCDoHandle handle,
+        OCClientResponse *clientResponse);
+
+OCStackApplicationResult ProvisionEnrolleeResponse(void *ctx, OCDoHandle handle,
+        OCClientResponse *clientResponse);
+
+OCStackResult ProvisionEnrollee(OCQualityOfService qos, const char *query, const char *resUri,
+        OCDevAddr *destination, int pauseBeforeStart);
+
+OCStackApplicationResult GetProvisioningStatusResponse(void *ctx, OCDoHandle handle,
+        OCClientResponse *clientResponse);
+
+OCStackResult InvokeOCDoResource(const char *query, OCMethod method, const OCDevAddr *dest,
+        OCQualityOfService qos, OCClientResponseHandler cb, OCRepPayload *payload,
+        OCHeaderOption *options, uint8_t numOptions);
+
+OCStackApplicationResult FindProvisioningResourceResponse(void *ctx, OCDoHandle handle,
+        OCClientResponse *clientResponse);
+
+void *FindProvisioningResource(void *data);
+
+ProvisioningInfo *PrepareProvisioingStatusCB(OCClientResponse *clientResponse,
+        ProvStatus provStatus);
+
+/**
+ * Internal Util functions.
+ */
+void LogProvisioningResponse(OCRepPayloadValue * val);
+
+bool ConfigEnrolleeObject(const ProvConfig *netInfo, WiFiOnboadingConnection *onboardConn);
+
+bool ClearMemory();
+
+void SuccessCallback(OCClientResponse * clientResponse);
+
+void ErrorCallback(ProvStatus status);
+
+bool ValidateEnrolleeResponse(OCClientResponse * clientResponse);
+
+bool ValidateFindResourceResponse(OCClientResponse * clientResponse);
+
+bool ValidateEnrolleeBasicResponse(OCClientResponse * clientResponse);
+
+ProvisioningInfo *GetCallbackObjectOnSuccess(OCClientResponse *clientResponse,
+        ProvStatus provStatus);
+
+ProvisioningInfo *GetCallbackObjectOnError(ProvStatus status);
+
+ProvisioningInfo *CreateCallBackObject();
+
+bool ResetProgress();
+
+bool SetProgress(OCProvisioningStatusCB provisioningStatusCallback);
+
+bool InProgress();
+
+bool ValidateEasySetupParams(const ProvConfig *netInfo, WiFiOnboadingConnection *onboardConn,
+        OCProvisioningStatusCB provisioningStatusCallback);
+
+bool IsSetupStopped();
+
+#endif //__ES_PROVISIONING_HANDLER_H_
+
diff --git a/service/easy-setup/mediator/csdk/inc/provisioningapi.h b/service/easy-setup/mediator/csdk/inc/provisioningapi.h
new file mode 100755 (executable)
index 0000000..5fa60fa
--- /dev/null
@@ -0,0 +1,56 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#ifndef __EASYSETUP_MGR_H_
+#define __EASYSETUP_MGR_H_
+
+#include <string.h>
+
+#include "logger.h"
+#include "ocstack.h"
+#include "octypes.h"
+#include "escommon.h"
+
+#include "provisioning.h"
+
+//-----------------------------------------------------------------------------
+// Defines
+//-----------------------------------------------------------------------------
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+    OCStackResult InitProvProcess();
+
+    OCStackResult ResetProvProcess();
+
+    OCStackResult RegisterCallback(OCProvisioningStatusCB provisioningStatusCallback);
+
+    void UnRegisterCallback();
+
+    OCStackResult StartProvisioning(const ProvConfig *netInfo,
+            WiFiOnboadingConnection *onboardConn);
+
+    OCStackResult StopProvisioning(OCConnectivityType connectivityType);
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/service/easy-setup/mediator/csdk/src/provisioning.cpp b/service/easy-setup/mediator/csdk/src/provisioning.cpp
new file mode 100755 (executable)
index 0000000..ac6ac5b
--- /dev/null
@@ -0,0 +1,577 @@
+//******************************************************************
+//
+// 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 "provisioning.h"
+
+//Standard includes
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <signal.h>
+#include <unistd.h>
+#include <pthread.h>
+
+//EasySetup include files
+#include "ocpayload.h"
+#include "escommon.h"
+
+// External includes
+#include "logger.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+
+#define ES_PROV_TAG "EASY_SETUP_PROVISIONING"
+
+bool gProvisioningCondFlag = false;
+
+static ProvConfig *gProvConfig;
+static WiFiOnboadingConnection *gOnboardConn;
+static char gSzFindResourceQueryUri[64] =
+{ 0 };
+
+/**
+ * @var cbData
+ * @brief Callback for providing provisioning status callback to application
+ */
+static OCProvisioningStatusCB cbData = NULL;
+
+/**
+ * Utility function for error callback.
+ */
+void ErrorCallback(ProvStatus status)
+{
+    ProvisioningInfo *provInfo = GetCallbackObjectOnError(status);
+    if(cbData != NULL)
+    {
+        cbData(provInfo);
+    }
+}
+
+/**
+ * Functions implementing the exposed APIs.
+ */
+OCStackResult InitProvisioningHandler()
+{
+    OCStackResult ret = OC_STACK_ERROR;
+    /* Initialize OCStack*/
+    if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, ES_PROV_TAG, "OCStack init error");
+        return ret;
+    }
+
+    return OC_STACK_OK;
+}
+
+OCStackResult StartProvisioningProcess(const ProvConfig *netInfo,
+        WiFiOnboadingConnection *onboardConn, OCProvisioningStatusCB provisioningStatusCallback,
+        char *findResQuery)
+{
+
+    if (findResQuery != NULL)
+    {
+        OICStrcpy(gSzFindResourceQueryUri, sizeof(gSzFindResourceQueryUri) - 1, findResQuery);
+    }
+    else
+    {
+        OIC_LOG(ERROR, ES_PROV_TAG, PCF("Find resource query is NULL"));
+        goto Error;
+    }
+
+    pthread_t thread_handle;
+
+    if (!ValidateEasySetupParams(netInfo, onboardConn, provisioningStatusCallback))
+    {
+        goto Error;
+    }
+
+    if (!SetProgress(provisioningStatusCallback))
+    {
+        // Device provisioning session is running already.
+        OIC_LOG(INFO, ES_PROV_TAG, PCF("Device provisioning session is running already"));
+        goto Error;
+    }
+
+    if (!ConfigEnrolleeObject(netInfo, onboardConn))
+    {
+        goto Error;
+    }
+
+    if (pthread_create(&thread_handle, NULL, FindProvisioningResource, NULL))
+    {
+        goto Error;
+
+    }
+
+    pthread_join(thread_handle, NULL);
+
+    return OC_STACK_OK;
+
+    Error:
+    {
+        ErrorCallback(DEVICE_NOT_PROVISIONED);
+        ClearMemory();
+        return OC_STACK_ERROR;
+    }
+
+}
+
+void StopProvisioningProcess()
+{
+    ResetProgress();
+}
+
+OCStackResult TerminateProvisioningHandler()
+{
+    OCStackResult ret = OC_STACK_ERROR;
+    if (OCStop() != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, ES_PROV_TAG, "OCStack stop error");
+    }
+
+    gProvisioningCondFlag = true;
+    ResetProgress();
+
+    ret = OC_STACK_OK;
+    return ret;
+}
+
+OCStackApplicationResult TriggerNetworkConnectionResponse(void* /*ctx*/, OCDoHandle /*handle*/,
+        OCClientResponse *clientResponse)
+{
+    OIC_LOG_V(DEBUG, ES_PROV_TAG, "INSIDE TriggerNetworkConnectionResponse");
+
+    // If user stopped the process then return from this function;
+    if (IsSetupStopped())
+    {
+        ErrorCallback(DEVICE_NOT_PROVISIONED);
+        ClearMemory();
+        return OC_STACK_DELETE_TRANSACTION;
+    }
+
+    if (!ValidateEnrolleeBasicResponse(clientResponse))
+    {
+        ErrorCallback(DEVICE_NOT_PROVISIONED);
+        return OC_STACK_DELETE_TRANSACTION;
+    }
+
+    SuccessCallback(clientResponse);
+    return OC_STACK_KEEP_TRANSACTION;
+}
+
+OCStackResult TriggerNetworkConnection(OCQualityOfService qos, const char *query,
+        const char *resUri, OCDevAddr *destination, int /*pauseBeforeStart*/)
+{
+    OIC_LOG_V(INFO, ES_PROV_TAG, "Inside TriggerNetworkConnection");
+
+    OCRepPayload *payload = OCRepPayloadCreate();
+
+    OCRepPayloadSetUri(payload, resUri);
+    OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_TR, ES_PS_TRIGGER_CONNECTION);
+
+    OIC_LOG_V(DEBUG, ES_PROV_TAG, "Triggering network connection from Mediator");
+
+    OCStackResult ret = InvokeOCDoResource(query, OC_REST_POST, destination, qos,
+            TriggerNetworkConnectionResponse, payload, NULL, 0);
+
+    return ret;
+}
+
+
+
+bool ClearMemory()
+{
+
+    OIC_LOG(DEBUG, ES_PROV_TAG, "thread_pool_add_task of FindProvisioningResource failed");
+    OICFree(gProvConfig);
+    OICFree(gOnboardConn);
+
+    return true;
+
+}
+
+bool ConfigEnrolleeObject(const ProvConfig *netInfo, WiFiOnboadingConnection *connection)
+{
+
+    //Copy Network Provisioning  Information
+    gProvConfig = (ProvConfig *) OICCalloc(1, sizeof(ProvConfig));
+    gOnboardConn = (WiFiOnboadingConnection *) OICCalloc(1, sizeof(WiFiOnboadingConnection));
+
+    if (gProvConfig == NULL)
+    {
+        OIC_LOG(ERROR, ES_PROV_TAG, "Invalid input..");
+        return false;
+    }
+
+    if (gOnboardConn == NULL)
+    {
+        OIC_LOG(ERROR, ES_PROV_TAG, "Invalid input..");
+        return false;
+    }
+
+    memcpy(gProvConfig, netInfo, sizeof(ProvConfig));
+    memcpy(gOnboardConn, connection, sizeof(WiFiOnboadingConnection));
+
+    OIC_LOG_V(DEBUG, ES_PROV_TAG, "Network Provisioning Info. SSID = %s",
+            gProvConfig->provData.WIFI.ssid);
+
+    OIC_LOG_V(DEBUG, ES_PROV_TAG, "Network Provisioning Info. PWD = %s",
+            gProvConfig->provData.WIFI.pwd);
+
+    return true;
+
+}
+
+void LogProvisioningResponse(OCRepPayloadValue * val)
+{
+
+    switch (val->type)
+    {
+        case OCREP_PROP_NULL:
+            OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s: NULL", val->name);
+            break;
+        case OCREP_PROP_INT:
+            OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(int):%lld", val->name, val->i);
+            break;
+        case OCREP_PROP_DOUBLE:
+            OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(double):%f", val->name, val->d);
+            break;
+        case OCREP_PROP_BOOL:
+            OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(bool):%s", val->name, val->b ? "true" : "false");
+            break;
+        case OCREP_PROP_STRING:
+            OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(string):%s", val->name, val->str);
+            break;
+        case OCREP_PROP_OBJECT:
+            // Note: Only prints the URI (if available), to print further, you'll
+            // need to dig into the object better!
+            OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(OCRep):%s", val->name, val->obj->uri);
+            break;
+        case OCREP_PROP_ARRAY:
+            switch (val->arr.type)
+            {
+                case OCREP_PROP_INT:
+                    OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(int array):%zu x %zu x %zu",
+                            val->name,
+                            val->arr.dimensions[0], val->arr.dimensions[1],
+                            val->arr.dimensions[2]);
+                    break;
+                case OCREP_PROP_DOUBLE:
+                    OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(double array):%zu x %zu x %zu",
+                            val->name,
+                            val->arr.dimensions[0], val->arr.dimensions[1],
+                            val->arr.dimensions[2]);
+                    break;
+                case OCREP_PROP_BOOL:
+                    OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(bool array):%zu x %zu x %zu",
+                            val->name,
+                            val->arr.dimensions[0], val->arr.dimensions[1],
+                            val->arr.dimensions[2]);
+                    break;
+                case OCREP_PROP_STRING:
+                    OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(string array):%zu x %zu x %zu",
+                            val->name,
+                            val->arr.dimensions[0], val->arr.dimensions[1],
+                            val->arr.dimensions[2]);
+                    break;
+                case OCREP_PROP_OBJECT:
+                    OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(OCRep array):%zu x %zu x %zu",
+                            val->name,
+                            val->arr.dimensions[0], val->arr.dimensions[1],
+                            val->arr.dimensions[2]);
+                    break;
+                default:
+                    break;
+            }
+            break;
+        default:
+            break;
+    }
+}
+
+OCStackResult FindNetworkResource()
+{
+    OCStackResult ret = OC_STACK_ERROR;
+    if (OCStop() != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, ES_PROV_TAG, "OCStack stop error");
+    }
+
+    return ret;
+}
+
+ProvisioningInfo *PrepareProvisioingStatusCB(OCClientResponse *clientResponse,
+        ProvStatus provStatus)
+{
+
+    ProvisioningInfo *provInfo = (ProvisioningInfo *) OICCalloc(1, sizeof(ProvisioningInfo));
+
+    if (provInfo == NULL)
+    {
+        OIC_LOG_V(ERROR, ES_PROV_TAG, "Failed to allocate memory");
+        return NULL;
+    }
+
+    OCDevAddr *devAddr = (OCDevAddr *) OICCalloc(1, sizeof(OCDevAddr));
+
+    if (devAddr == NULL)
+    {
+        OIC_LOG_V(ERROR, ES_PROV_TAG, "Failed to allocate memory");
+        OICFree(provInfo);
+        return NULL;
+    }
+
+    OICStrcpy(devAddr->addr, sizeof(devAddr->addr), clientResponse->addr->addr);
+
+    devAddr->port = clientResponse->addr->port;
+
+    provInfo->provDeviceInfo.addr = devAddr;
+
+    provInfo->provStatus = provStatus;
+
+    return provInfo;
+}
+
+bool InProgress()
+{
+
+    // It means already Easy Setup provisioning session is going on.
+    if (NULL != cbData)
+    {
+        OIC_LOG(ERROR, ES_PROV_TAG, "Easy setup session is already in progress");
+        return true;
+    }
+
+    return false;
+}
+
+bool SetProgress(OCProvisioningStatusCB provisioningStatusCallback)
+{
+
+    if (InProgress())
+        return false;
+
+    cbData = provisioningStatusCallback;
+
+    return true;
+}
+
+bool ResetProgress()
+{
+
+    cbData = NULL;
+    return true;
+}
+
+ProvisioningInfo *CreateCallBackObject()
+{
+
+    ProvisioningInfo *provInfo = (ProvisioningInfo *) OICCalloc(1, sizeof(ProvisioningInfo));
+
+    if (provInfo == NULL)
+    {
+        OIC_LOG_V(ERROR, ES_PROV_TAG, "Failed to allocate memory");
+        return NULL;
+    }
+
+    OCDevAddr *devAddr = (OCDevAddr *) OICCalloc(1, sizeof(OCDevAddr));
+
+    if (devAddr == NULL)
+    {
+        OIC_LOG_V(ERROR, ES_PROV_TAG, "Failed to allocate memory");
+        OICFree(provInfo);
+        return NULL;
+    }
+
+    provInfo->provDeviceInfo.addr = devAddr;
+
+    return provInfo;
+
+}
+
+ProvisioningInfo *GetCallbackObjectOnError(ProvStatus status)
+{
+
+    ProvisioningInfo *provInfo = CreateCallBackObject();
+    OICStrcpy(provInfo->provDeviceInfo.addr->addr, sizeof(provInfo->provDeviceInfo.addr->addr),
+            gOnboardConn->ipAddress);
+
+    provInfo->provDeviceInfo.addr->port = IP_PORT;
+    provInfo->provStatus = status;
+    return provInfo;
+}
+
+ProvisioningInfo *GetCallbackObjectOnSuccess(OCClientResponse *clientResponse,
+        ProvStatus provStatus)
+{
+    ProvisioningInfo *provInfo = CreateCallBackObject();
+    OICStrcpy(provInfo->provDeviceInfo.addr->addr, sizeof(provInfo->provDeviceInfo.addr->addr),
+            clientResponse->addr->addr);
+
+    provInfo->provDeviceInfo.addr->port = clientResponse->addr->port;
+    provInfo->provStatus = provStatus;
+    return provInfo;
+}
+
+bool ValidateFindResourceResponse(OCClientResponse * clientResponse)
+{
+    if (!(clientResponse) || !(clientResponse->payload))
+    {
+        OIC_LOG_V(INFO, ES_PROV_TAG, "Received Null clientResponse");
+        return false;
+    }
+
+    if (clientResponse->payload->type != PAYLOAD_TYPE_DISCOVERY)
+    {
+        OIC_LOG_V(DEBUG, ES_PROV_TAG, "Payload is not discovery type");
+        return false;
+    }
+
+    return true;
+}
+
+bool ValidateEnrolleeResponse(OCClientResponse * clientResponse)
+{
+    if (!(clientResponse) || !(clientResponse->payload))
+    {
+        OIC_LOG_V(INFO, ES_PROV_TAG, "Received Null clientResponse");
+        return false;
+    }
+
+    if (clientResponse->payload->type != PAYLOAD_TYPE_REPRESENTATION)
+    {
+        OIC_LOG_V(DEBUG, ES_PROV_TAG, "Incoming payload is not a representation");
+        return false;
+    }
+
+    // If flow reachese here means no error condition hit.
+    return true;
+}
+
+bool ValidateEnrolleeBasicResponse(OCClientResponse * clientResponse)
+{
+    if (!clientResponse)
+    {
+        OIC_LOG_V(INFO, ES_PROV_TAG, "Received Null clientResponse");
+        return false;
+    }
+
+    if(clientResponse->result != OC_STACK_OK)
+    {
+        OIC_LOG_V(INFO, ES_PROV_TAG, "Received error response");
+        return false;
+    }
+
+    // If flow reaches, then there no error condition hit.
+    return true;
+}
+
+
+void SuccessCallback(OCClientResponse * clientResponse)
+{
+    ProvisioningInfo *provInfo = GetCallbackObjectOnSuccess(clientResponse, DEVICE_PROVISIONED);
+    if(cbData != NULL)
+    {
+        cbData(provInfo);
+    }
+}
+
+void* FindProvisioningResource(void* /*data*/)
+{
+
+    // If user stopped the process before thread get scheduled then check and return from this function;
+    if (IsSetupStopped())
+    {
+        ErrorCallback(DEVICE_NOT_PROVISIONED);
+        ClearMemory();
+        return NULL;
+    }
+
+    OCStackResult ret = OC_STACK_ERROR;
+
+    OIC_LOG_V(DEBUG, ES_PROV_TAG, "szFindResourceQueryUri = %s", gSzFindResourceQueryUri);
+
+    OCCallbackData ocCBData;
+
+    ocCBData.cb = FindProvisioningResourceResponse;
+    ocCBData.context = (void *) EASY_SETUP_DEFAULT_CONTEXT_VALUE;
+    ocCBData.cd = NULL;
+
+    ret = OCDoResource(NULL, OC_REST_DISCOVER, gSzFindResourceQueryUri, NULL, NULL,
+            gProvConfig->connType, OC_LOW_QOS, &ocCBData, NULL, 0);
+
+    if (ret != OC_STACK_OK)
+    {
+        ErrorCallback(DEVICE_NOT_PROVISIONED);
+        ClearMemory();
+    }
+
+    return NULL;
+}
+
+OCStackResult InvokeOCDoResource(const char *query, OCMethod method, const OCDevAddr *dest,
+        OCQualityOfService qos, OCClientResponseHandler cb, OCRepPayload *payload,
+        OCHeaderOption *options, uint8_t numOptions)
+{
+    OCStackResult ret;
+    OCCallbackData cbData;
+
+    cbData.cb = cb;
+    cbData.context = (void *) EASY_SETUP_DEFAULT_CONTEXT_VALUE;
+    cbData.cd = NULL;
+
+    ret = OCDoResource(NULL, method, query, dest, (OCPayload *) payload, gProvConfig->connType, qos,
+            &cbData, options, numOptions);
+
+    if (ret != OC_STACK_OK)
+    {
+        OIC_LOG_V(ERROR, ES_PROV_TAG, "OCDoResource returns error %d with method %d", ret, method);
+    }
+
+    return ret;
+}
+
+OCStackResult ProvisionEnrollee(OCQualityOfService qos, const char *query, const char *resUri,
+        OCDevAddr *destination, int pauseBeforeStart)
+{
+
+    // This sleep is required in case of BLE provisioning due to packet drop issue.
+    OIC_LOG_V(INFO, ES_PROV_TAG, "Sleeping for %d seconds", pauseBeforeStart);
+    sleep(pauseBeforeStart);
+    OIC_LOG_V(INFO, ES_PROV_TAG, "\n\nExecuting ProvisionEnrollee%s", __func__);
+
+    OCRepPayload *payload = OCRepPayloadCreate();
+
+    OCRepPayloadSetUri(payload, resUri);
+    OCRepPayloadSetPropString(payload, OC_RSRVD_ES_TNN, gProvConfig->provData.WIFI.ssid);
+    OCRepPayloadSetPropString(payload, OC_RSRVD_ES_CD, gProvConfig->provData.WIFI.pwd);
+
+    OIC_LOG_V(DEBUG, ES_PROV_TAG, "OCPayload ready for ProvisionEnrollee");
+
+    OCStackResult ret = InvokeOCDoResource(query, OC_REST_POST, destination, qos,
+            ProvisionEnrolleeResponse, payload, NULL, 0);
+
+    return ret;
+}
+
+bool IsSetupStopped()
+{
+    return (cbData == NULL) ? true : false;
+}
diff --git a/service/easy-setup/mediator/csdk/src/provisioningapi.cpp b/service/easy-setup/mediator/csdk/src/provisioningapi.cpp
new file mode 100755 (executable)
index 0000000..988921e
--- /dev/null
@@ -0,0 +1,127 @@
+//******************************************************************
+//
+// 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 <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <signal.h>
+#include <unistd.h>
+#include <stdint.h>
+#include <sstream>
+
+#include "provisioningapi.h"
+#include "oic_string.h"
+
+#define ES_PROV_ADAP_TAG "ES_PROVISIONING_ADAPTER"
+
+//Use ipv4addr for both InitDiscovery and InitDeviceDiscovery
+char ipv4addr[IPV4_ADDR_SIZE] =
+{ 0 };
+
+#ifdef REMOTE_ARDUINO_ENROLEE
+//Arduino Enrollee needs mediator application provide IP and port55555 which is specific
+// to Arduino WiFi enrollee
+static const char * UNICAST_PROVISIONING_QUERY = "coap://%s:%d/oic/res?rt=oic.r.prov";
+#else
+static const char * UNICAST_PROVISIONING_QUERY = "/oic/res?rt=oic.r.prov";
+#endif
+
+volatile static OCProvisioningStatusCB cbData = NULL;
+
+OCStackResult InitProvProcess()
+{
+
+    OCStackResult result = OC_STACK_ERROR;
+
+    if (InitProvisioningHandler() == OC_STACK_OK)
+    {
+        result = OC_STACK_OK;
+        OIC_LOG(DEBUG, ES_PROV_ADAP_TAG, "InitProvisioningHandler returned Success");
+    }
+    else
+    {
+        result = OC_STACK_ERROR;
+        OIC_LOG_V(ERROR, ES_PROV_ADAP_TAG, "InitProvisioningHandler returned error = %d",
+                result);
+    }
+
+    return result;
+}
+
+OCStackResult ResetProvProcess()
+{
+    return TerminateProvisioningHandler();
+}
+
+OCStackResult RegisterCallback(OCProvisioningStatusCB provisioningStatusCallback)
+{
+    OCStackResult result = OC_STACK_OK;
+
+    if (provisioningStatusCallback != NULL)
+    {
+        cbData = provisioningStatusCallback;
+    }
+    else
+    {
+        result = OC_STACK_ERROR;
+        OIC_LOG(ERROR, ES_PROV_ADAP_TAG, "provisioningStatusCallback is NULL");
+    }
+
+    return result;
+}
+
+void UnRegisterCallback()
+{
+    if (cbData)
+    {
+        cbData = NULL;
+    }
+}
+
+OCStackResult StartProvisioning(const ProvConfig *provConfig, WiFiOnboadingConnection *onboardConn)
+{
+
+    char findQuery[64] =
+    { 0 };
+
+    if (provConfig == NULL || onboardConn == NULL)
+    {
+        return OC_STACK_ERROR;
+    }
+
+#ifdef REMOTE_ARDUINO_ENROLEE
+    //Arduino Enrollee needs mediator application provide IP and port55555 which is specific
+    // to Arduino WiFi enrollee
+    snprintf(findQuery, sizeof(findQuery) - 1, UNICAST_PROVISIONING_QUERY,
+            onboardConn->ipAddress, IP_PORT);
+#else
+    OICStrcpy(findQuery, sizeof(findQuery) - 1, UNICAST_PROVISIONING_QUERY);
+#endif
+
+    return StartProvisioningProcess(provConfig, onboardConn, cbData, findQuery);
+}
+
+OCStackResult StopProvisioning(OCConnectivityType /*connectivityType*/)
+{
+    OCStackResult result = OC_STACK_OK;
+
+    StopProvisioningProcess();
+
+    return result;
+}
diff --git a/service/easy-setup/mediator/csdk/src/wifiprovisioning.cpp b/service/easy-setup/mediator/csdk/src/wifiprovisioning.cpp
new file mode 100755 (executable)
index 0000000..d8d40fe
--- /dev/null
@@ -0,0 +1,274 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+// NOTE : Keeping Wifi provisioning in this file to have adaptability while doing OOPs refactoring
+
+#include "provisioning.h"
+
+//Standard includes
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <signal.h>
+#include <unistd.h>
+#include <pthread.h>
+
+//EasySetup include files
+#include "ocpayload.h"
+#include "escommon.h"
+
+// External includes
+#include "logger.h"
+#include "oic_string.h"
+
+#define ES_WIFI_PROV_TAG "ES_WIFI_PROVISIONING"
+
+static const char * UNICAST_PROV_STATUS_QUERY = "coap://%s:%d%s";
+
+OCStackApplicationResult ProvisionEnrolleeResponse(void* /*ctx*/, OCDoHandle /*handle*/,
+        OCClientResponse *clientResponse)
+{
+    OIC_LOG_V(DEBUG, ES_WIFI_PROV_TAG, "Inside ProvisionEnrolleeResponse");
+
+    // If user stopped the process then return from this function;
+    if (IsSetupStopped())
+    {
+        ErrorCallback(DEVICE_NOT_PROVISIONED);
+        ClearMemory();
+        return OC_STACK_DELETE_TRANSACTION;
+    }
+
+    if (!ValidateEnrolleeResponse(clientResponse))
+    {
+        ErrorCallback(DEVICE_NOT_PROVISIONED);
+        return OC_STACK_DELETE_TRANSACTION;
+    }
+
+    char query[OIC_STRING_MAX_VALUE] =
+    { '\0' };
+    char resUri[MAX_URI_LENGTH] =
+    { '\0' };
+
+    OIC_LOG_V(DEBUG, ES_WIFI_PROV_TAG, "Resource URI = %s", clientResponse->resourceUri);
+
+    OICStrcpy(resUri, sizeof(resUri), clientResponse->resourceUri);
+
+#ifdef REMOTE_ARDUINO_ENROLEE
+    //Arduino Enrollee needs mediator application provide IP and port55555 which is specific
+    // to Arduino WiFi enrollee
+    // REMOTE_ARDUINO_ENROLEE has to be defined if Mediator is being tested with Arduino
+    snprintf(query, sizeof(query), UNICAST_PROV_STATUS_QUERY, clientResponse->addr->addr, IP_PORT,
+            resUri);
+#else
+    snprintf(query, sizeof(query), UNICAST_PROV_STATUS_QUERY, clientResponse->addr->addr,
+            clientResponse->addr->port, resUri);
+#endif
+
+    if (TriggerNetworkConnection(OC_HIGH_QOS, query, OC_RSRVD_ES_URI_PROV, clientResponse->addr, 0)
+            != OC_STACK_OK)
+    {
+        OIC_LOG(INFO, ES_WIFI_PROV_TAG, "GetProvisioningStatusResponse received NULL clientResponse");
+
+        ErrorCallback(DEVICE_NOT_PROVISIONED);
+        ClearMemory();
+    }
+
+    return OC_STACK_DELETE_TRANSACTION;
+}
+
+OCStackApplicationResult GetProvisioningStatusResponse(void* /*ctx*/, OCDoHandle /*handle*/,
+        OCClientResponse *clientResponse)
+{
+    // If user stopped the process then return from this function;
+    if (IsSetupStopped())
+    {
+        ErrorCallback(DEVICE_NOT_PROVISIONED);
+        ClearMemory();
+        return OC_STACK_DELETE_TRANSACTION;
+    }
+
+    if (!ValidateEnrolleeResponse(clientResponse))
+    {
+        ErrorCallback(DEVICE_NOT_PROVISIONED);
+        ClearMemory();
+        return OC_STACK_DELETE_TRANSACTION;
+    }
+
+    OCRepPayload *input = (OCRepPayload *) (clientResponse->payload);
+
+    char resUri[MAX_URI_LENGTH] = { '\0' };
+
+    OIC_LOG_V(DEBUG, ES_WIFI_PROV_TAG, "resUri = %s", clientResponse->resourceUri);
+
+    OICStrcpy(resUri, sizeof(resUri), clientResponse->resourceUri);
+
+    while (input)
+    {
+        int64_t ps;
+        if (OCRepPayloadGetPropInt(input, OC_RSRVD_ES_PS, &ps))
+        {
+
+            if (ps == ES_PS_NEED_PROVISIONING)
+            {
+                input = input->next;
+                continue;
+            }
+            else
+            {
+                ErrorCallback(DEVICE_NOT_PROVISIONED);
+                ClearMemory();
+                return OC_STACK_DELETE_TRANSACTION;
+            }
+        }
+
+        LogProvisioningResponse(input->values);
+        input = input->next;
+    }
+
+    char query[OIC_STRING_MAX_VALUE] =
+    { '\0' };
+
+#ifdef REMOTE_ARDUINO_ENROLEE
+    //Arduino Enrollee needs mediator application provide IP and port55555 which is specific
+    // to Arduino WiFi enrollee
+    // REMOTE_ARDUINO_ENROLEE has to be defined if Mediator is being tested with Arduino
+    snprintf(query, sizeof(query), UNICAST_PROV_STATUS_QUERY, clientResponse->addr->addr, IP_PORT,
+            resUri);
+#else
+    snprintf(query, sizeof(query), UNICAST_PROV_STATUS_QUERY, clientResponse->addr->addr,
+            clientResponse->addr->port, resUri);
+#endif
+
+    if (ProvisionEnrollee(OC_HIGH_QOS, query, OC_RSRVD_ES_URI_PROV, clientResponse->addr, 0)
+            != OC_STACK_OK)
+    {
+        OIC_LOG(INFO, ES_WIFI_PROV_TAG, "GetProvisioningStatusResponse received NULL clientResponse");
+
+        ErrorCallback(DEVICE_NOT_PROVISIONED);
+        ClearMemory();
+        return OC_STACK_DELETE_TRANSACTION;
+    }
+
+    return OC_STACK_KEEP_TRANSACTION;
+
+}
+
+OCStackResult GetProvisioningStatus(OCQualityOfService qos, const char *query,
+        const OCDevAddr *destination)
+{
+    OCStackResult ret = OC_STACK_ERROR;
+    OCHeaderOption options[MAX_HEADER_OPTIONS];
+
+    OIC_LOG(DEBUG, ES_WIFI_PROV_TAG, "Inside GetProvisioningStatus");
+
+    uint8_t option0[] =
+    { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
+    uint8_t option1[] =
+    { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
+    memset(options, 0, sizeof(OCHeaderOption) * MAX_HEADER_OPTIONS);
+    options[0].protocolID = OC_COAP_ID;
+    options[0].optionID = 2048;
+    memcpy(options[0].optionData, option0, sizeof(option0));
+    options[0].optionLength = 10;
+    options[1].protocolID = OC_COAP_ID;
+    options[1].optionID = 3000;
+    memcpy(options[1].optionData, option1, sizeof(option1));
+    options[1].optionLength = 10;
+
+    ret = InvokeOCDoResource(query, OC_REST_GET, destination, qos, GetProvisioningStatusResponse,
+    NULL, options, 2);
+    return ret;
+}
+
+// This is a function called back when a device is discovered
+OCStackApplicationResult FindProvisioningResourceResponse(void* /*ctx*/, OCDoHandle /*handle*/,
+        OCClientResponse *clientResponse)
+{
+
+    OIC_LOG_V(INFO, ES_WIFI_PROV_TAG, "Entering FindProvisioningResourceResponse %s",
+            clientResponse->devAddr.addr);
+
+    // If user stopped the process then return from this function;
+    if (IsSetupStopped())
+    {
+        ErrorCallback(DEVICE_NOT_PROVISIONED);
+        ClearMemory();
+        return OC_STACK_DELETE_TRANSACTION;
+    }
+
+    if (!ValidateFindResourceResponse(clientResponse))
+    {
+        ErrorCallback(DEVICE_NOT_PROVISIONED);
+        return OC_STACK_DELETE_TRANSACTION;
+    }
+
+    char szQueryUri[64] =
+    { 0 };
+
+    OCDiscoveryPayload *discoveryPayload = (OCDiscoveryPayload *) (clientResponse->payload);
+
+    OIC_LOG_V(DEBUG, ES_WIFI_PROV_TAG, "resUri = %s", discoveryPayload->resources->uri);
+
+#ifdef REMOTE_ARDUINO_ENROLEE
+    //Arduino Enrollee needs mediator application provide IP and port55555 which is specific
+    // to Arduino WiFi enrollee
+    // REMOTE_ARDUINO_ENROLEE has to be defined if Mediator is being tested with Arduino
+    snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_PROV_STATUS_QUERY,
+            clientResponse->addr->addr,
+            IP_PORT,
+            discoveryPayload->resources->uri);
+#else
+    snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_PROV_STATUS_QUERY,
+            clientResponse->devAddr.addr, clientResponse->devAddr.port,
+            discoveryPayload->resources->uri);
+#endif
+
+    OIC_LOG_V(DEBUG, ES_WIFI_PROV_TAG, "query before GetProvisioningStatus call = %s", szQueryUri);
+
+    if (GetProvisioningStatus(OC_HIGH_QOS, szQueryUri, &clientResponse->devAddr) != OC_STACK_OK)
+    {
+        ErrorCallback(DEVICE_NOT_PROVISIONED);
+        return OC_STACK_DELETE_TRANSACTION;
+    }
+
+    return OC_STACK_KEEP_TRANSACTION;
+
+}
+
+bool ValidateEasySetupParams(const ProvConfig */*netInfo*/, WiFiOnboadingConnection *onboardConn,
+        OCProvisioningStatusCB provisioningStatusCallback)
+{
+
+    if (onboardConn == NULL || strlen(onboardConn->ipAddress) == 0)
+    {
+        OIC_LOG(ERROR, ES_WIFI_PROV_TAG, "Request URI is NULL");
+        return false;
+    }
+
+    if (provisioningStatusCallback == NULL)
+    {
+        OIC_LOG(ERROR, ES_WIFI_PROV_TAG, "ProvisioningStatusCallback is NULL");
+        return false;
+    }
+
+    return true;
+
+}
+
diff --git a/service/easy-setup/mediator/csdk/unittests/MediatorCSDKTest.cpp b/service/easy-setup/mediator/csdk/unittests/MediatorCSDKTest.cpp
new file mode 100644 (file)
index 0000000..9c0c57a
--- /dev/null
@@ -0,0 +1,124 @@
+//******************************************************************
+//
+// 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 "UnitTestHelper.h"
+
+#include "ocstack.h"
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "oic_string.h"
+#include "logger.h"
+
+#include "provisioningapi.h"
+#include "provisioning.h"
+#include "escommon.h"
+
+#include <iostream>
+#include <string.h>
+#include <functional>
+#include <pthread.h>
+#include <condition_variable>
+
+class MediatorCSDKTest: public TestWithMock
+{
+
+    protected:
+        void SetUp()
+        {
+            TestWithMock::SetUp();
+        }
+
+        void TearDown()
+        {
+            TestWithMock::TearDown();
+        }
+
+};
+
+//callbacks
+void OCProvisioningStatusCallback(EasySetupInfo  *easySetupInfo) 
+{
+    (void) easySetupInfo;
+}
+
+/* Test cases for prov_adapter*/
+
+//InitProvProcess
+TEST_F(MediatorCSDKTest, testInitProvProcess)
+{
+    OCStackResult result = InitProvProcess();
+    ASSERT_EQ(OC_STACK_OK, result);
+}
+
+//ResetProvProcess
+TEST_F(MediatorCSDKTest, testResetProvProcess)
+{
+    OCStackResult result = ResetProvProcess();
+    ASSERT_EQ(OC_STACK_OK, result);
+}
+
+//RegisterCallback [positive]
+TEST_F(MediatorCSDKTest, testRegisterCallback)
+{
+    OCStackResult result = RegisterCallback(&OCProvisioningStatusCallback);
+    ASSERT_EQ(OC_STACK_OK, result);
+}
+
+//RegisterCallback [Negative]
+TEST_F(MediatorCSDKTest, testRegisterCallbackNegative)
+{
+    OCStackResult result = RegisterCallback(NULL);
+    ASSERT_EQ(OC_STACK_ERROR, result);
+}
+
+//StartProvisioning [positive]
+TEST_F(MediatorCSDKTest, testStartProvisioning)
+{
+    ProvConfig provConfig;
+    WiFiOnboadingConnection onboardConn;
+
+    strncpy(onboardConn.ipAddress, "1.1.1.1", IPV4_ADDR_SIZE - 1);
+
+    strncpy(provConfig.provData.WIFI.ssid, "testAP", NET_WIFI_SSID_SIZE - 1);
+    strncpy(provConfig.provData.WIFI.pwd, "test@123", NET_WIFI_PWD_SIZE - 1);
+    provConfig.connType = CT_ADAPTER_IP;
+
+    //API Call
+    OCStackResult result =    StartProvisioning(&provConfig, &onboardConn);
+
+    ASSERT_EQ(OC_STACK_OK, result);
+}
+
+//StartProvisioning [Negative]
+TEST_F(MediatorCSDKTest, testStartProvisioningNegative)
+{
+    OCStackResult result = StartProvisioning(NULL, NULL);
+    ASSERT_EQ(OC_STACK_ERROR, result);
+}
+
+//StopProvisioning
+TEST_F(MediatorCSDKTest, testStopProvisioning)
+{
+    // This API always return success
+    OCStackResult result = StopProvisioning(CT_ADAPTER_IP);
+    ASSERT_EQ(OC_STACK_OK, result);
+}
+
+
diff --git a/service/easy-setup/mediator/csdk/unittests/SConscript b/service/easy-setup/mediator/csdk/unittests/SConscript
new file mode 100644 (file)
index 0000000..734f051
--- /dev/null
@@ -0,0 +1,103 @@
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+##
+# Mediator[CSDK] Unit Test build script
+##
+import os
+Import('env')
+
+if env.get('RELEASE'):
+    env.AppendUnique(CCFLAGS = ['-Os'])
+    env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+else:
+    env.AppendUnique(CCFLAGS = ['-g'])
+
+if env.get('LOGGING'):
+    env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+# Add third party libraries
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+
+target_os = env.get('TARGET_OS')
+if target_os == 'linux':
+    # Verify that 'google unit test' library is installed.  If not,
+    # get it and install it
+    SConscript(env.get('SRC_DIR') + '/extlibs/gtest/SConscript')
+
+    # Verify that 'hippomocks' mocking code is installed.  If not,
+    # get it and install it
+    SConscript(env.get('SRC_DIR') + '/extlibs/hippomocks.scons')
+
+mediator_csdk_test_env = lib_env.Clone()
+
+######################################################################
+#unit test setting
+######################################################################
+src_dir = lib_env.get('SRC_DIR')
+gtest_dir = src_dir + '/extlibs/gtest/gtest-1.7.0'
+
+######################################################################
+# Build flags
+######################################################################
+gtest = File(gtest_dir + '/lib/.libs/libgtest.a')
+gtest_main = File(gtest_dir + '/lib/.libs/libgtest_main.a')
+
+mediator_csdk_test_env.AppendUnique(
+        CPPPATH = [
+                src_dir + '/extlibs/hippomocks-master',
+                src_dir + '/extlibs/gtest/gtest-1.7.0/include',
+                '../inc',
+                '../../../inc',
+        ])
+
+if target_os not in ['windows', 'winrt']:
+        mediator_csdk_test_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
+        if target_os != 'android':
+                mediator_csdk_test_env.AppendUnique(CXXFLAGS = ['-pthread'])
+                mediator_csdk_test_env.AppendUnique(LIBS = ['pthread'])
+
+mediator_csdk_test_env.PrependUnique(LIBS = [
+    'ESMediatorCSDK',
+    'oc',
+    'octbstack',
+    'oc_logger',
+    'oc_logger_core',
+    'connectivity_abstraction',
+    gtest,
+    gtest_main])
+
+mediator_csdk_test_env.AppendUnique(LIBS = ['dl'])
+
+######################################################################
+# Build Test
+######################################################################
+mediator_csdk_test_src = env.Glob('./*.cpp')
+
+mediator_csdk_test = mediator_csdk_test_env.Program('mediator_csdk_test', mediator_csdk_test_src)
+Alias("mediator_csdk_test", mediator_csdk_test)
+env.AppendTarget('mediator_csdk_test')
+
+if env.get('TEST') == '1':
+    target_os = env.get('TARGET_OS')
+    if target_os == 'linux':
+        from tools.scons.RunTest import *
+        run_test(mediator_csdk_test_env, '', 'service/easy-setup/mediator/csdk/unittests/mediator_csdk_test')
\ No newline at end of file
diff --git a/service/easy-setup/mediator/csdk/unittests/UnitTestHelper.h b/service/easy-setup/mediator/csdk/unittests/UnitTestHelper.h
new file mode 100644 (file)
index 0000000..2bf7424
--- /dev/null
@@ -0,0 +1,48 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef COMMON_UTILS_UNITTESTHELPER_H
+#define COMMON_UTILS_UNITTESTHELPER_H
+
+#include <gtest/gtest.h>
+#include <HippoMocks/hippomocks.h>
+
+class TestWithMock: public testing::Test
+{
+    public:
+        MockRepository mocks;
+
+    protected:
+        virtual ~TestWithMock() noexcept(noexcept(std::declval<Test>().~Test())) {}
+
+        virtual void TearDown()
+        {
+            try
+            {
+                mocks.VerifyAll();
+            }
+            catch (...)
+            {
+                mocks.reset();
+                throw;
+            }
+        }
+};
+#endif // COMMON_UTILS_UNITTESTHELPER_H
diff --git a/service/easy-setup/mediator/richsdk/SConscript b/service/easy-setup/mediator/richsdk/SConscript
new file mode 100644 (file)
index 0000000..f631761
--- /dev/null
@@ -0,0 +1,143 @@
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+######################################################################
+# easy-setup Mediator C++[Rich] SDK build script
+######################################################################
+import os.path
+Import('env')
+
+easysetup_path = os.curdir
+
+if env.get('RELEASE'):
+    env.AppendUnique(CCFLAGS = ['-Os'])
+    env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+else:
+    env.AppendUnique(CCFLAGS = ['-g'])
+
+if env.get('LOGGING'):
+    env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+# Easysetup provides reference implemenation of Arduino Enrollee.
+# Mediator applications developed on different platforms will be default defining the
+# flag 'REMOTE_ARDUINO_ENROLEE'. If the target Enrollee is not Arduino, the below commented
+# modifications must be enabled instead (and the existing define must be commented).
+#
+##### The following lines must be uncommented, if target Enrollee is not Arduino
+target_enrollee = env.get('ES_TARGET_ENROLLEE')
+if target_enrollee == 'arduino':
+       print "REMOTE_ARDUINO_ENROLEE flag is defined."
+       print "The Mediator application will be working only with Arduino Enrollee."
+       env.AppendUnique(CPPDEFINES = ['REMOTE_ARDUINO_ENROLEE'])
+
+# Add third party libraries
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+
+easy_setup_env = lib_env.Clone()
+target_os = env.get('TARGET_OS')
+
+######################################################################
+# Build flags
+######################################################################
+easy_setup_env.AppendUnique(CPPPATH = ['inc', 'src', '../../inc'])
+
+if target_os not in ['windows', 'winrt']:
+    easy_setup_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x'])
+
+if target_os in ['linux']:
+   easy_setup_env.AppendUnique(LIBS = ['pthread', 'dl'])
+
+if target_os in ['android']:
+       easy_setup_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+       if env.get('SECURED') == '1':
+               easy_setup_env.AppendUnique(LIBPATH = [env.get('SRC_DIR')+'/android/android_api/base/libs/armeabi'])
+       easy_setup_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
+       easy_setup_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
+       easy_setup_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'gnustl_shared'])
+       if env.get('SECURED') == '1':
+               easy_setup_env.AppendUnique(LIBS = ['ocpmapi','ocprovision'])
+       if not env.get('RELEASE'):
+               easy_setup_env.AppendUnique(LIBS = ['log'])
+
+if target_os in ['linux']:
+       easy_setup_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+       easy_setup_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
+       easy_setup_env.AppendUnique(CXXFLAGS = ['-pthread'])
+       easy_setup_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'pthread', 'connectivity_abstraction'])
+       if env.get('SECURED') == '1':
+               easy_setup_env.AppendUnique(LIBS = ['ocpmapi', 'ocprovision'])
+
+if target_os in ['android','linux']:
+       easy_setup_env.PrependUnique(CPPPATH = [
+               env.get('SRC_DIR') + '/resource/c_common/oic_malloc/include',
+               env.get('SRC_DIR') + '/resource/include',
+               env.get('SRC_DIR') + '/resource/csdk/logger/include',
+               env.get('SRC_DIR') + '/resource/csdk/stack/include',
+               env.get('SRC_DIR') + '/resource/csdk/logger/include',
+               env.get('SRC_DIR') + '/resource/csdk/security/include',
+               env.get('SRC_DIR') + '/extlibs/cjson',
+               env.get('SRC_DIR') + '/extlibs/sqlite3',
+               env.get('SRC_DIR') + '/service/easy-setup/inc',
+               'inc'])
+       if env.get('SECURED') == '1':
+               easy_setup_env.AppendUnique(CPPPATH = [
+                       env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include',
+                       env.get('SRC_DIR') + '/resource/csdk/connectivity/api/',
+                       env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include/internal',
+                       env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include/oxm'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+
+
+print"easysetup_path %s" % easysetup_path
+
+es_src = None
+
+if target_os in ['android','linux']:
+       if env.get('SECURED') == '1':
+               env.AppendUnique(es_src = [os.path.join(easysetup_path, 'src/EnrolleeSecurity.cpp')])
+
+       es_common_src = ['src/RemoteEnrollee.cpp',
+               'src/RemoteEnrolleeResource.cpp',
+               'src/EasySetup.cpp',
+               'src/ESException.cpp']
+
+       env.AppendUnique(es_src = es_common_src)
+
+       es_sdk_shared = easy_setup_env.SharedLibrary('ESMediatorRich', env.get('es_src'))
+       easy_setup_env.InstallTarget(es_sdk_shared, 'libESMediatorRich')
+
+print "Files path is %s" % env.get('es_src')
+
+######################################################################
+# Build RichSDK Mediator Sample App
+################################################ ######################
+if target_os == 'linux':
+       SConscript('../../sampleapp/mediator/linux/richsdk_sample/SConscript')
+
+######################################################################
+#Build UnitTestcases for Mediator[RichSDK]
+################################################ ######################
+if target_os == 'linux':
+    SConscript('unittests/SConscript')
+
diff --git a/service/easy-setup/mediator/richsdk/android/EasySetupCore/build.gradle b/service/easy-setup/mediator/richsdk/android/EasySetupCore/build.gradle
new file mode 100644 (file)
index 0000000..778bce9
--- /dev/null
@@ -0,0 +1,36 @@
+apply plugin: 'com.android.library'
+// Top-level build file where you can add configuration options common to all sub-projects/modules.
+buildscript {
+    repositories {
+        jcenter()
+    }
+    dependencies {
+        classpath 'com.android.tools.build:gradle:1.2.3'
+    }
+}
+
+allprojects {
+    repositories {
+        jcenter()
+    }
+}
+
+android {
+    compileSdkVersion 21
+    buildToolsVersion '21.1.2'
+
+    defaultConfig {
+        minSdkVersion 21
+        targetSdkVersion 21
+    }
+
+    buildTypes {
+        release {
+            minifyEnabled false
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
+        }
+    }
+    sourceSets {
+        main { java.srcDirs = ['src/main/java', 'src/main/java/common', 'src/main/java/interface'] }
+    }
+}
\ No newline at end of file
diff --git a/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/EasySetupServiceConfigTest.java b/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/EasySetupServiceConfigTest.java
new file mode 100644 (file)
index 0000000..3ee90fd
--- /dev/null
@@ -0,0 +1,74 @@
+/**
+ * ***************************************************************
+ * <p/>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p/>
+ * <p/>
+ * <p/>
+ * 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
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * 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.
+ * <p/>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+import android.test.AndroidTestCase;
+
+
+public class EasySetupServiceConfigTest extends AndroidTestCase {
+
+
+    public void testConstruction() {
+
+        EasySetupService service = EasySetupService.getInstance(getContext(), new EasySetupStatus() {
+            @Override
+            public void onFinished(EnrolleeDevice enrolledevice) {
+
+            }
+
+            @Override
+            public void onProgress(EnrolleeDevice enrolleeDevice) {
+
+            }
+        });
+
+        assertTrue(service != null);
+
+
+    }
+
+    public void testFinish() {
+        EasySetupService service = EasySetupService.getInstance(getContext(), new EasySetupStatus() {
+            @Override
+            public void onFinished(EnrolleeDevice enrolledevice) {
+
+            }
+
+            @Override
+            public void onProgress(EnrolleeDevice enrolleeDevice) {
+
+            }
+        });
+        service.finish();
+
+        // No runtime exception is thrown means test is successful
+        assertTrue(true);
+
+    }
+
+    public void testEnrolleeDeviceFacotryConstruction() {
+        EnrolleeDeviceFactory factory = EnrolleeDeviceFactory.newInstance(getContext());
+        assertTrue(factory != null);
+    }
+
+}
diff --git a/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/EasySetupServiceTest.java b/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/EasySetupServiceTest.java
new file mode 100755 (executable)
index 0000000..5fb19cd
--- /dev/null
@@ -0,0 +1,158 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+package org.iotivity.service.easysetup.mediator;
+
+import android.net.wifi.WifiConfiguration;
+import android.test.AndroidTestCase;
+import android.util.Log;
+
+import java.io.IOException;
+
+public class EasySetupServiceTest extends AndroidTestCase {
+
+
+    public void testStartSetupWithWiFiOnboarding() {
+
+        EasySetupService mService;
+        EnrolleeDevice mDevice;
+        EnrolleeDeviceFactory mFactory;
+
+        final Object lock = new Object();
+
+
+        /* Create Easy Setup service */
+        mService = EasySetupService.getInstance(getContext(), new EasySetupStatus() {
+            @Override
+            public void onFinished(EnrolleeDevice enrolledevice) {
+
+                //countDownLatch.countDown();
+                Utility.toNotify(lock);
+
+                if (enrolledevice.isSetupSuccessful()) {
+
+                    if (enrolledevice.mOnBoardingConfig.getConnType() == WiFiOnBoardingConfig.ConnType.WiFi) {
+                        IpOnBoardingConnection conn = (IpOnBoardingConnection) enrolledevice.getConnection();
+                        String ip = conn.getIp();
+                        if (ip == null || ip.isEmpty()) {
+                            assertTrue(false);
+                            return;
+                        }
+                        String mac = conn.getHardwareAddress();
+                        if (mac == null || mac.isEmpty()) {
+                            assertTrue(false);
+                            return;
+                        }
+                        // Device configured successfully
+                        assertTrue(true);
+                    }
+
+                } else {
+                    assertTrue(false);
+                }
+            }
+
+            @Override
+            public void onProgress(EnrolleeDevice enrolleeDevice) {
+                // Handled in EasySetupStatusTest
+            }
+        });
+
+
+        /* Create On boarding configuration */
+        WiFiOnBoardingConfig mWiFiOnBoardingConfig = new WiFiOnBoardingConfig();
+        mWiFiOnBoardingConfig.setSSId("EasySetup123");
+        mWiFiOnBoardingConfig.setSharedKey("EasySetup123");
+        mWiFiOnBoardingConfig.setAuthAlgo(WifiConfiguration.AuthAlgorithm.OPEN);
+        mWiFiOnBoardingConfig.setKms(WifiConfiguration.KeyMgmt.WPA_PSK);
+
+        /* Create provisioning configuration */
+        WiFiProvConfig mWiFiProvConfig = new WiFiProvConfig("hub2.4G", "11112222");
+
+        /* Create enrolling device factory instance */
+        mFactory = EnrolleeDeviceFactory.newInstance(getContext());
+
+        /* Check if the factory created successfully */
+        assertTrue(mFactory != null);
+
+        /* Create enrolling device */
+        mDevice = mFactory.newEnrolleeDevice(mWiFiProvConfig, mWiFiOnBoardingConfig);
+
+        /* Check if the the device is created successfully*/
+        assertTrue(mDevice != null);
+
+        /* Check if the the correct device is created as per the given configuration*/
+        assertTrue((mDevice instanceof EnrolleeDeviceWiFiOnboarding));
+
+
+        try {
+            mService.startSetup(mDevice);
+            // If no exception is thrown means setup started successfully.
+            assertTrue(true);
+
+        } catch (IOException e) {
+            assertTrue(false);
+        }
+        catch (ESException e) {
+            assertTrue(false);
+        }
+
+        try {
+
+            Utility.toWait(lock);
+
+            Log.i("EasySetupTest", "Lock is released");
+
+            if (!mDevice.isSetupSuccessful()) {
+                assertTrue(false);
+                return;
+            }
+
+            IpOnBoardingConnection conn = (IpOnBoardingConnection) mDevice.getConnection();
+            if (conn == null) {
+                assertTrue(false);
+                return;
+            }
+
+            String ip = conn.getIp();
+            if (ip == null || ip.isEmpty()) {
+                assertTrue(false);
+                return;
+            }
+
+            String mac = conn.getHardwareAddress();
+            if (mac == null || mac.isEmpty()) {
+                assertTrue(false);
+                return;
+            }
+
+            Log.i("EasySetupTest", "Ip" + conn.getIp());
+            Log.i("EasySetupTest", "MAC" + conn.getHardwareAddress());
+
+            // Device configured successfully
+            assertTrue(true);
+
+        } catch (Exception e) {
+            e.printStackTrace();
+            assertTrue(false);
+        }
+
+    }
+
+}
\ No newline at end of file
diff --git a/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/EasySetupStatusTest.java b/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/EasySetupStatusTest.java
new file mode 100755 (executable)
index 0000000..f3d9d1a
--- /dev/null
@@ -0,0 +1,165 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+package org.iotivity.service.easysetup.mediator;
+
+import android.net.wifi.WifiConfiguration;
+import android.test.AndroidTestCase;
+import android.util.Log;
+
+import java.io.IOException;
+
+public class EasySetupStatusTest extends AndroidTestCase {
+
+
+    public void testStartSetupWithWiFiOnboarding() {
+
+        EasySetupService mService;
+        EnrolleeDevice mDevice;
+        EnrolleeDeviceFactory mFactory;
+
+        final Object lock = new Object();
+
+
+        /* Create Easy Setup service */
+        mService = EasySetupService.getInstance(getContext(), new EasySetupStatus() {
+            EnrolleeState old_state = null;
+
+            @Override
+            public void onFinished(EnrolleeDevice enrolledevice) {
+
+                //countDownLatch.countDown();
+                Utility.toNotify(lock);
+
+                if (enrolledevice.isSetupSuccessful()) {
+
+                    if (enrolledevice.mOnBoardingConfig.getConnType() == WiFiOnBoardingConfig.ConnType.WiFi) {
+                        IpOnBoardingConnection conn = (IpOnBoardingConnection) enrolledevice.getConnection();
+                        String ip = conn.getIp();
+                        if (ip == null || ip.isEmpty()) {
+                            assertTrue(false);
+                            return;
+                        }
+                        String mac = conn.getHardwareAddress();
+                        if (mac == null || mac.isEmpty()) {
+                            assertTrue(false);
+                            return;
+                        }
+                        // Device configured successfully
+                        assertTrue(true);
+                    }
+
+                } else {
+                    assertTrue(false);
+                }
+            }
+
+            @Override
+            public void onProgress(EnrolleeDevice enrolleeDevice) {
+                EnrolleeState state = enrolleeDevice.mState;
+                // TODO
+                switch (state) {
+                    case DEVICE_INIT_STATE:
+                        Log.d("enrollee state", "DEVICE_INIT_STATE");
+                        assertTrue(false);
+                        break;
+                    case DEVICE_ON_BOARDING_STATE:
+                        if (old_state == null)
+                            assertTrue(true);
+                        else assertTrue(false);
+                        old_state = EnrolleeState.DEVICE_ON_BOARDING_STATE;
+                        Log.d("enrollee state", "DEVICE_ON_BOARDING_STATE");
+                        break;
+
+                    case DEVICE_ON_BOARDED_STATE:
+                        if (old_state == EnrolleeState.DEVICE_ON_BOARDING_STATE)
+                            assertTrue(true);
+                        else assertTrue(false);
+                        old_state = EnrolleeState.DEVICE_ON_BOARDED_STATE;
+                        Log.d("enrollee state", "DEVICE_ON_BOARDED_STATE");
+                        break;
+
+                    case DEVICE_PROVISIONING_STATE:
+                        if (old_state == EnrolleeState.DEVICE_ON_BOARDED_STATE)
+                            assertTrue(true);
+                        else assertTrue(false);
+                        old_state = EnrolleeState.DEVICE_PROVISIONING_STATE;
+                        Log.d("enrollee state", "DEVICE_PROVISIONING_STATE");
+                        break;
+
+                    case DEVICE_PROVISIONED_STATE:
+                        if (old_state == EnrolleeState.DEVICE_PROVISIONING_STATE)
+                            assertTrue(true);
+                        else assertTrue(false);
+                        Log.d("enrollee state", "DEVICE_PROVISIONING_SUCCESS_STATE");
+                        break;
+
+                    default:
+                        Log.d("enrollee state", "unknown state");
+                        assertTrue(false);
+                        break;
+                }
+
+            }
+        });
+
+
+        /* Create On boarding configuration */
+        WiFiOnBoardingConfig mWiFiOnBoardingConfig = new WiFiOnBoardingConfig();
+        mWiFiOnBoardingConfig.setSSId("EasySetup123");
+        mWiFiOnBoardingConfig.setSharedKey("EasySetup123");
+        mWiFiOnBoardingConfig.setAuthAlgo(WifiConfiguration.AuthAlgorithm.OPEN);
+        mWiFiOnBoardingConfig.setKms(WifiConfiguration.KeyMgmt.WPA_PSK);
+
+        /* Create provisioning configuration */
+        WiFiProvConfig mWiFiProvConfig = new WiFiProvConfig("hub2.4G", "11112222");
+
+        /* Create enrolling device factory instance */
+        mFactory = EnrolleeDeviceFactory.newInstance(getContext());
+
+        /* Create enrolling device */
+        mDevice = mFactory.newEnrolleeDevice(mWiFiProvConfig, mWiFiOnBoardingConfig);
+
+        try {
+            mService.startSetup(mDevice);
+        } catch (ESException e) {
+        }
+        catch (IOException e) {
+        }
+
+        try {
+
+            Utility.toWait(lock);
+
+            Log.i("EasySetupTest", "Lock is released");
+
+            IpOnBoardingConnection conn = (IpOnBoardingConnection) mDevice.getConnection();
+
+            Log.i("EasySetupTest", "Ip" + conn.getIp());
+            Log.i("EasySetupTest", "MAC" + conn.getHardwareAddress());
+
+            // Device configured successfully
+
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+    }
+
+}
\ No newline at end of file
diff --git a/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/EnrolleeDeviceFactoryTest.java b/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/EnrolleeDeviceFactoryTest.java
new file mode 100755 (executable)
index 0000000..f513fa0
--- /dev/null
@@ -0,0 +1,70 @@
+/**
+ * ***************************************************************
+ * <p/>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p/>
+ * <p/>
+ * <p/>
+ * 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
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * 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.
+ * <p/>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+import android.net.wifi.WifiConfiguration;
+import android.test.AndroidTestCase;
+
+public class EnrolleeDeviceFactoryTest extends AndroidTestCase {
+
+    EnrolleeDeviceFactory mFactory;
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        mFactory = EnrolleeDeviceFactory.newInstance(getContext());
+        assertTrue(mFactory != null);
+
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        super.tearDown();
+        mFactory = null;
+    }
+
+
+    public void testNewEnrolleeDevice_with_WiFiOnboarding() {
+
+        /* Create On boarding configuration */
+        WiFiOnBoardingConfig mWiFiOnBoardingConfig = new WiFiOnBoardingConfig();
+        mWiFiOnBoardingConfig.setSSId("EasySetup123");
+        mWiFiOnBoardingConfig.setSharedKey("EasySetup123");
+        mWiFiOnBoardingConfig.setAuthAlgo(WifiConfiguration.AuthAlgorithm.OPEN);
+        mWiFiOnBoardingConfig.setKms(WifiConfiguration.KeyMgmt.WPA_PSK);
+
+        /* Create provisioning configuration */
+        WiFiProvConfig mWiFiProvConfig = new WiFiProvConfig("hub2.4G", "11112222");
+
+        /* Create enrolling device */
+        EnrolleeDevice device = mFactory.newEnrolleeDevice(mWiFiProvConfig, mWiFiOnBoardingConfig);
+
+        /* Check if the the device is created */
+        assertTrue(device != null);
+
+        /* Check if the the correct device is created as per the given configuration*/
+        assertTrue((device instanceof EnrolleeDeviceWiFiOnboarding));
+
+    }
+
+}
diff --git a/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/Utility.java b/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/Utility.java
new file mode 100644 (file)
index 0000000..6b0484e
--- /dev/null
@@ -0,0 +1,42 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+
+package org.iotivity.service.easysetup.mediator;
+
+
+public class Utility {
+
+    public static void toNotify(Object toLock) {
+        synchronized (toLock) {
+            toLock.notify();
+        }
+    }
+
+    public static void toWait(Object toLock) {
+        synchronized (toLock) {
+            try {
+                toLock.wait(45000);
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+            }
+        }
+    }
+}
diff --git a/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ESException.java b/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ESException.java
new file mode 100644 (file)
index 0000000..49937b4
--- /dev/null
@@ -0,0 +1,32 @@
+/**
+ * ***************************************************************
+ * <p>
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ * <p>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+/**
+ * This is the Exception class for the EasySetup APIs
+ */
+public class ESException extends Exception {
+    public ESException(String exception) {
+        super(exception);
+    }
+}
diff --git a/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EasySetupService.java b/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EasySetupService.java
new file mode 100755 (executable)
index 0000000..128dc14
--- /dev/null
@@ -0,0 +1,233 @@
+/**
+ * ***************************************************************
+ * <p/>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p/>
+ * <p/>
+ * <p/>
+ * 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
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * 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.
+ * <p/>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+import android.content.Context;
+import android.util.Log;
+
+import java.io.IOException;
+import java.util.ArrayList;
+
+/**
+ * This is facade class, a single point of contact for Application.
+ * It contains set of APIs to do easy setup of the enrolling device.
+ * ON-BOARDING - This is a step to establish connectivity between the device & Mediator device.
+ * PROVISION   - This is a step where the netowork's detail & credentials are given to the
+ * enrolling device.
+ */
+public class EasySetupService {
+
+    private static final String TAG = EasySetupService.class.getName();
+
+    private static EasySetupService sInstance;
+
+    private final EasySetupStatus mCallback;
+
+    private ArrayList<EnrolleeDevice> mEnrolleeDeviceList;
+
+    private final ProvisioningCallback mProvisioningCallback;
+
+    private static Context mContext;
+
+    protected RemoteEnrollee mRemoteEnrollee;
+
+    //function to call the native createEnrolleeDevice
+    private native RemoteEnrollee nativeCreateEnrolleeDevice(String ip, String ssid,
+                                                     String password, int type, boolean isSecured );
+
+    static {
+        // Load Easy Setup JNI interface
+        System.loadLibrary("ESMediatorRich");
+        System.loadLibrary("easysetup-jni");
+    }
+
+    private EasySetupService(EasySetupStatus callback) {
+        mCallback = callback;
+        mProvisioningCallback = new ProvisioningCallbackImpl(mCallback);
+        mEnrolleeDeviceList = new ArrayList<EnrolleeDevice>();
+        mContext = null;
+    }
+
+    /**
+     * Gives a singleton instance of Easy setup service and initialize the service
+     *
+     * @param callback Application needs to provide this callback to receive the status of easy
+     *                 setup process.
+     */
+
+    public synchronized static EasySetupService getInstance(Context context, EasySetupStatus
+            callback) {
+        if (sInstance == null) {
+            sInstance = new EasySetupService(callback);
+            mContext = context;
+        }
+        return sInstance;
+    }
+
+    /**
+     * Reset the Easy setup Service
+     */
+
+    public void finish() {
+            //Call the stop Provisioning
+            for (EnrolleeDevice enrolleeDevice : mEnrolleeDeviceList) {
+                enrolleeDevice.stopProvisioningProcess();
+        }
+    }
+
+    /**
+     * Starts Easy setup process for the enrolling device.
+     *
+     * @param enrolledevice Device to be enrolled in network
+     * @throws IOException Throws exception in case of any connection error.
+     */
+
+    public synchronized void startSetup(final EnrolleeDevice enrolledevice) throws IOException,ESException {
+
+        if (null == enrolledevice) {
+            throw new ESException("enrolledevice is NULL");
+        }
+
+        mEnrolleeDeviceList.add(enrolledevice);
+
+        // Starts the provisioning directly if the device is already on boarded on the network.
+        if (enrolledevice.onBoarded()) {
+            if(null == enrolledevice.mRemoteEnrollee){
+                //create Native RemoteEnrollee
+                WiFiProvConfig config = (WiFiProvConfig)enrolledevice.mProvConfig;
+                String ip = "";
+                String ssid = config.getSsId();
+                String password = config.getPassword();
+                int connectivityType = config.getConnType().getValue();
+                boolean isSecured = config.isSecured();
+
+                //native call
+                mRemoteEnrollee = nativeCreateEnrolleeDevice(ip, ssid, password,
+                        connectivityType, isSecured);
+                enrolledevice.mRemoteEnrollee = mRemoteEnrollee;
+            }
+            enrolledevice.startProvisioning(mProvisioningCallback);
+            return;
+        }
+        enrolledevice.mState = EnrolleeState.DEVICE_ON_BOARDING_STATE;
+        mCallback.onProgress(enrolledevice);
+        enrolledevice.startOnBoarding(new OnBoardingCallback() {
+
+            @Override
+            public void onFinished(OnBoardingConnection connection) {
+                if (connection.isConnected()) {
+                    Log.i(TAG, "On boarding is successful ");
+                    // Start provisioning here
+                    enrolledevice.mState = EnrolleeState.DEVICE_ON_BOARDED_STATE;
+                    mCallback.onProgress(enrolledevice);
+                    enrolledevice.setConnection(connection);
+
+                    //create a native RemoteEnrollee with network info
+                    IpOnBoardingConnection conn = (IpOnBoardingConnection) connection;
+                    WiFiProvConfig config = (WiFiProvConfig)enrolledevice.mProvConfig;
+                    String ip = conn.getIp();
+                    String ssid = config.getSsId();
+                    String password = config.getPassword();
+                    int connectivityType = config.getConnType().getValue();
+                    boolean isSecured = config.isSecured();
+
+                    //native call
+                    mRemoteEnrollee = nativeCreateEnrolleeDevice(ip, ssid, password,
+                                connectivityType, isSecured);
+
+                    enrolledevice.mRemoteEnrollee = mRemoteEnrollee;
+
+                    /* Delay is set according to Soft AP host and Mediator platform;
+                    *  For Android with Soft AP it is 2000 ms
+                    */
+                    delayProvisioning(connection);
+                    enrolledevice.startProvisioning(mProvisioningCallback);
+                } else {
+                    enrolledevice.mState = EnrolleeState.DEVICE_INIT_STATE;
+                    mProvisioningCallback.onFinished(enrolledevice);
+                }
+            }
+        });
+    }
+
+    /**
+     * Stops on-going Easy setup process for enrolling device.
+     *
+     * @param enrolleedevice Device to be enrolled in network
+     */
+    public synchronized void stopSetup(EnrolleeDevice enrolleedevice) throws ESException {
+
+        if (null == enrolleedevice) {
+            throw new ESException("enrolledevice is NULL");
+        }
+
+        if (mEnrolleeDeviceList.contains(enrolleedevice)) {
+            if (enrolleedevice.mState == EnrolleeState.DEVICE_ON_BOARDING_STATE) {
+                Log.i(TAG, "stopOnBoardingProcess for enrolleedevice");
+                enrolleedevice.stopOnBoardingProcess();
+            }else if (enrolleedevice.mState == EnrolleeState.DEVICE_PROVISIONING_STATE) {
+                Log.i(TAG, "stopEnrolleeProvisioning for enrolleedevice");
+                enrolleedevice.stopProvisioningProcess();
+            }
+            enrolleedevice.mState = EnrolleeState.DEVICE_INIT_STATE;
+            mCallback.onProgress(enrolleedevice);
+            mEnrolleeDeviceList.remove(enrolleedevice);
+        }
+    }
+
+    class ProvisioningCallbackImpl extends ProvisioningCallback {
+
+        private final EasySetupStatus mCallback;
+
+        ProvisioningCallbackImpl(EasySetupStatus callback) {
+            mCallback = callback;
+        }
+
+        @Override
+        public void onFinished(EnrolleeDevice enrolledevice) {
+            synchronized (EasySetupService.this) {
+                if (mEnrolleeDeviceList.contains(enrolledevice)) {
+                    Log.i(TAG, "onFinished() is received " + enrolledevice.isSetupSuccessful());
+                    mCallback.onFinished(enrolledevice);
+                    mEnrolleeDeviceList.remove(enrolledevice);
+                }
+            }
+        }
+
+        @Override
+        public void onProgress(EnrolleeDevice enrolledevice) {
+            mCallback.onProgress(enrolledevice);
+        }
+    }
+
+    private void delayProvisioning(OnBoardingConnection conn) {
+        if (((IpOnBoardingConnection)conn).getThrottlingDelay()>0) {
+            try {
+                Log.i(TAG, "waiting for 20 seconds to start provisioning");
+                Thread.sleep(20000);//Sleep for allowing thin device to start the services
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeDevice.java b/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeDevice.java
new file mode 100644 (file)
index 0000000..abb080d
--- /dev/null
@@ -0,0 +1,173 @@
+/**
+ * ***************************************************************
+ * <p/>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p/>
+ * <p/>
+ * <p/>
+ * 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
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * 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.
+ * <p/>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+/**
+ * This is an abstract class represents the device being provisioned into the network. The
+ * device being enrolled or provisioned into the network is called Enrollee.
+ * Application has to extend this class and provide implementation of abstract methods according
+ * to the ON-BOARDING & PROVISION connectivity i.e. WiFi etc.
+ */
+
+public abstract class EnrolleeDevice {
+
+    protected EnrolleeState mState;
+    private EnrolleeSetupError mError;
+
+    OnBoardingConnection mConnection;
+    final ProvisioningConfig mProvConfig;
+    final OnBoardingConfig mOnBoardingConfig;
+
+    protected OnBoardingCallback mOnBoardingCallback;
+    protected ProvisioningCallback mProvisioningCallback;
+    protected RemoteEnrollee mRemoteEnrollee;
+
+    /**
+     * @param onBoardingConfig Contains details about the connectivity to be established between
+     *                         the Enrollee device & Mediator device in order to perform
+     *                         on-boarding
+     * @param provConfig       Contains details about the network to which Enrollee device is
+     *                         going to connect.
+     */
+    protected EnrolleeDevice(OnBoardingConfig onBoardingConfig, ProvisioningConfig provConfig) {
+        mProvConfig = provConfig;
+        mOnBoardingConfig = onBoardingConfig;
+    }
+
+    /**
+     * Application has to implement it according to the on boarding connectivity the device is
+     * having.
+     * This method will be called back during the easy setup process.
+     */
+    protected abstract void startOnBoardingProcess();
+
+    /**
+     * This method is called back during the easy setup process if Application cancels the setup.
+     * Easy setup service checks the state of device and calls this function accordingly.
+     * Application has to provide implementation for this method to cancel the on boarding step.
+     */
+    protected abstract void stopOnBoardingProcess();
+
+    /**
+     * Application has to implement it according to the type of the network device is going to
+     * connect or provisioned.
+     * This method will be called back once on-boarding of the device is successful.
+     *
+     * @param conn Contains detail about the network established between the Enrollee device &
+     *             Mediator device. Its implementation vary according to the connectivity type.
+     */
+    protected abstract void startProvisioningProcess(OnBoardingConnection conn);
+
+    /**
+     * Application has to implement it according to the type of the network device is going to
+     * connect or provisioned.
+     * This method will stop the provisioning process if it is in progress
+     *
+     */
+    protected abstract void stopProvisioningProcess();
+
+    /**
+     * Once on boarding is successful concrete Enrollee class would call this method and set the
+     * Connection.
+     *
+     * @param conn Connectivity between Enrollee device & Mediator device.
+     */
+    protected void setConnection(OnBoardingConnection conn) {
+        mConnection = conn;
+    }
+
+    /**
+     * This method returns the OnBoardingConnection object depending on the connection type
+     *
+     * @return onBoardingConnection object
+     */
+    public OnBoardingConnection getConnection() {
+        return mConnection;
+    }
+
+
+    /**
+     * This method is called back by Easy setup service if on boarding needs to be done.
+     *
+     * @param onBoardingCallback This is called back once the on boarding is completed.
+     */
+    void startOnBoarding(OnBoardingCallback onBoardingCallback) {
+        mOnBoardingCallback = onBoardingCallback;
+        startOnBoardingProcess();
+    }
+
+    /**
+     * This method is called back by Easy setup service once on boarding is successful
+     *
+     * @param provisioningCallback This is called back once the provisioning process is completed
+     */
+    void startProvisioning(ProvisioningCallback provisioningCallback) {
+        mProvisioningCallback = provisioningCallback;
+        startProvisioningProcess(mConnection);
+    }
+
+    /**
+     * This method is used to check easy setup status
+     *
+     * @return true if successful or false
+     */
+
+    public boolean isSetupSuccessful() {
+        return (mState == EnrolleeState.DEVICE_PROVISIONED_STATE) ? true : false;
+    }
+
+    /**
+     * sets error occured during easy setup process
+     */
+    protected void setError(EnrolleeSetupError error) {
+        mError = error;
+    }
+
+    /**
+     * Returns error occured during easy setup process
+     *
+     * @return True EnrolleeSetupError object
+     */
+    public EnrolleeSetupError getError() {
+        return mError;
+    }
+
+    /**
+     * Gives the state of the device being enrolled during the easy setup process.
+     *
+     * @return Returns EnrolleeState object
+     */
+    public EnrolleeState getState() {
+        return mState;
+    }
+
+    /**
+     * This method is used to know if the device is on boarded or not
+     *
+     * @return True if on-boarded successfully or False
+     */
+
+    protected boolean onBoarded() {
+        return (mState == EnrolleeState.DEVICE_ON_BOARDED_STATE) ? true : false;
+    }
+}
diff --git a/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeDeviceFactory.java b/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeDeviceFactory.java
new file mode 100644 (file)
index 0000000..bcf8219
--- /dev/null
@@ -0,0 +1,81 @@
+/**
+ * ***************************************************************
+ * <p/>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p/>
+ * <p/>
+ * <p/>
+ * 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
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * 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.
+ * <p/>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+import android.content.Context;
+
+/**
+ * This a factory class provides the native implementation of the various Enrollee devices.
+ * Application can make use of Enrollee factory if it does not want to create its own Enrollee devices.
+ */
+public class EnrolleeDeviceFactory {
+
+    Context mContext;
+
+    /**
+     * This method create & returns instance of EnrolleeDeviceFactory
+     *
+     * @param context This is Android Application context
+     */
+    public static EnrolleeDeviceFactory newInstance(Context context) {
+        return new EnrolleeDeviceFactory(context);
+    }
+
+    private EnrolleeDeviceFactory(Context context) {
+        mContext = context;
+    }
+
+    /**
+     * This method create & returns instance of Enrollee device of supported configuration
+     *
+     * @param onboardingConfig Contains details about the connectivity to be established between the Enrollee device & Mediator device in order to perform on-boarding
+     * @param provConfig       Contains details about the network to which Enrollee device is going to connect.
+     * @return Instance of the Enrollee device created natively.
+     */
+
+    public EnrolleeDevice newEnrolleeDevice(ProvisioningConfig provConfig, OnBoardingConfig onboardingConfig) throws IllegalArgumentException {
+
+        if (null == provConfig  || null == onboardingConfig) {
+            throw new IllegalArgumentException("provConfig/onboardingConfig is NULL");
+        }
+        else if (onboardingConfig.getConnType() != OnBoardingConfig.ConnType.WiFi) {
+            throw new IllegalArgumentException("OnBoarding configuration is not supported");
+        }
+        return new EnrolleeDeviceWiFiOnboarding(mContext, onboardingConfig, provConfig);
+    }
+
+    /**
+     * This method create & returns instance of Enrollee device of supported configuration
+     * [When SoftAP is going to be created on Enrollee side]
+     *
+     * @param provConfig       Contains details about the network to which Enrollee device is going to connect.
+     * @return Instance of the Enrollee device created natively.
+     */
+    public EnrolleeDevice newEnrolleeDevice(ProvisioningConfig provConfig) throws IllegalArgumentException {
+
+        if (null == provConfig) {
+            throw new IllegalArgumentException("provConfig is NULL");
+        }
+        return new EnrolleeDeviceWiFiOnboarding(mContext, new IpOnBoardingConnection(true), provConfig);
+    }
+}
diff --git a/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeDeviceWiFiOnboarding.java b/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeDeviceWiFiOnboarding.java
new file mode 100644 (file)
index 0000000..66f12d0
--- /dev/null
@@ -0,0 +1,193 @@
+/**
+ * ***************************************************************
+ * <p/>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p/>
+ * <p/>
+ * <p/>
+ * 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
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * 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.
+ * <p/>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+import java.util.Timer;
+import java.util.TimerTask;
+
+import org.iotivity.service.easysetup.core.EnrolleeInfo;
+import org.iotivity.service.easysetup.core.IOnBoardingStatus;
+import org.iotivity.service.easysetup.core.ip.WiFiSoftAPManager;
+
+import android.content.Context;
+import android.net.wifi.WifiConfiguration;
+import android.util.Log;
+
+/**
+ * This is a ready to use class for Enrollee device having Soft AP as on-boarding connectivity.
+ */
+public class EnrolleeDeviceWiFiOnboarding extends EnrolleeDevice {
+
+    public static final String TAG = EnrolleeDeviceWiFiOnboarding.class.getName();
+
+    final Context mContext;
+    final WiFiSoftAPManager mWifiSoftAPManager;
+    EnrolleeInfo connectedDevice;
+    Timer myTimer = null;
+
+    IOnBoardingStatus deviceScanListener = new IOnBoardingStatus() {
+
+        @Override
+        public void deviceOnBoardingStatus(EnrolleeInfo enrolleStatus) {
+            myTimer.cancel();
+            Log.d("ESSoftAPOnBoarding", "Entered");
+            if (mState == EnrolleeState.DEVICE_ON_BOARDING_STATE) {
+                Log.d("ESSoftAPOnBoarding", "Device in OnBoarding State");
+                if (enrolleStatus != null && enrolleStatus.getIpAddr() != null) {
+                    String finalResult = "Easy Connect : ";
+
+                    if (enrolleStatus.isReachable()) {
+                        finalResult = "Device OnBoarded" + "["
+                                + enrolleStatus.getIpAddr() + "]";
+
+                        connectedDevice = enrolleStatus;
+                        IpOnBoardingConnection conn = new IpOnBoardingConnection();
+
+                        conn.setConnectivity(true);
+                        conn.setIp(connectedDevice.getIpAddr());
+                        conn.setHardwareAddress(enrolleStatus.getHWAddr());
+                        conn.setDeviceName(enrolleStatus.getDevice());
+
+                        Log.d("ESSoftAPOnBoarding", "Entered" + finalResult);
+                        mOnBoardingCallback.onFinished(conn);
+                        return;
+
+                    }
+                }
+
+                IpOnBoardingConnection conn = new IpOnBoardingConnection();
+                conn.setConnectivity(false);
+                mOnBoardingCallback.onFinished(conn);
+            } else {
+                Log.e("ESSoftAPOnBoarding", "Device NOT in OnBoarding State. Ignoring the event");
+            }
+        }
+    };
+
+
+    protected EnrolleeDeviceWiFiOnboarding(Context context, OnBoardingConfig onBoardingConfig,
+                                           ProvisioningConfig provConfig) {
+        super(onBoardingConfig, provConfig);
+        mContext = context;
+        mState = EnrolleeState.DEVICE_INIT_STATE;
+        mWifiSoftAPManager = new WiFiSoftAPManager(mContext);
+    }
+
+    protected EnrolleeDeviceWiFiOnboarding(Context context, IpOnBoardingConnection conn,
+                                           ProvisioningConfig provConfig) {
+        super(new WiFiOnBoardingConfig(), provConfig);
+        mContext = context;
+        mState = EnrolleeState.DEVICE_ON_BOARDED_STATE;
+        mConnection = conn;
+        mWifiSoftAPManager = new WiFiSoftAPManager(mContext);
+    }
+
+    @Override
+    protected void startOnBoardingProcess() {
+        Log.i(TAG, "Starting on boarding process");
+
+        //1. Create Soft AP
+        boolean status = mWifiSoftAPManager.setWifiApEnabled((WifiConfiguration)
+                mOnBoardingConfig.getConfig(), true);
+
+        mState = EnrolleeState.DEVICE_ON_BOARDING_STATE;
+
+        Log.i(TAG, "Soft AP is created with status " + status);
+
+        myTimer = new Timer();
+        myTimer.schedule(new TimerTask() {
+            @Override
+            public void run() {
+                // Below function to be called after 5 seconds
+                mWifiSoftAPManager.getClientList(deviceScanListener, 300);
+            }
+
+        }, 0, 5000);
+    }
+
+    protected void stopOnBoardingProcess() {
+        Log.i(TAG, "Stopping on boarding process");
+        if(myTimer != null)
+        {
+            myTimer.cancel();
+        }
+        boolean status = mWifiSoftAPManager.setWifiApEnabled(null, false);
+        Log.i(TAG, "Soft AP is disabled with status " + status);
+    }
+
+    @Override
+    protected void startProvisioningProcess(OnBoardingConnection conn)  {
+
+        mState = EnrolleeState.DEVICE_PROVISIONING_STATE;
+        mProvisioningCallback.onProgress(this);
+        final EnrolleeDevice device = this;
+        if (mProvConfig.getConnType() == ProvisioningConfig.ConnType.WiFi) {
+             try {
+                 mRemoteEnrollee.registerProvisioningHandler(new IProvisionStatusNativeHandler() {
+                     @Override
+                     public void onStatusRecieved(int state) {
+                         device.mState = convertIntToProvisioningState(state);
+                         Log.i(TAG,"Device state changed :"+device.mState);
+                         mProvisioningCallback.onProgress(device);
+                         if(0==state) {
+                             mProvisioningCallback.onFinished(EnrolleeDeviceWiFiOnboarding.this);
+                         }
+                     }
+                 });
+                 //native call
+                mRemoteEnrollee.startProvision();
+             }catch(ESException e) {
+                 Log.i(TAG,"startProvisioningProcess Register Listener to native exception");
+             }
+        }
+    }
+
+    protected void stopProvisioningProcess(){
+        if(mState == EnrolleeState.DEVICE_PROVISIONING_STATE)
+        {    //native call
+            try {
+                mRemoteEnrollee.stopProvision();
+            } catch (ESException e) {
+                Log.i(TAG,"stopProvisioningProcess exception");
+            }
+        }else{
+           Log.i(TAG,"stopProvisioningProcess : Provisioning is not in progress");
+        }
+    }
+
+    private EnrolleeState convertIntToProvisioningState(int state){
+
+        switch(state)
+        {
+            case 0 :
+                return EnrolleeState.DEVICE_PROVISIONED_STATE;
+            case 1:
+                return EnrolleeState.DEVICE_NOT_PROVISIONED;
+            case 2:
+                return EnrolleeState.DEVICE_PROVISIONED_STATE;
+            case 3:
+                return EnrolleeState.DEVICE_NOT_PROVISIONED;
+        }
+        return EnrolleeState.DEVICE_INIT_STATE;
+    }
+}
diff --git a/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeState.java b/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeState.java
new file mode 100644 (file)
index 0000000..91b8231
--- /dev/null
@@ -0,0 +1,88 @@
+/**
+ * ***************************************************************
+ * <p>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ * <p>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+/**
+ * It defines various states of the Enrollee device during easy setup process
+ */
+
+public enum EnrolleeState {
+
+    /**
+     * Default state of the device
+     */
+    DEVICE_INIT_STATE,
+
+    /**
+     * Device will move to this state after successful on-boarding of the device
+     */
+    DEVICE_ON_BOARDED_STATE,
+
+    /**
+     * Device will move to this state once the on boarding begins
+     */
+    DEVICE_ON_BOARDING_STATE,
+
+    /**
+     * Device will move to this state once the on boarding is done
+     */
+    DEVICE_PROVISIONING_STATE,
+
+    /**
+     * Easy setup process is successful.
+     */
+    DEVICE_PROVISIONED_STATE,
+
+    /**
+     * Easy setup process failed.
+     */
+    DEVICE_NOT_PROVISIONED,
+
+    /**
+     * This state is arbitrary one, any time device can come into this state
+     * Device will move to this state if the ownership transfer initiated  by the Application
+     */
+    DEVICE_OWNERSHIP_TRANSFERRING_STATE,
+
+    /**
+     * This state is arbitrary one, any time device can come into this state
+     * Device will move to this state if the ownership transfer is completed
+     */
+    DEVICE_OWNERSHIP_TRANSFERRED_STATE,
+
+    /**
+     * This state is arbitrary one, any time device can come into this state
+     * Device will move to this state if the ownership transfer is not completed
+     */
+    DEVICE_NOT_OWNED,
+
+    /**
+     * This state is arbitrary one, any time device can come into this state
+     * Device will move to this state once the Application factory reset the device
+     */
+    DEVICE_FACTORY_RESET_STATE,
+
+
+
+
+}
diff --git a/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/IProvisionStatusNativeHandler.java b/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/IProvisionStatusNativeHandler.java
new file mode 100644 (file)
index 0000000..9ca1083
--- /dev/null
@@ -0,0 +1,29 @@
+/**
+ * ***************************************************************
+ * <p/>
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ * <p/>
+ * <p/>
+ * <p/>
+ * 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
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * 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.
+ * <p/>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+public interface IProvisionStatusNativeHandler {
+
+    public void onStatusRecieved(int state);
+
+}
diff --git a/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/IpOnBoardingConnection.java b/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/IpOnBoardingConnection.java
new file mode 100644 (file)
index 0000000..64599f8
--- /dev/null
@@ -0,0 +1,94 @@
+/**
+ * ***************************************************************
+ * <p/>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p/>
+ * <p/>
+ * <p/>
+ * 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
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * 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.
+ * <p/>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+public class IpOnBoardingConnection implements OnBoardingConnection {
+
+    private boolean mIsConnected;
+    private String mIp;
+    private String mHardwareAddress;
+    private String mDeviceName;
+
+    /**
+     * @mThrottlingDelay
+     * After creating the Soft AP at Mediator & on-boarding the-
+     * -Enrollee device on it provisioning needs to be delayed by at least 2000 ms for Android Mediator
+     */
+    private int mThrottlingDelay = 2000 ;
+
+    int getThrottlingDelay() {
+        return mThrottlingDelay;
+    }
+
+    IpOnBoardingConnection(boolean enrolleeOnboarded) {
+        mThrottlingDelay = 0;
+        mIp = "0.0.0.01";
+        mIsConnected = enrolleeOnboarded; // Always true for this constructor
+    }
+
+    IpOnBoardingConnection(){}
+
+    public void setHardwareAddress(String address) {
+        mHardwareAddress = address;
+    }
+
+    public String getHardwareAddress() {
+        return mHardwareAddress;
+    }
+
+    public void setDeviceName(String name) {
+        mDeviceName = name;
+    }
+
+    public String getDeviceName() {
+        return mDeviceName;
+    }
+
+    public void setConnectivity(boolean connected) {
+        mIsConnected = connected;
+    }
+
+    public void setIp(String ip) {
+        mIp = ip;
+    }
+
+    public String getIp() {
+        return mIp;
+    }
+
+    @Override
+    public String getDesc() {
+        return "Description";
+    }
+
+    @Override
+    public boolean isConnected() {
+        return mIsConnected;
+    }
+
+    @Override
+    public Object getConnection() {
+        return this;
+    }
+
+}
diff --git a/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/OnBoardingCallback.java b/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/OnBoardingCallback.java
new file mode 100644 (file)
index 0000000..08c75f9
--- /dev/null
@@ -0,0 +1,27 @@
+/**
+ * ***************************************************************
+ * <p/>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p/>
+ * <p/>
+ * <p/>
+ * 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
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * 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.
+ * <p/>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+public abstract class OnBoardingCallback {
+    public abstract void onFinished(OnBoardingConnection connection);
+}
diff --git a/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/OnBoardingConfig.java b/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/OnBoardingConfig.java
new file mode 100644 (file)
index 0000000..db62640
--- /dev/null
@@ -0,0 +1,73 @@
+/**
+ * ***************************************************************
+ * <p/>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p/>
+ * <p/>
+ * <p/>
+ * 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
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * 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.
+ * <p/>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+import android.util.Log;
+
+import org.iotivity.base.OcConnectivityType;
+
+/**
+ * It contains configuration details about the connectivity type between the Enrollee device &
+ * Mediator device in order to perform on-boarding.
+ */
+
+public interface OnBoardingConfig {
+    /**
+     * It provides constants for connectivity types used for on-boarding Enrollee device
+     */
+    public static enum ConnType {
+        // Note : Enum Ids should matched with Native Ids
+        WiFi(OcConnectivityType.CT_ADAPTER_IP.getValue()),
+        BLE(OcConnectivityType.CT_ADAPTER_GATT_BTLE.getValue());
+
+        private int mConnType;
+
+        ConnType(int connType) {
+            mConnType = connType;
+        }
+
+        public int getValue() {
+            return mConnType;
+        }
+
+    }
+
+    /**
+     * Gives configuration object specific to the on-boarding connectivity of the enrolling device.
+     *
+     * @return instance object of configuration according to connectivity type
+     */
+    public Object getConfig();
+
+    /**
+     * Gives connectivity type of on-boarding device
+     *
+     * @return on-boarding connectivity type
+     */
+    public ConnType getConnType();
+
+    public boolean isSecured();
+
+    public void setSecured(boolean isSecured);
+
+}
diff --git a/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/OnBoardingConnection.java b/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/OnBoardingConnection.java
new file mode 100644 (file)
index 0000000..3267536
--- /dev/null
@@ -0,0 +1,50 @@
+/**
+ * ***************************************************************
+ * <p/>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p/>
+ * <p/>
+ * <p/>
+ * 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
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * 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.
+ * <p/>
+ * ****************************************************************
+ */
+package org.iotivity.service.easysetup.mediator;
+
+/**
+ * This interface contains the connection details of the enrollee device
+ */
+public interface OnBoardingConnection {
+
+    /**
+     * This method returns the implementation of the Connection
+     *
+     * @return implementation
+     */
+    public Object getConnection();
+
+    /**
+     * This method returns description on the connectivity.
+     *
+     * @return description
+     */
+    public String getDesc();
+
+    /**
+     * This method is used to know if the device is connected or not
+     *
+     * @return True if connected or False
+     */
+    public boolean isConnected();
+
+}
diff --git a/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ProvisioningConfig.java b/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ProvisioningConfig.java
new file mode 100644 (file)
index 0000000..a1b96c8
--- /dev/null
@@ -0,0 +1,73 @@
+/**
+ * ***************************************************************
+ * <p>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ * <p>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+import android.util.Log;
+
+import org.iotivity.base.OcConnectivityType;
+/**
+ * It contains configuration details about the the target network where Enrollee device is
+ * going to be enrolled.
+ */
+public interface ProvisioningConfig {
+
+    /**
+     * It provides constants for connectivity types of target network
+     */
+    public static enum ConnType {
+        // Note : Enum Ids should matched with Native Ids
+        WiFi(OcConnectivityType.CT_ADAPTER_IP.getValue()),
+        BLE(OcConnectivityType.CT_ADAPTER_GATT_BTLE.getValue());
+
+        private int mConnType;
+
+        ConnType(int connType) {
+            mConnType = connType;
+        }
+
+        public int getValue() {
+            return mConnType;
+        }
+    }
+
+    /**
+     * Gives the instance of the configuration object created according to the connectivity
+     * type of target network.
+     *
+     * @return instance object of configuration according to connectivity type of target network
+     */
+    Object getConfig();
+
+
+    /**
+     * Gives connectivity type of target network
+     *
+     * @return Connectivity type of target network
+     */
+    ConnType getConnType();
+
+    public boolean isSecured();
+
+    public void setSecured(boolean isSecured);
+
+}
diff --git a/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/RemoteEnrollee.java b/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/RemoteEnrollee.java
new file mode 100644 (file)
index 0000000..38328bc
--- /dev/null
@@ -0,0 +1,59 @@
+/**
+ * ***************************************************************
+ * <p/>
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ * <p/>
+ * <p/>
+ * <p/>
+ * 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
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * 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.
+ * <p/>
+ * ****************************************************************
+ */
+
+
+package org.iotivity.service.easysetup.mediator;
+
+import android.util.Log;
+
+public class RemoteEnrollee{
+
+    public static final String TAG = RemoteEnrollee.class.getName();
+    private long m_nativeHandle;
+
+    private native void nativeStartProvision();
+    private native void nativeStopProvision();
+    private native void nativeRegisterProvisioningHandler(IProvisionStatusNativeHandler listener);
+
+    /* constructor will be invoked from the native layer */
+    private RemoteEnrollee(long nativeHandle){
+        this.m_nativeHandle = nativeHandle;
+    }
+
+    /* Register native Listener for the Provisioning state */
+    public void registerProvisioningHandler( IProvisionStatusNativeHandler provisioningListener) throws ESException{
+       // this.provisioningListener = provisioningListener;
+        nativeRegisterProvisioningHandler(provisioningListener);
+        Log.i(TAG, "JNI Callback is registered for getting provisioning status");
+    }
+
+    /* native StartProvision */
+    public void startProvision() throws ESException{
+    nativeStartProvision();
+}
+
+    /* native stopProvision */
+    public void stopProvision() throws  ESException{
+    nativeStopProvision();
+}
+
+}
diff --git a/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/WiFiOnBoardingConfig.java b/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/WiFiOnBoardingConfig.java
new file mode 100644 (file)
index 0000000..4369cf4
--- /dev/null
@@ -0,0 +1,75 @@
+/**
+ * ***************************************************************
+ * <p/>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p/>
+ * <p/>
+ * <p/>
+ * 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
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * 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.
+ * <p/>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+import org.iotivity.service.easysetup.mediator.OnBoardingConfig;
+
+import android.net.wifi.WifiConfiguration;
+
+/**
+ * This class contains on boarding configuration information for Soft AP on boarding connectivity.
+ * It implements OnBoardingConfig interface & provide implementation for WiFi Soft AP connectivity.
+ */
+
+public class WiFiOnBoardingConfig implements OnBoardingConfig {
+
+    private boolean isSecured;
+    private final WifiConfiguration config = new WifiConfiguration();
+    private final ConnType mConnType = OnBoardingConfig.ConnType.WiFi;
+
+    @Override
+    public Object getConfig() {
+        return config;
+    }
+
+    public void setSSId(String ssid) {
+        config.SSID = ssid;
+    }
+
+    public void setSharedKey(String sharedKey) {
+        config.preSharedKey = sharedKey;
+    }
+
+    public void setAuthAlgo(int aurthAlgo) {
+        config.allowedAuthAlgorithms.set(aurthAlgo);
+    }
+
+    public void setKms(int kms) {
+        config.allowedKeyManagement.set(kms);
+    }
+
+    @Override
+    public ConnType getConnType() {
+        return mConnType;
+    }
+
+    @Override
+    public boolean isSecured(){
+        return isSecured;
+    }
+
+    @Override
+    public void setSecured(boolean flag) {
+        isSecured = flag;
+    }
+}
diff --git a/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/WiFiProvConfig.java b/service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/WiFiProvConfig.java
new file mode 100644 (file)
index 0000000..1087f6e
--- /dev/null
@@ -0,0 +1,79 @@
+/**
+ * ***************************************************************
+ * <p>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ * <p>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+import org.iotivity.service.easysetup.mediator.ProvisioningConfig;
+
+/**
+ * This class contains on provisioning configuration information for for target network.
+ * It implements ProvisioningConfig interface and provide configuration object specific to WiFi target network
+ */
+public class WiFiProvConfig implements ProvisioningConfig {
+
+    private final ConnType mConnType = ProvisioningConfig.ConnType.WiFi;
+    private boolean isSecured;
+
+    private final String mSsId;
+    private final String mPassword;
+
+    public WiFiProvConfig(String ssid, String pass) {
+        mSsId = ssid;
+        mPassword = pass;
+    }
+
+    @Override
+    public Object getConfig() {
+        return this;
+    }
+
+    @Override
+    public ConnType getConnType() {
+        return mConnType;
+    }
+
+    /**
+     * This method returns the SSID of the Target WIFI network
+     * @return SSID of Target Network
+     */
+    public String getSsId() {
+        return mSsId;
+    }
+
+    /**
+     * This method returns the password of the Target WIFI network
+     * @return password of Target Network
+     */
+    public String getPassword() {
+        return mPassword;
+    }
+
+    @Override
+    public boolean isSecured(){
+        return isSecured;
+    }
+
+    @Override
+    public void setSecured(boolean flag) {
+        isSecured = flag;
+    }
+}
diff --git a/service/easy-setup/mediator/richsdk/android/jni/Android.mk b/service/easy-setup/mediator/richsdk/android/jni/Android.mk
new file mode 100644 (file)
index 0000000..87518ac
--- /dev/null
@@ -0,0 +1,60 @@
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../../../out/android/$(TARGET_ARCH_ABI)/debug
+LOCAL_MODULE := android-oc
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboc.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../../../out/android/$(TARGET_ARCH_ABI)/debug
+LOCAL_MODULE := android-easysetup
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libESMediatorRich.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE    := easysetup-jni
+
+#Add Pre processor definitions
+DEFINE_FLAG =  -DWITH_POSIX -D__ANDROID__
+
+#Add Debug flags here
+DEBUG_FLAG      = -DTB_LOG
+
+BUILD_FLAG = $(DEFINE_FLAG) $(DEBUG_FLAG)
+
+LOCAL_CPPFLAGS = $(BUILD_FLAG)
+LOCAL_CPPFLAGS += -std=c++0x -frtti -fexceptions
+
+$(info CPPFLAGSUPDATED=$(LOCAL_CPPFLAGS))
+
+LOCAL_C_INCLUDES := $(LOCAL_PATH) \
+                                       $(LOCAL_PATH)/../../inc \
+                                       $(LOCAL_PATH)/../../src \
+                                       $(LOCAL_PATH)/../../../../inc \
+                                       $(LOCAL_PATH)/../../../../../../resource/csdk/logger/include \
+                                   $(LOCAL_PATH)/../../../../../../resource/csdk/connectivity/common/inc \
+                                       $(LOCAL_PATH)/../../../../../../resource/c_common/oic_string/include \
+                                       $(LOCAL_PATH)/../../../../../../resource/include \
+                                       $(LOCAL_PATH)/../../../../../../resource/c_common \
+                                       $(LOCAL_PATH)/../../../../../../resource/oc_logger/include \
+                                       $(LOCAL_PATH)/../../../../../../resource/csdk/ocmalloc/include \
+                                       $(LOCAL_PATH)/../../../../../../resource/csdk/connectivity/api \
+                                       $(LOCAL_PATH)/../../../../../../resource/csdk/stack/include \
+                                       $(LOCAL_PATH)/../../../../../../resource/csdk/logger/include \
+                                       $(LOCAL_PATH)/../../../../../../resource/csdk/security/include \
+                                       $(LOCAL_PATH)/../../../../../../extlibs/cjson \
+                                       $(LOCAL_PATH)/../../../../../../extlibs/boost/boost_1_58_0 \
+                    $(LOCAL_PATH)/../../../../../../extlibs/timer \
+                                       $(LOCAL_PATH)/../../../../../../android/android_api/base/jni \
+
+LOCAL_SRC_FILES += $(patsubst $(LOCAL_PATH)/%, %, $(wildcard $(LOCAL_PATH)/*.cpp))
+LOCAL_SRC_FILES += $(patsubst $(LOCAL_PATH)/%, %, $(wildcard $(LOCAL_PATH)/*.h))
+
+LOCAL_LDLIBS := -llog
+#LOCAL_SHARED_LIBRARIES += android-connectivity_abstraction
+LOCAL_SHARED_LIBRARIES += android-oc
+LOCAL_SHARED_LIBRARIES += android-easysetup
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/service/easy-setup/mediator/richsdk/android/jni/JniEasySetup.cpp b/service/easy-setup/mediator/richsdk/android/jni/JniEasySetup.cpp
new file mode 100644 (file)
index 0000000..a237936
--- /dev/null
@@ -0,0 +1,85 @@
+/******************************************************************
+ *
+ * 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 "JniEasySetup.h"
+
+using namespace OIC::Service;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+JNIEXPORT jobject JNICALL
+Java_org_iotivity_service_easysetup_mediator_EasySetupService_nativeCreateEnrolleeDevice
+(JNIEnv *env, jobject interfaceClass, jstring ip, jstring ssid, jstring password,
+ jint connectivityType, jboolean isSecured)
+{
+
+    LOGI("JniEasySetup::nativeCreateEnrolleeDevice enter");
+
+    std::shared_ptr<RemoteEnrollee> nativeRemoteEnrollee;
+    jobject jRemoteEnrollee;
+    ProvConfig netInfo;
+    WiFiOnboadingConnection onboardConn;
+
+    const char *cIp = (env)->GetStringUTFChars(ip, NULL);
+    const char *cSssid = (env)->GetStringUTFChars(ssid, NULL);
+    const char *cPassword = (env)->GetStringUTFChars(password, NULL);
+
+    std::string sIp(cIp);
+    std::string sSssid(cSssid);
+    std::string sPassword(cPassword);
+
+    netInfo.connType = getOCConnectivityTypeFromInt(connectivityType);
+
+    onboardConn.isSecured = bool(isSecured);
+
+    OICStrcpy(onboardConn.ipAddress, IPV4_ADDR_SIZE - 1, sIp.c_str());
+    OICStrcpy(netInfo.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, sSssid.c_str());
+    OICStrcpy(netInfo.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, sPassword.c_str());
+
+    try
+    {
+        nativeRemoteEnrollee = EasySetup::getInstance()->createEnrolleeDevice(netInfo,onboardConn);
+        //create the java object
+        jRemoteEnrollee = env->NewObject(g_cls_RemoteEnrollee, g_mid_RemoteEnrollee_ctor);
+        if (!jRemoteEnrollee)
+        {
+            LOGE("JniEasySetup::nativeCreateEnrolleeDevice Unable to create the java object");
+            return NULL;
+        }
+
+        JniRemoteEnrollee *jniRemoteEnrollee = new JniRemoteEnrollee(nativeRemoteEnrollee);
+        ESSetHandle<JniRemoteEnrollee>(env, jRemoteEnrollee, jniRemoteEnrollee);
+    }
+    catch (ESBadRequestException exception)
+    {
+        LOGE("JniEasySetup::nativeCreateEnrolleeDevice Unable to create the Native EnrolleeDevice");
+        //throw the exception to java layer
+        throwESException( env,  exception.what());
+    }
+
+    LOGI("JniEasySetup::nativeCreateEnrolleeDevice exit");
+
+    return jRemoteEnrollee;
+}
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/service/easy-setup/mediator/richsdk/android/jni/JniEasySetup.h b/service/easy-setup/mediator/richsdk/android/jni/JniEasySetup.h
new file mode 100644 (file)
index 0000000..2af8935
--- /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.
+ *
+ ******************************************************************/
+
+/** @file   JniEasySetup.h
+ *
+ *   @brief  This file contains native API for creating RemoteEnrollee Device
+ */
+
+#ifndef __JNI_ES_EASYSETUP_H
+#define __JNI_ES_EASYSETUP_H
+
+#include <jni.h>
+
+#include "EasySetup.h"
+#include "RemoteEnrollee.h"
+#include "ESException.h"
+#include "oic_string.h"
+
+#include "JniJvm.h"
+#include "JniEasySetup.h"
+#include "JniRemoteEnrollee.h"
+#include "JniEsUtils.h"
+
+using namespace OIC::Service;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * API for creating and returning the RemoteEnrollee object to Java Layer
+ *
+ * @param ip - ip address of Enrollee
+ * @param ssid - ssid of the Enroller
+ * @param password - password of the enroller
+ * @param connectivityType - Connectivity Type
+ * @param needSecuredEasysetup - need secured easy setup or not
+ *
+ * @return jobject - RemoteEnrolleee
+ */
+JNIEXPORT jobject JNICALL
+Java_org_iotivity_service_easysetup_mediator_EasySetupService_nativeCreateEnrolleeDevice
+(JNIEnv *env, jobject interfaceClass, jstring ip, jstring ssid, jstring password,
+ jint connectivityType, jboolean needSecuredEasysetup);
+
+#ifdef __cplusplus
+}
+#endif
+#endif // __JNI_ES_EASYSETUP_H
\ No newline at end of file
diff --git a/service/easy-setup/mediator/richsdk/android/jni/JniEsListenerManager.h b/service/easy-setup/mediator/richsdk/android/jni/JniEsListenerManager.h
new file mode 100644 (file)
index 0000000..a01ec8d
--- /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.
+ *
+ ******************************************************************/
+
+/** @file   JniEsLisenerManager.h
+ *
+ *   @brief  This file contains JNI Listener Manager class for JniRemoteEnrollee
+ */
+
+#ifndef __JNI_ES_LISTENER_MANAGER_H_
+#define __JNI_ES_LISTENER_MANAGER_H_
+
+#include <mutex>
+#include <map>
+
+class JniRemoteEnrollee;
+
+/**
+ * @class   JniEsListenerManager
+ * @brief   This class provides functions for managing listeners
+ *
+ */
+template <class T>
+class JniEsListenerManager
+{
+    public:
+        /**
+         * API for Adding the Listener to listener Map.
+         *
+         * @param owner - JniRemoteEnrollee
+         */
+        T *addListener(JNIEnv *env, jobject jListener, JniRemoteEnrollee *owner)
+        {
+            T *onEventListener = NULL;
+
+            m_mapMutex.lock();
+
+            for (auto it = m_listenerMap.begin(); it != m_listenerMap.end(); ++it)
+            {
+                if (env->IsSameObject(jListener, it->first))
+                {
+                    auto refPair = it->second;
+                    onEventListener = refPair.first;
+                    refPair.second++;
+                    it->second = refPair;
+                    m_listenerMap.insert(*it);
+                    LOGD("OnEventListener: ref. count is incremented");
+                    break;
+                }
+            }
+            if (!onEventListener)
+            {
+                onEventListener = new T(env, jListener, owner);
+                jobject jgListener = env->NewGlobalRef(jListener);
+
+                if (jgListener)
+                {
+                    m_listenerMap.insert(
+                        std::pair < jobject,
+                        std::pair<T *, int >> (jgListener, std::pair<T *, int>(onEventListener, 1)));
+                }
+                else
+                {
+                    LOGD("OnEventListener: Failed to create global listener ref.");
+                    delete onEventListener;
+                }
+                LOGD("OnEventListener: new listener");
+            }
+            m_mapMutex.unlock();
+            return onEventListener;
+        }
+
+        /**
+         * @brief API for removing the Listener from listener Map.
+         */
+        void removeListener(JNIEnv *env, jobject jListener)
+        {
+            m_mapMutex.lock();
+            for (auto it = m_listenerMap.begin(); it != m_listenerMap.end(); ++it)
+            {
+                if (env->IsSameObject(jListener, it->first))
+                {
+                    auto refPair = it->second;
+                    if (refPair.second > 1)
+                    {
+                        refPair.second--;
+                        it->second = refPair;
+                        m_listenerMap.insert(*it);
+                        LOGI("OnEventListener: ref. count is decremented");
+                    }
+                    else
+                    {
+                        env->DeleteGlobalRef(it->first);
+                        T *listener = refPair.first;
+                        delete listener;
+                        m_listenerMap.erase(it);
+
+                        LOGI("OnEventListener is removed");
+                    }
+                    break;
+                }
+            }
+            m_mapMutex.unlock();
+        }
+
+        /**
+         * @brief API for removing all the Listener from listener Map.
+         */
+        void removeAllListeners(JNIEnv *env)
+        {
+            m_mapMutex.lock();
+
+            for (auto &pair : m_listenerMap)
+            {
+                env->DeleteGlobalRef(pair.first);
+                auto refPair = pair.second;
+                delete refPair.first;
+            }
+            m_listenerMap.clear();
+
+            m_mapMutex.unlock();
+        }
+
+    private:
+        std::map<jobject, std::pair<T *, int>> m_listenerMap;
+        std::mutex m_mapMutex;
+};
+
+#endif //__JNI_ES_LISTENER_MANAGER_H_
diff --git a/service/easy-setup/mediator/richsdk/android/jni/JniEsUtils.cpp b/service/easy-setup/mediator/richsdk/android/jni/JniEsUtils.cpp
new file mode 100644 (file)
index 0000000..991ad31
--- /dev/null
@@ -0,0 +1,62 @@
+/******************************************************************
+ *
+ * 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 "JniEsUtils.h"
+
+void throwESException(JNIEnv *env, std::string reason)
+{
+    jobject ex = env->NewObject(g_cls_ESException, g_mid_ESException_ctor,
+                                env->NewStringUTF(reason.c_str()));
+    if (!ex)
+    {
+        LOGI("throwException : jobject is NULL");
+    }
+    env->Throw((jthrowable)ex);
+}
+
+OCConnectivityType  getOCConnectivityTypeFromInt(int connectivityType)
+{
+    switch (connectivityType)
+    {
+        case CT_DEFAULT:
+            return CT_DEFAULT;
+        case CT_ADAPTER_IP:
+            return CT_ADAPTER_IP;
+
+            //May be need to add more types, if easy setup service support more transport.
+    }
+    return CT_DEFAULT;
+}
+
+int convertNativeProvisionStateToInt(EasySetupState nativeState)
+{
+    switch (nativeState)
+    {
+        case EasySetupState::DEVICE_PROVISIONED:
+            return 0;
+        case EasySetupState::DEVICE_NOT_PROVISIONED:
+            return 1;
+        case EasySetupState::DEVICE_OWNED:
+            return 2;
+        case EasySetupState::DEVICE_NOT_OWNED:
+            return 3;
+    }
+    return -1;
+}
\ No newline at end of file
diff --git a/service/easy-setup/mediator/richsdk/android/jni/JniEsUtils.h b/service/easy-setup/mediator/richsdk/android/jni/JniEsUtils.h
new file mode 100644 (file)
index 0000000..f65a68c
--- /dev/null
@@ -0,0 +1,55 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+/**
+  * @file   JniESUtils.h
+  *
+  * @brief  This file contains the utility functions for JNI layer
+  */
+
+#ifndef __JNI_ES_UTILS_H_
+#define __JNI_ES_UTILS_H_
+
+#include <jni.h>
+#include <string>
+
+#include "ESRichCommon.h"
+#include "octypes.h"
+
+#include "JniJvm.h"
+
+using namespace OIC::Service;
+
+/**
+ * @brief Throw the Exception to the java layer
+ */
+void throwESException(JNIEnv *env, std::string reason);
+
+/**
+* @brief Convert integer to OCconnectivity Enum
+*/
+OCConnectivityType  getOCConnectivityTypeFromInt(int connectivityType);
+
+/**
+* @brief Convert EasySetupState Enum Value to int
+*/
+int convertNativeProvisionStateToInt(EasySetupState nativeState);
+
+#endif //__JNI_ES_UTILS_H_
diff --git a/service/easy-setup/mediator/richsdk/android/jni/JniJvm.cpp b/service/easy-setup/mediator/richsdk/android/jni/JniJvm.cpp
new file mode 100644 (file)
index 0000000..2e02060
--- /dev/null
@@ -0,0 +1,80 @@
+/******************************************************************
+ *
+ * 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 "JniJvm.h"
+
+JavaVM *g_jvm = NULL;
+
+jclass g_cls_RemoteEnrollee = NULL;
+jclass g_cls_ESException = NULL;
+
+jmethodID g_mid_RemoteEnrollee_ctor = NULL;
+jmethodID g_mid_ESException_ctor = NULL;
+
+// JNI OnLoad
+JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
+{
+    LOGI("JNI_OnLoad");
+    JNIEnv *env;
+    g_jvm = vm;
+
+    if (g_jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION) != JNI_OK)
+    {
+        LOGE("Failed to get the environment using GetEnv()");
+        return JNI_ERR;
+    }
+
+    jclass clazz = nullptr;
+
+    //Remote Enrollee
+    clazz = env->FindClass("org/iotivity/service/easysetup/mediator/RemoteEnrollee");
+    if (!clazz) return JNI_ERR;
+    g_cls_RemoteEnrollee = (jclass)env->NewGlobalRef(clazz);
+    env->DeleteLocalRef(clazz);
+
+    g_mid_RemoteEnrollee_ctor = env->GetMethodID(g_cls_RemoteEnrollee, "<init>",
+                                "(J)V");
+    if (!g_mid_RemoteEnrollee_ctor) return JNI_ERR;
+
+    //ESException
+    clazz = env->FindClass("org/iotivity/service/easysetup/mediator/ESException");
+    if (!clazz) return JNI_ERR;
+    g_cls_ESException = (jclass)env->NewGlobalRef(clazz);
+    env->DeleteLocalRef(clazz);
+
+    g_mid_ESException_ctor = env->GetMethodID(g_cls_ESException, "<init>", "(Ljava/lang/String;)V");
+    if (!g_mid_ESException_ctor) return JNI_ERR;
+
+    return JNI_CURRENT_VERSION;
+}
+
+//JNI OnUnload
+JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)
+{
+    LOGI("JNI_OnUnload");
+    JNIEnv *env;
+
+    if (g_jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION) != JNI_OK)
+    {
+        LOGE("Failed to get the environment using GetEnv()");
+        return;
+    }
+    env->DeleteGlobalRef(g_cls_RemoteEnrollee);
+    env->DeleteGlobalRef(g_cls_ESException);
+}
diff --git a/service/easy-setup/mediator/richsdk/android/jni/JniJvm.h b/service/easy-setup/mediator/richsdk/android/jni/JniJvm.h
new file mode 100644 (file)
index 0000000..8f69842
--- /dev/null
@@ -0,0 +1,112 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+/**
+  * @file   JniJvm.h
+  *
+  * @brief  This file contains the essential declarations and functions required
+  *            for JNI implementation
+  */
+
+#ifndef __JNI_ES_JVM_H
+#define __JNI_ES_JVM_H
+
+#include <jni.h>
+#include<string>
+#include <android/log.h>
+
+#define ESTAG "ES-JNI"
+#define JNI_CURRENT_VERSION JNI_VERSION_1_6
+
+#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, ESTAG, __VA_ARGS__)
+#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, ESTAG, __VA_ARGS__)
+#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, ESTAG, __VA_ARGS__)
+
+extern JavaVM *g_jvm;
+
+extern jclass g_cls_RemoteEnrollee;
+extern jclass g_cls_ESException;
+
+extern jmethodID g_mid_RemoteEnrollee_ctor ;
+extern jmethodID g_mid_ESException_ctor;
+
+typedef void(*RemoveListenerCallback)(JNIEnv *env, jobject jListener);
+
+/**
+ * @brief Get the native handle field
+ */
+static jfieldID ESGetHandleField(JNIEnv *env, jobject jobj)
+{
+    jclass cls = env->GetObjectClass(jobj);
+    return env->GetFieldID(cls, "m_nativeHandle", "J");
+}
+
+/**
+ * @brief Get the native handle
+ */
+template <typename T>
+static T *ESGetHandle(JNIEnv *env, jobject jobj)
+{
+    jlong handle = env->GetLongField(jobj, ESGetHandleField(env, jobj));
+    return reinterpret_cast<T *>(handle);
+}
+
+/**
+ * @brief Set the native handle
+ */
+template <typename T>
+static void ESSetHandle(JNIEnv *env, jobject jobj, T *type)
+{
+    jlong handle = reinterpret_cast<jlong>(type);
+
+    env->SetLongField(jobj, ESGetHandleField(env, jobj), handle);
+}
+
+/**
+ * @brief Get the JNI Environment
+ */
+static JNIEnv *GetESJNIEnv(jint &ret)
+{
+    JNIEnv *env = NULL;
+
+    ret = g_jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION);
+    switch (ret)
+    {
+        case JNI_OK:
+            return env;
+        case JNI_EDETACHED:
+            if (g_jvm->AttachCurrentThread(&env, NULL) < 0)
+            {
+                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;
+    }
+}
+#endif // __JNI_ES_JVM_H
diff --git a/service/easy-setup/mediator/richsdk/android/jni/JniProvisioningStatusLisener.cpp b/service/easy-setup/mediator/richsdk/android/jni/JniProvisioningStatusLisener.cpp
new file mode 100644 (file)
index 0000000..94b15d2
--- /dev/null
@@ -0,0 +1,107 @@
+/******************************************************************
+ *
+ * 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 "JniProvisioningStatusListener.h"
+#include "JniRemoteEnrollee.h"
+
+using namespace OIC::Service;
+
+JniProvisioningStatusListener::JniProvisioningStatusListener(JNIEnv *env, jobject jListener,
+        JniRemoteEnrollee *owner)
+    : m_ownerResource(owner)
+{
+    m_jwListener = env->NewWeakGlobalRef(jListener);
+}
+
+JniProvisioningStatusListener::~JniProvisioningStatusListener()
+{
+    LOGI("~JniProvisioningStatusListener()");
+    if (m_jwListener)
+    {
+        jint ret;
+        JNIEnv *env = GetESJNIEnv(ret);
+        if (NULL == env) return;
+        env->DeleteWeakGlobalRef(m_jwListener);
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+    }
+}
+
+void JniProvisioningStatusListener::provisionStatusCallback (std::shared_ptr<EasySetupStatus>
+        easySetupStatus)
+{
+
+    LOGI("JniProvisioningStatusListener::provisioiningStatusCallback enter");
+
+    jint ret;
+    JNIEnv *env = GetESJNIEnv(ret);
+    if (NULL == 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;
+    }
+
+    jmethodID midL = env->GetMethodID(clsL, "onStatusRecieved",
+                                      "(I)V");
+    if (!midL)
+    {
+        checkExAndRemoveListener(env);
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        return;
+    }
+
+    EasySetupState nativeProvisioningState = easySetupStatus->getEasySetupState();
+    int provisionState = convertNativeProvisionStateToInt(nativeProvisioningState);
+    env->CallVoidMethod(jListener, midL, provisionState);
+    if (env->ExceptionCheck())
+    {
+        LOGE("Java exception is thrown");
+        checkExAndRemoveListener(env);
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        return;
+    }
+
+    if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+}
+
+void JniProvisioningStatusListener::checkExAndRemoveListener(JNIEnv *env)
+{
+    if (env->ExceptionCheck())
+    {
+        jthrowable ex = env->ExceptionOccurred();
+        env->ExceptionClear();
+        m_ownerResource->removeProvisioningStatusListener(env, m_jwListener);
+        env->Throw((jthrowable)ex);
+    }
+    else
+    {
+        m_ownerResource->removeProvisioningStatusListener(env, m_jwListener);
+    }
+}
diff --git a/service/easy-setup/mediator/richsdk/android/jni/JniProvisioningStatusListener.h b/service/easy-setup/mediator/richsdk/android/jni/JniProvisioningStatusListener.h
new file mode 100644 (file)
index 0000000..8b37cac
--- /dev/null
@@ -0,0 +1,68 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+/** @file   JniProvisioningStatusListener.h
+ *
+ *   @brief  This file contains JNI Provisioing status Listener class
+ */
+
+#ifndef __JNI_ES_PROVISIONING_STATUS_LISTENER_H_
+#define __JNI_ES_PROVISIONING_STATUS_LISTENER_H_
+
+#include <jni.h>
+
+#include "RemoteEnrollee.h"
+#include "ESRichCommon.h"
+
+#include "JniJvm.h"
+
+class JniRemoteEnrollee;
+
+using namespace OIC::Service;
+
+/**
+ * @class   JniProvisioningStatusListener
+ * @brief   This class provides functions for handling the provisioning status callback between the Java and native layer
+ *
+ */
+class JniProvisioningStatusListener
+{
+    public:
+        /**
+         * @brief constructor
+         */
+        JniProvisioningStatusListener(JNIEnv *env, jobject jListener, JniRemoteEnrollee *resource);
+
+        /**
+         * @brief destructor
+        */
+        ~JniProvisioningStatusListener();
+
+        /**
+         * @brief callback function that will be passed to Native layer
+        */
+        void provisionStatusCallback (std::shared_ptr<EasySetupStatus> easySetupStatus);
+
+    private:
+        jweak m_jwListener;
+        JniRemoteEnrollee *m_ownerResource;
+        void checkExAndRemoveListener(JNIEnv *env);
+};
+
+#endif //__JNI_ES_PROVISIONING_STATUS_LISTENER_H_
diff --git a/service/easy-setup/mediator/richsdk/android/jni/JniRemoteEnrollee.cpp b/service/easy-setup/mediator/richsdk/android/jni/JniRemoteEnrollee.cpp
new file mode 100644 (file)
index 0000000..353d642
--- /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 "JniRemoteEnrollee.h"
+
+using namespace OIC::Service;
+
+JniRemoteEnrollee::JniRemoteEnrollee(std::shared_ptr<RemoteEnrollee> remoteEnrollee)
+    : m_sharedResource(remoteEnrollee) {}
+
+JniRemoteEnrollee::~JniRemoteEnrollee()
+{
+    LOGD("JniRemoteEnrollee::~JniRemoteEnrollee()");
+    m_sharedResource = NULL;
+
+    jint envRet;
+    JNIEnv *env = GetESJNIEnv(envRet);
+    if (NULL == env) return;
+
+    if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+
+}
+
+JniRemoteEnrollee *JniRemoteEnrollee::getJniRemoteEnrollee(JNIEnv *env, jobject thiz)
+{
+    JniRemoteEnrollee *remoteEnrollee = ESGetHandle<JniRemoteEnrollee>(env, thiz);
+    if (env->ExceptionCheck())
+    {
+        LOGE("getJniRemoteEnrollee :: Failed to get native handle from RemoteEnrollee object");
+    }
+    if (!remoteEnrollee)
+    {
+        LOGE("getJniRemoteEnrollee :: no resource");
+    }
+    return remoteEnrollee;
+}
+
+void JniRemoteEnrollee::startProvisioning(JNIEnv *env)
+{
+    try
+    {
+        m_sharedResource->startProvisioning();
+    }
+    catch (ESBadRequestException exception)
+    {
+        LOGE("JNI startProvisioning :: Exception occured");
+        //throw the exception to java
+        throwESException( env,  exception.what());
+    }
+}
+void JniRemoteEnrollee::stopProvisioning(JNIEnv *env)
+{
+    try
+    {
+        m_sharedResource->stopProvisioning();
+    }
+    catch (ESBadRequestException exception)
+    {
+        LOGE("JNI stopProvisioning :: Exception occured");
+        //throw the exception to java
+        throwESException( env,  exception.what());
+    }
+}
+
+void JniRemoteEnrollee::registerProvisioningHandler(JNIEnv *env, jobject jListener)
+{
+    JniProvisioningStatusListener *onProvisioningStatusReceived = addProvisioningStatusListener(env,
+            jListener);
+
+    RemoteEnrollee::EasySetupStatusCB provisionStatusCallback = [onProvisioningStatusReceived]
+            (std::shared_ptr< OIC::Service::EasySetupStatus > easySetupStatus)
+
+    {
+        onProvisioningStatusReceived->provisionStatusCallback(easySetupStatus);
+    };
+
+    try
+    {
+        m_sharedResource->registerEasySetupStatusHandler(provisionStatusCallback);
+    }
+    catch (ESException exception)
+    {
+        LOGE("JNI stopProvisioning :: Exception occured");
+        //throw the exception to java
+        throwESException( env,  exception.what());
+    }
+
+}
+
+JniProvisioningStatusListener *JniRemoteEnrollee::addProvisioningStatusListener(JNIEnv *env,
+        jobject jListener)
+{
+    return this->m_provisioingStatus.addListener(env, jListener, this);
+}
+
+void JniRemoteEnrollee::removeProvisioningStatusListener(JNIEnv *env, jobject jListener)
+{
+    this->m_provisioingStatus.removeListener(env, jListener);
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeStartProvision
+(JNIEnv *env, jobject jClass)
+{
+    LOGD("nativeStartProvision Enter");
+
+    JniRemoteEnrollee *remoteEnrollee = JniRemoteEnrollee::getJniRemoteEnrollee(env, jClass);
+    remoteEnrollee->startProvisioning(env);
+
+    LOGD("nativeStartProvision Exit");
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeStopProvision
+(JNIEnv *env, jobject jClass)
+{
+
+    LOGD("nativeStopProvision Enter");
+
+    JniRemoteEnrollee *remoteEnrollee = JniRemoteEnrollee::getJniRemoteEnrollee(env, jClass);
+    remoteEnrollee->stopProvisioning(env);
+
+    LOGD("nativeStopProvision Exit");
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeRegisterProvisioningHandler
+(JNIEnv *env, jobject jClass, jobject provisiongListener)
+{
+    LOGD("nativeRegisterProvisioningHandler Enter");
+
+    if (!provisiongListener)
+    {
+        LOGE("nativeRegisterProvisioningHandler : listener is NULL");
+        return;
+    }
+    JniRemoteEnrollee *remoteEnrollee = JniRemoteEnrollee::getJniRemoteEnrollee(env, jClass);
+    remoteEnrollee->registerProvisioningHandler(env, provisiongListener);
+
+    LOGD("nativeRegisterProvisioningHandler Exit");
+}
+
diff --git a/service/easy-setup/mediator/richsdk/android/jni/JniRemoteEnrollee.h b/service/easy-setup/mediator/richsdk/android/jni/JniRemoteEnrollee.h
new file mode 100644 (file)
index 0000000..de1f297
--- /dev/null
@@ -0,0 +1,109 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+/** @file   JniRemoteEnrollee.h
+ *
+ *   @brief  This file contains the JniRemoteEnrollee class
+ *               & declaration of RemoteEnrollee APIs for JNI implementation
+ */
+
+#ifndef __JNI_ES_REMOTEENROLLEE_H
+#define __JNI_ES_REMOTEENROLLEE_H
+
+#include "RemoteEnrollee.h"
+#include "ESRichCommon.h"
+#include "ESException.h"
+
+#include "JniJvm.h"
+#include "JniEsUtils.h"
+#include "JniProvisioningStatusListener.h"
+#include "JniEsListenerManager.h"
+
+using namespace OIC::Service;
+
+/**
+ * @class   JniRemoteEnrollee
+ * @brief   This class contains all the APIs for RemoteEnrollee
+ *
+ * NOTE: JNI APIs internally call the APIs of this class.
+ */
+class JniRemoteEnrollee
+{
+    public:
+
+        /**
+        *@brief constructor
+        */
+        JniRemoteEnrollee(std::shared_ptr< RemoteEnrollee> remoteEnrollee);
+
+        /**
+         *@brief destructor
+        */
+        ~JniRemoteEnrollee();
+
+        // ***** JNI APIs internally call the APIs of this class ***** //
+
+        void startProvisioning(JNIEnv *env);
+        void stopProvisioning(JNIEnv *env);
+        void registerProvisioningHandler(JNIEnv *env, jobject jListener);
+
+        JniProvisioningStatusListener *addProvisioningStatusListener(JNIEnv *env, jobject jListener);
+        void removeProvisioningStatusListener(JNIEnv *env, jobject jListener);
+
+        static JniRemoteEnrollee *getJniRemoteEnrollee(JNIEnv *env, jobject thiz);
+
+    private:
+        JniEsListenerManager<JniProvisioningStatusListener> m_provisioingStatus;
+        std::shared_ptr<RemoteEnrollee> m_sharedResource;
+
+};
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * API for starting the provisioning process.
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeStartProvision
+(JNIEnv *env, jobject jClass);
+
+/**
+ * API for stopping the provisioning process.
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeStopProvision
+(JNIEnv *env, jobject jClass);
+
+/**
+ * API for setting the lisener for recieiving provisioning status.
+ *
+ * @param provisiongListener - Provisioning listener [callback from native layer will be passing to this listener]
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeRegisterProvisioningHandler
+(JNIEnv *env, jobject jClass, jobject provisiongListener);
+
+#ifdef __cplusplus
+}
+#endif
+#endif // __JNI_ES_REMOTEENROLLEE_H
diff --git a/service/easy-setup/mediator/richsdk/inc/ESException.h b/service/easy-setup/mediator/richsdk/inc/ESException.h
new file mode 100644 (file)
index 0000000..d5096bf
--- /dev/null
@@ -0,0 +1,185 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+
+#ifndef EASY_SETUP_EXCEPTION_H
+#define EASY_SETUP_EXCEPTION_H
+
+#include <string>
+#include <octypes.h>
+/**
+ * @file
+ *
+ * This file contains the declaration of exception classes for easy setup
+ */
+namespace OIC
+{
+    namespace Service
+    {
+
+        /**
+         * The base exception class for resource encapsulation.
+         *
+         */
+        class ESException: public std::exception
+        {
+        public:
+
+            /**
+             * Constructs an exception with an empty description.
+             */
+            ESException();
+
+            /**
+             * Constructs an exception with a description.
+             *
+             * @param what The description for the error.
+             */
+            explicit ESException(const std::string &what);
+
+            /**
+             * @overload
+             */
+            explicit ESException(std::string &&what);
+
+            virtual ~ESException() noexcept;
+
+            /**
+             * Returns the exception description.
+             *
+             */
+            virtual const char *what() const noexcept;
+
+        private:
+            /**
+             *  Exception description
+             */
+            const std::string m_what;
+        };
+
+        /**
+         * Thrown when OC layer returns an error.
+         *
+         */
+        class ESPlatformException: public ESException
+        {
+        public:
+
+            /**
+             * Constructs an exception with a description.
+             *
+             * @param OCStackResult The description for the error.
+             */
+            explicit ESPlatformException(OCStackResult reason);
+
+            /**
+             * Returns the reason.
+             *
+             */
+            OCStackResult getReasonCode() const;
+
+            /**
+             * This function returns description of the exception.
+             *
+             */
+            std::string getReason() const;
+
+        private:
+            OCStackResult m_reason;
+        };
+
+        /**
+         * Thrown when a request is not acceptable.
+         *
+         */
+        class ESBadRequestException: public ESException
+        {
+        public:
+            /**
+             * Constructs an exception with a description.
+             *
+             * @param OCStackResult The description for the error.
+             */
+            explicit ESBadRequestException(const std::string& what);
+            /**
+             * @overload
+             */
+            explicit ESBadRequestException(std::string&& what);
+        };
+
+        /**
+         * Thrown when a parameter is not valid.
+         *
+         */
+        class ESInvalidParameterException: public ESException
+        {
+        public:
+            /**
+             * Constructs an exception with a description.
+             *
+             * @param OCStackResult The description for the error.
+             */
+            explicit ESInvalidParameterException(const std::string& what);
+         /**
+             * @overload
+             */
+            explicit ESInvalidParameterException(std::string&& what);
+        };
+
+        /**
+         * Thrown when getting value with wrong template parameter.
+         */
+        class ESBadGetException: public ESException
+        {
+        public:
+            /**
+             * Constructs an exception with a description.
+             *
+             * @param OCStackResult The description for the error.
+             */
+            explicit ESBadGetException(const std::string& what);
+           /**
+             * @overload
+             */
+            explicit ESBadGetException(std::string&& what);
+        };
+
+        /**
+         * Thrown when a key is invalid.
+         *
+         */
+        class ESInvalidKeyException: public ESException
+        {
+        public:
+            /**
+             * Constructs an exception with a description.
+             *
+             * @param OCStackResult The description for the error.
+             */
+            explicit ESInvalidKeyException(const std::string& what);
+             /**
+             * @overload
+             */
+            explicit ESInvalidKeyException(std::string&& what);
+        };
+    }
+}
+
+#endif // EASY_SETUP_EXCEPTION_H
diff --git a/service/easy-setup/mediator/richsdk/inc/ESRichCommon.h b/service/easy-setup/mediator/richsdk/inc/ESRichCommon.h
new file mode 100755 (executable)
index 0000000..e9e344b
--- /dev/null
@@ -0,0 +1,381 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef ES_COMMON_RICH_H_
+#define ES_COMMON_RICH_H_
+
+#include <iostream>
+#include <string>
+#ifndef WITH_ARDUINO
+#include <memory>
+#endif
+
+#include "ocstack.h"
+#include "octypes.h"
+
+using namespace std;
+
+// Defines
+#define OIC_STRING_MAX_VALUE    100
+#define IPV4_ADDR_SIZE          16
+#define IP_PORT                 55555
+#define NET_WIFI_SSID_SIZE      100
+#define NET_WIFI_PWD_SIZE       100
+
+/**
+ * @brief Mac address length for BT port
+ */
+#define NET_MACADDR_SIZE 18
+
+/**
+ * Attributes used to form a proper easysetup conforming JSON message.
+ */
+#define OC_RSRVD_ES_PS                     "ps"
+#define OC_RSRVD_ES_TNN                    "tnn"
+#define OC_RSRVD_ES_CD                     "cd"
+#define OC_RSRVD_ES_TR                     "tr"
+#define OC_RSRVD_ES_TNT                    "tnt"
+#define OC_RSRVD_ES_ANT                    "ant"
+
+/**
+ * Easysetup defined resoruce types and uris.
+ */
+#define OC_RSRVD_ES_PROV_RES_TYPE           "oic.r.prov"
+#define OC_RSRVD_ES_URI_PROV               "/oic/prov"
+#define OC_RSRVD_ES_URI_NET                "/oic/net"
+
+/**
+ * @brief Defines for Provisioning status accepted values
+ */
+#define ES_PS_NEED_PROVISIONING         1
+#define ES_PS_PROVISIONING_COMPLETED    2
+#define ES_PS_TRIGGER_INIT_VALUE        0
+#define ES_PS_TRIGGER_CONNECTION        1
+
+#ifndef WITH_ARDUINO
+namespace OIC
+{
+    namespace Service
+    {
+
+        /**
+        * Device Roles defined for each device type used in easy setup
+        */
+        typedef enum
+        {
+            ENROLLEE,
+            MEDIATOR,
+            ENROLLER,
+        } DeviceRole;
+
+        /**
+        * On-boarding connection to create Adhoc network.
+        */
+        typedef enum
+        {
+            SOFTAP,
+            BLE,
+        } OBConnection;
+
+        typedef enum
+        {
+            ES_ERROR = -1,
+            ES_OK = 0,
+            ES_NETWORKFOUND = 1,
+            ES_NETWORKCONNECTED,
+            ES_NETWORKNOTCONNECTED,
+            ES_RESOURCECREATED = 11,
+            ES_RECVREQOFPROVRES = 21,
+            ES_RECVREQOFNETRES,
+            ES_RECVUPDATEOFPROVRES,
+            ES_RECVTRIGGEROFPROVRES,
+        } ESResult;
+
+        typedef enum
+        {
+            /**
+             * Default state of the device
+             */
+            ES_INIT_STATE,
+
+            /**
+             * Device will move to this state once the on boarding begins
+             */
+            ES_ON_BOARDING_STATE,
+
+            /**
+             * Device will move to this state after successful on-boarding of the device
+             */
+            ES_ON_BOARDED_STATE,
+
+            /**
+             * Device will move to this state once the on boarding is done
+             */
+            ES_PROVISIONING_STATE,
+
+            /**
+             * Easy setup process is successful.
+             */
+            ES_PROVISIONED_STATE,
+
+            /**
+             * This state is arbitrary one, any time device can come into this state
+             * Device will move to this state if the ownership transfer initiated  by the Application
+             */
+            ES_OWNERSHIP_TRANSFERRING_STATE,
+
+            /**
+             * This state is arbitrary one, any time device can come into this state
+             * Device will move to this state if the ownership transfer is completed
+             */
+            ES_OWNERSHIP_TRANSFERRED_STATE,
+
+            /**
+             * This state is arbitrary one, any time device can come into this state
+             * Device will move to this state once the Application factory reset the device
+             */
+            ES_FACTORY_RESET_STATE,
+
+            /**
+             * Enrollee moves to this state after connecting to target network
+             */
+            ES_ON_BOARDED_TARGET_NETWORK_STATE,
+        }EnrolleeState;
+
+        /**
+         * Provisioning Device Status
+         */
+        typedef struct
+        {
+            // Address of remote server
+            OCDevAddr * addr;
+            // Indicates adaptor type on which the response was received
+            OCConnectivityType connType;
+        } EasySetupDeviceInfo;
+
+        /**
+         * Provosioning Status
+         */
+        typedef enum
+        {
+            DEVICE_PROVISIONED = 0,
+            DEVICE_NOT_PROVISIONED,
+            DEVICE_OWNED,
+            DEVICE_NOT_OWNED
+        } EasySetupState, ProvStatus;
+
+        /**
+         * Response from queries to remote servers.
+         */
+        typedef struct
+        {
+            // EasySetup Status
+            EasySetupState provStatus;
+            // EasySetup Device Info
+            EasySetupDeviceInfo provDeviceInfo;
+        } EasySetupInfo, ProvisioningInfo;
+
+        /**
+         * @brief  Network information of the Enroller
+         */
+        typedef union
+        {
+            /**
+             * @brief BT Mac Information
+             */
+            struct
+            {
+                char btMacAddress[NET_MACADDR_SIZE];   /**< BT mac address **/
+            } BT;
+
+            /**
+             * @brief LE MAC Information
+             */
+            struct
+            {
+                char leMacAddress[NET_MACADDR_SIZE];   /**< BLE mac address **/
+            } LE;
+
+            /**
+             * @brief IP Information
+             */
+            struct
+            {
+                char ssid[NET_WIFI_SSID_SIZE]; /**< ssid of the Enroller**/
+                char pwd[NET_WIFI_PWD_SIZE]; /**< pwd of the Enroller**/
+            } WIFI;
+        } ProvData;
+
+        /**
+         * @brief Network Information
+         */
+        typedef struct
+        {
+            ProvData provData;    /**< Enroller Network Info**/
+            OCConnectivityType connType;    /**< Connectivity Type**/
+        } ProvConfig;
+
+        /**
+         * Client applications implement this callback to consume responses received from Servers.
+         */
+        typedef void (*OCProvisioningStatusCB)(EasySetupInfo *easySetupInfo);
+
+        /**
+         * @brief This structure represent configuration information to create wifi onboarding SoftAP or connection.
+        */
+
+        // Note : Below structure is not currently used but added for future purpose.
+        typedef struct
+        {
+            char ssid[NET_WIFI_SSID_SIZE]; /**< ssid of the onboarding Adhoc Wifi network**/
+            char pwd[NET_WIFI_PWD_SIZE]; /**< pwd of the onboarding Adhoc wifi network**/
+            bool isSecured;                 /**< Secure connection**/
+        }WiFiOnboardingConfig;
+
+        /**
+         * @brief This structure represent onboarding connection instance.
+        */
+        typedef struct
+        {
+         /*Actual use of ipAddress is for unicast discovery, but also used to identify the Enrollee device as of now,
+            device identification should be based on DeviceID in next release.*/
+           char ipAddress[IPV4_ADDR_SIZE]; /**< IP Address of the Enrollee **/
+           bool isSecured;                 /**< Secure connection**/
+        }WiFiOnboadingConnection;
+
+        typedef enum
+        {
+            ES_PROVISIONING_ERROR = -1,
+            ES_NEED_PROVISIONING,
+            ES_PROVISIONED_ALREADY,
+            ES_PROVISIONING_SUCCESS
+        } ESState;
+
+        typedef enum
+        {
+            ES_UNKNOWN = 0,
+            ES_ONBOARDED,
+            ES_OWNED,
+            ES_PROVISIONED
+        } CurrentESState;
+
+        typedef enum
+        {
+            ES_SEC_UNKNOWN = 0,
+            ES_SEC_OWNED,
+            ES_SEC_ACL_PROVISIONED,
+            ES_SEC_CREDS_PROVISIONED
+        } EnrolleeSecState;
+
+        /**
+         * Security Provisioning Status
+         */
+        class SecProvisioningResult
+        {
+        public:
+            std::shared_ptr< SecProvisioningResult > shared_ptr;
+            SecProvisioningResult(std::string deviceUUID, ESResult result) :
+                m_devUUID(deviceUUID), m_result(result)
+            {
+
+            }
+
+            std::string getDeviceUUID()
+            {
+                return m_devUUID;
+            }
+
+            ESResult getResult()
+            {
+                return m_result;
+            }
+        private:
+            std::string m_devUUID;
+            ESResult m_result;
+        };
+
+        /**
+         * Callback function definition for providing Enrollee security status .
+         */
+        typedef std::function< void(std::shared_ptr<SecProvisioningResult>) > EnrolleeSecStatusCb;
+
+        /**
+         * Callback definition to be invoked when the security stack expects a pin from application.
+         */
+        typedef std::function< void(std::string&) > SecurityPinCb;
+
+        /**
+         * Callback definition to be invoked when the stack expects a db path.
+         */
+        typedef std::function< void(std::string&) > SecProvisioningDbPathCb;
+
+        class ProvisioningStatus
+        {
+        public:
+            std::shared_ptr< ProvisioningStatus > shared_ptr;
+            ProvisioningStatus(ESResult result, ESState esState) :
+                    m_result(result), m_esState(esState)
+            {
+
+            }
+
+            ESResult getESResult()
+            {
+                return m_result;
+            }
+
+            ESState getESState()
+            {
+                return m_esState;
+            }
+        private:
+            ESResult m_result;
+            ESState m_esState;
+        };
+
+        class EasySetupStatus
+        {
+        public:
+            std::shared_ptr< EasySetupStatus > shared_ptr;
+            EasySetupStatus(const EasySetupState& easySetupState,
+                    const ProvConfig& provConfig) :
+                    m_easySetupState(easySetupState), m_ProvConfig(provConfig)
+            {
+
+            }
+
+            ProvConfig getProvConfig()
+            {
+                return m_ProvConfig;
+            }
+
+            EasySetupState getEasySetupState()
+            {
+                return m_easySetupState;
+            }
+        private:
+            EasySetupState m_easySetupState;
+            ProvConfig m_ProvConfig;
+        };
+    }
+}
+#endif //WITH_ARDUINO
+
+#endif //ES_COMMON_RICH_H_
diff --git a/service/easy-setup/mediator/richsdk/inc/EasySetup.h b/service/easy-setup/mediator/richsdk/inc/EasySetup.h
new file mode 100644 (file)
index 0000000..b7914f4
--- /dev/null
@@ -0,0 +1,81 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef EASYSETUP_H_
+#define EASYSETUP_H_
+
+#include <memory>
+#include <vector>
+
+#include "ESRichCommon.h"
+#include "RemoteEnrollee.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+        class RemoteEnrollee;
+
+        /**
+         * This provides methods for Mediator devices to perform EasySetup of Enrollee devices.
+         * EasySetup involves
+         * 1) Ownership transfer for enabling secured communication between Mediator and Enrollee
+         * devices.
+         * 2) Provisioning of Enrollee devices using the credentails of target Enroller devices.
+         */
+        class EasySetup
+        {
+        public:
+            /**
+             * API for getting the instance of EasySetup singleton class.
+             * @return EasySetup instance.
+             */
+            static EasySetup* getInstance();
+
+            /**
+             * This API is used for creating a remote Enrollee device instance.
+             * @param ProvConfig Provisioning information for configuring the Enrollee.
+             * @param WiFiOnboadingConnection Onboarding connection information for configuring the Enrollee.
+             *
+             * @throws ESBadRequestException If createEnrolleeDevice is invoked with the same
+             *         provisioning information.
+             *
+             * @return Pointer to RemoteEnrollee instance.
+             */
+            std::shared_ptr<RemoteEnrollee> createEnrolleeDevice (
+                         const ProvConfig& enrolleeNWProvInfo,
+                         const WiFiOnboadingConnection& wifiOnboardingconn);
+        private:
+            EasySetup();
+            ~EasySetup();
+
+            RemoteEnrollee::shared_ptr findDeviceInProvisioningList(
+                                const ProvConfig& enrolleeNWProvInfo,
+                                const WiFiOnboadingConnection& wifiOnboardingconn);
+            bool addDeviceToProvisioningList(const RemoteEnrollee::shared_ptr remoteEnrollee);
+            bool deleteDeviceFromProvisioningList (const ProvConfig& enrolleeNWProvInfo);
+
+            std::vector< RemoteEnrollee::shared_ptr > m_activeEnrolleeList;
+            static EasySetup *s_instance;
+        };
+    }
+}
+
+#endif /* EASYSETUP_H_ */
diff --git a/service/easy-setup/mediator/richsdk/inc/EnrolleeSecurity.h b/service/easy-setup/mediator/richsdk/inc/EnrolleeSecurity.h
new file mode 100755 (executable)
index 0000000..5308b0b
--- /dev/null
@@ -0,0 +1,69 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef ENROLLEE_SECURITY_H_
+#define ENROLLEE_SECURITY_H_
+
+#include <functional>
+
+#include "ESRichCommon.h"
+#include "OCProvisioningManager.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+#define ENROLEE_SECURITY_TAG "ENROLEE_SECURITY"
+
+        class RemoteEnrolleeResource;
+        class OCSecureResource;
+
+        /**
+         * This class contains the methods needed for security  layer interaction.
+         *
+         * @see EnrolleeSecurity
+         */
+        class EnrolleeSecurity
+        {
+        public:
+            EnrolleeSecurity(std::shared_ptr< RemoteEnrolleeResource > remoteEnrolleeResource,
+            std::string secDbPath);
+            ESResult registerCallbackHandler(EnrolleeSecStatusCb enrolleeSecStatusCb,
+                    SecurityPinCb securityPinCb, SecProvisioningDbPathCb secProvisioningDbPathCb);
+            EasySetupState performOwnershipTransfer();
+
+        private:
+            std::shared_ptr< RemoteEnrolleeResource > m_remoteEnrolleeResource;
+            EnrolleeSecStatusCb m_enrolleeSecStatusCb;
+            SecurityPinCb m_securityPinCb;
+            SecProvisioningDbPathCb m_secProvisioningDbPathCb;
+            std::shared_ptr< OC::OCSecureResource > m_unownedDevice;
+
+            EnrolleeSecState m_enrolleeSecState;std::shared_ptr< OC::OCSecureResource > m_securedResource;
+
+            std::shared_ptr< OC::OCSecureResource > getEnrollee(OC::DeviceList_t &list);
+            void ownershipTransferCb(OC::PMResultList_t *result, int hasError);
+            void convertUUIDToString(OicUuid_t uuid, std::string& uuidString);
+        };
+    }
+}
+
+#endif /* ENROLLEE_SECURITY_H_*/
+
diff --git a/service/easy-setup/mediator/richsdk/inc/RemoteEnrollee.h b/service/easy-setup/mediator/richsdk/inc/RemoteEnrollee.h
new file mode 100644 (file)
index 0000000..1fb83b3
--- /dev/null
@@ -0,0 +1,152 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef REMOTE_ENROLLEE_H_
+#define REMOTE_ENROLLEE_H_
+
+#include "ESRichCommon.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+        class RemoteEnrolleeResource;
+        class EnrolleeSecurity;
+
+        /**
+         * This class represents Remote Enrollee device instance.
+         * It will provide APIs for Mediator to perform operations to enable the Enrollee device
+         * to connect to the Enroller.
+         */
+        class RemoteEnrollee
+        {
+        public:
+            /**
+             * RemoteEnrollee constructor
+             *
+             * @param enrolleeNWProvInfo Provisioning information for the Enrollee
+             *
+             * @throw ESBadRequestException is thrown if the parameters are invalid
+             */
+            RemoteEnrollee(const ProvConfig& enrolleeNWProvInfo, const WiFiOnboadingConnection& connection) ;
+
+            ~RemoteEnrollee() = default;
+
+            typedef std::shared_ptr< RemoteEnrollee > shared_ptr;
+
+            /**
+             * Callback definition to be invoked when EasySetup status is changed.
+             * The same callback will be invoked when there is an error in the
+             * EasySetup process.
+             *
+             * @see registerResourceHandler
+             * @see ResourceState
+             */
+            typedef std::function< void(std::shared_ptr< EasySetupStatus >) >
+                                                                        EasySetupStatusCB;
+
+#ifdef __WITH_DTLS__
+            /**
+             * Register Security status and other information callback handlers.
+             *
+             * @param secProvisioningDbCb Callback to be invoked when the stack expects a
+             *        path for the provisioning db.
+             * @param securityPinCb Callback to get security pin during pin based ownership transfer.
+             *
+             * @throws InvalidParameterException If callback is an empty function or null.
+             * @throws ESBadRequestException If registration is already completed.
+             *
+             * @see SecProvisioningResult
+             */
+            ESResult registerSecurityCallbackHandler(SecurityPinCb securityPinCb,
+                    SecProvisioningDbPathCb secProvisioningDbPathCb);
+#endif //__WITH_DTLS__
+
+            /**
+             * Register EasySetup status handler.
+             *
+             * @param callback Callback to get EasySetup status.
+             * @param secProvisioningDbCB Callback to be invoked when the stack expects a
+             *        path for the provisioning db.
+             *
+             * @throws InvalidParameterException If callback is an empty function or null.
+             * @throws ESBadRequestException If registration is already completed.
+             *
+             * @see EasySetupStatus
+             */
+            void registerEasySetupStatusHandler(EasySetupStatusCB callback);
+
+            /**
+             * Start provisioning of target Enrollers information to the Enrollee.
+             *
+             * @throws ESBadRequestException If RemoteEnrollee device not created prior to this call.
+             *
+             * @see RemoteEnrollee
+             */
+            void startProvisioning();
+
+            /**
+             * Stop provisioning process that is currently in progress.
+             *
+             * @throws BadRequestException If provisioning is not in progress.
+             */
+            void stopProvisioning();
+
+            /**
+             * Check if the Enrollee device provisioned.
+             */
+            bool isEnrolleeProvisioned();
+
+            /**
+             * Get the Provisioning information provided for the current Enrollee.
+             *
+             * @return ProvConfig Provisioning information provided for the current Enrollee.
+             */
+            ProvConfig getProvConfig ();
+
+            /**
+             * Get the Onboarding connection information between Mediator and Enrollee.
+             *
+             * @return WiFiOnboadingConnection information between Mediator and Enrollee.
+             */
+
+            WiFiOnboadingConnection getOnboardConn();
+
+        private:
+            std::shared_ptr< RemoteEnrolleeResource > m_remoteResource;
+            EasySetupStatusCB m_easySetupStatusCb;
+            EnrolleeSecStatusCb m_enrolleeSecStatusCb;
+            SecurityPinCb m_securityPinCb;
+            SecProvisioningDbPathCb m_secProvisioningDbPathCb;
+            ProvConfig m_ProvConfig;
+            WiFiOnboadingConnection m_wifiOnboardingconn;
+
+            std::shared_ptr< EnrolleeSecurity > m_enrolleeSecurity;
+            CurrentESState m_currentESState;
+            bool m_isSecured;
+
+            void provisioningStatusHandler (std::shared_ptr< ProvisioningStatus > provStatus);
+            void easySetupSecurityStatusCallback(
+            std::shared_ptr< SecProvisioningResult > secProvisioningResult);
+        };
+    }
+}
+
+#endif //REMOTE_ENROLLEE_H_
diff --git a/service/easy-setup/mediator/richsdk/inc/RemoteEnrolleeResource.h b/service/easy-setup/mediator/richsdk/inc/RemoteEnrolleeResource.h
new file mode 100755 (executable)
index 0000000..6828a9b
--- /dev/null
@@ -0,0 +1,131 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef REMOTE_ENROLLEE_RESOURCE_H_
+#define REMOTE_ENROLLEE_RESOURCE_H_
+
+#include <mutex>
+#include <memory>
+
+#include "ESRichCommon.h"
+
+#include "OCApi.h"
+
+using namespace OC;
+
+namespace OIC
+{
+    namespace Service
+    {
+        class OCResource;
+        class EnrolleeSecurity;
+
+        /**
+         * This class contains the resource discovery methods.
+         *
+         * @see RemoteEnrolleeResource
+         */
+        class RemoteEnrolleeResource
+        {
+            friend class EnrolleeSecurity;
+
+        public:
+            typedef std::shared_ptr< RemoteEnrolleeResource > Ptr;
+
+            typedef std::function< void(std::shared_ptr< ProvisioningStatus >) > ProvStatusCb;
+
+            /**
+             * RemoteEnrolleeResource constructor
+             *
+             * @param enrolleeNWProvInfo Provisioning information for the Enrollee
+             *
+             * @throw ESBadRequestException is thrown if the parameters are invalid
+             */
+            RemoteEnrolleeResource(const ProvConfig &enrolleeNWProvInfo,
+                                               const WiFiOnboadingConnection &onboardingconn);
+
+            ~RemoteEnrolleeResource() = default;
+
+            /**
+             * Register provisioning status handler.
+             *
+             * @param callback Callback to get Provisioning status.
+             *
+             * @throws InvalidParameterException If callback is an empty function or null.
+             * @throws ESBadRequestException If registration is already completed.
+             *
+             * @see ProvisioningStatus
+             */
+            void registerProvStatusCallback (ProvStatusCb provStatusCb);
+
+            /**
+             * Construct Remote OIC resource using the enrollee host and connectivity information
+             * provided in the constructor of RemoteEnrolleeResource.
+             *
+             * @throws InvalidParameterException If the provided information is invalid.
+             * @throws ESBadRequestException If resource is already constructed.
+             *
+             * @see ProvisioningStatus
+             */
+            ESResult constructResourceObject();
+
+            /**
+             * Function for provisioning of Remote Enrollee resource using the information provided.
+             *
+             * @throws InvalidParameterException If cb is empty.
+             */
+            void provisionEnrollee();
+
+            /**
+             * Function for unprovisioning of Remote Enrollee and bring to unprovisioned state
+             *
+             * @throws ESBadRequestException If device is not provisioned already.
+             */
+            void unprovisionEnrollee();
+
+
+
+        private:
+            std::shared_ptr< OC::OCResource > m_ocResource;
+            std::mutex m_mutex;
+            ProvStatusCb m_provStatusCb;
+            ProvConfig m_ProvConfig;
+            WiFiOnboadingConnection m_wifiOnboardingconn;
+            bool m_discoveryResponse;
+
+            void getProvStatusResponse(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                    const int eCode);
+
+            void checkProvInformationCb(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                    const int eCode);
+
+            ESResult ESDiscoveryTimeout(unsigned short waittime);
+
+            void onDeviceDiscovered(std::shared_ptr<OC::OCResource> resource);
+
+            void triggerNetworkConnection();
+
+            void triggerNetworkConnectionCb(
+                    const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                    const int eCode);
+        };
+    }
+}
+#endif
diff --git a/service/easy-setup/mediator/richsdk/src/ESException.cpp b/service/easy-setup/mediator/richsdk/src/ESException.cpp
new file mode 100644 (file)
index 0000000..9551a5a
--- /dev/null
@@ -0,0 +1,114 @@
+//******************************************************************
+//
+// 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 "ESException.h"
+
+#include "OCException.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+
+        ESException::ESException()
+        {
+        }
+
+        ESException::ESException(const std::string& what) :
+                m_what{ what }
+        {
+        }
+
+        ESException::ESException(std::string&& what) :
+                m_what{ std::move(what) }
+        {
+        }
+
+        ESException::~ESException() noexcept
+        {
+        }
+
+        const char* ESException::what() const noexcept
+        {
+            return m_what.c_str();
+        }
+
+
+        ESPlatformException::ESPlatformException(OCStackResult reason) :
+                ESException{ "Failed : " + OC::OCException::reason(reason) },
+                m_reason { reason }
+        {
+        }
+
+        OCStackResult ESPlatformException::getReasonCode() const
+        {
+            return m_reason;
+        }
+
+        std::string ESPlatformException::getReason() const
+        {
+            return  OC::OCException::reason(m_reason);
+        }
+
+
+        ESBadRequestException::ESBadRequestException(const std::string& what) :
+                ESException{ what }
+        {
+        }
+
+        ESBadRequestException::ESBadRequestException(std::string&& what) :
+                ESException{ std::move(what) }
+        {
+        }
+
+
+        ESInvalidParameterException::ESInvalidParameterException(const std::string& what) :
+                ESException{ what }
+        {
+        }
+
+        ESInvalidParameterException::ESInvalidParameterException(std::string&& what) :
+                ESException{ std::move(what) }
+        {
+        }
+
+
+        ESBadGetException::ESBadGetException(const std::string& what) :
+                ESException{ what }
+        {
+        }
+
+        ESBadGetException::ESBadGetException(std::string&& what) :
+                ESException{ std::move(what) }
+        {
+        }
+
+
+        ESInvalidKeyException::ESInvalidKeyException(const std::string& what) :
+                ESException{ what }
+        {
+        }
+
+        ESInvalidKeyException::ESInvalidKeyException(std::string&& what) :
+                ESException{ std::move(what) }
+        {
+        }
+    }
+}
diff --git a/service/easy-setup/mediator/richsdk/src/EasySetup.cpp b/service/easy-setup/mediator/richsdk/src/EasySetup.cpp
new file mode 100644 (file)
index 0000000..3a6929e
--- /dev/null
@@ -0,0 +1,127 @@
+//******************************************************************
+//
+// 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 "EasySetup.h"
+
+#include "logger.h"
+#include "ESException.h"
+#include "RemoteEnrollee.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+        #define EASYSETUP_TAG "EASY_SETUP"
+
+        EasySetup * EasySetup::s_instance = nullptr;
+
+        EasySetup::EasySetup()
+        {
+
+        }
+
+        EasySetup* EasySetup::getInstance ()
+        {
+            if (s_instance == nullptr)
+            {
+                s_instance = new EasySetup ();
+            }
+            return s_instance;
+        }
+
+        RemoteEnrollee::shared_ptr EasySetup::findDeviceInProvisioningList (
+                            const ProvConfig& provConfig, const WiFiOnboadingConnection& onboardingconn)
+        {
+            OIC_LOG(DEBUG,EASYSETUP_TAG,"Entered findDeviceInProvisioningList ()");
+
+            std::vector< std::shared_ptr< RemoteEnrollee > >::iterator it;
+
+            std::shared_ptr< RemoteEnrollee > remoteEnrollee = nullptr;
+            for(auto it : m_activeEnrolleeList)
+            {
+                OIC_LOG_V(DEBUG,EASYSETUP_TAG,"entered the iterator");
+
+                ProvConfig activeEnrolleConfig =  it->getProvConfig();
+                WiFiOnboadingConnection activeEnrolleConn = it->getOnboardConn();
+                if ((0 == memcmp(&activeEnrolleConfig.provData,
+                                &provConfig.provData, sizeof(ProvConfig))) &&
+                    (0 == memcmp(&activeEnrolleConn.ipAddress,
+                          &onboardingconn.ipAddress, sizeof(onboardingconn.ipAddress))))
+                {
+                    remoteEnrollee = it;
+                    return remoteEnrollee;
+                }
+            }
+
+            OIC_LOG_V(DEBUG,EASYSETUP_TAG,"Return nullptr for  findDeviceInProvisioningList call");
+            return remoteEnrollee;
+        }
+
+        bool EasySetup::addDeviceToProvisioningList(const RemoteEnrollee::shared_ptr remoteEnrollee)
+        {
+            ProvConfig remoteEnrolleConfig =  remoteEnrollee->getProvConfig();
+            WiFiOnboadingConnection remoteEnrolleConn = remoteEnrollee->getOnboardConn();
+
+            for (auto it : m_activeEnrolleeList)
+            {
+                ProvConfig activeEnrolleConfig =  it->getProvConfig();
+                WiFiOnboadingConnection activeEnrolleConn = it->getOnboardConn();
+                if ( (0 == memcmp(&activeEnrolleConfig.provData,
+                                &remoteEnrolleConfig.provData,
+                                sizeof(ProvConfig)))  &&
+                     (0 == memcmp(&activeEnrolleConn.ipAddress,
+                                &remoteEnrolleConn.ipAddress,
+                                sizeof(remoteEnrolleConn.ipAddress)))
+                   )
+                {
+                    return false;
+                }
+            }
+
+            OIC_LOG_V(DEBUG,EASYSETUP_TAG,"Adding new device RemoteEnrollee list");
+            m_activeEnrolleeList.push_back(remoteEnrollee);
+            return true;
+        }
+
+        std::shared_ptr<RemoteEnrollee> EasySetup::createEnrolleeDevice (
+                                        const ProvConfig& provConfig, const WiFiOnboadingConnection& wifiOnboardingconn)
+        {
+            if (findDeviceInProvisioningList(provConfig,wifiOnboardingconn) != nullptr)
+            {
+                throw ESBadRequestException { "Device already created exception" };
+            }
+
+            RemoteEnrollee::shared_ptr remoteEnrollee;
+
+            remoteEnrollee = std::make_shared< RemoteEnrollee > (provConfig, wifiOnboardingconn);
+
+
+            if (!addDeviceToProvisioningList (remoteEnrollee))
+            {
+                return nullptr;
+            }
+
+            return remoteEnrollee;
+        }
+
+
+    }
+}
+
diff --git a/service/easy-setup/mediator/richsdk/src/EnrolleeSecurity.cpp b/service/easy-setup/mediator/richsdk/src/EnrolleeSecurity.cpp
new file mode 100755 (executable)
index 0000000..0f35ce6
--- /dev/null
@@ -0,0 +1,233 @@
+//******************************************************************
+//
+// 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 "base64.h"
+
+#include "EnrolleeSecurity.h"
+#include "oxmjustworks.h"
+#include "oxmrandompin.h"
+#include "RemoteEnrolleeResource.h"
+#include "logger.h"
+#include "ESException.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+        #define MAX_PERMISSION_LENGTH (5)
+        #define CREATE (1)
+        #define READ (2)
+        #define UPDATE (4)
+        #define DELETE (8)
+        #define NOTIFY (16)
+        #define DASH '-'
+
+        //TODO : Currently discovery timeout for owned and unowned devices is fixed as 5
+        // The value should be accepted from the application as a parameter during ocplatform
+        // config call
+#define ES_SEC_DISCOVERY_TIMEOUT 5
+
+        EnrolleeSecurity::EnrolleeSecurity(
+        std::shared_ptr< RemoteEnrolleeResource > remoteEnrolleeResource,
+        std::string secDbPath)
+        {
+            m_enrolleeSecState = EnrolleeSecState::ES_SEC_UNKNOWN;
+            m_remoteEnrolleeResource = remoteEnrolleeResource;
+        }
+
+        ESResult EnrolleeSecurity::registerCallbackHandler(EnrolleeSecStatusCb enrolleeSecStatusCb,
+                SecurityPinCb securityPinCb, SecProvisioningDbPathCb secProvisioningDbPathCb)
+
+        {
+            m_enrolleeSecStatusCb = enrolleeSecStatusCb;
+            m_securityPinCb = securityPinCb;
+            m_secProvisioningDbPathCb = secProvisioningDbPathCb;
+
+            return ES_ERROR;
+        }
+
+        std::shared_ptr< OC::OCSecureResource > EnrolleeSecurity::getEnrollee(DeviceList_t &list)
+        {
+            for (unsigned int i = 0; i < list.size(); i++)
+            {
+                OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "Device %d ID %s ", i + 1,
+                        list[i]->getDeviceID().c_str());
+                OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "From IP :%s", list[i]->getDevAddr().c_str());
+
+                //Always return the first element of the unOwned devices. This is considering that Mediator is
+                // always connected with only one Enrollee for which ownership transfer is being performed.
+                // Incase of multiple Enrollee devices connected to the Mediator via any OnBoarding method (SoftAp
+                // for example), the Enrollee devices will be provisioned in the first come first serve basis in the order
+                // returned by the security layer.
+                return list[i];
+            }
+            OIC_LOG(ERROR, ENROLEE_SECURITY_TAG,"Error!!! DeviceList_t is NULL");
+            return NULL;
+        }
+
+        void EnrolleeSecurity::convertUUIDToString(OicUuid_t uuid, std::string& uuidString)
+        {
+            char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*) 0)->id)) + 1] =
+            { 0, };
+            uint32_t outLen = 0;
+            B64Result b64Ret = B64_OK;
+            std::ostringstream deviceId("");
+
+            b64Ret = b64Encode(uuid.id, sizeof(uuid.id),
+                    base64Buff, sizeof(base64Buff), &outLen);
+
+            if (B64_OK == b64Ret)
+            {
+                deviceId << base64Buff;
+            }
+            uuidString =  deviceId.str();
+        }
+
+        void EnrolleeSecurity::ownershipTransferCb(OC::PMResultList_t *result, int hasError)
+        {
+            if (hasError)
+            {
+                OIC_LOG(ERROR, ENROLEE_SECURITY_TAG,"Error!!! in OwnershipTransfer");
+
+                std::shared_ptr< SecProvisioningResult > securityProvisioningStatus = nullptr;
+                std::string uuid;
+                convertUUIDToString(result->at(0).deviceId, uuid);
+                securityProvisioningStatus = std::make_shared< SecProvisioningResult >(uuid,
+                        ES_ERROR);
+
+                m_enrolleeSecStatusCb(securityProvisioningStatus);
+                return;
+            }
+            else
+            {
+                OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "ownershipTransferCb : Received provisioning results: ");
+                for (unsigned int i = 0; i < result->size(); i++)
+                {
+                    OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "Result is = %d for device",result->at(i).res);
+                    std::string uuid;
+                    convertUUIDToString(result->at(0).deviceId, uuid);
+
+                    OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "UUID : %s",uuid.c_str());
+                    std::shared_ptr< SecProvisioningResult > securityProvisioningStatus = nullptr;
+                    securityProvisioningStatus = std::make_shared< SecProvisioningResult >(uuid,
+                            ES_OK);
+
+                    m_enrolleeSecStatusCb(securityProvisioningStatus);
+                    return;
+                }
+
+                delete result;
+            }
+        }
+
+        EasySetupState EnrolleeSecurity::performOwnershipTransfer()
+        {
+            EasySetupState ownershipStatus = DEVICE_NOT_OWNED;
+
+            OC::DeviceList_t pUnownedDevList, pOwnedDevList;
+
+            pOwnedDevList.clear();
+            pUnownedDevList.clear();
+
+            OCStackResult result;
+
+            //Developer note : Always test the mediator and enrollee applications on different devices. Running
+            // Mediator and Enrollee in same device will result in returning the same device as already owned.
+            /*result = OCSecure::discoverOwnedDevices(ES_SEC_DISCOVERY_TIMEOUT,
+                    pOwnedDevList);
+            if (result != OC_STACK_OK)
+            {
+                OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "Owned Discovery failed.");
+                ownershipStatus = DEVICE_NOT_OWNED;
+                //Throw exception
+                throw ESPlatformException(result);
+                return ownershipStatus;
+            }
+            else if (pOwnedDevList.size())
+            {
+                OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "Found owned devices. Count =%d",
+                        pOwnedDevList.size());
+                std::shared_ptr< OC::OCSecureResource > ownedDevice = getEnrollee(pOwnedDevList);
+                if (ownedDevice)
+                {
+                    ownershipStatus = DEVICE_OWNED;
+                    return ownershipStatus;
+                }
+            }
+            else
+            {
+                OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "No owned devices found.");
+                ownershipStatus = DEVICE_NOT_OWNED;
+            }*/
+
+            result = OCSecure::discoverUnownedDevices(ES_SEC_DISCOVERY_TIMEOUT, pUnownedDevList);
+            if (result != OC_STACK_OK)
+            {
+                OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "UnOwned Discovery failed.");
+                ownershipStatus = DEVICE_NOT_OWNED;
+                //Throw exception
+                throw ESPlatformException(result);
+            }
+            else if (pUnownedDevList.size())
+            {
+                OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "Found Unowned devices. Count =%d",
+                        pUnownedDevList.size());
+
+                m_unownedDevice = getEnrollee(pUnownedDevList);
+                if (m_unownedDevice)
+                {
+                    OTMCallbackData_t justWorksCBData;
+                    justWorksCBData.loadSecretCB = LoadSecretJustWorksCallback;
+                    justWorksCBData.createSecureSessionCB = CreateSecureSessionJustWorksCallback;
+                    justWorksCBData.createSelectOxmPayloadCB = CreateJustWorksSelectOxmPayload;
+                    justWorksCBData.createOwnerTransferPayloadCB =
+                            CreateJustWorksOwnerTransferPayload;
+                    OCSecure::setOwnerTransferCallbackData(OIC_JUST_WORKS, &justWorksCBData, NULL);
+
+                    OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "Transfering ownership for : %s ",
+                            m_unownedDevice->getDeviceID().c_str());
+
+                    OC::ResultCallBack ownershipTransferCb = std::bind(
+                            &EnrolleeSecurity::ownershipTransferCb, this, std::placeholders::_1,
+                            std::placeholders::_2);
+
+                    if (m_unownedDevice->doOwnershipTransfer(ownershipTransferCb) != OC_STACK_OK)
+                    {
+                        OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "OwnershipTransferCallback is failed");
+                        ownershipStatus = DEVICE_NOT_OWNED;
+                        return ownershipStatus;
+                    }
+                    ownershipStatus = DEVICE_NOT_OWNED;
+                }
+            }
+            else
+            {
+                OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "No unSecure devices found.");
+                ownershipStatus = DEVICE_NOT_OWNED;
+
+                return ownershipStatus;
+            }
+
+            return ownershipStatus;
+        }
+    }
+}
diff --git a/service/easy-setup/mediator/richsdk/src/RemoteEnrollee.cpp b/service/easy-setup/mediator/richsdk/src/RemoteEnrollee.cpp
new file mode 100755 (executable)
index 0000000..cb6cb7a
--- /dev/null
@@ -0,0 +1,304 @@
+//******************************************************************
+//
+// 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 "RemoteEnrollee.h"
+#include "RemoteEnrolleeResource.h"
+#include "ESException.h"
+#include "logger.h"
+#ifdef __WITH_DTLS__
+#include "EnrolleeSecurity.h"
+#endif //__WITH_DTLS
+
+namespace OIC
+{
+    #define ES_REMOTE_ENROLLEE_TAG "ES_REMOTE_ENROLLEE"
+
+    namespace Service
+    {
+        RemoteEnrollee::RemoteEnrollee(const ProvConfig& provConfig, const WiFiOnboadingConnection& connection) :
+                m_ProvConfig(provConfig), m_wifiOnboardingconn(connection)
+        {
+            m_currentESState = CurrentESState::ES_UNKNOWN;
+            m_isSecured = connection.isSecured; //enrolleeNWProvInfo.needSecuredEasysetup;
+
+            OIC_LOG ( DEBUG, ES_REMOTE_ENROLLEE_TAG, "Inside RemoteEnrollee constr");
+        }
+
+#ifdef __WITH_DTLS__
+        ESResult RemoteEnrollee::registerSecurityCallbackHandler(SecurityPinCb securityPinCb,
+                SecProvisioningDbPathCb secProvisioningDbPathCb)
+        {
+            // No need to check NULL for m_secProvisioningDbPathCB as this is not a mandatory
+            // callback function. If m_secProvisioningDbPathCB is NULL, provisioning manager
+            // in security layer will try to find the PDM.db file in the local path.
+            // If PDM.db is found, the provisioning manager operations will succeed.
+            // Otherwise all the provisioning manager operations will fail.
+            m_secProvisioningDbPathCb = secProvisioningDbPathCb;
+            m_securityPinCb = securityPinCb;
+            return ES_OK;
+        }
+#endif //__WITH_DTLS__
+
+        void RemoteEnrollee::registerEasySetupStatusHandler(EasySetupStatusCB callback)
+        {
+            OIC_LOG ( DEBUG, ES_REMOTE_ENROLLEE_TAG, "Entered registerStatusHandler");
+            if(!callback)
+            {
+                throw ESInvalidParameterException("Callback is empty");
+            }
+
+            if (m_easySetupStatusCb)
+            {
+                throw ESBadRequestException("Callback handler already registered");
+            }
+            else
+            {
+                m_easySetupStatusCb = callback;
+
+                m_remoteResource = std::make_shared< RemoteEnrolleeResource >(m_ProvConfig, m_wifiOnboardingconn);
+            }
+        }
+
+        void RemoteEnrollee::easySetupSecurityStatusCallback(
+                        std::shared_ptr< SecProvisioningResult > secProvisioningResult)
+        {
+            OIC_LOG_V(DEBUG, ES_REMOTE_ENROLLEE_TAG, "easySetupStatusCallback status is, UUID = %s, "
+                    "Status = %d", secProvisioningResult->getDeviceUUID().c_str(),
+                    secProvisioningResult->getResult());
+
+            if(secProvisioningResult->getResult() == ES_OK)
+            {
+                OIC_LOG(DEBUG, ES_REMOTE_ENROLLEE_TAG, "Ownership and ACL are successful. "
+                        "Continue with Network information provisioning");
+
+                m_currentESState = CurrentESState::ES_OWNED;
+
+                OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Before ProvisionEnrollee");
+
+                RemoteEnrolleeResource::ProvStatusCb provStatusCb = std::bind(
+                        &RemoteEnrollee::provisioningStatusHandler, this, std::placeholders::_1);
+
+                m_remoteResource->registerProvStatusCallback(provStatusCb);
+                m_remoteResource->provisionEnrollee();
+            }
+            else
+            {
+                OIC_LOG(DEBUG, ES_REMOTE_ENROLLEE_TAG, "Ownership and ACL are successful");
+                std::shared_ptr< EasySetupStatus > easySetupStatus = nullptr;
+                easySetupStatus = std::make_shared< EasySetupStatus >(DEVICE_NOT_PROVISIONED,
+                                            m_ProvConfig);
+                if (m_easySetupStatusCb)
+                {
+                    if (easySetupStatus)
+                    {
+                        m_easySetupStatusCb(easySetupStatus);
+                    }
+                    else
+                    {
+                        m_easySetupStatusCb(nullptr);
+                    }
+                }
+            }
+        }
+
+        void RemoteEnrollee::provisioningStatusHandler(
+                std::shared_ptr< ProvisioningStatus > provStatus)
+        {
+            OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Entering ProvisioningStatusHandler");
+
+            OIC_LOG_V(DEBUG,ES_REMOTE_ENROLLEE_TAG,"ProvStatus = %d", provStatus->getESResult());
+
+            std::shared_ptr< EasySetupStatus > easySetupStatus = nullptr;
+
+            if (m_isSecured)
+            {
+                if (m_currentESState >= CurrentESState::ES_OWNED)
+                {
+                    goto CALLBACK_CHECK;
+                }
+                else
+                {
+                    goto FAILURE;
+                }
+            }
+            else
+            {
+                goto CALLBACK_CHECK;
+            }
+
+            CALLBACK_CHECK:
+
+            if (provStatus->getESResult() == ES_OK)
+            {
+                if (provStatus->getESState() >= ESState::ES_PROVISIONED_ALREADY)
+                {
+                    easySetupStatus = std::make_shared< EasySetupStatus >(DEVICE_PROVISIONED,
+                            m_ProvConfig);
+                }
+                else
+                {
+                    easySetupStatus = std::make_shared< EasySetupStatus >(DEVICE_NOT_PROVISIONED,
+                            m_ProvConfig);
+                }
+            }
+            else
+            {
+                easySetupStatus = std::make_shared< EasySetupStatus >(DEVICE_NOT_PROVISIONED,
+                        m_ProvConfig);
+            }
+
+            if (m_easySetupStatusCb)
+            {
+                if (easySetupStatus)
+                {
+                    m_easySetupStatusCb(easySetupStatus);
+                }
+                else
+                {
+                    m_easySetupStatusCb(nullptr);
+                }
+            }
+
+            return;
+
+            FAILURE:
+
+            easySetupStatus = std::make_shared< EasySetupStatus >(DEVICE_NOT_PROVISIONED,
+                                    m_ProvConfig);
+
+            if (easySetupStatus)
+            {
+                m_easySetupStatusCb(easySetupStatus);
+            }
+            else
+            {
+                m_easySetupStatusCb(nullptr);
+            }
+            return;
+        }
+
+        void RemoteEnrollee::startProvisioning()
+        {
+            OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Entering startProvisioning");
+            if (m_remoteResource == nullptr)
+            {
+                throw ESBadRequestException ("Device not created");
+            }
+
+            ESResult result = ES_ERROR;
+
+            result = m_remoteResource->constructResourceObject();
+
+            if (result == ES_ERROR)
+            {
+                OIC_LOG(ERROR,ES_REMOTE_ENROLLEE_TAG,
+                                    "Failed to create device using constructResourceObject");
+                throw ESBadRequestException ("Device not created");
+            }
+
+            m_currentESState = CurrentESState::ES_ONBOARDED;
+
+#ifdef __WITH_DTLS__
+            if (m_isSecured && m_currentESState < CurrentESState::ES_OWNED)
+            {
+                EnrolleeSecStatusCb securityProvStatusCb = std::bind(
+                        &RemoteEnrollee::easySetupSecurityStatusCallback,
+                        this,
+                        std::placeholders::_1);
+                //TODO : DBPath is passed empty as of now. Need to take dbpath from application.
+                m_enrolleeSecurity = std::make_shared <EnrolleeSecurity> (m_remoteResource, "");
+
+                m_enrolleeSecurity->registerCallbackHandler(securityProvStatusCb,
+                        m_securityPinCb, m_secProvisioningDbPathCb);
+
+                try
+                {
+                    EasySetupState easySetupState = m_enrolleeSecurity->performOwnershipTransfer();
+                    if (easySetupState == DEVICE_NOT_OWNED)
+                    {
+                        OIC_LOG_V(DEBUG, ES_REMOTE_ENROLLEE_TAG,
+                                "performOwnershipTransfer returned : %d",
+                                easySetupState);
+                        return;
+                    }
+                    else if (easySetupState == DEVICE_OWNED)
+                    {
+                        OIC_LOG_V(DEBUG, ES_REMOTE_ENROLLEE_TAG,
+                                "performOwnershipTransfer returned : %d",
+                                easySetupState);
+                        OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Before ProvisionEnrollee");
+
+                        RemoteEnrolleeResource::ProvStatusCb provStatusCb = std::bind(
+                                &RemoteEnrollee::provisioningStatusHandler,
+                                this, std::placeholders::_1);
+
+                        m_remoteResource->registerProvStatusCallback(provStatusCb);
+                        m_remoteResource->provisionEnrollee();
+                    }
+                }
+                catch (OCException & e)
+                {
+                    OIC_LOG_V(ERROR, ES_REMOTE_ENROLLEE_TAG,
+                            "Exception for performOwnershipTransfer : %s", e.reason().c_str());
+                    return ;
+                }
+            }
+#else
+            OIC_LOG(DEBUG,ES_REMOTE_ENROLLEE_TAG,"Before ProvisionEnrollee");
+
+            RemoteEnrolleeResource::ProvStatusCb provStatusCb = std::bind(
+                    &RemoteEnrollee::provisioningStatusHandler, this, std::placeholders::_1);
+
+            m_remoteResource->registerProvStatusCallback(provStatusCb);
+            m_remoteResource->provisionEnrollee();
+#endif
+        }
+
+        void RemoteEnrollee::stopProvisioning()
+        {
+            m_currentESState = CurrentESState::ES_UNKNOWN;
+
+            m_remoteResource->unprovisionEnrollee();
+        }
+
+        bool RemoteEnrollee::isEnrolleeProvisioned()
+        {
+            if(m_currentESState >= CurrentESState::ES_PROVISIONED)
+            {
+                return true;
+            }
+            else
+            {
+                return false;
+            }
+        }
+
+        ProvConfig RemoteEnrollee::getProvConfig ()
+        {
+            return m_ProvConfig;
+        }
+
+       WiFiOnboadingConnection RemoteEnrollee::getOnboardConn()
+       {
+         return m_wifiOnboardingconn;
+       }
+
+    }
+}
diff --git a/service/easy-setup/mediator/richsdk/src/RemoteEnrolleeResource.cpp b/service/easy-setup/mediator/richsdk/src/RemoteEnrolleeResource.cpp
new file mode 100755 (executable)
index 0000000..368c5e0
--- /dev/null
@@ -0,0 +1,485 @@
+//******************************************************************
+//
+// 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 <functional>
+#include <time.h>
+
+#include "RemoteEnrolleeResource.h"
+
+#include "OCPlatform.h"
+#include "ESException.h"
+#include "OCResource.h"
+#include "logger.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+        #define ES_REMOTE_ENROLLEE_RES_TAG "ES_REMOTE_ENROLLEE_RES"
+        #define DISCOVERY_TIMEOUT 5
+
+        static const char ES_BASE_RES_URI[] = "/oic/res";
+        static const char ES_PROV_RES_URI[] = "/oic/prov";
+        static const char ES_PROV_RES_TYPE[] = "oic.r.prov";
+
+        RemoteEnrolleeResource::RemoteEnrolleeResource(const ProvConfig &provConfig,
+                                                  const WiFiOnboadingConnection &onboardingconn)
+        {
+            m_ProvConfig = provConfig;
+            m_wifiOnboardingconn = onboardingconn;
+            m_discoveryResponse = false;
+        }
+
+        void RemoteEnrolleeResource::triggerNetworkConnectionCb(
+                const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep,
+                const int eCode)
+        {
+            OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "checkProvInformationCb : %s, eCode = %d",
+                    rep.getUri().c_str(),
+                    eCode);
+
+            if (eCode != 0)
+            {
+                OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
+                        "triggerNetworkConnectionCb : Trigger action failed ");
+                std::shared_ptr< ProvisioningStatus > provStatus = std::make_shared<
+                        ProvisioningStatus >(ESResult::ES_ERROR, ESState::ES_PROVISIONING_ERROR);
+                m_provStatusCb(provStatus);
+                return;
+            }
+            else
+            {
+                OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
+                        "triggerNetworkConnectionCb : Provisioning is success ");
+                std::shared_ptr< ProvisioningStatus > provStatus = std::make_shared<
+                        ProvisioningStatus >(ESResult::ES_OK, ESState::ES_PROVISIONING_SUCCESS);
+                m_provStatusCb(provStatus);
+                return;
+            }
+        }
+
+        void RemoteEnrolleeResource::triggerNetworkConnection()
+        {
+            if (m_ocResource == nullptr)
+            {
+                throw ESBadRequestException("Resource is not initialized");
+            }
+
+            OCRepresentation provisioningRepresentation;
+
+            provisioningRepresentation.setValue(OC_RSRVD_ES_TR, 1);
+
+            m_ocResource->post(provisioningRepresentation, QueryParamsMap(),
+                    std::function<
+                            void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                                    const int eCode) >(
+                            std::bind(&RemoteEnrolleeResource::triggerNetworkConnectionCb, this,
+                                    std::placeholders::_1, std::placeholders::_2,
+                                    std::placeholders::_3)));
+        }
+
+        void RemoteEnrolleeResource::checkProvInformationCb(const HeaderOptions& /*headerOptions*/,
+                const OCRepresentation& rep, const int eCode)
+        {
+            OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "checkProvInformationCb : %s, eCode = %d",
+                    rep.getUri().c_str(),
+                    eCode);
+
+            if (eCode != 0)
+            {
+                OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
+                        "checkProvInformationCb : Provisioning is failed ");
+                std::shared_ptr< ProvisioningStatus > provStatus = std::make_shared<
+                        ProvisioningStatus >(ESResult::ES_ERROR, ESState::ES_PROVISIONING_ERROR);
+                m_provStatusCb(provStatus);
+                return;
+            }
+
+            int ps = -1;
+
+            rep.getValue(OC_RSRVD_ES_PS, ps);
+
+            OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "checkProvInformationCb : ps - %d", ps);
+
+            //Provisioning status check
+            if (ps == ES_PS_PROVISIONING_COMPLETED)
+            {
+                OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
+                        "checkProvInformationCb : Provisioning is success. "
+                        "Now trigger network connection ");
+
+                #ifdef REMOTE_ARDUINO_ENROLEE
+                 std::shared_ptr< ProvisioningStatus > provStatus = std::make_shared<
+                        ProvisioningStatus >(ESResult::ES_OK, ESState::ES_PROVISIONING_SUCCESS);
+                m_provStatusCb(provStatus);
+                #endif
+
+                triggerNetworkConnection();
+                return;
+            }
+            else
+            {
+                OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
+                        "checkProvInformationCb : Provisioning is failed ");
+                std::shared_ptr< ProvisioningStatus > provStatus = std::make_shared<
+                        ProvisioningStatus >(ESResult::ES_ERROR, ESState::ES_PROVISIONING_ERROR);
+                m_provStatusCb(provStatus);
+                return;
+            }
+        }
+
+        void RemoteEnrolleeResource::getProvStatusResponse(const HeaderOptions& /*headerOptions*/,
+                const OCRepresentation& rep, const int eCode)
+        {
+            OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "getProvStatusResponse : %s, eCode = %d",
+                    rep.getUri().c_str(),
+                    eCode);
+
+            if (eCode != 0)
+            {
+                OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
+                        "getProvStatusResponse : Provisioning is failed ");
+                std::shared_ptr< ProvisioningStatus > provStatus = std::make_shared<
+                        ProvisioningStatus >(ESResult::ES_ERROR, ESState::ES_PROVISIONING_ERROR);
+                m_provStatusCb(provStatus);
+                return;
+            }
+
+            int ps = -1;
+
+            rep.getValue(OC_RSRVD_ES_PS, ps);
+
+            OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "getProvStatusResponse : ps - %d",
+                    ps);
+
+            if (ps == ES_PS_NEED_PROVISIONING) //Indicates the need for provisioning
+            {
+                OCRepresentation provisioningRepresentation;
+
+                provisioningRepresentation.setValue(OC_RSRVD_ES_TNN,
+                std::string(m_ProvConfig.provData.WIFI.ssid));
+                provisioningRepresentation.setValue(OC_RSRVD_ES_CD,
+                std::string(m_ProvConfig.provData.WIFI.pwd));
+
+                OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "getProvStatusResponse : ssid - %s",
+                        m_ProvConfig.provData.WIFI.ssid);
+                OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "getProvStatusResponse : pwd - %s",
+                        m_ProvConfig.provData.WIFI.pwd);
+
+                m_ocResource->post(provisioningRepresentation, QueryParamsMap(),
+                        std::function<
+                                void(const HeaderOptions& headerOptions,
+                                        const OCRepresentation& rep, const int eCode) >(
+                        std::bind(&RemoteEnrolleeResource::checkProvInformationCb, this,
+                        std::placeholders::_1, std::placeholders::_2,
+                        std::placeholders::_3)));
+            }
+            else if (ps == ES_PS_PROVISIONING_COMPLETED) //Indicates that provisioning is completed
+            {
+                OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
+                        "getProvStatusResponse : Provisioning is successful");
+                std::shared_ptr< ProvisioningStatus > provStatus = std::make_shared<
+                        ProvisioningStatus >(ESResult::ES_OK, ESState::ES_PROVISIONED_ALREADY);
+                m_provStatusCb(provStatus);
+            }
+        }
+
+        void RemoteEnrolleeResource::registerProvStatusCallback(ProvStatusCb provStatusCb)
+        {
+            m_provStatusCb = provStatusCb;
+        }
+
+        ESResult RemoteEnrolleeResource::ESDiscoveryTimeout(unsigned short waittime)
+        {
+            struct timespec startTime;
+            startTime.tv_sec=0;
+            startTime.tv_sec=0;
+            struct timespec currTime;
+            currTime.tv_sec=0;
+            currTime.tv_nsec=0;
+
+            ESResult res = ES_OK;
+            #ifdef _POSIX_MONOTONIC_CLOCK
+                int clock_res = clock_gettime(CLOCK_MONOTONIC, &startTime);
+            #else
+                int clock_res = clock_gettime(CLOCK_REALTIME, &startTime);
+            #endif
+
+            if (0 != clock_res)
+            {
+                return ES_ERROR;
+            }
+
+            while (ES_OK == res || m_discoveryResponse == false)
+            {
+                #ifdef _POSIX_MONOTONIC_CLOCK
+                        clock_res = clock_gettime(CLOCK_MONOTONIC, &currTime);
+                #else
+                        clock_res = clock_gettime(CLOCK_REALTIME, &currTime);
+                #endif
+
+                if (0 != clock_res)
+                {
+                    return ES_ERROR;
+                }
+                long elapsed = (currTime.tv_sec - startTime.tv_sec);
+                if (elapsed > waittime)
+                {
+                    return ES_OK;
+                }
+                if (m_discoveryResponse)
+                {
+                    res = ES_OK;
+                }
+             }
+             return res;
+        }
+
+        void RemoteEnrolleeResource::onDeviceDiscovered(std::shared_ptr<OC::OCResource> resource)
+        {
+            OIC_LOG (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "onDeviceDiscovered");
+
+            std::string resourceURI;
+            std::string hostAddress;
+            try
+            {
+                if(resource)
+                {
+                    // Get the resource URI
+                    resourceURI = resource->uri();
+                    OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
+                            "URI of the resource: %s", resourceURI.c_str());
+
+                    // Get the resource host address
+                    hostAddress = resource->host();
+                    OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
+                            "Host address of the resource: %s", hostAddress.c_str());
+
+                    /*
+                     * Easysetup is always performed with a single Enrollee device and
+                     * in a private network (SoftAP or BLE), so the assumption is that
+                     * only the intended device will respond for the discovery.
+                     * With the above assumption the below two statements are written.
+                     */
+                    m_ocResource = resource;
+                    m_discoveryResponse = true;
+                }
+                else
+                {
+                    OIC_LOG (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "Resource is invalid");
+                }
+
+            }
+            catch(std::exception& e)
+            {
+                OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
+                        "Exception in foundResource: %s", e.what());
+            }
+        }
+
+
+        ESResult RemoteEnrolleeResource::constructResourceObject()
+        {
+            if (m_ocResource != nullptr)
+            {
+                throw ESBadRequestException("Remote resource is already created");
+            }
+
+#ifdef REMOTE_ARDUINO_ENROLEE
+            //This process will create OCResource with port 55555 which is specific
+            // to Arduino WiFi enrollee
+            try
+            {
+
+                std::vector< std::string > interface =
+                {   DEFAULT_INTERFACE};
+                std::vector< std::string > resTypes =
+                {   ES_PROV_RES_TYPE};
+
+                OIC_LOG(DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "Before OCPlatform::constructResourceObject");
+
+                OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "m_host = %s",
+                        m_wifiOnboardingconn.ipAddress);
+                OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "ES_PROV_RES_URI = %s", ES_PROV_RES_URI);
+                OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "m_connectivityType = %d",
+                        m_ProvConfig.connType);
+                OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "resTypes = %s",
+                        resTypes.at(0).c_str());
+                OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "interface = %s", interface.at(0).c_str());
+
+                std::string host;
+                if(m_wifiOnboardingconn.isSecured)
+                {
+                    host.append("coaps://");
+                }
+                else
+                {
+                    host.append("coap://");
+                }
+
+                if(m_ProvConfig.connType == CT_ADAPTER_IP)
+                {
+                    // TODO : RemoteEnrollee is current handling easysetup on IP transport.
+                    // WiFiRemoteEnrollee need to extend RemoteEnrollee for providing IP specific
+                    // Enrollee easysetup.
+
+                    host.append(m_wifiOnboardingconn.ipAddress);
+                    //TODO : If the target Enrollee is not a Arduino Wi-Fi device,
+                    // then the port number will be found during resource discovery instead of
+                    // using 55555
+                    host.append(":55555");
+                }
+
+                OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "HOST = %s", host.c_str());
+
+                m_ocResource = OC::OCPlatform::constructResourceObject(host,
+                        ES_PROV_RES_URI,
+                        m_ProvConfig.connType,
+                        true,
+                        resTypes,
+                        interface);
+                OIC_LOG_V(DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
+                        "created OCResource : %s", m_ocResource->uri().c_str());
+
+                return ES_OK;
+            }
+            catch (OCException & e)
+            {
+                OIC_LOG_V(ERROR, ES_REMOTE_ENROLLEE_RES_TAG,
+                        "Exception for constructResourceObject : %s", e.reason().c_str());
+                return ES_ERROR;
+            }
+#else
+            std::string host("");
+            std::string query("");
+
+            if (m_wifiOnboardingconn.isSecured)
+            {
+                host.append("coaps://");
+            }
+            else
+            {
+                host.append("coap://");
+            }
+
+            if (m_ProvConfig.connType == CT_ADAPTER_IP)
+            {
+                // TODO : RemoteEnrollee is current handling easysetup on IP transport.
+                // WiFiRemoteEnrollee need to extend RemoteEnrollee for providing IP specific
+                // Enrollee easysetup.
+
+                host.append(m_wifiOnboardingconn.ipAddress);
+            }
+
+            query.append(ES_BASE_RES_URI);
+            query.append("?rt=");
+            query.append(ES_PROV_RES_TYPE);
+
+            OIC_LOG(DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "Before OCPlatform::constructResourceObject");
+
+            OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "host = %s",
+                    host.c_str());
+            OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "query = %s", query.c_str());
+            OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "m_connectivityType = %d",
+                    m_ProvConfig.connType);
+
+            m_discoveryResponse = false;
+            std::function< void (std::shared_ptr<OC::OCResource>) > onDeviceDiscoveredCb =
+                    std::bind(&RemoteEnrolleeResource::onDeviceDiscovered, this,
+                                                    std::placeholders::_1);
+            OCStackResult result = OC::OCPlatform::findResource("", query, CT_DEFAULT,
+                    onDeviceDiscoveredCb);
+
+            if (result != OCStackResult::OC_STACK_OK)
+            {
+                OIC_LOG(ERROR,ES_REMOTE_ENROLLEE_RES_TAG,
+                        "Failed to create device using constructResourceObject");
+                return ES_ERROR;
+            }
+
+
+            ESResult foundResponse = ESDiscoveryTimeout (DISCOVERY_TIMEOUT);
+
+            if (foundResponse ==ES_ERROR || !m_discoveryResponse)
+            {
+                OIC_LOG(ERROR,ES_REMOTE_ENROLLEE_RES_TAG,
+                        "Failed to create device using constructResourceObject");
+                return ES_ERROR;
+            }
+
+            return ES_OK;
+#endif
+        }
+
+        void RemoteEnrolleeResource::provisionEnrollee()
+
+        {
+            if (m_ocResource == nullptr)
+            {
+                throw ESBadRequestException("Resource is not initialized");
+            }
+
+            OC::QueryParamsMap query;
+            OC::OCRepresentation rep;
+
+            std::function< OCStackResult(void) > getProvisioingStatus = [&]
+            {   return m_ocResource->get(m_ocResource->getResourceTypes().at(0),
+                        m_ocResource->getResourceInterfaces().at(0), query,
+                        std::function<
+                        void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                                const int eCode) >(
+                                std::bind(&RemoteEnrolleeResource::getProvStatusResponse, this,
+                                        std::placeholders::_1, std::placeholders::_2,
+                                        std::placeholders::_3)));
+            };
+
+            OCStackResult result = getProvisioingStatus();
+
+            if (result != OCStackResult::OC_STACK_OK)
+            {
+                std::shared_ptr< ProvisioningStatus > provStatus = std::make_shared<
+                        ProvisioningStatus >(ESResult::ES_ERROR, ESState::ES_PROVISIONING_ERROR);
+                m_provStatusCb(provStatus);
+                return;
+            }
+        }
+
+        void RemoteEnrolleeResource::unprovisionEnrollee()
+        {
+            if (m_ocResource == nullptr)
+            {
+                throw ESBadRequestException("Resource is not initialized");
+            }
+
+            OCRepresentation provisioningRepresentation;
+
+            provisioningRepresentation.setValue(OC_RSRVD_ES_TNN, "");
+            provisioningRepresentation.setValue(OC_RSRVD_ES_CD, "");
+
+            m_ocResource->post(provisioningRepresentation, QueryParamsMap(),
+                    std::function<
+                            void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                                    const int eCode) >(
+                    std::bind(&RemoteEnrolleeResource::checkProvInformationCb, this,
+                    std::placeholders::_1, std::placeholders::_2,
+                    std::placeholders::_3)));
+        }
+    }
+}
diff --git a/service/easy-setup/mediator/richsdk/unittests/MediatorRichTest.cpp b/service/easy-setup/mediator/richsdk/unittests/MediatorRichTest.cpp
new file mode 100644 (file)
index 0000000..3f0ecc1
--- /dev/null
@@ -0,0 +1,335 @@
+//******************************************************************
+//
+// 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 "UnitTestHelper.h"
+
+#include "ocstack.h"
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "oic_string.h"
+#include "logger.h"
+
+#include "EasySetup.h"
+#include "RemoteEnrollee.h"
+#include "ESException.h"
+
+#include <iostream>
+#include <functional>
+#include <pthread.h>
+#include <condition_variable>
+
+using namespace OIC::Service;
+
+const std::string  ipaddress = "1.1.1.1";
+const std::string  ssid = "test";
+const std::string  pwd = "test@123";
+
+class MediatorRichTest: public TestWithMock
+{
+    protected:
+        void SetUp()
+        {
+            TestWithMock::SetUp();
+        }
+
+        void TearDown()
+        {
+            TestWithMock::TearDown();
+        }
+};
+
+//callbacks
+void easySetupStatusCallback (std::shared_ptr< EasySetupStatus > /*easySetupStatus*/)
+{
+
+
+}
+
+/* Test cases for easysetyup class*/
+
+//getInstance
+TEST_F(MediatorRichTest, testGetInstance)
+{
+    EasySetup *easySetupIntance1 = EasySetup::getInstance();
+    EasySetup *easySetupIntance2 = EasySetup::getInstance();
+
+    EXPECT_EQ(easySetupIntance1, easySetupIntance2);
+}
+
+//createEnrolleeDevice [positive]
+TEST_F(MediatorRichTest, testCreateEnrolleeDevice)
+{
+    RemoteEnrollee::shared_ptr remoteEnrollee = NULL;
+    ProvConfig netInfo;
+    WiFiOnboadingConnection onboardingConn;
+
+    netInfo.connType = CT_ADAPTER_IP;
+
+    OICStrcpy(netInfo.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, ssid.c_str());
+    OICStrcpy(netInfo.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, pwd.c_str());
+
+    onboardingConn.isSecured = false;
+    OICStrcpy(onboardingConn.ipAddress, IPV4_ADDR_SIZE - 1, ipaddress.c_str());
+
+    remoteEnrollee = EasySetup::getInstance()->createEnrolleeDevice(netInfo, onboardingConn);
+
+    EXPECT_TRUE(remoteEnrollee != NULL);
+}
+
+//createEnrolleeDevice [Negative]
+TEST_F(MediatorRichTest, testCreateEnrolleeDeviceNegative)
+{
+    RemoteEnrollee::shared_ptr remoteEnrollee = NULL;
+    ProvConfig netInfo;
+    WiFiOnboadingConnection onboardingConn;
+    EasySetup *easysetupInstance = EasySetup::getInstance();
+
+    netInfo.connType = CT_ADAPTER_IP;
+
+    OICStrcpy(netInfo.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, ssid.c_str());
+    OICStrcpy(netInfo.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, pwd.c_str());
+
+    onboardingConn.isSecured = false;
+    OICStrcpy(onboardingConn.ipAddress, IPV4_ADDR_SIZE - 1, ipaddress.c_str());
+
+    //calling the createEnrolleeDevice
+    remoteEnrollee = easysetupInstance->createEnrolleeDevice(netInfo, onboardingConn);
+    //calling again the createEnrolleeDevice with same config & connection info [API throws the exception]
+    EXPECT_ANY_THROW(easysetupInstance->createEnrolleeDevice(netInfo, onboardingConn));
+}
+
+//createEnrolleeDevice [positive (creating the two RemoteEnrolleeDevice with different config)]
+TEST_F(MediatorRichTest, testCreateEnrolleeMultipleDevice)
+{
+    RemoteEnrollee::shared_ptr remoteEnrollee1 = NULL;
+    RemoteEnrollee::shared_ptr remoteEnrollee2 = NULL;
+    WiFiOnboadingConnection onboardingConn1;
+    WiFiOnboadingConnection onboardingConn2;
+    ProvConfig netInfo1;
+    ProvConfig netInfo2;
+    std::string  ipaddress2 = "0.0.0.0";
+
+    //calling the API for the first device
+    netInfo1.connType = CT_ADAPTER_IP;
+    OICStrcpy(netInfo1.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, ssid.c_str());
+    OICStrcpy(netInfo1.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, pwd.c_str());
+
+    onboardingConn1.isSecured = false;
+    OICStrcpy(onboardingConn1.ipAddress, IPV4_ADDR_SIZE - 1, ipaddress.c_str());
+    remoteEnrollee1 = EasySetup::getInstance()->createEnrolleeDevice(netInfo1, onboardingConn1);
+
+    //calling the API for the second device
+    netInfo1.connType = CT_ADAPTER_IP;
+    OICStrcpy(netInfo1.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, ssid.c_str());
+    OICStrcpy(netInfo1.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, pwd.c_str());
+
+    onboardingConn1.isSecured = false;
+    OICStrcpy(onboardingConn1.ipAddress, IPV4_ADDR_SIZE - 1, ipaddress2.c_str());
+    remoteEnrollee2 = EasySetup::getInstance()->createEnrolleeDevice(netInfo2, onboardingConn2);
+
+    EXPECT_TRUE(remoteEnrollee1 != NULL);
+    EXPECT_TRUE(remoteEnrollee2 != NULL);
+}
+
+/*Test cases for RemoteEnrollee class*/
+
+//registerEasySetupStatusHandler [positive]
+TEST_F(MediatorRichTest, testRegisterEasySetupStatusHandler)
+{
+    //creation of the Remote Enrollee Device
+    RemoteEnrollee::shared_ptr remoteEnrollee = NULL;
+    ProvConfig netInfo;
+    WiFiOnboadingConnection onboardingConn;
+
+    netInfo.connType = CT_ADAPTER_IP;
+
+    OICStrcpy(netInfo.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, ssid.c_str());
+    OICStrcpy(netInfo.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, pwd.c_str());
+
+    onboardingConn.isSecured = false;
+    OICStrcpy(onboardingConn.ipAddress, IPV4_ADDR_SIZE - 1, ipaddress.c_str());
+
+    remoteEnrollee = EasySetup::getInstance()->createEnrolleeDevice(netInfo, onboardingConn);
+
+    //calling the API
+    EXPECT_NO_THROW( remoteEnrollee->registerEasySetupStatusHandler(&easySetupStatusCallback));
+}
+
+//registerEasySetupStatusHandler [Negative]
+TEST_F(MediatorRichTest, testRegisterEasySetupStatusHandlerNegative)
+{
+    //creation of the Remote Enrollee Device
+    RemoteEnrollee::shared_ptr remoteEnrollee = NULL;
+    ProvConfig netInfo;
+    WiFiOnboadingConnection onboardingConn;
+
+    netInfo.connType = CT_ADAPTER_IP;
+
+    OICStrcpy(netInfo.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, ssid.c_str());
+    OICStrcpy(netInfo.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, pwd.c_str());
+
+    onboardingConn.isSecured = false;
+    OICStrcpy(onboardingConn.ipAddress, IPV4_ADDR_SIZE - 1, ipaddress.c_str());
+
+    remoteEnrollee = EasySetup::getInstance()->createEnrolleeDevice(netInfo, onboardingConn);
+
+    //calling the API
+    EXPECT_ANY_THROW( remoteEnrollee->registerEasySetupStatusHandler(NULL));
+}
+
+//isEnrolleeProvisioned
+TEST_F(MediatorRichTest, testIsEnrolleeProvisioned)
+{
+    //creation of the Remote Enrollee Device
+    RemoteEnrollee::shared_ptr remoteEnrollee = NULL;
+    ProvConfig netInfo;
+    WiFiOnboadingConnection onboardingConn;
+
+    netInfo.connType = CT_ADAPTER_IP;
+
+    OICStrcpy(netInfo.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, ssid.c_str());
+    OICStrcpy(netInfo.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, pwd.c_str());
+
+    onboardingConn.isSecured = false;
+    OICStrcpy(onboardingConn.ipAddress, IPV4_ADDR_SIZE - 1, ipaddress.c_str());
+
+    remoteEnrollee = EasySetup::getInstance()->createEnrolleeDevice(netInfo, onboardingConn);
+
+    //calling the API
+    bool isEnrolleeProvisioned = remoteEnrollee->isEnrolleeProvisioned();
+
+    EXPECT_TRUE(false == isEnrolleeProvisioned);
+}
+
+//startProvisioning [positive]
+TEST_F(MediatorRichTest, testStartProvisioning)
+{
+    //creation of the Remote Enrollee Device
+    RemoteEnrollee::shared_ptr remoteEnrollee = NULL;
+    ProvConfig netInfo;
+    WiFiOnboadingConnection onboardingConn;
+
+    netInfo.connType = CT_ADAPTER_IP;
+
+    OICStrcpy(netInfo.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, ssid.c_str());
+    OICStrcpy(netInfo.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, pwd.c_str());
+
+    onboardingConn.isSecured = false;
+    OICStrcpy(onboardingConn.ipAddress, IPV4_ADDR_SIZE - 1, ipaddress.c_str());
+
+    remoteEnrollee = EasySetup::getInstance()->createEnrolleeDevice(netInfo, onboardingConn);
+    remoteEnrollee->registerEasySetupStatusHandler(&easySetupStatusCallback);
+
+#ifdef REMOTE_ARDUINO_ENROLEE
+    EXPECT_NO_THROW(remoteEnrollee->startProvisioning());
+
+#else
+    /* It will throw the exception
+     * as it will not able to discover the provisioning resource in the network
+     */
+    EXPECT_ANY_THROW(remoteEnrollee->startProvisioning());
+#endif
+}
+
+//startProvisioning [Negative]
+TEST_F(MediatorRichTest, testStartProvisioningNegative)
+{
+    //creation of the Remote Enrollee Device
+    RemoteEnrollee::shared_ptr remoteEnrollee = NULL;
+    ProvConfig netInfo;
+    WiFiOnboadingConnection onboardingConn;
+
+    netInfo.connType = CT_ADAPTER_IP;
+
+    OICStrcpy(netInfo.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, ssid.c_str());
+    OICStrcpy(netInfo.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, pwd.c_str());
+
+    onboardingConn.isSecured = false;
+    OICStrcpy(onboardingConn.ipAddress, IPV4_ADDR_SIZE - 1, ipaddress.c_str());
+
+    remoteEnrollee = EasySetup::getInstance()->createEnrolleeDevice(netInfo, onboardingConn);
+
+    /* We are not registering the EasySetupStatusHandler, so startProvisioning
+     * will throw the Exception &  we are checking the same
+     */
+    EXPECT_ANY_THROW(remoteEnrollee->startProvisioning());
+}
+
+//stopProvisioning [positive]
+TEST_F(MediatorRichTest, testStopProvisioning)
+{
+    //creation of the Remote Enrollee Device
+    RemoteEnrollee::shared_ptr remoteEnrollee = NULL;
+    ProvConfig netInfo;
+    WiFiOnboadingConnection onboardingConn;
+
+    netInfo.connType = CT_ADAPTER_IP;
+
+    OICStrcpy(netInfo.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, ssid.c_str());
+    OICStrcpy(netInfo.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, pwd.c_str());
+
+    onboardingConn.isSecured = false;
+    OICStrcpy(onboardingConn.ipAddress, IPV4_ADDR_SIZE - 1, ipaddress.c_str());
+
+    remoteEnrollee = EasySetup::getInstance()->createEnrolleeDevice(netInfo, onboardingConn);
+    remoteEnrollee->registerEasySetupStatusHandler(&easySetupStatusCallback);
+
+#ifdef REMOTE_ARDUINO_ENROLEE
+        EXPECT_NO_THROW(remoteEnrollee->startProvisioning());
+        EXPECT_NO_THROW(remoteEnrollee->stopProvisioning());
+
+#else
+    /* It will throw the exception as
+     * it will not able to discover the provisioning resource in the network
+     */
+     EXPECT_ANY_THROW(remoteEnrollee->startProvisioning());
+
+    /* It will throw an exception
+     * as internally resource will be empty [startProvisioning is not succeed]
+     */
+    EXPECT_ANY_THROW(remoteEnrollee->stopProvisioning());
+#endif
+}
+
+//stopProvisioning [Negative]
+TEST_F(MediatorRichTest, testStopProvisioningNegative)
+{
+    //creation of the Remote Enrollee Device
+    RemoteEnrollee::shared_ptr remoteEnrollee = NULL;
+    ProvConfig netInfo;
+    WiFiOnboadingConnection onboardingConn;
+
+    netInfo.connType = CT_ADAPTER_IP;
+
+    OICStrcpy(netInfo.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, ssid.c_str());
+    OICStrcpy(netInfo.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, pwd.c_str());
+
+    onboardingConn.isSecured = false;
+    OICStrcpy(onboardingConn.ipAddress, IPV4_ADDR_SIZE - 1, ipaddress.c_str());
+
+    remoteEnrollee = EasySetup::getInstance()->createEnrolleeDevice(netInfo, onboardingConn);
+    remoteEnrollee->registerEasySetupStatusHandler(&easySetupStatusCallback);
+
+    /* we didn't call the start provisioning API and directly calling stopProvisioning API.
+     * In this case API will throw the exception & we are checking the same.
+     */
+    EXPECT_ANY_THROW(remoteEnrollee->stopProvisioning());
+}
+
diff --git a/service/easy-setup/mediator/richsdk/unittests/SConscript b/service/easy-setup/mediator/richsdk/unittests/SConscript
new file mode 100644 (file)
index 0000000..480df19
--- /dev/null
@@ -0,0 +1,108 @@
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+##
+# Mediator[RichSDK] Unit Test build script
+##
+import os
+Import('env')
+
+if env.get('RELEASE'):
+    env.AppendUnique(CCFLAGS = ['-Os'])
+    env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+else:
+    env.AppendUnique(CCFLAGS = ['-g'])
+
+if env.get('LOGGING'):
+    env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+# Add third party libraries
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+
+target_os = env.get('TARGET_OS')
+if target_os == 'linux':
+    # Verify that 'google unit test' library is installed.  If not,
+    # get it and install it
+    SConscript(env.get('SRC_DIR') + '/extlibs/gtest/SConscript')
+
+    # Verify that 'hippomocks' mocking code is installed.  If not,
+    # get it and install it
+    SConscript(env.get('SRC_DIR') + '/extlibs/hippomocks.scons')
+
+mediator_rich_test_env = lib_env.Clone()
+
+######################################################################
+#unit test setting
+######################################################################
+src_dir = lib_env.get('SRC_DIR')
+gtest_dir = src_dir + '/extlibs/gtest/gtest-1.7.0'
+
+######################################################################
+# Build flags
+######################################################################
+gtest = File(gtest_dir + '/lib/.libs/libgtest.a')
+gtest_main = File(gtest_dir + '/lib/.libs/libgtest_main.a')
+
+mediator_rich_test_env.AppendUnique(
+        CPPPATH = [
+                src_dir + '/extlibs/hippomocks-master',
+                src_dir + '/extlibs/gtest/gtest-1.7.0/include',
+                '../inc',
+                '../../../inc',
+        ])
+
+if target_os not in ['windows', 'winrt']:
+        mediator_rich_test_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
+        if target_os != 'android':
+                mediator_rich_test_env.AppendUnique(CXXFLAGS = ['-pthread'])
+                mediator_rich_test_env.AppendUnique(LIBS = ['pthread'])
+
+
+if env.get('SECURED') == '1':
+            mediator_rich_test_env.PrependUnique(LIBS = ['tinydtls','ocprovision', 'ocpmapi'])
+
+mediator_rich_test_env.PrependUnique(LIBS = [
+    'oc',
+    'octbstack',
+    'oc_logger',
+    'oc_logger_core',
+    'connectivity_abstraction',
+    'coap',
+    'ESMediatorRich',
+    gtest,
+    gtest_main])
+
+mediator_rich_test_env.AppendUnique(LIBS = ['dl'])
+
+######################################################################
+# Build Test
+######################################################################
+mediator_richsdk_test_src = env.Glob('./*.cpp')
+
+mediator_richsdk_test = mediator_rich_test_env.Program('mediator_richsdk_test', mediator_richsdk_test_src)
+Alias("mediator_richsdk_test", mediator_richsdk_test)
+env.AppendTarget('mediator_richsdk_test')
+
+if env.get('TEST') == '1':
+    target_os = env.get('TARGET_OS')
+    if target_os == 'linux':
+        from tools.scons.RunTest import *
+        run_test(mediator_rich_test_env, '', 'service/easy-setup/mediator/richsdk/unittests/mediator_richsdk_test')
\ No newline at end of file
diff --git a/service/easy-setup/mediator/richsdk/unittests/UnitTestHelper.h b/service/easy-setup/mediator/richsdk/unittests/UnitTestHelper.h
new file mode 100644 (file)
index 0000000..2bf7424
--- /dev/null
@@ -0,0 +1,48 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef COMMON_UTILS_UNITTESTHELPER_H
+#define COMMON_UTILS_UNITTESTHELPER_H
+
+#include <gtest/gtest.h>
+#include <HippoMocks/hippomocks.h>
+
+class TestWithMock: public testing::Test
+{
+    public:
+        MockRepository mocks;
+
+    protected:
+        virtual ~TestWithMock() noexcept(noexcept(std::declval<Test>().~Test())) {}
+
+        virtual void TearDown()
+        {
+            try
+            {
+                mocks.VerifyAll();
+            }
+            catch (...)
+            {
+                mocks.reset();
+                throw;
+            }
+        }
+};
+#endif // COMMON_UTILS_UNITTESTHELPER_H
diff --git a/service/easy-setup/sampleapp/SConscript b/service/easy-setup/sampleapp/SConscript
deleted file mode 100644 (file)
index 95b780a..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-#******************************************************************
-#
-# 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.
-#
-#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-##
-# sampleapp build script
-##
-
-Import('env')
-
-# Add third party libraries
-lib_env = env.Clone()
-
-sample_env = lib_env.Clone()
-target_os = env.get('TARGET_OS')
-
-######################################################################
-# Build flags
-######################################################################
-
-######################################################################
-# Source files and Targets
-######################################################################
-if target_os == 'arduino' :
-       # Build linux sample app
-       SConscript('enrollee/arduino/SConscript')
-
-if target_os == 'linux' :
-       # Build linux sample app
-       SConscript('mediator/linux/SConscript')
old mode 100644 (file)
new mode 100755 (executable)
index 2fa74cd..57b2d04
 #
 #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+######################################################################
+# Build script for Arduino Enrollee Sample App
+######################################################################
+
 Import('env')
 
 enrollee_env = env.Clone()
@@ -27,22 +31,21 @@ transport = enrollee_env.get('TARGET_TRANSPORT')
 # Build flags
 ######################################################################
 enrollee_env.PrependUnique(CPPPATH = [
-        '../../../../../resource/oc_logger/include',
-        '../../../../../resource/csdk/logger/include',
-        '../../../../../resource/csdk/stack/include',
-       '../../../../../extlibs/cjson',
-       '../../../sdk/common',
-       '../../../sdk/enrollee/arduino/wifi',
-       '../../../sdk/enrollee/api',
-       '../../../sdk/enrollee/inc',
-       '../../../sdk/enrollee/src'
-       ])
+        env.get('SRC_DIR') + '/resource/oc_logger/include',
+        env.get('SRC_DIR') + '/resource/csdk/logger/include',
+        env.get('SRC_DIR') + '/resource/csdk/stack/include',
+               env.get('SRC_DIR') + '/extlibs/cjson',
+               env.get('SRC_DIR') + '/service/easy-setup/inc',
+               env.get('SRC_DIR') + '/service/easy-setup/enrollee/arduino/wifi',
+               env.get('SRC_DIR') + '/service/easy-setup/enrollee/inc',
+               env.get('SRC_DIR') + '/service/easy-setup/enrollee/src'])
+
 enrollee_env.AppendUnique(CPPDEFINES = ['TB_LOG', 'ESWIFI'])
-       
+
 enrollee_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 
-enrollee_env.PrependUnique(LIBS = ['octbstack','ocsrm','connectivity_abstraction','coap', 'ESSDKLibrary'])
-enrollee = enrollee_env.Program('enrollee', 'enrollee_wifi.cpp')
+enrollee_env.PrependUnique(LIBS = ['octbstack','ocsrm','connectivity_abstraction','coap', 'ESEnrolleeSDK'])
+enrollee = enrollee_env.Program('enrollee', 'enrolleewifi.cpp')
 env.CreateBin('enrollee')
 
 i_enrollee = enrollee_env.Install(env.get('BUILD_DIR'), enrollee)
diff --git a/service/easy-setup/sampleapp/enrollee/arduino/enrollee_wifi.cpp b/service/easy-setup/sampleapp/enrollee/arduino/enrollee_wifi.cpp
deleted file mode 100755 (executable)
index dd3c58c..0000000
+++ /dev/null
@@ -1,287 +0,0 @@
-//******************************************************************
-//
-// 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 "Arduino.h"
-
-#include "logger.h"
-#include <string.h>
-
-#ifdef ARDUINOWIFI
-// Arduino WiFi Shield
-#include <SPI.h>
-#include <WiFi.h>
-#include <WiFiUdp.h>
-#else
-// Arduino Ethernet Shield
-#include <EthernetServer.h>
-#include <Ethernet.h>
-#include <Dns.h>
-#include <EthernetClient.h>
-#include <util.h>
-#include <EthernetUdp.h>
-#include <Dhcp.h>
-#endif
-
-#include "easysetup.h"
-
-#define TAG "TS"
-
-const char *getResult(OCStackResult result);
-
-/**
- * @var ssid
- * @brief Target SSID of the Soft Access point to which the device has to connect
- */
-static char ssid[] = "EasySetup123";
-
-/**
- * @var passwd
- * @brief Password of the Soft Access point to which the device has to connect
- */
-static char passwd[] = "EasySetup123";
-
-/**
- * @var g_OnBoardingSucceeded
- * @brief This variable will be set if OnBoarding is successful
- */
-static bool g_OnBoardingSucceeded = false;
-
-/**
- * @var g_ProvisioningSucceeded
- * @brief This variable will be set if Provisioning is successful
- */
-static bool g_ProvisioningSucceeded = false;
-
-static bool g_isInitialized = false;
-
-bool is_connected=false;
-
-void GetData(char *readInput, size_t bufferLength, size_t *dataLength)
-{
-    if (!readInput || bufferLength == 0 || !dataLength)
-    {
-        Serial.println("Invalid buffer");
-        return;
-    }
-
-    while (!Serial.available())
-    {
-        delay(500);
-    }
-    int len = 0;
-    while (Serial.available())
-    {
-        delay(100);
-        char c = Serial.read();
-        if ('\n' != c && '\r' != c && len < bufferLength - 1)
-        {
-            readInput[len++] = c;
-        }
-        else
-        {
-            break;
-        }
-    }
-
-    readInput[len] = '\0';
-    Serial.flush();
-    Serial.print("PD: ");
-    Serial.println(readInput);
-    (*dataLength) = len;
-}
-
-void PrintMenu()
-{
-    Serial.println("============");
-    Serial.println("s: start easy setup");
-    Serial.println("p: start provisioning resources");
-    Serial.println("t: terminate");
-    Serial.println("q: quit");
-    Serial.println("============");
-}
-
-void EventCallbackInApp(ESResult esResult, EnrolleeState enrolleeState)
-{
-    Serial.println("callback!!! in app");
-
-    if(esResult == ES_OK)
-    {
-        if(!g_OnBoardingSucceeded){
-            Serial.println("Device is successfully OnBoarded");
-            g_OnBoardingSucceeded = true;
-        }
-        else if(g_OnBoardingSucceeded & enrolleeState == ES_ON_BOARDED_STATE){
-            Serial.println("Device is successfully OnBoared with SoftAP");
-            g_ProvisioningSucceeded = true;
-        }
-    }
-    else if (esResult == ES_ERROR)
-    {
-        if(g_OnBoardingSucceeded)
-        {
-            OC_LOG_V(ERROR, TAG, "Failure in Provisioning. \
-                                        Current Enrollee State: %d",enrolleeState);
-            g_OnBoardingSucceeded = false;
-        }
-        else if(g_ProvisioningSucceeded)
-        {
-            OC_LOG_V(ERROR, TAG, "Failure in connect to target network. \
-                                        Current Enrollee State: %d",enrolleeState);
-            g_ProvisioningSucceeded = false;
-        }
-    }
-    PrintMenu();
-}
-
-// On Arduino Atmel boards with Harvard memory architecture, the stack grows
-// downwards from the top and the heap grows upwards. This method will print
-// the distance(in terms of bytes) between those two.
-// See here for more details :
-// http://www.atmel.com/webdoc/AVRLibcReferenceManual/malloc_1malloc_intro.html
-void PrintArduinoMemoryStats()
-{
-#ifdef ARDUINO_AVR_MEGA2560
-    //This var is declared in avr-libc/stdlib/malloc.c
-    //It keeps the largest address not allocated for heap
-    extern char *__brkval;
-    //address of tmp gives us the current stack boundry
-    int tmp;
-    OC_LOG_V(INFO, TAG, "Stack: %u         Heap: %u", (unsigned int)&tmp, (unsigned int)__brkval);
-    OC_LOG_V(INFO, TAG, "Unallocated Memory between heap and stack: %u",
-            ((unsigned int)&tmp - (unsigned int)__brkval));
-#endif
-}
-
-void StartEasySetup()
-{
-    OC_LOG(DEBUG, TAG, "OCServer is starting...");
-
-    if(InitEasySetup(CT_ADAPTER_IP, ssid, passwd, EventCallbackInApp) == ES_ERROR)
-    {
-        OC_LOG(ERROR, TAG, "OnBoarding Failed");
-        return;
-    }
-
-    g_isInitialized = true;
-
-    OC_LOG_V(ERROR, TAG, "OnBoarding succeeded. Successfully connected to ssid : %s",ssid);
-}
-
-void StartProvisioning()
-{
-    OC_LOG(DEBUG, TAG, "StartProvisioning is invoked...");
-
-    if(InitProvisioning()== ES_ERROR)
-    {
-        OC_LOG(ERROR, TAG, "Init Provisioning Failed");
-        return;
-    }
-}
-
-void StopEasySetup()
-{
-    OC_LOG(DEBUG, TAG, "Stopping EasySetup is invoked...");
-
-    g_isInitialized = false;
-
-    if(TerminateEasySetup()== ES_ERROR)
-    {
-        OC_LOG(ERROR, TAG, "TerminateEasySetup Failed");
-        return;
-    }
-}
-
-
-//The setup function is called once at startup of the sketch
-void setup()
-{
-    // Add your initialization code here
-    // Note : This will initialize Serial port on Arduino at 115200 bauds
-    OC_LOG_INIT();
-
-    Serial.println("#########################");
-    Serial.println("EasySetup Enrollee SAMPLE");
-    Serial.println("#########################");
-    PrintMenu();
-}
-
-// The loop function is called in an endless loop
-void loop()
-{
-    char buffer[5] = {0};
-    size_t len;
-    if (Serial.available() > 0)
-    {
-        GetData(buffer, sizeof(buffer), &len);
-        if (0 >= len)
-        {
-            Serial.println("Input Error err");
-            return;
-        }
-        switch (toupper(buffer[0]))
-        {
-            case 'H': // help
-                PrintMenu();
-                break;
-
-            case 'Q': // quit
-                Serial.println("quit");
-                return;
-
-            case 'S': // start easy setup
-                StartEasySetup();
-                break;
-
-            case 'P': // start provisioning
-                StartProvisioning();
-                break;
-
-            case 'T': // stop easy setup
-                StopEasySetup();
-                break;
-
-            default:
-                Serial.println("wrong option");
-                break;
-        }
-    }
-
-    //check g_isInitialized to see if stack init is success
-    if (g_isInitialized)
-    {
-        // This call displays the amount of free SRAM available on Arduino
-        PrintArduinoMemoryStats();
-        if (WiFi.status() == WL_CONNECTED)
-            is_connected = true;
-        else if (is_connected)
-            TerminateEasySetup();
-
-        // Give CPU cycles to OCStack to perform send/recv and other OCStack stuff
-        if (OCProcess() != OC_STACK_OK)
-        {
-            OC_LOG(ERROR, TAG, "OCStack process error");
-            return;
-        }
-    }
-
-    // This artificial delay is kept here to avoid endless spinning
-    // of Arduino microcontroller. Modify it as per specific application needs.
-    delay(2000);
-}
diff --git a/service/easy-setup/sampleapp/enrollee/arduino/enrolleewifi.cpp b/service/easy-setup/sampleapp/enrollee/arduino/enrolleewifi.cpp
new file mode 100644 (file)
index 0000000..d867f51
--- /dev/null
@@ -0,0 +1,304 @@
+//******************************************************************
+//
+// 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 "Arduino.h"
+
+#include "logger.h"
+#include <string.h>
+
+#ifdef ARDUINOWIFI
+// Arduino WiFi Shield
+#include <SPI.h>
+#include <WiFi.h>
+#include <WiFiUdp.h>
+#else
+// Arduino Ethernet Shield
+#include <EthernetServer.h>
+#include <Ethernet.h>
+#include <Dns.h>
+#include <EthernetClient.h>
+#include <util.h>
+#include <EthernetUdp.h>
+#include <Dhcp.h>
+#endif
+
+#include "easysetup.h"
+
+#define TAG "TS"
+
+const char *getResult(OCStackResult result);
+
+/**
+ * @var ssid
+ * @brief Target SSID of the Soft Access point to which the device has to connect
+ */
+static char ssid[] = "EasySetup123";
+
+/**
+ * @var passwd
+ * @brief Password of the Soft Access point to which the device has to connect
+ */
+static char passwd[] = "EasySetup123";
+
+/**
+ * @var g_OnBoardingSucceeded
+ * @brief This variable will be set if OnBoarding is successful
+ */
+static bool g_OnBoardingSucceeded = false;
+
+/**
+ * @var g_ProvisioningSucceeded
+ * @brief This variable will be set if Provisioning is successful
+ */
+static bool g_ProvisioningSucceeded = false;
+
+static bool g_isInitialized = false;
+
+bool is_connected=false;
+
+void GetData(char *readInput, size_t bufferLength, size_t *dataLength)
+{
+    if (!readInput || bufferLength == 0 || !dataLength)
+    {
+        Serial.println("Invalid buffer");
+        return;
+    }
+
+    while (!Serial.available())
+    {
+        delay(500);
+    }
+    int len = 0;
+    while (Serial.available())
+    {
+        delay(100);
+        char c = Serial.read();
+        if ('\n' != c && '\r' != c && len < bufferLength - 1)
+        {
+            readInput[len++] = c;
+        }
+        else
+        {
+            break;
+        }
+    }
+
+    readInput[len] = '\0';
+    Serial.flush();
+    Serial.print("PD: ");
+    Serial.println(readInput);
+    (*dataLength) = len;
+}
+
+void PrintMenu()
+{
+    Serial.println("============");
+    Serial.println("s: start easy setup");
+    Serial.println("p: start provisioning resources");
+    Serial.println("t: terminate");
+    Serial.println("q: quit");
+    Serial.println("============");
+}
+
+void EventCallbackInApp(ESResult esResult, ESEnrolleeState enrolleeState)
+{
+    Serial.println("callback!!! in app");
+
+    if(esResult == ES_OK)
+    {
+        if(!g_OnBoardingSucceeded){
+            Serial.println("Device is successfully OnBoarded");
+            g_OnBoardingSucceeded = true;
+        }
+        else if(g_OnBoardingSucceeded & enrolleeState == ES_ON_BOARDED_STATE){
+            Serial.println("Device is successfully OnBoared with SoftAP");
+            g_ProvisioningSucceeded = true;
+        }
+    }
+    else if (esResult == ES_ERROR)
+    {
+        if(g_OnBoardingSucceeded)
+        {
+            OIC_LOG_V(ERROR, TAG, "Failure in Provisioning. \
+                                        Current Enrollee State: %d",enrolleeState);
+            g_OnBoardingSucceeded = false;
+        }
+        else if(g_ProvisioningSucceeded)
+        {
+            OIC_LOG_V(ERROR, TAG, "Failure in connect to target network. \
+                                        Current Enrollee State: %d",enrolleeState);
+            g_ProvisioningSucceeded = false;
+        }
+    }
+    PrintMenu();
+}
+
+// On Arduino Atmel boards with Harvard memory architecture, the stack grows
+// downwards from the top and the heap grows upwards. This method will print
+// the distance(in terms of bytes) between those two.
+// See here for more details :
+// http://www.atmel.com/webdoc/AVRLibcReferenceManual/malloc_1malloc_intro.html
+void PrintArduinoMemoryStats()
+{
+#ifdef ARDUINO_AVR_MEGA2560
+    //This var is declared in avr-libc/stdlib/malloc.c
+    //It keeps the largest address not allocated for heap
+    extern char *__brkval;
+    //address of tmp gives us the current stack boundry
+    int tmp;
+    OIC_LOG_V(INFO, TAG, "Stack: %u         Heap: %u", (unsigned int)&tmp, (unsigned int)__brkval);
+    OIC_LOG_V(INFO, TAG, "Unallocated Memory between heap and stack: %u",
+            ((unsigned int)&tmp - (unsigned int)__brkval));
+#endif
+}
+
+void StartEasySetup()
+{
+    OIC_LOG(DEBUG, TAG, "OCServer is starting...");
+
+    //ESInitEnrollee with sercurity mode disabled for arduino
+    if(ESInitEnrollee(CT_ADAPTER_IP, ssid, passwd, false, EventCallbackInApp) == ES_ERROR)
+    {
+        OIC_LOG(ERROR, TAG, "OnBoarding Failed");
+        return;
+    }
+
+    g_isInitialized = true;
+
+    OIC_LOG_V(ERROR, TAG, "OnBoarding succeded. Successfully connected to ssid : %s",ssid);
+}
+
+void ESInitResources()
+{
+    OIC_LOG(DEBUG, TAG, "ESInitResources is invoked...");
+
+    // Initialize the OC Stack in Server mode
+    if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, TAG, "OCStack init error!!");
+        return;
+    }
+
+    if (ESInitProvisioning() == ES_ERROR)
+    {
+        OIC_LOG(ERROR, TAG, "Init Provisioning Failed!!");
+        return;
+    }
+}
+
+void StopEasySetup()
+{
+    OIC_LOG(DEBUG, TAG, "Stopping EasySetup is invoked...");
+
+    g_isInitialized = false;
+
+    if (ESTerminateEnrollee() == ES_ERROR)
+    {
+        OIC_LOG(ERROR, TAG, "ESTerminateEnrollee Failed!!");
+        return;
+    }
+
+    //stop OC Stack
+    if (OCStop() != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, TAG, "OCStack stop failed!!");
+        return;
+    }
+
+    OIC_LOG(DEBUG, TAG, "Stopping EasySetup done");
+}
+
+
+//The setup function is called once at startup of the sketch
+void setup()
+{
+    // Add your initialization code here
+    // Note : This will initialize Serial port on Arduino at 115200 bauds
+    OIC_LOG_INIT();
+
+    Serial.println("#########################");
+    Serial.println("EasySetup Enrollee SAMPLE");
+    Serial.println("#########################");
+    PrintMenu();
+}
+
+// The loop function is called in an endless loop
+void loop()
+{
+    char buffer[5] = {0};
+    size_t len;
+    if (Serial.available() > 0)
+    {
+        GetData(buffer, sizeof(buffer), &len);
+        if (0 >= len)
+        {
+            Serial.println("Input Error err");
+            return;
+        }
+        switch (toupper(buffer[0]))
+        {
+            case 'H': // help
+                PrintMenu();
+                break;
+
+            case 'Q': // quit
+                Serial.println("quit");
+                return;
+
+            case 'S': // start easy setup
+                StartEasySetup();
+                break;
+
+            case 'P': // start provisioning
+                ESInitResources();
+                break;
+
+            case 'T': // stop easy setup
+                StopEasySetup();
+                break;
+
+            default:
+                Serial.println("wrong option");
+                break;
+        }
+    }
+
+    //check g_isInitialized to see if stack init is success
+    if (g_isInitialized)
+    {
+        // This call displays the amount of free SRAM available on Arduino
+        PrintArduinoMemoryStats();
+        if (WiFi.status() == WL_CONNECTED)
+            is_connected = true;
+        else if (is_connected)
+            ESTerminateEnrollee();
+
+        // Give CPU cycles to OCStack to perform send/recv and other OCStack stuff
+        if (OCProcess() != OC_STACK_OK)
+        {
+            OIC_LOG(ERROR, TAG, "OCStack process error");
+            return;
+        }
+    }
+
+    // This artificial delay is kept here to avoid endless spinning
+    // of Arduino microcontroller. Modify it as per specific application needs.
+    delay(2000);
+}
diff --git a/service/easy-setup/sampleapp/enrollee/linux/SConscript b/service/easy-setup/sampleapp/enrollee/linux/SConscript
new file mode 100644 (file)
index 0000000..6fb0f68
--- /dev/null
@@ -0,0 +1,67 @@
+#######################################################################
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+######################################################################
+# Build script for Linux Enrollee Sample App
+######################################################################
+
+Import('env')
+
+print Dir('#').abspath
+print Dir('.').abspath
+
+enrollee_env = env.Clone()
+transport = enrollee_env.get('TARGET_TRANSPORT')
+
+######################################################################
+# Build flags
+######################################################################
+enrollee_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+enrollee_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x'])
+
+if env.get('RELEASE'):
+    enrollee_env.AppendUnique(CCFLAGS = ['-Os'])
+    enrollee_env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+else:
+    enrollee_env.AppendUnique(CCFLAGS = ['-g'])
+
+if env.get('LOGGING'):
+    env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+enrollee_env.PrependUnique(CPPPATH = [
+               env.get('SRC_DIR') + '/resource/include',
+        env.get('SRC_DIR') + '/resource/oc_logger/include',
+        env.get('SRC_DIR') + '/resource/csdk/logger/include',
+        env.get('SRC_DIR') + '/resource/csdk/stack/include',
+        env.get('SRC_DIR') + '/extlibs/cjson',
+        env.get('SRC_DIR') + '/service/easy-setup/inc',
+        env.get('SRC_DIR') + '/service/easy-setup/enrollee/linux/wifi',
+        env.get('SRC_DIR') + '/service/easy-setup/enrollee/inc',
+        env.get('SRC_DIR') + '/service/easy-setup/enrollee/src'])
+
+enrollee_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'ocsrm', 'pthread', 'connectivity_abstraction','coap', 'ESEnrolleeSDK'])
+if enrollee_env.get('SECURED') == '1':
+       enrollee_env.PrependUnique(LIBS = ['ocpmapi', 'ocprovision'])
+
+enrollee = enrollee_env.Program('enrollee', 'enrolleewifi.c')
+
+i_enrollee = enrollee_env.Install(env.get('BUILD_DIR'), enrollee)
+
+Alias('enrollee', i_enrollee)
+env.AppendTarget('enrollee')
diff --git a/service/easy-setup/sampleapp/enrollee/linux/enrolleewifi.c b/service/easy-setup/sampleapp/enrollee/linux/enrolleewifi.c
new file mode 100644 (file)
index 0000000..e645bc4
--- /dev/null
@@ -0,0 +1,247 @@
+//******************************************************************
+//
+// 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 "easysetup.h"
+
+#include <unistd.h>
+#include <string.h>
+#include <stdio.h>
+#include <pthread.h>
+
+#define TAG "TS"
+
+void *listeningFunc(void *);
+
+/**
+ * @var ssid
+ * @brief Target SSID of the Soft Access point to which the device has to connect
+ */
+static char ssid[] = "EasySetup123";
+
+/**
+ * @var passwd
+ * @brief Password of the Soft Access point to which the device has to connect
+ */
+static char passwd[] = "EasySetup123";
+
+/**
+ * Secure Virtual Resource database for Iotivity Server
+ * It contains Server's Identity and the PSK credentials
+ * of other devices which the server trusts
+ */
+static char CRED_FILE[] = "oic_svr_db_server.dat";
+
+OCPersistentStorage ps ;
+
+
+/**
+ * @var gIsSecured
+ * @brief Variable to check if secure mode is enabled or not.
+ */
+static bool gIsSecured = false;
+
+void PrintMenu()
+{
+    printf("============\n");
+    printf("S: Enabled Security\n");
+    printf("I: Init easy setup\n");
+    printf("P: start provisioning resources\n");
+    printf("T: terminate\n");
+    printf("Q: quit\n");
+    printf("============\n");
+}
+
+void EventCallbackInApp(ESResult esResult, ESEnrolleeState enrolleeState)
+{
+    printf("Easy setup event callback\n");
+
+    if(esResult == ES_OK)
+    {
+        if(enrolleeState == ES_ON_BOARDED_STATE)
+        {
+            printf("Device is successfully OnBoared on Adhoc network\n");
+        }
+        else if (enrolleeState == ES_PROVISIONED_STATE)
+        {
+            printf("Device is provisioned with target network's credentials\n");
+        }
+        else if (enrolleeState == ES_ON_BOARDED_TARGET_NETWORK_STATE)
+        {
+            printf("Device is onboarded/connected with target network\n");
+        }
+        else
+        {
+            printf("Wrong state !! Easy setup is failed at Enrollee state = %d\n",enrolleeState);
+        }
+    }
+    else
+    {
+        printf("Easy stup is failed at Enrollee state = %d\n",enrolleeState);;
+    }
+
+    PrintMenu();
+}
+
+FILE* server_fopen(const char *path, const char *mode)
+{
+    (void) path;
+    return fopen(CRED_FILE, mode);
+}
+
+void EnableSecurity()
+{
+    printf("Inside EnableSecurity API..\n");
+
+    gIsSecured = true;
+
+    // Initialize Persistent Storage for SVR database
+    ps = (OCPersistentStorage){ server_fopen, fread, fwrite, fclose, unlink };
+    OCRegisterPersistentStorageHandler(&ps);
+}
+
+void StartEasySetup()
+{
+    printf("StartEasySetup and onboarding started..\n");
+
+    if(ESInitEnrollee(CT_ADAPTER_IP, ssid, passwd, gIsSecured, EventCallbackInApp) == ES_ERROR)
+    {
+        printf("StartEasySetup and onboarding Fail!!\n");
+        return;
+    }
+}
+
+void ESInitResources()
+{
+    printf("Starting Enrollee Provisioning\n");
+
+    // Initialize the OC Stack in Server mode
+    if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
+    {
+        printf("OCStack init error!!\n");
+        return;
+    }
+
+    if (ESInitProvisioning() == ES_ERROR)
+    {
+        printf("Init Provisioning Failed!!\n");
+        return;
+    }
+
+    pthread_t thread_handle;
+    if (pthread_create(&thread_handle, NULL, listeningFunc, NULL))
+    {
+        printf("Thread creation failed\n");
+    }
+
+    printf("ESInitProvisioning Success\n");
+}
+
+void StopEasySetup()
+{
+    printf("StopEasySetup IN\n");
+
+    if (ESTerminateEnrollee() == ES_ERROR)
+    {
+        printf("ESTerminateEnrollee Failed!!\n");
+        return;
+    }
+
+    //stop OC Stack
+    if (OCStop() != OC_STACK_OK)
+    {
+        printf("OCStack stop failed!!\n");
+        return;
+    }
+
+    printf("StopEasySetup OUT\n");
+}
+
+int main()
+{
+    printf("#########################\n");
+    printf("EasySetup Enrollee SAMPLE\n");
+    printf("#########################\n");
+    PrintMenu();
+    char option = 'T';
+
+    while(true)
+    {
+        scanf("%c",&option);
+
+       if(option!= '\n')
+      {
+            switch (option)
+            {
+                case 'H': // help
+                case 'h':
+                    PrintMenu();
+                    break;
+
+                case 'Q': // quit
+                case 'q':
+                    printf("quit");
+                    break;
+
+                case 'S': // Enable Security
+                case 's':
+                    EnableSecurity();
+                    break;
+
+                case 'I': // Init EasySetup
+                case 'i':
+                    StartEasySetup();
+                    break;
+
+                case 'P': // start provisioning
+                case 'p':
+                    ESInitResources();
+                    break;
+
+                case 'T': // stop easy setup
+                case 't':
+                    StopEasySetup();
+                    break;
+
+                default:
+                    printf("wrong option\n");
+                    break;
+            }
+            if (option == 'Q' || option == 'q') break;
+        }
+    }
+    return 0;
+}
+
+void *listeningFunc(void * a)
+{
+    OCStackResult result;
+
+    while (true)
+    {
+        result = OCProcess();
+        if (result != OC_STACK_OK)
+        {
+           printf("OCStack stop error");
+        }
+    }
+    return NULL;
+}
+
diff --git a/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/SConscript b/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/SConscript
new file mode 100644 (file)
index 0000000..0cd8288
--- /dev/null
@@ -0,0 +1,219 @@
+##########################################################################
+#
+# 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.
+#
+##########################################################################
+
+##
+# This script includes generic build options:
+#    release/debug, target os, target arch, cross toolchain, build environment etc
+##
+import os
+import platform
+
+print "Inside the Config SConscript"
+# Map of host os and allowed target os (host: allowed target os)
+host_target_map = {
+        'linux': ['linux', 'android', 'arduino', 'yocto', 'tizen'],
+        'windows': ['windows', 'winrt', 'android', 'arduino', 'tizen'],
+        'darwin': ['darwin', 'ios', 'android', 'arduino'],
+        }
+
+# Map of os and allowed archs (os: allowed archs)
+os_arch_map = {
+        'linux': ['x86', 'x86_64', 'arm', 'arm64'],
+        'android': ['x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'armeabi-v7a-hard', 'arm64-v8a'],
+        'windows': ['x86', 'amd64', 'arm'],
+        'winrt': ['arm'],
+        'darwin': ['i386', 'x86_64'],
+        'ios': ['i386', 'x86_64', 'armv7', 'armv7s', 'arm64'],
+        'arduino': ['avr', 'arm'],
+                'yocto': ['x86', 'x86_64'],
+        'tizen': ['armv7'],
+        }
+
+host = platform.system().lower()
+
+if not host_target_map.has_key(host):
+    print "\nError: Current system (%s) isn't supported\n" % host
+    Exit(1)
+
+######################################################################
+# Get build options (the optins from command line)
+######################################################################
+target_os = ARGUMENTS.get('TARGET_OS', host).lower() # target os
+
+if target_os not in host_target_map[host]:
+    print "\nError: Unknown target os: %s (Allow values: %s)\n" % (target_os, host_target_map[host])
+    Exit(1)
+
+default_arch = platform.machine()
+if default_arch not in os_arch_map[target_os]:
+    default_arch = os_arch_map[target_os][0].lower()
+
+target_arch = ARGUMENTS.get('TARGET_ARCH', default_arch) # target arch
+
+######################################################################
+# Common build options (release, target os, target arch)
+######################################################################
+help_vars = Variables()
+help_vars.Add(BoolVariable('RELEASE', 'Build for release?', True)) # set to 'no', 'false' or 0 for debug
+help_vars.Add(EnumVariable('TARGET_OS', 'Target platform', host, host_target_map[host]))
+help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'IP', 'BT', 'BLE']))
+help_vars.Add(EnumVariable('TARGET_ARCH', 'Target architecture', default_arch, os_arch_map[target_os]))
+help_vars.Add(EnumVariable('SECURED', 'Build with DTLS', '0', allowed_values=('0', '1')))
+help_vars.Add(EnumVariable('ROUTING', 'Enable routing', 'EP', allowed_values=('GW', 'EP')))
+
+######################################################################
+# Platform(build target) specific options: SDK/NDK & toolchain
+######################################################################
+targets_support_cc = ['tizen']
+
+if target_os in targets_support_cc:
+    # Set cross compile toolchain
+    help_vars.Add('TC_PREFIX', "Toolchain prefix (Generally only be required for cross-compiling)", os.environ.get('TC_PREFIX'))
+    help_vars.Add(PathVariable('TC_PATH',
+            'Toolchain path (Generally only be required for cross-compiling)',
+            os.environ.get('TC_PATH')))
+
+if target_os in ['android', 'arduino']: # Android/Arduino always uses GNU compiler regardless of the host
+    env = Environment(variables = help_vars,
+            tools = ['gnulink', 'gcc', 'g++', 'ar', 'as']
+            )
+else:
+    env = Environment(variables = help_vars, TARGET_ARCH = target_arch, TARGET_OS = target_os)
+
+Help(help_vars.GenerateHelpText(env))
+
+tc_set_msg = '''
+************************************ Warning **********************************
+*   Enviornment variable TC_PREFIX/TC_PATH is set. It will change the default *
+* toolchain, if it isn't what you expect you should unset it, otherwise it may*
+* cause inexplicable errors.                                                  *
+*******************************************************************************
+'''
+
+if target_os in targets_support_cc:
+    prefix = env.get('TC_PREFIX')
+    tc_path = env.get('TC_PATH')
+    if prefix:
+        env.Replace(CC = prefix + 'gcc')
+        env.Replace(CXX = prefix + 'g++')
+        env.Replace(AR = prefix + 'ar')
+        env.Replace(AS = prefix + 'as')
+        env.Replace(LINK = prefix + 'ld')
+        env.Replace(RANLIB = prefix + 'ranlib')
+
+    if tc_path:
+        env.PrependENVPath('PATH', tc_path)
+        sys_root = os.path.abspath(tc_path + '/../')
+        env.AppendUnique(CCFLAGS = ['--sysroot=' + sys_root])
+        env.AppendUnique(LINKFLAGS = ['--sysroot=' + sys_root])
+
+    if prefix or tc_path:
+        print tc_set_msg
+
+# Ensure scons be able to change its working directory
+env.SConscriptChdir(1)
+
+# Set the source directory and build directory
+#   Source directory: 'dir'
+#   Build directory: 'dir'/out/<target_os>/<target_arch>/<release or debug>/
+#
+# You can get the directory as following:
+#   env.get('SRC_DIR')
+#   env.get('BUILD_DIR')
+
+def __set_dir(env, dir):
+    if not os.path.exists(dir + '/SConstruct'):
+        print '''
+*************************************** Error *********************************
+* The directory(%s) seems isn't a source code directory, no SConstruct file is
+* found. *
+*******************************************************************************
+''' % dir
+        Exit(1)
+
+    if env.get('RELEASE'):
+        build_dir = dir + '/out/' + target_os + '/' + target_arch + '/release/'
+    else:
+        build_dir = dir + '/out/' + target_os + '/' + target_arch + '/debug/'
+    env.VariantDir(build_dir, dir, duplicate=0)
+
+    env.Replace(BUILD_DIR = build_dir)
+    env.Replace(SRC_DIR = dir)
+
+def __src_to_obj(env, src, home = ''):
+    obj = env.get('BUILD_DIR') + src.replace(home, '')
+    if env.get('OBJSUFFIX'):
+        obj += env.get('OBJSUFFIX')
+    return env.Object(obj, src)
+
+def __install(ienv, targets, name):
+    i_n = ienv.Install(env.get('BUILD_DIR'), targets)
+    Alias(name, i_n)
+    env.AppendUnique(TS = [name])
+
+def __append_target(ienv, target):
+    env.AppendUnique(TS = [target])
+
+def __print_targets(env):
+    Help('''
+===============================================================================
+Targets:\n    ''')
+    for t in env.get('TS'):
+        Help(t + ' ')
+    Help('''
+\nDefault all targets will be built. You can specify the target to build:
+
+    $ scons [options] [target]
+===============================================================================
+''')
+
+env.AddMethod(__set_dir, 'SetDir')
+env.AddMethod(__print_targets, 'PrintTargets')
+env.AddMethod(__src_to_obj, 'SrcToObj')
+env.AddMethod(__append_target, 'AppendTarget')
+env.AddMethod(__install, 'InstallTarget')
+env.SetDir(env.GetLaunchDir())
+env['ROOT_DIR']=env.GetLaunchDir()
+
+env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+if env.get('ROUTING') == 'GW':
+    env.AppendUnique(CPPDEFINES = ['ROUTING_GATEWAY'])
+elif env.get('ROUTING') == 'EP':
+    env.AppendUnique(CPPDEFINES = ['ROUTING_EP'])
+env.AppendUnique(CPPDEFINES = ['__TIZEN__'])
+
+Export('env')
+
+######################################################################
+# continue with the regular build process. Load config of target os
+######################################################################
+env.SConscript(target_os + '/SConscript')
+
+# Delete the temp files of configuration
+if env.GetOption('clean'):
+    dir = env.get('SRC_DIR')
+
+    if os.path.exists(dir + '/config.log'):
+        Execute(Delete(dir + '/config.log'))
+        Execute(Delete(dir + '/.sconsign.dblite'))
+        Execute(Delete(dir + '/.sconf_temp'))
+
+Return('env')
+
diff --git a/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/SConscript b/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/SConscript
new file mode 100644 (file)
index 0000000..7082662
--- /dev/null
@@ -0,0 +1,266 @@
+##
+# This script includes generic build options:
+#    release/debug, target os, target arch, cross toolchain, build environment etc
+##
+import os
+import platform
+
+# Map of host os and allowed target os (host: allowed target os)
+host_target_map = {
+               'linux': ['linux', 'android', 'arduino', 'yocto', 'tizen'],
+               'windows': ['windows', 'winrt', 'android', 'arduino'],
+               'darwin': ['darwin', 'ios', 'android', 'arduino'],
+               }
+
+# Map of os and allowed archs (os: allowed archs)
+os_arch_map = {
+               'linux': ['x86', 'x86_64', 'arm', 'arm64'],
+               'tizen': ['x86', 'x86_64', 'arm', 'arm64'],
+               'android': ['x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'armeabi-v7a-hard', 'arm64-v8a'],
+               'windows': ['x86', 'amd64', 'arm'],
+               'winrt': ['arm'],
+               'darwin': ['i386', 'x86_64'],
+               'ios': ['i386', 'x86_64', 'armv7', 'armv7s', 'arm64'],
+               'arduino': ['avr', 'arm'],
+                'yocto': ['i586', 'x86_64', 'arm', 'powerpc', 'powerpc64', 'mips', 'mipsel'],
+               }
+
+es_role_map = {
+               'enrollee', 'mediator'
+               }
+
+es_target_enrollee_map = {
+               'arduino', 'tizen', 'linux'
+               }
+
+es_softap_mode_map = {
+               'ENROLLEE_SOFTAP', 'MEDIATOR_SOFTAP'
+               }
+
+host = platform.system().lower()
+
+if not host_target_map.has_key(host):
+       print "\nError: Current system (%s) isn't supported\n" % host
+       Exit(1)
+
+######################################################################
+# Get build options (the optins from command line)
+######################################################################
+target_os = ARGUMENTS.get('TARGET_OS', host).lower() # target os
+
+if target_os not in host_target_map[host]:
+       print "\nError: Unknown target os: %s (Allow values: %s)\n" % (target_os, host_target_map[host])
+       Exit(1)
+
+default_arch = platform.machine()
+if default_arch not in os_arch_map[target_os]:
+       default_arch = os_arch_map[target_os][0].lower()
+
+target_arch = ARGUMENTS.get('TARGET_ARCH', default_arch) # target arch
+
+# True if binary needs to be installed on board. (Might need root permissions)
+# set to 'no', 'false' or 0 for only compilation
+require_upload = ARGUMENTS.get('UPLOAD', True)
+
+# Get the device name
+device_name = ARGUMENTS.get('DEVICE_NAME', "OIC-DEVICE")
+
+# Get es_role
+es_role = ARGUMENTS.get('ES_ROLE')
+
+if es_role not in es_role_map:
+       print "\nError: Unknown ES_ROLE: %s (Allow values: %s)\n" % (es_role, es_role_map)
+       Exit(1)
+
+# Get es_target_enrollee
+es_target_enrollee = ARGUMENTS.get('ES_TARGET_ENROLLEE')
+
+if es_target_enrollee not in es_target_enrollee_map:
+       print "\nError: Unknown ES_TARGET_ENROLLEE: %s (Allow values: %s)\n" % (es_target_enrollee, es_target_enrollee_map)
+       Exit(1)
+
+# Get es_soft_mode
+es_soft_mode = ARGUMENTS.get('ES_SOFTAP_MODE')
+
+if es_soft_mode not in es_softap_mode_map:
+       print "\nError: Unknown ES_SOFTAP_MODE: %s (Allow values: %s)\n" % (es_soft_mode, es_softap_mode_map)
+       Exit(1)
+
+######################################################################
+# Common build options (release, target os, target arch)
+######################################################################
+help_vars = Variables()
+help_vars.Add(BoolVariable('RELEASE', 'Build for release?', True)) # set to 'no', 'false' or 0 for debug
+help_vars.Add(BoolVariable('LOGGING', 'Enable stack logging', False))
+help_vars.Add(EnumVariable('TARGET_OS', 'Target platform', host, host_target_map[host]))
+help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'BT', 'BLE', 'IP', 'TCP']))
+help_vars.Add(EnumVariable('TARGET_ARCH', 'Target architecture', default_arch, os_arch_map[target_os]))
+help_vars.Add(EnumVariable('SECURED', 'Build with DTLS', '0', allowed_values=('0', '1')))
+help_vars.Add(BoolVariable('UPLOAD', 'Upload binary ? (For Arduino)', require_upload))
+help_vars.Add(EnumVariable('ROUTING', 'Enable routing', 'EP', allowed_values=('GW', 'EP')))
+help_vars.Add(EnumVariable('BUILD_SAMPLE', 'Build with sample', 'ON', allowed_values=('ON', 'OFF')))
+
+help_vars.AddVariables(('DEVICE_NAME', 'Network display name for device', 'OIC-DEVICE', None, None),)
+
+#ES_TARGET_ENROLLEE is for specifying what is our target enrollee (Arduino or rest of platforms which support Multicast)
+help_vars.Add(EnumVariable('ES_TARGET_ENROLLEE', 'Target Enrollee', 'arduino', allowed_values=('arduino', 'tizen', 'linux')))
+#ES_ROLE is for specifying the role (Enrollee or Mediator) for which scons is being executed
+help_vars.Add(EnumVariable('ES_ROLE', 'Target build mode', 'mediator', allowed_values=('mediator', 'enrollee')))
+#ES_SOFT_MODE is for specifying MODE (Mode 1 : Enrollee with  Soft AP or Mode 2  : Mediator with Soft AP)
+help_vars.Add(EnumVariable('ES_SOFTAP_MODE', 'Target build mode', 'ENROLLEE_SOFTAP', allowed_values=('ENROLLEE_SOFTAP', 'MEDIATOR_SOFTAP')))
+
+AddOption('--prefix',
+                  dest='prefix',
+                  type='string',
+                  nargs=1,
+                  action='store',
+                  metavar='DIR',
+                  help='installation prefix')
+
+######################################################################
+# Platform(build target) specific options: SDK/NDK & toolchain
+######################################################################
+targets_support_cc = ['linux', 'arduino', 'tizen']
+
+if target_os in targets_support_cc:
+       # Set cross compile toolchain
+       help_vars.Add('TC_PREFIX', "Toolchain prefix (Generally only be required for cross-compiling)", os.environ.get('TC_PREFIX'))
+       help_vars.Add(PathVariable('TC_PATH',
+                       'Toolchain path (Generally only be required for cross-compiling)',
+                       os.environ.get('TC_PATH')))
+
+if target_os in ['android', 'arduino']: # Android/Arduino always uses GNU compiler regardless of the host
+       env = Environment(variables = help_vars,
+                       tools = ['gnulink', 'gcc', 'g++', 'ar', 'as']
+                       )
+else:
+       env = Environment(variables = help_vars, TARGET_ARCH = target_arch, TARGET_OS = target_os, ES_ROLE = es_role, ES_TARGET_ENROLLEE = es_target_enrollee, ES_SOFTAP_MODE = es_soft_mode, ESPREFIX = GetOption('prefix'))
+
+Help(help_vars.GenerateHelpText(env))
+
+# Set device name to __OIC_DEVICE_NAME__
+env.AppendUnique(CPPDEFINES = ['-D__OIC_DEVICE_NAME__=' + "\'\"" + device_name + "\"\'"])
+
+tc_set_msg = '''
+************************************ Warning **********************************
+*   Enviornment variable TC_PREFIX/TC_PATH is set. It will change the default *
+* toolchain, if it isn't what you expect you should unset it, otherwise it may*
+* cause inexplicable errors.                                                  *
+*******************************************************************************
+'''
+
+if target_os in targets_support_cc:
+       prefix = env.get('TC_PREFIX')
+       tc_path = env.get('TC_PATH')
+       if prefix:
+               env.Replace(CC = prefix + 'gcc')
+               env.Replace(CXX = prefix + 'g++')
+               env.Replace(AR = prefix + 'ar')
+               env.Replace(AS = prefix + 'as')
+               env.Replace(LINK = prefix + 'ld')
+               env.Replace(RANLIB = prefix + 'ranlib')
+
+       if tc_path:
+               env.PrependENVPath('PATH', tc_path)
+               sys_root = os.path.abspath(tc_path + '/../')
+               env.AppendUnique(CCFLAGS = ['--sysroot=' + sys_root])
+               env.AppendUnique(LINKFLAGS = ['--sysroot=' + sys_root])
+
+       if prefix or tc_path:
+               print tc_set_msg
+
+# Ensure scons be able to change its working directory
+env.SConscriptChdir(1)
+
+# Set the source directory and build directory
+#   Source directory: 'dir'
+#   Build directory: 'dir'/out/<target_os>/<target_arch>/<release or debug>/
+#
+# You can get the directory as following:
+#   env.get('SRC_DIR')
+#   env.get('BUILD_DIR')
+
+def __set_dir(env, dir):
+       if not os.path.exists(dir + '/SConstruct'):
+               print '''
+*************************************** Error *********************************
+* The directory(%s) seems isn't a source code directory, no SConstruct file is
+* found. *
+*******************************************************************************
+''' % dir
+               Exit(1)
+
+       if env.get('RELEASE'):
+               build_dir = dir + '/out/' + target_os + '/' + target_arch + '/release/'
+       else:
+               build_dir = dir + '/out/' + target_os + '/' + target_arch + '/debug/'
+       env.VariantDir(build_dir, dir, duplicate=0)
+
+       env.Replace(BUILD_DIR = build_dir)
+       env.Replace(SRC_DIR = dir)
+
+def __src_to_obj(env, src, home = ''):
+       obj = env.get('BUILD_DIR') + src.replace(home, '')
+       if env.get('OBJSUFFIX'):
+               obj += env.get('OBJSUFFIX')
+       return env.Object(obj, src)
+
+def __install(ienv, targets, name):
+       i_n = ienv.Install(env.get('BUILD_DIR'), targets)
+       Alias(name, i_n)
+       env.AppendUnique(TS = [name])
+
+def __installlib(ienv, targets, name):
+       user_prefix = env.get('PREFIX')
+       if user_prefix:
+               i_n = ienv.Install(user_prefix + '/lib', targets)
+       else:
+               i_n = ienv.Install(env.get('BUILD_DIR'), targets)
+       ienv.Alias("install", i_n)
+
+def __installbin(ienv, targets, name):
+       user_prefix = env.get('PREFIX')
+       if user_prefix:
+               i_n = ienv.Install(user_prefix + '/bin', targets)
+       else:
+               i_n = ienv.Install(env.get('BUILD_DIR'), targets)
+       ienv.Alias("install", i_n)
+
+def __append_target(ienv, target):
+       env.AppendUnique(TS = [target])
+
+def __print_targets(env):
+       Help('''
+===============================================================================
+Targets:\n    ''')
+       for t in env.get('TS'):
+               Help(t + ' ')
+       Help('''
+\nDefault all targets will be built. You can specify the target to build:
+
+    $ scons [options] [target]
+===============================================================================
+''')
+
+env.AddMethod(__set_dir, 'SetDir')
+env.AddMethod(__print_targets, 'PrintTargets')
+env.AddMethod(__src_to_obj, 'SrcToObj')
+env.AddMethod(__append_target, 'AppendTarget')
+env.AddMethod(__install, 'InstallTarget')
+env.AddMethod(__installlib, 'UserInstallTargetLib')
+env.AddMethod(__installbin, 'UserInstallTargetBin')
+env.SetDir(env.GetLaunchDir())
+env['ROOT_DIR']=env.GetLaunchDir()+'/..'
+
+Export('env')
+
+# Delete the temp files of configuration
+if env.GetOption('clean'):
+       dir = env.get('SRC_DIR')
+
+       if os.path.exists(dir + '/config.log'):
+               Execute(Delete(dir + '/config.log'))
+               Execute(Delete(dir + '/.sconsign.dblite'))
+               Execute(Delete(dir + '/.sconf_temp'))
+
+Return('env')
diff --git a/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/tizen/Makefile b/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/tizen/Makefile
new file mode 100644 (file)
index 0000000..726faee
--- /dev/null
@@ -0,0 +1,65 @@
+##
+# override with `make BUILD=debug`
+# override with `make PLATFORM=arduinomega` or `make PLATFORM=arduinodue`
+# default to release build
+# default to build for linux
+BUILD   := debug
+PLATFORM := tizen
+OBJ_DIR := ./bin
+ROOT_DIR := .
+VERSION_MAJOR := 0
+VERSION_MINOR := 1
+VERSION_PATCH := 0
+ADAPTER_MACRO := -DWIFI_ADAPTER
+
+$(info *******************tizen Build !!******************)
+
+CC=gcc
+LIBCOAP=./lib/libcoap-4.1.1/
+LIBCOAP_OBJ_DIR=./lib/libcoap-4.1.1/obj
+
+TINYDTLS=./lib/extlibs/tinydtls
+TINYDTLS_OBJ_DIR=./lib/extlibs/tinydtls/obj
+
+# TODO : Currently Hardcoded WIFI_ADAPTER. Change it to generic
+CFLAGS.debug = -DWITH_POSIX -D__TIZEN__ -Wall -std=c99 -DSLP_SDK_LOG -g -D_GNU_SOURCE -DTIZEN_DEBUG_ENABLE -DTB_LOG $(ADAPTER_MACRO)
+CFLAGS.release = -DWITH_POSIX -D__TIZEN__ -Wall -std=c99 -DSLP_SDK_LOG -D_GNU_SOURCE -DTIZEN_DEBUG_ENABLE -DTB_LOG $(ADAPTER_MACRO)
+COMPILEFLAG = `pkg-config --cflags --libs capi-network-wifi dlog capi-network-bluetooth glib-2.0`
+
+# Include files will be copied into a single folder on gbsbuild.
+# NO NEED to mention the path explicitly.
+
+CA_INC              = $(ROOT_DIR)/
+DTLS_INC           = $(ROOT_DIR)/dtls/
+
+INC_DIRS        := -I$(CA_INC)
+INC_DIRS        += -I$(DTLS_INC)
+
+SRC = $(wildcard *.c)
+OBJECTS = $(patsubst %.c, %.o, $(SRC))
+
+#Currently compiling libcoap objects. If it's provided by external party.
+#Then don't compile, Instead directly extract objects and create liboicinterface.a
+all: $(OBJECTS)
+       $(MAKE) -C $(LIBCOAP) clean
+       $(MAKE) -C $(LIBCOAP)
+       -mkdir $(LIBCOAP_OBJ_DIR)
+       @cd $(LIBCOAP_OBJ_DIR) && $(AR) -x ../libcoap.a
+       ar rcs liboicinterface.a $(OBJECTS) $(LIBCOAP_OBJ_DIR)/*.o
+
+%.o : %.c
+       $(CC) -c $(CFLAGS.$(BUILD)) $(COMPILEFLAG) $(INC_DIRS) $< -o $@
+
+
+pack:
+#$(CC) $(CFLAGS) $(COMPILEFLAG) WiFiInterface.c bt_interface.c tc_interface.c sample_main.c -o sample /usr/lib/liboctbstack.a -lm -pthread
+       $(info **************************************TEST***************************)
+install:
+#cp -rf sample ./usr/apps/com.samsung.oicca/bin/sample
+
+clean:
+       rm -rf *.o sample
+       rm -f *.o *.d *.elf *.eep core.a *.hex *.bin *.map *-
+       rm -rf $(OBJ_DIR)
+       rm -rf $(LIBCOAP_OBJ_DIR)
+
diff --git a/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/tizen/SConscript b/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/tizen/SConscript
new file mode 100644 (file)
index 0000000..3831d79
--- /dev/null
@@ -0,0 +1,32 @@
+##
+# Enrollee sample build script
+##
+
+SConscript('./service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/SConscript')
+
+Import('env')
+
+target_os = env.get('TARGET_OS')
+transport = env.get('TARGET_TRANSPORT')
+buildsample = env.get('BUILD_SAMPLE')
+release_mode = env.get('RELEASE')
+secured = env.get('SECURED')
+logging = env.get('LOGGING')
+routing = env.get('ROUTING')
+es_role = env.get('ES_ROLE')
+es_target_enrollee = env.get('ES_TARGET_ENROLLEE')
+es_softap_mode = env.get('ES_SOFTAP_MODE')
+
+print "Given Transport is %s" % transport
+print "Given OS is %s" % target_os
+
+print "Given es_role is %s" % es_role
+print "Given es_target_enrollee is %s" % es_target_enrollee
+print "Given es_softap_mode is %s" % es_softap_mode
+
+
+if target_os == 'tizen':
+       command = "sh service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/tizen/gbsbuild.sh %s %s %s %s %s %s %s %s %s" % (transport, secured, buildsample, routing, release_mode, logging, es_role, es_target_enrollee, es_softap_mode)
+       print "Created Command is %s" % command
+       gbs_script = env.Command('gbs_build', None, command)
+       AlwaysBuild ('gbs_script')
\ No newline at end of file
diff --git a/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/tizen/SConstruct b/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/tizen/SConstruct
new file mode 100644 (file)
index 0000000..bc860fb
--- /dev/null
@@ -0,0 +1,23 @@
+##
+# The main build script
+#
+##
+
+# Load common build config
+# Load common build config
+SConscript('SConscript')
+
+Import('env')
+
+target_os = env.get('TARGET_OS')
+transport = env.get('TARGET_TRANSPORT')
+
+print "Given Transport is %s" % transport
+print "Given OS is %s" % target_os
+print "Secured %s" % env.get('SECURED')
+
+if target_os == 'tizen':
+        SConscript('scons/SConscript')
+else:
+       print "Given platform is not supported"
+
diff --git a/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/tizen/gbsbuild.sh b/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/tizen/gbsbuild.sh
new file mode 100644 (file)
index 0000000..5479bcc
--- /dev/null
@@ -0,0 +1,103 @@
+#!/bin/sh
+
+cur_dir="./service/easy-setup"
+
+spec=`ls ./service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/packaging/*.spec`
+version=`rpm --query --queryformat '%{version}\n' --specfile $spec`
+
+name=`echo $name|cut -d" " -f 1`
+version=`echo $version|cut -d" " -f 1`
+
+name=iotivity
+
+rm -rf $name-$version
+
+builddir=`pwd`
+sourcedir=`pwd`
+
+echo `pwd`
+
+rm -rf ./tmp
+
+# Create directory structure for GBS Build
+mkdir ./tmp
+mkdir ./tmp/con/
+mkdir ./tmp/extlibs/
+mkdir ./tmp/packaging
+cp -R ./build_common $sourcedir/tmp
+cp -R ./examples $sourcedir/tmp
+
+# tinycbor is available as soft-link, so copying with 'dereference' option.
+cp -LR ./extlibs/tinycbor $sourcedir/tmp/extlibs
+rm -rf $sourcedir/tmp/extlibs/tinycbor/tinycbor/.git
+
+cp -R ./extlibs/cjson $sourcedir/tmp/extlibs
+cp -R ./extlibs/tinydtls $sourcedir/tmp/extlibs
+cp -R ./extlibs/sqlite3 $sourcedir/tmp/extlibs
+cp -R ./extlibs/timer $sourcedir/tmp/extlibs
+cp -R ./extlibs/rapidxml $sourcedir/tmp/extlibs
+cp -R ./resource $sourcedir/tmp
+cp -R ./service $sourcedir/tmp
+cp ./extra_options.scons $sourcedir/tmp
+cp ./tools/tizen/*.spec ./tmp/packaging
+cp ./tools/tizen/*.manifest ./tmp/packaging
+cp ./SConstruct ./tmp
+cp ./LICENSE.md ./tmp
+
+# copy dependency RPMs and conf files for tizen build
+cp ./tools/tizen/*.rpm ./tmp
+cp ./tools/tizen/.gbs.conf ./tmp
+cp ./tools/tizen/*.rpm $sourcedir/tmp/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample
+cp ./tools/tizen/.gbs.conf ./tmp/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample
+cp -R $sourcedir/iotivity.pc.in $sourcedir/tmp
+
+cd $sourcedir/tmp
+
+echo `pwd`
+
+whoami
+# Initialize Git repository
+if [ ! -d .git ]; then
+   git init ./
+   git config user.email "you@example.com"
+   git config user.name "Your Name"
+   git add ./
+   git commit -m "Initial commit"
+fi
+
+echo "Calling core gbs build command"
+gbscommand="gbs build -A armv7l --include-all  --repository ./ --define 'TARGET_TRANSPORT $1' --define 'SECURED $2' --define 'RELEASE $5' --define 'LOGGING $6' --define 'ES_ROLE $7' --define 'ES_TARGET_ENROLLEE $8' --define 'ES_SOFTAP_MODE $9'"
+echo $gbscommand
+if eval $gbscommand; then
+   echo "Core build is successful"
+else
+   echo "Core build failed."
+   cd $sourcedir
+   rm -rf $sourcedir/tmp
+   exit 1
+fi
+
+cd service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample
+echo `pwd`
+# Initialize Git repository
+if [ ! -d .git ]; then
+  git init ./
+  git config user.email "you@example.com"
+  git config user.name "Your Name"
+  git add ./
+  git commit -m "Initial commit"
+fi
+echo "Calling sample gbs build command"
+gbscommand="gbs build -A armv7l -B ~/GBS-ROOT --include-all --repository ./ --define 'TARGET_TRANSPORT $1' --define 'SECURED $2' --define 'ROUTING $4' --define 'RELEASE $5' --define 'LOGGING $6' --define 'ES_ROLE $7' --define 'ES_TARGET_ENROLLEE $8' --define 'ES_SOFTAP_MODE $9'"
+echo $gbscommand
+if eval $gbscommand; then
+  echo "Sample build is successful"
+else
+  echo "Sample build is failed."
+  exit 1
+fi
+rm -rf tmp
+cd $sourcedir
+rm -rf $sourcedir/tmp
+
+exit 0
diff --git a/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/com.oic.es.sample.manifest b/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/com.oic.es.sample.manifest
new file mode 100644 (file)
index 0000000..b37c690
--- /dev/null
@@ -0,0 +1,26 @@
+<manifest>
+       <define>
+         <domain name="essample" />
+         <permit>
+               <smack permit="system::use_internet" type="rwx"/>
+         </permit>
+         <request>
+                <smack request="system::use_internet" type="rwx"/>
+                <smack request="bt-service" type="rwx"/>
+               <smack request="sap" type="rwx"/>
+                <smack request="bt-service::spp" type="rwx"/>
+                <smack request="bt-service::gap" type="rwx"/>
+                <smack request="bt-service::admin" type="rwx"/>
+                <smack request="bt-service::manager" type="rwx"/>
+                <smack request="bt-service::public" type="rwx"/>
+                 <smack request="bt-service::platform" type="rwx"/>
+         </request>
+       </define>
+       <assign>
+               <filesystem path="/opt/apps/com.oic.es.sample/bin/sample" exec_label="sample" />
+       </assign>
+       <request>
+               <domain name="essample" />
+       </request>
+</manifest>
+
diff --git a/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/com.oic.es.sample.xml b/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/com.oic.es.sample.xml
new file mode 100644 (file)
index 0000000..fcf94d6
--- /dev/null
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns="http://tizen.org/ns/packages" package="com.oic.es.sample" version="0.1.12" install-location="internal-only">
+       <label>essample</label>
+       <author email="oic" href="www.iotivity.org">OIC</author>
+       <description>essample</description>
+       <ui-application appid="com.oic.es.sample" exec="/usr/apps/com.oic.es.sample/bin/sample" nodisplay="false" multiple="false" type="capp" taskmanage="true">
+               <icon>com.oic.es.sample.png</icon>
+               <label>essample</label>
+               <label xml:lang="en-us">essample</label>
+               <label xml:lang="nl-nl">essample</label>
+       </ui-application>
+       <privileges>
+               <privilege>http://tizen.org/privilege/socket</privilege>
+       </privileges>
+
+</manifest>
+
diff --git a/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/enrolleewifi.cpp b/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/enrolleewifi.cpp
new file mode 100755 (executable)
index 0000000..79943b1
--- /dev/null
@@ -0,0 +1,245 @@
+//******************************************************************
+//
+// 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 "easysetup.h"
+
+#include <unistd.h>
+#include <string.h>
+#include <iostream>
+#include <pthread.h>
+
+#define TAG "TS"
+
+using namespace std;
+
+void *listeningFunc(void*);
+
+/**
+ * @var ssid
+ * @brief Target SSID of the Soft Access point to which the device has to connect
+ */
+static char ssid[] = "EasySetup123";
+
+/**
+ * @var passwd
+ * @brief Password of the Soft Access point to which the device has to connect
+ */
+static char passwd[] = "EasySetup123";
+
+/**
+ * Secure Virtual Resource database for Iotivity Server
+ * It contains Server's Identity and the PSK credentials
+ * of other devices which the server trusts
+ */
+static char CRED_FILE[] = "oic_svr_db_server.dat";
+
+OCPersistentStorage ps ;
+
+
+/**
+ * @var gIsSecured
+ * @brief Variable to check if secure mode is enabled or not.
+ */
+static bool gIsSecured = false;
+
+void PrintMenu()
+{
+    cout<<"============"<<endl;
+    cout<<"S: Enabled Security"<<endl;
+    cout<<"I: Init easy setup"<<endl;
+    cout<<"P: start provisioning resources"<<endl;
+    cout<<"T: terminate"<<endl;
+    cout<<"Q: quit"<<endl;
+    cout<<"============"<<endl;
+}
+
+void EventCallbackInApp(ESResult esResult, ESEnrolleeState enrolleeState)
+{
+    cout<<"Easy setup event callback"<<endl;
+
+    if(esResult == ES_OK)
+    {
+        if(enrolleeState == ES_ON_BOARDED_STATE)
+        {
+            cout<<"Device is successfully OnBoared on Adhoc network"<<endl;
+        }
+        else if (enrolleeState == ES_PROVISIONED_STATE)
+        {
+            cout<<"Device is provisioned with target network's credentials"<<endl;
+        }
+        else if (enrolleeState == ES_ON_BOARDED_TARGET_NETWORK_STATE)
+        {
+            cout<<"Device is onboarded/connected with target network"<<endl;
+        }
+        else
+        {
+            cout<<"Wrong state !! Easy setup is failed at Enrollee state = "<<enrolleeState<<endl;
+        }
+    }
+    else
+    {
+        cout<<"Easy stup is failed at Enrollee state = "<<enrolleeState<<endl;
+    }
+
+    PrintMenu();
+}
+
+FILE* server_fopen(const char *path, const char *mode)
+{
+    (void) path;
+    return fopen(CRED_FILE, mode);
+}
+
+void EnableSecurity()
+{
+    cout << "Inside EnableSecurity API.." << endl;
+
+    gIsSecured = true;
+
+    // Initialize Persistent Storage for SVR database
+    ps = { server_fopen, fread, fwrite, fclose, unlink };
+    OCRegisterPersistentStorageHandler(&ps);
+}
+
+void StartEasySetup()
+{
+    cout<<"StartEasySetup and onboarding started.."<<endl;
+
+    if(ESInitEnrollee(CT_ADAPTER_IP, ssid, passwd, gIsSecured, EventCallbackInApp) == ES_ERROR)
+    {
+        cout<<"StartEasySetup and onboarding Fail!!"<<endl;
+        return;
+    }
+}
+
+void ESInitResources()
+{
+    cout<<"Starting Enrollee Provisioning"<<endl;
+
+    // Initialize the OC Stack in Server mode
+    if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
+    {
+        cout<<"OCStack init error!!"<<endl;
+        return;
+    }
+
+    if (ESInitProvisioning() == ES_ERROR)
+    {
+        cout<<"Init Provisioning Failed!!"<<endl;
+        return;
+    }
+
+    pthread_t thread_handle;
+    if (pthread_create(&thread_handle, NULL, listeningFunc, NULL))
+    {
+        cout<<"Thread creation failed"<<endl;
+    }
+
+    cout<<"ESInitProvisioning Success"<<endl;
+}
+
+void StopEasySetup()
+{
+    cout<<"StopEasySetup IN"<<endl;
+
+    if (ESTerminateEnrollee() == ES_ERROR)
+    {
+        cout<<"ESTerminateEnrollee Failed!!"<<endl;
+        return;
+    }
+
+    //stop OC Stack
+    if (OCStop() != OC_STACK_OK)
+    {
+        cout<<"OCStack stop failed!!"<<endl;
+        return;
+    }
+
+    cout<<"StopEasySetup OUT"<<endl;
+}
+
+int main()
+{
+    cout<<"#########################"<<endl;
+    cout<<"EasySetup Enrollee SAMPLE"<<endl;
+    cout<<"#########################"<<endl;
+    PrintMenu();
+    char option;
+
+    while(true)
+    {
+        cin>>option;
+        switch (option)
+        {
+            case 'H': // help
+            case 'h':
+                PrintMenu();
+                break;
+
+            case 'Q': // quit
+            case 'q':
+                cout<<"quit";
+                break;
+
+            case 'S': // Enable Security
+            case 's':
+                EnableSecurity();
+                break;
+
+            case 'I': // Init EasySetup
+            case 'i':
+                StartEasySetup();
+                break;
+
+            case 'P': // start provisioning
+            case 'p':
+                ESInitResources();
+                break;
+
+            case 'T': // stop easy setup
+            case 't':
+                StopEasySetup();
+                break;
+
+            default:
+                cout<<"wrong option"<<endl;
+                break;
+        }
+        if (option == 'Q' || option == 'q') break;
+    }
+    return 0;
+}
+
+void *listeningFunc(void*)
+{
+    OCStackResult result;
+
+    while (true)
+    {
+        result = OCProcess();
+        if (result != OC_STACK_OK)
+        {
+           cout<<"OCStack stop error";
+        }
+    }
+    return NULL;
+}
+
diff --git a/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/packaging/com.oic.es.sample.spec b/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/packaging/com.oic.es.sample.spec
new file mode 100644 (file)
index 0000000..3b49c9a
--- /dev/null
@@ -0,0 +1,52 @@
+%define PREFIX /usr/apps/com.oic.es.sample
+%define ROOTDIR  %{_builddir}/%{name}-%{version}
+
+Name: com-oic-es-sample
+Version:    0.1
+Release:    1
+Summary: Tizen adapter interfacesample application
+URL: http://slp-source.sec.samsung.net
+Source: %{name}-%{version}.tar.gz
+License: Apache-2.0
+Group: Applications/OICSample
+BuildRequires: pkgconfig(dlog)
+BuildRequires: pkgconfig(glib-2.0)
+BuildRequires: boost-devel
+BuildRequires: boost-thread
+BuildRequires: boost-system
+BuildRequires: boost-filesystem
+BuildRequires: pkgconfig(capi-network-wifi)
+BuildRequires: pkgconfig(capi-network-bluetooth)
+BuildRequires: scons
+BuildRequires: iotivity
+BuildRequires: iotivity-devel
+BuildRequires: iotivity-service
+
+
+%description
+EasySetup Sample application
+
+%prep
+%setup -q
+
+%build
+
+scons TARGET_OS=tizen LOGGING=True TARGET_TRANSPORT=%{TARGET_TRANSPORT} SECURED=%{SECURED} RELEASE=%{RELEASE} ROUTING=%{ROUTING} ES_ROLE=%{ES_ROLE} ES_TARGET_ENROLLEE=%{ES_TARGET_ENROLLEE} ES_SOFTAP_MODE=%{ES_SOFTAP_MODE}
+
+%install
+
+mkdir -p %{buildroot}%{_datadir}/packages
+mkdir -p %{buildroot}/%{_sysconfdir}/smack/accesses2.d
+mkdir -p %{buildroot}/usr/apps/com.oic.es.sample/bin/
+mkdir -p %{buildroot}/usr/apps/com.oic.es.sample/bin/internal
+
+cp -rf %{ROOTDIR}/com.oic.es.sample.xml %{buildroot}/%{_datadir}/packages
+cp -rf %{ROOTDIR}/scons/enrollee_wifi %{buildroot}/usr/apps/com.oic.es.sample/bin/
+
+%files
+%manifest com.oic.es.sample.manifest
+%defattr(-,root,root,-)
+/usr/apps/com.oic.es.sample/bin/enrollee_wifi
+/%{_datadir}/packages/com.oic.es.sample.xml
+
+
diff --git a/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/scons/SConscript b/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/scons/SConscript
new file mode 100644 (file)
index 0000000..bc58c75
--- /dev/null
@@ -0,0 +1,50 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+Import('env')
+
+target_os = env.get('TARGET_OS')
+transport = env.get('TARGET_TRANSPORT')
+secured = env.get('SECURED')
+routing = env.get('ROUTING')
+OIC_LIB = 'oic'
+root_dir = env.get('ROOT_DIR')
+build_dir = env.get('BUILD_DIR')
+sample_dir = build_dir
+
+env.AppendUnique(CPPFLAGS = ['-std=c++0x', '-fPIC', '-D__TIZEN__','-DWITH_POSIX', '-Wall', '-DSLP_SDK_LOG', '-g','-D_GNU_SOURCE','-DTIZEN_DEBUG_ENABLE', '-DTB_LOG','`pkg-config', '--cflags', '--libs','dlog','capi-network-wifi',
+                               'gobject-2.0','glib-2.0`'])
+
+env.AppendUnique(CPPDEFINES = ['TB_LOG', 'ESWIFI'])
+
+env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+
+if routing == 'GW':
+       env.AppendUnique(CPPDEFINES = ['ROUTING_GATEWAY'])
+elif routing == 'EP':
+       env.AppendUnique(CPPDEFINES = ['ROUTING_EP'])
+env.Append(LIBS=['octbstack','connectivity_abstraction','coap', 'libESEnrolleeSDK','pthread'])
+
+if secured == '1':
+       env.PrependUnique(CPPPATH = [root_dir + '/external/inc/'])
+       env.AppendUnique(CPPDEFINES = ['__WITH_DTLS__'])
+
+env.Program('enrollee_wifi', [sample_dir + 'enrolleewifi.cpp'])
+
diff --git a/service/easy-setup/sampleapp/enrollee/tizen-sdb/README.txt b/service/easy-setup/sampleapp/enrollee/tizen-sdb/README.txt
new file mode 100644 (file)
index 0000000..4d44594
--- /dev/null
@@ -0,0 +1,65 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+Build Procedure
+===============
+
+1) If you are building first time, then delete GBS-ROOT folder from home directory.
+   Note: Default build server URL for Tizen is set in gbs configuration file @ iotivity/tools/tizen/.gbs.conf.
+         If needed, same can be modified as per appropriate target.
+
+2) Go to "iotivity/" folder.
+3) Execute following command(s) to start build based on transport selection required :
+
+scons -f service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/tizen/SConscript TARGET_OS=tizen TARGET_TRANSPORT=IP ROUTING=EP RELEASE=0 LOGGING=true
+                       ES_ROLE=enrollee ES_TARGET_ENROLLEE=android ES_SOFTAP_MODE=ENROLLEE_SOFTAP
+
+4) If built for security mode:
+        After installing sample RPM on device, copy required .dat files and other applications to the same path where enrollee_wifi(executable) is available
+
+(If needed, modify the parameters accordingly)
+Note :- Upon successful execution of above command(s) RI library and sample console application(for tizen enrollee)
+        will be generated at path "~/GBS-ROOT/local/repos/<target>/armv7l/RPMS".
+
+Procedure to Execute Sample App:
+================================
+    1) Copy the generated rpms(iotivity-1.0.0-0.armv7l.rpm,iotivity-devel-1.0.0-0.armv7l.rpm,iotivity-service-1.0.0-0.armv7l.rpm,com-oic-es-sample-0.1-1.armv7l.rpm) to Tizen Device
+       (say /opt/usr/media/xxx/)
+    2) sdb shell
+    3) su
+    4) cd /opt/usr/media/xxx/
+    5) change-booting-mode.sh --update
+
+    6) Install the rpms using the following commands:
+        a) rpm -Uvh iotivity-1.0.1-0.armv7l.rpm --force --nodeps
+        a) rpm -Uvh iotivity-devel-1.0.1-0.armv7l.rpm --force --nodeps
+        a) rpm -Uvh iotivity-service-1.0.1-0.armv7l.rpm --force --nodeps
+        b) rpm -Uvh com-oic-es-sample-0.1-1.armv7l.rpm --force --nodeps
+    7) For IP transport, apply net-config smack rules using below command:
+        a) chsmack -a "net-config" /usr/apps/com.oic.es.sample/bin/*
+        b) chsmack -e "net-config" /usr/apps/com.oic.es.sample/bin/*
+    7) RPM will be installed in "/usr/apps/"
+       Execute the sample app by below commands
+        i) cd /usr/apps/com.oic.es.sample/bin
+        If executing with secure mode enabled then do the below step (no. ii)
+        ii) cp /usr/lib/oic_svr_db_server.dat .
+
+        Execute the application
+        ./enrollee_wifi
index fa408da..c249744 100644 (file)
@@ -18,6 +18,4 @@ android {
 }\r
 \r
 dependencies {\r
-    compile project(':EasySetupCore-debug')\r
-    compile project(':iotivity-armeabi-base-debug')\r
 }
\ No newline at end of file
diff --git a/service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/assets/oic_svr_db_client.dat b/service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/assets/oic_svr_db_client.dat
new file mode 100644 (file)
index 0000000..cb6a70f
Binary files /dev/null and b/service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/assets/oic_svr_db_client.dat differ
diff --git a/service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/assets/oic_svr_db_client.json b/service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/assets/oic_svr_db_client.json
new file mode 100644 (file)
index 0000000..592bc1b
--- /dev/null
@@ -0,0 +1,88 @@
+{\r
+    "acl": {\r
+        "aclist": {\r
+            "aces": [\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/res",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/p",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/types/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/ad",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/acl",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/doxm",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        } ,\r
+                        {\r
+                            "href": "/oic/sec/pstat",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                }\r
+            ]\r
+        },\r
+        "rowneruuid" : "61646d69-6e44-6576-6963-655575696430"\r
+    },\r
+    "pstat": {\r
+        "isop": true,\r
+        "deviceuuid": "61646d69-6e44-6576-6963-655575696430",\r
+        "rowneruuid": "61646d69-6e44-6576-6963-655575696430",\r
+        "cm": 0,\r
+        "tm": 0,\r
+        "om": 3,\r
+        "sm": 3\r
+        },\r
+    "doxm": {\r
+        "oxms": [0],\r
+        "oxmsel": 0,\r
+        "sct": 1,\r
+        "owned": true,\r
+        "deviceuuid": "61646d69-6e44-6576-6963-655575696430",\r
+        "devowneruuid": "61646d69-6e44-6576-6963-655575696430",\r
+        "rowneruuid": "61646d69-6e44-6576-6963-655575696430",\r
+        "dpc": false\r
+    }\r
+}\r
index 4153496..ad34966 100755 (executable)
 \r
 package org.iotivity.service.easysetup;\r
 \r
-import java.io.IOException;\r
-\r
-import org.iotivity.service.easysetup.mediator.EasySetupService;\r
-import org.iotivity.service.easysetup.mediator.EasySetupStatus;\r
-import org.iotivity.service.easysetup.mediator.EnrolleeDevice;\r
-import org.iotivity.service.easysetup.mediator.IpOnBoardingConnection;\r
-import org.iotivity.service.easysetup.mediator.EnrolleeDeviceFactory;\r
-import org.iotivity.service.easysetup.mediator.WiFiOnBoardingConfig;\r
-import org.iotivity.service.easysetup.mediator.WiFiProvConfig;\r
-\r
 import android.app.Activity;\r
+import android.app.AlertDialog;\r
+import android.content.DialogInterface;\r
+import android.content.Intent;\r
+import android.content.SharedPreferences;\r
+import android.database.sqlite.SQLiteDatabase;\r
+import android.net.ConnectivityManager;\r
+import android.net.NetworkInfo;\r
 import android.net.wifi.WifiConfiguration;\r
+import android.net.wifi.WifiManager;\r
 import android.os.Bundle;\r
 import android.os.Handler;\r
 import android.os.Message;\r
+import android.preference.PreferenceManager;\r
 import android.util.Log;\r
 import android.view.View;\r
 import android.view.View.OnClickListener;\r
 import android.widget.Button;\r
 import android.widget.EditText;\r
+import android.widget.LinearLayout;\r
 import android.widget.ProgressBar;\r
+import android.widget.RadioButton;\r
+import android.widget.RelativeLayout;\r
 import android.widget.TextView;\r
 import android.widget.Toast;\r
 \r
-public class MainActivity extends Activity {\r
+import org.iotivity.base.ModeType;\r
+import org.iotivity.base.OcException;\r
+import org.iotivity.base.OcPlatform;\r
+import org.iotivity.base.OcProvisioning;\r
+import org.iotivity.base.PlatformConfig;\r
+import org.iotivity.base.QualityOfService;\r
+import org.iotivity.base.ServiceType;\r
+import org.iotivity.service.easysetup.mediator.EasySetupService;\r
+import org.iotivity.service.easysetup.mediator.EasySetupStatus;\r
+import org.iotivity.service.easysetup.mediator.EnrolleeDevice;\r
+import org.iotivity.service.easysetup.mediator.IpOnBoardingConnection;\r
+import org.iotivity.service.easysetup.mediator.EnrolleeDeviceFactory;\r
+import org.iotivity.service.easysetup.mediator.WiFiOnBoardingConfig;\r
+import org.iotivity.service.easysetup.mediator.WiFiProvConfig;\r
+\r
+import java.io.File;\r
+import java.io.FileNotFoundException;\r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
+import java.io.InputStream;\r
+import java.io.OutputStream;\r
+\r
 \r
+public class MainActivity extends Activity {\r
+    private static final String TAG = "Easysetup Mediator: ";\r
 \r
-    /*Status to update the UI */\r
-    public static final int SUCCESS = 0;\r
-    public static final int FAILED = 1;\r
+    /* Status to update the UI */\r
+    public static final int SUCCESS       = 0;\r
+    public static final int FAILED        = 1;\r
     public static final int STATE_CHANGED = 2;\r
 \r
-    EditText mSsidText;\r
-    EditText mPassText;\r
+    public static final String OIC_CLIENT_JSON_DB_FILE =  "oic_svr_db_client.dat";\r
+    public static final String OIC_SQL_DB_FILE =  "PDM.db";\r
+\r
+    private static final int BUFFER_SIZE = 1024;\r
+    private String filePath = "";\r
+    private boolean isSecurityEnabled = false;\r
+    //create platform config\r
+    PlatformConfig cfg;\r
+\r
+\r
+    String                  mSoftAPSsid;\r
+    String                  mSoftAPPassword;\r
+    String                  mEnrollerSsid;\r
+    String                  mEnrollerPassword;\r
 \r
-    EditText mEnrolleeSsidText;\r
-    EditText mmEnrolleePasswordPassText;\r
+    EditText                mSoftAPSsidText;\r
+    EditText                mSoftAPPassText;\r
+    EditText                mEnrollerSsidText;\r
+    EditText                mEnrollerPasswordPassText;\r
 \r
+    TextView                mDeviceIpTextView;\r
+    TextView                mDeviceMacTextView;\r
+    TextView                mResultTextView;\r
 \r
-    TextView mDeviceIpTextView;\r
-    TextView mDeviceMacTextView;\r
+    ProgressBar             mProgressbar;\r
 \r
+    Button                  mStartButton;\r
+    Button                  mStopButton;\r
 \r
-    TextView mResultTextView;\r
-    ProgressBar mProgressbar;\r
-    Button mStartButton;\r
-    Button mStopButton;\r
-    Handler mHandler = new ThreadHandler();\r
+    RadioButton             mEnrollee;\r
+    RadioButton             mMediator;\r
+    RadioButton             mEnableSecurity;\r
+\r
+    LinearLayout            mSoftAP;\r
+    RelativeLayout          mDeviceInfo;\r
+    TextView                mDeviceText;\r
+\r
+    Handler                 mHandler      = new ThreadHandler();\r
 \r
     /**\r
      * Objects to be instantiated by the programmer\r
      */\r
-    WiFiProvConfig mWiFiProvConfig;\r
-    WiFiOnBoardingConfig mWiFiOnBoardingConfig;\r
-    EasySetupService mEasySetupService;\r
-    EnrolleeDeviceFactory mDeviceFactory;\r
-    EnrolleeDevice mDevice;\r
+    WiFiProvConfig          mWiFiProvConfig;\r
+    WiFiOnBoardingConfig    mWiFiOnBoardingConfig;\r
+    EasySetupService        mEasySetupService;\r
+    EnrolleeDeviceFactory   mDeviceFactory;\r
+    EnrolleeDevice          mDevice;\r
 \r
     @Override\r
     protected void onCreate(Bundle savedInstanceState) {\r
         super.onCreate(savedInstanceState);\r
         setContentView(R.layout.activity_main);\r
 \r
-        /* Initialize widgets to get user input for target network's SSID & password*/\r
-        mSsidText = (EditText) findViewById(R.id.ssid);\r
-        mPassText = (EditText) findViewById(R.id.password);\r
-        mEnrolleeSsidText = (EditText) findViewById(R.id.enrolleeSsid);\r
-        mmEnrolleePasswordPassText = (EditText) findViewById(R.id.enrolleePass);\r
+        /*\r
+         * Initialize widgets to get user input for target network's SSID &\r
+         * password\r
+         */\r
+        mSoftAP = (LinearLayout) findViewById(R.id.softAP);\r
+        mDeviceInfo = (RelativeLayout) findViewById(R.id.deviceInfo);\r
+        mDeviceText = (TextView) findViewById(R.id.textViewDeviceinfo);\r
+\r
+        mSoftAPSsidText = (EditText) findViewById(R.id.ssid);\r
+        mSoftAPPassText = (EditText) findViewById(R.id.password);\r
+        mEnrollerSsidText = (EditText) findViewById(R.id.enrolleeSsid);\r
+        mEnrollerPasswordPassText = (EditText) findViewById(R.id.enrolleePass);\r
         mDeviceIpTextView = (TextView) findViewById(R.id.ipAddr);\r
         mDeviceMacTextView = (TextView) findViewById(R.id.hardAddr);\r
 \r
         mResultTextView = (TextView) findViewById(R.id.status);\r
         mProgressbar = (ProgressBar) findViewById(R.id.progressBar);\r
 \r
+        mEnrollee = (RadioButton) findViewById(R.id.enrollee);\r
+        mMediator = (RadioButton) findViewById(R.id.mediator);\r
+        mEnableSecurity = (RadioButton) findViewById(R.id.enablesecurity);\r
 \r
+        mStartButton = (Button) findViewById(R.id.startSetup);\r
 \r
+        mEnrollee.setChecked(false);\r
+        mMediator.setChecked(false);\r
+        mStartButton.setEnabled(false);\r
 \r
-       /* Create Easy Setup Service instance*/\r
-        mEasySetupService = EasySetupService.getInstance(getApplicationContext(),\r
-                new EasySetupStatus() {\r
+        /* Create EnrolleeDevice Factory instance */\r
+        mDeviceFactory = EnrolleeDeviceFactory\r
+                .newInstance(getApplicationContext());\r
+\r
+        addListenerForStartAP();\r
+        addListenerForStopAP();\r
+\r
+        // default values for target network\r
+        mEnrollerSsidText.setText(R.string.target_default_ssid);\r
+        mEnrollerPasswordPassText.setText(R.string.target_default_pwd);\r
+        mSoftAPSsidText.setEnabled(false);\r
+        mSoftAPPassText.setEnabled(false);\r
+\r
+        mEnrollee.setOnClickListener(new OnClickListener() {\r
+            @Override\r
+            public void onClick(View v) {\r
+\r
+                mMediator.setChecked(false);\r
+                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(\r
+                        MainActivity.this);\r
+                alertDialogBuilder.setTitle("Network selection");\r
+                alertDialogBuilder\r
+                        .setMessage("Proceed to select the network!")\r
+                        .setCancelable(false)\r
+                        .setPositiveButton("Yes",\r
+                                new DialogInterface.OnClickListener() {\r
+                                    public void onClick(DialogInterface dialog,\r
+                                                        int id) {\r
+                                        MainActivity.this\r
+                                                .startActivity(new Intent(\r
+                                                        WifiManager.ACTION_PICK_WIFI_NETWORK));\r
+\r
+                                        mStartButton.setEnabled(true);\r
+                                        mSoftAP.setVisibility(View.INVISIBLE);\r
+                                        mDeviceInfo\r
+                                                .setVisibility(View.INVISIBLE);\r
+                                        mDeviceText\r
+                                                .setVisibility(View.INVISIBLE);\r
+                                    }\r
+                                })\r
+                        .setNegativeButton("No",\r
+                                new DialogInterface.OnClickListener() {\r
+                                    public void onClick(DialogInterface dialog,\r
+                                                        int id) {\r
+                                        mEnrollee.setChecked(false);\r
+                                        mStartButton.setEnabled(false);\r
+                                        dialog.cancel();\r
+                                    }\r
+                                });\r
+                alertDialogBuilder.create().show();\r
+            }\r
+        });\r
+\r
+        mMediator.setOnClickListener(new OnClickListener() {\r
+            @Override\r
+            public void onClick(View v) {\r
+                mStartButton.setEnabled(true);\r
+                mEnrollee.setChecked(false);\r
+                mSoftAPSsidText.setEnabled(false);\r
+                mSoftAPPassText.setEnabled(false);\r
+                mSoftAPSsidText.setText(R.string.softAP_ssid);\r
+                mSoftAPPassText.setText(R.string.softAP_pwd);\r
+                mDeviceIpTextView.setText(R.string.not_available);\r
+                mDeviceMacTextView.setText(R.string.not_available);\r
+                mResultTextView.setText(R.string.not_started);\r
+                mSoftAP.setVisibility(View.VISIBLE);\r
+                mDeviceInfo.setVisibility(View.VISIBLE);\r
+                mDeviceText.setVisibility(View.VISIBLE);\r
+            }\r
+        });\r
+\r
+        mEnableSecurity.setOnClickListener(new OnClickListener() {\r
+            @Override\r
+            public void onClick(View v) {\r
+                filePath = getFilesDir().getPath() + "/";\r
+                if (isSecurityEnabled) {\r
+                    isSecurityEnabled = false;\r
+                    mEnableSecurity.setChecked(false);\r
+                }\r
+                else {\r
+                    isSecurityEnabled = true;\r
+                    mEnableSecurity.setChecked(true);\r
+                }\r
+                //copy json when application runs first time\r
+                SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences\r
+                        (getApplicationContext());\r
+                boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);\r
+                if (isFirstRun) {\r
+                    copyJsonFromAsset();\r
+                    SharedPreferences.Editor editor = wmbPreference.edit();\r
+                    editor.putBoolean("FIRSTRUN", false);\r
+                    editor.commit();\r
+                }\r
+\r
+                initOICStack();\r
+            }\r
+        });\r
+        /* Create Easy Setup Service instance */\r
+        mEasySetupService = EasySetupService.getInstance(\r
+                getApplicationContext(), new EasySetupStatus() {\r
 \r
                     @Override\r
                     public void onFinished(final EnrolleeDevice enrolledevice) {\r
-                        Log.i("MainActivity", "onFinished() is received " + enrolledevice\r
-                                .isSetupSuccessful());\r
+                        Log.i("MainActivity", "onFinished() is received "\r
+                                + enrolledevice.isSetupSuccessful());\r
                         if (enrolledevice.isSetupSuccessful()) {\r
                             mHandler.sendEmptyMessage(SUCCESS);\r
                         } else {\r
@@ -119,49 +277,107 @@ public class MainActivity extends Activity {
                         Log.i("MainActivity", "onProgress() is received ");\r
                         mHandler.sendEmptyMessage(STATE_CHANGED);\r
                     }\r
-\r
                 });\r
-\r
-        /* Create EnrolleeDevice Factory instance*/\r
-        mDeviceFactory = EnrolleeDeviceFactory.newInstance(getApplicationContext());\r
-\r
-        /* Create a device using Factory instance*/\r
-        mDevice = mDeviceFactory.newEnrolleeDevice(getOnBoardingWifiConfig(),\r
-                getEnrollerWifiConfig());\r
-\r
-        addListenerForStartAP();\r
-        addListenerForStopAP();\r
     }\r
 \r
-    public WiFiProvConfig getEnrollerWifiConfig() {\r
-        /* Provide the credentials for the Mediator Soft AP to be connected by Enrollee*/\r
-        mWiFiProvConfig = new WiFiProvConfig("hub2.4G", "11112222");\r
-        mEnrolleeSsidText.setText("hub2.4G");\r
-        mmEnrolleePasswordPassText.setText("11112222");\r
-\r
-        return mWiFiProvConfig;\r
+    /**\r
+     * configure OIC platform and call findResource\r
+     */\r
+    private void initOICStack() {\r
+        cfg = new PlatformConfig(\r
+                this,\r
+                ServiceType.IN_PROC,\r
+                ModeType.CLIENT_SERVER,\r
+                "0.0.0.0", // bind to all available interfaces\r
+                0,\r
+                QualityOfService.LOW, filePath + OIC_CLIENT_JSON_DB_FILE);\r
+        try {\r
+            /*\r
+             * Initialize DataBase\r
+             */\r
+\r
+            OcPlatform.Configure(cfg);\r
+\r
+            String sqlDbPath = getFilesDir().getAbsolutePath().replace("files", "databases") +\r
+                    File.separator;\r
+            File file = new File(sqlDbPath);\r
+            //check files directory exists\r
+            if (!(file.isDirectory())) {\r
+                file.mkdirs();\r
+                Log.d(TAG, "Sql db directory created at " + sqlDbPath);\r
+            }\r
+            Log.d(TAG, "Sql db directory exists at " + sqlDbPath);\r
+\r
+            //SQLiteDatabase.openOrCreateDatabase(sqlDbPath+ OIC_SQL_DB_FILE, null);\r
+            OcProvisioning.provisionInit(sqlDbPath + OIC_SQL_DB_FILE);\r
+        } catch (OcException e) {\r
+            logMessage(TAG + "provisionInit error: " + e.getMessage());\r
+            Log.e(TAG, e.getMessage());\r
+        } catch (UnsatisfiedLinkError e) {\r
+\r
+           // Note : Easy setup is built with SECURED = 0, but user still selects Security feature\r
+           // while running the Mediator App it couldn't find "libocprovision.so".\r
+           // As per the programmer guide, security feature should be invoked only if build is done with SECURED = 1.\r
+            Log.e(TAG, " Easy setup is built with secured  = 0, but executed with security feature");\r
+            Toast.makeText(this,"Security is not enabled [Easy setup is built with SECURED = 0]",\r
+                                                                   Toast.LENGTH_LONG).show();\r
+            mEnableSecurity.setChecked(false);\r
+        }\r
+    }\r
+    /**\r
+     * Copy svr db json file from assets folder to app data files dir\r
+     */\r
+    private void copyJsonFromAsset() {\r
+        InputStream inputStream = null;\r
+        OutputStream outputStream = null;\r
+        int length;\r
+        byte[] buffer = new byte[BUFFER_SIZE];\r
+        try {\r
+            inputStream = getAssets().open(OIC_CLIENT_JSON_DB_FILE);\r
+            File file = new File(filePath);\r
+            //check files directory exists\r
+            if (!(file.exists() && file.isDirectory())) {\r
+                file.mkdirs();\r
+            }\r
+            outputStream = new FileOutputStream(filePath + OIC_CLIENT_JSON_DB_FILE);\r
+            while ((length = inputStream.read(buffer)) != -1) {\r
+                outputStream.write(buffer, 0, length);\r
+            }\r
+        } catch (NullPointerException e) {\r
+            logMessage(TAG + "Null pointer exception " + e.getMessage());\r
+            Log.e(TAG, e.getMessage());\r
+        } catch (FileNotFoundException e) {\r
+            logMessage(TAG + "Json svr db file not found " + e.getMessage());\r
+            Log.e(TAG, e.getMessage());\r
+        } catch (IOException e) {\r
+            logMessage(TAG + OIC_CLIENT_JSON_DB_FILE + " file copy failed");\r
+            Log.e(TAG, e.getMessage());\r
+        } finally {\r
+            if (inputStream != null) {\r
+                try {\r
+                    inputStream.close();\r
+                } catch (IOException e) {\r
+                    Log.e(TAG, e.getMessage());\r
+                }\r
+            }\r
+            if (outputStream != null) {\r
+                try {\r
+                    outputStream.close();\r
+                } catch (IOException e) {\r
+                    Log.e(TAG, e.getMessage());\r
+                }\r
+            }\r
+        }\r
     }\r
 \r
-    public WiFiOnBoardingConfig getOnBoardingWifiConfig() {\r
-        mWiFiOnBoardingConfig = new WiFiOnBoardingConfig();\r
-\r
-        /* Provide the target credentials to be provisioned to the Enrollee by Mediator*/\r
-        mWiFiOnBoardingConfig.setSSId("EasySetup123");\r
-        mWiFiOnBoardingConfig.setSharedKey("EasySetup123");\r
-        mWiFiOnBoardingConfig.setAuthAlgo(WifiConfiguration.AuthAlgorithm.OPEN);\r
-        mWiFiOnBoardingConfig.setKms(WifiConfiguration.KeyMgmt.WPA_PSK);\r
-\r
-        // Updating the UI with default credentials\r
-        mSsidText.setText("EasySetup123");\r
-        mPassText.setText("EasySetup123");\r
+    public void logMessage(String text) {\r
 \r
-        return mWiFiOnBoardingConfig;\r
     }\r
 \r
 \r
     public void onDestroy() {\r
         super.onDestroy();\r
-        /*Reset the Easy setup process*/\r
+        /* Reset the Easy setup process */\r
         if (mEasySetupService != null) {\r
             mEasySetupService.finish();\r
         }\r
@@ -169,50 +385,81 @@ public class MainActivity extends Activity {
 \r
     public void addListenerForStartAP() {\r
         mStartButton = (Button) findViewById(R.id.startSetup);\r
-\r
         mStartButton.setOnClickListener(new OnClickListener() {\r
             @Override\r
             public void onClick(View arg0) {\r
                 try {\r
+                    if (mEnrollee.isChecked()) {\r
+                        // Check the wifi connectivity\r
+                        if (!isConnectedTowifi()) {\r
+                            return;\r
+                        }\r
 \r
+                        mEnrollerSsid = mEnrollerSsidText.getText().toString();\r
+                        mEnrollerPassword = mEnrollerPasswordPassText.getText()\r
+                                .toString();\r
+\r
+                        mWiFiProvConfig = new WiFiProvConfig(mEnrollerSsid,\r
+                                mEnrollerPassword);\r
+                        mWiFiProvConfig.setSecured(isSecurityEnabled);\r
+                        mDevice = mDeviceFactory\r
+                                .newEnrolleeDevice(mWiFiProvConfig);\r
+                            Thread thread = new Thread() {\r
+                            @Override\r
+                            public void run() {\r
+                                try {\r
+                                       mEasySetupService.startSetup(mDevice);\r
+                                }catch (Exception e) {\r
+                                    e.printStackTrace();\r
+                                }\r
+                            }\r
+                        };\r
+                        thread.start();\r
+                    } else {\r
+                        mSoftAPSsid = mSoftAPSsidText.getText().toString();\r
+                        mSoftAPPassword = mSoftAPPassText.getText().toString();\r
+                        mEnrollerSsid = mEnrollerSsidText.getText().toString();\r
+                        mEnrollerPassword = mEnrollerPasswordPassText.getText()\r
+                                .toString();\r
+\r
+                        mWiFiProvConfig = new WiFiProvConfig(mEnrollerSsid,\r
+                                mEnrollerPassword);\r
+                        mWiFiProvConfig.setSecured(isSecurityEnabled);\r
+                        mWiFiOnBoardingConfig = new WiFiOnBoardingConfig();\r
+\r
+                        /*\r
+                         * Provide the target credentials to be provisioned to\r
+                         * the Enrollee by Mediator\r
+                         */\r
+                        mWiFiOnBoardingConfig.setSSId("EasySetup123");\r
+                        mWiFiOnBoardingConfig.setSharedKey("EasySetup123");\r
+                        mWiFiOnBoardingConfig\r
+                                .setAuthAlgo(WifiConfiguration.AuthAlgorithm.OPEN);\r
+                        mWiFiOnBoardingConfig\r
+                                .setKms(WifiConfiguration.KeyMgmt.WPA_PSK);\r
+                        mDevice = mDeviceFactory.newEnrolleeDevice(\r
+                                mWiFiProvConfig, mWiFiOnBoardingConfig);\r
+                        mEasySetupService.startSetup(mDevice);\r
+                    }\r
                     mProgressbar.setVisibility(View.VISIBLE);\r
                     mProgressbar.setIndeterminate(true);\r
                     mStartButton.setEnabled(false);\r
                     mResultTextView.setText(R.string.running);\r
 \r
-                    //Reset Device information\r
+                    // Reset Device information\r
                     mDeviceIpTextView.setText(R.string.not_available);\r
                     mDeviceMacTextView.setText(R.string.not_available);\r
-\r
-\r
-                    String ssid = mSsidText.getText().toString();\r
-                    String password = mPassText.getText().toString();\r
-\r
-                    String enrolleeSsid = mEnrolleeSsidText.getText().toString();\r
-                    String enrolleePassword = mmEnrolleePasswordPassText.getText().toString();\r
-\r
-                    mWiFiProvConfig = new WiFiProvConfig(enrolleeSsid, enrolleePassword);\r
-\r
-                    mWiFiOnBoardingConfig.setSSId(ssid);\r
-                    mWiFiOnBoardingConfig.setSharedKey(password);\r
-\r
-\r
-                    mEasySetupService.startSetup(mDevice);\r
-\r
                     mStopButton.setEnabled(true);\r
 \r
-\r
-                } catch (IOException e) {\r
+                } catch (Exception e) {\r
                     e.printStackTrace();\r
                 }\r
-\r
             }\r
         });\r
     }\r
 \r
     public void addListenerForStopAP() {\r
         mStopButton = (Button) findViewById(R.id.stopSetup);\r
-\r
         mStopButton.setOnClickListener(new OnClickListener() {\r
             @Override\r
             public void onClick(View arg0) {\r
@@ -221,11 +468,65 @@ public class MainActivity extends Activity {
                 mResultTextView.setText(R.string.stopped);\r
                 mProgressbar.setIndeterminate(false);\r
                 mProgressbar.setVisibility(View.INVISIBLE);\r
-                mEasySetupService.stopSetup(mDevice);\r
+                try {\r
+                    Thread thread = new Thread() {\r
+                        @Override\r
+                        public void run() {\r
+                            try {\r
+                                mEasySetupService.stopSetup(mDevice);\r
+                            }catch (Exception e) {\r
+                                e.printStackTrace();\r
+                            }\r
+                        }\r
+                    };\r
+                    thread.start();\r
+\r
+                }catch(Exception e){\r
+                    Log.i("Stop setup", "Exception");\r
+                }\r
             }\r
         });\r
     }\r
 \r
+    private boolean isConnectedTowifi() {\r
+\r
+        AlertDialog dialog;\r
+        ConnectivityManager connManager;\r
+        NetworkInfo wifi;\r
+\r
+        // Check the wifi connectivity\r
+        connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);\r
+        wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);\r
+        if (false == wifi.isConnected()) {\r
+\r
+            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);\r
+            dialogBuilder.setTitle("Error");\r
+            dialogBuilder\r
+                    .setMessage("WiFi is not enabled/connected! Please connect the WiFi..");\r
+            dialogBuilder.setCancelable(false);\r
+            dialogBuilder.setPositiveButton("OK",\r
+                    new DialogInterface.OnClickListener() {\r
+                        @Override\r
+                        public void onClick(DialogInterface dialog, int which) {\r
+\r
+                            MainActivity.this.startActivity(new Intent(\r
+                                    WifiManager.ACTION_PICK_WIFI_NETWORK));\r
+\r
+                        }\r
+                    });\r
+            dialogBuilder.setNegativeButton("Cancel",\r
+                    new DialogInterface.OnClickListener() {\r
+                        @Override\r
+                        public void onClick(DialogInterface dialog, int which) {\r
+                        }\r
+                    });\r
+\r
+            dialog = dialogBuilder.create();\r
+            dialog.show();\r
+            return false;\r
+        }\r
+        return true;\r
+    }\r
 \r
     class ThreadHandler extends Handler {\r
         @Override\r
@@ -247,7 +548,8 @@ public class MainActivity extends Activity {
                     mDeviceIpTextView.setText(connection.getIp());\r
                     mDeviceMacTextView.setText(connection.getHardwareAddress());\r
 \r
-                    Toast.makeText(getApplicationContext(), resultMsg, Toast.LENGTH_SHORT).show();\r
+                    Toast.makeText(getApplicationContext(), resultMsg,\r
+                            Toast.LENGTH_SHORT).show();\r
                     break;\r
                 }\r
                 case FAILED: {\r
@@ -258,20 +560,18 @@ public class MainActivity extends Activity {
                     mProgressbar.setVisibility(View.INVISIBLE);\r
                     String resultMsg = "Device configuration failed";\r
                     mResultTextView.setText(R.string.failed);\r
-                    Toast.makeText(getApplicationContext(), resultMsg, Toast.LENGTH_SHORT).show();\r
+                    Toast.makeText(getApplicationContext(), resultMsg,\r
+                            Toast.LENGTH_SHORT).show();\r
                     break;\r
                 }\r
 \r
                 case STATE_CHANGED: {\r
                     String resultMsg = "Device state changed";\r
-                    Toast.makeText(getApplicationContext(), resultMsg, Toast.LENGTH_SHORT).show();\r
+                    Toast.makeText(getApplicationContext(), resultMsg,\r
+                            Toast.LENGTH_SHORT).show();\r
                     break;\r
                 }\r
-\r
             }\r
-\r
-\r
         }\r
     }\r
-\r
 }\r
old mode 100644 (file)
new mode 100755 (executable)
index 4c2e087..5d02597
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_gravity="center"
-        android:layout_marginTop="5dp"
+        android:orientation="horizontal">
+
+        <TextView
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_gravity="center_vertical"
+            android:textStyle="bold"
+            android:textColor="@android:color/holo_red_dark"
+            android:textSize="20dp"
+            android:text="Soft AP   "/>
+
+        <RadioButton
+
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:text="Enrollee  "
+            android:id="@+id/enrollee"
+            android:textStyle="bold"
+            android:layout_gravity="center_horizontal"
+            android:checked="false"
+            />
+
+        <RadioButton
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:text="Mediator"
+            android:id="@+id/mediator"
+            android:textStyle="bold"
+            android:layout_gravity="center_horizontal"
+            android:checked="false"
+            />
+    </LinearLayout>
+
+    <LinearLayout
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_gravity="center"
         android:orientation="horizontal">
 
 
             android:layout_marginRight="30dp"
             android:text="@string/not_started"
             android:textColor="@android:color/background_light"
-            android:textSize="20dp" />
+            android:textSize="10dp" />
 
     </LinearLayout>
 
+    <RadioButton
+        android:layout_width="120dp"
+        android:layout_height="wrap_content"
+        android:text="Enable Security"
+        android:id="@+id/enablesecurity"
+        android:textStyle="bold"
+        android:layout_gravity="center_horizontal"
+        android:checked="false"/>
+
     <LinearLayout
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_centerHorizontal="true"
         android:layout_gravity="center"
-        android:layout_marginTop="10dp"
+        android:layout_marginTop="5dp"
         android:orientation="vertical">
 
         <TextView
         <TextView
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
-            android:layout_marginTop="10dp"
+            android:layout_marginTop="5dp"
             android:text="Enter Enroller's Password" />
 
 
 
 
     <LinearLayout
+        android:id="@+id/softAP"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_centerHorizontal="true"
         android:layout_gravity="center"
-        android:layout_marginTop="10dp"
+        android:layout_marginTop="5dp"
         android:orientation="vertical">
 
         <TextView
             android:id="@+id/textView2"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
-            android:layout_marginTop="10dp"
+            android:layout_marginTop="5dp"
             android:text="Enter SoftAP PWD" />
 
 
 
 
     <TextView
+        android:id="@+id/textViewDeviceinfo"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_gravity="center_horizontal"
         android:textAppearance="?android:attr/textAppearanceMedium" />
 
     <RelativeLayout
+        android:id="@+id/deviceInfo"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_centerHorizontal="true"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_gravity="center_horizontal"
-            android:text="IP Address"
+            android:text="IP Address : "
             android:textAppearance="?android:attr/textAppearanceSmall" />
 
         <TextView
             android:layout_height="wrap_content"
             android:layout_below="@id/ipAddrLable"
             android:layout_gravity="center_horizontal"
-            android:text="MAC Address"
+            android:text="MAC Address : "
             android:textAppearance="?android:attr/textAppearanceSmall" />
 
         <TextView
     <LinearLayout
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
-        android:layout_centerHorizontal="true"
-        android:layout_gravity="center"
-        android:layout_marginTop="20dp"
-        android:orientation="horizontal">
+        android:layout_marginTop="5dp"
+        android:orientation="horizontal"
+        android:weightSum="1">
 
         <Button
             android:id="@+id/startSetup"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
+            android:layout_width="160dp"
+            android:layout_height="50dp"
             android:layout_alignParentTop="true"
-            android:layout_centerHorizontal="true"
             android:layout_margin="10dp"
             android:layout_marginTop="20dp"
             android:elegantTextHeight="true"
 
         <Button
             android:id="@+id/stopSetup"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:layout_below="@+id/startSetup"
-            android:layout_centerHorizontal="true"
+            android:layout_width="160dp"
+            android:layout_height="50dp"
             android:layout_margin="10dp"
             android:elegantTextHeight="true"
             android:enabled="false"
             android:text="@string/stopSetup"
             android:textAllCaps="false"
-            android:textSize="18sp" />
+            android:textSize="18sp"
+            />
 
     </LinearLayout>
 
index 8383bac..c554cb7 100644 (file)
@@ -4,10 +4,10 @@
     <string name="action_settings">Settings</string>
     <string name="textview2">Device Information</string>
     <string name="textview1"> -- empty -- </string>
-    <string name="scan_qr_code">Scan QR Code</string> 
-       <string name="start_easy_setup">Start Easy Setup</string> 
+    <string name="scan_qr_code">Scan QR Code</string>
+       <string name="start_easy_setup">Start Easy Setup</string>
        <string name="start_soft_ap">Start Wi-Fi Soft AP</string>
-       <string name="stop_soft_ap">Stop Soft AP</string>  
+       <string name="stop_soft_ap">Stop Soft AP</string>
     <string name="provision_device">Provision Connected Device</string>
 
     <string name="startSetup">Start Setup</string>
     <string name="test_status">Device configuration</string>
     <string name="running">Running</string>
     <string name="stopped">Stopped</string>
+    <string name="softAP_ssid">EasySetup123</string>
+    <string name="softAP_pwd">EasySetup123</string>
+    <string name="target_default_ssid">DLNA_LISMORE1</string>
+    <string name="target_default_pwd">dlna@010203</string>
     <string name="not_available">Not available</string>
 
 
diff --git a/service/easy-setup/sampleapp/mediator/linux/SConscript b/service/easy-setup/sampleapp/mediator/linux/SConscript
deleted file mode 100644 (file)
index 8522aaa..0000000
+++ /dev/null
@@ -1,51 +0,0 @@
-#******************************************************************
-#
-# 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.
-#
-#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-Import('env')
-
-mediator_env = env.Clone()
-
-target_os = env.get('TARGET_OS')
-
-######################################################################
-# Build flags
-######################################################################
-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/csdk/connectivity/common/inc',
-                       env.get('SRC_DIR') + '/resource/csdk/connectivity/api',
-                       env.get('SRC_DIR') + '/resource/csdk/stack/include',
-                       env.get('SRC_DIR') + '/resource/csdk/logger/include',
-                       env.get('SRC_DIR') + '/resource/csdk/security/include',
-                       env.get('SRC_DIR') + '/extlibs/cjson',
-                       env.get('SRC_DIR') + '/service/easy-setup/sdk/mediator/inc',
-                       env.get('SRC_DIR') + '/service/easy-setup/sdk/common'])
-
-mediator_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'pthread', 'connectivity_abstraction', 'coap', 'ESSDKLibrary'])
-
-mediator = mediator_env.Program('mediator', 'mediator.cpp')
-
-i_mediator = mediator_env.Install(env.get('BUILD_DIR'), mediator)
-
-Alias('mediator', i_mediator)
-env.AppendTarget('mediator')
diff --git a/service/easy-setup/sampleapp/mediator/linux/csdk_sample/SConscript b/service/easy-setup/sampleapp/mediator/linux/csdk_sample/SConscript
new file mode 100644 (file)
index 0000000..4d60705
--- /dev/null
@@ -0,0 +1,64 @@
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+Import('env')
+
+mediator_env = env.Clone()
+
+target_os = env.get('TARGET_OS')
+
+######################################################################
+# Build flags
+######################################################################
+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/csdk/connectivity/common/inc',
+                       env.get('SRC_DIR') + '/resource/csdk/connectivity/api',
+                       env.get('SRC_DIR') + '/resource/csdk/stack/include',
+                       env.get('SRC_DIR') + '/resource/csdk/logger/include',
+                       env.get('SRC_DIR') + '/resource/csdk/security/include',
+                       env.get('SRC_DIR') + '/extlibs/cjson',
+                       env.get('SRC_DIR') + '/service/easy-setup/mediator/csdk/inc',
+                       env.get('SRC_DIR') + '/service/easy-setup/inc'])
+
+mediator_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'pthread', 'connectivity_abstraction', 'coap', 'ESMediatorCSDK'])
+
+mediator = mediator_env.Program('mediator_c', 'mediator.cpp')
+
+i_mediator = mediator_env.Install(env.get('BUILD_DIR'), mediator)
+
+Alias('mediator_c', i_mediator)
+env.AppendTarget('mediator_c')
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/service/easy-setup/sampleapp/mediator/linux/csdk_sample/mediator.cpp b/service/easy-setup/sampleapp/mediator/linux/csdk_sample/mediator.cpp
new file mode 100755 (executable)
index 0000000..31ae79d
--- /dev/null
@@ -0,0 +1,123 @@
+//******************************************************************
+//
+// 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 <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <signal.h>
+#include <unistd.h>
+#include <stdint.h>
+#include <sstream>
+
+#include "provisioningapi.h"
+#include "logger.h"
+
+#define ES_MEDIATOR_TAG "easysetupsample"
+
+int quitFlag = 0;
+
+/* SIGINT handler: set quitFlag to 1 for graceful termination */
+void handleSigInt(int signum) {
+    if (signum == SIGINT) {
+        quitFlag = 1;
+    }
+}
+
+/**
+ * This callback function is used to receive the notifications about the provisioning status
+ * In success or failure, ProvisioningInfo structure holds the current state of provisioning
+ * and also holds the Enrollee information for which provisioning is requested
+ * This function can be used to update the application about the current provisioning status of the Enrollee
+ */
+void ProvisioningStatusCallback(ProvisioningInfo * provInfo) {
+    OIC_LOG_V(INFO, ES_MEDIATOR_TAG, "Enrollee connectivity: %d", provInfo->provDeviceInfo.connType);
+    if (provInfo->provStatus == DEVICE_PROVISIONED) {
+        OIC_LOG_V(INFO, ES_MEDIATOR_TAG, "Successfully provisioned the Enrollee with IP : %s ",
+                  provInfo->provDeviceInfo.addr->addr);
+    }
+    else {
+        OIC_LOG_V(INFO, ES_MEDIATOR_TAG, "Provisioing Failed for the Enrollee with IP : %s",
+                  provInfo->provDeviceInfo.addr->addr);
+    }
+}
+
+static void PrintUsage() {
+    OIC_LOG(INFO, ES_MEDIATOR_TAG, "Usage : occlient -d \"192.168.0.20\"");
+}
+
+int main(int argc, char **argv) {
+    int opt;
+
+    ProvConfig provConfig;
+    //WiFiOnboardingConfig onboardConfig;
+    WiFiOnboadingConnection onboardConn;
+
+    PrintUsage();
+    InitProvProcess();
+
+
+    RegisterCallback(&ProvisioningStatusCallback);
+
+    while ((opt = getopt(argc, argv, "d:s:p:")) != -1) {
+        switch (opt) {
+            case 'd':
+                strncpy(onboardConn.ipAddress, optarg, IPV4_ADDR_SIZE - 1);
+                break;
+            case 's':
+                strncpy(provConfig.provData.WIFI.ssid, optarg, NET_WIFI_SSID_SIZE - 1);
+                break;
+            case 'p':
+                strncpy(provConfig.provData.WIFI.pwd, optarg, NET_WIFI_PWD_SIZE - 1);
+                break;
+            default:
+                PrintUsage();
+                return -1;
+        }
+    }
+
+    provConfig.connType = CT_ADAPTER_IP;
+    OIC_LOG_V(INFO, ES_MEDIATOR_TAG, "IP Address of the Provisioning device is =%s\n",
+              onboardConn.ipAddress);
+    OIC_LOG_V(INFO, ES_MEDIATOR_TAG, "SSID of the Enroller is =%s\n", provConfig.provData.WIFI.ssid);
+    OIC_LOG_V(INFO, ES_MEDIATOR_TAG, "Password of the Enroller is =%s\n", provConfig.provData.WIFI.pwd);
+
+    StartProvisioning(&provConfig, &onboardConn);
+
+    signal(SIGINT, handleSigInt);
+    while (!quitFlag) {
+        OCStackResult result;
+
+        result = OCProcess();
+
+        if (result != OC_STACK_OK)
+        {
+            OIC_LOG(ERROR, "Mediator_CSDK", "OCStack stop error");
+        }
+
+        // To minimize CPU utilization we may wish to do this with sleep
+        sleep(1);
+    }
+
+    ResetProvProcess();
+    OIC_LOG(INFO, ES_MEDIATOR_TAG, "Exiting occlient main loop...");
+
+    return 0;
+}
+
diff --git a/service/easy-setup/sampleapp/mediator/linux/mediator.cpp b/service/easy-setup/sampleapp/mediator/linux/mediator.cpp
deleted file mode 100644 (file)
index 50e7cb7..0000000
+++ /dev/null
@@ -1,109 +0,0 @@
-//******************************************************************
-//
-// 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 <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <signal.h>
-#include <unistd.h>
-#include <stdint.h>
-#include <sstream>
-
-#include "prov_adapter.h"
-#include "logger.h"
-
-#define ES_MEDIATOR_TAG "easysetupsample"
-
-int quitFlag = 0;
-
-/* SIGINT handler: set quitFlag to 1 for graceful termination */
-void handleSigInt(int signum) {
-    if (signum == SIGINT) {
-        quitFlag = 1;
-    }
-}
-
-/**
- * This callback function is used to receive the notifications about the provisioning status
- * In success or failure, ProvisioningInfo structure holds the current state of provisioning
- * and also holds the Enrollee information for which provisioning is requested
- * This function can be used to update the application about the current provisioning status of the Enrollee
- */
-void ProvisioningStatusCallback(ProvisioningInfo * provInfo) {
-    OIC_LOG_V(INFO, ES_MEDIATOR_TAG, "Enrollee connectivity: %d", provInfo->provDeviceInfo.connType);
-    if (provInfo->provStatus == DEVICE_PROVISIONED) {
-        OIC_LOG_V(INFO, ES_MEDIATOR_TAG, "Successfully provisioned the Enrollee with IP : %s ",
-                  provInfo->provDeviceInfo.addr->addr);
-    }
-    else {
-        OIC_LOG_V(INFO, ES_MEDIATOR_TAG, "Provisioing Failed for the Enrollee with IP : %s",
-                  provInfo->provDeviceInfo.addr->addr);
-    }
-}
-
-static void PrintUsage() {
-    OIC_LOG(INFO, ES_MEDIATOR_TAG, "Usage : occlient -d \"192.168.0.20\"");
-}
-
-int main(int argc, char **argv) {
-    int opt;
-    EnrolleeNWProvInfo_t netInfo;
-    PrintUsage();
-    InitProvProcess();
-
-
-    RegisterCallback(ProvisioningStatusCallback);
-
-    while ((opt = getopt(argc, argv, "d:s:p:")) != -1) {
-        switch (opt) {
-            case 'd':
-                strncpy(netInfo.netAddressInfo.WIFI.ipAddress, optarg, IPV4_ADDR_SIZE - 1);
-                break;
-            case 's':
-                strncpy(netInfo.netAddressInfo.WIFI.ssid, optarg, NET_WIFI_SSID_SIZE - 1);
-                break;
-            case 'p':
-                strncpy(netInfo.netAddressInfo.WIFI.pwd, optarg, NET_WIFI_PWD_SIZE - 1);
-                break;
-            default:
-                PrintUsage();
-                return -1;
-        }
-    }
-
-    netInfo.connType = CT_ADAPTER_IP;
-    OIC_LOG_V(INFO, ES_MEDIATOR_TAG, "IP Address of the Provisioning device is =%s\n",
-              netInfo.netAddressInfo.WIFI.ipAddress);
-    OIC_LOG_V(INFO, ES_MEDIATOR_TAG, "SSID of the Enroller is =%s\n", netInfo.netAddressInfo.WIFI.ssid);
-    OIC_LOG_V(INFO, ES_MEDIATOR_TAG, "Password of the Enroller is =%s\n", netInfo.netAddressInfo.WIFI.pwd);
-
-    StartProvisioning(&netInfo);
-
-    signal(SIGINT, handleSigInt);
-    while (!quitFlag) {
-        sleep(1);
-    }
-
-    ResetProvProcess();
-    OIC_LOG(INFO, ES_MEDIATOR_TAG, "Exiting occlient main loop...");
-
-    return 0;
-}
-
diff --git a/service/easy-setup/sampleapp/mediator/linux/richsdk_sample/SConscript b/service/easy-setup/sampleapp/mediator/linux/richsdk_sample/SConscript
new file mode 100644 (file)
index 0000000..ef24ed2
--- /dev/null
@@ -0,0 +1,70 @@
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+Import('env')
+
+mediator_env = env.Clone()
+
+target_os = env.get('TARGET_OS')
+
+######################################################################
+# Build flags
+######################################################################
+mediator_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+
+if env.get('RELEASE'):
+    mediator_env.AppendUnique(CCFLAGS = ['-Os'])
+    mediator_env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+else:
+    mediator_env.AppendUnique(CCFLAGS = ['-g'])
+
+if env.get('LOGGING'):
+    env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+env.AppendUnique(CPPDEFINES = ['CPP_MEDIATOR'])
+
+if target_os not in ['windows', 'winrt']:
+    mediator_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x'])
+       
+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/csdk/stack/include',
+                       env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include',
+                       env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include/internal',
+                       env.get('SRC_DIR') + '/resource/csdk/logger/include',
+                       env.get('SRC_DIR') + '/resource/csdk/security/include',
+                       env.get('SRC_DIR') + '/resource/csdk/connectivity/api',
+                       env.get('SRC_DIR') + '/extlibs/cjson',
+                       env.get('SRC_DIR') + '/service/easy-setup/mediator/richsdk/inc',
+                       env.get('SRC_DIR') + '/service/easy-setup/mediator/richsdk/src',
+                       env.get('SRC_DIR') + '/service/easy-setup/inc'])
+
+mediator_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'pthread', 'connectivity_abstraction', 'coap', 'ESMediatorRich'])
+if env.get('SECURED') == '1':
+       mediator_env.PrependUnique(LIBS = ['ocpmapi', 'ocprovision'])
+
+mediator = mediator_env.Program('mediator_rich', 'mediator_cpp.cpp')
+
+i_mediator = mediator_env.Install(env.get('BUILD_DIR'), mediator)
+
+Alias('mediator_rich', i_mediator)
+env.AppendTarget('mediator_rich')
diff --git a/service/easy-setup/sampleapp/mediator/linux/richsdk_sample/mediator_cpp.cpp b/service/easy-setup/sampleapp/mediator/linux/richsdk_sample/mediator_cpp.cpp
new file mode 100755 (executable)
index 0000000..ec960bc
--- /dev/null
@@ -0,0 +1,236 @@
+//******************************************************************
+//
+// 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 <iostream>
+#include<stdio.h>
+
+#include "oic_string.h"
+#include "EasySetup.h"
+#include "OCPlatform.h"
+#include "logger.h"
+#include "OCProvisioningManager.h"
+
+
+#define ES_SAMPLE_APP_TAG "ES_SAMPLE_APP_TAG"
+#define DECLARE_MENU(FUNC, ...) { #FUNC, FUNC }
+
+#define JSON_DB_PATH "./oic_svr_db_client.dat"
+
+using namespace OC;
+using namespace OIC::Service;
+
+static EasySetup *easySetupIntance = nullptr;
+static ProvConfig netInfo;
+static WiFiOnboadingConnection onboardingConn;
+static RemoteEnrollee::shared_ptr remoteEnrollee = nullptr;
+
+static std::string ipaddress, ssid, pwd;
+char security;
+
+struct CloseApp
+{
+};
+
+typedef void (*Runner)();
+
+Runner g_currentRun;
+
+int processUserInput(int min, int max)
+{
+    assert(min <= max);
+
+    int input;
+
+    std::cin >> input;
+
+    if (!std::cin.fail())
+    {
+        if(input == max + 1) throw CloseApp();
+        if(min <= input && input <= max) return input;
+    }
+
+    std::cin.clear();
+    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
+
+    throw std::runtime_error("Invalid Input, please try again");
+}
+
+void easySetupStatusCallback (std::shared_ptr< EasySetupStatus > easySetupStatus)
+{
+    OIC_LOG_V(DEBUG, ES_SAMPLE_APP_TAG, "easySetupStatusCallback status is Status = %d",
+            easySetupStatus->getEasySetupState());
+
+}
+
+void startProvisioning()
+{
+    try
+    {
+        remoteEnrollee->startProvisioning();
+    }
+    catch(OCException &exception)
+    {
+        std::cout << "Exception : " << exception.reason();
+    }
+}
+
+void initEasySetup()
+{
+
+    easySetupIntance = EasySetup::getInstance();
+
+    cout<<"\n Enter the IP address : ";
+    cin>>ipaddress;
+    cout<<"\n Enter the Target Network SSID : ";
+    cin>>ssid;
+    cout<<"\n Enter the Target Network Password : ";
+    cin>>pwd;
+    cout<<"\n Enable Security: [Y/N] ";
+    cin>>security;
+
+    if ( ipaddress.size() == 0 || ssid.size() == 0  || pwd.size()==0 )
+    {
+         cout<<"\n Invalid information try again !!!";
+    }
+    else
+     {
+           cout <<"\n Entered details are :  \n";
+           cout<<"\n IP address : "<<ipaddress;
+           cout<<"\n Target Network SSID : "<<ssid;
+           cout<<"\n Target Network Password : "<<pwd;
+
+          if (security == 'Y' || security == 'y' )
+          {
+                  onboardingConn.isSecured = true;
+                  cout<<"\n Security is Enabled\n\n\n";
+           }
+           else
+           {
+                 onboardingConn.isSecured = false;
+                 cout<<"\n Security is not Enabled\n\n\n";
+           }
+
+          netInfo.connType = CT_ADAPTER_IP;
+
+         OICStrcpy(netInfo.provData.WIFI.ssid, NET_WIFI_SSID_SIZE - 1, ssid.c_str());
+         OICStrcpy(netInfo.provData.WIFI.pwd, NET_WIFI_PWD_SIZE - 1, pwd.c_str());
+
+         OICStrcpy(onboardingConn.ipAddress, IPV4_ADDR_SIZE - 1, ipaddress.c_str());
+
+         try
+         {
+             remoteEnrollee = easySetupIntance->createEnrolleeDevice(netInfo,onboardingConn);
+         }
+         catch (OCException &e)
+         {
+             std::cout << "Exception during createEnrolleeDevice call" << e.reason();
+             return;
+         }
+
+         remoteEnrollee->registerEasySetupStatusHandler(&easySetupStatusCallback);
+    }
+
+}
+void runEasySetupMenu()
+{
+    constexpr int EASY_SETUP_INIT = 1;
+    constexpr int START_PROVISIONING = 2;
+    constexpr int STOP_PROVISIONING = 3;
+    constexpr int STOP_EASY_SETUP = 4;
+
+    std::cout << "========================================================\n";
+    std::cout << EASY_SETUP_INIT << ". Easy Setup Init                    \n";
+    std::cout << START_PROVISIONING << ". Start Provisioning              \n";
+    std::cout << STOP_PROVISIONING << ". Stop Provisioning                \n";
+    std::cout << STOP_EASY_SETUP << ". Stop Easy Setup                    \n";
+    std::cout << STOP_EASY_SETUP + 1 << ". Quit                           \n";
+    std::cout << "========================================================\n";
+
+    int selection = processUserInput(EASY_SETUP_INIT, STOP_EASY_SETUP);
+
+    switch (selection)
+    {
+        case EASY_SETUP_INIT:
+            initEasySetup();
+            break;
+        case START_PROVISIONING:
+            startProvisioning();
+            break;
+        case STOP_PROVISIONING:
+            //stopProvisioning();
+            break;
+        case STOP_EASY_SETUP:
+            //stopEasySetup();
+            break;
+        default:
+            break;
+    };
+}
+
+static FILE* client_open(const char *UNUSED_PARAM, const char *mode)
+{
+    (void)UNUSED_PARAM;
+    return fopen(JSON_DB_PATH, mode);
+}
+
+int main()
+{
+    OCPersistentStorage ps {client_open, fread, fwrite, fclose, unlink };
+
+    PlatformConfig config
+    {
+        OC::ServiceType::InProc, ModeType::Both, "0.0.0.0", 0, OC::QualityOfService::LowQos, &ps
+    };
+
+    OCPlatform::Configure(config);
+
+#ifdef __WITH_DTLS__
+    //Initializing the provisioning client stack using the db path provided by the application.
+    OCStackResult result = OCSecure::provisionInit("");
+
+    if (result != OC_STACK_OK)
+    {
+        return -1;
+    }
+#endif
+
+    g_currentRun = runEasySetupMenu;
+
+    while (true)
+    {
+        try
+        {
+            g_currentRun();
+        }
+        catch (const std::exception& e)
+        {
+            std::cout << "Exception caught in main " << e.what() << std::endl;
+        }
+        catch (const CloseApp&)
+        {
+            break;
+        }
+    }
+
+    std::cout << "Stopping the client" << std::endl;
+
+    return 0;
+}
+
diff --git a/service/easy-setup/sdk/common/escommon.h b/service/easy-setup/sdk/common/escommon.h
deleted file mode 100644 (file)
index 3375490..0000000
+++ /dev/null
@@ -1,191 +0,0 @@
-//******************************************************************
-//
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#ifndef ES_COMMON_H_
-#define ES_COMMON_H_
-
-#include "ocstack.h"
-#include "octypes.h"
-
-// Defines
-#define OIC_STRING_MAX_VALUE 100
-#define IPV4_ADDR_SIZE 16
-#define IP_PORT 55555
-#define NET_WIFI_SSID_SIZE 16
-#define NET_WIFI_PWD_SIZE 16
-
-/**
- * @brief Mac address length for BT port
- */
-#define NET_MACADDR_SIZE 18
-
-/**
- * Attributes used to form a proper easysetup conforming JSON message.
- */
-#define OC_RSRVD_ES_PS                     "ps"
-#define OC_RSRVD_ES_TNN                    "tnn"
-#define OC_RSRVD_ES_CD                     "cd"
-#define OC_RSRVD_ES_TR                     "tr"
-#define OC_RSRVD_ES_TNT                    "tnt"
-#define OC_RSRVD_ES_ANT                    "ant"
-#define OC_RSRVD_ES_URI_PROV               "/oic/prov"
-#define OC_RSRVD_ES_URI_NET                "/oic/net"
-
-
-
-typedef enum
-{
-
-    ES_ERROR = -1,
-    ES_OK = 0,
-    ES_NETWORKFOUND = 1,
-    ES_NETWORKCONNECTED,
-    ES_NETWORKNOTCONNECTED,
-    ES_RESOURCECREATED = 11,
-    ES_RECVREQOFPROVRES = 21,
-    ES_RECVREQOFNETRES,
-    ES_RECVUPDATEOFPROVRES,
-    ES_RECVTRIGGEROFPROVRES,
-} ESResult;
-
-typedef enum
-{
-    /**
-        * Default state of the device
-        */
-    ES_INIT_STATE,
-
-    /**
-        * Device will move to this state once the on boarding begins
-        */
-    ES_ON_BOARDING_STATE,
-
-    /**
-        * Device will move to this state after successful on-boarding of the device
-        */
-    ES_ON_BOARDED_STATE,
-
-    /**
-        * Device will move to this state once the on boarding is done
-        */
-    ES_PROVISIONING_STATE,
-
-    /**
-        * Easy setup process is successful.
-        */
-    ES_PROVISIONED_STATE,
-
-    /**
-        * This state is arbitrary one, any time device can come into this state
-        * Device will move to this state if the ownership transfer initiated  by the Application
-        */
-    ES_OWNERSHIP_TRANSFERRING_STATE,
-
-    /**
-        * This state is arbitrary one, any time device can come into this state
-        * Device will move to this state if the ownership transfer is completed
-        */
-    ES_OWNERSHIP_TRANSFERRED_STATE,
-
-    /**
-        * This state is arbitrary one, any time device can come into this state
-        * Device will move to this state once the Application factory reset the device
-        */
-    ES_FACTORY_RESET_STATE,
-}EnrolleeState;
-
-
-
-/**
- * Provisioning Device Status
- */
-typedef struct {
-    /// Address of remote server
-    OCDevAddr * addr;
-    /// Indicates adaptor type on which the response was received
-    OCConnectivityType connType;
-} ProvDeviceInfo;
-
-/**
- * Provosioning Status
- */
-typedef enum {
-    DEVICE_PROVISIONED = 0, DEVICE_NOT_PROVISIONED
-} ProvStatus;
-
-/**
- * Response from queries to remote servers.
- */
-typedef struct {
-    // Provisioning Status
-    ProvStatus provStatus;
-    // Provisioning Device Info
-    ProvDeviceInfo provDeviceInfo;
-} ProvisioningInfo;
-
-/**
- * @brief  Network information of the Enroller
- */
-typedef union
-{
-    /**
-     * @brief BT Mac Information
-     */
-    struct
-    {
-        char btMacAddress[NET_MACADDR_SIZE];   /**< BT mac address **/
-    } BT;
-
-    /**
-     * @brief LE MAC Information
-     */
-    struct
-    {
-        char leMacAddress[NET_MACADDR_SIZE];   /**< BLE mac address **/
-    } LE;
-
-    /**
-     * @brief IP Information
-     */
-    struct
-    {
-        char ipAddress[IPV4_ADDR_SIZE]; /**< IP Address of the Enroller**/
-        char ssid[NET_WIFI_SSID_SIZE]; /**< ssid of the Enroller**/
-        char pwd[NET_WIFI_PWD_SIZE]; /**< pwd of the Enroller**/
-    } WIFI;
-} EnrolleeInfo_t;
-
-
-/**
- * @brief Network Information
- */
-typedef struct
-{
-    EnrolleeInfo_t netAddressInfo;          /**< Enroller Network Info**/
-    OCConnectivityType connType;            /**< Connectivity Type**/
-    bool isSecured;                         /**< Secure connection**/
-} EnrolleeNWProvInfo_t;
-
-/**
- * Client applications implement this callback to consume responses received from Servers.
- */
-typedef void (*OCProvisioningStatusCB)(ProvisioningInfo *provInfo);
-
-#endif
diff --git a/service/easy-setup/sdk/enrollee/api/easysetup.h b/service/easy-setup/sdk/enrollee/api/easysetup.h
deleted file mode 100644 (file)
index e3b0adc..0000000
+++ /dev/null
@@ -1,79 +0,0 @@
-//******************************************************************
-//
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-/**
- * @file
- *
- * This file contains SDK APIs for device operating in Enrollee Mode of EasySetup
- */
-
-#ifndef EASYSETUP_ENROLLEE_H__
-#define EASYSETUP_ENROLLEE_H__
-
-#include "Arduino.h"
-#include "escommon.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif // __cplusplus
-
-/*
- * Callback function for updating the Enrollee OnBoarding and Provisioning status result to the application
- *
- * @param esResult ESResult provides the current state of the Enrollee Device
- */
-typedef void (*EventCallback)(ESResult esResult, EnrolleeState enrolleeState);
-
-/**
- * This function Initializes the EasySetup. This API must be called prior to invoking any other API
- *
- * @param networkType       NetworkType on which OnBoarding has to be performed.
- * @param ssid                   SSID of the target SoftAP network to which the Enrollee is connecting.
- * @param passwd              Password of the target SoftAP network to which the Enrollee is connecting
- * @param eventCallback     EventCallback for for updating the Enrollee OnBoarding and Provisioning status
- *                                    result to the application
- * @return ::ES_OK on success, some other value upon failure.
- */
-ESResult InitEasySetup(OCConnectivityType networkType, const char *ssid,
-                          const char *passwd,
-                          EventCallback eventCallback);
-
-/**
- * This function performs initialization of Provisioning and Network resources needed for EasySetup process.
- *
- * @return ::ES_OK on success, some other value upon failure.
- */
-ESResult InitProvisioning();
-
-/**
- * This function performs termination of Provisioning and Network resources.
- * Also terminates the IoTivity core stack.
- *
- * @return ::ES_OK on success, some other value upon failure.
- */
-ESResult TerminateEasySetup();
-
-#ifdef __cplusplus
-}
-#endif // __cplusplus
-
-
-#endif /* EASYSETUP_ENROLLEE_H__ */
-
diff --git a/service/easy-setup/sdk/enrollee/arduino/wifi/networkHandler.cpp b/service/easy-setup/sdk/enrollee/arduino/wifi/networkHandler.cpp
deleted file mode 100644 (file)
index d4b3327..0000000
+++ /dev/null
@@ -1,247 +0,0 @@
-//******************************************************************
-//
-// 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 "networkHandler.h"
-
-// Arduino WiFi Shield includes
-#include <SPI.h>
-#include <WiFi.h>
-#include <WiFiUdp.h>
-
-#include <string.h>
-
-#include "logger.h"
-
-/**
- * @var ES_NH_TAG
- * @brief Logging tag for module name.
- */
-#define ES_NH_TAG "ES_NH"
-
-//-----------------------------------------------------------------------------
-// Defines
-//-----------------------------------------------------------------------------
-/**
- *  ES_MAX_NETWORK_RETRY sets the default number of retry count for network connection.
- */
-#define ES_MAX_NETWORK_RETRY (5)
-
-//-----------------------------------------------------------------------------
-// Private variables
-//-----------------------------------------------------------------------------
-static IPAddress enrolleeIP;
-
-/**
- * @var g_retryCounter
- * @brief Retry counter for cancelling network retry. Currently network retry is limited to 5 attempts
- */
-static uint16_t g_retryCounter = 0;
-
-
-
-//-----------------------------------------------------------------------------
-// Private internal function prototypes
-//-----------------------------------------------------------------------------
-int findNetwork(const char *ssid);
-int ConnectToNetwork(const char *ssid, const char *pass);
-void printEncryptionType(int thisType);
-
-// Arduino WiFi Shield
-// Note : Arduino WiFi Shield currently does NOT support multicast and therefore
-// this server will NOT be listening on 224.0.1.187 multicast address.
-static const char ARDUINO_WIFI_SHIELD_UDP_FW_VER[] = "1.1.0";
-
-ESResult ConnectToWiFiNetwork(const char *ssid, const char *pass, NetworkEventCallback cb)
-{
-    char *fwVersion;
-    int status = WL_IDLE_STATUS;
-    int res;
-
-    // check for the presence of the shield:
-    if (WiFi.status() == WL_NO_SHIELD)
-    {
-        OC_LOG(ERROR, ES_NH_TAG, "WiFi shield not present");
-        return ES_ERROR;
-    }
-
-    // Verify that WiFi Shield is running the firmware with all UDP fixes
-    fwVersion = WiFi.firmwareVersion();
-    OC_LOG_V(INFO, ES_NH_TAG, "WiFi Shield Firmware version %s", fwVersion);
-    if (strncmp(fwVersion, ARDUINO_WIFI_SHIELD_UDP_FW_VER, sizeof(ARDUINO_WIFI_SHIELD_UDP_FW_VER))
-            != 0)
-    {
-        OC_LOG(DEBUG, ES_NH_TAG, "!!!!! Upgrade WiFi Shield Firmware version !!!!!!");
-        return ES_ERROR;
-    }
-
-    //Retry counter is reset everytime the ConnectToWiFiNetwork is invoked
-    g_retryCounter = 0;
-
-    OC_LOG_V(INFO, ES_NH_TAG, "Finding SSID: %s", ssid);
-
-    while ((findNetwork(ssid) == 0) && g_retryCounter < ES_MAX_NETWORK_RETRY) // found
-    {
-        delay(1000);
-        g_retryCounter++;
-    }
-
-    if(g_retryCounter == ES_MAX_NETWORK_RETRY){
-        OC_LOG_V(ERROR, ES_NH_TAG, "Connection to network failed after %d attempts",
-                                                                    g_retryCounter);
-        return ES_ERROR;
-    }
-
-    if (cb != NULL)
-    {
-        cb(ES_OK);
-    }
-
-    if (WiFi.status() == WL_CONNECTED)
-        WiFi.disconnect();
-
-    //Retry counter is reset everytime the ConnectToWiFiNetwork is invoked
-    g_retryCounter = 0;
-
-    res = ConnectToNetwork(ssid, pass);
-
-    if (res == 0)
-    {
-        return ES_NETWORKCONNECTED;
-    }
-    else
-    {
-        return ES_NETWORKNOTCONNECTED;
-    }
-}
-
-int findNetwork(const char *ssid)
-{
-    int res = 0;
-    // scan for nearby networks:
-    Serial.println("** Scan Networks **");
-    int numSsid = WiFi.scanNetworks();
-    if (numSsid == -1)
-    {
-        Serial.println("Couldn't get a wifi connection");
-
-        return res;
-    }
-
-    // print the list of networks seen:
-    Serial.print("number of available networks:");
-    Serial.println(numSsid);
-
-    // print the network number and name for each network found:
-    for (int thisNet = 0; thisNet < numSsid; thisNet++)
-    {
-        Serial.print(thisNet);
-        Serial.print(") ");
-        Serial.print(WiFi.SSID(thisNet));
-        Serial.print("\tEncryption: ");
-        printEncryptionType(WiFi.encryptionType(thisNet));
-
-        if (strcmp(WiFi.SSID(thisNet), ssid) == 0)
-        {
-            res = 1;
-        }
-    }
-
-    return res;
-}
-
-int ConnectToNetwork(const char *ssid, const char *pass)
-{
-    int status = WL_IDLE_STATUS;
-
-    // attempt to connect to Wifi network:
-    while (status != WL_CONNECTED && g_retryCounter < ES_MAX_NETWORK_RETRY)
-    {
-        OC_LOG_V(INFO, ES_NH_TAG, "Attempting to connect to SSID: %s", ssid);
-
-        status = WiFi.begin((char *) ssid, (char *) pass);
-
-        // wait 10 seconds for connection:
-        delay(10000);
-
-        g_retryCounter++;
-    }
-
-    if(g_retryCounter == ES_MAX_NETWORK_RETRY){
-        OC_LOG_V(ERROR, ES_NH_TAG, "Connection to network failed after %d attempts",
-                                                                    g_retryCounter);
-        return ES_ERROR;
-    }
-
-    OC_LOG(DEBUG, ES_NH_TAG, "Connected to wifi");
-
-    enrolleeIP = WiFi.localIP();
-    OC_LOG_V(INFO, ES_NH_TAG, "IP Address:  %d.%d.%d.%d", enrolleeIP[0], enrolleeIP[1],
-                                                          enrolleeIP[2], enrolleeIP[3]);
-
-    char buf[50];
-    sprintf(buf, "IP Address:  %d.%d.%d.%d", enrolleeIP[0], enrolleeIP[1],
-                                             enrolleeIP[2], enrolleeIP[3]);
-    Serial.println(buf);
-
-    return 0;
-}
-
-ESResult getCurrentNetworkInfo(OCConnectivityType targetType, NetworkInfo *info)
-{
-    if (targetType == CT_ADAPTER_IP && WiFi.status() == WL_CONNECTED)
-    {
-        info->type = CT_ADAPTER_IP;
-        info->ipaddr = WiFi.localIP();
-        if(strlen(WiFi.SSID())<=MAXSSIDLEN)
-        {
-            strcpy(info->ssid, WiFi.SSID());
-            return ES_OK;
-        }
-        else
-        {
-            return ES_ERROR;
-        }
-    }
-
-    return ES_ERROR;
-}
-
-void printEncryptionType(int thisType)
-{
-    // read the encryption type and print out the name:
-    switch (thisType)
-    {
-        case ENC_TYPE_WEP:
-            Serial.println("WEP");
-            break;
-        case ENC_TYPE_TKIP:
-            Serial.println("WPA");
-            break;
-        case ENC_TYPE_CCMP:
-            Serial.println("WPA2");
-            break;
-        case ENC_TYPE_NONE:
-            Serial.println("None");
-            break;
-        case ENC_TYPE_AUTO:
-            Serial.println("Auto");
-            break;
-    }
-}
diff --git a/service/easy-setup/sdk/enrollee/arduino/wifi/networkHandler.h b/service/easy-setup/sdk/enrollee/arduino/wifi/networkHandler.h
deleted file mode 100644 (file)
index df67b8f..0000000
+++ /dev/null
@@ -1,67 +0,0 @@
-//******************************************************************
-//
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-/**
- * @file
- *
- * This file contains IP network handling functionality for Enrollee device
- */
-
-#ifndef ES_NETWORK_HANDLER_H_
-#define ES_NETWORK_HANDLER_H_
-
-// Do not remove the include below
-#include "Arduino.h"
-
-// Arduino WiFi Shield includes
-#include <SPI.h>
-#include <WiFi.h>
-#include <WiFiUdp.h>
-
-#include <string.h>
-#include "logger.h"
-#include "escommon.h"
-
-#define MAXSSIDLEN 33
-#define MAXNETCREDLEN 20
-#define MAXNUMTYPE 5
-#define MAXADDRLEN 15
-
-/*
- * Callback function for updating the Network status to the subscribers
- *
- * @param esResult ESResult provides the current state of the network connection status
- */
-typedef void (*NetworkEventCallback)(ESResult esResult);
-
-typedef struct
-{
-    OCConnectivityType type;
-    // for WiFI
-    IPAddress ipaddr;
-    char ssid[MAXSSIDLEN];
-    // for BT, BLE
-    byte mac[6];
-} NetworkInfo;
-
-ESResult ConnectToWiFiNetwork(const char *ssid, const char *pass, NetworkEventCallback);
-ESResult getCurrentNetworkInfo(OCConnectivityType targetType, NetworkInfo *info);
-
-#endif
diff --git a/service/easy-setup/sdk/enrollee/inc/resourceHandler.h b/service/easy-setup/sdk/enrollee/inc/resourceHandler.h
deleted file mode 100644 (file)
index 6d24877..0000000
+++ /dev/null
@@ -1,66 +0,0 @@
-//******************************************************************
-//
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-// Do not remove the include below
-#include "Arduino.h"
-
-#include <string.h>
-#include "logger.h"
-#include "ocstack.h"
-#include "escommon.h"
-#include "networkHandler.h"
-#include "octypes.h"
-
-#ifndef ES_RESOURCE_HANDLER_H_
-#define ES_RESOURCE_HANDLER_H_
-
-typedef void (*ResourceEventCallback)(ESResult);
-
-/* Structure to represent a Light resource */
-typedef struct PROVRESOURCE
-{
-    OCResourceHandle handle;
-    int ps; // provisiong status, 1 : need to provisioning, 2 : Connected to Internet
-    int tnt; // target network type, 1: WLAN, 2: BT, 3: BLE, 4: Zigbee, ...
-    char tnn[MAXSSIDLEN]; // target network name, i.e. SSID for WLAN, MAC address for BT
-    char cd[MAXNETCREDLEN]; // credential information
-} ProvResource;
-
-/* Structure to represent a Light resource */
-typedef struct NETRESOURCE
-{
-    OCResourceHandle handle;
-    int cnt; // current network type, 1: WLAN, 2: BT, 3: BLE, 4: Zigbee, ...
-    int ant[MAXNUMTYPE]; // available network type, 1: WLAN, 2: BT, 3: BLE, 4: Zigbee, ...
-    char ipaddr[MAXADDRLEN]; // ip address
-    char cnn[MAXSSIDLEN]; // current network name
-} NetResource;
-
-OCStackResult CreateProvisioningResource();
-
-//created only for in case of wifi
-#ifdef ESWIFI
-OCStackResult CreateNetworkResource();
-#endif
-
-void GetTargetNetworkInfoFromProvResource(char *, char *);
-void RegisterResourceEventCallBack(ResourceEventCallback);
-
-#endif
diff --git a/service/easy-setup/sdk/enrollee/src/easysetup.cpp b/service/easy-setup/sdk/enrollee/src/easysetup.cpp
deleted file mode 100644 (file)
index 9855710..0000000
+++ /dev/null
@@ -1,228 +0,0 @@
-//******************************************************************
-//
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-/**
- * @file
- *
- * This file contains the implementation for EasySetup Enrollee device
- */
-
-#include "easysetup.h"
-
-#include "logger.h"
-#include "resourceHandler.h"
-
-/**
- * @var ES_ENROLLEE_TAG
- * @brief Logging tag for module name.
- */
-#define ES_ENROLLEE_TAG "ES"
-
-//-----------------------------------------------------------------------------
-// Private variables
-//-----------------------------------------------------------------------------
-
-/**
- * @var targetSsid
- * @brief Target SSID of the Soft Access point to which the device has to connect
- */
-static char *targetSsid;
-
-/**
- * @var targetPass
- * @brief Password of the target access point to which the device has to connect
- */
-static char *targetPass;
-
-/**
- * @var g_cbForEnrolleeStatus
- * @brief Fucntion pointer holding the callback for intimation of EasySetup Enrollee status callback
- */
-static EventCallback g_cbForEnrolleeStatus = NULL;
-
-//-----------------------------------------------------------------------------
-// Private internal function prototypes
-//-----------------------------------------------------------------------------
-
-void EventCallbackInOnboarding(ESResult esResult);
-void EventCallbackInProvisioning(ESResult esResult);
-void EventCallbackAfterProvisioning(ESResult esResult);
-
-void EventCallbackInOnboarding(ESResult esResult)
-{
-    if (g_cbForEnrolleeStatus != NULL){
-        OC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "Calling the application with esResult = %d", esResult);
-        if(esResult == ES_OK){
-            OC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "Calling the application with enrolleestate = %d",
-                                                ES_ON_BOARDED_STATE);
-            g_cbForEnrolleeStatus(esResult, ES_ON_BOARDED_STATE);
-        }
-        else{
-            OC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "Calling the application with enrolleestate = %d",
-                                                ES_INIT_STATE);
-            g_cbForEnrolleeStatus(esResult, ES_INIT_STATE);
-        }
-    }
-    else{
-        OC_LOG(ERROR, ES_ENROLLEE_TAG, "g_cbForEnrolleeStatus is NULL");
-    }
-}
-
-void EventCallbackInProvisioning(ESResult esResult)
-{
-    ESResult res = ES_OK;
-
-    if (esResult == ES_RECVTRIGGEROFPROVRES)
-    {
-        targetSsid = (char *) malloc(MAXSSIDLEN);
-        targetPass = (char *) malloc(MAXNETCREDLEN);
-
-        if(TerminateEasySetup() != OC_STACK_OK)
-        {
-            OC_LOG(ERROR, ES_ENROLLEE_TAG, "Terminating stack failed");
-            return;
-        }
-
-        GetTargetNetworkInfoFromProvResource(targetSsid, targetPass);
-
-        res = ConnectToWiFiNetwork(targetSsid, targetPass, EventCallbackAfterProvisioning);
-
-        if (g_cbForEnrolleeStatus != NULL)
-        {
-            if(res == ES_NETWORKCONNECTED){
-                OC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "Calling the application with enrolleestate = %d",
-                                                    ES_PROVISIONED_STATE);
-                g_cbForEnrolleeStatus(ES_OK, ES_PROVISIONED_STATE);
-            }
-            else{
-                OC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "Calling the application with enrolleestate = %d",
-                                                    ES_PROVISIONING_STATE);
-                g_cbForEnrolleeStatus(ES_OK, ES_PROVISIONING_STATE);
-            }
-
-        }
-    }
-}
-
-void EventCallbackAfterProvisioning(ESResult esResult)
-{
-    if (g_cbForEnrolleeStatus != NULL){
-        if(esResult == ES_OK){
-            OC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "Calling the application with enrolleestate = %d",
-                                                   ES_PROVISIONED_STATE);
-            g_cbForEnrolleeStatus(esResult, ES_PROVISIONED_STATE);
-        }
-        else{
-            OC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "Calling the application with enrolleestate = %d",
-                                                   ES_PROVISIONING_STATE);
-            g_cbForEnrolleeStatus(esResult, ES_PROVISIONING_STATE);
-        }
-    }
-    else{
-        OC_LOG(ERROR, ES_ENROLLEE_TAG, "g_cbForEnrolleeStatus is NULL");
-    }
-}
-
-ESResult FindNetworkForOnboarding(OCConnectivityType networkType,
-                                           const char *ssid,
-                                           const char *passwd,
-                                           EventCallback cb)
-{
-    if (!ssid || !passwd)
-    {
-        return ES_ERROR;
-    }
-
-    if (networkType == CT_ADAPTER_IP)
-    {
-        if (g_cbForEnrolleeStatus == NULL)
-        {
-            g_cbForEnrolleeStatus = cb;
-        }
-
-        if(ConnectToWiFiNetwork(ssid, passwd, EventCallbackInOnboarding) != ES_NETWORKCONNECTED)
-        {
-            OC_LOG(ERROR, ES_ENROLLEE_TAG, "ConnectToWiFiNetwork Failed");
-            cb(ES_ERROR, ES_ON_BOARDING_STATE);
-            return ES_ERROR;
-        }
-        else{
-            OC_LOG(INFO, ES_ENROLLEE_TAG, "ConnectToWiFiNetwork Success");
-            cb(ES_OK, ES_ON_BOARDED_STATE);
-            return ES_OK;
-        }
-    }
-    return ES_ERROR;
-}
-
-
-ESResult InitEasySetup(OCConnectivityType networkType, const char *ssid, const char *passwd,
-              EventCallback cb)
-{
-    if(FindNetworkForOnboarding(networkType, ssid, passwd, cb) != ES_OK)
-    {
-        OC_LOG(ERROR, ES_ENROLLEE_TAG, "OnBoarding Failed");
-        return ES_ERROR;
-    }
-
-    // Initialize the OC Stack in Server mode
-    if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
-    {
-        OC_LOG(ERROR, ES_ENROLLEE_TAG, "OCStack init error");
-        return ES_ERROR;
-    }
-    else
-    {
-        OC_LOG(DEBUG, ES_ENROLLEE_TAG, "OCStack init success");
-        return ES_OK;
-    }
-}
-
-ESResult TerminateEasySetup()
-{
-    if(OCStop() != OC_STACK_OK)
-    {
-        OC_LOG(ERROR, ES_ENROLLEE_TAG, "OCStack stop failed");
-        return ES_ERROR;
-    }
-    else
-    {
-        OC_LOG(ERROR, ES_ENROLLEE_TAG, "OCStack stop success");
-        return ES_OK;
-    }
-}
-
-ESResult InitProvisioning()
-{
-    if (CreateProvisioningResource() != OC_STACK_OK)
-    {
-        return ES_ERROR;
-    }
-
-    if (CreateNetworkResource() != OC_STACK_OK)
-    {
-        return ES_ERROR;
-    }
-
-    RegisterResourceEventCallBack(EventCallbackInProvisioning);
-
-    return ES_RESOURCECREATED;
-}
-
diff --git a/service/easy-setup/sdk/enrollee/src/resourceHandler.cpp b/service/easy-setup/sdk/enrollee/src/resourceHandler.cpp
deleted file mode 100644 (file)
index 6c0fec2..0000000
+++ /dev/null
@@ -1,367 +0,0 @@
-//******************************************************************
-//
-// 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 "resourceHandler.h"
-#include "ocpayload.h"
-
-/**
- * @var ES_RH_TAG
- * @brief Logging tag for module name.
- */
-#define ES_RH_TAG "ES_RH"
-
-//-----------------------------------------------------------------------------
-// Private variables
-//-----------------------------------------------------------------------------
-
-/**
- * @var g_prov
- * @brief Structure for holding the Provisioning status and target information required to connect to the target network
- */
-static ProvResource g_prov;
-
-/**
- * @var g_net
- * @brief Structure forr holding the Provisioning status of network information
- */
-static NetResource g_net;
-
-//-----------------------------------------------------------------------------
-// Private internal function prototypes
-//-----------------------------------------------------------------------------
-OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag,
-        OCEntityHandlerRequest *ehRequest, void *callback);
-const char *getResult(OCStackResult result);
-
-OCEntityHandlerResult ProcessGetRequest(OCEntityHandlerRequest *ehRequest,
-                                               OCRepPayload** payload);
-OCEntityHandlerResult ProcessPutRequest(OCEntityHandlerRequest *ehRequest,
-                                               OCRepPayload** payload);
-OCEntityHandlerResult ProcessPostRequest(OCEntityHandlerRequest *ehRequest,
-                                                OCRepPayload** payload);
-OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest);
-
-static int g_flag = 0;
-
-ResourceEventCallback g_cbForResEvent = NULL;
-
-void RegisterResourceEventCallBack(ResourceEventCallback cb)
-{
-    g_cbForResEvent = cb;
-}
-
-void GetTargetNetworkInfoFromProvResource(char *name, char *pass)
-{
-    if (name != NULL && pass != NULL)
-    {
-        sprintf(name, "%s", g_prov.tnn);
-        sprintf(pass, "%s", g_prov.cd);
-    }
-}
-
-OCStackResult CreateProvisioningResource()
-{
-    g_prov.ps = 1; // need to provisioning
-    g_prov.tnt = CT_ADAPTER_IP;
-    sprintf(g_prov.tnn, "Unknown");
-    sprintf(g_prov.cd, "Unknown");
-
-    OCStackResult res = OCCreateResource(&g_prov.handle, "oic.r.prov", OC_RSRVD_INTERFACE_DEFAULT,
-            OC_RSRVD_ES_URI_PROV, OCEntityHandlerCb, NULL, OC_DISCOVERABLE | OC_OBSERVABLE);
-
-    OC_LOG_V(INFO, ES_RH_TAG, "Created Prov resource with result: %s", getResult(res));
-
-    return res;
-}
-#ifdef ESWIFI
-OCStackResult CreateNetworkResource()
-{
-    NetworkInfo netInfo;
-
-    if (getCurrentNetworkInfo(CT_ADAPTER_IP, &netInfo) != ES_OK)
-    {
-        return OC_STACK_ERROR;
-    }
-
-    if (netInfo.type != CT_ADAPTER_IP)
-    {
-        return OC_STACK_ERROR;
-    }
-
-    g_net.cnt = (int) netInfo.type;
-    g_net.ant[0] = (int) CT_ADAPTER_IP;
-    sprintf(g_net.ipaddr, "%d.%d.%d.%d", netInfo.ipaddr[0], netInfo.ipaddr[1], netInfo.ipaddr[2],
-            netInfo.ipaddr[3]);
-    sprintf(g_net.cnn, "%s", netInfo.ssid);
-
-    OC_LOG_V(INFO, ES_RH_TAG, "SSID: %s", g_net.cnn);
-    OC_LOG_V(INFO, ES_RH_TAG, "IP Address: %s", g_net.ipaddr);
-
-    OCStackResult res = OCCreateResource(&g_net.handle, "oic.r.net", OC_RSRVD_INTERFACE_DEFAULT,
-            OC_RSRVD_ES_URI_NET, OCEntityHandlerCb,NULL, OC_DISCOVERABLE | OC_OBSERVABLE);
-    OC_LOG_V(INFO, ES_RH_TAG, "Created Net resource with result: %s", getResult(res));
-
-    return res;
-}
-#endif
-OCEntityHandlerResult ProcessGetRequest(OCEntityHandlerRequest *ehRequest,
-                                                OCRepPayload **payload)
-{
-    OCEntityHandlerResult ehResult = OC_EH_ERROR;
-    if (!ehRequest)
-    {
-        OC_LOG(ERROR, ES_RH_TAG, "Request is Null");
-        return ehResult;
-    }
-    if (ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
-    {
-        OC_LOG(ERROR, ES_RH_TAG, "Incoming payload not a representation");
-        return ehResult;
-    }
-
-    OCRepPayload *getResp = constructResponse(ehRequest);
-    if (!getResp)
-    {
-        OC_LOG(ERROR, ES_RH_TAG, "constructResponse failed");
-        return OC_EH_ERROR;
-    }
-
-    *payload = getResp;
-    ehResult = OC_EH_OK;
-
-    return ehResult;
-}
-
-OCEntityHandlerResult ProcessPutRequest(OCEntityHandlerRequest *ehRequest,
-                                               OCRepPayload** payload)
-{
-
-    OCEntityHandlerResult ehResult = OC_EH_ERROR;
-    if (ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
-    {
-        OC_LOG(ERROR, ES_RH_TAG, "Incoming payload not a representation");
-        return ehResult;
-    }
-
-    OCRepPayload* input = (OCRepPayload*) (ehRequest->payload);
-    if (!input)
-    {
-        OC_LOG(ERROR, ES_RH_TAG, "Failed to parse");
-        return ehResult;
-    }
-
-    char* tnn;
-    if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_TNN, &tnn))
-    {
-        sprintf(g_prov.tnn, "%s", tnn);
-    }
-
-    char* cd;
-    if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_CD, &cd))
-    {
-        sprintf(g_prov.cd, "%s", cd);
-    }
-
-    g_flag = 1;
-
-    OCRepPayload *getResp = constructResponse(ehRequest);
-    if (!getResp)
-    {
-        OC_LOG(ERROR, ES_RH_TAG, "constructResponse failed");
-        return OC_EH_ERROR;
-    }
-
-    *payload = getResp;
-    ehResult = OC_EH_OK;
-
-    return ehResult;
-}
-
-OCEntityHandlerResult ProcessPostRequest(OCEntityHandlerRequest *ehRequest,
-                                                OCRepPayload** payload)
-{
-    OCEntityHandlerResult ehResult = OC_EH_ERROR;
-    if (!ehRequest)
-    {
-        OC_LOG(ERROR, ES_RH_TAG, "Request is Null");
-        return ehResult;
-    }
-    if (ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
-    {
-        OC_LOG(ERROR, ES_RH_TAG, "Incoming payload not a representation");
-        return ehResult;
-    }
-
-    OCRepPayload* input = (OCRepPayload*) (ehRequest->payload);
-    if (!input)
-    {
-        OC_LOG(ERROR, ES_RH_TAG, "Failed to parse");
-        return ehResult;
-    }
-    char* tr;
-    if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_TR, &tr))
-    {
-
-        // Triggering
-        ehResult = OC_EH_OK;
-    }
-
-    g_flag = 1;
-
-    return ehResult;
-}
-
-OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest)
-{
-    OCRepPayload* payload = OCRepPayloadCreate();
-    if (!payload)
-    {
-        OC_LOG(ERROR, ES_RH_TAG, "Failed to allocate Payload");
-        return NULL;
-    }
-
-    if (ehRequest->resource == g_prov.handle)
-    {
-        OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_PROV);
-        OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_PS, g_prov.ps);
-        OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_TNT, g_prov.tnt);
-        OCRepPayloadSetPropString(payload, OC_RSRVD_ES_TNN, g_prov.tnn);
-        OCRepPayloadSetPropString(payload, OC_RSRVD_ES_CD, g_prov.cd);
-    }
-    else if (ehRequest->requestHandle == g_net.handle)
-    {
-
-        OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_NET);
-        OCRepPayloadSetPropInt(payload, "ant", g_net.ant[0]);
-    }
-    return payload;
-}
-
-// This is the entity handler for the registered resource.
-// This is invoked by OCStack whenever it recevies a request for this resource.
-OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag,
-        OCEntityHandlerRequest* entityHandlerRequest, void *callback)
-{
-    (void) callback;
-    OCEntityHandlerResult ehRet = OC_EH_OK;
-    OCEntityHandlerResponse response =
-    { 0 };
-    OCRepPayload* payload = NULL;
-    if (entityHandlerRequest && (flag & OC_REQUEST_FLAG))
-    {
-        if (OC_REST_GET == entityHandlerRequest->method)
-        {
-            OC_LOG(INFO, ES_RH_TAG, "Received GET request");
-            ehRet = ProcessGetRequest(entityHandlerRequest, &payload);
-        }
-        else if (OC_REST_PUT == entityHandlerRequest->method)
-        {
-            OC_LOG(INFO, ES_RH_TAG, "Received PUT request");
-
-            if (g_prov.handle != NULL && entityHandlerRequest->resource == g_prov.handle)
-            {
-                ehRet = ProcessPutRequest(entityHandlerRequest, &payload);
-            }
-            else
-            {
-                ehRet = OC_EH_ERROR;
-            }
-        }
-        else if (OC_REST_POST == entityHandlerRequest->method)
-        {
-            // TODO: As of now, POST request will be not received.
-            OC_LOG(INFO, ES_RH_TAG, "Received OC_REST_POST from client");
-            //ehRet = ProcessPostRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
-        }
-
-        if (ehRet == OC_EH_OK)
-        {
-            // Format the response.  Note this requires some info about the request
-            response.requestHandle = entityHandlerRequest->requestHandle;
-            response.resourceHandle = entityHandlerRequest->resource;
-            response.ehResult = ehRet;
-            //response uses OCPaylod while all get,put methodes use OCRepPayload
-            response.payload = (OCPayload*) (payload);
-            response.numSendVendorSpecificHeaderOptions = 0;
-            memset(response.sendVendorSpecificHeaderOptions, 0,
-                    sizeof response.sendVendorSpecificHeaderOptions);
-            memset(response.resourceUri, 0, sizeof response.resourceUri);
-            // Indicate that response is NOT in a persistent buffer
-            response.persistentBufferFlag = 0;
-
-            // Send the response
-            if (OCDoResponse(&response) != OC_STACK_OK)
-            {
-                OC_LOG(ERROR, ES_RH_TAG, "Error sending response");
-                ehRet = OC_EH_ERROR;
-            }
-        }
-    }
-
-    if (g_flag == 1)
-    {
-        g_cbForResEvent(ES_RECVTRIGGEROFPROVRES);
-        g_flag = 0;
-    }
-
-    return ehRet;
-}
-
-const char *getResult(OCStackResult result)
-{
-    switch (result)
-    {
-        case OC_STACK_OK:
-            return "OC_STACK_OK";
-        case OC_STACK_INVALID_URI:
-            return "OC_STACK_INVALID_URI";
-        case OC_STACK_INVALID_QUERY:
-            return "OC_STACK_INVALID_QUERY";
-        case OC_STACK_INVALID_IP:
-            return "OC_STACK_INVALID_IP";
-        case OC_STACK_INVALID_PORT:
-            return "OC_STACK_INVALID_PORT";
-        case OC_STACK_INVALID_CALLBACK:
-            return "OC_STACK_INVALID_CALLBACK";
-        case OC_STACK_INVALID_METHOD:
-            return "OC_STACK_INVALID_METHOD";
-        case OC_STACK_NO_MEMORY:
-            return "OC_STACK_NO_MEMORY";
-        case OC_STACK_COMM_ERROR:
-            return "OC_STACK_COMM_ERROR";
-        case OC_STACK_INVALID_PARAM:
-            return "OC_STACK_INVALID_PARAM";
-        case OC_STACK_NOTIMPL:
-            return "OC_STACK_NOTIMPL";
-        case OC_STACK_NO_RESOURCE:
-            return "OC_STACK_NO_RESOURCE";
-        case OC_STACK_RESOURCE_ERROR:
-            return "OC_STACK_RESOURCE_ERROR";
-        case OC_STACK_SLOW_RESOURCE:
-            return "OC_STACK_SLOW_RESOURCE";
-        case OC_STACK_NO_OBSERVERS:
-            return "OC_STACK_NO_OBSERVERS";
-        case OC_STACK_ERROR:
-            return "OC_STACK_ERROR";
-        default:
-            return "UNKNOWN";
-    }
-}
-
diff --git a/service/easy-setup/sdk/mediator/android/.gitignore b/service/easy-setup/sdk/mediator/android/.gitignore
deleted file mode 100644 (file)
index 6451fc5..0000000
+++ /dev/null
@@ -1,50 +0,0 @@
-#built application files\r
-*.apk\r
-*.ap_\r
-\r
-# files for the dex VM\r
-*.dex\r
-\r
-# Java class files\r
-*.class\r
-\r
-# generated files\r
-bin/\r
-gen/\r
-\r
-# Local configuration file (sdk path, etc)\r
-local.properties\r
-\r
-# Proguard folder generated by Eclipse \r
-proguard/ \r
-\r
-# Windows thumbnail db\r
-Thumbs.db\r
-\r
-# OSX files\r
-.DS_Store\r
-\r
-# Eclipse project files\r
-.classpath\r
-.project\r
-\r
-#Android Studio & Gradle\r
-.gradle\r
-/local.properties\r
-/.idea/workspace.xml\r
-/.idea/libraries\r
-.DS_Store\r
-/build/*\r
-/base/build/*\r
-/base/obj/*\r
-/base/libs/*\r
-/sample/*\r
-\r
-#Some older projects\r
-/*/out\r
-/*/*/build\r
-/*/*/production\r
-*.iws\r
-*.ipr\r
-*~\r
-*.swp
\ No newline at end of file
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/build.gradle b/service/easy-setup/sdk/mediator/android/EasySetupCore/build.gradle
deleted file mode 100644 (file)
index c1f2134..0000000
+++ /dev/null
@@ -1,40 +0,0 @@
-apply plugin: 'com.android.library'\r
-// Top-level build file where you can add configuration options common to all sub-projects/modules.\r
-buildscript {\r
-    repositories {\r
-        jcenter()\r
-    }\r
-    dependencies {\r
-        classpath 'com.android.tools.build:gradle:1.2.3'\r
-    }\r
-}\r
-\r
-allprojects {\r
-    repositories {\r
-        jcenter()\r
-    }\r
-}\r
-\r
-android {\r
-    compileSdkVersion 21\r
-    buildToolsVersion '21.1.2'\r
-\r
-    defaultConfig {\r
-        minSdkVersion 21\r
-        targetSdkVersion 21\r
-    }\r
-\r
-    buildTypes {\r
-        release {\r
-            minifyEnabled false\r
-            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'\r
-        }\r
-    }\r
-    sourceSets {\r
-        main { java.srcDirs = ['src/main/java', 'src/main/java/common', 'src/main/java/interface'] }\r
-    }\r
-}\r
-\r
-dependencies {\r
-    compile project(':iotivity-armeabi-base-debug')\r
-}
\ No newline at end of file
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/settings.gradle b/service/easy-setup/sdk/mediator/android/EasySetupCore/settings.gradle
deleted file mode 100644 (file)
index 3f6e49d..0000000
+++ /dev/null
@@ -1 +0,0 @@
-include ':iotivity-armeabi-base-debug'
\ No newline at end of file
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/EasySetupServiceConfigTest.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/EasySetupServiceConfigTest.java
deleted file mode 100755 (executable)
index 54fec21..0000000
+++ /dev/null
@@ -1,74 +0,0 @@
-/**\r
- * ***************************************************************\r
- * <p/>\r
- * Copyright 2015 Samsung Electronics All Rights Reserved.\r
- * <p/>\r
- * <p/>\r
- * <p/>\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
- * <p/>\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * <p/>\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
- * <p/>\r
- * ****************************************************************\r
- */\r
-\r
-package org.iotivity.service.easysetup.mediator;\r
-\r
-import android.test.AndroidTestCase;\r
-\r
-\r
-public class EasySetupServiceConfigTest extends AndroidTestCase {\r
-\r
-\r
-    public void testConstruction() {\r
-\r
-        EasySetupService service = EasySetupService.getInstance(getContext(), new EasySetupStatus() {\r
-            @Override\r
-            public void onFinished(EnrolleeDevice enrolledevice) {\r
-\r
-            }\r
-\r
-            @Override\r
-            public void onProgress(EnrolleeDevice enrolleeDevice) {\r
-\r
-            }\r
-        });\r
-\r
-        assertTrue(service != null);\r
-\r
-\r
-    }\r
-\r
-    public void testFinish() {\r
-        EasySetupService service = EasySetupService.getInstance(getContext(), new EasySetupStatus() {\r
-            @Override\r
-            public void onFinished(EnrolleeDevice enrolledevice) {\r
-\r
-            }\r
-\r
-            @Override\r
-            public void onProgress(EnrolleeDevice enrolleeDevice) {\r
-\r
-            }\r
-        });\r
-        service.finish();\r
-\r
-        // No runtime exception is thrown means test is successful\r
-        assertTrue(true);\r
-\r
-    }\r
-\r
-    public void testEnrolleeDeviceFacotryConstruction() {\r
-        EnrolleeDeviceFactory factory = EnrolleeDeviceFactory.newInstance(getContext());\r
-        assertTrue(factory != null);\r
-    }\r
-\r
-}\r
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/EasySetupServiceTest.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/EasySetupServiceTest.java
deleted file mode 100755 (executable)
index 9ac1a18..0000000
+++ /dev/null
@@ -1,155 +0,0 @@
-//******************************************************************\r
-//\r
-// Copyright 2015 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
-package org.iotivity.service.easysetup.mediator;\r
-\r
-import android.net.wifi.WifiConfiguration;\r
-import android.test.AndroidTestCase;\r
-import android.util.Log;\r
-\r
-import java.io.IOException;\r
-\r
-public class EasySetupServiceTest extends AndroidTestCase {\r
-\r
-\r
-    public void testStartSetupWithWiFiOnboarding() {\r
-\r
-        EasySetupService mService;\r
-        EnrolleeDevice mDevice;\r
-        EnrolleeDeviceFactory mFactory;\r
-\r
-        final Object lock = new Object();\r
-\r
-\r
-        /* Create Easy Setup service */\r
-        mService = EasySetupService.getInstance(getContext(), new EasySetupStatus() {\r
-            @Override\r
-            public void onFinished(EnrolleeDevice enrolledevice) {\r
-\r
-                //countDownLatch.countDown();\r
-                Utility.toNotify(lock);\r
-\r
-                if (enrolledevice.isSetupSuccessful()) {\r
-\r
-                    if (enrolledevice.mOnBoardingConfig.getConnType() == WiFiOnBoardingConfig.ConnType.WiFi) {\r
-                        IpOnBoardingConnection conn = (IpOnBoardingConnection) enrolledevice.getConnection();\r
-                        String ip = conn.getIp();\r
-                        if (ip == null || ip.isEmpty()) {\r
-                            assertTrue(false);\r
-                            return;\r
-                        }\r
-                        String mac = conn.getHardwareAddress();\r
-                        if (mac == null || mac.isEmpty()) {\r
-                            assertTrue(false);\r
-                            return;\r
-                        }\r
-                        // Device configured successfully\r
-                        assertTrue(true);\r
-                    }\r
-\r
-                } else {\r
-                    assertTrue(false);\r
-                }\r
-            }\r
-\r
-            @Override\r
-            public void onProgress(EnrolleeDevice enrolleeDevice) {\r
-                // Handled in EasySetupStatusTest\r
-            }\r
-        });\r
-\r
-\r
-        /* Create On boarding configuration */\r
-        WiFiOnBoardingConfig mWiFiOnBoardingConfig = new WiFiOnBoardingConfig();\r
-        mWiFiOnBoardingConfig.setSSId("EasySetup123");\r
-        mWiFiOnBoardingConfig.setSharedKey("EasySetup123");\r
-        mWiFiOnBoardingConfig.setAuthAlgo(WifiConfiguration.AuthAlgorithm.OPEN);\r
-        mWiFiOnBoardingConfig.setKms(WifiConfiguration.KeyMgmt.WPA_PSK);\r
-\r
-        /* Create provisioning configuration */\r
-        WiFiProvConfig mWiFiProvConfig = new WiFiProvConfig("hub2.4G", "11112222");\r
-\r
-        /* Create enrolling device factory instance */\r
-        mFactory = EnrolleeDeviceFactory.newInstance(getContext());\r
-\r
-        /* Check if the factory created successfully */\r
-        assertTrue(mFactory != null);\r
-\r
-        /* Create enrolling device */\r
-        mDevice = mFactory.newEnrolleeDevice(mWiFiOnBoardingConfig, mWiFiProvConfig);\r
-\r
-        /* Check if the the device is created successfully*/\r
-        assertTrue(mDevice != null);\r
-\r
-        /* Check if the the correct device is created as per the given configuration*/\r
-        assertTrue((mDevice instanceof EnrolleeDeviceWiFiOnboarding));\r
-\r
-\r
-        try {\r
-            mService.startSetup(mDevice);\r
-            // If no exception is thrown means setup started successfully.\r
-            assertTrue(true);\r
-\r
-        } catch (IOException e) {\r
-            assertTrue(false);\r
-        }\r
-\r
-        try {\r
-\r
-            Utility.toWait(lock);\r
-\r
-            Log.i("EasySetupTest", "Lock is released");\r
-\r
-            if (!mDevice.isSetupSuccessful()) {\r
-                assertTrue(false);\r
-                return;\r
-            }\r
-\r
-            IpOnBoardingConnection conn = (IpOnBoardingConnection) mDevice.getConnection();\r
-            if (conn == null) {\r
-                assertTrue(false);\r
-                return;\r
-            }\r
-\r
-            String ip = conn.getIp();\r
-            if (ip == null || ip.isEmpty()) {\r
-                assertTrue(false);\r
-                return;\r
-            }\r
-\r
-            String mac = conn.getHardwareAddress();\r
-            if (mac == null || mac.isEmpty()) {\r
-                assertTrue(false);\r
-                return;\r
-            }\r
-\r
-            Log.i("EasySetupTest", "Ip" + conn.getIp());\r
-            Log.i("EasySetupTest", "MAC" + conn.getHardwareAddress());\r
-\r
-            // Device configured successfully\r
-            assertTrue(true);\r
-\r
-        } catch (Exception e) {\r
-            e.printStackTrace();\r
-            assertTrue(false);\r
-        }\r
-\r
-    }\r
-\r
-}
\ No newline at end of file
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/EasySetupStatusTest.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/EasySetupStatusTest.java
deleted file mode 100755 (executable)
index d1a1370..0000000
+++ /dev/null
@@ -1,163 +0,0 @@
-//******************************************************************
-//
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-package org.iotivity.service.easysetup.mediator;
-
-import android.net.wifi.WifiConfiguration;
-import android.test.AndroidTestCase;
-import android.util.Log;
-
-import java.io.IOException;
-
-public class EasySetupStatusTest extends AndroidTestCase {
-
-
-    public void testStartSetupWithWiFiOnboarding() {
-
-        EasySetupService mService;
-        EnrolleeDevice mDevice;
-        EnrolleeDeviceFactory mFactory;
-
-        final Object lock = new Object();
-
-
-        /* Create Easy Setup service */
-        mService = EasySetupService.getInstance(getContext(), new EasySetupStatus() {
-            EnrolleeState old_state = null;
-
-            @Override
-            public void onFinished(EnrolleeDevice enrolledevice) {
-
-                //countDownLatch.countDown();
-                Utility.toNotify(lock);
-
-                if (enrolledevice.isSetupSuccessful()) {
-
-                    if (enrolledevice.mOnBoardingConfig.getConnType() == WiFiOnBoardingConfig.ConnType.WiFi) {
-                        IpOnBoardingConnection conn = (IpOnBoardingConnection) enrolledevice.getConnection();
-                        String ip = conn.getIp();
-                        if (ip == null || ip.isEmpty()) {
-                            assertTrue(false);
-                            return;
-                        }
-                        String mac = conn.getHardwareAddress();
-                        if (mac == null || mac.isEmpty()) {
-                            assertTrue(false);
-                            return;
-                        }
-                        // Device configured successfully
-                        assertTrue(true);
-                    }
-
-                } else {
-                    assertTrue(false);
-                }
-            }
-
-            @Override
-            public void onProgress(EnrolleeDevice enrolleeDevice) {
-                EnrolleeState state = enrolleeDevice.mState;
-                // TODO
-                switch (state) {
-                    case DEVICE_INIT_STATE:
-                        Log.d("enrollee state", "DEVICE_INIT_STATE");
-                        assertTrue(false);
-                        break;
-                    case DEVICE_ON_BOARDING_STATE:
-                        if (old_state == null)
-                            assertTrue(true);
-                        else assertTrue(false);
-                        old_state = EnrolleeState.DEVICE_ON_BOARDING_STATE;
-                        Log.d("enrollee state", "DEVICE_ON_BOARDING_STATE");
-                        break;
-
-                    case DEVICE_ON_BOARDED_STATE:
-                        if (old_state == EnrolleeState.DEVICE_ON_BOARDING_STATE)
-                            assertTrue(true);
-                        else assertTrue(false);
-                        old_state = EnrolleeState.DEVICE_ON_BOARDED_STATE;
-                        Log.d("enrollee state", "DEVICE_ON_BOARDED_STATE");
-                        break;
-
-                    case DEVICE_PROVISIONING_STATE:
-                        if (old_state == EnrolleeState.DEVICE_ON_BOARDED_STATE)
-                            assertTrue(true);
-                        else assertTrue(false);
-                        old_state = EnrolleeState.DEVICE_PROVISIONING_STATE;
-                        Log.d("enrollee state", "DEVICE_PROVISIONING_STATE");
-                        break;
-
-                    case DEVICE_PROVISIONED_STATE:
-                        if (old_state == EnrolleeState.DEVICE_PROVISIONING_STATE)
-                            assertTrue(true);
-                        else assertTrue(false);
-                        Log.d("enrollee state", "DEVICE_PROVISIONING_SUCCESS_STATE");
-                        break;
-
-                    default:
-                        Log.d("enrollee state", "unknown state");
-                        assertTrue(false);
-                        break;
-                }
-
-            }
-        });
-
-
-        /* Create On boarding configuration */
-        WiFiOnBoardingConfig mWiFiOnBoardingConfig = new WiFiOnBoardingConfig();
-        mWiFiOnBoardingConfig.setSSId("EasySetup123");
-        mWiFiOnBoardingConfig.setSharedKey("EasySetup123");
-        mWiFiOnBoardingConfig.setAuthAlgo(WifiConfiguration.AuthAlgorithm.OPEN);
-        mWiFiOnBoardingConfig.setKms(WifiConfiguration.KeyMgmt.WPA_PSK);
-
-        /* Create provisioning configuration */
-        WiFiProvConfig mWiFiProvConfig = new WiFiProvConfig("hub2.4G", "11112222");
-
-        /* Create enrolling device factory instance */
-        mFactory = EnrolleeDeviceFactory.newInstance(getContext());
-
-        /* Create enrolling device */
-        mDevice = mFactory.newEnrolleeDevice(mWiFiOnBoardingConfig, mWiFiProvConfig);
-
-        try {
-            mService.startSetup(mDevice);
-        } catch (IOException e) {
-        }
-
-        try {
-
-            Utility.toWait(lock);
-
-            Log.i("EasySetupTest", "Lock is released");
-
-            IpOnBoardingConnection conn = (IpOnBoardingConnection) mDevice.getConnection();
-
-            Log.i("EasySetupTest", "Ip" + conn.getIp());
-            Log.i("EasySetupTest", "MAC" + conn.getHardwareAddress());
-
-            // Device configured successfully
-
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
-
-    }
-
-}
\ No newline at end of file
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/EnrolleeDeviceFactoryTest.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/EnrolleeDeviceFactoryTest.java
deleted file mode 100755 (executable)
index 42114c9..0000000
+++ /dev/null
@@ -1,70 +0,0 @@
-/**\r
- * ***************************************************************\r
- * <p/>\r
- * Copyright 2015 Samsung Electronics All Rights Reserved.\r
- * <p/>\r
- * <p/>\r
- * <p/>\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
- * <p/>\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * <p/>\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
- * <p/>\r
- * ****************************************************************\r
- */\r
-\r
-package org.iotivity.service.easysetup.mediator;\r
-\r
-import android.net.wifi.WifiConfiguration;\r
-import android.test.AndroidTestCase;\r
-\r
-public class EnrolleeDeviceFactoryTest extends AndroidTestCase {\r
-\r
-    EnrolleeDeviceFactory mFactory;\r
-\r
-    @Override\r
-    protected void setUp() throws Exception {\r
-        super.setUp();\r
-        mFactory = EnrolleeDeviceFactory.newInstance(getContext());\r
-        assertTrue(mFactory != null);\r
-\r
-    }\r
-\r
-    @Override\r
-    protected void tearDown() throws Exception {\r
-        super.tearDown();\r
-        mFactory = null;\r
-    }\r
-\r
-\r
-    public void testNewEnrolleeDevice_with_WiFiOnboarding() {\r
-\r
-        /* Create On boarding configuration */\r
-        WiFiOnBoardingConfig mWiFiOnBoardingConfig = new WiFiOnBoardingConfig();\r
-        mWiFiOnBoardingConfig.setSSId("EasySetup123");\r
-        mWiFiOnBoardingConfig.setSharedKey("EasySetup123");\r
-        mWiFiOnBoardingConfig.setAuthAlgo(WifiConfiguration.AuthAlgorithm.OPEN);\r
-        mWiFiOnBoardingConfig.setKms(WifiConfiguration.KeyMgmt.WPA_PSK);\r
-\r
-        /* Create provisioning configuration */\r
-        WiFiProvConfig mWiFiProvConfig = new WiFiProvConfig("hub2.4G", "11112222");\r
-\r
-        /* Create enrolling device */\r
-        EnrolleeDevice device = mFactory.newEnrolleeDevice(mWiFiOnBoardingConfig, mWiFiProvConfig);\r
-\r
-        /* Check if the the device is created */\r
-        assertTrue(device != null);\r
-\r
-        /* Check if the the correct device is created as per the given configuration*/\r
-        assertTrue((device instanceof EnrolleeDeviceWiFiOnboarding));\r
-\r
-    }\r
-\r
-}\r
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/Utility.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/androidTest/java/org/iotivity/service/easysetup/mediator/Utility.java
deleted file mode 100755 (executable)
index 84b2c7e..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-//******************************************************************\r
-//\r
-// Copyright 2015 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
-package org.iotivity.service.easysetup.mediator;\r
-\r
-\r
-public class Utility {\r
-\r
-    public static void toNotify(Object toLock) {\r
-        synchronized (toLock) {\r
-            toLock.notify();\r
-        }\r
-    }\r
-\r
-    public static void toWait(Object toLock) {\r
-        synchronized (toLock) {\r
-            try {\r
-                toLock.wait(45000);\r
-            } catch (InterruptedException e) {\r
-                e.printStackTrace();\r
-            }\r
-        }\r
-    }\r
-}\r
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/core/EasySetupCallbackHandler.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/core/EasySetupCallbackHandler.java
deleted file mode 100755 (executable)
index 685a12a..0000000
+++ /dev/null
@@ -1,54 +0,0 @@
-/**\r
- * ***************************************************************\r
- * <p>\r
- * Copyright 2015 Samsung Electronics All Rights Reserved.\r
- * <p>\r
- * <p>\r
- * <p>\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
- * <p>\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * <p>\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
- * <p>\r
- * ****************************************************************\r
- */\r
-package org.iotivity.service.easysetup.core;\r
-\r
-import android.util.Log;\r
-\r
-public class EasySetupCallbackHandler {\r
-    private static final String TAG = "ESCallbackHandler";\r
-    ProvisionEnrollee provisioningListener;\r
-\r
-    private static EasySetupCallbackHandler easySetupCallbackHandlerObj;\r
-\r
-    public static synchronized EasySetupCallbackHandler getInstance() {\r
-        if (null == easySetupCallbackHandlerObj) {\r
-            easySetupCallbackHandlerObj = new EasySetupCallbackHandler();\r
-        }\r
-        return easySetupCallbackHandlerObj;\r
-    }\r
-\r
-    public void ProvisioningStatusCallBack(int statuscode) {\r
-        Log.d(TAG,\r
-                "onFinishProvisioning() inside Android Java application. statuscode - "\r
-                        + statuscode);\r
-        if (this.provisioningListener != null) {\r
-            this.provisioningListener.ProvisioningStatusCallBack(statuscode);\r
-        } else {\r
-            Log.e(TAG, "provisioningListener is not registered");\r
-        }\r
-    }\r
-\r
-    public void registerProvisioningHandler(\r
-            ProvisionEnrollee provisioningListener) {\r
-        this.provisioningListener = provisioningListener;\r
-    }\r
-}\r
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/core/EasySetupManager.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/core/EasySetupManager.java
deleted file mode 100755 (executable)
index c85b051..0000000
+++ /dev/null
@@ -1,94 +0,0 @@
-/**\r
- * ***************************************************************\r
- * <p>\r
- * Copyright 2015 Samsung Electronics All Rights Reserved.\r
- * <p>\r
- * <p>\r
- * <p>\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
- * <p>\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * <p>\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
- * <p>\r
- * ****************************************************************\r
- */\r
-package org.iotivity.service.easysetup.core;\r
-\r
-import android.content.Context;\r
-\r
-import org.iotivity.ca.CaInterface;\r
-\r
-public class EasySetupManager {\r
-    private native void InitEasySetup();\r
-\r
-    private native void TerminateEasySetup();\r
-\r
-    // TODO : "OcConnectivityType connectivityType" has to be passed as the\r
-    // second parameter for PerformEasySetup\r
-    // instead of integer\r
-    private native void ProvisionEnrollee(String ipAddress, String netSSID,\r
-                                          String netPWD, int connectivityType);\r
-\r
-    private native void StopEnrolleeProvisioning(int connectivityType);\r
-\r
-    public static native void initialize(Context context);\r
-\r
-    private static EasySetupManager easySetupManagerInterfaceObj = null;\r
-    private Context appContext = null;\r
-\r
-    static {\r
-        // Load Easy Setup JNI interface\r
-        System.loadLibrary("gnustl_shared");\r
-        System.loadLibrary("octbstack");\r
-        System.loadLibrary("connectivity_abstraction");\r
-        System.loadLibrary("easysetup-jni");\r
-    }\r
-\r
-    private EasySetupManager() {\r
-\r
-    }\r
-\r
-    /**\r
-     * Function for Getting instance of EasySetupManager object.\r
-     *\r
-     * @return EasySetupManager instance.\r
-     *\r
-     */\r
-    public static synchronized EasySetupManager getInstance() {\r
-        if (null == easySetupManagerInterfaceObj) {\r
-            easySetupManagerInterfaceObj = new EasySetupManager();\r
-        }\r
-        return easySetupManagerInterfaceObj;\r
-    }\r
-\r
-    public void setApplicationContext(Context context) {\r
-        appContext = context;\r
-    }\r
-\r
-    public void initEasySetup() {\r
-        CaInterface.initialize(appContext);\r
-        InitEasySetup();\r
-    }\r
-\r
-    public void terminateEasySetup() {\r
-        TerminateEasySetup();\r
-    }\r
-\r
-    public void provisionEnrollee(String ipAddress, String netSSID,\r
-                                  String netPWD, int connectivityType) {\r
-\r
-        ProvisionEnrollee(ipAddress, netSSID, netPWD, connectivityType);\r
-    }\r
-\r
-    public void stopEnrolleeProvisioning(int connectivityType) {\r
-        StopEnrolleeProvisioning(connectivityType);\r
-    }\r
-\r
-}\r
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/core/IProvisioningListener.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/core/IProvisioningListener.java
deleted file mode 100755 (executable)
index 8c0118f..0000000
+++ /dev/null
@@ -1,30 +0,0 @@
-/**\r
- * ***************************************************************\r
- * <p>\r
- * Copyright 2015 Samsung Electronics All Rights Reserved.\r
- * <p>\r
- * <p>\r
- * <p>\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
- * <p>\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * <p>\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
- * <p>\r
- * ****************************************************************\r
- */\r
-package org.iotivity.service.easysetup.core;\r
-\r
-public interface IProvisioningListener {\r
-    /**\r
-     * Interface called when the provisioning finishes\r
-     */\r
-\r
-    public void onFinishProvisioning(int statuscode);\r
-}\r
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/core/ProvisionEnrollee.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/core/ProvisionEnrollee.java
deleted file mode 100755 (executable)
index e98bd66..0000000
+++ /dev/null
@@ -1,62 +0,0 @@
-/**\r
- * ***************************************************************\r
- * <p>\r
- * Copyright 2015 Samsung Electronics All Rights Reserved.\r
- * <p>\r
- * <p>\r
- * <p>\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
- * <p>\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * <p>\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
- * <p>\r
- * ****************************************************************\r
- */\r
-\r
-package org.iotivity.service.easysetup.core;\r
-\r
-import android.content.Context;\r
-import android.util.Log;\r
-\r
-public class ProvisionEnrollee {\r
-    private static final String TAG = "ProvisionEnrollee";\r
-    private IProvisioningListener provisioningListener;\r
-\r
-    /**\r
-     * Constructor for ProvisionEnrollee. Constructs a new ProvisionEnrollee.\r
-     */\r
-    public ProvisionEnrollee(Context context) {\r
-\r
-    }\r
-\r
-    public void provisionEnrollee(String ipAddress, String netSSID,\r
-                                  String netPWD, int connectivityType) {\r
-        Log.i(TAG, "JNI start provisioning is called ");\r
-    }\r
-\r
-    public void stopEnrolleeProvisioning(int connectivityType) {\r
-        Log.i(TAG, "JNI stop provisioning is called ");\r
-    }\r
-\r
-    public void ProvisioningStatusCallBack(int statuscode) {\r
-        Log.d(TAG,\r
-                "JNI onFinishProvisioning() inside Android Java application. statuscode - "\r
-                        + statuscode);\r
-        this.provisioningListener.onFinishProvisioning(statuscode);\r
-    }\r
-\r
-    public void registerProvisioningHandler(\r
-            IProvisioningListener provisioningListener) {\r
-        this.provisioningListener = provisioningListener;\r
-        EasySetupCallbackHandler.getInstance()\r
-                .registerProvisioningHandler(this);\r
-        Log.i(TAG, "JNI Callback is registered for getting provisioning status");\r
-    }\r
-}\r
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EasySetupService.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EasySetupService.java
deleted file mode 100755 (executable)
index 5e764a7..0000000
+++ /dev/null
@@ -1,188 +0,0 @@
-/**\r
- * ***************************************************************\r
- * <p/>\r
- * Copyright 2015 Samsung Electronics All Rights Reserved.\r
- * <p/>\r
- * <p/>\r
- * <p/>\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
- * <p/>\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * <p/>\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
- * <p/>\r
- * ****************************************************************\r
- */\r
-\r
-package org.iotivity.service.easysetup.mediator;\r
-\r
-import android.content.Context;\r
-import android.util.Log;\r
-\r
-import org.iotivity.service.easysetup.core.EasySetupManager;\r
-import org.iotivity.service.easysetup.core.ProvisionEnrollee;\r
-\r
-import java.io.IOException;\r
-import java.util.ArrayList;\r
-\r
-/**\r
- * This is facade class, a single point of contact for Application.\r
- * It contains set of APIs to do easy setup of the enrolling device.\r
- * ON-BOARDING - This is a step to establish connectivity between the device & Mediator device.\r
- * PROVISION   - This is a step where the netowork's detail & credentials are given to the\r
- * enrolling device.\r
- */\r
-public class EasySetupService {\r
-\r
-    private static final String TAG = EasySetupService.class.getName();\r
-\r
-    private static EasySetupService sInstance;\r
-\r
-    private final EasySetupStatus mCallback;\r
-\r
-    private ArrayList<EnrolleeDevice> mEnrolleeDeviceList;\r
-\r
-    private final ProvisioningCallback mProvisioningCallback;\r
-\r
-    private static Context mContext;\r
-\r
-\r
-    ProvisionEnrollee mProvisionEnrolleeInstance;\r
-\r
-    private EasySetupService(EasySetupStatus callback) {\r
-        mCallback = callback;\r
-        mProvisioningCallback = new ProvisioningCallbackImpl(mCallback);\r
-        mEnrolleeDeviceList = new ArrayList<EnrolleeDevice>();\r
-        mContext = null;\r
-\r
-    }\r
-\r
-    /**\r
-     * Gives a singleton instance of Easy setup service and initialize the service\r
-     *\r
-     * @param callback Application needs to provide this callback to receive the status of easy\r
-     *                 setup process.\r
-     */\r
-\r
-    public synchronized static EasySetupService getInstance(Context context, EasySetupStatus\r
-            callback) {\r
-        if (sInstance == null) {\r
-            sInstance = new EasySetupService(callback);\r
-            mContext = context;\r
-        }\r
-        return sInstance;\r
-    }\r
-\r
-    /**\r
-     * Reset the Easy setup Service\r
-     */\r
-\r
-    public void finish() {\r
-\r
-        //Native Api call to reset OIC stack\r
-        if (mProvisionEnrolleeInstance != null) {\r
-            mProvisionEnrolleeInstance.stopEnrolleeProvisioning(0);\r
-        }\r
-    }\r
-\r
-    /**\r
-     * Starts Easy setup process for the enrolling device.\r
-     *\r
-     * @param enrolledevice Device to be enrolled in network\r
-     * @throws IOException Throws exception in case of any connection error.\r
-     */\r
-\r
-    public synchronized void startSetup(final EnrolleeDevice enrolledevice) throws IOException {\r
-\r
-        mEnrolleeDeviceList.add(enrolledevice);\r
-\r
-\r
-        // Starts the provisioning directly if the device is already on boarded on the network.\r
-        if (enrolledevice.onBoarded()) {\r
-            enrolledevice.startProvisioning(mProvisioningCallback);\r
-            return;\r
-        }\r
-        enrolledevice.mState = EnrolleeState.DEVICE_ON_BOARDING_STATE;\r
-\r
-        mCallback.onProgress(enrolledevice);\r
-        enrolledevice.startOnBoarding(new OnBoardingCallback() {\r
-\r
-            @Override\r
-            public void onFinished(OnBoardingConnection connection) {\r
-                if (connection.isConnected()) {\r
-                    Log.i(TAG, "On boarding is successful ");\r
-                    // Start provisioning here\r
-                    enrolledevice.mState = EnrolleeState.DEVICE_ON_BOARDED_STATE;\r
-                    mCallback.onProgress(enrolledevice);\r
-                    enrolledevice.setConnection(connection);\r
-                    enrolledevice.startProvisioning(mProvisioningCallback);\r
-                } else {\r
-                    enrolledevice.mState = EnrolleeState.DEVICE_INIT_STATE;\r
-                    mProvisioningCallback.onFinished(enrolledevice);\r
-                }\r
-\r
-            }\r
-\r
-        });\r
-\r
-    }\r
-\r
-    /**\r
-     * Stops on-going Easy setup process for enrolling device.\r
-     *\r
-     * @param enrolleedevice Device to be enrolled in network\r
-     */\r
-    public synchronized void stopSetup(EnrolleeDevice enrolleedevice) {\r
-        if (mEnrolleeDeviceList.contains(enrolleedevice)) {\r
-            enrolleedevice.mState = EnrolleeState.DEVICE_INIT_STATE;\r
-            mCallback.onProgress(enrolleedevice);\r
-            if (enrolleedevice.mState == EnrolleeState.DEVICE_ON_BOARDING_STATE) {\r
-                Log.i(TAG, "stopOnBoardingProcess for enrolleedevice");\r
-                enrolleedevice.stopOnBoardingProcess();\r
-                mEnrolleeDeviceList.remove(enrolleedevice);\r
-            } else if (enrolleedevice.mState == EnrolleeState.DEVICE_PROVISIONING_STATE) {\r
-                Log.i(TAG, "stopOnBoardingProcess for enrolleedevice");\r
-                enrolleedevice.stopOnBoardingProcess();\r
-                Log.i(TAG, "stopEnrolleeProvisioning for enrolleedevice");\r
-                //Native Api call to stop on-going enrolling process for the enrolling device\r
-                EasySetupManager.getInstance().stopEnrolleeProvisioning(enrolleedevice\r
-                        .mOnBoardingConfig.getConnType().getValue());\r
-                mEnrolleeDeviceList.remove(enrolleedevice);\r
-\r
-            }\r
-        }\r
-    }\r
-\r
-    class ProvisioningCallbackImpl extends ProvisioningCallback {\r
-\r
-        private final EasySetupStatus mCallback;\r
-\r
-        ProvisioningCallbackImpl(EasySetupStatus callback) {\r
-            mCallback = callback;\r
-        }\r
-\r
-        @Override\r
-        public void onFinished(EnrolleeDevice enrolledevice) {\r
-            synchronized (EasySetupService.this) {\r
-                if (mEnrolleeDeviceList.contains(enrolledevice)) {\r
-                    Log.i(TAG, "onFinished() is received " + enrolledevice.isSetupSuccessful());\r
-                    mCallback.onFinished(enrolledevice);\r
-                    mEnrolleeDeviceList.remove(enrolledevice);\r
-                }\r
-            }\r
-        }\r
-\r
-        @Override\r
-        public void onProgress(EnrolleeDevice enrolledevice) {\r
-            mCallback.onProgress(enrolledevice);\r
-        }\r
-\r
-\r
-    }\r
-}
\ No newline at end of file
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeDevice.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeDevice.java
deleted file mode 100755 (executable)
index cdac2c5..0000000
+++ /dev/null
@@ -1,166 +0,0 @@
-/**\r
- * ***************************************************************\r
- * <p/>\r
- * Copyright 2015 Samsung Electronics All Rights Reserved.\r
- * <p/>\r
- * <p/>\r
- * <p/>\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
- * <p/>\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * <p/>\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
- * <p/>\r
- * ****************************************************************\r
- */\r
-\r
-package org.iotivity.service.easysetup.mediator;\r
-\r
-/**\r
- * This is an abstract class represents the device being provisioned into the network. The\r
- * device being enrolled or provisioned into the network is called Enrollee.\r
- * Application has to extend this class and provide implementation of abstract methods according\r
- * to the ON-BOARDING & PROVISION connectivity i.e. WiFi etc.\r
- */\r
-\r
-public abstract class EnrolleeDevice {\r
-\r
-    protected EnrolleeState mState;\r
-    private EnrolleeSetupError mError;\r
-\r
-    protected OnBoardingConnection mConnection;\r
-    protected final ProvisioningConfig mProvConfig;\r
-    protected final OnBoardingConfig mOnBoardingConfig;\r
-\r
-    protected OnBoardingCallback mOnBoardingCallback;\r
-    protected ProvisioningCallback mProvisioningCallback;\r
-\r
-    /**\r
-     * @param onBoardingConfig Contains details about the connectivity to be established between\r
-     *                         the Enrollee device & Mediator device in order to perform\r
-     *                         on-boarding\r
-     * @param provConfig       Contains details about the network to which Enrollee device is\r
-     *                         going to connect.\r
-     */\r
-    protected EnrolleeDevice(OnBoardingConfig onBoardingConfig, ProvisioningConfig provConfig) {\r
-        mProvConfig = provConfig;\r
-        mOnBoardingConfig = onBoardingConfig;\r
-    }\r
-\r
-    /**\r
-     * Application has to implement it according to the on boarding connectivity the device is\r
-     * having.\r
-     * This method will be called back during the easy setup process.\r
-     */\r
-    protected abstract void startOnBoardingProcess();\r
-\r
-    /**\r
-     * This method is called back during the easy setup process if Application cancels the setup.\r
-     * Easy setup service checks the state of device and calls this function accordingly.\r
-     * Application has to provide implementation for this method to cancel the on boarding step.\r
-     */\r
-    protected abstract void stopOnBoardingProcess();\r
-\r
-    /**\r
-     * Application has to implement it according to the type of the network device is going to\r
-     * connect or provisioned.\r
-     * This method will be called back once on-boarding of the device is successful.\r
-     *\r
-     * @param conn Contains detail about the network established between the Enrollee device &\r
-     *             Mediator device. Its implementation vary according to the connectivity type.\r
-     */\r
-    protected abstract void startProvisioningProcess(OnBoardingConnection conn);\r
-\r
-    /**\r
-     * Once on boarding is successful concrete Enrollee class would call this method and set the\r
-     * Connection.\r
-     *\r
-     * @param conn Connectivity between Enrollee device & Mediator device.\r
-     */\r
-    protected void setConnection(OnBoardingConnection conn) {\r
-        mConnection = conn;\r
-    }\r
-\r
-    /**\r
-     * This method returns the OnBoardingConnection object depending on the connection type\r
-     *\r
-     * @return onBoardingConnection object\r
-     */\r
-    public OnBoardingConnection getConnection() {\r
-        return mConnection;\r
-    }\r
-\r
-\r
-    /**\r
-     * This method is called back by Easy setup service if on boarding needs to be done.\r
-     *\r
-     * @param onBoardingCallback This is called back once the on boarding is completed.\r
-     */\r
-    void startOnBoarding(OnBoardingCallback onBoardingCallback) {\r
-        mOnBoardingCallback = onBoardingCallback;\r
-        startOnBoardingProcess();\r
-    }\r
-\r
-    /**\r
-     * This method is called back by Easy setup service once on boarding is successful\r
-     *\r
-     * @param provisioningCallback This is called back once the provisioning process is completed\r
-     */\r
-    void startProvisioning(ProvisioningCallback provisioningCallback) {\r
-        mProvisioningCallback = provisioningCallback;\r
-        startProvisioningProcess(mConnection);\r
-    }\r
-\r
-    /**\r
-     * This method is used to check easy setup status\r
-     *\r
-     * @return true if successful or false\r
-     */\r
-\r
-    public boolean isSetupSuccessful() {\r
-        return (mState == EnrolleeState.DEVICE_PROVISIONED_STATE) ? true : false;\r
-    }\r
-\r
-    /**\r
-     * sets error occured during easy setup process\r
-     */\r
-    protected void setError(EnrolleeSetupError error) {\r
-        mError = error;\r
-    }\r
-\r
-    /**\r
-     * Returns error occured during easy setup process\r
-     *\r
-     * @return True EnrolleeSetupError object\r
-     */\r
-    public EnrolleeSetupError getError() {\r
-        return mError;\r
-    }\r
-\r
-    /**\r
-     * Gives the state of the device being enrolled during the easy setup process.\r
-     *\r
-     * @return Returns EnrolleeState object\r
-     */\r
-    public EnrolleeState getState() {\r
-        return mState;\r
-    }\r
-\r
-    /**\r
-     * This method is used to know if the device is on boarded or not\r
-     *\r
-     * @return True if on-boarded successfully or False\r
-     */\r
-\r
-    protected boolean onBoarded() {\r
-        return (mState == EnrolleeState.DEVICE_PROVISIONING_STATE) ? true : false;\r
-    }\r
-\r
-\r
-}\r
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeDeviceFactory.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeDeviceFactory.java
deleted file mode 100755 (executable)
index de7c7fb..0000000
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- * ***************************************************************
- * <p/>
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- * <p/>
- * <p/>
- * <p/>
- * 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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * 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.
- * <p/>
- * ****************************************************************
- */
-
-package org.iotivity.service.easysetup.mediator;
-
-import android.content.Context;
-
-/**
- * This a factory class provides the native implementation of the various Enrollee devices.
- * Application can make use of Enrollee factory if it does not want to create its own Enrollee devices.
- */
-public class EnrolleeDeviceFactory {
-
-    Context mContext;
-
-    /**
-     * This method create & returns instance of EnrolleeDeviceFactory
-     *
-     * @param context This is Android Application context
-     */
-    public static EnrolleeDeviceFactory newInstance(Context context) {
-        return new EnrolleeDeviceFactory(context);
-    }
-
-    private EnrolleeDeviceFactory(Context context) {
-        mContext = context;
-    }
-
-    /**
-     * This method create & returns instance of Enrollee device of supported configuration
-     *
-     * @param onboardingConfig Contains details about the connectivity to be established between the Enrollee device & Mediator device in order to perform on-boarding
-     * @param provConfig       Contains details about the network to which Enrollee device is going to connect.
-     * @return Instance of the Enrollee device created natively.
-     */
-
-    public EnrolleeDevice newEnrolleeDevice(OnBoardingConfig onboardingConfig, ProvisioningConfig provConfig) {
-
-        if (onboardingConfig.getConnType() != OnBoardingConfig.ConnType.WiFi) {
-            throw new IllegalArgumentException("OnBoarding configuration is not supported");
-        }
-
-        EnrolleeDevice enrolleeDevice;
-        enrolleeDevice = new EnrolleeDeviceWiFiOnboarding(mContext, onboardingConfig, provConfig);
-
-        return enrolleeDevice;
-    }
-
-}
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeDeviceWiFiOnboarding.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeDeviceWiFiOnboarding.java
deleted file mode 100755 (executable)
index 09459a3..0000000
+++ /dev/null
@@ -1,171 +0,0 @@
-/**\r
- * ***************************************************************\r
- * <p/>\r
- * Copyright 2015 Samsung Electronics All Rights Reserved.\r
- * <p/>\r
- * <p/>\r
- * <p/>\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
- * <p/>\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * <p/>\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
- * <p/>\r
- * ****************************************************************\r
- */\r
-\r
-package org.iotivity.service.easysetup.mediator;\r
-\r
-import java.util.Timer;\r
-import java.util.TimerTask;\r
-\r
-import org.iotivity.service.easysetup.core.EasySetupManager;\r
-import org.iotivity.service.easysetup.core.EnrolleeInfo;\r
-import org.iotivity.service.easysetup.core.IOnBoardingStatus;\r
-import org.iotivity.service.easysetup.core.IProvisioningListener;\r
-import org.iotivity.service.easysetup.core.ProvisionEnrollee;\r
-import org.iotivity.service.easysetup.core.ip.WiFiSoftAPManager;\r
-\r
-import android.content.Context;\r
-import android.net.wifi.WifiConfiguration;\r
-import android.util.Log;\r
-\r
-/**\r
- * This is a ready to use class for Enrollee device having Soft AP as on-boarding connectivity.\r
- */\r
-public class EnrolleeDeviceWiFiOnboarding extends EnrolleeDevice {\r
-\r
-    public static final String TAG = EnrolleeDeviceWiFiOnboarding.class.getName();\r
-\r
-    final Context mContext;\r
-    final WiFiSoftAPManager mWifiSoftAPManager;\r
-    EnrolleeInfo connectedDevice;\r
-    private EasySetupManager easySetupManagerNativeInstance;\r
-    ProvisionEnrollee provisionEnrolleInstance;\r
-    Timer myTimer;\r
-\r
-    IOnBoardingStatus deviceScanListener = new IOnBoardingStatus() {\r
-\r
-        @Override\r
-        public void deviceOnBoardingStatus(EnrolleeInfo enrolleStatus) {\r
-            myTimer.cancel();\r
-            Log.d("ESSoftAPOnBoarding", "Entered");\r
-            if (mState == EnrolleeState.DEVICE_ON_BOARDING_STATE) {\r
-                Log.d("ESSoftAPOnBoarding", "Device in OnBoarding State");\r
-                if (enrolleStatus != null && enrolleStatus.getIpAddr() != null) {\r
-                    String finalResult = "Easy Connect : ";\r
-\r
-                    if (enrolleStatus.isReachable()) {\r
-                        finalResult = "Device OnBoarded" + "["\r
-                                + enrolleStatus.getIpAddr() + "]";\r
-\r
-                        connectedDevice = enrolleStatus;\r
-                        IpOnBoardingConnection conn = new IpOnBoardingConnection();\r
-\r
-                        conn.setConnectivity(true);\r
-                        conn.setIp(connectedDevice.getIpAddr());\r
-                        conn.setHardwareAddress(enrolleStatus.getHWAddr());\r
-                        conn.setDeviceName(enrolleStatus.getDevice());\r
-\r
-                        Log.d("ESSoftAPOnBoarding", "Entered" + finalResult);\r
-                        mOnBoardingCallback.onFinished(conn);\r
-                        return;\r
-\r
-                    }\r
-                }\r
-\r
-                IpOnBoardingConnection conn = new IpOnBoardingConnection();\r
-                conn.setConnectivity(false);\r
-                mOnBoardingCallback.onFinished(conn);\r
-            } else {\r
-                Log.e("ESSoftAPOnBoarding", "Device NOT in OnBoarding State. Ignoring the event");\r
-            }\r
-        }\r
-    };\r
-\r
-\r
-    protected EnrolleeDeviceWiFiOnboarding(Context context, OnBoardingConfig onBoardingConfig,\r
-                                           ProvisioningConfig provConfig) {\r
-        super(onBoardingConfig, provConfig);\r
-        mContext = context;\r
-        mWifiSoftAPManager = new WiFiSoftAPManager(mContext);\r
-    }\r
-\r
-    @Override\r
-    protected void startOnBoardingProcess() {\r
-        Log.i(TAG, "Starting on boarding process");\r
-\r
-        //1. Create Soft AP\r
-        boolean status = mWifiSoftAPManager.setWifiApEnabled((WifiConfiguration)\r
-                mOnBoardingConfig.getConfig(), true);\r
-\r
-        mState = EnrolleeState.DEVICE_ON_BOARDING_STATE;\r
-\r
-        Log.i(TAG, "Soft AP is created with status " + status);\r
-\r
-        myTimer = new Timer();\r
-        myTimer.schedule(new TimerTask() {\r
-            @Override\r
-            public void run() {\r
-                // Below function to be called after 5 seconds\r
-                mWifiSoftAPManager.getClientList(deviceScanListener, 300);\r
-            }\r
-\r
-        }, 0, 5000);\r
-    }\r
-\r
-    protected void stopOnBoardingProcess() {\r
-        Log.i(TAG, "Stopping on boarding process");\r
-        myTimer.cancel();\r
-        boolean status = mWifiSoftAPManager.setWifiApEnabled(null, false);\r
-        Log.i(TAG, "Soft AP is disabled with status " + status);\r
-    }\r
-\r
-    @Override\r
-    protected void startProvisioningProcess(OnBoardingConnection conn) {\r
-        try {\r
-            Log.i(TAG, "waiting for 20 seconds to start provisioning");\r
-            Thread.sleep(20000);//Sleep for allowing thin device to start the services\r
-        } catch (InterruptedException e) {\r
-            e.printStackTrace();\r
-        }\r
-\r
-        mState = EnrolleeState.DEVICE_PROVISIONING_STATE;\r
-        mProvisioningCallback.onProgress(this);\r
-        final EnrolleeDevice device = this;\r
-        if (mProvConfig.getConnType() == ProvisioningConfig.ConnType.WiFi) {\r
-\r
-            provisionEnrolleInstance = new ProvisionEnrollee(mContext);\r
-\r
-            provisionEnrolleInstance.registerProvisioningHandler(new IProvisioningListener() {\r
-                @Override\r
-                public void onFinishProvisioning(int statuscode) {\r
-\r
-                    Log.i(TAG, "Provisioning is finished with status code " + statuscode);\r
-                    mState = (statuscode == 0) ? EnrolleeState.DEVICE_PROVISIONED_STATE\r
-                            : EnrolleeState.DEVICE_INIT_STATE;\r
-                    stopOnBoardingProcess();\r
-                    mProvisioningCallback.onProgress(device);\r
-                    mProvisioningCallback.onFinished(EnrolleeDeviceWiFiOnboarding.this);\r
-                }\r
-            });\r
-\r
-            IpOnBoardingConnection connection = (IpOnBoardingConnection) conn;\r
-            WiFiProvConfig wifiProvConfig = (WiFiProvConfig) mProvConfig;\r
-\r
-            easySetupManagerNativeInstance = EasySetupManager.getInstance();\r
-            easySetupManagerNativeInstance.setApplicationContext(mContext);\r
-            easySetupManagerNativeInstance.initEasySetup();\r
-\r
-            // Native Api call to start provisioning of the enrolling device\r
-            easySetupManagerNativeInstance.provisionEnrollee(connection.getIp(), wifiProvConfig\r
-                    .getSsId(), wifiProvConfig.getPassword(), 1);\r
-        }\r
-    }\r
-}\r
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeState.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EnrolleeState.java
deleted file mode 100755 (executable)
index 7dcf602..0000000
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- * ***************************************************************
- * <p>
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- * <p>
- * <p>
- * <p>
- * 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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * 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.
- * <p>
- * ****************************************************************
- */
-
-package org.iotivity.service.easysetup.mediator;
-
-/**
- * It defines various states of the Enrollee device during easy setup process
- */
-
-public enum EnrolleeState {
-
-    /**
-     * Default state of the device
-     */
-    DEVICE_INIT_STATE,
-
-    /**
-     * Device will move to this state after successful on-boarding of the device
-     */
-    DEVICE_ON_BOARDED_STATE,
-
-    /**
-     * Device will move to this state once the on boarding begins
-     */
-    DEVICE_ON_BOARDING_STATE,
-
-    /**
-     * Device will move to this state once the on boarding is done
-     */
-    DEVICE_PROVISIONING_STATE,
-
-    /**
-     * Easy setup process is successful.
-     */
-    DEVICE_PROVISIONED_STATE,
-
-    /**
-     * This state is arbitrary one, any time device can come into this state
-     * Device will move to this state if the ownership transfer initiated  by the Application
-     */
-    DEVICE_OWNERSHIP_TRANSFERRING_STATE,
-
-    /**
-     * This state is arbitrary one, any time device can come into this state
-     * Device will move to this state if the ownership transfer is completed
-     */
-    DEVICE_OWNERSHIP_TRANSFERRED_STATE,
-
-
-    /**
-     * This state is arbitrary one, any time device can come into this state
-     * Device will move to this state once the Application factory reset the device
-     */
-    DEVICE_FACTORY_RESET_STATE,
-
-}
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/IpOnBoardingConnection.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/IpOnBoardingConnection.java
deleted file mode 100755 (executable)
index 259514d..0000000
+++ /dev/null
@@ -1,75 +0,0 @@
-/**\r
- * ***************************************************************\r
- * <p/>\r
- * Copyright 2015 Samsung Electronics All Rights Reserved.\r
- * <p/>\r
- * <p/>\r
- * <p/>\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
- * <p/>\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * <p/>\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
- * <p/>\r
- * ****************************************************************\r
- */\r
-\r
-package org.iotivity.service.easysetup.mediator;\r
-\r
-public class IpOnBoardingConnection implements OnBoardingConnection {\r
-\r
-    private boolean mIsConnected;\r
-    private String mIp;\r
-    private String mHardwareAddress;\r
-    private String mDeviceName;\r
-\r
-    public void setHardwareAddress(String address) {\r
-        mHardwareAddress = address;\r
-    }\r
-\r
-    public String getHardwareAddress() {\r
-        return mHardwareAddress;\r
-    }\r
-\r
-    public void setDeviceName(String name) {\r
-        mDeviceName = name;\r
-    }\r
-\r
-    public String getDeviceName() {\r
-        return mDeviceName;\r
-    }\r
-\r
-    public void setConnectivity(boolean connected) {\r
-        mIsConnected = connected;\r
-    }\r
-\r
-    public void setIp(String ip) {\r
-        mIp = ip;\r
-    }\r
-\r
-    public String getIp() {\r
-        return mIp;\r
-    }\r
-\r
-    @Override\r
-    public String getDesc() {\r
-        return "Description";\r
-    }\r
-\r
-    @Override\r
-    public boolean isConnected() {\r
-        return mIsConnected;\r
-    }\r
-\r
-    @Override\r
-    public Object getConnection() {\r
-        return this;\r
-    }\r
-\r
-}\r
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/OnBoardingCallback.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/OnBoardingCallback.java
deleted file mode 100755 (executable)
index 60705fb..0000000
+++ /dev/null
@@ -1,27 +0,0 @@
-/**\r
- * ***************************************************************\r
- * <p/>\r
- * Copyright 2015 Samsung Electronics All Rights Reserved.\r
- * <p/>\r
- * <p/>\r
- * <p/>\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
- * <p/>\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * <p/>\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
- * <p/>\r
- * ****************************************************************\r
- */\r
-\r
-package org.iotivity.service.easysetup.mediator;\r
-\r
-public abstract class OnBoardingCallback {\r
-    public abstract void onFinished(OnBoardingConnection connection);\r
-}\r
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/OnBoardingConfig.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/OnBoardingConfig.java
deleted file mode 100755 (executable)
index 6aacce9..0000000
+++ /dev/null
@@ -1,69 +0,0 @@
-/**\r
- * ***************************************************************\r
- * <p/>\r
- * Copyright 2015 Samsung Electronics All Rights Reserved.\r
- * <p/>\r
- * <p/>\r
- * <p/>\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
- * <p/>\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * <p/>\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
- * <p/>\r
- * ****************************************************************\r
- */\r
-\r
-package org.iotivity.service.easysetup.mediator;\r
-\r
-import org.iotivity.base.OcConnectivityType;\r
-\r
-/**\r
- * It contains configuration details about the connectivity type between the Enrollee device &\r
- * Mediator device in order to perform on-boarding.\r
- */\r
-\r
-public interface OnBoardingConfig {\r
-\r
-    /**\r
-     * It provides constants for connectivity types used for on-boarding Enrollee device\r
-     */\r
-    public static enum ConnType {\r
-        // Note : Enum Ids should matched with Native Ids\r
-        WiFi(OcConnectivityType.CT_DEFAULT.getValue()),\r
-        BLE(OcConnectivityType.CT_ADAPTER_GATT_BTLE.getValue());\r
-\r
-        private int mConnType;\r
-\r
-        ConnType(int connType) {\r
-            mConnType = connType;\r
-        }\r
-\r
-        public int getValue() {\r
-            return mConnType;\r
-        }\r
-\r
-    }\r
-\r
-    /**\r
-     * Gives configuration object specific to the on-boarding connectivity of the enrolling device.\r
-     *\r
-     * @return instance object of configuration according to connectivity type\r
-     */\r
-    public Object getConfig();\r
-\r
-    /**\r
-     * Gives connectivity type of on-boarding device\r
-     *\r
-     * @return on-boarding connectivity type\r
-     */\r
-    public ConnType getConnType();\r
-\r
-\r
-}\r
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/OnBoardingConnection.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/OnBoardingConnection.java
deleted file mode 100755 (executable)
index 622c693..0000000
+++ /dev/null
@@ -1,50 +0,0 @@
-/**\r
- * ***************************************************************\r
- * <p/>\r
- * Copyright 2015 Samsung Electronics All Rights Reserved.\r
- * <p/>\r
- * <p/>\r
- * <p/>\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
- * <p/>\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * <p/>\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
- * <p/>\r
- * ****************************************************************\r
- */\r
-package org.iotivity.service.easysetup.mediator;\r
-\r
-/**\r
- * This interface contains the connection details of the enrollee device\r
- */\r
-public interface OnBoardingConnection {\r
-\r
-    /**\r
-     * This method returns the implementation of the Connection\r
-     *\r
-     * @return implementation\r
-     */\r
-    public Object getConnection();\r
-\r
-    /**\r
-     * This method returns description on the connectivity.\r
-     *\r
-     * @return description\r
-     */\r
-    public String getDesc();\r
-\r
-    /**\r
-     * This method is used to know if the device is connected or not\r
-     *\r
-     * @return True if connected or False\r
-     */\r
-    public boolean isConnected();\r
-\r
-}\r
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ProvisioningConfig.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/ProvisioningConfig.java
deleted file mode 100755 (executable)
index 4c15217..0000000
+++ /dev/null
@@ -1,54 +0,0 @@
-/**
- * ***************************************************************
- * <p>
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- * <p>
- * <p>
- * <p>
- * 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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * 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.
- * <p>
- * ****************************************************************
- */
-
-package org.iotivity.service.easysetup.mediator;
-/**
- * It contains configuration details about the the target network where Enrollee device is
- * going to be enrolled.
- */
-public interface ProvisioningConfig {
-
-    /**
-     * It provides constants for connectivity types of target network
-     */
-    public static enum ConnType {
-        WiFi,
-        BT
-    }
-
-    /**
-     * Gives the instance of the configuration object created according to the connectivity
-     * type of target network.
-     *
-     * @return instance object of configuration according to connectivity type of target network
-     */
-    Object getConfig();
-
-
-    /**
-     * Gives connectivity type of target network
-     *
-     * @return Connectivity type of target network
-     */
-    ConnType getConnType();
-
-}
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/WiFiOnBoardingConfig.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/WiFiOnBoardingConfig.java
deleted file mode 100755 (executable)
index 2477938..0000000
+++ /dev/null
@@ -1,64 +0,0 @@
-/**\r
- * ***************************************************************\r
- * <p/>\r
- * Copyright 2015 Samsung Electronics All Rights Reserved.\r
- * <p/>\r
- * <p/>\r
- * <p/>\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
- * <p/>\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * <p/>\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
- * <p/>\r
- * ****************************************************************\r
- */\r
-\r
-package org.iotivity.service.easysetup.mediator;\r
-\r
-import org.iotivity.service.easysetup.mediator.OnBoardingConfig;\r
-\r
-import android.net.wifi.WifiConfiguration;\r
-\r
-/**\r
- * This class contains on boarding configuration information for Soft AP on boarding connectivity.\r
- * It implements OnBoardingConfig interface & provide implementation for WiFi Soft AP connectivity.\r
- */\r
-\r
-public class WiFiOnBoardingConfig implements OnBoardingConfig {\r
-\r
-    private final WifiConfiguration config = new WifiConfiguration();\r
-    private final ConnType mConnType = OnBoardingConfig.ConnType.WiFi;\r
-\r
-    @Override\r
-    public Object getConfig() {\r
-        return config;\r
-    }\r
-\r
-    public void setSSId(String ssid) {\r
-        config.SSID = ssid;\r
-    }\r
-\r
-    public void setSharedKey(String sharedKey) {\r
-        config.preSharedKey = sharedKey;\r
-    }\r
-\r
-    public void setAuthAlgo(int aurthAlgo) {\r
-        config.allowedAuthAlgorithms.set(aurthAlgo);\r
-    }\r
-\r
-    public void setKms(int kms) {\r
-        config.allowedKeyManagement.set(kms);\r
-    }\r
-\r
-    @Override\r
-    public ConnType getConnType() {\r
-        return mConnType;\r
-    }\r
-}\r
diff --git a/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/WiFiProvConfig.java b/service/easy-setup/sdk/mediator/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/WiFiProvConfig.java
deleted file mode 100755 (executable)
index c7e6359..0000000
+++ /dev/null
@@ -1,69 +0,0 @@
-/**
- * ***************************************************************
- * <p>
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- * <p>
- * <p>
- * <p>
- * 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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * 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.
- * <p>
- * ****************************************************************
- */
-
-package org.iotivity.service.easysetup.mediator;
-
-import org.iotivity.service.easysetup.mediator.ProvisioningConfig;
-
-/**
- * This class contains on provisioning configuration information for for target network.
- * It implements ProvisioningConfig interface and provide configuration object specific to WiFi target network
- */
-public class WiFiProvConfig implements ProvisioningConfig {
-
-    private final ConnType mConnType = ProvisioningConfig.ConnType.WiFi;
-
-    private final String mSsId;
-    private final String mPassword;
-
-    public WiFiProvConfig(String ssid, String pass) {
-        mSsId = ssid;
-        mPassword = pass;
-    }
-
-    @Override
-    public Object getConfig() {
-        return this;
-    }
-
-    @Override
-    public ConnType getConnType() {
-        return mConnType;
-    }
-
-    /**
-     * This method returns the SSID of the Target WIFI network
-     * @return SSID of Target Network
-     */
-    public String getSsId() {
-        return mSsId;
-    }
-
-    /**
-     * This method returns the password of the Target WIFI network
-     * @return password of Target Network
-     */
-    public String getPassword() {
-        return mPassword;
-    }
-
-}
diff --git a/service/easy-setup/sdk/mediator/android/jni/Android.mk b/service/easy-setup/sdk/mediator/android/jni/Android.mk
deleted file mode 100644 (file)
index 0e87f2a..0000000
+++ /dev/null
@@ -1,85 +0,0 @@
-LOCAL_PATH := $(call my-dir)
-
-ifeq ($(strip $(ANDROID_NDK)),)
-$(error ANDROID_NDK is not set!)
-endif
-
-$(warning "Current path" $(LOCAL_PATH))
-$(info TC_PREFIX=$(TOOLCHAIN_PREFIX))
-$(info CFLAGS=$(TARGET_CFLAGS))
-$(info CXXFLAGS=$(TARGET_CXXFLAGS) $(TARGET_NO_EXECUTE_CFLAGS))
-$(info CPPFLAGS=$(TARGET_CPPFLAGS))
-$(info CPPPATH=$(TARGET_C_INCLUDES) $(__ndk_modules.$(APP_STL).EXPORT_C_INCLUDES))
-$(info SYSROOT=$(SYSROOT_LINK))
-$(info LDFLAGS=$(TARGET_LDFLAGS) $(TARGET_NO_EXECUTE_LDFLAGS) $(TARGET_NO_UNDEFINED_LDFLAGS) $(TARGET_RELRO_LDFLAGS))
-$(info TC_VER=$(TOOLCHAIN_VERSION))
-$(info PLATFORM=$(APP_PLATFORM))
-
-include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../../../out/android/$(TARGET_ARCH_ABI)/debug
-LOCAL_MODULE := android-octbstack
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboctbstack.so
-include $(PREBUILT_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../../../out/android/$(TARGET_ARCH_ABI)/debug
-LOCAL_MODULE := android-connectivity_abstraction
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libconnectivity_abstraction.so
-include $(PREBUILT_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../../../out/android/$(TARGET_ARCH_ABI)/debug
-LOCAL_MODULE := android-easysetup
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libESSDK.a
-include $(PREBUILT_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE    := easysetup-jni
-
-#Add Pre processor definitions
-DEFINE_FLAG =  -DWITH_POSIX -D__ANDROID__
-
-#Add Debug flags here
-DEBUG_FLAG      = -DTB_LOG
-
-BUILD_FLAG = $(DEFINE_FLAG) $(DEBUG_FLAG)
-
-LOCAL_CPPFLAGS = $(BUILD_FLAG)
-LOCAL_CPPFLAGS += -std=c++0x -frtti -fexceptions
-
-$(info CPPFLAGSUPDATED=$(LOCAL_CPPFLAGS))
-
-NDK_ROOT         := /home/madan/android-ndk-r10d
-
-LOCAL_C_INCLUDES := $(LOCAL_PATH) \
-                                       $(LOCAL_PATH)/jniutil/inc \
-                                       $(LOCAL_PATH)/../../../../../../service/easy-setup/sdk/mediator/inc \
-                                       $(LOCAL_PATH)/../../../../../../service/easy-setup/sdk/common \
-                                       $(LOCAL_PATH)/../../../../../../resource/csdk/logger/include \
-                                       $(LOCAL_PATH)/../../../../../../resource/csdk/connectivity/common/inc \
-                                       $(LOCAL_PATH)/../../../../../../resource/include \
-                                       $(LOCAL_PATH)/../../../../../../resource/c_common \
-                                       $(LOCAL_PATH)/../../../../../../resource/oc_logger/include \
-                                       $(LOCAL_PATH)/../../../../../../resource/csdk/ocmalloc/include \
-                                       $(LOCAL_PATH)/../../../../../../resource/csdk/connectivity/api \
-                                       $(LOCAL_PATH)/../../../../../../resource/csdk/stack/include \
-                                       $(LOCAL_PATH)/../../../../../../resource/csdk/logger/include \
-                                       $(LOCAL_PATH)/../../../../../../resource/csdk/security/include \
-                                       $(LOCAL_PATH)/../../../../../../extlibs/cjson \
-                                       $(LOCAL_PATH)/../../../../../../extlibs/boost/boost_1_58_0 \
-                    $(LOCAL_PATH)/../../../../../../extlibs/timer \
-                                       $(LOCAL_PATH)/../../../../../../android/android_api/base/jni \
-                                       $(NDK_ROOT)/sources/cxx-stl/gnu-libstdc++/$(TOOLCHAIN_VERSION)/include \
-                    $(NDK_ROOT)/sources/cxx-stl/gnu-libstdc++/$(TOOLCHAIN_VERSION)/libs/$(TARGET_ARCH_ABI)/include \
-                                       
-LOCAL_SRC_FILES += $(patsubst $(LOCAL_PATH)/%, %, $(wildcard $(LOCAL_PATH)/jni_easy_setup.cpp))
-LOCAL_SRC_FILES += $(patsubst $(LOCAL_PATH)/%, %, $(wildcard $(LOCAL_PATH)/jniutil/src/*.cpp))
-
-LOCAL_LDLIBS := -llog 
-LOCAL_LDLIBS += -L$(NDK_ROOT)/sources/cxx-stl/gnu-libstdc++/$(TOOLCHAIN_VERSION)/libs/$(TARGET_ARCH_ABI)
-LOCAL_SHARED_LIBRARIES := android-easysetup
-LOCAL_SHARED_LIBRARIES += android-connectivity_abstraction
-LOCAL_SHARED_LIBRARIES += android-octbstack
-
-include $(BUILD_SHARED_LIBRARY)
\ No newline at end of file
diff --git a/service/easy-setup/sdk/mediator/android/jni/jni_easy_setup.cpp b/service/easy-setup/sdk/mediator/android/jni/jni_easy_setup.cpp
deleted file mode 100644 (file)
index b704de5..0000000
+++ /dev/null
@@ -1,191 +0,0 @@
-//******************************************************************
-//
-// 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 "jni_easy_setup.h"
-
-#include "jni_easy_setup_jvm.h"
-#include "prov_adapter.h"
-
-void JNIProvisioningStatusCallback(ProvisioningInfo * provInfo) {
-       JNIEnv *env = EasySetupJVM::getEnv();
-       if (env == NULL) {
-               LOGE("JNIProvisioningStatusCallback : Getting JNIEnv failed");
-               return;
-       }
-
-       // Get EasySetupHandler class reference
-       jclass easysetupCallbacks = GetJClass(
-                       EASY_SETUP_SERVICE_CALLBACK_NATIVE_API_CLASS_PATH);
-       if (NULL == easysetupCallbacks) {
-               LOGE(
-                               "JNIProvisioningStatusCallback : GetJClass easysetupCallbacks failed");
-               EasySetupJVM::releaseEnv();
-               return;
-       }
-
-       // Get the easysetupCallback class instance
-       jobject jobjectCallback = GetJObjectInstance(
-                       EASY_SETUP_SERVICE_CALLBACK_NATIVE_API_CLASS_PATH);
-       if (NULL == jobjectCallback) {
-               LOGE("getInstance( %s) failed!",
-                               EASY_SETUP_SERVICE_CALLBACK_NATIVE_API_CLASS_PATH);
-               EasySetupJVM::releaseEnv();
-               return;
-       }
-
-       // Get onResourceCallback method reference
-       jmethodID method_id = env->GetMethodID(easysetupCallbacks,
-                       "ProvisioningStatusCallBack",
-                       METHOD_PROVISIONING_STATUS_INTEGER_CALLBACK);
-       if (NULL == method_id) {
-               LOGE(
-                               "JNIProvisioningStatusCallback: onResourceCallback : GetMethodID failed");
-               EasySetupJVM::releaseEnv();
-               return;
-       }
-
-       if ((env)->ExceptionCheck()) {
-               LOGE("JNIProvisioningStatusCallback : ExceptionCheck failed");
-               EasySetupJVM::releaseEnv();
-               return;
-       }
-
-       if (NULL == method_id) {
-               LOGI("JNI method_id is NULL");
-       } else {
-               LOGI("JNI method_id is VALID");
-
-               jint result;
-               if (provInfo->provStatus == DEVICE_PROVISIONED) {
-                       result = 0;
-               } else {
-                       result = -1;
-               }
-
-               env->CallVoidMethod(jobjectCallback, method_id, (jint) result);
-       }
-
-       EasySetupJVM::releaseEnv();
-}
-
-JNIEXPORT void JNICALL
-JNIInitEasySetup(JNIEnv
-               *env,
-               jobject thisObj
-)
-{
-       LOGI("JNI JNIInitEasySetup: Enter");
-
-       InitProvProcess();
-
-       RegisterCallback(JNIProvisioningStatusCallback);
-}
-
-JNIEXPORT void JNICALL
-JNITerminateEasySetup(JNIEnv
-               *env,
-               jobject thisObj
-)
-{
-       LOGI("JNI JNITerminateEasySetup: Enter");
-
-       ResetProvProcess();
-
-}
-
-JNIEXPORT void JNICALL
-JNIProvisionEnrollee(JNIEnv
-               *env,
-               jobject thisObj,
-               jstring
-               jIPAddress,
-               jstring jNetSSID,
-               jstring
-               jNetPWD,
-               jint jConnectivityType
-)
-{
-       LOGI("JNI JNIProvisionEnrollee: Enter");
-
-       if (!jIPAddress)
-       {
-               LOGE("JNI JNIProvisionEnrollee : jIPAddress is NULL!");
-               return;
-       }
-
-       const char *ipAddress = env->GetStringUTFChars(jIPAddress, NULL);
-       if (NULL == ipAddress)
-       {
-               LOGE("JNI JNIProvisionEnrollee : Failed to convert jstring to char string!");
-       }
-
-       LOGI("JNI JNIProvisionEnrollee : ipAddress is : %s",ipAddress);
-
-       const char *netSSID = env->GetStringUTFChars(jNetSSID, NULL);
-       if (NULL == netSSID)
-       {
-               LOGE("JNI JNIProvisionEnrollee : Failed to convert jstring to char string!");
-       }
-
-       LOGI("JNI JNIProvisionEnrollee : netSSID is : %s",netSSID);
-
-       const char *netPWD = env->GetStringUTFChars(jNetPWD, NULL);
-       if (NULL == netPWD)
-       {
-               LOGE("JNI JNIProvisionEnrollee : Failed to convert jstring to char string!");
-       }
-
-       LOGI("JNI JNIProvisionEnrollee : netPWD is : %s",netPWD);
-
-       OCConnectivityType connecitivityType;
-       EnrolleeNWProvInfo_t netInfo =
-       {       0};
-       strncpy(netInfo
-                       .netAddressInfo.WIFI.ipAddress, ipAddress, IPV4_ADDR_SIZE-1);
-       strncpy(netInfo
-                       .netAddressInfo.WIFI.ssid, netSSID, NET_WIFI_SSID_SIZE-1);
-       strncpy(netInfo
-                       .netAddressInfo.WIFI.pwd, netPWD, NET_WIFI_PWD_SIZE-1);
-       netInfo.
-       connType = (OCConnectivityType) jConnectivityType;
-
-       netInfo.
-       isSecured = true;
-
-       StartProvisioning(&netInfo);
-
-       return;
-}
-
-JNIEXPORT void JNICALL
-JNIStopEnrolleeProvisioning(JNIEnv
-               *env,
-               jobject thisObj,
-               jint
-               jConnectivityType)
-{
-       LOGI("JNI Stop Easy Setup: Entering");
-
-       StopProvisioning((OCConnectivityType)
-                       jConnectivityType);
-
-       return;
-}
-
diff --git a/service/easy-setup/sdk/mediator/android/jni/jni_easy_setup.h b/service/easy-setup/sdk/mediator/android/jni/jni_easy_setup.h
deleted file mode 100644 (file)
index a69d657..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-/* DO NOT EDIT THIS FILE - it is machine generated */\r
-#include <stdio.h>\r
-#include <string.h>\r
-\r
-#include <jni.h>\r
-#include <jni_string.h>\r
-\r
-#include "JniOcStack.h"\r
-\r
-#define METHOD_PROVISIONING_STATUS_VOID_CALLBACK    "("")V"\r
-#define METHOD_PROVISIONING_STATUS_INTEGER_CALLBACK    "("EASY_SETUP_JAVA_INTEGER_TYPE")V"\r
-\r
-/* Header for class org_iotivity_service_easyconnect_java_EasySetupHandler */\r
-\r
-#ifndef _Included_org_iotivity_service_easysetup_java_EasySetupHandler\r
-#define _Included_org_iotivity_service_easysetup_java_EasySetupHandler\r
-\r
-#ifdef __cplusplus\r
-extern "C" {\r
-#endif\r
-\r
-JNIEXPORT void JNICALL JNIInitEasySetup(JNIEnv *env, jobject thisObj);\r
-JNIEXPORT void JNICALL JNITerminateEasySetup(JNIEnv *env, jobject thisObj);\r
-\r
-/*\r
- * Class:     org_iotivity_service_easyconnect_java_EasySetupHandler\r
- * Method:    JNIProvisionEnrollee\r
- * Signature: ()V\r
- */\r
-JNIEXPORT void JNICALL JNIProvisionEnrollee(JNIEnv *env, jobject ,\r
-                                                jstring ,\r
-                                                jstring ,\r
-                                                jstring ,\r
-                                                jint jConnectivityType);\r
-\r
-JNIEXPORT void JNICALL JNIStopEnrolleeProvisioning(JNIEnv *, jobject, jint);\r
-\r
-\r
-#ifdef __cplusplus\r
-}\r
-#endif\r
-#endif\r
diff --git a/service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_easy_setup_jvm.h b/service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_easy_setup_jvm.h
deleted file mode 100755 (executable)
index 5997851..0000000
+++ /dev/null
@@ -1,94 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-/**
- * @file   jni_easy_setup_jvm.h
- *
- * @brief  This file contains the essential declarations and functions required
- *            for JNI implementation
- */
-
-#ifndef __JNI_EASY_SETUP_JVM_H_
-#define __JNI_EASY_SETUP_JVM_H_
-
-#include <jni.h>
-#include <thread>
-#include <mutex>
-
-#define EASY_SETUP_SERVICE_NATIVE_API_CLASS_PATH    "org/iotivity/service/easysetup/core/EasySetupManager"
-#define EASY_SETUP_SERVICE_NATIVE_API_CLASS_TYPE    "Lorg/iotivity/service/easysetup/core/EasySetupManager;"
-#define EASY_SETUP_SERVICE_CALLBACK_NATIVE_API_CLASS_PATH    "org/iotivity/service/easysetup/core/EasySetupCallbackHandler"
-#define EASY_SETUP_SERVICE_CALLBACK_NATIVE_API_CLASS_TYPE    "Lorg/iotivity/service/easysetup/core/EasySetupCallbackHandler;"
-
-#define EASY_SETUP_JAVA_STRING_TYPE "Ljava/lang/String;"
-#define EASY_SETUP_JAVA_INTEGER_TYPE "I"
-
-/**
- * @class   EasySetupJVM
- * @brief   This class provides functions related to JNI Environment.
- *
- */
-class EasySetupJVM {
-public:
-    /**
-     * @brief destructor
-     */
-    ~EasySetupJVM() {
-    }
-    ;
-
-    /**
-     * @brief  Get JVM instance
-     */
-    static JNIEnv *getEnv();
-
-    /**
-     * @brief  Release aquired JVM instance
-     */
-    static void releaseEnv();
-
-public:
-    /**
-     *  Java VM pointer
-     */
-    static JavaVM *m_jvm;
-
-private:
-    /**
-     * @brief constructor
-     */
-    EasySetupJVM();
-
-    /**
-     *  Mutex for thread synchronization
-     */
-    static std::mutex m_currentThreadMutex;
-};
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-jclass GetJClass(const char *szClassPath);
-jobject GetJObjectInstance(const char *szClassPath);
-#ifdef __cplusplus
-}
-#endif
-#endif //__JNI_EASY_SETUP_JVM_H_
-
diff --git a/service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_getter.h b/service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_getter.h
deleted file mode 100644 (file)
index fe92a82..0000000
+++ /dev/null
@@ -1,111 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-/**
- * @file   jni_getter.h
- *
- * @brief  This file contains the JGetter class  declarations and its functions required
- *            for getting and setting basic data types in C++ and Java
- */
-
-#ifndef __JNI_GETTER_H_
-#define __JNI_GETTER_H_
-
-#include <string>
-#include <jni.h>
-
-/**
- * @class   JGetter
- * @brief  This class provide utility for get/set basic data types in C++ and Java
- *
- */
-class JGetter {
-public:
-       /**
-        * This function is called to get String field from the C++ object
-        *
-        * @param env
-        *           JNI Environment reference
-        * @param object
-        *           JObject from which string field is expected
-        * @param fieldName
-        *           Name of the field to be extracted from JObject
-        * @param value
-        *         reference to string value mentioned in fieldName
-        *
-        * @return returns true on success and false on failer.
-        */
-       static bool getJStringField(JNIEnv *env, jobject &object,
-                       const char *fieldName, std::string &value);
-
-       /**
-        * This function is called to get Boolean field from the C++ object
-        *
-        * @param env
-        *           JNI Environment reference
-        * @param object
-        *           JObject from which boolean field is expected
-        * @param fieldName
-        *           Name of the field to be extracted from JObject
-        * @param value
-        *         reference to boolean value mentioned in fieldName
-        *
-        * @return returns true on success and false on failer.
-        */
-       static bool getJBoolField(JNIEnv *env, jobject &object,
-                       const char *fieldName, bool &value);
-
-       /**
-        * This function is called to get Integer field from the C++ object
-        *
-        * @param env
-        *           JNI Environment reference
-        * @param object
-        *           JObject from which integer field is expected
-        * @param fieldName
-        *           Name of the field to be extracted from JObject
-        * @param value
-        *         reference to integer value mentioned in fieldName
-        *
-        * @return returns true on success and false on failer.
-        */
-       static bool getJIntField(JNIEnv *env, jobject &object,
-                       const char *fieldName, int &value);
-
-       /**
-        * This function is called to get Object reference from the C++ object
-        *
-        * @param env
-        *           JNI Environment reference
-        * @param object
-        *           JObject from which Object reference is expected
-        * @param fieldName
-        *           Name of the field to be extracted from JObject
-        * @param fieldType
-        *           Type of the field to be extracted from JObject
-        * @param value
-        *         reference to Object reference mentioned in fieldName
-        *
-        * @return returns true on success and false on failer.
-        */
-       static bool getJObjectField(JNIEnv *env, jobject &object,
-                       const char *fieldName, const char *fieldType, jobject &value);
-};
-#endif //__JNI_GETTER_H_
diff --git a/service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_object.h b/service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_object.h
deleted file mode 100644 (file)
index 5f27a47..0000000
+++ /dev/null
@@ -1,96 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-/**
- * @file   jni_object.h
- *
- * @brief  This file contains the JObject class  declarations and its functions required
- *            for getting and setting basic data types in C++ and Java
- */
-
-#ifndef __JNI_OBJECT_H_
-#define __JNI_OBJECT_H_
-
-#include <jni.h>
-#include "JniOcResource.h"
-
-/**
- * @class   JObject
- * @brief   This class provides a set of functions for JNI object.
- *
- */
-class JObject {
-public:
-       /**
-        * @brief constructor
-        */
-       JObject(JNIEnv *env);
-
-       /**
-        * @brief constructor
-        */
-       JObject(JNIEnv *env, jobject obj);
-
-       /**
-        * @brief constructor
-        */
-       JObject(JNIEnv *env, const char *classPath);
-
-       /**
-        * @brief destructor
-        *
-        */
-       virtual ~JObject();
-
-       /**
-        * Function to get the jobject.
-        *
-        * @return jobject, returns a new JNI object or NULL otherwise.
-        *
-        */
-       virtual jobject getObject() const;
-
-       /**
-        * Function to detach the jobject.
-        *
-        * @return void
-        *
-        */
-       void detachObject();
-
-protected:
-       /**
-        *  JNI Environment Pointer
-        */
-       JNIEnv *m_pEnv;
-       /**
-        *  Java Object
-        */
-       jobject m_pObject;
-       /**
-        *  Java Class
-        */
-       jclass m_pClazz;
-       /**
-        *  Boolean variable to check if an object is new
-        */
-       bool m_fIsNewObject;
-};
-#endif //__JNI_OBJECT_H_
diff --git a/service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_setter.h b/service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_setter.h
deleted file mode 100644 (file)
index c4593cc..0000000
+++ /dev/null
@@ -1,128 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-/**
- * @file   jni_setter.h
- *
- * @brief  This file contains the JSetter class declarations and and its functions required
- *            to set data types in C++ object from Java object
- */
-
-#ifndef __JNI_SETTER_H_
-#define __JNI_SETTER_H_
-
-#include <jni.h>
-
-/**
- * @class   JSetter
- * @brief  This class provide utility to set data types in C++ object from Java object
- *
- */
-class JSetter {
-public:
-
-       /**
-        * This function is called to set Integer field in to C++ object.
-        *
-        * @param env
-        *           JNI Environment reference
-        * @param object
-        *           JObject to which integer field will be set.
-        * @param fieldName
-        *           Name of the field to be set in JObject
-        * @param value
-        *         integer value mentioned in fieldName
-        *
-        * @return returns true on success and false on failer.
-        */
-       static bool setJIntField(JNIEnv *env, jobject &object,
-                       const char *fieldName, int value);
-
-       /**
-        * This function is called to set Long field in to C++ object.
-        *
-        * @param env
-        *           JNI Environment reference
-        * @param object
-        *           JObject to which Long field will be set.
-        * @param fieldName
-        *           Name of the field to be set in JObject
-        * @param value
-        *         Long value mentioned in fieldName
-        *
-        * @return returns true on success and false on failer.
-        */
-       static bool setJLongField(JNIEnv *env, jobject &object,
-                       const char *fieldName, jlong value);
-
-       /**
-        * This function is called to Set Boolean field to C++ object
-        *
-        * @param env
-        *           JNI Environment reference
-        * @param object
-        *           JObject to which boolean field has to be set
-        * @param fieldName
-        *           Name of the field to be set in JObject
-        * @param value
-        *         boolean value mentioned in fieldName
-        *
-        * @return returns true on success and false on failer.
-        */
-       static bool setJBoolField(JNIEnv *env, jobject &object,
-                       const char *fieldName, bool value);
-       /**
-        * This function is called to Set String field from the C++ object
-        *
-        * @param env
-        *           JNI Environment reference
-        * @param object
-        *           JObject in which string value has to be set
-        * @param fieldName
-        *           Name of the field to be set in JObject
-        * @param value
-        *         string value mentioned in fieldName
-        *
-        * @return returns true on success and false on failer.
-        */
-       static bool setJStringField(JNIEnv *env, jobject &object,
-                       const char *fieldName, const char *value);
-
-       /**
-        * This function is called to set Object reference in C++ object.
-        *
-        * @param env
-        *           JNI Environment reference
-        * @param object
-        *           JObject to which Object reference is to be set.
-        * @param fieldName
-        *           Name of the field to be set in JObject
-        * @param fieldType
-        *           Type of the field to be set in JObject
-        * @param value
-        *         value of Object mentioned in fieldName
-        *
-        * @return returns true on success and false on failer.
-        */
-       static bool setJObjectField(JNIEnv *env, jobject &object,
-                       const char *fieldName, const char *fieldType, const jobject value);
-};
-
-#endif //__JNI_SETTER_H_
diff --git a/service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_string.h b/service/easy-setup/sdk/mediator/android/jni/jniutil/inc/jni_string.h
deleted file mode 100644 (file)
index 358e869..0000000
+++ /dev/null
@@ -1,80 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-/**
- * @file   jni_string.h
- *
- * @brief  This file contains the declaration of JString class and its members related to JString.
- *
- */
-
-#ifndef __JNI_STRING_H_
-#define __JNI_STRING_H_
-
-#include <string>
-
-#include "jni_object.h"
-
-/**
- * @class   JString
- * @brief   This class inherits JObject class and provides a set of functions for JNI String.
- *
- */
-class JString: public JObject {
-public:
-       /**
-        * @brief constructor
-        */
-       JString(JNIEnv *env, jstring value);
-       /**
-        * @brief constructor
-        */
-       JString(JNIEnv *env, const char *value);
-       /**
-        * @brief constructor
-        */
-       JString(JNIEnv *env, const std::string &value);
-       /**
-        * @brief destructor
-        */
-       ~JString();
-
-       /**
-        * Function to get the string value and set it.
-        *
-        * @param value - String value to set to a private member variable.
-        *
-        * @return bool - true on success
-        *
-        */
-       bool getValue(std::string &value);
-
-       /**
-        * Function to get the private string value.
-        *
-        * @return  C String value.
-        *
-        */
-       const char *c_str();
-
-private:
-       std::string m_cstr;
-};
-#endif //__JNI_STRING_H_
diff --git a/service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_easy_setup_jvm.cpp b/service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_easy_setup_jvm.cpp
deleted file mode 100644 (file)
index 6c33f95..0000000
+++ /dev/null
@@ -1,319 +0,0 @@
-/******************************************************************
- *
- * 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 "jni_easy_setup_jvm.h"
-#include <string>
-#include "jni_easy_setup.h"
-
-/**
- * @class   JClassMap
- * @brief   This class provides functions for initializing the Java class path and Java class.
- *
- */
-class JClassMap {
-public:
-    /**
-     *  Java Class
-     */
-    jclass classRef;
-    /**
-     *  Java Class Path
-     */
-    const char *szClassPath;
-
-    /**
-     * @brief constructor
-     */
-    JClassMap(const char *path) :
-            classRef(NULL) {
-        szClassPath = path;
-    }
-};
-
-/**
- * @class   JObjectMap
- * @brief   This class provides functins for initializing the Java Class path and Java Class
- * Object.
- *
- */
-class JObjectMap {
-public:
-    /**
-     *  Java Object
-     */
-    jobject object;
-    /**
-     *  Java Class Path
-     */
-    const char *szClassPath;
-
-    /**
-     * @brief constructor
-     */
-    JObjectMap(const char *path) :
-            object(NULL) {
-        szClassPath = path;
-    }
-};
-
-static JClassMap gJClassMapArray[] = { JClassMap(
-        EASY_SETUP_SERVICE_NATIVE_API_CLASS_PATH), JClassMap(
-        EASY_SETUP_SERVICE_CALLBACK_NATIVE_API_CLASS_PATH) };
-
-static JObjectMap gJObjectMapArray[] = { JObjectMap(
-        EASY_SETUP_SERVICE_CALLBACK_NATIVE_API_CLASS_PATH) };
-
-static JNINativeMethod gEasySetupMethodTable[] = {
-    { "InitEasySetup", "()V", (void *) JNIInitEasySetup },
-    { "TerminateEasySetup", "()V", (void *) JNITerminateEasySetup },
-    { "ProvisionEnrollee", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V",
-                                (void *) JNIProvisionEnrollee },
-    { "StopEnrolleeProvisioning", "(I)V", (void *) JNIStopEnrolleeProvisioning }, };
-
-static int gEasySetupMethodTableSize = sizeof(gEasySetupMethodTable)
-        / sizeof(gEasySetupMethodTable[0]);
-
-int InitializeJClassMapArray(JNIEnv *env) {
-    LOGI("InitializeJClassMapArray: Enter");
-
-    unsigned int nLen = sizeof(gJClassMapArray) / sizeof(JClassMap);
-
-    for (unsigned int i = 0; i < nLen; i++) {
-        jclass classRef = env->FindClass(gJClassMapArray[i].szClassPath);
-        if (NULL == classRef) {
-            LOGE("FindClass failed for [%s]", gJClassMapArray[i].szClassPath);
-            return -1;
-        }
-        gJClassMapArray[i].classRef = (jclass) env->NewGlobalRef(classRef);
-        env->DeleteLocalRef(classRef);
-    }
-
-    LOGI("InitializeJClassMapArray: Exit");
-    return 0;
-}
-
-jclass GetJClass(const char *szClassPath) {
-    unsigned int nLen = sizeof(gJClassMapArray) / sizeof(JClassMap);
-
-    jclass classRef = NULL;
-
-    for (unsigned int i = 0; i < nLen; i++) {
-        if (0 == strcmp(gJClassMapArray[i].szClassPath, szClassPath)) {
-            classRef = gJClassMapArray[i].classRef;
-            break;
-        }
-    }
-
-    return classRef;
-}
-
-void DeleteClassMapArray(JNIEnv *env) {
-    LOGI("DeleteClassMapArray: Enter");
-
-    unsigned int nLen = sizeof(gJClassMapArray) / sizeof(JClassMap);
-    for (unsigned int i = 0; i < nLen; i++) {
-        if (NULL != gJClassMapArray[i].classRef) {
-            env->DeleteGlobalRef(gJClassMapArray[i].classRef);
-            gJClassMapArray[i].classRef = NULL;
-        }
-    }
-
-    LOGI("DeleteClassMapArray: Exit");
-}
-
-int InitializeJObjectMapArray(JNIEnv *env) {
-    LOGI("InitializeJObjectMapArray: Enter");
-
-    unsigned int nLen = sizeof(gJObjectMapArray) / sizeof(JObjectMap);
-
-    for (unsigned int i = 0; i < nLen; i++) {
-        jclass classRef = env->FindClass(gJObjectMapArray[i].szClassPath);
-        if (NULL == classRef) {
-            LOGE("InitializeJObjectMapArray: FindClass failed for [%s]",
-                    gJObjectMapArray[i].szClassPath);
-            return -1;
-        }
-
-        std::string methodSignature = "()L";
-        methodSignature.append(gJObjectMapArray[i].szClassPath);
-        methodSignature.append(";");
-
-        // Get the object form "getInstance"
-        jmethodID methodid = env->GetStaticMethodID(classRef, "getInstance",
-                methodSignature.c_str());
-        if (NULL == methodid) {
-            LOGE("InitializeJObjectMapArray: GetStaticMethodID failed for [%s]",
-                    gJObjectMapArray[i].szClassPath);
-            return -1;
-        }
-
-        // Get the singleton object
-        jobject objectRef = (jobject) env->CallStaticObjectMethod(classRef,
-                methodid);
-        if (NULL == objectRef) {
-            LOGE(
-                    "InitializeJObjectMapArray: CallStaticObjectMethod failed for [%s]",
-                    gJObjectMapArray[i].szClassPath);
-            return -1;
-        }
-
-        gJObjectMapArray[i].object = (jobject) env->NewGlobalRef(objectRef);
-        env->DeleteLocalRef(classRef);
-    }
-
-    LOGI("InitializeJObjectMapArray: Exit");
-    return 0;
-}
-
-jobject GetJObjectInstance(const char *szClassPath) {
-    unsigned int nLen = sizeof(gJObjectMapArray) / sizeof(JObjectMap);
-
-    jobject object = NULL;
-
-    for (unsigned int i = 0; i < nLen; i++) {
-        if (0 == strcmp(gJObjectMapArray[i].szClassPath, szClassPath)) {
-            object = gJObjectMapArray[i].object;
-            break;
-        }
-    }
-
-    return object;
-}
-
-void DeleteObjectMapArray(JNIEnv *env) {
-    LOGI("DeleteObjectMapArray: Enter");
-
-    unsigned int nLen = sizeof(gJObjectMapArray) / sizeof(JObjectMap);
-    for (unsigned int i = 0; i < nLen; i++) {
-        if (NULL != gJObjectMapArray[i].object) {
-            env->DeleteGlobalRef(gJObjectMapArray[i].object);
-            gJObjectMapArray[i].object = NULL;
-        }
-    }
-
-    LOGI("DeleteObjectMapArray: Exit");
-}
-
-JavaVM *EasySetupJVM::m_jvm = NULL;
-std::mutex EasySetupJVM::m_currentThreadMutex;
-JNIEnv *EasySetupJVM::getEnv() {
-    std::unique_lock < std::mutex > scoped_lock(m_currentThreadMutex);
-
-    if (NULL == m_jvm) {
-        LOGE("Failed to get JVM");
-        return NULL;
-    }
-
-    JNIEnv *env = NULL;
-    jint ret = m_jvm->GetEnv((void **) &env, JNI_CURRENT_VERSION);
-    switch (ret) {
-    case JNI_OK:
-        return env;
-    case JNI_EDETACHED:
-        if (0 > m_jvm->AttachCurrentThread(&env, NULL)) {
-            LOGE("Failed to attach current thread to env");
-            return NULL;
-        }
-        return env;
-    case JNI_EVERSION:
-        LOGE("JNI version not supported");
-        return NULL;
-    default:
-        LOGE("Failed to get the environment");
-        return NULL;
-    }
-}
-
-void EasySetupJVM::releaseEnv() {
-    std::unique_lock < std::mutex > scoped_lock(m_currentThreadMutex);
-
-    if (0 == m_jvm) {
-        LOGE("Failed to release JVM");
-        return;
-    }
-
-    m_jvm->DetachCurrentThread();
-}
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
-    LOGD("JNI_OnLoad: Enter");
-
-    if (!vm) {
-        LOGE("JNI_OnLoad: vm is invalid");
-        return JNI_ERR;
-    }
-
-    JNIEnv *env = NULL;
-    if (JNI_OK != vm->GetEnv((void **) &env, JNI_CURRENT_VERSION)) {
-        LOGE("JNI_OnLoad: Version check is failed!");
-        return JNI_ERR;
-    }
-
-    if (0 != InitializeJClassMapArray(env)) {
-        LOGE("JNI_OnLoad: Initialize JClass Array failed!");
-        return JNI_ERR;
-    }
-
-    if (0 != InitializeJObjectMapArray(env)) {
-        LOGE("JNI_OnLoad: Initialize JObject Array failed!");
-        return JNI_ERR;
-    }
-
-    jclass easySetupClassRef = GetJClass(
-            EASY_SETUP_SERVICE_NATIVE_API_CLASS_PATH);
-    if (NULL == easySetupClassRef) {
-        LOGE("JNI_OnLoad: GetJClass gEasySetupClass failed !");
-        return JNI_ERR;
-    }
-    env->RegisterNatives(easySetupClassRef, gEasySetupMethodTable,
-            gEasySetupMethodTableSize);
-
-    EasySetupJVM::m_jvm = vm;
-
-    LOGI("JNI_OnLoad: Exit");
-    return JNI_CURRENT_VERSION;
-}
-
-JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)
-{
-    LOGD("JNI_OnUnload: Enter");
-
-    JNIEnv *env = NULL;
-    if (JNI_OK != vm->GetEnv((void **)&env, JNI_CURRENT_VERSION))
-    {
-        LOGE("JNI_OnLoad: Version check is failed!");
-        return;
-    }
-
-    // delete all class references
-    DeleteClassMapArray(env);
-
-    // delete all jobject
-    DeleteObjectMapArray(env);
-
-    LOGD("JNI_OnUnload: Exit");
-}
-
-#ifdef __cplusplus
-}
-#endif
-
diff --git a/service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_getter.cpp b/service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_getter.cpp
deleted file mode 100644 (file)
index 135f6a2..0000000
+++ /dev/null
@@ -1,148 +0,0 @@
-/******************************************************************
- *
- * 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 "jni_getter.h"
-
-#include <string>
-
-#include "JniOcResource.h"
-
-#define LOG_TAG "TM_JGetter"
-
-bool JGetter::getJStringField(JNIEnv *env, jobject &object,
-        const char *fieldName, std::string &value) {
-    if (NULL == env || NULL == object || NULL == fieldName) {
-        LOGE("getJStringField invalid parameters");
-        return false;
-    }
-
-    jclass clazz = env->GetObjectClass(object);
-    if (NULL == clazz) {
-        LOGE("GetObjectClass failed [%s]", fieldName);
-        return false;
-    }
-
-    jfieldID fieldID = env->GetFieldID(clazz, fieldName, "Ljava/lang/String;");
-    if (0 == fieldID) {
-        LOGE("GetFieldID failed [%s]", fieldName);
-        env->DeleteLocalRef(clazz);
-        return false;
-    }
-
-    jstring jValue = (jstring) env->GetObjectField(object, fieldID);
-    if (NULL == jValue) {
-        LOGE("GetObjectField failed [%s]", fieldName);
-        env->DeleteLocalRef(clazz);
-        return false;
-    }
-
-    const char *cstr = env->GetStringUTFChars(jValue, 0);
-    if (cstr == NULL) {
-        LOGE("GetStringUTFChars failed");
-    } else {
-        value = cstr;
-        env->ReleaseStringUTFChars(jValue, cstr);
-    }
-
-    env->DeleteLocalRef(clazz);
-    env->DeleteLocalRef(jValue);
-
-    return true;
-}
-
-bool JGetter::getJBoolField(JNIEnv *env, jobject &object, const char *fieldName,
-        bool &value) {
-    if (NULL == env || NULL == object || NULL == fieldName) {
-        LOGE("getJBoolField invalid parameters");
-        return false;
-    }
-
-    jclass clazz = env->GetObjectClass(object);
-    if (NULL == clazz) {
-        LOGE("GetObjectClass failed");
-        return false;
-    }
-
-    jfieldID fieldID = env->GetFieldID(clazz, fieldName, "Z");
-    if (0 == fieldID) {
-        LOGE("GetFieldID failed [%s]", fieldName);
-        env->DeleteLocalRef(clazz);
-        return false;
-    }
-
-    value = env->GetBooleanField(object, fieldID);
-
-    env->DeleteLocalRef(clazz);
-
-    return true;
-}
-
-bool JGetter::getJIntField(JNIEnv *env, jobject &object, const char *fieldName,
-        int &value) {
-    if (NULL == env || NULL == object || NULL == fieldName) {
-        LOGE("getJIntField invalid parameters");
-        return false;
-    }
-
-    jclass clazz = env->GetObjectClass(object);
-    if (NULL == clazz) {
-        LOGE("GetObjectClass failed");
-        return false;
-    }
-
-    jfieldID fieldID = env->GetFieldID(clazz, fieldName, "I");
-    if (0 == fieldID) {
-        LOGE("GetFieldID failed [%s]", fieldName);
-        env->DeleteLocalRef(clazz);
-        return false;
-    }
-
-    value = env->GetIntField(object, fieldID);
-
-    env->DeleteLocalRef(clazz);
-
-    return true;
-}
-
-bool JGetter::getJObjectField(JNIEnv *env, jobject &object,
-        const char *fieldName, const char *fieldType, jobject &value) {
-    if (NULL == env || NULL == object || NULL == fieldName) {
-        return false;
-    }
-
-    jclass clazz = env->GetObjectClass(object);
-    if (NULL == clazz) {
-        return false;
-    }
-
-    jfieldID fieldID = env->GetFieldID(clazz, fieldName, fieldType);
-    if (0 == fieldID) {
-        LOGE("GetFieldID failed [%s][%s]", fieldName, fieldType);
-        return false;
-    }
-
-    value = env->GetObjectField(object, fieldID);
-    if (NULL == value) {
-        return false;
-    }
-
-    env->DeleteLocalRef(clazz);
-
-    return true;
-}
diff --git a/service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_object.cpp b/service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_object.cpp
deleted file mode 100644 (file)
index 51c6bf6..0000000
+++ /dev/null
@@ -1,67 +0,0 @@
-#include "jni_object.h"
-
-//#define NULL 0
-#define LOG_TAG "TM_JObject"
-
-JObject::JObject(JNIEnv *env) :
-               m_pEnv(env), m_pObject(NULL), m_pClazz(NULL), m_fIsNewObject(true) {
-}
-
-JObject::JObject(JNIEnv *env, jobject obj) :
-               m_pEnv(NULL), m_pObject(NULL), m_pClazz(NULL), m_fIsNewObject(false) {
-       if (NULL == env || NULL == obj) {
-               return;
-       }
-
-       m_pEnv = env;
-       m_pObject = obj;
-       m_pClazz = m_pEnv->GetObjectClass(obj);
-}
-
-JObject::JObject(JNIEnv *env, const char *classPath) :
-               m_pEnv(NULL), m_pObject(NULL), m_pClazz(NULL), m_fIsNewObject(true) {
-       if (NULL == env || NULL == classPath) {
-               LOGI("JObject Invalid parameters");
-               return;
-       }
-
-       m_pEnv = env;
-       //m_pClazz = GetJClass( classPath );
-
-       if (NULL == m_pClazz) {
-               LOGE("GetJClass failed [%s]", classPath);
-               return;
-       }
-
-       jmethodID mid = env->GetMethodID(m_pClazz, "<init>", "()V");
-       if (NULL == mid) {
-               LOGE("GetMethodID failed [%s]", classPath);
-               return;
-       }
-
-       m_pObject = env->NewObject(m_pClazz, mid);
-}
-
-JObject::~JObject() {
-       if (m_pEnv) {
-               if (m_pObject && m_fIsNewObject) {
-                       m_pEnv->DeleteLocalRef(m_pObject);
-               }
-
-               if (m_pClazz && !m_fIsNewObject) {
-                       m_pEnv->DeleteLocalRef(m_pClazz);
-               }
-       }
-}
-
-jobject JObject::getObject() const {
-       return m_pObject;
-}
-
-void JObject::detachObject() {
-       if (m_fIsNewObject) {
-               m_fIsNewObject = false;
-               m_pClazz = NULL;
-       }
-}
-
diff --git a/service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_setter.cpp b/service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_setter.cpp
deleted file mode 100644 (file)
index 6c38004..0000000
+++ /dev/null
@@ -1,175 +0,0 @@
-/******************************************************************
- *
- * 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 "jni_setter.h"
-
-#include <string>
-
-#include "JniOcResource.h"
-
-#define LOG_TAG "TM_JSetter"
-
-bool JSetter::setJStringField(JNIEnv *env, jobject &object,
-               const char *fieldName, const char *value) {
-       if (NULL == env || NULL == fieldName) {
-               LOGE("setJStringField invalid parameters");
-               return false;
-       }
-
-       jclass clazz = env->GetObjectClass(object);
-       if (NULL == clazz) {
-               LOGE("GetObjectClass failed");
-               return false;
-       }
-
-       jfieldID fieldID = env->GetFieldID(clazz, fieldName, "Ljava/lang/String;");
-       if (0 == fieldID) {
-               LOGE("GetFieldID failed [%s]", fieldName);
-               env->DeleteLocalRef(clazz);
-               return false;
-       }
-
-       jstring jvalue;
-       if (value != NULL && strlen(value) > 0) {
-               jclass strClass = env->FindClass("java/lang/String");
-               jmethodID ctorID = env->GetMethodID(strClass, "<init>",
-                               "([BLjava/lang/String;)V");
-               jbyteArray bytes = env->NewByteArray(strlen(value));
-               env->SetByteArrayRegion(bytes, 0, strlen(value), (jbyte *) value);
-               jstring encoding = env->NewStringUTF("utf-8");
-               jvalue = (jstring) env->NewObject(strClass, ctorID, bytes, encoding);
-               env->DeleteLocalRef(strClass);
-               env->DeleteLocalRef(bytes);
-               env->DeleteLocalRef(encoding);
-       } else {
-               jvalue = env->NewStringUTF("");
-       }
-
-       env->SetObjectField(object, fieldID, jvalue);
-
-       env->DeleteLocalRef(jvalue);
-       env->DeleteLocalRef(clazz);
-
-       return true;
-}
-
-bool JSetter::setJIntField(JNIEnv *env, jobject &object, const char *fieldName,
-               int value) {
-       if (NULL == env || NULL == fieldName) {
-               LOGE("setJIntField invalid paramter");
-               return false;
-       }
-
-       jclass clazz = env->GetObjectClass(object);
-       if (NULL == clazz) {
-               LOGE("GetObjectClass failed");
-               return false;
-       }
-
-       jfieldID fieldID = env->GetFieldID(clazz, fieldName, "I");
-       if (0 == fieldID) {
-               LOGE("GetFieldID failed [%s]", fieldName);
-               env->DeleteLocalRef(clazz);
-               return false;
-       }
-       env->SetIntField(object, fieldID, value);
-
-       env->DeleteLocalRef(clazz);
-
-       return true;
-}
-
-bool JSetter::setJLongField(JNIEnv *env, jobject &object, const char *fieldName,
-               jlong value) {
-       if (NULL == env || NULL == fieldName) {
-               LOGE("setJLongField invalid parameters");
-               return false;
-       }
-
-       jclass clazz = env->GetObjectClass(object);
-       if (NULL == clazz) {
-               LOGE("GetObjectClass failed");
-               return false;
-       }
-
-       jfieldID fieldID = env->GetFieldID(clazz, fieldName, "J");
-       if (0 == fieldID) {
-               LOGE("GetFieldID failed [%s]", fieldName);
-               env->DeleteLocalRef(clazz);
-               return false;
-       }
-       env->SetLongField(object, fieldID, value);
-
-       env->DeleteLocalRef(clazz);
-
-       return true;
-}
-
-bool JSetter::setJBoolField(JNIEnv *env, jobject &object, const char *fieldName,
-               bool value) {
-       if (NULL == env || NULL == fieldName) {
-               LOGE("setJBoolField invalid parameters");
-               return false;
-       }
-
-       jclass clazz = env->GetObjectClass(object);
-       if (NULL == clazz) {
-               LOGE("GetObjectClass failed");
-               return false;
-       }
-
-       jfieldID fieldID = env->GetFieldID(clazz, fieldName, "Z");
-       if (0 == fieldID) {
-               LOGE("GetFieldID failed [%s]", fieldName);
-               env->DeleteLocalRef(clazz);
-               return false;
-       }
-       env->SetBooleanField(object, fieldID, value);
-
-       env->DeleteLocalRef(clazz);
-
-       return true;
-}
-
-bool JSetter::setJObjectField(JNIEnv *env, jobject &object,
-               const char *fieldName, const char *fieldType, const jobject value) {
-       if (NULL == env || NULL == fieldName) {
-               LOGE("setJBoolField invalid parameters");
-               return false;
-       }
-
-       jclass clazz = env->GetObjectClass(object);
-       if (NULL == clazz) {
-               LOGE("GetObjectClass failed");
-               return false;
-       }
-
-       jfieldID fieldID = env->GetFieldID(clazz, fieldName, fieldType);
-       if (0 == fieldID) {
-               LOGE("GetFieldID failed [%s] [%s]", fieldName, fieldType);
-               env->DeleteLocalRef(clazz);
-               return false;
-       }
-       env->SetObjectField(object, fieldID, value);
-
-       env->DeleteLocalRef(clazz);
-
-       return true;
-}
-
diff --git a/service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_string.cpp b/service/easy-setup/sdk/mediator/android/jni/jniutil/src/jni_string.cpp
deleted file mode 100644 (file)
index 93bcdf4..0000000
+++ /dev/null
@@ -1,62 +0,0 @@
-/******************************************************************
- *
- * 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 "jni_string.h"
-
-#define LOG_TAG "TM_JString"
-
-JString::JString(JNIEnv *env, jstring value) :
-               JObject(env, value) {
-       const char *buff = env->GetStringUTFChars(value, 0);
-
-       m_cstr = buff;
-
-       env->ReleaseStringUTFChars(value, buff);
-}
-
-JString::JString(JNIEnv *env, const char *value) :
-               JObject(env) {
-       m_cstr = value;
-
-       if (env) {
-               m_pObject = env->NewStringUTF(value);
-       }
-}
-
-JString::JString(JNIEnv *env, const std::string &value) :
-               JObject(env) {
-       m_cstr = value;
-
-       if (env) {
-               m_pObject = env->NewStringUTF(value.c_str());
-       }
-}
-
-JString::~JString() {
-}
-
-bool JString::getValue(std::string &value) {
-       value = m_cstr;
-       return true;
-}
-
-const char *JString::c_str() {
-       return m_cstr.c_str();
-}
-
diff --git a/service/easy-setup/sdk/mediator/inc/prov_adapter.h b/service/easy-setup/sdk/mediator/inc/prov_adapter.h
deleted file mode 100644 (file)
index fdd611f..0000000
+++ /dev/null
@@ -1,58 +0,0 @@
-//******************************************************************
-//
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#ifndef __EASYSETUP_MGR_H_
-#define __EASYSETUP_MGR_H_
-
-#include <string.h>
-
-#include "logger.h"
-#include "ocstack.h"
-#include "octypes.h"
-#include "escommon.h"
-
-#include "provisioning.h"
-
-
-//-----------------------------------------------------------------------------
-// Defines
-//-----------------------------------------------------------------------------
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-OCStackResult InitProvProcess();
-
-OCStackResult ResetProvProcess();
-
-OCStackResult RegisterCallback(
-        OCProvisioningStatusCB provisioningStatusCallback);
-
-void UnRegisterCallback();
-
-OCStackResult StartProvisioning(const EnrolleeNWProvInfo_t *netInfo);
-
-OCStackResult StopProvisioning(OCConnectivityType connectivityType);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
diff --git a/service/easy-setup/sdk/mediator/inc/provisioning.h b/service/easy-setup/sdk/mediator/inc/provisioning.h
deleted file mode 100644 (file)
index 058d975..0000000
+++ /dev/null
@@ -1,117 +0,0 @@
-//******************************************************************
-//
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-
-#ifndef __PROVISIONING_HANDLER_H_
-#define __PROVISIONING_HANDLER_H_
-
-#include "octypes.h"
-
-#include "logger.h"
-#include "ocstack.h"
-#include "escommon.h"
-
-//-----------------------------------------------------------------------------
-// Defines
-//-----------------------------------------------------------------------------
-#define EASY_SETUP_DEFAULT_CONTEXT_VALUE 0x99
-
-
-//-----------------------------------------------------------------------------
-// Typedefs
-//-----------------------------------------------------------------------------
-
-/**
- * List of methods that can be inititated from the client
- */
-OCStackResult InitProvisioningHandler();
-
-OCStackResult TerminateProvisioningHandler();
-
-void *listeningFunc(void *);
-
-OCStackApplicationResult ProvisionEnrolleeResponse(void *ctx, OCDoHandle handle,
-                                                   OCClientResponse *clientResponse);
-
-OCStackResult ProvisionEnrollee(OCQualityOfService qos, const char *query, const char *resUri,
-                                OCDevAddr *destination, int pauseBeforeStart);
-
-OCStackApplicationResult GetProvisioningStatusResponse(void *ctx, OCDoHandle handle,
-                                                       OCClientResponse *clientResponse);
-
-OCStackResult InvokeOCDoResource(const char *query, OCMethod method, const OCDevAddr *dest,
-                                 OCQualityOfService qos, OCClientResponseHandler cb,
-                                 OCRepPayload *payload,
-                                 OCHeaderOption *options, uint8_t numOptions);
-
-OCStackResult GetProvisioningStatus(OCQualityOfService qos, const char *query,
-                                    const OCDevAddr *destination);
-
-OCStackResult StartProvisioningProcess(const EnrolleeNWProvInfo_t *netInfo,
-                                       OCProvisioningStatusCB provisioningStatusCallback,
-                                       char *findResQuery);
-
-void StopProvisioningProcess();
-
-OCStackApplicationResult FindProvisioningResourceResponse(void *ctx, OCDoHandle handle,
-                                                          OCClientResponse *clientResponse);
-
-void *FindProvisioningResource(void *data);
-
-//Invoke Provisioning Status Callback
-ProvisioningInfo *PrepareProvisioingStatusCB(OCClientResponse *clientResponse,
-                                             ProvStatus provStatus);
-
-
-void LogProvisioningResponse(OCRepPayloadValue * val);
-
-bool ConfigEnrolleeObject(const EnrolleeNWProvInfo_t *netInfo);
-
-bool ClearMemory();
-
-void SuccessCallback(OCClientResponse * clientResponse);
-
-void ErrorCallback(ProvStatus status);
-
-bool ValidateEnrolleResponse(OCClientResponse * clientResponse);
-
-bool ValidateFinddResourceResponse(OCClientResponse * clientResponse);
-
-ProvisioningInfo *GetCallbackObjectOnSuccess(OCClientResponse *clientResponse,
-                                             ProvStatus provStatus);
-
-ProvisioningInfo *GetCallbackObjectOnError(ProvStatus status);
-
-ProvisioningInfo *CreateCallBackObject();
-
-bool ResetProgress();
-
-bool SetProgress(OCProvisioningStatusCB provisioningStatusCallback);
-
-bool InProgress();
-
-bool ValidateEasySetupParams(const EnrolleeNWProvInfo_t *netInfo,
-                             OCProvisioningStatusCB provisioningStatusCallback);
-
-bool IsSetupStopped();
-
-
-#endif
-
diff --git a/service/easy-setup/sdk/mediator/src/prov_adapter.cpp b/service/easy-setup/sdk/mediator/src/prov_adapter.cpp
deleted file mode 100644 (file)
index 3ec79ba..0000000
+++ /dev/null
@@ -1,97 +0,0 @@
-//******************************************************************
-//
-// 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 <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <signal.h>
-#include <unistd.h>
-#include <stdint.h>
-#include <sstream>
-
-#include "prov_adapter.h"
-
-#define ES_PROV_ADAP_TAG "ES_PROVISIONING_ADAPTER"
-
-//Use ipv4addr for both InitDiscovery and InitDeviceDiscovery
-char ipv4addr[IPV4_ADDR_SIZE] = {0};
-
-static const char * UNICAST_PROVISIONING_QUERY = "coap://%s:%d/oic/res?rt=oic.r.prov";
-
-volatile static OCProvisioningStatusCB cbData = NULL;
-
-OCStackResult InitProvProcess() {
-
-
-    OCStackResult result = OC_STACK_ERROR;
-
-    if (InitProvisioningHandler() == OC_STACK_OK) {
-        result = OC_STACK_OK;
-        OIC_LOG(DEBUG, ES_PROV_ADAP_TAG, "InitProvisioningHandler returned Success");
-    } else {
-        result = OC_STACK_ERROR;
-        OIC_LOG_V(ERROR, ES_PROV_ADAP_TAG, "InitProvisioningHandler returned error = %s",
-                  result);
-    }
-
-    return result;
-}
-
-OCStackResult ResetProvProcess() {
-    return TerminateProvisioningHandler();
-}
-
-OCStackResult RegisterCallback(OCProvisioningStatusCB provisioningStatusCallback) {
-    OCStackResult result = OC_STACK_OK;
-
-    if (provisioningStatusCallback != NULL) {
-        cbData = provisioningStatusCallback;
-    }
-    else {
-        result = OC_STACK_ERROR;
-        OIC_LOG(ERROR, ES_PROV_ADAP_TAG, "provisioningStatusCallback is NULL");
-    }
-
-    return result;
-}
-
-void UnRegisterCallback() {
-    if (cbData) {
-        cbData = NULL;
-    }
-}
-
-OCStackResult StartProvisioning(const EnrolleeNWProvInfo_t *netInfo) {
-
-    char findQuery[64] = {0};
-    snprintf(findQuery, sizeof(findQuery) - 1, UNICAST_PROVISIONING_QUERY,
-             netInfo->netAddressInfo.WIFI.ipAddress, IP_PORT);
-
-    return StartProvisioningProcess(netInfo, cbData, findQuery);
-}
-
-OCStackResult StopProvisioning(OCConnectivityType /*connectivityType*/) {
-    OCStackResult result = OC_STACK_OK;
-
-    StopProvisioningProcess();
-
-    return result;
-}
-
-
diff --git a/service/easy-setup/sdk/mediator/src/provisioning.cpp b/service/easy-setup/sdk/mediator/src/provisioning.cpp
deleted file mode 100644 (file)
index 86bef53..0000000
+++ /dev/null
@@ -1,576 +0,0 @@
-//******************************************************************
-//
-// 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 "provisioning.h"
-
-//Standard includes
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <signal.h>
-#include <unistd.h>
-#include <pthread.h>
-
-//EasySetup include files
-#include "ocpayload.h"
-#include "escommon.h"
-
-
-// External includes
-#include "logger.h"
-#include "oic_malloc.h"
-#include "oic_string.h"
-
-#define ES_PROV_TAG "EASY_SETUP_PROVISIONING"
-
-bool g_provisioningCondFlag = false;
-
-static EnrolleeNWProvInfo_t *netProvInfo;
-
-char szFindResourceQueryUri[64] = {0};
-
-/**
- * @var cbData
- * @brief Callback for providing provisioning status callback to application
- */
-static OCProvisioningStatusCB cbData = NULL;
-
-
-void ErrorCallback(ProvStatus status) {
-    ProvisioningInfo *provInfo = GetCallbackObjectOnError(status);
-    cbData(provInfo);
-    ResetProgress();
-}
-
-
-OCStackResult InitProvisioningHandler() {
-    OCStackResult ret = OC_STACK_ERROR;
-    /* Initialize OCStack*/
-    if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK) {
-        OIC_LOG(ERROR, ES_PROV_TAG, "OCStack init error");
-        return ret;
-    }
-
-
-    pthread_t thread_handle;
-
-    if (pthread_create(&thread_handle, NULL, listeningFunc, NULL)) {
-        OIC_LOG(DEBUG, ES_PROV_TAG, "Thread creation failed");
-        return OC_STACK_ERROR;
-    }
-
-    return OC_STACK_OK;
-}
-
-OCStackResult TerminateProvisioningHandler() {
-    OCStackResult ret = OC_STACK_ERROR;
-    if (OCStop() != OC_STACK_OK) {
-        OIC_LOG(ERROR, ES_PROV_TAG, "OCStack stop error");
-    }
-
-    g_provisioningCondFlag = true;
-
-    ret = OC_STACK_OK;
-    return ret;
-}
-
-void *listeningFunc(void* /*data*/) {
-    while (!g_provisioningCondFlag) {
-        OCStackResult result;
-
-        result = OCProcess();
-
-        if (result != OC_STACK_OK) {
-            OIC_LOG(ERROR, ES_PROV_TAG, "OCStack stop error");
-        }
-
-        // To minimize CPU utilization we may wish to do this with sleep
-        sleep(1);
-    }
-    return NULL;
-}
-
-
-OCStackApplicationResult ProvisionEnrolleeResponse(void* /*ctx*/, OCDoHandle /*handle*/,
-                                                   OCClientResponse *clientResponse) {
-    OIC_LOG_V(DEBUG, ES_PROV_TAG, "INSIDE ProvisionEnrolleeResponse");
-
-    // If user stopped the process then return from this function;
-    if (IsSetupStopped()) {
-        ErrorCallback(DEVICE_NOT_PROVISIONED);
-        ClearMemory();
-        return OC_STACK_DELETE_TRANSACTION;
-    }
-
-    if (!ValidateEnrolleResponse(clientResponse)) {
-        ErrorCallback(DEVICE_NOT_PROVISIONED);
-        return OC_STACK_DELETE_TRANSACTION;
-    }
-
-    char *tnn;
-    char *cd;
-
-    OCRepPayload *input = (OCRepPayload * )(clientResponse->payload);
-
-    while (input) {
-
-        int64_t ps;
-        if (OCRepPayloadGetPropInt(input, OC_RSRVD_ES_PS, &ps)) {
-
-            if (ps == 1) {
-                input = input->next;
-                continue;
-            }
-            else {
-                OIC_LOG_V(DEBUG, ES_PROV_TAG, "PS is NOT proper");
-                goto Error;
-
-            }
-        }
-
-        if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_TNN, &tnn)) {
-            if (!strcmp(tnn, netProvInfo->netAddressInfo.WIFI.ssid)) {
-                OIC_LOG_V(DEBUG, ES_PROV_TAG, "SSID is proper");
-                input = input->next;
-                continue;
-            }
-            else {
-                OIC_LOG_V(DEBUG, ES_PROV_TAG, "SSID is NOT proper");
-                goto Error;
-            }
-        }
-
-        if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_CD, &cd)) {
-            if (!strcmp(cd, netProvInfo->netAddressInfo.WIFI.pwd)) {
-                OIC_LOG_V(DEBUG, ES_PROV_TAG, "Password is proper");
-                input = input->next;
-                continue;
-            }
-            else {
-                OIC_LOG_V(DEBUG, ES_PROV_TAG, "Password is NOT proper");
-                goto Error;
-            }
-        }
-
-        LogProvisioningResponse(input->values);
-
-        input = input->next;
-
-        OICFree(tnn);
-        OICFree(cd);
-    }
-
-    SuccessCallback(clientResponse);
-
-    return OC_STACK_KEEP_TRANSACTION;
-
-    Error:
-    {
-        OICFree(tnn);
-        OICFree(cd);
-
-        ErrorCallback(DEVICE_NOT_PROVISIONED);
-
-        return OC_STACK_DELETE_TRANSACTION;
-    }
-
-}
-
-OCStackResult StartProvisioningProcess(const EnrolleeNWProvInfo_t *netInfo,
-                                       OCProvisioningStatusCB provisioningStatusCallback,
-                                       char *findResQuery) {
-
-    if(findResQuery != NULL)
-    {
-        OICStrcpy(szFindResourceQueryUri, sizeof(szFindResourceQueryUri) - 1, findResQuery);
-    }
-    else
-    {
-        OIC_LOG(ERROR, ES_PROV_TAG, PCF("Find resource query is NULL"));
-        goto Error;
-    }
-
-    pthread_t thread_handle;
-
-    if (!ValidateEasySetupParams(netInfo, provisioningStatusCallback)) {
-        goto Error;
-    }
-
-    if (!SetProgress(provisioningStatusCallback)) {
-        // Device provisioning session is running already.
-        OIC_LOG(INFO, ES_PROV_TAG, PCF("Device provisioning session is running already"));
-        goto Error;
-    }
-
-    if (!ConfigEnrolleeObject(netInfo)) {
-        goto Error;
-    }
-
-    if (pthread_create(&thread_handle, NULL, FindProvisioningResource, NULL)) {
-        goto Error;
-
-    }
-
-    pthread_join(thread_handle, NULL);
-
-
-    return OC_STACK_OK;
-
-    Error:
-    {
-        ErrorCallback(DEVICE_NOT_PROVISIONED);
-        ClearMemory();
-        return OC_STACK_ERROR;
-    }
-
-}
-
-void StopProvisioningProcess() {
-    //Only basis test is done for below API
-    ResetProgress();
-}
-
-bool ClearMemory() {
-
-    OIC_LOG(DEBUG, ES_PROV_TAG, "thread_pool_add_task of FindProvisioningResource failed");
-    OICFree(netProvInfo);
-    return true;
-
-}
-
-bool ConfigEnrolleeObject(const EnrolleeNWProvInfo_t *netInfo) {
-
-    //Copy Network Provisioning  Information
-    netProvInfo = (EnrolleeNWProvInfo_t *) OICCalloc(1, sizeof(EnrolleeNWProvInfo_t));
-
-    if (netProvInfo == NULL) {
-        OIC_LOG(ERROR, ES_PROV_TAG, "Invalid input..");
-        return false;
-    }
-
-    memcpy(netProvInfo, netInfo, sizeof(EnrolleeNWProvInfo_t));
-
-    OIC_LOG_V(DEBUG, ES_PROV_TAG, "Network Provisioning Info. SSID = %s",
-              netProvInfo->netAddressInfo.WIFI.ssid);
-
-    OIC_LOG_V(DEBUG, ES_PROV_TAG, "Network Provisioning Info. PWD = %s",
-              netProvInfo->netAddressInfo.WIFI.pwd);
-
-    return true;
-
-}
-
-void LogProvisioningResponse(OCRepPayloadValue * val) {
-
-    switch (val->type) {
-        case OCREP_PROP_NULL:
-            OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s: NULL", val->name);
-            break;
-        case OCREP_PROP_INT:
-            OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(int):%lld", val->name, val->i);
-            break;
-        case OCREP_PROP_DOUBLE:
-            OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(double):%f", val->name, val->d);
-            break;
-        case OCREP_PROP_BOOL:
-            OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(bool):%s", val->name, val->b ? "true" : "false");
-            break;
-        case OCREP_PROP_STRING:
-            OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(string):%s", val->name, val->str);
-            break;
-        case OCREP_PROP_OBJECT:
-            // Note: Only prints the URI (if available), to print further, you'll
-            // need to dig into the object better!
-            OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(OCRep):%s", val->name, val->obj->uri);
-            break;
-        case OCREP_PROP_ARRAY:
-            switch (val->arr.type) {
-                case OCREP_PROP_INT:
-                    OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(int array):%d x %d x %d",
-                              val->name,
-                              val->arr.dimensions[0], val->arr.dimensions[1],
-                              val->arr.dimensions[2]);
-                    break;
-                case OCREP_PROP_DOUBLE:
-                    OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(double array):%d x %d x %d",
-                              val->name,
-                              val->arr.dimensions[0], val->arr.dimensions[1],
-                              val->arr.dimensions[2]);
-                    break;
-                case OCREP_PROP_BOOL:
-                    OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(bool array):%d x %d x %d",
-                              val->name,
-                              val->arr.dimensions[0], val->arr.dimensions[1],
-                              val->arr.dimensions[2]);
-                    break;
-                case OCREP_PROP_STRING:
-                    OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(string array):%d x %d x %d",
-                              val->name,
-                              val->arr.dimensions[0], val->arr.dimensions[1],
-                              val->arr.dimensions[2]);
-                    break;
-                case OCREP_PROP_OBJECT:
-                    OIC_LOG_V(DEBUG, ES_PROV_TAG, "\t\t%s(OCRep array):%d x %d x %d",
-                              val->name,
-                              val->arr.dimensions[0], val->arr.dimensions[1],
-                              val->arr.dimensions[2]);
-                    break;
-                default:
-                    break;
-            }
-            break;
-        default:
-            break;
-    }
-}
-
-OCStackResult FindNetworkResource() {
-    OCStackResult ret = OC_STACK_ERROR;
-    if (OCStop() != OC_STACK_OK) {
-        OIC_LOG(ERROR, ES_PROV_TAG, "OCStack stop error");
-    }
-
-    return ret;
-}
-
-ProvisioningInfo *PrepareProvisioingStatusCB(OCClientResponse *clientResponse,
-                                             ProvStatus provStatus) {
-
-    ProvisioningInfo *provInfo = (ProvisioningInfo *) OICCalloc(1, sizeof(ProvisioningInfo));
-
-    if (provInfo == NULL) {
-        OIC_LOG_V(ERROR, ES_PROV_TAG, "Failed to allocate memory");
-        return NULL;
-    }
-
-    OCDevAddr *devAddr = (OCDevAddr *) OICCalloc(1, sizeof(OCDevAddr));
-
-    if (devAddr == NULL) {
-        OIC_LOG_V(ERROR, ES_PROV_TAG, "Failed to allocate memory");
-        OICFree(provInfo);
-        return NULL;
-    }
-
-    OICStrcpy(devAddr->addr, sizeof(devAddr->addr), clientResponse->addr->addr);
-
-    devAddr->port = clientResponse->addr->port;
-
-    provInfo->provDeviceInfo.addr = devAddr;
-
-    provInfo->provStatus = provStatus;
-
-    return provInfo;
-}
-
-
-bool InProgress() {
-
-    // It means already Easy Setup provisioning session is going on.
-    if (NULL != cbData) {
-        OIC_LOG(ERROR, ES_PROV_TAG, "Easy setup session is already in progress");
-        return true;
-    }
-
-    return false;
-}
-
-bool SetProgress(OCProvisioningStatusCB provisioningStatusCallback) {
-
-    if (InProgress())
-        return false;
-
-    cbData = provisioningStatusCallback;
-
-
-    return true;
-}
-
-bool ResetProgress() {
-
-    cbData = NULL;
-    return true;
-}
-
-ProvisioningInfo *CreateCallBackObject() {
-
-    ProvisioningInfo *provInfo = (ProvisioningInfo *) OICCalloc(1, sizeof(ProvisioningInfo));
-
-    if (provInfo == NULL) {
-        OIC_LOG_V(ERROR, ES_PROV_TAG, "Failed to allocate memory");
-        return NULL;
-    }
-
-    OCDevAddr *devAddr = (OCDevAddr *) OICCalloc(1, sizeof(OCDevAddr));
-
-    if (devAddr == NULL) {
-        OIC_LOG_V(ERROR, ES_PROV_TAG, "Failed to allocate memory");
-        OICFree(provInfo);
-        return NULL;
-    }
-
-    provInfo->provDeviceInfo.addr = devAddr;
-
-    return provInfo;
-
-}
-
-ProvisioningInfo *GetCallbackObjectOnError(ProvStatus status) {
-
-    ProvisioningInfo *provInfo = CreateCallBackObject();
-    OICStrcpy(provInfo->provDeviceInfo.addr->addr, sizeof(provInfo->provDeviceInfo.addr->addr),
-        netProvInfo->netAddressInfo.WIFI.ipAddress);
-
-    provInfo->provDeviceInfo.addr->port = IP_PORT;
-    provInfo->provStatus = status;
-    return provInfo;
-}
-
-ProvisioningInfo *GetCallbackObjectOnSuccess(OCClientResponse *clientResponse,
-                                             ProvStatus provStatus) {
-    ProvisioningInfo *provInfo = CreateCallBackObject();
-    OICStrcpy(provInfo->provDeviceInfo.addr->addr, sizeof(provInfo->provDeviceInfo.addr->addr),
-                        clientResponse->addr->addr);
-
-    provInfo->provDeviceInfo.addr->port = clientResponse->addr->port;
-    provInfo->provStatus = provStatus;
-    return provInfo;
-}
-
-bool ValidateFinddResourceResponse(OCClientResponse * clientResponse) {
-
-    if (!(clientResponse) || !(clientResponse->payload)) {
-
-        OIC_LOG_V(INFO, ES_PROV_TAG, "ProvisionEnrolleeResponse received Null clientResponse");
-
-        return false;
-
-    }
-    return true;
-}
-
-bool ValidateEnrolleResponse(OCClientResponse * clientResponse) {
-
-    if (!(clientResponse) || !(clientResponse->payload)) {
-
-        OIC_LOG_V(INFO, ES_PROV_TAG, "ProvisionEnrolleeResponse received Null clientResponse");
-
-        return false;
-
-    }
-
-    if (clientResponse->payload->type != PAYLOAD_TYPE_REPRESENTATION) {
-
-        OIC_LOG_V(DEBUG, ES_PROV_TAG, "Incoming payload not a representation");
-        return false;
-
-    }
-
-    // If flow reachese here means no error condition hit.
-    return true;
-
-}
-
-void SuccessCallback(OCClientResponse * clientResponse) {
-    ProvisioningInfo *provInfo = GetCallbackObjectOnSuccess(clientResponse, DEVICE_PROVISIONED);
-    cbData(provInfo);
-    ResetProgress();
-}
-
-void* FindProvisioningResource(void* /*data*/) {
-
-    // If user stopped the process before thread get scheduled then check and return from this function;
-    if (IsSetupStopped()) {
-        ErrorCallback(DEVICE_NOT_PROVISIONED);
-        ClearMemory();
-        return NULL;
-    }
-
-    OCStackResult ret = OC_STACK_ERROR;
-
-    OIC_LOG_V(DEBUG, ES_PROV_TAG, "szFindResourceQueryUri = %s", szFindResourceQueryUri);
-
-    OCCallbackData ocCBData;
-
-    ocCBData.cb = FindProvisioningResourceResponse;
-    ocCBData.context = (void *) EASY_SETUP_DEFAULT_CONTEXT_VALUE;
-    ocCBData.cd = NULL;
-
-
-    ret = OCDoResource(NULL, OC_REST_DISCOVER, szFindResourceQueryUri, NULL, NULL,
-                       netProvInfo->connType, OC_LOW_QOS,
-                       &ocCBData, NULL, 0);
-
-    if (ret != OC_STACK_OK) {
-        ErrorCallback(DEVICE_NOT_PROVISIONED);
-        ClearMemory();
-    }
-
-    return NULL;
-}
-
-OCStackResult InvokeOCDoResource(const char *query, OCMethod method, const OCDevAddr *dest,
-                                 OCQualityOfService qos, OCClientResponseHandler cb,
-                                 OCRepPayload *payload,
-                                 OCHeaderOption *options, uint8_t numOptions) {
-    OCStackResult ret;
-    OCCallbackData cbData;
-
-    cbData.cb = cb;
-    cbData.context = (void *) EASY_SETUP_DEFAULT_CONTEXT_VALUE;
-    cbData.cd = NULL;
-
-    ret = OCDoResource(NULL, method, query, dest, (OCPayload *) payload, netProvInfo->connType, qos,
-                       &cbData, options, numOptions);
-
-    if (ret != OC_STACK_OK) {
-        OIC_LOG_V(ERROR, ES_PROV_TAG, "OCDoResource returns error %d with method %d", ret, method);
-    }
-
-    return ret;
-}
-
-OCStackResult ProvisionEnrollee(OCQualityOfService qos, const char *query, const char *resUri,
-                                OCDevAddr *destination, int pauseBeforeStart) {
-
-
-    // This sleep is required in case of BLE provisioning due to packet drop issue.
-    OIC_LOG_V(INFO, ES_PROV_TAG, "Sleeping for %d seconds", pauseBeforeStart);
-    sleep(pauseBeforeStart);
-    OIC_LOG_V(INFO, ES_PROV_TAG, "\n\nExecuting ProvisionEnrollee%s", __func__);
-
-    OCRepPayload *payload = OCRepPayloadCreate();
-
-    OCRepPayloadSetUri(payload, resUri);
-    OCRepPayloadSetPropString(payload, OC_RSRVD_ES_TNN, netProvInfo->netAddressInfo.WIFI.ssid);
-    OCRepPayloadSetPropString(payload, OC_RSRVD_ES_CD, netProvInfo->netAddressInfo.WIFI.pwd);
-
-    OIC_LOG_V(DEBUG, ES_PROV_TAG, "OCPayload ready for ProvisionEnrollee");
-
-    OCStackResult ret = InvokeOCDoResource(query, OC_REST_PUT, destination, qos,
-                                           ProvisionEnrolleeResponse, payload, NULL, 0);
-
-    return ret;
-}
-
-bool IsSetupStopped() {
-    return (cbData == NULL) ? true : false;
-}
-
-
diff --git a/service/easy-setup/sdk/mediator/src/wifi_provisioning.cpp b/service/easy-setup/sdk/mediator/src/wifi_provisioning.cpp
deleted file mode 100644 (file)
index aa8f161..0000000
+++ /dev/null
@@ -1,174 +0,0 @@
-//******************************************************************
-//
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-// NOTE : Keeping Wifi provisioning in this file to have adaptability while doing OOPs refactoring
-
-#include "provisioning.h"
-
-//Standard includes
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <signal.h>
-#include <unistd.h>
-#include <pthread.h>
-
-//EasySetup include files
-#include "ocpayload.h"
-#include "escommon.h"
-
-// External includes
-#include "logger.h"
-
-#define ES_WIFI_PROV_TAG "ES_WIFI_PROVISIONING"
-
-static const char * UNICAST_PROV_STATUS_QUERY = "coap://%s:%d%s";
-
-OCStackApplicationResult GetProvisioningStatusResponse(void* /*ctx*/,
-                                                        OCDoHandle /*handle*/,
-                                                        OCClientResponse *clientResponse) {
-
-
-    // If user stopped the process then return from this function;
-    if (IsSetupStopped()) {
-        ErrorCallback(DEVICE_NOT_PROVISIONED);
-        ClearMemory();
-        return OC_STACK_DELETE_TRANSACTION;
-    }
-
-    if (!ValidateEnrolleResponse(clientResponse)) {
-        ErrorCallback(DEVICE_NOT_PROVISIONED);
-        ClearMemory();
-        return OC_STACK_DELETE_TRANSACTION;
-    }
-
-    OCRepPayload *input = (OCRepPayload * )(clientResponse->payload);
-
-    char query[OIC_STRING_MAX_VALUE] =
-            {'\0'};
-    char resURI[MAX_URI_LENGTH] =
-            {'\0'};
-
-    OIC_LOG_V(DEBUG, ES_WIFI_PROV_TAG, "resUri = %s", input->uri);
-
-    strncpy(resURI, input->uri, sizeof(resURI) - 1);
-
-    snprintf(query, sizeof(query), UNICAST_PROV_STATUS_QUERY, clientResponse->addr->addr, IP_PORT,
-             resURI);
-
-    if (ProvisionEnrollee(OC_HIGH_QOS, query, OC_RSRVD_ES_URI_PROV, clientResponse->addr, 0)
-        != OC_STACK_OK) {
-        OIC_LOG(INFO, ES_WIFI_PROV_TAG, "GetProvisioningStatusResponse received NULL clientResponse");
-
-        ErrorCallback(DEVICE_NOT_PROVISIONED);
-        ClearMemory();
-        return OC_STACK_DELETE_TRANSACTION;
-    }
-
-    return OC_STACK_KEEP_TRANSACTION;
-
-}
-
-OCStackResult GetProvisioningStatus(OCQualityOfService qos, const char *query,
-                                    const OCDevAddr *destination) {
-    OCStackResult ret = OC_STACK_ERROR;
-    OCHeaderOption options[MAX_HEADER_OPTIONS];
-
-    OIC_LOG_V(INFO, ES_WIFI_PROV_TAG, "\n\nExecuting %s", __func__);
-
-    uint8_t option0[] =
-            {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
-    uint8_t option1[] =
-            {11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
-    memset(options, 0, sizeof(OCHeaderOption) * MAX_HEADER_OPTIONS);
-    options[0].protocolID = OC_COAP_ID;
-    options[0].optionID = 2048;
-    memcpy(options[0].optionData, option0, sizeof(option0));
-    options[0].optionLength = 10;
-    options[1].protocolID = OC_COAP_ID;
-    options[1].optionID = 3000;
-    memcpy(options[1].optionData, option1, sizeof(option1));
-    options[1].optionLength = 10;
-
-    ret = InvokeOCDoResource(query, OC_REST_GET, destination, qos,
-                             GetProvisioningStatusResponse, NULL, options, 2);
-    return ret;
-}
-
-
-// This is a function called back when a device is discovered
-OCStackApplicationResult FindProvisioningResourceResponse(void* /*ctx*/,
-                                                            OCDoHandle /*handle*/,
-                                                            OCClientResponse *clientResponse) {
-
-    OIC_LOG(INFO, ES_WIFI_PROV_TAG, PCF("Entering FindProvisioningResourceResponse"));
-
-    // If user stopped the process then return from this function;
-    if (IsSetupStopped()) {
-        ErrorCallback(DEVICE_NOT_PROVISIONED);
-        ClearMemory();
-        return OC_STACK_DELETE_TRANSACTION;
-    }
-
-
-    if (!ValidateFinddResourceResponse(clientResponse)) {
-        ErrorCallback(DEVICE_NOT_PROVISIONED);
-        return OC_STACK_DELETE_TRANSACTION;
-    }
-
-    char szQueryUri[64] = {0};
-
-    OCDiscoveryPayload *discoveryPayload = (OCDiscoveryPayload * )(clientResponse->payload);
-
-    OIC_LOG_V(DEBUG, ES_WIFI_PROV_TAG, "resUri = %s", discoveryPayload->resources->uri);
-
-    snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_PROV_STATUS_QUERY,
-             clientResponse->devAddr.addr, IP_PORT, discoveryPayload->resources->uri);
-
-    OIC_LOG_V(DEBUG, ES_WIFI_PROV_TAG, "query before GetProvisioningStatus call = %s", szQueryUri);
-
-    if (GetProvisioningStatus(OC_HIGH_QOS, szQueryUri, &clientResponse->devAddr) != OC_STACK_OK) {
-        ErrorCallback(DEVICE_NOT_PROVISIONED);
-        return OC_STACK_DELETE_TRANSACTION;
-    }
-
-    return OC_STACK_KEEP_TRANSACTION;
-
-}
-
-bool ValidateEasySetupParams(const EnrolleeNWProvInfo_t *netInfo,
-                             OCProvisioningStatusCB provisioningStatusCallback) {
-
-    if (netInfo == NULL || strlen(netInfo->netAddressInfo.WIFI.ipAddress) == 0) {
-        OIC_LOG(ERROR, ES_WIFI_PROV_TAG, "Request URI is NULL");
-        return false;
-    }
-
-    if (provisioningStatusCallback == NULL) {
-        OIC_LOG(ERROR, ES_WIFI_PROV_TAG, "ProvisioningStatusCallback is NULL");
-        return false;
-    }
-
-    return true;
-
-}
-
-
-
index ac49ba1..9a27b96 100644 (file)
@@ -114,11 +114,7 @@ if int(containerJavaSupport):
 ######################################################################
 # Source files and Targets
 ######################################################################
-res_container_src = ['src/BaseActivator.cpp','src/BundleActivator.cpp','src/RCSBundleInfo.cpp',
-    'src/BundleInfoInternal.cpp', 'src/BundleResource.cpp', 'src/Configuration.cpp', 'src/JavaBundleResource.cpp', 'src/ProtocolBridgeResource.cpp',
-    'src/ProtocolBridgeConnector.cpp', 'src/RCSResourceContainer.cpp', 'src/ResourceContainerBundleAPI.cpp', 'src/ResourceContainerImpl.cpp',
-    'src/SoftSensorResource.cpp', 'src/DiscoverResourceUnit.cpp', 'src/RemoteResourceUnit.cpp',
-    ]
+res_container_src = [ Glob('src/*.cpp') ]
 
 res_container_static = resource_container_env.StaticLibrary('rcs_container', res_container_src)
 res_container_shared = resource_container_env.SharedLibrary('rcs_container', res_container_src)
@@ -126,8 +122,8 @@ res_container_shared = resource_container_env.SharedLibrary('rcs_container', res
 resource_container_env.InstallTarget([res_container_static,res_container_shared], 'libResContainer')
 resource_container_env.UserInstallTargetLib([res_container_static,res_container_shared], 'libResContainer')
 
-resource_container_env.UserInstallTargetHeader('include/RCSBundleInfo.h', 'iotivity-service', 'RCSBundleInfo.h')
-resource_container_env.UserInstallTargetHeader('include/RCSResourceContainer.h', 'iotivity-service', 'RCSResourceContainer.h')
+resource_container_env.UserInstallTargetHeader('include/RCSBundleInfo.h', 'service/resource-container', 'RCSBundleInfo.h')
+resource_container_env.UserInstallTargetHeader('include/RCSResourceContainer.h', 'service/resource-container', 'RCSResourceContainer.h')
 
 ######################################################################
 # build discomfort index sensor sample bundle
index 49ffed7..3f04414 100644 (file)
@@ -4,6 +4,6 @@
 /.idea/libraries
 .DS_Store
 /build/*
-/service/build/*
-/service/src/main/obj/*
-/service/src/main/libs/*
+/resource-container/build/*
+/resource-container/src/main/obj/*
+/resource-container/src/main/libs/*
index ce0d922..ee9f351 100644 (file)
@@ -41,12 +41,9 @@ if not os.path.exists(android_home + '/platforms/android-21') or not os.path.exi
 ...Opening Android SDK Manager now. Once you are finished, the build will continue.
 '''
     os.system(android_home + '/tools/android')
-
-
+    
 def ensure_libs(target, source, env):
-    return target, [source, env.get('BUILD_DIR') + 'librcs_server.so',
-                    env.get('BUILD_DIR') + 'librcs_client.so',
-                    env.get('BUILD_DIR') + 'librcs_container.so']
+    return target, [source, env.get('BUILD_DIR') + 'librcs_container.so']
 
 jdk_env = Environment(ENV=os.environ)
 jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') +
@@ -54,5 +51,5 @@ jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') +
     emitter = ensure_libs)
 jdk_env['BUILD_DIR'] = env.get('BUILD_DIR')
 
-jdk_env.Gradle(target="service/objs",
+jdk_env.Gradle(target="resource-container/objs",
     source="resource-container/src/main/java/org/iotivity/service/resourcecontainer/RcsBundleInfo.java")
index 50c7205..d466538 100644 (file)
 
 apply plugin: 'com.android.library'
 
+task jar(type: Jar) {
+    from fileTree(dir: 'build/intermediates/classes/release')
+}
+
 android {
     compileSdkVersion 21
     buildToolsVersion "20.0.0"
@@ -97,7 +101,7 @@ task buildNative(type: Exec) {
         //for windows use 'ndk-build.cmd'
         //def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build.cmd')
         def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build')
-        commandLine ndkBuild, "APP_ABI=$TARGET_ARCH", "APP_OPTIM=$RELEASE", '-C', file('src/main').absolutePath
+        commandLine ndkBuild, "V=1", "APP_ABI=$TARGET_ARCH", "APP_OPTIM=$RELEASE", '-C', file('src/main').absolutePath
     } else {
         println '##################'
         println 'Skipping NDK build'
diff --git a/service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/BundleActivator.java b/service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/BundleActivator.java
new file mode 100644 (file)
index 0000000..ebfd7ce
--- /dev/null
@@ -0,0 +1,59 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+package org.iotivity.service.resourcecontainer;
+
+import android.content.Context;
+import java.util.List;
+
+/**
+ * Every resource bundle has to provide a bundle activator that can be called
+ * by the resource container on bundle startup.
+ */
+public abstract class BundleActivator {
+    protected RcsResourceContainerBundleAPI bundleAPI;
+    protected Context appContext;
+    
+    public BundleActivator(RcsResourceContainerBundleAPI bundleAPI, Context appContext){
+        this.bundleAPI = bundleAPI;
+        this.appContext = appContext;
+    }
+    /**
+     * Activates the bundle and creates all resources.
+     */
+    public abstract void activateBundle();
+
+    /**
+     * Deactivates the bundle and destroys all resources.
+     */
+    public abstract void deactivateBundle();
+
+    /**
+     * Creates a resources
+     * @param resource Instance of a BundleResource
+     */
+    public abstract void createResource(ResourceConfig resource);
+
+    /**
+     * Destroys a resource
+     * @param resource Instance of a BundleResource
+     */
+    public abstract void destroyResource(BundleResource resource);
+
+}
\ No newline at end of file
diff --git a/service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/BundleResource.java b/service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/BundleResource.java
new file mode 100644 (file)
index 0000000..86b0b17
--- /dev/null
@@ -0,0 +1,234 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.service.resourcecontainer;
+
+import java.util.HashMap;
+import java.util.Set;
+import android.content.Context;
+import android.util.Log;
+
+/**
+ * Basic BundleResource that should be used as a base class by a bundle
+ * resources. A concrete technology has to override the setAttribute and
+ * getAttribute method and map the according reads and writes to the technology
+ * specific messages.
+ */
+public abstract class BundleResource {
+    protected String                m_name, m_uri, m_resourceType, m_address;
+
+    protected RcsResourceAttributes m_attributes = new RcsResourceAttributes();
+
+    protected Context               m_context;
+    
+    long mNativeHandle;
+    
+    protected native void updateNativeInstance(RcsResourceAttributes update);
+
+    public BundleResource() {
+        initAttributes();
+    }
+
+    public BundleResource(Context context) {
+        this();
+        this.m_context = context;
+    }
+
+    /**
+     * Initialize the internal attribute structure.
+     */
+    protected abstract void initAttributes();
+
+    /**
+     * Set the attribute (map to a send command for the according protocol)
+     * 
+     * @param key
+     *            name of the attribute to be set
+     * @param value
+     *            new value of the attribute
+     */
+    protected final void setAttribute(String key, RcsValue value, boolean notify) {
+        m_attributes.put(key, value);
+        
+        if(notify){
+            updateNativeInstance(m_attributes);
+        }
+    }
+    
+    /**
+     * Set the attribute (map to a send command for the according protocol)
+     * 
+     * @param key
+     *            name of the attribute to be set
+     * @param value
+     *            new value of the attribute
+     */
+    protected final void setAttribute(String key, RcsValue value) {
+        setAttribute(key, value, false);
+    }
+
+    /**
+     * Set the attribute (map to a send command for the according protocol)
+     * 
+     * @param key
+     *            name of the attribute to be set
+     * @param value
+     *            new value of the attribute
+     */
+    protected final void setAttributes(RcsResourceAttributes value, boolean notify) {
+        m_attributes.put(value);
+        
+        if(notify){
+            updateNativeInstance(m_attributes);
+        }
+    }
+
+    protected final void setAttributes(RcsResourceAttributes value) {
+        setAttributes(value, false);
+    }
+
+    /**
+     * Set the attribute (map to a send command for the according protocol)
+     * 
+     * @param key
+     *            name of the attribute to be set
+     * @param value
+     *            new value of the attribute
+     */
+    public abstract void handleSetAttributesRequest(RcsResourceAttributes value);
+    
+    /**
+     * Deactivates the resource
+     */ 
+    public abstract void deactivateResource();
+
+    /**
+     * Retrieve the attribute (only data)
+     * 
+     * @param key
+     *            name of the attribute to be read
+     * @return Value of the attribute
+     */
+    protected final RcsValue getAttribute(String key) {
+        return m_attributes.get(key);
+    }
+
+    protected final RcsResourceAttributes getAttributes() {
+        RcsResourceAttributes ret = new RcsResourceAttributes(this.m_attributes);             
+        return ret;
+    }
+
+    /**
+     * Retrieve the attribute (map to read command)
+     * 
+     * @param key
+     *            name of the attribute to be set
+     * @param value
+     *            new value of the attribute
+     */
+    public abstract RcsResourceAttributes handleGetAttributesRequest();
+
+    /**
+     * Attribute keys provided through by the bundle resource.
+     * 
+     * @return Name of attribute keys as string array
+     */
+    public String[] getAttributeKeys() {
+           Set<String> keys = m_attributes.keySet();
+           return keys.toArray(new String[keys.size()]);
+       }
+
+    /**
+     * Setter for the uri property
+     * 
+     * @param uri
+     *            URI of the resource
+     */
+    public void setURI(String uri) {
+        this.m_uri = uri;
+    }
+
+    /**
+     * Returns the URI of the resource
+     * 
+     * @return Resource URI
+     */
+    public String getURI() {
+        return m_uri;
+    }
+
+    /**
+     * Sets the resource type property
+     * 
+     * @param resourceType
+     *            OIC resource type
+     */
+    public void setResourceType(String resourceType) {
+        this.m_resourceType = resourceType;
+    }
+
+    /**
+     * Getter for the resource type
+     * 
+     * @return OIC resource type
+     */
+    public String getResourceType() {
+        return m_resourceType;
+    }
+
+    /**
+     * Sets the technology specific address information (e.g., ZigBee short or
+     * long identifier)
+     * 
+     * @param address
+     *            Resource address
+     */
+    public void setAddress(String address) {
+        this.m_address = address;
+    }
+
+    /**
+     * Returns the technology specific address information
+     * 
+     * @return Resource address
+     */
+    public String getAddress() {
+        return m_address;
+    }
+
+    /**
+     * Sets the name property of the resource
+     * 
+     * @param name
+     *            Resource name
+     */
+    public void setName(String name) {
+        this.m_name = name;
+    }
+
+    /**
+     * Returns the name property of the resource
+     * 
+     * @return Resource name
+     */
+    public String getName() {
+        return m_name;
+    }
+}
diff --git a/service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/BundleSoftSensorResource.java b/service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/BundleSoftSensorResource.java
new file mode 100644 (file)
index 0000000..46eb9d3
--- /dev/null
@@ -0,0 +1,52 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+
+package org.iotivity.service.resourcecontainer;
+
+import java.util.HashMap;
+import java.util.Set;
+import java.util.Vector;
+import android.content.Context;
+import android.util.Log;
+
+/**
+ * Every resource bundle has to provide a bundle activator that can be called
+ * by the resource container on bundle startup.
+ */
+public abstract class BundleSoftSensorResource extends BundleResource {
+    protected HashMap<String, RcsValue> m_mapInputData;
+    
+    public BundleSoftSensorResource(Context context) {
+        super(context);
+    }
+    /**
+     * Initialize the internal attribute structure.
+     */
+    protected abstract void onUpdatedInputResource(String attributeName,  Vector<RcsValue> values);
+
+    /**
+     * SoftSensor logic. Has to be provided by the soft sensor developer.
+     * This function will be executed if an input attribute is updated.
+     *
+     * @return void
+     */
+    protected abstract void executeLogic();
+}
\ No newline at end of file
index 670ceca..8e6273f 100644 (file)
@@ -1,22 +1,23 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 
 /**
  * @file
  */
 package org.iotivity.service.resourcecontainer;
 
-import org.iotivity.service.utils.RcsObject;
-
 /**
  * This class provides APIs for getting and setting the Bundle Information
  */
-public class RcsBundleInfo extends RcsObject {
-    private native String nativeGetID();
-
-    private native String nativeGetPath();
-
-    private native String nativeGetActivatorName();
-
-    private native String nativeGetLibraryPath();
+public class RcsBundleInfo {
+    private final String mId;
+    private final String mPath;
+    private final String mActivatorName;
+    private final String mLibraryPath;
+    private final String mVersion;
+    private boolean mActivated; // not final since it might be modified for Android-specific bundles
 
-    private native String nativeGetVersion();
+    private RcsBundleInfo(String id, String path, String activatorName,
+            String libraryPath, String version) {
+        mId = id;
+        mPath = path;
+        mActivatorName = activatorName;
+        mLibraryPath = libraryPath;
+        mVersion = version;
+        mActivated = false;
+    }
 
-    private RcsBundleInfo() {
+    private RcsBundleInfo(String id, String path, String activatorName,
+            String libraryPath, String version, boolean activated) {
+        mId = id;
+        mPath = path;
+        mActivatorName = activatorName;
+        mLibraryPath = libraryPath;
+        mVersion = version;
+        mActivated = activated;
     }
 
     /**
@@ -50,7 +63,7 @@ public class RcsBundleInfo extends RcsObject {
      *
      */
     public String getID() {
-        return nativeGetID();
+        return mId;
     }
 
     /**
@@ -60,7 +73,7 @@ public class RcsBundleInfo extends RcsObject {
      *
      */
     public String getPath() {
-        return nativeGetPath();
+        return mPath;
     }
 
     /**
@@ -70,27 +83,36 @@ public class RcsBundleInfo extends RcsObject {
      *
      */
     public String getActivatorName() {
-        return nativeGetActivatorName();
+        return mActivatorName;
     }
 
     /**
-     * API for getting the library path for the bundle
+     * API for getting the version of the bundle
+     *
+     * @return string - version of the bundle
+     *
+     */
+    public String getVersion() {
+        return mVersion;
+    }
+    
+    /**
+     * Returns the current activation status of the bundle
      *
-     * @return string - Library path in string form
+     * @return boolean - bundle has been successfully loaded and started
      *
      */
-    public String getLibraryPath() {
-        return nativeGetLibraryPath();
+    public boolean isActivated() {
+        return mActivated;
     }
 
     /**
-     * API for getting the version of the bundle
+     * Set the current activation status of the bundle
      *
-     * @return string - version of the bundle
+     * @return boolean - bundle has been successfully loaded and started
      *
      */
-    public String getVersion() {
-        return nativeGetVersion();
+    protected void setActivated(boolean activated) {
+        mActivated = activated;
     }
-
 }
diff --git a/service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/RcsResourceAttributes.java b/service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/RcsResourceAttributes.java
new file mode 100644 (file)
index 0000000..87bb7e4
--- /dev/null
@@ -0,0 +1,202 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+
+package org.iotivity.service.resourcecontainer;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ *
+ * This class represents the attributes for a resource.
+ *
+ * @see RcsValue
+ */
+public final class RcsResourceAttributes 
+{
+
+    private final Map<String, RcsValue> mCache = new HashMap<>();
+
+    public RcsResourceAttributes() {
+    }
+
+    public RcsResourceAttributes(RcsResourceAttributes attrs){
+        for (final String key : attrs.keySet()) {
+            mCache.put(key, attrs.get(key));
+        }
+    }
+
+    /**
+     * Returns a unmodifiable Set view of the keys contained in this attributes.
+     *
+     * @return an unmodifiable set view of the keys in this attributes
+     */
+    public Set<String> keySet() {
+        return Collections.unmodifiableSet(mCache.keySet());
+    }
+
+    /**
+     * Returns the value to which the specified key is mapped, or null if this
+     * contains no mapping for the key.
+     *
+     * @param key
+     *            the key whose associated value is to be returned
+     *
+     * @return the value to which the specified key is mapped, or null if this
+     *         contains no mapping for the key
+     *
+     * @throws NullPointerException
+     *             if key is null
+     */
+    public RcsValue get(String key) {
+        if (key == null) throw new NullPointerException("key is null");
+        
+        return mCache.get(key);
+    }
+
+    /**
+     * Sets the specified value with the specified key.
+     * If the object previously contained a mapping for the key, the old value
+     * is replaced by the specified value.
+     *
+     * @param key
+     *            key with which the specified value is to be associated
+     *
+     * @param value
+     *            value to be associated with the specified key
+     *
+     * @throws NullPointerException
+     *             if key or value is null
+     *
+     */
+    public void put(String key, RcsValue value) {
+        if (key == null) throw new NullPointerException("key is null");
+        if (value == null) throw new NullPointerException("value is null");
+
+        mCache.put(key, value);
+    }
+
+    /**
+     * Sets the specified value with the specified key.
+     * If the object previously contained a mapping for the key, the old value
+     * is replaced by the specified value.
+     *
+     * @param key
+     *            key with which the specified value is to be associated
+     *
+     * @param value
+     *            value to be associated with the specified key
+     *
+     * @throws NullPointerException
+     *             if key or value is null
+     * @throws IllegalArgumentException
+     *             if object is not supported type by {@link RcsValue}
+     */
+    public void put(String key, Object object) {
+        if (key == null) throw new NullPointerException("key is null");
+
+        put(key, new RcsValue(object));
+    }
+
+    /**
+     * Returns true if this contains no key-value mappings.
+     *
+     * @return true if this contains no key-value mappings
+     */
+    public boolean isEmpty() {
+        return mCache.isEmpty();
+    }
+
+    /**
+     * Returns the number of key-value mappings.
+     *
+     * @return the number of key-value mappings
+     */
+    public int size() {
+        return mCache.size();
+    }
+
+    /**
+     * Removes the mapping for a key from this attributes if it is present.
+     *
+     * @param key
+     *            key whose mapping is to be removed
+     *
+     * @return true if the key is present and the the value mapped is removed.
+     */
+    public boolean remove(String key) {
+        if (key == null) throw new NullPointerException("key is null");
+      
+        final boolean cacheRemove = mCache.remove(key) != null;      
+
+        return cacheRemove;
+    }
+
+    /**
+     * Removes all of the mappings.
+     */
+    public void clear(){
+        mCache.clear();
+    }
+
+    /**
+     * Returns true if this contains a mapping for the specified key.
+     *
+     * @param key
+     *            key whose presence is to be tested
+     *
+     * @return true if this contains a mapping for the specified key.
+     *
+     * @throws NullPointerException
+     *             if key is null
+     */
+    public boolean contains(String key) {
+        if (key == null) throw new NullPointerException("key is null");
+
+        return mCache.containsKey(key);
+    }
+    
+
+    @Override
+    public boolean equals(Object o) {
+        if (o == this) return true;
+        if (!(o instanceof RcsResourceAttributes)) return false;        
+        RcsResourceAttributes rhs = (RcsResourceAttributes) o;
+        return mCache.equals(rhs.mCache);
+    }
+
+    @Override
+    public int hashCode() {
+        return mCache.hashCode();
+    }
+    
+    /**
+     * Updates all properties provided as parameter.
+     */
+    public void put(RcsResourceAttributes attrs){
+        for (final String key : attrs.keySet()) {
+            mCache.put(key, attrs.get(key));
+        }
+    }
+}
index bb19810..da26675 100644 (file)
@@ -1,22 +1,23 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 
 /**
  * @file
 package org.iotivity.service.resourcecontainer;
 
 import java.util.List;
+
 import java.util.Map;
+import java.util.Enumeration;
+import android.util.Log;
+import android.content.Context;
+import java.util.Vector;
+
+import dalvik.system.DexFile;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
+import dalvik.system.PathClassLoader;
+import java.net.URLClassLoader;
+
+import java.util.Hashtable;
+import java.io.File;
+import java.net.URL;
+
+import java.lang.reflect.InvocationTargetException;
 
-// TODO null check for parameters
 /**
  * This class provides APIs for managing the container and bundles in the
  * container.
  */
-public class RcsResourceContainer {
+public class RcsResourceContainer implements RcsResourceContainerBundleAPI {
+
+    private static final String TAG = RcsResourceContainer.class.getSimpleName();
 
     static {
         System.loadLibrary("gnustl_shared");
@@ -48,7 +67,7 @@ public class RcsResourceContainer {
         System.loadLibrary("resource_container_jni");
     }
 
-    private static RcsResourceContainer sInstance = new RcsResourceContainer();
+    private Context appContext;
 
     private native void nativeStartContainer(String configFile);
 
@@ -72,14 +91,24 @@ public class RcsResourceContainer {
             String resourceUri);
 
     private native List<String> nativeListBundleResources(String bundleId);
-
-    /**
-     * API for getting the Instance of ResourceContainer class
-     *
-     */
-    public static RcsResourceContainer getInstance() {
-        return sInstance;
+    
+    private native void nativeRegisterBundleResource(BundleResource resource,
+        String[] attributes, String bundleId, String uri,
+        String resourceType, String name);
+    
+    private native void nativeUnregisterBundleResource(BundleResource resource,
+        String uri);
+    
+    private native int nativeGetNumberOfConfiguredResources(String bundleId);
+        
+    private native String[] nativeGetConfiguredResourceParams(String bundleId,
+        int resId);  
+    
+    public RcsResourceContainer(Context appContext){
+        this.appContext = appContext;
     }
+    
+    private Hashtable<String, BundleActivator> activators = new Hashtable<String, BundleActivator>();
 
     /**
      * API for starting the Container
@@ -92,14 +121,109 @@ public class RcsResourceContainer {
      *            information.
      *
      */
-    public void startContainer(String configFile) {
+    public List<RcsBundleInfo> startContainer(String configFile) {
+        if(configFile == null || configFile.isEmpty()){
+            throw new IllegalArgumentException(
+               "Configuration file is null or empty.");
+       }
         nativeStartContainer(configFile);
+        Log.d(TAG, "startContainer in Java");
+        List<RcsBundleInfo> bundles = listBundles();
+        Log.d(TAG, "startContainer. There are " + bundles.size() + " bundles.");
+        for(RcsBundleInfo bundleInfo : bundles){
+            Log.d(TAG, "bundle-id: " + bundleInfo.getID() + ", " + bundleInfo.getPath());
+            if(bundleInfo.getPath().endsWith(".apk")){ // load classes from standalone application
+                startBundleFromStandaloneApp(bundleInfo);
+            }else if(bundleInfo.getPath().endsWith(".jar")){ // load classes from library
+                startBundleFromJar(bundleInfo);
+            }
+        }
+        return bundles;
+    }
+
+    private void startBundleFromStandaloneApp(RcsBundleInfo bundleInfo){
+        if(bundleInfo == null){
+            throw new IllegalArgumentException(
+               "bundleInfo parameter is null or empty.");
+        }
+        String packageName = bundleInfo.getPath().replace(".apk", "");
+        try{
+            PackageManager packageManager = appContext.getPackageManager();
+            ApplicationInfo appInfo = packageManager.getApplicationInfo(packageName, 0);
+            DexFile df = new DexFile(appInfo.sourceDir);
+            ClassLoader cl = appContext.getClassLoader();
+            for (Enumeration<String> iter = df.entries(); iter.hasMoreElements(); ) {
+                String classN = iter.nextElement();
+                if (classN.contains(packageName)) {
+                    Log.d(TAG,"Class: " + classN);
+                    df.loadClass(classN, cl);
+                }
+            }
+            String className = bundleInfo.getActivatorName();
+            Log.d(TAG, "Loading activator: " + className);
+            Class activatorClass = df.loadClass(className, cl);
+            activateBundle(activatorClass, bundleInfo);
+        }
+        catch(Exception e){
+            Log.e(TAG, e.getMessage(), e);
+        }
+        Log.d(TAG, "Have to register android bundle");
+    }
+    
+    private void startBundleFromJar(RcsBundleInfo bundleInfo){
+        if(bundleInfo == null){
+            throw new IllegalArgumentException(
+               "bundleInfo parameter is null");
+        }
+        try{
+            Log.e(TAG, "Loading from .jar file.");
+            
+            PathClassLoader classLoader = new PathClassLoader(bundleInfo.getPath(),
+                    RcsResourceContainer.class.getClassLoader());
+           
+            String className = bundleInfo.getActivatorName().replace('/', '.');
+            Log.d(TAG, "Loading activator: " + className);
+            Class activatorClass = Class.forName(className, true, classLoader);
+
+            activateBundle(activatorClass, bundleInfo);
+        }
+        catch(Exception e){
+            Log.e(TAG, e.getMessage(), e);
+        }
+        Log.d(TAG, "Have to register android bundle");
+    }
+    
+    private void activateBundle(Class activatorClass, RcsBundleInfo bundleInfo) throws
+        NoSuchMethodException, InstantiationException, IllegalAccessException, 
+        InvocationTargetException{
+        if(activatorClass == null){
+            throw new IllegalArgumentException(
+               "activatorClass is null.");
+        }
+        if(bundleInfo == null){
+            throw new IllegalArgumentException(
+               "bundleInfo is null.");
+        }
+        if(activatorClass!= null){
+            BundleActivator activator = (BundleActivator) activatorClass.
+                    getConstructor(RcsResourceContainerBundleAPI.class, Context.class).
+                    newInstance(this, appContext);
+            activator.activateBundle();
+            activators.put(bundleInfo.getID(), activator);
+            bundleInfo.setActivated(true);
+        }else{
+            Log.e(TAG, "Activator is null.");
+        }
     }
 
     /**
      * API for stopping the Container
      */
     public void stopContainer() {
+        // stop all android bundles
+        for(BundleActivator activator :activators.values()){
+            activator.deactivateBundle();
+        }
         nativeStopContainer();
     }
 
@@ -135,6 +259,22 @@ public class RcsResourceContainer {
      */
     public void addBundle(String bundleId, String bundleUri, String bundlePath,
             String activator, Map<String, String> params) {
+        if(bundleId == null){
+            throw new IllegalArgumentException(
+               "bundleId parameter is null.");
+        }
+       if(bundleUri == null){
+            throw new IllegalArgumentException(
+               "bundleUri is null.");
+        }
+       if(bundlePath == null){
+            throw new IllegalArgumentException(
+               "bundlePath is null.");
+        }
+       if(activator == null){
+            throw new IllegalArgumentException(
+               "activator is null.");
+        }
         nativeAddBundle(bundleId, bundleUri, bundlePath, activator, params);
     }
 
@@ -146,6 +286,14 @@ public class RcsResourceContainer {
      *
      */
     public void removeBundle(String bundleId) {
+        if(bundleId == null || bundleId.isEmpty()){
+            throw new IllegalArgumentException(
+               "bundleId parameter is null or empty.");
+        }
+        if(activators.contains(bundleId)){
+            // deactivate android bundle
+            activators.get(bundleId).deactivateBundle();
+        }
         nativeRemoveBundle(bundleId);
     }
 
@@ -157,7 +305,27 @@ public class RcsResourceContainer {
      *
      */
     public void startBundle(String bundleId) {
-        nativeStartBundle(bundleId);
+        Log.d(TAG, "startBundle");
+        if(bundleId == null || bundleId.isEmpty()){
+            throw new IllegalArgumentException(
+               "bundleId parameter is null or empty.");
+        }
+        List<RcsBundleInfo> bundles = listBundles();
+
+        for(RcsBundleInfo bundleInfo : bundles){
+            if(bundleInfo.getID().equals(bundleId) && bundleInfo.getPath().endsWith(".apk")){
+                Log.d(TAG, "Have to start android bundle");
+                Log.d(TAG, "bundle-id: " + bundleInfo.getID() + ", " + bundleInfo.getPath());
+                if(bundleInfo.getPath().endsWith(".apk")){
+                    startBundleFromStandaloneApp(bundleInfo);
+                }else if(bundleInfo.getID().equals(bundleId) &&
+                        bundleInfo.getPath().endsWith(".jar")){ // load classes from library
+                    startBundleFromJar(bundleInfo);
+                }
+            }else{
+                nativeStartBundle(bundleId);
+            }
+        }
     }
 
     /**
@@ -167,7 +335,11 @@ public class RcsResourceContainer {
      *            Id of the Bundle
      *
      */
-    public void stopBundle(String bundleId) {
+    public void stopBundle(String bundleId){
+        if(bundleId == null || bundleId.isEmpty()){
+            throw new IllegalArgumentException(
+               "bundleId parameter is null or empty.");
+        }
         nativeStopBundle(bundleId);
     }
 
@@ -184,6 +356,14 @@ public class RcsResourceContainer {
      */
     public void addResourceConfig(String bundleId, String resourceUri,
             Map<String, String> params) {
+        if(bundleId == null || bundleId.isEmpty()){
+            throw new IllegalArgumentException(
+               "bundleId parameter is null or empty.");
+        }
+       if(resourceUri == null || resourceUri.isEmpty()){
+            throw new IllegalArgumentException(
+               "resourceUri parameter is null or empty.");
+        }
         nativeAddResourceConfig(bundleId, resourceUri, params);
     }
 
@@ -197,6 +377,14 @@ public class RcsResourceContainer {
      *
      */
     public void removeResourceConfig(String bundleId, String resourceUri) {
+        if(bundleId == null || bundleId.isEmpty()){
+            throw new IllegalArgumentException(
+               "bundleId parameter is null or empty.");
+        }
+       if(resourceUri == null || resourceUri.isEmpty()){
+            throw new IllegalArgumentException(
+               "resourceUri parameter is null or empty.");
+        }
         nativeRemoveResourceConfig(bundleId, resourceUri);
     }
 
@@ -209,6 +397,114 @@ public class RcsResourceContainer {
      * @return List<String> All the bundle resources
      */
     public List<String> listBundleResources(String bundleId) {
+        if(bundleId == null || bundleId.isEmpty()){
+            throw new IllegalArgumentException(
+               "bundleId parameter is null or empty.");
+        }
         return nativeListBundleResources(bundleId);
     }
+
+    /**
+     * Registers a bundle resource
+     *
+     * @param bundleId
+     *            Id of the Bundle
+     * @param resource
+     *            resource to be registered
+     */
+    public void registerResource(String bundleId, BundleResource resource){
+        Log.d(TAG, "register Resource");
+        // bundleResources.add(resource);
+        
+        if(bundleId == null || bundleId.isEmpty()){
+               throw new IllegalArgumentException(
+               "bundleId parameter is null or empty.");
+        }
+       if(resource == null){
+               throw new IllegalArgumentException(
+               "resource parameter is null.");
+        }
+        nativeRegisterBundleResource(resource, resource.getAttributeKeys(), bundleId,
+                        resource.getURI(), resource.getResourceType(),
+                        resource.getName());
+    }
+
+    /**
+     * Returns the bundle configuration for the resources
+     *
+     * @param bundleId
+     *            Id of the Bundle
+     *
+     * @return List<ResourceConfig> All the resource configurations for the given bundle
+     */
+    public List<ResourceConfig> getConfiguredBundleResources(String bundleId) {
+        Log.d(TAG, "getConfiguredBundleResource " + bundleId);
+        Vector<ResourceConfig> configs = new Vector<ResourceConfig>();
+        if(bundleId == null || bundleId.isEmpty()){
+            throw new IllegalArgumentException(
+               "bundleId parameter is null or empty.");
+        }
+        int configuredResources = getNumberOfConfiguredResources(bundleId);
+        Log.d(TAG, "configured resources " + configuredResources);
+
+        for (int i = 0; i < configuredResources; i++) {
+                String[] resourceParams = getConfiguredResourceParams(bundleId, i);
+                ResourceConfig config = new ResourceConfig(resourceParams);
+                configs.add(config);
+        }
+        return configs;
+    }
+
+    /**
+     * Unregisters a bundle resource
+     *
+     * @param resource
+     *            Resource to be unregistered
+     */
+    public void unregisterResource(BundleResource resource){
+        Log.d(TAG, "unregister Resource");
+        if(resource == null){
+               throw new IllegalArgumentException(
+               "resource is null.");
+        }
+        nativeUnregisterBundleResource(resource, resource.getURI());
+    }
+
+    /**
+     * Returns the number of configured resources
+     *
+     * @param bundleId
+     *            Id of the Bundle
+     * @return number of configured resources
+     */
+    public int getNumberOfConfiguredResources(String bundleId){
+        Log.d(TAG, "getNumberOfConfiguredResources");
+        if(bundleId == null || bundleId.isEmpty()){
+            throw new IllegalArgumentException(
+               "bundleId parameter is null or empty.");
+        }
+        return nativeGetNumberOfConfiguredResources(bundleId);
+    }
+
+    /**
+     * Provides the configured resource parameter
+     *
+     * @param bundleId
+     *            Id of the Bundle
+     * @param resId
+                  Continuous numeric identifier within the bundle
+     * @return resource paramaters such as URI, resource type, name, etc. for the resource
+     */
+    public String[] getConfiguredResourceParams(String bundleId, int resId){
+        Log.d(TAG, "getConfiguredResourceParams");
+        if(bundleId == null || bundleId.isEmpty()){ 
+            throw new IllegalArgumentException(
+               "bundleId parameter is null or empty.");
+        }
+       if(resId < 0){
+           throw new IllegalArgumentException(
+               "resId paramater has to be non-negative.");
+       }
+        return nativeGetConfiguredResourceParams(bundleId, resId);
+    }
 }
diff --git a/service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/RcsResourceContainerBundleAPI.java b/service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/RcsResourceContainerBundleAPI.java
new file mode 100644 (file)
index 0000000..721a7fb
--- /dev/null
@@ -0,0 +1,44 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+
+/**
+ * @file
+ * This file contains the Resource Container APIs
+ */
+package org.iotivity.service.resourcecontainer;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+
+/**
+ * This class provides APIs for managing the container and bundles in the
+ * container. The container provides such an interface to the bundle developer
+ * to access the configuration and to register/unregister resources.
+ */
+public interface RcsResourceContainerBundleAPI{
+
+    public void registerResource(String bundleId, BundleResource resource);
+
+    public void unregisterResource(BundleResource resource);
+
+    public List<ResourceConfig> getConfiguredBundleResources(String bundleId);
+}
diff --git a/service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/RcsValue.java b/service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/RcsValue.java
new file mode 100644 (file)
index 0000000..f21ccc9
--- /dev/null
@@ -0,0 +1,877 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.service.resourcecontainer;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Value holds a value among various types at a time.
+ *
+ * Type helps identify type information of Value.
+ *
+ * @see RcsResourceAttributes
+ * @see Type
+ */
+public final class RcsValue {
+
+    private static class NullType {
+        @Override
+        public String toString() {
+            return "";
+        }
+    }
+
+    /**
+     * Identifiers for types of Value.
+     *
+     * @see Type
+     */
+    public static enum TypeId {
+        NULL, BOOLEAN, INTEGER, DOUBLE, STRING, ATTRIBUTES, ARRAY;
+    }
+
+    /**
+     * A Helper class to identify types of Value.
+     *
+     * @see RcsResourceAttributes
+     * @see RcsValue
+     * @see TypeId
+     */
+    public static class Type {
+        private final TypeId mTypeId;
+
+        Type(TypeId typeId) {
+            mTypeId = typeId;
+        }
+
+        /**
+         * Returns type identifier.
+         *
+         * @return Identifier of type
+         *
+         * @see #getBaseTypeId(RcsValue.Type)
+         */
+        public final TypeId getId() {
+            return mTypeId;
+        }
+
+        protected TypeId getBaseTypeId() {
+            return mTypeId;
+        }
+
+        protected int getDepth() {
+            return 0;
+        }
+
+        /**
+         * Returns the type identifier of a base type of sequence.
+         *
+         * For non sequence types, it is equivalent to calling {@link #getId()}.
+         *
+         * @return identifier of type
+         *
+         * @see getDepth
+         * @see getId
+         */
+        public static TypeId getBaseTypeId(Type t) {
+            return t.getBaseTypeId();
+        }
+
+        /**
+         * Returns the depth of a type.
+         *
+         * The return will be zero for non sequence types.
+         *
+         * @see getBaseTypeId
+         */
+        public static int getDepth(Type t) {
+            return t.getDepth();
+        }
+
+        /**
+         * Factory method to create Type instance from an object.
+         * Note that object must be a supported type by RcsValue.
+         *
+         * @return An instance that has TypeId for obj.
+         *
+         * @throws NullPointerException
+         *             if obj is null.
+         * @throws IllegalArgumentException
+         *             if obj is not supported type.
+         *
+         */
+        public static Type typeOf(Object obj) {
+            if (obj == null) {
+                throw new NullPointerException("object is null");
+            }
+
+            return typeOf(obj.getClass());
+        }
+
+        /**
+         * Factory method to create Type instance from a class.
+         * Note that class must be a supported type by RcsValue.
+         *
+         * @return An instance that has TypeId for class.
+         *
+         * @throws NullPointerException
+         *             if cls is null.
+         * @throws IllegalArgumentException
+         *             if cls is not supported type.
+         *
+         */
+        public static Type typeOf(Class<?> cls) {
+            if (cls == null) {
+                throw new NullPointerException("class is null");
+            }
+
+            if (sTypes.containsKey(cls)) return sTypes.get(cls);
+
+            throw new IllegalArgumentException(
+                    cls.getSimpleName() + " is not supported type.");
+        }
+    }
+
+    private static class ArrayType extends Type {
+        private final TypeId mBaseTypeId;
+        private final int    mDimension;
+
+        ArrayType(TypeId baseTypeId, int dimension) {
+            super(TypeId.ARRAY);
+
+            mBaseTypeId = baseTypeId;
+            mDimension = dimension;
+        }
+
+        @Override
+        protected TypeId getBaseTypeId() {
+            return mBaseTypeId;
+        }
+
+        @Override
+        protected int getDepth() {
+            return mDimension;
+        }
+    }
+
+    private static final NullType sNullValue = new NullType();
+
+    private static Map<Class<?>, Type> sTypes;
+
+    private final Object mObject;
+    private Type         mType;
+
+    static {
+        final Map<Class<?>, Type> types = new HashMap<Class<?>, Type>();
+
+        types.put(NullType.class, new Type(TypeId.NULL));
+        types.put(Boolean.class, new Type(TypeId.BOOLEAN));
+        types.put(Integer.class, new Type(TypeId.INTEGER));
+        types.put(Double.class, new Type(TypeId.DOUBLE));
+        types.put(String.class, new Type(TypeId.STRING));
+        types.put(RcsResourceAttributes.class, new Type(TypeId.ATTRIBUTES));
+
+        types.put(boolean[].class, new ArrayType(TypeId.BOOLEAN, 1));
+        types.put(int[].class, new ArrayType(TypeId.INTEGER, 1));
+        types.put(double[].class, new ArrayType(TypeId.DOUBLE, 1));
+        types.put(String[].class, new ArrayType(TypeId.STRING, 1));
+        types.put(RcsResourceAttributes[].class,
+                new ArrayType(TypeId.ATTRIBUTES, 1));
+
+        types.put(boolean[][].class, new ArrayType(TypeId.BOOLEAN, 2));
+        types.put(int[][].class, new ArrayType(TypeId.INTEGER, 2));
+        types.put(double[][].class, new ArrayType(TypeId.DOUBLE, 2));
+        types.put(String[][].class, new ArrayType(TypeId.STRING, 2));
+        types.put(RcsResourceAttributes[][].class,
+                new ArrayType(TypeId.ATTRIBUTES, 2));
+
+        types.put(boolean[][][].class, new ArrayType(TypeId.BOOLEAN, 3));
+        types.put(int[][][].class, new ArrayType(TypeId.INTEGER, 3));
+        types.put(double[][][].class, new ArrayType(TypeId.DOUBLE, 3));
+        types.put(String[][][].class, new ArrayType(TypeId.STRING, 3));
+        types.put(RcsResourceAttributes[][][].class,
+                new ArrayType(TypeId.ATTRIBUTES, 3));
+
+        sTypes = Collections.unmodifiableMap(types);
+
+    }
+
+    static boolean isSupportedType(Class<?> cls) {
+        return sTypes.containsKey(cls);
+    }
+
+    static void verifySupportedType(Class<?> cls) {
+        if (!isSupportedType(cls)) {
+            throw new IllegalArgumentException(
+                    cls.getSimpleName() + " is not supported type.");
+        }
+    }
+
+    /**
+     * Constructs a new value with an object.
+     *
+     * @param value
+     *            An object
+     *
+     * @throws NullPointerException
+     *             if value is null.
+     * @throws IllegalArgumentException
+     *             if value is not supported type.
+     */
+    public RcsValue(Object value) {
+        if (value == null) throw new NullPointerException("value is null!");
+
+        verifySupportedType(value.getClass());
+
+        mObject = value;
+    }
+
+    /**
+     * Constructs a new value that holds null value.
+     *
+     */
+    public RcsValue() {
+        this(sNullValue);
+    }
+
+    /**
+     * Constructs a new value that holds a boolean value.
+     *
+     * @param value
+     *            a boolean
+     */
+    public RcsValue(boolean value) {
+        this((Object) value);
+    }
+
+    /**
+     * Constructs a new value that holds an int value.
+     *
+     * @param value
+     *            an int
+     */
+    public RcsValue(int value) {
+        this((Object) value);
+    }
+
+    /**
+     * Constructs a new value that holds a double value.
+     *
+     * @param value
+     *            a double
+     */
+    public RcsValue(double value) {
+        this((Object) value);
+    }
+
+    /**
+     * Constructs a new value that holds a String value.
+     *
+     * @param value
+     *            a String
+     *
+     * @throws NullPointerException
+     *             if value is null.
+     */
+    public RcsValue(String value) {
+        this((Object) value);
+    }
+
+    /**
+     * Constructs a new value that holds a RcsResourceAttributes value.
+     *
+     * @param value
+     *            a RcsResourceAttributes
+     *
+     * @throws NullPointerException
+     *             if value is null.
+     */
+    public RcsValue(RcsResourceAttributes value) {
+        this((Object) value);
+    }
+
+    /**
+     * Constructs a new value that holds a boolean array.
+     *
+     * @param value
+     *            a boolean array
+     *
+     * @throws NullPointerException
+     *             if value is null.
+     */
+    public RcsValue(boolean[] value) {
+        this((Object) value);
+    }
+
+    /**
+     * Constructs a new value that holds a two-dimensional boolean array.
+     *
+     * @param value
+     *            a two-dimensional boolean array
+     *
+     * @throws NullPointerException
+     *             if value is null.
+     */
+    public RcsValue(boolean[][] value) {
+        this((Object) value);
+    }
+
+    /**
+     * Constructs a new value that holds a three-dimensional boolean array.
+     *
+     * @param value
+     *            a three-dimensional boolean array
+     *
+     * @throws NullPointerException
+     *             if value is null.
+     */
+    public RcsValue(boolean[][][] value) {
+        this((Object) value);
+    }
+
+    /**
+     * Constructs a new value that holds an int array.
+     *
+     * @param value
+     *            an int array
+     *
+     * @throws NullPointerException
+     *             if value is null.
+     */
+    public RcsValue(int[] value) {
+        this((Object) value);
+    }
+
+    /**
+     * Constructs a new value that holds a two-dimensional int array.
+     *
+     * @param value
+     *            a two-dimensional int array
+     *
+     * @throws NullPointerException
+     *             if value is null.
+     */
+    public RcsValue(int[][] value) {
+        this((Object) value);
+    }
+
+    /**
+     * Constructs a new value that holds a three-dimensional int array.
+     *
+     * @param value
+     *            a three-dimensional int array
+     *
+     * @throws NullPointerException
+     *             if value is null.
+     */
+    public RcsValue(int[][][] value) {
+        this((Object) value);
+    }
+
+    /**
+     * Constructs a new value that holds a double array.
+     *
+     * @param value
+     *            a double array
+     *
+     * @throws NullPointerException
+     *             if value is null.
+     */
+    public RcsValue(double[] value) {
+        this((Object) value);
+    }
+
+    /**
+     * Constructs a new value that holds a two-dimensional double array.
+     *
+     * @param value
+     *            a two-dimensional double array
+     *
+     * @throws NullPointerException
+     *             if value is null.
+     */
+    public RcsValue(double[][] value) {
+        this((Object) value);
+    }
+
+    /**
+     * Constructs a new value that holds a three-dimensional double array.
+     *
+     * @param value
+     *            a three-dimensional double array
+     *
+     * @throws NullPointerException
+     *             if value is null.
+     */
+    public RcsValue(double[][][] value) {
+        this((Object) value);
+    }
+
+    /**
+     * Constructs a new value that holds a String array.
+     *
+     * @param value
+     *            a String array
+     *
+     * @throws NullPointerException
+     *             if value is null.
+     */
+    public RcsValue(String[] value) {
+        this((Object) value);
+    }
+
+    /**
+     * Constructs a new value that holds a two-dimensional String array.
+     *
+     * @param value
+     *            a two-dimensional String array
+     *
+     * @throws NullPointerException
+     *             if value is null.
+     */
+    public RcsValue(String[][] value) {
+        this((Object) value);
+    }
+
+    /**
+     * Constructs a new value that holds a three-dimensional String array.
+     *
+     * @param value
+     *            a three-dimensional String array
+     *
+     * @throws NullPointerException
+     *             if value is null.
+     */
+    public RcsValue(String[][][] value) {
+        this((Object) value);
+    }
+
+    /**
+     * Constructs a new value that holds a RcsResourceAttributes array.
+     *
+     * @param value
+     *            a RcsResourceAttributes array
+     *
+     * @throws NullPointerException
+     *             if value is null.
+     */
+    public RcsValue(RcsResourceAttributes[] value) {
+        this((Object) value);
+    }
+
+    /**
+     * Constructs a new value that holds a two-dimensional RcsResourceAttributes
+     * array.
+     *
+     * @param value
+     *            a two-dimensional RcsResourceAttributes array
+     *
+     * @throws NullPointerException
+     *             if value is null.
+     */
+    public RcsValue(RcsResourceAttributes[][] value) {
+        this((Object) value);
+    }
+
+    /**
+     * Constructs a new value that holds a three-dimensional
+     * RcsResourceAttributes array.
+     *
+     * @param value
+     *            a three-dimensional RcsResourceAttributes array
+     *
+     * @throws NullPointerException
+     *             if value is null.
+     */
+    public RcsValue(RcsResourceAttributes[][][] value) {
+        this((Object) value);
+    }
+
+    /**
+     * Returns whether the value is null.
+     *
+     * @return true if the value is null.
+     */
+    public boolean isNull() {
+        return isNullObject(mObject);
+    }
+
+    /**
+     * Returns whether the object represents null for RcsValue.
+     *
+     * @param o
+     *            an object to be tested
+     *
+     * @return true if the object represents null.
+     */
+    public static boolean isNullObject(Object o) {
+        return o == sNullValue;
+    }
+
+    /**
+     * Returns type information.
+     *
+     * @return type information for the value.
+     */
+    public Type getType() {
+        if (mType == null) mType = Type.typeOf(mObject);
+        return mType;
+    }
+
+    /**
+     * Returns the value as T.
+     *
+     * @return a value as T
+     *
+     * @throws ClassCastException
+     *             if the value is not of T.
+     */
+    @SuppressWarnings("unchecked")
+    public <T> T get() {
+        return (T) mObject;
+    }
+
+    @SuppressWarnings("unchecked")
+    private <T> T getOrNull() {
+        try {
+            return (T) mObject;
+        } catch (final ClassCastException e) {
+            return null;
+        }
+    }
+
+    /**
+     * Returns the value as an Object.
+     *
+     * @return an Object
+     */
+    public Object asObject() {
+        return mObject;
+    }
+
+    /**
+     * Returns the value as a boolean, false if the value is not the desired
+     * type.
+     *
+     * @return a boolean value
+     *
+     */
+    public boolean asBoolean() {
+        return asBoolean(false);
+    }
+
+    /**
+     * Returns the value as a boolean.
+     *
+     * @param defaultValue
+     *            value to return if the value is not boolean.
+     *
+     * @return a boolean value
+     *
+     */
+    public boolean asBoolean(boolean defaultValue) {
+        try {
+            return get();
+        } catch (final ClassCastException e) {
+            return defaultValue;
+        }
+    }
+
+    /**
+     * Returns the value as an int, 0 if the value is not the desired type.
+     *
+     * @return an int value
+     *
+     */
+    public int asInt() {
+        return asInt(0);
+    }
+
+    /**
+     * Returns the value as an int.
+     *
+     * @param defaultValue
+     *            value to return if the value is not int.
+     *
+     * @return an int value
+     *
+     */
+    public int asInt(int defaultValue) {
+        try {
+            return get();
+        } catch (final ClassCastException e) {
+            return defaultValue;
+        }
+    }
+
+    /**
+     * Returns the value as a double, 0 if the value is not the desired type.
+     *
+     * @return a double value
+     *
+     */
+    public double asDouble() {
+        return asDouble(0);
+    }
+
+    /**
+     * Returns the value as a double.
+     *
+     * @param defaultValue
+     *            value to return if the value is not double.
+     *
+     * @return a double value
+     *
+     */
+    public double asDouble(double defaultValue) {
+        try {
+            return get();
+        } catch (final ClassCastException e) {
+            return defaultValue;
+        }
+    }
+
+    /**
+     * Returns the value as a string, null if the value is not the desired type.
+     *
+     * @return a string value
+     *
+     */
+    public String asString() {
+        return asString(null);
+    }
+
+    /**
+     * Returns the value as a String.
+     *
+     * @param defaultValue
+     *            value to return if the value is not String.
+     *
+     * @return a String value
+     *
+     */
+    public String asString(String defaultValue) {
+        try {
+            return get();
+        } catch (final ClassCastException e) {
+            return defaultValue;
+        }
+    }
+
+    /**
+     * Returns the value as a RcsResourceAttributes,
+     * null if the value is not the desired type.
+     *
+     * @return a RcsResourceAttributes value
+     *
+     */
+    public RcsResourceAttributes asAttributes() {
+        return getOrNull();
+    }
+
+    /**
+     * Returns the value as a boolean array, null if the value is not the
+     * desired type.
+     *
+     * @return a boolean array
+     *
+     */
+    public boolean[] asBooleanArray() {
+        return getOrNull();
+    }
+
+    /**
+     * Returns the value as a two-dimensional boolean array, null if the value
+     * is not the desired type.
+     *
+     * @return a two-dimensional boolean array
+     *
+     */
+    public boolean[][] asBoolean2DArray() {
+        return getOrNull();
+    }
+
+    /**
+     * Returns the value as a three-dimensional boolean array, null if the value
+     * is not the desired type.
+     *
+     * @return a three-dimensional boolean array
+     *
+     */
+    public boolean[][][] asBoolean3DArray() {
+        return getOrNull();
+    }
+
+    /**
+     * Returns the value as an int array, null if the value is not the
+     * desired type.
+     *
+     * @return an int array
+     *
+     */
+    public int[] asIntArray() {
+        return getOrNull();
+    }
+
+    /**
+     * Returns the value as a two-dimensional int array, null if the value
+     * is not the desired type.
+     *
+     * @return a two-dimensional int array
+     *
+     */
+    public int[][] asInt2DArray() {
+        return getOrNull();
+    }
+
+    /**
+     * Returns the value as a three-dimensional int array, null if the value
+     * is not the desired type.
+     *
+     * @return a three-dimensional int array
+     *
+     */
+    public int[][][] asInt3DArray() {
+        return getOrNull();
+    }
+
+    /**
+     * Returns the value as a double array, null if the value is not the
+     * desired type.
+     *
+     * @return a double array
+     *
+     */
+    public double[] asDoubleArray() {
+        return getOrNull();
+    }
+
+    /**
+     * Returns the value as a two-dimensional double array, null if the value
+     * is not the desired type.
+     *
+     * @return a two-dimensional double array
+     *
+     */
+    public double[][] asDouble2DArray() {
+        return getOrNull();
+    }
+
+    /**
+     * Returns the value as a three-dimensional double array, null if the value
+     * is not the desired type.
+     *
+     * @return a three-dimensional double array
+     *
+     */
+    public double[][][] asDouble3DArray() {
+        return getOrNull();
+    }
+
+    /**
+     * Returns the value as a string array, null if the value is not the
+     * desired type.
+     *
+     * @return a string array
+     *
+     */
+    public String[] asStringArray() {
+        return getOrNull();
+    }
+
+    /**
+     * Returns the value as a two-dimensional string array, null if the value
+     * is not the desired type.
+     *
+     * @return a two-dimensional string array
+     *
+     */
+    public String[][] asString2DArray() {
+        return getOrNull();
+    }
+
+    /**
+     * Returns the value as a three-dimensional string array, null if the value
+     * is not the desired type.
+     *
+     * @return a three-dimensional string array
+     *
+     */
+    public String[][][] asString3DArray() {
+        return getOrNull();
+    }
+
+    /**
+     * Returns the value as an attributes array, null if the value is not the
+     * desired type.
+     *
+     * @return an attributes array
+     *
+     */
+    public RcsResourceAttributes[] asAttributesArray() {
+        return getOrNull();
+    }
+
+    /**
+     * Returns the value as a two-dimensional attributes array, null if the
+     * value is not the desired type.
+     *
+     * @return a two-dimensional attributes array
+     *
+     */
+    public RcsResourceAttributes[][] asAttributes2DArray() {
+        return getOrNull();
+    }
+
+    /**
+     * Returns the value as a three-dimensional attributes array, null if the
+     * value is not the desired type.
+     *
+     * @return a three-dimensional attributes array
+     *
+     */
+    public RcsResourceAttributes[][][] asAttributes3DArray() {
+        return getOrNull();
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (o == this) return true;
+        if (!(o instanceof RcsValue)) return false;
+
+        final RcsValue rhs = (RcsValue) o;
+
+        return mObject.equals(rhs.mObject);
+    }
+
+    @Override
+    public int hashCode() {
+        return mObject.hashCode();
+    }
+
+    @Override
+    public String toString() {
+        return mObject.toString();
+    }
+
+}
diff --git a/service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/ResourceConfig.java b/service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/ResourceConfig.java
new file mode 100644 (file)
index 0000000..e0d0879
--- /dev/null
@@ -0,0 +1,118 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.service.resourcecontainer;
+
+/**
+ * This class holds the configuration parameters for a single resource instance provided
+ * by the resource bundle.
+ */
+public class ResourceConfig {
+    private String m_name, m_uri, m_resourceType, m_address;
+
+    /**
+     * Empty constructor for resoure config.
+     */
+    public ResourceConfig() {
+    }
+
+    /**
+     * Creates a new resource config instance.
+     * @param params Resource parameters as array. 1. Name, 2. URI, 3. Resource Type, 4. Address 
+     */
+    public ResourceConfig(String[] params) {
+        m_name = params[0];
+        m_uri = params[1];
+        m_resourceType = params[2];
+        m_address = params[3];
+    }
+
+    /**
+     * Returns the configured name
+     * @return name property
+     */
+    public String getName() {
+        return m_name;
+    }
+
+    /**
+     * Sets the name
+     * @param m_name Resource name
+     */
+    public void setName(String m_name) {
+        this.m_name = m_name;
+    }
+
+    /**
+     * Returns the configured URI
+     * @return Configured URI
+     */
+    public String getURI() {
+        return m_uri;
+    }
+
+    /**
+     * Sets the configured URI
+     * @param m_uri Configuration URI
+     */
+    public void setURI(String m_uri) {
+        this.m_uri = m_uri;
+    }
+
+    /**
+     * Returns the configured resource type
+     * @return configured resource type
+     */
+    public String getResourceType() {
+        return m_resourceType;
+    }
+
+    /**
+     * Sets the configured resource type
+     * @param m_resourceType updates the configured resource type
+     */
+    public void setResourceType(String m_resourceType) {
+        this.m_resourceType = m_resourceType;
+    }
+
+    /**
+     * Returns the configured address
+     * @return Configured address
+     */
+    public String getAddress() {
+        return m_address;
+    }
+
+    /**
+     * Sets the configured address
+     * @param m_address Configured address
+     */
+    public void setAddress(String m_address) {
+        this.m_address = m_address;
+    }
+
+    @Override
+    public String toString() {
+        return "ResourceConfig [m_name=" + m_name + ", m_uri=" + m_uri
+                + ", m_resourceType=" + m_resourceType + ", m_address="
+                + m_address + "]";
+    }
+
+}
diff --git a/service/resource-container/android/resource-container/src/main/java/org/iotivity/service/utils/RcsException.java b/service/resource-container/android/resource-container/src/main/java/org/iotivity/service/utils/RcsException.java
deleted file mode 100644 (file)
index 70b46c7..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-package org.iotivity.service.utils;
-
-/**
- * An exception that indicates there was an error with execution of Rcs APIs.
- */
-public class RcsException extends Exception {
-
-    private static final long serialVersionUID = 7044421943523001940L;
-
-    public RcsException(String message) {
-        super(message);
-    }
-}
diff --git a/service/resource-container/android/resource-container/src/main/java/org/iotivity/service/utils/RcsIllegalStateException.java b/service/resource-container/android/resource-container/src/main/java/org/iotivity/service/utils/RcsIllegalStateException.java
deleted file mode 100644 (file)
index c6150f5..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-package org.iotivity.service.utils;
-
-/**
- * Thrown when an action is attempted at a time when not in the correct state.
- *
- */
-public class RcsIllegalStateException extends RcsException {
-
-    private static final long serialVersionUID = 6142669404885957616L;
-
-    public RcsIllegalStateException(String message) {
-        super(message);
-    }
-
-}
diff --git a/service/resource-container/android/resource-container/src/main/java/org/iotivity/service/utils/RcsObject.java b/service/resource-container/android/resource-container/src/main/java/org/iotivity/service/utils/RcsObject.java
deleted file mode 100644 (file)
index 203651c..0000000
+++ /dev/null
@@ -1,58 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-package org.iotivity.service.utils;
-
-public class RcsObject {
-    static {
-        System.loadLibrary("gnustl_shared");
-        System.loadLibrary("oc_logger");
-        System.loadLibrary("connectivity_abstraction");
-        System.loadLibrary("ca-interface");
-        System.loadLibrary("octbstack");
-        System.loadLibrary("oc");
-        System.loadLibrary("rcs_client");
-        System.loadLibrary("rcs_server");
-        System.loadLibrary("rcs_common");
-        System.loadLibrary("rcs_container");
-        System.loadLibrary("resource_container_jni");
-    }
-
-    private long mNativeHandle;
-
-    private native void nativeDispose();
-
-    protected RcsObject() {
-    }
-
-    @Override
-    protected void finalize() throws Throwable {
-        super.finalize();
-
-        dispose();
-    }
-
-    protected void dispose() {
-        if (mNativeHandle != 0L) nativeDispose();
-    }
-
-    protected boolean hasHandle() {
-        return mNativeHandle != 0L;
-    }
-}
diff --git a/service/resource-container/android/resource-container/src/main/java/org/iotivity/service/utils/RcsPlatformException.java b/service/resource-container/android/resource-container/src/main/java/org/iotivity/service/utils/RcsPlatformException.java
deleted file mode 100644 (file)
index 52297be..0000000
+++ /dev/null
@@ -1,22 +0,0 @@
-package org.iotivity.service.utils;
-
-/**
- * Thrown when an operation that has base-layer dependency is failed.
- *
- */
-public class RcsPlatformException extends RcsException {
-
-    private static final long serialVersionUID = -6093438347973754721L;
-
-    private final int mReasonCode;
-
-    public RcsPlatformException(String message, int reasonCode) {
-        super(message);
-
-        mReasonCode = reasonCode;
-    }
-
-    public int getReasonCode() {
-        return mReasonCode;
-    }
-}
index 7a01fc1..d5620f6 100644 (file)
@@ -9,27 +9,46 @@ LOCAL_SRC_FILES := $(IOTIVITY_LIB_PATH)/librcs_container.so
 include $(PREBUILT_SHARED_LIBRARY)
 
 include $(CLEAR_VARS)
-LOCAL_LDLIBS := -L$(LOCAL_PATH)/$(IOTIVITY_LIB_PATH)/
-LOCAL_LDLIBS += -lrcs_common
+LOCAL_MODULE := rcs_common
+LOCAL_SRC_FILES := $(IOTIVITY_LIB_PATH)/librcs_common.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := rcs_client
+LOCAL_SRC_FILES := $(IOTIVITY_LIB_PATH)/librcs_client.so
+include $(PREBUILT_SHARED_LIBRARY)
 
+include $(CLEAR_VARS)
+LOCAL_MODULE := rcs_server
+LOCAL_SRC_FILES := $(IOTIVITY_LIB_PATH)/librcs_server.so
+include $(PREBUILT_SHARED_LIBRARY)
+include $(CLEAR_VARS)
 OIC_SRC_DIR := ../../../../../..
 LOCAL_MODULE := resource_container_jni
 
 LOCAL_C_INCLUDES := $(LOCAL_PATH)/util
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/c_common
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/csdk/stack/include
 LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/extlibs/boost/boost_1_58_0
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/service/resource-encapsulation/include
 LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/service/resource-container/include
+LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/service/resource-container/bundle-api/include
+LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/service/resource-container/src
+LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/service/resource-encapsulation/include
 LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/service/resource-encapsulation/src/serverBuilder/include
+LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/csdk/stack/include
+LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/csdk/logger/include
+LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/oc_logger/include
+LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/c_common
+
+LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/extlibs/
 
 LOCAL_SRC_FILES += $(patsubst $(LOCAL_PATH)/%, %, $(wildcard $(LOCAL_PATH)/util/*.cpp))
 LOCAL_SRC_FILES += $(patsubst $(LOCAL_PATH)/%, %, $(wildcard $(LOCAL_PATH)/*.cpp))
 
 LOCAL_CPPFLAGS := -std=c++0x -frtti -fexceptions
 
-LOCAL_LDLIBS += -llog
 
-LOCAL_SHARED_LIBRARIES += rcs_container
+
+LOCAL_LDLIBS := -llog 
+
+LOCAL_SHARED_LIBRARIES += rcs_container rcs_common rcs_client rcs_server rcs_jni
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/service/resource-container/android/resource-container/src/main/jni/JniBundleResource.cpp b/service/resource-container/android/resource-container/src/main/jni/JniBundleResource.cpp
new file mode 100644 (file)
index 0000000..1bed71c
--- /dev/null
@@ -0,0 +1,361 @@
+//******************************************************************
+//
+// 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 "JniBundleResource.h"
+#include "JniRcsResourceAttributes.h"
+#include "JavaClasses.h"
+#include "JavaLocalRef.h"
+#include "JNIEnvWrapper.h"
+#include "JniRcsValue.h"
+
+#include <jni.h>
+#include <string.h>
+#include <iostream>
+#include "Log.h"
+
+#define LOG_TAG "JNI-JniBundleResource"
+
+using namespace OIC::Service;
+using namespace std;
+
+namespace
+{
+    jclass g_cls_RCSBundleInfo;
+    jfieldID g_field_mNativeHandle;
+}
+
+void initRCSJniBundleResource(JNIEnvWrapper *env)
+{
+    auto clsJniBundleResource = env->FindClass(PACKAGE_NAME "/BundleResource");
+
+    g_field_mNativeHandle = env->GetFieldID(clsJniBundleResource, "mNativeHandle", "J");
+}
+
+JniBundleResource::JniBundleResource()
+{
+
+}
+
+void JniBundleResource::initAttributes()
+{
+
+}
+
+JniBundleResource::JniBundleResource(JNIEnv *env, jobject obj, jobject bundleResource,
+                                       string bundleId, jobjectArray attributes)
+{
+    LOGD("Creating android resource, bundleId: %s", bundleId.c_str());
+    (void) obj;
+    m_env = env;
+    int stringCount = m_env->GetArrayLength(attributes);
+    LOGD("string count is %d", stringCount);
+
+    LOGD("Get java vm.");
+    int jvmAccess = m_env->GetJavaVM(&m_jvm);
+
+
+    for (int i = 0; i < stringCount; i++)
+    {
+        jstring str = (jstring) m_env->GetObjectArrayElement(attributes, i);
+        const char *rawString = m_env->GetStringUTFChars(str, 0);
+        string s(rawString, strlen(rawString));
+        JniBundleResource::setAttribute(s, "");
+        m_env->ReleaseStringUTFChars(str, rawString);
+        m_env->DeleteLocalRef(str);
+        LOGD("Deleting and releasing resources - JNI bundle resource");
+    }
+
+    m_bundleId = bundleId;
+
+    this->m_bundleResource = m_env->NewGlobalRef(bundleResource);
+
+    m_bundleResourceClass = (jclass) m_env->NewGlobalRef(m_env->GetObjectClass(bundleResource));
+    LOGD("Looking for setter.");
+    m_attributeSetRequestHandler = m_env->GetMethodID(m_bundleResourceClass,
+            "handleSetAttributesRequest",
+            "(Lorg/iotivity/service/resourcecontainer/RcsResourceAttributes;)V");
+    LOGD("Looking for getter.");
+    m_attributeGetRequestHandler = m_env->GetMethodID(m_bundleResourceClass,
+            "handleGetAttributesRequest",
+            "()Lorg/iotivity/service/resourcecontainer/RcsResourceAttributes;");
+
+    LOGD("Looking for onUpdatedInputResource.");
+    m_superclass = (jclass) m_env->NewGlobalRef(m_env->GetSuperclass(m_bundleResourceClass));
+
+    m_classClass = (jclass) m_env->NewGlobalRef(m_env->FindClass("java/lang/Class"));
+
+
+    m_vectorClazz = (jclass) m_env->NewGlobalRef(m_env->FindClass("java/util/Vector"));
+    if (m_env->ExceptionCheck()) {
+        m_env->ExceptionDescribe();
+    }
+
+    if (m_env->ExceptionCheck()) {
+       m_env->ExceptionDescribe();
+    }
+
+    if(m_classClass != NULL){
+        // Find the getName() method on the class object
+        jmethodID mid = env->GetMethodID(m_classClass, "getName", "()Ljava/lang/String;");
+
+        // Call the getName() to get a jstring object back
+        if(m_superclass != NULL){
+            jstring strObj = (jstring)env->CallObjectMethod(m_superclass, mid);
+
+            // Now get the c string from the java jstring object
+            const char* str = env->GetStringUTFChars(strObj, NULL);
+
+            LOGD("Name of super class is %s", str);
+
+            //check for softsensor resource
+            if(strcmp("org.iotivity.service.resourcecontainer.BundleSoftSensorResource", str) == 0){
+               m_onUpdatedInputResource = m_env->GetMethodID(m_bundleResourceClass,
+                       "onUpdatedInputResource", "(Ljava/lang/String;Ljava/util/Vector;)V");
+               if (m_env->ExceptionCheck()) {
+                   m_env->ExceptionDescribe();
+               }
+
+               LOGD("Looking up vector add method.");
+               if(m_vectorClazz != NULL){
+                   m_vectorAddMethod =  m_env->GetMethodID(m_vectorClazz, "add", "(Ljava/lang/Object;)Z");
+                   if (m_env->ExceptionCheck()) {
+                       m_env->ExceptionDescribe();
+                   }
+               }
+
+            }
+            LOGD("Deleting and releasing resources - JNIBundleResource 2");
+            m_env->ReleaseStringUTFChars(strObj, str);
+        }
+    }
+}
+
+JniBundleResource::~JniBundleResource()
+{
+
+}
+
+RCSResourceAttributes::Value JniBundleResource::handleGetAttributeRequest(
+        const std::string &attributeName)
+{
+    LOGD("handleGetAttributeRequest called2");
+    LOGD("Attaching thread now");
+    int attached = m_jvm->AttachCurrentThread(&m_env, NULL);
+    if(attached>0)
+    {
+        LOGE("Failed to attach thread to JavaVM");
+    }
+    else{
+        if(m_attributeGetRequestHandler != NULL){
+            jstring attrName = m_env->NewStringUTF(attributeName.c_str());
+            auto responseObj =  m_env->CallObjectMethod(m_bundleResource,
+                    m_attributeGetRequestHandler, attrName);
+
+            if (responseObj)
+            {
+                LOGD("parsing attributes");
+                RCSResourceAttributes attrs = toNativeAttributes(m_env, responseObj);
+                LOGD("Received attributes %d", attrs.size());
+            }
+        }
+    }
+    return JniBundleResource::getAttribute(attributeName);
+}
+
+void JniBundleResource::handleSetAttributeRequest(const std::string &attributeName,
+                                      RCSResourceAttributes::Value &&value)
+{
+    if(m_attributeSetRequestHandler != NULL){
+        jstring attrName = m_env->NewStringUTF(attributeName.c_str());
+        jstring val = m_env->NewStringUTF(value.toString().c_str());
+
+        //LOGD("handleSetAttributeRequest calling object method %d", &m_attributeSetRequestHandler);
+        m_env->CallObjectMethod(m_bundleResource, m_attributeSetRequestHandler, attrName, val);
+    }
+    JniBundleResource::setAttribute(attributeName, std::move(value));
+}
+
+
+void JniBundleResource::handleSetAttributesRequest(const RCSResourceAttributes &attrs){
+    LOGD("handleSetAttributesRequest called %d", attrs.size());
+
+    //m_env->CallObjectMethod(m_bundleResource, m_attributeSetRequestHandler, attrName, val);
+    //JniBundleResource::setAttribute(attributeName, std::move(value));
+    if(m_attributeSetRequestHandler != NULL && m_bundleResource != NULL){
+        int attached = m_jvm->AttachCurrentThread(&m_env, NULL);
+
+        if(attached>0)
+        {
+            LOGE("Failed to attach thread to JavaVM");
+        }
+        else{
+            LOGD("Creating resource attributes for JNI.");
+
+            m_env->MonitorEnter(m_bundleResource);
+            auto jniRcsAttributes = newAttributesObject(m_env, attrs);
+            LOGD("jobject created. calling");
+            m_env->CallVoidMethod(m_bundleResource,
+                    m_attributeSetRequestHandler, jniRcsAttributes);
+            JniBundleResource::setAttributes(attrs);
+            m_env->MonitorExit(m_bundleResource);
+
+            m_jvm->DetachCurrentThread();
+        }
+    }
+}
+
+RCSResourceAttributes JniBundleResource::handleGetAttributesRequest()
+{
+    LOGD("handleGetAttributesRequest");
+
+    if(m_attributeGetRequestHandler != NULL && m_bundleResource != NULL){
+        LOGD("attaching thread");
+        int attached = m_jvm->AttachCurrentThread(&m_env, NULL);
+        if(attached>0)
+        {
+            LOGE("Failed to attach thread to JavaVM");
+        }
+        else{
+            LOGD("attached, calling get request handler");
+            auto responseObj =  m_env->CallObjectMethod(m_bundleResource,
+                    m_attributeGetRequestHandler);
+
+            if (responseObj)
+            {
+                LOGD("parsing attributes");
+                m_env->MonitorEnter(m_bundleResource);
+                LOGD("to native attributes");
+                const RCSResourceAttributes attrs = toNativeAttributes(m_env, responseObj);
+                LOGD("Received attributes %d", attrs.size());
+                JniBundleResource::setAttributes(attrs, false);
+                m_env->MonitorExit(m_bundleResource);
+            }
+
+            m_jvm->DetachCurrentThread();
+        }
+        LOGD("JniBundleResource::getAttributes().size() %d",
+                JniBundleResource::getAttributes().size());
+    }
+    return JniBundleResource::getAttributes();
+}
+
+void JniBundleResource::executeLogic(){
+    // IS CALLED AT JAVA LAYER
+}
+
+void JniBundleResource::onUpdatedInputResource(const std::string attributeName,
+        std::vector<RCSResourceAttributes::Value> values){
+    LOGD("onUpdatedInputResource");
+    if(m_vectorClazz == NULL || m_classClass == NULL){
+        return;
+    }
+    int attached = m_jvm->AttachCurrentThread(&m_env, NULL);
+    jobject valueObj;
+    if(attached>0)
+    {
+        LOGE("Failed to attach thread to JavaVM");
+    }
+    else{
+
+
+        jobject obj = m_env->NewObject(m_vectorClazz,
+                m_env->GetMethodID(m_vectorClazz, "<init>", "()V"));
+
+        LOGD("Looking up vector add method.");
+
+        jmethodID m_vectorAddMethod =  m_env->GetMethodID(m_vectorClazz, "add",
+                "(Ljava/lang/Object;)Z");
+        if (m_env->ExceptionCheck()) {
+            m_env->ExceptionDescribe();
+        }
+
+        if(m_vectorAddMethod == NULL){
+            m_jvm->DetachCurrentThread();
+            return;
+        }
+
+        for (int n=0;n<values.size();n++)
+        {
+           valueObj  = newRCSValueObject(m_env, values[n]);
+           m_env->CallBooleanMethod(obj, m_vectorAddMethod, valueObj);
+        }
+
+        // Find the getName() method on the class object
+        jmethodID mid = m_env->GetMethodID(m_classClass, "getName",
+                "()Ljava/lang/String;");
+
+        // Call the getName() to get a jstring object back
+        if(m_superclass == NULL || mid == NULL){
+            m_jvm->DetachCurrentThread();
+            return;
+        }
+
+        jstring strObj = (jstring)m_env->CallObjectMethod(m_superclass, mid);
+
+        // Now get the c string from the java jstring object
+        if(strObj == NULL){
+            m_jvm->DetachCurrentThread();
+            return;
+        }
+        const char* str = m_env->GetStringUTFChars(strObj, NULL);
+
+        LOGD("Name of super class is %s", str);
+
+        jstring attrName = m_env->NewStringUTF(attributeName.c_str());
+
+        //check for softsensor resource
+        if(strcmp("org.iotivity.service.resourcecontainer.BundleSoftSensorResource", str) == 0){
+            jmethodID m_onUpdatedInputResource = m_env->GetMethodID(m_bundleResourceClass,
+                    "onUpdatedInputResource", "(Ljava/lang/String;Ljava/util/Vector;)V");
+            if(m_onUpdatedInputResource != NULL){
+                m_env->MonitorEnter(m_bundleResource);
+                m_env->CallVoidMethod(m_bundleResource,
+                m_onUpdatedInputResource, attrName, obj);
+                m_env->MonitorExit(m_bundleResource);
+                if (m_env->ExceptionCheck()) {
+                    m_env->ExceptionDescribe();
+                }
+            }
+        }
+        LOGD("Deleting and releasing resources - onUpdatedInputResource");
+        m_env->DeleteLocalRef(attrName);
+        m_env->ReleaseStringUTFChars(strObj, str);
+
+        if (m_env->ExceptionCheck()) {
+               m_env->ExceptionDescribe();
+        }
+        m_jvm->DetachCurrentThread();
+    }
+
+    LOGD("JniBundleResource::getAttributes().size() %d", JniBundleResource::getAttributes().size());
+}
+
+JNIEXPORT void
+JNICALL Java_org_iotivity_service_resourcecontainer_BundleResource_updateNativeInstance
+(JNIEnv* env, jobject obj, jobject updates)
+{
+    LOGD("updateNativeInstance");
+    BundleResource* JniBundleResource =
+            reinterpret_cast<BundleResource*>(env->GetLongField(obj, g_field_mNativeHandle));
+    RCSResourceAttributes attrs = toNativeAttributes(env, updates);
+    LOGD("Received attributes %d", attrs.size());
+    JniBundleResource->setAttributes(attrs, true);
+}
diff --git a/service/resource-container/android/resource-container/src/main/jni/JniBundleResource.h b/service/resource-container/android/resource-container/src/main/jni/JniBundleResource.h
new file mode 100644 (file)
index 0000000..7530db2
--- /dev/null
@@ -0,0 +1,120 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef JNI_BUNDLERESOURCE_H_
+#define JNI_BUNDLERESOURCE_H_
+
+#include <map>
+#include <vector>
+#include <string>
+#include <jni.h>
+#include "BundleResource.h"
+#include "SoftSensorResource.h"
+#include "ResourceContainerImpl.h"
+
+#include <jni.h>
+
+class JNIEnvWrapper;
+
+void initRCSJniBundleResource(JNIEnvWrapper *);
+
+using namespace std;
+
+namespace OIC
+{
+    namespace Service
+    {
+        class JniBundleResource: public SoftSensorResource
+        {
+        public:
+            JniBundleResource();
+            JniBundleResource(JNIEnv *env, jobject obj, jobject bundleResource, string bundleId,
+                    jobjectArray attributes);
+            virtual ~JniBundleResource();
+
+            void handleSetAttributeRequest(const std::string& key,
+                    RCSResourceAttributes::Value&&);
+
+            RCSResourceAttributes::Value handleGetAttributeRequest(const std::string& key);
+
+            virtual void handleSetAttributesRequest(const RCSResourceAttributes &attrs);
+
+            virtual RCSResourceAttributes handleGetAttributesRequest();
+
+            /**
+            * SoftSensor logic. Has to be provided by the soft sensor developer.
+            * This function will be executed if an input attribute is updated.
+            *
+            * @return void
+            */
+            virtual void executeLogic();
+
+            /**
+            * Callback from the client module in the container.
+            * This function will be called if input data from remote resources are updated.
+            * SoftSensor resource can get a vector of input data from multiple input resources
+            *    which have attributeName that softsensor needs to execute its logic.
+            *
+            * @param attributeName Attribute key of input data
+            *
+            * @param values Vector of input data value
+            *
+            * @return void
+            */
+            virtual void onUpdatedInputResource(const std::string attributeName,
+                                                std::vector<RCSResourceAttributes::Value> values);
+
+            virtual void initAttributes();
+        private:
+            // needs to be a GlobalRef
+            jobject m_bundleResource;
+            jobjectArray m_attributes;
+            jclass m_bundleResourceClass;
+            jmethodID m_attributeSetRequestHandler;
+            jmethodID m_attributeGetRequestHandler;
+            jmethodID m_onUpdatedInputResource;
+            jclass m_vectorClazz;
+            jmethodID m_vectorAddMethod;
+            string m_bundleId;
+            jclass m_superclass;
+            jclass m_classClass;
+            JNIEnv *m_env;
+            JavaVM *m_jvm;
+            jfieldID g_field_mNativeHandle;
+        };
+    }
+}
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+/*
+ * Class:     org_iotivity_service_resourcecontainer_JniBundleResource
+ * Method:    updateNativeInstance
+ * Signature: (Lorg/iotivity/service/resourcecontainer/RcsResourceAttributes;)V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_service_resourcecontainer_BundleResource_updateNativeInstance
+  (JNIEnv *, jobject, jobject);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
+
index 16b6894..7052ec2 100644 (file)
  *
  ******************************************************************/
 
-#include "JniRcsObject.h"
-
 #include "JniRcsResourceContainer.h"
+#include "JniRcsResourceAttributes.h"
 #include "JavaClasses.h"
-#include "JavaExceptions.h"
 #include "JNIEnvWrapper.h"
 #include "Log.h"
+#include "JniRcsValue.h"
+#include "JavaExceptions.h"
+#include "JniRcsValue.h"
+#include  "JniBundleResource.h"
 
 #define LOG_TAG "JNI-Main"
 
@@ -50,8 +52,10 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
     {
         initJavaClasses(&envWrapper);
         initJavaExceptions(&envWrapper);
-        initRCSObject(&envWrapper);
+        initRCSValue(&envWrapper);
         initRCSResourceContainer(&envWrapper);
+        initRCSResourceAttributes(&envWrapper);
+        initRCSJniBundleResource(&envWrapper);
     }
     catch (const JavaException &)
     {
@@ -78,8 +82,6 @@ JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)
     try
     {
         clearRCSResourceContainer(&envWrapper);
-        clearRCSObject(&envWrapper);
-        clearJavaExceptions(&envWrapper);
         clearJavaClasses(&envWrapper);
     }
     catch (const JavaException &)
diff --git a/service/resource-container/android/resource-container/src/main/jni/JniRcsBundleInfo.cpp b/service/resource-container/android/resource-container/src/main/jni/JniRcsBundleInfo.cpp
deleted file mode 100644 (file)
index 7bbac93..0000000
+++ /dev/null
@@ -1,100 +0,0 @@
-/******************************************************************
- *
- * 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 "JniRcsBundleInfo.h"
-
-#include "Log.h"
-#include "Verify.h"
-#include "JniRcsObject.h"
-
-#include "RCSBundleInfo.h"
-
-#define LOG_TAG "JNI-RCSBundleInfo"
-
-using namespace OIC::Service;
-
-namespace
-{
-    RCSBundleInfo *getNativeBundleInfo(JNIEnv *env, jobject obj)
-    {
-        return getNativeHandleAs< RCSBundleInfo * >(env, obj);
-    }
-}
-
-JNIEXPORT jstring JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsBundleInfo_nativeGetID
-(JNIEnv *env, jobject obj)
-{
-    LOGI("nativeGetID");
-
-    auto bundleInfo = getNativeBundleInfo(env, obj);
-    VERIFY_NO_EXC_RET_DEF(env);
-
-    return newStringObject(env, bundleInfo->getID());
-}
-
-JNIEXPORT jstring JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsBundleInfo_nativeGetPath
-(JNIEnv *env, jobject obj)
-{
-    LOGI("nativeGetPath");
-
-    auto bundleInfo = getNativeBundleInfo(env, obj);
-    VERIFY_NO_EXC_RET_DEF(env);
-
-    return newStringObject(env, bundleInfo->getPath());
-}
-
-JNIEXPORT jstring JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsBundleInfo_nativeGetActivatorName
-(JNIEnv *env, jobject obj)
-{
-    LOGI("nativeGetActivatorName");
-
-    auto bundleInfo = getNativeBundleInfo(env, obj);
-    VERIFY_NO_EXC_RET_DEF(env);
-
-    return newStringObject(env, bundleInfo->getActivatorName());
-}
-
-JNIEXPORT jstring JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsBundleInfo_nativeGetLibraryPath
-(JNIEnv *env, jobject obj)
-{
-    LOGI("nativeGetLibraryPath");
-
-    auto bundleInfo = getNativeBundleInfo(env, obj);
-    VERIFY_NO_EXC_RET_DEF(env);
-
-    return newStringObject(env, bundleInfo->getLibraryPath());
-}
-
-JNIEXPORT jstring JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsBundleInfo_nativeGetVersion
-(JNIEnv *env, jobject obj)
-{
-    LOGI("nativeGetVersion");
-
-    auto bundleInfo = getNativeBundleInfo(env, obj);
-    VERIFY_NO_EXC_RET_DEF(env);
-
-    return newStringObject(env, bundleInfo->getVersion());
-}
-
diff --git a/service/resource-container/android/resource-container/src/main/jni/JniRcsBundleInfo.h b/service/resource-container/android/resource-container/src/main/jni/JniRcsBundleInfo.h
deleted file mode 100644 (file)
index 83b5dcd..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-/** @file   jni_re_rcs_bundle_info.h
- *
- * @brief This file contains the JniBundleInfo class
- *               & declaration of RCSBundleInfo APIs for JNI implementation
- */
-
-#ifndef JNI_RCS_BUNDLE_INFO_H_
-#define JNI_RCS_BUNDLE_INFO_H_
-
-#include <jni.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-JNIEXPORT jstring JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsBundleInfo_nativeGetID
-(JNIEnv *, jobject);
-
-JNIEXPORT jstring JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsBundleInfo_nativeGetPath
-(JNIEnv *, jobject);
-
-JNIEXPORT jstring JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsBundleInfo_nativeGetActivatorName
-(JNIEnv *, jobject);
-
-JNIEXPORT jstring JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsBundleInfo_nativeGetLibraryPath
-(JNIEnv *, jobject);
-
-JNIEXPORT jstring JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsBundleInfo_nativeGetVersion
-(JNIEnv *, jobject);
-
-#ifdef __cplusplus
-}
-#endif
-#endif // JNI_RCS_BUNDLE_INFO_H_
-
diff --git a/service/resource-container/android/resource-container/src/main/jni/JniRcsObject.cpp b/service/resource-container/android/resource-container/src/main/jni/JniRcsObject.cpp
deleted file mode 100644 (file)
index 7a3c014..0000000
+++ /dev/null
@@ -1,48 +0,0 @@
-/******************************************************************
- *
- * 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 "JniRcsObject.h"
-
-#include "JavaClasses.h"
-#include "JNIEnvWrapper.h"
-#include "Log.h"
-#include "Verify.h"
-
-#define LOG_TAG "JNI-RCSObject"
-
-jfieldID g_field_mNativeHandle;
-
-void initRCSObject(JNIEnvWrapper *env)
-{
-    auto clsRCSObject = env->FindClass(PACKAGE_NAME "/utils/RcsObject");
-
-    g_field_mNativeHandle = env->GetFieldID(clsRCSObject, "mNativeHandle", "J");
-}
-
-void clearRCSObject(JNIEnvWrapper *env)
-{
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_utils_RcsObject_nativeDispose(JNIEnv *env, jobject obj)
-{
-    LOGD("release nativeHandle!");
-    releaseNativeHandle(env, obj);
-}
diff --git a/service/resource-container/android/resource-container/src/main/jni/JniRcsObject.h b/service/resource-container/android/resource-container/src/main/jni/JniRcsObject.h
deleted file mode 100644 (file)
index cfa7a71..0000000
+++ /dev/null
@@ -1,125 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-#ifndef JNI_RCS_OBJECT_H_
-#define JNI_RCS_OBJECT_H_
-
-#include <jni.h>
-
-#include <memory>
-
-#include "JavaClasses.h"
-#include "JNIEnvWrapper.h"
-
-extern jfieldID g_field_mNativeHandle;
-
-void initRCSObject(JNIEnvWrapper *);
-void clearRCSObject(JNIEnvWrapper *);
-
-namespace Detail
-{
-    struct BaseHandleHolder
-    {
-        virtual ~BaseHandleHolder() {}
-    };
-
-    template< typename T >
-    struct HandleHolder: public BaseHandleHolder
-    {
-        HandleHolder(T *ptr) : m_ptr { ptr } {}
-
-        virtual ~HandleHolder() { delete m_ptr; }
-
-        T *m_ptr;
-    };
-
-    template< typename ENV >
-    void *getNativeHandle(ENV *env, jobject obj)
-    {
-        return reinterpret_cast< void * >(env->GetLongField(obj, g_field_mNativeHandle));
-    }
-}
-
-template< typename ENV >
-bool hasNativeHandle(ENV *env, jobject obj)
-{
-    return Detail::getNativeHandle(env, obj) != nullptr;
-}
-
-template< typename T, typename ENV, typename ...PARAMS >
-inline void setSafeNativeHandle(ENV *env, jobject obj, PARAMS &&... params)
-{
-    static_assert(!std::is_array< T >::value, "Array is not supported!");
-
-    std::unique_ptr< Detail::HandleHolder< T > > p(
-    new Detail::HandleHolder< T > { new T{ std::forward< PARAMS >(params)... } });
-
-    env->SetLongField(obj, g_field_mNativeHandle, reinterpret_cast< jlong >(p.get()));
-
-    if (env->ExceptionCheck()) return;
-
-    p.release();
-}
-
-template< typename ENV >
-void releaseNativeHandle(ENV *env, jobject obj)
-{
-    auto handleHolder = reinterpret_cast< Detail::BaseHandleHolder * >(
-                            env->GetLongField(obj, g_field_mNativeHandle));
-
-    delete handleHolder;
-
-    env->SetLongField(obj, g_field_mNativeHandle, 0);
-}
-
-
-template< typename T >
-inline T &getNativeHandleAs(JNIEnv *env, jobject obj)
-{
-    auto handleHolder = static_cast< Detail::HandleHolder< T >* >(Detail::getNativeHandle(env, obj));
-
-    if (!handleHolder)
-    {
-        env->ThrowNew(env->FindClass(EXC_NAME_ILLEGAL_STATE), "Internal handle is null!");
-    }
-
-    return *handleHolder->m_ptr;
-}
-
-template< typename T >
-inline T &getNativeHandleAs(JNIEnvWrapper *env, jobject obj)
-{
-    getNativeHandleAs< T >(env->get(), obj);
-    if (env->ExceptionCheck()) throw JavaException();
-}
-
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_utils_RcsObject_nativeDispose(JNIEnv *, jobject);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // JNI_RCS_OBJECT_H_
diff --git a/service/resource-container/android/resource-container/src/main/jni/JniRcsResourceAttributes.cpp b/service/resource-container/android/resource-container/src/main/jni/JniRcsResourceAttributes.cpp
new file mode 100644 (file)
index 0000000..d947e3b
--- /dev/null
@@ -0,0 +1,174 @@
+/******************************************************************
+ *
+ * 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 "JniRcsResourceAttributes.h"
+
+#include "JNIEnvWrapper.h"
+#include "JavaClasses.h"
+#include "JavaLocalRef.h"
+#include "JniRcsValue.h"
+#include "Log.h"
+#include "Verify.h"
+
+using namespace OIC::Service;
+
+#define LOG_TAG "JNI-RCSResourceAttributes"
+
+namespace
+{
+    jclass g_cls_RCSResourceAttributes;
+
+    jmethodID g_ctor_RCSResourceAttributes;
+
+    jfieldID g_field_mCache;
+}
+
+void initRCSResourceAttributes(JNIEnvWrapper* env)
+{
+    g_cls_RCSResourceAttributes = env->FindClassAsGlobalRef(CLS_NAME_RESOURCEATTRIBUTES);
+    g_ctor_RCSResourceAttributes = env->GetConstructorID(g_cls_RCSResourceAttributes, "()V");
+
+    g_field_mCache = env->GetFieldID(g_cls_RCSResourceAttributes, "mCache", AS_SIG(CLS_NAME_MAP));
+}
+
+void clearRCSResourceAttributes(JNIEnvWrapper* env)
+{
+    env->DeleteGlobalRef(g_cls_RCSResourceAttributes);
+}
+
+jobject newAttributesObject(JNIEnv* env, const RCSResourceAttributes& attrs)
+{
+    jobject obj = env->NewObject(g_cls_RCSResourceAttributes, g_ctor_RCSResourceAttributes);
+    VERIFY_NO_EXC_RET_DEF(env);
+
+    jobject mapObj = env->GetObjectField(obj, g_field_mCache);
+
+    //EXPECT(mapObj, "Map is null.");
+    for (const auto& p : attrs) {
+        JavaLocalObject keyObj{ env, newStringObject(env, p.key()) };
+        //VERIFY_NO_EXC(env);
+
+        JavaLocalObject valueObj{ env, newRCSValueObject(env, p.value()) };
+        //VERIFY_NO_EXC(env);
+
+        invoke_Map_put(env, mapObj, keyObj, valueObj);
+        //VERIFY_NO_EXC(env);
+    }
+
+ //   setSafeNativeHandle< RCSResourceAttributes >(env, obj, attrs);
+
+    return obj;
+}
+
+jobject newAttributesObject(JNIEnvWrapper* env, const RCSResourceAttributes& attrs)
+{
+    jobject obj = env->NewObject(g_cls_RCSResourceAttributes, g_ctor_RCSResourceAttributes);
+
+    jobject mapObj = env->GetObjectField(obj, g_field_mCache);
+
+    //EXPECT(mapObj, "Map is null.");
+    for (const auto& p : attrs) {
+        JavaLocalObject keyObj{ env, newStringObject(env, p.key()) };
+        //VERIFY_NO_EXC(env);
+
+        JavaLocalObject valueObj{ env, newRCSValueObject(env, p.value()) };
+        //VERIFY_NO_EXC(env);
+
+        invoke_Map_put(env, mapObj, keyObj, valueObj);
+        //VERIFY_NO_EXC(env);
+    }
+
+//    setSafeNativeHandle< RCSResourceAttributes >(env, obj, attrs);
+
+    return obj;
+}
+
+RCSResourceAttributes toNativeAttributes(JNIEnv* env, jobject attrsObj)
+{
+    EXPECT_RET(attrsObj, "attrsObj is null!", { });
+
+    JNIEnvWrapper envWrapper{ env };
+
+    try
+    {
+        return toNativeAttributes(&envWrapper, attrsObj);
+    }
+    catch (const JavaException&)
+    {
+        return {};
+    }
+}
+
+RCSResourceAttributes toNativeAttributes(JNIEnvWrapper* env, jobject attrsObj)
+{
+    EXPECT_RET(attrsObj, "attrsObj is null!", { });
+
+    RCSResourceAttributes attrs;
+
+    /*if (hasNativeHandle(env, attrsObj))
+    {
+        attrs = getNativeHandleAs< RCSResourceAttributes >(env, attrsObj);
+    }*/
+    LOGD("writeNativeAttributesFromMap");
+
+    writeNativeAttributesFromMap(env,
+            JavaLocalObject{ env, env->GetObjectField(attrsObj, g_field_mCache) }, attrs);
+
+    return attrs;
+}
+
+void writeNativeAttributesFromMap(JNIEnv* env, jobject mapObj, RCSResourceAttributes& targetAttrs)
+{
+    JNIEnvWrapper envWrapper{ env };
+
+    try
+    {
+        return writeNativeAttributesFromMap(&envWrapper, mapObj, targetAttrs);
+    }
+    catch (const JavaException&)
+    {
+    }
+}
+
+void writeNativeAttributesFromMap(JNIEnvWrapper* env, jobject mapObj,
+        RCSResourceAttributes& targetAttrs)
+{
+    LOGD("in write native attributes from map");
+    LOGD("invoke map entry set");
+    JavaLocalObject setObj{ env, invoke_Map_entrySet(env, mapObj) };
+    LOGD("invoke set iterator");
+    JavaLocalObject iterObj{ env, invoke_Set_iterator(env, setObj) };
+    LOGD("invoke has next");
+    while (invoke_Iterator_hasNext(env, iterObj))
+    {
+        LOGD("invoke entry obj next");
+        JavaLocalObject entryObj{ env, invoke_Iterator_next(env, iterObj) };
+        LOGD("invoke key obj next");
+        JavaLocalObject keyObj{ env, invoke_MapEntry_getKey(env, entryObj) };
+        LOGD("invoke value obj next");
+        JavaLocalObject valueObj{ env, invoke_MapEntry_getValue(env, entryObj) };
+        LOGD("invoke toStdString");
+        auto key = toStdString(env, static_cast< jstring >(keyObj.get()));
+        LOGD("invoke toNativeAttrsvalue");
+        targetAttrs[std::move(key)] = toNativeAttrsValue(env, valueObj);
+    }
+    LOGD("in write native attributes from map finished");
+}
+
diff --git a/service/resource-container/android/resource-container/src/main/jni/JniRcsResourceAttributes.h b/service/resource-container/android/resource-container/src/main/jni/JniRcsResourceAttributes.h
new file mode 100644 (file)
index 0000000..122d196
--- /dev/null
@@ -0,0 +1,50 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef JNI_RCS_RESOURCE_ATTRIBUTES_H_
+#define JNI_RCS_RESOURCE_ATTRIBUTES_H_
+
+#include <jni.h>
+
+namespace OIC
+{
+    namespace Service
+    {
+        class RCSResourceAttributes;
+    }
+}
+
+class JNIEnvWrapper;
+
+void initRCSResourceAttributes(JNIEnvWrapper*);
+void clearRCSResourceAttributes(JNIEnvWrapper*);
+
+jobject newAttributesObject(JNIEnv*, const OIC::Service::RCSResourceAttributes&);
+jobject newAttributesObject(JNIEnvWrapper*, const OIC::Service::RCSResourceAttributes&);
+
+OIC::Service::RCSResourceAttributes toNativeAttributes(JNIEnv*, jobject);
+OIC::Service::RCSResourceAttributes toNativeAttributes(JNIEnvWrapper*, jobject);
+
+void writeNativeAttributesFromMap(JNIEnv*, jobject mapObj,
+        OIC::Service::RCSResourceAttributes& targetAttrs);
+void writeNativeAttributesFromMap(JNIEnvWrapper*, jobject mapObj,
+        OIC::Service::RCSResourceAttributes& targetAttrs);
+
+#endif  //JNI_RCS_RESOURCE_ATTRIBUTES_H_
index 02944a6..5a5b420 100644 (file)
 
 #include "JniRcsResourceContainer.h"
 
+#include "JavaClasses.h"
 #include "JavaLocalRef.h"
 #include "JNIEnvWrapper.h"
 #include "Log.h"
 #include "Verify.h"
-#include "JniRcsObject.h"
+#include <dlfcn.h>
 
+#include "ResourceContainerBundleAPI.h"
+#include "JniBundleResource.h"
 #include "RCSResourceContainer.h"
-#include "RCSBundleInfo.h"
 
-#define LOG_TAG "JNI-RCSResourceContainer"
 
-using namespace OIC::Service;
 
-#define CLS_NAME_BUNDLE_INFO PACKAGE_NAME "/resourcecontainer/RcsBundleInfo"
+#define LOG_TAG "JNI-RCSResourceContainer"
 
-#include <android/log.h>
+using namespace OIC::Service;
 
+#define CLS_NAME_BUNDLE_INFO "org/iotivity/service/resourcecontainer/RcsBundleInfo"
 
+std::map< string, BundleResource::Ptr > android_resources;
 
 namespace
 {
     jclass g_cls_RCSBundleInfo;
+    jfieldID g_field_mNativeHandle;
 
     jmethodID g_ctor_RCSBundleInfo;
 
@@ -60,24 +63,48 @@ namespace
             JavaLocalObject entryObj { env, invoke_Iterator_next(env, iterObj) };
 
             JavaLocalString keyObj { env,
-                                     static_cast< jstring >(invoke_MapEntry_getKey(env, entryObj))
-                                   };
+                static_cast< jstring >(invoke_MapEntry_getKey(env, entryObj)) };
+
             JavaLocalString valueObj { env,
-                                       static_cast< jstring >(invoke_MapEntry_getValue(env, entryObj))
-                                     };
+                static_cast< jstring >(invoke_MapEntry_getValue(env, entryObj)) };
 
             ret.emplace(toStdString(env, keyObj), toStdString(env, valueObj));
         }
 
         return ret;
     }
+
+    jobject newBundleInfoObj(JNIEnvWrapper *env, const std::unique_ptr< RCSBundleInfo > &bundleInfo)
+    {
+        LOGD("new bundle info");
+        __android_log_print(ANDROID_LOG_DEBUG, "CONTAINER", "newBundleInfoObj %s",bundleInfo->getActivatorName().c_str());
+        JavaLocalString id{env, newStringObject(env, bundleInfo->getID()) };
+        JavaLocalString path{env, newStringObject(env, bundleInfo->getPath()) };
+        JavaLocalString activatorName{env, newStringObject(env, bundleInfo->getActivatorName()) };
+        JavaLocalString libraryPath{env, newStringObject(env, bundleInfo->getLibraryPath()) };
+        JavaLocalString version{env, newStringObject(env, bundleInfo->getVersion()) };
+
+        return env->NewObject(g_cls_RCSBundleInfo, g_ctor_RCSBundleInfo,
+                id.get(), path.get(), activatorName.get(), libraryPath.get(), version.get(),
+                bundleInfo->isActivated());
+    }
 }
 
 void initRCSResourceContainer(JNIEnvWrapper *env)
 {
     g_cls_RCSBundleInfo = env->FindClassAsGlobalRef(CLS_NAME_BUNDLE_INFO);
 
-    g_ctor_RCSBundleInfo = env->GetConstructorID(g_cls_RCSBundleInfo, "()V");
+    g_ctor_RCSBundleInfo = env->GetConstructorID(g_cls_RCSBundleInfo, "("
+            AS_SIG(CLS_NAME_STRING)
+            AS_SIG(CLS_NAME_STRING)
+            AS_SIG(CLS_NAME_STRING)
+            AS_SIG(CLS_NAME_STRING)
+            AS_SIG(CLS_NAME_STRING)
+            ")V");
+
+    auto clsJniBundleResource = env->FindClass(PACKAGE_NAME "/BundleResource");
+
+    g_field_mNativeHandle = env->GetFieldID(clsJniBundleResource, "mNativeHandle", "J");
 }
 
 void clearRCSResourceContainer(JNIEnvWrapper *env)
@@ -91,6 +118,15 @@ Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeStartCont
 {
     LOGD("nativeStartContainer");
 
+    // A strange error message happens if the container is used as native library on Android
+    // and further native libraries are loaded at runtime.
+    const char *error;
+    if ((error = dlerror()) != NULL)
+    {
+        __android_log_print(ANDROID_LOG_DEBUG, "JNI-RCSResourceContainer",
+                "dlerror: %s.", error);
+    }
+
     EXPECT(configFileObj, "ConfigFile is null.");
 
     auto configFile = toStdString(env, configFileObj);
@@ -101,11 +137,19 @@ Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeStartCont
 }
 
 JNIEXPORT void JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeStopContainer
-(JNIEnv *env, jobject)
+Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeStopContainer(JNIEnv *env, jobject)
 {
     LOGD("nativeStopContainers");
 
+    // A strange error message happens if the container is used as native library on Android
+    // and further native libraries are loaded at runtime.
+    const char *error;
+    if ((error = dlerror()) != NULL)
+    {
+        __android_log_print(ANDROID_LOG_DEBUG, "JNI-RCSResourceContainer",
+                "dlerror: %s.", error);
+    }
+
     RCSResourceContainer::getInstance()->stopContainer();
 }
 
@@ -116,6 +160,15 @@ Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeAddBundle
 {
     LOGD("nativeAddBundle");
 
+    // A strange error message happens if the container is used as native library on Android
+    // and further native libraries are loaded at runtime.
+    const char *error;
+    if ((error = dlerror()) != NULL)
+    {
+        __android_log_print(ANDROID_LOG_DEBUG, "JNI-RCSResourceContainer",
+                "dlerror: %s.", error);
+    }
+
     EXPECT(idObj, "BundleId is null.");
     EXPECT(pathObj, "BundlePath is null.");
     EXPECT(activatorObj, "Activator is null.");
@@ -144,6 +197,15 @@ Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeRemoveBun
 {
     LOGD("nativeRemoveBundle");
 
+    // A strange error message happens if the container is used as native library on Android
+    // and further native libraries are loaded at runtime.
+    const char *error;
+    if ((error = dlerror()) != NULL)
+    {
+        __android_log_print(ANDROID_LOG_DEBUG, "JNI-RCSResourceContainer",
+                "dlerror: %s.", error);
+    }
+
     EXPECT(idObj, "BundleId is null.");
 
     auto id = toStdString(env, idObj);
@@ -159,23 +221,24 @@ Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeListBundl
 {
     LOGD("nativeListBundles");
 
+    // A strange error message happens if the container is used as native library on Android
+    // and further native libraries are loaded at runtime.
+    const char *error;
+    if ((error = dlerror()) != NULL)
+    {
+        __android_log_print(ANDROID_LOG_DEBUG, "JNI-RCSResourceContainer",
+                "dlerror: %s.", error);
+    }
+
     JNIEnvWrapper envWrapper(env);
 
     try
     {
         auto listObj = newArrayList(&envWrapper);
 
-        for (auto& uniqeBundleInfo : RCSResourceContainer::getInstance()->listBundles())
+        for (const auto& bundleInfo : RCSResourceContainer::getInstance()->listBundles())
         {
-            RCSBundleInfo* bundleInfo = uniqeBundleInfo.release();
-            // FIXME we need a safe way to keep bundle info in java obj!!
-            // because we currently put raw pointer in the java obj.
-
-            JavaLocalObject bundleInfoObj { &envWrapper,
-                envWrapper.NewObject(g_cls_RCSBundleInfo, g_ctor_RCSBundleInfo) };
-
-            setSafeNativeHandle< RCSBundleInfo* >(&envWrapper, bundleInfoObj, bundleInfo);
-
+            JavaLocalObject bundleInfoObj{ &envWrapper, newBundleInfoObj(&envWrapper, bundleInfo) };
             invoke_Collection_add(&envWrapper, listObj, bundleInfoObj);
         }
         return listObj;
@@ -193,6 +256,15 @@ Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeStartBund
 {
     LOGD("nativeStartBundle");
 
+    // A strange error message happens if the container is used as native library on Android
+    // and further native libraries are loaded at runtime.
+    const char *error;
+    if ((error = dlerror()) != NULL)
+    {
+        __android_log_print(ANDROID_LOG_DEBUG, "JNI-RCSResourceContainer",
+                "dlerror: %s.", error);
+    }
+
     EXPECT(idObj, "BundleId is null.");
 
     auto id = env->GetStringUTFChars(idObj, NULL);
@@ -207,6 +279,15 @@ Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeStopBundl
 {
     LOGD("nativeStopBundle");
 
+    // A strange error message happens if the container is used as native library on Android
+    // and further native libraries are loaded at runtime.
+    const char *error;
+    if ((error = dlerror()) != NULL)
+    {
+        __android_log_print(ANDROID_LOG_DEBUG, "JNI-RCSResourceContainer",
+                "dlerror: %s.", error);
+    }
+
     EXPECT(idObj, "BundleId is null.");
 
     auto id = env->GetStringUTFChars(idObj, NULL);
@@ -271,9 +352,9 @@ Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeListBundl
 
         auto listObj = newArrayList(&envWrapper);
 
-        for (const auto & s : RCSResourceContainer::getInstance()->listBundleResources(id))
+        for (const auto& s : RCSResourceContainer::getInstance()->listBundleResources(id))
         {
-            JavaLocalString strObj { &envWrapper, newStringObject(&envWrapper, s) };
+            JavaLocalString strObj{ &envWrapper, newStringObject(&envWrapper, s) };
 
             invoke_Collection_add(&envWrapper, listObj, strObj);
         }
@@ -288,3 +369,114 @@ Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeListBundl
     return nullptr;
 }
 
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeRegisterBundleResource
+(JNIEnv *env, jobject obj, jobject bundleResource, jobjectArray attributes, jstring bundleId,
+ jstring uri, jstring resourceType, jstring res_name)
+{
+    JNIEnvWrapper envWrapper(env);
+    LOGD("nativeRegisterJniBundleResource");
+    auto str_bundle_id = toStdString(&envWrapper, bundleId);
+    __android_log_print(ANDROID_LOG_DEBUG, "JNI-RCSResourceContainer", "retrieved bundle id: %s.",
+            str_bundle_id.c_str());
+    auto str_uri = toStdString(&envWrapper, uri);
+    __android_log_print(ANDROID_LOG_DEBUG, "JNI-RCSResourceContainer", "retrieved uri: %s.",
+            str_uri.c_str());
+    auto str_resourceType = toStdString(&envWrapper, resourceType);
+    __android_log_print(ANDROID_LOG_DEBUG, "JNI-RCSResourceContainer", "retrieved resource type: %s.",
+            str_resourceType.c_str());
+    auto str_res_name = toStdString(&envWrapper, res_name);
+    LOGD("retrieved res name.");
+    JniBundleResource res;
+
+    BundleResource::Ptr androidResource = std::make_shared< JniBundleResource >
+            (env, obj, bundleResource, str_bundle_id, attributes);
+    ResourceContainerImpl *container = ResourceContainerImpl::getImplInstance();
+
+    androidResource->m_uri = str_uri;
+    androidResource->m_resourceType = str_resourceType;
+    androidResource->m_name = str_res_name;
+    androidResource->m_bundleId = str_bundle_id;
+
+    // link java resource instance to c++ resource instance
+    env->SetLongField(bundleResource, g_field_mNativeHandle, reinterpret_cast< jlong >(androidResource.get()));
+
+    container->registerResource(androidResource);
+
+    android_resources[str_uri] = androidResource;
+}
+
+/*
+ * Class:     org_iotivity_resourcecontainer_bundle_api_BaseActivator
+ * Method:    unregisterJavaResource
+ * Signature: (Lorg/iotivity/resourcecontainer/bundle/api/BundleResource;)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeUnregisterBundleResource
+(JNIEnv *env, jobject obj, jobject bundleResource, jstring uri)
+{
+    (void)obj;
+    (void)bundleResource;
+    const char *str_uri = env->GetStringUTFChars(uri, 0);
+
+    if (android_resources[str_uri] != NULL)
+    {
+        ResourceContainerImpl *container = ResourceContainerImpl::getImplInstance();
+        container->unregisterResource(android_resources[str_uri]);
+        android_resources.erase(str_uri);
+    }
+}
+
+/*
+ * Class:     org_iotivity_resourcecontainer_bundle_api_BaseActivator
+ * Method:    getNumberOfConfiguredResources
+ * Signature: (Ljava/lang/String;)I
+ */
+JNIEXPORT jint JNICALL
+Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeGetNumberOfConfiguredResources(
+    JNIEnv *env, jobject obj, jstring bundleId)
+{
+    (void)obj;
+    LOGD("nativeGetNumberOfConfiguredResources");
+    const char *str_bundleId = env->GetStringUTFChars(bundleId, 0);
+    LOGD("retrieved bundle id");
+    __android_log_print(ANDROID_LOG_DEBUG, "CONTAINER", "getNumberOfConfiguredResources %s",str_bundleId);
+    ResourceContainerImpl *container = ResourceContainerImpl::getImplInstance();
+    vector< resourceInfo > resourceConfig;
+    container->getResourceConfiguration(str_bundleId, &resourceConfig);
+
+    return resourceConfig.size();
+}
+
+/*
+ * Class:     org_iotivity_resourcecontainer_bundle_api_BaseActivator
+ * Method:    getConfiguredResourceParams
+ * Signature: (Ljava/lang/String;I)[Ljava/lang/String;
+ */
+JNIEXPORT jobjectArray JNICALL
+Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeGetConfiguredResourceParams(
+    JNIEnv *env, jobject obj, jstring bundleId, jint resourceId)
+{
+    (void)obj;
+    jobjectArray ret;
+    ret = (jobjectArray) env->NewObjectArray(4, env->FindClass("java/lang/String"),
+                    env->NewStringUTF(""));
+    if(bundleId != NULL){
+        const char *str_bundleId = env->GetStringUTFChars(bundleId, 0);
+
+        ResourceContainerImpl *container = ResourceContainerImpl::getImplInstance();
+        vector< resourceInfo > resourceConfig;
+        container->getResourceConfiguration(str_bundleId, &resourceConfig);
+
+        if(resourceConfig.size() > resourceId && resourceId >=0){
+            resourceInfo conf = resourceConfig[resourceId];
+            env->SetObjectArrayElement(ret, 0, env->NewStringUTF(conf.name.c_str()));
+            env->SetObjectArrayElement(ret, 1, env->NewStringUTF(conf.uri.c_str()));
+            env->SetObjectArrayElement(ret, 2, env->NewStringUTF(conf.resourceType.c_str()));
+            env->SetObjectArrayElement(ret, 3, env->NewStringUTF(conf.address.c_str()));
+        }
+    }
+    return ret;
+}
+
index 2474b7e..db2fc07 100644 (file)
@@ -40,7 +40,7 @@ extern "C" {
 
 JNIEXPORT void JNICALL
 Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeStartContainer
-(JNIEnv *, jobject, jstring configFile);
+(JNIEnv *, jobject, jstring);
 
 JNIEXPORT void JNICALL
 Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeStopContainer
@@ -79,6 +79,20 @@ JNIEXPORT jobject JNICALL
 Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeListBundleResources
 (JNIEnv *, jobject, jstring bundleId);
 
+JNIEXPORT void JNICALL Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeRegisterBundleResource
+  (JNIEnv *, jobject, jobject, jobjectArray, jstring, jstring, jstring, jstring);
+
+JNIEXPORT void JNICALL Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeUnregisterBundleResource
+  (JNIEnv *, jobject, jobject, jstring);
+
+JNIEXPORT jint JNICALL Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeGetNumberOfConfiguredResources
+  (JNIEnv *, jobject,  jstring);
+
+JNIEXPORT jobjectArray JNICALL Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeGetConfiguredResourceParams
+  (JNIEnv *, jobject, jstring, jint);
+
+
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/service/resource-container/android/resource-container/src/main/jni/JniRcsValue.cpp b/service/resource-container/android/resource-container/src/main/jni/JniRcsValue.cpp
new file mode 100644 (file)
index 0000000..80e00f5
--- /dev/null
@@ -0,0 +1,572 @@
+/******************************************************************
+ *
+ * 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 "JniRcsValue.h"
+
+#include "JNIEnvWrapper.h"
+#include "JniRcsResourceAttributes.h"
+#include "JavaClasses.h"
+#include "JavaExceptions.h"
+#include "JavaLocalRef.h"
+#include "Log.h"
+
+using namespace OIC::Service;
+
+#define LOG_TAG "JNI-RCSValue"
+
+#define CLS_NAME_VALUE_TYPE CLS_NAME_VALUE "$Type"
+#define CLS_NAME_VALUE_TYPEID CLS_NAME_VALUE "$TypeId"
+#define CLS_NAME_VALUE_NULL_TYPE CLS_NAME_VALUE "$NullType"
+
+namespace
+{
+    jclass g_cls_RCSValue;
+    jclass g_cls_Type;
+    jclass g_cls_TypeId;
+
+    jmethodID g_ctor_RCSValue;
+
+    jmethodID g_smethod_Type_getDepth;
+    jmethodID g_smethod_Type_getBaseTypeId;
+
+    jmethodID g_method_RCSValue_getType;
+
+    jfieldID g_field_RCSValue_mObject;
+    jfieldID g_field_RCSValue_sNullValue;
+
+    jobject g_obj_TypeId_Null;
+    jobject g_obj_TypeId_Boolean;
+    jobject g_obj_TypeId_Integer;
+    jobject g_obj_TypeId_Double;
+    jobject g_obj_TypeId_String;
+    jobject g_obj_TypeId_Attributes;
+    jobject g_obj_TypeId_Array;
+
+    template< int >
+    struct Int2Type{ };
+
+    template< int DEPTH, typename BASE_TYPE >
+    struct SeqType
+    {
+        typedef std::vector< typename SeqType< DEPTH - 1, BASE_TYPE >::type > type;
+    };
+
+    template< typename BASE_TYPE >
+    struct SeqType< 0, BASE_TYPE >
+    {
+        typedef BASE_TYPE type;
+    };
+
+    template< typename T >
+    struct BaseType
+    {
+      typedef T type;
+    };
+
+    template< typename T >
+    struct BaseType< std::vector< T > >
+    {
+      typedef typename BaseType< T >::type type;
+    };
+
+
+    template< int D >
+    struct ArrayPrefix
+    {
+        static constexpr char str[] = "";
+    };
+    template< int D >
+    constexpr char ArrayPrefix< D >::str[];
+
+    template<>
+    struct ArrayPrefix< 1 >
+    {
+        static constexpr char str[] = "[";
+    };
+    constexpr char ArrayPrefix< 1 >::str[];
+
+    template<>
+    struct ArrayPrefix< 2 >
+    {
+        static constexpr char str[] = "[[";
+    };
+    constexpr char ArrayPrefix< 2 >::str[];
+
+    struct PrimitiveType {
+        static constexpr bool isPrimitive = true;
+    };
+
+    struct ObjectType {
+        static constexpr bool isPrimitive = false;
+    };
+
+    template< typename T >
+    struct JniTypeTrait;
+
+    template<>
+    struct JniTypeTrait< int >: public PrimitiveType
+    {
+        static_assert(sizeof(int) == sizeof(jint), "int and jint have different size!");
+
+        static constexpr decltype(&JNIEnvWrapper::NewIntArray) newArrayFunc =
+                &JNIEnvWrapper::NewIntArray;
+        static constexpr decltype(&JNIEnvWrapper::SetIntArrayRegion) setArrayRegionFunc =
+                      &JNIEnvWrapper::SetIntArrayRegion;
+
+        static constexpr decltype(&invoke_Integer_intValue<JNIEnvWrapper>) converter =
+                      &invoke_Integer_intValue<JNIEnvWrapper>;
+
+        static constexpr decltype(&newIntegerObject<JNIEnvWrapper>) newObjectFunc =
+                &newIntegerObject<JNIEnvWrapper>;
+
+        static constexpr char className[] = "I";
+    };
+    constexpr char JniTypeTrait< int >::className[];
+
+    template<>
+    struct JniTypeTrait< bool >: public PrimitiveType
+    {
+        static_assert(sizeof(bool) == sizeof(jboolean), "bool and jboolean have different size!");
+
+        static constexpr decltype(&JNIEnvWrapper::NewBooleanArray) newArrayFunc =
+                &JNIEnvWrapper::NewBooleanArray;
+        static constexpr decltype(&JNIEnvWrapper::SetBooleanArrayRegion) setArrayRegionFunc =
+                      &JNIEnvWrapper::SetBooleanArrayRegion;
+
+        static constexpr decltype(&invoke_Boolean_booleanValue<JNIEnvWrapper>) converter =
+                      &invoke_Boolean_booleanValue<JNIEnvWrapper>;
+
+        static constexpr decltype(&newBooleanObject<JNIEnvWrapper>) newObjectFunc =
+                &newBooleanObject<JNIEnvWrapper>;
+
+        static constexpr char className[] = "Z";
+    };
+    constexpr char JniTypeTrait< bool >::className[];
+
+    template<>
+    struct JniTypeTrait< double > : public PrimitiveType
+    {
+        static_assert(sizeof(double) == sizeof(jdouble), "double and jdouble have different size!");
+
+        static constexpr decltype(&JNIEnvWrapper::NewDoubleArray) newArrayFunc =
+                &JNIEnvWrapper::NewDoubleArray;
+        static constexpr decltype(&JNIEnvWrapper::SetDoubleArrayRegion) setArrayRegionFunc =
+                      &JNIEnvWrapper::SetDoubleArrayRegion;
+
+        static constexpr decltype(&invoke_Double_doubleValue<JNIEnvWrapper>) converter =
+                      &invoke_Double_doubleValue<JNIEnvWrapper>;
+
+        static constexpr decltype(&newDoubleObject<JNIEnvWrapper>) newObjectFunc =
+                &newDoubleObject<JNIEnvWrapper>;
+
+        static constexpr char className[] = "D";
+    };
+    constexpr char JniTypeTrait< double >::className[];
+
+    template<>
+    struct JniTypeTrait< std::string >: public ObjectType
+    {
+        static constexpr decltype(&newStringObject<JNIEnvWrapper>) newObjectFunc =
+                &newStringObject<JNIEnvWrapper>;
+
+        static constexpr char className[] = "L" CLS_NAME_STRING ";";
+    };
+    constexpr char JniTypeTrait< std::string >::className[];
+
+    template<>
+    struct JniTypeTrait< RCSResourceAttributes >: public ObjectType
+    {
+        inline static jobject newObjectFunc(JNIEnvWrapper* env, const RCSResourceAttributes& value)
+        {
+            return newAttributesObject(env, value);
+        }
+
+        inline static RCSResourceAttributes converter(JNIEnvWrapper* env, jobject obj)
+        {
+            return toNativeAttributes(env, obj);
+        }
+
+        static constexpr char className[] = "L" CLS_NAME_RESOURCEATTRIBUTES ";";
+    };
+    constexpr char JniTypeTrait< RCSResourceAttributes >::className[];
+
+    inline void toNativeValue(JNIEnvWrapper* env, jobject obj, std::string& result, Int2Type< 0 >)
+    {
+        result = toStdString(env, static_cast< jstring >(obj));
+    }
+
+    template< typename T >
+    inline void toNativeValue(JNIEnvWrapper* env, jobject obj, T& result, Int2Type< 0 >)
+    {
+        result = JniTypeTrait< T >::converter(env, obj);
+    }
+
+    template< int DEPTH, typename RET >
+    inline void toNativeValue(JNIEnvWrapper* env, jobject obj, RET& result, Int2Type< DEPTH >)
+    {
+        const auto arrayObj = static_cast< jobjectArray >(obj);
+        result.resize(env->GetArrayLength(arrayObj));
+
+        for (typename RET::size_type i = 0; i < result.size(); ++i)
+        {
+            JavaLocalObject elementObj{ env, env->GetObjectArrayElement(arrayObj, i) };
+
+            toNativeValue(env, elementObj, result[i], Int2Type< DEPTH - 1 >{ });
+        }
+    }
+
+    template< typename T >
+    inline typename std::enable_if< JniTypeTrait< T >::isPrimitive >::type
+    toNativeValue(JNIEnvWrapper* env, jobject obj, std::vector< T >& result, Int2Type< 1 >)
+    {
+        const auto arrayObj = static_cast< jobjectArray >(obj);
+        const jsize arraySize = env->GetArrayLength(arrayObj);
+
+        T* raw = static_cast< T* >(env->GetPrimitiveArrayCritical(arrayObj, nullptr));
+
+        try
+        {
+            result = std::vector< T >(raw, raw + arraySize);
+        } catch (...)
+        {
+        }
+
+        env->ReleasePrimitiveArrayCritical(arrayObj, raw, JNI_ABORT);
+    }
+
+    template< typename T >
+    inline typename std::enable_if< !JniTypeTrait< T >::isPrimitive >::type
+    toNativeValue(JNIEnvWrapper* env, jobject obj, std::vector< T >& result, Int2Type< 1 >)
+    {
+        const auto arrayObj = static_cast< jobjectArray >(obj);
+        const jsize arraySize = env->GetArrayLength(arrayObj);
+
+        result.resize(arraySize);
+
+        for (typename std::vector< T >::size_type i = 0; i < result.size(); ++i)
+        {
+            JavaLocalObject elementObj{ env,  env->GetObjectArrayElement(arrayObj, i) };
+            toNativeValue(env, elementObj, result[i], Int2Type< 0 >{ });
+        }
+    }
+
+
+    template< typename T, int DEPTH, typename RET = typename SeqType< DEPTH, T >::type >
+    inline RET toNativeValue(JNIEnvWrapper* env, jobject obj)
+    {
+        static_assert(DEPTH >= 0, "DEPTH must be positive!");
+
+        typename SeqType< DEPTH, T >::type result;
+
+        toNativeValue(env, obj, result, Int2Type< DEPTH >{ });
+
+        return result;
+    }
+
+    template< typename T >
+    inline RCSResourceAttributes::Value toNativeValue(JNIEnvWrapper* env, jobject val, int depth)
+    {
+        switch (depth)
+        {
+            case 0: return toNativeValue< T, 0 >(env, val);
+            case 1: return toNativeValue< T, 1 >(env, val);
+            case 2: return toNativeValue< T, 2 >(env, val);
+            case 3: return toNativeValue< T, 3 >(env, val);
+        }
+
+        return {};
+    }
+
+    inline RCSResourceAttributes::Value toNativeValue(JNIEnvWrapper* env, jobject val, int depth,
+            RCSResourceAttributes::TypeId typeId)
+    {
+        LOGD("toNativeValue depth is %d", depth);
+        EXPECT_RET(depth >= 0 && depth <= 3, "Unsupported depth!", {});
+
+        switch (typeId)
+         {
+             case RCSResourceAttributes::TypeId::NULL_T: return { };
+
+             case RCSResourceAttributes::TypeId::BOOL:
+                 return toNativeValue< bool >(env, val, depth);
+
+             case RCSResourceAttributes::TypeId::INT:
+                 return toNativeValue< int >(env, val, depth);
+
+             case RCSResourceAttributes::TypeId::DOUBLE:
+                 return toNativeValue< double >(env, val, depth);
+
+             case RCSResourceAttributes::TypeId::STRING:
+                 return toNativeValue< std::string >(env, val, depth);
+
+             case RCSResourceAttributes::TypeId::ATTRIBUTES:
+                 return toNativeValue< RCSResourceAttributes >(env, val, depth);
+         }
+
+        throwRCSException(env, "Failed to convert RCSValue : unknown type id");
+        return {};
+    }
+
+    template< typename T, int DEPTH, typename BASE_TYPE = typename BaseType< T >::type >
+    inline jobject createJavaObject(JNIEnvWrapper* env, const T& value, Int2Type< DEPTH >)
+    {
+        const std::string elementClsName{ std::string{ ArrayPrefix< DEPTH - 1 >::str }
+            + JniTypeTrait< BASE_TYPE >::className };
+
+        LOGD("create array %dd, %s", DEPTH, elementClsName.c_str());
+
+        auto cls = env->FindClass(elementClsName.c_str());
+
+        const jsize len = value.size();
+
+        auto array = env->NewObjectArray(len, cls, nullptr);
+
+        for(jsize i = 0; i < len; ++i)
+        {
+            auto element = createJavaObject(env, value[i], Int2Type< DEPTH - 1>{ });
+            env->SetObjectArrayElement(array, i, element);
+        }
+
+        return array;
+    }
+
+    template< typename T, typename TRAIT = JniTypeTrait< T > >
+    inline typename std::enable_if< TRAIT::isPrimitive, jobject >::type
+    createJavaObject(JNIEnvWrapper* env, const std::vector< T >& value, Int2Type< 1 >)
+    {
+        LOGD("create array with newArray");
+        const jsize len = value.size();
+
+        auto array = (env->*TRAIT::newArrayFunc)(len);
+
+        if (!value.empty()) (env->*TRAIT::setArrayRegionFunc)(array, 0, len, &value[0]);
+
+        return array;
+    }
+
+    inline jobject createJavaObject(JNIEnvWrapper* env, const std::vector< bool >& value, Int2Type< 1 >)
+    {
+        const auto len = value.size();
+        LOGD("create bool array with newArray %d", len);
+
+        auto arrayObj = env->NewBooleanArray(len);
+
+        bool* raw = static_cast< bool* >(env->GetPrimitiveArrayCritical(arrayObj, 0));
+
+        std::copy(value.begin(), value.end(), raw);
+
+        env->ReleasePrimitiveArrayCritical(arrayObj, raw, 0);
+
+        return arrayObj;
+    }
+
+    template< typename T, typename TRAIT = JniTypeTrait< T > >
+    inline jobject createJavaObject(JNIEnvWrapper* env, const T& value, Int2Type< 0 >)
+    {
+        LOGD("createJavaObject 0-depth");
+        return TRAIT::newObjectFunc(env, value);
+    }
+
+    template< int DEPTH >
+    inline jobject createJavaObject(JNIEnvWrapper* env, const RCSResourceAttributes::Value& value)
+    {
+        const auto type = value.getType();
+        const auto baseType = RCSResourceAttributes::Type::getBaseTypeId(type);
+
+        LOGD("createJavaObject with DEPTH. type is %d", static_cast< int >(baseType));
+
+        switch (baseType)
+        {
+            case RCSResourceAttributes::TypeId::NULL_T:
+                return env->GetStaticObjectField(g_cls_RCSValue, g_field_RCSValue_sNullValue);
+
+            case RCSResourceAttributes::TypeId::BOOL:
+                return createJavaObject(env, value.get< typename SeqType< DEPTH, bool >::type >(),
+                        Int2Type< DEPTH >{ });
+
+            case RCSResourceAttributes::TypeId::INT:
+                return createJavaObject(env, value.get< typename SeqType< DEPTH, int >::type >(),
+                        Int2Type< DEPTH >{ });
+
+            case RCSResourceAttributes::TypeId::DOUBLE:
+                return createJavaObject(env, value.get< typename SeqType< DEPTH, double >::type >(),
+                        Int2Type< DEPTH >{ });
+
+            case RCSResourceAttributes::TypeId::STRING:
+                return createJavaObject(env,
+                        value.get< typename SeqType< DEPTH, std::string >::type >(),
+                        Int2Type< DEPTH >{ });
+
+            case RCSResourceAttributes::TypeId::ATTRIBUTES:
+                return createJavaObject(env,
+                        value.get< typename SeqType< DEPTH, RCSResourceAttributes >::type >(),
+                        Int2Type< DEPTH >{ });
+        }
+
+        LOGE("Unknown type!");
+
+        return nullptr;
+    }
+
+    inline jobject createJavaObject(JNIEnvWrapper* env, const RCSResourceAttributes::Value& value)
+    {
+        const auto type = value.getType();
+        const auto depth = RCSResourceAttributes::Type::getDepth(type);
+
+        EXPECT_RET(depth >= 0 && depth <= 3, "Unsupported depth!", {});
+
+        switch (depth)
+        {
+            case 0: return createJavaObject< 0 >(env, value);
+            case 1: return createJavaObject< 1 >(env, value);
+            case 2: return createJavaObject< 2 >(env, value);
+            case 3: return createJavaObject< 3 >(env, value);
+        }
+
+        return nullptr;
+    }
+
+    inline RCSResourceAttributes::TypeId toNativeTypeId(JNIEnvWrapper* env, jobject typeIdObj)
+    {
+        typedef RCSResourceAttributes::TypeId TypeId;
+
+        if (env->IsSameObject(g_obj_TypeId_Null, typeIdObj)) return TypeId::NULL_T;
+        if (env->IsSameObject(g_obj_TypeId_Boolean, typeIdObj)) return TypeId::BOOL;
+        if (env->IsSameObject(g_obj_TypeId_Integer, typeIdObj)) return TypeId::INT;
+        if (env->IsSameObject(g_obj_TypeId_Double, typeIdObj)) return TypeId::DOUBLE;
+        if (env->IsSameObject(g_obj_TypeId_String, typeIdObj)) return TypeId::STRING;
+        if (env->IsSameObject(g_obj_TypeId_Attributes, typeIdObj)) return TypeId::ATTRIBUTES;
+        if (env->IsSameObject(g_obj_TypeId_Array, typeIdObj)) return TypeId::VECTOR;
+
+        throwRCSException(env, "Failed to convert RCSValue : unknown type id");
+        return TypeId::NULL_T;
+    }
+
+    jobject getTypeIdObj(JNIEnvWrapper* env, const char* name)
+    {
+        return env->NewGlobalRef(
+                env->GetStaticObjectField(g_cls_TypeId, name, AS_SIG(CLS_NAME_VALUE_TYPEID)));
+    }
+}
+
+void initRCSValue(JNIEnvWrapper* env)
+{
+    g_cls_RCSValue = env->FindClassAsGlobalRef(CLS_NAME_VALUE);
+    g_ctor_RCSValue = env->GetConstructorID(g_cls_RCSValue, "(" AS_SIG(CLS_NAME_OBJECT) ")V");
+
+    g_method_RCSValue_getType = env->GetMethodID(g_cls_RCSValue, "getType",
+            "()" AS_SIG(CLS_NAME_VALUE_TYPE));
+
+    g_field_RCSValue_mObject = env->GetFieldID(g_cls_RCSValue, "mObject", AS_SIG(CLS_NAME_OBJECT));
+
+    g_field_RCSValue_sNullValue = env->GetStaticFieldID(g_cls_RCSValue, "sNullValue",
+            AS_SIG(CLS_NAME_VALUE_NULL_TYPE));
+
+    g_cls_Type = env->FindClassAsGlobalRef(CLS_NAME_VALUE_TYPE);
+
+    g_smethod_Type_getBaseTypeId = env->GetStaticMethodID(g_cls_Type, "getBaseTypeId",
+            "(" AS_SIG(CLS_NAME_VALUE_TYPE) ")" AS_SIG(CLS_NAME_VALUE_TYPEID));
+
+    g_smethod_Type_getDepth = env->GetStaticMethodID(g_cls_Type, "getDepth",
+                "(" AS_SIG(CLS_NAME_VALUE_TYPE) ")I");
+
+    g_cls_TypeId = env->FindClassAsGlobalRef(CLS_NAME_VALUE_TYPEID);
+
+    g_obj_TypeId_Null = getTypeIdObj(env, "NULL");
+    g_obj_TypeId_Boolean = getTypeIdObj(env, "BOOLEAN");
+    g_obj_TypeId_Integer = getTypeIdObj(env, "INTEGER");
+    g_obj_TypeId_Double = getTypeIdObj(env, "DOUBLE");
+    g_obj_TypeId_String = getTypeIdObj(env, "STRING");
+    g_obj_TypeId_Attributes = getTypeIdObj(env, "ATTRIBUTES");
+    g_obj_TypeId_Array = getTypeIdObj(env, "ARRAY");
+}
+
+void clearRCSValue(JNIEnvWrapper* env)
+{
+    env->DeleteGlobalRef(g_cls_RCSValue);
+    env->DeleteGlobalRef(g_cls_Type);
+    env->DeleteGlobalRef(g_cls_TypeId);
+
+    env->DeleteGlobalRef(g_obj_TypeId_Null);
+    env->DeleteGlobalRef(g_obj_TypeId_Boolean);
+    env->DeleteGlobalRef(g_obj_TypeId_Integer);
+    env->DeleteGlobalRef(g_obj_TypeId_Double);
+    env->DeleteGlobalRef(g_obj_TypeId_String);
+    env->DeleteGlobalRef(g_obj_TypeId_Attributes);
+    env->DeleteGlobalRef(g_obj_TypeId_Array);
+}
+
+RCSResourceAttributes::Value toNativeAttrsValue(JNIEnv* env, jobject valueObj)
+{
+    JNIEnvWrapper envWrapper(env);
+
+    try
+    {
+        return toNativeAttrsValue(&envWrapper, valueObj);
+    }
+    catch (const JavaException&)
+    {
+        return { };
+    }
+}
+
+RCSResourceAttributes::Value toNativeAttrsValue(JNIEnvWrapper* env, jobject valueObj)
+{
+    LOGD("Type object");
+    auto typeObj = env->CallObjectMethod(valueObj, g_method_RCSValue_getType);
+    LOGD("Type base type object");
+    auto typeIdObj = env->CallStaticObjectMethod(g_cls_Type, g_smethod_Type_getBaseTypeId, typeObj);
+    LOGD("Type getDepth");
+    auto depth = env->CallStaticIntMethod(g_cls_Type, g_smethod_Type_getDepth, typeObj);
+    LOGD("Type get object field");
+    auto memObj = env->GetObjectField(valueObj, g_field_RCSValue_mObject);
+
+    LOGD("Type to native value");
+    auto ret = toNativeValue(env, memObj, depth, toNativeTypeId(env, typeIdObj));
+
+    if (env->get()->ExceptionCheck()) throw JavaException();
+
+    return ret;
+}
+
+jobject newRCSValueObject(JNIEnv* env, const RCSResourceAttributes::Value& value)
+{
+    JNIEnvWrapper envWrapper(env);
+
+    try
+    {
+        return newRCSValueObject(&envWrapper, value);
+    }
+    catch (const JavaException&)
+    {
+        return {};
+    }
+}
+
+jobject newRCSValueObject(JNIEnvWrapper* env, const RCSResourceAttributes::Value& value)
+{
+    LOGD("newRCSValueObject");
+
+    JavaLocalObject valueObj{ env, createJavaObject(env, value) };
+
+    if (env->get()->ExceptionCheck()) throw JavaException();
+
+    return env->NewObject(g_cls_RCSValue, g_ctor_RCSValue, valueObj.get());
+}
diff --git a/service/resource-container/android/resource-container/src/main/jni/JniRcsValue.h b/service/resource-container/android/resource-container/src/main/jni/JniRcsValue.h
new file mode 100644 (file)
index 0000000..c27c23f
--- /dev/null
@@ -0,0 +1,39 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef JNI_RCS_VALUE_H_
+#define JNI_RCS_VALUE_H_
+
+#include <jni.h>
+
+#include "RCSResourceAttributes.h"
+
+class JNIEnvWrapper;
+
+void initRCSValue(JNIEnvWrapper*);
+void clearRCSValue(JNIEnvWrapper*);
+
+OIC::Service::RCSResourceAttributes::Value toNativeAttrsValue(JNIEnv*, jobject);
+OIC::Service::RCSResourceAttributes::Value toNativeAttrsValue(JNIEnvWrapper*, jobject);
+
+jobject newRCSValueObject(JNIEnv*, const OIC::Service::RCSResourceAttributes::Value&);
+jobject newRCSValueObject(JNIEnvWrapper*, const OIC::Service::RCSResourceAttributes::Value&);
+
+#endif // JNI_RCS_VALUE_H_
index f84f4d9..1232d8c 100644 (file)
@@ -58,7 +58,7 @@ jmethodID g_ctor_ArrayList;
 
 namespace
 {
-    inline void initPrimitiveTypes(JNIEnvWrapper *env)
+    inline void initPrimitiveTypes(JNIEnvWrapperenv)
     {
         g_cls_Boolean = env->FindClassAsGlobalRef(CLS_NAME_BOOLEAN);
         g_ctor_Boolean = env->GetConstructorID(g_cls_Boolean, "(Z)V");
@@ -76,13 +76,13 @@ namespace
     }
 }
 
-void initJavaClasses(JNIEnvWrapper *env)
+void initJavaClasses(JNIEnvWrapperenv)
 {
     initPrimitiveTypes(env);
 
     auto clsCollection = env->FindClass(CLS_NAME_COLLECTION);
     g_method_Collection_add = env->GetMethodID(clsCollection, "add",
-                              "(" AS_SIG(CLS_NAME_OBJECT) ")Z");
+            "(" AS_SIG(CLS_NAME_OBJECT) ")Z");
 
     g_cls_ArrayList = env->FindClassAsGlobalRef(CLS_NAME_ARRAY_LIST);
     g_ctor_ArrayList = env->GetConstructorID(g_cls_ArrayList, "()V");
@@ -93,20 +93,20 @@ void initJavaClasses(JNIEnvWrapper *env)
     g_cls_Map = env->FindClassAsGlobalRef(CLS_NAME_MAP);
     g_method_Map_entrySet = env->GetMethodID(g_cls_Map, "entrySet", "()" AS_SIG(CLS_NAME_SET));
     g_method_Map_put = env->GetMethodID(g_cls_Map, "put",
-                                        "(" AS_SIG(CLS_NAME_OBJECT) AS_SIG(CLS_NAME_OBJECT) ")" AS_SIG(CLS_NAME_OBJECT));
+            "(" AS_SIG(CLS_NAME_OBJECT) AS_SIG(CLS_NAME_OBJECT) ")" AS_SIG(CLS_NAME_OBJECT));
 
     g_cls_MapEntry = env->FindClassAsGlobalRef(CLS_NAME_MAP_ENTRY);
     g_method_MapEntry_getKey = env->GetMethodID(g_cls_MapEntry, "getKey",
-                               "()" AS_SIG(CLS_NAME_OBJECT));
+            "()" AS_SIG(CLS_NAME_OBJECT));
     g_method_MapEntry_getValue = env->GetMethodID(g_cls_MapEntry, "getValue",
-                                 "()" AS_SIG(CLS_NAME_OBJECT));
+            "()" AS_SIG(CLS_NAME_OBJECT));
 
     g_cls_Iterator = env->FindClassAsGlobalRef(CLS_NAME_ITERATOR);
     g_method_Iterator_hasNext = env->GetMethodID(g_cls_Iterator, "hasNext", "()Z");
     g_method_Iterator_next = env->GetMethodID(g_cls_Iterator, "next", "()" AS_SIG(CLS_NAME_OBJECT));
 }
 
-void clearJavaClasses(JNIEnvWrapper *env)
+void clearJavaClasses(JNIEnvWrapperenv)
 {
     env->DeleteGlobalRef(g_cls_Boolean);
     env->DeleteGlobalRef(g_cls_Integer);
index b91ffea..83e01dd 100644 (file)
 
 #include <string>
 
-#define PACKAGE_NAME "org/iotivity/service"
+#define PACKAGE_NAME "org/iotivity/service/resourcecontainer"
+
+#define CLS_NAME_VALUE PACKAGE_NAME "/RcsValue"
+
+#define CLS_NAME_RESOURCEATTRIBUTES PACKAGE_NAME "/RcsResourceAttributes"
 
 #define CLS_NAME_OBJECT "java/lang/Object"
 #define CLS_NAME_STRING "java/lang/String"
 #define CLS_NAME_MAP_ENTRY "java/util/Map$Entry"
 #define CLS_NAME_ITERATOR "java/util/Iterator"
 
-#define EXC_NAME_RCS PACKAGE_NAME "/utils/RcsException"
-#define EXC_NAME_PLATFORM PACKAGE_NAME "/utils/RcsPlatformException"
-#define EXC_NAME_ILLEGAL_STATE PACKAGE_NAME "/utils/RcsIllegalStateException"
-
 #define AS_SIG(CLS_NAME) "L" CLS_NAME ";"
 
 class JNIEnvWrapper;
@@ -81,42 +81,41 @@ extern jmethodID g_ctor_Integer;
 extern jmethodID g_ctor_Double;
 
 extern jmethodID g_ctor_ArrayList;
-
 void initJavaClasses(JNIEnvWrapper *);
 void clearJavaClasses(JNIEnvWrapper *);
 
 template< typename ENV >
-inline jobject newBooleanObject(ENV *env, bool value)
+inline jobject newBooleanObject(ENVenv, bool value)
 {
     return env->NewObject(g_cls_Boolean, g_ctor_Boolean, value);
 }
 
 template< typename ENV >
-inline jobject newIntegerObject(ENV *env, int value)
+inline jobject newIntegerObject(ENVenv, int value)
 {
     return env->NewObject(g_cls_Integer, g_ctor_Integer, value);
 }
 
 template< typename ENV >
-inline jobject newDoubleObject(ENV *env, double value)
+inline jobject newDoubleObject(ENVenv, double value)
 {
     return env->NewObject(g_cls_Double, g_ctor_Double, value);
 }
 
 template< typename ENV >
-inline jstring newStringObject(ENV *env, const std::string &value)
+inline jstring newStringObject(ENV* env, const std::string& value)
 {
     return env->NewStringUTF(value.c_str());
 }
 
 template< typename ENV >
-inline jstring newStringObjectCstr(ENV *env, const char *value)
+inline jstring newStringObjectCstr(ENV* env, const char* value)
 {
     return env->NewStringUTF(value);
 }
 
 template< typename ENV >
-inline std::string toStdString(ENV *env, jstring obj)
+inline std::string toStdString(ENVenv, jstring obj)
 {
     if (!obj) return "";
 
@@ -124,7 +123,7 @@ inline std::string toStdString(ENV *env, jstring obj)
 
     if (!cstr) return "";
 
-    std::string result { cstr };
+    std::string result{ cstr };
 
     env->ReleaseStringUTFChars(obj, cstr);
 
@@ -132,73 +131,73 @@ inline std::string toStdString(ENV *env, jstring obj)
 }
 
 template< typename ENV >
-inline jobject newArrayList(ENV *env)
+inline jobject newArrayList(ENVenv)
 {
     return env->NewObject(g_cls_ArrayList, g_ctor_ArrayList);
 }
 
 template< typename ENV >
-inline bool invoke_Boolean_booleanValue(ENV *env, jobject obj)
+inline bool invoke_Boolean_booleanValue(ENVenv, jobject obj)
 {
     return env->CallBooleanMethod(obj, g_method_Boolean_booleanValue);
 }
 
 template< typename ENV >
-inline int invoke_Integer_intValue(ENV *env, jobject obj)
+inline int invoke_Integer_intValue(ENVenv, jobject obj)
 {
     return env->CallIntMethod(obj, g_method_Integer_intValue);
 }
 
 template< typename ENV >
-inline double invoke_Double_doubleValue(ENV *env, jobject obj)
+inline double invoke_Double_doubleValue(ENVenv, jobject obj)
 {
     return env->CallDoubleMethod(obj, g_method_Double_doubleValue);
 }
 
 template< typename ENV >
-inline jboolean invoke_Collection_add(ENV *env, jobject collectionObj, jobject valueObj)
+inline jboolean invoke_Collection_add(ENVenv, jobject collectionObj, jobject valueObj)
 {
     return env->CallBooleanMethod(collectionObj, g_method_Collection_add, valueObj);
 }
 
 template< typename ENV >
-inline jobject invoke_Map_entrySet(ENV *env, jobject mapObj)
+inline jobject invoke_Map_entrySet(ENVenv, jobject mapObj)
 {
     return env->CallObjectMethod(mapObj, g_method_Map_entrySet);
 }
 
 template< typename ENV >
-inline jobject invoke_Map_put(ENV *env, jobject mapObj, jobject keyObj, jobject valueObj)
+inline jobject invoke_Map_put(ENVenv, jobject mapObj, jobject keyObj, jobject valueObj)
 {
     return env->CallObjectMethod(mapObj, g_method_Map_put, keyObj, valueObj);
 }
 
 template< typename ENV >
-inline jobject invoke_MapEntry_getKey(ENV *env, jobject entryObj)
+inline jobject invoke_MapEntry_getKey(ENVenv, jobject entryObj)
 {
     return env->CallObjectMethod(entryObj, g_method_MapEntry_getKey);
 }
 
 template< typename ENV >
-inline jobject invoke_MapEntry_getValue(ENV *env, jobject entryObj)
+inline jobject invoke_MapEntry_getValue(ENVenv, jobject entryObj)
 {
     return env->CallObjectMethod(entryObj, g_method_MapEntry_getValue);
 }
 
 template< typename ENV >
-inline jobject invoke_Set_iterator(ENV *env, jobject setObj)
+inline jobject invoke_Set_iterator(ENVenv, jobject setObj)
 {
     return env->CallObjectMethod(setObj, g_method_Set_iterator);
 }
 
 template< typename ENV >
-inline bool invoke_Iterator_hasNext(ENV *env, jobject iterObj)
+inline bool invoke_Iterator_hasNext(ENVenv, jobject iterObj)
 {
     return env->CallBooleanMethod(iterObj, g_method_Iterator_hasNext);
 }
 
 template< typename ENV >
-inline jobject invoke_Iterator_next(ENV *env, jobject iterObj)
+inline jobject invoke_Iterator_next(ENVenv, jobject iterObj)
 {
     return env->CallObjectMethod(iterObj, g_method_Iterator_next);
 }
index 4774a72..b1e13a0 100644 (file)
@@ -32,26 +32,26 @@ namespace
     jmethodID g_ctor_PlatformException;
 }
 
-void initJavaExceptions(JNIEnvWrapper *env)
+void initJavaExceptions(JNIEnvWrapperenv)
 {
-    g_cls_PlatformException = env->FindClassAsGlobalRef(EXC_NAME_PLATFORM);
+    /*g_cls_PlatformException = env->FindClassAsGlobalRef(EXC_NAME_PLATFORM);
     g_ctor_PlatformException = env->GetConstructorID(g_cls_PlatformException,
-                               "(" AS_SIG(CLS_NAME_STRING) "I)V");
+            "(" AS_SIG(CLS_NAME_STRING) "I)V");*/
 }
 
-void clearJavaExceptions(JNIEnvWrapper *env)
+void clearJavaExceptions(JNIEnvWrapperenv)
 {
-    env->DeleteGlobalRef(g_cls_PlatformException);
+    //env->DeleteGlobalRef(g_cls_PlatformException);
 }
 
-void throwPlatformException(JNIEnv *env, const OIC::Service::RCSPlatformException &e)
+void throwPlatformException(JNIEnv* env, const OIC::Service::RCSPlatformException& e)
 {
-    auto msg = newStringObject(env, e.getReason());
+    /*auto msg = newStringObject(env, e.getReason());
     VERIFY_NO_EXC(env);
 
     auto exObj = env->NewObject(g_cls_PlatformException, g_ctor_PlatformException,
-                                msg, e.getReasonCode());
+            msg, e.getReasonCode());
     VERIFY_NO_EXC(env);
 
-    env->Throw(static_cast< jthrowable >(exObj));
+    env->Throw(static_cast< jthrowable >(exObj));*/
 }
index 40b8999..bbde9ec 100644 (file)
@@ -35,15 +35,15 @@ namespace OIC
 
 class JNIEnvWrapper;
 
-void initJavaExceptions(JNIEnvWrapper *);
-void clearJavaExceptions(JNIEnvWrapper *);
+void initJavaExceptions(JNIEnvWrapper*);
+void clearJavaExceptions(JNIEnvWrapper*);
 
-void throwPlatformException(JNIEnv *, const OIC::Service::RCSPlatformException &);
+void throwPlatformException(JNIEnv*, const OIC::Service::RCSPlatformException&);
 
 template < typename ENV >
-void throwRCSException(ENV *env, const char *msg)
+void throwRCSException(ENV* env, const char* msg)
 {
-    env->ThrowNew(env->FindClass(EXC_NAME_RCS), msg);
+    //env->ThrowNew(env->FindClass(EXC_NAME_RCS), msg);
 }
 
 
diff --git a/service/resource-container/android/resource-container/src/main/jni/util/JavaGlobalRef.h b/service/resource-container/android/resource-container/src/main/jni/util/JavaGlobalRef.h
deleted file mode 100644 (file)
index 812fb41..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-#ifndef JAVA_GLOBAL_REF_H_
-#define JAVA_GLOBAL_REF_H_
-
-#include <memory>
-#include <cassert>
-
-#include "ScopedEnv.h"
-
-class JavaGlobalRef
-{
-    public:
-    JavaGlobalRef(JNIEnv *env, jobject obj) noexcept :
-        m_obj { }
-        {
-            assert(env  &&"JNIEnv is nullptr");
-
-            static auto deleter = [](jobject * obj)
-            {
-                if (obj && *obj)
-                {
-                    ScopedEnv env;
-                    env->DeleteGlobalRef(*obj);
-                }
-                delete obj;
-            };
-
-            m_obj.reset(new jobject{ env->NewGlobalRef(obj) }, deleter);
-        }
-
-        operator jobject() const noexcept
-        {
-            return *m_obj;
-        }
-
-    private:
-        std::shared_ptr< jobject > m_obj;
-};
-
-
-
-#endif // JAVA_GLOBAL_REF_H_
index 34e7d1e..af4f204 100644 (file)
 template < typename T >
 class JavaLocalRef
 {
-    public:
+public:
     JavaLocalRef(JNIEnv *env, T obj) noexcept :
         m_env { env },
         m_obj { obj }
         {
-            assert(env  &&"JNIEnv is nullptr");
+            assert(env && "JNIEnv is nullptr");
         }
 
-        template< typename ENV >
+    template< typename ENV >
     JavaLocalRef(ENV *env, T obj) noexcept :
-        m_env { env->get() },
-        m_obj { obj }
-        {
-            assert(env  &&"JNIEnv is nullptr");
-        }
+    m_env { env->get() },
+    m_obj { obj }
+    {
+        assert(env  && "JNIEnv is nullptr");
+    }
 
-        ~JavaLocalRef()
-        {
-            if (m_obj) m_env->DeleteLocalRef(m_obj);
-        }
+    ~JavaLocalRef()
+    {
+        if (m_obj) m_env->DeleteLocalRef(m_obj);
+    }
 
-        operator bool() const noexcept { return m_obj; }
-        operator T() const noexcept { return m_obj; }
+    operator bool() const noexcept { return m_obj; }
+    operator T() const noexcept { return m_obj; }
 
-        jobject get() const noexcept { return m_obj; }
+    jobject get() const noexcept { return m_obj; }
 
-        JavaLocalRef(const JavaLocalRef &) = delete;
-        JavaLocalRef &operator=(const JavaLocalRef &) = delete;
+    JavaLocalRef(const JavaLocalRef &) = delete;
+    JavaLocalRef &operator=(const JavaLocalRef &) = delete;
 
-        JavaLocalRef &operator=(JavaLocalRef && ) = delete;
+    JavaLocalRef &operator=(JavaLocalRef && ) = delete;
 
-    private:
-        JNIEnv *m_env;
-        T m_obj;
+private:
+    JNIEnv *m_env;
+    T m_obj;
 };
 
 typedef JavaLocalRef< jobject > JavaLocalObject;
index a8b7d4b..c1b9030 100644 (file)
 #include "JNIEnvWrapper.h"
 #include "Log.h"
 
-extern JavaVM *g_jvm;
+extern JavaVMg_jvm;
 
 namespace Detail
 {
-    inline std::pair<JNIEnv *, bool> getEnv()
+    inline std::pair<JNIEnv*, bool> getEnv()
     {
-        JNIEnv *env { };
-        bool needToDetach { };
+        JNIEnv* env{ };
+        bool needToDetach{ };
 
-        auto ret = g_jvm->GetEnv((void **) &env, JNI_VERSION_1_6);
+        auto ret = g_jvm->GetEnv((void**) &env, JNI_VERSION_1_6);
 
         switch (ret)
         {
@@ -45,19 +45,19 @@ namespace Detail
                 break;
 
             case JNI_EDETACHED:
+            {
+                auto attachRet = g_jvm->AttachCurrentThread(&env, NULL);
+
+                if (attachRet != JNI_OK)
+                {
+                    LOGT_E("JNI-ScopedEnv", "Failed to get the environment : %d", attachRet);
+                }
+                else
                 {
-                    auto attachRet = g_jvm->AttachCurrentThread(&env, NULL);
-
-                    if (attachRet != JNI_OK)
-                    {
-                        LOGT_E("JNI-ScopedEnv", "Failed to get the environment : %d", attachRet);
-                    }
-                    else
-                    {
-                        needToDetach = true;
-                    }
-                    break;
+                    needToDetach = true;
                 }
+                break;
+            }
             case JNI_EVERSION:
                 LOGT_E("JNI-ScopedEnv", "JNI version not supported");
                 break;
@@ -73,90 +73,90 @@ namespace Detail
 
 class ScopedEnv
 {
-    public:
+public:
     ScopedEnv() noexcept :
         m_env { },
-        m_needToDetach { false }
-        {
-            auto val = Detail::getEnv();
+        m_needToDetach{ false }
+    {
+        auto val = Detail::getEnv();
 
-            m_env = val.first;
-            m_needToDetach = val.second;
-        }
+        m_env = val.first;
+        m_needToDetach = val.second;
+    }
 
-        ~ScopedEnv()
+    ~ScopedEnv()
+    {
+        if (m_env && m_needToDetach)
         {
-            if (m_env && m_needToDetach)
-            {
-                g_jvm->DetachCurrentThread();
-            }
+            g_jvm->DetachCurrentThread();
         }
+    }
 
-        ScopedEnv(const ScopedEnv &) = delete;
-        ScopedEnv &operator=(const ScopedEnv &) = delete;
+    ScopedEnv(const ScopedEnv&) = delete;
+    ScopedEnv& operator=(const ScopedEnv&) = delete;
 
-        operator bool() const noexcept
-        {
-            return m_env;
-        }
+    operator bool() const noexcept
+    {
+        return m_env;
+    }
 
-        JNIEnv *operator->() noexcept
-        {
-            return m_env;
-        }
+    JNIEnv* operator->() noexcept
+    {
+        return m_env;
+    }
 
-        JNIEnv *get() noexcept
-        {
-            return m_env;
-        }
+    JNIEnv* get() noexcept
+    {
+        return m_env;
+    }
 
-    private:
-        JNIEnv *m_env;
-        bool m_needToDetach;
+private:
+    JNIEnv* m_env;
+    bool m_needToDetach;
 };
 
 class ScopedEnvWrapper
 {
-    public:
+public:
     ScopedEnvWrapper() noexcept :
         m_env { },
-        m_needToDetach { false }
-        {
-            auto val = Detail::getEnv();
+        m_needToDetach{ false }
+    {
+        auto val = Detail::getEnv();
 
-            m_env = val.first;
-            m_needToDetach = val.second;
-        }
+        m_env = val.first;
+        m_needToDetach = val.second;
+    }
 
-        ~ScopedEnvWrapper()
+    ~ScopedEnvWrapper()
+    {
+        if (m_env && m_needToDetach)
         {
-            if (m_env && m_needToDetach)
-            {
-                g_jvm->DetachCurrentThread();
-            }
+            g_jvm->DetachCurrentThread();
         }
+    }
 
-        ScopedEnvWrapper(const ScopedEnvWrapper &) = delete;
-        ScopedEnvWrapper &operator=(const ScopedEnvWrapper &) = delete;
+    ScopedEnvWrapper(const ScopedEnvWrapper&) = delete;
+    ScopedEnvWrapper& operator=(const ScopedEnvWrapper&) = delete;
 
-        operator bool() const noexcept
-        {
-            return m_env;
-        }
+    operator bool() const noexcept
+    {
+        return m_env;
+    }
 
-        JNIEnvWrapper *operator->() noexcept
-        {
-            return &m_env;
-        }
+    JNIEnvWrapper* operator->() noexcept
+    {
+        return &m_env;
+    }
 
-        JNIEnvWrapper *get() noexcept
-        {
-            return &m_env;
-        }
+    JNIEnvWrapper* get() noexcept
+    {
+        return &m_env;
+    }
 
-    private:
-        JNIEnvWrapper m_env;
-        bool m_needToDetach;
+private:
+    JNIEnvWrapper m_env;
+    bool m_needToDetach;
 };
 
 #endif // RCS_JIN_SCOPEDENV_H_
index ddc79ca..5a69fb1 100644 (file)
@@ -43,12 +43,12 @@ namespace OIC
                 /**
                 * Constructor for BundleActivator
                 */
-                BundleActivator();
+                BundleActivator() { };
 
                 /**
                 * Virtual destructor for BundleActivator
                 */
-                virtual ~BundleActivator();
+                virtual ~BundleActivator() { };
 
                 /**
                 * Activate the Bundle to make bundle work and create bundle resources
@@ -60,14 +60,14 @@ namespace OIC
                 * @return void
                 */
                 virtual void activateBundle(ResourceContainerBundleAPI *resourceContainer,
-                                            std::string bundleId);
+                                            std::string bundleId) = 0;
 
                 /**
                 * Deactivate the Bundle to stop working and destroy bundle resources
                 *
                 * @return void
                 */
-                virtual void deactivateBundle();
+                virtual void deactivateBundle() = 0;
 
                 /**
                 * Create Bundle Resource instance and register the resource in the container
@@ -79,7 +79,7 @@ namespace OIC
                 virtual void createResource(resourceInfo resourceInfo) = 0;
 
                 /**
-                * Destroy Bundle Resource instance and register the resource in the container
+                * Unregister the resource in the container and destroy the Bundle Resource
                 *
                 * @param pBundleResource Bundle resource to be destroyed
                 *
index 5315edd..23e9f85 100644 (file)
@@ -26,6 +26,8 @@
 #include <map>
 #include <vector>
 #include <memory>
+#include <mutex>
+
 
 #include "NotificationReceiver.h"
 #include "RCSResourceAttributes.h"
@@ -79,14 +81,14 @@ namespace OIC
                 *
                 * @return void
                 */
-                void registerObserver(NotificationReceiver *pNotiReceiver);
+                void registerObserver(NotificationReceiverpNotiReceiver);
 
                 /**
                 * Return all attributes of the resource
                 *
                 * @return Attributes of the resource
                 */
-                RCSResourceAttributes &getAttributes();
+                const RCSResourceAttributes getAttributes();
 
                 /**
                 * Set attributes of the resource
@@ -95,7 +97,9 @@ namespace OIC
                 *
                 * @return void
                 */
-                void setAttributes(RCSResourceAttributes &attrs);
+                void setAttributes(const RCSResourceAttributes &attrs);
+
+                void setAttributes(const RCSResourceAttributes &attrs, bool notify);
 
                 /**
                 * Return the value of an attribute
@@ -127,11 +131,36 @@ namespace OIC
                 *
                 * @param value Value of attribute to set
                 *
+                * @param notify Flag to indicate if OIC clients should be notified about an update
+                *
+                * @return void
+                */
+                void setAttribute(const std::string &key, RCSResourceAttributes::Value &value,
+                                  bool notify);
+
+                /**
+                * Sets the value of an attribute
+                *
+                * @param key Name of attribute to set
+                *
+                * @param value Value of attribute to set
+                *
                 * @return void
                 */
                 void setAttribute(const std::string &key, RCSResourceAttributes::Value &&value);
 
                 /**
+                * Sets the value of an attribute
+                *
+                * @param key Name of attribute to set
+                *
+                * @param value Value of attribute to set
+                *
+                * @return void
+                */
+                void setAttribute(const std::string &key, RCSResourceAttributes::Value &value);
+
+                /**
                 * This function should be implemented by the according bundle resource
                 * and execute the according business logic (e.g., light switch or sensor resource)
                 * to retrieve a sensor value. If a new sensor value is retrieved, the
@@ -141,7 +170,7 @@ namespace OIC
                 *
                 * @return All attributes
                 */
-                virtual RCSResourceAttributes &handleGetAttributesRequest() = 0;
+                virtual RCSResourceAttributes handleGetAttributesRequest() = 0;
 
                 /**
                 * This function should be implemented by the according bundle resource
@@ -159,18 +188,21 @@ namespace OIC
                 *
                 * @return void
                 */
-                virtual void handleSetAttributesRequest(RCSResourceAttributes &attrs) = 0;
+                virtual void handleSetAttributesRequest(const RCSResourceAttributes &attrs) = 0;
+            private:
 
+                void sendNotification(NotificationReceiver *notficiationRecevier, std::string uri);
 
             public:
                 std::string m_bundleId;
-                std::string m_name, m_uri, m_resourceType, m_address;
+                std::string m_name, m_uri, m_resourceType, m_interface, m_address;
                 std::map< std::string,
-                    std::vector< std::map< std::string, std::string > > > m_mapResourceProperty;
+                std::vector< std::map< std::string, std::string > > > m_mapResourceProperty;
 
             private:
-                NotificationReceiver *m_pNotiReceiver;
+                NotificationReceiverm_pNotiReceiver;
                 RCSResourceAttributes m_resourceAttributes;
+                std::mutex m_resourceAttributes_mutex;
         };
     }
 }
index 414d688..a549d2e 100644 (file)
@@ -43,12 +43,12 @@ namespace OIC
                 /**
                 * Constructor for ProtocolBridgeConnector
                 */
-                ProtocolBridgeConnector();
+                ProtocolBridgeConnector() { };
 
                 /**
                 * Virtual destructor for ProtocolBridgeConnector
                 */
-                virtual ~ProtocolBridgeConnector();
+                virtual ~ProtocolBridgeConnector() { };
 
                 /**
                 * Execute the logic needed for connection with different protocol from IoTivity
index b8cfc8e..8ec6b87 100644 (file)
@@ -43,12 +43,12 @@ namespace OIC
                 /**
                 * Constructor for ProtocolBridgeResource
                 */
-                ProtocolBridgeResource();
+                ProtocolBridgeResource() { };
 
                 /**
                 * Virtual destructor for ProtocolBridgeResource
                 */
-                virtual ~ProtocolBridgeResource();
+                virtual ~ProtocolBridgeResource() { };
 
                 /**
                 * Initialize attributes of the resource
@@ -67,7 +67,7 @@ namespace OIC
                 *
                 * @return Value of all attributes
                 */
-                virtual RCSResourceAttributes &handleGetAttributesRequest() = 0;
+                virtual RCSResourceAttributes handleGetAttributesRequest() = 0;
 
                 /**
                 * This function should be implemented by the according bundle resource
@@ -85,7 +85,7 @@ namespace OIC
                 *
                 * @return void
                 */
-                virtual void handleSetAttributesRequest(RCSResourceAttributes &attrs) = 0;
+                virtual void handleSetAttributesRequest(const RCSResourceAttributes &attrs) = 0;
         };
     }
 }
index c8593e5..5c713fb 100644 (file)
@@ -54,9 +54,12 @@ namespace OIC
                 *
                 * @param resource bundle resource to register
                 *
-                * @return void
+                * @return int
+                *       0        in case of an success
+                *       -EEXIST  when the resource already exists and was not registered
+                *       -EINVAL  when it was not possible to create such a resource
                 */
-                virtual void registerResource(BundleResource::Ptr resource) = 0;
+                virtual int registerResource(BundleResource::Ptr resource) = 0;
 
                 /**
                 * Unregister bundle resource from the container
@@ -110,4 +113,4 @@ namespace OIC
     }
 }
 
-#endif
+#endif
\ No newline at end of file
index d26654d..c48e72a 100644 (file)
@@ -64,7 +64,7 @@ namespace OIC
                 *
                 * @return Value of all attributes
                 */
-                virtual RCSResourceAttributes &handleGetAttributesRequest() = 0;
+                virtual RCSResourceAttributes handleGetAttributesRequest() = 0;
 
                 /**
                 * This function should be implemented by the according bundle resource
@@ -82,7 +82,7 @@ namespace OIC
                 *
                 * @return void
                 */
-                virtual void handleSetAttributesRequest(RCSResourceAttributes &attrs) = 0;
+                virtual void handleSetAttributesRequest(const RCSResourceAttributes &attrs) = 0;
 
                 /**
                 * SoftSensor logic. Has to be provided by the soft sensor developer.
index b8e2e88..b7aab58 100644 (file)
@@ -73,10 +73,14 @@ public class BaseActivator implements BundleActivator {
         * @param resource
         *            bundle resource instance that should be made available as OIC
         *            resource
-        */
-       public void registerResource(BundleResource resource) {
+         * @return int
+         *       0        in case of an success
+         *       -EEXIST  when the resource already exists and was not registered
+         *       -EINVAL  when it was not possible to create such a resource
+         */
+       public int registerResource(BundleResource resource) {
                bundleResources.add(resource);
-               registerJavaResource(resource, resource.getAttributeKeys(), bundleId,
+               return registerJavaResource(resource, resource.getAttributeKeys(), bundleId,
                                resource.getURI(), resource.getResourceType(),
                                resource.getName());
        }
@@ -117,8 +121,13 @@ public class BaseActivator implements BundleActivator {
         *            unique bundle identifier
         * @param uri
         *            Uri that should be used to register the resource
-        */
-       private native void registerJavaResource(BundleResource resource,
+         *
+         * @return int
+         *       0        in case of an success
+         *       -EEXIST  when the resource already exists and was not registered
+         *       -EINVAL  when it was not possible to create such a resource
+         */
+       private native int registerJavaResource(BundleResource resource,
                        String[] attributes, String bundleId, String uri,
                        String resourceType, String name);
 
index 67d5692..46f7d52 100644 (file)
@@ -41,7 +41,7 @@ public interface BundleActivator {
      * Registers a single resource instance at the resource container
      * @param resource Instance of a BundleResource
      */
-    public void registerResource(BundleResource resource);
+    public int registerResource(BundleResource resource);
 
     /**
      * Unregisters a single resource instance at the resource container
index e264962..dcdca42 100644 (file)
@@ -35,9 +35,9 @@ class BMISensorResource : public SoftSensorResource
         BMISensorResource& operator=( const BMISensorResource& rhs )=delete;
         ~BMISensorResource();
 
-        virtual void handleSetAttributesRequest(RCSResourceAttributes &attrs);
+        virtual void handleSetAttributesRequest(const RCSResourceAttributes &attrs);
 
-        virtual RCSResourceAttributes &handleGetAttributesRequest();
+        virtual RCSResourceAttributes handleGetAttributesRequest();
 
         virtual void executeLogic();
 
index 9bfe09f..a9ae815 100644 (file)
@@ -32,12 +32,12 @@ BMISensorResource::~BMISensorResource()
 }
 
 void BMISensorResource::handleSetAttributesRequest(
-    RCSResourceAttributes &value)
+    const RCSResourceAttributes &value)
 {
     BundleResource::setAttributes(value);
 }
 
-RCSResourceAttributes &BMISensorResource::handleGetAttributesRequest()
+RCSResourceAttributes BMISensorResource::handleGetAttributesRequest()
 {
     return BundleResource::getAttributes();
 }
@@ -57,10 +57,10 @@ void BMISensorResource::onUpdatedInputResource(const std::string attributeName,
     m_mapInputData.clear();
 
     if (!attributeName.compare("weight"))
-        m_mapInputData.insert(std::make_pair("weight", values.back().toString()));
+        m_mapInputData.insert(std::make_pair("weight", values.back().get< std::string >()));
 
     if (!attributeName.compare("height"))
-        m_mapInputData.insert(std::make_pair("height", values.back().toString()));
+        m_mapInputData.insert(std::make_pair("height", values.back().get< std::string >()));
 
     executeLogic();
-}
\ No newline at end of file
+}
index e223629..420119a 100644 (file)
 
 #if defined(__linux__)
 #include <unistd.h>
+#include <string.h>
 #endif
 
 #include "RCSResourceContainer.h"
 #include "RCSBundleInfo.h"
-#include "oc_logger.hpp"
+
 #include <iostream>
+#include <functional>
+#include <limits>
+#include <stdexcept>
+#include <string>
 
-using namespace std;
 using namespace OIC::Service;
-using OC::oc_log_stream;
-
-#define MAX_PATH 2048
 
-/* Another way to create a context: */
-auto info_logger = []() -> boost::iostreams::stream<OC::oc_log_stream> &
+namespace
 {
-    static OC::oc_log_stream ols(oc_make_ostream_logger);
-    static boost::iostreams::stream<OC::oc_log_stream> os(ols);
-    return os;
+    typedef enum
+    {
+        START_RC = 1, STOP_RC,
+        ADD_SAMPLE_BUNDLE, START_SAMPLE_BUNDLE,
+        STOP_SAMPLE_BUNDLE, REMOVE_SAMPLE_BUNDLE,
+        ADD_SAMPLE_RESOURCE, REMOVE_SAMPLE_RESOURCE,
+        LIST_BUNDLES, LIST_RESOURCES,
+        EXIT = 11
+    } APPMenu;
+
+    struct CloseApp {};
+
+    const int MAX_PATH = 2048;
+
+    const std::string EXAMPLE_CONFIG_PATH = "/examples/ResourceContainerConfig.xml";
+    const std::string EXAMPLE_BUNDLE_ID = "oic.bundle.hueSample";
+    const std::string EXAMPLE_BUNDLE_URI = "/hueSample";
+    const std::string EXAMPLE_BUNDLE_PATH = "libHueBundle.so";
+    const std::string EXAMPLE_BUNDLE_ACTIVATOR = "huesample";
+    const std::string EXAMPLE_RESOURCE_URI = "/hue/light/sample";
+    const std::string EXAMPLE_RESOURCE_TYPE = "oic.r.light";
+    const std::string EXAMPLE_ADDRESS = "http://192.168.0.2/api/newdeveloper/lights/1";
 };
 
+bool g_bContainerStarted = false;
+bool g_bSampleBundleStarted = false;
+RCSResourceContainer *g_pResourceContainer = nullptr;
+
 void getCurrentPath(std::string *pPath)
 {
     char buffer[MAX_PATH];
 
+    if (!pPath->empty())
+        pPath->clear();
+
 #if defined(__linux__)
     char *strPath = NULL;
     int length = readlink("/proc/self/exe", buffer, MAX_PATH - 1);
@@ -61,129 +87,356 @@ void getCurrentPath(std::string *pPath)
     pPath->append(buffer);
 }
 
-int main()
+int processUserInput(int min, int max)
 {
-    info_logger()->set_module("ContainerTest");
-    info_logger()->set_level(OC_LOG_INFO);
+    int input;
 
-    info_logger() << "Starting container test." << std::flush;
+    std::cin >> input;
 
-    std::string strConfigPath;
-    getCurrentPath(&strConfigPath);
-    strConfigPath.append("/examples/ResourceContainerConfig.xml");
+    if (!std::cin.fail() && min <= input && input <= max)
+        return input;
 
-    RCSResourceContainer *container = RCSResourceContainer::getInstance();
-    container->startContainer(strConfigPath);
+    std::cin.clear();
+    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
+    throw std::runtime_error("Invalid Input, please try again");
+}
 
-    /*so bundle add test*/
-    cout << "++++++++++++++++++++++++++" << endl;
-    cout << "+++ Test for SO Bundle +++" << endl;
-    cout << "++++++++++++++++++++++++++" << endl;
-    cout << "Press enter to add SO bundle " << endl;
-    getchar();
-    std::map<string, string> bundleParams;
-    container->addBundle("oic.bundle.hueSample", "", "libHueBundle.so", "huesample", bundleParams);
+std::string processUserStringInput()
+{
+    std::string input;
+
+    std::cin >> input;
+
+    return input;
+}
 
-    std::list<unique_ptr<RCSBundleInfo>> bundles = container->listBundles();
-    std::list<unique_ptr<RCSBundleInfo>>::iterator bundleIt;
+void displayMenu()
+{
+    std::cout << "================================================================" << std::endl;
+    std::cout << "          IoTivity Resource Container Test Application             " << std::endl;
+    std::cout << "================================================================" << std::endl;
+    std::cout << "   1.  Start Resource Container                                 " << std::endl;
+    std::cout << "   2.  Stop Resource Container                                  " << std::endl;
+    std::cout << "   3.  Add Sample Bundle                                        " << std::endl;
+    std::cout << "   4.  Start Sample Bundle                                      " << std::endl;
+    std::cout << "   5.  Stop Sample Bundle                                       " << std::endl;
+    std::cout << "   6.  Remove Sample Bundle                                     " << std::endl;
+    std::cout << "   7.  Add Sample Resource                                      " << std::endl;
+    std::cout << "   8.  Remove Sample Resource                                   " << std::endl;
+    std::cout << "   9.  List Bundles                                             " << std::endl;
+    std::cout << "   10. List Resources                                           " << std::endl;
+    std::cout << "   11. Exit                                                     " << std::endl;
+    std::cout << "================================================================" << std::endl;
+    std::cout << "   Please Enter the NO: ";
+}
 
-    cout << "\t>>> bundle list size : " << bundles.size() << endl;
-    for (bundleIt = bundles.begin(); bundleIt != bundles.end(); bundleIt++)
+bool checkBundleRegistered(std::string bundleId)
+{
+    std::list< std::unique_ptr< RCSBundleInfo > > bundleList;
+
+    if (g_bContainerStarted)
     {
-        cout << "\t>>> bundle Id : " << (*bundleIt)->getID().c_str() << endl;
+        bundleList = g_pResourceContainer->listBundles();
+
+        for (auto &bundle : bundleList)
+        {
+            if (bundle->getID().compare(bundleId) == 0)
+                return true;
+        }
     }
 
-    cout << "\nPress enter to start SO bundle " << endl;
-    getchar();
-    container->startBundle("oic.bundle.hueSample");
+    std::cout << "Bundle \'" << bundleId << "\' is not registered." << std::endl;
+    return false;
+}
 
-    std::map<string, string> resourceParams;
-    cout << "Press enter to add SO bundle resource " << endl;
-    getchar();
-    resourceParams["resourceType"] = "oic.r.light";
-    resourceParams["address"] = "http://192.168.0.2/api/newdeveloper/lights/1";
-    container->addResourceConfig("oic.bundle.hueSample", "", resourceParams);
-    container->addResourceConfig("oic.bundle.hueSample", "", resourceParams);
+bool checkResourceRegistered(std::string bundleId, std::string resourceUri)
+{
+    std::list< std::string > resourceList;
 
-    std::list<string> resources = container->listBundleResources("oic.bundle.hueSample");
-    std::list<string>::iterator resourceIt;
-    cout << "\t>>> resource list size : " << resources.size() << endl;
-    for (resourceIt = resources.begin(); resourceIt != resources.end(); resourceIt++)
+    if (g_bContainerStarted && checkBundleRegistered(bundleId))
     {
-        cout << "\t>>> resource uri : " << (*resourceIt).c_str() << endl;
+        resourceList = g_pResourceContainer->listBundleResources(bundleId);
+
+        for (auto &resource : resourceList)
+        {
+            if (resource.compare(resourceUri) == 0)
+                return true;
+        }
     }
 
-    cout << "\nPress enter to remove SO bundle resource " << endl;
-    getchar();
-    container->removeResourceConfig("oic.bundle.hueSample", "/hue/light/1");
+    std::cout << "Resource \'" << resourceUri << "\' is not registered." << std::endl;
+    return false;
+}
 
-    resources = container->listBundleResources("oic.bundle.hueSample");
-    cout << "\t>>> resource list size : " << resources.size() << endl;
-    for (resourceIt = resources.begin(); resourceIt != resources.end(); resourceIt++)
+void StartContainer(std::string configPath)
+{
+    if (!g_bContainerStarted)
+    {
+        g_pResourceContainer->startContainer(configPath);
+        g_bContainerStarted = true;
+        std::cout << "Container started." << std::endl;
+    }
+    else
     {
-        cout << "\t>>> resource uri : " << (*resourceIt).c_str() << endl;
+        std::cout << "Container is already started." << std::endl;
     }
+}
 
-    cout << "\nPress enter to stop SO Bundle " << endl;
-    getchar();
-    container->stopBundle("oic.bundle.hueSample");
+void StopContainer()
+{
+    if (g_pResourceContainer && g_bContainerStarted)
+    {
+        g_pResourceContainer->stopContainer();
+        g_bContainerStarted = false;
+    }
+    else
+    {
+        std::cout << "Container is not started." << std::endl;
+    }
+}
 
-    cout << "Press enter to test remove SO Bundle " << endl;
-    getchar();
-    container->removeBundle("oic.bundle.hueSample");
+void AddSampleBundle()
+{
+    std::map< std::string, std::string > bundleParams;
 
-    bundles = container->listBundles();
-    cout << "\t>>> bundle list size : " << bundles.size() << endl;
-    for (bundleIt = bundles.begin(); bundleIt != bundles.end(); bundleIt++)
+    if (g_pResourceContainer && g_bContainerStarted)
     {
-        cout << "\t>>> bundle Id : " << (*bundleIt)->getID().c_str() << endl;
+        g_pResourceContainer->addBundle(EXAMPLE_BUNDLE_ID, EXAMPLE_BUNDLE_URI,
+                                        EXAMPLE_BUNDLE_PATH, EXAMPLE_BUNDLE_ACTIVATOR,
+                                        bundleParams);
     }
+    else
+    {
+        std::cout << "Container is not started." << std::endl;
+    }
+}
 
-#if(JAVA_SUPPORT)
-    /*java bundle add test*/
-    cout << "\n++++++++++++++++++++++++++++" << endl;
-    cout << "+++ Test for JAVA Bundle +++" << endl;
-    cout << "++++++++++++++++++++++++++++" << endl;
-    cout << "Press enter to add java bundle " << endl;
-    getchar();
-    bundleParams["libraryPath"] = ".";
-    std::string activator = "org.iotivity.bundle.hue.HueBundleActivator";
-    container->addBundle("oic.bundle.hueJavaSample2", "/hueJava",
-                 "../../../../../../service/resource-container/" \
-                 "examples/HueJavaSampleBundle/hue/target/hue-0.1-jar-with-dependencies.jar",
-                 activator,
-                 bundleParams);
+void StartSampleBundle()
+{
+    if (g_pResourceContainer && g_bContainerStarted)
+    {
+        if (checkBundleRegistered(EXAMPLE_BUNDLE_ID))
+        {
+            g_pResourceContainer->startBundle(EXAMPLE_BUNDLE_ID);
+            g_bSampleBundleStarted = true;
+        }
+    }
+    else
+    {
+        std::cout << "Container is not started." << std::endl;
+    }
+}
 
-    bundles = container->listBundles();
-    cout << "\t>>> bundle list size : " << bundles.size() << endl;
-    for (bundleIt = bundles.begin(); bundleIt != bundles.end(); bundleIt++)
+void StopSampleBundle()
+{
+    if (g_pResourceContainer && g_bContainerStarted)
     {
-        cout << "\t>>> bundle Id : " << (*bundleIt)->getID().c_str() << endl;
+        if (checkBundleRegistered(EXAMPLE_BUNDLE_ID) && g_bSampleBundleStarted)
+        {
+            g_pResourceContainer->stopBundle(EXAMPLE_BUNDLE_ID);
+            g_bSampleBundleStarted = false;
+        }
+        else
+            std::cout << "Sample Bundle is not started." << std::endl;
     }
+    else
+    {
+        std::cout << "Container is not started." << std::endl;
+    }
+}
 
-    cout << "\nPress enter to start java bundle " << endl;
-    getchar();
-    container->startBundle("oic.bundle.hueJavaSample2");
+void RemoveSampleBundle()
+{
+    if (g_pResourceContainer && g_bContainerStarted)
+    {
+        if (checkBundleRegistered(EXAMPLE_BUNDLE_ID))
+            g_pResourceContainer->removeBundle(EXAMPLE_BUNDLE_ID);
+    }
+    else
+    {
+        std::cout << "Container is not started." << std::endl;
+    }
+}
 
-    cout << "Press enter to stop java Bundle " << endl;
-    getchar();
-    container->stopBundle("oic.bundle.hueJavaSample2");
+void AddSampleBundleResource()
+{
+    std::map< std::string, std::string > resourceParams;
 
-    cout << "Press enter to test remove java Bundle " << endl;
-    getchar();
-    container->removeBundle("oic.bundle.hueJavaSample2");
+    if (g_pResourceContainer && g_bContainerStarted)
+    {
+        if (checkBundleRegistered(EXAMPLE_BUNDLE_ID) && g_bSampleBundleStarted)
+        {
+            resourceParams.insert(std::make_pair("resourceType", EXAMPLE_RESOURCE_TYPE));
+            resourceParams.insert(std::make_pair("address", EXAMPLE_ADDRESS));
+
+            g_pResourceContainer->addResourceConfig(EXAMPLE_BUNDLE_ID, EXAMPLE_RESOURCE_URI,
+                                                    resourceParams);
+        }
+        else
+            std::cout << "Sample Bundle is not started." << std::endl;
+    }
+    else
+    {
+        std::cout << "Container is not started." << std::endl;
+    }
+}
 
-    bundles = container->listBundles();
-    cout << "\t>>> bundle list size : " << bundles.size() << endl;
-    for (bundleIt = bundles.begin(); bundleIt != bundles.end(); bundleIt++)
+void RemoveSampleBundleResource()
+{
+    if (g_pResourceContainer && g_bContainerStarted)
     {
-        cout << "\t>>> bundle Id : " << (*bundleIt)->getID().c_str() << endl;
+        if (checkResourceRegistered(EXAMPLE_BUNDLE_ID, EXAMPLE_RESOURCE_URI)
+            && g_bSampleBundleStarted)
+            g_pResourceContainer->removeResourceConfig(EXAMPLE_BUNDLE_ID, EXAMPLE_RESOURCE_URI);
+        else
+            std::cout << "Sample Bundle is not started." << std::endl;
     }
-#endif
+    else
+    {
+        std::cout << "Container is not started." << std::endl;
+    }
+}
+
+void printBundleList(std::list< std::unique_ptr< RCSBundleInfo > > &list)
+{
+    std::cout << std::endl;
+    for (auto &bundleinfo : list)
+    {
+        std::cout << "-- " << bundleinfo->getID() << std::endl;
+    }
+    std::cout << std::endl;
+}
+
+void ListBundles()
+{
+    std::list< std::unique_ptr< RCSBundleInfo > > bundles;
+
+    if (g_pResourceContainer && g_bContainerStarted)
+    {
+        bundles = g_pResourceContainer->listBundles();
+        printBundleList(bundles);
+    }
+    else
+    {
+        std::cout << "Container is not started." << std::endl;
+    }
+}
+
+void printResourceList(std::list< std::string > &list)
+{
+    std::cout << std::endl;
+    for (auto &bundleResource : list)
+    {
+        std::cout << "-- " << bundleResource << std::endl;
+    }
+    std::cout << std::endl;
+}
+
+void ListResources(std::string bundleId)
+{
+    std::list< std::string > resources;
+
+    if (g_pResourceContainer && g_bContainerStarted)
+    {
+        if (checkBundleRegistered(bundleId))
+        {
+            resources = g_pResourceContainer->listBundleResources(bundleId);
+            printResourceList(resources);
+        }
+    }
+    else
+    {
+        std::cout << "Container is not started." << std::endl;
+    }
+}
+
+void ExecuteCommand(APPMenu menu)
+{
+    switch (menu)
+    {
+        case APPMenu::START_RC:
+            {
+                std::string filePath;
+                std::cout << "Type Configuration File Path (Press \'0\' to start with example): ";
+
+                if ((filePath = processUserStringInput()).compare("0") == 0)
+                {
+                    getCurrentPath(&filePath);
+                    filePath.append(EXAMPLE_CONFIG_PATH);
+                }
+
+                StartContainer(filePath);
+            }
+            break;
+        case APPMenu::STOP_RC:
+            StopContainer();
+            break;
+        case APPMenu::ADD_SAMPLE_BUNDLE:
+            AddSampleBundle();
+            break;
+        case APPMenu::START_SAMPLE_BUNDLE:
+            StartSampleBundle();
+            break;
+        case APPMenu::STOP_SAMPLE_BUNDLE:
+            StopSampleBundle();
+            break;
+        case APPMenu::REMOVE_SAMPLE_BUNDLE:
+            RemoveSampleBundle();
+            break;
+        case APPMenu::ADD_SAMPLE_RESOURCE:
+            AddSampleBundleResource();
+            break;
+        case APPMenu::REMOVE_SAMPLE_RESOURCE:
+            RemoveSampleBundleResource();
+            break;
+        case APPMenu::LIST_BUNDLES:
+            ListBundles();
+            break;
+        case APPMenu::LIST_RESOURCES:
+            {
+                std::string bundleId;
+                std::cout <<
+                          "Type Bundle Id to get Resource List (Press \'0\' to get example resource list): ";
+
+                if ((bundleId = processUserStringInput()).compare("0") == 0)
+                {
+                    bundleId = EXAMPLE_BUNDLE_ID;
+                }
+
+                ListResources(bundleId);
+            }
+            break;
+        case APPMenu::EXIT:
+            throw CloseApp();
+            break;
+    }
+}
+
+int main()
+{
+    g_pResourceContainer = RCSResourceContainer::getInstance();
+
+    while (true)
+    {
+        try
+        {
+            displayMenu();
+            ExecuteCommand((APPMenu)processUserInput(APPMenu::START_RC, APPMenu::EXIT));
+        }
+        catch (const std::exception &e)
+        {
+            std::cout << e.what() << std::endl;
+        }
+        catch (const CloseApp &)
+        {
+            break;
+        }
+    }
+
+    if (g_bContainerStarted)
+        g_pResourceContainer->stopContainer();
 
-    cout << "\nPress enter to stop container " << endl;
-    getchar();
-    container->stopContainer();
+    g_pResourceContainer = nullptr;
 
-    cout << "Container stopped. Bye" << endl;
+    return 0;
 }
index e7ce3f3..3a8bf4e 100644 (file)
@@ -53,6 +53,18 @@ class Light
         }
 };
 
+class LightSensor
+{
+public:
+        int m_intensity;
+
+        std::string m_name;
+
+        LightSensor() : m_intensity(0), m_name("")
+        {
+        }
+};
+
 Light mylight;
 
 int observe_count()
@@ -103,6 +115,45 @@ void onObserve(const HeaderOptions headerOptions, const OCRepresentation &rep,
 
 }
 
+
+void onLightIntensityObserve(const HeaderOptions headerOptions, const OCRepresentation &rep,
+               const int &eCode, const int &sequenceNumber)
+{
+    (void)headerOptions;
+    try
+    {
+        if (eCode == OC_STACK_OK)
+        {
+            std::cout << "OBSERVE RESULT:" << std::endl;
+            std::cout << "\tSequenceNumber: " << sequenceNumber << std::endl;
+
+
+            std::cout << "\tintensity: " << rep.getValue<int>("intensity") << std::endl;
+
+
+            if (observe_count() > 10)
+            {
+                std::cout << "Cancelling Observe..." << std::endl;
+                OCStackResult result = curResource->cancelObserve();
+
+                std::cout << "Cancel result: " << result << std::endl;
+                sleep(10);
+                std::cout << "DONE" << std::endl;
+                std::exit(0);
+            }
+        }
+        else
+        {
+            std::cout << "onObserve Response error: " << eCode << std::endl;
+        }
+    }
+    catch (std::exception &e)
+    {
+        std::cout << "Exception: " << e.what() << " in onObserve" << std::endl;
+    }
+
+}
+
 void onPost2(const HeaderOptions &headerOptions, const OCRepresentation &rep, const int eCode)
 {
     (void)headerOptions;
@@ -194,7 +245,7 @@ void onPost(const HeaderOptions &headerOptions, const OCRepresentation &rep, con
     }
 }
 
-// Local function to put a different state for this resource
+// Local function to put a different state for this re<< std::endlsource
 void postLightRepresentation(std::shared_ptr<OCResource> resource)
 {
     if (resource)
@@ -289,7 +340,7 @@ void putLightRepresentation(std::shared_ptr<OCResource> resource)
 
         // Invoke resource's put API with rep, query map and the callback parameter
 
-        resource->put(rep, QueryParamsMap(), &onPut);
+        resource->post(rep, QueryParamsMap(), &onPut);
     }
 }
 
@@ -305,16 +356,13 @@ void onGet(const HeaderOptions &headerOptions, const OCRepresentation &rep, cons
             std::cout << "Resource URI: " << rep.getUri() << std::endl;
 
             std::cout << "Payload: " << rep.getPayload() << std::endl;
+            std::cout << "On-off: " << rep.getValueToString("on-off") << std::endl;
 
             rep.getValue("on-off", mylight.m_on_off);
-            rep.getValue("dim", mylight.m_dim);
-            rep.getValue("color", mylight.m_color);
 
             std::cout << "\ton-off: " << mylight.m_on_off << std::endl;
-            std::cout << "\tcolor: " << mylight.m_color << std::endl;
-            std::cout << "\tdim: " << mylight.m_dim << std::endl;
 
-            putLightRepresentation(curResource);
+            postLightRepresentation(curResource);
         }
         else
         {
@@ -353,6 +401,45 @@ void onGetForDISensor(const HeaderOptions &headerOptions, const OCRepresentation
     }
 }
 
+
+void onGetForLightIntensitySensor(const HeaderOptions &headerOptions, const OCRepresentation &rep,
+                      const int eCode)
+{
+    (void)headerOptions;
+    try
+    {
+        if (eCode == OC_STACK_OK)
+        {
+            std::cout << "GET request was successful" << std::endl;
+            //std::cout << "Resource URI: " << DISensorResource->uri() << std::endl;
+
+            std::cout << "Payload: " << rep.getPayload() << std::endl;
+
+            std::cout << "\tlightIntensity: " << rep.getValue<int>("intensity") << std::endl;
+
+            // iterating over all elements
+            OCRepresentation::const_iterator itr = rep.begin();
+            OCRepresentation::const_iterator endItr = rep.end();
+
+            for(;itr!=endItr;++itr)
+            {
+                std::cout << itr->attrname() << " ";
+                std::cout << itr->getValue<int>() << std::endl;
+            }
+
+            curResource->observe(OBSERVE_TYPE_TO_USE, QueryParamsMap(), &onLightIntensityObserve);
+        }
+        else
+        {
+            std::cout << "onGET Response error: " << eCode << std::endl;
+        }
+    }
+    catch (std::exception &e)
+    {
+        std::cout << "Exception: " << e.what() << " in onPut" << std::endl;
+    }
+}
+
 // Local function to get representation of light resource
 void getLightRepresentation(std::shared_ptr<OCResource> resource)
 {
@@ -367,47 +454,108 @@ void getLightRepresentation(std::shared_ptr<OCResource> resource)
     }
 }
 
-// Callback to found resources
-void foundResource(std::shared_ptr<OCResource> resource)
+void onGetDiscomfortIndex(const HeaderOptions &headerOptions, const OCRepresentation &rep,
+                      const int eCode)
 {
-    std::cout << "In foundResource\n";
-    std::string resourceURI = resource->uri();
-    std::string hostAddress;
+    (void)headerOptions;
+    std::cout << "onGetDiscomfortIndex" << std::endl;
     try
     {
+        if (eCode == OC_STACK_OK)
         {
-            std::lock_guard<std::mutex> lock(curResourceLock);
-            if (discoveredResources.find(resource->uniqueIdentifier()) == discoveredResources.end())
-            {
-                std::cout << "Found resource " << resource->uniqueIdentifier() <<
-                          " for the first time on server with ID: " << resource->sid() << std::endl;
-                discoveredResources[resource->uniqueIdentifier()] = resource;
-
-                if (resourceURI.find("/discomfortIndex") != std::string::npos)
-                {
-                    std::cout << "discomfortIndex found !!! " << std::endl;
+            std::cout << "GET request was successful" << std::endl;
 
-                    DISensorResource = resource;
+            std::cout << "Payload: " << rep.getPayload() << std::endl;
 
-                    OCRepresentation rep;
+            std::cout << "\tdiscomfortIndex: " << rep.getValue<double>("discomfortIndex") << std::endl;
+        }
+        else
+        {
+            std::cout << "onGET Response error: " << eCode << std::endl;
+        }
+    }
+    catch (std::exception &e)
+    {
+        std::cout << "Exception: " << e.what() << " in onPut" << std::endl;
+    }
+}
 
-                    rep.setValue("humidity", std::string("30"));
-                    rep.setValue("temperature", std::string("27"));
+void onObserveDiscomfort(const HeaderOptions headerOptions, const OCRepresentation &rep,
+               const int &eCode, const int &sequenceNumber)
+{
+    (void)headerOptions;
+    try
+    {
+        if (eCode == OC_STACK_OK)
+        {
+            std::cout << "OBSERVE RESULT:" << std::endl;
+            std::cout << "\tSequenceNumber: " << sequenceNumber << std::endl;
+            std::cout << "\tdiscomfortIndex: " << rep.getValue<double>("discomfortIndex") << std::endl;
 
-                    resource->put(rep, QueryParamsMap(), &onPutForDISensor);
-                }
-            }
-            else
+            if (observe_count() > 10)
             {
-                std::cout << "Found resource " << resource->uniqueIdentifier() << " again!" << std::endl;
-            }
+                std::cout << "Cancelling Observe..." << std::endl;
+                OCStackResult result = curResource->cancelObserve();
 
-            if (curResource)
-            {
-                std::cout << "Found another resource, ignoring" << std::endl;
-                return;
+                std::cout << "Cancel result: " << result << std::endl;
+                sleep(10);
+                std::cout << "DONE" << std::endl;
+                std::exit(0);
             }
         }
+        else
+        {
+            std::cout << "onObserve Response error: " << eCode << std::endl;
+        }
+    }
+    catch (std::exception &e)
+    {
+        std::cout << "Exception: " << e.what() << " in onObserve" << std::endl;
+    }
+
+}
+
+// Local function to get representation of light resource
+void getDiscomfortRepresentation(std::shared_ptr<OCResource> resource)
+{
+    if (resource)
+    {
+        std::cout << "Getting Discomfort Representation..." << std::endl;
+        // Invoke resource's get API with the callback parameter
+
+        QueryParamsMap test;
+        std::cout << "Sending request to: " << resource->uri() << std::endl;
+        resource->get(test, &onGetDiscomfortIndex);
+        //resource->observe(ObserveType::Observe, QueryParamsMap(), &onObserve);
+    }
+}
+
+
+
+
+// Local function to get representation of light resource
+void getLightIntensityRepresentation(std::shared_ptr<OCResource> resource)
+{
+    if (resource)
+    {
+        std::cout << "Getting Light Representation..." << std::endl;
+        // Invoke resource's get API with the callback parameter
+
+        QueryParamsMap test;
+        std::cout << "Sending request to: " << resource->uri() << std::endl;
+        resource->get(test, &onGetForLightIntensitySensor);
+    }
+}
+
+// Callback to found resources
+void foundResource(std::shared_ptr<OCResource> resource)
+{
+    std::cout << "In foundResource\n";
+    std::string resourceURI = resource->uri();
+    std::string hostAddress;
+    try
+    {
+
 
         // Do some operations with resource object.
         if (resource)
@@ -426,12 +574,18 @@ void foundResource(std::shared_ptr<OCResource> resource)
             for (auto &resourceTypes : resource->getResourceTypes())
             {
                 std::cout << "\t\t" << resourceTypes << std::endl;
-
-                if (resourceTypes == "oic.r.light")
+                /*if (resourceTypes == "oic.r.light")
                 {
                     curResource = resource;
                     // Call a local function which will internally invoke get API on the resource pointer
                     getLightRepresentation(resource);
+                }*/
+                if (resourceTypes == "oic.r.discomfortindex")
+                {
+                    curResource = resource;
+                    std::cout << "\t\tGet discomfort representation " << std::endl;
+                    // Call a local function which will internally invoke get API on the resource pointer
+                    getDiscomfortRepresentation(resource);
                 }
             }
 
index 583094e..17edfcb 100644 (file)
@@ -35,9 +35,9 @@ class DiscomfortIndexSensorResource : public SoftSensorResource
         DiscomfortIndexSensorResource(const DiscomfortIndexSensorResource &other)=delete;
         DiscomfortIndexSensorResource& operator=( const DiscomfortIndexSensorResource& rhs )=delete;
 
-        virtual void handleSetAttributesRequest(RCSResourceAttributes &attrs);
+        virtual void handleSetAttributesRequest(const RCSResourceAttributes &attrs);
 
-        virtual RCSResourceAttributes &handleGetAttributesRequest();
+        virtual RCSResourceAttributes handleGetAttributesRequest();
 
         virtual void executeLogic();
 
index d51febb..4817ae9 100644 (file)
@@ -35,12 +35,12 @@ DiscomfortIndexSensorResource::~DiscomfortIndexSensorResource()
 }
 
 void DiscomfortIndexSensorResource::handleSetAttributesRequest(
-    RCSResourceAttributes &value)
+    const RCSResourceAttributes &value)
 {
     BundleResource::setAttributes(value);
 }
 
-RCSResourceAttributes &DiscomfortIndexSensorResource::handleGetAttributesRequest()
+RCSResourceAttributes DiscomfortIndexSensorResource::handleGetAttributesRequest()
 {
     return BundleResource::getAttributes();
 }
@@ -51,7 +51,7 @@ void DiscomfortIndexSensorResource::executeLogic()
 
     m_pDiscomfortIndexSensor->executeDISensorLogic(&m_mapInputData, &strDiscomfortIndex);
 
-    setAttribute("discomfortIndex", RCSResourceAttributes::Value(strDiscomfortIndex.c_str()));
+    setAttribute("discomfortIndex", RCSResourceAttributes::Value(strDiscomfortIndex.c_str()), true);
 
     for (auto it : m_mapInputData)
     {
index 40c4aa0..1aa0835 100644 (file)
@@ -40,9 +40,9 @@ namespace OIC
 
                 virtual void initAttributes();
 
-                virtual void handleSetAttributesRequest(RCSResourceAttributes &attrs);
+                virtual void handleSetAttributesRequest(const RCSResourceAttributes &attrs);
 
-                virtual RCSResourceAttributes &handleGetAttributesRequest();
+                virtual RCSResourceAttributes handleGetAttributesRequest();
 
 
             private:
index 6490685..ba77414 100644 (file)
@@ -44,46 +44,46 @@ HueLight::~HueLight()
 
 void HueLight::initAttributes()
 {
-    BundleResource::setAttribute("on-off", false);
-    BundleResource::setAttribute("dim", 0);
-    BundleResource::setAttribute("color", 0);
+    BundleResource::setAttribute("on-off", false, false);
+    BundleResource::setAttribute("dim", 0, false);
+    BundleResource::setAttribute("color", 0, false);
 }
 
-RCSResourceAttributes &HueLight::handleGetAttributesRequest()
+RCSResourceAttributes HueLight::handleGetAttributesRequest()
 {
     cout << "HueLight::handleGetAttributesRequest" << endl;
     // TODO read from HueLight and update attribute data
     return BundleResource::getAttributes();
 }
 
-void HueLight::handleSetAttributesRequest(RCSResourceAttributes &value)
+void HueLight::handleSetAttributesRequest(const RCSResourceAttributes &value)
 {
     cout << "HueLight::handleSetAttributesRequest" << std::endl;
 
     // TODO construct single write
 
-    for (RCSResourceAttributes::iterator it = value.begin(); it != value.end(); it++)
+    for (RCSResourceAttributes::const_iterator it = value.begin(); it != value.end(); it++)
     {
         std::string attributeName = it->key();
         RCSResourceAttributes::Value attrValue = it->value();
 
         if (attributeName == "on-off")
         {
-            m_connector->transmit(this->m_address + "/state", "{\"on\":" + attrValue.toString() + "}");
+            //m_connector->transmit(this->m_address + "/state", "{\"on\":" + attrValue.toString() + "}");
         }
 
         if (attributeName == "dim")
         {
             // needs conversion * 2.5
-            m_connector->transmit(this->m_address + "/state", "{\"bri\":" + attrValue.toString() + "}");
+            //m_connector->transmit(this->m_address + "/state", "{\"bri\":" + attrValue.toString() + "}");
         }
 
         if (attributeName == "color")
         {
             // needs conversion *650
-            m_connector->transmit(this->m_address + "/state", "{\"hue\":" + attrValue.toString() + "}");
+            //m_connector->transmit(this->m_address + "/state", "{\"hue\":" + attrValue.toString() + "}");
         }
     }
 
     BundleResource::setAttributes(value);
-}
\ No newline at end of file
+}
index 36fad24..02b045a 100644 (file)
@@ -74,14 +74,14 @@ void HueSampleBundleActivator::deactivateBundle()
 
 void HueSampleBundleActivator::createResource(resourceInfo resourceInfo)
 {
-
     if (resourceInfo.resourceType == "oic.r.light")
     {
         static int lightCount = 1;
         BundleResource::Ptr hueLight = std::make_shared< HueLight >(m_connector, resourceInfo.address);
-        resourceInfo.uri = "/hue/light/" + std::to_string(lightCount++);
+
         hueLight->m_bundleId = m_bundleId;
-        hueLight->m_uri = resourceInfo.uri;
+        hueLight->m_uri = resourceInfo.uri.empty() ?
+                          "/hue/light/" + std::to_string(lightCount++) : resourceInfo.uri;
         hueLight->m_resourceType = resourceInfo.resourceType;
         hueLight->m_name = resourceInfo.name;
 
index c3a56a2..fe38130 100644 (file)
@@ -72,6 +72,8 @@
         </resources>
     </bundle>
 
+    <!-- Will be loaded dynamically with sample application -->
+    <!--
     <bundle>
         <id>oic.bundle.hueSample</id>
         <path>libHueBundle.so</path>
@@ -85,7 +87,9 @@
             </resourceInfo>       
         </resources>
     </bundle>
-    
+    -->
+
+    <!-- Example Configuration For Java Bundle -->
     <!--
     <bundle>
         <id>oic.bundle.hueJavaSample</id>       
         </resources>
     </bundle>
     -->
-    
+
 </container>
\ No newline at end of file
diff --git a/service/resource-container/examples/android/AndroidBundle/AndroidBundle.iml b/service/resource-container/examples/android/AndroidBundle/AndroidBundle.iml
new file mode 100755 (executable)
index 0000000..fb858b9
--- /dev/null
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module external.linked.project.id="AndroidBundle" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
+  <component name="FacetManager">
+    <facet type="java-gradle" name="Java-Gradle">
+      <configuration>
+        <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />
+        <option name="BUILDABLE" value="false" />
+      </configuration>
+    </facet>
+  </component>
+  <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="true">
+    <exclude-output />
+    <content url="file://$MODULE_DIR$">
+      <excludeFolder url="file://$MODULE_DIR$/.gradle" />
+    </content>
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+  </component>
+</module>
\ No newline at end of file
diff --git a/service/resource-container/examples/android/AndroidBundle/app/app.iml b/service/resource-container/examples/android/AndroidBundle/app/app.iml
new file mode 100755 (executable)
index 0000000..98e7737
--- /dev/null
@@ -0,0 +1,94 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module external.linked.project.id=":app" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="AndroidBundle" 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=":app" />
+      </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/exploded-aar/iotivity-armeabi-v7a-resource-container-release/jars" />
+      <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/tmp" />
+    </content>
+    <orderEntry type="jdk" jdkName="Android API 23 Platform" jdkType="Android SDK" />
+    <orderEntry type="sourceFolder" forTests="false" />
+    <orderEntry type="library" exported="" name="iotivity-armeabi-v7a-resource-container-release-" level="project" />
+  </component>
+</module>
\ No newline at end of file
diff --git a/service/resource-container/examples/android/AndroidBundle/app/build.gradle b/service/resource-container/examples/android/AndroidBundle/app/build.gradle
new file mode 100755 (executable)
index 0000000..9e88223
--- /dev/null
@@ -0,0 +1,24 @@
+apply plugin: 'com.android.library'
+
+android {
+    compileSdkVersion 23
+    buildToolsVersion "22.0.1"
+
+    defaultConfig {
+        minSdkVersion 21
+        targetSdkVersion 23
+        versionCode 1
+        versionName "1.0"
+    }
+    buildTypes {
+        release {
+            minifyEnabled false
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+        }
+    }
+}
+
+dependencies {
+    compile fileTree(dir: 'libs', include: ['*.jar'])
+    compile(name:'iotivity-armeabi-v7a-resource-container-release', ext:'aar')
+}
diff --git a/service/resource-container/examples/android/AndroidBundle/app/src/androidTest/java/org/iotivity/service/sample/androidbundle/ApplicationTest.java b/service/resource-container/examples/android/AndroidBundle/app/src/androidTest/java/org/iotivity/service/sample/androidbundle/ApplicationTest.java
new file mode 100755 (executable)
index 0000000..6d4ab8e
--- /dev/null
@@ -0,0 +1,13 @@
+package org.iotivity.service.sample.androidbundle;
+
+import android.app.Application;
+import android.test.ApplicationTestCase;
+
+/**
+ * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
+ */
+public class ApplicationTest extends ApplicationTestCase<Application> {
+    public ApplicationTest() {
+        super(Application.class);
+    }
+}
\ No newline at end of file
diff --git a/service/resource-container/examples/android/AndroidBundle/app/src/main/AndroidManifest.xml b/service/resource-container/examples/android/AndroidBundle/app/src/main/AndroidManifest.xml
new file mode 100755 (executable)
index 0000000..0d6218a
--- /dev/null
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="org.iotivity.service.sample.androidbundle" >
+
+    <application
+        android:allowBackup="true"
+        android:icon="@mipmap/ic_launcher"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme" >
+        <activity
+            android:name=".DummyActivity"
+            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/service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/DummyActivity.java b/service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/DummyActivity.java
new file mode 100755 (executable)
index 0000000..283db78
--- /dev/null
@@ -0,0 +1,57 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.service.sample.androidbundle;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.view.Menu;
+import android.view.MenuItem;
+
+public class DummyActivity extends Activity {
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.activity_main);
+    }
+
+    @Override
+    public boolean onCreateOptionsMenu(Menu menu) {
+        // Inflate the menu; this adds items to the action bar if it is present.
+        getMenuInflater().inflate(R.menu.menu_main, menu);
+        return true;
+    }
+
+    @Override
+    public boolean onOptionsItemSelected(MenuItem item) {
+        // Handle action bar item clicks here. The action bar will
+        // automatically handle clicks on the Home/Up button, so long
+        // as you specify a parent activity in AndroidManifest.xml.
+        int id = item.getItemId();
+
+        //noinspection SimplifiableIfStatement
+        if (id == R.id.action_settings) {
+            return true;
+        }
+
+        return super.onOptionsItemSelected(item);
+    }
+}
diff --git a/service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/SampleActivator.java b/service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/SampleActivator.java
new file mode 100755 (executable)
index 0000000..7af38c5
--- /dev/null
@@ -0,0 +1,151 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.service.sample.androidbundle;
+
+import android.content.Context;
+import android.util.Log;
+
+import org.iotivity.service.resourcecontainer.BundleActivator;
+import org.iotivity.service.resourcecontainer.BundleResource;
+import org.iotivity.service.resourcecontainer.RcsResourceContainerBundleAPI;
+import org.iotivity.service.resourcecontainer.ResourceConfig;
+import org.iotivity.service.sample.androidbundle.resources.DiscomfortIndexResource;
+import org.iotivity.service.sample.androidbundle.resources.GyroscopeResource;
+import org.iotivity.service.sample.androidbundle.resources.HumidityResource;
+import org.iotivity.service.sample.androidbundle.resources.LightIntensityResource;
+import org.iotivity.service.sample.androidbundle.resources.TemperatureResource;
+
+import java.util.List;
+import java.util.Vector;
+
+public class SampleActivator extends BundleActivator {
+    private List<BundleResource> resources = new Vector<BundleResource>();
+
+    public SampleActivator(RcsResourceContainerBundleAPI bundleAPI, Context appContext){
+        super(bundleAPI, appContext);
+        Log.d(SampleActivator.class.getName(), "Created activator instance " + bundleAPI
+                + "," + appContext);
+    }
+
+    @Override
+    public void activateBundle() {
+        Log.d(SampleActivator.class.getName(), "Activate bundle called");
+
+        Log.d(SampleActivator.class.getName(), "requesting configured bundle resources");
+
+        Log.d(SampleActivator.class.getName(), "Bundle API: " + this.bundleAPI);
+        if(this.bundleAPI != null)
+        {
+            List<ResourceConfig> configuredBundleResources = this.bundleAPI.
+                    getConfiguredBundleResources("oic.android.sample");
+
+            if(configuredBundleResources !=null) {
+                Log.d(SampleActivator.class.getName(), "configured bundle resources: " +
+                        configuredBundleResources.size());
+
+                for (ResourceConfig config : configuredBundleResources) {
+                    BundleResource resource = null;
+                    Log.d(SampleActivator.class.getName(), "Creating " +
+                        config.getResourceType());
+
+                    if ("oic.r.lightsensor".equals(config.getResourceType())) {
+                        resource =
+                                new LightIntensityResource(this.appContext);
+                    } else if ("oic.r.temperature".equals(config.getResourceType())) {
+                        resource =
+                                new TemperatureResource(this.appContext);
+
+                    } else if ("oic.r.gyroscope".equals(config.getResourceType())) {
+                        resource =
+                                new GyroscopeResource(this.appContext);
+                    } else if ("oic.r.discomfortindex".equals(config.getResourceType())) {
+                        resource =
+                                new DiscomfortIndexResource(this.appContext);
+                    } else if ("oic.r.humidity".equals(config.getResourceType())) {
+                        resource =
+                                new HumidityResource(this.appContext);
+                    }
+
+                    if (resource != null) {
+                        resource.setURI(config.getURI());
+                        resource.setName(config.getName());
+                        bundleAPI.registerResource("oic.android.sample", resource);
+                        resources.add(resource);
+                        Log.d(SampleActivator.class.getName(), "Registering resource " +
+                                config.getURI());
+                    }
+                }
+                Log.d(SampleActivator.class.getName(), "Activate bundle finished");
+            }
+            else{
+                Log.d(SampleActivator.class.getName(), "configured bundle resources is null");
+            }
+        }
+        else{
+            Log.d(SampleActivator.class.getName(), "Bundle API is null");
+        }
+
+
+    }
+
+    @Override
+    public void deactivateBundle() {
+        Log.d(SampleActivator.class.getName(), "De-activate bundle called.");
+        for(BundleResource resource : resources){
+            bundleAPI.unregisterResource(resource);
+        }
+    }
+
+    @Override
+    public void createResource(ResourceConfig config) {
+        BundleResource resource = null;
+
+        if("oic.r.lightsensor".equals(config.getResourceType())){
+            resource =
+                    new LightIntensityResource(this.appContext);
+        } else if("oic.r.temperature".equals(config.getResourceType())){
+            resource =
+                    new TemperatureResource(this.appContext);
+        } else if("oic.r.discomfortindex".equals(config.getResourceType())){
+            resource =
+                    new DiscomfortIndexResource(this.appContext);
+        } else if("oic.r.gyroscope".equals(config.getResourceType())){
+            resource =
+                    new GyroscopeResource(this.appContext);
+        } else if ("oic.r.humidity".equals(config.getResourceType())) {
+            resource =
+                    new HumidityResource(this.appContext);
+        }
+
+        if(resource != null) {
+            resource.setURI(config.getURI());
+            resource.setName(config.getName());
+            bundleAPI.registerResource("oic.android.sample", resource);
+            resources.add(resource);
+        }
+    }
+
+    @Override
+    public void destroyResource(BundleResource androidBundleResource) {
+        Log.d(SampleActivator.class.getName(), "Destroy resource called.");
+        bundleAPI.unregisterResource(androidBundleResource);
+    }
+}
diff --git a/service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/resources/DiscomfortIndexResource.java b/service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/resources/DiscomfortIndexResource.java
new file mode 100755 (executable)
index 0000000..d974a32
--- /dev/null
@@ -0,0 +1,110 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.service.sample.androidbundle.resources;
+
+import android.app.Notification;
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import org.iotivity.service.resourcecontainer.BundleSoftSensorResource;
+import org.iotivity.service.resourcecontainer.RcsResourceAttributes;
+import org.iotivity.service.resourcecontainer.RcsValue;
+
+import java.util.HashMap;
+import java.util.Vector;
+
+import org.iotivity.service.sample.androidbundle.DummyActivity;
+import org.iotivity.service.sample.androidbundle.R;
+
+public class DiscomfortIndexResource extends BundleSoftSensorResource {
+    private static final String LOG_TAG = DiscomfortIndexResource.class.getSimpleName();
+
+    public DiscomfortIndexResource(Context context){
+        super(context);
+        this.setResourceType("oic.r.discomfortindex");
+        this.setName("discomfortIndex");
+        m_mapInputData = new HashMap<String, RcsValue>();
+    }
+
+    @Override
+    protected void initAttributes() {
+        this.m_attributes.put("discomfortIndex", 0);
+        this.m_attributes.put("humidity", 0);
+        this.m_attributes.put("temperature", 0);
+    }
+
+    @Override
+    protected void onUpdatedInputResource(String attributeName, Vector<RcsValue> values) {
+        m_mapInputData.put(attributeName, values.get(0));
+        executeLogic();
+    }
+
+    @Override
+    protected void executeLogic() {
+        if(m_mapInputData.get("humidity") != null && m_mapInputData.get("temperature") != null){
+            double dDI = 0.0;
+            Vector v = new Vector();
+
+            int t = m_mapInputData.get("temperature").asInt();
+            int h = m_mapInputData.get("humidity").asInt();
+            double F = (9.0 * (double) t) / 5.0 + 32.0;
+
+            // calculation of discomfortIndex
+            dDI = F - (F - 58.0) * (double)((100 - h) * 55) / 10000.0;
+
+            this.setAttribute("temperature", new RcsValue(t));
+            this.setAttribute("humidity", new RcsValue(h));
+            this.setAttribute("discomfortIndex", new RcsValue(dDI));
+
+            setAttribute("discomfortIndex",new RcsValue(dDI), true ); // notify observers
+            Log.i(LOG_TAG, "Discomfort Index" + dDI);
+            showNotification(" " + dDI, this.m_context);
+        }
+        else{
+            Log.i(LOG_TAG, "Discomfort Index input data - humidity:  " +
+                    m_mapInputData.get("humidity") + " temp: " +
+                    m_mapInputData.get("temperature") );
+        }
+    }
+
+    @Override
+    public void handleSetAttributesRequest(RcsResourceAttributes rcsResourceAttributes) {
+        this.setAttributes(rcsResourceAttributes);
+        executeLogic();
+    }
+
+    @Override
+    public RcsResourceAttributes handleGetAttributesRequest() {
+        return this.getAttributes();
+    }
+
+    private void showNotification(String eventtext, Context ctx) {
+        // Set the icon, scrolling text and timestamp
+        Log.i(LOG_TAG, "*************************************** ");
+        Log.i(LOG_TAG, "*************************************** ");
+        Log.i(LOG_TAG, "*************************************** ");
+        Log.i(LOG_TAG, eventtext);
+        Log.i(LOG_TAG, "*************************************** ");
+        Log.i(LOG_TAG, "*************************************** ");
+        Log.i(LOG_TAG, "*************************************** ");
+    }
+}
diff --git a/service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/resources/GyroscopeResource.java b/service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/resources/GyroscopeResource.java
new file mode 100755 (executable)
index 0000000..1f167a5
--- /dev/null
@@ -0,0 +1,89 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.service.sample.androidbundle.resources;
+
+import android.content.Context;
+import android.hardware.Sensor;
+import android.hardware.SensorEvent;
+import android.hardware.SensorEventListener;
+import android.hardware.SensorManager;
+import android.util.Log;
+
+import org.iotivity.service.resourcecontainer.BundleResource;
+import org.iotivity.service.resourcecontainer.BundleResource;
+import org.iotivity.service.resourcecontainer.RcsResourceAttributes;
+import org.iotivity.service.resourcecontainer.RcsValue;
+
+public class GyroscopeResource extends BundleResource implements SensorEventListener {
+    private static final String LOG_TAG = GyroscopeResource.class.getSimpleName();
+    private final SensorManager mSensorManager;
+    private final Sensor humiditySensor;
+
+    public GyroscopeResource(Context context){
+        super(context);
+        this.setResourceType("oic.r.gyroscope");
+        this.setName("gyroscopeSensor");
+        mSensorManager = (SensorManager) context.getApplicationContext().
+                getSystemService(Context.SENSOR_SERVICE);
+        humiditySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
+        mSensorManager.registerListener(this, humiditySensor, SensorManager.SENSOR_DELAY_NORMAL);
+        Log.d(LOG_TAG, "Created new gyroscope instance");
+    }
+
+    @Override
+    protected void initAttributes() {
+        this.m_attributes.put("x", 0d);
+        this.m_attributes.put("y", 0d);
+        this.m_attributes.put("z", 0d);
+    }
+
+    @Override
+    public void handleSetAttributesRequest(RcsResourceAttributes attrs) {
+        Log.i(LOG_TAG, "Set Attributes called with ");
+        for(String key: attrs.keySet()){
+            Log.i(LOG_TAG, " " + key + ": " + attrs.get(key));
+        }
+    }
+
+    @Override
+    public RcsResourceAttributes handleGetAttributesRequest() {
+        Log.i(LOG_TAG, "Get Attributes called");
+        Log.i(LOG_TAG, "Returning: ");
+        for(String key:m_attributes.keySet()){
+            Log.i(LOG_TAG, " " + key + ": " + m_attributes.get(key));
+        }
+        return this.m_attributes;
+    }
+
+    @Override
+    public void onSensorChanged(SensorEvent sensorEvent) {
+        Log.i(LOG_TAG, "Sensor event " + sensorEvent.values[0] + ", " + sensorEvent.values[1]
+            + ", " + sensorEvent.values[2]);
+        setAttribute("x", new RcsValue( (int) (sensorEvent.values[0])), true);
+        setAttribute("y", new RcsValue( (int) (sensorEvent.values[1]) ) , true);
+        setAttribute("z", new RcsValue( (int) (sensorEvent.values[2]) ) , true);
+    }
+
+    @Override
+    public void onAccuracyChanged(Sensor sensor, int i) {
+
+    }
+}
diff --git a/service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/resources/HumidityResource.java b/service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/resources/HumidityResource.java
new file mode 100755 (executable)
index 0000000..c40c117
--- /dev/null
@@ -0,0 +1,83 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.service.sample.androidbundle.resources;
+
+import android.content.Context;
+import android.hardware.Sensor;
+import android.hardware.SensorEvent;
+import android.hardware.SensorEventListener;
+import android.hardware.SensorManager;
+import android.util.Log;
+
+import org.iotivity.service.resourcecontainer.BundleResource;
+import org.iotivity.service.resourcecontainer.RcsResourceAttributes;
+import org.iotivity.service.resourcecontainer.RcsValue;
+
+public class HumidityResource extends BundleResource implements SensorEventListener {
+    private static final String LOG_TAG = HumidityResource.class.getSimpleName();
+    private final SensorManager mSensorManager;
+    private final Sensor humiditySensor;
+
+    public HumidityResource(Context context){
+        super(context);
+        this.setResourceType("oic.r.humidity");
+        this.setName("humiditySensor");
+        mSensorManager = (SensorManager) context.getApplicationContext().
+                getSystemService(Context.SENSOR_SERVICE);
+        humiditySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
+        mSensorManager.registerListener(this, humiditySensor, SensorManager.SENSOR_DELAY_NORMAL);
+    }
+
+    @Override
+    protected void initAttributes() {
+        this.m_attributes.put("humidity", 0d);
+    }
+
+    @Override
+    public void handleSetAttributesRequest(RcsResourceAttributes attrs) {
+        Log.i(LOG_TAG, "Set Attributes called with ");
+        for(String key: attrs.keySet()){
+            Log.i(LOG_TAG, " " + key + ": " + attrs.get(key));
+        }
+    }
+
+    @Override
+    public RcsResourceAttributes handleGetAttributesRequest() {
+        Log.i(LOG_TAG, "Get Attributes called");
+        Log.i(LOG_TAG, "Returning: ");
+        for(String key: m_attributes.keySet()){
+            Log.i(LOG_TAG, " " + key + ": " + m_attributes.get(key));
+        }
+        return this.m_attributes;
+    }
+
+    @Override
+    public void onSensorChanged(SensorEvent sensorEvent) {
+        Log.i(LOG_TAG, "Sensor event " + sensorEvent.values[0]);
+
+        setAttribute("humidity", new RcsValue( (int) (sensorEvent.values[0]) ) , true);
+    }
+
+    @Override
+    public void onAccuracyChanged(Sensor sensor, int i) {
+
+    }
+}
diff --git a/service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/resources/LightIntensityResource.java b/service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/resources/LightIntensityResource.java
new file mode 100755 (executable)
index 0000000..0c1017e
--- /dev/null
@@ -0,0 +1,83 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.service.sample.androidbundle.resources;
+
+import android.content.Context;
+import android.hardware.Sensor;
+import android.hardware.SensorEvent;
+import android.hardware.SensorEventListener;
+import android.hardware.SensorManager;
+import android.util.Log;
+
+import org.iotivity.service.resourcecontainer.BundleResource;
+import org.iotivity.service.resourcecontainer.RcsResourceAttributes;
+import org.iotivity.service.resourcecontainer.RcsValue;
+
+public class LightIntensityResource extends BundleResource implements SensorEventListener {
+    private static final String LOG_TAG = LightIntensityResource.class.getSimpleName();
+    private final SensorManager mSensorManager;
+    private final Sensor lightSensor;
+
+    public LightIntensityResource(Context context){
+        super(context);
+        this.setResourceType("oic.r.lightsensor");
+        this.setName("lightSensor");
+        mSensorManager = (SensorManager) context.getApplicationContext().
+                getSystemService(Context.SENSOR_SERVICE);
+        lightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
+        mSensorManager.registerListener(this, lightSensor, SensorManager.SENSOR_DELAY_NORMAL);
+    }
+
+    @Override
+    protected void initAttributes() {
+        this.m_attributes.put("intensity", 0);
+    }
+
+    @Override
+    public void handleSetAttributesRequest(RcsResourceAttributes attrs) {
+        Log.i(LOG_TAG, "Set Attributes called with ");
+        for(String key: attrs.keySet()){
+            Log.i(LOG_TAG, " " + key + ": " + attrs.get(key));
+        }
+    }
+
+    @Override
+    public RcsResourceAttributes handleGetAttributesRequest() {
+        Log.i(LOG_TAG, "Get Attributes called");
+        Log.i(LOG_TAG, "Returning: ");
+        for(String key: m_attributes.keySet()){
+            Log.i(LOG_TAG, " " + key + ": " + m_attributes.get(key));
+        }
+        return this.m_attributes;
+    }
+
+    @Override
+    public void onSensorChanged(SensorEvent sensorEvent) {
+        Log.i(LOG_TAG, "Sensor event " + sensorEvent.values[0]);
+
+        setAttribute("intensity", new RcsValue( (int) (sensorEvent.values[0]) ) , true);
+    }
+
+    @Override
+    public void onAccuracyChanged(Sensor sensor, int i) {
+
+    }
+}
diff --git a/service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/resources/TemperatureResource.java b/service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/resources/TemperatureResource.java
new file mode 100755 (executable)
index 0000000..be88d7a
--- /dev/null
@@ -0,0 +1,83 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.service.sample.androidbundle.resources;
+
+import android.content.Context;
+import android.hardware.Sensor;
+import android.hardware.SensorEvent;
+import android.hardware.SensorEventListener;
+import android.hardware.SensorManager;
+import android.util.Log;
+
+import org.iotivity.service.resourcecontainer.BundleResource;
+import org.iotivity.service.resourcecontainer.RcsResourceAttributes;
+import org.iotivity.service.resourcecontainer.RcsValue;
+
+public class TemperatureResource  extends BundleResource implements SensorEventListener {
+    private static final String LOG_TAG = HumidityResource.class.getSimpleName();
+    private final SensorManager mSensorManager;
+    private final Sensor temperatureSensor;
+
+    public TemperatureResource(Context context){
+        super(context);
+        this.setResourceType("oic.r.temperature");
+        this.setName("temperatureSensor");
+        mSensorManager = (SensorManager) context.getApplicationContext().
+                getSystemService(Context.SENSOR_SERVICE);
+        temperatureSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
+        mSensorManager.registerListener(this, temperatureSensor, SensorManager.SENSOR_DELAY_NORMAL);
+    }
+
+    @Override
+    protected void initAttributes() {
+        this.m_attributes.put("temperature", 0d);
+    }
+
+    @Override
+    public void handleSetAttributesRequest(RcsResourceAttributes attrs) {
+        Log.i(LOG_TAG, "Set Attributes called with ");
+        for(String key: attrs.keySet()){
+            Log.i(LOG_TAG, " " + key + ": " + attrs.get(key));
+        }
+    }
+
+    @Override
+    public RcsResourceAttributes handleGetAttributesRequest() {
+        Log.i(LOG_TAG, "Get Attributes called");
+        Log.i(LOG_TAG, "Returning: ");
+        for(String key: m_attributes.keySet()){
+            Log.i(LOG_TAG, " " + key + ": " + m_attributes.get(key));
+        }
+        return this.m_attributes;
+    }
+
+    @Override
+    public void onSensorChanged(SensorEvent sensorEvent) {
+        Log.i(LOG_TAG, "Sensor event " + sensorEvent.values[0]);
+
+        setAttribute("temperature", new RcsValue( (int) (sensorEvent.values[0]) ) , true);
+    }
+
+    @Override
+    public void onAccuracyChanged(Sensor sensor, int i) {
+
+    }
+}
diff --git a/service/resource-container/examples/android/AndroidBundle/app/src/main/res/layout/activity_main.xml b/service/resource-container/examples/android/AndroidBundle/app/src/main/res/layout/activity_main.xml
new file mode 100755 (executable)
index 0000000..f7158b8
--- /dev/null
@@ -0,0 +1,11 @@
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
+    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
+    android:paddingRight="@dimen/activity_horizontal_margin"
+    android:paddingTop="@dimen/activity_vertical_margin"
+    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
+
+    <TextView android:text="@string/hello_world" android:layout_width="wrap_content"
+        android:layout_height="wrap_content" />
+
+</RelativeLayout>
diff --git a/service/resource-container/examples/android/AndroidBundle/app/src/main/res/menu/menu_main.xml b/service/resource-container/examples/android/AndroidBundle/app/src/main/res/menu/menu_main.xml
new file mode 100755 (executable)
index 0000000..87a750e
--- /dev/null
@@ -0,0 +1,5 @@
+<menu xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">
+    <item android:id="@+id/action_settings" android:title="@string/action_settings"
+        android:orderInCategory="100" android:showAsAction="never" />
+</menu>
diff --git a/service/resource-container/examples/android/AndroidBundle/app/src/main/res/mipmap-hdpi/ic_launcher.png b/service/resource-container/examples/android/AndroidBundle/app/src/main/res/mipmap-hdpi/ic_launcher.png
new file mode 100755 (executable)
index 0000000..cde69bc
Binary files /dev/null and b/service/resource-container/examples/android/AndroidBundle/app/src/main/res/mipmap-hdpi/ic_launcher.png differ
diff --git a/service/resource-container/examples/android/AndroidBundle/app/src/main/res/mipmap-mdpi/ic_launcher.png b/service/resource-container/examples/android/AndroidBundle/app/src/main/res/mipmap-mdpi/ic_launcher.png
new file mode 100755 (executable)
index 0000000..c133a0c
Binary files /dev/null and b/service/resource-container/examples/android/AndroidBundle/app/src/main/res/mipmap-mdpi/ic_launcher.png differ
diff --git a/service/resource-container/examples/android/AndroidBundle/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/service/resource-container/examples/android/AndroidBundle/app/src/main/res/mipmap-xhdpi/ic_launcher.png
new file mode 100755 (executable)
index 0000000..bfa42f0
Binary files /dev/null and b/service/resource-container/examples/android/AndroidBundle/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ
diff --git a/service/resource-container/examples/android/AndroidBundle/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/service/resource-container/examples/android/AndroidBundle/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
new file mode 100755 (executable)
index 0000000..324e72c
Binary files /dev/null and b/service/resource-container/examples/android/AndroidBundle/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ
diff --git a/service/resource-container/examples/android/AndroidBundle/app/src/main/res/values-v21/styles.xml b/service/resource-container/examples/android/AndroidBundle/app/src/main/res/values-v21/styles.xml
new file mode 100755 (executable)
index 0000000..dba3c41
--- /dev/null
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <style name="AppTheme" parent="android:Theme.Material.Light">
+    </style>
+</resources>
diff --git a/service/resource-container/examples/android/AndroidBundle/app/src/main/res/values-w820dp/dimens.xml b/service/resource-container/examples/android/AndroidBundle/app/src/main/res/values-w820dp/dimens.xml
new file mode 100755 (executable)
index 0000000..63fc816
--- /dev/null
@@ -0,0 +1,6 @@
+<resources>
+    <!-- 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). -->
+    <dimen name="activity_horizontal_margin">64dp</dimen>
+</resources>
diff --git a/service/resource-container/examples/android/AndroidBundle/app/src/main/res/values/dimens.xml b/service/resource-container/examples/android/AndroidBundle/app/src/main/res/values/dimens.xml
new file mode 100755 (executable)
index 0000000..47c8224
--- /dev/null
@@ -0,0 +1,5 @@
+<resources>
+    <!-- Default screen margins, per the Android Design guidelines. -->
+    <dimen name="activity_horizontal_margin">16dp</dimen>
+    <dimen name="activity_vertical_margin">16dp</dimen>
+</resources>
diff --git a/service/resource-container/examples/android/AndroidBundle/app/src/main/res/values/strings.xml b/service/resource-container/examples/android/AndroidBundle/app/src/main/res/values/strings.xml
new file mode 100755 (executable)
index 0000000..26cc74c
--- /dev/null
@@ -0,0 +1,6 @@
+<resources>
+    <string name="app_name">AndroidBundle</string>
+
+    <string name="hello_world">Hello world!</string>
+    <string name="action_settings">Settings</string>
+</resources>
diff --git a/service/resource-container/examples/android/AndroidBundle/app/src/main/res/values/styles.xml b/service/resource-container/examples/android/AndroidBundle/app/src/main/res/values/styles.xml
new file mode 100755 (executable)
index 0000000..ff6c9d2
--- /dev/null
@@ -0,0 +1,8 @@
+<resources>
+
+    <!-- Base application theme. -->
+    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
+        <!-- Customize your theme here. -->
+    </style>
+
+</resources>
diff --git a/service/resource-container/examples/android/AndroidBundle/build.gradle b/service/resource-container/examples/android/AndroidBundle/build.gradle
new file mode 100755 (executable)
index 0000000..dcc70df
--- /dev/null
@@ -0,0 +1,20 @@
+// Top-level build file where you can add configuration options common to all sub-projects/modules.
+
+buildscript {
+    repositories {
+        jcenter()
+    }
+    dependencies {
+        classpath 'com.android.tools.build:gradle:1.3.0'
+
+        // NOTE: Do not place your application dependencies here; they belong
+        // in the individual module build.gradle files
+    }
+}
+
+allprojects {
+    repositories {
+        maven { url 'http://jcenter.bintray.com/' }
+        flatDir { dirs 'libs' }
+    }
+}
diff --git a/service/resource-container/examples/android/AndroidBundle/gradle/wrapper/gradle-wrapper.properties b/service/resource-container/examples/android/AndroidBundle/gradle/wrapper/gradle-wrapper.properties
new file mode 100755 (executable)
index 0000000..c882135
--- /dev/null
@@ -0,0 +1,6 @@
+#Sun Nov 08 19:01:42 KST 2015
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-all.zip
diff --git a/service/resource-container/examples/android/AndroidBundle/settings.gradle b/service/resource-container/examples/android/AndroidBundle/settings.gradle
new file mode 100755 (executable)
index 0000000..e7b4def
--- /dev/null
@@ -0,0 +1 @@
+include ':app'
diff --git a/service/resource-container/examples/android/RCSampleClientApp/.gitignore b/service/resource-container/examples/android/RCSampleClientApp/.gitignore
deleted file mode 100644 (file)
index 8b41237..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-.gradle
-/local.properties
-/.idea
-.DS_Store
-/build
-/captures
-/gradle
diff --git a/service/resource-container/examples/android/RCSampleClientApp/RCSampleClientApp.iml b/service/resource-container/examples/android/RCSampleClientApp/RCSampleClientApp.iml
deleted file mode 100644 (file)
index 2a02201..0000000
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" type="JAVA_MODULE" version="4">
-  <component name="FacetManager">
-    <facet type="java-gradle" name="Java-Gradle">
-      <configuration>
-        <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />
-      </configuration>
-    </facet>
-  </component>
-  <component name="NewModuleRootManager" inherit-compiler-output="false">
-    <output url="file://$MODULE_DIR$/build/classes/main" />
-    <output-test url="file://$MODULE_DIR$/build/classes/test" />
-    <exclude-output />
-    <content url="file://$MODULE_DIR$">
-      <excludeFolder url="file://$MODULE_DIR$/.gradle" />
-    </content>
-    <orderEntry type="inheritedJdk" />
-    <orderEntry type="sourceFolder" forTests="false" />
-  </component>
-</module>
-
diff --git a/service/resource-container/examples/android/RCSampleClientApp/app/.gitignore b/service/resource-container/examples/android/RCSampleClientApp/app/.gitignore
deleted file mode 100644 (file)
index 6a384b7..0000000
+++ /dev/null
@@ -1,2 +0,0 @@
-/build
-/libs/*
index a8285a4..5d58224 100644 (file)
@@ -2,7 +2,7 @@ apply plugin: 'com.android.application'
 
 android {
     compileSdkVersion 21
-    buildToolsVersion "21.1.2"
+    buildToolsVersion "20.0.0"
 
     defaultConfig {
         applicationId "org.iotivity.service.sample.client"
index 319d5e1..86a005f 100644 (file)
@@ -20,8 +20,11 @@ package org.iotivity.service.sample.client;
 
 import android.app.Activity;
 import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
 import android.util.Log;
 import android.view.View;
+import android.widget.ListView;
 import android.widget.TextView;
 
 import org.iotivity.service.RcsException;
@@ -29,47 +32,132 @@ import org.iotivity.service.client.RcsAddress;
 import org.iotivity.service.client.RcsDiscoveryManager;
 import org.iotivity.service.client.RcsRemoteResourceObject;
 
+import java.lang.ref.WeakReference;
+import java.util.ArrayList;
+import java.util.List;
+
 /**
  * It contains the discover resource API for Discovering Container Resource
  */
+
 public class ContainerClientActivity extends Activity implements
         RcsDiscoveryManager.OnResourceDiscoveredListener {
+    public static final int MSG_ID_ATTRIBUTE_RECEIVED  = 0;
+    public static final int MSG_ID_CACHEDATA_RECEIVED  = 1;
+
     private final String LOG_TAG = "[SampleClient] "
                                          + this.getClass().getSimpleName();
+    private final String RESOURCE_DISCOVERY_URI_KEYWORD = "discomfort";
+
+    private Handler    mHandler;
 
+    private ResourceListAdapter mResourceListViewAdapter;
+
+    private ListView mResourceListView;
     private TextView     mLogView;
 
+    private List<String> mFoundResourceUris;
+    private List<ResourceListItem> mFoundResources;
+
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_container_client);
+
+        mFoundResourceUris = new ArrayList<String>();
+        mFoundResources = new ArrayList<ResourceListItem>();
+
+        mHandler = new ContainerClientHandler(this);
+
+        mResourceListViewAdapter = new ResourceListAdapter(this, R.layout.discovered_resource, mFoundResources);
+        mResourceListView = (ListView) findViewById(R.id.ResourceListView);
+        mResourceListView.setAdapter(mResourceListViewAdapter);
+
         mLogView = (TextView) findViewById(R.id.log);
     }
 
     public void onDiscoverResourceClick(View v) {
         try {
-            RcsDiscoveryManager.getInstance().discoverResourceByType(
-                    RcsAddress.multicast(), "oic.r.sensor",
+            RcsDiscoveryManager.getInstance().discoverResource(
+                    RcsAddress.multicast(),
                     ContainerClientActivity.this);
+
+            mFoundResourceUris.clear();
+            mFoundResources.clear();
+            mResourceListViewAdapter.notifyDataSetChanged();
+
             mLogView.setText("");
         } catch (RcsException e) {
             e.printStackTrace();
         }
     }
 
+    private boolean IsFoundResource(String resourceUri)
+    {
+        if (mFoundResourceUris.contains(resourceUri))
+            return true;
+
+        return false;
+    }
+
     @Override
     public void onResourceDiscovered(
             final RcsRemoteResourceObject discoveredResource) {
-        Log.i(LOG_TAG, "onResourceDiscovered");
 
         runOnUiThread(new Runnable() {
             public void run() {
                 try {
-                    mLogView.setText(Utils.resourceInfo(discoveredResource));
+                    String uri = discoveredResource.getUri();
+                    Log.i(LOG_TAG, "onResourceDiscovered -- " + uri);
+
+                    if (uri.contains(RESOURCE_DISCOVERY_URI_KEYWORD) && !IsFoundResource(uri)) {
+                        mFoundResourceUris.add(uri);
+                        mFoundResources.add(new ResourceListItem(uri, discoveredResource, ContainerClientActivity.this.getHandler()));
+                        mResourceListViewAdapter.notifyDataSetChanged();
+                    }
                 } catch (RcsException e) {
-                    Utils.showError(ContainerClientActivity.this, LOG_TAG, e);
+                    e.printStackTrace();
                 }
             }
         });
     }
-}
+
+    private void printLog(String message) {
+        Log.i(LOG_TAG, message);
+        mLogView.setText(message);
+    }
+
+    public Handler getHandler() {
+        return mHandler;
+    }
+
+    private static class ContainerClientHandler extends Handler {
+        private WeakReference<ContainerClientActivity> mActivityRef;
+        private String logMsg;
+
+        private ContainerClientHandler(ContainerClientActivity activity) {
+            mActivityRef = new WeakReference<>(activity);
+        }
+
+        @Override
+        public void handleMessage(Message msg) {
+            super.handleMessage(msg);
+
+            ContainerClientActivity activity = mActivityRef.get();
+            if (activity == null) return;
+
+            switch (msg.what) {
+                case MSG_ID_ATTRIBUTE_RECEIVED:
+                    logMsg = "-- ATTRIBUTE_RECEIVED\n";
+                    logMsg += msg.obj.toString();
+                    break;
+
+                case MSG_ID_CACHEDATA_RECEIVED:
+                    logMsg = "-- CACHEDATA_RECEIVED\n";
+                    logMsg += msg.obj.toString();
+                    break;
+            }
+            activity.printLog(logMsg);
+        }
+    }
+}
\ No newline at end of file
diff --git a/service/resource-container/examples/android/RCSampleClientApp/app/src/main/java/org/iotivity/service/sample/client/ResourceListAdapter.java b/service/resource-container/examples/android/RCSampleClientApp/app/src/main/java/org/iotivity/service/sample/client/ResourceListAdapter.java
new file mode 100644 (file)
index 0000000..8145bc8
--- /dev/null
@@ -0,0 +1,120 @@
+/******************************************************************
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.service.sample.client;
+
+import android.app.Activity;
+import android.content.Context;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.TextView;
+import android.widget.ToggleButton;
+
+import org.iotivity.service.RcsException;
+
+import java.util.List;
+
+public class ResourceListAdapter extends ArrayAdapter<ResourceListItem> {
+
+    private Context mContext;
+    private int mLayoutId;
+    private List<ResourceListItem> foundResources;
+
+    public ResourceListAdapter(Context context, int layoutId, List<ResourceListItem> foundResources)
+    {
+        super(context, layoutId, foundResources);
+
+        this.mLayoutId = layoutId;
+        this.mContext = context;
+        this.foundResources = foundResources;
+    }
+
+    @Override
+    public View getView(final int position, View convertView, final ViewGroup parent) {
+        if (convertView == null)
+        {
+            LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
+            convertView = inflater.inflate(mLayoutId, parent, false);
+        }
+
+        String resourceUri = foundResources.get(position).mResourceUri;
+
+        TextView textViewUri = (TextView) convertView.findViewById(R.id.textView_uri);
+        textViewUri.setText(resourceUri);
+
+        textViewUri.setOnClickListener(new View.OnClickListener() {
+
+            @Override
+            public void onClick(View view) {
+                try {
+                    TextView textView = (TextView) ((Activity) mContext).findViewById(R.id.log);
+                    textView.setText(Utils.resourceInfo(foundResources.get(position).mResource));
+                } catch (RcsException e) {
+                    e.printStackTrace();
+                }
+            }
+        });
+
+        Button buttonGet = (Button) convertView.findViewById(R.id.button_get);
+        buttonGet.setOnClickListener(new View.OnClickListener() {
+
+            @Override
+            public void onClick(View view) {
+                ResourceListItem selectedResource = foundResources.get(position);
+                try {
+                    TextView textView = (TextView) ((Activity) mContext).findViewById(R.id.log);
+                    textView.setText("Get Remote Attributes from \'" + selectedResource.mResourceUri + "\'");
+                    selectedResource.mResource.getRemoteAttributes(selectedResource.mGetListener);
+                } catch (RcsException e) {
+                    e.printStackTrace();
+                }
+            }
+        });
+
+        ToggleButton buttonObserve = (ToggleButton) convertView.findViewById(R.id.button_observe);
+        buttonObserve.setOnClickListener(new View.OnClickListener() {
+
+            @Override
+            public void onClick(View view) {
+                ResourceListItem selectedResource = foundResources.get(position);
+                TextView textView = (TextView) ((Activity) mContext).findViewById(R.id.log);
+
+                try {
+                    if (!selectedResource.mCacheStarted) {
+                        textView.setText("Start Observe \'" + selectedResource.mResourceUri + "\'");
+                        selectedResource.mResource.startCaching(selectedResource.mCacheListener);
+                        selectedResource.mCacheStarted = true;
+                        ((ToggleButton) view).setChecked(true);
+                    } else {
+                        textView.setText("Stop Observing \'" + selectedResource.mResourceUri + "\'");
+                        selectedResource.mResource.stopCaching();
+                        selectedResource.mCacheStarted = false;
+                        ((ToggleButton) view).setChecked(false);
+                    }
+                } catch (RcsException e) {
+                    e.printStackTrace();
+                }
+            }
+        });
+
+        return convertView;
+    }
+}
\ No newline at end of file
diff --git a/service/resource-container/examples/android/RCSampleClientApp/app/src/main/java/org/iotivity/service/sample/client/ResourceListItem.java b/service/resource-container/examples/android/RCSampleClientApp/app/src/main/java/org/iotivity/service/sample/client/ResourceListItem.java
new file mode 100644 (file)
index 0000000..e9f205f
--- /dev/null
@@ -0,0 +1,101 @@
+/******************************************************************
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.service.sample.client;
+
+import android.os.Handler;
+import android.util.Log;
+
+import org.iotivity.service.RcsException;
+import org.iotivity.service.RcsResourceAttributes;
+import org.iotivity.service.client.RcsRemoteResourceObject;
+
+public class ResourceListItem {
+    private final String LOG_TAG = "[RCSampleClient] "
+            + this.getClass().getSimpleName();
+
+    public String mResourceUri;
+    public RcsRemoteResourceObject mResource;
+    public RemoteResourceGetListener mGetListener;
+    public RemoteResourceCacheListener mCacheListener;
+    public boolean mCacheStarted;
+
+    private Handler mHandler;
+
+    public ResourceListItem(String resourceUri, RcsRemoteResourceObject resource, Handler handler)
+    {
+        mResourceUri = resourceUri;
+        mResource = resource;
+
+        mGetListener = new RemoteResourceGetListener();
+        mCacheListener = new RemoteResourceCacheListener();
+        mCacheStarted = false;
+
+        mHandler = handler;
+    }
+
+    private class RemoteResourceGetListener implements RcsRemoteResourceObject.OnRemoteAttributesReceivedListener
+    {
+
+        @Override
+        public void onAttributesReceived(final RcsResourceAttributes rcsResourceAttributes, int eCode) {
+            Log.i(LOG_TAG, "onAttributesReceived -- " + mResourceUri);
+
+            new Thread(new Runnable() {
+
+                @Override
+                public void run() {
+                    try {
+                        String logMessage;
+                        logMessage = "-- " + mResourceUri + "\n";
+                        logMessage += Utils.resourceAttributes(rcsResourceAttributes);
+
+                        mHandler.obtainMessage(ContainerClientActivity.MSG_ID_ATTRIBUTE_RECEIVED, logMessage).sendToTarget();
+                    } catch (RcsException e) {
+                        e.printStackTrace();
+                    }
+                 }
+            }).run();
+        }
+    }
+
+    private class RemoteResourceCacheListener implements RcsRemoteResourceObject.OnCacheUpdatedListener
+    {
+
+        @Override
+        public void onCacheUpdated(final RcsResourceAttributes rcsResourceAttributes) {
+            Log.i(LOG_TAG, "onCacheUpdated -- " + mResourceUri);
+
+            new Thread(new Runnable() {
+
+                @Override
+                public void run() {
+                    try {
+                        String logMessage;
+                        logMessage = "-- " + mResourceUri + "\n";
+                        logMessage += Utils.resourceAttributes(rcsResourceAttributes);
+
+                        mHandler.obtainMessage(ContainerClientActivity.MSG_ID_CACHEDATA_RECEIVED, logMessage).sendToTarget();
+                    } catch (RcsException e) {
+                        e.printStackTrace();
+                    }
+                }
+            }).run();
+        }
+    }
+}
\ No newline at end of file
index a39afd1..46e2828 100644 (file)
@@ -1,10 +1,25 @@
-package org.iotivity.service.sample.client;
+/******************************************************************
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ ******************************************************************/
 
-import android.content.Context;
-import android.util.Log;
-import android.widget.Toast;
+package org.iotivity.service.sample.client;
 
 import org.iotivity.service.RcsException;
+import org.iotivity.service.RcsResourceAttributes;
 import org.iotivity.service.client.RcsRemoteResourceObject;
 
 public class Utils {
@@ -27,13 +42,15 @@ public class Utils {
         return sb.toString();
     }
 
-    public static void showError(Context ctx, String tag, String msg) {
-        Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
-        Log.e(tag, msg);
-    }
+    public static String resourceAttributes(RcsResourceAttributes attr)
+            throws RcsException {
+        StringBuilder sb = new StringBuilder();
+
+        for (String key : attr.keySet())
+        {
+            sb.append(key + " : " + attr.get(key) + "\n");
+        }
 
-    public static void showError(Context ctx, String tag, Exception e) {
-        Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_SHORT).show();
-        Log.e(tag, e.getMessage(), e);
+        return sb.toString();
     }
 }
index 09634a3..2d3f7a0 100644 (file)
@@ -4,14 +4,17 @@
     android:layout_height="match_parent"
     android:orientation="vertical"
     android:id="@+id/main"
-    android:weightSum="1">
+    android:weightSum="1"
+    android:padding="5dp">
 
     <Button
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:onClick="onDiscoverResourceClick"
         android:text="@string/discover_resource"
-        android:id="@+id/di" />
+        android:id="@+id/di"
+        android:layout_alignParentTop="true"
+        android:layout_alignParentStart="true" />
 
     <TextView
         android:id="@+id/log"
         android:layout_height="250dp"
         android:ems="10"
         android:layout_weight="0.26"
+        android:layout_alignParentStart="true"
+        android:layout_alignParentBottom="true"
+        android:background="#32437200"
+        android:padding="10dp" />
+
+    <ListView
+        android:layout_width="wrap_content"
+        android:layout_height="376dp"
+        android:id="@+id/ResourceListView"
         android:layout_below="@+id/di"
-        android:layout_alignParentStart="true" />
+        android:layout_alignParentStart="true"
+        android:layout_above="@+id/log" />
 
 </RelativeLayout>
diff --git a/service/resource-container/examples/android/RCSampleClientApp/app/src/main/res/layout/discovered_resource.xml b/service/resource-container/examples/android/RCSampleClientApp/app/src/main/res/layout/discovered_resource.xml
new file mode 100644 (file)
index 0000000..40ec219
--- /dev/null
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="utf-8"?>
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent" android:layout_height="match_parent">
+
+    <TextView
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:text="/softsensor/discomfortIndex/1"
+        android:id="@+id/textView_uri"
+        android:layout_alignBaseline="@+id/button_get"
+        android:layout_alignBottom="@+id/button_get"
+        android:layout_alignParentStart="true"
+        android:paddingStart="10dp"
+        android:textStyle="bold" />
+
+    <Button
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:text="Get"
+        android:id="@+id/button_get"
+        android:layout_alignParentTop="true"
+        android:layout_toStartOf="@+id/button_observe" />
+
+    <ToggleButton
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:id="@+id/button_observe"
+        android:layout_alignBottom="@+id/button_get"
+        android:layout_alignParentEnd="true"
+        android:textOff="Observe"
+        android:textOn="Observe" />
+
+</RelativeLayout>
\ No newline at end of file
diff --git a/service/resource-container/examples/android/RCSampleServerApp/.gitignore b/service/resource-container/examples/android/RCSampleServerApp/.gitignore
deleted file mode 100644 (file)
index 8b41237..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-.gradle
-/local.properties
-/.idea
-.DS_Store
-/build
-/captures
-/gradle
old mode 100644 (file)
new mode 100755 (executable)
index 2a02201..47ed257
@@ -1,21 +1,19 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" type="JAVA_MODULE" version="4">
+<module external.linked.project.id="RCSampleServerApp" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
   <component name="FacetManager">
     <facet type="java-gradle" name="Java-Gradle">
       <configuration>
         <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />
+        <option name="BUILDABLE" value="false" />
       </configuration>
     </facet>
   </component>
-  <component name="NewModuleRootManager" inherit-compiler-output="false">
-    <output url="file://$MODULE_DIR$/build/classes/main" />
-    <output-test url="file://$MODULE_DIR$/build/classes/test" />
+  <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="true">
     <exclude-output />
     <content url="file://$MODULE_DIR$">
       <excludeFolder url="file://$MODULE_DIR$/.gradle" />
     </content>
-    <orderEntry type="inheritedJdk" />
+    <orderEntry type="jdk" jdkName="1.8" jdkType="JavaSDK" />
     <orderEntry type="sourceFolder" forTests="false" />
   </component>
 </module>
-
old mode 100644 (file)
new mode 100755 (executable)
index b0dd604..5364aec
@@ -5,7 +5,6 @@ To build the app
 2. Copy aar files into app/libs folder
    - {Iotivity_root}/android/android_api/base/build/outputs/aar/iotivity-{TARGET_ARCH}-base-{MODE}.aar
    - {Iotivity_root}/service/resource-encapsulation/android/service/build/outputs/aar/iotivity-{TARGET_ARCH}-service-{MODE}.aar
-   - {Iotivity_root}/service/resource-container/android/resource-container/build/outputs/aar/iotivity-{TARGET_ARCH}-resource-container-{MODE}.aar
 
 3. Configure dependencies for libs in app/build.gradle
    - default TARGET_ARCH is armeabi
@@ -18,8 +17,7 @@ To build the app
    then, dependencies should be modified like below
 
    dependencies {
-      compile(name:'iotivity-x86-base-debug', ext:'aar')
       compile(name:'iotivity-x86-service-debug', ext:'aar')
-      compile(name:'iotivity-x86-resource-container-debug', ext:'aar')
+      compile(name:'iotivity-x86-base-debug', ext:'aar')
    }
    
diff --git a/service/resource-container/examples/android/RCSampleServerApp/app/.gitignore b/service/resource-container/examples/android/RCSampleServerApp/app/.gitignore
deleted file mode 100644 (file)
index 6a384b7..0000000
+++ /dev/null
@@ -1,2 +0,0 @@
-/build
-/libs/*
old mode 100644 (file)
new mode 100755 (executable)
index 2d5414e..ae4d481
@@ -1,5 +1,5 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" type="JAVA_MODULE" version="4">
+<module external.linked.project.id=":app" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="RCSampleServerApp" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
   <component name="FacetManager">
     <facet type="android-gradle" name="Android-Gradle">
       <configuration>
@@ -9,11 +9,15 @@
     <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="assembleDebugTest" />
-        <option name="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
-        <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />
+        <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" />
@@ -22,8 +26,9 @@
       </configuration>
     </facet>
   </component>
-  <component name="NewModuleRootManager" inherit-compiler-output="false">
+  <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/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/generated/debug" type="java-resource" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/test/debug" isTestSource="true" generated="true" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />
-      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/test/debug" type="java-test-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" />
@@ -66,6 +71,8 @@
       <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/exploded-aar/iotivity-armeabi-v7a-resource-container-release/jars" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/iotivity-base-armeabi-v7a-release/jars" />
       <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
       <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
       <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
@@ -83,9 +90,7 @@
     </content>
     <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
     <orderEntry type="sourceFolder" forTests="false" />
-    <orderEntry type="library" exported="" name="iotivity-service-release-" level="project" />
-    <orderEntry type="library" exported="" name="iotivity-resource-container-release-" level="project" />
-    <orderEntry type="library" exported="" name="iotivity-base-release-" level="project" />
+    <orderEntry type="library" exported="" name="iotivity-armeabi-v7a-resource-container-release-" level="project" />
+    <orderEntry type="library" exported="" name="iotivity-base-armeabi-v7a-release-" level="project" />
   </component>
 </module>
-
old mode 100644 (file)
new mode 100755 (executable)
index bcb90e5..8a0f06d
@@ -2,10 +2,10 @@ apply plugin: 'com.android.application'
 
 android {
     compileSdkVersion 21
-    buildToolsVersion "21.1.2"
+    buildToolsVersion "20.0.0"
 
     defaultConfig {
-        applicationId "org.iotivity.service.sample.server"
+        applicationId "org.iotivity.service.sample.resourcecontainer"
         minSdkVersion 21
         targetSdkVersion 21
         versionCode 1
@@ -17,11 +17,19 @@ android {
             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
         }
     }
+
+    /*packagingOptions{
+        exclude 'lib/armeabi-v7a/librcs_client.so'
+        exclude 'lib/armeabi-v7a/librcs_common.so'
+        exclude 'lib/armeabi-v7a/librcs_server.so'
+    }*/
+
 }
 
 dependencies {
     compile fileTree(include: ['*.jar'], dir: 'libs')
-    compile(name:'iotivity-base-release', ext:'aar')
-    compile(name:'iotivity-service-release', ext:'aar')
-    compile(name:'iotivity-resource-container-release', ext:'aar')
+    //provided(name:'iotivity-armeabi-v7a-service-release', ext:'aar')
+    compile(name:'iotivity-armeabi-v7a-resource-container-release', ext:'aar')
+   // compile(name:'iotivity-armeabi-v7a-resource-container-debug', ext:'aar')
+    compile(name:'iotivity-base-armeabi-v7a-release', ext:'aar')
 }
diff --git a/service/resource-container/examples/android/RCSampleServerApp/app/src/androidTest/assets/lib/ResourceContainerConfig.xml b/service/resource-container/examples/android/RCSampleServerApp/app/src/androidTest/assets/lib/ResourceContainerConfig.xml
new file mode 100755 (executable)
index 0000000..4c52d93
--- /dev/null
@@ -0,0 +1,105 @@
+<container>
+    <bundle>
+        <id>oic.bundle.discomfortIndexSensor</id>
+        <path>/data/local/tmp/org.iotivity.service.sample.resourcecontainer.test/files/libSoftSensorBundle.so</path>
+        <activator>disensor</activator>
+        <version>1.0.0</version>
+        <resources>
+            <resourceInfo>
+                <name>DiscomfortIndexSensor1</name>
+                <resourceType>oic.r.sensor</resourceType>
+                <outputs>
+                    <output>
+                        <name>discomfortIndex</name>
+                        <type>int</type>
+                    </output>
+                    <output>
+                        <name>humidity</name>
+                        <type>double</type>
+                    </output>
+                    <output>
+                        <name>temperature</name>
+                        <type>double</type>
+                    </output>
+                </outputs>
+                <inputs>
+                    <input>
+                        <name>humidity</name>
+                        <type>double</type>
+                        <resourceType>oic.r.humidity</resourceType>
+                    </input>
+                    <input>
+                        <name>temperature</name>
+                        <type>double</type>
+                        <resourceType>oic.r.temperature</resourceType>
+                    </input>
+                </inputs>
+            </resourceInfo>
+        </resources>
+    </bundle>
+    <!--
+    <bundle>
+        <id>oic.android.sample</id>
+        <path>org.iotivity.service.sample.androidbundle.apk</path>
+        <activator>org.iotivity.service.sample.androidbundle.SampleActivator</activator>
+        <version>1.0.0</version>
+        <resources>
+           <resourceInfo>
+                <name>LightResource1</name>
+                <resourceType>oic.r.light</resourceType>
+                <resourceUri>/android/light/1</resourceUri>
+            </resourceInfo>
+            <resourceInfo>
+                 <name>LightIntensity1</name>
+                 <resourceType>oic.r.lightintensity</resourceType>
+                 <resourceUri>/android/lightintensity/1</resourceUri>
+            </resourceInfo>
+            <resourceInfo>
+                <name>Humidity1</name>
+                <resogitkurceType>oic.r.humidity</resogitkurceType>
+                <resourceUri>/android/humidity/1</resourceUri>
+            </resourceInfo>
+            <resourceInfo>
+                <name>Tepmerature1</name>
+                <resourceType>oic.r.temperature</resourceType>
+                <resourceUri>/android/temperature/1</resourceUri>
+            </resourceInfo>
+            <resourceInfo>
+                <name>Gyroscope1</name>
+                <resourceType>oic.r.gyroscope</resourceType>
+                <resourceUri>/android/gyroscope/1</resourceUri>
+            </resourceInfo>
+            <resourceInfo>
+                <name>DiscomfortIndexSensor1</name>
+                <resourceType>oic.r.discomfortindex</resourceType>
+                <resourceUri>/android/discomfortindex/1</resourceUri>
+                <outputs>
+                    <output>
+                        <name>discomfortIndex</name>
+                        <type>int</type>
+                    </output>
+                    <output>
+                        <name>humidity</name>
+                        <type>double</type>
+                    </output>
+                    <output>
+                        <name>temperature</name>
+                        <type>double</type>
+                    </output>
+                </outputs>
+                <inputs>
+                    <input>
+                        <name>humidity</name>
+                        <type>double</type>
+                        <resourceType>oic.r.humidity</resourceType>
+                    </input>
+                    <input>
+                        <name>temperature</name>
+                        <type>double</type>
+                        <resourceType>oic.r.temperature</resourceType>
+                    </input>
+                </inputs>
+            </resourceInfo>
+        </resources>
+    </bundle>-->
+</container>
\ No newline at end of file
diff --git a/service/resource-container/examples/android/RCSampleServerApp/app/src/androidTest/java/org/iotivity/service/sample/container/ResourceContainerTest.java b/service/resource-container/examples/android/RCSampleServerApp/app/src/androidTest/java/org/iotivity/service/sample/container/ResourceContainerTest.java
new file mode 100755 (executable)
index 0000000..53e4113
--- /dev/null
@@ -0,0 +1,73 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+package org.iotivity.service.sample.container;
+
+import android.test.InstrumentationTestCase;
+import android.util.Log;
+
+import org.iotivity.service.resourcecontainer.RcsResourceContainer;
+
+import java.util.HashMap;
+
+public class ResourceContainerTest extends InstrumentationTestCase {
+    private RcsResourceContainer resourceContainerInstance;
+    private final String sdCardDir =
+            "/data/local/tmp/org.iotivity.service.sample.resourcecontainer.test/files/";
+
+    @Override
+    public void setUp(){
+        resourceContainerInstance = new RcsResourceContainer(getInstrumentation().getContext());
+    }
+
+    public void testStartContainer() {
+        resourceContainerInstance.startContainer("");
+        assertTrue(resourceContainerInstance.listBundles().size() == 0);
+        resourceContainerInstance.stopContainer();
+    }
+
+    public void testAddConfig(){
+        resourceContainerInstance.startContainer("");
+        //resourceContainerInstance.addBundle("");
+        assertTrue(resourceContainerInstance.listBundles().size() == 0);
+        resourceContainerInstance.stopContainer();
+    }
+
+    public void testStartBundle(){
+        resourceContainerInstance.startBundle("not.existing");
+        assertEquals(0, resourceContainerInstance.listBundles().size());
+    }
+
+    public void testStopBundle(){
+        resourceContainerInstance.startBundle("not.existing");
+        assertEquals(0, resourceContainerInstance.listBundles().size());
+    }
+
+    public void testAddBundle(){
+        resourceContainerInstance.startContainer(
+                "");
+
+        resourceContainerInstance.addBundle("oic.bundle.test", "",
+                sdCardDir + "libSoftSensorBundle.so",
+                "disensor", new HashMap<String, String>());
+        resourceContainerInstance.startBundle("oic.bundle.test");
+        resourceContainerInstance.stopContainer();
+    }
+}
\ No newline at end of file
old mode 100644 (file)
new mode 100755 (executable)
index d12abc4..f58486e
@@ -3,7 +3,18 @@
 
     <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
-    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
+
+    <uses-permission android:name="android.permission.CAMERA" />
+    <uses-permission android:name="android.permission.FLASHLIGHT"/>
+    <uses-permission android:name="android.permission.WAKE_LOCK"/>
+    <uses-feature android:name="android.hardware.camera" />
+    <uses-feature android:name="android.hardware.camera.autofocus" />
+    <uses-feature android:name="android.hardware.camera.flash" />
+
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
+    </uses-permission>
+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE">
+    </uses-permission>
 
     <application android:allowBackup="true" android:label="@string/app_name"
         android:icon="@mipmap/ic_launcher" android:theme="@style/AppTheme">
old mode 100644 (file)
new mode 100755 (executable)
index bd04739..d6fe5b3
@@ -1,8 +1,73 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
 <container>
+<!--
     <bundle>
+        <id>oic.android.sample</id>
+        <path>data/data/org.iotivity.service.sample.resourcecontainer/files/android_sample_bundle.jar</path>
+        <activator>org.iotivity.service.sample.androidbundle.SampleActivator</activator>
+        <version>1.0.0</version>
+        <resources>
+            <resourceInfo>
+                <name>LightResource1</name>
+                <resourceType>oic.r.light</resourceType>
+                <resourceUri>/android/light/1</resourceUri>
+            </resourceInfo>
+            <resourceInfo>
+                <name>LightIntensity1</name>
+                <resourceType>oic.r.lightintensity</resourceType>
+                <resourceUri>/android/lightintensity/1</resourceUri>
+            </resourceInfo>
+            <resourceInfo>
+                <name>Humidity1</name>
+                <resourceType>oic.r.humidity</resourceType>
+                <resourceUri>/android/humidity/1</resourceUri>
+            </resourceInfo>
+            <resourceInfo>
+                <name>Tepmerature1</name>
+                <resourceType>oic.r.temperature</resourceType>
+                <resourceUri>/android/temperature/1</resourceUri>
+            </resourceInfo>
+            <resourceInfo>
+                <name>Gyroscope1</name>
+                <resourceType>oic.r.gyroscope</resourceType>
+                <resourceUri>/android/gyroscope/1</resourceUri>
+            </resourceInfo>
+            <resourceInfo>
+                <name>DiscomfortIndexSensor1</name>
+                <resourceType>oic.r.discomfortindex</resourceType>
+                <resourceUri>/android/discomfortindex/1</resourceUri>
+                <resourceClass>org.iotivity.service.sample.androidbundle.resources.DiscomfortIndexResource</resourceClass>
+                <outputs>
+                    <output>
+                        <name>discomfortIndex</name>
+                        <type>int</type>
+                    </output>
+                    <output>
+                        <name>humidity</name>
+                        <type>double</type>
+                    </output>
+                    <output>
+                        <name>temperature</name>
+                        <type>double</type>
+                    </output>
+                </outputs>
+                <inputs>
+                    <input>
+                        <name>humidity</name>
+                        <type>double</type>
+                        <resourceType>oic.r.humidity</resourceType>
+                    </input>
+                    <input>
+                        <name>temperature</name>
+                        <type>double</type>
+                        <resourceType>oic.r.temperature</resourceType>
+                    </input>
+                </inputs>
+            </resourceInfo>
+        </resources>
+    </bundle>
+   <bundle>
         <id>oic.bundle.discomfortIndexSensor</id>
-        <path>data/data/org.iotivity.service.sample.server/files/libDISensorBundle.so</path>
+        <path>data/data/org.iotivity.service.sample.resourcecontainer/files/libDISensorBundle.so</path>
         <activator>disensor</activator>
         <version>1.0.0</version>
         <resources>
             </resourceInfo>
         </resources>
     </bundle>
+-->
 </container>
\ No newline at end of file
old mode 100644 (file)
new mode 100755 (executable)
index 5c051de..55223fb
 
 package org.iotivity.service.sample.container;
 
+import android.content.Context;
 import android.os.Message;
 
+import android.os.PowerManager;
 import android.util.Log;
 
 import org.iotivity.service.resourcecontainer.RcsBundleInfo;
@@ -47,13 +49,17 @@ public class ResourceContainer {
     private static Message                   msg;
     public static boolean                    startBundleFlag;
     private static boolean                   isStarted     = false;
-    public static boolean                    isInitialized = false;
+    PowerManager pm = null;
+    PowerManager.WakeLock wl = null;
 
     // constructor
     public ResourceContainer() {
         resourceContainerActivityInstance = ResourceContainerActivity
                 .getResourceContainerActivityObj();
-        containerInstance = RcsResourceContainer.getInstance();
+        containerInstance = new RcsResourceContainer(
+                resourceContainerActivityInstance.getApplicationContext());
+        pm = (PowerManager) resourceContainerActivityInstance.getApplicationContext().
+                getSystemService(Context.POWER_SERVICE);
     }
 
     // Start Container
@@ -63,26 +69,38 @@ public class ResourceContainer {
         Log.i("startContainer : config path : ", configFile);
 
         if (!isStarted) {
-            for (int i = 0; i < 2; i++) {
-                containerInstance.startContainer(configFile);
-                isStarted = true;
-            }
-        } else {
+            wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK,
+                    "ResourceContainer sample");
+            wl.acquire();
             containerInstance.startContainer(configFile);
-        }
+            isStarted = true;
+            logMessage = "Container Started ";
 
-        logMessage = "Container Started ";
-        logMessage += "with one Bundle" + "\n";
-        logMessage += "ID : oic.bundle.discomfortIndexSensor";
+            ResourceContainerActivity.setMessageLog(logMessage);
+            msg = Message.obtain();
+            msg.what = 1;
+            resourceContainerActivityInstance.getHandler().sendMessage(msg);
 
-        ResourceContainerActivity.setMessageLog(logMessage);
-        msg = Message.obtain();
-        msg.what = 1;
-        resourceContainerActivityInstance.getHandler().sendMessage(msg);
+            msg = Message.obtain();
+            msg.what = 0;
+            resourceContainerActivityInstance.getHandler().sendMessage(msg);
 
-        msg = Message.obtain();
-        msg.what = 0;
-        resourceContainerActivityInstance.getHandler().sendMessage(msg);
+            // initialize the information of the bundles
+            // which registered at the starting time of the container
+            List<RcsBundleInfo> bundleList = containerInstance.listBundles();
+            Iterator<RcsBundleInfo> it = bundleList.iterator();
+
+            while (it.hasNext())
+            {
+                String id = ((RcsBundleInfo) it.next()).getID();
+                if (id.equals(ExampleBundleDescription.DIBundle.mBundleId)) {
+                    ExampleBundleDescription.DIBundle.isStarted = true;
+                }
+                else if (id.equals(ExampleBundleDescription.DIAndroidBundle.mBundleId)) {
+                    ExampleBundleDescription.DIAndroidBundle.isStarted = true;
+                }
+            }
+        }
     }
 
     // Stop Container
@@ -92,6 +110,7 @@ public class ResourceContainer {
             containerInstance.stopContainer();
             logMessage = "Container stopped";
             isStarted = false;
+            wl.release();
         } else {
             logMessage = "Container not started";
         }
@@ -103,10 +122,10 @@ public class ResourceContainer {
     }
 
     // List Bundle Resources
-    public void listDIBundleResources() {
+    public void listBundleResources(String bundleId) {
 
         List<String> bundleResources = containerInstance
-                .listBundleResources("oic.bundle.discomfortIndexSensor");
+                .listBundleResources(bundleId);
         Iterator<String> it = bundleResources.iterator();
         logMessage = "";
 
@@ -151,30 +170,36 @@ public class ResourceContainer {
         resourceContainerActivityInstance.getHandler().sendMessage(msg);
     }
 
-    // Add BMI Bundles
-    public void addBMIBundle() {
-
-        Map<String, String> bundleParams = null;
+    public boolean bundleExists(String bundleId)
+    {
         List<RcsBundleInfo> bundleList = containerInstance.listBundles();
-        if (1 < bundleList.size()) {
-            logMessage = "Bundle already added" + "\n";
+        Iterator<RcsBundleInfo> it = bundleList.iterator();
 
-        } else {
-            for (int i = 0; i < 2; i++) {
-                containerInstance
-                        .addBundle(
-                                "oic.bundle.BMISensor",
-                                "xyz",
-                                "data/data/org.iotivity.service.sample.server/files/libBMISensorBundle.so",
-                                "bmisensor", bundleParams);
-            }
+        while (it.hasNext())
+        {
+            if (it.next().getID().equals(bundleId))
+                return true;
+        }
+
+        return false;
+    }
+
+    // add Bundles
+    public void addBundle(BundleInformation bundle) {
+        if (bundleExists(bundle.mBundleId))
+            logMessage = "Bundle \'" + bundle.mBundleId + "\' already added" + "\n";
+
+        else {
+            containerInstance
+                    .addBundle(bundle.mBundleId, bundle.mBundleUri,
+                            bundle.mBundlePath, bundle.mActivator, bundle.mBundleParams);
 
             logMessage = "bundle to add : " + "\n";
-            logMessage = logMessage + "ID :" + "oic.bundle.BMISensor" + "\n";
-            logMessage = logMessage + "Uri: " + "xyz" + "\n";
+            logMessage = logMessage + "ID : " + bundle.mBundleId + "\n";
+            logMessage = logMessage + "Uri: " + bundle.mBundleUri + "\n";
             logMessage = logMessage
                     + "Path : "
-                    + "data/data/org.iotivity.service.sample.server/files/libBMISensorBundle.so"
+                    + bundle.mBundlePath
                     + "\n\n";
             logMessage = logMessage + "bundle added successfully" + "\n";
         }
@@ -185,70 +210,42 @@ public class ResourceContainer {
         resourceContainerActivityInstance.getHandler().sendMessage(msg);
     }
 
-    // Remove Bundle BMI
-    public void removeBMIBundle() {
+    // remove Bundles
+    public void removeBundle(BundleInformation bundle) {
 
-        List<RcsBundleInfo> bundleList = containerInstance.listBundles();
-        if (1 == bundleList.size()) {
-            logMessage = "BMI Bundle not added" + "\n";
+        if (!bundleExists(bundle.mBundleId))
+            logMessage = "Bundle \'" + bundle.mBundleId + "\' not added" + "\n";
 
-        } else {
+        else {
+            containerInstance.removeBundle(bundle.mBundleId);
 
-            for (int i = 0; i < 2; i++) {
-                containerInstance.removeBundle("oic.bundle.BMISensor");
-            }
-            startBundleFlag = false;
+            bundle.isStarted = false;
             logMessage = "bundle to remove : " + "\n";
-            logMessage = logMessage + "ID :" + "oic.bundle.BMISensor" + "\n\n";
+            logMessage = logMessage + "ID : " + bundle.mBundleId + "\n\n";
             logMessage = logMessage + " bundle removed  successfully" + "\n";
         }
+
         ResourceContainerActivity.setMessageLog(logMessage);
         msg = Message.obtain();
         msg.what = 1;
         resourceContainerActivityInstance.getHandler().sendMessage(msg);
     }
 
-    // Start Bundle BMI
-    public void startBMIBundle() {
+    // start Bundles
+    public void startBundle(BundleInformation bundle) {
 
-        List<RcsBundleInfo> bundleList = containerInstance.listBundles();
-        if (1 == bundleList.size()) {
-            logMessage = "BMI bundle not added" + "\n";
-        } else if (true == startBundleFlag) {
-            logMessage = "Bundle already started" + "\n";
+        if (!bundleExists(bundle.mBundleId)) {
+            logMessage = "Bundle \'" + bundle.mBundleId + "\' not added" + "\n";
+        } else if (bundle.isStarted) {
+            logMessage = "Bundle \'" + bundle.mBundleId + "\' already started" + "\n";
         } else {
-            startBundleFlag = true;
-            containerInstance.startBundle("oic.bundle.BMISensor");
+            bundle.isStarted = true;
+            containerInstance.startBundle(bundle.mBundleId);
 
             logMessage = " bundle to start" + "\n";
-            logMessage += " ID : oic.bundle.BMISensor" + "\n\n";
+            logMessage += " ID : " + bundle.mBundleId + "\n\n";
             logMessage += " bundle started successfully" + "\n";
         }
-        ResourceContainerActivity.setMessageLog(logMessage);
-        msg = Message.obtain();
-        msg.what = 1;
-        resourceContainerActivityInstance.getHandler().sendMessage(msg);
-    }
-
-    // Stop Bundle BMI
-    public void stopBMIBundle() {
-
-        if (false == startBundleFlag) {
-            logMessage = "Bundle is not Started" + "\n";
-        } else {
-
-            List<RcsBundleInfo> bundleList = containerInstance.listBundles();
-            if (0 == bundleList.size()) {
-                logMessage = "No bundle to Stop" + "\n";
-
-            } else {
-                containerInstance.stopBundle("oic.bundle.BMISensor");
-                startBundleFlag = false;
-                logMessage = " bundle to stop" + "\n";
-                logMessage = logMessage + " ID : oic.bundle.BMISensor" + "\n\n";
-                logMessage = logMessage + " bundle stopped successfully" + "\n";
-            }
-        }
 
         ResourceContainerActivity.setMessageLog(logMessage);
         msg = Message.obtain();
@@ -256,145 +253,67 @@ public class ResourceContainer {
         resourceContainerActivityInstance.getHandler().sendMessage(msg);
     }
 
-    // Add Resource Configuration DI
-    public void addDIResourceConfig() {
-
-        List<RcsBundleInfo> bundleList = containerInstance.listBundles();
-        List<String> bundleResources = containerInstance
-                .listBundleResources("oic.bundle.discomfortIndexSensor");
-
-        if (0 == bundleList.size()) {
-            logMessage = "No bundle found" + "\n";
-        } else if ((0 == bundleList.size()) && (0 == bundleResources.size())) {
+    // Stop Bundles
+    public void stopBundle(BundleInformation bundle) {
 
-            logMessage = "No bundle found" + "\n";
-        } else {
-
-            Map<String, String> params = new HashMap<String, String>();
-            params.put("resourceType", "oic.r.sensor");
-            params.put("address",
-                    "http://192.168.0.2/api/newdeveloper/sensor/22");
-            containerInstance.addResourceConfig(
-                    "oic.bundle.discomfortIndexSensor", "", params);
-            logMessage = "resource added successfully" + "\n";
+        if (!bundleExists(bundle.mBundleId)) {
+            logMessage = "Bundle \'" + bundle.mBundleId + "\' not added" + "\n";
         }
-        ResourceContainerActivity.setMessageLog(logMessage);
-        msg = Message.obtain();
-        msg.what = 1;
-        resourceContainerActivityInstance.getHandler().sendMessage(msg);
-    }
-
-    // Remove Resource Configuration DI
-    public void removeDIResourceConfig() {
-
-        List<String> bundleResources = containerInstance
-                .listBundleResources("oic.bundle.discomfortIndexSensor");
-        if (bundleResources.size() >= 1) {
-            String element = bundleResources.get(0);
-            containerInstance.removeResourceConfig(
-                    "oic.bundle.discomfortIndexSensor", element);
-            Message msg;
-            logMessage = "resource removed successfully: \n" + element + "\n";
-            ResourceContainerActivity.setMessageLog(logMessage);
-            msg = Message.obtain();
-            msg.what = 1;
-            resourceContainerActivityInstance.getHandler().sendMessage(msg);
-        } else {
-            logMessage = "No resource to remove" + "\n";
-            ResourceContainerActivity.setMessageLog(logMessage);
-            msg = Message.obtain();
-            msg.what = 1;
-            resourceContainerActivityInstance.getHandler().sendMessage(msg);
-        }
-    }
-
-    // Add Resource Configuration BMI
-    public void addBMIResourceConfig() {
-
-        if (false == startBundleFlag) {
-            logMessage = "Bundle is not started" + "\n";
+        else if (!bundle.isStarted) {
+            logMessage = "Bundle \'" + bundle.mBundleId + "\' is not Started" + "\n";
         } else {
-            List<RcsBundleInfo> bundleList = containerInstance.listBundles();
-            List<String> bundleResources = containerInstance
-                    .listBundleResources("oic.bundle.BMISensor");
-
-            if (0 == bundleList.size()) {
-                logMessage = "No bundle found" + "\n";
-            } else if ((0 == bundleList.size())
-                    && (0 == bundleResources.size())) {
-
-                logMessage = "No bundle found" + "\n";
-            } else {
-
-                Map<String, String> params = new HashMap<String, String>();
-                params.put("resourceType", "oic.r.sensor");
-                params.put("address",
-                        "http://192.168.0.2/api/newdeveloper/sensor/22");
-                containerInstance.addResourceConfig("oic.bundle.BMISensor", "",
-                        params);
-                logMessage = "resource added successfully" + "\n";
-            }
+            containerInstance.stopBundle(bundle.mBundleId);
+            bundle.isStarted = false;
+            logMessage = " bundle to stop" + "\n";
+            logMessage = logMessage + " ID : " + bundle.mBundleId  + "\n\n";
+            logMessage = logMessage + " bundle stopped successfully" + "\n";
         }
-        ResourceContainerActivity.setMessageLog(logMessage);
-        msg = Message.obtain();
-        msg.what = 1;
-        resourceContainerActivityInstance.getHandler().sendMessage(msg);
-    }
-
-    // Remove Resource Configuration BMI
-    public void removeBMIResourceConfig() {
-
-        if (false == startBundleFlag) {
-            logMessage = "Bundle is not started" + "\n";
 
-        } else {
-            List<String> bundleResources = containerInstance
-                    .listBundleResources("oic.bundle.BMISensor");
-            if (bundleResources.size() >= 1) {
-                String element = bundleResources.get(0);
-                containerInstance.removeResourceConfig("oic.bundle.BMISensor",
-                        element);
-                Message msg;
-                logMessage = "resource removed successfully: \n" + element
-                        + "\n";
-
-            } else {
-                logMessage = "No resource to remove" + "\n";
-            }
-        }
         ResourceContainerActivity.setMessageLog(logMessage);
         msg = Message.obtain();
         msg.what = 1;
         resourceContainerActivityInstance.getHandler().sendMessage(msg);
     }
+}
 
-    // List Bundle Resources
-    public void listBMIBundleResources() {
-
-        if (false == startBundleFlag) {
-            logMessage = "Bundle is not started" + "\n";
-
-        } else {
-            List<String> bundleResources = containerInstance
-                    .listBundleResources("oic.bundle.BMISensor");
-            Iterator<String> it = bundleResources.iterator();
-            logMessage = "";
-
-            if (0 == bundleResources.size()) {
-                logMessage = logMessage + "No resource found in the bundle"
-                        + "\n";
-            } else {
-                while (it.hasNext()) {
-                    String element = (String) it.next();
-                    logMessage = logMessage + element + "\n";
-                }
-            }
-
-        }
-        ResourceContainerActivity.setMessageLog(logMessage);
-        msg = Message.obtain();
-        msg.what = 1;
-        resourceContainerActivityInstance.getHandler().sendMessage(msg);
-    }
+class ExampleBundleDescription
+{
+    static final BundleInformation BMIBundle =
+            new BundleInformation ("oic.bundle.BMISensor", "",
+                    "/data/data/org.iotivity.service.sample.resourcecontainer/files/" +
+                            "libBMISensorBundle.so",
+                    "bmisensor", new HashMap<String, String>());
+
+    static final BundleInformation DIBundle =
+            new BundleInformation ("oic.bundle.discomfortIndexSensor", "",
+                    "/data/data/org.iotivity.service.sample.resourcecontainer/files/" +
+                            "libDISensorBundle.so",
+                    "disensor", new HashMap<String, String>());
+
+    static final BundleInformation DIAndroidBundle =
+            new BundleInformation ("oic.android.sample", "",
+                    "org.iotivity.service.sample.androidbundle.apk",
+                    "org.iotivity.service.sample.androidbundle.SampleActivator",
+                    new HashMap<String, String>());
 }
 
+class BundleInformation
+{
+    String mBundleId;
+    String mBundleUri;
+    String mBundlePath;
+    String mActivator;
+    Map<String, String> mBundleParams;
+
+    Boolean isStarted;
+
+    public BundleInformation(String id, String uri, String path, String activator, Map<String, String> params)
+    {
+        mBundleId = id;
+        mBundleUri = uri;
+        mBundlePath = path;
+        mActivator = activator;
+        mBundleParams = params;
+        isStarted = false;
+    }
+}
\ No newline at end of file
old mode 100644 (file)
new mode 100755 (executable)
index 7da5645..51e78fe
@@ -60,12 +60,10 @@ import java.util.List;
  * for updating UI.
  */
 public class ResourceContainerActivity extends Activity {
-    // private static final String LOG_TAG =
-    // ResourceContainerActivity.class.getSimpleName();
 
-    private final String                     LOG_TAG = "[ContainerSampleApp] "
-                                                             + this.getClass()
-                                                                     .getSimpleName();
+    private final String                     LOG_TAG = "[RCSampleServerApp] "
+            + this.getClass()
+            .getSimpleName();
     private static ResourceContainerActivity resourceContainerActivityInstance;
     private ResourceContainer                resourceContainerInstance;
     private static String                    logMessage;
@@ -73,9 +71,12 @@ public class ResourceContainerActivity extends Activity {
     private Context                          context;
     public ExpandableListAdapter             listAdapter;
     public ExpandableListView                expListView;
+    private int lastExpandedPosition = -1;
+
     public List<String>                      sensors;
     public List<String>                      diApiList;
     public List<String>                      bmiApiList;
+    public List<String>                      diAndroidApiList;
     HashMap<String, List<String>>            listChild;
 
     private static Handler                   mHandler;
@@ -98,10 +99,10 @@ public class ResourceContainerActivity extends Activity {
         super.onCreate(savedInstanceState);
         context = this;
 
-        if (!isWifiConnected()) {
+        /*if (!isWifiConnected()) {
             showWifiUnavailableDialog();
             return;
-        }
+        }*/
 
         configurePlatform();
         CopyAssetsToSDCard();
@@ -118,30 +119,40 @@ public class ResourceContainerActivity extends Activity {
         logs = (EditText) findViewById(R.id.log);
 
         sensors = new ArrayList<String>();
-        diApiList = new ArrayList<String>();
         bmiApiList = new ArrayList<String>();
+        diApiList = new ArrayList<String>();
+        diAndroidApiList = new ArrayList<String>();
         listChild = new HashMap<String, List<String>>();
 
         // Adding list items (header)
-        sensors.add("Discomfort Index Sensor");
         sensors.add("BMI Sensor");
-
-        // Adding child data [discomfort Index sensor]
-        diApiList.add("1. List bundle resources");
-        diApiList.add("2. Add Resource");
-        diApiList.add("3. Remove Resource");
+        sensors.add("Discomfort Index Sensor");
+        sensors.add("Android Discomfort Index Sensor");
 
         // Adding child data [BMI sensor]
-        bmiApiList.add("1. Add Bundle");
-        bmiApiList.add("2. Start Bundle");
+        bmiApiList.add("1. Add BMI sensor bundle");
+        bmiApiList.add("2. Start BMI sensor bundle");
         bmiApiList.add("3. List bundle resources");
-        bmiApiList.add("4. Add Resource ");
-        bmiApiList.add("5. Remove Resource");
-        bmiApiList.add("6. Stop Bundle");
-        bmiApiList.add("7. Remove Bundle");
+        bmiApiList.add("4. Stop BMI sensor bundle");
+        bmiApiList.add("5. Remove BMI sensor bundle");
 
-        listChild.put(sensors.get(0), diApiList);
-        listChild.put(sensors.get(1), bmiApiList);
+        // Adding child data [discomfort Index sensor]
+        diApiList.add("1. Add DI sensor bundle");
+        diApiList.add("2. Start DI sensor bundle");
+        diApiList.add("3. List bundle resources");
+        diApiList.add("4. Stop DI sensor bundle");
+        diApiList.add("5. Remove DI sensor bundle");
+
+        // Adding child data [discomfort Index sensor - android]
+        diAndroidApiList.add("1. Add Android DI sensor bundle");
+        diAndroidApiList.add("2. Start Android DI sensor bundle");
+        diAndroidApiList.add("3. List bundle resources");
+        diAndroidApiList.add("4. Stop Android DI sensor bundle");
+        diAndroidApiList.add("5. Remove Android DI sensor bundle");
+
+        listChild.put(sensors.get(0), bmiApiList);
+        listChild.put(sensors.get(1), diApiList);
+        listChild.put(sensors.get(2), diAndroidApiList);
         listAdapter = new ExpandableList(this, sensors, listChild);
 
         // getting the sd card path
@@ -204,46 +215,70 @@ public class ResourceContainerActivity extends Activity {
             }
         });
 
-        // Listener for the expandable list
+
+        expListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
+            @Override
+            public void onGroupExpand(int groupPosition) {
+                if (lastExpandedPosition != -1
+                        && groupPosition != lastExpandedPosition) {
+                    expListView.collapseGroup(lastExpandedPosition);
+                }
+                lastExpandedPosition = groupPosition;
+            }
+        });
+
         expListView
                 .setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
 
                     @Override
                     public boolean onChildClick(ExpandableListView parent,
-                            View v, int groupPosition, int childPosition,
-                            long id) {
+                                                View v, int groupPosition, int childPosition,
+                                                long id) {
+                        BundleInformation bundleToTest;
 
-                        if (0 == groupPosition) {
-                            if (childPosition == 0) {
-                                resourceContainerInstance
-                                        .listDIBundleResources();
-                            } else if (childPosition == 1) {
-                                resourceContainerInstance.addDIResourceConfig();
-                            } else if (childPosition == 2) {
-                                resourceContainerInstance
-                                        .removeDIResourceConfig();
-                            }
-                        } else {
-                            if (childPosition == 0) {
-                                resourceContainerInstance.addBMIBundle();
-                            } else if (childPosition == 1) {
-                                resourceContainerInstance.startBMIBundle();
-                            } else if (childPosition == 2) {
-                                resourceContainerInstance
-                                        .listBMIBundleResources();
-                            } else if (childPosition == 3) {
-                                resourceContainerInstance
-                                        .addBMIResourceConfig();
-                            } else if (childPosition == 4) {
+                        switch (groupPosition) {
+                            case 0:
+                                bundleToTest = ExampleBundleDescription.BMIBundle;
+                                break;
+
+                            case 1:
+                                bundleToTest = ExampleBundleDescription.DIBundle;
+                                break;
+
+                            case 2:
+                                bundleToTest = ExampleBundleDescription.DIAndroidBundle;
+                                break;
+
+                            default:
+                                return false;
+                        }
+
+                        switch (childPosition) {
+                            case 0:
+                                resourceContainerInstance.addBundle(bundleToTest);
+                                break;
+
+                            case 1:
+                                resourceContainerInstance.startBundle(bundleToTest);
+                                break;
+
+                            case 2:
                                 resourceContainerInstance
-                                        .removeBMIResourceConfig();
-                            } else if (childPosition == 5) {
-                                resourceContainerInstance.stopBMIBundle();
-                            } else if (childPosition == 6) {
-                                resourceContainerInstance.removeBMIBundle();
-                            }
+                                        .listBundleResources(bundleToTest.mBundleId);
+                                break;
+
+                            case 3:
+                                resourceContainerInstance.stopBundle(bundleToTest);
+                                break;
+
+                            case 4:
+                                resourceContainerInstance.removeBundle(bundleToTest);
+                                break;
+
+                            default:
+                                return false;
                         }
-                        return false;
+                        return true;
                     }
                 });
     }
@@ -305,7 +340,7 @@ public class ResourceContainerActivity extends Activity {
 
         // constructor
         public ExpandableList(Context context, List<String> dataHeader,
-                HashMap<String, List<String>> childData) {
+                              HashMap<String, List<String>> childData) {
             this.mContext = context;
             this.mListDataHeader = dataHeader;
             this.mListDataChild = childData;
@@ -327,7 +362,7 @@ public class ResourceContainerActivity extends Activity {
         // get Group View
         @Override
         public View getGroupView(int grpPosition, boolean isExpandable,
-                View changeView, ViewGroup head) {
+                                 View changeView, ViewGroup head) {
             String mainHeading = (String) getGroup(grpPosition);
             if (changeView == null) {
                 LayoutInflater flater;
@@ -373,7 +408,7 @@ public class ResourceContainerActivity extends Activity {
         // get Group View
         @Override
         public View getChildView(int grpPosition, final int childPosition,
-                boolean isLastItem, View changeView, ViewGroup head) {
+                                 boolean isLastItem, View changeView, ViewGroup head) {
 
             final String innerText = (String) getChild(grpPosition,
                     childPosition);
old mode 100644 (file)
new mode 100755 (executable)
index 50456c4..423709a
@@ -1,7 +1,8 @@
 <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
-    android:layout_height="match_parent" >
+    android:layout_height="match_parent"
+    android:padding="5dp">
 
     <Button
         android:id="@+id/startContainer"
@@ -33,6 +34,8 @@
         android:layout_alignParentLeft="true"
         android:layout_below="@id/lvExp"
         android:editable="false"
-        android:ems="10" />
+        android:ems="10"
+        android:background="#32437200"
+        android:padding="10dp" />
 
 </RelativeLayout>
old mode 100644 (file)
new mode 100755 (executable)
index 34a7ef9..2d39d08
@@ -2,10 +2,12 @@
 
 buildscript {
     repositories {
-        jcenter()
+        maven{
+            url "http://jcenter.bintray.com/"
+        }
     }
     dependencies {
-        classpath 'com.android.tools.build:gradle:1.0.0'
+        classpath 'com.android.tools.build:gradle:1.3.0'
 
         // NOTE: Do not place your application dependencies here; they belong
         // in the individual module build.gradle files
@@ -14,10 +16,14 @@ buildscript {
 
 allprojects {
     repositories {
-        jcenter()
+        maven{
+            url "http://jcenter.bintray.com/"
+        }
 
         flatDir {
             dirs 'libs'
         }
     }
 }
+
+
diff --git a/service/resource-container/examples/android/RCSampleServerApp/gradlew b/service/resource-container/examples/android/RCSampleServerApp/gradlew
new file mode 100755 (executable)
index 0000000..91a7e26
--- /dev/null
@@ -0,0 +1,164 @@
+#!/usr/bin/env bash
+
+##############################################################################
+##
+##  Gradle start up script for UN*X
+##
+##############################################################################
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn ( ) {
+    echo "$*"
+}
+
+die ( ) {
+    echo
+    echo "$*"
+    echo
+    exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+case "`uname`" in
+  CYGWIN* )
+    cygwin=true
+    ;;
+  Darwin* )
+    darwin=true
+    ;;
+  MINGW* )
+    msys=true
+    ;;
+esac
+
+# For Cygwin, ensure paths are in UNIX format before anything is touched.
+if $cygwin ; then
+    [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
+fi
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+    ls=`ls -ld "$PRG"`
+    link=`expr "$ls" : '.*-> \(.*\)$'`
+    if expr "$link" : '/.*' > /dev/null; then
+        PRG="$link"
+    else
+        PRG=`dirname "$PRG"`"/$link"
+    fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >&-
+APP_HOME="`pwd -P`"
+cd "$SAVED" >&-
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+        # IBM's JDK on AIX uses strange locations for the executables
+        JAVACMD="$JAVA_HOME/jre/sh/java"
+    else
+        JAVACMD="$JAVA_HOME/bin/java"
+    fi
+    if [ ! -x "$JAVACMD" ] ; then
+        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+    fi
+else
+    JAVACMD="java"
+    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
+    MAX_FD_LIMIT=`ulimit -H -n`
+    if [ $? -eq 0 ] ; then
+        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+            MAX_FD="$MAX_FD_LIMIT"
+        fi
+        ulimit -n $MAX_FD
+        if [ $? -ne 0 ] ; then
+            warn "Could not set maximum file descriptor limit: $MAX_FD"
+        fi
+    else
+        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+    fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+    APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+
+    # We build the pattern for arguments to be converted via cygpath
+    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+    SEP=""
+    for dir in $ROOTDIRSRAW ; do
+        ROOTDIRS="$ROOTDIRS$SEP$dir"
+        SEP="|"
+    done
+    OURCYGPATTERN="(^($ROOTDIRS))"
+    # Add a user-defined pattern to the cygpath arguments
+    if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+    fi
+    # Now convert the arguments - kludge to limit ourselves to /bin/sh
+    i=0
+    for arg in "$@" ; do
+        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option
+
+        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition
+            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+        else
+            eval `echo args$i`="\"$arg\""
+        fi
+        i=$((i+1))
+    done
+    case $i in
+        (0) set -- ;;
+        (1) set -- "$args0" ;;
+        (2) set -- "$args0" "$args1" ;;
+        (3) set -- "$args0" "$args1" "$args2" ;;
+        (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+        (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+        (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+        (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+        (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+        (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+    esac
+fi
+
+# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
+function splitJvmOpts() {
+    JVM_OPTS=("$@")
+}
+eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
+JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
+
+exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
diff --git a/service/resource-container/examples/android/RCSampleServerApp/gradlew.bat b/service/resource-container/examples/android/RCSampleServerApp/gradlew.bat
new file mode 100755 (executable)
index 0000000..8a0b282
--- /dev/null
@@ -0,0 +1,90 @@
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem  Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS=
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto init
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto init
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:init
+@rem Get command-line arguments, handling Windowz variants
+
+if not "%OS%" == "Windows_NT" goto win9xME_args
+if "%@eval[2+2]" == "4" goto 4NT_args
+
+:win9xME_args
+@rem Slurp the command line arguments.
+set CMD_LINE_ARGS=
+set _SKIP=2
+
+:win9xME_args_slurp
+if "x%~1" == "x" goto execute
+
+set CMD_LINE_ARGS=%*
+goto execute
+
+:4NT_args
+@rem Get arguments from the 4NT Shell from JP Software
+set CMD_LINE_ARGS=%$
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if  not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
index 3dfc9a9..9938053 100644 (file)
@@ -6,11 +6,11 @@
         <activator>huesample</activator>
         <version>1.0.0</version>
         <resources>
-            <resourceInfo>
-                <name>light</name>
-                <resourceType>oic.r.control</resourceType>
-                <address>http://192.168.0.2/api/newdeveloper/lights/1</address>
-            </resourceInfo>
+            
         </resources>
-    </bundle>
+    </bundle>       
 </container>
+
+
+
+
index eb5572b..64652d5 100644 (file)
@@ -528,18 +528,6 @@ void *showContainerAPIs(void *data)
         elm_list_item_append(listnew, "4. Remove HUE Bundle Resource", NULL, NULL,
                              removeHueResourceConfig, NULL);
 
-        elm_list_item_append(listnew, "5. Add BMI Bundle", NULL, NULL,
-                             addBMIBundle, NULL);
-
-        elm_list_item_append(listnew, "6. Start BMI Bundle", NULL, NULL,
-                             startBMIBundle, NULL);
-
-        elm_list_item_append(listnew, "7. Remove BMI Bundle", NULL, NULL,
-                             removeBMIBundle, NULL);
-
-        elm_list_item_append(listnew, "8. Stop BMI Bundle", NULL, NULL,
-                             stopBMIBundle, NULL);
-
         elm_list_go(listnew);
     }
     return NULL;
@@ -593,8 +581,8 @@ static void stopContainer(void *data, Evas_Object *obj, void *event_info)
     if (checkContainer)
     {
         s_containerFlag = false;
-        removeHueBundle(NULL, NULL, NULL);
         stopHueBundle(NULL, NULL, NULL);
+        removeHueBundle(NULL, NULL, NULL);
 
         container->stopContainer();
         logMessage += "CONTAINER STOPPED<br>";
index 31d2902..3a11445 100644 (file)
@@ -82,8 +82,16 @@ namespace OIC
                 */
                 virtual const std::string &getVersion() = 0;
 
-                RCSBundleInfo();
-                virtual ~RCSBundleInfo();
+                /**
+                * API for getting the activation status of the bundle
+                *
+                * @return activation status of the bundle
+                *
+                */
+                virtual bool isActivated() = 0;
+
+                RCSBundleInfo(){};
+                virtual ~RCSBundleInfo(){};
             protected:
                 std::string m_ID, m_path, m_version;
 
diff --git a/service/resource-container/src/AndroidBundleResource.h b/service/resource-container/src/AndroidBundleResource.h
new file mode 100644 (file)
index 0000000..c0b074e
--- /dev/null
@@ -0,0 +1,67 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef ANDROIDBUNDLERESOURCE_H_
+#define ANDROIDBUNDLERESOURCE_H_
+
+#include <map>
+#include <vector>
+#include <string>
+#include <jni.h>
+#include "BundleResource.h"
+#include "ResourceContainerImpl.h"
+
+using namespace std;
+
+namespace OIC
+{
+    namespace Service
+    {
+        class JavaBundleResource: public BundleResource
+        {
+        public:
+            JavaBundleResource();
+            JavaBundleResource(JNIEnv *env, jobject obj, jobject bundleResource, string bundleId,
+                    jobjectArray attributes);
+            virtual ~JavaBundleResource();
+
+            void handleSetAttributeRequest(const std::string& key,
+                    RCSResourceAttributes::Value&&);
+
+            RCSResourceAttributes::Value handleGetAttributeRequest(const std::string& key);
+
+            virtual void handleSetAttributesRequest(RCSResourceAttributes &attrs);
+
+            virtual RCSResourceAttributes& handleGetAttributesRequest();
+
+            virtual void initAttributes();
+        private:
+            // needs to be a GlobalRef
+            jobject m_bundleResource;
+            jobjectArray m_attributes;
+            jclass m_bundleResourceClass;
+            jmethodID m_attributeSetRequestHandler;
+            jmethodID m_attributeGetRequestHandler;
+            string m_bundleId;
+        };
+    }
+}
+
+#endif
index e5cf71c..c4533ba 100644 (file)
@@ -30,9 +30,9 @@ std::map< string, BundleResource::Ptr > java_resources;
 /*
  * Class:     org_iotivity_resourcecontainer_bundle_api_BaseActivator
  * Method:    registerJavaResource
- * Signature: (Lorg/iotivity/resourcecontainer/bundle/api/BundleResource;[Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V
+ * Signature: (Lorg/iotivity/resourcecontainer/bundle/api/BundleResource;[Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)I
  */
-JNIEXPORT void JNICALL
+JNIEXPORT jint JNICALL
 Java_org_iotivity_resourcecontainer_bundle_api_BaseActivator_registerJavaResource
 (JNIEnv *env, jobject obj, jobject bundleResource, jobjectArray attributes, jstring bundleId,
  jstring uri, jstring resourceType, jstring res_name)
@@ -41,6 +41,7 @@ Java_org_iotivity_resourcecontainer_bundle_api_BaseActivator_registerJavaResourc
     const char *str_uri = env->GetStringUTFChars(uri, 0);
     const char *str_resourceType = env->GetStringUTFChars(resourceType, 0);
     const char *str_res_name = env->GetStringUTFChars(res_name, 0);
+    int ret;
 
     BundleResource::Ptr javaBundleResource = std::make_shared< JavaBundleResource >
             (env, obj, bundleResource, str_bundleId, attributes);
@@ -49,9 +50,11 @@ Java_org_iotivity_resourcecontainer_bundle_api_BaseActivator_registerJavaResourc
     javaBundleResource->m_uri = string(str_uri, strlen(str_uri));
     javaBundleResource->m_resourceType = string(str_resourceType, strlen(str_resourceType));
     javaBundleResource->m_name = string(str_res_name, strlen(str_res_name));
-    container->registerResource(javaBundleResource);
+    ret = container->registerResource(javaBundleResource);
 
     java_resources[str_uri] = javaBundleResource;
+
+    return ret;
 }
 
 /*
@@ -120,4 +123,4 @@ Java_org_iotivity_resourcecontainer_bundle_api_BaseActivator_getConfiguredResour
     env->SetObjectArrayElement(ret, 3, env->NewStringUTF(conf.address.c_str()));
     return ret;
 }
-#endif
\ No newline at end of file
+#endif
diff --git a/service/resource-container/src/BundleActivator.cpp b/service/resource-container/src/BundleActivator.cpp
deleted file mode 100644 (file)
index f2f17ea..0000000
+++ /dev/null
@@ -1,53 +0,0 @@
-//******************************************************************
-//
-// 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 "BundleActivator.h"
-#include "RCSResourceContainer.h"
-
-using namespace OIC::Service;
-
-namespace OIC
-{
-    namespace Service
-    {
-        BundleActivator::BundleActivator()
-        {
-
-        }
-
-        BundleActivator::~BundleActivator()
-        {
-
-        }
-
-        void BundleActivator::activateBundle(ResourceContainerBundleAPI *resourceContainer,
-                std::string bundleId)
-        {
-            (void)(resourceContainer);
-            (void)(bundleId);
-        }
-
-        void BundleActivator::deactivateBundle()
-        {
-
-        }
-    }
-}
-
index 6adef62..a15ae9c 100644 (file)
@@ -32,6 +32,7 @@ namespace OIC
             m_resourceCreator = nullptr;
             m_resourceDestroyer = nullptr;
             m_bundleHandle = nullptr;
+            m_so_bundle = nullptr;
 
             m_loaded = false;
             m_activated = false;
@@ -157,6 +158,16 @@ namespace OIC
             return m_java_bundle;
         }
 
+        void BundleInfoInternal::setSoBundle(bool soBundle)
+        {
+            m_so_bundle = soBundle;
+        }
+
+        bool BundleInfoInternal::getSoBundle()
+        {
+            return m_so_bundle;
+        }
+
         void BundleInfoInternal::setActivatorName( const std::string &activatorName)
         {
             m_activator_name = activatorName;
@@ -209,9 +220,11 @@ namespace OIC
         }
 #endif
 
-        void BundleInfoInternal::setBundleInfo(RCSBundleInfo *bundleInfo)
+        void BundleInfoInternal::setBundleInfo(shared_ptr<RCSBundleInfo> bundleInfo)
         {
-            BundleInfoInternal *source = (BundleInfoInternal *)bundleInfo;
+            shared_ptr<BundleInfoInternal> source =
+                                std::static_pointer_cast<BundleInfoInternal>(bundleInfo);
+
             m_ID = source->getID();
             m_path = source->getPath();
             m_version = source->getVersion();
@@ -220,6 +233,7 @@ namespace OIC
             m_java_bundle = source->getJavaBundle();
             m_activator = source->getBundleActivator();
             m_bundleHandle = source->getBundleHandle();
+            m_activator_name = source->getActivatorName();
         }
     }
 }
index 13337bf..1dbe4fd 100644 (file)
@@ -77,7 +77,7 @@ namespace OIC
                 void setResourceDestroyer(resourceDestroyer_t *);
                 resourceDestroyer_t *getResourceDestroyer();
 
-                void setBundleInfo(RCSBundleInfo *bundleInfo);
+                void setBundleInfo(shared_ptr<RCSBundleInfo> bundleInfo);
 
                 void setBundleHandle(void *);
                 void *getBundleHandle();
@@ -85,6 +85,9 @@ namespace OIC
                 void setJavaBundle(bool javaBundle);
                 bool getJavaBundle();
 
+                void setSoBundle(bool javaBundle);
+                bool getSoBundle();
+
 #if (JAVA_SUPPORT)
                 void setJavaBundleActivatorMethod(jmethodID activator);
                 jmethodID getJavaBundleActivatorMethod();
@@ -96,7 +99,7 @@ namespace OIC
 #endif
 
             private:
-                bool m_loaded, m_activated, m_java_bundle;
+                bool m_loaded, m_activated, m_java_bundle, m_so_bundle;
                 int m_id;
                 activator_t *m_activator;
                 deactivator_t *m_deactivator;
index 93c255f..f39e77c 100644 (file)
@@ -22,6 +22,9 @@
 
 #include <list>
 #include <string.h>
+#include <iostream>
+#include <boost/thread.hpp>
+#include "NotificationReceiver.h"
 
 #include "InternalTypes.h"
 
@@ -29,9 +32,9 @@ namespace OIC
 {
     namespace Service
     {
-        BundleResource::BundleResource()
+        BundleResource::BundleResource() : m_pNotiReceiver(nullptr), m_resourceAttributes_mutex()
         {
-            m_pNotiReceiver = nullptr;
+
         }
 
         BundleResource::~BundleResource()
@@ -47,51 +50,97 @@ namespace OIC
         std::list< std::string > BundleResource::getAttributeNames()
         {
             std::list< std::string > ret;
-            for (RCSResourceAttributes::iterator it = m_resourceAttributes.begin();
-                 it != m_resourceAttributes.end(); ++it)
-            {
-                ret.push_back(it->key());
+
+            for (auto &it : m_resourceAttributes){
+                ret.push_back(it.key());
             }
+
             return ret;
         }
 
-        RCSResourceAttributes &BundleResource::getAttributes()
+        const RCSResourceAttributes BundleResource::getAttributes()
         {
-            return m_resourceAttributes;
+            std::lock_guard<std::mutex> lock(m_resourceAttributes_mutex);
+            return RCSResourceAttributes(m_resourceAttributes);
         }
 
-        void BundleResource::setAttributes(RCSResourceAttributes &attrs)
+        void BundleResource::setAttributes(const RCSResourceAttributes &attrs)
         {
-            for (RCSResourceAttributes::iterator it = attrs.begin(); it != attrs.end(); ++it)
+            setAttributes(attrs, true);
+        }
+
+        void BundleResource::setAttributes(const RCSResourceAttributes &attrs, bool notify)
+        {
+            std::lock_guard<std::mutex> lock(m_resourceAttributes_mutex);
+
+            for (auto &it : attrs)
             {
-                OC_LOG_V(INFO, CONTAINER_TAG, "set attribute \(%s)'",
-                         std::string(it->key() + "\', with " + it->value().toString()).c_str());
+                OIC_LOG_V(INFO, CONTAINER_TAG, "set attribute \(%s)'",
+                           std::string(it.key() + "\', with " + it.value().toString()).c_str());
+
+                m_resourceAttributes[it.key()] = it.value();
+            }
 
-                m_resourceAttributes[it->key()] = it->value();
+            if(notify){
+                // asynchronous notification
+                auto notifyFunc = [](NotificationReceiver *notificationReceiver,
+                                        std::string uri)
+                {
+                    if (notificationReceiver){
+                        notificationReceiver->onNotificationReceived(uri);
+                    }
+                };
+                auto f = std::bind(notifyFunc, m_pNotiReceiver, m_uri);
+                boost::thread notifyThread(f);
             }
+
         }
 
         void BundleResource::setAttribute(const std::string &key,
                                           RCSResourceAttributes::Value &&value, bool notify)
         {
-            OC_LOG_V(INFO, CONTAINER_TAG, "set attribute \(%s)'", std::string(key + "\', with " +
+            OIC_LOG_V(INFO, CONTAINER_TAG, "set attribute \(%s)'", std::string(key + "\', with " +
                      value.toString()).c_str());
+            std::lock_guard<std::mutex> lock(m_resourceAttributes_mutex);
+            m_resourceAttributes[key] = std::move(value);
+
+            if(notify){
+                // asynchronous notification
+                auto notifyFunc = [](NotificationReceiver *notificationReceiver,
+                                        std::string uri)
+                {
+                    if (notificationReceiver){
+                        notificationReceiver->onNotificationReceived(uri);
+                    }
+                };
+                auto f = std::bind(notifyFunc, m_pNotiReceiver, m_uri);
+                boost::thread notifyThread(f);
+            }
 
-            m_resourceAttributes[key] = value;
+        }
 
-            if (notify && m_pNotiReceiver)
-                m_pNotiReceiver->onNotificationReceived(m_uri);
+        void BundleResource::setAttribute(const std::string &key,
+                                                 RCSResourceAttributes::Value &value, bool notify)
+        {
+            setAttribute(key, RCSResourceAttributes::Value(value), notify);
         }
 
-        void BundleResource::setAttribute(const std::string &key, RCSResourceAttributes::Value &&value)
+        void BundleResource::setAttribute(const std::string &key,
+                RCSResourceAttributes::Value &&value)
         {
             setAttribute(key, std::move(value), true);
         }
 
-        RCSResourceAttributes::Value BundleResource::getAttribute(const std::string &key)
+        void BundleResource::setAttribute(const std::string &key,
+                        RCSResourceAttributes::Value &value)
         {
-            OC_LOG_V(INFO, CONTAINER_TAG, "get attribute \'(%s)" , std::string(key + "\'").c_str());
+            setAttribute(key, value, true);
+        }
 
+        RCSResourceAttributes::Value BundleResource::getAttribute(const std::string &key)
+        {
+            OIC_LOG_V(INFO, CONTAINER_TAG, "get attribute \'(%s)" , std::string(key + "\'").c_str());
+            std::lock_guard<std::mutex> lock(m_resourceAttributes_mutex);
             return m_resourceAttributes.at(key);
         }
     }
index e545c25..c1dd082 100644 (file)
@@ -25,6 +25,7 @@
 #include "InternalTypes.h"
 
 #define CONTAINER_TAG "RESOURCE_CONTAINER"
+#define DISCOVER_TAG "DISCOVER_RESOURCE_UNIT"
 
 namespace OIC
 {
@@ -70,12 +71,15 @@ namespace OIC
 
         bool Configuration::isHasInput(std::string &bundleId) const
         {
+
             try
             {
+                OIC_LOG_V(INFO, CONTAINER_TAG, "isHasInput: (%d) %s",m_mapisHasInput.at(bundleId), bundleId.c_str() );
                 return m_mapisHasInput.at(bundleId);
             }
             catch (std::out_of_range &e)
             {
+                OIC_LOG_V(INFO, CONTAINER_TAG, "isHasInput out of range %s.", bundleId.c_str());
                 return false;
             }
         }
@@ -91,30 +95,34 @@ namespace OIC
             {
                 try
                 {
-                    for (bundle = m_xmlDoc.first_node()->first_node(BUNDLE_TAG); bundle; bundle =
-                             bundle->next_sibling())
+                    bundle = m_xmlDoc.first_node();
+                    if (bundle)
                     {
-                        std::map< std::string, std::string > bundleMap;
-                        for (subItem = bundle->first_node(); subItem;
-                             subItem = subItem->next_sibling())
+                        for (bundle = bundle->first_node(BUNDLE_TAG); bundle; bundle =
+                                 bundle->next_sibling())
                         {
-                            strKey = subItem->name();
-                            strValue = subItem->value();
-
-                            if (strlen(subItem->value()) > 0)
+                            std::map< std::string, std::string > bundleMap;
+                            for (subItem = bundle->first_node(); subItem;
+                                 subItem = subItem->next_sibling())
                             {
-                                bundleMap.insert(
-                                    std::make_pair(trim_both(strKey), trim_both(strValue)));
+                                strKey = subItem->name();
+                                strValue = subItem->value();
+
+                                if (strlen(subItem->value()) > 0)
+                                {
+                                    bundleMap.insert(
+                                        std::make_pair(trim_both(strKey), trim_both(strValue)));
+                                }
                             }
+                            configOutput->push_back(bundleMap);
                         }
-                        configOutput->push_back(bundleMap);
                     }
 
                 }
                 catch (rapidxml::parse_error &e)
                 {
-                    OC_LOG(ERROR, CONTAINER_TAG, "xml parsing failed !!");
-                    OC_LOG_V(ERROR, CONTAINER_TAG, "Exception : (%s)", e.what());
+                    OIC_LOG(ERROR, CONTAINER_TAG, "xml parsing failed !!");
+                    OIC_LOG_V(ERROR, CONTAINER_TAG, "Exception : (%s)", e.what());
                 }
             }
         }
@@ -132,126 +140,288 @@ namespace OIC
                     std::map< std::string, std::string > bundleConfigMap;
 
                     // <bundle>
-                    for (bundle = m_xmlDoc.first_node()->first_node(BUNDLE_TAG); bundle; bundle =
-                             bundle->next_sibling())
+                    bundle = m_xmlDoc.first_node();
+                    if (bundle)
                     {
-                        // <id>
-                        strBundleId = bundle->first_node(BUNDLE_ID)->value();
-
-                        if (!strBundleId.compare(bundleId))
+                        for (bundle = bundle->first_node(BUNDLE_TAG); bundle; bundle =
+                                 bundle->next_sibling())
                         {
-                            bundleConfigMap.insert(std::make_pair(BUNDLE_ID, trim_both(strBundleId)));
+                            // <id>
+                            if (bundle->first_node(BUNDLE_ID))
+                            {
+                                strBundleId = bundle->first_node(BUNDLE_ID)->value();
+                            }
+                            else{
+                                strBundleId = "";
+                            }
 
-                            // <path>
-                            strPath = bundle->first_node(BUNDLE_PATH)->value();
-                            bundleConfigMap.insert(std::make_pair(BUNDLE_PATH, trim_both(strPath)));
+                            if (!strBundleId.compare(bundleId))
+                            {
+                                bundleConfigMap.insert(std::make_pair(BUNDLE_ID, trim_both(strBundleId)));
 
-                            // <version>
-                            strVersion = bundle->first_node(BUNDLE_VERSION)->value();
-                            bundleConfigMap.insert(
-                                std::make_pair(BUNDLE_VERSION, trim_both(strVersion)));
+                                // <path>
+                                if (bundle->first_node(BUNDLE_PATH)){
+                                    strPath = bundle->first_node(BUNDLE_PATH)->value();
+                                }
+                                else{
+                                    strPath = "";
+                                }
+                                bundleConfigMap.insert(std::make_pair(BUNDLE_PATH, trim_both(strPath)));
+
+                                // <version>
+                                if (bundle->first_node(BUNDLE_VERSION)){
+                                    strVersion = bundle->first_node(BUNDLE_VERSION)->value();
+                                }
+                                else{
+                                    strVersion = "";
+                                }
+                                bundleConfigMap.insert(
+                                    std::make_pair(BUNDLE_VERSION, trim_both(strVersion)));
 
-                            configOutput->push_back(bundleConfigMap);
+                                configOutput->push_back(bundleConfigMap);
 
-                            break;
+                                break;
+                            }
                         }
                     }
                 }
                 catch (rapidxml::parse_error &e)
                 {
-                    OC_LOG(ERROR, CONTAINER_TAG, "xml parsing failed !!");
-                    OC_LOG_V(ERROR, CONTAINER_TAG, "Exception (%s)", e.what());
+                    OIC_LOG(ERROR, CONTAINER_TAG, "xml parsing failed !!");
+                    OIC_LOG_V(ERROR, CONTAINER_TAG, "Exception (%s)", e.what());
                 }
             }
         }
 
-        void Configuration::getResourceConfiguration(std::string bundleId,
-                std::vector< resourceInfo > *configOutput)
-        {
+        void Configuration::getResourceConfiguration(std::string bundleId, std::string resourceUri,
+                        resourceInfo *resourceInfoOut){
             rapidxml::xml_node< char > *bundle;
             rapidxml::xml_node< char > *resource;
             rapidxml::xml_node< char > *item, *subItem, *subItem2;
 
             string strBundleId;
             string strKey, strValue;
+            OIC_LOG_V(INFO, CONTAINER_TAG, "Loading resource configuration for %s %s!",
+                bundleId.c_str(), resourceUri.c_str());
 
             if (m_loaded)
             {
                 try
                 {
                     // <bundle>
-                    for (bundle = m_xmlDoc.first_node()->first_node(BUNDLE_TAG); bundle; bundle =
-                             bundle->next_sibling())
+                    bundle = m_xmlDoc.first_node();
+                    if (bundle)
                     {
-                        // <id>
-                        strBundleId = bundle->first_node(BUNDLE_ID)->value();
-
-                        if (!strBundleId.compare(bundleId))
+                        for (bundle = bundle->first_node(BUNDLE_TAG); bundle;
+                            bundle = bundle->next_sibling())
                         {
-                            // <resourceInfo>
-                            for (resource = bundle->first_node(OUTPUT_RESOURCES_TAG)->first_node(OUTPUT_RESOURCE_INFO);
-                                 resource; resource = resource->next_sibling())
+                            // <id>
+                            strBundleId = bundle->first_node(BUNDLE_ID)->value();
+
+                            OIC_LOG_V(INFO, CONTAINER_TAG, "Comparing bundle id %s - %s !",
+                                    strBundleId.c_str(), bundleId.c_str());
+
+                            if (!strBundleId.compare(bundleId))
                             {
-                                resourceInfo tempResourceInfo;
+                                OIC_LOG_V(INFO, CONTAINER_TAG, "Inspecting");
+                                // <resourceInfo>
+                                bundle = bundle->first_node(OUTPUT_RESOURCES_TAG);
+                                if (bundle){
+                                    for (resource = bundle->first_node(OUTPUT_RESOURCE_INFO);
+                                         resource; resource = resource->next_sibling())
+                                    {
 
-                                for (item = resource->first_node(); item; item =
-                                         item->next_sibling())
-                                {
-                                    strKey = item->name();
-                                    strValue = item->value();
+                                        for (item = resource->first_node(); item; item =
+                                                 item->next_sibling())
+                                        {
+                                            strKey = item->name();
+                                            strValue = item->value();
 
-                                    if (!strKey.compare(OUTPUT_RESOURCE_NAME))
-                                        tempResourceInfo.name = trim_both(strValue);
+                                            if (!strKey.compare(OUTPUT_RESOURCE_NAME))
+                                            {
+                                                
+                                                resourceInfoOut->name = trim_both(strValue);
+                                            }
 
-                                    else if (!strKey.compare(OUTPUT_RESOURCE_URI))
-                                        tempResourceInfo.uri = trim_both(strValue);
+                                            else if (!strKey.compare(OUTPUT_RESOURCE_URI))
+                                            {
+                                                if (trim_both(strValue).compare(resourceUri) != 0)
+                                                {
+                                                    break;
+                                                }
+                                                resourceInfoOut->uri = trim_both(strValue);
+                                            }
 
-                                    else if (!strKey.compare(OUTPUT_RESOURCE_ADDR))
-                                        tempResourceInfo.address = trim_both(strValue);
+                                            else if (!strKey.compare(OUTPUT_RESOURCE_ADDR))
+                                                resourceInfoOut->address = trim_both(strValue);
 
-                                    else if (!strKey.compare(OUTPUT_RESOURCE_TYPE))
-                                        tempResourceInfo.resourceType = trim_both(strValue);
+                                            else if (!strKey.compare(OUTPUT_RESOURCE_TYPE))
+                                                resourceInfoOut->resourceType = trim_both(strValue);
 
-                                    else
+                                            else
+                                            {
+                                                for (subItem = item->first_node(); subItem; subItem =
+                                                         subItem->next_sibling())
+                                                {
+                                                    map< string, string > propertyMap;
+
+                                                    strKey = subItem->name();
+
+                                                    if (strKey.compare(INPUT_RESOURCE))
+                                                    {
+                                                        m_mapisHasInput[strBundleId] = true;
+                                                        OIC_LOG_V(INFO, CONTAINER_TAG,
+                                                                "Bundle has input (%s)",
+                                                                strBundleId.c_str());
+                                                    }
+
+                                                    for (subItem2 = subItem->first_node(); subItem2;
+                                                         subItem2 = subItem2->next_sibling())
+                                                    {
+                                                        string newStrKey = subItem2->name();
+                                                        string newStrValue = subItem2->value();
+                                                        OIC_LOG_V(INFO, CONTAINER_TAG,
+                                                                "key: %s, value %s",
+                                                                newStrKey.c_str(), newStrValue.c_str());
+
+                                                        propertyMap[trim_both(newStrKey)] =
+                                                                trim_both(newStrValue);
+                                                    }
+
+                                                    resourceInfoOut->resourceProperty[trim_both(strKey)].push_back(
+                                                        propertyMap);
+                                                }
+                                            }
+                                        }
+
+                                    }
+                                }
+                            }
+                        }
+                    }
+                }
+                catch (rapidxml::parse_error &e)
+                {
+                    OIC_LOG(ERROR, CONTAINER_TAG, "xml parsing failed !!");
+                    OIC_LOG_V(ERROR, CONTAINER_TAG, "Exception (%s)", e.what());
+                }
+            }
+            else{
+                OIC_LOG(INFO, CONTAINER_TAG, "config is not loaded yet !!");
+            }
+        }
+
+        void Configuration::getResourceConfiguration(std::string bundleId,
+                std::vector< resourceInfo > *configOutput)
+        {
+            rapidxml::xml_node< char > *bundle;
+            rapidxml::xml_node< char > *resource;
+            rapidxml::xml_node< char > *item, *subItem, *subItem2;
+
+            string strBundleId;
+            string strKey, strValue;
+            OIC_LOG(INFO, CONTAINER_TAG, "Loading resource configuration!");
+
+            if (m_loaded)
+            {
+                try
+                {
+                    // <bundle>
+                    bundle = m_xmlDoc.first_node();
+                    if (bundle)
+                    {
+                        for (bundle = bundle->first_node(BUNDLE_TAG); bundle; bundle =
+                                 bundle->next_sibling())
+                        {
+                            // <id>
+                            strBundleId = bundle->first_node(BUNDLE_ID)->value();
+
+                            OIC_LOG_V(INFO, CONTAINER_TAG, "Comparing bundle ids %s - %s !",
+                                    strBundleId.c_str(), bundleId.c_str());
+
+                            if (!strBundleId.compare(bundleId))
+                            {
+                                OIC_LOG_V(INFO, CONTAINER_TAG, "Inspecting");
+                                // <resourceInfo>
+                                bundle = bundle->first_node(OUTPUT_RESOURCES_TAG);
+                                if (bundle)
+                                {
+                                    for (resource = bundle->
+                                            first_node(OUTPUT_RESOURCE_INFO);
+                                         resource; resource = resource->next_sibling())
                                     {
-                                        for (subItem = item->first_node(); subItem; subItem =
-                                                 subItem->next_sibling())
+                                        resourceInfo tempResourceInfo;
+
+                                        for (item = resource->first_node(); item; item =
+                                                 item->next_sibling())
                                         {
-                                            map< string, string > propertyMap;
+                                            strKey = item->name();
+                                            strValue = item->value();
 
-                                            strKey = subItem->name();
+                                            if (!strKey.compare(OUTPUT_RESOURCE_NAME))
+                                                tempResourceInfo.name = trim_both(strValue);
 
-                                            if (strKey.compare(INPUT_RESOURCE))
-                                            {
-                                                m_mapisHasInput[strBundleId] = true;
-                                            }
+                                            else if (!strKey.compare(OUTPUT_RESOURCE_URI))
+                                                tempResourceInfo.uri = trim_both(strValue);
 
-                                            for (subItem2 = subItem->first_node(); subItem2;
-                                                 subItem2 = subItem2->next_sibling())
-                                            {
-                                                string newStrKey = subItem2->name();
-                                                string newStrValue = subItem2->value();
+                                            else if (!strKey.compare(OUTPUT_RESOURCE_ADDR))
+                                                tempResourceInfo.address = trim_both(strValue);
 
-                                                propertyMap[trim_both(newStrKey)] = trim_both(
-                                                                                        newStrValue);
-                                            }
+                                            else if (!strKey.compare(OUTPUT_RESOURCE_TYPE))
+                                                tempResourceInfo.resourceType = trim_both(strValue);
 
-                                            tempResourceInfo.resourceProperty[trim_both(strKey)].push_back(
-                                                propertyMap);
+                                            else
+                                            {
+                                                for (subItem = item->first_node(); subItem; subItem =
+                                                         subItem->next_sibling())
+                                                {
+                                                    map< string, string > propertyMap;
+
+                                                    strKey = subItem->name();
+
+                                                    if (strKey.compare(INPUT_RESOURCE))
+                                                    {
+                                                        m_mapisHasInput[strBundleId] = true;
+                                                        OIC_LOG_V(INFO, CONTAINER_TAG,
+                                                                "Bundle has input (%s)",
+                                                                strBundleId.c_str());
+                                                    }
+
+                                                    for (subItem2 = subItem->first_node(); subItem2;
+                                                         subItem2 = subItem2->next_sibling())
+                                                    {
+                                                        string newStrKey = subItem2->name();
+                                                        string newStrValue = subItem2->value();
+                                                        OIC_LOG_V(INFO, CONTAINER_TAG,
+                                                                "key: %s, value %s",
+                                                                newStrKey.c_str(),
+                                                                newStrValue.c_str());
+
+                                                        propertyMap[trim_both(newStrKey)] =
+                                                                trim_both(newStrValue);
+                                                    }
+
+                                                    tempResourceInfo.resourceProperty[trim_both(strKey)].
+                                                    push_back(propertyMap);
+                                                }
+                                            }
                                         }
+                                        configOutput->push_back(tempResourceInfo);
                                     }
                                 }
-                                configOutput->push_back(tempResourceInfo);
                             }
                         }
                     }
                 }
                 catch (rapidxml::parse_error &e)
                 {
-                    OC_LOG(ERROR, CONTAINER_TAG, "xml parsing failed !!");
-                    OC_LOG_V(ERROR, CONTAINER_TAG, "Exception (%s)", e.what());
+                    OIC_LOG(ERROR, CONTAINER_TAG, "xml parsing failed !!");
+                    OIC_LOG_V(ERROR, CONTAINER_TAG, "Exception (%s)", e.what());
                 }
             }
+            else{
+                OIC_LOG(INFO, CONTAINER_TAG, "config is not loaded yet !!");
+            }
         }
 
         void Configuration::getConfigDocument(std::string pathConfigFile)
@@ -278,14 +448,14 @@ namespace OIC
                 }
                 catch (rapidxml::parse_error &e)
                 {
-                    OC_LOG(ERROR, CONTAINER_TAG, "xml parsing failed !!");
-                    OC_LOG_V(ERROR, CONTAINER_TAG, "Exception (%s)", e.what());
+                    OIC_LOG(ERROR, CONTAINER_TAG, "xml parsing failed !!");
+                    OIC_LOG_V(ERROR, CONTAINER_TAG, "Exception (%s)", e.what());
                 }
             }
             else
             {
-                OC_LOG(ERROR, CONTAINER_TAG, "Configuration File load failed !!");
+                OIC_LOG(ERROR, CONTAINER_TAG, "Configuration File load failed !!");
             }
         }
     }
-}
\ No newline at end of file
+}
index 1a39353..ed94470 100644 (file)
@@ -61,6 +61,7 @@ namespace OIC
                 void getConfiguredBundles(configInfo *configOutput);
                 void getBundleConfiguration(string bundleId, configInfo *configOutput);
                 void getResourceConfiguration(string bundleId, vector< resourceInfo > *configOutput);
+                void getResourceConfiguration(string bundleId, string resourceName, resourceInfo *resourceInfoOutput);
 
             private:
                 void getConfigDocument(string pathConfigFile);
index a4ec65c..36c2bc6 100644 (file)
@@ -52,6 +52,8 @@ void DiscoverResourceUnit::startDiscover(DiscoverResourceInfo info, UpdatedCB up
         return;
     }
 
+    OIC_LOG_V(DEBUG, DISCOVER_TAG, "Start discover %s", info.resourceUri.c_str());
+
     m_Uri = info.resourceUri;
     m_ResourceType = info.resourceType;
     m_AttrubuteName = info.attributeName;
@@ -86,14 +88,19 @@ void DiscoverResourceUnit::discoverdCB(RCSRemoteResourceObject::Ptr remoteObject
 {
     if (remoteObject && !isAlreadyDiscoveredResource(remoteObject))
     {
-        RemoteResourceUnit::Ptr newDiscoveredResource =
-            RemoteResourceUnit::createRemoteResourceInfo(remoteObject, pUpdatedCBFromServer);
-
-        if (uri.empty() || uri.compare(remoteObject->getUri()) == 0)
-        {
-            m_vecRemoteResource.push_back(newDiscoveredResource);
-            newDiscoveredResource->startMonitoring();
-            newDiscoveredResource->startCaching();
+        OIC_LOG_V(DEBUG, DISCOVER_TAG, "Discovered - uri: %s", uri.c_str());
+        if (uri.empty() || uri.compare(remoteObject->getUri()) == 0){
+            RemoteResourceUnit::Ptr newDiscoveredResource =
+                       RemoteResourceUnit::createRemoteResourceInfo(remoteObject,
+                               pUpdatedCBFromServer);
+                m_vecRemoteResource.push_back(newDiscoveredResource);
+                newDiscoveredResource->startMonitoring();
+                newDiscoveredResource->startCaching();
+
+            OIC_LOG_V(DEBUG, DISCOVER_TAG, "Created remote resource unit");
+        }
+        else{
+            OIC_LOG_V(DEBUG, DISCOVER_TAG, "URI is not matching - uri: %s", uri.c_str());
         }
     }
     else
index b6635ed..38a440b 100644 (file)
@@ -32,6 +32,7 @@
 #include "RCSRemoteResourceObject.h"
 #include "RCSResourceAttributes.h"
 #include "RemoteResourceUnit.h"
+#include "InternalTypes.h"
 
 namespace OIC
 {
index 580f118..76cc224 100644 (file)
@@ -28,6 +28,7 @@ namespace OIC
     namespace Service
     {
         constexpr char CONTAINER_TAG[] = "RESOURCE_CONTAINER";
+        constexpr char DISCOVER_TAG[] = "DISCOVER_RESOURCE_UNIT";
 
         constexpr char BUNDLE_TAG[] = "bundle";
         constexpr char BUNDLE_ID[] = "id";
index 67e71b1..70f46c9 100644 (file)
@@ -80,19 +80,19 @@ RCSResourceAttributes::Value JavaBundleResource::handleGetAttributeRequest(
     JavaVM *vm = ResourceContainerImpl::getImplInstance()->getJavaVM(m_bundleId);
 
     JNIEnv *env;
-    int envStat = vm->GetEnv((void **) &env, JNI_VERSION_1_4);
+    int envStat = vm->GetEnv(&env, JNI_VERSION_1_4);
 
     if (envStat == JNI_EDETACHED)
     {
-        if (vm->AttachCurrentThread((void **) &env, NULL) != 0)
+        if (vm->AttachCurrentThread(&env, NULL) != 0)
         {
-            OC_LOG_V(ERROR, CONTAINER_TAG,
+            OIC_LOG_V(ERROR, CONTAINER_TAG,
                     "[JavaBundleResource::handleGetAttributeRequest] Failed to attach ");
         }
     }
     else if (envStat == JNI_EVERSION)
     {
-        OC_LOG_V(ERROR, CONTAINER_TAG,
+        OIC_LOG_V(ERROR, CONTAINER_TAG,
                 "[JavaBundleResource::handleGetAttributeRequest] Env: version not supported");
     }
 
@@ -121,13 +121,13 @@ void JavaBundleResource::handleSetAttributeRequest(const std::string &attributeN
     {
         if (vm->AttachCurrentThread((void **) &env, NULL) != 0)
         {
-            OC_LOG_V(ERROR, CONTAINER_TAG,
+            OIC_LOG_V(ERROR, CONTAINER_TAG,
                     "[JavaBundleResource::handleSetAttributeRequest] Failed to attach ");
         }
     }
     else if (envStat == JNI_EVERSION)
     {
-        OC_LOG_V(ERROR, CONTAINER_TAG,
+        OIC_LOG_V(ERROR, CONTAINER_TAG,
                 "[JavaBundleResource::handleSetAttributeRequest] Env: version not supported ");
     }
 
@@ -140,14 +140,14 @@ void JavaBundleResource::handleSetAttributeRequest(const std::string &attributeN
 }
 
 
-void JavaBundleResource::handleSetAttributesRequest(RCSResourceAttributes &attrs){
+void JavaBundleResource::handleSetAttributesRequest(const RCSResourceAttributes &attrs){
     for (RCSResourceAttributes::iterator it = attrs.begin(); it != attrs.end(); ++it)
     {
         handleSetAttributeRequest(it->key(),std::move(it->value()));
     }
 }
 
-RCSResourceAttributes & JavaBundleResource::handleGetAttributesRequest()
+const RCSResourceAttributes JavaBundleResource::handleGetAttributesRequest()
 {
     std::list<string> attrsNames = getAttributeNames();
     for(std::list<string>::iterator iterator = attrsNames.begin();
index 0dc750b..c0c687c 100644 (file)
@@ -47,9 +47,9 @@ namespace OIC
 
             RCSResourceAttributes::Value handleGetAttributeRequest(const std::string& key);
 
-            virtual void handleSetAttributesRequest(RCSResourceAttributes &attrs);
+            virtual void handleSetAttributesRequest(const RCSResourceAttributes &attrs);
 
-            virtual RCSResourceAttributes& handleGetAttributesRequest();
+            virtual RCSResourceAttributes handleGetAttributesRequest();
 
             virtual void initAttributes();
         private:
diff --git a/service/resource-container/src/ProtocolBridgeConnector.cpp b/service/resource-container/src/ProtocolBridgeConnector.cpp
deleted file mode 100644 (file)
index f55d8af..0000000
+++ /dev/null
@@ -1,40 +0,0 @@
-//******************************************************************
-//
-// 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 "ProtocolBridgeConnector.h"
-
-using namespace OIC::Service;
-
-namespace OIC
-{
-    namespace Service
-    {
-        ProtocolBridgeConnector::ProtocolBridgeConnector()
-        {
-
-        }
-
-        ProtocolBridgeConnector::~ProtocolBridgeConnector()
-        {
-
-        }
-    }
-}
-
diff --git a/service/resource-container/src/ProtocolBridgeResource.cpp b/service/resource-container/src/ProtocolBridgeResource.cpp
deleted file mode 100644 (file)
index 5820cef..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
-//******************************************************************
-//
-// 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 "ProtocolBridgeResource.h"
-
-using namespace OIC::Service;
-
-namespace OIC
-{
-    namespace Service
-    {
-        ProtocolBridgeResource::ProtocolBridgeResource()
-        {
-
-        }
-
-        ProtocolBridgeResource::~ProtocolBridgeResource()
-        {
-
-        }
-    }
-}
-
-
diff --git a/service/resource-container/src/RCSBundleInfo.cpp b/service/resource-container/src/RCSBundleInfo.cpp
deleted file mode 100644 (file)
index d89ab7c..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-//******************************************************************
-//
-// 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 "RCSBundleInfo.h"
-#include "BundleInfoInternal.h"
-
-namespace OIC
-{
-    namespace Service
-    {
-        RCSBundleInfo::RCSBundleInfo()
-        {
-
-        }
-
-        RCSBundleInfo::~RCSBundleInfo()
-        {
-
-        }
-    }
-}
index 80d1523..7a5bda3 100644 (file)
@@ -19,6 +19,9 @@
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include "RemoteResourceUnit.h"
+#include "InternalTypes.h"
+
+#include <exception>
 
 using namespace OIC::Service;
 
@@ -36,11 +39,21 @@ RemoteResourceUnit::~RemoteResourceUnit()
     {
         if(remoteObject->isCaching())
         {
-            remoteObject->stopCaching();
+            try{
+                remoteObject->stopCaching();
+            }
+            catch(std::exception &e){
+                OIC_LOG_V(ERROR, CONTAINER_TAG, "%s", e.what());
+            }
         }
         if(remoteObject->isMonitoring())
         {
-            remoteObject->stopMonitoring();
+            try{
+                remoteObject->stopMonitoring();
+            }
+            catch(std::exception &e){
+                OIC_LOG_V(ERROR, CONTAINER_TAG, "%s", e.what());
+            }
         }
     }
 }
index aaff441..ff04522 100644 (file)
@@ -59,79 +59,73 @@ namespace OIC
 
         void ResourceContainerImpl::startContainer(const std::string &configFile)
         {
-            OC_LOG(INFO, CONTAINER_TAG, "Starting resource container.");
+            OIC_LOG(INFO, CONTAINER_TAG, "Starting resource container.");
 #if (JAVA_SUPPORT)
-            OC_LOG(INFO, CONTAINER_TAG, "Resource container has Java support.");
+            OIC_LOG(INFO, CONTAINER_TAG, "Resource container has Java support.");
 #else
-            OC_LOG(INFO, CONTAINER_TAG, "Resource container without Java support.");
+            OIC_LOG(INFO, CONTAINER_TAG, "Resource container without Java support.");
 #endif
 
 
             activationLock.lock();
-            if (!configFile.empty())
-            {
-                m_config = new Configuration(configFile);
-
-                if (m_config->isLoaded())
+            try{
+                if (!configFile.empty())
                 {
-                    configInfo bundles;
-                    m_config->getConfiguredBundles(&bundles);
+                    m_config = new Configuration(configFile);
 
-                    for (unsigned int i = 0; i < bundles.size(); i++)
+                    if (m_config->isLoaded())
                     {
-                        BundleInfoInternal *bundleInfo = new BundleInfoInternal();
-                        bundleInfo->setPath(bundles[i][BUNDLE_PATH]);
-                        bundleInfo->setVersion(bundles[i][BUNDLE_VERSION]);
-                        bundleInfo->setID(bundles[i][BUNDLE_ID]);
-                        if (!bundles[i][BUNDLE_ACTIVATOR].empty())
+                        configInfo bundles;
+                        m_config->getConfiguredBundles(&bundles);
+
+                        for (unsigned int i = 0; i < bundles.size(); i++)
                         {
-                            string activatorName = bundles[i][BUNDLE_ACTIVATOR];
-                            std::replace(activatorName.begin(), activatorName.end(), '.', '/');
-                            ((BundleInfoInternal *) bundleInfo)->setActivatorName(activatorName);
-                            ((BundleInfoInternal *) bundleInfo)->setLibraryPath(
-                                bundles[i][BUNDLE_LIBRARY_PATH]);
-                        }
+                            shared_ptr<BundleInfoInternal> bundleInfo(new BundleInfoInternal);
+                            bundleInfo->setPath(bundles[i][BUNDLE_PATH]);
+                            bundleInfo->setVersion(bundles[i][BUNDLE_VERSION]);
+                            bundleInfo->setID(bundles[i][BUNDLE_ID]);
+                            if (!bundles[i][BUNDLE_ACTIVATOR].empty())
+                            {
+                                string activatorName = bundles[i][BUNDLE_ACTIVATOR];
+                                std::replace(activatorName.begin(), activatorName.end(), '.', '/');
+                                bundleInfo->setActivatorName(activatorName);
+                                bundleInfo->setLibraryPath(bundles[i][BUNDLE_LIBRARY_PATH]);
+                            }
 
-                        OC_LOG_V(INFO, CONTAINER_TAG, "Init Bundle:(%s)",
-                                 std::string(bundles[i][BUNDLE_ID] + ";" +
-                                             bundles[i][BUNDLE_PATH]).c_str());
+                            OIC_LOG_V(INFO, CONTAINER_TAG, "Init Bundle:(%s)",
+                                     std::string(bundles[i][BUNDLE_ID] + ";" +
+                                                 bundles[i][BUNDLE_PATH]).c_str());
 
-                        registerBundle(bundleInfo);
-                        activateBundle(bundleInfo);
+                            registerBundle(bundleInfo);
+                            activateBundle(bundleInfo);
+                        }
+                    }
+                    else
+                    {
+                        OIC_LOG_V(ERROR, CONTAINER_TAG, "Container started with invalid configfile path.");
                     }
                 }
                 else
                 {
-                    OC_LOG_V(ERROR, CONTAINER_TAG, "Container started with invalid configfile path.");
+                    OIC_LOG_V(INFO, CONTAINER_TAG, "No configuration file for the container provided.");
                 }
-            }
-            else
-            {
-                OC_LOG_V(INFO, CONTAINER_TAG, "No configuration file for the container provided.");
-            }
-
-            map<std::string, boost::thread >::iterator activatorIterator;
 
-            for (activatorIterator = m_activators.begin(); activatorIterator != m_activators.end();
-                 activatorIterator++)
-            {
-                activatorIterator->second.timed_join(
-                    boost::posix_time::seconds(BUNDLE_ACTIVATION_WAIT_SEC));
-                // wait for bundles to be activated
+                OIC_LOG(INFO, CONTAINER_TAG, "Resource container started.");
+            }catch(...){
+                OIC_LOG(INFO, CONTAINER_TAG, "Resource container failed starting.");
             }
             activationLock.unlock();
         }
 
         void ResourceContainerImpl::stopContainer()
         {
-            OC_LOG(INFO, CONTAINER_TAG, "Stopping resource container.");
+            OIC_LOG(INFO, CONTAINER_TAG, "Stopping resource container.");
 
-            for (std::map< std::string, BundleInfoInternal * >::iterator it = m_bundles.begin();
+            for (std::map< std::string, shared_ptr<BundleInfoInternal> >::iterator it = m_bundles.begin();
                  it != m_bundles.end(); ++it)
             {
-                BundleInfoInternal *bundleInfo = it->second;
-                deactivateBundle(bundleInfo);
-                unregisterBundle(bundleInfo);
+                deactivateBundle(it->second);
+                unregisterBundle(it->second);
             }
 
             if (!m_mapServers.empty())
@@ -151,10 +145,12 @@ namespace OIC
                 delete m_config;
         }
 
-        void ResourceContainerImpl::activateBundle(RCSBundleInfo *bundleInfo)
+        void ResourceContainerImpl::activateBundle(shared_ptr<RCSBundleInfo> bundleInfo)
         {
             activationLock.lock();
-            BundleInfoInternal *bundleInfoInternal = (BundleInfoInternal *) bundleInfo;
+
+            shared_ptr<BundleInfoInternal> bundleInfoInternal =
+                    std::static_pointer_cast<BundleInfoInternal>(bundleInfo);
 
             if (bundleInfoInternal->isLoaded())
             {
@@ -163,25 +159,31 @@ namespace OIC
             activationLock.unlock();
         }
 
-        void ResourceContainerImpl::deactivateBundle(RCSBundleInfo *bundleInfo)
+        void ResourceContainerImpl::deactivateBundle(shared_ptr<RCSBundleInfo> bundleInfo)
         {
-            if (((BundleInfoInternal *) bundleInfo)->isActivated())
+            shared_ptr<BundleInfoInternal> bundleInfoInternal =
+                                std::static_pointer_cast<BundleInfoInternal>(bundleInfo);
+            if (bundleInfoInternal->isActivated())
             {
-                deactivateBundle(bundleInfo->getID());
+                deactivateBundle(bundleInfoInternal->getID());
             }
         }
 
         void ResourceContainerImpl::activateBundle(const std::string &id)
         {
-            OC_LOG_V(INFO, CONTAINER_TAG, "Activating bundle: (%s)",
+            OIC_LOG_V(INFO, CONTAINER_TAG, "Activating bundle: (%s)",
                      std::string(m_bundles[id]->getID()).c_str());
+
             activationLock.lock();
-            auto f = std::bind(&ResourceContainerImpl::activateBundleThread, this,
-                               id);
-            boost::thread activator(f);
-            activator.timed_join(boost::posix_time::seconds(BUNDLE_SET_GET_WAIT_SEC));
+            try{
+                activateBundleThread(id);
+            }
+            catch(...){
+                OIC_LOG_V(INFO, CONTAINER_TAG, "Activating bundle: (%s) failed",
+                                     std::string(m_bundles[id]->getID()).c_str());
+            }
             activationLock.unlock();
-            OC_LOG_V(INFO, CONTAINER_TAG, "Bundle activated: (%s)",
+            OIC_LOG_V(INFO, CONTAINER_TAG, "Bundle activated: (%s)",
                      std::string(m_bundles[id]->getID()).c_str());
         }
 
@@ -200,35 +202,51 @@ namespace OIC
         }
 
         // loads the bundle
-        void ResourceContainerImpl::registerBundle(RCSBundleInfo *bundleInfo)
+        void ResourceContainerImpl::registerBundle(shared_ptr<RCSBundleInfo> bundleInfo)
         {
-            OC_LOG_V(INFO, CONTAINER_TAG, "Registering bundle: (%s)",
+            OIC_LOG_V(INFO, CONTAINER_TAG, "Registering bundle: (%s)",
                      std::string(bundleInfo->getPath()).c_str());
+            shared_ptr<BundleInfoInternal> bundleInfoInternal =
+                                          std::static_pointer_cast<BundleInfoInternal>(bundleInfo);
 
             if (has_suffix(bundleInfo->getPath(), ".jar"))
             {
 #if(JAVA_SUPPORT)
-                ((BundleInfoInternal *) bundleInfo)->setJavaBundle(true);
+                bundleInfoInternal->setJavaBundle(true);
+                bundleInfoInternal->setSoBundle(false);
                 registerJavaBundle(bundleInfo);
+#else
+                // android .jar library
+                bundleInfoInternal->setSoBundle(false);
+                bundleInfoInternal->setJavaBundle(false);
+                registerExtBundle(bundleInfo);
 #endif
             }
-            else
+            else if(has_suffix(bundleInfo->getPath(), ".so"))
             {
-                ((BundleInfoInternal *) bundleInfo)->setJavaBundle(false);
+                bundleInfoInternal->setSoBundle(true);
+                bundleInfoInternal->setJavaBundle(false);
                 registerSoBundle(bundleInfo);
             }
+            // other cases might be for example .apk for android, which are loaded in the wrapper
+            else{
+                bundleInfoInternal->setSoBundle(false);
+                bundleInfoInternal->setJavaBundle(false);
+                registerExtBundle(bundleInfo);
+            }
         }
 
-        void ResourceContainerImpl::unregisterBundle(RCSBundleInfo *bundleInfo)
+        void ResourceContainerImpl::unregisterBundle(shared_ptr<RCSBundleInfo> bundleInfo)
         {
-            BundleInfoInternal *bundleInfoInternal = (BundleInfoInternal *) bundleInfo;
+            shared_ptr<BundleInfoInternal> bundleInfoInternal =
+                                          std::static_pointer_cast<BundleInfoInternal>(bundleInfo);
             if (bundleInfoInternal->isLoaded() && !bundleInfoInternal->isActivated())
             {
-                if (!bundleInfoInternal->getJavaBundle())
+                if (bundleInfoInternal->getSoBundle())
                 {
                     unregisterBundleSo(bundleInfo->getID());
                 }
-                else
+                else if(bundleInfoInternal->getJavaBundle())
                 {
 #if(JAVA_SUPPORT)
                     unregisterBundleJava(bundleInfo->getID());
@@ -241,7 +259,7 @@ namespace OIC
         {
             void *bundleHandle = m_bundles[id]->getBundleHandle();
 
-            OC_LOG_V(INFO, CONTAINER_TAG, "Unregister bundle: (%s)",
+            OIC_LOG_V(INFO, CONTAINER_TAG, "Unregister bundle: (%s)",
                      std::string(m_bundles[id]->getID()).c_str());
 
             const char *error;
@@ -249,28 +267,34 @@ namespace OIC
 
             if ((error = dlerror()) != NULL)
             {
-                OC_LOG_V(ERROR, CONTAINER_TAG, "Error (%s)", error);
+                OIC_LOG_V(ERROR, CONTAINER_TAG, "Error (%s)", error);
             }
             else
             {
-                delete m_bundles[id];
                 m_bundles.erase(id);
             }
         }
 
-        void ResourceContainerImpl::registerResource(BundleResource::Ptr resource)
+        int ResourceContainerImpl::registerResource(BundleResource::Ptr resource)
         {
             string strUri = resource->m_uri;
             string strResourceType = resource->m_resourceType;
+            string strInterface = resource->m_interface;
             RCSResourceObject::Ptr server = nullptr;
+            int ret = EINVAL;
 
-            OC_LOG_V(INFO, CONTAINER_TAG, "Registration of resource (%s)" ,
-                     std::string(strUri + ", " + strResourceType).c_str());
+            OIC_LOG_V(INFO, CONTAINER_TAG, "Registration of resource (%s)" ,
+                     std::string(strUri + ", " + strResourceType + "," +
+                             resource->m_bundleId).c_str());
 
             registrationLock.lock();
             if (m_mapResources.find(strUri) == m_mapResources.end())
             {
-                server = buildResourceObject(strUri, strResourceType);
+                if (strInterface.empty()) {
+                    strInterface = "oic.if.baseline";
+                }
+
+                server = buildResourceObject(strUri, strResourceType, strInterface);
 
                 if (server != nullptr)
                 {
@@ -286,25 +310,40 @@ namespace OIC
                         std::bind(&ResourceContainerImpl::setRequestHandler, this,
                                   std::placeholders::_1, std::placeholders::_2));
 
-                    OC_LOG_V(INFO, CONTAINER_TAG, "Registration finished (%s)",
-                             std::string(strUri + ", " +
-                                         strResourceType).c_str());
+                    OIC_LOG_V(INFO, CONTAINER_TAG, "Registration finished (%s)",
+                            std::string(strUri + ", " +
+                                                          strResourceType).c_str());
 
-                    if (m_config->isHasInput(resource->m_bundleId))
+                    if (m_config && m_config->isHasInput(resource->m_bundleId))
                     {
+                        OIC_LOG_V(INFO, CONTAINER_TAG, "Resource has input (%s)",
+                              std::string(strUri + ", " +
+                              strResourceType).c_str());
                         discoverInputResource(strUri);
                     }
+                    else{
+                        OIC_LOG_V(INFO, CONTAINER_TAG, "Resource has no input (%s)",
+                                 std::string(strUri + ", " +
+                                 strResourceType).c_str());
+                    }
+                    OIC_LOG_V(INFO, CONTAINER_TAG, "Registration finished (%s)",
+                                                std::string(strUri + ", " +
+                                                            strResourceType).c_str());
 
                     // to get notified if bundle resource attributes are updated
-                    resource->registerObserver((NotificationReceiver *) this);
+                    resource->registerObserver(this);
+                    ret = 0;
                 }
             }
             else
             {
-                OC_LOG_V(ERROR, CONTAINER_TAG, "resource with (%s)",
+                OIC_LOG_V(ERROR, CONTAINER_TAG, "resource with (%s)",
                          std::string(strUri + " already exists.").c_str());
+                ret = -EEXIST;
             }
             registrationLock.unlock();
+
+            return ret;
         }
 
         void ResourceContainerImpl::unregisterResource(BundleResource::Ptr resource)
@@ -312,20 +351,30 @@ namespace OIC
             string strUri = resource->m_uri;
             string strResourceType = resource->m_resourceType;
 
-            OC_LOG_V(INFO, CONTAINER_TAG, "Unregistration of resource (%s)",
+            OIC_LOG_V(INFO, CONTAINER_TAG, "Unregistration of resource (%s)",
                      std::string(resource->m_uri + ", " +
                                  resource->m_resourceType).c_str());
 
-            if (m_config->isHasInput(resource->m_bundleId))
+            if (m_config && m_config->isHasInput(resource->m_bundleId))
             {
+                OIC_LOG_V(INFO, CONTAINER_TAG, "Calling undiscover (%s)",
+                                     std::string(resource->m_uri + ", " +
+                                                 resource->m_resourceType).c_str());
                 undiscoverInputResource(strUri);
             }
 
             if (m_mapServers.find(strUri) != m_mapServers.end())
             {
+                OIC_LOG_V(INFO, CONTAINER_TAG, "Resetting server (%s)",
+                                     std::string(resource->m_uri + ", " +
+                                                 resource->m_resourceType).c_str());
                 m_mapServers[strUri].reset();
 
                 m_mapResources.erase(m_mapResources.find(strUri));
+
+                OIC_LOG_V(INFO, CONTAINER_TAG, "Remove bundle resource (%s)",
+                                     std::string(resource->m_uri + ", " +
+                                                 resource->m_resourceType).c_str());
                 m_mapBundleResources[resource->m_bundleId].remove(strUri);
             }
         }
@@ -346,6 +395,9 @@ namespace OIC
             {
                 m_config->getResourceConfiguration(bundleId, configOutput);
             }
+            else{
+                OIC_LOG_V(DEBUG, CONTAINER_TAG, "no config present ");
+            }
         }
 
         RCSGetResponse ResourceContainerImpl::getRequestHandler(const RCSRequest &request,
@@ -353,6 +405,7 @@ namespace OIC
         {
             RCSResourceAttributes attr;
             std::string strResourceUri = request.getResourceUri();
+            OIC_LOG_V(INFO, CONTAINER_TAG, "Container get request for %s",strResourceUri.c_str());
 
             if (m_mapServers.find(strResourceUri) != m_mapServers.end()
                 && m_mapResources.find(strResourceUri) != m_mapResources.end())
@@ -368,6 +421,7 @@ namespace OIC
 
                 }
             }
+            OIC_LOG_V(INFO, CONTAINER_TAG, "Container get request for %s finished, %d attributes",strResourceUri.c_str(), attr.size());
 
             return RCSGetResponse::create(std::move(attr), 200);
         }
@@ -379,6 +433,8 @@ namespace OIC
             std::list<std::string> lstAttributes;
             std::string strResourceUri = request.getResourceUri();
 
+            OIC_LOG_V(INFO, CONTAINER_TAG, "Container set request for %s, %d attributes",strResourceUri.c_str(), attributes.size());
+
             if (m_mapServers.find(strResourceUri) != m_mapServers.end()
                 && m_mapResources.find(strResourceUri) != m_mapResources.end())
             {
@@ -398,6 +454,7 @@ namespace OIC
                             }
                         }
 
+                        OIC_LOG_V(INFO, CONTAINER_TAG, "Calling handleSetAttributeRequest");
                         m_mapResources[strResourceUri]->handleSetAttributesRequest(attr);
                     };
                     boost::thread setThread(setFunction);
@@ -410,7 +467,7 @@ namespace OIC
 
         void ResourceContainerImpl::onNotificationReceived(const std::string &strResourceUri)
         {
-            OC_LOG_V(INFO, CONTAINER_TAG,
+            OIC_LOG_V(INFO, CONTAINER_TAG,
                      "notification from (%s)", std::string(strResourceUri + ".").c_str());
 
             if (m_mapServers.find(strResourceUri) != m_mapServers.end())
@@ -426,61 +483,65 @@ namespace OIC
         }
 
         RCSResourceObject::Ptr ResourceContainerImpl::buildResourceObject(const std::string &strUri,
-                const std::string &strResourceType)
+                const std::string &strResourceType, const std::string &strInterface)
         {
             return RCSResourceObject::Builder(strUri, strResourceType,
-                                              "oic.if.baseline").setObservable(
+                                              strInterface).setObservable(
                        true).setDiscoverable(true).build();
         }
 
         void ResourceContainerImpl::startBundle(const std::string &bundleId)
         {
+            OIC_LOG_V(INFO, CONTAINER_TAG, "startBundle %s",bundleId.c_str());
             if (m_bundles.find(bundleId) != m_bundles.end())
             {
                 if (!m_bundles[bundleId]->isActivated())
                     activateBundle(m_bundles[bundleId]);
                 else
                 {
-                    OC_LOG(ERROR, CONTAINER_TAG, "Bundle already started");
+                    OIC_LOG(ERROR, CONTAINER_TAG, "Bundle already started");
                 }
             }
             else
             {
-                OC_LOG_V(ERROR, CONTAINER_TAG, "Bundle with ID \'(%s)",
+                OIC_LOG_V(ERROR, CONTAINER_TAG, "Bundle with ID \'(%s)",
                          std::string(bundleId + "\' is not registered.").c_str());
             }
         }
 
         void ResourceContainerImpl::stopBundle(const std::string &bundleId)
         {
+            OIC_LOG_V(INFO, CONTAINER_TAG, "stopBundle %s",bundleId.c_str());
             if (m_bundles.find(bundleId) != m_bundles.end())
             {
                 if (m_bundles[bundleId]->isActivated())
                     deactivateBundle(m_bundles[bundleId]);
                 else
                 {
-                    OC_LOG(ERROR, CONTAINER_TAG, "Bundle not activated");
+                    OIC_LOG(ERROR, CONTAINER_TAG, "Bundle not activated");
                 }
             }
             else
             {
-                OC_LOG_V(ERROR, CONTAINER_TAG, "Bundle with ID \'(%s)",
+                OIC_LOG_V(ERROR, CONTAINER_TAG, "Bundle with ID \'(%s)",
                          std::string(bundleId + "\' is not registered.").c_str());
             }
         }
 
         void ResourceContainerImpl::addBundle(const std::string &bundleId,
-                                              const std::string &bundleUri, const std::string &bundlePath,
-                                              const std::string &activator, std::map< string, string > params)
+                                              const std::string &bundleUri,
+                                              const std::string &bundlePath,
+                                              const std::string &activator,
+                                              std::map< string, string > params)
         {
             (void) bundleUri;
 
             if (m_bundles.find(bundleId) != m_bundles.end())
-                OC_LOG(ERROR, CONTAINER_TAG, "BundleId already exist");
+                OIC_LOG(ERROR, CONTAINER_TAG, "BundleId already exist");
 
             else
             {
-                BundleInfoInternal *bundleInfo = new BundleInfoInternal();
+                shared_ptr<BundleInfoInternal> bundleInfo = std::make_shared<BundleInfoInternal>();
                 bundleInfo->setID(bundleId);
                 bundleInfo->setPath(bundlePath);
                 bundleInfo->setActivatorName(activator);
@@ -488,11 +549,11 @@ namespace OIC
                 {
                     string activatorName = activator; // modify activator for Java bundle
                     std::replace(activatorName.begin(), activatorName.end(), '.', '/');
-                    ((BundleInfoInternal *) bundleInfo)->setActivatorName(activatorName);
-                    ((BundleInfoInternal *)bundleInfo)->setLibraryPath(params[BUNDLE_LIBRARY_PATH]);
+                    bundleInfo->setActivatorName(activatorName);
+                    bundleInfo->setLibraryPath(params[BUNDLE_LIBRARY_PATH]);
                 }
 
-                OC_LOG_V(INFO, CONTAINER_TAG, "Add Bundle: (%s)",
+                OIC_LOG_V(INFO, CONTAINER_TAG, "Add Bundle: (%s)",
                          std::string(bundleInfo->getID() + "; " +
                                      bundleInfo->getPath()).c_str());
 
@@ -502,9 +563,10 @@ namespace OIC
 
         void ResourceContainerImpl::removeBundle(const std::string &bundleId)
         {
+            OIC_LOG_V(INFO, CONTAINER_TAG, "removeBundle %s",bundleId.c_str());
             if (m_bundles.find(bundleId) != m_bundles.end())
             {
-                BundleInfoInternal *bundleInfo = m_bundles[bundleId];
+                shared_ptr<BundleInfoInternal> bundleInfo = m_bundles[bundleId];
                 if (bundleInfo->isActivated())
                     deactivateBundle(bundleInfo);
 
@@ -513,20 +575,22 @@ namespace OIC
             }
             else
             {
-                OC_LOG_V(ERROR, CONTAINER_TAG, "Bundle with ID \'(%s)",
-                         std::string(bundleId + "\' is not registered.").c_str());
+                OIC_LOG_V(ERROR, CONTAINER_TAG, "Bundle with ID \'(%s)",
+                         std::string(bundleId + "\' is not ced.").c_str());
             }
         }
 
         std::list<std::unique_ptr<RCSBundleInfo>> ResourceContainerImpl::listBundles()
         {
+            OIC_LOG_V(INFO, CONTAINER_TAG,
+                                 "list bundles (%d)", m_bundles.size());
             std::list<std::unique_ptr<RCSBundleInfo> > ret;
-            for (std::map< std::string, BundleInfoInternal * >::iterator it = m_bundles.begin();
+            for (std::map< std::string, shared_ptr<BundleInfoInternal> >::iterator it = m_bundles.begin();
                  it != m_bundles.end(); ++it)
             {
                 {
                     std::unique_ptr<BundleInfoInternal> bundleInfo(new BundleInfoInternal);
-                    (bundleInfo)->setBundleInfo(it->second);
+                    bundleInfo->setBundleInfo(it->second);
                     ret.push_back(std::move(bundleInfo));
                 }
             }
@@ -555,7 +619,7 @@ namespace OIC
             }
             else
             {
-                OC_LOG_V(ERROR, CONTAINER_TAG, "Bundle with ID \'(%s)",
+                OIC_LOG_V(ERROR, CONTAINER_TAG, "Bundle with ID \'(%s)",
                          std::string(bundleId + "\' is not registered.").c_str());
             }
         }
@@ -563,22 +627,25 @@ namespace OIC
         void ResourceContainerImpl::removeResourceConfig(const std::string &bundleId,
                 const std::string &resourceUri)
         {
+            OIC_LOG_V(INFO, CONTAINER_TAG, "removeResourceConfig %s, %s",bundleId.c_str(),
+                    resourceUri.c_str());
             if (m_bundles.find(bundleId) != m_bundles.end())
             {
-                if (!m_bundles[bundleId]->getJavaBundle())
+                if (m_bundles[bundleId]->getSoBundle())
                 {
                     removeSoBundleResource(bundleId, resourceUri);
                 }
             }
             else
             {
-                OC_LOG_V(ERROR, CONTAINER_TAG, "Bundle with ID \'(%s)",
+                OIC_LOG_V(ERROR, CONTAINER_TAG, "Bundle with ID \'(%s)",
                          std::string(bundleId + "\' is not registered.").c_str());
             }
         }
 
         std::list< string > ResourceContainerImpl::listBundleResources(const std::string &bundleId)
         {
+            OIC_LOG_V(INFO, CONTAINER_TAG, "listBundleResources %s",bundleId.c_str());
             std::list < string > ret;
 
             if (m_mapBundleResources.find(bundleId) != m_mapBundleResources.end())
@@ -590,61 +657,128 @@ namespace OIC
 
         }
 
-        void ResourceContainerImpl::registerSoBundle(RCSBundleInfo *bundleInfo)
+        void ResourceContainerImpl::registerSoBundle(shared_ptr<RCSBundleInfo> bundleInfo)
         {
+            OIC_LOG_V(DEBUG, CONTAINER_TAG, "Register SO bundle");
             const char *error;
 
             activator_t *bundleActivator = NULL;
             deactivator_t *bundleDeactivator = NULL;
             resourceCreator_t *resourceCreator = NULL;
             resourceDestroyer_t *resourceDestroyer = NULL;
-            BundleInfoInternal *bundleInfoInternal = (BundleInfoInternal *) bundleInfo;
+            shared_ptr<BundleInfoInternal> bundleInfoInternal =
+                                std::static_pointer_cast<BundleInfoInternal>(bundleInfo);
+
             void *bundleHandle = NULL;
             bundleHandle = dlopen(bundleInfo->getPath().c_str(), RTLD_LAZY);
+            if ((error = dlerror()) != NULL)
+            {
+              OIC_LOG_V(ERROR, CONTAINER_TAG, "Error while loading .so bundle: (%s)", error);
+            }
 
             if (bundleHandle != NULL)
             {
+                OIC_LOG_V(DEBUG, CONTAINER_TAG, "Activator name %s",
+                        bundleInfoInternal->getActivatorName().c_str());
                 bundleActivator =
                     (activator_t *) dlsym(bundleHandle,
                                           ("" + bundleInfoInternal->getActivatorName()
                                            + "_externalActivateBundle").c_str());
+                if ((error = dlerror()) != NULL)
+                {
+                  OIC_LOG_V(ERROR, CONTAINER_TAG, "Error while loading .so bundle: (%s)", error);
+                }
+                else{
+                  OIC_LOG_V(DEBUG, CONTAINER_TAG, "Looked up %s", ("" +
+                          bundleInfoInternal->getActivatorName()
+                          + "_externalActivateBundle").c_str());
+                }
                 bundleDeactivator =
                     (deactivator_t *) dlsym(bundleHandle,
                                             ("" + bundleInfoInternal->getActivatorName()
                                              + "_externalDeactivateBundle").c_str());
+                if ((error = dlerror()) != NULL)
+                {
+                  OIC_LOG_V(ERROR, CONTAINER_TAG, "Error while loading .so bundle: (%s)", error);
+                }
+                else{
+                  OIC_LOG_V(DEBUG, CONTAINER_TAG, "Looked up %s", ("" +
+                          bundleInfoInternal->getActivatorName()
+                          + "_externalDeactivateBundle").c_str());
+                }
                 resourceCreator =
                     (resourceCreator_t *) dlsym(bundleHandle,
                                                 ("" + bundleInfoInternal->getActivatorName()
                                                  + "_externalCreateResource").c_str());
+                if ((error = dlerror()) != NULL)
+                {
+                  OIC_LOG_V(ERROR, CONTAINER_TAG, "Error while loading .so bundle: (%s)", error);
+                }
+                else{
+                  OIC_LOG_V(DEBUG, CONTAINER_TAG, "Looked up %s", ("" +
+                          bundleInfoInternal->getActivatorName()
+                          + "_externalCreateResource").c_str());
+                }
                 resourceDestroyer =
                     (resourceDestroyer_t *) dlsym(bundleHandle,
                                                   ("" + bundleInfoInternal->getActivatorName()
                                                    + "_externalDestroyResource").c_str());
+                if ((error = dlerror()) != NULL)
+                {
+                  OIC_LOG_V(ERROR, CONTAINER_TAG, "Error while loading .so bundle: (%s)", error);
+                }
+                else{
+                  OIC_LOG_V(DEBUG, CONTAINER_TAG, "Looked up %s", ("" +
+                          bundleInfoInternal->getActivatorName()
+                          + "_externalDestroyResource").c_str());
+                }
 
 
                 if ((error = dlerror()) != NULL)
                 {
-                    OC_LOG_V(ERROR, CONTAINER_TAG, "Error : (%s)", error);
+                    OIC_LOG_V(ERROR, CONTAINER_TAG, "Error : (%s)", error);
                 }
                 else
                 {
-                    ((BundleInfoInternal *) bundleInfo)->setBundleActivator(bundleActivator);
-                    ((BundleInfoInternal *) bundleInfo)->setBundleDeactivator(bundleDeactivator);
-                    ((BundleInfoInternal *) bundleInfo)->setResourceCreator(resourceCreator);
-                    ((BundleInfoInternal *) bundleInfo)->setResourceDestroyer(resourceDestroyer);
-                    ((BundleInfoInternal *) bundleInfo)->setLoaded(true);
-                    ((BundleInfoInternal *) bundleInfo)->setBundleHandle(bundleHandle);
-
-                    m_bundles[bundleInfo->getID()] = ((BundleInfoInternal *) bundleInfo);
+                    bundleInfoInternal->setBundleActivator(bundleActivator);
+                    bundleInfoInternal->setBundleDeactivator(bundleDeactivator);
+                    bundleInfoInternal->setResourceCreator(resourceCreator);
+                    bundleInfoInternal->setResourceDestroyer(resourceDestroyer);
+                    bundleInfoInternal->setLoaded(true);
+                    bundleInfoInternal->setBundleHandle(bundleHandle);
+
+                    m_bundles[bundleInfo->getID()] = bundleInfoInternal;
                 }
             }
             else
             {
                 if ((error = dlerror()) != NULL)
                 {
-                    OC_LOG_V(ERROR, CONTAINER_TAG, "Error : (%s)", error);
+                    OIC_LOG_V(ERROR, CONTAINER_TAG, "Error : (%s)", error);
                 }
             }
+            OIC_LOG_V(DEBUG, CONTAINER_TAG, "Register SO bundle finished");
+        }
+
+        void ResourceContainerImpl::registerExtBundle(shared_ptr<RCSBundleInfo> bundleInfo){
+            OIC_LOG_V(INFO, CONTAINER_TAG, "Registering ext bundle (%s)",
+                                 std::string(bundleInfo->getID()).c_str());
+            OIC_LOG_V(INFO, CONTAINER_TAG, "Activator name (%s)",
+                                             std::string(bundleInfo->getActivatorName()).c_str());
+
+            shared_ptr<BundleInfoInternal> bundleInfoInternal =
+                                std::static_pointer_cast<BundleInfoInternal>(bundleInfo);
+
+            m_bundles[bundleInfo->getID()] = bundleInfoInternal;
+            // in this case at least the resource configuration needs to be loaded
+            // in order to mark potential input resources for soft sensors
+            std::vector< resourceInfo > temp;
+            OIC_LOG_V(INFO, CONTAINER_TAG, "Loading resource config(%s)",
+                                                         std::string(bundleInfo->getID()).c_str());
+            getResourceConfiguration(bundleInfo->getID(),
+                            &temp);
+
+            OIC_LOG(INFO, CONTAINER_TAG, "Bundle registered");
         }
 
         void ResourceContainerImpl::activateSoBundle(const std::string &bundleId)
@@ -659,10 +793,10 @@ namespace OIC
             else
             {
                 //Unload module and return error
-                OC_LOG(ERROR, CONTAINER_TAG, "Activation unsuccessful.");
+                OIC_LOG(ERROR, CONTAINER_TAG, "Activation unsuccessful.");
             }
 
-            BundleInfoInternal *bundleInfoInternal = (BundleInfoInternal *) m_bundles[bundleId];
+            shared_ptr<BundleInfoInternal> bundleInfoInternal = m_bundles[bundleId];
             bundleInfoInternal->setActivated(true);
 
         }
@@ -672,14 +806,21 @@ namespace OIC
             auto foundDiscoverResource = m_mapDiscoverResourceUnits.find(outputResourceUri);
             if (foundDiscoverResource != m_mapDiscoverResourceUnits.end())
             {
+                OIC_LOG(DEBUG, CONTAINER_TAG, "Erase discover resource.");
                 m_mapDiscoverResourceUnits.erase(foundDiscoverResource);
+                OIC_LOG(DEBUG, CONTAINER_TAG, "Erase discover resource done.");
             }
         }
 
         void ResourceContainerImpl::discoverInputResource(const std::string &outputResourceUri)
         {
+            OIC_LOG_V(DEBUG, CONTAINER_TAG, "Discover input resource %s", outputResourceUri.c_str());
             auto foundOutputResource = m_mapResources.find(outputResourceUri);
-            auto resourceProperty = foundOutputResource->second->m_mapResourceProperty;
+
+            resourceInfo info;
+            m_config->getResourceConfiguration(foundOutputResource->second->m_bundleId,
+                outputResourceUri, &info);
+            map< string, vector< map< string, string > > > resourceProperty = info.resourceProperty;
 
             try
             {
@@ -687,6 +828,7 @@ namespace OIC
             }
             catch (std::out_of_range &e)
             {
+                OIC_LOG_V(DEBUG, CONTAINER_TAG, "No input resource %s", outputResourceUri.c_str());
                 return;
             }
 
@@ -713,13 +855,17 @@ namespace OIC
                         std::string type = makeValue(INPUT_RESOURCE_TYPE);
                         std::string attributeName = makeValue(INPUT_RESOURCE_ATTRIBUTENAME);
 
+
+                        OIC_LOG_V(DEBUG, CONTAINER_TAG, "Start discovery: %s, %s, %s", uri.c_str(),
+                                type.c_str(), attributeName.c_str());
                         DiscoverResourceUnit::Ptr newDiscoverUnit = std::make_shared
                                 < DiscoverResourceUnit > (outputResourceUri);
                         newDiscoverUnit->startDiscover(
                             DiscoverResourceUnit::DiscoverResourceInfo(uri, type,
                                     attributeName),
                             std::bind(&SoftSensorResource::onUpdatedInputResource,
-                                      std::static_pointer_cast< SoftSensorResource > (foundOutputResource->second),
+                                      std::static_pointer_cast< SoftSensorResource >
+                        (foundOutputResource->second),
                                       std::placeholders::_1, std::placeholders::_2));
 
                         auto foundDiscoverResource = m_mapDiscoverResourceUnits.find(
@@ -744,7 +890,7 @@ namespace OIC
         {
             deactivator_t *bundleDeactivator = m_bundles[id]->getBundleDeactivator();
 
-            OC_LOG_V(INFO, CONTAINER_TAG, "De-activating bundle: (%s)", std::string(
+            OIC_LOG_V(INFO, CONTAINER_TAG, "De-activating bundle: (%s)", std::string(
                          m_bundles[id]->getID()).c_str());
 
             if (bundleDeactivator != NULL)
@@ -755,7 +901,7 @@ namespace OIC
             else
             {
                 //Unload module and return error
-                OC_LOG(ERROR, CONTAINER_TAG, "De-activation unsuccessful.");
+                OIC_LOG(ERROR, CONTAINER_TAG, "De-activation unsuccessful.");
             }
         }
 
@@ -772,7 +918,7 @@ namespace OIC
             }
             else
             {
-                OC_LOG(ERROR, CONTAINER_TAG, "addResource unsuccessful.");
+                OIC_LOG(ERROR, CONTAINER_TAG, "addResource unsuccessful.");
             }
         }
 
@@ -790,14 +936,14 @@ namespace OIC
                 }
                 else
                 {
-                    OC_LOG(ERROR, CONTAINER_TAG, "removeResource unsuccessful.");
+                    OIC_LOG(ERROR, CONTAINER_TAG, "removeResource unsuccessful.");
                 }
             }
         }
 
         void ResourceContainerImpl::activateBundleThread(const std::string &id)
         {
-            OC_LOG_V(INFO, CONTAINER_TAG, "Activating bundle: (%s)",
+            OIC_LOG_V(INFO, CONTAINER_TAG, "Activating bundle: (%s)",
                      std::string(m_bundles[id]->getID()).c_str());
 
             if (m_bundles[id]->getJavaBundle())
@@ -806,12 +952,12 @@ namespace OIC
                 activateJavaBundle(id);
 #endif
             }
-            else
+            else if(m_bundles[id]->getSoBundle())
             {
                 activateSoBundle (id);
             }
 
-            OC_LOG_V(INFO, CONTAINER_TAG, "Bundle activated: (%s)",
+            OIC_LOG_V(INFO, CONTAINER_TAG, "Bundle activated: (%s)",
                      std::string(m_bundles[id]->getID()).c_str());
         }
 
@@ -821,28 +967,30 @@ namespace OIC
             return m_bundleVM[bundleId];
         }
 
-        void ResourceContainerImpl::registerJavaBundle(RCSBundleInfo *bundleInfo)
+        void ResourceContainerImpl::registerJavaBundle(shared_ptr<RCSBundleInfo> bundleInfo)
         {
-            OC_LOG_V(INFO, CONTAINER_TAG, "Registering Java bundle (%s)",
+            OIC_LOG_V(INFO, CONTAINER_TAG, "Registering Java bundle (%s)",
                      std::string(bundleInfo->getID()).c_str());
             JavaVM *jvm;
             JNIEnv *env;
             JavaVMInitArgs vm_args;
             JavaVMOption options[3];
 
-            BundleInfoInternal *bundleInfoInternal = (BundleInfoInternal *) bundleInfo;
+            shared_ptr<BundleInfoInternal> bundleInfoInternal =
+                                std::static_pointer_cast<BundleInfoInternal>(bundleInfo);
+
 
             if (FILE *file = fopen(bundleInfo->getPath().c_str(), "r"))
             {
                 fclose(file);
 
-                OC_LOG_V(INFO, CONTAINER_TAG, "Resource bundle (%s)",
+                OIC_LOG_V(INFO, CONTAINER_TAG, "Resource bundle (%s)",
                          std::string(bundleInfo->getPath() +
                                      " available.").c_str());
             }
             else
             {
-                OC_LOG_V(ERROR, CONTAINER_TAG, "Resource bundle (%s)",
+                OIC_LOG_V(ERROR, CONTAINER_TAG, "Resource bundle (%s)",
                          std::string(bundleInfo->getPath() + " not available.").c_str());
 
                 return;
@@ -852,19 +1000,19 @@ namespace OIC
             options[0].optionString = optionString;
             char classpath[1000];
             strcpy(classpath, "-Djava.class.path=");
-            strcat(classpath, bundleInfo->getPath().c_str());
+            strncat(classpath, bundleInfo->getPath().c_str(), BUNDLE_PATH_MAXLEN);
 
-            OC_LOG(INFO, CONTAINER_TAG,
+            OIC_LOG(INFO, CONTAINER_TAG,
                    std::string("Configured classpath: ").append(classpath).c_str());
 
             options[1].optionString = classpath;
 
             char libraryPath[1000];
             strcpy(libraryPath, "-Djava.library.path=");
-            strcat(libraryPath, bundleInfo->getLibraryPath().c_str());
+            strncat(libraryPath, bundleInfo->getLibraryPath().c_str(), BUNDLE_PATH_MAXLEN);
             options[2].optionString = libraryPath;
 
-            OC_LOG(INFO, CONTAINER_TAG,
+            OIC_LOG(INFO, CONTAINER_TAG,
                    std::string("Configured library path: ").append(libraryPath).c_str());
 
             vm_args.version = JNI_VERSION_1_4;
@@ -877,28 +1025,29 @@ namespace OIC
 
             if (res < 0)
             {
-                OC_LOG(ERROR, CONTAINER_TAG, "cannot create JavaVM.");
+                OIC_LOG(ERROR, CONTAINER_TAG, "cannot create JavaVM.");
                 return;
             }
             else
             {
-                OC_LOG(INFO, CONTAINER_TAG, "JVM successfully created.");
+                OIC_LOG(INFO, CONTAINER_TAG, "JVM successfully created.");
             }
 
             m_bundleVM.insert(std::pair< string, JavaVM * >(bundleInfo->getID(), jvm));
 
             const char *className = bundleInfoInternal->getActivatorName().c_str();
 
-            OC_LOG_V(INFO, CONTAINER_TAG, "Looking up class: (%s)", std::string(
+            OIC_LOG_V(INFO, CONTAINER_TAG, "Looking up class: (%s)", std::string(
                          bundleInfoInternal->getActivatorName() + "|").c_str());
 
             jclass bundleActivatorClass = env->FindClass(className);
 
             if (bundleActivatorClass == NULL)
             {
-                OC_LOG_V(ERROR, CONTAINER_TAG, "Cannot register bundle (%s)",
+                OIC_LOG_V(ERROR, CONTAINER_TAG, "Cannot register bundle (%s)",
                          std::string( bundleInfoInternal->getID()
-                                      + " bundle activator(" + bundleInfoInternal->getActivatorName()
+                                      + " bundle activator(" +
+                                      bundleInfoInternal->getActivatorName()
                                       + ") not found ").c_str());
                 return;
             }
@@ -908,7 +1057,7 @@ namespace OIC
 
             if (activateMethod == NULL)
             {
-                OC_LOG_V(ERROR, CONTAINER_TAG, "Cannot register bundle (%s)",
+                OIC_LOG_V(ERROR, CONTAINER_TAG, "Cannot register bundle (%s)",
                          std::string( bundleInfoInternal->getID()
                                       + " activate bundle method not found ").c_str());
                 return;
@@ -920,7 +1069,7 @@ namespace OIC
 
             if (deactivateMethod == NULL)
             {
-                OC_LOG_V(ERROR, CONTAINER_TAG, "Cannot register bundle (%s)",
+                OIC_LOG_V(ERROR, CONTAINER_TAG, "Cannot register bundle (%s)",
                          std::string( bundleInfoInternal->getID()
                                       + " deactivate bundle method not found ").c_str());
                 return;
@@ -940,18 +1089,20 @@ namespace OIC
 
             bundleInfoInternal->setLoaded(true);
 
-            m_bundles[bundleInfo->getID()] = ((BundleInfoInternal *)bundleInfo);
+            m_bundles[bundleInfo->getID()] = bundleInfoInternal;
 
 
-            OC_LOG(INFO, CONTAINER_TAG, "Bundle registered");
+            OIC_LOG(INFO, CONTAINER_TAG, "Bundle registered");
         }
 
+
+
         void ResourceContainerImpl::activateJavaBundle(string bundleId)
         {
-            OC_LOG(INFO, CONTAINER_TAG, "Activating java bundle");
+            OIC_LOG(INFO, CONTAINER_TAG, "Activating java bundle");
 
             JavaVM *vm = getJavaVM(bundleId);
-            BundleInfoInternal *bundleInfoInternal = (BundleInfoInternal *) m_bundles[bundleId];
+            bundleInfoInternal = m_bundles[bundleId];
             JNIEnv *env;
             int envStat = vm->GetEnv((void **) &env, JNI_VERSION_1_4);
 
@@ -959,12 +1110,12 @@ namespace OIC
             {
                 if (vm->AttachCurrentThread((void **) &env, NULL) != 0)
                 {
-                    OC_LOG(ERROR, CONTAINER_TAG, "Failed to attach ");
+                    OIC_LOG(ERROR, CONTAINER_TAG, "Failed to attach ");
                 }
             }
             else if (envStat == JNI_EVERSION)
             {
-                OC_LOG(ERROR, CONTAINER_TAG, "Env: version not supported ");
+                OIC_LOG(ERROR, CONTAINER_TAG, "Env: version not supported ");
             }
 
             env->CallVoidMethod(bundleInfoInternal->getJavaBundleActivatorObject(),
@@ -975,10 +1126,10 @@ namespace OIC
 
         void ResourceContainerImpl::deactivateJavaBundle(string bundleId)
         {
-            OC_LOG(INFO, CONTAINER_TAG, "Deactivating java bundle");
+            OIC_LOG(INFO, CONTAINER_TAG, "Deactivating java bundle");
 
             JavaVM *vm = getJavaVM(bundleId);
-            BundleInfoInternal *bundleInfoInternal = (BundleInfoInternal *) m_bundles[bundleId];
+            shared_ptr<BundleInfoInternal>bundleInfoInternal = m_bundles[bundleId];
             JNIEnv *env;
             int envStat = vm->GetEnv((void **) &env, JNI_VERSION_1_4);
 
@@ -986,12 +1137,12 @@ namespace OIC
             {
                 if (vm->AttachCurrentThread((void **) &env, NULL) != 0)
                 {
-                    OC_LOG(ERROR, CONTAINER_TAG, "Failed to attach ");
+                    OIC_LOG(ERROR, CONTAINER_TAG, "Failed to attach ");
                 }
             }
             else if (envStat == JNI_EVERSION)
             {
-                OC_LOG(ERROR, CONTAINER_TAG, "Env: version not supported ");
+                OIC_LOG(ERROR, CONTAINER_TAG, "Env: version not supported ");
             }
 
             env->CallVoidMethod(bundleInfoInternal->getJavaBundleActivatorObject(),
@@ -1002,14 +1153,13 @@ namespace OIC
 
         void ResourceContainerImpl::unregisterBundleJava(string id)
         {
-            OC_LOG_V(INFO, CONTAINER_TAG, "Unregister Java bundle: (%s)", std::string(
+            OIC_LOG_V(INFO, CONTAINER_TAG, "Unregister Java bundle: (%s)", std::string(
                          m_bundles[id]->getID()).c_str());
 
-            OC_LOG(INFO, CONTAINER_TAG, "Destroying JVM");
+            OIC_LOG(INFO, CONTAINER_TAG, "Destroying JVM");
 
             m_bundleVM[id]->DestroyJavaVM();
 
-            delete m_bundles[id];
             m_bundles.erase(id);
         }
 #endif
index e141fec..5d5f81b 100644 (file)
@@ -42,6 +42,7 @@
 
 #define BUNDLE_ACTIVATION_WAIT_SEC 10
 #define BUNDLE_SET_GET_WAIT_SEC 10
+#define BUNDLE_PATH_MAXLEN 300
 
 using namespace OIC::Service;
 
@@ -56,16 +57,9 @@ namespace OIC
                 // methods from ResourceContainer
                 void startContainer(const std::string &configFile);
                 void stopContainer();
-                void activateBundle(RCSBundleInfo *bundleInfo);
-                void deactivateBundle(RCSBundleInfo *bundleInfo);
-                void activateBundle(const std::string &bundleId);
-                void deactivateBundle(const std::string &bundleId);
-                void registerBundle(RCSBundleInfo *bundleinfo);
-                void unregisterBundle(RCSBundleInfo *bundleinfo);
-                void unregisterBundleSo(const std::string &id);
 
                 // methods from ResourceContainerBundleAPI
-                void registerResource(BundleResource::Ptr resource);
+                int registerResource(BundleResource::Ptr resource);
                 void unregisterResource(BundleResource::Ptr resource);
 
                 void getBundleConfiguration(const std::string &bundleId, configInfo *configOutput);
@@ -81,7 +75,7 @@ namespace OIC
 
                 static ResourceContainerImpl *getImplInstance();
                 static RCSResourceObject::Ptr buildResourceObject(const std::string &strUri,
-                        const std::string &strResourceType);
+                        const std::string &strResourceType, const std::string &strInterface);
 
                 void startBundle(const std::string &bundleId);
                 void stopBundle(const std::string &bundleId);
@@ -105,7 +99,7 @@ namespace OIC
 #endif
 
             private:
-                map< std::string, BundleInfoInternal * > m_bundles; // <bundleID, bundleInfo>
+                map< std::string, shared_ptr<BundleInfoInternal>> m_bundles; // <bundleID, bundleInfo>
                 map< std::string, RCSResourceObject::Ptr > m_mapServers; //<uri, serverPtr>
                 map< std::string, BundleResource::Ptr > m_mapResources; //<uri, resourcePtr>
                 map< std::string, list< string > > m_mapBundleResources; //<bundleID, vector<uri>>
@@ -113,8 +107,6 @@ namespace OIC
                 //<uri, DiscoverUnit>
                 string m_configFile;
                 Configuration *m_config;
-                // holds for a bundle the threads for bundle activation
-                map< std::string, boost::thread > m_activators;
                 // used for synchronize the resource registration of multiple bundles
                 std::mutex registrationLock;
                 // used to synchronize the startup of the container with other operation
@@ -134,15 +126,24 @@ namespace OIC
                 void addSoBundleResource(const std::string &bundleId, resourceInfo newResourceInfo);
                 void removeSoBundleResource(const std::string &bundleId,
                                             const std::string &resourceUri);
-                void registerSoBundle(RCSBundleInfo *bundleInfo);
+                void registerSoBundle(shared_ptr<RCSBundleInfo> bundleInfo);
+                void registerExtBundle(shared_ptr<RCSBundleInfo> bundleInfo);
                 void discoverInputResource(const std::string &outputResourceUri);
                 void undiscoverInputResource(const std::string &outputResourceUri);
                 void activateBundleThread(const std::string &bundleId);
 
+                void activateBundle(shared_ptr<RCSBundleInfo> bundleInfo);
+                void deactivateBundle(shared_ptr<RCSBundleInfo> bundleInfo);
+                void activateBundle(const std::string &bundleId);
+                void deactivateBundle(const std::string &bundleId);
+                void registerBundle(shared_ptr<RCSBundleInfo> bundleInfo);
+                void unregisterBundle(shared_ptr<RCSBundleInfo> bundleInfo);
+                void unregisterBundleSo(const std::string &id);
+
 #if(JAVA_SUPPORT)
                 map<string, JavaVM *> m_bundleVM;
 
-                void registerJavaBundle(RCSBundleInfo *bundleInfo);
+                void registerJavaBundle(shared_ptr<RCSBundleInfo> bundleInfo);
                 void activateJavaBundle(string bundleId);
                 void deactivateJavaBundle(string bundleId);
 
index 3b99bbf..7d00a9b 100644 (file)
@@ -26,6 +26,7 @@
 #include <map>
 #include <vector>
 #include <memory>
+#include <algorithm>
 
 #include <UnitTestHelper.h>
 
@@ -42,6 +43,7 @@
 
 #include "RCSResourceObject.h"
 #include "RCSRemoteResourceObject.h"
+#include "SoftSensorResource.h"
 
 #include "ResourceContainerTestSimulator.h"
 
@@ -98,17 +100,67 @@ class TestBundleResource: public BundleResource
     public:
         virtual void initAttributes() { }
 
-        virtual void handleSetAttributesRequest(RCSResourceAttributes &attr)
+        virtual void handleSetAttributesRequest(const RCSResourceAttributes &attr)
         {
             BundleResource::setAttributes(attr);
         }
 
-        virtual RCSResourceAttributes &handleGetAttributesRequest()
+        virtual RCSResourceAttributes handleGetAttributesRequest()
         {
             return BundleResource::getAttributes();
         }
 };
 
+/*Fake bundle resource class for testing*/
+class TestBundleResourceWithAttrs: public BundleResource
+{
+    public:
+        virtual void initAttributes() {
+            setAttribute("attrib1", RCSResourceAttributes::Value("test"));
+            setAttribute("attrib2", RCSResourceAttributes::Value(1));
+            setAttribute("attrib3", RCSResourceAttributes::Value(true));
+        }
+
+        virtual void handleSetAttributesRequest(const RCSResourceAttributes &attr)
+        {
+            BundleResource::setAttributes(attr);
+        }
+
+        virtual RCSResourceAttributes handleGetAttributesRequest()
+        {
+            return BundleResource::getAttributes();
+        }
+};
+
+
+/*Fake bundle resource class for testing*/
+class TestSoftSensorResource: public SoftSensorResource
+{
+    public:
+        virtual void initAttributes() {
+            SoftSensorResource::initAttributes();
+        }
+
+        virtual void handleSetAttributesRequest(const RCSResourceAttributes &attr)
+        {
+            BundleResource::setAttributes(attr);
+        }
+
+        virtual RCSResourceAttributes handleGetAttributesRequest()
+        {
+            return BundleResource::getAttributes();
+        }
+
+        virtual void executeLogic(){
+
+        }
+
+        virtual void onUpdatedInputResource(
+                std::string, std::vector<OIC::Service::RCSResourceAttributes::Value>){
+
+        }
+};
+
 class ResourceContainerTest: public TestWithMock
 {
 
@@ -127,18 +179,70 @@ class ResourceContainerTest: public TestWithMock
         }
 };
 
+TEST_F(ResourceContainerTest, TestBundleResource)
+{
+    TestBundleResourceWithAttrs testResource;
+    testResource.initAttributes();
+
+    // check if initAttributes worked
+    EXPECT_STREQ("\"test\"", testResource.getAttribute("attrib1").toString().c_str());
+
+    std::list<string> attrNames = testResource.getAttributeNames();
+    ASSERT_TRUE(std::find(attrNames.begin(), attrNames.end(), "attrib1") != attrNames.end());
+
+    ASSERT_FALSE(testResource.getAttributes().contains("attrib4"));
+
+    testResource.getAttributeNames();
+
+    RCSResourceAttributes fullAttributes;
+
+    fullAttributes["attrib1"] = "test";
+    fullAttributes["attrib2"] = 1;
+    fullAttributes["attrib3"] = true;
+
+    testResource.setAttributes(fullAttributes);
+
+    ASSERT_TRUE(testResource.getAttributes().contains("attrib1"));
+
+    fullAttributes["attrib1"] = "test2";
+    fullAttributes["attrib2"] = 2;
+    fullAttributes["attrib3"] = false;
+
+    testResource.handleSetAttributesRequest(fullAttributes);
+
+    EXPECT_EQ((unsigned int) 3, testResource.getAttributeNames().size());
+
+    EXPECT_EQ((unsigned int) 3, testResource.handleGetAttributesRequest().size());
+    std::string testString = "test";
+    testResource.setAttribute("attrib1", RCSResourceAttributes::Value(testString), false);
+
+    testResource.setAttributes(fullAttributes, false);
+
+    EXPECT_STREQ("\"test2\"", testResource.getAttribute("attrib1").toString().c_str());
+    EXPECT_EQ(2, testResource.getAttribute("attrib2"));
+
+    testResource.setAttribute("attrib1", RCSResourceAttributes::Value("test"));
+    EXPECT_STREQ("\"test\"", testResource.getAttribute("attrib1").toString().c_str());
+    EXPECT_EQ(2, testResource.getAttribute("attrib2"));
+}
+
+TEST_F(ResourceContainerTest, TestSoftSensorResource)
+{
+    TestSoftSensorResource softSensorResource;
+    softSensorResource.initAttributes();
+    EXPECT_EQ((unsigned int) 0, softSensorResource.getAttributeNames().size());
+}
+
+
 TEST_F(ResourceContainerTest, BundleRegisteredWhenContainerStartedWithValidConfigFile)
 {
     m_pResourceContainer->startContainer(m_strConfigPath);
     EXPECT_GT(m_pResourceContainer->listBundles().size(), (unsigned int) 0);
-    cout << "now checking for bunlde ids " << endl;
     EXPECT_STREQ("oic.bundle.test",
                  (*m_pResourceContainer->listBundles().begin())->getID().c_str());
     EXPECT_STREQ("libTestBundle.so",
                  (*m_pResourceContainer->listBundles().begin())->getPath().c_str());
     EXPECT_STREQ("1.0.0", (*m_pResourceContainer->listBundles().begin())->getVersion().c_str());
-
-    cout << "Now stopping container." << endl;
     m_pResourceContainer->stopContainer();
 }
 
@@ -148,7 +252,7 @@ TEST_F(ResourceContainerTest, BundleLoadedWhenContainerStartedWithValidConfigFil
 
     EXPECT_GT(m_pResourceContainer->listBundles().size(), (unsigned int) 0);
     unique_ptr<RCSBundleInfo> first = std::move(*m_pResourceContainer->listBundles().begin());
-    unique_ptr<BundleInfoInternal> firstInternal(static_cast<BundleInfoInternal*>(first.release()));
+    unique_ptr<BundleInfoInternal> firstInternal((BundleInfoInternal*)first.release());
     EXPECT_TRUE( firstInternal->isLoaded() );
     EXPECT_NE(nullptr,
                firstInternal->getBundleHandle());
@@ -162,7 +266,7 @@ TEST_F(ResourceContainerTest, BundleActivatedWhenContainerStartedWithValidConfig
 
     EXPECT_GT(m_pResourceContainer->listBundles().size(), (unsigned int) 0);
     unique_ptr<RCSBundleInfo> first = std::move(*m_pResourceContainer->listBundles().begin());
-    unique_ptr<BundleInfoInternal> firstInternal(static_cast<BundleInfoInternal*>(first.release()));
+    unique_ptr<BundleInfoInternal> firstInternal((BundleInfoInternal*)first.release());
     EXPECT_TRUE(firstInternal->isActivated());
     EXPECT_NE(nullptr,firstInternal->getBundleActivator());
 
@@ -197,7 +301,7 @@ TEST_F(ResourceContainerTest, BundleStoppedWithStartBundleAPI)
     m_pResourceContainer->stopBundle("oic.bundle.test");
 
     unique_ptr<RCSBundleInfo> first = std::move(*m_pResourceContainer->listBundles().begin());
-    unique_ptr<BundleInfoInternal> firstInternal(static_cast<BundleInfoInternal*>(first.release()));
+    unique_ptr<BundleInfoInternal> firstInternal((BundleInfoInternal*)first.release());
     EXPECT_FALSE(firstInternal->isActivated());
 
     m_pResourceContainer->stopContainer();
@@ -209,7 +313,7 @@ TEST_F(ResourceContainerTest, BundleStartedWithStartBundleAPI)
     m_pResourceContainer->stopBundle("oic.bundle.test");
     m_pResourceContainer->startBundle("oic.bundle.test");
     unique_ptr<RCSBundleInfo> first = std::move(*m_pResourceContainer->listBundles().begin());
-    unique_ptr<BundleInfoInternal> firstInternal(static_cast<BundleInfoInternal*>(first.release()));
+    unique_ptr<BundleInfoInternal> firstInternal((BundleInfoInternal*)first.release());
     EXPECT_TRUE(firstInternal->isActivated());
 
     m_pResourceContainer->stopContainer();
@@ -225,7 +329,7 @@ TEST_F(ResourceContainerTest, AddNewSoBundleToContainer)
 
     EXPECT_EQ(bundles.size() + 1, m_pResourceContainer->listBundles().size());
     unique_ptr<RCSBundleInfo> first = std::move(*m_pResourceContainer->listBundles().begin());
-    unique_ptr<BundleInfoInternal> firstInternal(static_cast<BundleInfoInternal*>(first.release()));
+    unique_ptr<BundleInfoInternal> firstInternal((BundleInfoInternal*)first.release());
     EXPECT_TRUE(firstInternal->isLoaded());
 }
 
@@ -306,6 +410,7 @@ class ResourceContainerBundleAPITest: public TestWithMock
             m_pBundleResource->m_bundleId = "oic.bundle.test";
             m_pBundleResource->m_uri = "/test_resource";
             m_pBundleResource->m_resourceType = "container.test";
+            m_pBundleResource->m_interface = "oic.if.baseline";
         }
 };
 
@@ -315,9 +420,10 @@ TEST_F(ResourceContainerBundleAPITest, ResourceServerCreatedWhenRegisterResource
     m_pBundleResource->m_bundleId = "oic.bundle.test";
     m_pBundleResource->m_uri = "/test_resource/test";
     m_pBundleResource->m_resourceType = "container.test";
+    m_pBundleResource->m_interface = "oic.if.baseline";
 
     mocks.ExpectCallFunc(ResourceContainerImpl::buildResourceObject).With(m_pBundleResource->m_uri,
-            m_pBundleResource->m_resourceType).Return(nullptr);
+            m_pBundleResource->m_resourceType, m_pBundleResource->m_interface).Return(nullptr);
 
     m_pResourceContainer->registerResource(m_pBundleResource);
 }
@@ -410,168 +516,22 @@ class ResourceContainerImplTest: public TestWithMock
 
     public:
         ResourceContainerImpl *m_pResourceContainer;
-        BundleInfoInternal *m_pBundleInfo;
+        shared_ptr<BundleInfoInternal> m_pBundleInfo;
 
     protected:
         void SetUp()
         {
             TestWithMock::SetUp();
             m_pResourceContainer = ResourceContainerImpl::getImplInstance();
-            m_pBundleInfo = new BundleInfoInternal();
+            m_pBundleInfo = std::make_shared<BundleInfoInternal>();
         }
 
         void TearDown()
         {
-            delete m_pBundleInfo;
+            m_pBundleInfo.reset();
         }
 };
 
-TEST_F(ResourceContainerImplTest, SoBundleLoadedWhenRegisteredWithRegisterBundleAPI)
-{
-    m_pBundleInfo->setPath("libTestBundle.so");
-    m_pBundleInfo->setActivatorName("test");
-    m_pBundleInfo->setVersion("1.0");
-    m_pBundleInfo->setLibraryPath(".");
-    m_pBundleInfo->setID("oic.bundle.test");
-
-    m_pResourceContainer->registerBundle(m_pBundleInfo);
-
-    EXPECT_NE(nullptr, ((BundleInfoInternal *)m_pBundleInfo)->getBundleHandle());
-}
-
-#if (JAVA_SUPPORT_TEST)
-TEST_F(ResourceContainerImplTest, JavaBundleLoadedWhenRegisteredWithRegisterBundleAPIWrongPath)
-{
-    m_pBundleInfo->setPath("wrong_path.jar");
-    m_pBundleInfo->setActivatorName("org/iotivity/bundle/hue/HueBundleActivator");
-    m_pBundleInfo->setLibraryPath("../.");
-    m_pBundleInfo->setVersion("1.0");
-    m_pBundleInfo->setID("oic.bundle.java.test");
-
-    m_pResourceContainer->registerBundle(m_pBundleInfo);
-    EXPECT_FALSE(((BundleInfoInternal *)m_pBundleInfo)->isLoaded());
-}
-
-TEST_F(ResourceContainerImplTest, JavaBundleTest)
-{
-    m_pBundleInfo->setPath("TestBundleJava/hue-0.1-jar-with-dependencies.jar");
-    m_pBundleInfo->setActivatorName("org/iotivity/bundle/hue/HueBundleActivator");
-    m_pBundleInfo->setLibraryPath("../.");
-    m_pBundleInfo->setVersion("1.0");
-    m_pBundleInfo->setID("oic.bundle.java.test");
-
-    m_pResourceContainer->registerBundle(m_pBundleInfo);
-    EXPECT_TRUE(((BundleInfoInternal *)m_pBundleInfo)->isLoaded());
-
-    m_pResourceContainer->activateBundle(m_pBundleInfo);
-    EXPECT_TRUE(((BundleInfoInternal *) m_pBundleInfo)->isActivated());
-
-    m_pResourceContainer->deactivateBundle(m_pBundleInfo);
-    EXPECT_FALSE(((BundleInfoInternal *) m_pBundleInfo)->isActivated());
-}
-#endif
-
-TEST_F(ResourceContainerImplTest, BundleNotRegisteredIfBundlePathIsInvalid)
-{
-    m_pBundleInfo->setPath("");
-    m_pBundleInfo->setVersion("1.0");
-    m_pBundleInfo->setLibraryPath("../.");
-    m_pBundleInfo->setID("oic.bundle.test");
-
-    m_pResourceContainer->registerBundle(m_pBundleInfo);
-
-    EXPECT_EQ(nullptr, ((BundleInfoInternal *)m_pBundleInfo)->getBundleHandle());
-
-}
-
-TEST_F(ResourceContainerImplTest, SoBundleActivatedWithValidBundleInfo)
-{
-    m_pBundleInfo->setPath("libTestBundle.so");
-    m_pBundleInfo->setVersion("1.0");
-    m_pBundleInfo->setActivatorName("test");
-    m_pBundleInfo->setLibraryPath("../.");
-    m_pBundleInfo->setID("oic.bundle.test");
-
-    m_pResourceContainer->registerBundle(m_pBundleInfo);
-    m_pResourceContainer->activateBundle(m_pBundleInfo);
-
-    EXPECT_NE(nullptr, ((BundleInfoInternal *)m_pBundleInfo)->getBundleActivator());
-}
-
-TEST_F(ResourceContainerImplTest, BundleNotActivatedWhenNotRegistered)
-{
-    m_pBundleInfo->setPath("libTestBundle.so");
-    m_pBundleInfo->setActivatorName("test");
-    m_pBundleInfo->setVersion("1.0");
-    m_pBundleInfo->setLibraryPath("../.");
-    m_pBundleInfo->setID("oic.bundle.test");
-
-    m_pResourceContainer->activateBundle(m_pBundleInfo);
-
-    EXPECT_EQ(nullptr, ((BundleInfoInternal *)m_pBundleInfo)->getBundleActivator());
-}
-
-TEST_F(ResourceContainerImplTest, SoBundleActivatedWithBundleID)
-{
-    m_pBundleInfo->setPath("libTestBundle.so");
-    m_pBundleInfo->setVersion("1.0");
-    m_pBundleInfo->setLibraryPath("../.");
-    m_pBundleInfo->setActivatorName("test");
-    m_pBundleInfo->setID("oic.bundle.test");
-
-    m_pResourceContainer->registerBundle(m_pBundleInfo);
-    m_pResourceContainer->activateBundle(m_pBundleInfo->getID());
-
-    EXPECT_NE(nullptr, ((BundleInfoInternal *)m_pBundleInfo)->getBundleActivator());
-    EXPECT_TRUE(((BundleInfoInternal *)m_pBundleInfo)->isActivated());
-}
-
-TEST_F(ResourceContainerImplTest, BundleDeactivatedWithBundleInfo)
-{
-    m_pBundleInfo->setPath("libTestBundle.so");
-    m_pBundleInfo->setVersion("1.0");
-    m_pBundleInfo->setLibraryPath("../.");
-    m_pBundleInfo->setActivatorName("test");
-    m_pBundleInfo->setID("oic.bundle.test");
-
-    m_pResourceContainer->registerBundle(m_pBundleInfo);
-    m_pResourceContainer->activateBundle(m_pBundleInfo);
-    m_pResourceContainer->deactivateBundle(m_pBundleInfo);
-
-    EXPECT_NE(nullptr, ((BundleInfoInternal *)m_pBundleInfo)->getBundleDeactivator());
-    EXPECT_FALSE(((BundleInfoInternal *)m_pBundleInfo)->isActivated());
-}
-
-TEST_F(ResourceContainerImplTest, BundleDeactivatedWithBundleInfoJava)
-{
-    m_pBundleInfo->setPath("TestBundle/hue-0.1-jar-with-dependencies.jar");
-    m_pBundleInfo->setActivatorName("org/iotivity/bundle/hue/HueBundleActivator");
-    m_pBundleInfo->setLibraryPath("../.");
-    m_pBundleInfo->setVersion("1.0");
-    m_pBundleInfo->setID("oic.bundle.java.test");
-
-    m_pResourceContainer->registerBundle(m_pBundleInfo);
-    m_pResourceContainer->activateBundle(m_pBundleInfo);
-    m_pResourceContainer->deactivateBundle(m_pBundleInfo);
-    EXPECT_FALSE(((BundleInfoInternal *) m_pBundleInfo)->isActivated());
-}
-
-TEST_F(ResourceContainerImplTest, SoBundleDeactivatedWithBundleID)
-{
-    m_pBundleInfo->setPath("libTestBundle.so");
-    m_pBundleInfo->setVersion("1.0");
-    m_pBundleInfo->setLibraryPath("../.");
-    m_pBundleInfo->setActivatorName("test");
-    m_pBundleInfo->setID("oic.bundle.test");
-
-    m_pResourceContainer->registerBundle(m_pBundleInfo);
-    m_pResourceContainer->activateBundle(m_pBundleInfo);
-
-    m_pResourceContainer->deactivateBundle(m_pBundleInfo->getID());
-
-    EXPECT_FALSE(((BundleInfoInternal *)m_pBundleInfo)->isActivated());
-}
-
 
 /* Test for Configuration */
 TEST(ConfigurationTest, ConfigFileLoadedWithValidPath)
@@ -700,12 +660,6 @@ TEST(ConfigurationTest, BundleResourceConfigurationNotParsedWithInvalidBundleId)
     delete config;
 }
 
-namespace
-{
-    void discoverdCB(RCSRemoteResourceObject::Ptr);
-    void onUpdate(RemoteResourceUnit::UPDATE_MSG, RCSRemoteResourceObject::Ptr);
-}
-
 class DiscoverResourceUnitTest: public TestWithMock
 {
     private:
@@ -767,7 +721,6 @@ TEST_F(DiscoverResourceUnitTest, onUpdateCalled)
 
 namespace
 {
-    void onStateCB(ResourceState) { }
     void onCacheCB(const RCSResourceAttributes &) { }
 }
 
@@ -787,7 +740,6 @@ class RemoteResourceUnitTest: public TestWithMock
         void SetUp()
         {
             TestWithMock::SetUp();
-
             testObject = std::make_shared<ResourceContainerTestSimulator>();
             testObject->defaultRunSimulator();
             m_pRCSRemoteResourceObject = testObject->getRemoteResource();
index 4d2cf9f..40d1370 100644 (file)
@@ -66,13 +66,20 @@ class ResourceContainerTestSimulator
 
         ~ResourceContainerTestSimulator()
         {
-            if (remoteResource != nullptr && remoteResource->isCaching())
+            try
             {
-                remoteResource->stopCaching();
+                if (remoteResource != nullptr && remoteResource->isCaching())
+                {
+                    remoteResource->stopCaching();
+                }
+                if (remoteResource != nullptr && remoteResource->isMonitoring())
+                {
+                    remoteResource->stopMonitoring();
+                }
             }
-            if (remoteResource != nullptr && remoteResource->isMonitoring())
+            catch (RCSException &e)
             {
-                remoteResource->stopMonitoring();
+                std::cout << "exception : " << e.what() << std::endl;
             }
         }
 
@@ -150,7 +157,7 @@ class ResourceContainerTestSimulator
                                               std::weak_ptr<ResourceContainerTestSimulator>(shared_from_this())));
                 mutexForDiscovery.lock();
             }
-            catch (std::exception &e)
+            catch (RCSInvalidParameterException &e)
             {
                 std::cout << "exception : " << e.what() << std::endl;
             }
index 0bbbf9c..dd91058 100644 (file)
@@ -52,16 +52,16 @@ class TestBundleResource : public BundleResource
     public:
         void initAttributes() { };
 
-        RCSResourceAttributes &handleGetAttributesRequest()
+        RCSResourceAttributes handleGetAttributesRequest()
         {
             return BundleResource::getAttributes();
         }
 
         void handleSetAttributesRequest(
-            RCSResourceAttributes &value)
+            const RCSResourceAttributes &value)
         {
             BundleResource::setAttributes(value);
         }
 };
 
-#endif /* TESTBUNDLE_H_ */
\ No newline at end of file
+#endif /* TESTBUNDLE_H_ */
index 3e02991..b6ef553 100755 (executable)
@@ -75,6 +75,9 @@ else :
     rdsdk = rd_env.StaticLibrary('resource_directory', rd_src)
 
 rd_env.InstallTarget(rdsdk, 'libresource_directory')
+rd_env.UserInstallTargetLib(rdsdk, 'libresource_directory')
+rd_env.UserInstallTargetHeader('/include/rd_client.h', 'service/resource-directory', 'rd_client.h')
+rd_env.UserInstallTargetHeader('/include/rd_server.h', 'service/resource-directory', 'rd_server.h')
 
 ######################################################################
 # Samples for the resource directory
index 475eb75..da55d5b 100644 (file)
@@ -28,9 +28,6 @@
 extern "C" {
 #endif // __cplusplus
 
-/** Max ADDR SIZE */
-#define MAX_ADDR_STR_SIZE                (40)
-
 /** Callback function for returning RDDiscovery Result. */
 typedef int (* OCRDBiasFactorCB)(char addr[MAX_ADDR_STR_SIZE], uint16_t port);
 
index 69877d8..f662739 100644 (file)
@@ -50,13 +50,14 @@ OCStackResult OCRDStop();
  *
  * @param interfaceType a interface type that is being queried.
  * @param resourceType a resource type that is being queried.
- * @param payload A payload of the maching resource type or interface type or NULL. 
+ * @param payload A payload of the matching resource type or interface type or NULL.
+ * @param addr A device address.
  *
  * @return ::OC_STACK_OK upon success, ::OC_STACK_ERROR is returned except
  * the case that OC_STACK_SUCCESS is returned.
  */
 OCStackResult OCRDCheckPublishedResource(const char *interfaceType, const char *resourceType,
-        OCResourceCollectionPayload **payload);
+        OCResourceCollectionPayload **payload, OCDevAddr *addr);
 
 #ifdef __cplusplus
 }
index 444ceac..2897af7 100644 (file)
@@ -98,7 +98,14 @@ int main()
 
     std::cout << "Created Platform..." << std::endl;
 
-    registerLocalResources();
+    try
+    {
+        registerLocalResources();
+    }
+    catch (std::runtime_error e)
+    {
+        std::cout << "Caught OCException [Code: " << e.what() << std::endl;
+    }
 
     while (1)
     {
index 1d0ba5a..2f6c922 100644 (file)
@@ -36,7 +36,7 @@ static OCRDStorePublishResources *g_rdStorage = NULL;
 
 static void printStoragedResources(OCRDStorePublishResources *payload)
 {
-    OC_LOG(DEBUG, TAG, "Print Storage Resources ... ");
+    OIC_LOG(DEBUG, TAG, "Print Storage Resources ... ");
     for (OCRDStorePublishResources *temp = payload; temp; temp = temp->next)
     {
         if (temp->publishedResource)
@@ -52,21 +52,18 @@ OCStackResult OCRDStorePublishedResources(const OCResourceCollectionPayload *pay
     OCResourceCollectionPayload *storeResource = (OCResourceCollectionPayload *)OICCalloc(1, sizeof(OCResourceCollectionPayload));
     if (!storeResource)
     {
-        OC_LOG(ERROR, TAG, "Failed allocating memory for OCRDStorePublishResources.");
+        OIC_LOG(ERROR, TAG, "Failed allocating memory for OCRDStorePublishResources.");
         return OC_STACK_NO_MEMORY;
     }
 
-    OC_LOG_V(DEBUG, TAG, "Storing Resources for %s:%u", address->addr, address->port);
-
-    char rdPubAddr[MAX_ADDR_STR_SIZE];
-    snprintf(rdPubAddr, MAX_ADDR_STR_SIZE, "%s:%d", address->addr, address->port);
+    OIC_LOG_V(DEBUG, TAG, "Storing Resources for %s:%u", address->addr, address->port);
 
     OCTagsPayload *tags = payload->tags;
-    storeResource->tags = OCCopyTagsResources(tags->n.deviceName, tags->di.id, rdPubAddr,
+    storeResource->tags = OCCopyTagsResources(tags->n.deviceName, tags->di.id, tags->baseURI,
         tags->bitmap, address->port, tags->ins, tags->rts, tags->drel, tags->ttl);
     if (!storeResource->tags)
     {
-        OC_LOG(ERROR, TAG, "Failed allocating memory for tags.");
+        OIC_LOG(ERROR, TAG, "Failed allocating memory for tags.");
         OCFreeCollectionResource(storeResource);
         return OC_STACK_NO_MEMORY;
     }
@@ -79,7 +76,7 @@ OCStackResult OCRDStorePublishedResources(const OCResourceCollectionPayload *pay
                 links->rel, links->obs, links->title, links->uri, links->ins, links->mt);
             if (!storeResource->setLinks)
             {
-                OC_LOG(ERROR, TAG, "Failed allocating memory for links.");
+                OIC_LOG(ERROR, TAG, "Failed allocating memory for links.");
                 OCFreeCollectionResource(storeResource);
                 return OC_STACK_NO_MEMORY;
             }
@@ -95,7 +92,7 @@ OCStackResult OCRDStorePublishedResources(const OCResourceCollectionPayload *pay
                 links->obs, links->title, links->uri, links->ins, links->mt);
             if (!temp->next)
             {
-                OC_LOG(ERROR, TAG, "Failed allocating memory for links.");
+                OIC_LOG(ERROR, TAG, "Failed allocating memory for links.");
                 OCFreeCollectionResource(storeResource);
                 return OC_STACK_NO_MEMORY;
             }
@@ -110,6 +107,7 @@ OCStackResult OCRDStorePublishedResources(const OCResourceCollectionPayload *pay
         return OC_STACK_NO_MEMORY;
     }
     resources->publishedResource = storeResource;
+    resources->devAddr = *address;
 
     pthread_mutex_lock(&storageMutex);
     if (g_rdStorage)
@@ -132,17 +130,17 @@ OCStackResult OCRDStorePublishedResources(const OCResourceCollectionPayload *pay
 }
 
 OCStackResult OCRDCheckPublishedResource(const char *interfaceType, const char *resourceType,
-        OCResourceCollectionPayload **payload)
+        OCResourceCollectionPayload **payload, OCDevAddr *devAddr)
 {
     // ResourceType and InterfaceType if both are NULL it will return. If either is
     // not null it will continue execution.
     if (!resourceType && !interfaceType)
     {
-        OC_LOG(DEBUG, TAG, "Missing resource type and interace type.");
+        OIC_LOG(DEBUG, TAG, "Missing resource type or interace type.");
         return OC_STACK_INVALID_PARAM;
     }
 
-    OC_LOG(DEBUG, TAG, "Check Resource in RD");
+    OIC_LOG(DEBUG, TAG, "Check Resource in RD");
     if (g_rdStorage && g_rdStorage->publishedResource)
     {
         for (OCRDStorePublishResources *pResource = g_rdStorage;
@@ -155,7 +153,7 @@ OCStackResult OCRDCheckPublishedResource(const char *interfaceType, const char *
                     // If either rt or itf are NULL, it should skip remaining code execution.
                     if (!tLinks->rt || !tLinks->itf)
                     {
-                        OC_LOG(DEBUG, TAG, "Either resource type and interface type are missing.");
+                        OIC_LOG(DEBUG, TAG, "Either resource type or interface type is missing.");
                         continue;
                     }
                     if (resourceType)
@@ -163,7 +161,7 @@ OCStackResult OCRDCheckPublishedResource(const char *interfaceType, const char *
                         OCStringLL *temp = tLinks->rt;
                         while(temp)
                         {
-                            OC_LOG_V(DEBUG, TAG, "Resource Type: %s %s", resourceType, temp->value);
+                            OIC_LOG_V(DEBUG, TAG, "Resource Type: %s %s", resourceType, temp->value);
                             if (strcmp(resourceType, temp->value) == 0)
                             {
                                 OCTagsPayload *tag = pResource->publishedResource->tags;
@@ -187,6 +185,7 @@ OCStackResult OCRDCheckPublishedResource(const char *interfaceType, const char *
                                     OCFreeLinksResource(links);
                                     return OC_STACK_NO_MEMORY;
                                 }
+                                memcpy(devAddr, &pResource->devAddr, sizeof(*devAddr));
                                 return OC_STACK_OK;
                             }
                             temp = temp->next;
@@ -197,7 +196,7 @@ OCStackResult OCRDCheckPublishedResource(const char *interfaceType, const char *
                         OCStringLL *temp = tLinks->itf;
                         while (temp)
                         {
-                            OC_LOG_V(DEBUG, TAG, "Interface Type: %s %s", interfaceType, temp->value);
+                            OIC_LOG_V(DEBUG, TAG, "Interface Type: %s %s", interfaceType, temp->value);
                             if (strcmp(interfaceType, temp->value) == 0)
                             {
                                 OCTagsPayload *tag = pResource->publishedResource->tags;
@@ -221,6 +220,7 @@ OCStackResult OCRDCheckPublishedResource(const char *interfaceType, const char *
                                     OCFreeLinksResource(links);
                                     return OC_STACK_NO_MEMORY;
                                 }
+                                devAddr = &pResource->devAddr;
                                 return OC_STACK_OK;
                             }
                             temp = temp->next;
index aefdb46..e91cee9 100644 (file)
 
 #include "octypes.h"
 
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
 /** Stucture holding Published Resources on the Resource Directory. */
 typedef struct OCRDStorePublishResources
 {
+    OCDevAddr devAddr;
     /** Publish resource. */
     OCResourceCollectionPayload *publishedResource;
     /** Linked list pointing to next published resource. */
index d8bbfa6..a50bf2c 100644 (file)
@@ -52,11 +52,11 @@ static OCStackResult sendRequest(OCMethod method, char *uri, OCDevAddr *addr,
 
     if (result == OC_STACK_OK)
     {
-        OC_LOG(DEBUG, TAG, "Resource Directory send successful...");
+        OIC_LOG(DEBUG, TAG, "Resource Directory send successful...");
     }
     else
     {
-        OC_LOG(ERROR, TAG, "Resource Directory send failed...");
+        OIC_LOG(ERROR, TAG, "Resource Directory send failed...");
     }
 
     return result;
@@ -67,15 +67,15 @@ static OCStackApplicationResult handlePublishCB(__attribute__((unused))void *ctx
         __attribute__((unused)) OCClientResponse *clientResponse)
 {
     OCStackApplicationResult ret = OC_STACK_DELETE_TRANSACTION;
-    OC_LOG(DEBUG, TAG, "Successfully published resources.");
+    OIC_LOG(DEBUG, TAG, "Successfully published resources.");
 
     if (OC_STACK_OK == OCStopMulticastServer())
     {
-        OC_LOG_V(DEBUG, TAG, "Stopped receiving the multicast traffic.");
+        OIC_LOG_V(DEBUG, TAG, "Stopped receiving the multicast traffic.");
     }
     else
     {
-        OC_LOG_V(DEBUG, TAG, "Failed stopping the multicast traffic.");
+        OIC_LOG_V(DEBUG, TAG, "Failed stopping the multicast traffic.");
     }
 
     return ret;
@@ -83,11 +83,10 @@ static OCStackApplicationResult handlePublishCB(__attribute__((unused))void *ctx
 
 static void retreiveRDDetails(OCClientResponse *clientResponse, OCRDBiasFactorCB clientCB)
 {
-    OC_LOG_V(DEBUG, TAG, "\tAddress of the RD: %s:%d", clientResponse->devAddr.addr,
+    OIC_LOG_V(DEBUG, TAG, "\tAddress of the RD: %s:%d", clientResponse->devAddr.addr,
             clientResponse->devAddr.port);
 
-    OCRDPayload *payload = (OCRDPayload *) clientResponse->payload;
-    OC_LOG_PAYLOAD(DEBUG, (OCPayload *) payload);
+    OIC_LOG_PAYLOAD(DEBUG, clientResponse->payload);
 
     // TODO: Multiple Resource Directory will have different biasFactor,
     // needs to cache here detail
@@ -102,31 +101,37 @@ static void retreiveRDDetails(OCClientResponse *clientResponse, OCRDBiasFactorCB
 static OCStackApplicationResult handleDiscoverCB(void *ctx,
         __attribute__((unused)) OCDoHandle handle, OCClientResponse *clientResponse)
 {
-    OC_LOG(DEBUG, TAG, "Found Resource Directory");
+    OIC_LOG(DEBUG, TAG, "Found Resource Directory");
     OCStackApplicationResult ret = OC_STACK_DELETE_TRANSACTION;
 
     OCRDClientContextCB *cb = (OCRDClientContextCB *)ctx;
     if (!cb)
     {
-        OC_LOG(ERROR, TAG, "RD Context Invalid Parameters.");
+        OIC_LOG(ERROR, TAG, "RD Context Invalid Parameters.");
         return ret;
     }
 
     if (cb->context != (void *) DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(ERROR, TAG, "RD Context Invalid Context Value Parameters.");
+        OIC_LOG(ERROR, TAG, "RD Context Invalid Context Value Parameters.");
         return ret;
     }
 
-    OC_LOG_V(DEBUG, TAG, "Callback Context for DISCOVER query received successfully :%d.", clientResponse->result);
-
-    if (clientResponse && clientResponse->result == OC_STACK_OK)
+    if (clientResponse)
     {
-        retreiveRDDetails(clientResponse, cb->cbFunc);
+        OIC_LOG_V(DEBUG, TAG, "Callback Context for DISCOVER query received successfully :%d.", clientResponse->result);
+        if (clientResponse->result == OC_STACK_OK)
+        {
+            retreiveRDDetails(clientResponse, cb->cbFunc);
+        }
+        else
+        {
+            OIC_LOG(ERROR, TAG, "Discovery of RD Failed");
+        }
     }
     else
     {
-        OC_LOG(ERROR, TAG, "Discovery of RD Failed");
+        OIC_LOG(ERROR, TAG, "No client response.");
     }
 
     OICFree(cb);
@@ -138,7 +143,7 @@ OCStackResult OCRDDiscover(OCRDBiasFactorCB cbBiasFactor)
 {
     if (!cbBiasFactor)
     {
-        OC_LOG(DEBUG, TAG, "No callback function specified.");
+        OIC_LOG(DEBUG, TAG, "No callback function specified.");
         return OC_STACK_INVALID_CALLBACK;
     }
 
@@ -146,12 +151,12 @@ OCStackResult OCRDDiscover(OCRDBiasFactorCB cbBiasFactor)
     char queryUri[MAX_URI_LENGTH] = { '\0' };
     snprintf(queryUri, MAX_URI_LENGTH, "coap://%s%s", OC_MULTICAST_PREFIX, OC_RSRVD_RD_URI);
 
-    OC_LOG_V(DEBUG, TAG, "Querying RD: %s\n", queryUri);
+    OIC_LOG_V(DEBUG, TAG, "Querying RD: %s\n", queryUri);
 
     OCRDClientContextCB *cbContext = (OCRDClientContextCB *)OICCalloc(1, sizeof(OCRDClientContextCB));
     if (!cbContext)
     {
-        OC_LOG(ERROR, TAG, "Failed allocating memory.");
+        OIC_LOG(ERROR, TAG, "Failed allocating memory.");
         return OC_STACK_NO_MEMORY;
     }
 
@@ -177,13 +182,13 @@ static OCStackResult createStringLL(uint8_t numElements, OCResourceHandle handle
             *stringLL = (OCStringLL *)OICCalloc(1, sizeof(OCStringLL));
             if (!*stringLL)
             {
-                OC_LOG(ERROR, TAG, "Failed allocating memory.");
+                OIC_LOG(ERROR, TAG, "Failed allocating memory.");
                 return OC_STACK_NO_MEMORY;
             }
             (*stringLL)->value = OICStrdup(value);
             if (!(*stringLL)->value)
             {
-                OC_LOG(ERROR, TAG, "Failed copying to OCStringLL.");
+                OIC_LOG(ERROR, TAG, "Failed copying to OCStringLL.");
                 return OC_STACK_NO_MEMORY;
             }
         }
@@ -197,13 +202,13 @@ static OCStackResult createStringLL(uint8_t numElements, OCResourceHandle handle
             cur->next = (OCStringLL *)OICCalloc(1, sizeof(OCStringLL));
             if (!cur->next)
             {
-                OC_LOG(ERROR, TAG, "Failed allocating memory.");
+                OIC_LOG(ERROR, TAG, "Failed allocating memory.");
                 return OC_STACK_NO_MEMORY;
             }
             cur->next->value = OICStrdup(value);
             if (!cur->next->value)
             {
-                OC_LOG(ERROR, TAG, "Failed copying to OCStringLL.");
+                OIC_LOG(ERROR, TAG, "Failed copying to OCStringLL.");
                 return OC_STACK_NO_MEMORY;
             }
         }
@@ -215,14 +220,14 @@ OCStackResult OCRDPublish(char *addr, uint16_t port, int numArg, ... )
 {
     if (!addr)
     {
-        OC_LOG(ERROR, TAG, "RD address not specified.");
+        OIC_LOG(ERROR, TAG, "RD address not specified.");
         return OC_STACK_INVALID_PARAM;
     }
 
     char targetUri[MAX_URI_LENGTH];
     snprintf(targetUri, MAX_URI_LENGTH, "coap://%s:%d%s?rt=%s", addr, port,
             OC_RSRVD_RD_URI, OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
-    OC_LOG_V(DEBUG, TAG, "Target URI : %s", targetUri);
+    OIC_LOG_V(DEBUG, TAG, "Target URI : %s", targetUri);
 
     // Gather all resources locally and do publish
     OCCallbackData cbData = { 0 };
@@ -266,7 +271,6 @@ OCStackResult OCRDPublish(char *addr, uint16_t port, int numArg, ... )
                 OCStackResult res = createStringLL(numElement, handle, OCGetResourceTypeName, &rt);
                 if (res != OC_STACK_OK || !rt)
                 {
-                    va_end(arguments);
                     goto no_memory;
                 }
             }
@@ -276,7 +280,6 @@ OCStackResult OCRDPublish(char *addr, uint16_t port, int numArg, ... )
                 OCStackResult res = createStringLL(numElement, handle, OCGetResourceInterfaceName, &itf);
                 if (res != OC_STACK_OK || !itf)
                 {
-                    va_end(arguments);
                     goto no_memory;
                 }
             }
@@ -284,13 +287,11 @@ OCStackResult OCRDPublish(char *addr, uint16_t port, int numArg, ... )
             mt = (OCStringLL *)OICCalloc(1, sizeof(OCStringLL));
             if (!mt)
             {
-                va_end(arguments);
                 goto no_memory;
             }
             mt->value = OICStrdup("application/json");
             if (!mt->value)
             {
-                va_end(arguments);
                 goto no_memory;
             }
 
@@ -337,17 +338,33 @@ OCStackResult OCRDPublish(char *addr, uint16_t port, int numArg, ... )
     OICStrcpy(rdAddr.addr, MAX_ADDR_STR_SIZE, addr);
     rdAddr.port = port;
 
-    OC_LOG_PAYLOAD(DEBUG, (OCPayload *) rdPayload);
+    OIC_LOG_PAYLOAD(DEBUG, (OCPayload *) rdPayload);
 
     return sendRequest(OC_REST_POST, targetUri, &rdAddr, (OCPayload *)rdPayload, cbData);
 
 no_memory:
-    OC_LOG(ERROR, TAG, "Failed allocating memory.");
-    OCFreeOCStringLL(rt);
-    OCFreeOCStringLL(itf);
-    OCFreeOCStringLL(mt);
-    OCFreeTagsResource(tagsPayload);
-    OCFreeLinksResource(linksPayload);
+    OIC_LOG(ERROR, TAG, "Failed allocating memory.");
+    va_end(arguments);
+    if (rt)
+    {
+        OCFreeOCStringLL(rt);
+    }
+    if (itf)
+    {
+        OCFreeOCStringLL(itf);
+    }
+    if (mt)
+    {
+        OCFreeOCStringLL(mt);
+    }
+    if (tagsPayload)
+    {
+        OCFreeTagsResource(tagsPayload);
+    }
+    if (linksPayload)
+    {
+        OCFreeLinksResource(linksPayload);
+    }
     OCRDPayloadDestroy(rdPayload);
     return OC_STACK_NO_MEMORY;
 }
index 7713679..e97fedf 100644 (file)
@@ -47,12 +47,12 @@ static OCEntityHandlerResult handleGetRequest(const OCEntityHandlerRequest *ehRe
 {
     if (!ehRequest)
     {
-        OC_LOG(DEBUG, TAG, "Invalid request pointer.");
+        OIC_LOG(DEBUG, TAG, "Invalid request pointer.");
         return OC_EH_ERROR;
     }
 
     OCEntityHandlerResult ehResult = OC_EH_OK;
-    OC_LOG_V(DEBUG, TAG, "Received OC_REST_GET from client with query: %s.", ehRequest->query);
+    OIC_LOG_V(DEBUG, TAG, "Received OC_REST_GET from client with query: %s.", ehRequest->query);
 
     OCRDPayload *rdPayload = OCRDPayloadCreate();
     if (!rdPayload)
@@ -67,11 +67,11 @@ static OCEntityHandlerResult handleGetRequest(const OCEntityHandlerRequest *ehRe
         return OC_STACK_NO_MEMORY;
     }
 
-    OC_LOG_PAYLOAD(DEBUG, (OCPayload *) rdPayload);
+    OIC_LOG_PAYLOAD(DEBUG, (OCPayload *) rdPayload);
 
     if (sendResponse(ehRequest, rdPayload) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "Sending response failed.");
+        OIC_LOG(ERROR, TAG, "Sending response failed.");
         ehResult = OC_EH_ERROR;
     }
 
@@ -88,11 +88,11 @@ static OCEntityHandlerResult handlePublishRequest(const OCEntityHandlerRequest *
 
     if (!ehRequest)
     {
-        OC_LOG(DEBUG, TAG, "Invalid request pointer");
+        OIC_LOG(DEBUG, TAG, "Invalid request pointer");
         return OC_EH_ERROR;
     }
 
-    OC_LOG_V(DEBUG, TAG, "Received OC_REST_PUT from client with query: %s.", ehRequest->query);
+    OIC_LOG_V(DEBUG, TAG, "Received OC_REST_PUT from client with query: %s.", ehRequest->query);
 
     OCRDPayload *payload = (OCRDPayload *)ehRequest->payload;
     if (payload && payload->rdPublish)
@@ -103,15 +103,15 @@ static OCEntityHandlerResult handlePublishRequest(const OCEntityHandlerRequest *
     OCRDPayload *rdPayload = OCRDPayloadCreate();
     if (!rdPayload)
     {
-        OC_LOG(ERROR, TAG, "Failed allocating memory.");
+        OIC_LOG(ERROR, TAG, "Failed allocating memory.");
         return OC_STACK_NO_MEMORY;
     }
 
-    OC_LOG_PAYLOAD(DEBUG, (OCPayload *) rdPayload);
+    OIC_LOG_PAYLOAD(DEBUG, (OCPayload *) rdPayload);
 
     if (sendResponse(ehRequest, rdPayload) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "Sending response failed.");
+        OIC_LOG(ERROR, TAG, "Sending response failed.");
         ehResult = OC_EH_ERROR;
     }
 
@@ -134,7 +134,7 @@ static OCEntityHandlerResult rdEntityHandler(OCEntityHandlerFlag flag,
 
     if (flag & OC_REQUEST_FLAG)
     {
-        OC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG.");
+        OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG.");
         switch (ehRequest->method)
         {
             case OC_REST_GET:
@@ -175,11 +175,11 @@ OCStackResult OCRDStart()
 
     if (result == OC_STACK_OK)
     {
-        OC_LOG(DEBUG, TAG, "Resource Directory Started.");
+        OIC_LOG(DEBUG, TAG, "Resource Directory Started.");
     }
     else
     {
-        OC_LOG(ERROR, TAG, "Failed starting Resource Directory.");
+        OIC_LOG(ERROR, TAG, "Failed starting Resource Directory.");
     }
 
     return result;
@@ -194,11 +194,11 @@ OCStackResult OCRDStop()
 
     if (result == OC_STACK_OK)
     {
-        OC_LOG(DEBUG, TAG, "Resource Directory Stopped.");
+        OIC_LOG(DEBUG, TAG, "Resource Directory Stopped.");
     }
     else
     {
-        OC_LOG(ERROR, TAG, "Failed stopping Resource Directory.");
+        OIC_LOG(ERROR, TAG, "Failed stopping Resource Directory.");
     }
     return result;
 }
index 29b7722..d82b5f5 100644 (file)
@@ -95,14 +95,14 @@ ResourceClientsdk_shared = resourceClient_env.SharedLibrary('rcs_client', client
 
 resourceClient_env.InstallTarget([ResourceClientsdk_static,ResourceClientsdk_shared], 'librcs_client')
 resourceClient_env.UserInstallTargetLib([ResourceClientsdk_static,ResourceClientsdk_shared], 'librcs_client')
-resourceClient_env.UserInstallTargetHeader('include/RCSAddress.h', 'iotivity-service', 'RCSAddress.h')
-resourceClient_env.UserInstallTargetHeader('include/RCSDiscoveryManager.h', 'iotivity-service', 'RCSDiscoveryManager.h')
-resourceClient_env.UserInstallTargetHeader('include/RCSRemoteResourceObject.h', 'iotivity-service', 'RCSRemoteResourceObject.h')
-resourceClient_env.UserInstallTargetHeader('include/RCSResourceAttributes.h', 'iotivity-service', 'RCSResourceAttributes.h')
-resourceClient_env.UserInstallTargetHeader('include/RCSResourceObject.h', 'iotivity-service', 'RCSResourceObject.h')
-resourceClient_env.UserInstallTargetHeader('include/RCSException.h', 'iotivity-service', 'RCSException.h')
-resourceClient_env.UserInstallTargetHeader('include/RCSRequest.h', 'iotivity-service', 'RCSRequest.h')
-resourceClient_env.UserInstallTargetHeader('include/RCSResponse.h', 'iotivity-service', 'RCSResponse.h')
+resourceClient_env.UserInstallTargetHeader('include/RCSAddress.h', 'service/resource-encapsulation', 'RCSAddress.h')
+resourceClient_env.UserInstallTargetHeader('include/RCSDiscoveryManager.h', 'service/resource-encapsulation', 'RCSDiscoveryManager.h')
+resourceClient_env.UserInstallTargetHeader('include/RCSRemoteResourceObject.h', 'service/resource-encapsulation', 'RCSRemoteResourceObject.h')
+resourceClient_env.UserInstallTargetHeader('include/RCSResourceAttributes.h', 'service/resource-encapsulation', 'RCSResourceAttributes.h')
+resourceClient_env.UserInstallTargetHeader('include/RCSResourceObject.h', 'service/resource-encapsulation', 'RCSResourceObject.h')
+resourceClient_env.UserInstallTargetHeader('include/RCSException.h', 'service/resource-encapsulation', 'RCSException.h')
+resourceClient_env.UserInstallTargetHeader('include/RCSRequest.h', 'service/resource-encapsulation', 'RCSRequest.h')
+resourceClient_env.UserInstallTargetHeader('include/RCSResponse.h', 'service/resource-encapsulation', 'RCSResponse.h')
 
 ######################################################################
 # Build Sample App: SampleResourceClient & SampleResourceServer
@@ -110,7 +110,7 @@ resourceClient_env.UserInstallTargetHeader('include/RCSResponse.h', 'iotivity-se
 SConscript('examples/SConscript')
 
 ######################################################################
-# Build UnitTests Resource Client , resourceCache and resourceBroker and
+# Build UnitTests Resource Client , resourceCache and resourceBroker and 
 # DiscoveryManager
 ################################################ ######################
 if target_os == 'linux':
index f890404..915004e 100644 (file)
@@ -224,6 +224,8 @@ public final class RcsResourceObject extends RcsObject {
          *
          * @throws RcsIllegalStateException
          *             if not in locked state
+         * @throws RcsPlatformException
+         *             if auto notify failed
          */
         public void apply() throws RcsIllegalStateException {
             if (mCurrentAttributes == null) {
index 01d8daf..9ab9118 100644 (file)
@@ -23,6 +23,7 @@ OIC_SRC_DIR := ../../../../../..
 LOCAL_MODULE := rcs_jni
 
 LOCAL_C_INCLUDES := $(LOCAL_PATH)/util
+LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/include
 LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/c_common
 LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/csdk/stack/include
 LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/extlibs/boost/boost_1_58_0
index 98273c9..ad05590 100644 (file)
@@ -25,6 +25,7 @@
 #include "JniRcsValue.h"
 #include "Log.h"
 #include "Verify.h"
+#include "JavaExceptions.h"
 
 #include "RCSResourceObject.h"
 
@@ -153,7 +154,15 @@ Java_org_iotivity_service_server_RcsLockedAttributes_nativeApply
     auto res = getResource(env, resourceObject);
     VERIFY_NO_EXC(env);
 
-    writeNativeAttributesFromMap(env, cacheObj, res->getAttributes());
+    try
+    {
+        RCSResourceObject::LockGuard lock(res);
+        writeNativeAttributesFromMap(env, cacheObj, res->getAttributes());
+    }
+    catch (const RCSPlatformException& e)
+    {
+        throwPlatformException(env, e);
+    }
 }
 
 JNIEXPORT void JNICALL
@@ -163,7 +172,8 @@ Java_org_iotivity_service_server_RcsLockedAttributes_nativeLock
     auto res = getResource(env, resourceObject);
     VERIFY_NO_EXC(env);
 
-    setSafeNativeHandle< RCSResourceObject::LockGuard >(env, obj, res);
+    setSafeNativeHandle< RCSResourceObject::LockGuard >(env, obj,
+            res, RCSResourceObject::AutoNotifyPolicy::NEVER);
 }
 
 JNIEXPORT void JNICALL
index 4354032..fe47ef8 100644 (file)
@@ -32,6 +32,7 @@
 
 #include "RCSResourceObject.h"
 #include "RCSResponse.h"
+#include "RCSRequest.h"
 #include "RequestHandler.h"
 
 #define LOG_TAG "JNI-RCSResourceObject"
@@ -503,7 +504,7 @@ Java_org_iotivity_service_server_RcsResourceObject_nativeGetAttributes
     auto res = getResource(env, obj);
     VERIFY_NO_EXC_RET_DEF(env);
 
-    RCSResourceObject::LockGuard lock{ res };
+    RCSResourceObject::LockGuard lock{ res, RCSResourceObject::AutoNotifyPolicy::NEVER };
     return newAttributesObject(env, res->getAttributes());
 }
 
index 7b4983f..923ee3b 100644 (file)
@@ -2,7 +2,7 @@ apply plugin: 'com.android.application'
 
 android {
     compileSdkVersion 21
-    buildToolsVersion "21.1.2"
+    buildToolsVersion "20.0.0"
 
     defaultConfig {
         applicationId "org.iotivity.service.sample.client"
index f25cfb2..cb1c742 100644 (file)
@@ -63,6 +63,7 @@ public class ResourceClientActivity extends Activity
     private static final int MSG_ID_ATTRIBUTE_RECEIVED  = 1;
     private static final int MSG_ID_PRINT_LOG           = 2;
 
+    private static final String RESOURCE_TYPE = "oic.r.temperature.sensor";
     private static final String ATTR_KEY_TEMPERATURE = "Temperature";
 
     private TextView mLogView;
@@ -128,6 +129,10 @@ public class ResourceClientActivity extends Activity
             }
 
             mResourceObj.startMonitoring(mOnStateChangedListener);
+
+            if (mResourceObj.isMonitoring()) {
+                printLog("Monitoring started successfully");
+            }
         }
     };
 
@@ -135,8 +140,13 @@ public class ResourceClientActivity extends Activity
         @Override
         public void execute() throws RcsException {
             if (mResourceObj.isMonitoring()) {
+
                 mResourceObj.stopMonitoring();
-                printLog("Stopped Resource Monitoring");
+
+                if (!mResourceObj.isMonitoring()) {
+                    printLog("Monitoring stopped successfully");
+                }
+
             } else {
                 printLog("Monitoring not started");
             }
@@ -168,6 +178,11 @@ public class ResourceClientActivity extends Activity
             }
 
             mResourceObj.startCaching(mOnCacheUpdatedListener);
+
+            if (mResourceObj.isCaching()) {
+                printLog("Caching started successfully");
+            }
+
         }
     };
 
@@ -197,8 +212,21 @@ public class ResourceClientActivity extends Activity
     private Item mStopCaching = new Item("9. Stop Caching") {
         @Override
         public void execute() throws RcsException {
-            mResourceObj.stopCaching();
+            if (mResourceObj.isCaching()) {
+
+                mResourceObj.stopCaching();
+
+                if (!mResourceObj.isCaching()) {
+                    printLog("Caching stopped successfully");
+                } else {
+                    printLog("Stopping caching unsuccessful");
+                }
+
+            } else {
+                printLog("Caching not started");
+            }
         }
+
     };
 
     @Override
@@ -219,10 +247,8 @@ public class ResourceClientActivity extends Activity
     protected void onDestroy() {
         super.onDestroy();
 
-        if (mDiscoveryTask != null)
-            mDiscoveryTask.cancel();
-        if (mResourceObj != null)
-            mResourceObj.destroy();
+        if (mDiscoveryTask != null) mDiscoveryTask.cancel();
+        if (mResourceObj != null) mResourceObj.destroy();
     }
 
     private void initMenuList() {
@@ -262,7 +288,7 @@ public class ResourceClientActivity extends Activity
         if (mDiscoveryTask == null) {
             try {
                 mDiscoveryTask = RcsDiscoveryManager.getInstance()
-                        .discoverResource(RcsAddress.multicast(),
+                        .discoverResourceByType(RcsAddress.multicast(), RESOURCE_TYPE,
                                 mOnResourceDiscoveredListener);
                 mDiscoveryBtn.setText(R.string.cancel_discovery);
 
@@ -414,8 +440,7 @@ public class ResourceClientActivity extends Activity
             super.handleMessage(msg);
 
             ResourceClientActivity activity = mActivityRef.get();
-            if (activity == null)
-                return;
+            if (activity == null) return;
 
             switch (msg.what) {
                 case MSG_ID_RESOURCE_DISCOVERED:
index f6bc21a..30a16ff 100644 (file)
@@ -2,7 +2,7 @@ apply plugin: 'com.android.application'
 
 android {
     compileSdkVersion 21
-    buildToolsVersion "21.1.2"
+    buildToolsVersion "20.0.0"
 
     defaultConfig {
         applicationId "org.iotivity.service.sample.server"
diff --git a/service/resource-encapsulation/examples/linux/NestedAttributeClient.cpp b/service/resource-encapsulation/examples/linux/NestedAttributeClient.cpp
deleted file mode 100644 (file)
index 73a417a..0000000
+++ /dev/null
@@ -1,334 +0,0 @@
-//******************************************************************
-//
-// 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<iostream>
-#include "mutex"
-#include "condition_variable"
-
-#include "RCSDiscoveryManager.h"
-#include "RCSRemoteResourceObject.h"
-#include "RCSResourceAttributes.h"
-#include "RCSAddress.h"
-
-#include "OCPlatform.h"
-
-#define nestedAtrribute std::vector<std::vector<RCSResourceAttributes>>
-
-using namespace OC;
-using namespace OIC::Service;
-
-constexpr int CORRECT_INPUT = 1;
-constexpr int INCORRECT_INPUT = 2;
-constexpr int QUIT_INPUT = 3;
-
-std::shared_ptr<RCSRemoteResourceObject>  resource;
-
-const std::string defaultKey = "deviceInfo";
-const std::string resourceType = "core.ac";
-const std::string relativetUri = OC_RSRVD_WELL_KNOWN_URI;
-
-RCSResourceAttributes model;
-RCSResourceAttributes speed;
-RCSResourceAttributes airCirculation;
-RCSResourceAttributes temperature;
-RCSResourceAttributes humidity;
-RCSResourceAttributes power;
-RCSResourceAttributes capacity;
-RCSResourceAttributes weight;
-RCSResourceAttributes dimensions;
-RCSResourceAttributes red;
-RCSResourceAttributes green;
-
-std::vector<RCSResourceAttributes> generalInfo;
-std::vector<RCSResourceAttributes> fan;
-std::vector<RCSResourceAttributes> tempSensor;
-std::vector<RCSResourceAttributes> efficiency;
-std::vector<RCSResourceAttributes> light;
-
-
-std::mutex mtx;
-std::condition_variable cond;
-
-void getAttributeFromRemoteServer();
-void setAttributeToRemoteServer();
-
-enum Menu
-{
-    GET_ATTRIBUTE = 1,
-    SET_ATTRIBUTE,
-    QUIT,
-    END_OF_MENU
-};
-
-typedef void(*ClientMenuHandler)();
-typedef int ReturnValue;
-
-struct ClientMenu
-{
-    Menu m_menu;
-    ClientMenuHandler m_handler;
-    ReturnValue m_result;
-};
-
-ClientMenu clientMenu[] =
-{
-    {Menu::GET_ATTRIBUTE, getAttributeFromRemoteServer, CORRECT_INPUT},
-    {Menu::SET_ATTRIBUTE, setAttributeToRemoteServer, CORRECT_INPUT},
-    {Menu::QUIT, [](){}, QUIT_INPUT},
-    {Menu::END_OF_MENU, nullptr, INCORRECT_INPUT}
-};
-
-void displayMenu()
-{
-    std::cout << std::endl;
-    std::cout << "1 :: Get Attribute" << std::endl;
-    std::cout << "2 :: Set Attribute" << std::endl;
-}
-
-void onResourceDiscovered(std::shared_ptr<RCSRemoteResourceObject> foundResource)
-{
-    std::cout << "onResourceDiscovered callback" << std::endl;
-
-    std::string resourceURI = foundResource->getUri();
-    std::string hostAddress = foundResource->getAddress();
-
-    std::cout << "\t\tResource URI : " << resourceURI << std::endl;
-    std::cout << "\t\tResource Host : " << hostAddress << std::endl;
-
-    resource = foundResource;
-
-    cond.notify_all();
-}
-
-void onRemoteAttributesReceivedCallback(const RCSResourceAttributes &attributes, int /*eCode*/)
-{
-    std::cout << "onRemoteAttributesReceivedCallback callback\n" << std::endl;
-
-    if (attributes.empty())
-    {
-        std::cout << "\tAttribute is Empty" << std::endl;
-        return;
-    }
-
-    for (const auto & attr : attributes)
-    {
-        std::cout << "\tkey : " << attr.key() << "\n\tvalue : "
-                  << attr.value().toString() << std::endl;
-        std::cout << "=============================================\n" << std::endl;
-
-        OIC::Service::RCSResourceAttributes::Value attrValue =  attr.value();
-        std::vector< std::vector<RCSResourceAttributes >> attrVector =
-                    attrValue.get<std::vector< std::vector<RCSResourceAttributes >>>();
-
-        for (auto itr = attrVector.begin(); itr != attrVector.end(); ++itr)
-        {
-            std::vector<RCSResourceAttributes > attrKeyVector = *itr;
-            for (auto itrKey = attrKeyVector.begin(); itrKey != attrKeyVector.end(); ++itrKey)
-            {
-                for (const auto & attribute : *itrKey)
-                {
-                    std::cout << "\t" << attribute.key() << "  :  "  << attribute.value().toString() << std::endl;
-                }
-            }
-            std::cout << std::endl;
-        }
-    }
-    std::cout << "=============================================\n" << std::endl;
-    displayMenu();
-}
-
-nestedAtrribute createNestedAttribute(int speedValue, int aircValue)
-{
-    nestedAtrribute *acServer = new nestedAtrribute();
-
-    model["model"] = "SamsungAC";
-
-    speed["speed"] = speedValue;
-    airCirculation["air"] = aircValue;
-
-    temperature["temp"] = 30;
-    humidity["humidity"] = 30;
-
-    power["power"] = 1600;
-    capacity["capacity"] = 1;
-
-    weight["weight"] = 3;
-    dimensions["dimensions"] = "10x25x35";
-
-    red["red"] = 50;
-    green["green"] = 60;
-
-    generalInfo.clear();
-    generalInfo.push_back(model);
-    generalInfo.push_back(weight);
-    generalInfo.push_back(dimensions);
-
-    fan.clear();
-    fan.push_back(speed);
-    fan.push_back(airCirculation);
-
-    tempSensor.clear();
-    tempSensor.push_back(temperature);
-    tempSensor.push_back(humidity);
-
-    efficiency.clear();
-    efficiency.push_back(power);
-    efficiency.push_back(capacity);
-
-    light.clear();
-    light.push_back(red);
-    light.push_back(green);
-
-    if (nullptr == acServer)
-    {
-         std::cout << "Null nestedAtrribute" << std::endl;
-    }
-    else
-    {
-        acServer->push_back(generalInfo);
-        acServer->push_back(fan);
-        acServer->push_back(tempSensor);
-        acServer->push_back(efficiency);
-        acServer->push_back(light);
-    }
-
-    return *acServer;
-}
-
-int processUserInput()
-{
-    int userInput;
-    std::cin >> userInput;
-    if (std::cin.fail())
-    {
-        std::cin.clear();
-        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
-        return -1;
-    }
-    return userInput;
-}
-
-void getAttributeFromRemoteServer()
-{
-    if(nullptr == resource)
-        return;
-
-    resource->getRemoteAttributes(&onRemoteAttributesReceivedCallback);
-}
-
-void setAttributeToRemoteServer()
-{
-    if(nullptr == resource)
-        return;
-
-    int speed, airc;
-
-    std::cout << "\tEnter the Fan Speed you want to set : ";
-    std::cin >> speed;
-    std::cout << "\tEnter the Air circulation value you want to set :";
-    std::cin >> airc;
-
-    nestedAtrribute nestedAttr = createNestedAttribute(speed, airc);
-
-    RCSResourceAttributes setAttribute;
-    setAttribute[defaultKey] = nestedAttr;
-
-    resource->setRemoteAttributes(setAttribute,
-                                  &onRemoteAttributesReceivedCallback);
-}
-
-int selectClientMenu(int selectedMenu)
-{
-    for (int i = 0; clientMenu[i].m_menu != Menu::END_OF_MENU; i++)
-    {
-        if (clientMenu[i].m_menu == selectedMenu)
-        {
-            clientMenu[i].m_handler();
-            return clientMenu[i].m_result;
-        }
-    }
-
-    std::cout << "Invalid input, please try again" << std::endl;
-
-    return INCORRECT_INPUT;
-}
-
-void process()
-{
-    while (true)
-    {
-        displayMenu();
-
-        if (selectClientMenu(processUserInput()) == QUIT_INPUT)
-            break;
-    }
-}
-
-void platFormConfigure()
-{
-    PlatformConfig config
-    {
-        OC::ServiceType::InProc, ModeType::Client, "0.0.0.0", 0, OC::QualityOfService::LowQos
-    };
-    OCPlatform::Configure(config);
-}
-
-bool discoverResource()
-{
-    std::cout << "Wait 2 seconds until discovered." << std::endl;
-
-    try
-    {
-        RCSDiscoveryManager::getInstance()->discoverResourceByType(RCSAddress::multicast(),
-                relativetUri, resourceType, &onResourceDiscovered);
-    }
-    catch(const RCSPlatformException& e)
-    {
-         std::cout << e.what() << std::endl;
-    }
-    std::unique_lock<std::mutex> lck(mtx);
-    cond.wait_for(lck, std::chrono::seconds(2));
-
-    return resource != nullptr;
-}
-
-int main()
-{
-    platFormConfigure();
-
-    if (!discoverResource())
-    {
-        std::cout << "Can't discovered Server... Exiting the Client." << std::endl;
-        return -1;
-    }
-
-    try
-    {
-        process();
-    }
-    catch (const std::exception &e)
-    {
-        std::cout << "main exception : " << e.what() << std::endl;
-    }
-
-    std::cout << "Stopping the Client" << std::endl;
-
-    return 0;
-}
diff --git a/service/resource-encapsulation/examples/linux/NestedAttributeServer.cpp b/service/resource-encapsulation/examples/linux/NestedAttributeServer.cpp
deleted file mode 100644 (file)
index 86a8a3d..0000000
+++ /dev/null
@@ -1,367 +0,0 @@
-/******************************************************************
- *
- * 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 "PrimitiveResource.h"
-#include "RCSResourceObject.h"
-#include "OCPlatform.h"
-#include "OCApi.h"
-
-#define nestedAtrribute std::vector<std::vector<RCSResourceAttributes>>
-
-using namespace OC;
-using namespace OC::OCPlatform;
-using namespace OIC::Service;
-
-constexpr int DEFAULT_SPEED = 30;
-constexpr int UP_SPEED = 50;
-constexpr int DOWN_SPEED = 10;
-
-constexpr int DEFALUT_SERVER = 1;
-constexpr int CUSTOM_SERVER = 2;
-constexpr int STOP = 3;
-
-constexpr int PRINT_ATTRIBUTES = 1;
-constexpr int INCREASE_SPEEDATTRIBUTE = 2;
-constexpr int DECREASE_SPEEDATTRIBUTE = 3;
-constexpr int STOP_SENSOR = 4;
-
-constexpr int CORRECT_INPUT = 1;
-constexpr int INCORRECT_INPUT = 2;
-constexpr int QUIT = 3;
-
-std::string resourceUri = "/a/airConditioner";
-std::string resourceType = "core.ac";
-std::string resourceInterface = "oic.if.";
-std::string attributeKey = "deviceInfo";
-
-RCSResourceAttributes model;
-RCSResourceAttributes speed;
-RCSResourceAttributes airCirculation;
-RCSResourceAttributes temperature;
-RCSResourceAttributes humidity;
-RCSResourceAttributes power;
-RCSResourceAttributes capacity;
-RCSResourceAttributes weight;
-RCSResourceAttributes dimensions;
-RCSResourceAttributes red;
-RCSResourceAttributes green;
-
-std::vector<RCSResourceAttributes> generalInfo;
-std::vector<RCSResourceAttributes> fan;
-std::vector<RCSResourceAttributes> tempSensor;
-std::vector<RCSResourceAttributes> efficiency;
-std::vector<RCSResourceAttributes> light;
-
-RCSResourceObject::Ptr server;
-
-void displayMenu()
-{
-    std::cout << "====================================================================="
-              << std::endl;
-    std::cout << "   1 - Creation of Resource [Auto control for requests]" << std::endl;
-    std::cout << "   2 - Creation of Resource [Developer control for Get and Set requests]"
-              << std::endl;
-    std::cout << "   3 - Quit" << std::endl;
-    std::cout << "====================================================================="
-              << std::endl;
-}
-
-void displayControlMenu()
-{
-    std::cout << "========================================================" << std::endl;
-    std::cout << "1. Print Nested attributes" << std::endl;
-    std::cout << "2. Increase Speed attributes" << std::endl;
-    std::cout << "3. Decrease Speed attributes" << std::endl;
-    std::cout << "4. Stop the Sensor" << std::endl;
-    std::cout << "========================================================" << std::endl;
-}
-
-nestedAtrribute createNestedAttribute(int speedValue)
-{
-    nestedAtrribute *acServer = new nestedAtrribute();
-
-    model["model"] = "SamsungAC";
-
-    speed["speed"] = speedValue;
-    airCirculation["air"] = 425;
-
-    temperature["temp"] = 30;
-    humidity["humidity"] = 30;
-
-    power["power"] = 1600;
-    capacity["capacity"] = 1;
-
-    weight["weight"] = 3;
-    dimensions["dimensions"] = "10x25x35";
-
-    red["red"] = 50;
-    green["green"] = 60;
-
-    generalInfo.clear();
-    generalInfo.push_back(model);
-    generalInfo.push_back(weight);
-    generalInfo.push_back(dimensions);
-
-    fan.clear();
-    fan.push_back(speed);
-    fan.push_back(airCirculation);
-
-    tempSensor.clear();
-    tempSensor.push_back(temperature);
-    tempSensor.push_back(humidity);
-
-    efficiency.clear();
-    efficiency.push_back(power);
-    efficiency.push_back(capacity);
-
-    light.clear();
-    light.push_back(red);
-    light.push_back(green);
-
-    if (nullptr == acServer)
-    {
-         std::cout << "Null nestedAtrribute" << std::endl;
-    }
-    else
-    {
-        acServer->push_back(generalInfo);
-        acServer->push_back(fan);
-        acServer->push_back(tempSensor);
-        acServer->push_back(efficiency);
-        acServer->push_back(light);
-    }
-
-    return *acServer;
-}
-
-void printAttribute(const RCSResourceAttributes &attrs)
-{
-    for (const auto & attr : attrs)
-    {
-        std::cout << "\tkey : " << attr.key() << "\n\tvalue : "
-                  << attr.value().toString() << std::endl;
-        std::cout << "=============================================\n" << std::endl;
-
-        OIC::Service::RCSResourceAttributes::Value attrValue =  attr.value();
-        std::vector< std::vector<RCSResourceAttributes >> attrVector =
-                    attrValue.get<std::vector< std::vector<RCSResourceAttributes >>>();
-
-        for (auto itr = attrVector.begin(); itr != attrVector.end(); ++itr)
-        {
-            std::vector<RCSResourceAttributes > attrKeyVector = *itr;
-            for (auto itrKey = attrKeyVector.begin(); itrKey != attrKeyVector.end(); ++itrKey)
-            {
-                for (const auto & attribute : *itrKey)
-                {
-                    std::cout << "\t" << attribute.key() << "  :  "  << attribute.value().toString() << std::endl;
-                }
-            }
-            std::cout << std::endl;
-        }
-        std::cout << "=============================================\n" << std::endl;
-    }
-}
-
-void printNestedAttribute()
-{
-    RCSResourceObject::LockGuard lock(*server);
-    RCSResourceAttributes attributes = server->getAttributes();
-
-    std::cout << "\nPrinting nested attributes" << std::endl;
-    printAttribute(attributes);
-    return;
-}
-
-void changeSpeedAttribute(int state)
-{
-    nestedAtrribute attr;
-
-    if (INCREASE_SPEEDATTRIBUTE == state)
-    {
-        std::cout << "Increasing speed  attribute to : " << UP_SPEED  <<  std::endl;
-        attr = createNestedAttribute(UP_SPEED);
-    }
-    else if (DECREASE_SPEEDATTRIBUTE == state)
-    {
-        std::cout << "Decreasing speed  attribute to : " << DOWN_SPEED << std::endl;
-        attr = createNestedAttribute(DOWN_SPEED);
-    }
-
-    RCSResourceObject::LockGuard lock(*server);
-    server->getAttributes()[attributeKey] = attr;
-    printNestedAttribute();
-}
-
-//hander for get request (if developer choose second option for resource Creation)
-RCSGetResponse requestHandlerForGet(const RCSRequest &request,
-                                    RCSResourceAttributes &attrs)
-{
-    std::cout << "Recieved a Get request from Client" << std::endl;
-
-    RCSResourceObject::LockGuard lock(*server);
-    RCSResourceAttributes attributes = server->getAttributes();
-
-    std::cout << "\nSending response to Client : " << std::endl;
-    printAttribute(attributes);
-
-    return RCSGetResponse::defaultAction();
-}
-
-//hander for set request (if developer choose second option for resource Creation)
-RCSSetResponse requestHandlerForSet(const RCSRequest &request,
-                                    RCSResourceAttributes &attrs)
-{
-    std::cout << "Recieved a Set request from Client" << std::endl;
-
-    std::cout << "\n\nSending response to Client : " << std::endl;
-    RCSResourceObject::LockGuard lock(*server);
-    printAttribute(attrs);
-    return RCSSetResponse::defaultAction();
-}
-
-void createResource()
-{
-    server = RCSResourceObject::Builder(resourceUri, resourceType,
-                                        resourceInterface).setDiscoverable(true).setObservable(true).build();
-}
-
-void initServer()
-{
-    try
-    {
-        createResource();
-    }
-    catch (const RCSPlatformException &e)
-    {
-        std::cout << "Exception in initServer : " << e.what() << std::endl;
-    }
-
-    if (nullptr == server)
-    {
-         std::cout << "Null server resource" << std::endl;
-         return;
-    }
-
-    server->setAutoNotifyPolicy(RCSResourceObject::AutoNotifyPolicy::UPDATED);
-    server->setSetRequestHandlerPolicy(RCSResourceObject::SetRequestHandlerPolicy::NEVER);
-
-    nestedAtrribute attr = createNestedAttribute(DEFAULT_SPEED);
-    server->setAttribute(attributeKey, attr);
-}
-
-int processUserInput()
-{
-    int userInput;
-    std::cin >> userInput;
-    if (std::cin.fail())
-    {
-        std::cin.clear();
-        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
-        return -1;
-    }
-    return userInput;
-}
-
-int selectControlMenu()
-{
-    switch (processUserInput())
-    {
-        case PRINT_ATTRIBUTES:
-            printNestedAttribute();
-            return CORRECT_INPUT;
-
-        case INCREASE_SPEEDATTRIBUTE:
-            changeSpeedAttribute(INCREASE_SPEEDATTRIBUTE);
-            return CORRECT_INPUT;
-
-        case DECREASE_SPEEDATTRIBUTE:
-            changeSpeedAttribute(DECREASE_SPEEDATTRIBUTE);
-            return CORRECT_INPUT;
-
-        case STOP_SENSOR:
-            return QUIT;
-
-        default:
-            std::cout << "Invalid input. Please try again." << std::endl;
-            return INCORRECT_INPUT;
-    }
-}
-
-int selectServerMenu()
-{
-    switch (processUserInput())
-    {
-        case DEFALUT_SERVER: // Creation of Resource & Auto control for all requests from Client.
-            initServer();
-            return CORRECT_INPUT;
-
-        case CUSTOM_SERVER:
-            // Creation of Resource & setting get and set handler for handling get and
-            // set request from client in application.
-            initServer();
-
-            server->setGetRequestHandler(requestHandlerForGet);
-            server->setSetRequestHandler(requestHandlerForSet);
-            return CORRECT_INPUT;
-        case STOP :
-            return QUIT;
-
-        default :
-            std::cout << "Invalid input, please try again" << std::endl;
-            return INCORRECT_INPUT;
-    }
-}
-
-void process()
-{
-    while (true)
-    {
-        displayMenu();
-
-        int ret = selectServerMenu();
-
-        if (ret == QUIT) return;
-        if (ret == CORRECT_INPUT) break;
-    }
-
-    while (true)
-    {
-        displayControlMenu();
-
-        if (selectControlMenu() == QUIT) return;
-    }
-}
-
-int main(void)
-{
-    startPresence(3);
-
-    try
-    {
-        process();
-        server = NULL;
-    }
-    catch (const std::exception &e)
-    {
-        std::cout << "main exception  : " << e.what() << std::endl;
-    }
-
-    std::cout << "Stopping the Server" << std::endl;
-}
diff --git a/service/resource-encapsulation/examples/linux/NestedAttributesClient.cpp b/service/resource-encapsulation/examples/linux/NestedAttributesClient.cpp
new file mode 100644 (file)
index 0000000..5c764f7
--- /dev/null
@@ -0,0 +1,295 @@
+//******************************************************************
+//
+// 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 <iostream>
+
+#include <mutex>
+#include <condition_variable>
+
+#include "RCSDiscoveryManager.h"
+#include "RCSRemoteResourceObject.h"
+#include "RCSResourceAttributes.h"
+#include "RCSAddress.h"
+
+#include "OCPlatform.h"
+
+using namespace OC;
+using namespace OIC::Service;
+
+constexpr int CORRECT_INPUT = 1;
+constexpr int INCORRECT_INPUT = 2;
+constexpr int QUIT_INPUT = 3;
+
+enum Menu
+{
+    GET_ATTRIBUTE = 1,
+    SET_ATTRIBUTE,
+    QUIT,
+    END_OF_MENU
+};
+
+typedef void(*ClientMenuHandler)();
+typedef int ReturnValue;
+
+struct ClientMenu
+{
+    Menu m_menu;
+    ClientMenuHandler m_handler;
+    ReturnValue m_result;
+};
+
+void getAttributeFromRemoteServer();
+void setAttributeToRemoteServer();
+
+ClientMenu clientMenu[] =
+{
+    {Menu::GET_ATTRIBUTE, getAttributeFromRemoteServer, CORRECT_INPUT},
+    {Menu::SET_ATTRIBUTE, setAttributeToRemoteServer, CORRECT_INPUT},
+    {Menu::QUIT, [](){}, QUIT_INPUT},
+    {Menu::END_OF_MENU, nullptr, INCORRECT_INPUT}
+};
+
+const std::string defaultKey = "deviceInfo";
+const std::string resourceType = "core.ac";
+
+std::mutex mtx;
+std::condition_variable cond;
+
+RCSRemoteResourceObject::Ptr g_resource;
+
+void displayMenu()
+{
+    std::cout << std::endl;
+    std::cout << "1 :: Get Attribute" << std::endl;
+    std::cout << "2 :: Set Attribute" << std::endl;
+}
+
+void onResourceDiscovered(RCSRemoteResourceObject::Ptr foundResource)
+{
+    std::cout << "onResourceDiscovered callback" << std::endl;
+
+    std::cout << "\t\tResource URI : " << foundResource->getUri() << std::endl;
+    std::cout << "\t\tResource Host : " << foundResource->getAddress() << std::endl;
+
+    g_resource = foundResource;
+
+    cond.notify_all();
+}
+
+void onRemoteAttributesReceivedCallback(const RCSResourceAttributes &attributes, int /*eCode*/)
+{
+    std::cout << "onRemoteAttributesReceivedCallback callback\n" << std::endl;
+
+    if (attributes.empty())
+    {
+        std::cout << "\tAttribute is Empty" << std::endl;
+        return;
+    }
+
+    for (const auto & attr : attributes)
+    {
+        std::cout << "\tkey : " << attr.key() << "\n\tvalue : "
+                  << attr.value().toString() << std::endl;
+        std::cout << "=============================================\n" << std::endl;
+
+        const auto& doubleVector = attr.value().
+                get< std::vector< std::vector< RCSResourceAttributes > > >();
+
+        for (const auto& vector : doubleVector)
+        {
+            for (const auto& attrs : vector)
+            {
+                for (const auto & kvPair : attrs)
+                {
+                    std::cout << "\t" << kvPair.key() << " : "  <<
+                            kvPair.value().toString() << std::endl;
+                }
+            }
+            std::cout << std::endl;
+        }
+        std::cout << "=============================================\n" << std::endl;
+    }
+    displayMenu();
+}
+
+std::vector< std::vector< RCSResourceAttributes > > createNestedAttribute(int speedValue,
+        int aircValue)
+{
+    RCSResourceAttributes model;
+    RCSResourceAttributes weight;
+    RCSResourceAttributes dimensions;
+
+    model["model"] = "SamsungAC";
+    weight["weight"] = 3;
+    dimensions["dimensions"] = "10x25x35";
+
+    RCSResourceAttributes speed;
+    RCSResourceAttributes airCirculation;
+
+    speed["speed"] = speedValue;
+    airCirculation["air"] = aircValue;
+
+    RCSResourceAttributes temperature;
+    RCSResourceAttributes humidity;
+
+    temperature["temp"] = 30;
+    humidity["humidity"] = 30;
+
+    RCSResourceAttributes power;
+    RCSResourceAttributes capacity;
+
+    power["power"] = 1600;
+    capacity["capacity"] = 1;
+
+    RCSResourceAttributes red;
+    RCSResourceAttributes green;
+
+    red["red"] = 50;
+    green["green"] = 60;
+
+    std::vector< RCSResourceAttributes > generalInfo{ model, weight, dimensions };
+    std::vector< RCSResourceAttributes > fan{ speed, airCirculation } ;
+    std::vector< RCSResourceAttributes > tempSensor{ temperature, humidity } ;
+    std::vector< RCSResourceAttributes > efficiency{ power, capacity };
+    std::vector< RCSResourceAttributes > light{ red, green };
+
+    std::vector< std::vector< RCSResourceAttributes > > acServer;
+
+    acServer.push_back(generalInfo);
+    acServer.push_back(fan);
+    acServer.push_back(tempSensor);
+    acServer.push_back(efficiency);
+    acServer.push_back(light);
+
+    return acServer;
+}
+
+int processUserInput()
+{
+    int userInput;
+    std::cin >> userInput;
+    if (std::cin.fail())
+    {
+        std::cin.clear();
+        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
+        return -1;
+    }
+    return userInput;
+}
+
+void getAttributeFromRemoteServer()
+{
+    g_resource->getRemoteAttributes(&onRemoteAttributesReceivedCallback);
+}
+
+void setAttributeToRemoteServer()
+{
+    int speed, airc;
+
+    std::cout << "\tEnter the Fan Speed you want to set : ";
+    std::cin >> speed;
+    std::cout << "\tEnter the Air circulation value you want to set :";
+    std::cin >> airc;
+
+    RCSResourceAttributes setAttribute;
+    setAttribute[defaultKey] = createNestedAttribute(speed, airc);
+
+    g_resource->setRemoteAttributes(setAttribute,
+                                  &onRemoteAttributesReceivedCallback);
+}
+
+int selectClientMenu(int selectedMenu)
+{
+    for (int i = 0; clientMenu[i].m_menu != Menu::END_OF_MENU; i++)
+    {
+        if (clientMenu[i].m_menu == selectedMenu)
+        {
+            clientMenu[i].m_handler();
+            return clientMenu[i].m_result;
+        }
+    }
+
+    std::cout << "Invalid input, please try again" << std::endl;
+
+    return INCORRECT_INPUT;
+}
+
+void process()
+{
+    while (true)
+    {
+        displayMenu();
+
+        if (selectClientMenu(processUserInput()) == QUIT_INPUT)
+            break;
+    }
+}
+
+void platFormConfigure()
+{
+    PlatformConfig config
+    {
+        OC::ServiceType::InProc, ModeType::Client, "0.0.0.0", 0, OC::QualityOfService::LowQos
+    };
+    OCPlatform::Configure(config);
+}
+
+bool discoverResource()
+{
+    std::cout << "Wait 2 seconds until discovered." << std::endl;
+
+    try
+    {
+        RCSDiscoveryManager::getInstance()->discoverResourceByType(RCSAddress::multicast(),
+                resourceType, &onResourceDiscovered);
+    }
+    catch(const RCSPlatformException& e)
+    {
+         std::cout << e.what() << std::endl;
+    }
+    std::unique_lock<std::mutex> lck(mtx);
+    cond.wait_for(lck, std::chrono::seconds(2));
+
+    return g_resource != nullptr;
+}
+
+int main()
+{
+    platFormConfigure();
+
+    if (!discoverResource())
+    {
+        std::cout << "Can't discovered Server... Exiting the Client." << std::endl;
+        return -1;
+    }
+
+    try
+    {
+        process();
+    }
+    catch (const std::exception &e)
+    {
+        std::cout << "main exception : " << e.what() << std::endl;
+    }
+
+    std::cout << "Stopping the client" << std::endl;
+
+    return 0;
+}
diff --git a/service/resource-encapsulation/examples/linux/NestedAttributesServer.cpp b/service/resource-encapsulation/examples/linux/NestedAttributesServer.cpp
new file mode 100644 (file)
index 0000000..fc579e7
--- /dev/null
@@ -0,0 +1,320 @@
+/******************************************************************
+ *
+ * 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 <iostream>
+
+#include "RCSResourceObject.h"
+
+using namespace OIC::Service;
+
+constexpr int DEFAULT_SPEED = 30;
+constexpr int UP_SPEED = 50;
+constexpr int DOWN_SPEED = 10;
+
+constexpr int DEFALUT_SERVER = 1;
+constexpr int CUSTOM_SERVER = 2;
+constexpr int STOP = 3;
+
+constexpr int PRINT_ATTRIBUTES = 1;
+constexpr int INCREASE_SPEED_ATTRIBUTE = 2;
+constexpr int DECREASE_SPEED_ATTRIBUTE = 3;
+constexpr int STOP_SENSOR = 4;
+
+constexpr int CORRECT_INPUT = 1;
+constexpr int INCORRECT_INPUT = 2;
+constexpr int QUIT = 3;
+
+const std::string resourceUri = "/a/airConditioner";
+const std::string resourceType = "core.ac";
+const std::string resourceInterface = "oic.if.baseline";
+const std::string attributeKey = "deviceInfo";
+
+RCSResourceObject::Ptr g_server;
+
+void displayMenu()
+{
+    std::cout << "====================================================================="
+              << std::endl;
+    std::cout << "   1 - Creation of Resource [Auto control for requests]" << std::endl;
+    std::cout << "   2 - Creation of Resource [Developer control for Get and Set requests]"
+              << std::endl;
+    std::cout << "   3 - Quit" << std::endl;
+    std::cout << "====================================================================="
+              << std::endl;
+}
+
+void displayControlMenu()
+{
+    std::cout << "========================================================" << std::endl;
+    std::cout << "1. Print Nested attributes" << std::endl;
+    std::cout << "2. Increase Speed attributes" << std::endl;
+    std::cout << "3. Decrease Speed attributes" << std::endl;
+    std::cout << "4. Stop the Sensor" << std::endl;
+    std::cout << "========================================================" << std::endl;
+}
+
+std::vector< std::vector< RCSResourceAttributes > > createNestedAttribute(int speedValue)
+{
+    RCSResourceAttributes model;
+    RCSResourceAttributes weight;
+    RCSResourceAttributes dimensions;
+
+    model["model"] = "SamsungAC";
+    weight["weight"] = 3;
+    dimensions["dimensions"] = "10x25x35";
+
+    RCSResourceAttributes speed;
+    RCSResourceAttributes airCirculation;
+
+    speed["speed"] = speedValue;
+    airCirculation["air"] = 425;
+
+    RCSResourceAttributes temperature;
+    RCSResourceAttributes humidity;
+
+    temperature["temp"] = 30;
+    humidity["humidity"] = 30;
+
+    RCSResourceAttributes power;
+    RCSResourceAttributes capacity;
+
+    power["power"] = 1600;
+    capacity["capacity"] = 1;
+
+    RCSResourceAttributes red;
+    RCSResourceAttributes green;
+
+    red["red"] = 50;
+    green["green"] = 60;
+
+    std::vector< RCSResourceAttributes > generalInfo{ model, weight, dimensions };
+    std::vector< RCSResourceAttributes > fan{ speed, airCirculation };
+    std::vector< RCSResourceAttributes > tempSensor{ temperature, humidity };
+    std::vector< RCSResourceAttributes > efficiency{ power, capacity };
+    std::vector< RCSResourceAttributes > light{ red, green };
+
+    std::vector< std::vector< RCSResourceAttributes > > acServer;
+
+    acServer.push_back(generalInfo);
+    acServer.push_back(fan);
+    acServer.push_back(tempSensor);
+    acServer.push_back(efficiency);
+    acServer.push_back(light);
+
+    return acServer;
+}
+
+void printAttribute(const RCSResourceAttributes &attrs)
+{
+    for (const auto & attr : attrs)
+    {
+        std::cout << "\tkey : " << attr.key() << "\n\tvalue : "
+                  << attr.value().toString() << std::endl;
+        std::cout << "=============================================\n" << std::endl;
+
+        const auto& doubleVector = attr.value().
+                get< std::vector< std::vector< RCSResourceAttributes > > >();
+
+        for (const auto& vector : doubleVector)
+        {
+            for (const auto& attrs : vector)
+            {
+                for (const auto & kvPair : attrs)
+                {
+                    std::cout << "\t" << kvPair.key() << " : "  <<
+                            kvPair.value().toString() << std::endl;
+                }
+            }
+            std::cout << std::endl;
+        }
+        std::cout << "=============================================\n" << std::endl;
+    }
+}
+
+void printNestedAttribute()
+{
+    RCSResourceObject::LockGuard lock(*g_server);
+    const auto& attributes = g_server->getAttributes();
+
+    std::cout << "\nPrinting nested attributes" << std::endl;
+    printAttribute(attributes);
+    return;
+}
+
+void changeSpeedAttribute(int state)
+{
+    std::vector< std::vector< RCSResourceAttributes > > attr;
+
+    if (INCREASE_SPEED_ATTRIBUTE == state)
+    {
+        std::cout << "Increasing speed  attribute to : " << UP_SPEED  <<  std::endl;
+        attr = createNestedAttribute(UP_SPEED);
+    }
+    else if (DECREASE_SPEED_ATTRIBUTE == state)
+    {
+        std::cout << "Decreasing speed  attribute to : " << DOWN_SPEED << std::endl;
+        attr = createNestedAttribute(DOWN_SPEED);
+    }
+
+    RCSResourceObject::LockGuard lock(*g_server);
+    g_server->getAttributes()[attributeKey] = attr;
+    printNestedAttribute();
+}
+
+//hander for get request (if developer choose second option for resource Creation)
+RCSGetResponse requestHandlerForGet(const RCSRequest& /*request*/,
+                                    RCSResourceAttributes& /*attrs*/)
+{
+    std::cout << "Recieved a Get request from Client" << std::endl;
+
+    RCSResourceObject::LockGuard lock(*g_server);
+    std::cout << "Sending response to Client : " << std::endl;
+    printAttribute(g_server->getAttributes());
+
+    return RCSGetResponse::defaultAction();
+}
+
+//hander for set request (if developer choose second option for resource Creation)
+RCSSetResponse requestHandlerForSet(const RCSRequest& /*request*/,
+                                    RCSResourceAttributes &attrs)
+{
+    std::cout << "Recieved a Set request from Client" << std::endl;
+
+    std::cout << "Requested attributes : " << std::endl;
+    printAttribute(attrs);
+    return RCSSetResponse::defaultAction();
+}
+
+void initServer()
+{
+    try
+    {
+        g_server = RCSResourceObject::Builder(resourceUri, resourceType,
+                                            resourceInterface).build();
+    }
+    catch (const RCSPlatformException &e)
+    {
+        std::cout << "Exception in initServer : " << e.what() << std::endl;
+        return;
+    }
+
+    g_server->setAutoNotifyPolicy(RCSResourceObject::AutoNotifyPolicy::UPDATED);
+    g_server->setSetRequestHandlerPolicy(RCSResourceObject::SetRequestHandlerPolicy::NEVER);
+
+    g_server->setAttribute(attributeKey, createNestedAttribute(DEFAULT_SPEED));
+}
+
+int processUserInput()
+{
+    int userInput;
+    std::cin >> userInput;
+    if (std::cin.fail())
+    {
+        std::cin.clear();
+        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
+        return -1;
+    }
+    return userInput;
+}
+
+int selectControlMenu()
+{
+    switch (processUserInput())
+    {
+        case PRINT_ATTRIBUTES:
+            printNestedAttribute();
+            return CORRECT_INPUT;
+
+        case INCREASE_SPEED_ATTRIBUTE:
+            changeSpeedAttribute(INCREASE_SPEED_ATTRIBUTE);
+            return CORRECT_INPUT;
+
+        case DECREASE_SPEED_ATTRIBUTE:
+            changeSpeedAttribute(DECREASE_SPEED_ATTRIBUTE);
+            return CORRECT_INPUT;
+
+        case STOP_SENSOR:
+            return QUIT;
+
+        default:
+            std::cout << "Invalid input. Please try again." << std::endl;
+            return INCORRECT_INPUT;
+    }
+}
+
+int selectServerMenu()
+{
+    switch (processUserInput())
+    {
+        case DEFALUT_SERVER:
+            // Creation of Resource & Auto control for all requests from Client.
+            initServer();
+            return CORRECT_INPUT;
+
+        case CUSTOM_SERVER:
+            // Creation of Resource & setting get and set handler for handling get and
+            // set request from client in application.
+            initServer();
+
+            g_server->setGetRequestHandler(requestHandlerForGet);
+            g_server->setSetRequestHandler(requestHandlerForSet);
+            return CORRECT_INPUT;
+        case STOP :
+            return QUIT;
+
+        default :
+            std::cout << "Invalid input, please try again" << std::endl;
+            return INCORRECT_INPUT;
+    }
+}
+
+void process()
+{
+    while (true)
+    {
+        displayMenu();
+
+        int ret = selectServerMenu();
+
+        if (ret == QUIT) return;
+        if (ret == CORRECT_INPUT) break;
+    }
+
+    while (true)
+    {
+        displayControlMenu();
+
+        if (selectControlMenu() == QUIT) return;
+    }
+}
+
+int main(void)
+{
+    try
+    {
+        process();
+    }
+    catch (const std::exception &e)
+    {
+        std::cout << "main exception  : " << e.what() << std::endl;
+    }
+
+    std::cout << "Stopping the server" << std::endl;
+}
index e80012d..b8a6828 100644 (file)
@@ -27,77 +27,47 @@ Import('env')
 lib_env = env.Clone()
 SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
 
-ResourceClient_env = lib_env.Clone()
-ResourceServer_env = lib_env.Clone()
-NestedAttributeServer_env = lib_env.Clone()
-NestedAttributeClient_env = lib_env.Clone()
+sample_env = lib_env.Clone()
 
-######################################################################
-# ##### Resource Client #####
-######################################################################
+sample_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x'])
+sample_env.AppendUnique(LIBS = [
+    'rcs_common',
+    'oc',
+    'octbstack',
+    'oc_logger',
+    'connectivity_abstraction',
+    'coap',
+    'pthread'
+    ])
+sample_env.AppendUnique(CPPPATH = ['../../include'])
 
-ResourceClient_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
-ResourceClient_env.AppendUnique(LIBS = ['rcs_client', 'rcs_common','oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap', 'pthread'])
-ResourceClient_env.AppendUnique(CPPPATH = ['../../include'])
-ResourceClient_env.AppendUnique(CPPPATH = ['../../src/resourceBroker/include'])
-ResourceClient_env.AppendUnique(CPPPATH = ['../../src/resourceCache/include'])
-ResourceClient_env.AppendUnique(CPPPATH = ['../../src/common/primitiveResource/include'])
+if env.get('SECURED') == '1':
+    sample_env.AppendUnique(LIBS = ['tinydtls'])
+
+if 'rt' in sample_env.get('LIBS'):
+    sample_env.Append(LIBS = ['rt'])
 
 ######################################################################
-# ##### Nested Attribute Client #####
+# ##### Client #####
 ######################################################################
+client_env = sample_env.Clone()
+client_env.AppendUnique(LIBS = 'rcs_client')
 
-NestedAttributeClient_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
-NestedAttributeClient_env.AppendUnique(LIBS = ['rcs_client', 'rcs_common','oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap', 'pthread'])
-NestedAttributeClient_env.AppendUnique(CPPPATH = ['../../include'])
-NestedAttributeClient_env.AppendUnique(CPPPATH = ['../../src/resourceBroker/include'])
-NestedAttributeClient_env.AppendUnique(CPPPATH = ['../../src/resourceCache/include'])
-NestedAttributeClient_env.AppendUnique(CPPPATH = ['../../src/common/primitiveResource/include'])
+sampleResourceClient = client_env.Program('sampleResourceClient', 'SampleResourceClient.cpp')
+nestedAttributesClient = client_env.Program('nestedAttributesClient', 'NestedAttributesClient.cpp')
 
 ######################################################################
-# ##### Resource Server #####
+# ##### Server #####
 ######################################################################
+server_env = sample_env.Clone()
+server_env.AppendUnique(LIBS = 'rcs_server')
 
-ResourceServer_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
-ResourceServer_env.AppendUnique(LIBS = ['rcs_server', 'rcs_common','oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap', 'pthread'])
-ResourceServer_env.AppendUnique(CPPPATH = ['../../include'])
-ResourceServer_env.AppendUnique(CPPPATH = ['../../src/common/primitiveResource/include'])
-ResourceServer_env.AppendUnique(CPPPATH = ['../../src/serverBuilder/include'])
+sampleResourceServer = server_env.Program('sampleResourceServer', 'SampleResourceServer.cpp')
+separateResponseServer = server_env.Program('separateResponseServer', 'SeparateResponseServer.cpp')
+nestedAttributesServer = server_env.Program('nestedAttributesServer', 'NestedAttributesServer.cpp')
 
 ######################################################################
-# ##### Nested Attribute Server #####
+# ##### Build the RE Secure Resource Example #####
 ######################################################################
-
-NestedAttributeServer_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
-NestedAttributeServer_env.AppendUnique(LIBS = ['rcs_server', 'rcs_common','oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap', 'pthread'])
-NestedAttributeServer_env.AppendUnique(CPPPATH = ['../../include'])
-NestedAttributeServer_env.AppendUnique(CPPPATH = ['../../src/common/primitiveResource/include'])
-NestedAttributeServer_env.AppendUnique(CPPPATH = ['../../src/serverBuilder/include'])
-
 if env.get('SECURED') == '1':
-    ResourceClient_env.AppendUnique(LIBS = ['tinydtls'])
-    NestedAttributeClient_env.AppendUnique(LIBS = ['tinydtls'])
-    ResourceServer_env.AppendUnique(LIBS = ['tinydtls'])
-    NestedAttributeServer_env.AppendUnique(LIBS = ['tinydtls'])
-
-if 'rt' in ResourceClient_env.get('LIBS'):
-    ResourceClient_env.Append(LIBS = ['rt'])
-if 'rt' in NestedAttributeClient_env.get('LIBS'):
-    NestedAttributeClient_env.Append(LIBS = ['rt'])
-if 'rt' in ResourceServer_env.get('LIBS'):
-    ResourceServer_env.Append(LIBS = ['rt'])
-if 'rt' in NestedAttributeServer_env.get('LIBS'):
-    NestedAttributeServer_env.Append(LIBS = ['rt'])
-
-####################################################################
-# Source files and Targets
-####################################################################
-sampleResourceClient = ResourceClient_env.Program('sampleResourceClient', 'SampleResourceClient.cpp')
-nestedAttributeClient = NestedAttributeClient_env.Program('nestedAttributeClient', 'NestedAttributeClient.cpp')
-sampleResourceServer = ResourceServer_env.Program('sampleResourceServer', 'SampleResourceServer.cpp')
-nestedAttributeServer = NestedAttributeServer_env.Program('nestedAttributeServer', 'NestedAttributeServer.cpp')
-
-ResourceClient_env.InstallTarget(sampleResourceClient, 'sampleResourceClient')
-NestedAttributeClient_env.InstallTarget(nestedAttributeClient, 'nestedAttributeClient')
-ResourceServer_env.InstallTarget(sampleResourceServer, 'sampleResourceServer')
-NestedAttributeServer_env.InstallTarget(nestedAttributeServer, 'nestedAttributeServer')
+       SConscript('secureResourceExample/SConscript')
index 98d7076..1d15dc8 100644 (file)
 #include <iostream>
 
 #include "RCSDiscoveryManager.h"
+#include "RCSRepresentation.h"
 #include "RCSRemoteResourceObject.h"
 #include "RCSResourceAttributes.h"
 #include "RCSAddress.h"
 
 #include "OCPlatform.h"
 
+#define DECLARE_MENU(FUNC, ...) { #FUNC, FUNC }
+
 using namespace OC;
 using namespace OIC::Service;
 
-#define DECLARE_MENU(FUNC, ...) { #FUNC, FUNC, __VA_ARGS__ }
-
-void startMonitoring();
-void startMonitoring();
-void stopMonitoring();
-void getAttributeFromRemoteServer();
-void setAttributeToRemoteServer();
-void startCachingWithoutCallback();
-void startCachingWithCallback();
-void getResourceCacheState();
-void getCachedAttributes();
-void getCachedAttribute();
-void stopCaching();
-void discoverResource();
-void cancelDiscovery();
-int processUserInput();
-void selectResource();
-void printAttributes(const RCSResourceAttributes& attributes);
-
-class MenuList;
-
-class MenuItem
+struct CloseApp {};
+
+struct MenuItem
 {
 private:
-    typedef void(*MenuHandler)();
+    typedef void(*Handler)();
 
 public:
-    MenuItem(const char* funcName, MenuHandler handler = nullptr,
-            MenuHandler optionHandler = nullptr, MenuList* state = nullptr)
-        : m_name(funcName), m_handler(handler), m_optionHandler(optionHandler),
-          m_nextState(state)
-    {
-    }
+    const std::string title;
+    const Handler handler;
+};
 
-    MenuList* command() const
-    {
-        std::cout << m_name << " start.." << std::endl;
-        if(m_handler) m_handler();
+typedef void(*Runner)();
 
-        if(m_optionHandler != nullptr) m_optionHandler();
+constexpr int RESOURCE_TEMP = 1;
+constexpr int RESOURCE_LIGHT = 2;
 
-        return m_nextState;
-    }
+const std::string RESOURCE_TYPE_TEMP = "oic.r.temperaturesensor";
+const std::string RESOURCE_TYPE_LIGHT = "oic.r.light";
 
-    const char* getTitle() const
-    {
-        return m_name.c_str();
-    }
+RCSRemoteResourceObject::Ptr g_selectedResource;
+std::vector<RCSRemoteResourceObject::Ptr> g_discoveredResources;
 
-private:
-    const std::string m_name;
-    const MenuHandler m_handler;
-    const MenuHandler m_optionHandler;
-    MenuList* const m_nextState ;
-};
+std::string g_attrKey;
 
-class MenuList
+Runner g_currentRun;
+
+std::ostream& operator<<(std::ostream& os, const RCSRemoteResourceObject::Ptr& object)
 {
-public:
-    MenuList(std::initializer_list<MenuItem> il)
-        :m_menuItemList(std::move(il))
+    return os << "\turi : " << object->getUri() << std::endl <<
+            "\thost address : " << object->getAddress();
+}
+
+std::ostream& operator<<(std::ostream& os, const MenuItem& item)
+{
+    return os << item.title;
+}
+
+void onSelected(const RCSRemoteResourceObject::Ptr& object)
+{
+    g_selectedResource = object;
+}
+
+void onSelected(const MenuItem& item)
+{
+    std::cout << item.title << " start.." << std::endl;
+    item.handler();
+}
+
+int processUserInput(int min = std::numeric_limits<int>::min(),
+        int max = std::numeric_limits<int>::max())
+{
+    assert(min <= max);
+
+    int input;
+
+    std::cin >> input;
+    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
+
+    if (!std::cin.fail() && min <= input && input <= max) return input;
+
+    std::cin.clear();
+    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
+
+    throw std::runtime_error("Invalid Input, please try again");
+}
+
+template<typename D>
+void displayItem(int width, int index, const D& data)
+{
+    std::cout.width(width);
+    std::cout << std::right << index << ". ";
+    std::cout << data << std::endl;
+}
+
+template<typename T>
+void displayItems(const std::vector<T>& items)
+{
+    std::cout << std::endl;
+
+    const auto width = (items.size() + 1) / 10 + 1;
+
+    for(size_t i = 0; i < items.size(); ++i)
     {
+        displayItem(width, i + 1, items[i]);
     }
+    displayItem(width, items.size() + 1, "quit");
+}
 
-    void display() const
-    {
-        std::cout << std::endl;
-        int menuNum = 1;
+template<typename T>
+void selectItem(const std::vector<T>& items)
+{
+    int selected = processUserInput(1, items.size() + 1) - 1;
 
-        for(const auto& menuItem : m_menuItemList)
-        {
-            std::cout.width(2);
-            std::cout << std::right << menuNum++ <<  ". ";
-            std::cout << menuItem.getTitle() << std::endl;
-        }
-    }
+    if(selected == static_cast<int>(items.size())) throw CloseApp();
 
-    MenuList* select()
-    {
-        int input = processUserInput();
+    onSelected(items[selected]);
+}
 
-        if(input == static_cast<int>(m_menuItemList.size())) return nullptr;
+template<typename T>
+void handleItems(const std::vector<T>& items)
+{
+    displayItems(items);
+    selectItem(items);
+}
 
-        if(input > static_cast<int>(m_menuItemList.size()) || input <= 0)
-        {
-            std::cout << "Invalid input, please try again" << std::endl;
-            return this;
-        }
-        auto nextMenuList = m_menuItemList[input-1].command();
+std::string inputInterface()
+{
+    std::string interfaceName;
 
-        return nextMenuList == nullptr ? this : nextMenuList;
-    }
+    std::cout << "\tInput the Interface you want to set : ";
+    std::cin >> interfaceName;
 
-private:
-    const std::vector<MenuItem> m_menuItemList;
-};
+    return interfaceName;
+}
 
-constexpr int REQUEST_TEMP = 1;
-constexpr int REQUEST_LIGHT = 2;
+RCSResourceAttributes inputKeyValue()
+{
+    std::string key;
 
-const std::string TEMP = "oic.r.temperaturesensor";
-const std::string LIGHT = "oic.r.light";
+    std::cout << "\tEnter the Key you want to set : ";
+    std::cin >> key;
 
-std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> discoveryTask;
+    std::cout << "\tEnter the value(INT) you want to set :";
+    RCSResourceAttributes attrs;
+    attrs[key] = processUserInput();
 
-std::vector<RCSRemoteResourceObject::Ptr> resourceList;
-RCSRemoteResourceObject::Ptr selectedResource;
+    return attrs;
+}
 
-std::string defaultKey;
+void printAttribute(const std::string& key, const RCSResourceAttributes::Value& value)
+{
+    std::cout << "\tkey : " << key << std::endl
+              << "\tvalue : " << value.toString() << std::endl;
+}
 
-MenuList* currentMenuList;
+void printAttributes(const RCSResourceAttributes& attributes)
+{
+    if (attributes.empty())
+    {
+       std::cout << "\tattributes is empty" << std::endl;
+    }
 
-MenuList resourceMenu = {
-    DECLARE_MENU(startMonitoring),
-    DECLARE_MENU(stopMonitoring),
-    DECLARE_MENU(getAttributeFromRemoteServer),
-    DECLARE_MENU(setAttributeToRemoteServer),
-    DECLARE_MENU(startCachingWithoutCallback),
-    DECLARE_MENU(startCachingWithCallback),
-    DECLARE_MENU(getResourceCacheState),
-    DECLARE_MENU(getCachedAttributes),
-    DECLARE_MENU(getCachedAttribute),
-    DECLARE_MENU(stopCaching),
-    { "quit" }
-};
+    for(const auto& attr : attributes)
+    {
+        printAttribute(attr.key(), attr.value());
+    }
+}
 
-MenuList cancelDiscoveryMenu = {
-    DECLARE_MENU(cancelDiscovery, selectResource, &resourceMenu),
-    { "quit" }
-};
+void print(const std::string& name, const std::vector< std::string >& elements)
+{
+    if (elements.empty())
+    {
+       std::cout << "\t" << name << " is empty" << std::endl;
+       return;
+    }
 
-MenuList discoveryMenu = {
-    DECLARE_MENU(discoverResource, nullptr, &cancelDiscoveryMenu),
-    { "quit" }
-};
+    std::cout << "\t" << name << " : " << std::endl;
+    for(const auto& item : elements)
+    {
+        std::cout << item << " ";
+    }
+    std::cout << std::endl;
+}
+
+void printUri(const std::string& uri)
+{
+    if(uri.empty())
+    {
+        std::cout << "\turi is empty" << std::endl;
+    }
+    else
+    {
+        std::cout << "\turi : " << uri << std::endl;
+    }
+}
 
-void onResourceDiscovered(std::shared_ptr<RCSRemoteResourceObject> discoveredResource)
+void printRepresentation(const RCSRepresentation& rep)
 {
-    std::cout << "onResourceDiscovered callback :: " << std::endl;
+    printUri(rep.getUri());
+    print("interfaces", rep.getInterfaces());
+    print("resourceTypes", rep.getResourceTypes());
+    printAttributes(rep.getAttributes());
 
-    std::cout << "resourceURI : " << discoveredResource->getUri() << std::endl;
-    std::cout << "hostAddress : " << discoveredResource->getAddress() << std::endl;
+    const auto& children = rep.getChildren();
 
-    resourceList.push_back(discoveredResource);
+    if(children.empty())
+    {
+        std::cout << "\tchildren is empty" << std::endl;
+    }
+    else
+    {
+        int cnt = 0;
+        for(const auto& child : children)
+        {
+            std::cout << "========================================================" << std::endl;
+            std::cout << ++cnt << " chlid" << std::endl;
+            printRepresentation(child);
+            std::cout << "========================================================" << std::endl;
+        }
+    }
 }
 
-void onResourceStateChanged(const ResourceState& resourceState)
+void onResourceStateChanged(ResourceState resourceState)
 {
     std::cout << "onResourceStateChanged callback" << std::endl;
 
@@ -218,62 +278,80 @@ void onRemoteAttributesReceived(const RCSResourceAttributes& attributes, int)
     printAttributes(attributes);
 }
 
+void onRemoteGetReceived(const HeaderOpts&, const RCSRepresentation& rep, int)
+{
+    std::cout << "onRemoteGetReceived callback" << std::endl;
+
+    printRepresentation(rep);
+}
+
+void onRemoteSetReceived(const HeaderOpts&, const RCSRepresentation& rep, int)
+{
+    std::cout << "onRemoteSetReceived callback" << std::endl;
+
+    printRepresentation(rep);
+}
+
 void startMonitoring()
 {
-    if (!selectedResource->isMonitoring())
-    {
-        selectedResource->startMonitoring(&onResourceStateChanged);
-        std::cout << "\tHosting Started..." << std::endl;
-    }
-    else
+    if (g_selectedResource->isMonitoring())
     {
         std::cout << "\tAlready Started..." << std::endl;
+        return;
     }
+
+    g_selectedResource->startMonitoring(&onResourceStateChanged);
+    std::cout << "\tMonitoring Started..." << std::endl;
 }
 
 void stopMonitoring()
 {
-    if (selectedResource->isMonitoring())
+    if (!g_selectedResource->isMonitoring())
     {
-        selectedResource->stopMonitoring();
-        std::cout << "\tHosting stopped..." << std::endl;
-    }
-    else
-    {
-       std::cout << "\tHosting not started..." << std::endl;
+        std::cout << "\tMonitoring not started..." << std::endl;
+        return;
     }
+
+    g_selectedResource->stopMonitoring();
+    std::cout << "\tMonitoring stopped..." << std::endl;
 }
 
-void getAttributeFromRemoteServer()
+void getRemoteAttributes()
 {
-    selectedResource->getRemoteAttributes(&onRemoteAttributesReceived);
+    g_selectedResource->getRemoteAttributes(onRemoteAttributesReceived);
 }
 
-void setAttributeToRemoteServer()
+void setRemoteAttributes()
 {
-    std::string key;
-    RCSResourceAttributes setAttribute;
+    g_selectedResource->setRemoteAttributes(inputKeyValue(), onRemoteAttributesReceived);
+}
 
-    std::cout << "\tEnter the Key you want to set : ";
-    std::cin >> key;
-    std::cout << "\tEnter the value(INT) you want to set :";
+void getWithInterface()
+{
+    RCSQueryParams queryParams;
+    queryParams.setResourceInterface(inputInterface());
+
+    g_selectedResource->get(queryParams, onRemoteGetReceived);
+}
+
+void setWithInterface()
+{
+    RCSQueryParams queryParams;
+    queryParams.setResourceInterface(inputInterface());
 
-    setAttribute[key] = processUserInput();
-    selectedResource->setRemoteAttributes(setAttribute,
-                                  &onRemoteAttributesReceived);
+    g_selectedResource->set(queryParams, inputKeyValue(), onRemoteSetReceived);
 }
 
 void startCaching(RCSRemoteResourceObject::CacheUpdatedCallback cb)
 {
-    if (!selectedResource->isCaching())
-    {
-        selectedResource->startCaching(std::move(cb));
-        std::cout << "\tCaching Started..." << std::endl;
-    }
-    else
+    if (g_selectedResource->isCaching())
     {
         std::cout << "\tAlready Started Caching..." << std::endl;
+        return;
     }
+
+    g_selectedResource->startCaching(std::move(cb));
+    std::cout << "\tCaching Started..." << std::endl;
 }
 
 void startCachingWithoutCallback()
@@ -288,7 +366,7 @@ void startCachingWithCallback()
 
 void getResourceCacheState()
 {
-    switch(selectedResource->getCacheState())
+    switch(g_selectedResource->getCacheState())
     {
         case CacheState::READY:
             std::cout << "\tCurrent Cache State : CACHE_STATE::READY" << std::endl;
@@ -310,102 +388,50 @@ void getResourceCacheState()
 
 void getCachedAttributes()
 {
-    try
-    {
-        printAttributes(selectedResource->getCachedAttributes());
-    }
-    catch (const RCSBadRequestException& e)
-    {
-        std::cout << "Exception in getCachedAttributes : " << e.what() << std::endl;
-    }
+    printAttributes(g_selectedResource->getCachedAttributes());
 }
 
 void getCachedAttribute()
 {
-    try
-    {
-        std::cout << "\tkey : " << defaultKey << std::endl
-                  << "\tvalue : " << selectedResource->getCachedAttribute(defaultKey).get< int >()
-                  << std::endl;
-    }
-    catch (const RCSBadRequestException& e)
-    {
-        std::cout << "Exception in getCachedAttribute : " << e.what() << std::endl;
-    }
-    catch (const RCSBadGetException& e)
-    {
-        std::cout << "Exception in getCachedAttribute : " << e.what() << std::endl;
-    }
+    printAttribute(g_attrKey, g_selectedResource->getCachedAttribute(g_attrKey));
 }
 
 void stopCaching()
 {
-    if(selectedResource->isCaching())
-    {
-        selectedResource->stopCaching();
-        std::cout << "\tCaching stopped..." << std::endl;
-    }
-    else
+    if(!g_selectedResource->isCaching())
     {
         std::cout << "\tCaching not started..." << std::endl;
+        return;
     }
-}
-
-void platFormConfigure()
-{
-    PlatformConfig config
-    {
-        OC::ServiceType::InProc, ModeType::Client, "0.0.0.0", 0, OC::QualityOfService::LowQos
-    };
-    OCPlatform::Configure(config);
-}
 
-int processUserInput()
-{
-    int userInput;
-
-    while(true)
-    {
-        std::cin >> userInput;
-        if (std::cin.fail())
-        {
-            std::cin.clear();
-            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
-            std::cout << "Invalid Input, please try again" << std::endl;
-        }
-        else break;
-    }
-    return userInput;
+    g_selectedResource->stopCaching();
+    std::cout << "\tCaching stopped..." << std::endl;
 }
 
-bool selectResourceType(std::string& resourceType)
+std::string selectResourceType()
 {
     std::cout << "========================================================" << std::endl;
     std::cout << "1. Temperature Resource Discovery" << std::endl;
     std::cout << "2. Light Resource Discovery" << std::endl;
     std::cout << "========================================================" << std::endl;
 
-    switch (processUserInput())
+    switch (processUserInput(RESOURCE_TEMP, RESOURCE_LIGHT))
     {
-    case REQUEST_TEMP:
-        resourceType = TEMP;
-        defaultKey = "Temperature";
-        return true;
-    case REQUEST_LIGHT:
-        resourceType = LIGHT;
-        defaultKey = "Brightness";
-        return true;
-    default :
-        std::cout << "Invalid input, please try again" << std::endl;
-        return false;
+    case RESOURCE_TEMP:
+        g_attrKey = "Temperature";
+        return RESOURCE_TYPE_TEMP;
+    case RESOURCE_LIGHT:
+        g_attrKey = "Brightness";
+        return RESOURCE_TYPE_LIGHT;
     }
+
+    throw std::logic_error("unreachable");
 }
 
 RCSAddress inputAddress()
 {
     std::cout << "========================================================" << std::endl;
-    std::cout << "Please input address" << std::endl;
-    std::cout << "(default is multicast. when you want to use unicast, input address" << std::endl;
+    std::cout << "Please input address (empty for multicast)" << std::endl;
     std::cout << "========================================================" << std::endl;
 
     std::string address;
@@ -415,96 +441,111 @@ RCSAddress inputAddress()
     return address.empty() ? RCSAddress::multicast() : RCSAddress::unicast(address);
 }
 
-void discoverResource()
+void printDiscoveryInProgress()
 {
-    std::string resourceType = "";
-
-    while(!selectResourceType(resourceType)) {}
-
-    while(!discoveryTask)
-    {
-        try
-        {
-            discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(
-                    inputAddress(), resourceType, &onResourceDiscovered);
-        }
-        catch (const RCSPlatformException& e)
-        {
-            std::cout << e.what() << std::endl;
-        }
-    }
+    std::cout << "Discovery in progress, press '1' to stop." << std::endl;
 }
 
-void displayResourceList()
+void discoverResource()
 {
-    int cnt = 1;
-    for(const auto& resource : resourceList)
+    auto onResourceDiscovered = [](
+            const RCSRemoteResourceObject::Ptr& discoveredResource)
     {
-        std::cout << cnt++ << ".\tresourceURI : " << resource->getUri() << std::endl <<
-                              "\thostAddress : " << resource->getAddress() << std::endl;
-    }
-}
+        std::cout << "onResourceDiscovered callback :: " << std::endl;
 
-void selectResource()
-{
-    displayResourceList();
+        std::cout << "uri : " << discoveredResource->getUri() << std::endl;
+        std::cout << "host address : " << discoveredResource->getAddress() << std::endl;
+
+        g_discoveredResources.push_back(discoveredResource);
+
+        printDiscoveryInProgress();
+    };
 
-    std::cout << "select Resource..." << std::endl;
+    auto resourceType = selectResourceType();
+    auto address = inputAddress();
 
-    selectedResource = resourceList[processUserInput()-1];
+    printDiscoveryInProgress();
 
-    resourceList.clear();
+    auto discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(address,
+            resourceType, onResourceDiscovered);
+
+    while(processUserInput() != 1);
+
+    discoveryTask->cancel();
 }
 
-void cancelDiscovery()
+void runResourceControl()
 {
-    if(!discoveryTask)
-    {
-        std::cout << "There is no discovery request..." << std::endl;
-        return;
-    }
-    discoveryTask->cancel();
+    static std::vector<MenuItem> resourceMenuItems {
+        DECLARE_MENU(startMonitoring),
+        DECLARE_MENU(stopMonitoring),
+        DECLARE_MENU(getRemoteAttributes),
+        DECLARE_MENU(setRemoteAttributes),
+        DECLARE_MENU(getWithInterface),
+        DECLARE_MENU(setWithInterface),
+        DECLARE_MENU(startCachingWithoutCallback),
+        DECLARE_MENU(startCachingWithCallback),
+        DECLARE_MENU(getResourceCacheState),
+        DECLARE_MENU(getCachedAttributes),
+        DECLARE_MENU(getCachedAttribute),
+        DECLARE_MENU(stopCaching),
+    };
+
+    handleItems(resourceMenuItems);
 }
 
-void printAttribute(const std::string key, const RCSResourceAttributes::Value& value)
+void runResourceSelection()
 {
-    std::cout << "\tkey : " << key << std::endl
-              << "\tvalue : " << value.toString() << std::endl;
+    handleItems(g_discoveredResources);
+
+    g_currentRun = runResourceControl;
 }
 
-void printAttributes(const RCSResourceAttributes& attributes)
+void runDiscovery()
 {
-    if (attributes.empty())
-    {
-       std::cout << "\tattributes is empty" << std::endl;
-    }
-    for(const auto& attr : attributes)
+    static std::vector<MenuItem> discoveryMenuItems {
+        DECLARE_MENU(discoverResource),
+    };
+
+    handleItems(discoveryMenuItems);
+
+    if (g_discoveredResources.empty()) throw std::runtime_error("No resource found!");
+
+    g_currentRun = runResourceSelection;
+}
+
+void configurePlatform()
+{
+    PlatformConfig config
     {
-        printAttribute(attr.key(), attr.value());
-    }
+        OC::ServiceType::InProc, ModeType::Client, "0.0.0.0", 0, OC::QualityOfService::LowQos
+    };
+    OCPlatform::Configure(config);
 }
 
 int main()
 {
-    platFormConfigure();
+    configurePlatform();
 
-    currentMenuList = &discoveryMenu;
+    g_currentRun = runDiscovery;
 
-    try
+    while (true)
     {
-        while(currentMenuList)
+        try
         {
-            currentMenuList->display();
-
-            currentMenuList = currentMenuList->select();
+            g_currentRun();
+        }
+        catch (const std::exception& e)
+        {
+            std::cout << e.what() << std::endl;
+        }
+        catch (const CloseApp&)
+        {
+            break;
         }
-    }
-    catch (const std::exception& e)
-    {
-        std::cout << "main exception : " << e.what() << std::endl;
     }
 
-    std::cout << "Stopping the Client" << std::endl;
+    std::cout << "Stopping the client" << std::endl;
 
     return 0;
 }
old mode 100644 (file)
new mode 100755 (executable)
index e118781..3c03da3
  *
  ******************************************************************/
 
-#include "PrimitiveResource.h"
 #include "RCSResourceObject.h"
 #include "OCPlatform.h"
-#include "OCApi.h"
 
-using namespace OC;
 using namespace OC::OCPlatform;
 using namespace OIC::Service;
 
-constexpr int DEFALUT_VALUE = 0;
+struct CloseApp{};
 
-constexpr int REQUEST_TEMP = 1;
-constexpr int REQUEST_LIGHT = 2;
-
-constexpr int PRESENCE_ON = 1;
-constexpr int PRESENCE_OFF = 2;
+constexpr int RESOURCE_TEMP = 1;
+constexpr int RESOURCE_LIGHT = 2;
 
 constexpr int DEFALUT_SERVER = 1;
 constexpr int CUSTOM_SERVER = 2;
-constexpr int STOP = 3;
 
-constexpr int INCREASE_TEMPERATURE = 1;
-constexpr int DECREASE_TEMPERATURE = 2;
-constexpr int STOP_TEMPERATURE_SENSOR = 3;
+constexpr int INCREASE = 1;
+constexpr int DECREASE = 2;
 
-constexpr int INCREASE_BRIGHTNESS = 1;
-constexpr int DECREASE_BRIGHTNESS = 2;
-constexpr int STOP_LIGHT_SENSOR = 3;
+const std::string BASELINE_INTERFACE = "oic.if.baseline";
+const std::string ACTUATOR_INTERFACE = "oic.if.a";
+const std::string SENSOR_INTERFACE = "oic.if.s";
+const std::string CUSTOM_INTERFACE = "test.custom";
 
-constexpr int CORRECT_INPUT = 1;
-constexpr int INCORRECT_INPUT = 2;
-constexpr int QUIT = 3;
+typedef void (*DisplayControlMenuFunc)();
+typedef std::function<void()> Run;
 
+Run g_currentRun;
 
-std::string resourceType = "oic.r.temperaturesensor";
-std::string resourceInterface = "oic.if.";
-std::string resourceUri;
-std::string attributeKey;
-int isPresenceOn = PRESENCE_ON;
+bool g_isPresenceStarted = false;
 
-RCSResourceObject::Ptr server;
+RCSResourceObject::Ptr g_resource;
 
-int processUserInput();
+int processUserInput(int min, int max)
+{
+    assert(min <= max);
 
-enum class Control{
-    INCREASE,
-    DECREASE
-};
+    int input;
 
-void displayMenu()
-{
-    std::cout << "====================================================================="
-              << std::endl;
-    std::cout << "   1 - Creation of Resource [Auto control for requests]" << std::endl;
-    std::cout << "   2 - Creation of Resource [Developer control for Get and Set requests]"
-              << std::endl;
-    std::cout << "   3 - Quit" << std::endl;
-    std::cout << "====================================================================="
-              << std::endl;
-}
+    std::cin >> input;
 
-void displayResourceTypeMenu()
-{
-    std::cout << "========================================================" << std::endl;
-    std::cout << "Select Resource Type" << std::endl;
-    std::cout << "1. Temperature" << std::endl;
-    std::cout << "2. Light" << std::endl;
-    std::cout << "========================================================" << std::endl;
+    if (!std::cin.fail())
+    {
+        if(input == max + 1) throw CloseApp();
+        if(min <= input && input <= max) return input;
+    }
+
+    std::cin.clear();
+    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
+
+    throw std::runtime_error("Invalid Input, please try again");
 }
 
 void displayControlTemperatureMenu()
 {
-    std::cout << "========================================================" << std::endl;
-    std::cout << "1. Increase Temperature by 1 degree" << std::endl;
-    std::cout << "2. Decrease Temperature by 1 degree" << std::endl;
-    std::cout << "3. Stop the Sensor" << std::endl;
-    std::cout << "========================================================" << std::endl;
+    std::cout << "========================================================\n";
+    std::cout << INCREASE << ". Increase Temperature by 1 degree          \n";
+    std::cout << DECREASE << ". Decrease Temperature by 1 degree          \n";
+    std::cout << DECREASE + 1 << ". Quit                                  \n";
+    std::cout << "========================================================\n";
 }
 
 void displayControlLightMenu()
 {
-    std::cout << "========================================================" << std::endl;
-    std::cout << "1. Increase Brightness by 1 stage" << std::endl;
-    std::cout << "2. Decrease Brightness by 1 stage" << std::endl;
-    std::cout << "3. Stop the Sensor" << std::endl;
-    std::cout << "========================================================" << std::endl;
+    std::cout << "========================================================\n";
+    std::cout << INCREASE << ". Increase Brightness by 1 stage            \n";
+    std::cout << DECREASE << ". Decrease Brightness by 1 stage            \n";
+    std::cout << DECREASE + 1 << ". Quit                                  \n";
+    std::cout << "========================================================\n";
 }
 
-void printAttribute(const RCSResourceAttributes& attrs)
+void printAttributes(const RCSResourceAttributes& attrs)
 {
     for(const auto& attr : attrs)
     {
@@ -115,261 +96,169 @@ void printAttribute(const RCSResourceAttributes& attrs)
     }
 }
 
-//hander for get request (if developer choose second option for resource Creation)
-RCSGetResponse requestHandlerForGet(const RCSRequest& request,
-        RCSResourceAttributes& attrs)
+RCSGetResponse requestHandlerForGet(const RCSRequest&, RCSResourceAttributes& attrs)
 {
     std::cout << "Received a Get request from Client" << std::endl;
-    RCSResourceObject::LockGuard lock(*server);
-    RCSResourceAttributes attributes = server->getAttributes();
+    printAttributes(attrs);
 
-    std::cout << "\nSending response to Client : " << std::endl;
-    printAttribute(attributes);
+    {
+        RCSResourceObject::LockGuard lock(g_resource);
+        std::cout << "\nSending response to Client : " << std::endl;
+        printAttributes(g_resource->getAttributes());
+    }
 
     return RCSGetResponse::defaultAction();
 }
 
-//hander for set request (if developer choose second option for resource Creation)
-RCSSetResponse requestHandlerForSet(const RCSRequest& request,
-        RCSResourceAttributes& attrs)
+RCSSetResponse requestHandlerForSet(const RCSRequest&, RCSResourceAttributes& attrs)
 {
     std::cout << "Received a Set request from Client" << std::endl;
+    printAttributes(attrs);
 
-    std::cout << "\n\nSending response to Client : " << std::endl;
-    RCSResourceObject::LockGuard lock(*server);
-    printAttribute(attrs);
     return RCSSetResponse::defaultAction();
 }
 
-void createResource()
+void initServer(const std::string& resourceUri, const std::string& resourceType,
+        const std::string& attrKey)
 {
-    server = RCSResourceObject::Builder(resourceUri, resourceType,resourceInterface).
-            setDiscoverable(true).setObservable(true).build();
+    g_resource = RCSResourceObject::Builder(resourceUri, resourceType, ACTUATOR_INTERFACE)
+            .addInterface(CUSTOM_INTERFACE)
+            .addInterface(SENSOR_INTERFACE)
+            .setDefaultInterface(BASELINE_INTERFACE)
+            .setDiscoverable(true)
+            .setObservable(true)
+            .build();
+
+    g_resource->setAutoNotifyPolicy(RCSResourceObject::AutoNotifyPolicy::UPDATED);
+    g_resource->setSetRequestHandlerPolicy(RCSResourceObject::SetRequestHandlerPolicy::NEVER);
+    g_resource->setAttribute(attrKey, 0);
 }
 
-void initServer()
+void updateAttribute(const std::string& attrKey, int control)
 {
-    try
-    {
-        createResource();
-    }
-    catch (const RCSPlatformException& e)
+    const int diff = control == INCREASE ? 1 : - 1;
+
     {
-        std::cout << "Exception in initServer : " << e.what() << std::endl;
+        RCSResourceObject::LockGuard lock(g_resource);
+        auto& attrs = g_resource->getAttributes();
+        attrs[attrKey] = attrs[attrKey].get<int>() + diff;
     }
 
-    server->setAutoNotifyPolicy(RCSResourceObject::AutoNotifyPolicy::UPDATED);
-    server->setSetRequestHandlerPolicy(RCSResourceObject::SetRequestHandlerPolicy::NEVER);
-    server->setAttribute(attributeKey, DEFALUT_VALUE);
-}
-
-void changeAttribute(Control control)
-{
-    RCSResourceObject::LockGuard lock(server);
-    if(Control::INCREASE == control)
+    if(control == INCREASE)
     {
-        server->getAttributes()[attributeKey] =
-                server->getAttribute<int>(attributeKey) + 1;
-        std::cout << attributeKey << " increased." << std::endl;
+        std::cout << attrKey << " increased." << std::endl;
     }
-    else if(Control::DECREASE == control)
+    else
     {
-        server->getAttributes()[attributeKey] =
-                        server->getAttribute<int>(attributeKey) - 1;
-        std::cout << attributeKey << " Decreased." << std::endl;
+        std::cout << attrKey << " decreased." << std::endl;
     }
-    std::cout << "\nCurrent " << attributeKey << ": "
-            << server->getAttributeValue(attributeKey).get<int>() << std::endl;
+    std::cout << "\nCurrent " << attrKey << ": "
+            << g_resource->getAttributeValue(attrKey).get<int>() << std::endl;
 }
 
-int processUserInput()
+void runResourceControl(DisplayControlMenuFunc displayMenuFunc, const std::string& attrKey)
 {
-    int userInput;
-    std::cin >> userInput;
-    if (std::cin.fail())
-    {
-        std::cin.clear();
-        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
-        return -1;
-    }
-    return userInput;
+    displayMenuFunc();
+    updateAttribute(attrKey, processUserInput(INCREASE, DECREASE));
 }
 
-int selectPresenceMenu()
+void runResourceTypeSelection(int resourceMode)
 {
-    std::cout << "========================================================" << std::endl;
-    std::cout << "1. Presence On" << std::endl;
-    std::cout << "2. Presence Off" << std::endl;
-    std::cout << "========================================================" << std::endl;
+    std::cout << "========================================================\n";
+    std::cout << "Select Resource Type                                    \n";
+    std::cout << RESOURCE_TEMP << ". Temperature                          \n";
+    std::cout << RESOURCE_LIGHT << ". Light                               \n";
+    std::cout << RESOURCE_LIGHT + 1 << ". Quit                            \n";
+    std::cout << "========================================================\n";
+
+    int resourceType = processUserInput(RESOURCE_TEMP, RESOURCE_LIGHT);
+    DisplayControlMenuFunc displayMenuFunc;
+    std::string attrKey;
+
+    switch (resourceType)
+    {
+        case RESOURCE_TEMP:
+            attrKey = "Temperature";
+            initServer("/a/TempSensor", "oic.r.temperaturesensor", attrKey);
 
-    switch(processUserInput())
-        {
-        case PRESENCE_ON:
-            isPresenceOn = PRESENCE_ON;
-            startPresence(3);
-            return CORRECT_INPUT;
-        case PRESENCE_OFF:
-            isPresenceOn = PRESENCE_OFF;
-            return CORRECT_INPUT;
-        default :
-            std::cout << "Invalid input, please try again" << std::endl;
-            return INCORRECT_INPUT;
-        }
-}
+            displayMenuFunc = displayControlTemperatureMenu;
+            break;
 
-int selectResourceTypeMenu()
-{
-    displayResourceTypeMenu();
+        case RESOURCE_LIGHT:
+            attrKey = "Brightness";
+            initServer("/a/light", "oic.r.light", attrKey);
 
-    switch(processUserInput())
-    {
-        case REQUEST_TEMP:
-            resourceUri = "/a/TempSensor";
-            resourceType = "oic.r.temperaturesensor";
-            attributeKey = "Temperature";
-            return CORRECT_INPUT;
-        case REQUEST_LIGHT:
-            resourceUri = "/a/light";
-            resourceType = "oic.r.light";
-            attributeKey = "Brightness";
-            return CORRECT_INPUT;
-        default :
-            std::cout << "Invalid input, please try again" << std::endl;
-            return INCORRECT_INPUT;
+            displayMenuFunc = displayControlLightMenu;
+            break;
     }
-}
 
-int selectServerMenu()
-{
-    switch (processUserInput())
+    if (resourceMode == CUSTOM_SERVER)
     {
-        case DEFALUT_SERVER: // Creation of Resource & Auto control for all requests from Client.
-            while(true)
-            {
-                int ret = selectResourceTypeMenu();
-                if(ret == CORRECT_INPUT) break;
-            }
-            initServer();
-            return CORRECT_INPUT;
-
-        case CUSTOM_SERVER:
-            // Creation of Resource & setting get and set handler for handling get and
-            // set request from client in application.
-            while(true)
-            {
-                int ret = selectResourceTypeMenu();
-                if(ret == CORRECT_INPUT) break;
-            }
-            initServer();
-
-            server->setGetRequestHandler(requestHandlerForGet);
-            server->setSetRequestHandler(requestHandlerForSet);
-            return CORRECT_INPUT;
-        case STOP :
-            return QUIT;
-
-        default :
-            std::cout << "Invalid input, please try again" << std::endl;
-            return INCORRECT_INPUT;
+        g_resource->setGetRequestHandler(requestHandlerForGet);
+        g_resource->setSetRequestHandler(requestHandlerForSet);
     }
+
+    g_currentRun = std::bind(runResourceControl, displayMenuFunc, std::move(attrKey));
 }
 
-int selectControlTemperatureMenu()
+void runResourceModeSelection()
 {
-    displayControlTemperatureMenu();
-
-    switch (processUserInput())
-    {
-       case INCREASE_TEMPERATURE:
-           changeAttribute(Control::INCREASE);
-           return CORRECT_INPUT;
-
-       case DECREASE_TEMPERATURE:
-           changeAttribute(Control::DECREASE);
-           return CORRECT_INPUT;
-
-       case STOP_TEMPERATURE_SENSOR:
-           return QUIT;
-
-       default:
-           std::cout << "Invalid input. Please try again." << std::endl;
-           return INCORRECT_INPUT;
-   }
+    std::cout << "========================================================          \n";
+    std::cout << DEFALUT_SERVER << ". Creation of Simple Resource Without Handlers  \n";
+    std::cout << CUSTOM_SERVER << ". Creation of Resource With Set and Get Handlers \n";
+    std::cout << CUSTOM_SERVER + 1 << ". Quit                                       \n";
+    std::cout << "========================================================          \n";
+
+    g_currentRun = std::bind(runResourceTypeSelection,
+            processUserInput(DEFALUT_SERVER, CUSTOM_SERVER));
 }
 
-int selectControlLightMenu()
+void runPresenceSelection()
 {
-    displayControlLightMenu();
-
-    switch (processUserInput())
-    {
-        case INCREASE_BRIGHTNESS:
-            changeAttribute(Control::INCREASE);
-            return CORRECT_INPUT;
+    constexpr int PRESENCE_ON = 1;
+    constexpr int PRESENCE_OFF = 2;
 
-        case DECREASE_BRIGHTNESS:
-            changeAttribute(Control::DECREASE);
-            return CORRECT_INPUT;
+    std::cout << "========================================================\n";
+    std::cout << PRESENCE_ON << ". Presence On                            \n";
+    std::cout << PRESENCE_OFF << ". Presence Off                          \n";
+    std::cout << PRESENCE_OFF + 1 << ". Quit                              \n";
+    std::cout << "========================================================\n";
 
-        case STOP_LIGHT_SENSOR:
-            return QUIT;
-
-        default:
-            std::cout << "Invalid input. Please try again." << std::endl;
-            return INCORRECT_INPUT;
-    }
-}
-
-void process()
-{
-    while(true)
+    if (processUserInput(PRESENCE_ON, PRESENCE_OFF) == PRESENCE_ON)
     {
-        int ret = selectPresenceMenu();
-        if(ret == CORRECT_INPUT) break;
+        g_isPresenceStarted = true;
+        startPresence(3);
     }
 
-    while(true)
-    {
-        displayMenu();
-        int ret = selectServerMenu();
+    g_currentRun = runResourceModeSelection;
+}
 
-        if(ret == QUIT) return;
-        if(ret == CORRECT_INPUT) break;
-    }
+int main(void)
+{
+    g_currentRun = runPresenceSelection;
 
     while(true)
     {
-        if(resourceType == "oic.r.temperaturesensor")
+        try
         {
-            int ret = selectControlTemperatureMenu();
-            if (ret == QUIT) return;
-            if (ret == INCORRECT_INPUT) continue;
+            g_currentRun();
         }
-        else if(resourceType == "oic.r.light")
+        catch(const std::exception& e)
         {
-            int ret = selectControlLightMenu();
-            if (ret == QUIT) return;
-            if (ret == INCORRECT_INPUT) continue;
+            std::cout << e.what() << std::endl;
         }
-    }
-}
-
-int main(void)
-{
-    try
-    {
-        process();
-        server = NULL;
-
-        if(isPresenceOn == PRESENCE_ON)
+        catch(const CloseApp&)
         {
-            stopPresence();
+            break;
         }
     }
-    catch (const std::exception& e)
+    std::cout << "Stopping the server" << std::endl;
+
+    g_resource.reset();
+
+    if(g_isPresenceStarted)
     {
-        std::cout << "main exception  : " << e.what() << std::endl;
+        stopPresence();
     }
-    std::cout << "Stopping the Server" << std::endl;
 }
 
diff --git a/service/resource-encapsulation/examples/linux/SeparateResponseServer.cpp b/service/resource-encapsulation/examples/linux/SeparateResponseServer.cpp
new file mode 100755 (executable)
index 0000000..9edf591
--- /dev/null
@@ -0,0 +1,160 @@
+/******************************************************************
+ *
+ * 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 "RCSResourceObject.h"
+#include "RCSRequest.h"
+#include "RCSSeparateResponse.h"
+
+#include "OCPlatform.h"
+
+using namespace OC::OCPlatform;
+using namespace OIC::Service;
+
+constexpr int RESOURCE_TEMP = 1;
+constexpr int RESOURCE_LIGHT = 2;
+
+RCSResourceObject::Ptr g_resource;
+
+void handleRequestWithDelay(int delayInMillis, const RCSRequest& request,
+        const RCSResourceAttributes& requestedAttrs)
+{
+    std::this_thread::sleep_for(std::chrono::milliseconds{ delayInMillis });
+
+    if (!requestedAttrs.empty())
+    {
+        auto resObject = request.getResourceObject().lock();
+
+        RCSResourceObject::LockGuard lock{ resObject };
+        auto& resAttrs = resObject->getAttributes();
+        for (const auto& kv : requestedAttrs)
+        {
+            if (resAttrs.contains(kv.key())) resAttrs[kv.key()] = kv.value();
+        }
+    }
+
+    RCSSeparateResponse(request).set();
+
+    std::cout << "Separate response is set!" << std::endl;
+}
+
+void doSeparateResponse(const RCSRequest& request, const RCSResourceAttributes& requestedAttrs)
+{
+    int delay = std::rand() % 3000 + 500;
+
+    std::cout << "Response will be sent in " << delay << "ms" << std::endl;
+
+    std::thread(handleRequestWithDelay, delay, request, requestedAttrs).detach();
+}
+
+int processUserInput(int min, int max)
+{
+    assert(min <= max);
+
+    int input;
+
+    while(true)
+    {
+        std::cin >> input;
+
+        if (!std::cin.fail())
+        {
+            if(min <= input && input <= max) return input;
+        }
+
+        std::cin.clear();
+        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
+
+        std::cout << "Invalid Input, please try again\n";
+    }
+}
+
+void printAttributes(const RCSResourceAttributes& attrs)
+{
+    for(const auto& attr : attrs)
+    {
+        std::cout << "\tkey : " << attr.key() << "\n\tvalue : "
+                  << attr.value().toString() << std::endl;
+    }
+}
+
+RCSGetResponse requestHandlerForGet(const RCSRequest& request, RCSResourceAttributes&)
+{
+    std::cout << "Received a Get request from Client" << std::endl;
+
+    doSeparateResponse(request, RCSResourceAttributes{ });
+
+    return RCSGetResponse::separate();
+}
+
+RCSSetResponse requestHandlerForSet(const RCSRequest& request, RCSResourceAttributes& attrs)
+{
+    std::cout << "Received a Set request from Client" << std::endl;
+    printAttributes(attrs);
+
+    doSeparateResponse(request, attrs);
+
+    return RCSSetResponse::separate();
+}
+
+void initServer(const std::string& resourceUri, const std::string& resourceType)
+{
+    g_resource = RCSResourceObject::Builder(resourceUri, resourceType, "oic.if.").build();
+}
+
+void selectResourceType()
+{
+    std::cout << "========================================================\n";
+    std::cout << "Select Resource Type                                    \n";
+    std::cout << RESOURCE_TEMP << ". Temperature                          \n";
+    std::cout << RESOURCE_LIGHT << ". Light                               \n";
+    std::cout << "========================================================\n";
+
+    int resourceType = processUserInput(RESOURCE_TEMP, RESOURCE_LIGHT);
+
+    switch (resourceType)
+    {
+        case RESOURCE_TEMP:
+            initServer("/a/TempSensor", "oic.r.temperaturesensor");
+            break;
+
+        case RESOURCE_LIGHT:
+            initServer("/a/light", "oic.r.light");
+            break;
+    }
+
+    g_resource->setGetRequestHandler(requestHandlerForGet);
+    g_resource->setSetRequestHandler(requestHandlerForSet);
+}
+
+int main(void)
+{
+    selectResourceType();
+
+    std::cout << "Resource successfully created!" << std::endl;
+
+    std::cout << "Press '1' to stop the process" << std::endl;
+
+    while (std::cin.get() != '1');
+
+    std::cout << "Stopping the server" << std::endl;
+
+    g_resource.reset();
+}
+
diff --git a/service/resource-encapsulation/examples/linux/secureResourceExample/README b/service/resource-encapsulation/examples/linux/secureResourceExample/README
new file mode 100644 (file)
index 0000000..d1401a6
--- /dev/null
@@ -0,0 +1,75 @@
+### Build Instruction ###
+
+1) build Iotivity code for linux platform
+
+   $ scons SECURED=1
+
+NOTE:
+   To build in debug mode
+   $ scons SECURED=1 RELEASE=0
+
+### Sample Apps Running Instructions ###
+
+1) Change directory to:
+
+   ~/iotivity/out/linux/{TARGET_ARCH}/{MODE}/service/resource-encapsulation/examples/linux/secureResourceExample
+
+   {TARGET_ARCH} is your machine Architecture. For Example : x86
+   {MODE} is build mode i.e. RELEASE mode or DEBUG mode.
+
+2) Set the Library Path
+
+   $ export LD_LIBRARY_PATH=../../../../../../{MODE}
+
+3) Run the sample Resource Server -> ./sampleSecureServer
+   Follow the instructions on the screen to create a secure resource.
+
+4) Open a new terminal and repeat the step (1) & (2).
+
+5) Run the Sample client -> ./sampleAutorizedClient
+   Follow the instructions on the screen to test the client functionalities.
+
+### Varification of Secure Resource ###
+
+In order to verify the resource that you created is secure or not
+you can run the other client app to access the secure resource:
+
+1) Open the new terminal goto : ~/iotivity/out/linux/{TARGET_ARCH}/{MODE}/service/resource-encapsulation/examples/linux
+
+2) Set the Library Path
+
+   $ export LD_LIBRARY_PATH=../../../../../{MODE}
+
+3) Run the sample Resource Client -> ./sampleResourceClient
+
+4) Perform the discovery for Light Resource.
+
+5) Once you discovery of Light resource done. select the option provided in the app.
+
+   For example : startMonitoring , If you select the option you will see on the server side
+   i.e. secure resource No request has came & client side no response. Because the sample that we ran is not the authorized client.
+   It doesn't have the credentials to access the resource.
+
+### About the Sample Applications ###
+
+1) In the main function of both the Client and Server samples, we are passing the json files to the OCPersistentStorage
+   Structure and same OCPersistentStorage's reference passing as the last parameter to "PlatformConfig" API.
+
+   oic_svr_db_client --> In Client Sample
+   oic_svr_db_server --> In server sample
+
+2) Additionally, on server-side while creating a Secure resource we have spcified the OC_SECURE as the
+   resource property flag.
+
+3) After Platform configuration and Resource creation, it is the Security manager module (~/iotivity/resource/csdk/security)
+   who decides whether to accept/reject the request as per the json file passed for platform configuration.
+
+4) Json files contains the static values. It means server contains the entry for the client in the ACL List, credentials and
+   other fields and client has the same subject id, credentials etc. for the server as it is there in the server Json file.
+
+5) The same json files can be used for the different client and server samples. Sample Applications is just to show that at
+   the RE layer we can have the Secure resource like we have at the CSDK and RI layer. in real scenerios
+   this json files will be populated with the mechanisms provided by the Security module of Iotivity stack.
+   (~/iotivity/resource/csdk/security).
+
+NOTE : More information about "Iotivity Security mechanism" can be found at : https://wiki.iotivity.org/iotivity_security
diff --git a/service/resource-encapsulation/examples/linux/secureResourceExample/SConscript b/service/resource-encapsulation/examples/linux/secureResourceExample/SConscript
new file mode 100644 (file)
index 0000000..3ad2106
--- /dev/null
@@ -0,0 +1,76 @@
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+##
+# linux RE Secure sample apps  build script (Secure Server &  Client)
+##
+Import('env')
+
+# Add third party libraries
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+
+sample_env = lib_env.Clone()
+
+sample_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x'])
+sample_env.AppendUnique(LIBS = [
+    'rcs_common',
+    'oc',
+    'octbstack',
+    'oc_logger',
+    'connectivity_abstraction',
+    'coap',
+    'pthread',
+    'tinydtls'
+    ])
+sample_env.AppendUnique(CPPPATH = ['../../../include'])
+
+if 'rt' in sample_env.get('LIBS'):
+    sample_env.Append(LIBS = ['rt'])
+
+######################################################################
+# ##### Authorized Client #####
+######################################################################
+client_env = sample_env.Clone()
+client_env.AppendUnique(LIBS = 'rcs_client')
+
+sampleAuthorizedClient = client_env.Program('sampleAuthorizedClient', 'SampleAuthorizedClient.cpp')
+client_env.InstallTarget(sampleAuthorizedClient, 'sampleAuthorizedClient')
+
+######################################################################
+# ##### Secure Server #####
+######################################################################
+server_env = sample_env.Clone()
+server_env.AppendUnique(LIBS = 'rcs_server')
+
+sampleSecureServer = server_env.Program('sampleSecureServer', 'SampleSecureServer.cpp')
+server_env.InstallTarget(sampleSecureServer, 'sampleSecureServer')
+
+######################################################################
+# ##### Copy the client & Server credentials files to build directory #####
+######################################################################
+
+src_dir = sample_env.get('SRC_DIR')
+svr_db_src_dir = src_dir + '/service/resource-encapsulation/examples/linux/secureResourceExample/'
+svr_db_build_dir = env.get('BUILD_DIR') +'/service/resource-encapsulation/examples/linux/secureResourceExample/'
+sample_env.Alias("install", sample_env.Install( svr_db_build_dir,
+                svr_db_src_dir + 'oic_svr_db_client.json'))
+sample_env.Alias("install", sample_env.Install( svr_db_build_dir,
+                svr_db_src_dir + 'oic_svr_db_server.json'))
diff --git a/service/resource-encapsulation/examples/linux/secureResourceExample/SampleAuthorizedClient.cpp b/service/resource-encapsulation/examples/linux/secureResourceExample/SampleAuthorizedClient.cpp
new file mode 100644 (file)
index 0000000..5b53677
--- /dev/null
@@ -0,0 +1,361 @@
+//******************************************************************
+//
+// 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 <iostream>
+
+#include "RCSDiscoveryManager.h"
+#include "RCSRemoteResourceObject.h"
+#include "RCSResourceAttributes.h"
+#include "RCSAddress.h"
+
+#include "OCPlatform.h"
+
+#define DECLARE_MENU(FUNC, ...) { #FUNC, FUNC }
+
+using namespace OC;
+using namespace OIC::Service;
+
+struct CloseApp {};
+
+struct MenuItem
+{
+    private:
+        typedef void(*Handler)();
+
+    public:
+        const std::string title;
+        const Handler handler;
+};
+
+typedef void(*Runner)();
+
+constexpr int RESOURCE_TEMP = 1;
+constexpr int RESOURCE_LIGHT = 2;
+
+const std::string RESOURCE_TYPE_LIGHT = "oic.r.light";
+
+RCSRemoteResourceObject::Ptr g_selectedResource;
+std::vector<RCSRemoteResourceObject::Ptr> g_discoveredResources;
+
+std::string g_attrKey;
+Runner g_currentRun;
+
+std::ostream &operator<<(std::ostream &os, const RCSRemoteResourceObject::Ptr &object)
+{
+    return os << "\turi : " << object->getUri() << std::endl <<
+           "\thost address : " << object->getAddress();
+}
+
+std::ostream &operator<<(std::ostream &os, const MenuItem &item)
+{
+    return os << item.title;
+}
+
+void onSelected(const RCSRemoteResourceObject::Ptr &object)
+{
+    g_selectedResource = object;
+}
+
+void onSelected(const MenuItem &item)
+{
+    std::cout << item.title << " start.." << std::endl;
+    item.handler();
+}
+
+int processUserInput(int min = std::numeric_limits<int>::min(),
+                     int max = std::numeric_limits<int>::max())
+{
+    assert(min <= max);
+
+    int input;
+
+    std::cin >> input;
+    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
+
+    if (!std::cin.fail() && min <= input && input <= max) return input;
+
+    std::cin.clear();
+    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
+
+    throw std::runtime_error("Invalid Input, please try again");
+}
+
+template<typename D>
+void displayItem(int width, int index, const D &data)
+{
+    std::cout.width(width);
+    std::cout << std::right << index << ". ";
+    std::cout << data << std::endl;
+}
+
+template<typename T>
+void displayItems(const std::vector<T> &items)
+{
+    std::cout << std::endl;
+
+    const auto width = (items.size() + 1) / 10 + 1;
+
+    for (size_t i = 0; i < items.size(); ++i)
+    {
+        displayItem(width, i + 1, items[i]);
+    }
+    displayItem(width, items.size() + 1, "quit");
+}
+
+template<typename T>
+void selectItem(const std::vector<T> &items)
+{
+    int selected = processUserInput(1, items.size() + 1) - 1;
+
+    if (selected == static_cast<int>(items.size())) throw CloseApp();
+
+    onSelected(items[selected]);
+}
+
+template<typename T>
+void handleItems(const std::vector<T> &items)
+{
+    displayItems(items);
+    selectItem(items);
+}
+
+void printAttribute(const std::string &key, const RCSResourceAttributes::Value &value)
+{
+    std::cout << "\tkey : " << key << std::endl
+              << "\tvalue : " << value.toString() << std::endl;
+}
+
+void printAttributes(const RCSResourceAttributes &attributes)
+{
+    if (attributes.empty())
+    {
+        std::cout << "\tattributes is empty" << std::endl;
+    }
+
+    for (const auto &attr : attributes)
+    {
+        printAttribute(attr.key(), attr.value());
+    }
+}
+
+void onResourceStateChanged(ResourceState resourceState)
+{
+    std::cout << "onResourceStateChanged callback" << std::endl;
+
+    switch (resourceState)
+    {
+        case ResourceState::NONE:
+            std::cout << "\tState changed to : NOT_MONITORING" << std::endl;
+            break;
+
+        case ResourceState::ALIVE:
+            std::cout << "\tState changed to : ALIVE" << std::endl;
+            break;
+
+        case ResourceState::REQUESTED:
+            std::cout << "\tState changed to : REQUESTED" << std::endl;
+            break;
+
+        case ResourceState::LOST_SIGNAL:
+            std::cout << "\tState changed to : LOST_SIGNAL" << std::endl;
+            break;
+
+        case ResourceState::DESTROYED:
+            std::cout << "\tState changed to : DESTROYED" << std::endl;
+            break;
+    }
+}
+
+void onRemoteAttributesReceived(const RCSResourceAttributes &attributes, int)
+{
+    std::cout << "onRemoteAttributesReceived callback" << std::endl;
+    printAttributes(attributes);
+}
+
+void startMonitoring()
+{
+    if (g_selectedResource->isMonitoring())
+    {
+        std::cout << "\tAlready Started..." << std::endl;
+        return;
+    }
+
+    g_selectedResource->startMonitoring(&onResourceStateChanged);
+    std::cout << "\tMonitoring Started..." << std::endl;
+}
+
+void stopMonitoring()
+{
+    if (!g_selectedResource->isMonitoring())
+    {
+        std::cout << "\tMonitoring not started..." << std::endl;
+        return;
+    }
+
+    g_selectedResource->stopMonitoring();
+    std::cout << "\tMonitoring stopped..." << std::endl;
+}
+
+void getRemoteAttributes()
+{
+    g_selectedResource->getRemoteAttributes(onRemoteAttributesReceived);
+}
+
+void setRemoteAttributes()
+{
+    std::string key;
+
+    std::cout << "\tEnter the Key you want to set : ";
+    std::cin >> key;
+
+    std::cout << "\tEnter the value(INT) you want to set :";
+    RCSResourceAttributes attrs;
+    attrs[key] = processUserInput();
+
+    g_selectedResource->setRemoteAttributes(attrs, onRemoteAttributesReceived);
+}
+
+RCSAddress inputAddress()
+{
+    std::cout << "========================================================";
+    std::cout << "==================" << std::endl;
+    std::cout << "Please enter the address for Unicast Discovery or press enter for multicast" <<
+              std::endl;
+    std::cout << "========================================================";
+    std::cout << "==================" << std::endl;
+
+    std::string address;
+
+    if (std::cin.peek() != '\n') std::cin >> address;
+
+    return address.empty() ? RCSAddress::multicast() : RCSAddress::unicast(address);
+}
+
+void printDiscoveryInProgress()
+{
+    std::cout << "Discovery in progress, press '1' to stop." << std::endl;
+}
+
+void discoverResource()
+{
+    auto onResourceDiscovered = [](
+                                    const RCSRemoteResourceObject::Ptr & discoveredResource)
+    {
+        std::cout << "onResourceDiscovered callback :: " << std::endl;
+
+        std::cout << "\t uri : " << discoveredResource->getUri() << std::endl;
+        std::cout << "\t host address : " << discoveredResource->getAddress() << std::endl;
+
+        g_discoveredResources.push_back(discoveredResource);
+
+        printDiscoveryInProgress();
+    };
+
+    auto resourceType = RESOURCE_TYPE_LIGHT;
+    auto address = inputAddress();
+
+    printDiscoveryInProgress();
+
+    auto discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(address,
+                         resourceType, onResourceDiscovered);
+
+    while (processUserInput() != 1);
+
+    discoveryTask->cancel();
+}
+
+void runResourceControl()
+{
+    static std::vector<MenuItem> resourceMenuItems
+    {
+        DECLARE_MENU(startMonitoring),
+        DECLARE_MENU(stopMonitoring),
+        DECLARE_MENU(getRemoteAttributes),
+        DECLARE_MENU(setRemoteAttributes),
+    };
+
+    handleItems(resourceMenuItems);
+}
+
+void runResourceSelection()
+{
+    handleItems(g_discoveredResources);
+    g_currentRun = runResourceControl;
+}
+
+void runDiscovery()
+{
+    static std::vector<MenuItem> discoveryMenuItems
+    {
+        DECLARE_MENU(discoverResource),
+    };
+
+    handleItems(discoveryMenuItems);
+
+    if (g_discoveredResources.empty()) throw std::runtime_error("No resource found!");
+
+    g_currentRun = runResourceSelection;
+}
+
+static FILE *client_open(const char * /*path*/, const char *mode)
+{
+    return fopen("./oic_svr_db_client.json", mode);
+}
+
+int main()
+{
+
+    OCPersistentStorage ps {client_open, fread, fwrite, fclose, unlink };
+
+    PlatformConfig cfg
+    {
+        OC::ServiceType::InProc, OC::ModeType::Both, "0.0.0.0", 0,
+        OC::QualityOfService::LowQos, &ps
+    };
+
+    OCPlatform::Configure(cfg);
+
+    g_currentRun = runDiscovery;
+
+    while (true)
+    {
+        try
+        {
+            g_currentRun();
+        }
+        catch (const std::exception &e)
+        {
+            std::cout << e.what() << std::endl;
+        }
+        catch (const CloseApp &)
+        {
+            break;
+        }
+    }
+
+    if ((g_selectedResource) && (g_selectedResource->isMonitoring()))
+    {
+        g_selectedResource->stopMonitoring();
+    }
+
+    std::cout << "Stopping the client" << std::endl;
+
+    return 0;
+}
diff --git a/service/resource-encapsulation/examples/linux/secureResourceExample/SampleSecureServer.cpp b/service/resource-encapsulation/examples/linux/secureResourceExample/SampleSecureServer.cpp
new file mode 100644 (file)
index 0000000..5d5a345
--- /dev/null
@@ -0,0 +1,251 @@
+/******************************************************************
+ *
+ * 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 "RCSResourceObject.h"
+#include "OCPlatform.h"
+
+using namespace OC::OCPlatform;
+using namespace OIC::Service;
+
+struct CloseApp {};
+
+constexpr int RESOURCE_LIGHT = 1;
+
+constexpr int DEFALUT_SERVER = 1;
+constexpr int CUSTOM_SERVER = 2;
+
+constexpr int INCREASE = 1;
+constexpr int DECREASE = 2;
+
+typedef void (*DisplayControlMenuFunc)();
+typedef std::function<void()> Run;
+
+Run g_currentRun;
+bool g_isPresenceStarted = false;
+
+RCSResourceObject::Ptr g_resource;
+
+int processUserInput(int min, int max)
+{
+    assert(min <= max);
+
+    int input;
+
+    std::cin >> input;
+
+    if (!std::cin.fail())
+    {
+        if (input == max + 1) throw CloseApp();
+        if (min <= input) return input;
+    }
+
+    std::cin.clear();
+    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
+
+    throw std::runtime_error("Invalid Input, please try again");
+}
+
+void displayControlLightMenu()
+{
+    std::cout << "========================================================\n";
+    std::cout << INCREASE << ". Increase Brightness by 1 stage            \n";
+    std::cout << DECREASE << ". Decrease Brightness by 1 stage            \n";
+    std::cout << DECREASE + 1 << ". Quit                                  \n";
+    std::cout << "========================================================\n";
+}
+
+void printAttributes(const RCSResourceAttributes &attrs)
+{
+    for (const auto &attr : attrs)
+    {
+        std::cout << "\tkey : " << attr.key() << "\n\tvalue : "
+                  << attr.value().toString() << std::endl;
+    }
+}
+
+RCSGetResponse requestHandlerForGet(const RCSRequest &, RCSResourceAttributes &attrs)
+{
+    std::cout << "Received a Get request from Client" << std::endl;
+    printAttributes(attrs);
+
+    {
+        RCSResourceObject::LockGuard lock(g_resource);
+        std::cout << "\nSending response to Client : " << std::endl;
+        printAttributes(g_resource->getAttributes());
+    }
+
+    return RCSGetResponse::defaultAction();
+}
+
+RCSSetResponse requestHandlerForSet(const RCSRequest &, RCSResourceAttributes &attrs)
+{
+    std::cout << "Received a Set request from Client" << std::endl;
+    printAttributes(attrs);
+
+    return RCSSetResponse::defaultAction();
+}
+
+void initServer(const std::string &resourceUri, const std::string &resourceType,
+                const std::string &attrKey)
+{
+
+    g_resource = RCSResourceObject::Builder(resourceUri, resourceType, "oic.if.baseline").
+                 setDiscoverable(true).setObservable(true).setSecureFlag(true).build();
+
+    g_resource->setAutoNotifyPolicy(RCSResourceObject::AutoNotifyPolicy::UPDATED);
+    g_resource->setSetRequestHandlerPolicy(RCSResourceObject::SetRequestHandlerPolicy::NEVER);
+    g_resource->setAttribute(attrKey, 0);
+}
+
+void updateAttribute(const std::string &attrKey, int control)
+{
+    const int diff = control == INCREASE ? 1 : - 1;
+
+    {
+        RCSResourceObject::LockGuard lock(g_resource);
+        auto &attrs = g_resource->getAttributes();
+        attrs[attrKey] = attrs[attrKey].get<int>() + diff;
+    }
+
+    if (control == INCREASE)
+    {
+        std::cout << attrKey << " increased." << std::endl;
+    }
+    else
+    {
+        std::cout << attrKey << " decreased." << std::endl;
+    }
+    std::cout << "\nCurrent " << attrKey << ": "
+              << g_resource->getAttributeValue(attrKey).get<int>() << std::endl;
+}
+
+void runResourceControl(DisplayControlMenuFunc displayMenuFunc, const std::string &attrKey)
+{
+    displayMenuFunc();
+    updateAttribute(attrKey, processUserInput(INCREASE, DECREASE));
+}
+
+void runResourceTypeSelection(int resourceMode)
+{
+    std::cout << "========================================================\n";
+    std::cout << RESOURCE_LIGHT << ". Create a Secure Light Resource                              \n";
+    std::cout << RESOURCE_LIGHT + 1 << ". Quit                            \n";
+    std::cout << "========================================================\n";
+
+    int resourceType = processUserInput(RESOURCE_LIGHT, RESOURCE_LIGHT);
+    DisplayControlMenuFunc displayMenuFunc;
+    std::string attrKey;
+
+    switch (resourceType)
+    {
+        case RESOURCE_LIGHT:
+            attrKey = "Brightness";
+            initServer("/a/light", "oic.r.light", attrKey);
+
+            displayMenuFunc = displayControlLightMenu;
+            break;
+    }
+
+    if (resourceMode == CUSTOM_SERVER)
+    {
+        g_resource->setGetRequestHandler(requestHandlerForGet);
+        g_resource->setSetRequestHandler(requestHandlerForSet);
+    }
+
+    g_currentRun = std::bind(runResourceControl, displayMenuFunc, std::move(attrKey));
+}
+
+void runResourceModeSelection()
+{
+    std::cout << "========================================================          \n";
+    std::cout << DEFALUT_SERVER << ". Creation of Secure Resource Without Handlers  \n";
+    std::cout << CUSTOM_SERVER << ". Creation of Secure Resource With Set and Get Handlers \n";
+    std::cout << CUSTOM_SERVER + 1 << ". Quit                                       \n";
+    std::cout << "========================================================          \n";
+
+    g_currentRun = std::bind(runResourceTypeSelection,
+                             processUserInput(DEFALUT_SERVER, CUSTOM_SERVER));
+}
+
+void runPresenceSelection()
+{
+    constexpr int PRESENCE_ON = 1;
+    constexpr int PRESENCE_OFF = 2;
+
+    std::cout << "========================================================\n";
+    std::cout << PRESENCE_ON << ". Presence On                            \n";
+    std::cout << PRESENCE_OFF << ". Presence Off                          \n";
+    std::cout << PRESENCE_OFF + 1 << ". Quit                              \n";
+    std::cout << "========================================================\n";
+
+    if (processUserInput(PRESENCE_ON, PRESENCE_OFF) == PRESENCE_ON)
+    {
+        g_isPresenceStarted = true;
+        startPresence(3);
+    }
+
+    g_currentRun = runResourceModeSelection;
+}
+
+static FILE *client_open(const char * /*path*/, const char *mode)
+{
+    return fopen("./oic_svr_db_server.json", mode);
+}
+
+int main(void)
+{
+    OCPersistentStorage ps {client_open, fread, fwrite, fclose, unlink };
+
+    OC::PlatformConfig cfg
+    {
+        OC::ServiceType::InProc, OC::ModeType::Server, "0.0.0.0", 0,
+        OC::QualityOfService::LowQos, &ps
+    };
+
+    OC::OCPlatform::Configure(cfg);
+
+    g_currentRun = runPresenceSelection;
+
+    while (true)
+    {
+        try
+        {
+            g_currentRun();
+        }
+        catch (const std::exception &e)
+        {
+            std::cout << e.what() << std::endl;
+        }
+        catch (const CloseApp &)
+        {
+            break;
+        }
+    }
+    std::cout << "Stopping the server" << std::endl;
+
+    g_resource.reset();
+
+    if (g_isPresenceStarted)
+    {
+        stopPresence();
+    }
+
+}
+
diff --git a/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_client.dat b/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_client.dat
new file mode 100644 (file)
index 0000000..9de47b8
Binary files /dev/null and b/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_client.dat differ
diff --git a/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_client.json b/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_client.json
new file mode 100644 (file)
index 0000000..5052bd1
--- /dev/null
@@ -0,0 +1,102 @@
+{\r
+    "acl": {\r
+        "aclist": {\r
+            "aces": [\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/res",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/p",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/types/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/ad",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/acl",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/doxm",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        } ,\r
+                        {\r
+                            "href": "/oic/sec/pstat",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                }\r
+            ]\r
+        },\r
+        "rowneruuid" : "32323232-3232-3232-3232-323232323232"\r
+    },\r
+    "pstat": {\r
+        "isop": true,\r
+        "deviceuuid": "32323232-3232-3232-3232-323232323232",\r
+        "rowneruuid": "32323232-3232-3232-3232-323232323232",\r
+        "cm": 0,\r
+        "tm": 0,\r
+        "om": 3,\r
+        "sm": 3\r
+        },\r
+    "doxm": {\r
+        "oxms": [0],\r
+        "oxmsel": 0,\r
+        "sct": 1,\r
+        "owned": true,\r
+        "deviceuuid": "32323232-3232-3232-3232-323232323232",\r
+        "devowneruuid": "32323232-3232-3232-3232-323232323232",\r
+        "rowneruuid": "32323232-3232-3232-3232-323232323232",\r
+        "dpc": false\r
+    },\r
+    "cred": {\r
+        "creds": [\r
+            {\r
+                "credid": 1,\r
+                "subjectuuid": "31313131-3131-3131-3131-313131313131",\r
+                "credtype": 1,\r
+                "privatedata": {\r
+                    "data": "AAAAAAAAAAAAAAAA",\r
+                    "encoding": "oic.sec.encoding.raw"\r
+                }\r
+            }\r
+        ],\r
+        "rowneruuid": "32323232-3232-3232-3232-323232323232"\r
+    }\r
+}
\ No newline at end of file
diff --git a/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_server.dat b/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_server.dat
new file mode 100644 (file)
index 0000000..31e1814
Binary files /dev/null and b/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_server.dat differ
diff --git a/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_server.json b/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_server.json
new file mode 100644 (file)
index 0000000..0e1bf23
--- /dev/null
@@ -0,0 +1,127 @@
+{\r
+    "acl": {\r
+        "aclist": {\r
+            "aces": [\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/res",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/p",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/res/types/d",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/ad",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/acl",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/doxm",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        } ,\r
+                        {\r
+                            "href": "/oic/sec/pstat",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/a/light",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/a/light0",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        },\r
+                        {\r
+                            "href": "/a/light1",\r
+                            "rel": "",\r
+                            "rt": "",\r
+                            "if": ""\r
+                        }\r
+                    ],\r
+                    "permission": 6\r
+                }\r
+            ]\r
+        },\r
+        "rowneruuid" : "31313131-3131-3131-3131-313131313131"\r
+    },\r
+    "pstat": {\r
+        "isop": true,\r
+        "deviceuuid": "31313131-3131-3131-3131-313131313131",\r
+        "rowneruuid": "31313131-3131-3131-3131-313131313131",\r
+        "cm": 0,\r
+        "tm": 0,\r
+        "om": 3,\r
+        "sm": 3\r
+        },\r
+    "doxm": {\r
+        "oxms": [0],\r
+        "oxmsel": 0,\r
+        "sct": 1,\r
+        "owned": true,\r
+        "deviceuuid": "31313131-3131-3131-3131-313131313131",\r
+        "devowneruuid": "32323232-3232-3232-3232-323232323232",\r
+        "rowneruuid": "31313131-3131-3131-3131-313131313131",\r
+        "dpc": false\r
+    },\r
+    "cred": {\r
+        "creds": [\r
+            {\r
+                "credid": 1,\r
+                "subjectuuid": "32323232-3232-3232-3232-323232323232",\r
+                "credtype": 1,\r
+                "privatedata": {\r
+                    "data": "AAAAAAAAAAAAAAAA",\r
+                    "encoding": "oic.sec.encoding.raw"\r
+                }\r
+            }\r
+        ],\r
+        "rowneruuid": "31313131-3131-3131-3131-313131313131"\r
+    }\r
+}\r
+\r
index e394253..f8b53ab 100644 (file)
@@ -60,64 +60,3 @@ group
         }
     }
 }
-
-group
-{
-    name: "popup_datetime_text";
-    parts
-    {
-        part
-        {
-            name: "pad_l";
-            type: SPACER;
-            scale: 1;
-            description
-            {
-                state: "default" 0.0;
-                min: POPUP_CONTENT_DEFAULT_PADDING_LEFT_MIN_INC 0;
-                fixed: 1 0;
-                rel1.relative: 0.0 0.0;
-                rel2.relative: 0.0 1.0;
-                align: 0.0 0.0;
-            }
-        }
-        part
-        {
-            name: "pad_r";
-            type: SPACER;
-            scale: 1;
-            description
-            {
-                state: "default" 0.0;
-                min: POPUP_CONTENT_DEFAULT_PADDING_LEFT_MIN_INC 0;
-                fixed: 1 0;
-                rel1.relative: 1.0 0.0;
-                rel2.relative: 1.0 1.0;
-                align: 1.0 0.0;
-            }
-        }
-        part
-        {
-            name: "elm.swallow.content";
-            type: SWALLOW;
-            scale: 1;
-            description
-            {
-                state: "default" 0.0;
-                min: 0 POPUP_EDITFIELD_LAYOUT_MINMAX_HEIGHT_INC;
-                max: -1 POPUP_EDITFIELD_LAYOUT_MINMAX_HEIGHT_INC;
-                align: 0.5 0.5;
-                rel1
-                {
-                    relative: 1.0 0.0;
-                    to_x: "pad_l";
-                }
-                rel2
-                {
-                    relative: 0.0 1.0;
-                    to_x: "pad_r";
-                }
-            }
-        }
-    }
-}
index 40662a7..ec9b7f4 100644 (file)
@@ -102,7 +102,7 @@ void *showContainerAPIs(void *data)
         elm_list_item_append(listnew, "1. Find Light resource", NULL, NULL,
                              findLight, NULL);
 
-        elm_list_item_append(listnew, "1. Find Softsensor resource", NULL, NULL,
+        elm_list_item_append(listnew, "2. Find Softsensor resource", NULL, NULL,
                              findSoftsensor, NULL);
 
         elm_list_go(listnew);
index 5c5ffe7..d9d75d7 100644 (file)
 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
 <?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
-       <storageModule moduleId="org.eclipse.cdt.core.settings">
-               <cconfiguration id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109">
-                       <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109" moduleId="org.eclipse.cdt.core.settings" name="Debug">
-                               <externalSettings/>
-                               <extensions>
-                                       <extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
-                                       <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
-                                       <extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
-                                       <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
-                                       <extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
-                                       <extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
-                                       <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
-                               </extensions>
-                       </storageModule>
-                       <storageModule moduleId="cdtBuildSystem" version="4.0.0">
-                               <configuration artifactName="resampleclient" buildArtefactType="org.tizen.nativecore.buildArtefactType.app" buildProperties="org.eclipse.cdt.build.core.buildArtefactType=org.tizen.nativecore.buildArtefactType.app,org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.debug" description="" errorParsers="org.eclipse.cdt.core.MakeErrorParser;org.eclipse.cdt.core.GCCErrorParser;" id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109" name="Debug" parent="org.tizen.nativecore.config.sbi.gcc45.app.debug">
-                                       <folderInfo id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109." name="/" resourcePath="">
-                                               <toolChain id="org.tizen.nativecore.toolchain.sbi.gcc45.app.debug.266200202" name="Tizen Native Toolchain" superClass="org.tizen.nativecore.toolchain.sbi.gcc45.app.debug">
-                                                       <targetPlatform binaryParser="org.eclipse.cdt.core.ELF" id="org.tizen.nativeide.target.sbi.gnu.platform.base.1788661429" osList="linux,win32" superClass="org.tizen.nativeide.target.sbi.gnu.platform.base"/>
-                                                       <builder arguments="--eval=&quot;SHELL=cmd&quot; -r" autoBuildTarget="all" buildPath="${workspace_loc:/TMSampleApp}/Debug" enableAutoBuild="true" id="org.tizen.nativecore.target.sbi.gnu.builder.1749302123" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Tizen Application Builder" superClass="org.tizen.nativecore.target.sbi.gnu.builder"/>
-                                                       <tool id="org.tizen.nativecore.tool.sbi.gnu.archiver.345678603" name="Archiver" superClass="org.tizen.nativecore.tool.sbi.gnu.archiver"/>
-                                                       <tool command="arm-linux-gnueabi-g++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler.1794187316" name="C++ Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler">
-                                                               <option id="gnu.cpp.compiler.option.optimization.level.719656926" name="Optimization Level" superClass="gnu.cpp.compiler.option.optimization.level" useByScannerDiscovery="false" value="gnu.cpp.compiler.optimization.level.none" valueType="enumerated"/>
-                                                               <option id="sbi.gnu.cpp.compiler.option.debugging.level.core.378028433" name="Debug level" superClass="sbi.gnu.cpp.compiler.option.debugging.level.core" useByScannerDiscovery="false" value="gnu.cpp.compiler.debugging.level.max" valueType="enumerated"/>
-                                                               <option id="sbi.gnu.cpp.compiler.option.831567474" name="Tizen-Target" superClass="sbi.gnu.cpp.compiler.option" useByScannerDiscovery="false" valueType="userObjs">
-                                                                       <listOptionValue builtIn="false" value="mobile-2.3-device.core_gcc46.armel.core.app"/>
-                                                               </option>
-                                                               <option id="sbi.gnu.cpp.compiler.option.frameworks_inc.core.1543030783" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.cpp.compiler.option.frameworks_inc.core" useByScannerDiscovery="false" valueType="includePath">
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
-                                                               </option>
-                                                               <option id="sbi.gnu.cpp.compiler.option.frameworks_cflags.core.1612037830" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.cpp.compiler.option.frameworks_cflags.core" useByScannerDiscovery="false" valueType="stringList">
-                                                                       <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
-                                                                       <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
-                                                                       <listOptionValue builtIn="false" value=" -fPIE"/>
-                                                                       <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="-mthumb"/>
-                                                               </option>
-                                                               <option id="gnu.cpp.compiler.option.include.paths.1501991974" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" useByScannerDiscovery="false" valueType="includePath">
-                                                                       <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;..\..\..\..\src\resourceBroker\include&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;..\..\..\..\src\resourceCache\include&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;..\..\..\..\src\common\utils\include&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;..\..\..\..\src\common\expiryTimer\include&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;..\..\..\..\src\common\expiryTimer\src&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;..\..\..\..\src\common\primitiveResource\include&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;..\..\..\..\include&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\include&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\c_common&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\stack\include&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\logger\include&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\occoap\include&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\ocrandom\include&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\ocsocket\include&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\oc_logger\include&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\extlibs\timer&quot;"/>
-                                                               </option>
-                                                               <option id="sbi.gnu.cpp.compiler.option.frameworks.core.1095600730" name="Tizen-Frameworks" superClass="sbi.gnu.cpp.compiler.option.frameworks.core" useByScannerDiscovery="false" valueType="userObjs">
-                                                                       <listOptionValue builtIn="false" value="Native_API"/>
-                                                               </option>
-                                                               <option id="gnu.cpp.compiler.option.preprocessor.def.371963530" name="Defined symbols (-D)" superClass="gnu.cpp.compiler.option.preprocessor.def" useByScannerDiscovery="false" valueType="definedSymbols">
-                                                                       <listOptionValue builtIn="false" value="_DEBUG"/>
-                                                               </option>
-                                                               <option id="gnu.cpp.compiler.option.dialect.std.1929207991" name="Language standard" superClass="gnu.cpp.compiler.option.dialect.std" value="gnu.cpp.compiler.dialect.default" valueType="enumerated"/>
-                                                               <option id="sbi.gnu.cpp.compiler.option.misc.pic.core.755649926" name="-fPIC option" superClass="sbi.gnu.cpp.compiler.option.misc.pic.core" value="true" valueType="boolean"/>
-                                                               <option id="gnu.cpp.compiler.option.other.other.1760093561" name="Other flags" superClass="gnu.cpp.compiler.option.other.other" value="-c -fmessage-length=0 -std=c++0x" valueType="string"/>
-                                                               <inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.1956958926" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
-                                                       </tool>
-                                                       <tool command="arm-linux-gnueabi-gcc.exe" id="org.tizen.nativecore.tool.sbi.gnu.c.compiler.2072036030" name="C Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.c.compiler">
-                                                               <option defaultValue="gnu.c.optimization.level.none" id="gnu.c.compiler.option.optimization.level.1042898971" name="Optimization Level" superClass="gnu.c.compiler.option.optimization.level" useByScannerDiscovery="false" valueType="enumerated"/>
-                                                               <option id="sbi.gnu.c.compiler.option.debugging.level.core.135607770" name="Debug level" superClass="sbi.gnu.c.compiler.option.debugging.level.core" useByScannerDiscovery="false" value="gnu.c.debugging.level.max" valueType="enumerated"/>
-                                                               <option id="sbi.gnu.c.compiler.option.571493571" name="Tizen-Target" superClass="sbi.gnu.c.compiler.option" useByScannerDiscovery="false" valueType="userObjs">
-                                                                       <listOptionValue builtIn="false" value="mobile-2.3-device.core_gcc46.armel.core.app"/>
-                                                               </option>
-                                                               <option id="sbi.gnu.c.compiler.option.frameworks_inc.core.107632308" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.c.compiler.option.frameworks_inc.core" useByScannerDiscovery="false" valueType="includePath">
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
-                                                               </option>
-                                                               <option id="sbi.gnu.c.compiler.option.frameworks_cflags.core.1275911900" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.c.compiler.option.frameworks_cflags.core" useByScannerDiscovery="false" valueType="stringList">
-                                                                       <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
-                                                                       <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
-                                                                       <listOptionValue builtIn="false" value=" -fPIE"/>
-                                                                       <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="-mthumb"/>
-                                                               </option>
-                                                               <option id="gnu.c.compiler.option.include.paths.109116980" name="Include paths (-I)" superClass="gnu.c.compiler.option.include.paths" useByScannerDiscovery="false" valueType="includePath">
-                                                                       <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
-                                                               </option>
-                                                               <option id="sbi.gnu.c.compiler.option.frameworks.core.1552601669" name="Tizen-Frameworks" superClass="sbi.gnu.c.compiler.option.frameworks.core" useByScannerDiscovery="false" valueType="userObjs">
-                                                                       <listOptionValue builtIn="false" value="Native_API"/>
-                                                               </option>
-                                                               <option id="gnu.c.compiler.option.preprocessor.def.symbols.2021130927" name="Defined symbols (-D)" superClass="gnu.c.compiler.option.preprocessor.def.symbols" useByScannerDiscovery="false" valueType="definedSymbols">
-                                                                       <listOptionValue builtIn="false" value="_DEBUG"/>
-                                                               </option>
-                                                               <option id="sbi.gnu.c.compiler.option.misc.pic.core.1304419386" name="-fPIC option" superClass="sbi.gnu.c.compiler.option.misc.pic.core" value="false" valueType="boolean"/>
-                                                               <option id="gnu.c.compiler.option.misc.other.2029079564" name="Other flags" superClass="gnu.c.compiler.option.misc.other" value="-c -fmessage-length=0 -std=c++0x" valueType="string"/>
-                                                               <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.1859092644" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
-                                                       </tool>
-                                                       <tool id="org.tizen.nativeide.tool.sbi.gnu.c.linker.base.944066372" name="C Linker" superClass="org.tizen.nativeide.tool.sbi.gnu.c.linker.base"/>
-                                                       <tool command="arm-linux-gnueabi-g++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.linker.1667264058" name="C++ Linker" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.linker">
-                                                               <option id="sbi.gnu.cpp.linker.option.frameworks_lflags.core.1178784315" name="Tizen-Frameworks-Other-Lflags" superClass="sbi.gnu.cpp.linker.option.frameworks_lflags.core" valueType="stringList">
-                                                                       <listOptionValue builtIn="false" value="${TC_LINKER_MISC}"/>
-                                                                       <listOptionValue builtIn="false" value="${RS_LINKER_MISC}"/>
-                                                                       <listOptionValue builtIn="false" value="-pie -lpthread "/>
-                                                                       <listOptionValue builtIn="false" value="-Xlinker -rpath=&quot;/home/developer/sdk_tools/lib&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="-Xlinker --version-script=${PROJ_PATH}/.exportMap"/>
-                                                                       <listOptionValue builtIn="false" value="-L&quot;${SBI_SYSROOT}/usr/lib&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="$(RS_LIBRARIES)"/>
-                                                               </option>
-                                                               <option id="gnu.cpp.link.option.paths.1087248355" name="Library search path (-L)" superClass="gnu.cpp.link.option.paths" valueType="libPaths">
-                                                                       <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/lib}&quot;"/>
-                                                               </option>
-                                                               <option id="gnu.cpp.link.option.libs.2039500142" name="Libraries (-l)" superClass="gnu.cpp.link.option.libs" valueType="libs">
-                                                                       <listOptionValue builtIn="false" value="oc"/>
-                                                                       <listOptionValue builtIn="false" value="octbstack"/>
-                                                                       <listOptionValue builtIn="false" value="oc_logger"/>
-                                                                       <listOptionValue builtIn="false" value="oc_logger_core"/>
-                                                                       <listOptionValue builtIn="false" value="connectivity_abstraction"/>
-                                                                       <listOptionValue builtIn="false" value="uuid"/>
-                                                                       <listOptionValue builtIn="false" value="boost_date_time"/>
-                                                                       <listOptionValue builtIn="false" value="boost_system"/>
-                                                                       <listOptionValue builtIn="false" value="boost_thread"/>
-                                                                       <listOptionValue builtIn="false" value="rcs_client"/>
-                                                                       <listOptionValue builtIn="false" value="rcs_common"/>
-                                                                       <listOptionValue builtIn="false" value="rcs_server"/>
-                                                               </option>
-                                                               <inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.618645708" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
-                                                                       <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
-                                                                       <additionalInput kind="additionalinput" paths="$(LIBS)"/>
-                                                               </inputType>
-                                                       </tool>
-                                                       <tool command="arm-linux-gnueabi-as.exe" id="org.tizen.nativeapp.tool.sbi.gnu.assembler.base.1585687908" name="Assembler" superClass="org.tizen.nativeapp.tool.sbi.gnu.assembler.base">
-                                                               <inputType id="cdt.managedbuild.tool.gnu.assembler.input.89256350" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
-                                                       </tool>
-                                                       <tool id="org.tizen.nativecore.tool.fnmapgen.353447784" name="C FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen"/>
-                                                       <tool id="org.tizen.nativecore.tool.fnmapgen.cpp.734608698" name="C++ FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen.cpp"/>
-                                                       <tool id="org.tizen.nativecore.tool.ast.125567506" name="C Static Analyzer" superClass="org.tizen.nativecore.tool.ast"/>
-                                                       <tool id="org.tizen.nativecore.tool.ast.cpp.2107204356" name="C++ Static Analyzer" superClass="org.tizen.nativecore.tool.ast.cpp"/>
-                                                       <tool id="org.tizen.nativecore.tool.sbi.po.compiler.1190161351" name="PO Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.po.compiler"/>
-                                                       <tool id="org.tizen.nativecore.tool.sbi.edc.compiler.1621384631" name="EDC Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.edc.compiler"/>
-                                               </toolChain>
-                                       </folderInfo>
-                                       <sourceEntries>
-                                               <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="inc"/>
-                                               <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="res"/>
-                                               <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
-                                       </sourceEntries>
-                               </configuration>
-                       </storageModule>
-                       <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
-               </cconfiguration>
-               <cconfiguration id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396">
-                       <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396" moduleId="org.eclipse.cdt.core.settings" name="Release">
-                               <externalSettings/>
-                               <extensions>
-                                       <extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
-                                       <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
-                                       <extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
-                                       <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
-                                       <extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
-                                       <extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
-                                       <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
-                               </extensions>
-                       </storageModule>
-                       <storageModule moduleId="cdtBuildSystem" version="4.0.0">
-                               <configuration artifactName="tmsampleapp" buildArtefactType="org.tizen.nativecore.buildArtefactType.app" buildProperties="org.eclipse.cdt.build.core.buildArtefactType=org.tizen.nativecore.buildArtefactType.app,org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.release" description="" errorParsers="org.eclipse.cdt.core.MakeErrorParser;org.eclipse.cdt.core.GCCErrorParser;" id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396" name="Release" parent="org.tizen.nativecore.config.sbi.gcc45.app.release">
-                                       <folderInfo id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396." name="/" resourcePath="">
-                                               <toolChain id="org.tizen.nativecore.toolchain.sbi.gcc45.app.release.32000863" name="Tizen Native Toolchain" superClass="org.tizen.nativecore.toolchain.sbi.gcc45.app.release">
-                                                       <targetPlatform binaryParser="org.eclipse.cdt.core.ELF" id="org.tizen.nativeide.target.sbi.gnu.platform.base.1750758769" osList="linux,win32" superClass="org.tizen.nativeide.target.sbi.gnu.platform.base"/>
-                                                       <builder buildPath="${workspace_loc:/TMSampleApp}/Release" id="org.tizen.nativecore.target.sbi.gnu.builder.2029564551" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Tizen Application Builder" superClass="org.tizen.nativecore.target.sbi.gnu.builder"/>
-                                                       <tool id="org.tizen.nativecore.tool.sbi.gnu.archiver.224082468" name="Archiver" superClass="org.tizen.nativecore.tool.sbi.gnu.archiver"/>
-                                                       <tool command="clang++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler.1434486618" name="C++ Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler">
-                                                               <option id="gnu.cpp.compiler.option.optimization.level.1709393206" name="Optimization Level" superClass="gnu.cpp.compiler.option.optimization.level" value="gnu.cpp.compiler.optimization.level.most" valueType="enumerated"/>
-                                                               <option id="sbi.gnu.cpp.compiler.option.debugging.level.core.221700213" name="Debug level" superClass="sbi.gnu.cpp.compiler.option.debugging.level.core"/>
-                                                               <option id="sbi.gnu.cpp.compiler.option.710876023" name="Tizen-Target" superClass="sbi.gnu.cpp.compiler.option" valueType="userObjs">
-                                                                       <listOptionValue builtIn="false" value="mobile-2.3-emulator.core_llvm34.i386.core.app"/>
-                                                               </option>
-                                                               <option id="sbi.gnu.cpp.compiler.option.frameworks_inc.core.1622581330" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.cpp.compiler.option.frameworks_inc.core" valueType="includePath">
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
-                                                               </option>
-                                                               <option id="sbi.gnu.cpp.compiler.option.frameworks_cflags.core.1695583788" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.cpp.compiler.option.frameworks_cflags.core" valueType="stringList">
-                                                                       <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
-                                                                       <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
-                                                                       <listOptionValue builtIn="false" value=" -fPIE"/>
-                                                                       <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
-                                                               </option>
-                                                               <option id="gnu.cpp.compiler.option.include.paths.585301879" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" valueType="includePath">
-                                                                       <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
-                                                               </option>
-                                                               <option id="sbi.gnu.cpp.compiler.option.frameworks.core.708669314" name="Tizen-Frameworks" superClass="sbi.gnu.cpp.compiler.option.frameworks.core" valueType="userObjs">
-                                                                       <listOptionValue builtIn="false" value="Native_API"/>
-                                                               </option>
-                                                               <inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.2006056090" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
-                                                       </tool>
-                                                       <tool command="clang.exe" id="org.tizen.nativecore.tool.sbi.gnu.c.compiler.601285388" name="C Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.c.compiler">
-                                                               <option defaultValue="gnu.c.optimization.level.most" id="gnu.c.compiler.option.optimization.level.1778561828" name="Optimization Level" superClass="gnu.c.compiler.option.optimization.level" valueType="enumerated"/>
-                                                               <option id="sbi.gnu.c.compiler.option.debugging.level.core.1695949408" name="Debug level" superClass="sbi.gnu.c.compiler.option.debugging.level.core"/>
-                                                               <option id="sbi.gnu.c.compiler.option.1422818783" name="Tizen-Target" superClass="sbi.gnu.c.compiler.option" valueType="userObjs">
-                                                                       <listOptionValue builtIn="false" value="mobile-2.3-emulator.core_llvm34.i386.core.app"/>
-                                                               </option>
-                                                               <option id="sbi.gnu.c.compiler.option.frameworks_inc.core.1871683675" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.c.compiler.option.frameworks_inc.core" valueType="includePath">
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
-                                                               </option>
-                                                               <option id="sbi.gnu.c.compiler.option.frameworks_cflags.core.371848582" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.c.compiler.option.frameworks_cflags.core" valueType="stringList">
-                                                                       <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
-                                                                       <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
-                                                                       <listOptionValue builtIn="false" value=" -fPIE"/>
-                                                                       <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
-                                                               </option>
-                                                               <option id="gnu.c.compiler.option.include.paths.1254567673" name="Include paths (-I)" superClass="gnu.c.compiler.option.include.paths" valueType="includePath">
-                                                                       <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
-                                                               </option>
-                                                               <option id="sbi.gnu.c.compiler.option.frameworks.core.627340354" name="Tizen-Frameworks" superClass="sbi.gnu.c.compiler.option.frameworks.core" valueType="userObjs">
-                                                                       <listOptionValue builtIn="false" value="Native_API"/>
-                                                               </option>
-                                                               <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.749706957" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
-                                                       </tool>
-                                                       <tool id="org.tizen.nativeide.tool.sbi.gnu.c.linker.base.1794486202" name="C Linker" superClass="org.tizen.nativeide.tool.sbi.gnu.c.linker.base"/>
-                                                       <tool command="clang++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.linker.2579106" name="C++ Linker" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.linker">
-                                                               <option id="sbi.gnu.cpp.linker.option.frameworks_lflags.core.1582557344" name="Tizen-Frameworks-Other-Lflags" superClass="sbi.gnu.cpp.linker.option.frameworks_lflags.core" valueType="stringList">
-                                                                       <listOptionValue builtIn="false" value="${TC_LINKER_MISC}"/>
-                                                                       <listOptionValue builtIn="false" value="${RS_LINKER_MISC}"/>
-                                                                       <listOptionValue builtIn="false" value="-pie -lpthread "/>
-                                                                       <listOptionValue builtIn="false" value="-Xlinker -rpath=&quot;/home/developer/sdk_tools/lib&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="-Xlinker --version-script=${PROJ_PATH}/.exportMap"/>
-                                                                       <listOptionValue builtIn="false" value="-L&quot;${SBI_SYSROOT}/usr/lib&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="$(RS_LIBRARIES)"/>
-                                                               </option>
-                                                               <option id="gnu.cpp.link.option.paths.1396123174" name="Library search path (-L)" superClass="gnu.cpp.link.option.paths" valueType="libPaths">
-                                                                       <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/lib}&quot;"/>
-                                                               </option>
-                                                               <inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.768667264" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
-                                                                       <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
-                                                                       <additionalInput kind="additionalinput" paths="$(LIBS)"/>
-                                                               </inputType>
-                                                       </tool>
-                                                       <tool command="i386-linux-gnueabi-as.exe" id="org.tizen.nativeapp.tool.sbi.gnu.assembler.base.380499784" name="Assembler" superClass="org.tizen.nativeapp.tool.sbi.gnu.assembler.base">
-                                                               <inputType id="cdt.managedbuild.tool.gnu.assembler.input.1638213209" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
-                                                       </tool>
-                                                       <tool id="org.tizen.nativecore.tool.fnmapgen.1617359663" name="C FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen"/>
-                                                       <tool id="org.tizen.nativecore.tool.fnmapgen.cpp.759297757" name="C++ FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen.cpp"/>
-                                                       <tool id="org.tizen.nativecore.tool.ast.495578509" name="C Static Analyzer" superClass="org.tizen.nativecore.tool.ast"/>
-                                                       <tool id="org.tizen.nativecore.tool.ast.cpp.91235808" name="C++ Static Analyzer" superClass="org.tizen.nativecore.tool.ast.cpp"/>
-                                                       <tool id="org.tizen.nativecore.tool.sbi.po.compiler.619869321" name="PO Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.po.compiler"/>
-                                                       <tool id="org.tizen.nativecore.tool.sbi.edc.compiler.1045552473" name="EDC Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.edc.compiler"/>
-                                               </toolChain>
-                                       </folderInfo>
-                                       <sourceEntries>
-                                               <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="inc"/>
-                                               <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="res"/>
-                                               <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
-                                       </sourceEntries>
-                               </configuration>
-                       </storageModule>
-                       <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
-               </cconfiguration>
-       </storageModule>
-       <storageModule moduleId="cdtBuildSystem" version="4.0.0">
-               <project id="TMSampleApp.org.tizen.nativecore.target.sbi.gcc45.app.278712545" name="Tizen Native Application" projectType="org.tizen.nativecore.target.sbi.gcc45.app"/>
-       </storageModule>
-       <storageModule moduleId="scannerConfiguration">
-               <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
-               <scannerConfigBuildInfo instanceId="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396">
-                       <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
-               </scannerConfigBuildInfo>
-               <scannerConfigBuildInfo instanceId="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109">
-                       <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
-               </scannerConfigBuildInfo>
-       </storageModule>
-       <storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
-       <storageModule moduleId="refreshScope" versionNumber="2">
-               <configuration configurationName="Debug">
-                       <resource resourceType="PROJECT" workspacePath="/TMSampleApp"/>
-               </configuration>
-               <configuration configurationName="Release">
-                       <resource resourceType="PROJECT" workspacePath="/TMSampleApp"/>
-               </configuration>
-       </storageModule>
-       <storageModule moduleId="com.samsung.tizen.nativeapp.projectInfo" version="1.0.0"/>
+     <storageModule moduleId="org.eclipse.cdt.core.settings">
+          <cconfiguration id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109">
+               <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109" moduleId="org.eclipse.cdt.core.settings" name="Debug">
+                    <externalSettings/>
+                    <extensions>
+                         <extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
+                         <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                         <extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                         <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                         <extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                         <extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
+                         <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    </extensions>
+               </storageModule>
+               <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+                    <configuration artifactName="resampleclient" buildArtefactType="org.tizen.nativecore.buildArtefactType.app" buildProperties="org.eclipse.cdt.build.core.buildArtefactType=org.tizen.nativecore.buildArtefactType.app,org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.debug" description="" errorParsers="org.eclipse.cdt.core.MakeErrorParser;org.eclipse.cdt.core.GCCErrorParser;" id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109" name="Debug" parent="org.tizen.nativecore.config.sbi.gcc45.app.debug">
+                         <folderInfo id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109." name="/" resourcePath="">
+                              <toolChain id="org.tizen.nativecore.toolchain.sbi.gcc45.app.debug.266200202" name="Tizen Native Toolchain" superClass="org.tizen.nativecore.toolchain.sbi.gcc45.app.debug">
+                                   <targetPlatform binaryParser="org.eclipse.cdt.core.ELF" id="org.tizen.nativeide.target.sbi.gnu.platform.base.1788661429" osList="linux,win32" superClass="org.tizen.nativeide.target.sbi.gnu.platform.base"/>
+                                   <builder arguments="--eval=&quot;SHELL=cmd&quot; -r" autoBuildTarget="all" buildPath="${workspace_loc:/TMSampleApp}/Debug" enableAutoBuild="true" id="org.tizen.nativecore.target.sbi.gnu.builder.1749302123" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Tizen Application Builder" superClass="org.tizen.nativecore.target.sbi.gnu.builder"/>
+                                   <tool id="org.tizen.nativecore.tool.sbi.gnu.archiver.345678603" name="Archiver" superClass="org.tizen.nativecore.tool.sbi.gnu.archiver"/>
+                                   <tool command="arm-linux-gnueabi-g++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler.1794187316" name="C++ Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler">
+                                        <option id="gnu.cpp.compiler.option.optimization.level.719656926" name="Optimization Level" superClass="gnu.cpp.compiler.option.optimization.level" useByScannerDiscovery="false" value="gnu.cpp.compiler.optimization.level.none" valueType="enumerated"/>
+                                        <option id="sbi.gnu.cpp.compiler.option.debugging.level.core.378028433" name="Debug level" superClass="sbi.gnu.cpp.compiler.option.debugging.level.core" useByScannerDiscovery="false" value="gnu.cpp.compiler.debugging.level.max" valueType="enumerated"/>
+                                        <option id="sbi.gnu.cpp.compiler.option.831567474" name="Tizen-Target" superClass="sbi.gnu.cpp.compiler.option" useByScannerDiscovery="false" valueType="userObjs">
+                                             <listOptionValue builtIn="false" value="mobile-2.3-device.core_gcc46.armel.core.app"/>
+                                        </option>
+                                        <option id="sbi.gnu.cpp.compiler.option.frameworks_inc.core.1543030783" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.cpp.compiler.option.frameworks_inc.core" useByScannerDiscovery="false" valueType="includePath">
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
+                                        </option>
+                                        <option id="sbi.gnu.cpp.compiler.option.frameworks_cflags.core.1612037830" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.cpp.compiler.option.frameworks_cflags.core" useByScannerDiscovery="false" valueType="stringList">
+                                             <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+                                             <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+                                             <listOptionValue builtIn="false" value=" -fPIE"/>
+                                             <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                             <listOptionValue builtIn="false" value="-mthumb"/>
+                                        </option>
+                                        <option id="gnu.cpp.compiler.option.include.paths.1501991974" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" useByScannerDiscovery="false" valueType="includePath">
+                                             <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;..\..\..\..\src\resourceBroker\include&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;..\..\..\..\src\resourceCache\include&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;..\..\..\..\src\common\utils\include&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;..\..\..\..\src\common\expiryTimer\include&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;..\..\..\..\src\common\expiryTimer\src&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;..\..\..\..\src\common\primitiveResource\include&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;..\..\..\..\include&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\include&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\c_common&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\stack\include&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\logger\include&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\occoap\include&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\ocrandom\include&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\ocsocket\include&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\oc_logger\include&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\extlibs\timer&quot;"/>
+                                        </option>
+                                        <option id="sbi.gnu.cpp.compiler.option.frameworks.core.1095600730" name="Tizen-Frameworks" superClass="sbi.gnu.cpp.compiler.option.frameworks.core" useByScannerDiscovery="false" valueType="userObjs">
+                                             <listOptionValue builtIn="false" value="Native_API"/>
+                                        </option>
+                                        <option id="gnu.cpp.compiler.option.preprocessor.def.371963530" name="Defined symbols (-D)" superClass="gnu.cpp.compiler.option.preprocessor.def" useByScannerDiscovery="false" valueType="definedSymbols">
+                                             <listOptionValue builtIn="false" value="_DEBUG"/>
+                                        </option>
+                                        <option id="gnu.cpp.compiler.option.dialect.std.1929207991" name="Language standard" superClass="gnu.cpp.compiler.option.dialect.std" value="gnu.cpp.compiler.dialect.default" valueType="enumerated"/>
+                                        <option id="sbi.gnu.cpp.compiler.option.misc.pic.core.755649926" name="-fPIC option" superClass="sbi.gnu.cpp.compiler.option.misc.pic.core" value="true" valueType="boolean"/>
+                                        <option id="gnu.cpp.compiler.option.other.other.1760093561" name="Other flags" superClass="gnu.cpp.compiler.option.other.other" value="-c -fmessage-length=0 -std=c++0x" valueType="string"/>
+                                        <inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.1956958926" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
+                                   </tool>
+                                   <tool command="arm-linux-gnueabi-gcc.exe" id="org.tizen.nativecore.tool.sbi.gnu.c.compiler.2072036030" name="C Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.c.compiler">
+                                        <option defaultValue="gnu.c.optimization.level.none" id="gnu.c.compiler.option.optimization.level.1042898971" name="Optimization Level" superClass="gnu.c.compiler.option.optimization.level" useByScannerDiscovery="false" valueType="enumerated"/>
+                                        <option id="sbi.gnu.c.compiler.option.debugging.level.core.135607770" name="Debug level" superClass="sbi.gnu.c.compiler.option.debugging.level.core" useByScannerDiscovery="false" value="gnu.c.debugging.level.max" valueType="enumerated"/>
+                                        <option id="sbi.gnu.c.compiler.option.571493571" name="Tizen-Target" superClass="sbi.gnu.c.compiler.option" useByScannerDiscovery="false" valueType="userObjs">
+                                             <listOptionValue builtIn="false" value="mobile-2.3-device.core_gcc46.armel.core.app"/>
+                                        </option>
+                                        <option id="sbi.gnu.c.compiler.option.frameworks_inc.core.107632308" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.c.compiler.option.frameworks_inc.core" useByScannerDiscovery="false" valueType="includePath">
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
+                                        </option>
+                                        <option id="sbi.gnu.c.compiler.option.frameworks_cflags.core.1275911900" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.c.compiler.option.frameworks_cflags.core" useByScannerDiscovery="false" valueType="stringList">
+                                             <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+                                             <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+                                             <listOptionValue builtIn="false" value=" -fPIE"/>
+                                             <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                             <listOptionValue builtIn="false" value="-mthumb"/>
+                                        </option>
+                                        <option id="gnu.c.compiler.option.include.paths.109116980" name="Include paths (-I)" superClass="gnu.c.compiler.option.include.paths" useByScannerDiscovery="false" valueType="includePath">
+                                             <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
+                                        </option>
+                                        <option id="sbi.gnu.c.compiler.option.frameworks.core.1552601669" name="Tizen-Frameworks" superClass="sbi.gnu.c.compiler.option.frameworks.core" useByScannerDiscovery="false" valueType="userObjs">
+                                             <listOptionValue builtIn="false" value="Native_API"/>
+                                        </option>
+                                        <option id="gnu.c.compiler.option.preprocessor.def.symbols.2021130927" name="Defined symbols (-D)" superClass="gnu.c.compiler.option.preprocessor.def.symbols" useByScannerDiscovery="false" valueType="definedSymbols">
+                                             <listOptionValue builtIn="false" value="_DEBUG"/>
+                                        </option>
+                                        <option id="sbi.gnu.c.compiler.option.misc.pic.core.1304419386" name="-fPIC option" superClass="sbi.gnu.c.compiler.option.misc.pic.core" value="false" valueType="boolean"/>
+                                        <option id="gnu.c.compiler.option.misc.other.2029079564" name="Other flags" superClass="gnu.c.compiler.option.misc.other" value="-c -fmessage-length=0 -std=c++0x" valueType="string"/>
+                                        <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.1859092644" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
+                                   </tool>
+                                   <tool id="org.tizen.nativeide.tool.sbi.gnu.c.linker.base.944066372" name="C Linker" superClass="org.tizen.nativeide.tool.sbi.gnu.c.linker.base"/>
+                                   <tool command="arm-linux-gnueabi-g++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.linker.1667264058" name="C++ Linker" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.linker">
+                                        <option id="sbi.gnu.cpp.linker.option.frameworks_lflags.core.1178784315" name="Tizen-Frameworks-Other-Lflags" superClass="sbi.gnu.cpp.linker.option.frameworks_lflags.core" valueType="stringList">
+                                             <listOptionValue builtIn="false" value="${TC_LINKER_MISC}"/>
+                                             <listOptionValue builtIn="false" value="${RS_LINKER_MISC}"/>
+                                             <listOptionValue builtIn="false" value="-pie -lpthread "/>
+                                             <listOptionValue builtIn="false" value="-Xlinker -rpath=&quot;/home/developer/sdk_tools/lib&quot;"/>
+                                             <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                             <listOptionValue builtIn="false" value="-Xlinker --version-script=${PROJ_PATH}/.exportMap"/>
+                                             <listOptionValue builtIn="false" value="-L&quot;${SBI_SYSROOT}/usr/lib&quot;"/>
+                                             <listOptionValue builtIn="false" value="$(RS_LIBRARIES)"/>
+                                        </option>
+                                        <option id="gnu.cpp.link.option.paths.1087248355" name="Library search path (-L)" superClass="gnu.cpp.link.option.paths" valueType="libPaths">
+                                             <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/lib}&quot;"/>
+                                        </option>
+                                        <option id="gnu.cpp.link.option.libs.2039500142" name="Libraries (-l)" superClass="gnu.cpp.link.option.libs" valueType="libs">
+                                             <listOptionValue builtIn="false" value="oc"/>
+                                             <listOptionValue builtIn="false" value="octbstack"/>
+                                             <listOptionValue builtIn="false" value="oc_logger"/>
+                                             <listOptionValue builtIn="false" value="oc_logger_core"/>
+                                             <listOptionValue builtIn="false" value="connectivity_abstraction"/>
+                                             <listOptionValue builtIn="false" value="uuid"/>
+                                             <listOptionValue builtIn="false" value="boost_date_time"/>
+                                             <listOptionValue builtIn="false" value="boost_system"/>
+                                             <listOptionValue builtIn="false" value="boost_thread"/>
+                                             <listOptionValue builtIn="false" value="rcs_client"/>
+                                             <listOptionValue builtIn="false" value="rcs_common"/>
+                                             <listOptionValue builtIn="false" value="rcs_server"/>
+                                        </option>
+                                        <inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.618645708" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
+                                             <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
+                                             <additionalInput kind="additionalinput" paths="$(LIBS)"/>
+                                        </inputType>
+                                   </tool>
+                                   <tool command="arm-linux-gnueabi-as.exe" id="org.tizen.nativeapp.tool.sbi.gnu.assembler.base.1585687908" name="Assembler" superClass="org.tizen.nativeapp.tool.sbi.gnu.assembler.base">
+                                        <inputType id="cdt.managedbuild.tool.gnu.assembler.input.89256350" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
+                                   </tool>
+                                   <tool id="org.tizen.nativecore.tool.fnmapgen.353447784" name="C FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen"/>
+                                   <tool id="org.tizen.nativecore.tool.fnmapgen.cpp.734608698" name="C++ FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen.cpp"/>
+                                   <tool id="org.tizen.nativecore.tool.ast.125567506" name="C Static Analyzer" superClass="org.tizen.nativecore.tool.ast"/>
+                                   <tool id="org.tizen.nativecore.tool.ast.cpp.2107204356" name="C++ Static Analyzer" superClass="org.tizen.nativecore.tool.ast.cpp"/>
+                                   <tool id="org.tizen.nativecore.tool.sbi.po.compiler.1190161351" name="PO Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.po.compiler"/>
+                                   <tool id="org.tizen.nativecore.tool.sbi.edc.compiler.1621384631" name="EDC Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.edc.compiler"/>
+                              </toolChain>
+                         </folderInfo>
+                         <sourceEntries>
+                              <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="inc"/>
+                              <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="res"/>
+                              <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
+                         </sourceEntries>
+                    </configuration>
+               </storageModule>
+               <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
+          </cconfiguration>
+          <cconfiguration id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396">
+               <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396" moduleId="org.eclipse.cdt.core.settings" name="Release">
+                    <externalSettings/>
+                    <extensions>
+                         <extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
+                         <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                         <extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                         <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                         <extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                         <extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
+                         <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    </extensions>
+               </storageModule>
+               <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+                    <configuration artifactName="tmsampleapp" buildArtefactType="org.tizen.nativecore.buildArtefactType.app" buildProperties="org.eclipse.cdt.build.core.buildArtefactType=org.tizen.nativecore.buildArtefactType.app,org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.release" description="" errorParsers="org.eclipse.cdt.core.MakeErrorParser;org.eclipse.cdt.core.GCCErrorParser;" id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396" name="Release" parent="org.tizen.nativecore.config.sbi.gcc45.app.release">
+                         <folderInfo id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396." name="/" resourcePath="">
+                              <toolChain id="org.tizen.nativecore.toolchain.sbi.gcc45.app.release.32000863" name="Tizen Native Toolchain" superClass="org.tizen.nativecore.toolchain.sbi.gcc45.app.release">
+                                   <targetPlatform binaryParser="org.eclipse.cdt.core.ELF" id="org.tizen.nativeide.target.sbi.gnu.platform.base.1750758769" osList="linux,win32" superClass="org.tizen.nativeide.target.sbi.gnu.platform.base"/>
+                                   <builder buildPath="${workspace_loc:/TMSampleApp}/Release" id="org.tizen.nativecore.target.sbi.gnu.builder.2029564551" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Tizen Application Builder" superClass="org.tizen.nativecore.target.sbi.gnu.builder"/>
+                                   <tool id="org.tizen.nativecore.tool.sbi.gnu.archiver.224082468" name="Archiver" superClass="org.tizen.nativecore.tool.sbi.gnu.archiver"/>
+                                   <tool command="clang++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler.1434486618" name="C++ Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler">
+                                        <option id="gnu.cpp.compiler.option.optimization.level.1709393206" name="Optimization Level" superClass="gnu.cpp.compiler.option.optimization.level" value="gnu.cpp.compiler.optimization.level.most" valueType="enumerated"/>
+                                        <option id="sbi.gnu.cpp.compiler.option.debugging.level.core.221700213" name="Debug level" superClass="sbi.gnu.cpp.compiler.option.debugging.level.core"/>
+                                        <option id="sbi.gnu.cpp.compiler.option.710876023" name="Tizen-Target" superClass="sbi.gnu.cpp.compiler.option" valueType="userObjs">
+                                             <listOptionValue builtIn="false" value="mobile-2.3-emulator.core_llvm34.i386.core.app"/>
+                                        </option>
+                                        <option id="sbi.gnu.cpp.compiler.option.frameworks_inc.core.1622581330" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.cpp.compiler.option.frameworks_inc.core" valueType="includePath">
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
+                                        </option>
+                                        <option id="sbi.gnu.cpp.compiler.option.frameworks_cflags.core.1695583788" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.cpp.compiler.option.frameworks_cflags.core" valueType="stringList">
+                                             <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+                                             <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+                                             <listOptionValue builtIn="false" value=" -fPIE"/>
+                                             <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                        </option>
+                                        <option id="gnu.cpp.compiler.option.include.paths.585301879" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" valueType="includePath">
+                                             <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
+                                        </option>
+                                        <option id="sbi.gnu.cpp.compiler.option.frameworks.core.708669314" name="Tizen-Frameworks" superClass="sbi.gnu.cpp.compiler.option.frameworks.core" valueType="userObjs">
+                                             <listOptionValue builtIn="false" value="Native_API"/>
+                                        </option>
+                                        <inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.2006056090" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
+                                   </tool>
+                                   <tool command="clang.exe" id="org.tizen.nativecore.tool.sbi.gnu.c.compiler.601285388" name="C Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.c.compiler">
+                                        <option defaultValue="gnu.c.optimization.level.most" id="gnu.c.compiler.option.optimization.level.1778561828" name="Optimization Level" superClass="gnu.c.compiler.option.optimization.level" valueType="enumerated"/>
+                                        <option id="sbi.gnu.c.compiler.option.debugging.level.core.1695949408" name="Debug level" superClass="sbi.gnu.c.compiler.option.debugging.level.core"/>
+                                        <option id="sbi.gnu.c.compiler.option.1422818783" name="Tizen-Target" superClass="sbi.gnu.c.compiler.option" valueType="userObjs">
+                                             <listOptionValue builtIn="false" value="mobile-2.3-emulator.core_llvm34.i386.core.app"/>
+                                        </option>
+                                        <option id="sbi.gnu.c.compiler.option.frameworks_inc.core.1871683675" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.c.compiler.option.frameworks_inc.core" valueType="includePath">
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
+                                             <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
+                                        </option>
+                                        <option id="sbi.gnu.c.compiler.option.frameworks_cflags.core.371848582" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.c.compiler.option.frameworks_cflags.core" valueType="stringList">
+                                             <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+                                             <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+                                             <listOptionValue builtIn="false" value=" -fPIE"/>
+                                             <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                        </option>
+                                        <option id="gnu.c.compiler.option.include.paths.1254567673" name="Include paths (-I)" superClass="gnu.c.compiler.option.include.paths" valueType="includePath">
+                                             <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
+                                        </option>
+                                        <option id="sbi.gnu.c.compiler.option.frameworks.core.627340354" name="Tizen-Frameworks" superClass="sbi.gnu.c.compiler.option.frameworks.core" valueType="userObjs">
+                                             <listOptionValue builtIn="false" value="Native_API"/>
+                                        </option>
+                                        <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.749706957" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
+                                   </tool>
+                                   <tool id="org.tizen.nativeide.tool.sbi.gnu.c.linker.base.1794486202" name="C Linker" superClass="org.tizen.nativeide.tool.sbi.gnu.c.linker.base"/>
+                                   <tool command="clang++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.linker.2579106" name="C++ Linker" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.linker">
+                                        <option id="sbi.gnu.cpp.linker.option.frameworks_lflags.core.1582557344" name="Tizen-Frameworks-Other-Lflags" superClass="sbi.gnu.cpp.linker.option.frameworks_lflags.core" valueType="stringList">
+                                             <listOptionValue builtIn="false" value="${TC_LINKER_MISC}"/>
+                                             <listOptionValue builtIn="false" value="${RS_LINKER_MISC}"/>
+                                             <listOptionValue builtIn="false" value="-pie -lpthread "/>
+                                             <listOptionValue builtIn="false" value="-Xlinker -rpath=&quot;/home/developer/sdk_tools/lib&quot;"/>
+                                             <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                             <listOptionValue builtIn="false" value="-Xlinker --version-script=${PROJ_PATH}/.exportMap"/>
+                                             <listOptionValue builtIn="false" value="-L&quot;${SBI_SYSROOT}/usr/lib&quot;"/>
+                                             <listOptionValue builtIn="false" value="$(RS_LIBRARIES)"/>
+                                        </option>
+                                        <option id="gnu.cpp.link.option.paths.1396123174" name="Library search path (-L)" superClass="gnu.cpp.link.option.paths" valueType="libPaths">
+                                             <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/lib}&quot;"/>
+                                        </option>
+                                        <inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.768667264" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
+                                             <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
+                                             <additionalInput kind="additionalinput" paths="$(LIBS)"/>
+                                        </inputType>
+                                   </tool>
+                                   <tool command="i386-linux-gnueabi-as.exe" id="org.tizen.nativeapp.tool.sbi.gnu.assembler.base.380499784" name="Assembler" superClass="org.tizen.nativeapp.tool.sbi.gnu.assembler.base">
+                                        <inputType id="cdt.managedbuild.tool.gnu.assembler.input.1638213209" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
+                                   </tool>
+                                   <tool id="org.tizen.nativecore.tool.fnmapgen.1617359663" name="C FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen"/>
+                                   <tool id="org.tizen.nativecore.tool.fnmapgen.cpp.759297757" name="C++ FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen.cpp"/>
+                                   <tool id="org.tizen.nativecore.tool.ast.495578509" name="C Static Analyzer" superClass="org.tizen.nativecore.tool.ast"/>
+                                   <tool id="org.tizen.nativecore.tool.ast.cpp.91235808" name="C++ Static Analyzer" superClass="org.tizen.nativecore.tool.ast.cpp"/>
+                                   <tool id="org.tizen.nativecore.tool.sbi.po.compiler.619869321" name="PO Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.po.compiler"/>
+                                   <tool id="org.tizen.nativecore.tool.sbi.edc.compiler.1045552473" name="EDC Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.edc.compiler"/>
+                              </toolChain>
+                         </folderInfo>
+                         <sourceEntries>
+                              <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="inc"/>
+                              <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="res"/>
+                              <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
+                         </sourceEntries>
+                    </configuration>
+               </storageModule>
+               <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
+          </cconfiguration>
+     </storageModule>
+     <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+          <project id="TMSampleApp.org.tizen.nativecore.target.sbi.gcc45.app.278712545" name="Tizen Native Application" projectType="org.tizen.nativecore.target.sbi.gcc45.app"/>
+     </storageModule>
+     <storageModule moduleId="scannerConfiguration">
+          <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+          <scannerConfigBuildInfo instanceId="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396">
+               <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+          </scannerConfigBuildInfo>
+          <scannerConfigBuildInfo instanceId="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109">
+               <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+          </scannerConfigBuildInfo>
+     </storageModule>
+     <storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
+     <storageModule moduleId="refreshScope" versionNumber="2">
+          <configuration configurationName="Debug">
+               <resource resourceType="PROJECT" workspacePath="/TMSampleApp"/>
+          </configuration>
+          <configuration configurationName="Release">
+               <resource resourceType="PROJECT" workspacePath="/TMSampleApp"/>
+          </configuration>
+     </storageModule>
+     <storageModule moduleId="com.samsung.tizen.nativeapp.projectInfo" version="1.0.0"/>
 </cproject>
index 8761e1d..07aa7ed 100644 (file)
@@ -538,27 +538,69 @@ popup_set_clicked_cb(void *data, Evas_Object *obj, void *event_info)
     const char *attributeString = elm_entry_entry_get(entry);
     // Remove white spaces(if any) at the beginning
     int beginning = 0;
+    int negative = 0;
+    int invalidFlag = 0;
+
     while (attributeString[beginning] == ' ')
     {
         (beginning)++;
     }
 
     int len = strlen(attributeString);
-    if (NULL == attributeString || 1 > len)
+
+    if((len >= 1) && ( '-' == attributeString[0]))
+    {
+        negative = 1;
+    }
+
+    if(((len > 3) && negative) || (len > 2 && (!negative)) || (len==1 && negative))
     {
-        dlog_print(DLOG_INFO, LOG_TAG, "#### Read NULL attribute Value");
-        string logMessage = g_attributeKey + " Cannot be NULL<br>";
+        invalidFlag = 1;
+        dlog_print(DLOG_INFO, LOG_TAG, "#### Not in allowed Range [-99 to 99]");
+        string logMessage = g_attributeKey + " Not in allowed Range [-99 to 99]<br>";
         logMessage += "----------------------<br>";
         dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
-        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog, &logMessage);
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
+                                                            &logMessage);
     }
     else
     {
+        if (NULL == attributeString || 1 > len)
+        {
+            invalidFlag = 1;
+            dlog_print(DLOG_INFO, LOG_TAG, "#### Read NULL attribute Value");
+            string logMessage = g_attributeKey + " Cannot be NULL<br>";
+            logMessage += "----------------------<br>";
+            dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
+            ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
+                                                             &logMessage);
+        }
+        else
+        {
+            int i = 0;
+            while(i < len)
+            {
+                if(attributeString[i] < '0' || attributeString[i] > '9')
+                {
+                    invalidFlag = 1;
+                    dlog_print(DLOG_INFO, LOG_TAG, "#### Read invalid attribute Value");
+                    string logMessage = g_attributeKey + " Invalid charaters in input<br>";
+                    logMessage += "----------------------<br>";
+                    dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
+                    ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
+                                                              &logMessage);
+                }
+                i++;
+            }
+        }
+    }
+
+    if(invalidFlag != 1)
+    {
         int attributeValue = atoi(attributeString);
         string attrString(attributeString);
         setAttributeToRemoteServer(attributeValue);
         dlog_print(DLOG_INFO, LOG_TAG, "#### Attribute to set : %d", attributeValue);
-
         string logMessage = g_attributeKey + " to set : " + attrString + "<br>";
         logMessage += "----------------------<br>";
         dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
index 29fc919..c368e55 100644 (file)
  *
  */
 
-#ifndef RCSDISCOVERYMANAGER_H
-#define RCSDISCOVERYMANAGER_H
+#ifndef RCS_DISCOVERYMANAGER_H_
+#define RCS_DISCOVERYMANAGER_H_
 
 #include <memory>
 #include <functional>
+#include <vector>
 
 namespace OIC
 {
     namespace Service
     {
-        class RCSRemoteResourceObject;
         class RCSAddress;
-
+        class RCSRemoteResourceObject;
         /**
          * This class contains the resource discovery methods.
          *
@@ -46,143 +46,171 @@ namespace OIC
          */
         class RCSDiscoveryManager
         {
-            public:
+        public:
 
             /**
              * This class represents a discovery task.
              *
-             * @note A discovery task will be automatically canceled when destroyed.
              */
-                class DiscoveryTask
-                {
-                    public:
-                        typedef std::unique_ptr<DiscoveryTask> Ptr;
+            class DiscoveryTask
+            {
+            public:
+                typedef std::unique_ptr< DiscoveryTask > Ptr;
 
-                        ~DiscoveryTask();
+                ~DiscoveryTask();
 
-                        DiscoveryTask(const DiscoveryTask&) = delete;
-                        DiscoveryTask(DiscoveryTask&&) = delete;
-                        DiscoveryTask& operator = (const DiscoveryTask&) const = delete;
-                        DiscoveryTask& operator = (DiscoveryTask&&) const = delete;
+                DiscoveryTask(const DiscoveryTask&) = delete;
+                DiscoveryTask(DiscoveryTask&&) = delete;
+                DiscoveryTask& operator =(const DiscoveryTask&) const = delete;
+                DiscoveryTask& operator =(DiscoveryTask&&) const = delete;
 
-                        /**
-                         * Cancel the task for discovery request. If cancel is called in duplicate, the request is ignored.
-                         */
-                        void cancel();
+                /**
+                 * It cancels the task of discovery.
+                 * If it is already canceled, the operation is ignored.
+                 */
+                void cancel();
 
-                        /**
-                         * Return a boolean value whether the discovery request is canceled or not.
-                         */
-                        bool isCanceled();
+                /**
+                 * Returns whether the discovery request is canceled or not.
+                 */
+                bool isCanceled();
 
-                    private:
-                        explicit DiscoveryTask(unsigned int);
+            private:
+                explicit DiscoveryTask(unsigned int);
 
-                    private:
-                        unsigned int m_id;
-                        friend class RCSDiscoveryManagerImpl;
-                };
+            private:
+                unsigned int m_id;
 
-            public:
+                friend class RCSDiscoveryManagerImpl;
+            };
 
-                /**
-                 * Typedef for callback of discoverResource APIs
-                 *
-                 * @see discoverResource
-                 */
-                typedef std::function< void(std::shared_ptr< RCSRemoteResourceObject >) >
-                                       ResourceDiscoveredCallback;
+        public:
 
-                /**
-                 * @return RCSDiscoveryManager instance.
-                 *
-                 */
-                static RCSDiscoveryManager* getInstance();
+            /**
+             * Typedef for callback of discoverResource APIs
+             *
+             * @see discoverResource
+             */
+            typedef std::function< void(std::shared_ptr< RCSRemoteResourceObject >) >
+                        ResourceDiscoveredCallback;
 
-                /**
-                 * Discovering the resource of interest, regardless of uri and resource type.
-                 * Find resource matching request periodically until returned resource is disappeared or destroyed.
-                 *
-                 * @return Returned object must be received.
-                 *
-                 * @param address         A RCSAddress object
-                 * @param cb              A callback to obtain discovered resource
-                 *
-                 * @throws InvalidParameterException If cb is empty.
-                 *
-                 * @note The callback will be invoked in an internal thread.
-                 *
-                 */
-                DiscoveryTask::Ptr discoverResource(const RCSAddress& address,
-                        ResourceDiscoveredCallback cb);
+            /**
+             * @return RCSDiscoveryManager instance.
+             *
+             */
+            static RCSDiscoveryManager* getInstance();
 
-                /**
-                 * Discovering the resource of Interest, regardless of resource type.
-                 * Find resource matching request periodically until returned resource is disappeared or destroyed.
-                 *
-                 * @return Returned object must be received.
-                 *
-                 * @param address          A RCSAddress object
-                 * @param relativeURI      The relative uri of resource to be searched
-                 * @param cb               A callback to obtain discovered resource
-                 *
-                 * @throws InvalidParameterException If cb is empty.
-                 *
-                 * @note The callback will be invoked in an internal thread.
-                 *
-                 * @see RCSAddress
-                 *
-                 */
-                DiscoveryTask::Ptr discoverResource(const RCSAddress& address,
-                        const std::string& relativeURI, ResourceDiscoveredCallback cb);
+            /**
+             * Discovers resources of interest, regardless of uri and resource type.
+             * It will consistently discover resources until the discovery task is canceled.
+             *
+             * @param address         A RCSAddress object
+             * @param cb              A callback to obtain discovered resource
+             *
+             * @throws InvalidParameterException If cb is empty.
+             *
+             * @note The callback will be invoked in an internal thread.
+             *
+             */
+            DiscoveryTask::Ptr discoverResource(const RCSAddress& address,
+                    ResourceDiscoveredCallback cb);
 
-                /**
-                 * Discovering the resource of Interest by Resource type.
-                 * Find resource matching request periodically until returned resource is disappeared or destroyed.
-                 *
-                 * @return Returned object must be received.
-                 *
-                 * @param address          A RCSAddress object
-                 * @param resourceType     Resource Type
-                 * @param cb               A callback to obtain discovered resource
-                 *
-                 * @throws InvalidParameterException If cb is empty.
-                 *
-                 * @note The callback will be invoked in an internal thread.
-                 *
-                 * @see RCSAddress
-                 *
-                 */
-                DiscoveryTask::Ptr discoverResourceByType(const RCSAddress& address,
-                        const std::string& resourceType, ResourceDiscoveredCallback cb);
+            /**
+             * Discovers resources of interest, regardless of resource type.
+             * It will consistently discover resources until the discovery task is canceled.
+             *
+             * @param address          A RCSAddress object
+             * @param relativeUri      The relative uri of resource to be searched
+             * @param cb               A callback to obtain discovered resource
+             *
+             * @throws InvalidParameterException If cb is empty.
+             *
+             * @note The callback will be invoked in an internal thread.
+             *
+             */
+            DiscoveryTask::Ptr discoverResource(const RCSAddress& address,
+                    const std::string& relativeUri, ResourceDiscoveredCallback cb);
 
-                /**
-                 * Discovering the resource of Interest by Resource type with provided relativeURI.
-                 * Find resource matching request periodically until returned resource is disappeared or destroyed.
-                 *
-                 * @return Returned object must be received.
-                 *
-                 * @param address          A RCSAddress object
-                 * @param relativeURI      The relative uri of resource to be searched
-                 * @param resourceType     Resource Type
-                 * @param cb               A callback to obtain discovered resource
-                 *
-                 * @throws InvalidParameterException If cb is empty.
-                 *
-                 * @note The callback will be invoked in an internal thread.
-                 *
-                 * @see RCSAddress
-                 *
-                 */
-                DiscoveryTask::Ptr discoverResourceByType(const RCSAddress& address,
-                        const std::string& relativeURI, const std::string& resourceType,
-                        ResourceDiscoveredCallback cb);
+            /**
+             * Discovers resources of interest by resource type.
+             * It will consistently discover resources until the discovery task is canceled.
+             *
+             * @param address          A RCSAddress object
+             * @param resourceType     Resource Type
+             * @param cb               A callback to obtain discovered resource
+             *
+             * @throws InvalidParameterException If cb is empty.
+             *
+             * @note The callback will be invoked in an internal thread.
+             *
+             */
+            DiscoveryTask::Ptr discoverResourceByType(const RCSAddress& address,
+                    const std::string& resourceType, ResourceDiscoveredCallback cb);
 
-            private:
-                RCSDiscoveryManager() = default;
-                ~RCSDiscoveryManager()= default;
+            /**
+             * Discovers resources of interest by resource types.
+             * It will consistently discover resources until the discovery task is canceled.
+             *
+             * @param address          A RCSAddress object
+             * @param resourceTypes    List of Resource Types
+             * @param cb               A callback to obtain discovered resource
+             *
+             * @throws InvalidParameterException If cb is empty.
+             * @throws RCSBadRequestException If resourceTypes contain more than one element and
+             * any of them is empty.
+             *
+             * @note The callback will be invoked in an internal thread.
+             * @note If resourceTypes is empty, discovers resource by all resource types.
+             *
+             */
+            DiscoveryTask::Ptr discoverResourceByTypes(const RCSAddress& address,
+                    const std::vector< std::string >& resourceTypes,
+                    ResourceDiscoveredCallback cb);
+
+            /**
+             * Discovers resources of interest by a resource type with provided relativeUri.
+             * It will consistently discover resources until the discovery task is canceled.
+             *
+             * @param address          A RCSAddress object
+             * @param relativeUri      The relative uri of resource to be searched
+             * @param resourceType     Resource Type
+             * @param cb               A callback to obtain discovered resource
+             *
+             * @throws InvalidParameterException If cb is empty.
+             *
+             * @note The callback will be invoked in an internal thread.
+             *
+             */
+            DiscoveryTask::Ptr discoverResourceByType(const RCSAddress& address,
+                    const std::string& relativeUri, const std::string& resourceType,
+                    ResourceDiscoveredCallback cb);
+
+            /**
+             * Discovers resources of interest by resource types with provided relativeUri.
+             * It will consistently discover resources until the discovery task is canceled.
+             *
+             * @param address          A RCSAddress object
+             * @param relativeUri      The relative uri of resource to be searched
+             * @param resourceTypes     List of Resource Types
+             * @param cb               A callback to obtain discovered resource
+             *
+             * @throws InvalidParameterException If cb is empty.
+             * @throws RCSBadRequestException If resourceTypes contain more than one element and
+             * any of them is empty.
+             *
+             * @note The callback will be invoked in an internal thread.
+             * @note If resourceTypes is empty, discovers resource by all resource types.
+             *
+             */
+            DiscoveryTask::Ptr discoverResourceByTypes(const RCSAddress& address,
+                    const std::string& relativeUri,
+                    const std::vector< std::string >& resourceTypes,
+                    ResourceDiscoveredCallback cb);
+
+        private:
 
-                friend class DiscoveryTask;
+            RCSDiscoveryManager() = default;
+            ~RCSDiscoveryManager() = default;
         };
     }
 }
index d6156d3..1ced6af 100644 (file)
@@ -45,18 +45,27 @@ namespace OIC
 
             /**
              * Constructs an exception with an empty description.
+             *
+             * @see RCSException(const std::string &)
+             * @see RCSException(std::string &&)
              */
             RCSException();
 
             /**
              * Constructs an exception with a description.
-             *
+             * @overload
              * @param what The description for the error.
+             * @see RCSException()
+             * @see RCSException(std::string &&)
              */
             explicit RCSException(const std::string &what);
 
             /**
              * @overload
+             *
+             * @param what The description for the error.
+             * @see RCSException()
+             * @see RCSException(const std::string &)
              */
             explicit RCSException(std::string &&what);
 
index bd66a2f..5a27f0a 100644 (file)
 
 #include "RCSResourceAttributes.h"
 
+namespace OC
+{
+    class OCResource;
+
+    namespace HeaderOption
+    {
+        class OCHeaderOption;
+    }
+}
+
 namespace OIC
 {
     namespace Service
     {
+
+        class RCSRepresentation;
+
+        typedef std::vector< OC::HeaderOption::OCHeaderOption > HeaderOpts;
+
         /**
          * The states of caching.
          *
@@ -69,6 +84,74 @@ namespace OIC
         class PrimitiveResource;
 
         /**
+         * This is to specify query parameters for requests to the server.
+         *
+         * @see RCSRemoteResourceObject
+         */
+        class RCSQueryParams
+        {
+        public:
+            typedef std::unordered_map< std::string, std::string > Map;
+
+        public:
+
+            /**
+             * Sets an interface of the resource to operate on
+             *
+             * @param interface interface
+             */
+            RCSQueryParams& setResourceInterface(std::string interface);
+
+            /**
+             * Sets a resource type of the resource to operate on
+             *
+             * @param type resource type
+             */
+            RCSQueryParams& setResourceType(std::string type);
+
+            /**
+             * Sets a resource type of the resource to operate on
+             *
+             * @param key key to be inserted
+             * @param value value to be inserted
+             *
+             * @note "rt" and "if" are reserved, so you should avoid them as a key.
+             *
+             */
+            RCSQueryParams& put(std::string key, std::string value);
+
+            /**
+             * Returns the resource interface.
+             */
+            std::string getResourceInterface() const;
+
+            /**
+             * Returns the resource type.
+             */
+            std::string getResourceType() const;
+
+            /**
+             * Returns a value.
+             *
+             * @param key key of the element whose mapped value is accessed.
+             *
+             * @throws InvalidKeyException If @a key doesn't match the key of any value.
+             */
+            std::string get(const std::string& key) const;
+
+            /**
+             * Returns all params.
+             */
+            const Map& getAll() const;
+
+        private:
+            std::string m_resourceInterface;
+            std::string m_resourceType;
+
+            std::unordered_map< std::string, std::string > m_map;
+        };
+
+        /**
          *
          * This represents a remote resource and provides simple ways to interact with it.
          * Basically this is a client of a remote resource that runs on other device.
@@ -112,6 +195,18 @@ namespace OIC
                 RemoteAttributesGetCallback;
 
             /**
+             * Callback definition to be invoked when the response of get is received.
+             *
+             * @param HeaderOpts
+             * @param rep the result representation
+             * @param eCode the error code received from the resource
+             *
+             * @see get
+             */
+            typedef std::function< void(const HeaderOpts& headerOpts,
+                    const RCSRepresentation& rep, int eCode) > GetCallback;
+
+            /**
              * Callback definition to be invoked when the response of setRemoteAttributes is
              * received.
              *
@@ -120,9 +215,21 @@ namespace OIC
              *
              * @see setRemoteAttributes
              */
-            typedef std::function< void(const RCSResourceAttributes&, int) >
+            typedef std::function< void(const RCSResourceAttributes& attrs, int eCode) >
                 RemoteAttributesSetCallback;
 
+            /**
+             * Callback definition to be invoked when the response of set is received.
+             *
+             * @param HeaderOpts
+             * @param rep the result representation
+             * @param eCode the error code received from the resource
+             *
+             * @see set
+             */
+            typedef std::function< void(const HeaderOpts& headerOpts,
+                    const RCSRepresentation& rep, int eCode) > SetCallback;
+
         private:
             typedef int CacheID;
             typedef unsigned int BrokerID;
@@ -135,6 +242,14 @@ namespace OIC
             ~RCSRemoteResourceObject();
 
             /**
+             * Creates an instance from an OCResource instance.
+             *
+             * @throw RCSInvalidParameterException If ocResource is nullptr.
+             */
+            static RCSRemoteResourceObject::Ptr fromOCResource(
+                    std::shared_ptr< OC::OCResource > ocResource);
+
+            /**
              * Returns whether monitoring is enabled.
              *
              * @see startMonitoring()
@@ -298,18 +413,43 @@ namespace OIC
              * Gets resource attributes directly from the server.
              *
              * This API send a get request to the resource of interest and provides
-             * the attributes to the caller in the RemoteAttributesReceivedCallback.
+             * the attributes to the caller in the RemoteAttributesGetCallback.
              *
              * @throws PlatformException If the operation failed
              * @throws InvalidParameterException If cb is an empty function or null.
              *
-             * @see RCSResourceAttributes::Value
-             *
              * @note The callback will be invoked in an internal thread.
              */
             void getRemoteAttributes(RemoteAttributesGetCallback cb);
 
             /**
+             * Gets resource representation with empty query parameters directly from the server.
+             *
+             * @param cb A callback to receive the response.
+             *
+             * @throws PlatformException If the operation failed
+             * @throws InvalidParameterException If cb is an empty function or null.
+             *
+             * @note The callback will be invoked in an internal thread.
+             */
+            void get(GetCallback cb);
+
+            /**
+             * Gets resource representation directly from the server.
+             *
+             * The response could be different by the query parameters, it depends on server.
+             *
+             * @param queryParams Query parameters
+             * @param cb A callback to receive the response.
+             *
+             * @throws PlatformException If the operation failed
+             * @throws InvalidParameterException If cb is an empty function or null.
+             *
+             * @note The callback will be invoked in an internal thread.
+             */
+            void get(const RCSQueryParams& queryParams, GetCallback cb);
+
+            /**
              * Sends a set request with resource attributes to the server.
              *
              * The SetRequest behavior depends on the server, whether updating its attributes or not.
@@ -329,6 +469,44 @@ namespace OIC
                     RemoteAttributesSetCallback cb);
 
             /**
+             * Sends a set request with resource attributes to the server.
+             *
+             * The SetRequest behavior depends on query parameters and the server.
+             *
+             * @param attributes Attributes to set
+             * @param cb A callback to receive the response.
+             *
+             * @throws PlatformException If the operation failed
+             * @throws InvalidParameterException If cb is an empty function or null.
+             *
+             * @see RCSResourceObject
+             * @see RCSResourceObject::SetRequestHandlerPolicy
+             *
+             * @note The callback will be invoked in an internal thread.
+             */
+            void set(const RCSResourceAttributes& attributes, SetCallback cb);
+
+            /**
+             * Sends a set request with resource attributes to the server.
+             *
+             * The SetRequest behavior depends on query parameters and the server.
+             *
+             * @param queryParams Query parameters
+             * @param attributes Attributes to set
+             * @param cb A callback to receive the response.
+             *
+             * @throws PlatformException If the operation failed
+             * @throws InvalidParameterException If cb is an empty function or null.
+             *
+             * @see RCSResourceObject
+             * @see RCSResourceObject::SetRequestHandlerPolicy
+             *
+             * @note The callback will be invoked in an internal thread.
+             */
+            void set(const RCSQueryParams& queryParams, const RCSResourceAttributes& attributes,
+                    SetCallback cb);
+
+            /**
              * Returns the uri of the resource.
              *
              */
diff --git a/service/resource-encapsulation/include/RCSRepresentation.h b/service/resource-encapsulation/include/RCSRepresentation.h
new file mode 100644 (file)
index 0000000..bd17166
--- /dev/null
@@ -0,0 +1,176 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef RES_ENCAPSULATION_RCSREPRESENTATION_H_
+#define RES_ENCAPSULATION_RCSREPRESENTATION_H_
+
+#include "RCSResourceAttributes.h"
+
+namespace OC
+{
+    class OCRepresentation;
+}
+
+namespace OIC
+{
+    namespace Service
+    {
+
+        /**
+         * This class describes a resource representation.
+         *
+         * @see RCSResourceObject
+         * @see RCRemoteResourceObject
+         */
+        class RCSRepresentation
+        {
+        public:
+            RCSRepresentation();
+
+            explicit RCSRepresentation(const std::string& uri);
+            explicit RCSRepresentation(const RCSResourceAttributes& attrs);
+
+            RCSRepresentation(const std::string& uri, const std::vector< std::string >& interfaces,
+                    const std::vector< std::string >& resourceTypes);
+
+            RCSRepresentation(const std::string& uri, const std::vector< std::string >& interfaces,
+                    const std::vector< std::string >& resourceTypes,
+                    const RCSResourceAttributes& attrs);
+
+            /**
+             * Returns the uri.
+             */
+            std::string getUri() const;
+
+            /**
+             * Sets the uri of this representation.
+             */
+            void setUri(std::string uri);
+
+            /**
+             * Returns all interfaces added.
+             */
+            const std::vector< std::string >& getInterfaces() const;
+
+            /**
+             * Adds an interface.
+             *
+             * @param interface an interface to add
+             */
+            void addInterface(std::string interface);
+
+            /**
+             * Removes all interfaces added.
+             */
+            void clearInterfaces();
+
+            /**
+             * Returns all resource types added.
+             */
+            const std::vector< std::string >& getResourceTypes() const;
+
+
+            /**
+             * Adds a resource type.
+             */
+            void addResourceType(std::string resourceType);
+
+            /**
+             * Removes all resource types.
+             */
+            void clearResourceTypes();
+
+            /**
+             * Returns attributes set in this representation.
+             */
+            const RCSResourceAttributes& getAttributes() const;
+
+            /**
+             * @overload
+             */
+            RCSResourceAttributes& getAttributes();
+
+            /**
+             * Overwrite attributes.
+             *
+             * @param attrs new attributes.
+             */
+            void setAttributes(const RCSResourceAttributes& attrs);
+
+            /**
+             * @overload
+             */
+            void setAttributes(RCSResourceAttributes&& attrs);
+
+            /**
+             * Returns children of this representation.
+             */
+            const std::vector< RCSRepresentation >& getChildren() const;
+
+            /**
+             * Adds a child to this representation.
+             *
+             * @param child a representation to be attached
+             */
+            void addChild(RCSRepresentation child);
+
+            /**
+             * Sets children of this representation.
+             *
+             * @param children new children
+             */
+            void setChildren(std::vector< RCSRepresentation > children);
+
+            /**
+             * Removse all children
+             */
+            void clearChildren();
+
+            /**
+             * Converts OCRepresentation into RCSRepresentation.
+             *
+             * @see toOCRepresentation
+             */
+            static RCSRepresentation fromOCRepresentation(const OC::OCRepresentation&);
+
+
+            /**
+             * Converts RCSRepresentation into OCRepresentation.
+             *
+             * @see fromOCRepresentation
+             */
+            static OC::OCRepresentation toOCRepresentation(const RCSRepresentation&);
+            static OC::OCRepresentation toOCRepresentation(RCSRepresentation&&);
+
+        private:
+            std::string m_uri;
+
+            std::vector< std::string > m_interfaces;
+            std::vector< std::string > m_resourceTypes;
+
+            RCSResourceAttributes m_attributes;
+
+            std::vector< RCSRepresentation > m_children;
+        };
+
+    }
+}
+
+#endif /* RES_ENCAPSULATION_RCSREPRESENTATION_H_ */
index 9a78af8..9ecbc01 100644 (file)
 #ifndef SERVERBUILDER_PRIMITIVEREQUEST_H
 #define SERVERBUILDER_PRIMITIVEREQUEST_H
 
-#include <string>
+#include <memory>
+#include <map>
+
+namespace OC
+{
+    class OCResourceRequest;
+}
 
 namespace OIC
 {
     namespace Service
     {
+        class RCSResourceObject;
+
         /**
         * This class describes the request.
         *
         */
         class RCSRequest
         {
-            public:
-                /**
-                * Constructor to set resource URI.
-                *
-                * @param resourceUri URI of the resource for which the request is generated.
-                */
-                explicit RCSRequest(const std::string &resourceUri);
+        public:
+            RCSRequest() = default;
+
+            /**
+            * Constructor to set resource URI.
+            *
+            * @param resourceUri URI of the resource for which the request is generated.
+            */
+            explicit RCSRequest(const std::string& resourceUri);
+
+            RCSRequest(const std::shared_ptr< RCSResourceObject >&,
+                    const std::shared_ptr< OC::OCResourceRequest >&);
+
+            /**
+             * @return the resource object which receives this request.
+             */
+            std::weak_ptr< RCSResourceObject > getResourceObject() const noexcept;
+
+            /**
+            * @return the URI of the request.
+            *
+            */
+            std::string getResourceUri() const;
+
+            /**
+             * @return the OCResourceRequest.
+             */
+            std::shared_ptr< OC::OCResourceRequest > getOCRequest() const noexcept;
 
-                RCSRequest &operator=(RCSRequest &) = delete;
+            /**
+             * @return the query parameters of the request.
+             */
+            const std::map< std::string, std::string >& getQueryParams() const;
 
-                /**
-                * @return Returns the URI of the request.
-                *
-                */
-                std::string getResourceUri() const;
+            /**
+             * @return the interface of the request.
+             */
+            std::string getInterface() const;
 
-            private:
-                std::string m_resourceUri;
+        private:
+            std::weak_ptr< RCSResourceObject > m_resourceObject;
+            std::shared_ptr< OC::OCResourceRequest > m_ocRequest;
         };
 
     }
index 063a71f..2901d78 100644 (file)
 #include <unordered_map>
 #include <vector>
 
-#include <boost/variant.hpp>
-#include <boost/mpl/contains.hpp>
-#include <boost/mpl/find.hpp>
-#include <boost/mpl/distance.hpp>
-#include <boost/mpl/begin_end.hpp>
-#include <boost/scoped_ptr.hpp>
+#include "boost/variant.hpp"
+#include "boost/mpl/contains.hpp"
+#include "boost/mpl/find.hpp"
+#include "boost/mpl/distance.hpp"
+#include "boost/mpl/begin_end.hpp"
+#include "boost/scoped_ptr.hpp"
 
-#include <RCSException.h>
+#include "RCSException.h"
 
 namespace OIC
 {
@@ -109,7 +109,7 @@ namespace OIC
                 typedef V type;
             };
 
-            template< typename VISITOR >
+            template< typename VISITOR, typename MOVE = std::false_type >
             class KeyValueVisitorHelper: public boost::static_visitor< >
             {
             public:
@@ -118,12 +118,20 @@ namespace OIC
                 {
                 }
 
-                template< typename T >
-                void operator()(const std::string& key, const T& value) const
+                template< typename T, typename M = MOVE >
+                typename std::enable_if< std::is_same< M, std::false_type >::value >::type
+                operator()(const std::string& key, const T& value) const
                 {
                     m_visitor(key, value);
                 }
 
+                template< typename T, typename M = MOVE >
+                typename std::enable_if< std::is_same< M, std::true_type >::value >::type
+                operator()(const std::string& key, T& value)
+                {
+                    m_visitor(key, std::move(value));
+                }
+
             private:
                 VISITOR& m_visitor;
             };
@@ -523,6 +531,15 @@ namespace OIC
             bool erase(const std::string& key);
 
             /**
+             * Removes a single element.
+             *
+             * @param pos Iterator to the element to remove.
+             *
+             * @return Iterator following the last removed element.
+             */
+            iterator erase(const_iterator pos);
+
+            /**
              * Checks this contains an element for the specified key.
              *
              * @param key Key to check.
@@ -558,6 +575,18 @@ namespace OIC
                 }
             }
 
+            template< typename VISITOR >
+            void visitToMove(VISITOR& visitor)
+            {
+                KeyValueVisitorHelper< VISITOR, std::true_type > helper{ visitor };
+
+                for (auto& i : m_values)
+                {
+                    boost::variant< const std::string& > key{ i.first };
+                    boost::apply_visitor(helper, key, *i.second.m_data);
+                }
+            }
+
         private:
             std::unordered_map< std::string, Value > m_values;
 
@@ -582,6 +611,9 @@ namespace OIC
         public:
             ComparisonHelper(const Value&);
 
+            ComparisonHelper(const ComparisonHelper&) = delete;
+            ComparisonHelper& operator=(const ComparisonHelper&) = delete;
+
             template< typename T >
             typename std::enable_if< is_supported_type< T >::value, bool >::type equals(
                     const T& v) const
@@ -788,9 +820,9 @@ namespace OIC
 
         public:
             iterator();
-            iterator(const iterator&) = default;
+            iterator(const iterator&);
 
-            iterator& operator=(const iterator&) = default;
+            iterator& operator=(const iterator&);
 
             reference operator*();
             pointer operator->();
@@ -822,7 +854,7 @@ namespace OIC
          * @see iterator
          */
         class RCSResourceAttributes::const_iterator:
-                public std::iterator < std::forward_iterator_tag,
+                public std::iterator< std::forward_iterator_tag,
                                        const RCSResourceAttributes::KeyValuePair >
         {
         private:
@@ -830,10 +862,10 @@ namespace OIC
 
         public:
             const_iterator();
-            const_iterator(const const_iterator&) = default;
+            const_iterator(const const_iterator&);
             const_iterator(const RCSResourceAttributes::iterator&);
 
-            const_iterator& operator=(const const_iterator&) = default;
+            const_iterator& operator=(const const_iterator&);
             const_iterator& operator=(const RCSResourceAttributes::iterator&);
 
             reference operator*() const;
index 40044c6..8a58b15 100644 (file)
 #include <string>
 #include <mutex>
 #include <thread>
+#include <map>
 
-#include <RCSResourceAttributes.h>
-#include <RCSResponse.h>
-#include <RCSRequest.h>
+#include "RCSResourceAttributes.h"
+#include "RCSResponse.h"
 
 namespace OC
 {
@@ -44,6 +44,10 @@ namespace OIC
     namespace Service
     {
 
+        class RCSRequest;
+        class RCSRepresentation;
+        class InterfaceHandler;
+
         /**
          * @brief Thrown when lock has not been acquired.
          *
@@ -53,7 +57,7 @@ namespace OIC
         class NoLockException: public RCSException
         {
             public:
-                NoLockException(std::string &&what) : RCSException { std::move(what) } {}
+                NoLockException(std::string what) : RCSException { std::move(what) } {}
         };
 
         //! @cond
@@ -62,7 +66,7 @@ namespace OIC
         //! @endcond
 
         /**
-         * RCSResourceObject represents a resource and handles any requests from clients
+         * This class represents a resource and handles any requests from clients
          * automatically with attributes.
          *
          * It also provides an auto notification mechanism that notifies to the observers.
@@ -77,378 +81,478 @@ namespace OIC
          */
         class RCSResourceObject
         {
-            private:
-                class WeakGuard;
+        private:
+            class WeakGuard;
 
-                typedef AtomicWrapper< std::thread::id > AtomicThreadId;
+            typedef AtomicWrapper< std::thread::id > AtomicThreadId;
 
+        public:
+            /**
+             * Represents the policy of auto-notify function.
+             * In accord with this policy, observers are notified of attributes
+             * when the attributes are set.
+             *
+             * @note Attributes are set according to the execution of some functions which
+             * modify attributes or receipt of set requests.
+             *
+             * @see RCSResourceObject::setAttribute
+             * @see RCSResourceObject::removeAttribute
+             * @see RCSResourceObject::getAttributes
+             * @see RCSResourceObject::LockGuard
+             */
+            enum class AutoNotifyPolicy
+            {
+                NEVER,  /**< Never*/
+                ALWAYS, /**< Always*/
+                UPDATED /**< Only when attributes are changed*/
+            };
+
+            /**
+             * Represents the policy of set-request handler.
+             * In accord with this, the RCSResourceObject decides whether a set-request is
+             * acceptable or not.
+             */
+            enum class SetRequestHandlerPolicy
+            {
+                NEVER,     /**< Requests will be ignored if attributes of the request contain
+                                a new key or a value that has different type from the current
+                                value of the key. */
+                ACCEPTANCE /**< The attributes of the request will be applied unconditionally
+                                even if there are new name or type conflicts. */
+            };
+
+            typedef std::shared_ptr< RCSResourceObject > Ptr;
+            typedef std::shared_ptr< const RCSResourceObject > ConstPtr;
+
+            /**
+             * This is a builder to create resource with properties and attributes.
+             *
+             * The resource will be observable and discoverable by default, to make them disable
+             * set these properties explicitly with setDiscoverable and setObservable.
+             *
+             * "oic.if.baseline" is an interface that a resource always holds, by default,
+             * even it is not added manually.
+             */
+            class Builder
+            {
             public:
                 /**
-                 * Represents the policy of auto-notify function.
-                 * In accord with this policy, observers are notified of attributes
-                 * when the attributes are set.
+                 * Constructs a Builder.
                  *
-                 * @note Attributes are set according to the execution of some functions which
-                 * modify attributes or receipt of set requests.
+                 * @param uri Resource uri
+                 * @param type Resource type
+                 * @param interface Resource interface
                  *
-                 * @see RCSResourceObject::setAttribute
-                 * @see RCSResourceObject::removeAttribute
-                 * @see RCSResourceObject::getAttributes
-                 * @see RCSResourceObject::LockGuard
-                 */
-                enum class AutoNotifyPolicy
-                {
-                    NEVER,  /**< Never*/
-                    ALWAYS, /**< Always*/
-                    UPDATED /**< Only when attributes are changed*/
-                };
-
-                /**
-                 * Represents the policy of set-request handler.
-                 * In accord with this, the RCSResourceObject decides whether a set-request is
-                 * acceptable or not.
                  */
-                enum class SetRequestHandlerPolicy
-                {
-                    NEVER,     /**< Requests will be ignored if attributes of the request contain
-                                    a new key or a value that has different type from the current
-                                    value of the key. */
-                    ACCEPTANCE /**< The attributes of the request will be applied unconditionally
-                                    even if there are new name or type conflicts. */
-                };
-
-                typedef std::shared_ptr< RCSResourceObject > Ptr;
-                typedef std::shared_ptr< const RCSResourceObject > ConstPtr;
+                Builder(std::string uri, std::string type, std::string interface);
 
                 /**
-                 * This is a builder to create resource with properties and attributes.
+                 * Add an interface for the resource.
                  *
-                 * The resource will be observable and discoverable by default, to make them disable
-                 * set these properties explicitly with setDiscoverable and setObservable.
+                 * @param interface new interface.
                  */
-                class Builder
-                {
-                    public:
-                        /**
-                         * Constructs a Builder.
-                         *
-                         * @param uri Resource uri
-                         * @param type Resource type
-                         * @param interface Resource interface
-                         *
-                         */
-                        Builder(const std::string& uri, const std::string& type,
-                                const std::string& interface);
-
-                        /**
-                         * Sets whether the resource is discoverable.
-                         *
-                         * @param discoverable whether to be discoverable.
-                         *
-                         */
-                        Builder& setDiscoverable(bool discoverable);
-
-                        /**
-                         * Sets the observable property of the resource.
-                         *
-                         * @param observable whether to be observable.
-                         *
-                         */
-                        Builder& setObservable(bool observable);
-
-                        /**
-                         * Sets attributes for the resource.
-                         *
-                         * @param attributes attributes to set
-                         *
-                         */
-                        Builder& setAttributes(const RCSResourceAttributes &attributes);
-
-                        /**
-                         * @overload
-                         */
-                        Builder& setAttributes(RCSResourceAttributes &&attributes);
-
-                        /**
-                         * Register a resource and returns a RCSResourceObject.
-                         *
-                         * @throw RCSPlatformException if resource registration is failed.
-                         *
-                         */
-                        RCSResourceObject::Ptr build();
-
-                    private:
-                        std::string m_uri;
-                        std::string m_type;
-                        std::string m_interface;
-                        uint8_t m_properties;
-                        RCSResourceAttributes m_resourceAttributes;
-                };
-
-                class LockGuard;
+                Builder& addInterface(std::string interface);
 
                 /**
-                 * Callback definition for a handler to be invoked when a get request is received.
+                 * Add a type for the resource.
                  *
-                 * The handler will be called first when a get request is received, before the
-                 * RCSResourceObject handles.
-                 *
-                 * @param request the request information
-                 * @param attributes attributes of the request
-                 *
-                 * @return response to be sent and that indicates how the request to be handled by
-                 *         the RCSResourceObject.
-                 *
-                 * @see setGetRequestHandler
+                 * @param type new type.
                  */
-                typedef std::function < RCSGetResponse(const RCSRequest& request,
-                        RCSResourceAttributes& attributes) > GetRequestHandler;
+                Builder& addType(std::string type);
 
                 /**
-                 * Callback definition for a handler to be invoked when a set request is received.
-                 *
-                 * The handler will be called first when a get request is received, before the
-                 * RCSResourceObject handles. If the attributes are modified in the callback,
-                 * the modified attributes will be set in the RCSResourceObject if the request is
-                 * not ignored.
+                 * Sets the default interface.
+                 * If it is not called, the interface passed to the constructor is the default.
                  *
-                 * @param request the request information
-                 * @param attributes attributes of the request
-                 *
-                 * @return response to be sent and that indicates how the request to be handled by
-                 *         the RCSResourceObject.
-                 *
-                 * @see setGetRequestHandler
-                 */
-                typedef std::function < RCSSetResponse(const RCSRequest& request,
-                        RCSResourceAttributes& attributes) > SetRequestHandler;
-
-                /**
-                 * Callback definition to be invoked when an attribute is updated.
+                 * @param interface default interface name
                  *
-                 * @param oldValue the value before being changed
-                 * @param newValue changed value
                  */
-                typedef std::function < void(const RCSResourceAttributes::Value& oldValue,
-                            const RCSResourceAttributes::Value& newValue) > AttributeUpdatedListener;
-
-            public:
-                RCSResourceObject(RCSResourceObject&&) = delete;
-                RCSResourceObject(const RCSResourceObject&) = delete;
-
-                RCSResourceObject& operator=(RCSResourceObject&&) = delete;
-                RCSResourceObject& operator=(const RCSResourceObject&) = delete;
-
-                virtual ~RCSResourceObject();
+                Builder& setDefaultInterface(std::string interface);
 
                 /**
-                 * Sets a particular attribute value.
+                 * Sets whether the resource is discoverable.
                  *
-                 * @param key key of attribute
-                 * @param value value to be mapped against the key
+                 * @param discoverable whether to be discoverable.
                  *
-                 * @note Thread-safety is guaranteed for the attributes.
-                 */
-                void setAttribute(const std::string& key, const RCSResourceAttributes::Value& value);
-
-                /**
-                 * @overload
-                 */
-                void setAttribute(const std::string& key, RCSResourceAttributes::Value&& value);
-
-                /**
-                 * @overload
                  */
-                void setAttribute(std::string&& key, const RCSResourceAttributes::Value& value);
+                Builder& setDiscoverable(bool discoverable);
 
                 /**
-                 * @overload
-                 */
-                void setAttribute(std::string&& key, RCSResourceAttributes::Value&& value);
-
-                /**
-                 * Returns an attribute value corresponding to a key.
-                 *
-                 * @param key key of the attribute
-                 *
-                 * @throws RCSInvalidKeyException If key is invalid.
-                 *
-                 * @note Thread-safety is guaranteed for the attributes.
-                 */
-                RCSResourceAttributes::Value getAttributeValue(const std::string& key) const;
-
-                /**
-                 * Returns the attribute value as T.
-                 *
-                 * @param key key of the attribute
+                 * Sets the observable property of the resource.
                  *
-                 * @throws RCSBadGetException If type of the underlying value is not T.
-                 * @throws RCSInvalidKeyException If @a key doesn't match the key of any value.
+                 * @param observable whether to be observable.
                  *
-                 * @note Thread-safety is guaranteed for the attributes.
                  */
-                template< typename T >
-                T getAttribute(const std::string& key) const
-                {
-                    WeakGuard lock(*this);
-                    return m_resourceAttributes.at(key).get< T >();
-                }
+                Builder& setObservable(bool observable);
 
                 /**
-                 * Removes a particular attribute of the resource.
+                 * Sets whether the resource should be secure or not.
                  *
-                 * @param key key of the attribute.
+                 * @param secureFlag whether to be secure or not.
                  *
-                 * @return True if the key exists and matched attribute is removed, otherwise false.
-                 *
-                 * @note Thread-safety is guaranteed for the attributes.
                  */
-                bool removeAttribute(const std::string& key);
+                Builder& setSecureFlag(bool secureFlag);
 
                 /**
-                 * Checks whether a particular attribute exists or not.
-                 *
-                 * @param key key of the attribute
+                 * Sets attributes for the resource.
                  *
-                 * @return True if the key exists, otherwise false.
+                 * @param attributes attributes to set
                  *
-                 * @note Thread-safety is guaranteed for the attributes.
                  */
-                bool containsAttribute(const std::string& key) const;
-
-                /**
-                 * Returns reference to the attributes of the RCSResourceObject.
-                 *
-                 * @pre The call must be guarded by LockGuard.
-                 *
-                 *
-                 * @return Reference to the attributes
-                 *
-                 * @throws NoLockException If the call is not guarded by LockGuard.
-                 *
-                 * @note Here is the standard idiom for LockGuard:
-                 * @code
-                   {
-                      RCSResourceObject::LockGuard lock(rcsResourceObject);
-
-                      auto &attributes = server->getAttributes();
-                      ...
-                   }
-                 * @endcode
-                 */
-                RCSResourceAttributes& getAttributes();
+                Builder& setAttributes(const RCSResourceAttributes &attributes);
 
                 /**
                  * @overload
                  */
-                const RCSResourceAttributes& getAttributes() const;
-
-                /**
-                 * Checks whether the resource is observable or not.
-                 */
-                virtual bool isObservable() const;
-
-                /**
-                 * Checks whether the resource is discoverable or not.
-                 */
-                virtual bool isDiscoverable() const;
+                Builder& setAttributes(RCSResourceAttributes &&attributes);
 
                 /**
-                 * Sets the get request handler.
-                 * To remove handler, pass empty handler or nullptr.
+                 * Register a resource and returns a RCSResourceObject.
                  *
-                 * Default behavior is RCSGetResponse::defaultAction().
+                 * @throw RCSPlatformException if resource registration is failed.
                  *
-                 * @param handler a get request handler
-                 *
-                 * @see RCSGetResponse
-                 *
-                 */
-                virtual void setGetRequestHandler(GetRequestHandler handler);
-
-                /**
-                 * Sets the set request handler.
-                 * To remove handler, pass empty handler or nullptr.
-                 *
-                 * Default behavior is RCSSetResponse::defaultAction().
-                 *
-                 * @param handler a set request handler
-                 *
-                 * @see RCSSetResponse
-                 *
-                 */
-                virtual void setSetRequestHandler(SetRequestHandler handler);
-
-                /**
-                 * Adds a listener for a particular attribute updated.
-                 *
-                 * @param key the interested attribute's key
-                 * @param listener listener to be invoked
-                 *
-                 */
-                virtual void addAttributeUpdatedListener(const std::string& key,
-                        AttributeUpdatedListener listener);
-
-                /**
-                 * @overload
-                 */
-                virtual void addAttributeUpdatedListener(std::string&& key,
-                        AttributeUpdatedListener listener);
-
-                /**
-                 * Removes a listener for a particular attribute updated.
-                 *
-                 * @param key the key associated with the listener to be removed
-                 *
-                 * @return True if the listener added with same key exists and is removed.
-                 *
-                 */
-                virtual bool removeAttributeUpdatedListener(const std::string& key);
-
-                /**
-                 * Notifies all observers of the current attributes.
-                 *
-                 * @throws RCSPlatformException If the operation failed.
                  */
-                virtual void notify() const;
+                RCSResourceObject::Ptr build();
 
-                /**
-                 * Sets auto notify policy
-                 *
-                 * @param policy policy to be set
-                 *
-                 */
-                void setAutoNotifyPolicy(AutoNotifyPolicy policy);
+            private:
+                std::string m_uri;
+                std::vector< std::string > m_types;
+                std::vector< std::string > m_interfaces;
+                std::string m_defaultInterface;
+                uint8_t m_properties;
+                RCSResourceAttributes m_resourceAttributes;
+            };
+
+            class LockGuard;
+
+            /**
+             * Callback definition for a handler to be invoked when a get request is received.
+             *
+             * The handler will be called first when a get request is received, before the
+             * RCSResourceObject handles.
+             *
+             * @param request the request information
+             * @param attributes attributes of the request
+             *
+             * @return response to be sent and that indicates how the request to be handled by
+             *         the RCSResourceObject.
+             *
+             * @see setGetRequestHandler
+             */
+            typedef std::function < RCSGetResponse(const RCSRequest& request,
+                    RCSResourceAttributes& attributes) > GetRequestHandler;
+
+            /**
+             * Callback definition for a handler to be invoked when a set request is received.
+             *
+             * The handler will be called first when a get request is received, before the
+             * RCSResourceObject handles. If the attributes are modified in the callback,
+             * the modified attributes will be set in the RCSResourceObject if the request is
+             * not ignored.
+             *
+             * @param request the request information
+             * @param attributes attributes of the request
+             *
+             * @return response to be sent and that indicates how the request to be handled by
+             *         the RCSResourceObject.
+             *
+             * @see setGetRequestHandler
+             */
+            typedef std::function < RCSSetResponse(const RCSRequest& request,
+                    RCSResourceAttributes& attributes) > SetRequestHandler;
+
+            /**
+             * Callback definition to be invoked when an attribute is updated.
+             *
+             * @param oldValue the value before being changed
+             * @param newValue changed value
+             */
+            typedef std::function < void(const RCSResourceAttributes::Value& oldValue,
+                        const RCSResourceAttributes::Value& newValue) > AttributeUpdatedListener;
 
-                /**
-                 * Returns the current policy
-                 *
-                 */
-                AutoNotifyPolicy getAutoNotifyPolicy() const;
+        public:
+            RCSResourceObject(RCSResourceObject&&) = delete;
+            RCSResourceObject(const RCSResourceObject&) = delete;
+
+            RCSResourceObject& operator=(RCSResourceObject&&) = delete;
+            RCSResourceObject& operator=(const RCSResourceObject&) = delete;
+
+            virtual ~RCSResourceObject();
+
+            /**
+             * Sets a particular attribute value.
+             *
+             * @param key key of attribute
+             * @param value value to be mapped against the key
+             *
+             * @note Thread-safety is guaranteed for the attributes.
+             */
+            void setAttribute(const std::string& key, const RCSResourceAttributes::Value& value);
+
+            /**
+             * @overload
+             */
+            void setAttribute(const std::string& key, RCSResourceAttributes::Value&& value);
+
+            /**
+             * @overload
+             */
+            void setAttribute(std::string&& key, const RCSResourceAttributes::Value& value);
+
+            /**
+             * @overload
+             */
+            void setAttribute(std::string&& key, RCSResourceAttributes::Value&& value);
+
+            /**
+             * Returns an attribute value corresponding to a key.
+             *
+             * @param key key of the attribute
+             *
+             * @throws RCSInvalidKeyException If key is invalid.
+             *
+             * @note Thread-safety is guaranteed for the attributes.
+             */
+            RCSResourceAttributes::Value getAttributeValue(const std::string& key) const;
+
+            /**
+             * Returns the attribute value as T.
+             *
+             * @param key key of the attribute
+             *
+             * @throws RCSBadGetException If type of the underlying value is not T.
+             * @throws RCSInvalidKeyException If @a key doesn't match the key of any value.
+             *
+             * @note Thread-safety is guaranteed for the attributes.
+             */
+            template< typename T >
+            T getAttribute(const std::string& key) const
+            {
+                WeakGuard lock(*this);
+                return m_resourceAttributes.at(key).get< T >();
+            }
+
+            /**
+             * Removes a particular attribute of the resource.
+             *
+             * @param key key of the attribute.
+             *
+             * @return True if the key exists and matched attribute is removed, otherwise false.
+             *
+             * @note Thread-safety is guaranteed for the attributes.
+             */
+            bool removeAttribute(const std::string& key);
+
+            /**
+             * Checks whether a particular attribute exists or not.
+             *
+             * @param key key of the attribute
+             *
+             * @return True if the key exists, otherwise false.
+             *
+             * @note Thread-safety is guaranteed for the attributes.
+             */
+            bool containsAttribute(const std::string& key) const;
+
+            /**
+             * Returns reference to the attributes of the RCSResourceObject.
+             *
+             * @pre The call must be guarded by LockGuard.
+             *
+             *
+             * @return Reference to the attributes
+             *
+             * @throws NoLockException If the call is not guarded by LockGuard.
+             *
+             * @note Here is the standard idiom for LockGuard:
+             * @code
+               {
+                  RCSResourceObject::LockGuard lock(rcsResourceObject);
+
+                  auto &attributes = server->getAttributes();
+                  ...
+               }
+             * @endcode
+             */
+            RCSResourceAttributes& getAttributes();
+
+            /**
+             * @overload
+             */
+            const RCSResourceAttributes& getAttributes() const;
+
+            /**
+             * Checks whether the resource is observable or not.
+             */
+            virtual bool isObservable() const;
+
+            /**
+             * Checks whether the resource is discoverable or not.
+             */
+            virtual bool isDiscoverable() const;
+
+            /**
+             * Sets the get request handler.
+             * To remove handler, pass empty handler or nullptr.
+             *
+             * Default behavior is RCSGetResponse::defaultAction().
+             *
+             * @param handler a get request handler
+             *
+             * @see RCSGetResponse
+             *
+             */
+            virtual void setGetRequestHandler(GetRequestHandler handler);
+
+            /**
+             * Sets the set request handler.
+             * To remove handler, pass empty handler or nullptr.
+             *
+             * Default behavior is RCSSetResponse::defaultAction().
+             *
+             * @param handler a set request handler
+             *
+             * @see RCSSetResponse
+             *
+             */
+            virtual void setSetRequestHandler(SetRequestHandler handler);
+
+            /**
+             * Adds a listener for a particular attribute updated.
+             *
+             * @param key the interested attribute's key
+             * @param listener listener to be invoked
+             *
+             */
+            virtual void addAttributeUpdatedListener(const std::string& key,
+                    AttributeUpdatedListener listener);
+
+            /**
+             * @overload
+             */
+            virtual void addAttributeUpdatedListener(std::string&& key,
+                    AttributeUpdatedListener listener);
+
+            /**
+             * Removes a listener for a particular attribute updated.
+             *
+             * @param key the key associated with the listener to be removed
+             *
+             * @return True if the listener added with same key exists and is removed.
+             *
+             */
+            virtual bool removeAttributeUpdatedListener(const std::string& key);
+
+            /**
+             * Notifies all observers of the current attributes.
+             *
+             * @throws RCSPlatformException If the operation failed.
+             */
+            virtual void notify() const;
+
+            /**
+             * Sets auto notify policy
+             *
+             * @param policy policy to be set
+             *
+             */
+            void setAutoNotifyPolicy(AutoNotifyPolicy policy);
+
+            /**
+             * Returns the current policy
+             *
+             */
+            AutoNotifyPolicy getAutoNotifyPolicy() const;
+
+            /**
+             * Sets the policy for handling a set request.
+             *
+             * @param policy policy to be set
+             *
+             */
+            void setSetRequestHandlerPolicy(SetRequestHandlerPolicy policy);
+
+            /**
+             * Returns the current policy.
+             *
+             */
+            SetRequestHandlerPolicy getSetRequestHandlerPolicy() const;
+
+            /**
+             * Bind a resource to this resource.
+             * Binding another resource makes this resource work as a collection resource,
+             * by default.
+             *
+             * @param resource a resource to be bound to this resource.
+             *
+             * @throws RCSInvalidParameterException If resource is nullptr or itself.
+             * @throws RCSPlatformException If the operation failed.
+             *
+             * @see unbindResource
+             */
+            void bindResource(const RCSResourceObject::Ptr& resource);
+
+            /**
+             * Unbind a resource from this resource.
+             * If there is no bound resource left, the resource will run as a normal resource.
+             *
+             * @param resource a resource to be unbound from this resource.
+             *
+             * @throws RCSInvalidParameterException If resource is nullptr or itself.
+             * @throws RCSPlatformException If the operation failed.
+             *
+             * @see bindResource
+             */
+            void unbindResource(const RCSResourceObject::Ptr& resource);
+
+            /**
+             * Returns all bound resources to this resource.
+             */
+            std::vector< RCSResourceObject::Ptr > getBoundResources() const;
+
+            /**
+             * Returns the uri of the resource.
+             */
+            std::string getUri() const;
+
+            /**
+             * Returns the default interface of the resource
+             *
+             * @see Builder::setDefaultInterface
+             */
+            std::string getDefaultInterface() const;
+
+            /**
+             * Returns all interfaces added for the resource.
+             *
+             * @see Builder::addInterface
+             */
+            std::vector< std::string > getInterfaces() const;
+
+            /**
+             * Returns all types added for the resource.
+             *
+             * @see Builder::addType
+             */
+            std::vector< std::string > getTypes() const;
 
-                /**
-                 * Sets the policy for handling a set request.
-                 *
-                 * @param policy policy to be set
-                 *
-                 */
-                void setSetRequestHandlerPolicy(SetRequestHandlerPolicy policy);
+        private:
+            RCSResourceObject(const std::string&, uint8_t, RCSResourceAttributes&&);
 
-                /**
-                 * Returns the current policy.
-                 *
-                 */
-                SetRequestHandlerPolicy getSetRequestHandlerPolicy() const;
+            void init(OCResourceHandle, const std::vector< std::string >&,
+                    const std::vector< std::string >&, const std::string&);
 
-        private:
-            RCSResourceObject(uint8_t, RCSResourceAttributes&&);
+            static OCEntityHandlerResult entityHandler(const std::weak_ptr< RCSResourceObject >&,
+                    const std::shared_ptr< OC::OCResourceRequest >&);
 
-            OCEntityHandlerResult entityHandler(std::shared_ptr< OC::OCResourceRequest >);
+            OCEntityHandlerResult handleRequest(const RCSRequest&);
+            OCEntityHandlerResult handleRequestGet(const RCSRequest&);
+            OCEntityHandlerResult handleRequestSet(const RCSRequest&);
+            OCEntityHandlerResult handleObserve(const RCSRequest&);
 
-            OCEntityHandlerResult handleRequest(std::shared_ptr< OC::OCResourceRequest >);
-            OCEntityHandlerResult handleRequestGet(std::shared_ptr< OC::OCResourceRequest >);
-            OCEntityHandlerResult handleRequestSet(std::shared_ptr< OC::OCResourceRequest >);
-            OCEntityHandlerResult handleObserve(std::shared_ptr< OC::OCResourceRequest >);
+            template <typename RESPONSE, typename RESPONSE_BUILDER>
+            OCEntityHandlerResult sendResponse(const RCSRequest&,
+                     const RESPONSE&, const RESPONSE_BUILDER&);
 
             void expectOwnLock() const;
 
@@ -466,15 +570,24 @@ namespace OIC
 
             bool applyAcceptanceMethod(const RCSSetResponse&, const RCSResourceAttributes&);
 
+            InterfaceHandler findInterfaceHandler(const std::string&) const;
+
+            RCSRepresentation getRepresentation(const RCSRequest&) const;
+
         private:
             const uint8_t m_properties;
 
+            const std::string m_uri;
+            std::vector< std::string > m_interfaces;
+            std::vector< std::string > m_types;
+            std::string m_defaultInterface;
+
             OCResourceHandle m_resourceHandle;
 
             RCSResourceAttributes m_resourceAttributes;
 
-            GetRequestHandler m_getRequestHandler;
-            SetRequestHandler m_setRequestHandler;
+            std::shared_ptr< GetRequestHandler > m_getRequestHandler;
+            std::shared_ptr< SetRequestHandler > m_setRequestHandler;
 
             AutoNotifyPolicy m_autoNotifyPolicy;
             SetRequestHandlerPolicy m_setRequestHandlerPolicy;
@@ -487,6 +600,13 @@ namespace OIC
 
             std::mutex m_mutexAttributeUpdatedListeners;
 
+            mutable std::mutex m_mutexForBoundResources;
+
+            std::vector< RCSResourceObject::Ptr > m_boundResources;
+
+            std::map< std::string, InterfaceHandler > m_interfaceHandlers;
+
+            friend class RCSSeparateResponse;
         };
 
         /**
@@ -495,8 +615,10 @@ namespace OIC
          * the RCSResourceObject it is given. When control leaves the scope in which the LockGuard
          * object was created, the LockGuard is destructed and the attributes is unlocked.
          *
-         * Additionally when this is destructed, it tries to notify depending on AutoNotifyPolicy
-         * of the RCSResourceObject.
+         * Additionally when it is destructed and only when destructed not by stack unwinding
+         * caused by an exception, it tries to notify depending on AutoNotifyPolicy.
+         *
+         * @note The destrcutor can throw an exception if auto notify failed.
          */
         class RCSResourceObject::LockGuard
         {
@@ -519,7 +641,13 @@ namespace OIC
             * @overload
             */
             LockGuard(const RCSResourceObject::Ptr, AutoNotifyPolicy);
-            ~LockGuard();
+
+            /**
+             * @throws RCSPlatformException If auto notify operation failed.
+             *
+             * @note The exception will never be thrown while stack unwinding.
+             */
+            ~LockGuard() noexcept(false);
 
             LockGuard(const LockGuard&) = delete;
             LockGuard(LockGuard&&) = delete;
index 6a1a36b..d94b555 100644 (file)
@@ -60,7 +60,10 @@ namespace OIC
              * The attributes of the RCSResourceObject will be set as the result attributes.
              *
              * @param errorCode The error code to set in response.
-             *
+             * @see create(const RCSResourceAttributes&)
+             * @see create(RCSResourceAttributes&&)
+             * @see create(const RCSResourceAttributes&, int)
+             * @see create(RCSResourceAttributes&&, int)
              */
             static RCSGetResponse create(int errorCode);
 
@@ -69,15 +72,27 @@ namespace OIC
              * This sends the passed attributes as the result attributes
              * instead of the one the RCSResourceObject holds.
              *
+             * @overload
              * @param attrs The attributes to set.
              *
              * @see RCSResourceAttributes
+             * @see create(int)
+             * @see create(RCSResourceAttributes&&)
+             * @see create(const RCSResourceAttributes&, int)
+             * @see create(RCSResourceAttributes&&, int)
              *
              */
             static RCSGetResponse create(const RCSResourceAttributes& attrs);
 
             /**
-             * @override
+             * @overload
+             * @param attrs The attributes to set.
+             *
+             * @see RCSResourceAttributes
+             * @see create(int)
+             * @see create(const RCSResourceAttributes&)
+             * @see create(const RCSResourceAttributes&, int)
+             * @see create(RCSResourceAttributes&&, int)
              */
             static RCSGetResponse create(RCSResourceAttributes&& attrs);
 
@@ -86,24 +101,56 @@ namespace OIC
              * This sends the passed attributes as the result attributes
              * instead of the one the RCSResourceObject holds.
              *
+             * @overload
              * @param attrs The attributes to set.
              * @param errorCode The error code for response.
              *
              * @see RCSResourceAttributes
-             *
+             * @see create(int)
+             * @see create(const RCSResourceAttributes&)
+             * @see create(RCSResourceAttributes&&)
+             * @see create(const RCSResourceAttributes&, int)
+             * @see create(RCSResourceAttributes&&, int)
              */
             static RCSGetResponse create(const RCSResourceAttributes& attrs, int errorCode);
 
             /**
-             * @override
+             * @overload
+             * @param attrs The attributes to set.
+             * @param errorCode The error code for response.
+             *
+             * @see RCSResourceAttributes
+             * @see create(int)
+             * @see create(const RCSResourceAttributes&)
+             * @see create(RCSResourceAttributes&&)
+             * @see create(const RCSResourceAttributes&, int)
              */
             static RCSGetResponse create(RCSResourceAttributes&& attrs, int errorCode);
 
+            /**
+             * Creates a RCSGetResponse for the separate response.
+             * The separate response is to delay sending actual response to the client.
+             *
+             * @note A separate response needs to be set with RCSSeparateResponse
+             * to send the result of the request.
+             *
+             * @see RCSSeparateResponse
+             */
+            static RCSGetResponse separate();
+
+            /**
+             * Returns whether it is a separate response.
+             *
+             * @see separate()
+             */
+            bool isSeparate() const;
+
             //! @cond
             RequestHandler* getHandler() const;
             //! @endcond
 
         private:
+            RCSGetResponse();
             RCSGetResponse(std::shared_ptr< RequestHandler >&&);
 
         private:
@@ -160,6 +207,7 @@ namespace OIC
              * The response will have 200 for the errorCode.
              * The attributes of RCSResourceObject will be set as the result attributes.
              *
+             * @see accept(int)
              */
             static RCSSetResponse accept();
 
@@ -167,8 +215,10 @@ namespace OIC
              * Creates a RCSSetResponse that has AcceptanceMethod::ACCEPT and error code passed.
              * The attributes of the RCSResourceObject will be set as the result attributes.
              *
+             * @overload
              * @param errorCode The error code to set in response.
              *
+             * @see accept()
              */
             static RCSSetResponse accept(int errorCode);
 
@@ -193,8 +243,12 @@ namespace OIC
              * Creates a RCSSetResponse that has AcceptanceMethod::DEFAULT and error code passed.
              * The attributes of the RCSResourceObject will be set as the result attributes.
              *
+             * @overload
              * @param errorCode The error code to set in response.
-             *
+             * @see create(const RCSResourceAttributes&)
+             * @see create(RCSResourceAttributes&&)
+             * @see create(const RCSResourceAttributes&, int)
+             * @see create(RCSResourceAttributes&&, int)
              */
             static RCSSetResponse create(int errorCode);
 
@@ -203,15 +257,25 @@ namespace OIC
              * This sends the passed attributes as the result attributes
              * instead of the one the RCSResourceObject holds.
              *
+             * @overload
              * @param attrs The attributes to set.
              *
              * @see RCSResourceAttributes
-             *
+             * @see create(int)
+             * @see create(RCSResourceAttributes&&)
+             * @see create(const RCSResourceAttributes&, int)
+             * @see create(RCSResourceAttributes&&, int)
              */
             static RCSSetResponse create(const RCSResourceAttributes& attrs);
 
             /**
-             * @override
+             * @overload
+             * @param attrs The attributes to set.
+             * @see RCSResourceAttributes
+             * @see create(int)
+             * @see create(const RCSResourceAttributes&)
+             * @see create(const RCSResourceAttributes&, int)
+             * @see create(RCSResourceAttributes&&, int)
              */
             static RCSSetResponse create(RCSResourceAttributes&& attrs);
 
@@ -220,19 +284,47 @@ namespace OIC
              * This sends the passed attributes as the result attributes
              * instead of the one the RCSResourceObject holds.
              *
+             * @overload
              * @param attrs The attributes to set.
              * @param errorCode The error code for response.
              *
              * @see RCSResourceAttributes
-             *
+             * @see create(int)
+             * @see create(const RCSResourceAttributes&)
+             * @see create(RCSResourceAttributes&&)
+             * @see create(RCSResourceAttributes&&, int)
              */
             static RCSSetResponse create(const RCSResourceAttributes& attrs, int errorCode);
 
             /**
-             * @override
+             * @overload
+             * @param attrs The attributes to set.
+             * @param errorCode The error code for response.
+             * @see RCSResourceAttributes
+             * @see create(int)
+             * @see create(const RCSResourceAttributes&)
+             * @see create(RCSResourceAttributes&&)
+             * @see create(const RCSResourceAttributes&, int)
              */
             static RCSSetResponse create(RCSResourceAttributes&& attrs, int errorCode);
 
+            /**
+             * Creates a RCSSetResponse for a separate response.
+             * The separate response is to delay sending actual response to the client.
+             *
+             * @note A separate response needs to be set with RCSSeparateResponse
+             * to send the result of the request.
+             *
+             * @see RCSSeparateResponse
+             */
+            static RCSSetResponse separate();
+
+            /**
+             * Returns whether it is a separate response.
+             *
+             * @see separate()
+             */
+            bool isSeparate() const;
 
             //! @cond
             SetRequestHandler* getHandler() const;
@@ -257,6 +349,7 @@ namespace OIC
             RCSSetResponse& setAcceptanceMethod(AcceptanceMethod method);
 
         private:
+            RCSSetResponse();
             RCSSetResponse(std::shared_ptr< SetRequestHandler >&&);
             RCSSetResponse(std::shared_ptr< SetRequestHandler >&&, AcceptanceMethod);
 
diff --git a/service/resource-encapsulation/include/RCSSeparateResponse.h b/service/resource-encapsulation/include/RCSSeparateResponse.h
new file mode 100755 (executable)
index 0000000..0d8b7ed
--- /dev/null
@@ -0,0 +1,85 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef SERVERBUILDER_RCSSEPARATERESPONSE_H
+#define SERVERBUILDER_RCSSEPARATERESPONSE_H
+
+#include "RCSRequest.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+        /**
+         * This class is to send a delayed response for request handlers of the RCSResourceObject.
+         *
+         * @see RCSResourceObject
+         * @see RCSResourceObject::SetRequestHandler
+         * @see RCSResourceObject::GetRequestHandler
+         * @see RCSGetResponse::separate()
+         * @see RCSSetResponse::separate()
+         */
+        class RCSSeparateResponse
+        {
+        public:
+            /**
+             * Constructs with a request.
+             *
+             * @note The request must be from a request handler which returns separate().
+             *
+             * @see RCSResourceObject::SetRequestHandler
+             * @see RCSResourceObject::GetRequestHandler
+             * @see RCSGetResponse::separate()
+             * @see RCSSetResponse::separate()
+             */
+            explicit RCSSeparateResponse(const RCSRequest& request);
+
+            /**
+             * @overload
+             */
+            explicit RCSSeparateResponse(RCSRequest&& request);
+
+            RCSSeparateResponse(const RCSSeparateResponse&) = delete;
+            RCSSeparateResponse& operator=(const RCSSeparateResponse&) = delete;
+
+            RCSSeparateResponse(RCSSeparateResponse&&) = default;
+            RCSSeparateResponse& operator=(RCSSeparateResponse&&) =default;
+
+            /**
+             * Sends the response to the client.
+             * The payload will be composed of properties(including attributes) of
+             *      the resource object of the request.
+             *
+             * @throws RCSBadRequestException If the RCSResourceObject which receives the request
+             *      is gone or it is already set.
+             * @throws RCSPlatformException If the operation failed.
+             */
+            void set();
+
+        private:
+            RCSRequest m_request;
+
+            bool m_done;
+        };
+
+    }
+}
+
+#endif // SERVERBUILDER_RCSSEPARATERESPONSE_H
index 6d0ff9d..06efb88 100644 (file)
@@ -83,7 +83,7 @@ rcs_common_src = [
                RESOURCE_SRC + 'RCSException.cpp',
                RESOURCE_SRC + 'RCSAddress.cpp',
                RESOURCE_SRC + 'RCSResourceAttributes.cpp',
-               RESOURCE_SRC + 'ResponseStatement.cpp'
+               RESOURCE_SRC + 'RCSRepresentation.cpp'
         ]
 
 rcs_common_static = rcs_common_env.StaticLibrary('rcs_common', rcs_common_src)
index c91f9d9..f556f39 100644 (file)
 #define COMMON_INTERNAL_ASSERTUTILS_H
 
 #include <cstdint>
+#include <cstdlib>
 
 #include <memory>
 
-#include <octypes.h>
-#include <OCException.h>
+#include "octypes.h"
+#include "OCException.h"
 
-#include <RCSException.h>
+#include "RCSException.h"
 
 namespace OIC
 {
@@ -36,6 +37,47 @@ namespace OIC
     {
         namespace Detail
         {
+
+            // This is a helper class to avoid calling the base layer during terminating the process.
+            // The reason why you should not call the base layer in this situation is that
+            // OC apis are singletons or internally implemented as singleton.
+            // Singleton implemented with a static variable is initialized
+            // in the first call to the function.
+            // It means you can not guarantee the order of initialization of the singletons,
+            // which is the reverse order of destruction.
+            // Some of RE classes are also implemented as singletons.
+            // Now we have a problem if RE tries to call one of OC apis
+            // after OC classes are destroyed first.
+            // To solve this issue, it registers exit handler to catch the termination event.
+            // Keep this information with a bool flag dynamically allocated to
+            // make sure it is not destroyed during the destruction of the static objects.
+            class TerminationChecker
+            {
+            private:
+                static bool& getExited()
+                {
+                    static bool* flag = new bool{ false };
+                    return *flag;
+                }
+
+                static void atExitHandler()
+                {
+                    getExited() = true;
+                }
+
+                TerminationChecker()
+                {
+                    std::atexit(atExitHandler);
+                }
+
+            public:
+                static bool isInTermination()
+                {
+                    static TerminationChecker once;
+                    return getExited();
+                }
+            };
+
             struct NotOCStackResult;
 
             template <typename FUNC, typename ...PARAMS>
@@ -105,6 +147,8 @@ namespace OIC
         invokeOCFuncWithResultExpect(std::initializer_list<OCStackResult> allowed,
                 FUNC&& fn, PARAMS&& ...params)
         {
+            if (Detail::TerminationChecker::isInTermination()) return;
+
             try
             {
                 expectOCStackResult(fn(std::forward< PARAMS >(params)...), std::move(allowed));
@@ -121,6 +165,8 @@ namespace OIC
                 OCStackResult >::type
         invokeOCFunc(FUNC&& fn, PARAMS&& ...params)
         {
+            if (Detail::TerminationChecker::isInTermination()) return;
+
             try
             {
                 expectOCStackResultOK(fn(std::forward< PARAMS >(params)...));
@@ -136,6 +182,8 @@ namespace OIC
                         Detail::NotOCStackResult >::type
         invokeOCFunc(FUNC* fn, PARAMS&& ...params)
         {
+            if (Detail::TerminationChecker::isInTermination()) return;
+
             try
             {
                 return fn(std::forward< PARAMS >(params)...);
@@ -153,6 +201,8 @@ namespace OIC
                 decltype((obj->*fn)(std::forward< PARAMS >(params)...)), OCStackResult>::
                 type
         {
+            if (Detail::TerminationChecker::isInTermination()) return;
+
             try
             {
                 expectOCStackResultOK(obj->*fn(std::forward< PARAMS >(params)...));
@@ -171,6 +221,8 @@ namespace OIC
                     Detail::NotOCStackResult>::
                     type
         {
+            if (Detail::TerminationChecker::isInTermination()) return;
+
             try
             {
                 obj->*fn(std::forward< PARAMS >(params)...);
@@ -188,6 +240,8 @@ namespace OIC
                     decltype((obj.get()->*fn)(std::forward< PARAMS >(params)...)), OCStackResult>::
                     type
         {
+            if (Detail::TerminationChecker::isInTermination()) return;
+
             try
             {
                 expectOCStackResultOK((obj.get()->*fn)(std::forward< PARAMS >(params)...));
@@ -206,6 +260,8 @@ namespace OIC
                    Detail::NotOCStackResult>::
                    type
         {
+            if (Detail::TerminationChecker::isInTermination()) return { };
+
             try
             {
                 return (obj.get()->*fn)(std::forward< PARAMS >(params)...);
index 9744e49..e55e4cc 100644 (file)
 #include <string>
 #include <vector>
 
-#include <OCResource.h>
+#include "OCResource.h"
 
-#include <ResponseStatement.h>
-#include <RCSAddress.h>
+#include "ResponseStatement.h"
+#include "RCSAddress.h"
 
 namespace OIC
 {
@@ -39,7 +39,7 @@ namespace OIC
         typedef std::vector<HeaderOption> HeaderOptions;
 
         class RCSResourceAttributes;
-        class ResponseStatement;
+        class RCSRepresentation;
 
         class PrimitiveResource: public std::enable_shared_from_this< PrimitiveResource >
         {
@@ -47,25 +47,36 @@ namespace OIC
             typedef std::shared_ptr< PrimitiveResource > Ptr;
             typedef std::shared_ptr< const PrimitiveResource > ConstPtr;
 
-            typedef std::function<void(const HeaderOptions&, const ResponseStatement&, int)>
+            typedef std::function<void(const HeaderOptions&, const RCSRepresentation&, int)>
                     GetCallback;
 
-            typedef std::function<void(const HeaderOptions&, const ResponseStatement&, int)>
+            typedef std::function<void(const HeaderOptions&, const RCSRepresentation&, int)>
                     SetCallback;
 
-            typedef std::function<void(const HeaderOptions&, const ResponseStatement&, int)>
+            typedef std::function<void(const HeaderOptions&, const RCSRepresentation&, int)>
                     PutCallback;
 
-            typedef std::function<void(const HeaderOptions&, const ResponseStatement&, int, int)>
+            typedef std::function<void(const HeaderOptions&, const RCSRepresentation&, int, int)>
                     ObserveCallback;
 
         public:
             static PrimitiveResource::Ptr create(const std::shared_ptr<OC::OCResource>&);
 
-            virtual ~PrimitiveResource() { };
+            virtual ~PrimitiveResource() { }
 
             virtual void requestGet(GetCallback) = 0;
+
+            virtual void requestGetWith(const std::string& resourceType,
+                    const std::string& resourceInterface,
+                    const OC::QueryParamsMap& queryParametersMap, GetCallback) = 0;
+
             virtual void requestSet(const RCSResourceAttributes&, SetCallback) = 0;
+
+            virtual void requestSetWith(const std::string& resourceType,
+                    const std::string& resourceInterface,
+                    const OC::QueryParamsMap& queryParametersMap,
+                    const RCSResourceAttributes&, GetCallback) = 0;
+
             virtual void requestPut(const RCSResourceAttributes&, PutCallback) = 0;
             virtual void requestObserve(ObserveCallback) = 0;
             virtual void cancelObserve() = 0;
index a78d7b8..5d741ef 100644 (file)
 #ifndef COMMON_INTERNAL_PRIMITIVERESOURCEIMPL_H
 #define COMMON_INTERNAL_PRIMITIVERESOURCEIMPL_H
 
-#include <PrimitiveResource.h>
-#include <ResponseStatement.h>
-#include <AssertUtils.h>
+#include "PrimitiveResource.h"
+#include "AssertUtils.h"
 
-#include <ResourceAttributesConverter.h>
+#include "ResourceAttributesConverter.h"
 
 namespace OIC
 {
@@ -39,11 +38,10 @@ namespace OIC
             typedef std::shared_ptr< BaseResource > BaseResourcePtr;
 
         private:
-            static ResponseStatement createResponseStatement(
+            static RCSRepresentation convertRepresentation(
                     const OC::OCRepresentation& rep)
             {
-                return ResponseStatement::create(
-                        ResourceAttributesConverter::fromOCRepresentation(rep));
+                return RCSRepresentation::fromOCRepresentation(rep);
             }
 
             template< typename CALLBACK, typename ...ARGS >
@@ -62,7 +60,7 @@ namespace OIC
                     const CALLBACK& cb, const HeaderOptions& headerOptions,
                     const OC::OCRepresentation& rep, int errorCode)
             {
-                checkedCall(resource, cb, headerOptions, createResponseStatement(rep), errorCode);
+                checkedCall(resource, cb, headerOptions, convertRepresentation(rep), errorCode);
             }
 
             static void safeObserveCallback(const std::weak_ptr< const PrimitiveResource >& res,
@@ -70,7 +68,7 @@ namespace OIC
                     const HeaderOptions& headerOptions, const OC::OCRepresentation& rep,
                     int errorCode, int sequenceNumber)
             {
-                checkedCall(res, cb, headerOptions, createResponseStatement(rep), errorCode,
+                checkedCall(res, cb, headerOptions, convertRepresentation(rep), errorCode,
                         sequenceNumber);
             }
 
@@ -92,32 +90,49 @@ namespace OIC
 
             void requestGet(GetCallback callback)
             {
+                requestGetWith("", "", {}, std::move(callback));
+            }
+
+            void requestGetWith(const std::string& resourceType,
+                    const std::string& resourceInterface,
+                    const OC::QueryParamsMap& queryParametersMap, GetCallback callback)
+            {
                 using namespace std::placeholders;
 
                 typedef OCStackResult(BaseResource::*GetFunc)(
+                        const std::string&, const std::string&,
                         const OC::QueryParamsMap&, OC::GetCallback);
 
                 invokeOC(m_baseResource, static_cast< GetFunc >(&BaseResource::get),
-                        OC::QueryParamsMap{ },
+                        resourceType, resourceInterface, queryParametersMap,
                         std::bind(safeCallback< GetCallback >, WeakFromThis(),
                                 std::move(callback), _1, _2, _3));
             }
 
             void requestSet(const RCSResourceAttributes& attrs, SetCallback callback)
             {
+                requestSetWith("", "", {}, attrs, std::move(callback));
+            }
+
+            void requestSetWith(const std::string& resourceType,
+                          const std::string& resourceInterface,
+                          const OC::QueryParamsMap& queryParametersMap,
+                          const RCSResourceAttributes& attrs, GetCallback callback)
+            {
                 using namespace std::placeholders;
 
-                typedef OCStackResult(BaseResource::*PostFunc)(
-                        const OC::OCRepresentation&,
-                        const OC::QueryParamsMap&, OC::PostCallback);
+                typedef OCStackResult (BaseResource::*PostFunc)(const std::string&,
+                        const std::string&, const OC::OCRepresentation&, const OC::QueryParamsMap&,
+                        OC::GetCallback);
 
                 invokeOC(m_baseResource, static_cast< PostFunc >(&BaseResource::post),
-                        ResourceAttributesConverter::toOCRepresentation(attrs),
-                        OC::QueryParamsMap{ },
-                        std::bind(safeCallback< SetCallback >, WeakFromThis(),
-                                std::move(callback), _1, _2, _3));
+                        resourceType, resourceInterface,
+                        ResourceAttributesConverter::toOCRepresentation(attrs), queryParametersMap,
+                        std::bind(safeCallback< SetCallback >, WeakFromThis(), std::move(callback),
+                                _1, _2, _3));
             }
 
+
             void requestPut(const RCSResourceAttributes& attrs, PutCallback callback)
             {
                 using namespace std::placeholders;
index 0281ee3..4a52eaf 100644 (file)
@@ -39,6 +39,8 @@ namespace OIC
 
             const std::string& getAddress() const;
 
+            bool isMulticast() const;
+
         private:
             std::string m_addr;
         };
index 7181e75..8c49dc3 100644 (file)
 #ifndef COMMON_RESPONSESTATEMENT_H
 #define COMMON_RESPONSESTATEMENT_H
 
-#include <string>
-#include <vector>
-
-#include <RCSResourceAttributes.h>
-
-namespace OC
-{
-    class OCRepresentation;
-}
+#include "RCSRepresentation.h"
 
 namespace OIC
 {
     namespace Service
     {
-        class RCSResourceAttributes;
-
-        class ResponseStatement
-        {
-        public:
-            static ResponseStatement create(const OC::OCRepresentation&);
-            static ResponseStatement create(RCSResourceAttributes&&);
-
-            explicit ResponseStatement(const RCSResourceAttributes&);
-            explicit ResponseStatement(RCSResourceAttributes&&);
-
-            ResponseStatement(RCSResourceAttributes&&, std::string&& uri,
-                    std::vector< std::string >&& resourceTypes,
-                    std::vector< std::string >&& resourceInterfaces);
-
-            ResponseStatement(ResponseStatement&&) = default;
-
-            ResponseStatement& operator=(ResponseStatement&&) = default;
-
-            std::string getUri() const;
-            std::vector< std::string > getResourceTypes() const;
-            std::vector< std::string > getResourceInterfaces() const;
-
-            const RCSResourceAttributes& getAttributes() const;
-
-        private:
-            RCSResourceAttributes m_attrs;
-
-            std::string m_uri;
-            std::vector< std::string > m_resourceTypes;
-            std::vector< std::string > m_resourceInterfaces;
-        };
-
+        typedef RCSRepresentation ResponseStatement;
     }
 }
 
index ef2dd9b..905bd5a 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#include <PrimitiveResource.h>
+#include "PrimitiveResource.h"
 
-#include <PrimitiveResourceImpl.h>
-#include <AssertUtils.h>
-#include <RCSAddressDetail.h>
+#include "PrimitiveResourceImpl.h"
+#include "AssertUtils.h"
+#include "RCSAddressDetail.h"
 
-#include <OCPlatform.h>
+#include "OCPlatform.h"
 
 namespace OIC
 {
index 3bc4021..8518ba1 100644 (file)
@@ -67,5 +67,10 @@ namespace OIC
             return m_addr;
         }
 
+        bool RCSAddressDetail::isMulticast() const
+        {
+            return m_addr.empty();
+        }
+
     }
 }
diff --git a/service/resource-encapsulation/src/common/primitiveResource/src/RCSRepresentation.cpp b/service/resource-encapsulation/src/common/primitiveResource/src/RCSRepresentation.cpp
new file mode 100644 (file)
index 0000000..79db0bd
--- /dev/null
@@ -0,0 +1,177 @@
+//******************************************************************
+//
+// 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 "RCSRepresentation.h"
+
+#include "ResourceAttributesConverter.h"
+
+#include "OCRepresentation.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+
+        RCSRepresentation::RCSRepresentation() { }
+
+        RCSRepresentation::RCSRepresentation(const std::string& uri) :
+                m_uri{ uri }
+        {
+        }
+
+        RCSRepresentation::RCSRepresentation(const RCSResourceAttributes& attrs) :
+                m_uri{ },
+                m_interfaces{ },
+                m_resourceTypes{ },
+                m_attributes{ attrs }
+        {
+        }
+
+        RCSRepresentation::RCSRepresentation(const std::string& uri,
+                const std::vector< std::string >& interfaces,
+                const std::vector< std::string >& resourceTypes) :
+                m_uri{ uri },
+                m_interfaces{ interfaces },
+                m_resourceTypes{ resourceTypes }
+        {
+        }
+
+        RCSRepresentation::RCSRepresentation(const std::string& uri,
+                const std::vector< std::string >& interfaces,
+                const std::vector< std::string >& resourceTypes,
+                const RCSResourceAttributes& attrs) :
+                m_uri{ uri },
+                m_interfaces{ interfaces },
+                m_resourceTypes{ resourceTypes },
+                m_attributes{ attrs }
+        {
+        }
+
+        std::string RCSRepresentation::getUri() const
+        {
+            return m_uri;
+        }
+
+        void RCSRepresentation::setUri(std::string uri)
+        {
+            m_uri = std::move(uri);
+        }
+
+        const std::vector< std::string >& RCSRepresentation::getInterfaces() const
+        {
+            return m_interfaces;
+        }
+
+        void RCSRepresentation::addInterface(std::string interface)
+        {
+            m_interfaces.push_back(std::move(interface));
+        }
+
+        void RCSRepresentation::clearInterfaces()
+        {
+            m_interfaces.clear();
+        }
+
+        const std::vector< std::string >& RCSRepresentation::getResourceTypes() const
+        {
+            return m_resourceTypes;
+        }
+
+        void RCSRepresentation::addResourceType(std::string resourceType)
+        {
+            m_resourceTypes.push_back(std::move(resourceType));
+        }
+
+        void RCSRepresentation::clearResourceTypes()
+        {
+            m_resourceTypes.clear();
+        }
+
+        const RCSResourceAttributes& RCSRepresentation::getAttributes() const
+        {
+            return m_attributes;
+        }
+
+        RCSResourceAttributes& RCSRepresentation::getAttributes()
+        {
+            return m_attributes;
+        }
+
+        void RCSRepresentation::setAttributes(const RCSResourceAttributes& attrs)
+        {
+            m_attributes = attrs;
+        }
+
+        void RCSRepresentation::setAttributes(RCSResourceAttributes&& attrs)
+        {
+            m_attributes = std::move(attrs);
+        }
+
+        void RCSRepresentation::addChild(RCSRepresentation child)
+        {
+            m_children.push_back(std::move(child));
+        }
+
+        void RCSRepresentation::setChildren(std::vector< RCSRepresentation > children)
+        {
+            m_children = std::move(children);
+        }
+
+        const std::vector< RCSRepresentation >& RCSRepresentation::getChildren() const
+        {
+            return m_children;
+        }
+
+        void RCSRepresentation::clearChildren()
+        {
+            m_children.clear();
+        }
+
+
+        RCSRepresentation RCSRepresentation::fromOCRepresentation(const OC::OCRepresentation& ocRep)
+        {
+            return RCSRepresentation(ocRep.getUri(), ocRep.getResourceInterfaces(),
+                    ocRep.getResourceTypes(),
+                    ResourceAttributesConverter::fromOCRepresentation(ocRep));
+        }
+
+        OC::OCRepresentation RCSRepresentation::toOCRepresentation(const RCSRepresentation& rcsRep)
+        {
+            return toOCRepresentation(RCSRepresentation{ rcsRep });
+        }
+
+        OC::OCRepresentation RCSRepresentation::toOCRepresentation(RCSRepresentation&& rcsRep)
+        {
+            auto ocRep =
+                    ResourceAttributesConverter::toOCRepresentation(std::move(rcsRep.m_attributes));
+
+            ocRep.setUri(std::move(rcsRep.m_uri));
+            ocRep.setResourceInterfaces(std::move(rcsRep.m_interfaces));
+            ocRep.setResourceTypes(std::move(rcsRep.m_resourceTypes));
+
+            for (auto& child : rcsRep.m_children)
+            {
+                ocRep.addChild(toOCRepresentation(std::move(child)));
+            }
+
+            return ocRep;
+        }
+    }
+}
index cb339ec..e96e7cc 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#include <RCSResourceAttributes.h>
+#include "RCSResourceAttributes.h"
 
-#include <ResourceAttributesUtils.h>
-#include <ResourceAttributesConverter.h>
+#include <sstream>
 
-#include <boost/lexical_cast.hpp>
-#include <boost/mpl/advance.hpp>
-#include <boost/mpl/size.hpp>
-#include <boost/mpl/deref.hpp>
+#include "ResourceAttributesUtils.h"
+#include "ResourceAttributesConverter.h"
+
+#include "boost/lexical_cast.hpp"
+#include "boost/mpl/advance.hpp"
+#include "boost/mpl/size.hpp"
+#include "boost/mpl/deref.hpp"
 
 namespace
 {
 
     using namespace OIC::Service;
 
-    class ToStringVisitor: public boost::static_visitor< std::string >
+    class ToStringVisitor: public boost::static_visitor<>
     {
     public:
         ToStringVisitor() = default;
@@ -43,37 +45,56 @@ namespace
         ToStringVisitor& operator=(const ToStringVisitor&) = delete;
         ToStringVisitor& operator=(ToStringVisitor&&) = delete;
 
-        template < typename T >
-        std::string operator()(const T& value) const
+        template< typename T >
+        void operator()(const T& value)
         {
-            return boost::lexical_cast<std::string>(value);
+            m_stream << boost::lexical_cast< std::string >(value);
         }
 
         template< typename T >
-        std::string operator()(const std::vector< T >&) const
+        void operator()(const std::vector< T >& v)
         {
-            return "Vector";
+            m_stream << "[";
+            for (auto it = v.begin(); it != v.end(); ++it)
+            {
+                if (it != v.begin()) m_stream << ", ";
+                (*this)(*it);
+            }
+            m_stream << "]";
         }
 
-        std::string operator()(std::nullptr_t) const
+        void operator()(std::nullptr_t)
         {
-            return "";
+            m_stream << "";
         }
 
-        std::string operator()(bool value) const
+        void operator()(bool value)
         {
-            return value ? "true" : "false";
+            m_stream << (value ? "true" : "false");
         }
 
-        std::string operator()(const std::string& value) const
+        void operator()(const std::string& value)
         {
-            return value;
+            m_stream << "\"" + value + "\"";
         }
 
-        std::string operator()(const OIC::Service::RCSResourceAttributes&) const
+        void operator()(const RCSResourceAttributes& attrs)
         {
-            return "Attributes";
+            m_stream << "{";
+            for (auto it = attrs.begin(); it != attrs.end(); ++it)
+            {
+                if (it != attrs.begin()) m_stream << ", ";
+                m_stream << "\"" << it->key() << "\" : " << it->value().toString();
+            }
+            m_stream << "}";
+        }
+
+        std::string get() const {
+            return m_stream.str();
         }
+
+    private:
+        std::ostringstream m_stream;
     };
 
     class TypeVisitor: public boost::static_visitor< RCSResourceAttributes::Type >
@@ -333,7 +354,9 @@ namespace OIC
 
         std::string RCSResourceAttributes::Value::toString() const
         {
-            return boost::apply_visitor(ToStringVisitor(), *m_data);
+            ToStringVisitor visitor;
+            boost::apply_visitor(visitor, *m_data);
+            return visitor.get();
         }
 
         void RCSResourceAttributes::Value::swap(Value& rhs) noexcept
@@ -406,6 +429,18 @@ namespace OIC
         {
         }
 
+        RCSResourceAttributes::iterator::iterator(const iterator& rhs) :
+                m_cur{ rhs.m_cur },
+                m_keyValuePair{ this }
+        {
+        }
+
+        auto RCSResourceAttributes::iterator::operator=(const iterator& rhs) -> iterator&
+        {
+            m_cur = rhs.m_cur;
+            return *this;
+        }
+
         RCSResourceAttributes::iterator::iterator(base_iterator&& iter) :
                 m_cur{ std::move(iter) },
                 m_keyValuePair{ this }
@@ -456,6 +491,11 @@ namespace OIC
         {
         }
 
+        RCSResourceAttributes::const_iterator::const_iterator(const const_iterator& rhs) :
+                m_cur{ rhs.m_cur }, m_keyValuePair{ this }
+        {
+        }
+
         RCSResourceAttributes::const_iterator::const_iterator(
                 const RCSResourceAttributes::iterator& iter) :
                 m_cur{ iter.m_cur }, m_keyValuePair{ this }
@@ -463,6 +503,13 @@ namespace OIC
         }
 
         auto RCSResourceAttributes::const_iterator::operator=(
+                const const_iterator& rhs) -> const_iterator&
+        {
+            m_cur = rhs.m_cur;
+            return *this;
+        }
+
+        auto RCSResourceAttributes::const_iterator::operator=(
                 const RCSResourceAttributes::iterator& iter) -> const_iterator&
         {
             m_cur = iter.m_cur;
@@ -577,6 +624,11 @@ namespace OIC
             return m_values.erase(key) == 1U;
         }
 
+        auto RCSResourceAttributes::erase(const_iterator pos) -> iterator
+        {
+            return iterator{ m_values.erase(pos.m_cur) };
+        }
+
         bool RCSResourceAttributes::contains(const std::string& key) const
         {
             return m_values.find(key) != m_values.end();
diff --git a/service/resource-encapsulation/src/common/primitiveResource/src/ResponseStatement.cpp b/service/resource-encapsulation/src/common/primitiveResource/src/ResponseStatement.cpp
deleted file mode 100644 (file)
index 444547a..0000000
+++ /dev/null
@@ -1,82 +0,0 @@
-//******************************************************************
-//
-// 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 <ResponseStatement.h>
-
-#include <ResourceAttributesConverter.h>
-
-namespace OIC
-{
-    namespace Service
-    {
-        ResponseStatement ResponseStatement::create(const OC::OCRepresentation& ocRepresentation)
-        {
-            return ResponseStatement::create(
-                    ResourceAttributesConverter::fromOCRepresentation(ocRepresentation));
-        }
-
-        ResponseStatement ResponseStatement::create(RCSResourceAttributes&& attrs)
-        {
-            return ResponseStatement(std::move(attrs));
-        }
-
-        ResponseStatement::ResponseStatement(const RCSResourceAttributes& attrs) :
-                m_attrs{ attrs }
-        {
-        }
-
-        ResponseStatement::ResponseStatement(RCSResourceAttributes&& attrs) :
-                m_attrs{ std::move(attrs) }
-        {
-        }
-
-        ResponseStatement::ResponseStatement(RCSResourceAttributes&& attrs, std::string&& uri,
-                std::vector< std::string >&& resourceTypes,
-                std::vector< std::string >&& resourceInterfaces) :
-                m_attrs{ std::move(attrs) },
-                m_uri{ std::move(uri) },
-                m_resourceTypes { std::move(resourceTypes) },
-                m_resourceInterfaces{ std::move(resourceInterfaces) }
-        {
-        }
-
-        std::string ResponseStatement::getUri() const
-        {
-            return m_uri;
-        }
-
-        std::vector< std::string > ResponseStatement::getResourceTypes() const
-        {
-            return m_resourceTypes;
-        }
-
-        std::vector< std::string > ResponseStatement::getResourceInterfaces() const
-        {
-            return m_resourceInterfaces;
-        }
-
-        const RCSResourceAttributes& ResponseStatement::getAttributes() const
-        {
-            return m_attrs;
-        }
-
-    }
-}
-
index 15e8230..b1aa1a0 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#include <UnitTestHelper.h>
+#include "UnitTestHelper.h"
 
-#include <PrimitiveResourceImpl.h>
-#include <AssertUtils.h>
+#include "PrimitiveResourceImpl.h"
+#include "AssertUtils.h"
 
-#include <OCResource.h>
-#include <OCPlatform.h>
+#include "OCResource.h"
+#include "OCPlatform.h"
 
 using namespace OIC::Service;
 
@@ -35,12 +35,13 @@ class FakeOCResource
 public:
     virtual ~FakeOCResource() {};
 
-    virtual OCStackResult get(const OC::QueryParamsMap&, OC::GetCallback) = 0;
+    virtual OCStackResult get(const std::string&, const std::string&,
+            const OC::QueryParamsMap&, OC::GetCallback) = 0;
 
     virtual OCStackResult put(
             const OC::OCRepresentation&, const OC::QueryParamsMap&, OC::PutCallback) = 0;
 
-    virtual OCStackResult post(
+    virtual OCStackResult post(const std::string&, const std::string&,
             const OC::OCRepresentation&, const OC::QueryParamsMap&, OC::PostCallback) = 0;
 
     virtual OCStackResult observe(
@@ -88,29 +89,30 @@ TEST_F(PrimitiveResourceTest, RequestGetThrowsOCResourceGetReturnsNotOK)
     ASSERT_THROW(resource->requestGet(PrimitiveResource::GetCallback()), RCSPlatformException);
 }
 
-TEST_F(PrimitiveResourceTest, RequestSetInvokesOCResourcePut)
+TEST_F(PrimitiveResourceTest, RequestSetInvokesOCResourcePost)
 {
-    mocks.ExpectCall(fakeResource, FakeOCResource::put).Return(OC_STACK_OK);
+    mocks.ExpectCall(fakeResource, FakeOCResource::post).Return(OC_STACK_OK);
 
     resource->requestSet(RCSResourceAttributes{ }, PrimitiveResource::SetCallback());
 }
 
-TEST_F(PrimitiveResourceTest, RequestSetThrowsOCResourcePutReturnsNotOK)
+TEST_F(PrimitiveResourceTest, RequestSetThrowsOCResourcePostReturnsNotOK)
 {
-    mocks.OnCall(fakeResource, FakeOCResource::put).Return(OC_STACK_ERROR);
+    mocks.OnCall(fakeResource, FakeOCResource::post).Return(OC_STACK_ERROR);
 
     ASSERT_THROW(resource->requestSet(RCSResourceAttributes{ }, PrimitiveResource::SetCallback()),
             RCSPlatformException);
 }
 
-TEST_F(PrimitiveResourceTest, RequestSetPassResourceAttributesToOCResourcePut)
+TEST_F(PrimitiveResourceTest, RequestSetPassResourceAttributesToOCResourcePost)
 {
     constexpr int value{ -200 };
 
     RCSResourceAttributes attrs;
 
-    mocks.ExpectCall(fakeResource, FakeOCResource::put).Match(
-            [](const OC::OCRepresentation& ocRep, const OC::QueryParamsMap&, OC::PutCallback)
+    mocks.ExpectCall(fakeResource, FakeOCResource::post).Match(
+            [](const std::string&, const std::string&, const OC::OCRepresentation& ocRep,
+                    const OC::QueryParamsMap&, OC::PutCallback)
             {
                 return ocRep.getValue<int>(KEY) == value;
             }
@@ -156,7 +158,7 @@ TEST_F(PrimitiveResourceTest, ResponseStatementHasSameValuesWithOCRepresentation
     constexpr int value{ 1999 };
 
     mocks.OnCall(fakeResource, FakeOCResource::get).Do(
-            [](const OC::QueryParamsMap&, OC::GetCallback cb)
+            [](const std::string&, const std::string&, const OC::QueryParamsMap&, OC::GetCallback cb)
             {
                 OC::OCRepresentation ocRep;
                 ocRep[KEY] = value;
index 018e538..b34d5ad 100644 (file)
@@ -43,7 +43,7 @@ namespace OIC
                 {
                     static constexpr char DEFAULT_ENTER_STR[]{ "IN" };
 
-                    OC_LOG_V(m_level, m_tag, "%s %s", m_scopeName, DEFAULT_ENTER_STR);
+                    OIC_LOG_V(m_level, m_tag, "%s %s", m_scopeName, DEFAULT_ENTER_STR);
                 }
 
                 ~ScopeLogger()
@@ -52,12 +52,12 @@ namespace OIC
 
                     if (std::uncaught_exception())
                     {
-                        OC_LOG_V(m_level, m_tag, "%s %s by stack unwinding (uncaught exception)",
+                        OIC_LOG_V(m_level, m_tag, "%s %s by stack unwinding (uncaught exception)",
                                 m_scopeName, DEFAULT_EXIT_STR);
                     }
                     else
                     {
-                        OC_LOG_V(m_level, m_tag, "%s %s", m_scopeName, DEFAULT_EXIT_STR);
+                        OIC_LOG_V(m_level, m_tag, "%s %s", m_scopeName, DEFAULT_EXIT_STR);
                     }
                 }
 
index cfb7bc9..c34f876 100644 (file)
@@ -42,6 +42,12 @@ namespace OIC
             DevicePresence();
             ~DevicePresence();
 
+            DevicePresence(DevicePresence &&) = delete;
+            DevicePresence(const DevicePresence &) = delete;
+
+            DevicePresence & operator = (DevicePresence &&) = delete;
+            DevicePresence & operator = (const DevicePresence &) = delete;
+
             void initializeDevicePresence(PrimitiveResourcePtr pResource);
 
             void addPresenceResource(ResourcePresence * rPresence);
index 0176c7b..6cc97b7 100644 (file)
@@ -56,13 +56,13 @@ namespace OIC
 
         DevicePresencePtr DeviceAssociation::findDevice(const std::string & address)
         {
-            OC_LOG_V(DEBUG,BROKER_TAG,"findDevice()");
+            OIC_LOG_V(DEBUG,BROKER_TAG,"findDevice()");
             DevicePresencePtr retDevice = nullptr;
             for(auto it : s_deviceList)
             {
                 if(address == it->getAddress())
                 {
-                    OC_LOG_V(DEBUG,BROKER_TAG,"find device in deviceList");
+                    OIC_LOG_V(DEBUG,BROKER_TAG,"find device in deviceList");
                     retDevice = it;
                     break;
                 }
@@ -73,22 +73,22 @@ namespace OIC
 
         void DeviceAssociation::addDevice(DevicePresencePtr dPresence)
         {
-            OC_LOG_V(DEBUG,BROKER_TAG,"addDevice()");
+            OIC_LOG_V(DEBUG,BROKER_TAG,"addDevice()");
             DevicePresencePtr foundDevice = findDevice(dPresence->getAddress());
             if(foundDevice == nullptr)
             {
-                OC_LOG_V(DEBUG,BROKER_TAG,"add device in deviceList");
+                OIC_LOG_V(DEBUG,BROKER_TAG,"add device in deviceList");
                 s_deviceList.push_back(dPresence);
             }
         }
 
         void DeviceAssociation::removeDevice(DevicePresencePtr dPresence)
         {
-            OC_LOG_V(DEBUG,BROKER_TAG,"removeDevice()");
+            OIC_LOG_V(DEBUG,BROKER_TAG,"removeDevice()");
             DevicePresencePtr foundDevice = findDevice(dPresence->getAddress());
             if(foundDevice != nullptr)
             {
-                OC_LOG_V(DEBUG,BROKER_TAG,"remove device in deviceList");
+                OIC_LOG_V(DEBUG,BROKER_TAG,"remove device in deviceList");
                 s_deviceList.remove(foundDevice);
                 foundDevice.reset();
             }
@@ -96,7 +96,7 @@ namespace OIC
 
         bool DeviceAssociation::isEmptyDeviceList()
         {
-            OC_LOG_V(DEBUG,BROKER_TAG,"isEmptyDeviceList()");
+            OIC_LOG_V(DEBUG,BROKER_TAG,"isEmptyDeviceList()");
             return s_deviceList.empty();
         }
     } // namespace Service
index b3ada66..8d7391d 100644 (file)
@@ -41,28 +41,34 @@ namespace OIC
         {
             if(presenceSubscriber.isSubscribing())
             {
-                OC_LOG_V(DEBUG,BROKER_TAG,"unsubscribed presence.");
-                presenceSubscriber.unsubscribe();
+                OIC_LOG_V(DEBUG,BROKER_TAG,"unsubscribed presence.");
+                try
+                {
+                    presenceSubscriber.unsubscribe();
+                } catch (std::exception & e)
+                {
+                    OIC_LOG_V(DEBUG,BROKER_TAG,"unsubscribed presence : %s", e.what());
+                }
             }
             resourcePresenceList.clear();
-            OC_LOG_V(DEBUG,BROKER_TAG,"destroy Timer.");
+            OIC_LOG_V(DEBUG,BROKER_TAG,"destroy Timer.");
         }
 
         void DevicePresence::initializeDevicePresence(PrimitiveResourcePtr pResource)
         {
-            OC_LOG_V(DEBUG, BROKER_TAG, "initializeDevicePresence()");
+            OIC_LOG_V(DEBUG, BROKER_TAG, "initializeDevicePresence()");
             address = pResource->getHost();
 
-            OC_LOG_V(DEBUG, BROKER_TAG, "%s",address.c_str());
+            OIC_LOG_V(DEBUG, BROKER_TAG, "%s",address.c_str());
 
             try
             {
-                OC_LOG_V(DEBUG, BROKER_TAG, "subscribe Presence");
+                OIC_LOG_V(DEBUG, BROKER_TAG, "subscribe Presence");
                 presenceSubscriber
                 = PresenceSubscriber(address, BROKER_TRANSPORT, pSubscribeRequestCB);
             } catch(RCSPlatformException &e)
             {
-                OC_LOG_V(DEBUG, BROKER_TAG,
+                OIC_LOG_V(DEBUG, BROKER_TAG,
                         "exception in subscribe Presence %s", e.getReason().c_str());
                 throw;
             }
@@ -82,25 +88,25 @@ namespace OIC
 
         const std::string DevicePresence::getAddress() const
         {
-            OC_LOG_V(DEBUG, BROKER_TAG, "getAddress()");
+            OIC_LOG_V(DEBUG, BROKER_TAG, "getAddress()");
             return address;
         }
 
         void DevicePresence::addPresenceResource(ResourcePresence * rPresence)
         {
-            OC_LOG_V(DEBUG, BROKER_TAG, "addPresenceResource()");
+            OIC_LOG_V(DEBUG, BROKER_TAG, "addPresenceResource()");
             resourcePresenceList.push_back(rPresence);
         }
 
         void DevicePresence::removePresenceResource(ResourcePresence * rPresence)
         {
-            OC_LOG_V(DEBUG, BROKER_TAG, "removePresenceResource()");
+            OIC_LOG_V(DEBUG, BROKER_TAG, "removePresenceResource()");
             resourcePresenceList.remove(rPresence);
         }
 
         void DevicePresence::changeAllPresenceMode(BROKER_MODE mode)
         {
-            OC_LOG_V(DEBUG, BROKER_TAG, "changeAllPresenceMode()");
+            OIC_LOG_V(DEBUG, BROKER_TAG, "changeAllPresenceMode()");
             if(!resourcePresenceList.empty())
             {
                 for(auto it : resourcePresenceList)
@@ -112,16 +118,16 @@ namespace OIC
 
         bool DevicePresence::isEmptyResourcePresence() const
         {
-            OC_LOG_V(DEBUG, BROKER_TAG, "isEmptyResourcePresence()");
+            OIC_LOG_V(DEBUG, BROKER_TAG, "isEmptyResourcePresence()");
             return resourcePresenceList.empty();
         }
 
         void DevicePresence::subscribeCB(OCStackResult ret,
                 const unsigned int seq, const std::string & hostAddress)
         {
-            OC_LOG_V(DEBUG, BROKER_TAG, "subscribeCB()");
-            OC_LOG_V(DEBUG, BROKER_TAG, "Received presence CB from: %s",hostAddress.c_str());
-            OC_LOG_V(DEBUG, BROKER_TAG, "In subscribeCB: %d",ret);
+            OIC_LOG_V(DEBUG, BROKER_TAG, "subscribeCB()");
+            OIC_LOG_V(DEBUG, BROKER_TAG, "Received presence CB from: %s",hostAddress.c_str());
+            OIC_LOG_V(DEBUG, BROKER_TAG, "In subscribeCB: %d",ret);
 
             if(isRunningTimeOut)
             {
@@ -136,9 +142,9 @@ namespace OIC
                 case OC_STACK_RESOURCE_CREATED:
                 case OC_STACK_CONTINUE:
                 {
-                    OC_LOG_V(DEBUG, BROKER_TAG, "SEQ# %d",seq);
+                    OIC_LOG_V(DEBUG, BROKER_TAG, "SEQ# %d",seq);
                     setDeviceState(DEVICE_STATE::ALIVE);
-                    OC_LOG_V(DEBUG, BROKER_TAG, "device state : %d",
+                    OIC_LOG_V(DEBUG, BROKER_TAG, "device state : %d",
                             (int)getDeviceState());
                     changeAllPresenceMode(BROKER_MODE::DEVICE_PRESENCE_MODE);
                     presenceTimerHandle
@@ -159,7 +165,7 @@ namespace OIC
                 }
                 default:
                 {
-                    OC_LOG_V(DEBUG, BROKER_TAG, "Presence Lost Signal because unknown type");
+                    OIC_LOG_V(DEBUG, BROKER_TAG, "Presence Lost Signal because unknown type");
                     setDeviceState(DEVICE_STATE::LOST_SIGNAL);
                     changeAllPresenceMode(BROKER_MODE::NON_PRESENCE_MODE);
                     break;
@@ -169,11 +175,11 @@ namespace OIC
 
         void DevicePresence::timeOutCB(TimerID /*id*/)
         {
-            OC_LOG_V(DEBUG,BROKER_TAG,"timeOutCB()");
+            OIC_LOG_V(DEBUG,BROKER_TAG,"timeOutCB()");
             std::unique_lock<std::mutex> lock(timeoutMutex);
             isRunningTimeOut = true;
 
-            OC_LOG_V(DEBUG, BROKER_TAG,
+            OIC_LOG_V(DEBUG, BROKER_TAG,
                     "Timeout execution. will be discard after receiving cb message");
             setDeviceState(DEVICE_STATE::LOST_SIGNAL);
             changeAllPresenceMode(BROKER_MODE::NON_PRESENCE_MODE);
index fe1c852..2e3c3f9 100644 (file)
@@ -36,15 +36,13 @@ namespace OIC
         {
             if(s_presenceList != nullptr)
             {
-                OC_LOG_V(DEBUG, BROKER_TAG, "clear the ResourcePresenceList.");
+                OIC_LOG_V(DEBUG, BROKER_TAG, "clear the ResourcePresenceList.");
                 s_presenceList->erase(s_presenceList->begin(), s_presenceList->end());
-                s_presenceList->clear();
             }
             if(s_brokerIDMap != nullptr)
             {
-                OC_LOG_V(DEBUG, BROKER_TAG, "clear the brokerIDMap.");
+                OIC_LOG_V(DEBUG, BROKER_TAG, "clear the brokerIDMap.");
                 s_brokerIDMap->erase(s_brokerIDMap->begin(), s_brokerIDMap->end());
-                s_brokerIDMap->clear();
             }
         }
 
@@ -65,7 +63,7 @@ namespace OIC
 
         BrokerID ResourceBroker::hostResource(PrimitiveResourcePtr pResource, BrokerCB cb)
         {
-            OC_LOG_V(DEBUG, BROKER_TAG, "hostResource().");
+            OIC_LOG_V(DEBUG, BROKER_TAG, "hostResource().");
             if(pResource == nullptr || cb == nullptr || cb == NULL)
             {
                 throw InvalidParameterException("[hostResource] input parameter(PrimitiveResource or BrokerCB) is Invalid");
@@ -76,12 +74,12 @@ namespace OIC
             ResourcePresencePtr presenceItem = findResourcePresence(pResource);
             if(presenceItem == nullptr)
             {
-                OC_LOG_V(DEBUG, BROKER_TAG, "Not found any Handled Resource.");
-                OC_LOG_V(DEBUG, BROKER_TAG, "Create New Resource Presence Handler.");
+                OIC_LOG_V(DEBUG, BROKER_TAG, "Not found any Handled Resource.");
+                OIC_LOG_V(DEBUG, BROKER_TAG, "Create New Resource Presence Handler.");
 
                 try
                 {
-                    OC_LOG_V(DEBUG, BROKER_TAG, "create the ResourcePresence.");
+                    OIC_LOG_V(DEBUG, BROKER_TAG, "create the ResourcePresence.");
                     presenceItem.reset(new ResourcePresence());
                     presenceItem->initializeResourcePresence(pResource);
                 }catch(RCSPlatformException &e)
@@ -90,11 +88,11 @@ namespace OIC
                 }
                 if(s_presenceList != nullptr)
                 {
-                    OC_LOG_V(DEBUG, BROKER_TAG, "push the ResourcePresence in presenceList.");
+                    OIC_LOG_V(DEBUG, BROKER_TAG, "push the ResourcePresence in presenceList.");
                     s_presenceList->push_back(presenceItem);
                 }
             }
-            OC_LOG_V(DEBUG, BROKER_TAG, "add the BrokerRequester in ResourcePresence.");
+            OIC_LOG_V(DEBUG, BROKER_TAG, "add the BrokerRequester in ResourcePresence.");
             presenceItem->addBrokerRequester(retID, cb);
 
             BrokerCBResourcePair pair(presenceItem, cb);
@@ -106,12 +104,12 @@ namespace OIC
 
         void ResourceBroker::cancelHostResource(BrokerID brokerId)
         {
-            OC_LOG_V(DEBUG,BROKER_TAG,"cancelHostResource().");
+            OIC_LOG_V(DEBUG,BROKER_TAG,"cancelHostResource().");
             if(brokerId == 0)
             {
                 // input parameter is wrong.
                 // hostResource never return value 0;
-                OC_LOG_V(DEBUG,BROKER_TAG,"brokerId is zero.");
+                OIC_LOG_V(DEBUG,BROKER_TAG,"brokerId is zero.");
                 throw InvalidParameterException("[cancelHostResource] brokerId is invalid.");
             }
 
@@ -119,7 +117,7 @@ namespace OIC
             if(it == s_brokerIDMap->end())
             {
                 // not found requested brokerId in BrokerMap;
-                OC_LOG_V(DEBUG,BROKER_TAG,"brokerId is not found in brokerIDMap.");
+                OIC_LOG_V(DEBUG,BROKER_TAG,"brokerId is not found in brokerIDMap.");
                 throw InvalidParameterException("[cancelHostResource] brokerId is not found in brokerIDMap.");
             }
             else
@@ -130,7 +128,7 @@ namespace OIC
 
                 if(presenceItem->isEmptyRequester())
                 {
-                    OC_LOG_V(DEBUG,BROKER_TAG,"remove resourcePresence in presenceList because it is not including any requester info.");
+                    OIC_LOG_V(DEBUG,BROKER_TAG,"remove resourcePresence in presenceList because it is not including any requester info.");
                     s_presenceList->remove(presenceItem);
                 }
             }
@@ -138,10 +136,10 @@ namespace OIC
 
         BROKER_STATE ResourceBroker::getResourceState(BrokerID brokerId)
         {
-            OC_LOG_V(DEBUG,BROKER_TAG,"getResourceState().");
+            OIC_LOG_V(DEBUG,BROKER_TAG,"getResourceState().");
             if(brokerId == 0)
             {
-                OC_LOG_V(DEBUG,BROKER_TAG,"brokerId is zero.");
+                OIC_LOG_V(DEBUG,BROKER_TAG,"brokerId is zero.");
                 throw InvalidParameterException("[getResourceState] input BrokerID is Invalid");
             }
 
@@ -151,7 +149,7 @@ namespace OIC
             if(it == s_brokerIDMap->end())
             {
                 // not found requested brokerId in BrokerMap;
-                OC_LOG_V(DEBUG,BROKER_TAG,"brokerId is not found in brokerIDMap.");
+                OIC_LOG_V(DEBUG,BROKER_TAG,"brokerId is not found in brokerIDMap.");
                 throw InvalidParameterException("[getResourceState] input BrokerID is unknown ID");
             }
             else
@@ -165,7 +163,7 @@ namespace OIC
 
         BROKER_STATE ResourceBroker::getResourceState(PrimitiveResourcePtr pResource)
         {
-            OC_LOG_V(DEBUG,BROKER_TAG,"getResourceState().");
+            OIC_LOG_V(DEBUG,BROKER_TAG,"getResourceState().");
             if(pResource == nullptr)
             {
                 throw InvalidParameterException("[getResourceState] input PrimitiveResource is Invalid");
@@ -184,22 +182,22 @@ namespace OIC
 
         void ResourceBroker::initializeResourceBroker()
         {
-            OC_LOG_V(DEBUG,BROKER_TAG,"initializeResourceBroker().");
+            OIC_LOG_V(DEBUG,BROKER_TAG,"initializeResourceBroker().");
             if(s_presenceList == nullptr)
             {
-                OC_LOG_V(DEBUG,BROKER_TAG,"create the presenceList.");
+                OIC_LOG_V(DEBUG,BROKER_TAG,"create the presenceList.");
                 s_presenceList = std::unique_ptr<PresenceList>(new PresenceList);
             }
             if(s_brokerIDMap == nullptr)
             {
-                OC_LOG_V(DEBUG,BROKER_TAG,"create the brokerIDMap.");
+                OIC_LOG_V(DEBUG,BROKER_TAG,"create the brokerIDMap.");
                 s_brokerIDMap = std::unique_ptr<BrokerIDMap>(new BrokerIDMap);
             }
         }
 
         ResourcePresencePtr ResourceBroker::findResourcePresence(PrimitiveResourcePtr pResource)
         {
-            OC_LOG_V(DEBUG,BROKER_TAG,"findResourcePresence().");
+            OIC_LOG_V(DEBUG,BROKER_TAG,"findResourcePresence().");
             ResourcePresencePtr retResource(nullptr);
 
             if(s_presenceList->empty() != true)
@@ -220,7 +218,7 @@ namespace OIC
 
         BrokerID ResourceBroker::generateBrokerID()
         {
-            OC_LOG_V(DEBUG,BROKER_TAG,"generateBrokerID().");
+            OIC_LOG_V(DEBUG,BROKER_TAG,"generateBrokerID().");
             BrokerID retID = 0;
             srand(time(NULL));
 
index bb80de3..7174ba6 100644 (file)
@@ -40,7 +40,7 @@ using namespace OIC::Service;
     void getCallback(const HeaderOptions &hos, const ResponseStatement& rep,
             int eCode, std::weak_ptr<ResourcePresence> this_ptr)
     {
-        OC_LOG_V(DEBUG,BROKER_TAG,"getCallback().\n");
+        OIC_LOG_V(DEBUG,BROKER_TAG,"getCallback().\n");
         std::shared_ptr<ResourcePresence> Ptr = this_ptr.lock();
         if(Ptr)
         {
@@ -49,7 +49,7 @@ using namespace OIC::Service;
     }
     void timeOutCallback(unsigned int msg, std::weak_ptr<ResourcePresence> this_ptr)
     {
-        OC_LOG_V(DEBUG,BROKER_TAG,"timeOutCallback().\n");
+        OIC_LOG_V(DEBUG,BROKER_TAG,"timeOutCallback().\n");
         std::shared_ptr<ResourcePresence> Ptr = this_ptr.lock();
         if(Ptr)
         {
@@ -71,7 +71,7 @@ namespace OIC
 
         void ResourcePresence::initializeResourcePresence(PrimitiveResourcePtr pResource)
         {
-            OC_LOG_V(DEBUG,BROKER_TAG,"initializeResourcePresence().\n");
+            OIC_LOG_V(DEBUG,BROKER_TAG,"initializeResourcePresence().\n");
             pGetCB = std::bind(getCallback, std::placeholders::_1, std::placeholders::_2,
                     std::placeholders::_3, std::weak_ptr<ResourcePresence>(shared_from_this()));
             pTimeoutCB = std::bind(timeOutCallback, std::placeholders::_1,
@@ -84,7 +84,7 @@ namespace OIC
             (new std::list<BrokerRequesterInfoPtr>);
 
             timeoutHandle = expiryTimer.post(BROKER_SAFE_MILLISECOND, pTimeoutCB);
-            OC_LOG_V(DEBUG,BROKER_TAG,"initializeResourcePresence::requestGet.\n");
+            OIC_LOG_V(DEBUG,BROKER_TAG,"initializeResourcePresence::requestGet.\n");
             primitiveResource->requestGet(pGetCB);
 
             registerDevicePresence();
@@ -115,14 +115,14 @@ namespace OIC
 
         void ResourcePresence::addBrokerRequester(BrokerID _id, BrokerCB _cb)
         {
-            OC_LOG_V(DEBUG,BROKER_TAG,"addBrokerRequester().\n");
+            OIC_LOG_V(DEBUG,BROKER_TAG,"addBrokerRequester().\n");
             requesterList->push_back(
                     std::make_shared<BrokerRequesterInfo>(BrokerRequesterInfo(_id, _cb)));
         }
 
         void ResourcePresence::removeAllBrokerRequester()
         {
-            OC_LOG_V(DEBUG,BROKER_TAG,"removeAllBrokerRequester().\n");
+            OIC_LOG_V(DEBUG,BROKER_TAG,"removeAllBrokerRequester().\n");
             if(requesterList != nullptr)
             {
                 requesterList->erase(requesterList->begin(), requesterList->end());
@@ -131,13 +131,13 @@ namespace OIC
 
         void ResourcePresence::removeBrokerRequester(BrokerID _id)
         {
-            OC_LOG_V(DEBUG,BROKER_TAG,"removeBrokerRequester().\n");
+            OIC_LOG_V(DEBUG,BROKER_TAG,"removeBrokerRequester().\n");
             std::list<BrokerRequesterInfoPtr>::iterator iter = requesterList->begin();
             for(; iter != requesterList->end(); ++iter)
             {
                 if(iter->get()->brokerId == _id)
                 {
-                    OC_LOG_V(DEBUG,BROKER_TAG,"find broker-id in requesterList.\n");
+                    OIC_LOG_V(DEBUG,BROKER_TAG,"find broker-id in requesterList.\n");
                     requesterList->erase(iter);
                     break;
                 }
@@ -146,25 +146,25 @@ namespace OIC
 
         bool ResourcePresence::isEmptyRequester() const
         {
-            OC_LOG_V(DEBUG,BROKER_TAG,"isEmptyRequester().\n");
+            OIC_LOG_V(DEBUG,BROKER_TAG,"isEmptyRequester().\n");
             return (requesterList!=nullptr)?requesterList->empty():true;
         }
 
         int ResourcePresence::requesterListSize() const {
-            OC_LOG_V(DEBUG,BROKER_TAG,"requesterListSize().\n");
+            OIC_LOG_V(DEBUG,BROKER_TAG,"requesterListSize().\n");
             return (requesterList!=nullptr)?requesterList->size():0;
         }
 
         void ResourcePresence::requestResourceState() const
         {
-            OC_LOG_V(DEBUG,BROKER_TAG,"requestResourceState().\n");
+            OIC_LOG_V(DEBUG,BROKER_TAG,"requestResourceState().\n");
             primitiveResource->requestGet(pGetCB);
-            OC_LOG_V(DEBUG, BROKER_TAG, "Request Get\n");
+            OIC_LOG_V(DEBUG, BROKER_TAG, "Request Get\n");
         }
 
         void ResourcePresence::registerDevicePresence()
         {
-            OC_LOG_V(DEBUG,BROKER_TAG,"registerDevicePresence().\n");
+            OIC_LOG_V(DEBUG,BROKER_TAG,"registerDevicePresence().\n");
             std::string deviceAddress = primitiveResource->getHost();
 
             DevicePresencePtr foundDevice
@@ -187,7 +187,7 @@ namespace OIC
 
         void ResourcePresence::executeAllBrokerCB(BROKER_STATE changedState)
         {
-            OC_LOG_V(DEBUG, BROKER_TAG, "executeAllBrokerCB().\n");
+            OIC_LOG_V(DEBUG, BROKER_TAG, "executeAllBrokerCB().\n");
             if(state != changedState)
             {
                 setResourcestate(changedState);
@@ -204,14 +204,14 @@ namespace OIC
 
         void ResourcePresence::setResourcestate(BROKER_STATE _state)
         {
-            OC_LOG_V(DEBUG, BROKER_TAG, "setResourcestate().\n");
+            OIC_LOG_V(DEBUG, BROKER_TAG, "setResourcestate().\n");
             this->state = _state;
         }
 
         void ResourcePresence::timeOutCB(unsigned int /*msg*/)
         {
-            OC_LOG_V(DEBUG, BROKER_TAG, "timeOutCB()");
-            OC_LOG_V(DEBUG, BROKER_TAG, "waiting for terminate getCB\n");
+            OIC_LOG_V(DEBUG, BROKER_TAG, "timeOutCB()");
+            OIC_LOG_V(DEBUG, BROKER_TAG, "waiting for terminate getCB\n");
             std::unique_lock<std::mutex> lock(cbMutex);
 
             time_t currentTime;
@@ -224,7 +224,7 @@ namespace OIC
                 return;
             }
             this->isWithinTime = false;
-            OC_LOG_V(DEBUG, BROKER_TAG,
+            OIC_LOG_V(DEBUG, BROKER_TAG,
                     "Timeout execution. will be discard after receiving cb message.\n");
 
             executeAllBrokerCB(BROKER_STATE::LOST_SIGNAL);
@@ -233,7 +233,7 @@ namespace OIC
 
         void ResourcePresence::pollingCB(unsigned int /*msg*/)
         {
-            OC_LOG_V(DEBUG, BROKER_TAG, "pollingCB().\n");
+            OIC_LOG_V(DEBUG, BROKER_TAG, "pollingCB().\n");
             if(this->requesterList->size() != 0)
             {
                 this->requestResourceState();
@@ -244,8 +244,8 @@ namespace OIC
         void ResourcePresence::getCB(const HeaderOptions & /*hos*/,
                 const ResponseStatement & /*rep*/, int eCode)
         {
-            OC_LOG_V(DEBUG, BROKER_TAG, "getCB().\n");
-            OC_LOG_V(DEBUG, BROKER_TAG, "waiting for terminate TimeoutCB.\n");
+            OIC_LOG_V(DEBUG, BROKER_TAG, "getCB().\n");
+            OIC_LOG_V(DEBUG, BROKER_TAG, "waiting for terminate TimeoutCB.\n");
             std::unique_lock<std::mutex> lock(cbMutex);
 
             time_t currentTime;
@@ -269,7 +269,7 @@ namespace OIC
 
         void ResourcePresence::verifiedGetResponse(int eCode)
         {
-            OC_LOG_V(DEBUG, BROKER_TAG, "verifiedGetResponse().\n");
+            OIC_LOG_V(DEBUG, BROKER_TAG, "verifiedGetResponse().\n");
             BROKER_STATE verifiedState = BROKER_STATE::NONE;
             switch(eCode)
             {
@@ -293,24 +293,24 @@ namespace OIC
             }
 
             executeAllBrokerCB(verifiedState);
-            OC_LOG_V(DEBUG, BROKER_TAG, "resource state : %d",(int)state);
+            OIC_LOG_V(DEBUG, BROKER_TAG, "resource state : %d",(int)state);
         }
 
         const PrimitiveResourcePtr ResourcePresence::getPrimitiveResource() const
         {
-            OC_LOG_V(DEBUG, BROKER_TAG, "getPrimitiveResource()\n");
+            OIC_LOG_V(DEBUG, BROKER_TAG, "getPrimitiveResource()\n");
             return primitiveResource;
         }
 
         BROKER_STATE ResourcePresence::getResourceState() const
         {
-            OC_LOG_V(DEBUG, BROKER_TAG, "getResourceState()\n");
+            OIC_LOG_V(DEBUG, BROKER_TAG, "getResourceState()\n");
             return state;
         }
 
         void ResourcePresence::changePresenceMode(BROKER_MODE newMode)
         {
-            OC_LOG_V(DEBUG, BROKER_TAG, "changePresenceMode()\n");
+            OIC_LOG_V(DEBUG, BROKER_TAG, "changePresenceMode()\n");
             if(newMode != mode)
             {
                 expiryTimer.cancel(timeoutHandle);
index b1429c6..025aca6 100644 (file)
@@ -43,6 +43,11 @@ namespace OIC
                 DataCache();
                 ~DataCache();
 
+                DataCache(const DataCache &) = default;
+                DataCache(DataCache &&) = default;
+                DataCache & operator = (const DataCache &) = default;
+                DataCache & operator = (DataCache &&) = default;
+
                 void initializeDataCache(PrimitiveResourcePtr pResource);
 
                 CacheID addSubscriber(CacheCB func, REPORT_FREQUENCY rf, long repeatTime);
@@ -85,7 +90,7 @@ namespace OIC
 
             public:
                 void onObserve(const HeaderOptions &_hos,
-                               const ResponseStatement &_rep, int _result, int _seq);
+                               const ResponseStatement &_rep, int _result, unsigned int _seq);
                 void onGet(const HeaderOptions &_hos, const ResponseStatement &_rep, int _result);
             private:
                 void onTimeOut(const unsigned int timerID);
index e21973c..51b3536 100644 (file)
@@ -40,12 +40,12 @@ namespace OIC
         {
             void verifyObserveCB(
                 const HeaderOptions &_hos, const ResponseStatement &_rep,
-                int _result, int _seq, std::weak_ptr<DataCache> rpPtr)
+                int _result, unsigned int _seq, std::weak_ptr<DataCache> rpPtr)
             {
-                std::shared_ptr<DataCache> Ptr = rpPtr.lock();
-                if (Ptr)
+                std::shared_ptr<DataCache> ptr = rpPtr.lock();
+                if (ptr)
                 {
-                    Ptr->onObserve(_hos, _rep, _result, _seq);
+                    ptr->onObserve(_hos, _rep, _result, _seq);
                 }
             }
 
@@ -100,7 +100,7 @@ namespace OIC
                 subscriberList.release();
             }
 
-            if (mode == CACHE_MODE::OBSERVE)
+            if (sResource->isObservable())
             {
                 try
                 {
@@ -184,7 +184,7 @@ namespace OIC
 
         const PrimitiveResourcePtr DataCache::getPrimitiveResource() const
         {
-            return (sResource != nullptr) ? sResource : nullptr;
+            return sResource;
         }
 
         const RCSResourceAttributes DataCache::getCachedData() const
@@ -203,7 +203,7 @@ namespace OIC
         }
 
         void DataCache::onObserve(const HeaderOptions & /*_hos*/,
-                                  const ResponseStatement &_rep, int _result, int _seq)
+                                  const ResponseStatement &_rep, int _result, unsigned int _seq)
         {
 
             if (_result != OC_STACK_OK || _rep.getAttributes().empty() || lastSequenceNum > _seq)
index 41c3e6a..41029b7 100644 (file)
@@ -51,6 +51,8 @@ class DataCacheTest : public TestWithMock
         {
             TestWithMock::SetUp();
             pResource = PrimitiveResource::Ptr(mocks.Mock< PrimitiveResource >(), [](PrimitiveResource *) {});
+
+            mocks.OnCall(pResource.get(), PrimitiveResource::isObservable).Return(false);
             cacheHandler.reset(new DataCache());
             cb = ([](std::shared_ptr<PrimitiveResource >, const RCSResourceAttributes &)->OCStackResult {return OC_STACK_OK;});
         }
@@ -95,7 +97,7 @@ TEST_F(DataCacheTest, initializeDataCache_normalCaseObservable)
         OIC::Service::HeaderOptions hos;
         OIC::Service::RCSResourceAttributes attr;
         OIC::Service::ResponseStatement rep(attr);
-        int seq;
+        int seq = 0;
         callback(hos, rep, OC_STACK_OK, seq);
         return;
     }
index 14f3f40..5bf9f74 100644 (file)
@@ -41,6 +41,7 @@ class ResourceCacheManagerTest : public TestWithMock
             TestWithMock::SetUp();
             cacheInstance = ResourceCacheManager::getInstance();
             pResource = PrimitiveResource::Ptr(mocks.Mock< PrimitiveResource >(), [](PrimitiveResource *) {});
+            mocks.OnCall(pResource.get(), PrimitiveResource::isObservable).Return(false);
             cb = ([](std::shared_ptr<PrimitiveResource >, const RCSResourceAttributes &)->OCStackResult {return OC_STACK_OK;});
         }
 
old mode 100755 (executable)
new mode 100644 (file)
index 62b16b7..a44f5d0
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 #include "RCSDiscoveryManager.h"
-#include "RCSDiscoveryManagerImpl.h"
-
-#define TAG "RCSDiscoveryManager"
 
-namespace OIC {
-    namespace Service {
+#include "RCSDiscoveryManagerImpl.h"
 
+namespace OIC
+{
+    namespace Service
+    {
         RCSDiscoveryManager::DiscoveryTask::DiscoveryTask(unsigned int id) :
-                m_id{ id }
-        {
-        }
+                m_id { id } {}
 
-        RCSDiscoveryManager::DiscoveryTask::~DiscoveryTask()
-        {
-            cancel();
-        }
+        RCSDiscoveryManager::DiscoveryTask::~DiscoveryTask() = default;
 
         bool RCSDiscoveryManager::DiscoveryTask::isCanceled()
         {
-            return RCSDiscoveryManagerImpl::getInstance()->isCanceled(m_id);
+            return m_id == RCSDiscoveryManagerImpl::INVALID_ID;
         }
 
         void RCSDiscoveryManager::DiscoveryTask::cancel()
         {
+            if (isCanceled())
+                return;
+
             RCSDiscoveryManagerImpl::getInstance()->cancel(m_id);
+            m_id = RCSDiscoveryManagerImpl::INVALID_ID;
         }
 
-        RCSDiscoveryManager* RCSDiscoveryManager::getInstance() {
+        RCSDiscoveryManager* RCSDiscoveryManager::getInstance()
+        {
             static RCSDiscoveryManager instance;
             return &instance;
         }
 
-        std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> RCSDiscoveryManager::discoverResource
-        (const RCSAddress& address, ResourceDiscoveredCallback cb) {
-            return discoverResourceByType(address, OC_RSRVD_WELL_KNOWN_URI, "",
+        RCSDiscoveryManager::DiscoveryTask::Ptr RCSDiscoveryManager::discoverResource(
+                const RCSAddress& address, ResourceDiscoveredCallback cb)
+        {
+            return discoverResourceByType(address, OC_RSRVD_WELL_KNOWN_URI,
+                    RCSDiscoveryManagerImpl::ALL_RESOURCE_TYPE, std::move(cb));
+        }
+
+        RCSDiscoveryManager::DiscoveryTask::Ptr RCSDiscoveryManager::discoverResource(
+                const RCSAddress& address, const std::string& relativeUri,
+                ResourceDiscoveredCallback cb)
+        {
+            return discoverResourceByType(address, relativeUri,
+                    RCSDiscoveryManagerImpl::ALL_RESOURCE_TYPE, std::move(cb));
+        }
+
+        RCSDiscoveryManager::DiscoveryTask::Ptr RCSDiscoveryManager::discoverResourceByType(
+                const RCSAddress& address, const std::string& resourceType,
+                ResourceDiscoveredCallback cb)
+        {
+            return discoverResourceByType(address, OC_RSRVD_WELL_KNOWN_URI, resourceType,
                     std::move(cb));
         }
 
-        std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> RCSDiscoveryManager::discoverResource
-        (const RCSAddress& address, const std::string& relativeURI, ResourceDiscoveredCallback cb) {
-            return discoverResourceByType(address, relativeURI, "", std::move(cb));
+        RCSDiscoveryManager::DiscoveryTask::Ptr RCSDiscoveryManager::discoverResourceByTypes(
+                const RCSAddress& address, const std::vector< std::string >& resourceTypes,
+                ResourceDiscoveredCallback cb)
+        {
+            return discoverResourceByTypes(address, OC_RSRVD_WELL_KNOWN_URI, resourceTypes,
+                    std::move(cb));
         }
 
-        std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> RCSDiscoveryManager::discoverResourceByType(
-                const RCSAddress& address, const std::string& resourceType, ResourceDiscoveredCallback cb) {
-            return discoverResourceByType(address, OC_RSRVD_WELL_KNOWN_URI,
-                    resourceType, std::move(cb));
+        RCSDiscoveryManager::DiscoveryTask::Ptr RCSDiscoveryManager::discoverResourceByType(
+                const RCSAddress& address, const std::string& relativeUri,
+                const std::string& resourceType, ResourceDiscoveredCallback cb)
+        {
+            return discoverResourceByTypes(address, relativeUri,
+                    std::vector< std::string >{ resourceType }, std::move(cb));
         }
 
-        std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> RCSDiscoveryManager::discoverResourceByType(
-                const RCSAddress& address, const std::string& relativeURI,
-                const std::string& resourceType, ResourceDiscoveredCallback cb) {
-           return RCSDiscoveryManagerImpl::getInstance()->startDiscovery(address,
-                   relativeURI.empty() ? OC_RSRVD_WELL_KNOWN_URI : relativeURI,
-                   resourceType, std::move(cb));
+        RCSDiscoveryManager::DiscoveryTask::Ptr RCSDiscoveryManager::discoverResourceByTypes(
+                const RCSAddress& address, const std::string& relativeUri,
+                const std::vector< std::string >& resourceTypes, ResourceDiscoveredCallback cb)
+        {
+            return RCSDiscoveryManagerImpl::getInstance()->startDiscovery(address,
+                    relativeUri.empty() ? OC_RSRVD_WELL_KNOWN_URI : relativeUri,
+                    resourceTypes.empty() ? std::vector< std::string >{
+                            RCSDiscoveryManagerImpl::ALL_RESOURCE_TYPE } : resourceTypes,
+                    std::move(cb));
         }
     }
 }
index 6dec042..bc57893 100755 (executable)
@@ -17,7 +17,6 @@
 // limitations under the License.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#include <limits>
 
 #include "RCSDiscoveryManagerImpl.h"
 
 #include "PresenceSubscriber.h"
 #include "RCSAddressDetail.h"
 #include "RCSAddress.h"
+#include "RCSRemoteResourceObject.h"
 
 namespace
 {
-    constexpr unsigned int LIMITNUMBER = std::numeric_limits<unsigned int>::max();
-    constexpr unsigned int INTERVALTIME = 60000;
+    constexpr unsigned int POLLING_INTERVAL_TIME = 60000;
+
+    std::string makeResourceId(const std::shared_ptr< OIC::Service::PrimitiveResource >& resource)
+    {
+        return resource->getSid() + resource->getUri();
+    }
+
+    void validateTypes(const std::vector< std::string >& resourceTypes) {
+        if (resourceTypes.size() == 1) return;
+
+        for (const auto& type : resourceTypes)
+        {
+            if (type == OIC::Service::RCSDiscoveryManagerImpl::ALL_RESOURCE_TYPE)
+            {
+                throw OIC::Service::RCSBadRequestException{
+                    "resource types must have no empty string!" };
+            }
+        }
+    }
 }
 
 namespace OIC
 {
     namespace Service
     {
+        constexpr RCSDiscoveryManagerImpl::ID RCSDiscoveryManagerImpl::INVALID_ID;
+        constexpr char const* RCSDiscoveryManagerImpl::ALL_RESOURCE_TYPE;
+
         RCSDiscoveryManagerImpl::RCSDiscoveryManagerImpl()
         {
-            srand(time(NULL));
-            requestMulticastPresence();
-            m_timer.post(INTERVALTIME, std::bind(&RCSDiscoveryManagerImpl::onPolling, this));
+            subscribePresenceWithMulticast();
+
+            m_timer.post(POLLING_INTERVAL_TIME,
+                    std::bind(&RCSDiscoveryManagerImpl::onPolling, this));
         }
 
         RCSDiscoveryManagerImpl* RCSDiscoveryManagerImpl::getInstance()
@@ -49,135 +70,153 @@ namespace OIC
             return &instance;
         }
 
-        void RCSDiscoveryManagerImpl::onResourceFound(std::shared_ptr< PrimitiveResource > resource,
-                    RCSDiscoveryManagerImpl::ID discoveryId,
-                    const RCSDiscoveryManager::ResourceDiscoveredCallback& discoverCB)
+        void RCSDiscoveryManagerImpl::onResourceFound(
+                std::shared_ptr< PrimitiveResource > resource, ID discoveryId,
+                const RCSDiscoveryManager::ResourceDiscoveredCallback& discoverCB)
         {
             {
-                std::lock_guard<std::mutex> lock(m_mutex);
+                std::lock_guard < std::mutex > lock(m_mutex);
                 auto it = m_discoveryMap.find(discoveryId);
 
-                if(it == m_discoveryMap.end()) return;
-                if(it->second.isKnownResource(resource)) return;
+                if (it == m_discoveryMap.end()) return;
+                if (it->second.isKnownResource(resource)) return;
+
+                it->second.addKnownResource(resource);
             }
-            discoverCB(std::make_shared<RCSRemoteResourceObject>(resource));
+            discoverCB(std::make_shared < RCSRemoteResourceObject > (resource));
         }
 
-        RCSDiscoveryManager::DiscoveryTask::Ptr RCSDiscoveryManagerImpl::startDiscovery
-                (const RCSAddress& address, const std::string& relativeUri, const std::string& resourceType,
-                        RCSDiscoveryManager::ResourceDiscoveredCallback cb)
+        RCSDiscoveryManager::DiscoveryTask::Ptr RCSDiscoveryManagerImpl::startDiscovery(
+                const RCSAddress& address, const std::string& relativeUri,
+                const std::vector< std::string >& resourceTypes,
+                RCSDiscoveryManager::ResourceDiscoveredCallback cb)
         {
             if (!cb)
             {
-                throw RCSInvalidParameterException { "Callback is empty" };
+                throw RCSInvalidParameterException{ "Callback is empty" };
             }
 
-            ID discoveryId = createId();
-            auto discoverCb = std::bind(&RCSDiscoveryManagerImpl::onResourceFound, this,
-                    std::placeholders::_1, discoveryId, std::move(cb));
-            DiscoveryRequestInfo discoveryItem(RCSAddressDetail::getDetail(address)->getAddress(), relativeUri,
-                    resourceType, std::move(discoverCb));
-            discoveryItem.discoverRequest();
+            validateTypes(resourceTypes);
+
+            const ID discoveryId = createId();
+
+            DiscoveryRequestInfo discoveryInfo(address, relativeUri, resourceTypes,
+                    std::bind(&RCSDiscoveryManagerImpl::onResourceFound, this,
+                            std::placeholders::_1, discoveryId, std::move(cb)));
 
-            std::lock_guard<std::mutex> lock(m_mutex);
-            m_discoveryMap.insert(std::make_pair(discoveryId, std::move(discoveryItem)));
+            discoveryInfo.discover();
 
-            return std::unique_ptr<RCSDiscoveryManager::DiscoveryTask>(
+            {
+                std::lock_guard < std::mutex > lock(m_mutex);
+                m_discoveryMap.insert(std::make_pair(discoveryId, std::move(discoveryInfo)));
+            }
+
+            return std::unique_ptr< RCSDiscoveryManager::DiscoveryTask >(
                     new RCSDiscoveryManager::DiscoveryTask(discoveryId));
         }
 
-        void RCSDiscoveryManagerImpl::requestMulticastPresence()
+        void RCSDiscoveryManagerImpl::subscribePresenceWithMulticast()
         {
-            static constexpr char MULTICAST_PRESENCE_ADDRESS[] = "coap://" OC_MULTICAST_PREFIX;
+            using namespace std::placeholders;
+
+            constexpr char MULTICAST_PRESENCE_ADDRESS[] = "coap://" OC_MULTICAST_PREFIX;
+
             OCDoHandle presenceHandle;
-            subscribePresence(presenceHandle, MULTICAST_PRESENCE_ADDRESS, OCConnectivityType::CT_DEFAULT,
-                    std::move(std::bind(&RCSDiscoveryManagerImpl::onPresence, this,
-                            std::placeholders::_1, std::placeholders::_2,std::placeholders::_3)));
+            subscribePresence(presenceHandle, MULTICAST_PRESENCE_ADDRESS,
+                    OCConnectivityType::CT_DEFAULT,
+                    std::bind(&RCSDiscoveryManagerImpl::onPresence, this, _1, _2, _3));
         }
 
         void RCSDiscoveryManagerImpl::onPolling()
         {
-            std::lock_guard<std::mutex> lock(m_mutex);
-
-            for(const auto& it : m_discoveryMap)
             {
-                it.second.discoverRequest();
+                std::lock_guard < std::mutex > lock(m_mutex);
+
+                for (const auto& it : m_discoveryMap)
+                {
+                    it.second.discover();
+                }
             }
-            m_timer.post(INTERVALTIME, std::bind(&RCSDiscoveryManagerImpl::onPolling, this));
+            m_timer.post(POLLING_INTERVAL_TIME,
+                    std::bind(&RCSDiscoveryManagerImpl::onPolling, this));
         }
 
-        void RCSDiscoveryManagerImpl::onPresence(OCStackResult ret,
-                const unsigned int /*seq*/, const std::string& address)
+        void RCSDiscoveryManagerImpl::onPresence(OCStackResult result, const unsigned int /*seq*/,
+                const std::string& address)
         {
-            if(ret != OC_STACK_OK && ret != OC_STACK_RESOURCE_CREATED) return;
+            if (result != OC_STACK_OK && result != OC_STACK_RESOURCE_CREATED) return;
 
-            std::lock_guard<std::mutex> lock(m_mutex);
-            for(const auto& it : m_discoveryMap)
+            std::lock_guard < std::mutex > lock(m_mutex);
+            for (const auto& it : m_discoveryMap)
             {
-                if(it.second.isMatchingAddress(address))
+                if (it.second.isMatchedAddress(address))
                 {
-                    it.second.discoverRequest();
+                    it.second.discover();
                 }
             }
         }
 
-        RCSDiscoveryManagerImpl::ID RCSDiscoveryManagerImpl::createId()
+        RCSDiscoveryManagerImpl::ID RCSDiscoveryManagerImpl::createId() const
         {
-            std::lock_guard<std::mutex> lock(m_mutex);
-            static unsigned int s_uniqueId;
+            static ID s_nextId = INVALID_ID + 1;
 
-            if(m_discoveryMap.size() >= LIMITNUMBER)
-            {
-                throw RCSException { "Discovery request is full!" };
-            }
-            s_uniqueId++;
-            while(m_discoveryMap.find(s_uniqueId) != m_discoveryMap.end())
+            std::lock_guard < std::mutex > lock(m_mutex);
+
+            while (s_nextId == INVALID_ID || m_discoveryMap.find(s_nextId) != m_discoveryMap.end())
             {
-                s_uniqueId++;
+                ++s_nextId;
             }
-            return s_uniqueId;
+
+            assert(s_nextId != INVALID_ID && "Invalid ID!");
+
+            return s_nextId++;
         }
 
-        void RCSDiscoveryManagerImpl::cancel(unsigned int id)
+        void RCSDiscoveryManagerImpl::cancel(ID id)
         {
-            std::lock_guard<std::mutex> lock(m_mutex);
+            std::lock_guard < std::mutex > lock(m_mutex);
             m_discoveryMap.erase(id);
         }
 
-        bool RCSDiscoveryManagerImpl::isCanceled(unsigned int id)
+        DiscoveryRequestInfo::DiscoveryRequestInfo(const RCSAddress& address,
+                const std::string& relativeUri, const std::vector< std::string >& resourceTypes,
+                DiscoverCallback cb) :
+                m_address{ address },
+                m_relativeUri{ relativeUri },
+                m_resourceTypes{ resourceTypes },
+                m_knownResourceIds{ },
+                m_discoverCb{ std::move(cb) }
         {
-            std::lock_guard<std::mutex> lock(m_mutex);
-            auto it = m_discoveryMap.find(id);
-            if(it == m_discoveryMap.end()) return true;
-
-            return false;
+            if (m_resourceTypes.empty())
+            {
+                m_resourceTypes.push_back(RCSDiscoveryManagerImpl::ALL_RESOURCE_TYPE);
+            }
         }
 
-        DiscoveryRequestInfo::DiscoveryRequestInfo(const std::string &address, const std::string &relativeUri,
-                const std::string &resourceType, DiscoverCallback cb) : m_address(address),
-                        m_relativeUri(relativeUri), m_resourceType(resourceType), m_discoverCB(cb) {}
-
-        void DiscoveryRequestInfo::discoverRequest() const
+        void DiscoveryRequestInfo::discover() const
         {
-            OIC::Service::discoverResource(m_address, m_relativeUri + "?rt=" + m_resourceType,
-                    OCConnectivityType::CT_DEFAULT, m_discoverCB);
+            for (const auto& it : m_resourceTypes)
+            {
+                discoverResource(m_address, m_relativeUri + "?rt=" + it, m_discoverCb);
+            }
         }
 
-        bool DiscoveryRequestInfo::isKnownResource(const std::shared_ptr<PrimitiveResource>& resource)
+        bool DiscoveryRequestInfo::isKnownResource(
+                const std::shared_ptr< PrimitiveResource >& resource) const
         {
-            std::string resourceId = resource->getSid() + resource->getUri();
-
-            auto it = std::find(m_receivedIds.begin(), m_receivedIds.end(), resourceId);
+            return m_knownResourceIds.find(makeResourceId(resource)) != m_knownResourceIds.end();
+        }
 
-            if(it != m_receivedIds.end()) return true;
-            m_receivedIds.push_back(resourceId);
-            return false;
+        void DiscoveryRequestInfo::addKnownResource(
+                const std::shared_ptr< PrimitiveResource >& resource)
+        {
+            m_knownResourceIds.insert(makeResourceId(resource));
         }
 
-        bool DiscoveryRequestInfo::isMatchingAddress(const std::string& address) const
+        bool DiscoveryRequestInfo::isMatchedAddress(const std::string& address) const
         {
-            return m_address == RCSAddressDetail::getDetail(RCSAddress::multicast())->getAddress()
-                    || m_address == address;
+            return RCSAddressDetail::getDetail(m_address)->isMulticast()
+                    || RCSAddressDetail::getDetail(m_address)->getAddress() == address;
         }
     }
 }
old mode 100644 (file)
new mode 100755 (executable)
index 5f3dabc..0fea0cd
 
 #include <memory>
 #include <functional>
-#include <list>
 #include <mutex>
 #include <unordered_map>
+#include <unordered_set>
 
+#include "RCSAddress.h"
 #include "RCSDiscoveryManager.h"
 #include "ExpiryTimer.h"
 #include "PrimitiveResource.h"
-#include "RCSRemoteResourceObject.h"
 
 namespace OIC
 {
     namespace Service
     {
-        class RCSDiscoveryManager;
-        class PrimitiveResource;
-        class RCSAddress;
-
         /**
          * The class contains discovery request information
          *
@@ -56,55 +52,44 @@ namespace OIC
         class DiscoveryRequestInfo
         {
             public:
-                DiscoveryRequestInfo(const std::string &, const std::string &,
-                        const std::string &, DiscoverCallback);
+                DiscoveryRequestInfo(const RCSAddress&, const std::string&,
+                        const std::vector< std::string >&, DiscoverCallback);
+
+            public:
+                void discover() const;
+                bool isKnownResource(const std::shared_ptr< PrimitiveResource >&) const;
+                void addKnownResource(const std::shared_ptr< PrimitiveResource >&);
+                bool isMatchedAddress(const std::string&) const;
 
             private:
-                std::string m_address;
+                RCSAddress m_address;
                 std::string m_relativeUri;
-                std::string m_resourceType;
-                std::list<std::string> m_receivedIds;
-                DiscoverCallback m_discoverCB;
-            public:
-                void discoverRequest() const;
-                bool isKnownResource(const std::shared_ptr<PrimitiveResource>&);
-                bool isMatchingAddress(const std::string&) const;
+                std::vector< std::string > m_resourceTypes;
+                std::unordered_set< std::string > m_knownResourceIds;
+                DiscoverCallback m_discoverCb;
         };
 
-
         /**
          * The class contains the resource discovery and management requests methods.
          */
         class RCSDiscoveryManagerImpl
         {
-            static unsigned int s_uniqueId;
-
             public:
 
                 /*
-                 * Typedef for callback of requesting presence API
-                 *
-                 * @see requestMulticastPresence
-                 */
-                typedef std::function<void(OCStackResult, const unsigned int,
-                        const std::string&)> PresenceCallback;
-
-                /*
                  * Typedef for discovery request ID
                  *
                  * @note This is generated for each discovery request
                  */
                 typedef unsigned int ID;
+                constexpr static char const* ALL_RESOURCE_TYPE = "";
 
             public:
 
-                /*
-                 * @return Returns RCSDiscoveryManagerImpl instance.
-                 */
                 static RCSDiscoveryManagerImpl* getInstance();
 
                 /**
-                 * Starting discovery of resource
+                 * Start discovery of resource
                  *
                  * @return DiscoverTask pointer
                  *
@@ -115,30 +100,28 @@ namespace OIC
                  *
                  * @throws InvalidParameterException If cb is empty
                  *
-                 * @note If relativeURI is empty, will be discovered after be changed into "OC_RSRVD_WELL_KNOWN_URI"
+                 * @note If relativeURI is empty, will be discovered after be changed into
+                 * "OC_RSRVD_WELL_KNOWN_URI"
                  * @note If resourceType is empty, will be discovered all resources in network
                  *
                  * @see RCSAddress
                  * @see RCSDiscoveryManager
                  */
-                std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> startDiscovery(const RCSAddress& address,
-                        const std::string& relativeURI,const std::string& resourceType,
+                RCSDiscoveryManager::DiscoveryTask::Ptr startDiscovery(const RCSAddress& address,
+                        const std::string& relativeURI,
+                        const std::vector< std::string >& resourceTypes,
                         RCSDiscoveryManager::ResourceDiscoveredCallback cb);
 
                 void cancel(ID);
-                bool isCanceled(ID);
 
             private:
                 RCSDiscoveryManagerImpl();
                 ~RCSDiscoveryManagerImpl() = default;
 
-                /**
-                 * Requesting presence by multicast
-                 */
-                void requestMulticastPresence();
+                void subscribePresenceWithMulticast();
 
                 /**
-                 * Checking duplicated callback and invoking callback when resource is discovered
+                 * Check duplicated callback and invoke callback when resource is discovered
                  *
                  * @param resource     A pointer of discovered resource
                  * @param discoverID   The ID of discovery request
@@ -146,36 +129,36 @@ namespace OIC
                  *
                  * @see PrimitiveResource
                  */
-                void onResourceFound(std::shared_ptr<PrimitiveResource> resource, ID discoveryId,
+                void onResourceFound(std::shared_ptr< PrimitiveResource > resource, ID discoveryId,
                         const RCSDiscoveryManager::ResourceDiscoveredCallback& cb);
 
                 /**
-                 * Discovering resource on all requests and posting timer when timer is expired
+                 * Discover resource on all requests and posting timer when timer is expired
                  */
                 void onPolling();
 
                 /**
-                 * Discovering resource on all requests when supporting presence function resource enter into network
-                 *
-                 * @param ret          Not used in this class
-                 * @param seq          Not used in this class
-                 * @param address      A address of supporting presence function resource
+                 * Discover resource on all requests when supporting presence function resource
+                 * enter into network
                  */
-                void onPresence(OCStackResult ret, const unsigned int seq, const std::string& address);
+                void onPresence(OCStackResult, const unsigned int seq, const std::string& address);
 
                 /**
-                 * Creating unique id
+                 * Create unique id
                  *
                  * @return Returns the id
                  */
-                ID createId();
+                ID createId() const;
 
             public:
-                ExpiryTimer m_timer;
+                constexpr static ID INVALID_ID = 0;
 
             private:
-                std::unordered_map<ID,DiscoveryRequestInfo> m_discoveryMap;
-                std::mutex m_mutex;
+                ExpiryTimer m_timer;
+
+                std::unordered_map< ID, DiscoveryRequestInfo > m_discoveryMap;
+
+                mutable std::mutex m_mutex;
         };
     }
 }
index 388ac21..54e7ce8 100644 (file)
@@ -99,7 +99,7 @@ namespace
         return OC_STACK_OK;
     }
 
-    void setCallback(const HeaderOptions&, const ResponseStatement& response, int eCode,
+    void setRemoteAttributesCb(const HeaderOptions&, const ResponseStatement& response, int eCode,
             RCSRemoteResourceObject::RemoteAttributesSetCallback onRemoteAttributesSet)
     {
         SCOPE_LOG_F(DEBUG, TAG);
@@ -107,7 +107,7 @@ namespace
         onRemoteAttributesSet(response.getAttributes(), eCode);
     }
 
-    void getCallback(const HeaderOptions&, const ResponseStatement& response, int eCode,
+    void getRemoteAttributesCb(const HeaderOptions&, const ResponseStatement& response, int eCode,
             RCSRemoteResourceObject::RemoteAttributesGetCallback onRemoteAttributesReceived)
     {
         SCOPE_LOG_F(DEBUG, TAG);
@@ -120,9 +120,56 @@ namespace OIC
 {
     namespace Service
     {
+
+        RCSQueryParams& RCSQueryParams::setResourceInterface(std::string resourceInterface)
+        {
+            m_resourceInterface = std::move(resourceInterface);
+            return *this;
+        }
+
+        RCSQueryParams& RCSQueryParams::setResourceType(std::string resourceType)
+        {
+            m_resourceType = std::move(resourceType);
+            return *this;
+        }
+
+        RCSQueryParams& RCSQueryParams::put(std::string key, std::string value)
+        {
+            m_map[std::move(key)] = std::move(value);
+            return *this;
+        }
+
+        std::string RCSQueryParams::getResourceInterface() const
+        {
+            return m_resourceInterface;
+        }
+
+        std::string RCSQueryParams::getResourceType() const
+        {
+            return m_resourceType;
+        }
+
+        std::string RCSQueryParams::get(const std::string& key) const
+        {
+            try
+            {
+                return m_map.at(key);
+            }
+            catch (const std::out_of_range&)
+            {
+                throw RCSInvalidKeyException(key + " is an invalid key");
+            }
+        }
+
+        const RCSQueryParams::Map& RCSQueryParams::getAll() const
+        {
+            return m_map;
+        }
+
+
         RCSRemoteResourceObject::RCSRemoteResourceObject(
-                std::shared_ptr< PrimitiveResource > pResource) :
-                m_primitiveResource{ pResource },
+                std::shared_ptr< PrimitiveResource > primtiveResource) :
+                m_primitiveResource{ primtiveResource },
                 m_cacheId{ },
                 m_brokerId{ }
         {
@@ -132,8 +179,26 @@ namespace OIC
         {
             SCOPE_LOG_F(DEBUG, TAG);
 
-            stopCaching();
-            stopMonitoring();
+            try{
+                stopCaching();
+                stopMonitoring();
+            }
+            catch(std::exception &e){
+                OIC_LOG_V(ERROR, TAG, "%s", e.what());
+            }
+
+        }
+
+        RCSRemoteResourceObject::Ptr RCSRemoteResourceObject::fromOCResource(
+                std::shared_ptr< OC::OCResource > ocResource)
+        {
+            if (!ocResource)
+            {
+                throw RCSInvalidParameterException("the oc resource must not be nullptr.");
+            }
+
+            return std::make_shared< RCSRemoteResourceObject >(
+                    PrimitiveResource::create(ocResource));
         }
 
         bool RCSRemoteResourceObject::isMonitoring() const
@@ -162,7 +227,7 @@ namespace OIC
 
             if (isMonitoring())
             {
-                OC_LOG(DEBUG, TAG, "startMonitoring : already started");
+                OIC_LOG(DEBUG, TAG, "startMonitoring : already started");
                 throw RCSBadRequestException{ "Monitoring already started." };
             }
 
@@ -176,7 +241,7 @@ namespace OIC
 
             if (!isMonitoring())
             {
-                OC_LOG(DEBUG, TAG, "stopMonitoring : Not started");
+                OIC_LOG(DEBUG, TAG, "stopMonitoring : Not started");
                 return;
             }
 
@@ -208,7 +273,7 @@ namespace OIC
 
             if (isCaching())
             {
-                OC_LOG(DEBUG, TAG, "startCaching : already Started");
+                OIC_LOG(DEBUG, TAG, "startCaching : already Started");
                 throw RCSBadRequestException{ "Caching already started." };
             }
 
@@ -225,7 +290,7 @@ namespace OIC
                         m_primitiveResource, { }, REPORT_FREQUENCY::NONE, 0);
             }
 
-            OC_LOG_V(DEBUG, TAG, "startCaching CACHE ID %d", m_cacheId);
+            OIC_LOG_V(DEBUG, TAG, "startCaching CACHE ID %d", m_cacheId);
         }
 
         void RCSRemoteResourceObject::stopCaching()
@@ -234,7 +299,7 @@ namespace OIC
 
             if (!isCaching())
             {
-                OC_LOG(DEBUG, TAG, "Caching already terminated");
+                OIC_LOG(DEBUG, TAG, "Caching already terminated");
                 return;
             }
 
@@ -320,10 +385,39 @@ namespace OIC
             }
 
             m_primitiveResource->requestGet(
-                    std::bind(getCallback, std::placeholders::_1, std::placeholders::_2,
+                    std::bind(getRemoteAttributesCb, std::placeholders::_1, std::placeholders::_2,
                             std::placeholders::_3, std::move(cb)));
         }
 
+        void RCSRemoteResourceObject::get(GetCallback cb)
+        {
+            SCOPE_LOG_F(DEBUG, TAG);
+
+            if (!cb)
+            {
+                throw RCSInvalidParameterException{ "get : Callback is empty" };
+            }
+
+            m_primitiveResource->requestGet(std::move(cb));
+        }
+
+        void RCSRemoteResourceObject::get(const RCSQueryParams& queryParams, GetCallback cb)
+        {
+            SCOPE_LOG_F(DEBUG, TAG);
+
+            if (!cb)
+            {
+                throw RCSInvalidParameterException{ "get : Callback is empty" };
+            }
+
+            const auto& paramMap = queryParams.getAll();
+
+            m_primitiveResource->requestGetWith(
+                    queryParams.getResourceType(), queryParams.getResourceInterface(),
+                    OC::QueryParamsMap{ paramMap.begin(), paramMap.end() },
+                    std::move(cb));
+        }
+
         void RCSRemoteResourceObject::setRemoteAttributes(const RCSResourceAttributes& attribute,
                 RemoteAttributesSetCallback cb)
         {
@@ -335,8 +429,39 @@ namespace OIC
             }
 
             m_primitiveResource->requestSet(attribute,
-                    std::bind(setCallback, std::placeholders::_1, std::placeholders::_2,
+                    std::bind(setRemoteAttributesCb, std::placeholders::_1, std::placeholders::_2,
                             std::placeholders::_3, cb));
         }
+
+        void RCSRemoteResourceObject::set(const RCSResourceAttributes& attributes, SetCallback cb)
+        {
+            SCOPE_LOG_F(DEBUG, TAG);
+
+            if (!cb)
+            {
+                throw RCSInvalidParameterException{ "set : Callback is empty" };
+            }
+
+            m_primitiveResource->requestSet(attributes, std::move(cb));
+        }
+
+        void RCSRemoteResourceObject::set(const RCSQueryParams& queryParams,
+                const RCSResourceAttributes& attributes, SetCallback cb)
+        {
+            SCOPE_LOG_F(DEBUG, TAG);
+
+            if (!cb)
+            {
+                throw RCSInvalidParameterException{ "set : Callback is empty" };
+            }
+
+            const auto& paramMap = queryParams.getAll();
+
+            m_primitiveResource->requestSetWith(
+                    queryParams.getResourceType(), queryParams.getResourceInterface(),
+                    OC::QueryParamsMap{ paramMap.begin(), paramMap.end() }, attributes,
+                    std::move(cb));
+        }
+
     }
 }
diff --git a/service/resource-encapsulation/src/serverBuilder/include/InterfaceHandler.h b/service/resource-encapsulation/src/serverBuilder/include/InterfaceHandler.h
new file mode 100644 (file)
index 0000000..0049785
--- /dev/null
@@ -0,0 +1,68 @@
+//******************************************************************\r
+//\r
+// Copyright 2015 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
+#ifndef RE_INTERFACEHANDLER_H_\r
+#define RE_INTERFACEHANDLER_H_\r
+\r
+#include <string>\r
+#include <functional>\r
+\r
+namespace OIC\r
+{\r
+    namespace Service\r
+    {\r
+        class RCSRequest;\r
+        class RCSResourceObject;\r
+        class RCSRepresentation;\r
+        class RCSResourceAttributes;\r
+\r
+        const std::string BASELINE_INTERFACE = "oic.if.baseline";\r
+        const std::string ACTUATOR_INTERFACE = "oic.if.a";\r
+        const std::string SENSOR_INTERFACE = "oic.if.s";\r
+        const std::string BATCH_INTERFACE = "oic.if.b";\r
+\r
+        class InterfaceHandler\r
+        {\r
+        public:\r
+            typedef std::function< RCSRepresentation(RCSRequest, const RCSResourceObject&) >\r
+                GetResponseBuilder;\r
+\r
+            typedef std::function< RCSRepresentation(RCSRequest, const RCSResourceObject&) >\r
+                SetResponseBuilder;\r
+\r
+        public:\r
+            InterfaceHandler(GetResponseBuilder, SetResponseBuilder);\r
+\r
+            bool isGetSupported() const;\r
+            bool isSetSupported() const;\r
+\r
+            GetResponseBuilder getGetResponseBuilder() const;\r
+            SetResponseBuilder getSetResponseBuilder() const;\r
+\r
+        private:\r
+            GetResponseBuilder m_getBuilder;\r
+            SetResponseBuilder m_setBuilder;\r
+        };\r
+\r
+        InterfaceHandler getDefaultInterfaceHandler(const std::string&, const std::string&);\r
+    }\r
+}\r
+\r
+#endif /* RE_INTERFACEHANDLER_H_ */\r
index 8c6f345..6e0f2b6 100644 (file)
 #ifndef SERVERBUILDER_REQUESTHANDLER_H
 #define SERVERBUILDER_REQUESTHANDLER_H
 
-#include <RCSResponse.h>
-#include <RCSResourceAttributes.h>
+#include "RCSResponse.h"
+#include "RCSResourceAttributes.h"
 
-namespace OC
-{
-    class OCResourceResponse;
-    class OCRepresentation;
-}
+#include "OCRepresentation.h"
 
 namespace OIC
 {
@@ -39,15 +35,7 @@ namespace OIC
 
         class RequestHandler
         {
-        private:
-            typedef std::function< std::shared_ptr< OC::OCResourceResponse >(RCSResourceObject&) >
-                        BuildResponseHolder;
-
         public:
-            typedef std::shared_ptr< RequestHandler > Pre;
-
-            static constexpr int DEFAULT_ERROR_CODE = 200;
-
             RequestHandler();
 
             RequestHandler(const RequestHandler&) = delete;
@@ -61,10 +49,19 @@ namespace OIC
 
             virtual ~RequestHandler() { };
 
-            std::shared_ptr< OC::OCResourceResponse > buildResponse(RCSResourceObject&);
+            int getErrorCode() const;
+
+            bool hasCustomRepresentation() const;
+
+            OC::OCRepresentation getRepresentation() const;
+
+        public:
+            static constexpr int DEFAULT_ERROR_CODE = 200;
 
         private:
-            const BuildResponseHolder m_holder;
+            const int m_errorCode;
+            const bool m_customRep;
+            const OC::OCRepresentation m_ocRep;
         };
 
         class SetRequestHandler: public RequestHandler
@@ -74,8 +71,6 @@ namespace OIC
             typedef std::vector< AttrKeyValuePair > AttrKeyValuePairs;
 
         public:
-            typedef std::shared_ptr< SetRequestHandler > Ptr;
-
             SetRequestHandler(const SetRequestHandler&) = delete;
             SetRequestHandler(SetRequestHandler&&) = default;
 
diff --git a/service/resource-encapsulation/src/serverBuilder/src/InterfaceHandler.cpp b/service/resource-encapsulation/src/serverBuilder/src/InterfaceHandler.cpp
new file mode 100644 (file)
index 0000000..ea50568
--- /dev/null
@@ -0,0 +1,161 @@
+//******************************************************************
+//
+// 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 "InterfaceHandler.h"
+
+#include "OCResourceRequest.h"
+
+#include "RCSRepresentation.h"
+#include "RCSRequest.h"
+#include "RCSResourceObject.h"
+#include "RCSResourceAttributes.h"
+#include "ResourceAttributesConverter.h"
+
+#include <unordered_map>
+
+namespace
+{
+    using namespace OIC::Service;
+
+    RCSRepresentation toRepresentation(const RCSResourceObject& resource)
+    {
+        RCSResourceObject::LockGuard lock{ resource, RCSResourceObject::AutoNotifyPolicy::NEVER };
+
+        return RCSRepresentation{ resource.getUri(), resource.getInterfaces(), resource.getTypes(),
+            resource.getAttributes() };
+    }
+
+    RCSRepresentation buildGetBaselineResponse(const RCSRequest&, const RCSResourceObject& resource)
+    {
+        return toRepresentation(resource);
+    }
+
+    RCSRepresentation buildSetBaselineResponse(const RCSRequest& rcsRequest,
+            const RCSResourceObject& resource)
+    {
+        return buildGetBaselineResponse(rcsRequest, resource);
+    }
+
+    RCSRepresentation buildGetRequestResponse(const RCSRequest&, const RCSResourceObject& resource)
+    {
+        RCSResourceObject::LockGuard lock{ resource, RCSResourceObject::AutoNotifyPolicy::NEVER };
+
+        return RCSRepresentation{ resource.getAttributes() };
+    }
+
+    RCSRepresentation buildSetRequestResponse(const RCSRequest& rcsRequest,
+            const RCSResourceObject& resource)
+    {
+        auto requestAttr = ResourceAttributesConverter::fromOCRepresentation(
+                rcsRequest.getOCRequest()->getResourceRepresentation());
+
+        RCSResourceObject::LockGuard lock{ resource, RCSResourceObject::AutoNotifyPolicy::NEVER };
+
+        const RCSResourceAttributes& updatedAttr = resource.getAttributes();
+
+        for (auto it = requestAttr.begin(); it != requestAttr.end();)
+        {
+            if(updatedAttr.contains(it->key()))
+            {
+                it->value() = updatedAttr.at(it->key());
+                ++it;
+            }
+            else
+            {
+                it = requestAttr.erase(it);
+            }
+        }
+
+        return RCSRepresentation{ requestAttr };
+    }
+
+    RCSRepresentation buildGetBatchResponse(RCSRequest, const RCSResourceObject& resource)
+    {
+        RCSRepresentation rcsRep;
+
+        for (const auto& bound : resource.getBoundResources())
+        {
+            rcsRep.addChild(toRepresentation(*bound));
+        }
+
+        return rcsRep;
+    }
+
+    const std::unordered_map< std::string, InterfaceHandler > g_defaultHandlers {
+
+            { BASELINE_INTERFACE,
+                InterfaceHandler(buildGetBaselineResponse, buildSetBaselineResponse) },
+
+            { ACTUATOR_INTERFACE,
+                InterfaceHandler(buildGetRequestResponse, buildSetRequestResponse) },
+
+            { SENSOR_INTERFACE,
+                InterfaceHandler(buildGetRequestResponse, nullptr) },
+
+            { BATCH_INTERFACE,
+                InterfaceHandler(buildGetBatchResponse, buildSetBaselineResponse) }
+    };
+}
+
+namespace OIC
+{
+    namespace Service
+    {
+
+        InterfaceHandler::InterfaceHandler(GetResponseBuilder getBuilder,
+                SetResponseBuilder setBuilder) :
+                m_getBuilder{ std::move(getBuilder) },
+                m_setBuilder{ std::move(setBuilder) }
+        {
+        }
+
+        bool InterfaceHandler::isGetSupported() const
+        {
+            return m_getBuilder != nullptr;
+        }
+
+        bool InterfaceHandler::isSetSupported() const
+        {
+            return m_setBuilder != nullptr;
+        }
+
+        InterfaceHandler::GetResponseBuilder InterfaceHandler::getGetResponseBuilder() const
+        {
+            return m_getBuilder;
+        }
+
+        InterfaceHandler::SetResponseBuilder InterfaceHandler::getSetResponseBuilder() const
+        {
+            return m_setBuilder;
+        }
+
+        InterfaceHandler getDefaultInterfaceHandler(const std::string& interfaceName,
+                const std::string& defaultInterfaceName)
+        {
+            auto it = g_defaultHandlers.find(interfaceName);
+            if (it != g_defaultHandlers.end()) return it->second;
+
+            it = g_defaultHandlers.find(defaultInterfaceName);
+            if (it != g_defaultHandlers.end()) return it->second;
+
+            return g_defaultHandlers.find(OIC::Service::BASELINE_INTERFACE)->second;
+        }
+    }
+}
index 378e5ed..6efc456 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#include <RCSRequest.h>
+#include "RCSRequest.h"
+
+#include "OCResourceRequest.h"
 
 namespace OIC
 {
     namespace Service
     {
 
+        RCSRequest::RCSRequest(const std::shared_ptr< RCSResourceObject >& resourceObject,
+                const std::shared_ptr< OC::OCResourceRequest >& ocRequest) :
+                m_resourceObject{ resourceObject },
+                m_ocRequest{ ocRequest }
+        {
+        }
+
         RCSRequest::RCSRequest(const std::string& resourceUri) :
-                m_resourceUri{ resourceUri }
+                m_ocRequest{ std::make_shared< OC::OCResourceRequest >() }
+        {
+            m_ocRequest->setResourceUri(resourceUri);
+        }
+
+
+        std::weak_ptr< RCSResourceObject > RCSRequest::getResourceObject() const noexcept
         {
+            return m_resourceObject;
         }
 
         std::string RCSRequest::getResourceUri() const
         {
-            return m_resourceUri;
+            return m_ocRequest->getResourceUri();
+        }
+
+        std::shared_ptr< OC::OCResourceRequest > RCSRequest::getOCRequest() const noexcept
+        {
+            return m_ocRequest;
+        }
+
+        const std::map< std::string, std::string >& RCSRequest::getQueryParams() const
+        {
+            return m_ocRequest->getQueryParameters();
+        }
+
+        std::string RCSRequest::getInterface() const
+        {
+            const auto& params = m_ocRequest->getQueryParameters();
+
+            auto it = params.find(OC::Key::INTERFACESKEY);
+
+            if (it == params.end()) return "";
+
+            return it->second;
         }
 
     }
index 97ba03b..1a40150 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#include <RCSResourceObject.h>
+#include "RCSResourceObject.h"
 
-#include <string>
 #include <functional>
-#include <vector>
 
-#include <RequestHandler.h>
-#include <AssertUtils.h>
-#include <AtomicHelper.h>
-#include <ResourceAttributesConverter.h>
-#include <ResourceAttributesUtils.h>
+#include "RequestHandler.h"
+#include "AssertUtils.h"
+#include "AtomicHelper.h"
+#include "ResourceAttributesConverter.h"
+#include "ResourceAttributesUtils.h"
+#include "RCSRequest.h"
+#include "RCSRepresentation.h"
+#include "InterfaceHandler.h"
 
-#include <logger.h>
-#include <OCPlatform.h>
+#include "logger.h"
+#include "OCPlatform.h"
 
 #define LOG_TAG "RCSResourceObject"
 
@@ -54,11 +55,9 @@ namespace
         return base & ~target;
     }
 
-    template <typename RESPONSE>
-    OCEntityHandlerResult sendResponse(RCSResourceObject& resource,
-            std::shared_ptr< OC::OCResourceRequest > ocRequest, RESPONSE&& response)
+    OCEntityHandlerResult sendResponse(const std::shared_ptr< OC::OCResourceRequest >& ocRequest,
+            const std::shared_ptr< OC::OCResourceResponse >& ocResponse)
     {
-        auto ocResponse = response.getHandler()->buildResponse(resource);
         ocResponse->setRequestHandle(ocRequest->getRequestHandle());
         ocResponse->setResourceHandle(ocRequest->getResourceHandle());
 
@@ -71,14 +70,14 @@ namespace
         }
         catch (const OC::OCException& e)
         {
-            OC_LOG_V(WARNING, LOG_TAG, "Error (%s)", e.what());
+            OIC_LOG_V(WARNING, LOG_TAG, "Error (%s)", e.what());
         }
 
         return OC_EH_ERROR;
     }
 
     RCSResourceAttributes getAttributesFromOCRequest(
-            std::shared_ptr< OC::OCResourceRequest > request)
+            const std::shared_ptr< OC::OCResourceRequest >& request)
     {
         return ResourceAttributesConverter::fromOCRepresentation(
                 request->getResourceRepresentation());
@@ -86,12 +85,12 @@ namespace
 
     template< typename HANDLER, typename RESPONSE =
             typename std::decay<HANDLER>::type::result_type >
-    RESPONSE invokeHandler(RCSResourceAttributes& attrs,
-            std::shared_ptr< OC::OCResourceRequest > ocRequest, HANDLER&& handler)
+    RESPONSE invokeHandler(RCSResourceAttributes& attrs, const RCSRequest& request,
+            std::shared_ptr< HANDLER > handler)
     {
-        if (handler)
+        if (handler && *handler)
         {
-            return handler(RCSRequest{ ocRequest->getResourceUri() }, attrs);
+            return (*handler)(request, attrs);
         }
 
         return RESPONSE::defaultAction();
@@ -100,8 +99,9 @@ namespace
     typedef void (RCSResourceObject::* AutoNotifyFunc)
             (bool, RCSResourceObject::AutoNotifyPolicy) const;
 
-    std::function <void ()> createAutoNotifyInvoker(AutoNotifyFunc autoNotifyFunc,
-            const RCSResourceObject& resourceObject, const RCSResourceAttributes& resourceAttributes,
+    std::function<void()> createAutoNotifyInvoker(AutoNotifyFunc autoNotifyFunc,
+            const RCSResourceObject& resourceObject,
+            const RCSResourceAttributes& resourceAttributes,
             RCSResourceObject::AutoNotifyPolicy autoNotifyPolicy)
     {
         if(autoNotifyPolicy == RCSResourceObject::AutoNotifyPolicy::UPDATED)
@@ -120,22 +120,66 @@ namespace
         }
         return {};
     }
-} // unnamed namespace
 
+    void insertValue(std::vector<std::string>& container, std::string value)
+    {
+        if (value.empty()) return;
+
+        if (std::find(container.begin(), container.end(), value) == container.end())
+        {
+            container.push_back(std::move(value));
+        }
+    }
+
+} // unnamed namespace
 
 namespace OIC
 {
     namespace Service
     {
 
-        RCSResourceObject::Builder::Builder(const std::string& uri, const std::string& type,
-                const std::string& interface) :
-                m_uri{ uri },
-                m_type{ type },
-                m_interface{ interface },
+        RCSResourceObject::Builder::Builder(std::string uri, std::string type,
+                std::string interface) :
+                m_uri{ std::move(uri) },
+                m_types{ std::move(type) },
+                m_interfaces{ },
+                m_defaultInterface{ interface },
                 m_properties{ OC_DISCOVERABLE | OC_OBSERVABLE },
                 m_resourceAttributes{ }
         {
+            addInterface(interface);
+            addInterface(BASELINE_INTERFACE);
+
+            if (m_defaultInterface.empty())
+            {
+                m_defaultInterface = BASELINE_INTERFACE;
+            }
+        }
+
+        RCSResourceObject::Builder& RCSResourceObject::Builder::addInterface(std::string interface)
+        {
+            insertValue(m_interfaces, std::move(interface));
+            return *this;
+        }
+
+        RCSResourceObject::Builder& RCSResourceObject::Builder::addType(std::string type)
+        {
+            insertValue(m_types, std::move(type));
+            return *this;
+        }
+
+        RCSResourceObject::Builder& RCSResourceObject::Builder::setDefaultInterface(
+                std::string interface)
+        {
+            if (std::find(m_interfaces.begin(), m_interfaces.end(), interface) ==
+                    m_interfaces.end())
+            {
+                throw RCSBadRequestException{"The interface should be added, first."};
+            }
+
+            m_defaultInterface = std::move(interface);
+
+            return *this;
         }
 
         RCSResourceObject::Builder& RCSResourceObject::Builder::setDiscoverable(
@@ -152,6 +196,12 @@ namespace OIC
             return *this;
         }
 
+        RCSResourceObject::Builder& RCSResourceObject::Builder::setSecureFlag(
+            bool secureFlag)
+        {
+            m_properties = ::makePropertyFlags(m_properties, OC_SECURE, secureFlag);
+            return *this;
+        }
         RCSResourceObject::Builder& RCSResourceObject::Builder::setAttributes(
                 const RCSResourceAttributes& attrs)
         {
@@ -171,31 +221,46 @@ namespace OIC
             OCResourceHandle handle{ nullptr };
 
             RCSResourceObject::Ptr server {
-                new RCSResourceObject{ m_properties, std::move(m_resourceAttributes) } };
+                new RCSResourceObject{ m_uri, m_properties, std::move(m_resourceAttributes) } };
 
             OC::EntityHandler entityHandler{ std::bind(&RCSResourceObject::entityHandler,
-                    server.get(), std::placeholders::_1) };
+                    std::weak_ptr< RCSResourceObject >{ server }, std::placeholders::_1) };
 
             typedef OCStackResult (*RegisterResource)(OCResourceHandle&, std::string&,
                     const std::string&, const std::string&, OC::EntityHandler, uint8_t);
 
             invokeOCFunc(static_cast<RegisterResource>(OC::OCPlatform::registerResource),
-                    handle, m_uri, m_type, m_interface, entityHandler, m_properties);
+                    handle, m_uri, m_types[0], m_interfaces[0], entityHandler, m_properties);
+
+            std::for_each(m_interfaces.begin() + 1, m_interfaces.end(),
+                    [&handle](const std::string& interfaceName){
+                invokeOCFunc(OC::OCPlatform::bindInterfaceToResource, handle, interfaceName);
+            });
+
+            std::for_each(m_types.begin() + 1, m_types.end(),
+                    [&handle](const std::string& typeName){
+                invokeOCFunc(OC::OCPlatform::bindTypeToResource, handle, typeName);
+            });
 
-            server->m_resourceHandle = handle;
+            server->init(handle, m_interfaces, m_types, m_defaultInterface);
 
             return server;
         }
 
 
-        RCSResourceObject::RCSResourceObject(uint8_t properties, RCSResourceAttributes&& attrs) :
-                m_properties { properties },
+        RCSResourceObject::RCSResourceObject(const std::string& uri,
+                uint8_t properties, RCSResourceAttributes&& attrs) :
+                m_properties{ properties },
+                m_uri{ uri },
+                m_interfaces{ },
+                m_types{ },
+                m_defaultInterface{ },
                 m_resourceHandle{ },
                 m_resourceAttributes{ std::move(attrs) },
                 m_getRequestHandler{ },
                 m_setRequestHandler{ },
-                m_autoNotifyPolicy { AutoNotifyPolicy::UPDATED },
-                m_setRequestHandlerPolicy { SetRequestHandlerPolicy::NEVER },
+                m_autoNotifyPolicy{ AutoNotifyPolicy::UPDATED },
+                m_setRequestHandlerPolicy{ SetRequestHandlerPolicy::NEVER },
                 m_attributeUpdatedListeners{ },
                 m_lockOwner{ },
                 m_mutex{ },
@@ -204,17 +269,34 @@ namespace OIC
             m_lockOwner.reset(new AtomicThreadId);
         }
 
+        void RCSResourceObject::init(OCResourceHandle handle,
+                const std::vector< std::string >& interfaces,
+                const std::vector< std::string >& types,
+                const std::string& defaultInterface)
+        {
+            m_resourceHandle = handle;
+            m_interfaces = interfaces;
+            m_types = types;
+            m_defaultInterface = defaultInterface;
+
+            for (const auto& itf : interfaces)
+            {
+                m_interfaceHandlers.insert({ itf, getDefaultInterfaceHandler(itf,
+                        m_defaultInterface) });
+            }
+        }
+
         RCSResourceObject::~RCSResourceObject()
         {
             if (m_resourceHandle)
             {
                 try
                 {
-                    OC::OCPlatform::unregisterResource(m_resourceHandle);
+                    invokeOCFunc(OC::OCPlatform::unregisterResource, m_resourceHandle);
                 }
                 catch (...)
                 {
-                    OC_LOG(WARNING, LOG_TAG, "Failed to unregister resource.");
+                    OIC_LOG(WARNING, LOG_TAG, "Failed to unregister resource.");
                 }
             }
         }
@@ -337,12 +419,12 @@ namespace OIC
 
         void RCSResourceObject::setGetRequestHandler(GetRequestHandler h)
         {
-            m_getRequestHandler = std::move(h);
+            m_getRequestHandler = std::make_shared< GetRequestHandler >(std::move(h));
         }
 
         void RCSResourceObject::setSetRequestHandler(SetRequestHandler h)
         {
-            m_setRequestHandler = std::move(h);
+            m_setRequestHandler = std::make_shared< SetRequestHandler >(std::move(h));
         }
 
         void RCSResourceObject::notify() const
@@ -406,6 +488,78 @@ namespace OIC
             return m_setRequestHandlerPolicy;
         }
 
+        void RCSResourceObject::bindResource(const RCSResourceObject::Ptr& resource)
+        {
+            if (!resource || resource.get() == this)
+            {
+                throw RCSInvalidParameterException("The resource is invalid!");
+            }
+
+            invokeOCFunc(OC::OCPlatform::bindResource,
+                    m_resourceHandle, resource->m_resourceHandle);
+
+            std::lock_guard< std:: mutex > lock{ m_mutexForBoundResources };
+            m_boundResources.push_back(resource);
+        }
+
+        void RCSResourceObject::unbindResource(const RCSResourceObject::Ptr& resource)
+        {
+            if (!resource || resource.get() == this)
+            {
+                throw RCSInvalidParameterException("The resource is invalid!");
+            }
+
+            invokeOCFunc(OC::OCPlatform::unbindResource,
+                    m_resourceHandle, resource->m_resourceHandle);
+
+            std::lock_guard< std:: mutex > lock{ m_mutexForBoundResources };
+            m_boundResources.erase(std::find(m_boundResources.begin(), m_boundResources.end(),
+                    resource));
+        }
+
+        std::vector< RCSResourceObject::Ptr > RCSResourceObject::getBoundResources() const
+        {
+            std::lock_guard< std:: mutex > lock{ m_mutexForBoundResources };
+            return m_boundResources;
+        }
+
+        std::string RCSResourceObject::getUri() const
+        {
+            return m_uri;
+        }
+
+        std::string RCSResourceObject::getDefaultInterface() const
+        {
+            return m_defaultInterface;
+        }
+
+        std::vector< std::string > RCSResourceObject::getInterfaces() const
+        {
+            return m_interfaces;
+        }
+
+        std::vector< std::string > RCSResourceObject::getTypes() const
+        {
+            return m_types;
+        }
+
+        RCSRepresentation RCSResourceObject::getRepresentation(const RCSRequest& request) const
+        {
+            if (request.getOCRequest()->getRequestType() == "GET")
+            {
+                return findInterfaceHandler(
+                        request.getInterface()).getGetResponseBuilder()(request, *this);
+            }
+
+            if (request.getOCRequest()->getRequestType() == "POST")
+            {
+                return findInterfaceHandler(
+                        request.getInterface()).getSetResponseBuilder()(request, *this);
+            }
+
+            throw RCSBadRequestException{ "Unsupported request type!" };
+        }
+
         void RCSResourceObject::autoNotify(bool isAttributesChanged) const
         {
             autoNotify(isAttributesChanged, m_autoNotifyPolicy);
@@ -422,9 +576,14 @@ namespace OIC
         }
 
         OCEntityHandlerResult RCSResourceObject::entityHandler(
-                std::shared_ptr< OC::OCResourceRequest > request)
+                const std::weak_ptr< RCSResourceObject >& weakRes,
+                const std::shared_ptr< OC::OCResourceRequest >& request)
         {
-            OC_LOG(WARNING, LOG_TAG, "entityHandler");
+            auto resource = weakRes.lock();
+
+            if (!resource) return OC_EH_ERROR;
+
+            OIC_LOG(WARNING, LOG_TAG, "entityHandler");
             if (!request)
             {
                 return OC_EH_ERROR;
@@ -432,24 +591,26 @@ namespace OIC
 
             try
             {
+                RCSRequest rcsRequest{ resource, request };
+
                 if (request->getRequestHandlerFlag() & OC::RequestHandlerFlag::RequestFlag)
                 {
-                    return handleRequest(request);
+                    return resource->handleRequest(rcsRequest);
                 }
 
                 if (request->getRequestHandlerFlag() & OC::RequestHandlerFlag::ObserverFlag)
                 {
-                    return handleObserve(request);
+                    return resource->handleObserve(rcsRequest);
                 }
             }
             catch (const std::exception& e)
             {
-                OC_LOG_V(WARNING, LOG_TAG, "Failed to handle request : %s", e.what());
+                OIC_LOG_V(WARNING, LOG_TAG, "Failed to handle request : %s", e.what());
                 throw;
             }
             catch (...)
             {
-                OC_LOG(WARNING, LOG_TAG, "Failed to handle request.");
+                OIC_LOG(WARNING, LOG_TAG, "Failed to handle request.");
                 throw;
             }
 
@@ -457,16 +618,20 @@ namespace OIC
         }
 
         OCEntityHandlerResult RCSResourceObject::handleRequest(
-                std::shared_ptr< OC::OCResourceRequest > request)
+                const RCSRequest& request)
         {
-            assert(request != nullptr);
+            if (request.getInterface() != "" &&
+                    m_interfaceHandlers.find(request.getInterface()) == m_interfaceHandlers.end())
+            {
+                return OC_EH_ERROR;
+            }
 
-            if (request->getRequestType() == "GET")
+            if (request.getOCRequest()->getRequestType() == "GET")
             {
                 return handleRequestGet(request);
             }
 
-            if (request->getRequestType() == "POST")
+            if (request.getOCRequest()->getRequestType() == "POST")
             {
                 return handleRequestSet(request);
             }
@@ -474,27 +639,36 @@ namespace OIC
             return OC_EH_ERROR;
         }
 
-        OCEntityHandlerResult RCSResourceObject::handleRequestGet(
-                std::shared_ptr< OC::OCResourceRequest > request)
+        OCEntityHandlerResult RCSResourceObject::handleRequestGet(const RCSRequest& request)
         {
-            assert(request != nullptr);
+            if (!findInterfaceHandler(request.getInterface()).isGetSupported())
+            {
+                return OC_EH_ERROR;
+            }
 
-            auto attrs = getAttributesFromOCRequest(request);
+            auto attrs = getAttributesFromOCRequest(request.getOCRequest());
 
-            return sendResponse(*this, request, invokeHandler(attrs, request, m_getRequestHandler));
+            auto response = invokeHandler(attrs, request, m_getRequestHandler);
+
+            if (response.isSeparate()) return OC_EH_SLOW;
+
+            return sendResponse(request, response,
+                         findInterfaceHandler(request.getInterface()).getGetResponseBuilder());
         }
 
-        bool RCSResourceObject::applyAcceptanceMethod(const RCSSetResponse& response,
-                const RCSResourceAttributes& requstAttrs)
+        bool RCSResourceObject::applyAcceptanceMethod(
+                const RCSSetResponse& response, const RCSResourceAttributes& requestAttrs)
         {
             auto requestHandler = response.getHandler();
 
             assert(requestHandler != nullptr);
 
+            RCSResourceAttributes result;
+
             auto replaced = requestHandler->applyAcceptanceMethod(response.getAcceptanceMethod(),
-                    *this, requstAttrs);
+                    *this, requestAttrs);
 
-            OC_LOG_V(WARNING, LOG_TAG, "replaced num %d", replaced.size());
+            OIC_LOG_V(WARNING, LOG_TAG, "replaced num %zu", replaced.size());
             for (const auto& attrKeyValPair : replaced)
             {
                 std::shared_ptr< AttributeUpdatedListener > foundListener;
@@ -510,35 +684,33 @@ namespace OIC
 
                 if (foundListener)
                 {
-                    (*foundListener)(attrKeyValPair.second, requstAttrs.at(attrKeyValPair.first));
+                    (*foundListener)(attrKeyValPair.second, requestAttrs.at(attrKeyValPair.first));
                 }
             }
 
             return !replaced.empty();
         }
 
-        OCEntityHandlerResult RCSResourceObject::handleRequestSet(
-                std::shared_ptr< OC::OCResourceRequest > request)
+        OCEntityHandlerResult RCSResourceObject::handleRequestSet(const RCSRequest& request)
         {
-            assert(request != nullptr);
+            if (!findInterfaceHandler(request.getInterface()).isSetSupported())
+            {
+                return OC_EH_ERROR;
+            }
+
+            auto attrs = getAttributesFromOCRequest(request.getOCRequest());
 
-            auto attrs = getAttributesFromOCRequest(request);
             auto response = invokeHandler(attrs, request, m_setRequestHandler);
 
-            auto attrsChanged = applyAcceptanceMethod(response, attrs);
+            if (response.isSeparate()) return OC_EH_SLOW;
 
-            try
-            {
-                autoNotify(attrsChanged, m_autoNotifyPolicy);
-                return sendResponse(*this, request, response);
-            } catch (const RCSPlatformException& e) {
-                OC_LOG_V(ERROR, LOG_TAG, "Error : %s ", e.what());
-                return OC_EH_ERROR;
-            }
+            autoNotify(applyAcceptanceMethod(response, attrs), m_autoNotifyPolicy);
+
+            return sendResponse(request, response,
+                    findInterfaceHandler(request.getInterface()).getSetResponseBuilder());
         }
 
-        OCEntityHandlerResult RCSResourceObject::handleObserve(
-                std::shared_ptr< OC::OCResourceRequest >)
+        OCEntityHandlerResult RCSResourceObject::handleObserve(const RCSRequest&)
         {
             if (!isObservable())
             {
@@ -548,6 +720,43 @@ namespace OIC
             return OC_EH_OK;
         }
 
+        InterfaceHandler RCSResourceObject::findInterfaceHandler(
+                const std::string& interfaceName) const
+        {
+            auto it = m_interfaceHandlers.find(interfaceName);
+
+            if (it != m_interfaceHandlers.end()) return it->second;
+
+            assert(m_interfaceHandlers.find(m_defaultInterface) != m_interfaceHandlers.end());
+
+            return m_interfaceHandlers.find(m_defaultInterface)->second;
+        }
+
+        template <typename RESPONSE, typename RESPONSE_BUILDER>
+        OCEntityHandlerResult RCSResourceObject::sendResponse(
+                const RCSRequest& request, const RESPONSE& response,
+                const RESPONSE_BUILDER& resBuilder)
+        {
+            auto reqHandler = response.getHandler();
+            auto ocResponse = std::make_shared< OC::OCResourceResponse >();
+
+            ocResponse->setResponseResult(OC_EH_OK);
+            ocResponse->setErrorCode(reqHandler->getErrorCode());
+
+            if (reqHandler->hasCustomRepresentation())
+            {
+                ocResponse->setResourceRepresentation(reqHandler->getRepresentation());
+            }
+            else
+            {
+                ocResponse->setResourceRepresentation(
+                        RCSRepresentation::toOCRepresentation(resBuilder(request, *this)));
+            }
+
+            return ::sendResponse(request.getOCRequest(), ocResponse);
+        }
+
+
         RCSResourceObject::LockGuard::LockGuard(const RCSResourceObject::Ptr ptr) :
                 m_resourceObject(*ptr),
                 m_autoNotifyPolicy{ ptr->getAutoNotifyPolicy() },
@@ -583,9 +792,9 @@ namespace OIC
             init();
         }
 
-        RCSResourceObject::LockGuard::~LockGuard()
+        RCSResourceObject::LockGuard::~LockGuard() noexcept(false)
         {
-            if (m_autoNotifyFunc) m_autoNotifyFunc();
+            if (!std::uncaught_exception() && m_autoNotifyFunc) m_autoNotifyFunc();
 
             if (m_isOwningLock)
             {
index 9a91c61..79d42c3 100644 (file)
@@ -61,6 +61,20 @@ namespace OIC
                 std::move(attrs), errorCode) };
         }
 
+        RCSGetResponse RCSGetResponse::separate()
+        {
+            return RCSGetResponse();
+        }
+
+        bool RCSGetResponse::isSeparate() const
+        {
+            return !m_handler;
+        }
+
+        RCSGetResponse::RCSGetResponse()
+        {
+        }
+
         RCSGetResponse::RCSGetResponse(std::shared_ptr< RequestHandler >&& handler) :
                 m_handler{ std::move(handler) }
         {
@@ -123,6 +137,16 @@ namespace OIC
             return std::make_shared< SetRequestHandler >(std::move(attrs), errorCode);
         }
 
+        RCSSetResponse RCSSetResponse::separate()
+        {
+            return RCSSetResponse();
+        }
+
+        RCSSetResponse::RCSSetResponse() :
+                m_acceptanceMethod { AcceptanceMethod::DEFAULT }
+        {
+        }
+
         RCSSetResponse::RCSSetResponse(std::shared_ptr< SetRequestHandler >&& handler) :
                 m_acceptanceMethod { AcceptanceMethod::DEFAULT },
                 m_handler{ std::move(handler) }
@@ -137,6 +161,12 @@ namespace OIC
             assert(m_handler);
         }
 
+        bool RCSSetResponse::isSeparate() const
+        {
+            return !m_handler;
+        }
+
+
         SetRequestHandler* RCSSetResponse::getHandler() const
         {
             return m_handler.get();
diff --git a/service/resource-encapsulation/src/serverBuilder/src/RCSSeparateResponse.cpp b/service/resource-encapsulation/src/serverBuilder/src/RCSSeparateResponse.cpp
new file mode 100755 (executable)
index 0000000..8a9e1c0
--- /dev/null
@@ -0,0 +1,95 @@
+//******************************************************************\r
+//\r
+// Copyright 2015 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
+#include "RCSSeparateResponse.h"\r
+\r
+#include "RCSRequest.h"\r
+#include "RCSResourceObject.h"\r
+#include "RCSRepresentation.h"\r
+#include "AssertUtils.h"\r
+\r
+#include "OCPlatform.h"\r
+#include "OCResourceResponse.h"\r
+#include "OCResourceRequest.h"\r
+\r
+namespace OIC\r
+{\r
+    namespace Service\r
+    {\r
+\r
+        namespace\r
+        {\r
+            void validateRequest(const RCSRequest& request)\r
+            {\r
+                if (!request.getOCRequest() || request.getResourceObject().expired())\r
+                {\r
+                    throw RCSInvalidParameterException{\r
+                        "The request is incomplete. The resource for the request might be destroyed." };\r
+                }\r
+            }\r
+        }\r
+\r
+        RCSSeparateResponse::RCSSeparateResponse(const RCSRequest& request) :\r
+                m_request{ request },\r
+                m_done{ false }\r
+        {\r
+            validateRequest(m_request);\r
+        }\r
+\r
+        RCSSeparateResponse::RCSSeparateResponse(RCSRequest&& request) :\r
+                m_request{ std::move(request) },\r
+                m_done{ false }\r
+        {\r
+            validateRequest(m_request);\r
+        }\r
+\r
+        void RCSSeparateResponse::set()\r
+        {\r
+            if (!m_request.getOCRequest())\r
+            {\r
+                throw RCSBadRequestException{ "The state of this object is invalid!" };\r
+            }\r
+\r
+            auto resObj = m_request.getResourceObject().lock();\r
+            if (!resObj)\r
+            {\r
+                throw RCSBadRequestException{ "ResourceObject is unspecified(or destroyed)!" };\r
+            }\r
+\r
+            if (m_done) throw RCSBadRequestException{ "The response is already set!" };\r
+\r
+            auto ocRequest = m_request.getOCRequest();\r
+            auto response = std::make_shared< OC::OCResourceResponse >();\r
+\r
+            response->setRequestHandle(ocRequest->getRequestHandle());\r
+            response->setResourceHandle(ocRequest->getResourceHandle());\r
+\r
+            response->setResponseResult(OC_EH_OK);\r
+\r
+            response->setResourceRepresentation(\r
+                    RCSRepresentation::toOCRepresentation(resObj->getRepresentation(m_request)));\r
+\r
+            invokeOCFunc(OC::OCPlatform::sendResponse, response);\r
+\r
+            m_done = true;\r
+        }\r
+\r
+    }\r
+}\r
index f1facbc..04967dc 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#include <RequestHandler.h>
+#include "RequestHandler.h"
 
-#include <OCResourceResponse.h>
-#include <ResourceAttributesConverter.h>
-#include <RCSResourceObject.h>
-#include <ResourceAttributesUtils.h>
-
-#include <octypes.h>
+#include "ResourceAttributesConverter.h"
+#include "RCSResourceObject.h"
+#include "ResourceAttributesUtils.h"
 
 namespace
 {
     using namespace OIC::Service;
 
-    typedef std::function< OC::OCRepresentation(RCSResourceObject&) > OCRepresentationGetter;
-
-    OC::OCRepresentation getOCRepresentationFromResource(RCSResourceObject& resource)
-    {
-        RCSResourceObject::LockGuard lock{ resource, RCSResourceObject::AutoNotifyPolicy::NEVER };
-        return ResourceAttributesConverter::toOCRepresentation(resource.getAttributes());
-    }
-
-    OC::OCRepresentation getOCRepresentation(const RCSResourceAttributes& attrs)
-    {
-        return ResourceAttributesConverter::toOCRepresentation(attrs);
-    }
-
-    template< typename T >
-    OCRepresentationGetter wrapGetOCRepresentation(T&& attrs)
-    {
-        return std::bind(getOCRepresentation, std::forward<T>(attrs));
-    }
-
-    std::shared_ptr< OC::OCResourceResponse > doBuildResponse(RCSResourceObject& resource,
-             int errorCode, OCRepresentationGetter ocRepGetter)
-    {
-        auto response = std::make_shared< OC::OCResourceResponse >();
-
-        response->setResponseResult(OC_EH_OK);
-        response->setErrorCode(errorCode);
-        response->setResourceRepresentation(ocRepGetter(resource));
-
-        return response;
-    }
-
     AttrKeyValuePairs applyAcceptMethod(RCSResourceObject& resource,
             const RCSResourceAttributes& requestAttrs)
     {
@@ -117,35 +83,48 @@ namespace OIC
         constexpr int RequestHandler::DEFAULT_ERROR_CODE;
 
         RequestHandler::RequestHandler() :
-                m_holder{ std::bind(doBuildResponse, std::placeholders::_1, DEFAULT_ERROR_CODE,
-                        getOCRepresentationFromResource) }
+                m_errorCode{ DEFAULT_ERROR_CODE },
+                m_customRep{ false },
+                m_ocRep{ }
         {
         }
 
         RequestHandler::RequestHandler(int errorCode) :
-                m_holder{ std::bind(doBuildResponse, std::placeholders::_1, errorCode,
-                        getOCRepresentationFromResource) }
+                m_errorCode{ errorCode },
+                m_customRep{ false },
+                m_ocRep{ }
+
         {
         }
 
         RequestHandler::RequestHandler(const RCSResourceAttributes& attrs, int errorCode) :
-                m_holder{ std::bind(doBuildResponse, std::placeholders::_1, errorCode,
-                        wrapGetOCRepresentation(attrs)) }
+                m_errorCode{ errorCode },
+                m_customRep{ true },
+                m_ocRep{ ResourceAttributesConverter::toOCRepresentation(attrs) }
         {
         }
 
         RequestHandler::RequestHandler(RCSResourceAttributes&& attrs, int errorCode) :
-                m_holder{ std::bind(doBuildResponse, std::placeholders::_1, errorCode,
-                        wrapGetOCRepresentation(std::move(attrs))) }
+                m_errorCode{ errorCode },
+                m_customRep{ true },
+                m_ocRep{ ResourceAttributesConverter::toOCRepresentation(std::move(attrs)) }
         {
         }
 
-        std::shared_ptr< OC::OCResourceResponse > RequestHandler::buildResponse(
-                RCSResourceObject& resource)
+        int RequestHandler::getErrorCode() const
         {
-            return m_holder(resource);
+            return m_errorCode;
         }
 
+        bool RequestHandler::hasCustomRepresentation() const
+        {
+            return m_customRep;
+        }
+
+        OC::OCRepresentation RequestHandler::getRepresentation() const
+        {
+            return m_ocRep;
+        }
 
         SetRequestHandler::SetRequestHandler() :
                 RequestHandler{ }
index ba441fd..d942636 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#include <UnitTestHelper.h>
+#include "UnitTestHelper.h"
 
-#include <RCSResourceObject.h>
+#include "RCSResourceObject.h"
+#include "RCSRequest.h"
+#include "RCSSeparateResponse.h"
+#include "InterfaceHandler.h"
+#include "ResourceAttributesConverter.h"
 
-#include <OCPlatform.h>
+#include "OCPlatform.h"
 
 using namespace std;
 using namespace std::placeholders;
@@ -38,7 +42,8 @@ typedef OCStackResult (*NotifyAllObservers)(OCResourceHandle);
 constexpr char RESOURCE_URI[]{ "a/test" };
 constexpr char RESOURCE_TYPE[]{ "resourcetype" };
 constexpr char KEY[]{ "key" };
-constexpr int value{ 100 };
+constexpr char CUSTOM_INTERFACE[]{ "oic.if.custom" };
+constexpr int VALUE{ 100 };
 
 TEST(ResourceObjectBuilderCreateTest, ThrowIfUriIsInvalid)
 {
@@ -86,6 +91,39 @@ TEST_F(ResourceObjectBuilderTest, ResourceServerHasAttrsSetByBuilder)
     EXPECT_EQ(attrs, serverResource->getAttributes());
 }
 
+TEST_F(ResourceObjectBuilderTest, TypesAddedInBuilderWillBeBound)
+{
+    int count = 0;
+    mocks.OnCallFunc(OCPlatform::bindTypeToResource).Do(
+            [&count](const OCResourceHandle&, const std::string&)
+            {
+                ++count;
+                return OC_STACK_OK;
+            }
+    );
+
+    auto serverResource = RCSResourceObject::Builder(RESOURCE_URI, RESOURCE_TYPE, "").
+            addType("1").addType("2").build();
+
+    EXPECT_EQ(2, count);
+}
+
+TEST_F(ResourceObjectBuilderTest, InterfaceAddedInBuilderWillBeBound)
+{
+    int count = 0;
+    mocks.OnCallFunc(OCPlatform::bindInterfaceToResource).Do(
+            [&count](const OCResourceHandle&, const std::string&)
+            {
+                ++count;
+                return OC_STACK_OK;
+            }
+    );
+
+    auto serverResource = RCSResourceObject::Builder(RESOURCE_URI, RESOURCE_TYPE, "").
+            addInterface("1").addInterface("2").build();
+
+    EXPECT_EQ(2, count);
+}
 
 class ResourceObjectTest: public TestWithMock
 {
@@ -122,10 +160,10 @@ TEST_F(ResourceObjectTest, AccessAttributesWithLock)
     {
         RCSResourceObject::LockGuard lock{ server };
         auto& attr = server->getAttributes();
-        attr[KEY] = value;
+        attr[KEY] = VALUE;
     }
 
-    ASSERT_EQ(value, server->getAttribute<int>(KEY));
+    ASSERT_EQ(VALUE, server->getAttribute<int>(KEY));
 }
 
 TEST_F(ResourceObjectTest, ThrowIfTryToAccessAttributesWithoutGuard)
@@ -137,10 +175,10 @@ TEST_F(ResourceObjectTest, SettingAttributesWithinGuardDoesntCauseDeadLock)
 {
     {
         RCSResourceObject::LockGuard guard{ server };
-        server->setAttribute(KEY, value);
+        server->setAttribute(KEY, VALUE);
     }
 
-    ASSERT_EQ(value, server->getAttribute<int>(KEY));
+    ASSERT_EQ(VALUE, server->getAttribute<int>(KEY));
 }
 
 TEST_F(ResourceObjectTest, SettingNestedAttributesIsSameToGettingNestedAttributes)
@@ -164,7 +202,35 @@ TEST_F(ResourceObjectTest, SettingNestedVectorAttributesIsSameToGettingNestedVec
 
     server->setAttribute(KEY, arr31);
 
-    ASSERT_EQ(arr31, server->getAttribute<vector<vector<vector<int>>>>(KEY));
+    ASSERT_EQ(arr31, server->getAttributeValue(KEY));
+}
+
+TEST_F(ResourceObjectTest, ThrowIfResourceToBindIsInvalid)
+{
+    ASSERT_THROW(server->bindResource(server), RCSInvalidParameterException);
+}
+
+TEST_F(ResourceObjectTest, ThrowIfBindResourceFailed)
+{
+    mocks.OnCallFunc(OCBindResource).Return(OC_STACK_ERROR);
+
+    ASSERT_THROW(server->bindResource(
+            RCSResourceObject::Builder("a/temp", RESOURCE_TYPE, "").build()), RCSPlatformException);
+}
+
+TEST_F(ResourceObjectTest, ThrowIfResourceToUnbindIsInvalid)
+{
+    ASSERT_THROW(server->unbindResource(server), RCSInvalidParameterException);
+}
+
+TEST_F(ResourceObjectTest, BoundResourceCanBeRetrieved)
+{
+    mocks.OnCallFunc(OCBindResource).Return(OC_STACK_OK);
+
+    auto boundResource = RCSResourceObject::Builder("a/temp", RESOURCE_TYPE, "").build();
+    server->bindResource(boundResource);
+
+    ASSERT_EQ(boundResource, server->getBoundResources()[0]);
 }
 
 
@@ -197,23 +263,23 @@ TEST_F(AutoNotifyTest, AutoNotifyPolicyCanBeSet)
 TEST_F(AutoNotifyTest, WithUpdatedPolicy_NeverBeNotifiedIfAttributeIsNotChanged)
 {
     server->setAutoNotifyPolicy(RCSResourceObject::AutoNotifyPolicy::UPDATED);
-    server->setAttribute(KEY, value);
+    server->setAttribute(KEY, VALUE);
 
     mocks.NeverCallFuncOverload(static_cast< NotifyAllObservers >(
             OC::OCPlatform::notifyAllObservers));
 
-    server->setAttribute(KEY, value);
+    server->setAttribute(KEY, VALUE);
 }
 
 TEST_F(AutoNotifyTest, WithUpdatedPolicy_WillBeNotifiedIfAttributeIsChanged)
 {
     server->setAutoNotifyPolicy(RCSResourceObject::AutoNotifyPolicy::UPDATED);
-    server->setAttribute(KEY, value);
+    server->setAttribute(KEY, VALUE);
 
     mocks.ExpectCallFuncOverload(static_cast< NotifyAllObservers >(
             OC::OCPlatform::notifyAllObservers)).Return(OC_STACK_OK);
 
-    server->setAttribute(KEY, value + 1);
+    server->setAttribute(KEY, VALUE + 1);
 }
 
 TEST_F(AutoNotifyTest, WithUpdatedPolicy_WillBeNotifiedIfValueIsAdded)
@@ -224,7 +290,7 @@ TEST_F(AutoNotifyTest, WithUpdatedPolicy_WillBeNotifiedIfValueIsAdded)
     mocks.ExpectCallFuncOverload(static_cast< NotifyAllObservers >(
             OC::OCPlatform::notifyAllObservers)).Return(OC_STACK_OK);
 
-    server->setAttribute(newKey, value);
+    server->setAttribute(newKey, VALUE);
 }
 
 TEST_F(AutoNotifyTest, WithNeverPolicy_NeverBeNotifiedEvenIfAttributeIsChanged)
@@ -235,13 +301,13 @@ TEST_F(AutoNotifyTest, WithNeverPolicy_NeverBeNotifiedEvenIfAttributeIsChanged)
             OC::OCPlatform::notifyAllObservers));
 
     RCSResourceObject::LockGuard lock{ server };
-    server->setAttribute(KEY, value);
+    server->setAttribute(KEY, VALUE);
 }
 
 TEST_F(AutoNotifyTest, WithUpdatePolicy_WillBeNotifiedIfAttributeIsDeleted)
 {
     server->setAutoNotifyPolicy(RCSResourceObject::AutoNotifyPolicy::UPDATED);
-    server->setAttribute(KEY, value);
+    server->setAttribute(KEY, VALUE);
 
     mocks.ExpectCallFuncOverload(static_cast< NotifyAllObservers >(
             OC::OCPlatform::notifyAllObservers)).Return(OC_STACK_OK);
@@ -261,7 +327,7 @@ TEST_F(AutoNotifyWithGuardTest, GuardFollowsServerPolicyByDefault)
             OC::OCPlatform::notifyAllObservers)).Return(OC_STACK_OK);
 
     RCSResourceObject::LockGuard guard{ server };
-    server->setAttribute(KEY, value);
+    server->setAttribute(KEY, VALUE);
 }
 
 TEST_F(AutoNotifyWithGuardTest, GuardCanOverridePolicy)
@@ -272,7 +338,7 @@ TEST_F(AutoNotifyWithGuardTest, GuardCanOverridePolicy)
             OC::OCPlatform::notifyAllObservers));
 
     RCSResourceObject::LockGuard guard{ server, RCSResourceObject::AutoNotifyPolicy::NEVER };
-    server->getAttributes()[KEY] = value;
+    server->getAttributes()[KEY] = VALUE;
 }
 
 TEST_F(AutoNotifyWithGuardTest, GuardInvokesNotifyWhenDestroyed)
@@ -284,17 +350,15 @@ TEST_F(AutoNotifyWithGuardTest, GuardInvokesNotifyWhenDestroyed)
 
     {
         RCSResourceObject::LockGuard guard{ server, RCSResourceObject::AutoNotifyPolicy::ALWAYS };
-        server->setAttribute(KEY, value);
+        server->setAttribute(KEY, VALUE);
     }
 
     mocks.NeverCallFuncOverload(static_cast< NotifyAllObservers >(
                OC::OCPlatform::notifyAllObservers)).Return(OC_STACK_OK);
 
-    server->setAttribute(KEY, value);
+    server->setAttribute(KEY, VALUE);
 }
 
-
-
 class ResourceObjectHandlingRequestTest: public ResourceObjectTest
 {
 public:
@@ -307,7 +371,7 @@ public:
 
 public:
     OCResourceRequest::Ptr createRequest(OCMethod method = OC_REST_GET, OCRepresentation ocRep =
-            OCRepresentation{})
+            OCRepresentation{}, const string& interface="")
     {
         auto request = make_shared<OCResourceRequest>();
 
@@ -322,6 +386,12 @@ public:
         ocEntityHandlerRequest.method = method;
         ocEntityHandlerRequest.payload = reinterpret_cast<OCPayload*>(mc.getPayload());
 
+        if(!interface.empty())
+        {
+            const string query = string("if=" + interface);
+            ocEntityHandlerRequest.query = const_cast<char *> (query.c_str());
+        }
+
         formResourceRequest(OC_REQUEST_FLAG, &ocEntityHandlerRequest, request);
 
         return request;
@@ -396,7 +466,7 @@ TEST_F(ResourceObjectHandlingRequestTest, SendResponseWithRCSResponseResults)
 TEST_F(ResourceObjectHandlingRequestTest, SendSetResponseWithCustomAttrs)
 {
     constexpr int errorCode{ 1999 };
-    constexpr char value[]{ "value" };
+    constexpr char value[]{ "VALUE" };
 
     server->setSetRequestHandler(
             [](const RCSRequest&, RCSResourceAttributes&) -> RCSSetResponse
@@ -415,9 +485,225 @@ TEST_F(ResourceObjectHandlingRequestTest, SendSetResponseWithCustomAttrs)
             }
     ).Return(OC_STACK_OK);
 
-    ASSERT_EQ(OC_EH_OK, handler(createRequest(OC_REST_PUT)));
+    ASSERT_EQ(OC_EH_OK, handler(createRequest(OC_REST_POST)));
 }
 
+TEST_F(ResourceObjectHandlingRequestTest, SeparateResponseIsSlowResponse)
+{
+    server->setGetRequestHandler(
+            [](const RCSRequest&, RCSResourceAttributes&) -> RCSGetResponse
+            {
+                return RCSGetResponse::separate();
+            }
+    );
+
+    ASSERT_EQ(OC_EH_SLOW, handler(createRequest()));
+}
+
+TEST_F(ResourceObjectHandlingRequestTest, SetMethodOfSeparateResponseInvokesSendResponse)
+{
+    RCSRequest aRequest;
+    server->setGetRequestHandler(
+            [&aRequest](const RCSRequest& request, RCSResourceAttributes&) -> RCSGetResponse
+            {
+                aRequest = request;
+                return RCSGetResponse::separate();
+            }
+    );
+    handler(createRequest(OC_REST_GET));
+
+    mocks.ExpectCallFunc(OCPlatform::sendResponse).Return(OC_STACK_OK);
+
+    RCSSeparateResponse(aRequest).set();
+}
+
+TEST_F(ResourceObjectHandlingRequestTest, SetMethodOfSeparateResponseThrowsIfTheResourceIsDestroyed)
+{
+    RCSRequest aRequest;
+    server->setGetRequestHandler(
+            [&aRequest](const RCSRequest& request, RCSResourceAttributes&) -> RCSGetResponse
+            {
+                aRequest = request;
+                return RCSGetResponse::separate();
+            }
+    );
+    handler(createRequest(OC_REST_GET));
+
+    RCSSeparateResponse resp(aRequest);
+
+    server.reset();
+
+    EXPECT_THROW(resp.set(), RCSBadRequestException);
+}
+
+static bool checkResponse(const OCRepresentation& ocRep, const RCSResourceAttributes& rcsAttr,
+            const std::vector<std::string>& interfaces,
+            const std::vector<std::string>& resourceTypes, const std::string& resourceUri)
+{
+    return resourceUri == ocRep.getUri() &&
+           interfaces == ocRep.getResourceInterfaces() &&
+           resourceTypes == ocRep.getResourceTypes() &&
+           rcsAttr == ResourceAttributesConverter::fromOCRepresentation(ocRep);
+}
+
+static bool compareResponse(const OCRepresentation& ocRep1, const OCRepresentation& ocRep2)
+{
+    return ocRep1.getUri() == ocRep2.getUri() &&
+           ocRep1.getResourceInterfaces() == ocRep2.getResourceInterfaces() &&
+           ocRep1.getResourceTypes() == ocRep2.getResourceTypes() &&
+           ResourceAttributesConverter::fromOCRepresentation(ocRep1) ==
+                   ResourceAttributesConverter::fromOCRepresentation(ocRep2);
+}
+
+class ResourceObjectInterfaceHandlerTest: public ResourceObjectHandlingRequestTest
+{
+public:
+    void initServer(vector<string> interfaces,
+                const std::string& defaultInterface = BASELINE_INTERFACE)
+    {
+        auto initBuilder = RCSResourceObject::Builder(RESOURCE_URI, RESOURCE_TYPE,
+                BASELINE_INTERFACE);
+
+        for(const auto& itf : interfaces)
+        {
+            initBuilder.addInterface(itf);
+        }
+
+        RCSResourceAttributes rcsAttr;
+        rcsAttr[KEY] = 2;
+        initBuilder.setAttributes(rcsAttr);
+        initBuilder.setDefaultInterface(defaultInterface);
+
+        server = initBuilder.build();
+        server->setAutoNotifyPolicy(RCSResourceObject::AutoNotifyPolicy::NEVER);
+        server->setSetRequestHandlerPolicy(RCSResourceObject::SetRequestHandlerPolicy::ACCEPTANCE);
+    }
+
+protected:
+
+    void SetUp()
+    {
+        TestWithMock::SetUp();
+
+        initMocks();
+    }
+
+    void initMocks()
+    {
+        ResourceObjectHandlingRequestTest::initMocks();
+
+        mocks.OnCallFunc(OCPlatform::bindInterfaceToResource).Return(OC_STACK_OK);
+    }
+};
+
+TEST_F(ResourceObjectInterfaceHandlerTest, GetResponseForBaselineContainsAllPropertiesOfServer)
+{
+    initServer({BASELINE_INTERFACE});
+
+    OCRepresentation ocRep;
+
+    mocks.ExpectCallFunc(OCPlatform::sendResponse).Match(
+            [=](const shared_ptr<OCResourceResponse> response)
+            {
+                RCSResourceObject::LockGuard guard{ server };
+
+                return checkResponse(response->getResourceRepresentation(),
+                        server->getAttributes(), server->getInterfaces(), server->getTypes(),
+                        server->getUri());
+
+            }
+    ).Return(OC_STACK_OK);
+
+    handler(createRequest(OC_REST_GET, ocRep, BASELINE_INTERFACE));
+}
+
+TEST_F(ResourceObjectInterfaceHandlerTest, SetResponseForActuatorContainsOnlyRequestedAttributes)
+{
+    initServer({ACTUATOR_INTERFACE});
+
+    OCRepresentation ocRep;
+    ocRep[KEY] = VALUE;
+
+    mocks.ExpectCallFunc(OCPlatform::sendResponse).Match(
+            [&ocRep](const shared_ptr<OCResourceResponse> response)
+            {
+                return checkResponse(response->getResourceRepresentation(),
+                        ResourceAttributesConverter::fromOCRepresentation(ocRep), {}, {}, "");
+            }
+    ).Return(OC_STACK_OK);
+
+    handler(createRequest(OC_REST_POST, ocRep, ACTUATOR_INTERFACE));
+}
+
+TEST_F(ResourceObjectInterfaceHandlerTest, SetResponseForBaselineContainsAppliedAttributes)
+{
+    initServer({BASELINE_INTERFACE});
+
+    OCRepresentation ocRep;
+    ocRep["NEWKEY"] = std::string("NEWVALUE");
+
+    mocks.ExpectCallFunc(OCPlatform::sendResponse).Match(
+            [=](const shared_ptr<OCResourceResponse> response)
+            {
+                RCSResourceObject::LockGuard guard{ server };
+
+                return checkResponse(response->getResourceRepresentation(),
+                        server->getAttributes(), server->getInterfaces(), server->getTypes(),
+                        server->getUri());
+            }
+    ).Return(OC_STACK_OK);
+
+    handler(createRequest(OC_REST_POST, ocRep, BASELINE_INTERFACE));
+}
+
+TEST_F(ResourceObjectInterfaceHandlerTest, GetResponseForCustomEqualsResponseForDefault)
+{
+    initServer({CUSTOM_INTERFACE});
+
+    OCRepresentation ocRep;
+    OCRepresentation repArray[2];
+    int cnt = 0;
+
+    mocks.OnCallFunc(OCPlatform::sendResponse).Do(
+            [&repArray, &cnt](const shared_ptr<OCResourceResponse> response)
+            {
+                repArray[cnt++] = response->getResourceRepresentation();
+                return OC_STACK_OK;
+            }
+    );
+
+    handler(createRequest(OC_REST_GET, ocRep, CUSTOM_INTERFACE));
+    handler(createRequest(OC_REST_GET, ocRep, server->getDefaultInterface()));
+
+    EXPECT_EQ(cnt, 2);
+    EXPECT_TRUE(compareResponse(repArray[0], repArray[1]));
+}
+
+TEST_F(ResourceObjectInterfaceHandlerTest, SetRequestForSensorGotNoHandler)
+{
+    initServer({SENSOR_INTERFACE});
+
+    OCRepresentation ocRep;
+    ocRep[KEY] = VALUE;
+
+    EXPECT_EQ(OC_EH_ERROR, handler(createRequest(OC_REST_POST, ocRep, SENSOR_INTERFACE)));
+}
+
+TEST_F(ResourceObjectInterfaceHandlerTest, ThrowIfDefaultInterfaceIsInvalid)
+{
+    auto builder = RCSResourceObject::Builder(RESOURCE_URI, RESOURCE_TYPE, BASELINE_INTERFACE);
+
+    ASSERT_THROW(builder.setDefaultInterface(ACTUATOR_INTERFACE), RCSBadRequestException);
+}
+
+TEST_F(ResourceObjectInterfaceHandlerTest, SettingDefaultInterfaceEqualsGetDefaultInterface)
+{
+    initServer({SENSOR_INTERFACE}, BASELINE_INTERFACE);
+
+    EXPECT_EQ(BASELINE_INTERFACE, server->getDefaultInterface());
+}
+
+
 
 class SetRequestHandlerPolicyTest: public ResourceObjectHandlingRequestTest
 {
@@ -428,14 +714,7 @@ public:
     OCRepresentation createOCRepresentation()
     {
         OCRepresentation ocRep;
-
-        vector<string> interface{"oic.if.baseline"};
-        vector<string> type{"core.light"};
-
-        ocRep.setUri(RESOURCE_URI);
-        ocRep.setResourceInterfaces(interface);
-        ocRep.setResourceTypes(type);
-
+        ocRep[KEY] = VALUE;
         return ocRep;
     }
 
@@ -460,31 +739,28 @@ TEST_F(SetRequestHandlerPolicyTest, SetRequestHandlerPolicyCanBeSet)
                 server->getSetRequestHandlerPolicy());
 }
 
-TEST_F(SetRequestHandlerPolicyTest, WithNeverPolicy_NotAddedIfReceivedNewKeyValuePair)
+TEST_F(SetRequestHandlerPolicyTest, WithNeverPolicy_DeniedIfKeyIsNew)
 {
-    OCRepresentation ocRep = createOCRepresentation();
-    ocRep.setValue("NewKey", value);
     server->setSetRequestHandlerPolicy(RCSResourceObject::SetRequestHandlerPolicy::NEVER);
 
-    handler(createRequest(OC_REST_PUT, ocRep));
+    handler(createRequest(OC_REST_POST, createOCRepresentation()));
 
     RCSResourceObject::LockGuard guard{ server };
-    ASSERT_FALSE((server->getAttributes()).contains("NewKey"));
+    ASSERT_FALSE(server->getAttributes().contains(KEY));
 }
 
-TEST_F(SetRequestHandlerPolicyTest, WithAcceptancePolicy_WillBeAddedIfReceivedNewKeyValuePair)
+TEST_F(SetRequestHandlerPolicyTest, WithAcceptancePolicy_AcceptedEvenIfKeyIsNew)
 {
-    OCRepresentation ocRep = createOCRepresentation();
-    ocRep.setValue("NewKey", value);
     server->setSetRequestHandlerPolicy(RCSResourceObject::SetRequestHandlerPolicy::ACCEPTANCE);
 
-    handler(createRequest(OC_REST_PUT, ocRep));
+    handler(createRequest(OC_REST_POST, createOCRepresentation()));
 
     RCSResourceObject::LockGuard guard{ server };
-    ASSERT_TRUE((server->getAttributes()).contains("NewKey"));
+    ASSERT_TRUE(server->getAttributes().contains(KEY));
 }
 
 
+
 class ResourceObjectSynchronizationTest: public ResourceObjectHandlingRequestTest
 {
 public:
@@ -566,7 +842,7 @@ TEST_F(ResourceObjectSynchronizationTest, MultipleAccessToServerResourceWithRequ
             for (int i=0; i<10000; ++i)
             {
                 if (i % 5 == 0) handler(createRequest(OC_REST_OBSERVE));
-                handler(createRequest((i & 1) ? OC_REST_GET : OC_REST_PUT));
+                handler(createRequest((i & 1) ? OC_REST_GET : OC_REST_POST));
             }
         }
     });
@@ -580,6 +856,7 @@ TEST_F(ResourceObjectSynchronizationTest, MultipleAccessToServerResourceWithRequ
 }
 
 
+
 class AttributeUpdatedListenerTest: public ResourceObjectHandlingRequestTest
 {
 public:
@@ -589,98 +866,82 @@ public:
     OCRepresentation createOCRepresentation(void)
     {
         OCRepresentation ocRep;
-
-        vector<string> interface{"oic.if.baseline"};
-        vector<string> type{"core.light"};
-
-        ocRep.setUri(RESOURCE_URI);
-        ocRep.setResourceInterfaces(interface);
-        ocRep.setResourceTypes(type);
-        ocRep[KEY] = value;
-
+        ocRep[KEY] = VALUE;
         return ocRep;
     }
 
-    void initMocks()
+protected:
+    void SetUp()
     {
-        ResourceObjectHandlingRequestTest::initMocks();
+        ResourceObjectHandlingRequestTest::SetUp();
         mocks.OnCallFunc(OCPlatform::sendResponse).Return(OC_STACK_OK);
+
+        server->setAttribute(KEY, 0);
     }
 };
 
-class FunctionsForAttributeUpdatedListener
+class AttributeUpdatedListener
 {
 public:
-    virtual void fCalled(const OIC::Service::RCSResourceAttributes::Value&,
-        const OIC::Service::RCSResourceAttributes::Value&)=0;
-    virtual void fNotCalled(const OIC::Service::RCSResourceAttributes::Value&,
+    virtual void onUpdated(const OIC::Service::RCSResourceAttributes::Value&,
         const OIC::Service::RCSResourceAttributes::Value&)=0;
+
+    virtual ~AttributeUpdatedListener() {}
 };
 
-TEST_F(AttributeUpdatedListenerTest, AddListenerRunsAddedFunction)
-{
-    FunctionsForAttributeUpdatedListener *ptrMock =
-        mocks.Mock<FunctionsForAttributeUpdatedListener>();
 
-    server->setAttribute(KEY, 0);
+TEST_F(AttributeUpdatedListenerTest, RemoveListenerReturnsFalseIfListenerIsNotAdded)
+{
+    ASSERT_FALSE(server->removeAttributeUpdatedListener(KEY));
+}
 
-    mocks.ExpectCall(ptrMock, FunctionsForAttributeUpdatedListener::fCalled);
+TEST_F(AttributeUpdatedListenerTest, RemoveListenerReturnsTrueIfListenerIsAdded)
+{
+    auto listener = mocks.Mock< AttributeUpdatedListener >();
 
     server->addAttributeUpdatedListener(KEY,
-        (std::bind(&FunctionsForAttributeUpdatedListener::fCalled, ptrMock, _1, _2)));
+            std::bind(&AttributeUpdatedListener::onUpdated, listener, _1, _2));
 
-    handler(createRequest(OC_REST_PUT, createOCRepresentation()));
+    ASSERT_TRUE(server->removeAttributeUpdatedListener(KEY));
 }
 
-TEST_F(AttributeUpdatedListenerTest, AddListenerRunsAccordingToLastAddedFunction)
+TEST_F(AttributeUpdatedListenerTest, AddListenerRunsAddedFunction)
 {
-    FunctionsForAttributeUpdatedListener *ptrMock =
-        mocks.Mock<FunctionsForAttributeUpdatedListener>();
-
-    string duplicateKEY(KEY);
-    server->setAttribute(KEY, 0);
-
-    mocks.ExpectCall(ptrMock, FunctionsForAttributeUpdatedListener::fCalled);
-    mocks.NeverCall(ptrMock, FunctionsForAttributeUpdatedListener::fNotCalled);
+    auto listener = mocks.Mock< AttributeUpdatedListener >();
 
-    server->addAttributeUpdatedListener(duplicateKEY,
-        (std::bind(&FunctionsForAttributeUpdatedListener::fNotCalled, ptrMock, _1, _2)));
     server->addAttributeUpdatedListener(KEY,
-        (std::bind(&FunctionsForAttributeUpdatedListener::fCalled, ptrMock, _1, _2)));
+            std::bind(&AttributeUpdatedListener::onUpdated, listener, _1, _2));
 
-    handler(createRequest(OC_REST_PUT, createOCRepresentation()));
-}
+    mocks.ExpectCall(listener, AttributeUpdatedListener::onUpdated);
 
-TEST_F(AttributeUpdatedListenerTest, RemoveListenerReturnsTrueIfListenerIsNotAdded)
-{
-    ASSERT_FALSE(server->removeAttributeUpdatedListener(KEY));
+    handler(createRequest(OC_REST_POST, createOCRepresentation()));
 }
 
-TEST_F(AttributeUpdatedListenerTest, RemoveListenerReturnsTrueIfListenerIsAdded)
+TEST_F(AttributeUpdatedListenerTest, ListenerWithSameKeyOverridesPreviousOne)
 {
-    FunctionsForAttributeUpdatedListener *ptrMock =
-        mocks.Mock<FunctionsForAttributeUpdatedListener>();
+    auto first = mocks.Mock< AttributeUpdatedListener >();
+    auto second = mocks.Mock< AttributeUpdatedListener >();
 
+    mocks.NeverCall(first, AttributeUpdatedListener::onUpdated);
+    mocks.ExpectCall(second, AttributeUpdatedListener::onUpdated);
+
+    server->addAttributeUpdatedListener(KEY,
+            std::bind(&AttributeUpdatedListener::onUpdated, first, _1, _2));
     server->addAttributeUpdatedListener(KEY,
-        (std::bind(&FunctionsForAttributeUpdatedListener::fNotCalled, ptrMock, _1, _2)));
+            std::bind(&AttributeUpdatedListener::onUpdated, second, _1, _2));
 
-    ASSERT_TRUE(server->removeAttributeUpdatedListener(KEY));
+    handler(createRequest(OC_REST_POST, createOCRepresentation()));
 }
 
-TEST_F(AttributeUpdatedListenerTest, RemoveListenerNeverRunsRemovedFunc)
+TEST_F(AttributeUpdatedListenerTest, RemovedListenerNotBeInvoked)
 {
-    FunctionsForAttributeUpdatedListener *ptrMock =
-        mocks.Mock<FunctionsForAttributeUpdatedListener>();
+    auto listener = mocks.Mock< AttributeUpdatedListener >();
+    server->addAttributeUpdatedListener(KEY,
+            std::bind(&AttributeUpdatedListener::onUpdated, listener, _1, _2));
 
-    mocks.NeverCall(ptrMock, FunctionsForAttributeUpdatedListener::fNotCalled);
+    mocks.NeverCall(listener, AttributeUpdatedListener::onUpdated);
 
-    server->setAttribute(KEY, 0);
-    server->addAttributeUpdatedListener(KEY,
-        (std::bind(&FunctionsForAttributeUpdatedListener::fNotCalled, ptrMock, _1, _2)));
     server->removeAttributeUpdatedListener(KEY);
 
-    handler(createRequest(OC_REST_PUT, createOCRepresentation()));
+    handler(createRequest(OC_REST_POST, createOCRepresentation()));
 }
-
-
-
index 2ba3817..0e7acd3 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#include <UnitTestHelper.h>
+#include "UnitTestHelper.h"
 
-#include <RCSResponse.h>
-#include <RCSResourceObject.h>
-
-#include <RequestHandler.h>
-#include <ResourceAttributesConverter.h>
-
-#include <OCPlatform.h>
-
-using namespace std;
+#include "RCSResponse.h"
+#include "RCSSeparateResponse.h"
+#include "RCSException.h"
 
 using namespace OIC::Service;
-using namespace OC;
-
-typedef OCStackResult (*registerResourceSig)(OCResourceHandle&,
-                       string&,
-                       const string&,
-                       const string&,
-                       EntityHandler,
-                       uint8_t );
-
-static constexpr char KEY[] = "key";
-
-
-void EXPECT_RESPONSE(shared_ptr< OCResourceResponse > ocResponse, int errorCode,
-        const RCSResourceAttributes& attrs)
-{
-    EXPECT_EQ(ocResponse->getErrorCode(), errorCode);
-    EXPECT_EQ(ResourceAttributesConverter::fromOCRepresentation(
-                    ocResponse->getResourceRepresentation()), attrs);
-}
-
-
-class RCSResponseTest: public TestWithMock
-{
-public:
-    template< typename T >
-    shared_ptr< OCResourceResponse > buildResponse(const T& response)
-    {
-        RCSResourceObject::Ptr server =
-                RCSResourceObject::Builder("a/test", "", "").build();
-
-        return response.getHandler()->buildResponse(*server);
-    }
-
-protected:
-    void SetUp()
-    {
-        TestWithMock::SetUp();
-
-        mocks.OnCallFuncOverload(static_cast< registerResourceSig >(OCPlatform::registerResource))
-                .Return(OC_STACK_OK);
-
-        mocks.OnCallFunc(OCPlatform::unregisterResource).Return(OC_STACK_OK);
-    }
-};
-
-TEST_F(RCSResponseTest, GetDefaultActionHasEmptyAttrs)
-{
-    EXPECT_RESPONSE(buildResponse(RCSGetResponse::defaultAction()),
-            RequestHandler::DEFAULT_ERROR_CODE, RCSResourceAttributes());
-}
-
-TEST_F(RCSResponseTest, GetResponseHasResultsPassedCodes)
-{
-    constexpr int errorCode{ -10 };
-
-    EXPECT_RESPONSE(buildResponse(RCSGetResponse::create(errorCode)),
-            errorCode, RCSResourceAttributes());
-}
-
-TEST_F(RCSResponseTest, GetResponseHasAttrsAndResultsPassedCodes)
-{
-    constexpr int errorCode{ -10 };
-
-    RCSResourceAttributes attrs;
-    attrs[KEY] = 100;
-
-    EXPECT_RESPONSE(buildResponse(RCSGetResponse::create(attrs, errorCode)), errorCode, attrs);
-}
-
-TEST_F(RCSResponseTest, GetResponseCanMoveAttrs)
-{
-    constexpr int errorCode{ -10 };
-
-    RCSResourceAttributes attrs;
-    attrs[KEY] = 100;
 
-    RCSResourceAttributes attrsClone;
-    attrsClone[KEY] = 100;
-
-    EXPECT_RESPONSE(
-            buildResponse(RCSGetResponse::create(std::move(attrs), errorCode)),
-            errorCode, attrsClone);
-
-    EXPECT_TRUE(attrs.empty());
-}
-
-TEST_F(RCSResponseTest, SetDefaultActionHasEmptyAttrs)
-{
-    EXPECT_RESPONSE(buildResponse(RCSSetResponse::defaultAction()),
-            RequestHandler::DEFAULT_ERROR_CODE, RCSResourceAttributes());
-}
-
-TEST_F(RCSResponseTest, SetResponseHasResultsPassedCodes)
-{
-    constexpr int errorCode{ -10 };
-
-    EXPECT_RESPONSE(buildResponse(RCSSetResponse::create(errorCode)),
-            errorCode, RCSResourceAttributes());
-}
-
-TEST_F(RCSResponseTest, SetResponseHasAttrsAndResultsPassedCodes)
-{
-    constexpr int errorCode{ -10 };
-
-    RCSResourceAttributes attrs;
-    attrs[KEY] = 100;
-
-    EXPECT_RESPONSE(buildResponse(RCSSetResponse::create(attrs, errorCode)),
-            errorCode, attrs);
-}
-
-TEST_F(RCSResponseTest, SetResponseCanMoveAttrs)
-{
-    constexpr int errorCode{ -10 };
-
-    RCSResourceAttributes attrs;
-    attrs[KEY] = 100;
-
-    RCSResourceAttributes attrsClone;
-    attrsClone[KEY] = 100;
-
-    EXPECT_RESPONSE(buildResponse(RCSSetResponse::create(std::move(attrs), errorCode)),
-            errorCode, attrsClone);
-
-    EXPECT_TRUE(attrs.empty());
-}
-
-
-TEST_F(RCSResponseTest, DefaultSetResponseHasDefaultMethod)
+TEST(RCSResponseTest, DefaultSetResponseHasDefaultMethod)
 {
     EXPECT_EQ(RCSSetResponse::AcceptanceMethod::DEFAULT,
             RCSSetResponse::defaultAction().getAcceptanceMethod());
 }
 
-TEST_F(RCSResponseTest, AcceptSetResponseHasAcceptMethod)
+TEST(RCSResponseTest, AcceptSetResponseHasAcceptMethod)
 {
     EXPECT_EQ(RCSSetResponse::AcceptanceMethod::ACCEPT,
             RCSSetResponse::accept().getAcceptanceMethod());
 }
 
-TEST_F(RCSResponseTest, IgnoreSetResponseHasIgnoreMethod)
+TEST(RCSResponseTest, IgnoreSetResponseHasIgnoreMethod)
 {
     EXPECT_EQ(RCSSetResponse::AcceptanceMethod::IGNORE,
             RCSSetResponse::ignore().getAcceptanceMethod());
 }
 
-TEST_F(RCSResponseTest, SetResponseHasMethodSetBySetter)
+TEST(RCSResponseTest, SetResponseHasMethodSetBySetter)
 {
     RCSSetResponse::AcceptanceMethod method = RCSSetResponse::AcceptanceMethod::ACCEPT;
     RCSSetResponse response =
@@ -185,3 +52,16 @@ TEST_F(RCSResponseTest, SetResponseHasMethodSetBySetter)
 
     EXPECT_EQ(method, response.getAcceptanceMethod());
 }
+
+TEST(RCSResponseTest, SeparateResponseHasNoHandler)
+{
+    RCSGetResponse response = RCSGetResponse::separate();
+    EXPECT_EQ(nullptr, response.getHandler());
+}
+
+TEST(RCSResponseTest, ThrowIfRequestIsInvalidWhenConstructingSeparateResponse)
+{
+    RCSRequest aRequest;
+
+    EXPECT_THROW(RCSSeparateResponse resp(aRequest), RCSInvalidParameterException);
+}
index 7eba605..bc3b53e 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#include <UnitTestHelper.h>
+#include "UnitTestHelper.h"
 
-#include <RequestHandler.h>
-#include <RCSResourceObject.h>
+#include "RequestHandler.h"
+#include "RCSResourceObject.h"
+#include "ResourceAttributesConverter.h"
 
-#include <OCPlatform.h>
+#include "OCPlatform.h"
 
 using namespace std;
 
@@ -37,73 +38,51 @@ constexpr int NEW_VALUE{ 1 };
 typedef OCStackResult (*RegisterResource)(OCResourceHandle&, std::string&,
         const std::string&, const std::string&, OC::EntityHandler, uint8_t);
 
-class RequestHandlerTest: public TestWithMock
+TEST(RequestHandlerTest, DefaultHasNoCustomRepresntation)
 {
-public:
-    RCSResourceObject::Ptr server;
-
-protected:
-    void SetUp()
-    {
-        TestWithMock::SetUp();
-
-        mocks.OnCallFuncOverload(static_cast<RegisterResource>(OC::OCPlatform::registerResource))
-                .Return(OC_STACK_OK);
-
-        mocks.OnCallFunc(OC::OCPlatform::unregisterResource).Return(OC_STACK_OK);
-
-        server = RCSResourceObject::Builder("a/test", "resourcetype", "").build();
-
-        server->setAutoNotifyPolicy(RCSResourceObject::AutoNotifyPolicy::NEVER);
-        server->setAttribute(EXISTING, ORIGIN_VALUE);
-    }
-};
-
-TEST_F(RequestHandlerTest, ResponseHasSameValuesPassedToHandlerConstructor)
-{
-    RequestHandler handler{ -1000 };
-
-    auto response = handler.buildResponse(*server);
-
-    ASSERT_EQ(-1000, response->getErrorCode());
+    ASSERT_FALSE(RequestHandler().hasCustomRepresentation());
 }
 
-TEST_F(RequestHandlerTest, ResponseHasSameAttrsWithServerAttrs)
+TEST(RequestHandlerTest, HasCustomRepresentationIfConstructedWithAttributes)
 {
-    RequestHandler handler{};
-
-    auto response = handler.buildResponse(*server);
-
-    ASSERT_EQ(ORIGIN_VALUE, response->getResourceRepresentation()[EXISTING].getValue<int>());
+    ASSERT_TRUE(RequestHandler(RCSResourceAttributes{ }).hasCustomRepresentation());
 }
 
-TEST_F(RequestHandlerTest, ResponseHasAttrsSetByCustomAttrRequestHandler)
+TEST(RequestHandlerTest, CustomRepresentationContainsSameAttributesPassedToConstructor)
 {
-    constexpr char key[] { "key" };
-    constexpr int newValue{ 100 };
-
     RCSResourceAttributes attrs;
-    attrs[key] = newValue;
-    RequestHandler handler{ attrs };
+    attrs[EXISTING] = ORIGIN_VALUE;
 
-    auto response = handler.buildResponse(*server);
+    RequestHandler handler(attrs);
 
-    ASSERT_EQ(ORIGIN_VALUE, response->getResourceRepresentation()[key].getValue<int>());
+    auto converted = ResourceAttributesConverter::fromOCRepresentation(handler.getRepresentation());
+    ASSERT_EQ(attrs, converted);
 }
 
 
-
-class SetRequestHandlerAcceptanceTest: public RequestHandlerTest
+class SetRequestHandlerAcceptanceTest: public TestWithMock
 {
 public:
-    SetRequestHandler::Ptr setRequestHandler;
+    RCSResourceObject::Ptr server;
+
+    std::shared_ptr< SetRequestHandler > setRequestHandler;
 
     RCSResourceAttributes requestAttrs;
 
 protected:
     void SetUp()
     {
-        RequestHandlerTest::SetUp();
+        TestWithMock::SetUp();
+
+        mocks.OnCallFuncOverload(static_cast<RegisterResource>(OC::OCPlatform::registerResource))
+                .Return(OC_STACK_OK);
+
+        mocks.OnCallFunc(OC::OCPlatform::unregisterResource).Return(OC_STACK_OK);
+
+        server = RCSResourceObject::Builder("a/test", "resourcetype", "").build();
+
+        server->setAutoNotifyPolicy(RCSResourceObject::AutoNotifyPolicy::NEVER);
+        server->setAttribute(EXISTING, ORIGIN_VALUE);
 
         setRequestHandler = make_shared< SetRequestHandler >();
 
old mode 100644 (file)
new mode 100755 (executable)
index 361bfc1..7572022
 
 #include "OCPlatform.h"
 
-#include <condition_variable>
-#include <mutex>
-
 using namespace OIC::Service;
+using namespace OC;
 using namespace OC::OCPlatform;
 
-constexpr char RESOURCEURI[]{ "/a/TemperatureSensor" };
-constexpr char RESOURCETYPE[]{ "resource.type" };
-constexpr char RESOURCEINTERFACE[]{ "oic.if.baseline" };
-constexpr int DEFAULT_DISCOVERYTASK_DELAYTIME = 3000;
+typedef std::unique_ptr< RCSDiscoveryManager::DiscoveryTask > DiscoveryTaskPtr;
 
-void resourceDiscoveredForCall(RCSRemoteResourceObject::Ptr) {}
-void resourceDiscoveredForNeverCall(RCSRemoteResourceObject::Ptr) {}
+typedef OCStackResult (*OCFindResource)(const std::string&, const std::string&,
+            OCConnectivityType, FindCallback);
 
-class DiscoveryManagerTest: public TestWithMock
-{
-public:
+constexpr char RESOURCE_URI[]{ "/a/TemperatureSensor" };
+constexpr char RESOURCE_TYPE[]{ "resource.type" };
+constexpr char SECOND_RESOURCETYPE[]{ "resource.type.second" };
 
-    typedef std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> DiscoveryTaskPtr;
-    typedef std::function< void(std::shared_ptr< RCSRemoteResourceObject >) >
-                                       ResourceDiscoveredCallback;
-public:
+void onResourceDiscovered(RCSRemoteResourceObject::Ptr) {}
 
-    static DiscoveryTaskPtr discoverResource(ResourceDiscoveredCallback cb)
-    {
-        const std::string uri  = "/oic/res";
-        return RCSDiscoveryManager::getInstance()->discoverResourceByType(RCSAddress::multicast(),
-                 uri, RESOURCETYPE, cb);
-    }
-
-    void startDiscovery()
-    {
-        discoveryTask = discoverResource(resourceDiscoveredForCall);
-    }
-
-    void cancelDiscovery()
-    {
-        discoveryTask->cancel();
-    }
-
-    bool isCanceled()
+class ScopedTask
+{
+public:
+    ScopedTask(DiscoveryTaskPtr&& task) :
+        m_task{ std::move(task) }
     {
-        return discoveryTask->isCanceled();
     }
 
-    void createResource()
+    ~ScopedTask()
     {
-        server = RCSResourceObject::Builder(RESOURCEURI, RESOURCETYPE, RESOURCEINTERFACE).build();
+        if (m_task) m_task->cancel();
     }
 
-    void proceed()
+    RCSDiscoveryManager::DiscoveryTask* operator->()
     {
-        cond.notify_all();
+        return m_task.get();
     }
 
-    void waitForDiscoveryTask(int waitingTime = DEFAULT_DISCOVERYTASK_DELAYTIME)
-    {
-        std::unique_lock< std::mutex > lock{ mutex };
-        cond.wait_for(lock, std::chrono::milliseconds{ waitingTime });
-    }
+    ScopedTask(ScopedTask&&) = default;
+    ScopedTask& operator=(ScopedTask&&) = default;
 
 private:
-
-    std::condition_variable cond;
-    std::mutex mutex;
-    RCSResourceObject::Ptr server;
-    RCSRemoteResourceObject::Ptr object;
-    DiscoveryTaskPtr discoveryTask;
+    DiscoveryTaskPtr m_task;
 };
 
-TEST_F(DiscoveryManagerTest, resourceIsNotSupportedPresenceBeforeDiscovering)
+TEST(DiscoveryManagerTest, ThrowIfDiscoverWithEmptyCallback)
 {
-    createResource();
-
-    mocks.ExpectCallFunc(resourceDiscoveredForCall).Do(
-        [this](RCSRemoteResourceObject::Ptr){ proceed();});
-
-    startDiscovery();
-    waitForDiscoveryTask();
+    EXPECT_THROW(RCSDiscoveryManager::getInstance()->discoverResource(RCSAddress::multicast(), { }),
+            RCSInvalidParameterException);
 }
 
-TEST_F(DiscoveryManagerTest, resourceIsSupportedPresenceBeforeDiscovering)
+TEST(DiscoveryManagerTest, ThrowIfDiscoverWithMultipleTypesThatContainEmptyString)
 {
-    startPresence(10);
-    createResource();
-
-    mocks.ExpectCallFunc(resourceDiscoveredForCall).Do(
-        [this](RCSRemoteResourceObject::Ptr){ proceed();});
-
-    startDiscovery();
-    waitForDiscoveryTask();
-    stopPresence();
+    EXPECT_THROW(RCSDiscoveryManager::getInstance()->discoverResourceByTypes(
+            RCSAddress::multicast(), { "a", "" }, onResourceDiscovered), RCSBadRequestException);
 }
 
-TEST_F(DiscoveryManagerTest, resourceIsNotSupportedPresenceAfterDiscovering)
+TEST(DiscoveryManagerTest, DiscoverInvokesFindResource)
 {
-    mocks.ExpectCallFunc(resourceDiscoveredForCall).Do(
-        [this](RCSRemoteResourceObject::Ptr){ proceed();});
-
-    startDiscovery();
-    createResource();
-    waitForDiscoveryTask();
+    MockRepository mocks;
+    mocks.ExpectCallFuncOverload(static_cast<OCFindResource>(findResource)).Match(
+        [](const std::string& host, const std::string& resourceURI, OCConnectivityType, FindCallback)
+        {
+            return host.empty() && resourceURI == (std::string(RESOURCE_URI) + "?rt=" + RESOURCE_TYPE);
+        }
+    ).Return(OC_STACK_OK);
+
+    ScopedTask task {RCSDiscoveryManager::getInstance()->discoverResourceByType(
+            RCSAddress::multicast(), RESOURCE_URI, RESOURCE_TYPE, onResourceDiscovered)};
 }
 
-TEST_F(DiscoveryManagerTest, resourceIsSupportedPresenceAndAfterDiscovering)
+TEST(DiscoveryManagerTest, DiscoverWithMultipleTypesInvokesFindResourceMultipleTimes)
 {
-    mocks.ExpectCallFunc(resourceDiscoveredForCall).Do(
-        [this](RCSRemoteResourceObject::Ptr){ proceed();});
-
-    startPresence(10);
-    startDiscovery();
-    createResource();
-    waitForDiscoveryTask();
-    stopPresence();
+    MockRepository mocks;
+    const std::vector< std::string > resourceTypes{ RESOURCE_TYPE, SECOND_RESOURCETYPE };
+    size_t counter = 0;
+
+    mocks.OnCallFuncOverload(static_cast<OCFindResource>(findResource)).Do(
+        [&counter](const std::string&, const std::string&, OCConnectivityType, FindCallback)
+        {
+            ++counter;
+            return OC_STACK_OK;
+        }
+    ).Return(OC_STACK_OK);
+
+    ScopedTask task {RCSDiscoveryManager::getInstance()->discoverResourceByTypes(
+            RCSAddress::multicast(), resourceTypes, onResourceDiscovered)};
+
+    EXPECT_EQ(counter, resourceTypes.size());
 }
 
-TEST_F(DiscoveryManagerTest, cancelDiscoveryTaskAfterDiscoveryResource)
+TEST(DiscoveryManagerTest, TaskCanBeCanceled)
 {
-    startDiscovery();
-    cancelDiscovery();
+    ScopedTask aTask {RCSDiscoveryManager::getInstance()->discoverResource(RCSAddress::multicast(),
+            onResourceDiscovered)};
+    ScopedTask aTaskToBeCanceled {RCSDiscoveryManager::getInstance()->discoverResource(
+            RCSAddress::multicast(), onResourceDiscovered)};
 
-    mocks.NeverCallFunc(resourceDiscoveredForCall);
+    aTaskToBeCanceled->cancel();
 
-    waitForDiscoveryTask();
-    createResource();
+    ASSERT_FALSE(aTask->isCanceled());
+    ASSERT_TRUE(aTaskToBeCanceled->isCanceled());
 }
 
-TEST_F(DiscoveryManagerTest, cancelDiscoveryTaskNotStartDiscoveryResource)
-{
-    startDiscovery();
-    cancelDiscovery();
-    cancelDiscovery();
-}
+TEST(DiscoveryManagerTest, CallbackWouldNotBeCalledForSameRemoteResource) {
+    FindCallback callback;
 
-TEST_F(DiscoveryManagerTest, isCanceledAfterCancelDiscoveryTask)
-{
-    startDiscovery();
-    cancelDiscovery();
+    MockRepository mocks;
+    mocks.OnCallFuncOverload(static_cast<OCFindResource>(findResource)).Do(
+       [&callback](const std::string&, const std::string&, OCConnectivityType, FindCallback cb)
+       {
+           callback = cb;
+           return OC_STACK_OK;
+       }
+   ).Return(OC_STACK_OK);
 
-    ASSERT_TRUE(isCanceled());
-}
-
-TEST_F(DiscoveryManagerTest, multipleDiscoveryRequestAndCancelJustOneDiscoveryRequest)
-{
-    DiscoveryTaskPtr canceledTask = discoverResource(resourceDiscoveredForCall);
-    DiscoveryTaskPtr notCanceledTask_1 = discoverResource(resourceDiscoveredForCall);
-    DiscoveryTaskPtr notCanceledTask_2 = discoverResource(resourceDiscoveredForCall);
-
-    canceledTask->cancel();
-
-    ASSERT_TRUE(canceledTask->isCanceled());
-    ASSERT_FALSE(notCanceledTask_1->isCanceled());
-    ASSERT_FALSE(notCanceledTask_2->isCanceled());
-}
-
-TEST_F(DiscoveryManagerTest, equalDiscoveryRequestsAndCancelJustOneRequest)
-{
-    mocks.ExpectCallFunc(resourceDiscoveredForCall).Do(
-        [this](RCSRemoteResourceObject::Ptr){ proceed();});
+    ScopedTask aTask {RCSDiscoveryManager::getInstance()->discoverResource(RCSAddress::multicast(),
+            onResourceDiscovered)};
 
-    mocks.NeverCallFunc(resourceDiscoveredForNeverCall);
+    std::vector< std::string > interfaces{ "interface" };
+    std::vector< std::string > resourceTypes{ "resource.type" };
+    constexpr char fakeHost[] { "coap://127.0.0.1:1" };
 
-    DiscoveryTaskPtr notCanceledTask = discoverResource(resourceDiscoveredForCall);
-    DiscoveryTaskPtr canceledTask = discoverResource(resourceDiscoveredForNeverCall);
-    canceledTask->cancel();
+    mocks.ExpectCallFunc(onResourceDiscovered);
+    callback(OCPlatform::constructResourceObject(fakeHost, "/uri", OCConnectivityType::CT_ADAPTER_IP,
+            true, interfaces, resourceTypes));
 
-    createResource();
-    waitForDiscoveryTask();
+    mocks.NeverCallFunc(onResourceDiscovered);
+    callback(OCPlatform::constructResourceObject(fakeHost, "/uri", OCConnectivityType::CT_ADAPTER_IP,
+            true, interfaces, resourceTypes));
 }
index a0e5274..171531b 100644 (file)
@@ -24,6 +24,7 @@
 #include "RCSDiscoveryManager.h"
 #include "RCSResourceObject.h"
 #include "RCSAddress.h"
+#include "RCSRequest.h"
 
 #include <condition_variable>
 #include <mutex>
@@ -94,12 +95,12 @@ private:
     {
         for (int i=0; i<10 && !object; ++i)
         {
-            const std::string uri  = "/oic/res";
             auto discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(
-                    RCSAddress::multicast(), uri, RESOURCETYPE,
+                    RCSAddress::multicast(), RESOURCETYPE,
                     std::bind(&RemoteResourceObjectTest::resourceDiscovered, this,
                             std::placeholders::_1));
             Wait(1000);
+            discoveryTask->cancel();
         }
     }
 
@@ -163,6 +164,44 @@ TEST_F(RemoteResourceObjectTest, SetRemoteAttributesSetsAttributesOfServer)
     ASSERT_EQ(newValue, server->getAttributeValue(ATTR_KEY));
 }
 
+TEST_F(RemoteResourceObjectTest, QueryParamsForGetWillBePassedToBase)
+{
+    class CustomHandler
+    {
+    public:
+        virtual RCSGetResponse handle(const RCSRequest&, RCSResourceAttributes&) = 0;
+        virtual ~CustomHandler() {}
+    };
+
+    constexpr char PARAM_KEY[] { "aKey" };
+    constexpr char VALUE[] { "value" };
+
+    object->get(RCSQueryParams().setResourceInterface(RESOURCEINTERFACE).setResourceType(RESOURCETYPE).
+            put(PARAM_KEY, VALUE),
+            [](const HeaderOpts&, const RCSRepresentation&, int){});
+
+    auto mockHandler = mocks.Mock< CustomHandler >();
+
+    mocks.ExpectCall(mockHandler, CustomHandler::handle).
+            Match([](const RCSRequest& request, RCSResourceAttributes&)
+            {
+                return request.getInterface() == RESOURCEINTERFACE &&
+                        request.getQueryParams().at(PARAM_KEY) == VALUE;
+            }
+    ).
+            Do([this](const RCSRequest&, RCSResourceAttributes&)
+            {
+                Proceed();
+                return RCSGetResponse::defaultAction();
+            }
+    );
+
+    server->setGetRequestHandler(std::bind(&CustomHandler::handle, mockHandler,
+            std::placeholders::_1, std::placeholders::_2));
+
+    Wait();
+}
+
 TEST_F(RemoteResourceObjectTest, MonitoringIsNotStartedByDefault)
 {
     ASSERT_FALSE(object->isMonitoring());
index 13e68c2..6e02574 100644 (file)
@@ -90,11 +90,12 @@ else :
 
 resourcehosting_env.InstallTarget(resourcehostingsdk, 'libresource_hosting')
 resourcehosting_env.UserInstallTargetLib(resourcehostingsdk, 'libresource_hosting')
-resourcehosting_env.UserInstallTargetHeader('include/Hosting.h', 'iotivity-service', 'Hosting.h')
+resourcehosting_env.UserInstallTargetHeader('include/Hosting.h',\
+       'service/resource-hosting', 'Hosting.h')
 
 # Go to build Unit test
 if target_os == 'linux':
-       SConscript('src/unittest/SConscript')
+       SConscript('unittest/SConscript')
 
 # Go to build sample apps
 SConscript('SampleApp/SConscript')
index f46b880..c9b9e9b 100644 (file)
@@ -38,7 +38,7 @@ const int SUCCESS_RESPONSE = OC_STACK_OK;
 
 #define OBSERVE 1
 #define GET     2
-#define PUT     3
+#define POST    3
 #define DELETE  4
 
 std::shared_ptr< OCResource > g_curResource;
@@ -49,7 +49,7 @@ OCStackResult nmfindResource(const std::string &host , const std::string &resour
 void onObserve(const HeaderOptions &headerOption , const OCRepresentation &rep , const int &eCode,
                const int &sequenceNumber);
 
-void onPut(const HeaderOptions &headerOption, const OCRepresentation &rep, const int eCode);
+void onPost(const HeaderOptions &headerOption, const OCRepresentation &rep, const int eCode);
 void onGet(const HeaderOptions &headerOption , const OCRepresentation &rep , const int eCode);
 void onDelete(const HeaderOptions &headerOption , const int eCode);
 
@@ -113,7 +113,7 @@ void startGet(std::shared_ptr< OCResource > resource)
         std::cout << "To Fail resource get() process" << std::endl;
 }
 
-void startPut(std::shared_ptr< OCResource > resource)
+void startPost(std::shared_ptr< OCResource > resource)
 {
     if (resource == NULL)
     {
@@ -127,8 +127,8 @@ void startPut(std::shared_ptr< OCResource > resource)
     rep.setValue("humidity", 10);
 
     QueryParamsMap test;
-    if (OC_STACK_OK != resource->put(rep, test, &onPut))
-        std::cout << "To Fail resource put() process" << std::endl;
+    if (OC_STACK_OK != resource->post(rep, test, &onPost))
+        std::cout << "To Fail resource post() process" << std::endl;
 }
 
 void startDelete(std::shared_ptr< OCResource > resource)
@@ -236,13 +236,13 @@ void getRepresentation(std::shared_ptr< OCResource > resource)
     }
 }
 
-void onPut(const HeaderOptions &/*headerOption*/, const OCRepresentation &rep, const int eCode)
+void onPost(const HeaderOptions &/*headerOption*/, const OCRepresentation &rep, const int eCode)
 {
     try
     {
         if (eCode == OC_STACK_OK)
         {
-            std::cout << "PUT request was successful" << std::endl;
+            std::cout << "POST request was successful" << std::endl;
             int humidity;
             int temperature;
             rep.getValue("temperature", temperature);
@@ -254,13 +254,13 @@ void onPut(const HeaderOptions &/*headerOption*/, const OCRepresentation &rep, c
         }
         else
         {
-            std::cout << "onPut Response error: " << eCode << std::endl;
+            std::cout << "onPost Response error: " << eCode << std::endl;
             std::exit(-1);
         }
     }
     catch (std::exception &e)
     {
-        std::cout << "Exception: " << e.what() << " in onPut" << std::endl;
+        std::cout << "Exception: " << e.what() << " in onPost" << std::endl;
     }
 }
 
@@ -328,7 +328,7 @@ void PRINT()
     std::cout << "********************************************" << std::endl;
     std::cout << "*  method Type : 1 - Observe               *" << std::endl;
     std::cout << "*  method Type : 2 - Get                   *" << std::endl;
-    std::cout << "*  method Type : 3 - Put                   *" << std::endl;
+    std::cout << "*  method Type : 3 - Post                  *" << std::endl;
     std::cout << "********************************************" << std::endl;
     std::cout << std::endl;
 }
@@ -377,8 +377,8 @@ int main()
                 case GET:
                     startGet(g_curResource);
                     break;
-                case PUT:
-                    startPut(g_curResource);
+                case POST:
+                    startPost(g_curResource);
                     break;
                 default:
                     std::cout << "Invalid input, please try again" << std::endl;
index 0aaa0cf..bb99443 100644 (file)
@@ -273,6 +273,22 @@ OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request
             else if (requestType == "POST")
             {
                 cout << "\t\t\trequestType : POST\n";
+                OCRepresentation rep = request->getResourceRepresentation();
+                myResource.put(rep);
+
+                if (pResponse)
+                {
+                    pResponse->setErrorCode(200);
+                    pResponse->setResourceRepresentation(myResource.get());
+                }
+                if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+                {
+                    ehResult = OC_EH_OK;
+                }
+                else
+                {
+                    cout << "post request Error\n";
+                }
             }
 
             else if (requestType == "DELETE")
index 08785c2..a3691c7 100644 (file)
                                     <listOptionValue builtIn="false" value="../../../../../../extlibs/cjson"/>
                                     <listOptionValue builtIn="false" value="../../../../include"/>
                                     <listOptionValue builtIn="false" value="../../../../src"/>
-                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\include&quot;"/>
-                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\c_common&quot;"/>
-                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\stack\include&quot;"/>
-                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\logger\include&quot;"/>
-                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\occoap\include&quot;"/>
-                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\ocrandom\include&quot;"/>
-                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\ocsocket\include&quot;"/>
-                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\oc_logger\include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;../../../../../../resource/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;../../../../../../resource/c_common&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;../../../../../../resource/csdk/stack/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;../../../../../../resource/csdk/logger/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;../../../../../../resource/csdk/occoap/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;../../../../../../resource/csdk/ocrandom/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;../../../../../../resource/csdk/ocsocket/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;../../../../../../resource/oc_logger/include&quot;"/>
                                 </option>
                                 <option id="sbi.gnu.cpp.compiler.option.frameworks.core.856851155" name="Tizen-Frameworks" superClass="sbi.gnu.cpp.compiler.option.frameworks.core" valueType="userObjs">
                                     <listOptionValue builtIn="false" value="Native_API"/>
index faca8ce..4f88097 100644 (file)
@@ -91,17 +91,16 @@ JNIEXPORT jint JNICALL Java_org_iotivity_ResourceHosting_ResourceHosting_OICCoor
 JNIEXPORT jint JNICALL Java_org_iotivity_ResourceHosting_ResourceHosting_ResourceHostingInit
 (JNIEnv *env, jobject obj,jstring j_addr)
 {
-    const char* addr = env->GetStringUTFChars(j_addr,NULL);
-
     if (NULL == j_addr)
+    {
         return (jint)OCSTACK_ERROR;
+    }
 
-    if(OCInit(addr,USE_RANDOM_PORT,OC_CLIENT_SERVER)!=OC_STACK_OK)
+    if(OCInit1(OC_CLIENT_SERVER, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS))
     {
         return (jint)OCSTACK_ERROR;
     }
 
-    env->ReleaseStringUTFChars(j_addr,addr);
     return (jint)OCSTACK_OK;
 }
 
@@ -118,10 +117,6 @@ JNIEXPORT jint JNICALL Java_org_iotivity_ResourceHosting_ResourceHosting_Resourc
         threadRun = false;
         ocProcessThread.join();
     }
-    else
-    {
-        return (jint)HOSTING_THREAD_ERROR;
-    }
 
     return (jint)OCSTACK_OK;
 }
index c7c2005..40b7546 100644 (file)
@@ -43,26 +43,21 @@ OCStackResult OICStartCoordinate()
         OIC_HOSTING_LOG(DEBUG,
                 "[OICStartCoordinate] platformException, reason:%s", e.what());
         retResult = OC_STACK_ERROR;
-        throw;
     }catch(const RCSInvalidParameterException &e)
     {
         OIC_HOSTING_LOG(DEBUG,
                 "[OICStartCoordinate] InvalidParameterException, reason:%s", e.what());
         retResult = OC_STACK_ERROR;
-        throw;
     }catch(...)
     {
         OIC_HOSTING_LOG(DEBUG, "[OICStartCoordinate] Unknown Exception");
         retResult = OC_STACK_ERROR;
     }
-
     return retResult;
 }
 
 OCStackResult OICStopCoordinate()
 {
-    OCStackResult retResult = OC_STACK_OK;
     OIC::Service::ResourceHosting::getInstance()->stopHosting();
-
-    return retResult;
+    return OC_STACK_OK;
 }
index 3c0a1c3..ffbd056 100644 (file)
 
 #include "HostingObject.h"
 
-namespace OIC
-{
-namespace Service
-{
+#include "RCSSeparateResponse.h"
+#include "RequestObject.h"
 
-void OIC_HOSTING_LOG(LogLevel level, const char * format, ...)
+namespace OIC
 {
-    if (!format)
+    namespace Service
     {
-        return;
-    }
-    char buffer[MAX_LOG_V_BUFFER_SIZE] = {};
-    va_list args;
-    va_start(args, format);
-    vsnprintf(buffer, sizeof buffer - 1, format, args);
-    va_end(args);
-    OCLog(level, PCF("Hosting"), buffer);
-}
 
-namespace
-{
-    std::mutex mutexForCB;
-}
+        namespace
+        {
+            const auto sizeofHostingTag = strlen("/hosting");
+        }
 
-HostingObject::HostingObject()
-: remoteObject(nullptr), mirroredServer(nullptr),
-  remoteState(ResourceState::NONE),
-  pStateChangedCB(nullptr), pDataUpdateCB(nullptr),
-  pDestroyCB(nullptr), pSetRequestHandler(nullptr)
-{
-}
+        HostingObject::HostingObject()
+        : remoteObject(nullptr), mirroredServer(nullptr),
+          pDataUpdateCB(nullptr), pDestroyCB(nullptr)
+        {
+        }
 
-HostingObject::~HostingObject()
-{
-       // shared_ptr release
-    pStateChangedCB = {};
-    pDataUpdateCB = {};
+        HostingObject::~HostingObject()
+        {
+            pDataUpdateCB = {};
 
-    if (remoteObject)
-    {
-        remoteObject->stopMonitoring();
-        remoteObject->stopCaching();
-    }
-}
+            if (remoteObject)
+            {
+                remoteObject->stopMonitoring();
+                remoteObject->stopCaching();
+            }
+        }
 
-HostingObject::RemoteObjectPtr HostingObject::getRemoteResource() const
-{
-    return remoteObject;
-}
+        auto HostingObject::getRemoteResource() const -> RemoteObjectPtr
+        {
+            return remoteObject;
+        }
 
-void HostingObject::initializeHostingObject(RemoteObjectPtr rResource, DestroyedCallback destroyCB)
-{
-    remoteObject = rResource;
+        auto HostingObject::createHostingObject(const RemoteObjectPtr & rResource,
+                DestroyedCallback destroyCB) -> Ptr
+        {
+            auto newObject = std::make_shared<HostingObject>();
 
-    pStateChangedCB = std::bind(&HostingObject::stateChangedCB, this,
-            std::placeholders::_1, remoteObject);
-    pDataUpdateCB = std::bind(&HostingObject::dataChangedCB, this,
-            std::placeholders::_1, remoteObject);
-    pDestroyCB = destroyCB;
+            newObject->remoteObject = rResource;
+            newObject->pDestroyCB = destroyCB;
 
-    pSetRequestHandler = std::bind(&HostingObject::setRequestHandler, this,
-            std::placeholders::_1, std::placeholders::_2);
+            newObject->pDataUpdateCB = std::bind(&HostingObject::dataChangedCB, newObject,
+                    std::placeholders::_1);
 
-    try
-    {
-        remoteObject->startMonitoring(pStateChangedCB);
-        remoteObject->startCaching(pDataUpdateCB);
-    }catch(...)
-    {
-        throw;
-    }
-}
+            newObject->remoteObject->startMonitoring(
+                    std::bind(&HostingObject::stateChangedCB, newObject,
+                            std::placeholders::_1));
+            newObject->remoteObject->startCaching(newObject->pDataUpdateCB);
 
-void HostingObject::destroyHostingObject()
-{
-    pDestroyCB();
-}
+            return newObject;
+        }
 
-void HostingObject::stateChangedCB(ResourceState state, RemoteObjectPtr rObject)
-{
-    remoteState = state;
+        void HostingObject::destroyHostingObject()
+        {
+            if (pDestroyCB) pDestroyCB();
+        }
 
-    switch (state)
-    {
-    case ResourceState::ALIVE:
-    {
-        if(rObject->isCaching() == false)
+        void HostingObject::stateChangedCB(ResourceState state)
         {
-            try
+            switch (state)
             {
-                rObject->startCaching(pDataUpdateCB);
-            }catch(const RCSInvalidParameterException &e)
+            case ResourceState::ALIVE:
             {
-                OIC_HOSTING_LOG(DEBUG,
-                        "[HostingObject::stateChangedCB]startCaching InvalidParameterException:%s",
-                        e.what());
+                if (!this->remoteObject->isCaching())
+                {
+                    try
+                    {
+                        this->remoteObject->startCaching(pDataUpdateCB);
+                    } catch (const RCSException & e)
+                    {
+                        OIC_HOSTING_LOG(DEBUG,
+                                "[HostingObject::stateChangedCB]startCaching InvalidParameterException:%s",
+                                e.what());
+                    }
+                }
+                break;
             }
-        }
-        break;
-    }
-    case ResourceState::LOST_SIGNAL:
-    case ResourceState::DESTROYED:
-    {
-        if(rObject->isCaching() == true)
-        {
-            try
-            {
-                rObject->stopCaching();
-            }catch(const RCSInvalidParameterException &e)
+            case ResourceState::LOST_SIGNAL:
+            case ResourceState::DESTROYED:
             {
-                OIC_HOSTING_LOG(DEBUG,
-                        "[HostingObject::stateChangedCB]stopCaching InvalidParameterException:%s",
-                        e.what());
+                try
+                {
+                    this->remoteObject->stopCaching();
+                    this->remoteObject->stopMonitoring();
+                } catch (const RCSException & e)
+                {
+                    OIC_HOSTING_LOG(DEBUG,
+                            "[HostingObject::stateChangedCB]stopWatching InvalidParameterException:%s",
+                            e.what());
+                }
+                mirroredServer.reset();
+                destroyHostingObject();
+                break;
+            }
+            default:
+                // not support of state
+                break;
             }
         }
-        if(rObject->isMonitoring() == true)
+
+        void HostingObject::dataChangedCB(const RCSResourceAttributes & attributes)
         {
-            try
+            if (attributes.empty())
             {
-                rObject->stopMonitoring();
-            }catch(const RCSInvalidParameterException &e)
-            {
-                OIC_HOSTING_LOG(DEBUG,
-                        "[HostingObject::stateChangedCB]stopWatching InvalidParameterException:%s",
-                        e.what());
+                return;
             }
-        }
-        mirroredServer = nullptr;
-        destroyHostingObject();
-        break;
-    }
-    default:
-        // not support of state
-        break;
-    }
-}
 
-void HostingObject::dataChangedCB(const RCSResourceAttributes & attributes, RemoteObjectPtr rObject)
-{
-    std::unique_lock<std::mutex> lock(mutexForCB);
-    if(attributes.empty())
-    {
-        return;
-    }
+            std::unique_lock<std::mutex> lock(mutexForCB);
+            if (mirroredServer == nullptr)
+            {
+                try
+                {
+                    mirroredServer = createMirroredServer(this->remoteObject);
+                } catch (const RCSException & e)
+                {
+                    OIC_HOSTING_LOG(DEBUG,
+                                "[HostingObject::dataChangedCB]createMirroredServer Exception:%s",
+                                e.what());
+                    return;
+                }
+            }
+            lock.unlock();
 
-    if(mirroredServer == nullptr)
-    {
-        try
-        {
-            mirroredServer = createMirroredServer(rObject);
-        }catch(const RCSPlatformException &e)
-        {
-            OIC_HOSTING_LOG(DEBUG,
-                        "[HostingObject::dataChangedCB]createMirroredServer PlatformException:%s",
-                        e.what());
-            mirroredServer = nullptr;
-            return;
+            RCSResourceObject::LockGuard guard(mirroredServer);
+            mirroredServer->getAttributes() = std::move(attributes);
         }
-    }
 
-    RCSResourceAttributes rData;
-    {
-        RCSResourceObject::LockGuard guard(mirroredServer);
-        rData = mirroredServer->getAttributes();
-    }
-    if(rData.empty() || rData != attributes)
-    {
+        auto HostingObject::createMirroredServer(RemoteObjectPtr rObject) -> ResourceObjectPtr
         {
-            RCSResourceObject::LockGuard guard(mirroredServer);
-            for(auto it = rData.begin(); ; ++it)
+            if (rObject == nullptr)
             {
-                if(it == rData.end())
-                {
-                    break;
-                }
-                mirroredServer->removeAttribute(it->key());
+                throw RCSPlatformException(OC_STACK_ERROR);
             }
 
-            for(auto it = attributes.begin();; ++it)
+            std::string fulluri = rObject->getUri();
+            std::string uri = fulluri.substr(0, fulluri.size() - sizeofHostingTag);
+            std::vector<std::string> types = rObject->getTypes();
+            std::vector<std::string> interfaces = rObject->getInterfaces();
+            try
             {
-                if(it == attributes.end())
+                auto resourceBuild = RCSResourceObject::Builder(uri, types[0], interfaces[0]);
+                for (unsigned int i = 1; i < types.size(); ++i)
+                {
+                    resourceBuild.addType(types[i]);
+                }
+                for (unsigned int i = 1; i < interfaces.size(); ++i)
                 {
-                    break;
+                    resourceBuild.addInterface(interfaces[i]);
                 }
-                mirroredServer->setAttribute(it->key(), it->value());
+                auto retResource = resourceBuild.build();
+
+                retResource->setAutoNotifyPolicy(RCSResourceObject::AutoNotifyPolicy::UPDATED);
+                retResource->setSetRequestHandler(
+                        std::bind(&HostingObject::setRequestHandler, this,
+                                std::placeholders::_1, std::placeholders::_2));
+                return retResource;
+            } catch (...)
+            {
+                OIC_HOSTING_LOG(DEBUG, "[HostingObject::createMirroredServer] %s", "Exception");
+                throw;
             }
         }
-    }
-}
 
-HostingObject::ResourceObjectPtr HostingObject::createMirroredServer(RemoteObjectPtr rObject)
-{
-    ResourceObjectPtr retResource = nullptr;
-    if(rObject != nullptr)
-    {
-        std::string fulluri = rObject->getUri();
-        std::string uri = fulluri.substr(0, fulluri.size()-8);
-        std::vector<std::string> types = rObject->getTypes();
-        std::vector<std::string> interfaces = rObject->getInterfaces();
-        try
-        {
-            std::string type = types.begin()->c_str();
-            std::string interface = interfaces.begin()->c_str();
-            retResource = RCSResourceObject::Builder(uri, type, interface).
-                    setDiscoverable(true).setObservable(true).build();
-
-            // TODO need to bind types and interfaces
-            retResource->setAutoNotifyPolicy(RCSResourceObject::AutoNotifyPolicy::UPDATED);
-            retResource->setSetRequestHandler(pSetRequestHandler);
-        }catch(...)
+        RCSSetResponse HostingObject::setRequestHandler(const RCSRequest & primitiveRequest,
+                    RCSResourceAttributes & resourceAttibutes)
         {
-            OIC_HOSTING_LOG(DEBUG, "[HostingObject::createMirroredServer] %s", "PlatformException");
-            throw;
-        }
-    }
-    else
-    {
-        throw RCSPlatformException(OC_STACK_ERROR);
-    }
-
-    return retResource;
-}
+            try
+            {
+                RequestObject::invokeRequest(getRemoteResource(),
+                        primitiveRequest, RequestObject::RequestMethod::Set, resourceAttibutes);
 
-RCSSetResponse HostingObject::setRequestHandler(const RCSRequest & primitiveRequest,
-            RCSResourceAttributes & resourceAttibutes)
-{
-    (void)primitiveRequest;
-    try
-    {
-        RequestObject newRequest = { };
-        newRequest.invokeRequest(remoteObject, RequestObject::RequestMethod::Setter,
-                resourceAttibutes);
-    }catch(const RCSPlatformException &e)
-    {
-        OIC_HOSTING_LOG(DEBUG,
-                "[HostingObject::setRequestHandler] PlatformException:%s",
-                e.what());
-        throw;
-    }
+            } catch (const RCSPlatformException & e)
+            {
+                OIC_HOSTING_LOG(DEBUG,
+                        "[HostingObject::setRequestHandler] PlatformException:%s",
+                        e.what());
+                throw;
+            }
 
-    return RCSSetResponse::create(resourceAttibutes);
-}
+            return RCSSetResponse::separate();
+        }
 
-} /* namespace Service */
+    } /* namespace Service */
 } /* namespace OIC */
old mode 100644 (file)
new mode 100755 (executable)
index 4469bd2..4ff3df8
 
 #include "RCSRemoteResourceObject.h"
 #include "RCSResourceObject.h"
-#include "RequestObject.h"
+
+#define OIC_HOSTING_LOG(level, fmt, args...) OIC_LOG_V((level), PCF("Hosting"), fmt, ##args)
 
 namespace OIC
 {
-namespace Service
-{
+    namespace Service
+    {
 
-void OIC_HOSTING_LOG(LogLevel level, const char * format, ...);
-
-class HostingObject
-{
-private:
-    typedef std::shared_ptr<RCSResourceObject> ResourceObjectPtr;
-    typedef std::shared_ptr<RCSRemoteResourceObject> RemoteObjectPtr;
-    typedef std::shared_ptr<RequestObject> RequestObjectPtr;
-    typedef std::shared_ptr<PrimitiveResource> PrimiteveResourcePtr;
+        class HostingObject
+        {
+        private:
+            typedef RCSResourceObject::Ptr ResourceObjectPtr;
+            typedef RCSRemoteResourceObject::Ptr RemoteObjectPtr;
 
-public:
-    typedef std::shared_ptr<HostingObject> Ptr;
-    typedef std::function<void(ResourceState)> BrokerCallback;
-    typedef std::function<void(const RCSResourceAttributes &)> CacheCallback;
-    typedef std::function<void()> DestroyedCallback;
+        public:
+            typedef std::shared_ptr<HostingObject> Ptr;
+            typedef std::weak_ptr<HostingObject> wPtr;
 
-    typedef std::function<
-            RCSSetResponse(const RCSRequest&, RCSResourceAttributes&)> SetRequestHandler;
+            typedef std::function<void()> DestroyedCallback;
+            typedef RCSRemoteResourceObject::StateChangedCallback BrokerCallback;
+            typedef RCSRemoteResourceObject::CacheUpdatedCallback CacheCallback;
+            typedef RCSResourceObject::SetRequestHandler SetRequestHandler;
 
-public:
-    HostingObject();
-    ~HostingObject();
+        public:
+            HostingObject();
+            ~HostingObject();
 
-    void initializeHostingObject(RemoteObjectPtr rResource, DestroyedCallback destroyCB);
+            HostingObject(const HostingObject &) = delete;
+            HostingObject & operator = (const HostingObject &) = delete;
 
-    RemoteObjectPtr getRemoteResource() const;
+            HostingObject(HostingObject &&) = delete;
+            HostingObject & operator = (HostingObject &&) = delete;
 
-private:
-    RemoteObjectPtr remoteObject;
-    ResourceObjectPtr mirroredServer;
+            static HostingObject::Ptr createHostingObject(const RemoteObjectPtr & rResource,
+                    DestroyedCallback destroyCB);
 
-    ResourceState remoteState;
+            RemoteObjectPtr getRemoteResource() const;
 
-    BrokerCallback pStateChangedCB;
-    CacheCallback pDataUpdateCB;
-    DestroyedCallback pDestroyCB;
+        private:
+            RemoteObjectPtr remoteObject;
+            ResourceObjectPtr mirroredServer;
 
-    SetRequestHandler pSetRequestHandler;
+            CacheCallback pDataUpdateCB;
+            DestroyedCallback pDestroyCB;
 
-    ResourceObjectPtr createMirroredServer(RemoteObjectPtr rObject);
+            std::mutex mutexForCB;
 
-    void stateChangedCB(ResourceState state, RemoteObjectPtr rObject);
-    void dataChangedCB(const RCSResourceAttributes & attributes, RemoteObjectPtr rObject);
+            ResourceObjectPtr createMirroredServer(RemoteObjectPtr rObject);
 
-    RCSSetResponse setRequestHandler(
-            const RCSRequest & request, RCSResourceAttributes & attributes);
+            RCSSetResponse setRequestHandler(
+                    const RCSRequest & request, RCSResourceAttributes & attributes);
 
-    void destroyHostingObject();
+            void destroyHostingObject();
 
-};
+        public:
+            void stateChangedCB(ResourceState state);
+            void dataChangedCB(const RCSResourceAttributes & attributes);
+        };
 
-} /* namespace Service */
+    } /* namespace Service */
 } /* namespace OIC */
 
 #endif /* RH_HOSTINGOBJECT_H_ */
index b1a2313..c3215f4 100644 (file)
 
 #include "RequestObject.h"
 
-namespace OIC
-{
-namespace Service
-{
-
-RequestObject::RequestObject() : pSetRequestCB(nullptr){ }
-RequestObject::RequestObject(SetRequestCallback cb) : pSetRequestCB(cb){ };
-
-RequestObject::~RequestObject()
-{
-    pSetRequestCB = {};
-}
+#include "RCSResourceObject.h"
+#include "RCSSeparateResponse.h"
 
-void RequestObject::invokeRequest(RemoteObjectPtr remoteObject, RequestMethod method,
-        RCSResourceAttributes & resourceAttibutes)
+namespace OIC
 {
-    try
+    namespace Service
     {
-        switch (method)
-        {
-        case RequestMethod::Setter:
+        void RequestObject::invokeRequest(RCSRemoteResourceObject::Ptr remoteObject,
+                const RCSRequest & request, RequestMethod method,
+                const RCSResourceAttributes & resourceAttibutes, SetRequestCallback setCB)
         {
-            if(pSetRequestCB == nullptr)
+            RequestObject::Ptr createdRequestObject = std::make_shared<RequestObject>();
+
+            RCSRequest req(request.getResourceObject().lock(), request.getOCRequest());
+            switch (method)
             {
-                remoteObject->setRemoteAttributes(resourceAttibutes,
-                        std::bind(&RequestObject::setRequestCB, this,
-                                std::placeholders::_1, resourceAttibutes));
-            }
-            else
+            case RequestMethod::Set:
             {
-                remoteObject->setRemoteAttributes(resourceAttibutes,
-                        std::bind(pSetRequestCB,
-                                std::placeholders::_1, resourceAttibutes));
+                if (!setCB)
+                {
+                    remoteObject->setRemoteAttributes(resourceAttibutes,
+                            std::bind(&RequestObject::setRequestCB, createdRequestObject,
+                                    std::placeholders::_1, std::placeholders::_2,
+                                    req, createdRequestObject));
+                }
+                else
+                {
+                    remoteObject->setRemoteAttributes(resourceAttibutes,
+                            std::bind(std::move(setCB),
+                                    std::placeholders::_1, std::placeholders::_2,
+                                    req, createdRequestObject));
+                }
+            }
+                break;
+            case RequestMethod::Get:
+            case RequestMethod::Delete:
+            default:
+                // unknown type of method.
+                break;
             }
         }
-            break;
-        case RequestMethod::Getter:
-        case RequestMethod::Delete:
-        default:
-            // unknown type of method.
-            break;
-        }
-    }catch(...)
-    {
-        throw;
-    }
-}
 
-void RequestObject::setRequestCB(const RCSResourceAttributes & returnedAttributes,
-        RCSResourceAttributes & putAttibutes)
-{
-    if(putAttibutes != returnedAttributes)
-    {
-        // TODO fail set attributes
-    }
-}
+        void RequestObject::setRequestCB(
+                const RCSResourceAttributes & returnedAttributes, int /*eCode*/,
+                const RCSRequest & request, RequestObject::Ptr /*this_ptr*/)
+        {
+            auto server = request.getResourceObject().lock();
+            if (!server) return;
+
+            RCSResourceObject::LockGuard guard(server);
+            server->getAttributes() = RCSResourceAttributes(returnedAttributes);
+
+            // TODO need to set error code.
+            RCSSeparateResponse(request).set();
+        }
 
-} /* namespace Service */
+    } /* namespace Service */
 } /* namespace OIC */
index bb18236..94fa946 100644 (file)
 #define RH_REQUESTOBJECT_H_
 
 #include "RCSRemoteResourceObject.h"
-#include "RCSResourceObject.h"
+#include "RCSRequest.h"
 
 namespace OIC
 {
-namespace Service
-{
-
-class RequestObject
-{
-public:
-    typedef std::shared_ptr<RequestObject> Ptr;
-    typedef std::shared_ptr<RCSRemoteResourceObject> RemoteObjectPtr;
-    typedef void (*SetRequestCallback)(const RCSResourceAttributes &, RCSResourceAttributes &);
-
-    enum class RequestMethod
+    namespace Service
     {
-        Getter = 0,
-        Setter,
-        Delete
-    };
+        class RequestObject
+        {
+        public:
+            typedef std::shared_ptr<RequestObject> Ptr;
+            typedef std::function<void(const RCSResourceAttributes &, int,
+                    const RCSRequest &, RequestObject::Ptr)> SetRequestCallback;
+
+            enum class RequestMethod
+            {
+                Get = 0,
+                Set,
+                Post,
+                Delete
+            };
 
-private:
-    SetRequestCallback pSetRequestCB;
+        private:
+            typedef RCSRemoteResourceObject::Ptr RemoteObjectPtr;
 
-public:
-    RequestObject();
-    RequestObject(SetRequestCallback cb);
-    ~RequestObject();
+        public:
+            RequestObject() = default;
+            ~RequestObject() = default;
 
-    void invokeRequest(RemoteObjectPtr remoteObject, RequestMethod method,
-            RCSResourceAttributes & resourceAttibutes);
+            static void invokeRequest(RCSRemoteResourceObject::Ptr remoteObject,
+                    const RCSRequest & request, RequestMethod method,
+                    const RCSResourceAttributes & resourceAttibutes,
+                    SetRequestCallback setCB = nullptr);
 
-private:
-    void setRequestCB(const RCSResourceAttributes & returnedAttributes,
-            RCSResourceAttributes & putAttibutes);
-};
+        private:
+            void setRequestCB(const RCSResourceAttributes & returnedAttributes, int eCode,
+                    const RCSRequest & request, RequestObject::Ptr this_ptr);
+        };
 
-} /* namespace Service */
+    } /* namespace Service */
 } /* namespace OIC */
 
 #endif /* RH_REQUESTOBJECT_H_ */
old mode 100644 (file)
new mode 100755 (executable)
index 32516e3..2ead1e4
 
 #include "ResourceHosting.h"
 
-#include "PresenceSubscriber.h"
-#include "OCPlatform.h"
 #include "RCSDiscoveryManager.h"
+#include "RCSAddress.h"
 
 namespace OIC
 {
-namespace Service
-{
-
-namespace
-{
-    std::string HOSTING_TAG = "/hosting";
-    size_t HOSTING_TAG_SIZE = (size_t)HOSTING_TAG.size();
-    std::string MULTICAST_PRESENCE_ADDRESS = std::string("coap://") + OC_MULTICAST_PREFIX;
-    std::string HOSTING_RESOURSE_TYPE = "oic.r.resourcehosting";
-}
-
-ResourceHosting * ResourceHosting::s_instance(nullptr);
-std::mutex ResourceHosting::s_mutexForCreation;
-
-ResourceHosting::ResourceHosting()
-: hostingObjectList(),
-  discoveryManager(nullptr),
-  pDiscoveryCB(nullptr)
-{
-}
-
-ResourceHosting * ResourceHosting::getInstance()
-{
-    if (!s_instance)
+    namespace Service
     {
-        s_mutexForCreation.lock();
-        if (!s_instance)
+
+        namespace
         {
-            s_instance = new ResourceHosting();
-            s_instance->initializeResourceHosting();
+            const std::string HOSTING_TAG = "/hosting";
+            const auto HOSTING_TAG_SIZE = HOSTING_TAG.size();
+            const std::string HOSTING_RESOURSE_TYPE = "oic.r.resourcehosting";
         }
-        s_mutexForCreation.unlock();
-    }
-    return s_instance;
-}
 
-void ResourceHosting::startHosting()
-{
-    try
-    {
-        requestMulticastDiscovery();
-    }catch(const RCSPlatformException &e)
-    {
-        OIC_HOSTING_LOG(DEBUG,
-                "[ResourceHosting::startHosting]PlatformException:%s", e.what());
-        throw;
-    }catch(const RCSInvalidParameterException &e)
-    {
-        OIC_HOSTING_LOG(DEBUG,
-                "[ResourceHosting::startHosting]InvalidParameterException:%s", e.what());
-        throw;
-    }catch(const std::exception &e)
-    {
-        OIC_HOSTING_LOG(DEBUG,
-                "[ResourceHosting::startHosting]std::exception:%s", e.what());
-        throw;
-    }
-}
+        ResourceHosting::ResourceHosting()
+        : m_mutexForList(),
+          m_isStartedHosting(false),
+          m_hostingObjects(),
+          m_discoveryTask()
+        {
+        }
 
-void ResourceHosting::stopHosting()
-{
+        ResourceHosting * ResourceHosting::getInstance()
+        {
+            static ResourceHosting instance;
+            return & instance;
+        }
 
-    hostingObjectList.clear();
-}
+        void ResourceHosting::startHosting()
+        {
+            if (m_isStartedHosting) return;
+            m_isStartedHosting = true;
+            createDiscoveryListener();
+        }
 
-void ResourceHosting::initializeResourceHosting()
-{
-    pDiscoveryCB = std::bind(&ResourceHosting::discoverHandler, this,
-            std::placeholders::_1);
+        void ResourceHosting::stopHosting()
+        {
+            if (!m_isStartedHosting) return;
 
-    discoveryManager = RCSDiscoveryManager::getInstance();
-}
+            if (!m_discoveryTask->isCanceled())
+            {
+                m_discoveryTask->cancel();
+            }
 
-void ResourceHosting::requestMulticastDiscovery()
-{
-    discoveryTask = discoveryManager->discoverResourceByType(
-            RCSAddress::multicast(), OC_RSRVD_WELL_KNOWN_URI, HOSTING_RESOURSE_TYPE, pDiscoveryCB);
-}
+            m_isStartedHosting = false;
 
-void ResourceHosting::discoverHandler(RemoteObjectPtr remoteResource)
-{
-    std::string discoverdUri = remoteResource->getUri();
-    if(discoverdUri.compare(
-            discoverdUri.size()-HOSTING_TAG_SIZE, HOSTING_TAG_SIZE, HOSTING_TAG) != 0)
-    {
-        return;
-    }
+            RHLock lock(m_mutexForList);
+            m_hostingObjects.clear();
+        }
 
-    HostingObjectPtr foundHostingObject = findRemoteResource(remoteResource);
-    if(foundHostingObject == nullptr)
-    {
-        try
+        void ResourceHosting::createDiscoveryListener()
         {
-            foundHostingObject = std::make_shared<HostingObject>();
-            foundHostingObject->initializeHostingObject(remoteResource,
-                    std::bind(&ResourceHosting::destroyedHostingObject, this,
-                            HostingObjectWeakPtr(foundHostingObject)));
-            hostingObjectList.push_back(foundHostingObject);
-        }catch(const RCSInvalidParameterException &e)
-        {
-            OIC_HOSTING_LOG(DEBUG,
-                    "[ResourceHosting::discoverHandler]InvalidParameterException:%s", e.what());
+            m_discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(
+                    RCSAddress::multicast(), OC_RSRVD_WELL_KNOWN_URI, HOSTING_RESOURSE_TYPE,
+                    std::bind(&ResourceHosting::discoveryHandler, this,
+                                std::placeholders::_1));
         }
-    }
-}
-
-ResourceHosting::HostingObjectPtr ResourceHosting::findRemoteResource(
-        RemoteObjectPtr remoteResource)
-{
-    HostingObjectPtr retObject = nullptr;
 
-    for(auto it : hostingObjectList)
-    {
-        RemoteObjectPtr inListPtr = it->getRemoteResource();
-        if(inListPtr != nullptr && isSameRemoteResource(inListPtr, remoteResource))
+        void ResourceHosting::discoveryHandler(RemoteObjectPtr remoteResource)
         {
-            retObject = it;
+            auto discoverdUri = remoteResource->getUri();
+            if (discoverdUri.compare(
+                    discoverdUri.size()-HOSTING_TAG_SIZE, HOSTING_TAG_SIZE, HOSTING_TAG) != 0)
+            {
+                return;
+            }
+
+            auto foundHostingObject = findRemoteResource(remoteResource);
+            if (foundHostingObject != nullptr) return;
+
+            try
+            {
+                HostingObjectKey key = generateHostingObjectKey(remoteResource);
+                foundHostingObject = HostingObject::createHostingObject(remoteResource,
+                        std::bind(&ResourceHosting::destroyedHostingObject, this, key));
+
+                RHLock lock(m_mutexForList);
+                m_hostingObjects.insert(std::make_pair(key, foundHostingObject));
+
+            } catch (const RCSException & e)
+            {
+                OIC_HOSTING_LOG(DEBUG,
+                        "[ResourceHosting::discoverHandler]InvalidParameterException:%s", e.what());
+            }
         }
-    }
 
-    return retObject;
-}
+        HostingObject::Ptr ResourceHosting::findRemoteResource(RemoteObjectPtr remoteResource)
+        {
+            RHLock lock(m_mutexForList);
 
-bool ResourceHosting::isSameRemoteResource(
-        RemoteObjectPtr remoteResource_1, RemoteObjectPtr remoteResource_2)
-{
-    bool ret = false;
-    if(remoteResource_1->getAddress() == remoteResource_2->getAddress() &&
-       remoteResource_1->getUri() == remoteResource_2->getUri())
-    {
-        ret = true;
-    }
-    return ret;
-}
+            auto iter = m_hostingObjects.find(generateHostingObjectKey(remoteResource));
+            if (iter != m_hostingObjects.end()) return iter->second;
 
-void ResourceHosting::destroyedHostingObject(HostingObjectWeakPtr destroyedWeakPtr)
-{
-    auto destroyedPtr = destroyedWeakPtr.lock();
-    if (destroyedPtr) return;
+            return nullptr;
+        }
+
+        void ResourceHosting::destroyedHostingObject(const HostingObjectKey & key)
+        {
+            RHLock lock(m_mutexForList);
+            m_hostingObjects.erase(key);
+        }
 
-    std::unique_lock<std::mutex> lock(mutexForList);
-    hostingObjectList.remove(destroyedPtr);
-}
+        ResourceHosting::HostingObjectKey ResourceHosting::generateHostingObjectKey(
+                std::string && address, std::string && uri)
+        {
+            return HostingObjectKey(address + uri);
+        }
+
+        ResourceHosting::HostingObjectKey ResourceHosting::generateHostingObjectKey(
+                const std::string & address, const std::string & uri)
+        {
+            return generateHostingObjectKey(std::string(address), std::string(uri));
+        }
+        ResourceHosting::HostingObjectKey ResourceHosting::generateHostingObjectKey(
+                RemoteObjectPtr rResource)
+        {
+            return generateHostingObjectKey(rResource->getAddress(), rResource->getUri());
+        }
 
-} /* namespace Service */
+    } /* namespace Service */
 } /* namespace OIC */
old mode 100644 (file)
new mode 100755 (executable)
index 8d66776..39866d4
 #ifndef RH_RESOURCEHOSTING_H_
 #define RH_RESOURCEHOSTING_H_
 
-#include <cstdbool>
-#include <iostream>
+#include <atomic>
+#include <functional>
 #include <list>
 #include <memory>
-#include <functional>
-#include <string>
-#include <atomic>
+#include <mutex>
 
-#include "octypes.h"
-#include "RCSAddress.h"
-#include "PresenceSubscriber.h"
-#include "HostingObject.h"
-#include "PrimitiveResource.h"
 #include "RCSDiscoveryManager.h"
+#include "RCSRemoteResourceObject.h"
+#include "HostingObject.h"
 
 namespace OIC
 {
-namespace Service
-{
-
-class RCSDiscoveryManager;
-class ResourceHosting
-{
-private:
-    typedef std::shared_ptr<HostingObject> HostingObjectPtr;
-    typedef std::weak_ptr<HostingObject> HostingObjectWeakPtr;
-
-    typedef std::shared_ptr<RCSRemoteResourceObject> RemoteObjectPtr;
-    typedef std::shared_ptr<PrimitiveResource> PrimiteveResourcePtr;
-
-    typedef std::function<
-            void(std::shared_ptr<RCSRemoteResourceObject>)> DiscoveryCallback;
-    typedef std::function<void()> DestroyedCallback;
-
-public:
-    void startHosting();
-    void stopHosting();
+    namespace Service
+    {
 
-    static ResourceHosting * getInstance();
+        class ResourceHosting
+        {
+        private:
+            typedef RCSRemoteResourceObject::Ptr RemoteObjectPtr;
+            typedef std::lock_guard<std::mutex> RHLock;
+            typedef std::string HostingObjectKey;
 
-private:
-    ResourceHosting();
-    ~ResourceHosting() = default;
+            typedef std::function<void(RemoteObjectPtr)> DiscoveryCallback;
+            typedef HostingObject::DestroyedCallback DestroyedCallback;
 
-    ResourceHosting(const ResourceHosting&) = delete;
-    ResourceHosting(ResourceHosting&&) = delete;
-    ResourceHosting& operator=(const ResourceHosting&) const = delete;
-    ResourceHosting& operator=(ResourceHosting&&) const = delete;
+        public:
+            void startHosting();
+            void stopHosting();
 
-    static ResourceHosting * s_instance;
-    static std::mutex s_mutexForCreation;
-    std::mutex mutexForList;
+            static ResourceHosting * getInstance();
 
-    std::list<HostingObjectPtr> hostingObjectList;
+        private:
+            ResourceHosting();
+            ~ResourceHosting() = default;
 
-    RCSDiscoveryManager * discoveryManager;
-    std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> discoveryTask;
+            ResourceHosting(const ResourceHosting&) = delete;
+            ResourceHosting & operator = (const ResourceHosting &) = delete;
 
-    DiscoveryCallback pDiscoveryCB;
+            ResourceHosting(ResourceHosting &&) = delete;
+            ResourceHosting & operator = (ResourceHosting &&) = delete;
 
-    void initializeResourceHosting();
+            std::mutex m_mutexForList;
+            std::atomic_bool m_isStartedHosting;
 
-    void requestMulticastDiscovery();
+            std::unordered_map<HostingObjectKey, HostingObject::Ptr> m_hostingObjects;
+            RCSDiscoveryManager::DiscoveryTask::Ptr m_discoveryTask;
 
-    void discoverHandler(RemoteObjectPtr remoteResource);
+            void createDiscoveryListener();
+            void discoveryHandler(RemoteObjectPtr remoteResource);
 
-    HostingObjectPtr findRemoteResource(RemoteObjectPtr remoteResource);
-    bool isSameRemoteResource(RemoteObjectPtr remoteResource_1, RemoteObjectPtr remoteResource_2);
+            HostingObjectKey generateHostingObjectKey(RemoteObjectPtr rResource);
+            HostingObjectKey generateHostingObjectKey(std::string && address, std::string && uri);
+            HostingObjectKey generateHostingObjectKey(
+                    const std::string & address, const std::string & uri);
 
-    void destroyedHostingObject(HostingObjectWeakPtr destroyedWeakPtr);
+            HostingObject::Ptr findRemoteResource(RemoteObjectPtr remoteResource);
 
-};
+            void destroyedHostingObject(const HostingObjectKey & key);
+        };
 
-} /* namespace Service */
+    } /* namespace Service */
 } /* namespace OIC */
 
 #endif /* RH_RESOURCEHOSTING_H_ */
diff --git a/service/resource-hosting/src/unittest/HostingObjectUnitTest.cpp b/service/resource-hosting/src/unittest/HostingObjectUnitTest.cpp
deleted file mode 100644 (file)
index 4f28cec..0000000
+++ /dev/null
@@ -1,199 +0,0 @@
-//******************************************************************
-//
-// 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 <memory>
-
-#include "ResourceEncapsulationTestSimulator.h"
-#include "HostingObject.h"
-
-#include "RCSDiscoveryManager.h"
-
-using namespace testing;
-using namespace OIC::Service;
-
-namespace
-{
-    bool isDeleted = false;
-    void onDestroy(std::weak_ptr<HostingObject> rPtr)
-    {
-        HostingObject::Ptr ptr = rPtr.lock();
-        if(ptr) ptr.reset();
-        isDeleted = true;
-    }
-    void onDiscoveryResource(RCSRemoteResourceObject::Ptr){ }
-
-    void onUpdatedCache(const RCSResourceAttributes &) { }
-}
-
-class HostingObjectTest : public TestWithMock
-{
-public:
-    ResourceEncapsulationTestSimulator::Ptr testObject;
-    RCSRemoteResourceObject::Ptr remoteObject;
-
-    std::mutex mutexForCondition;
-    std::condition_variable responseCon;
-
-protected:
-
-    void SetUp()
-    {
-        TestWithMock::SetUp();
-
-        testObject = std::make_shared<ResourceEncapsulationTestSimulator>();
-        testObject->defaultRunSimulator();
-        remoteObject = testObject->getRemoteResource();
-
-        isDeleted = false;
-    }
-
-    void TearDown()
-    {
-        TestWithMock::TearDown();
-
-        if(remoteObject.use_count() > 0)
-        {
-            if(remoteObject->isCaching())
-            {
-                remoteObject->stopCaching();
-            }
-            if(remoteObject->isMonitoring())
-            {
-                remoteObject->stopMonitoring();
-            }
-        }
-        testObject->destroy();
-    }
-
-public:
-    void waitForCondition(int waitingTime = 1000)
-    {
-        std::unique_lock< std::mutex > lock{ mutexForCondition };
-        responseCon.wait_for(lock, std::chrono::milliseconds{ waitingTime });
-    }
-
-    void notifyCondition()
-    {
-        responseCon.notify_all();
-    }
-
-};
-
-TEST_F(HostingObjectTest, startCachingAtInitialize)
-{
-    HostingObject::Ptr instance = std::make_shared<HostingObject>();
-    instance->initializeHostingObject(
-            remoteObject, std::bind(onDestroy, std::weak_ptr<HostingObject>(instance)));
-
-    EXPECT_TRUE(remoteObject->isCaching());
-}
-
-TEST_F(HostingObjectTest, startMonitoringAtInitialize)
-{
-    HostingObject::Ptr instance = std::make_shared<HostingObject>();
-    instance->initializeHostingObject(
-            remoteObject, std::bind(onDestroy, std::weak_ptr<HostingObject>(instance)));
-
-    ASSERT_TRUE(remoteObject->isMonitoring());
-}
-
-TEST_F(HostingObjectTest, getRemoteResourceisValid)
-{
-    HostingObject::Ptr instance = std::make_shared<HostingObject>();
-    instance->initializeHostingObject(
-            remoteObject, std::bind(onDestroy, std::weak_ptr<HostingObject>(instance)));
-
-    ASSERT_EQ(remoteObject->getUri(), instance->getRemoteResource()->getUri());
-}
-
-TEST_F(HostingObjectTest, createMirroredServer)
-{
-    int waitForResponse = 1000;
-    std::string uri = "";
-
-    HostingObject::Ptr instance = std::make_shared<HostingObject>();
-    instance->initializeHostingObject(
-            remoteObject, std::bind(onDestroy, std::weak_ptr<HostingObject>(instance)));
-    std::this_thread::sleep_for(std::chrono::milliseconds {waitForResponse});
-
-    std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> discoveryTask = { };
-
-    mocks.OnCallFunc(onDiscoveryResource).Do(
-            [this, &uri, &discoveryTask](RCSRemoteResourceObject::Ptr ptr)
-            {
-                if(ptr->getUri() == testObject->getHostedServerUri())
-                {
-                    uri = ptr->getUri();
-                    discoveryTask->cancel();
-                    notifyCondition();
-                }
-            });
-
-    discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(
-            RCSAddress::multicast(), "resource.hosting", onDiscoveryResource);
-    waitForCondition(waitForResponse);
-
-    EXPECT_EQ(testObject->getHostedServerUri(), uri);
-}
-
-TEST_F(HostingObjectTest, UpdateCachedDataWhenChangedOriginResource)
-{
-    int waitForResponse = 1000;
-    HostingObject::Ptr instance = std::make_shared<HostingObject>();
-    instance->initializeHostingObject(
-            remoteObject, std::bind(onDestroy, std::weak_ptr<HostingObject>(instance)));
-    std::this_thread::sleep_for(std::chrono::milliseconds {waitForResponse});
-
-    std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> discoveryTask = { };
-    RCSRemoteResourceObject::Ptr discoveredResource = { };
-
-    mocks.OnCallFunc(onDiscoveryResource).Do(
-            [this, &discoveredResource, &discoveryTask](RCSRemoteResourceObject::Ptr ptr)
-            {
-                if(ptr->getUri() == testObject->getHostedServerUri())
-                {
-                    discoveredResource = ptr;
-                    discoveryTask->cancel();
-                    notifyCondition();
-                }
-            });
-
-    discoveryTask =  RCSDiscoveryManager::getInstance()->discoverResourceByType(
-            RCSAddress::multicast(), "resource.hosting", onDiscoveryResource);
-    waitForCondition(waitForResponse);
-
-    RCSResourceAttributes::Value result = { };
-    mocks.OnCallFunc(onUpdatedCache).Do(
-            [this, &result](const RCSResourceAttributes & att)
-            {
-                result = att.at("Temperature");
-                notifyCondition();
-            });
-
-    discoveredResource->startCaching(onUpdatedCache);
-    std::this_thread::sleep_for(std::chrono::milliseconds {waitForResponse});
-
-    RCSResourceAttributes::Value settingValue = 10;
-    testObject->getResourceServer()->setAttribute("Temperature", settingValue);
-    waitForCondition(waitForResponse);
-
-    EXPECT_EQ(result.toString(), settingValue.toString());
-
-}
diff --git a/service/resource-hosting/src/unittest/RequestObjectUnitTest.cpp b/service/resource-hosting/src/unittest/RequestObjectUnitTest.cpp
deleted file mode 100644 (file)
index 94df26b..0000000
+++ /dev/null
@@ -1,105 +0,0 @@
-//******************************************************************
-//
-// 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 "UnitTestHelper.h"
-
-#include "ResourceEncapsulationTestSimulator.h"
-#include "RequestObject.h"
-
-using namespace testing;
-using namespace OIC::Service;
-
-namespace
-{
-    void setRequestCB(const RCSResourceAttributes &, RCSResourceAttributes &) { }
-}
-
-class RequestObjectTest : public TestWithMock
-{
-public:
-    ResourceEncapsulationTestSimulator::Ptr testObject;
-    RCSResourceObject::Ptr server;
-    RCSRemoteResourceObject::Ptr remoteObject;
-
-    RCSResourceAttributes attr;
-
-    std::mutex mutexForCondition;
-    std::condition_variable responseCon;
-
-protected:
-
-    void SetUp()
-    {
-        TestWithMock::SetUp();
-
-        testObject = std::make_shared<ResourceEncapsulationTestSimulator>();
-        testObject->defaultRunSimulator();
-        remoteObject = testObject->getRemoteResource();
-    }
-
-    void TearDown()
-    {
-        TestWithMock::TearDown();
-        if(remoteObject)
-        {
-            if(remoteObject->isCaching())
-            {
-                remoteObject->stopCaching();
-            }
-            if(remoteObject->isMonitoring())
-            {
-                remoteObject->stopMonitoring();
-            }
-        }
-        testObject->destroy();
-    }
-
-public:
-    void waitForCondition(int waitingTime = 1000)
-    {
-        std::unique_lock< std::mutex > lock{ mutexForCondition };
-        responseCon.wait_for(lock, std::chrono::milliseconds{ waitingTime });
-    }
-
-    void notifyCondition()
-    {
-        responseCon.notify_all();
-    }
-};
-
-TEST_F(RequestObjectTest, invokeRequestExpectCallwithSetter)
-{
-   bool isCalled = false;
-   RequestObject::Ptr instance = std::make_shared<RequestObject>(setRequestCB);
-
-   mocks.ExpectCallFunc(setRequestCB).Do(
-           [this, &isCalled](const RCSResourceAttributes &, RCSResourceAttributes &)
-           {
-               isCalled = true;
-               notifyCondition();
-           });
-
-   RCSResourceAttributes att;
-   instance->invokeRequest(remoteObject, RequestObject::RequestMethod::Setter, att);
-
-   waitForCondition();
-
-   ASSERT_TRUE(isCalled);
-}
diff --git a/service/resource-hosting/src/unittest/ResourceEncapsulationTestSimulator.h b/service/resource-hosting/src/unittest/ResourceEncapsulationTestSimulator.h
deleted file mode 100644 (file)
index ac3c61d..0000000
+++ /dev/null
@@ -1,198 +0,0 @@
-//******************************************************************
-//
-// 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 <memory>
-#include <mutex>
-#include <atomic>
-#include <condition_variable>
-
-#include "UnitTestHelper.h"
-
-#include "RCSDiscoveryManager.h"
-#include "RCSRemoteResourceObject.h"
-#include "RCSResourceAttributes.h"
-#include "RCSAddress.h"
-
-#include "RequestObject.h"
-
-using namespace testing;
-using namespace OIC::Service;
-
-class ResourceEncapsulationTestSimulator
-        : public std::enable_shared_from_this<ResourceEncapsulationTestSimulator>
-{
-public:
-    typedef std::shared_ptr<ResourceEncapsulationTestSimulator> Ptr;
-
-    RCSResourceObject::Ptr server;
-    RCSRemoteResourceObject::Ptr remoteResource;
-
-private:
-    std::mutex mutexForDiscovery;
-    std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> discoveryTask;
-
-    std::string MULTICASTURI;
-    std::string HOSTED_RESOURCEURI;
-    std::string RESOURCEURI;
-    std::string RESOURCETYPE;
-    std::string RESOURCEINTERFACE;
-    std::string ATTR_KEY;
-    int ATTR_VALUE;
-
-public:
-    ResourceEncapsulationTestSimulator()
-    :server(nullptr), remoteResource(nullptr),
-     mutexForDiscovery(),
-     MULTICASTURI("/oic/res"),
-     HOSTED_RESOURCEURI("/a/TempHumSensor"),
-     RESOURCEURI("/a/TempHumSensor/hosting"),
-     RESOURCETYPE("resource.hosting"),
-     RESOURCEINTERFACE("oic.if.baseline"),
-     ATTR_KEY("Temperature"),
-     ATTR_VALUE(0)
-    { }
-    ~ResourceEncapsulationTestSimulator()
-    { }
-
-private:
-    void onDiscoveryResource_Impl(RCSRemoteResourceObject::Ptr resourceObject)
-    {
-        if (remoteResource != nullptr)
-        {
-            return;
-        }
-
-        if (RESOURCEURI.compare(resourceObject->getUri()) != 0)
-        {
-            return;
-        }
-
-        remoteResource = resourceObject;
-        mutexForDiscovery.unlock();
-    }
-
-    static void onDiscoveryResource(RCSRemoteResourceObject::Ptr resourceObject,
-            std::weak_ptr<ResourceEncapsulationTestSimulator> rPtr)
-    {
-        std::shared_ptr<ResourceEncapsulationTestSimulator> ptr = rPtr.lock();
-        if (ptr != nullptr)
-        {
-            ptr->onDiscoveryResource_Impl(resourceObject);
-        }
-    }
-    void waitForDiscovery()
-    {
-        std::chrono::milliseconds interval(100);
-        while(true)
-        {
-            if(mutexForDiscovery.try_lock())
-            {
-                mutexForDiscovery.unlock();
-                return;
-            }
-            std::this_thread::sleep_for(interval);
-        }
-    }
-    void WaitForPtrBeingUnique()
-    {
-        while((remoteResource && !remoteResource.unique()) || (server && !server.unique()))
-        {
-            std::this_thread::sleep_for(std::chrono::milliseconds{ 100 });
-        }
-    }
-
-public:
-    void destroy()
-    {
-        if(server.use_count()) server.reset();
-        if(remoteResource.use_count()) remoteResource.reset();
-        WaitForPtrBeingUnique();
-    }
-    void defaultRunSimulator()
-    {
-        createResource();
-        discoveryResource();
-        waitForDiscovery();
-    }
-
-    void createResource()
-    {
-        server = RCSResourceObject::Builder(RESOURCEURI, RESOURCETYPE, RESOURCEINTERFACE)
-                .setDiscoverable(true).setObservable(true).build();
-        server->setAttribute(ATTR_KEY, ATTR_VALUE);
-    }
-
-    void discoveryResource()
-    {
-        discoveryResource(RESOURCETYPE);
-    }
-
-    void discoveryResource(std::string & resourceType)
-    {
-        try
-        {
-            discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(
-                    RCSAddress::multicast(), MULTICASTURI, resourceType,
-                    std::bind(onDiscoveryResource, std::placeholders::_1,
-                        std::weak_ptr<ResourceEncapsulationTestSimulator>(shared_from_this())));
-            mutexForDiscovery.lock();
-        }
-        catch(std::exception & e)
-        {
-            std::cout << "exception : " << e.what() << std::endl;
-        }
-    }
-
-    std::string getServerUri() const
-    {
-        return RESOURCEURI;
-    }
-
-    std::string getHostedServerUri() const
-    {
-        return HOSTED_RESOURCEURI;
-    }
-
-    RCSResourceObject::Ptr getResourceServer() const
-    {
-        return server;
-    }
-    RCSRemoteResourceObject::Ptr getRemoteResource() const
-    {
-        return remoteResource;
-    }
-
-    void ChangeAttributeValue()
-    {
-        std::chrono::milliseconds interval(100);
-        if (server != nullptr)
-            server->setAttribute(ATTR_KEY, ATTR_VALUE + 10);
-        std::this_thread::sleep_for(interval);
-    }
-
-    void ChangeResourceState()
-    {
-        std::chrono::milliseconds interval(400);
-        if (server != nullptr)
-            server = nullptr;
-        std::this_thread::sleep_for(interval);
-    }
-};
diff --git a/service/resource-hosting/src/unittest/ResourceHostingUnitTest.cpp b/service/resource-hosting/src/unittest/ResourceHostingUnitTest.cpp
deleted file mode 100644 (file)
index 483c977..0000000
+++ /dev/null
@@ -1,135 +0,0 @@
-//******************************************************************
-//
-// 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 <memory>
-
-#include "ResourceEncapsulationTestSimulator.h"
-
-#include "ResourceHosting.h"
-
-using namespace testing;
-using namespace OIC::Service;
-
-namespace
-{
-    void onDiscoveryResource(RCSRemoteResourceObject::Ptr) { }
-}
-
-class ResourceHostingTest : public TestWithMock
-{
-public:
-    std::mutex mutexForCondition;
-    std::condition_variable responseCon;
-    std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> discoveryTask;
-
-protected:
-
-    void SetUp()
-    {
-        TestWithMock::SetUp();
-    }
-
-    void TearDown()
-    {
-        TestWithMock::TearDown();
-
-        if (ResourceHosting::getInstance())
-        {
-            ResourceHosting::getInstance()->stopHosting();
-        }
-
-    }
-
-public:
-    void waitForCondition(int waitingTime = 1000)
-    {
-        std::unique_lock< std::mutex > lock{ mutexForCondition };
-        responseCon.wait_for(lock, std::chrono::milliseconds{ waitingTime });
-    }
-
-    void notifyCondition()
-    {
-        responseCon.notify_all();
-    }
-
-};
-
-TEST(ResourceHostingSTATICMethodTest, getInstanceAllwaysSameReturnInstance)
-{
-    EXPECT_EQ(ResourceHosting::getInstance(), ResourceHosting::getInstance());
-}
-
-TEST_F(ResourceHostingTest, HostingFoundBeforeMakeOriginServer)
-{
-    ResourceEncapsulationTestSimulator::Ptr testObject
-        = std::make_shared<ResourceEncapsulationTestSimulator>();
-    testObject->createResource();
-
-    ResourceHosting::getInstance()->startHosting();
-    std::this_thread::sleep_for(std::chrono::milliseconds{1000});
-
-    std::string uri = "";
-    mocks.OnCallFunc(onDiscoveryResource).Do(
-            [this, &uri, &testObject](RCSRemoteResourceObject::Ptr ptr)
-            {
-                if(ptr->getUri() == testObject->getHostedServerUri())
-                {
-                    uri = ptr->getUri();
-                    discoveryTask->cancel();
-                    notifyCondition();
-                }
-            });
-
-    discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(
-            RCSAddress::multicast(), "resource.hosting", onDiscoveryResource);
-    waitForCondition(2000);
-
-    std::string mirroredUri = { testObject->getHostedServerUri() };
-
-    testObject->destroy();
-
-    ASSERT_EQ(mirroredUri, uri);
-}
-
-TEST_F(ResourceHostingTest, startHosting)
-{
-    ResourceEncapsulationTestSimulator::Ptr testObject
-        = std::make_shared<ResourceEncapsulationTestSimulator>();
-    testObject->createResource();
-
-    ResourceHosting::getInstance()->startHosting();
-    std::this_thread::sleep_for(std::chrono::milliseconds{1000});
-
-    testObject->destroy();
-}
-
-TEST_F(ResourceHostingTest, stopHosting)
-{
-    ResourceEncapsulationTestSimulator::Ptr testObject
-        = std::make_shared<ResourceEncapsulationTestSimulator>();
-    testObject->createResource();
-
-    ResourceHosting::getInstance()->startHosting();
-    std::this_thread::sleep_for(std::chrono::milliseconds{1000});
-
-    testObject->destroy();
-
-    ResourceHosting::getInstance()->stopHosting();
-}
diff --git a/service/resource-hosting/src/unittest/SConscript b/service/resource-hosting/src/unittest/SConscript
deleted file mode 100644 (file)
index 5c6747c..0000000
+++ /dev/null
@@ -1,89 +0,0 @@
-#******************************************************************
-#
-# 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.
-#
-#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-##
-# ResourceHosting Unit Test build script
-##
-
-Import('env')
-
-if env.get('RELEASE'):
-       env.AppendUnique(CCFLAGS = ['-Os'])
-       env.AppendUnique(CPPDEFINES = ['NDEBUG'])
-else:
-       env.AppendUnique(CCFLAGS = ['-g'])
-
-if env.get('LOGGING'):
-       env.AppendUnique(CPPDEFINES = ['TB_LOG'])
-
-lib_env = env.Clone()
-SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
-
-######################################################################
-#unit test setting
-######################################################################
-src_dir = lib_env.get('SRC_DIR')
-gtest_dir = src_dir + '/extlibs/gtest/gtest-1.7.0'
-
-hosting_test_env = lib_env.Clone()
-target_os = env.get('TARGET_OS')
-
-######################################################################
-# Build flags
-######################################################################
-GTest = File(gtest_dir + '/lib/.libs/libgtest.a')
-GTest_Main = File(gtest_dir + '/lib/.libs/libgtest_main.a')
-
-#hosting_test_env.AppendUnique(LIBPATH = [gtest_dir + '/lib/.libs'])
-hosting_test_env.AppendUnique(LIBPATH = [lib_env.get('BUILD_DIR')])
-hosting_test_env.AppendUnique(LIBS = [
-       'resource_hosting', 'rcs_server', 'rcs_client','rcs_common',
-       'oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap',
-       GTest_Main, GTest])
-
-if target_os not in ['windows', 'winrt']:
-    hosting_test_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
-
-if target_os == 'linux':
-       hosting_test_env.AppendUnique(CXXFLAGS = ['-pthread'])
-       hosting_test_env.AppendUnique(LIBS = ['pthread'])
-
-hosting_test_env.PrependUnique(CPPPATH = [ src_dir + '/extlibs/hippomocks-master',
-                             gtest_dir + '/include'])
-hosting_test_env.AppendUnique(CPPPATH = ['../'])
-hosting_test_env.AppendUnique(CPPPATH = ['../../../resource-encapsulation/include'])
-hosting_test_env.AppendUnique(CPPPATH = ['../../../resource-encapsulation/src/common/primitiveResource/include'])
-hosting_test_env.AppendUnique(CPPPATH = ['../../../resource-encapsulation/src/common/utils/include'])
-######################################################################
-# Build Test
-######################################################################
-
-hosting_test_src = env.Glob('./*.cpp')
-hosting_test = hosting_test_env.Program('hosting_test', hosting_test_src)
-Alias("hosting_test", hosting_test)
-env.AppendTarget('hosting_test')
-hosting_test_env.InstallTarget(hosting_test, 'hosting_test')
-
-#target_os = env.get('TARGET_OS')
-#if target_os == 'linux':
-#        from tools.scons.RunTest import *
-#        run_test(hosting_test_env,
-#                 '',
-#                 'service/notification-manager/NotificationManager/src/unittest/hosting_test')
\ No newline at end of file
diff --git a/service/resource-hosting/unittest/HostingObjectUnitTest.cpp b/service/resource-hosting/unittest/HostingObjectUnitTest.cpp
new file mode 100755 (executable)
index 0000000..b56a4cf
--- /dev/null
@@ -0,0 +1,214 @@
+//******************************************************************
+//
+// 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 <memory>
+
+#include "ResourceEncapsulationTestSimulator.h"
+#include "HostingObject.h"
+
+#include "RCSDiscoveryManager.h"
+
+using namespace testing;
+using namespace OIC::Service;
+
+namespace
+{
+    const std::string HOSTING_RESOURCE_TYPE = "oic.r.resourcehosting";
+    const std::string TEST_ATT_KEY = "Temperature";
+
+    bool isStarted = false;
+    bool isFinished = false;
+
+    ResourceEncapsulationTestSimulator testObject;
+    RCSRemoteResourceObject::Ptr remoteObject;
+
+    HostingObject::Ptr instance;
+    RCSRemoteResourceObject::Ptr discoveredResource;
+
+    std::condition_variable responseCon;
+
+    void onDestroy() { }
+    void onDiscoveryResource(RCSRemoteResourceObject::Ptr){ }
+    void onUpdatedCache(const RCSResourceAttributes &) { }
+    void onSetAttributes(const RCSResourceAttributes &, int) { }
+
+    void setup()
+    {
+        if(!isStarted)
+        {
+            testObject.defaultRunSimulator();
+            remoteObject = testObject.getRemoteResource();
+
+            instance = HostingObject::createHostingObject(
+                        remoteObject, &onDestroy);
+
+            testObject.getResourceServer()->setAttribute(
+                    "Temperature", RCSResourceAttributes::Value((int)0));
+
+            isStarted = true;
+        }
+    }
+
+    void tearDown()
+    {
+        if(isFinished)
+        {
+            testObject.destroy();
+            instance.reset();
+            isStarted = false;
+        }
+    }
+}
+
+class HostingObjectTest : public TestWithMock
+{
+public:
+    std::mutex mutexForCondition;
+
+protected:
+
+    void SetUp()
+    {
+        TestWithMock::SetUp();
+        setup();
+    }
+
+    void TearDown()
+    {
+        TestWithMock::TearDown();
+        tearDown();
+    }
+
+public:
+    void waitForCondition(int waitingTime = 1000)
+    {
+        std::unique_lock< std::mutex > lock{ mutexForCondition };
+        responseCon.wait_for(lock, std::chrono::milliseconds{ waitingTime });
+    }
+
+    void notifyCondition()
+    {
+        responseCon.notify_all();
+    }
+
+};
+
+TEST_F(HostingObjectTest, startCachingAtInitialize)
+{
+    EXPECT_TRUE(remoteObject->isCaching());
+}
+
+TEST_F(HostingObjectTest, startMonitoringAtInitialize)
+{
+    ASSERT_TRUE(remoteObject->isMonitoring());
+}
+
+TEST_F(HostingObjectTest, getRemoteResourceisValid)
+{
+    ASSERT_EQ(remoteObject->getUri(), instance->getRemoteResource()->getUri());
+}
+
+TEST_F(HostingObjectTest, createMirroredServer)
+{
+    int waitForResponse = 1000;
+    std::string uri = "";
+
+    std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> discoveryTask = { };
+
+    waitForCondition(waitForResponse);
+    mocks.OnCallFunc(onDiscoveryResource).Do(
+            [this, &uri, &discoveryTask, &testObject, &discoveredResource]
+             (RCSRemoteResourceObject::Ptr ptr)
+            {
+                if(ptr->getUri() == testObject.getHostedServerUri())
+                {
+                    uri = ptr->getUri();
+                    discoveredResource = ptr;
+                    discoveryTask->cancel();
+                    notifyCondition();
+                }
+            });
+
+    discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(
+            RCSAddress::multicast(), "/oic/res", HOSTING_RESOURCE_TYPE, onDiscoveryResource);
+    waitForCondition(waitForResponse);
+
+    EXPECT_EQ(testObject.getHostedServerUri(), uri);
+}
+
+TEST_F(HostingObjectTest, UpdateCachedDataWhenChangedOriginResource)
+{
+    int waitForResponse = 1000;
+    RCSResourceAttributes::Value result = { };
+
+    mocks.OnCallFunc(onUpdatedCache).Do(
+            [this, &result](const RCSResourceAttributes & att)
+            {
+                result = att.at(TEST_ATT_KEY);
+                notifyCondition();
+            });
+
+    discoveredResource->startCaching(onUpdatedCache);
+    std::this_thread::sleep_for(std::chrono::milliseconds {waitForResponse});
+
+    RCSResourceAttributes::Value settingValue = 10;
+    testObject.getResourceServer()->setAttribute(TEST_ATT_KEY, settingValue);
+    waitForCondition(waitForResponse);
+
+    isFinished = true;
+
+    EXPECT_EQ(result.toString(), settingValue.toString());
+
+}
+
+TEST_F(HostingObjectTest, SetDataToMirroredResource)
+{
+    int waitForResponse = 1000;
+    RCSResourceAttributes::Value result = { };
+
+    mocks.ExpectCallFunc(onSetAttributes).Do(
+            [this, & result](const RCSResourceAttributes &att, int)
+            {
+                result = att.at(TEST_ATT_KEY);
+                notifyCondition();
+            });
+    RCSResourceAttributes setAttrs;
+    RCSResourceAttributes::Value settingValue = 20;
+    setAttrs[TEST_ATT_KEY] = settingValue;
+    discoveredResource->setRemoteAttributes(setAttrs, onSetAttributes);
+    waitForCondition(waitForResponse);
+
+    EXPECT_EQ(result.toString(), settingValue.toString());
+}
+
+TEST_F(HostingObjectTest, ExpectCallOnDestroyWhenStopHostingObject)
+{
+    int waitForResponse = 1000;
+
+    mocks.ExpectCallFunc(onDestroy).Do(
+            [& responseCon]()
+            {
+                responseCon.notify_all();
+            });
+
+    testObject.destroy();
+    instance.reset();
+    waitForCondition(waitForResponse);
+}
diff --git a/service/resource-hosting/unittest/RequestObjectUnitTest.cpp b/service/resource-hosting/unittest/RequestObjectUnitTest.cpp
new file mode 100755 (executable)
index 0000000..299e931
--- /dev/null
@@ -0,0 +1,115 @@
+//******************************************************************
+//
+// 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 "UnitTestHelper.h"
+
+#include "ResourceEncapsulationTestSimulator.h"
+#include "RequestObject.h"
+
+using namespace testing;
+using namespace OIC::Service;
+
+namespace
+{
+    bool isStarted = false;
+    bool isFinished = false;
+
+    ResourceEncapsulationTestSimulator testObject;
+    RCSRemoteResourceObject::Ptr remoteObject;
+
+    void setRequestCB(const RCSResourceAttributes &, int, const RCSRequest &, RequestObject::Ptr)
+    {
+    }
+
+    void setup()
+    {
+        if(!isStarted)
+        {
+            testObject.defaultRunSimulator();
+            remoteObject = testObject.getRemoteResource();
+
+            isStarted = true;
+        }
+    }
+
+    void tearDown()
+    {
+        if(isFinished)
+        {
+            testObject.destroy();
+            isStarted = false;
+        }
+    }
+}
+
+class RequestObjectTest : public TestWithMock
+{
+public:
+    std::mutex mutexForCondition;
+    std::condition_variable responseCon;
+
+protected:
+
+    void SetUp()
+    {
+        TestWithMock::SetUp();
+        setup();
+    }
+
+    void TearDown()
+    {
+        TestWithMock::TearDown();
+        tearDown();
+    }
+
+public:
+    void waitForCondition(int waitingTime = 1000)
+    {
+        std::unique_lock< std::mutex > lock{ mutexForCondition };
+        responseCon.wait_for(lock, std::chrono::milliseconds{ waitingTime });
+    }
+
+    void notifyCondition()
+    {
+        responseCon.notify_all();
+    }
+};
+
+TEST_F(RequestObjectTest, invokeRequestExpectCallwithSetter)
+{
+   bool isCalled = false;
+
+   mocks.ExpectCallFunc(setRequestCB).Do(
+           [this, &isCalled](const RCSResourceAttributes &, int,
+                   const RCSRequest &, RequestObject::Ptr)
+           {
+               isCalled = true;
+               notifyCondition();
+           });
+
+   RCSResourceAttributes att;
+   std::shared_ptr<OC::OCResourceRequest> request;
+   RequestObject::invokeRequest(remoteObject, RCSRequest(testObject.getResourceServer(), request),
+           RequestObject::RequestMethod::Set, att, setRequestCB);
+
+   waitForCondition();
+
+   ASSERT_TRUE(isCalled);
+}
diff --git a/service/resource-hosting/unittest/ResourceEncapsulationTestSimulator.h b/service/resource-hosting/unittest/ResourceEncapsulationTestSimulator.h
new file mode 100755 (executable)
index 0000000..395bf21
--- /dev/null
@@ -0,0 +1,176 @@
+//******************************************************************
+//
+// 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 <memory>
+#include <mutex>
+#include <atomic>
+#include <condition_variable>
+
+#include "UnitTestHelper.h"
+
+#include "OCPlatform.h"
+#include "RCSDiscoveryManager.h"
+#include "RCSRemoteResourceObject.h"
+#include "RCSResourceObject.h"
+#include "RCSResourceAttributes.h"
+#include "RCSAddress.h"
+
+#include "RequestObject.h"
+
+using namespace testing;
+using namespace OIC::Service;
+
+class ResourceEncapsulationTestSimulator
+{
+public:
+    RCSResourceObject::Ptr server;
+    RCSRemoteResourceObject::Ptr remoteResource;
+
+private:
+    std::mutex mutexForDiscovery;
+    std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> discoveryTask;
+
+    std::string MULTICASTURI;
+    std::string HOSTED_RESOURCEURI;
+    std::string RESOURCEURI;
+    std::string RESOURCETYPE;
+    std::string RESOURCEINTERFACE;
+    std::string ATTR_KEY;
+    int ATTR_VALUE;
+
+public:
+    ResourceEncapsulationTestSimulator()
+    :server(nullptr), remoteResource(nullptr),
+     mutexForDiscovery(),
+     MULTICASTURI("/oic/res"),
+     HOSTED_RESOURCEURI("/a/TempHumSensor"),
+     RESOURCEURI("/a/TempHumSensor/hosting"),
+     RESOURCETYPE("oic.r.resourcehosting"),
+     RESOURCEINTERFACE("oic.if.baseline"),
+     ATTR_KEY("Temperature"),
+     ATTR_VALUE(0)
+    { }
+    ~ResourceEncapsulationTestSimulator()
+    { }
+
+private:
+    void onDiscoveryResource(RCSRemoteResourceObject::Ptr resourceObject)
+    {
+        if (remoteResource != nullptr)
+        {
+            return;
+        }
+
+        if (RESOURCEURI.compare(resourceObject->getUri()) != 0)
+        {
+            return;
+        }
+
+        remoteResource = resourceObject;
+        discoveryTask->cancel();
+        mutexForDiscovery.unlock();
+    }
+
+    void waitForDiscovery()
+    {
+        std::chrono::milliseconds interval(100);
+        while(true)
+        {
+            if(mutexForDiscovery.try_lock())
+            {
+                mutexForDiscovery.unlock();
+                return;
+            }
+            std::this_thread::sleep_for(interval);
+        }
+    }
+    void WaitForPtrBeingUnique()
+    {
+        while((remoteResource && !remoteResource.unique()) || (server && !server.unique()))
+        {
+            std::this_thread::sleep_for(std::chrono::milliseconds{ 1000 });
+        }
+    }
+
+public:
+    void destroy()
+    {
+        if(server.use_count()) server.reset();
+        if(remoteResource.use_count()) remoteResource.reset();
+        WaitForPtrBeingUnique();
+    }
+    void defaultRunSimulator()
+    {
+        createResource();
+        discoveryResource();
+        waitForDiscovery();
+    }
+
+    void createResource(std::string postUri = "")
+    {
+        HOSTED_RESOURCEURI = HOSTED_RESOURCEURI + postUri;
+        server = RCSResourceObject::Builder(HOSTED_RESOURCEURI +  "/hosting",
+                RESOURCETYPE, RESOURCEINTERFACE).
+                setDiscoverable(true).setObservable(true).build();
+        server->setAttribute(ATTR_KEY, RCSResourceAttributes::Value(ATTR_VALUE));
+    }
+
+    void discoveryResource()
+    {
+        discoveryResource(RESOURCETYPE);
+    }
+
+    void discoveryResource(std::string & resourceType)
+    {
+        try
+        {
+            discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(
+                    RCSAddress::multicast(), MULTICASTURI, resourceType,
+                    std::bind(
+                            &ResourceEncapsulationTestSimulator::onDiscoveryResource,
+                            this, std::placeholders::_1));
+            mutexForDiscovery.lock();
+        }
+        catch(std::exception & e)
+        {
+            std::cout << "exception : " << e.what() << std::endl;
+        }
+    }
+
+    std::string getServerUri() const
+    {
+        return RESOURCEURI;
+    }
+
+    std::string getHostedServerUri() const
+    {
+        return HOSTED_RESOURCEURI;
+    }
+
+    RCSResourceObject::Ptr getResourceServer() const
+    {
+        return server;
+    }
+    RCSRemoteResourceObject::Ptr getRemoteResource() const
+    {
+        return remoteResource;
+    }
+};
diff --git a/service/resource-hosting/unittest/ResourceHostingUnitTest.cpp b/service/resource-hosting/unittest/ResourceHostingUnitTest.cpp
new file mode 100755 (executable)
index 0000000..79b1d1d
--- /dev/null
@@ -0,0 +1,133 @@
+//******************************************************************
+//
+// 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 <memory>
+
+#include "ResourceEncapsulationTestSimulator.h"
+
+#include "ResourceHosting.h"
+
+using namespace testing;
+using namespace OIC::Service;
+
+namespace
+{
+    bool isStarted = false;
+    bool isFinished = false;
+
+    ResourceEncapsulationTestSimulator testObject;
+
+    void onDiscoveryResource(RCSRemoteResourceObject::Ptr) { }
+}
+
+class ResourceHostingTest : public TestWithMock
+{
+public:
+    std::mutex mutexForCondition;
+    std::condition_variable responseCon;
+    std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> discoveryTask;
+
+protected:
+
+    void SetUp()
+    {
+        TestWithMock::SetUp();
+        if(!isStarted)
+        {
+            testObject.createResource("1");
+
+            isStarted = true;
+        }
+    }
+
+    void TearDown()
+    {
+        TestWithMock::TearDown();
+
+        if(isFinished)
+        {
+            testObject.destroy();
+            isStarted = false;
+        }
+    }
+
+public:
+    void waitForCondition(int waitingTime = 1000)
+    {
+        std::unique_lock< std::mutex > lock{ mutexForCondition };
+        responseCon.wait_for(lock, std::chrono::milliseconds{ waitingTime });
+    }
+
+    void notifyCondition()
+    {
+        responseCon.notify_all();
+    }
+
+};
+
+TEST(ResourceHostingSTATICMethodTest, getInstanceAllwaysSameReturnInstance)
+{
+    EXPECT_EQ(ResourceHosting::getInstance(), ResourceHosting::getInstance());
+}
+
+TEST_F(ResourceHostingTest, startHosting)
+{
+    try
+    {
+        ResourceHosting::getInstance()->startHosting();
+    } catch (...)
+    {
+        FAIL() << "Non-Expected Exception";
+    }
+}
+
+TEST_F(ResourceHostingTest, HostingFoundBeforeMakeOriginServer)
+{
+    std::string uri = "";
+    testObject.getResourceServer()->setAttribute(
+            "Temperature", RCSResourceAttributes::Value((int)0));
+    waitForCondition();
+
+    mocks.OnCallFunc(onDiscoveryResource).Do(
+            [this, &uri, &testObject](RCSRemoteResourceObject::Ptr ptr)
+            {
+                if(ptr->getUri() == testObject.getHostedServerUri())
+                {
+                    uri = ptr->getUri();
+                    discoveryTask->cancel();
+                    notifyCondition();
+                }
+            });
+
+    discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(
+            RCSAddress::multicast(), "oic.r.resourcehosting", onDiscoveryResource);
+    waitForCondition();
+
+    std::string mirroredUri = { testObject.getHostedServerUri() };
+
+    ASSERT_EQ(mirroredUri, uri);
+}
+
+
+TEST_F(ResourceHostingTest, stopHosting)
+{
+    ResourceHosting::getInstance()->stopHosting();
+    isFinished = true;
+}
diff --git a/service/resource-hosting/unittest/SConscript b/service/resource-hosting/unittest/SConscript
new file mode 100644 (file)
index 0000000..2b15b0a
--- /dev/null
@@ -0,0 +1,87 @@
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+##
+# ResourceHosting Unit Test build script
+##
+
+Import('env')
+
+if env.get('RELEASE'):
+       env.AppendUnique(CCFLAGS = ['-Os'])
+       env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+else:
+       env.AppendUnique(CCFLAGS = ['-g'])
+
+if env.get('LOGGING'):
+       env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+
+######################################################################
+#unit test setting
+######################################################################
+src_dir = lib_env.get('SRC_DIR')
+gtest_dir = src_dir + '/extlibs/gtest/gtest-1.7.0'
+
+hosting_test_env = lib_env.Clone()
+target_os = env.get('TARGET_OS')
+
+######################################################################
+# Build flags
+######################################################################
+GTest = File(gtest_dir + '/lib/.libs/libgtest.a')
+GTest_Main = File(gtest_dir + '/lib/.libs/libgtest_main.a')
+
+#hosting_test_env.AppendUnique(LIBPATH = [gtest_dir + '/lib/.libs'])
+hosting_test_env.AppendUnique(LIBPATH = [lib_env.get('BUILD_DIR')])
+hosting_test_env.AppendUnique(LIBS = [
+       'resource_hosting', 'rcs_server', 'rcs_client','rcs_common',
+       'oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap',
+       GTest_Main, GTest])
+
+if target_os not in ['windows', 'winrt']:
+    hosting_test_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
+
+if target_os == 'linux':
+       hosting_test_env.AppendUnique(CXXFLAGS = ['-pthread'])
+       hosting_test_env.AppendUnique(LIBS = ['pthread'])
+
+hosting_test_env.PrependUnique(CPPPATH = [ src_dir + '/extlibs/hippomocks-master',
+                             gtest_dir + '/include'])
+hosting_test_env.AppendUnique(CPPPATH = ['../src'])
+hosting_test_env.AppendUnique(CPPPATH = ['../../resource-encapsulation/include'])
+hosting_test_env.AppendUnique(CPPPATH = ['../../resource-encapsulation/src/common/primitiveResource/include'])
+hosting_test_env.AppendUnique(CPPPATH = ['../../resource-encapsulation/src/common/utils/include'])
+######################################################################
+# Build Test
+######################################################################
+
+hosting_test_src = env.Glob('./*.cpp')
+hosting_test = hosting_test_env.Program('hosting_test', hosting_test_src)
+Alias("hosting_test", hosting_test)
+env.AppendTarget('hosting_test')
+
+if env.get('TEST') == '1':
+    target_os = env.get('TARGET_OS')
+    if target_os == 'linux':
+            from tools.scons.RunTest import *
+            run_test(hosting_test_env, '', 'service/resource-hosting/unittest/hosting_test')
\ No newline at end of file
diff --git a/service/scene-manager/README.txt b/service/scene-manager/README.txt
new file mode 100755 (executable)
index 0000000..7c21ad4
--- /dev/null
@@ -0,0 +1 @@
+initial file
diff --git a/service/scene-manager/SConscript b/service/scene-manager/SConscript
new file mode 100755 (executable)
index 0000000..9348578
--- /dev/null
@@ -0,0 +1,108 @@
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+##
+# NotificationManager build script
+##
+
+Import('env')
+
+if env.get('RELEASE'):
+    env.AppendUnique(CCFLAGS = ['-Os'])
+    env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+else:
+    env.AppendUnique(CCFLAGS = ['-g'])
+
+if env.get('LOGGING'):
+    env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+scenemanager_env = lib_env.Clone()
+
+target_os = env.get('TARGET_OS')
+######################################################################
+# Build flags
+######################################################################
+scenemanager_env.AppendUnique(CPPPATH = ['./include'])
+scenemanager_env.AppendUnique(CPPPATH = ['./src'])
+scenemanager_env.AppendUnique(CPPPATH = ['../../resource/csdk/connectivity/api'])
+scenemanager_env.AppendUnique(CPPPATH = ['../resource-encapsulation/include'])
+scenemanager_env.AppendUnique(CPPPATH = ['../resource-encapsulation/src/common/primitiveResource/include'])
+scenemanager_env.AppendUnique(CPPPATH = ['../resource-encapsulation/src/common/expiryTimer/include'])
+
+
+scenemanager_env.PrependUnique(LIBS = [
+    'rcs_client',
+    'rcs_server',
+    'rcs_common',
+    'oc',
+    'octbstack',
+    'oc_logger',
+    'connectivity_abstraction',
+    'libcoap'
+    ])
+
+if target_os not in ['windows', 'winrt']:
+    scenemanager_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
+
+if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
+    scenemanager_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
+
+if target_os == 'linux':
+    scenemanager_env.AppendUnique(LIBS = ['pthread'])
+    
+
+if target_os == 'android':
+    scenemanager_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
+    scenemanager_env.AppendUnique(LIBS = ['gnustl_shared','log'])
+
+if not env.get('RELEASE'):
+    scenemanager_env.PrependUnique(LIBS = ['gcov'])
+    scenemanager_env.AppendUnique(CXXFLAGS = ['--coverage'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+SCENE_SRC_DIR = './src/' 
+scenemanager_src = Glob(SCENE_SRC_DIR + '*.cpp')
+
+if target_os in ['tizen','android'] :
+    scenemanagersdk = scenemanager_env.SharedLibrary('scene_manager', scenemanager_src)
+else :
+    scenemanagersdk = scenemanager_env.StaticLibrary('scene_manager', scenemanager_src)
+
+scenemanager_env.InstallTarget(scenemanagersdk, 'libscene_manager')
+scenemanager_env.UserInstallTargetLib(scenemanagersdk, 'libscene_manager')
+scenemanager_env.UserInstallTargetHeader('include/SceneList.h', 'service/scene-manager', 'SceneList.h')
+scenemanager_env.UserInstallTargetHeader('include/SceneCollection.h', 'service/scene-manager', 'SceneCollection.h')
+scenemanager_env.UserInstallTargetHeader('include/Scene.h', 'service/scene-manager', 'Scene.h')
+scenemanager_env.UserInstallTargetHeader('include/SceneAction.h', 'service/scene-manager', 'SceneAction.h')
+scenemanager_env.UserInstallTargetHeader('include/RemoteSceneList.h', 'service/scene-manager', 'RemoteSceneList.h')
+scenemanager_env.UserInstallTargetHeader('include/RemoteSceneCollection.h', 'service/scene-manager', 'RemoteSceneCollection.h')
+scenemanager_env.UserInstallTargetHeader('include/RemoteScene.h', 'service/scene-manager', 'RemoteScene.h')
+scenemanager_env.UserInstallTargetHeader('include/RemoteSceneAction.h', 'service/scene-manager', 'RemoteSceneAction.h')
+
+# Go to build Unit test
+if target_os == 'linux':
+    SConscript('unittests/SConscript')
+
+# Go to build sample apps
+SConscript('sampleapp/SConscript')
diff --git a/service/scene-manager/include/RemoteScene.h b/service/scene-manager/include/RemoteScene.h
new file mode 100644 (file)
index 0000000..ee0fa0d
--- /dev/null
@@ -0,0 +1,193 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef SM_REMOTE_SCENE_H_
+#define SM_REMOTE_SCENE_H_
+
+#include <memory>
+#include <string>
+#include <unordered_map>
+#include <mutex>
+
+#include "RemoteSceneAction.h"
+#include "RCSRemoteResourceObject.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+        class SceneCollectionResourceRequestor;
+        class SceneMemberResourceRequestor;
+
+        /*
+        * @class RemoteScene
+        *
+        * @brief RemoteScene class is an interface class to send a request to a Scene provided by
+        * SceneCollection resource on remote side. This class provides APIs for adding new
+        * SceneAction to the Scene and creating a new SceneAction instance, retrieving all
+        * SceneAction instances created before. And it also provides an API to execute a Scene
+        * on remote side.
+        */
+        class RemoteScene
+        {
+            public:
+                typedef std::shared_ptr< RemoteScene > Ptr;
+
+                /**
+                * Callback definition to be invoked a the response of addNewSceneAction is
+                * received.
+                *
+                * @param action created RemoteSceneAction instance pointer
+                * @param eCode the error code received
+                *
+                * @note Error code '200' stands for success, '400' for bad request,
+                * and '500' for internal error.
+                *
+                * @see addNewSceneAction
+                */
+                typedef std::function< void(RemoteSceneAction::Ptr action, int eCode) >
+                    AddNewSceneActionCallback;
+
+                /**
+                * Callback definition to be invoked when a response of execute is
+                * received.
+                *
+                * @param sceneName name of the scene which is executed
+                * @param eCode the error code received
+                *
+                * @note Error code '200' stands for success, '400' for bad request,
+                * and '500' for internal error.
+                *
+                * @see execute
+                */
+                typedef std::function< void(const std::string &sceneName, int eCode) >
+                    RemoteSceneExecuteCallback;
+
+            public:
+                ~RemoteScene() = default;
+
+                /**
+                * Requests to add new SceneAction to the Scene on remote side and
+                * creates RemoteSceneAction instance corresponding to the created SceneAction.
+                *
+                * @param targetResource A pointer of discovered resource
+                * @param attrs AttributeS to set when the Scene executed
+                * @param cb A callback to receive created RemoteSceneAction instance
+                *
+                * @throws RCSInvalidParameterException If parameter is invalid.
+                * @throws PlatformException If the platform operation failed
+                *
+                * @note RemoteSceneAction instance is only produced by RemoteScene class
+                *
+                * @see RCSResourceAttributes
+                */
+                void addNewSceneAction(RCSRemoteResourceObject::Ptr targetResource,
+                    const RCSResourceAttributes &attrs, AddNewSceneActionCallback cb);
+
+                /**
+                * Requests to add new SceneAction to the Scene on remote side and
+                * creates RemoteSceneAction instance corresponding to the created SceneAction.
+                *
+                * @param targetResource A pointer of discovered resource
+                * @param key A key of an attribute
+                * @param value A value to be mapped against the key
+                * @param cb A callback to receive created RemoteSceneAction instance
+                *
+                * @throws RCSInvalidParameterException If parameter is invalid.
+                * @throws PlatformException If the platform operation failed
+                *
+                * @note RemoteSceneAction instance is only produced by RemoteScene class
+                *
+                * @see RCSResourceAttributes::Value
+                */
+                void addNewSceneAction(RCSRemoteResourceObject::Ptr targetResource,
+                                       const std::string &key,
+                                       const RCSResourceAttributes::Value &value,
+                                       AddNewSceneActionCallback cb);
+
+                /**
+                * Gets all RemoteSceneAction instances included in the Scene.
+                *
+                * @return A vector of shared pointer of RemoteSceneAction instances
+                */
+                std::vector< RemoteSceneAction::Ptr > getRemoteSceneActions() const;
+
+                /**
+                * Gets RemoteSceneAction instance by using a certain discovered resource.
+                *
+                * @param targetResource A pointer of discovered resource
+                *
+                * @return A shared pointer of RemoteSceneAction instance
+                *
+                * @throws RCSInvalidParameterException If targetResource is invalid
+                */
+                RemoteSceneAction::Ptr getRemoteSceneAction(
+                    const RCSRemoteResourceObject::Ptr targetResource) const;
+
+                /**
+                * Gets a name attribute of the Scene.
+                *
+                * @return A name of the Scene
+                */
+                std::string getName() const;
+
+                /**
+                * Requests to execute the Scene on remote side.
+                *
+                * @param cb A callback to receive result of Scene execution
+                *
+                * @throws RCSInvalidParameterException If callback is null
+                * @throws PlatformException If the platform operation failed
+                */
+                void execute(RemoteSceneExecuteCallback cb);
+
+            private:
+                RemoteScene(
+                    const std::string &name, std::shared_ptr< SceneCollectionResourceRequestor >);
+
+                RemoteSceneAction::Ptr createRemoteSceneAction(
+                    const std::string &,  const RCSResourceAttributes &);
+
+                void addExistingRemoteSceneAction(const std::string &, const std::string &,
+                    RCSRemoteResourceObject::Ptr, const std::string &key,
+                    const RCSResourceAttributes::Value &);
+
+                void onSceneActionAdded(
+                    int, RCSRemoteResourceObject::Ptr,
+                    const RCSResourceAttributes &, const AddNewSceneActionCallback &);
+
+                void onSceneExecuted(const std::string &name, int,
+                                    const RemoteSceneExecuteCallback &);
+
+            private:
+                std::string m_name;
+                mutable std::mutex m_sceneActionLock;
+                std::unordered_map < std::string, RemoteSceneAction::Ptr >
+                    m_remoteSceneActions;
+
+                std::shared_ptr< SceneCollectionResourceRequestor > m_requestor;
+
+                friend class RemoteSceneCollection;
+        };
+
+    }
+}
+
+#endif /* SM_REMOTE_SCENE_H_ */
\ No newline at end of file
diff --git a/service/scene-manager/include/RemoteSceneAction.h b/service/scene-manager/include/RemoteSceneAction.h
new file mode 100644 (file)
index 0000000..739ae27
--- /dev/null
@@ -0,0 +1,135 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef SM_REMOTE_SCENEACTION_H_
+#define SM_REMOTE_SCENEACTION_H_
+
+#include <memory>
+#include <string>
+#include <mutex>
+
+#include "RCSRemoteResourceObject.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+
+        class SceneMemberResourceRequestor;
+
+        /*
+        * @class RemoteSceneAction
+        *
+        * @brief RemoteSceneAction class indicates a unit of actions when a scene is executed.
+        * RemoteSceneAction instance is initialized with 3 essential parameters:
+        * a target resource, target attribute key, and its target value.
+        * And this class also provides APIs to update a target attribute information if one wants.
+        * Note that, adding a new RemoteSceneAction is done by sending a CoAP request to update a
+        * SceneMember resource's attribute.
+        */
+        class RemoteSceneAction
+        {
+            public:
+                typedef std::shared_ptr< RemoteSceneAction > Ptr;
+
+                /**
+                * Callback definition to be invoked when a response of resetExecutionParameter is
+                * received.
+                *
+                * @param eCode the error code received on a remote-side scene resource server
+                *
+                * @note Error code '200' stands for success, '400' for bad request,
+                * and '500' for internal error.
+                *
+                * @see resetExecutionParameter
+                */
+                typedef std::function< void(int eCode) > ResetExecutionParameterCallback;
+
+            public:
+                ~RemoteSceneAction() = default;
+
+                /**
+                * Requests to reset the RemoteSceneAction parameters like
+                * a target attribute key and its value.
+                *
+                * @param key key of attribute
+                * @param value value to be mapped against the key
+                * @param cb A callback to receive the response
+                *
+                * @throws RCSInvalidParameterException If parameter is invalid.
+                * @throws PlatformException If the platform operation failed
+                *
+                * @see RCSResourceAttributes::Value
+                */
+                void resetExecutionParameter(const std::string &key,
+                    const RCSResourceAttributes::Value &value, ResetExecutionParameterCallback cb);
+
+                /**
+                * Requests to reset the RemoteSceneAction parameters like
+                * a target attribute key and its value.
+                *
+                * @param attr Attributes to set
+                * @param cb A callback to receive the response
+                *
+                * @throws RCSInvalidParameterException If parameter is invalid.
+                * @throws PlatformException If the platform operation failed
+                *
+                * @see RCSResourceAttributes
+                */
+                void resetExecutionParameter(
+                    const RCSResourceAttributes &attr, ResetExecutionParameterCallback cb);
+
+                /**
+                * Returns an execution parameter of the SceneAction.
+                *
+                * @return RCSResourceAttributes
+                */
+                RCSResourceAttributes getExecutionParameter() const;
+
+                /**
+                * Returns a target remote resource object of the RemoteSceneAction instance
+                *
+                * @return pointer of RCSRemoteResourceObject
+                */
+                RCSRemoteResourceObject::Ptr getRemoteResourceObject() const;
+
+            private:
+                RemoteSceneAction(std::shared_ptr< SceneMemberResourceRequestor >,
+                                  const std::string &sceneName, const RCSResourceAttributes &);
+                RemoteSceneAction(std::shared_ptr< SceneMemberResourceRequestor >,
+                                  const std::string &sceneName,
+                                  const std::string &key, const RCSResourceAttributes::Value &);
+
+                void onExecutionParameterSet(int, const RCSResourceAttributes &,
+                    const ResetExecutionParameterCallback &);
+
+            private:
+                std::string m_sceneName;
+                mutable std::mutex m_attributeLock;
+                RCSResourceAttributes m_attributes;
+                std::shared_ptr< SceneMemberResourceRequestor > m_requestor;
+
+                friend class RemoteScene;
+        };
+
+    }
+}
+
+#endif /* SM_REMOTE_SCENEACTION_H_ */
\ No newline at end of file
diff --git a/service/scene-manager/include/RemoteSceneCollection.h b/service/scene-manager/include/RemoteSceneCollection.h
new file mode 100644 (file)
index 0000000..5db065d
--- /dev/null
@@ -0,0 +1,175 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef SM_REMOTE_SCENECOLLECTION_H_
+#define SM_REMOTE_SCENECOLLECTION_H_
+
+#include <memory>
+#include <functional>
+#include <string>
+#include <unordered_map>
+#include <mutex>
+
+#include "RemoteScene.h"
+#include "RCSRemoteResourceObject.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+
+        class SceneCollectionResourceRequestor;
+
+        /**
+        * @class RemoteSceneCollection
+        *
+        * @brief RemoteSceneCollection class is an interface class to send a request to
+        * SceneCollection resource on remote side. This class provides APIs for adding new Scene
+        * to the SceneCollection resource and creating a new RemoteSceneCollection instance
+        * corresponding to the created SceneCollection resource. This class also supports
+        * retrieving all Scene instances created before. Besides, it provides APIs for retrieving
+        * and updating attribute values of the SceneCollection resource like name attribute.
+        */
+        class RemoteSceneCollection
+        {
+            public:
+                typedef std::shared_ptr< RemoteSceneCollection > Ptr;
+
+                /**
+                * Callback definition to be invoked when a response of addNewScene is
+                * received.
+                *
+                * @param scene created RemoteScene instance pointer
+                * @param eCode the error code received from the SceneCollection on remote
+                *
+                * @note Error code '200' stands for success, '400' for bad request,
+                * and '500' for internal error.
+                *
+                * @see addNewScene
+                */
+                typedef std::function< void(RemoteScene::Ptr scene, int eCode) >
+                    AddNewSceneCallback;
+
+                /**
+                * Callback definition to be invoked when a response of setName is
+                * received.
+                *
+                * @param eCode the error code received from the SceneCollection on remote
+                *
+                * @note Error code '200' stands for success, '400' for bad request,
+                * and '500' for internal error.
+                *
+                * @see setName
+                */
+                typedef std::function< void(int eCode) > SetNameCallback;
+
+            public:
+                ~RemoteSceneCollection() = default;
+
+                /**
+                * Requests to add new Scene to the SceneCollection resource on remote side
+                * and creates RemoteScene instance corresponding to the created Scene.
+                *
+                * @param name A name of Scene to add
+                * @param cb A callback to receive created RemoteScene instance
+                *
+                * @throws RCSInvalidParameterException If parameter is invalid
+                * @throws PlatformException If the platform operation failed
+                *
+                * @note RemoteScene instance is only produced by RemoteSceneCollection class.
+                * @note Name of Scene must be unique in one SceneCollection
+                */
+                void addNewScene(const std::string &name, AddNewSceneCallback cb);
+
+                /**
+                * Gets all RemoteScene instances from RemoteSceneCollection instance.
+                *
+                * @return A unordered_map of shared pointers of RemoteScene instances
+                */
+                std::unordered_map< std::string, RemoteScene::Ptr > getRemoteScenes() const;
+
+                /**
+                * Gets RemoteScene instance with a specific Scene name.
+                *
+                * @param sceneName name of the Scene to get
+                *
+                * @return A shared pointer of RemoteScene instance
+                *
+                * @throws RCSInvalidParameterException If sceneName is invalid
+                */
+                RemoteScene::Ptr getRemoteScene(const std::string &sceneName) const;
+
+                /**
+                * Request to set a name attribute of the SceneCollection resource on remote side.
+                *
+                * @param name A name of the SceneCollection
+                * @param cb A callback to receive the response
+                *
+                * @throws RCSInvalidParameterException If callback is null
+                * @throws PlatformException If the platform operation failed
+                */
+                void setName(const std::string &name, SetNameCallback cb);
+
+                /**
+                * Gets a name attribute of the SceneCollection resource
+                *
+                * @return A name of the SceneCollection
+                */
+                std::string getName() const;
+
+                /**
+                * Gets an id attribute of the SceneCollection resource.
+                *
+                * @return an id of the SceneCollection resource
+                */
+                std::string getId() const;
+
+            private:
+                RemoteSceneCollection(
+                    std::shared_ptr< SceneCollectionResourceRequestor >,
+                    const std::string &id, const std::string &name);
+
+                void addExistingRemoteScenes(const std::vector< std::string > &);
+
+                void initializeRemoteScenes(const std::vector< RCSResourceAttributes > &,
+                                                     const std::string &);
+
+                RemoteScene::Ptr createRemoteScene(const std::string &);
+
+                void onSceneAddedRemoved(int, const std::string &name, int,
+                                         const AddNewSceneCallback &);
+
+                void onNameSet(int, const std::string &, const SetNameCallback &);
+
+            private:
+                std::string m_id;
+                std::string m_name;
+                mutable std::mutex m_nameLock;
+                mutable std::mutex m_sceneLock;
+                std::unordered_map< std::string, RemoteScene::Ptr > m_remoteScenes;
+                std::shared_ptr< SceneCollectionResourceRequestor > m_requestor;
+
+                friend class RemoteSceneList;
+        };
+
+    }
+}
+
+#endif /* SM_REMOTE_SCENECOLLECTION_H_ */
\ No newline at end of file
diff --git a/service/scene-manager/include/RemoteSceneList.h b/service/scene-manager/include/RemoteSceneList.h
new file mode 100644 (file)
index 0000000..b102a3c
--- /dev/null
@@ -0,0 +1,197 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef SM_REMOTE_SCENELIST_H_
+#define SM_REMOTE_SCENELIST_H_
+
+#include <memory>
+#include <vector>
+#include <functional>
+#include <mutex>
+
+#include "RemoteSceneCollection.h"
+#include "RCSRemoteResourceObject.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+        class SceneListResourceRequestor;
+
+        /**
+        * @class RemoteSceneList
+        *
+        * @brief RemoteSceneList class is an interface class to send a request to
+        * SceneList resource on remote side. This class provides APIs for adding
+        * new SceneCollection resource to the SceneList resource and
+        * creating a RemoteSceneCollection instance corresponding to the
+        * created SceneCollection resource. This class also supports retrieving the existing
+        * instances as well as setting/getting a name attribute of the SceneList resource.
+        */
+        class RemoteSceneList
+        {
+            public:
+                typedef std::unique_ptr< RemoteSceneList > Ptr;
+
+                /**
+                * Callback definition to be invoked when a response of createInstance is
+                * received.
+                *
+                * @param list Created RemoteSceneList instance pointer
+                * @param eCode The error code received from the SceneList on remote side
+                *
+                * @note Error code '200' stands for success, '400' for bad request,
+                * and '500' for internal error.
+                *
+                * @see createInstance
+                */
+                typedef std::function< void(RemoteSceneList::Ptr list, int eCode) >
+                    CreateInstanceCallback;
+
+                /**
+                * Callback definition to be invoked when a response of addNewSceneCollection is
+                * received.
+                *
+                * @param collection Created RemoteSceneCollection instance pointer
+                * @param eCode The error code received from the SceneList on remote
+                *
+                * @note Error code '200' stands for success, '400' for bad request,
+                * and '500' for internal error.
+                *
+                * @see addNewSceneCollection
+                */
+                typedef std::function< void(RemoteSceneCollection::Ptr collection, int eCode) >
+                    AddNewSceneCollectionCallback;
+
+                /**
+                * Callback definition to be invoked when a response of setName is
+                * received.
+                *
+                * @param eCode the error code received from the SceneList on remote
+                *
+                * @note Error code '200' stands for success, '400' for bad request,
+                * and '500' for internal error.
+                *
+                * @see setName
+                */
+                typedef std::function< void(int eCode) > SetNameCallback;
+
+            public:
+                ~RemoteSceneList() = default;
+
+                /**
+                * Creates RemoteSceneList instance with provided RCSRemoteResourceObject of
+                * discovered SceneList resource on remote side.
+                *
+                * To create RemoteSceneList instance, discovery of SceneList resource
+                * which has 'oic.wk.scenelist' as resource type is required,
+                * and the found resource should be provided as parameter.
+                * After that, one can acceess existing SceneCollections, Scenes, and SceneActions
+                * instances that are already produced at the SceneList resource.
+                * Created RemoteSceneList will be delivered to CreateInstanceCallback.
+                *
+                * @param sceneListResource RCSRemoteResourceObject pointer of SceneList
+                * @param cb A callback to receive the response
+                *
+                * @throws RCSInvalidParameterException If parameter is invalid.
+                * @throws PlatformException If the platform operation failed
+                *
+                * @see RCSRemoteResourceObject
+                */
+                static void createInstance(
+                    RCSRemoteResourceObject::Ptr sceneListResource, CreateInstanceCallback cb);
+
+                /**
+                * Requests to add new SceneCollection resource to the SceneList resource on remote
+                * side and creates RemoteSceneCollection instance corresponding to the created
+                * SceneCollection resource.
+                *
+                * @param cb A callback to receive created RemoteSceneCollection instance
+                *
+                * @throws RCSInvalidParameterException If callback is null.
+                * @throws PlatformException If the platform operation failed
+                *
+                * @note RemoteSceneCollection instance is only produced by RemoteSceneList class.
+                */
+                void addNewSceneCollection(AddNewSceneCollectionCallback cb);
+
+                /**
+                * Gets all RemoteSceneCollection instances stored in the RemoteSceneList instance.
+                *
+                * @return A vector of shared pointers of RemoteSceneCollection instances
+                */
+                std::vector< RemoteSceneCollection::Ptr > getRemoteSceneCollections() const;
+
+                /**
+                * Request to set a name attribute of the SceneList resource on remote side.
+                *
+                * @param name A name of the SceneList
+                * @param cb A callback to receive the response
+                *
+                * @throws RCSInvalidParameterException If callback is null.
+                * @throws PlatformException If the platform operation failed
+                */
+                void setName(const std::string &name, SetNameCallback cb);
+
+                /**
+                * Gets a name attribute of the SceneList resource.
+                *
+                * @return A name of the SceneList resource
+                */
+                std::string getName() const;
+
+            private:
+                RemoteSceneList(std::shared_ptr< SceneListResourceRequestor >);
+
+                static void onInstanceCreated(const RCSRepresentation &, int, const std::string &,
+                    std::shared_ptr< SceneListResourceRequestor >, const CreateInstanceCallback &);
+
+                static RemoteSceneList::Ptr buildSceneList(
+                    std::shared_ptr< SceneListResourceRequestor >, const RCSResourceAttributes &);
+
+                RemoteSceneCollection::Ptr createRemoteSceneCollection(
+                    const std::string &link, const std::string &id, const std::string &name);
+
+                std::shared_ptr< SceneListResourceRequestor > getListResourceRequestor() const;
+
+                std::vector<std::pair<RCSResourceAttributes, std::vector<RCSResourceAttributes>>>
+                    parseSceneListFromAttributes(const RCSResourceAttributes &);
+
+                std::vector<RCSResourceAttributes> getChildrenAttributes(
+                    const RCSResourceAttributes &) const;
+
+                void onSceneCollectionCreated(
+                    const std::string &link, const std::string &id, const std::string &name,
+                    int, const AddNewSceneCollectionCallback &);
+
+                void onNameSet(int, const std::string &, const SetNameCallback &);
+
+            private:
+                std::string m_name;
+                std::vector< RemoteSceneCollection::Ptr > m_remoteSceneCollections;
+                mutable std::mutex m_nameLock;
+                mutable std::mutex m_collectionLock;
+                std::shared_ptr< SceneListResourceRequestor > m_requestor;
+        };
+
+    }
+}
+
+#endif /* SM_REMOTE_SCENELIST_H_ */
\ No newline at end of file
diff --git a/service/scene-manager/include/Scene.h b/service/scene-manager/include/Scene.h
new file mode 100755 (executable)
index 0000000..231c2e5
--- /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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef SM_SCENE_H_
+#define SM_SCENE_H_
+
+#include "SceneAction.h"
+
+#include <vector>
+
+namespace OIC
+{
+    namespace Service
+    {
+
+        class SceneCollectionResource;
+
+        /**
+         * @class Scene
+         *
+         * @brief Scene class is an interface class to manage scenes provided by SceneCollection
+         * resource. This class provide APIs for creating a new SceneAction instance, retrieving all
+         * SceneAction instances created before. And it provides an API to execute a scene.
+         *
+         */
+        class Scene
+        {
+        public:
+            typedef std::shared_ptr< Scene > Ptr;
+
+            /**
+             * Typedef for callback of execute APIs
+             *
+             * @see execute
+             */
+            typedef std::function< void(int) >  ExecuteCallback;
+
+        private:
+            Scene(const Scene&) = default;
+            Scene(const std::string&, std::shared_ptr<SceneCollectionResource>);
+            friend class SceneCollection;
+
+        public:
+
+            /**
+             * Adds new SceneAction instance to the Scene instance
+             *
+             * @param pRCSRemoteResourceObject        A pointer of discovered resource
+             * @param key                               A key of attributes
+             * @param value                             A value to be mapped against the key
+             *
+             * @return A shared pointer of SceneAction instance
+             *
+             * @throws RCSInvalidParameterException if pRCSRemoteResourceObject is nullptr
+             * @throws RCSBadRequestException if scene member resource is already registered
+             *
+             * @note SceneAction instance is only produced by Scene class
+             *
+             * @see RCSResourceAttributes
+             */
+            SceneAction::Ptr addNewSceneAction(
+                    const RCSRemoteResourceObject::Ptr& pRCSRemoteResourceObject,
+                    std::string key, RCSResourceAttributes::Value value);
+
+            /**
+             * Adds new SceneAction instance to the Scene instance
+             *
+             * @param pRCSRemoteResourceObject        A pointer of discovered resource
+             * @param attr                              A attribute set of key and value
+             *
+             * @return A shared pointer of SceneAction instance
+             *
+             * @throws RCSInvalidParameterException if pRCSRemoteResourceObject is nullptr
+             * @throws RCSBadRequestException if SceneMember is already registered
+             *
+             * @note SceneAction instance is only produced by Scene class
+             *
+             * @see RCSResourceAttributes
+             */
+            SceneAction::Ptr addNewSceneAction(
+                    const RCSRemoteResourceObject::Ptr& pRCSRemoteResourceObject,
+                    RCSResourceAttributes attr);
+
+            /**
+             * Gets SceneAction using discovered resource
+             *
+             * @param pRCSRemoteResourceObject        A pointer of discovered resource
+             *
+             * @return A shared pointer of SceneAction
+             *
+             * @throws RCSInvalidParameterException
+             * if pRCSRemoteResourceObject is unknown resource
+             */
+            SceneAction::Ptr getSceneAction(
+                    const RCSRemoteResourceObject::Ptr& pRCSRemoteResourceObject) const;
+
+            /**
+             * Gets all SceneActions include current Scene
+             *
+             * @return A vector of shared pointer of SceneAction instance
+             *
+             */
+            std::vector<SceneAction::Ptr> getSceneActions() const ;
+
+            /**
+             * Gets Scene's name provided SceneCollection resource
+             *
+             * @return Scene's name
+             */
+            std::string getName() const;
+
+            /**
+             * Requests executing Scene to SceneCollection resource
+             *
+             * @param cb                        A callback to execute Scene
+             */
+            void execute(ExecuteCallback cb);
+
+        private:
+            std::string m_name;
+            std::shared_ptr< SceneCollectionResource > m_sceneCollectionResource;
+
+        };
+    } /* namespace Service */
+} /* namespace OIC */
+
+#endif /* SM_SCENE_H_ */
+
diff --git a/service/scene-manager/include/SceneAction.h b/service/scene-manager/include/SceneAction.h
new file mode 100755 (executable)
index 0000000..8c2fd45
--- /dev/null
@@ -0,0 +1,102 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef SM_SCENEACTION_H_
+#define SM_SCENEACTION_H_
+
+#include "RCSRemoteResourceObject.h"
+#include "RCSResourceAttributes.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+
+        class SceneMemberResource;
+
+        /**
+         * @class SceneAction
+         *
+         * @brief SceneAction class indicates a unit of actions when a scene is executed.
+         * SceneAction instance is initialized with 3 essential parameters: a target resource,
+         * target attribute key, and its target value. And this class also provide APIs to update
+         * a target attribute information if one wants
+         *
+         */
+        class SceneAction
+        {
+        public:
+            typedef std::shared_ptr< SceneAction > Ptr;
+
+        private:
+            SceneAction(const std::shared_ptr< SceneMemberResource >,
+                    const std::string&, const RCSResourceAttributes&);
+            SceneAction(const std::shared_ptr< SceneMemberResource >,
+                    const std::string&, const std::string&,
+                    const RCSResourceAttributes::Value&);
+            friend class Scene;
+
+        public:
+            /**
+             * Sets the SceneAction parameters like a target attribute key and its value
+             * It replaces existing execution parameter
+             *
+             * @param key                   A key of attributes
+             * @param value                 A value to be mapped against the key
+             *
+             * @see RCSResourceAttributes
+             */
+            void resetExecutionParameter(const std::string& key, RCSResourceAttributes::Value value);
+
+            /**
+             * Sets the SceneAction parameters like a target attribute key and its value
+             * It replaces existing execution parameter
+             *
+             * @param attr                  Attributes to set
+             *
+             * @see RCSResourceAttributes
+             */
+            void resetExecutionParameter(const RCSResourceAttributes& attr);
+
+            /**
+             * Gets execution parameter of the SceneAction instance
+             *
+             * @return attributes of SceneMember resource
+             *
+             * @see RCSResourceAttributes
+             */
+            RCSResourceAttributes getExecutionParameter() const;
+
+            /**
+             * Gets remote resource object
+             *
+             * @return RCSRemoteResourceObject
+             */
+            RCSRemoteResourceObject::Ptr getRemoteResourceObject() const;
+
+        private:
+            RCSRemoteResourceObject::Ptr m_pRemoteResourceObject;
+            std::string m_sceneName;
+            std::shared_ptr< SceneMemberResource > m_sceneMemberResource;
+        };
+    } /* namespace Service */
+} /* namespace OIC */
+
+#endif /* SM_SCENEACTION_H_ */
diff --git a/service/scene-manager/include/SceneCollection.h b/service/scene-manager/include/SceneCollection.h
new file mode 100755 (executable)
index 0000000..ecc96d8
--- /dev/null
@@ -0,0 +1,117 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef SM_SCENECOLLECTION_H_
+#define SM_SCENECOLLECTION_H_
+
+#include "Scene.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+
+        class SceneCollectionResource;
+
+        /**
+         * @class SceneCollection
+         *
+         * @brief SceneCollection class is an interface class to manage SceneCollection resource.
+         * This class provides APIs to create a new Scene instance and retrieve all Scene instances
+         * created before. Besides, it provide APIs for retrieving and updating attribute values
+         * like name attribute
+         *
+         */
+        class SceneCollection
+        {
+        public:
+            typedef std::shared_ptr< SceneCollection > Ptr;
+
+        private:
+            SceneCollection(const std::shared_ptr< SceneCollectionResource >&);
+            friend class SceneList;
+
+        public:
+
+            /**
+             * Adds new Scene instance to SceneCollection resource
+             *
+             * @param sceneName              A scene's name
+             *
+             * @return A shared pointer of Scene instance
+             *
+             * @throw RCSInvalidParameterException if scene name is empty
+             * @throw RCSInvalidParameterException if scene name is dupltcated
+             *
+             * @note Scene instance is only produced by SceneCollection class
+             * @note Scene's name must unique in one SceneCollection resource
+             */
+            Scene::Ptr addNewScene(const std::string& sceneName);
+
+            /**
+             * Gets all Scene instances from SceneCollection resource
+             *
+             * @return A unordered_map of shared pointers of Scene instances with a Scene's name
+             */
+            std::unordered_map< std::string, Scene::Ptr > getScenes() const;
+
+            /**
+             * Gets a Scene instance with a specific Scene's name.
+             *
+             * @param sceneName             A Scene's name
+             *
+             * @return A shared pointer of Scene instance
+             *
+             * @throws RCSInvalidParameterException
+             * if Scene's name does not exist in SceneCollection resource
+             */
+            Scene::Ptr getScene(const std::string& sceneName) const;
+
+            /**
+             * Sets a name attribute of SceneCollection resource
+             *
+             * @param name               A SceneCollection resource's name
+             */
+            void setName(const std::string& name);
+
+            /**
+             * Gets a name attribute from SceneCollection resource.
+             *
+             * @return A SceneCollection resource's name
+             */
+            std::string getName() const;
+
+            /**
+             * Gets a Id attribute of SceneCollection resource.
+             *
+             * @return A SceneCollection resource's Id
+             *
+             */
+            std::string getId() const;
+
+        private:
+            std::shared_ptr< SceneCollectionResource > m_sceneCollectionResource;
+
+        };
+    } /* namespace Service */
+} /* namespace OIC */
+
+#endif /* SM_SCENECOLLECTION_H_ */
+
diff --git a/service/scene-manager/include/SceneList.h b/service/scene-manager/include/SceneList.h
new file mode 100755 (executable)
index 0000000..89d3334
--- /dev/null
@@ -0,0 +1,92 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef SM_SCENELIST_H_
+#define SM_SCENELIST_H_
+
+#include "SceneCollection.h"
+
+#include <string>
+
+namespace OIC
+{
+    namespace Service
+    {
+
+        /**
+         * @class SceneList
+         *
+         * @brief SceneList class is an interface class to manage SceneList resource. This class
+         * provides APIs for creating a new SceneCollection instance and retrieving the existing
+         * instances as well as for setting/getting a name attribute of SceneList resource.
+         *
+         */
+        class SceneList
+        {
+        private:
+            SceneList() = default;
+            ~SceneList() = default;
+
+        public:
+            /**
+             * Gets static instance of SceneList
+             *
+             * @return SceneList instance
+             *
+             */
+            static SceneList* getInstance();
+
+            /**
+             * Adds new SceneCollection instance
+             *
+             * @return A shared pointer of SceneCollection instance
+             *
+             * @note SceneCollection instance is only produced by SceneList class
+             */
+            SceneCollection::Ptr addNewSceneCollection();
+
+            /**
+             * Gets all SceneCollection instances stored in SceneList resource
+             *
+             * @return A vector of shared pointers of SceneCollection instances
+             *
+             * @note SceneCollection instance that addNewSceneCollection returns is not same
+             * instance that getSceneCollections returns
+             */
+            std::vector<SceneCollection::Ptr> getSceneCollections() const;
+
+            /**
+             * Sets a name attribute of SceneList resource
+             *
+             * @param sceneListName               A SceneList resource's name
+             */
+            void setName(const std::string& sceneListName);
+
+            /**
+             * Gets a name attribute of SceneList resource
+             *
+             * @return A SceneList resource's name
+             */
+            std::string getName() const;
+        };
+    } /* namespace Service */
+} /* namespace OIC */
+
+#endif /* SM_SCENELIST_H_ */
diff --git a/service/scene-manager/sampleapp/SConscript b/service/scene-manager/sampleapp/SConscript
new file mode 100755 (executable)
index 0000000..d59dc6d
--- /dev/null
@@ -0,0 +1,10 @@
+##
+# Examples build script
+##
+Import('env')
+
+target_os = env.get('TARGET_OS')
+if target_os == 'linux':
+       SConscript('linux/SConscript')
+elif target_os == 'arduino':
+       SConscript('arduino/SConscript')
\ No newline at end of file
diff --git a/service/scene-manager/sampleapp/linux/SConscript b/service/scene-manager/sampleapp/linux/SConscript
new file mode 100755 (executable)
index 0000000..6946510
--- /dev/null
@@ -0,0 +1,48 @@
+##
+# GroupManager build script
+##
+
+Import('env')
+
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+scenemanager_sample_env = lib_env.Clone()
+
+######################################################################
+# Build flags
+######################################################################
+scenemanager_sample_env.AppendUnique(CPPPATH = ['../../include', '../../src'])
+scenemanager_sample_env.AppendUnique(CPPPATH = ['../../../resource-encapsulation/include'])
+scenemanager_sample_env.AppendUnique(CPPPATH = ['../../../../extlibs/cjson'])
+scenemanager_sample_env.AppendUnique(CPPPATH = ['../../../../resource/csdk/connectivity/api'])
+scenemanager_sample_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
+
+scenemanager_sample_env.AppendUnique(LIBS = [
+    'scene_manager',
+    'rcs_client',
+    'rcs_server',
+    'rcs_common',
+    'oc',
+    'octbstack',
+    'oc_logger',
+    'connectivity_abstraction',
+    'coap',
+    'pthread'
+    ])
+
+if env.get('SECURED') == '1':
+    scenemanager_sample_env.AppendUnique(LIBS = ['tinydtls'])
+
+if 'rt' in scenemanager_sample_env.get('LIBS'):
+    scenemanager_sample_env.Append(LIBS = ['rt'])
+
+if not env.get('RELEASE'):
+    scenemanager_sample_env.PrependUnique(LIBS = ['gcov'])
+    scenemanager_sample_env.AppendUnique(CXXFLAGS = ['--coverage'])
+####################################################################
+# Source files and Targets
+######################################################################
+sceneserver = scenemanager_sample_env.Program('sceneserver', 'sceneserver.cpp')
+sceneclient = scenemanager_sample_env.Program('sceneclient', 'sceneclient.cpp')
+fanserver = scenemanager_sample_env.Program('fanserver', 'fanserver.cpp')
+lightserver = scenemanager_sample_env.Program('lightserver', 'lightserver.cpp')
\ No newline at end of file
diff --git a/service/scene-manager/sampleapp/linux/fanserver.cpp b/service/scene-manager/sampleapp/linux/fanserver.cpp
new file mode 100755 (executable)
index 0000000..4f6a3c7
--- /dev/null
@@ -0,0 +1,331 @@
+//******************************************************************
+//
+// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+///
+/// This sample provides steps to define an interface for a resource
+/// (properties and methods) and host this resource on the server.
+///
+
+#include <functional>
+
+#include <pthread.h>
+#include <mutex>
+#include <condition_variable>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+
+using namespace OC;
+using namespace std;
+namespace PH = std::placeholders;
+
+int gObservation = 0;
+void * ChangeLightRepresentation(void *param);
+void * handleSlowResponse(void *param, std::shared_ptr< OCResourceRequest > pRequest);
+
+// Specifies secure or non-secure
+// false: non-secure resource
+// true: secure resource
+bool isSecure = false;
+
+/// Specifies whether Entity handler is going to do slow response or not
+bool isSlowResponse = false;
+
+// Forward declaring the entityHandler
+
+/// This class represents a single resource named 'lightResource'. This resource has
+/// two simple properties named 'state' and 'power'
+
+class FanResource
+{
+
+public:
+    /// Access this property from a TB client
+    std::string m_speed;
+    std::string m_fanUri;
+    OCResourceHandle m_resourceHandle;
+    OCRepresentation m_fanRep;
+
+public:
+    /// Constructor
+    FanResource() :
+            m_speed("10"), m_fanUri("/a/fan"), m_resourceHandle(0)
+    {
+        // Initialize representation
+        m_fanRep.setUri(m_fanUri);
+
+        m_fanRep.setValue("speed", m_speed);
+    }
+
+    /* Note that this does not need to be a member function: for classes you do not have
+     access to, you can accomplish this with a free function: */
+
+    /// This function internally calls registerResource API.
+    void createResource()
+    {
+        std::string resourceURI = m_fanUri; //URI of the resource
+        std::string resourceTypeName = "core.fan"; //resource type name. In this case, it is light
+        std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
+
+        EntityHandler cb = std::bind(&FanResource::entityHandler, this, PH::_1);
+
+        // This will internally create and register the resource.
+        OCStackResult result = OCPlatform::registerResource(m_resourceHandle, resourceURI,
+                resourceTypeName, resourceInterface, cb, OC_DISCOVERABLE | OC_OBSERVABLE);
+
+        if (OC_STACK_OK != result)
+        {
+            cout << "Resource creation was unsuccessful\n";
+        }
+        else
+        {
+            cout << "Resource URI : " << resourceURI << endl;
+            cout << "\tResource Type Name : " << resourceTypeName << endl;
+            cout << "\tResource Interface : " << DEFAULT_INTERFACE << endl;
+            cout << "\tResource creation is successful with resource handle : " << m_resourceHandle
+                    << endl;
+        }
+    }
+
+    OCResourceHandle getHandle()
+    {
+        return m_resourceHandle;
+    }
+
+    // Puts representation.
+    // Gets values from the representation and
+    // updates the internal state
+    void put(OCRepresentation& rep)
+    {
+        try
+        {
+            if (rep.getValue("speed", m_speed))
+            {
+                cout << "\t\t\t\t" << "speed: " << m_speed << endl;
+            }
+            else
+            {
+                cout << "\t\t\t\t" << "speed not found in the representation" << endl;
+            }
+        }
+        catch (exception& e)
+        {
+            cout << e.what() << endl;
+        }
+
+    }
+
+    // Post representation.
+    // Post can create new resource or simply act like put.
+    // Gets values from the representation and
+    // updates the internal state
+    OCRepresentation post(OCRepresentation& rep)
+    {
+        put(rep);
+        return get();
+    }
+
+    // gets the updated representation.
+    // Updates the representation with latest internal state before
+    // sending out.
+    OCRepresentation get()
+    {
+        m_fanRep.setValue("speed", m_speed);
+
+        return m_fanRep;
+    }
+
+    void addType(const std::string& type) const
+    {
+        OCStackResult result = OCPlatform::bindTypeToResource(m_resourceHandle, type);
+        if (OC_STACK_OK != result)
+        {
+            cout << "Binding TypeName to Resource was unsuccessful\n";
+        }
+    }
+
+    void addInterface(const std::string& interface) const
+    {
+        OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
+        if (OC_STACK_OK != result)
+        {
+            cout << "Binding TypeName to Resource was unsuccessful\n";
+        }
+    }
+
+private:
+// This is just a sample implementation of entity handler.
+// Entity handler can be implemented in several ways by the manufacturer
+    OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request)
+    {
+        cout << "\tIn Server CPP entity handler:\n";
+        OCEntityHandlerResult ehResult = OC_EH_ERROR;
+        if (request)
+        {
+            // Get the request type and request flag
+            std::string requestType = request->getRequestType();
+            int requestFlag = request->getRequestHandlerFlag();
+
+            if (requestFlag & RequestHandlerFlag::RequestFlag)
+            {
+                cout << "\t\trequestFlag : Request\n";
+                auto pResponse = std::make_shared< OC::OCResourceResponse >();
+                pResponse->setRequestHandle(request->getRequestHandle());
+                pResponse->setResourceHandle(request->getResourceHandle());
+
+                // If the request type is GET
+                if (requestType == "GET")
+                {
+                    cout << "\t\t\trequestType : GET\n";
+                    if (isSlowResponse) // Slow response case
+                    {
+                        static int startedThread = 0;
+                        if (!startedThread)
+                        {
+                            std::thread t(handleSlowResponse, (void *) this, request);
+                            startedThread = 1;
+                            t.detach();
+                        }
+                        ehResult = OC_EH_SLOW;
+                    }
+                    else // normal response case.
+                    {
+                        pResponse->setErrorCode(200);
+                        pResponse->setResponseResult(OC_EH_OK);
+                        pResponse->setResourceRepresentation(get());
+                        if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+                        {
+                            ehResult = OC_EH_OK;
+                        }
+                    }
+                }
+                else if (requestType == "PUT")
+                {
+                    cout << "\t\t\trequestType : PUT\n";
+                    OCRepresentation rep = request->getResourceRepresentation();
+
+                    // Do related operations related to PUT request
+                    // Update the lightResource
+                    put(rep);
+                    pResponse->setErrorCode(200);
+                    pResponse->setResponseResult(OC_EH_OK);
+                    pResponse->setResourceRepresentation(get());
+                    if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+                    {
+                        ehResult = OC_EH_OK;
+                    }
+                }
+                else if (requestType == "POST")
+                {
+                    cout << "\t\t\trequestType : POST\n";
+
+                    OCRepresentation rep = request->getResourceRepresentation();
+
+                    // Do related operations related to POST request
+                    OCRepresentation rep_post = post(rep);
+                    pResponse->setResourceRepresentation(rep_post);
+                    pResponse->setErrorCode(200);
+                    if (rep_post.hasAttribute("createduri"))
+                    {
+                        pResponse->setResponseResult(OC_EH_RESOURCE_CREATED);
+                        pResponse->setNewResourceUri(
+                                rep_post.getValue< std::string >("createduri"));
+                    }
+
+                    if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+                    {
+                        ehResult = OC_EH_OK;
+                    }
+                }
+                else if (requestType == "DELETE")
+                {
+                    // DELETE request operations
+                }
+            }
+        }
+        else
+        {
+            std::cout << "Request invalid" << std::endl;
+        }
+
+        return ehResult;
+    }
+};
+
+void * handleSlowResponse(void *param, std::shared_ptr< OCResourceRequest > pRequest)
+{
+    // This function handles slow response case
+    FanResource* fanPtr = (FanResource*) param;
+    // Induce a case for slow response by using sleep
+    std::cout << "SLOW response" << std::endl;
+    sleep(10);
+
+    auto pResponse = std::make_shared< OC::OCResourceResponse >();
+    pResponse->setRequestHandle(pRequest->getRequestHandle());
+    pResponse->setResourceHandle(pRequest->getResourceHandle());
+    pResponse->setResourceRepresentation(fanPtr->get());
+    pResponse->setErrorCode(200);
+    pResponse->setResponseResult(OC_EH_OK);
+
+    // Set the slow response flag back to false
+    isSlowResponse = false;
+    OCPlatform::sendResponse(pResponse);
+    return NULL;
+}
+
+int main()
+{
+    // Create PlatformConfig object
+    PlatformConfig cfg
+    { OC::ServiceType::InProc, OC::ModeType::Server, "0.0.0.0",
+    // By setting to "0.0.0.0", it binds to all available interfaces
+            0,// Uses randomly available port
+            OC::QualityOfService::LowQos };
+
+    OCPlatform::Configure(cfg);
+    try
+    {
+        // Create the instance of the resource class
+        // (in this case instance of class 'LightResource').
+        FanResource myFan;
+
+        // Invoke createResource function of class light.
+        myFan.createResource();
+
+        // A condition variable will free the mutex it is given, then do a non-
+        // intensive block until 'notify' is called on it.  In this case, since we
+        // don't ever call cv.notify, this should be a non-processor intensive version
+        // of while(true);
+        std::mutex blocker;
+        std::condition_variable cv;
+        std::unique_lock < std::mutex > lock(blocker);
+        cv.wait(lock);
+    }
+    catch (OCException e)
+    {
+        //log(e.what());
+    }
+
+    // No explicit call to stop the platform.
+    // When OCPlatform::destructor is invoked, internally we do platform cleanup
+
+    return 0;
+}
diff --git a/service/scene-manager/sampleapp/linux/sceneclient.cpp b/service/scene-manager/sampleapp/linux/sceneclient.cpp
new file mode 100755 (executable)
index 0000000..22bdc20
--- /dev/null
@@ -0,0 +1,575 @@
+//******************************************************************
+//
+// 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 <iostream>
+#include <vector>
+#include <algorithm>
+#include <condition_variable>
+
+#include "OCPlatform.h"
+#include "RCSDiscoveryManager.h"
+#include "RCSRemoteResourceObject.h"
+#include "RCSAddress.h"
+#include "RemoteSceneList.h"
+
+using namespace OC;
+using namespace OIC::Service;
+
+constexpr int CREATE_REMOTE_SCENE_LIST = 1;
+
+constexpr int CREATE_REMOTE_SCENE_COLLECTION = 1;
+constexpr int SHOW_REMOTE_SCENE_COLLECTION = 2;
+
+constexpr int CREATE_REMOTE_SCENE = 1;
+constexpr int CREATE_REMOTE_SCENE_ACTION = 1;
+
+constexpr int EXECUTE_REMOTE_SCENE = 1;
+
+constexpr int SCENE_RESULT_OK = 200;
+
+constexpr int numCreatedSceneAction = 2;
+static int numRecvSceneActionCreationResp = 0;
+
+typedef std::function< void() > Run;
+Run g_currentRun;
+
+const std::string scene_name = "Night mode";
+const std::string relativetUri = OC_RSRVD_WELL_KNOWN_URI;
+const std::vector<std::string> resourceTypes{ "oic.wk.scenelist", "core.light", "core.fan" };
+
+std::mutex g_mtx;
+std::mutex g_discoverymtx;
+std::condition_variable g_cond;
+
+std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> g_discoveryTask;
+
+RCSRemoteResourceObject::Ptr g_foundListResource;
+RCSRemoteResourceObject::Ptr g_foundLightResource;
+RCSRemoteResourceObject::Ptr g_foundFanResource;
+
+RemoteSceneList::Ptr g_sceneList;
+RemoteSceneCollection::Ptr g_sceneCollection;
+RemoteScene::Ptr g_scene;
+
+void displaySceneList();
+void runCreateRemoteSceneList();
+void runRemoteSceneCollection();
+void runCreateRemoteScene();
+void runCreateRemoteSceneAction();
+void runExecuteCreatedRemoteScene();
+void runExecuteExistingRemoteScene();
+
+// Scene Manager Remote API sample ---
+void onRemoteSceneListCreated(RemoteSceneList::Ptr remoteSceneList, int eCode)
+{
+    std::cout << __func__ << " - error code : " << eCode << std::endl;
+
+    if (eCode == SCENE_RESULT_OK)
+    {
+        g_sceneList = std::move(remoteSceneList);
+        g_currentRun = runRemoteSceneCollection;
+    }
+    else
+    {
+        std::cout << "Create Remote scene list failed." << std::endl;
+        g_currentRun = runCreateRemoteSceneList;
+    }
+    g_currentRun();
+}
+
+void onRemoteSceneCollectionCreated(RemoteSceneCollection::Ptr remoteSceneCol, int eCode)
+{
+    std::cout << __func__ << " - error code : " << eCode << std::endl;
+
+    if (eCode == SCENE_RESULT_OK)
+    {
+        g_sceneCollection = remoteSceneCol;
+        g_currentRun = runCreateRemoteScene;
+    }
+    else
+    {
+        std::cout << "Create Remote scene collection failed." << std::endl;
+        g_currentRun = runRemoteSceneCollection;
+    }
+
+    g_currentRun();
+}
+
+void onRemoteSceneCreated(RemoteScene::Ptr remoteScene, int eCode)
+{
+    std::cout << __func__ << " - error code : " << eCode << std::endl;
+
+    if (eCode == SCENE_RESULT_OK)
+    {
+        g_scene = remoteScene;
+
+        g_currentRun = runCreateRemoteSceneAction;
+    }
+    else
+    {
+        std::cout << "Create Remote scene failed." << std::endl;
+        g_currentRun = runCreateRemoteScene;
+    }
+
+    g_currentRun();
+}
+
+void onRemoteSceneActionCreated(RemoteSceneAction::Ptr, int eCode)
+{
+    std::cout << __func__ << " - error code : " << eCode << std::endl;
+
+    if (eCode == SCENE_RESULT_OK)
+    {
+        g_currentRun = runExecuteCreatedRemoteScene;
+    }
+    else
+    {
+        std::cout << "Create Remote scene action failed." << std::endl;
+        g_currentRun = runCreateRemoteSceneAction;
+    }
+
+    numRecvSceneActionCreationResp++;
+
+    if(numCreatedSceneAction == numRecvSceneActionCreationResp)
+        g_currentRun();
+}
+
+void onRemoteSceneExecuted(const std::string &sceneName, int eCode)
+{
+    std::cout << __func__ << " - scene name : " << sceneName
+              <<  ", error code : " << eCode << std::endl;
+
+    if (eCode != SCENE_RESULT_OK)
+    {
+        std::cout << "Execute scene failed." << std::endl;
+    }
+
+    g_currentRun();
+}
+
+// --- Scene Manager Remote API sample
+
+void createRemoteSceneList()
+{
+    if (g_foundListResource)
+    {
+        RemoteSceneList::createInstance(g_foundListResource, onRemoteSceneListCreated);
+    }
+    else
+    {
+        std::cout << "Scene List Resource is not discovered." << std::endl;
+        g_currentRun();
+    }
+}
+
+void createRemoteSceneCollection()
+{
+    if (!g_sceneList) return;
+
+    g_sceneList->addNewSceneCollection(onRemoteSceneCollectionCreated);
+}
+
+void showRemoteSceneCollection()
+{
+    if (!g_sceneList) return;
+
+    if (g_sceneList->getRemoteSceneCollections().size() == 0) return;
+
+    g_sceneCollection = g_sceneList->getRemoteSceneCollections().at(0);
+
+    if( g_sceneCollection->getRemoteScenes().size() == 0) return;
+
+    g_scene = g_sceneCollection->getRemoteScenes().begin()->second;
+}
+
+void createRemoteScene()
+{
+    if (!g_sceneCollection) return;
+
+    g_sceneCollection->addNewScene(scene_name, onRemoteSceneCreated);
+}
+
+void createRemoteSceneAction(
+    RemoteScene::Ptr scene, RCSRemoteResourceObject::Ptr member,
+    const std::string &key, const std::string &value)
+{
+    if (scene && member)
+    {
+        g_scene->addNewSceneAction(member, key, RCSResourceAttributes::Value(value),
+            onRemoteSceneActionCreated);
+    }
+}
+
+void createRemoteSceneActions()
+{
+    createRemoteSceneAction(g_scene, g_foundLightResource, "power", "on");
+    createRemoteSceneAction(g_scene, g_foundFanResource, "speed", "50");
+}
+
+void executeScene()
+{
+    displaySceneList();
+
+    if (g_scene)
+    {
+        g_scene->execute(onRemoteSceneExecuted);
+        std::cout << "\n\t'" << g_scene->getName() << "' is executed!\n" << std::endl;
+    }
+}
+
+// --- Scene Manager Remote API sample
+
+void configurePlatform()
+{
+    PlatformConfig config
+    {
+        OC::ServiceType::InProc, ModeType::Both, "0.0.0.0", 0, OC::QualityOfService::LowQos
+    };
+    OCPlatform::Configure(config);
+}
+
+int processUserInput(int min, int max)
+{
+    assert(min <= max);
+
+    int input;
+
+    std::cin >> input;
+
+    if (!std::cin.fail())
+    {
+        if (input == max + 1)  exit(0);
+        if (min <= input && input <= max) return input;
+    }
+
+    std::cin.clear();
+    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
+
+    throw std::runtime_error("Invalid Input, please try again");
+}
+
+void displaySceneList()
+{
+    if (!g_sceneList) return;
+
+    std::cout << "\t" << g_sceneList->getName() << "(SceneList)" << std::endl;
+
+    if (!g_sceneCollection) return;
+
+    std::cout << "\t\t   |_ _ _ " << g_sceneCollection->getId() << " (SceneCollection)" << std::endl;
+
+    for( const auto &it_scene : g_sceneCollection->getRemoteScenes() )
+    {
+        std::cout << "\t\t\t   |_ _ _ " << it_scene.first << " (Scene)" << std::endl;
+
+        auto sceneActionList = it_scene.second->getRemoteSceneActions();
+        for (const auto &it : sceneActionList)
+        {
+            auto attr = it->getExecutionParameter();
+            for (const auto &att : attr)
+            {
+                std::cout << "\t\t\t      \t\t|_ _ _ ";
+                std::cout << it->getRemoteResourceObject()->getUri() << " : ";
+                std::cout << att.key() << " - " << att.value().toString() << std::endl;
+            }
+        }
+    }
+}
+
+void displayClear(Run runFunc)
+{
+    auto ret = std::system("/usr/bin/clear");
+    if(ret == -1)
+    {
+        std::cout << "clear error!" << std::endl;
+    }
+    g_currentRun = runFunc;
+}
+
+void displayCreateRemoteSceneListMenu()
+{
+    std::cout << "========================================================\n";
+    std::cout << CREATE_REMOTE_SCENE_LIST  << ". Create a RemoteSceneList \n";
+    std::cout << CREATE_REMOTE_SCENE_LIST + 1  << ". Quit                 \n";
+    std::cout << "========================================================\n";
+}
+
+void displayRemoteSceneCollectionMenu()
+{
+    std::cout << "========================================================               \n";
+    std::cout << CREATE_REMOTE_SCENE_COLLECTION  << ". Create a RemoteSceneCollection    \n";
+    std::cout << SHOW_REMOTE_SCENE_COLLECTION  << ". Show existing RemoteSceneCollection \n";
+    std::cout << SHOW_REMOTE_SCENE_COLLECTION + 1  << ". Quit                            \n";
+    std::cout << "========================================================               \n";
+}
+
+void displayRemoteSceneCreationMenu()
+{
+    std::cout << "========================================================\n";
+    std::cout << CREATE_REMOTE_SCENE  << ". Create a RemoteScene          \n";
+    std::cout << CREATE_REMOTE_SCENE + 1  << ". Quit                      \n";
+    std::cout << "========================================================\n";
+}
+
+void displayRemoteSceneActionCreationMenu()
+{
+    std::cout << "========================================================   \n";
+    std::cout << CREATE_REMOTE_SCENE_ACTION  << ". Create RemoteSceneActions \n";
+    std::cout << CREATE_REMOTE_SCENE_ACTION + 1  << ". Quit                  \n";
+    std::cout << "========================================================   \n";
+}
+
+void displayExecuteCreatedRemoteSceneCreationMenu()
+{
+    std::cout << "========================================================\n";
+    std::cout << EXECUTE_REMOTE_SCENE  << ". Execute RemoteScene          \n";
+    std::cout << EXECUTE_REMOTE_SCENE + 1  << ". Quit                     \n";
+    std::cout << "========================================================\n";
+}
+
+void displayExecuteExistingRemoteSceneCreationMenu()
+{
+    std::cout << "========================================================\n";
+    std::cout << EXECUTE_REMOTE_SCENE  << ". Execute a first RemoteScene  \n";
+    std::cout << EXECUTE_REMOTE_SCENE + 1  << ". Quit                     \n";
+    std::cout << "========================================================\n";
+}
+
+void runExecuteExistingRemoteScene()
+{
+    displaySceneList();
+
+    displayExecuteExistingRemoteSceneCreationMenu();
+
+    try
+    {
+        int command = processUserInput(EXECUTE_REMOTE_SCENE, EXECUTE_REMOTE_SCENE);
+        switch(command)
+        {
+            case EXECUTE_REMOTE_SCENE:
+                executeScene();
+                displayClear(runExecuteExistingRemoteScene);
+                break;
+        }
+    } catch (std::exception &e)
+    {
+        std::cout << e.what() << std::endl;
+        g_currentRun();
+    }
+}
+
+void runExecuteCreatedRemoteScene()
+{
+    displaySceneList();
+
+    displayExecuteCreatedRemoteSceneCreationMenu();
+
+    try
+    {
+        int command = processUserInput(EXECUTE_REMOTE_SCENE, EXECUTE_REMOTE_SCENE);
+        switch(command)
+        {
+            case EXECUTE_REMOTE_SCENE:
+                executeScene();
+                displayClear(runExecuteCreatedRemoteScene);
+                break;
+        }
+    } catch (std::exception &e)
+    {
+        std::cout << e.what() << std::endl;
+        g_currentRun();
+    }
+}
+
+void runCreateRemoteSceneAction()
+{
+    displaySceneList();
+
+    displayRemoteSceneActionCreationMenu();
+
+    try
+    {
+        int command = processUserInput(CREATE_REMOTE_SCENE_ACTION, CREATE_REMOTE_SCENE_ACTION);
+        switch(command)
+        {
+            case CREATE_REMOTE_SCENE_ACTION:
+                createRemoteSceneActions();
+                displayClear(runExecuteCreatedRemoteScene);
+                break;
+        }
+    } catch (std::exception &e)
+    {
+        std::cout << e.what() << std::endl;
+        g_currentRun();
+    }
+}
+
+void runCreateRemoteScene()
+{
+    displaySceneList();
+
+    displayRemoteSceneCreationMenu();
+
+    try
+    {
+        int command = processUserInput(CREATE_REMOTE_SCENE, CREATE_REMOTE_SCENE);
+        switch(command)
+        {
+            case CREATE_REMOTE_SCENE:
+                createRemoteScene();
+                displayClear(runCreateRemoteSceneAction);
+                break;
+        }
+    } catch (std::exception &e)
+    {
+        std::cout << e.what() << std::endl;
+        g_currentRun();
+    }
+}
+
+void runRemoteSceneCollection()
+{
+    displaySceneList();
+
+    displayRemoteSceneCollectionMenu();
+
+    try
+    {
+        int command = processUserInput(CREATE_REMOTE_SCENE_COLLECTION, SHOW_REMOTE_SCENE_COLLECTION);
+        switch(command)
+        {
+            case CREATE_REMOTE_SCENE_COLLECTION:
+                createRemoteSceneCollection();
+                displayClear(runCreateRemoteScene);
+                break;
+            case SHOW_REMOTE_SCENE_COLLECTION:
+                showRemoteSceneCollection();
+                displayClear(runExecuteExistingRemoteScene);
+                g_currentRun();
+                break;
+        }
+    } catch (std::exception &e)
+    {
+        std::cout << e.what() << std::endl;
+        g_currentRun();
+    }
+}
+
+void runCreateRemoteSceneList()
+{
+    displayCreateRemoteSceneListMenu();
+
+    try
+    {
+        int command = processUserInput(CREATE_REMOTE_SCENE_LIST, CREATE_REMOTE_SCENE_LIST);
+        switch(command)
+        {
+            case CREATE_REMOTE_SCENE_LIST:
+                createRemoteSceneList();
+                displayClear(runRemoteSceneCollection);
+                break;
+        }
+    } catch (std::exception &e)
+    {
+        std::cout << e.what() << std::endl;
+        g_currentRun();
+    }
+}
+
+void onResourceDiscovered(std::shared_ptr<RCSRemoteResourceObject> foundResource)
+{
+    std::lock_guard< std::mutex > lock(g_discoverymtx);
+    std::cout << "onResourceDiscovered callback" << std::endl;
+
+    std::string resourceURI = foundResource->getUri();
+    std::string hostAddress = foundResource->getAddress();
+    std::vector< std::string > vecRTs = foundResource->getTypes();
+
+    std::cout << "\t\tResource URI : " << resourceURI << std::endl;
+    std::cout << "\t\tResource Host : " << hostAddress << std::endl;
+
+    // if the found resource is a scene list resource
+    if (std::find(vecRTs.begin(), vecRTs.end(), "oic.wk.scenelist") != vecRTs.end())
+        g_foundListResource = foundResource;
+
+    // if the found resource is a light resource
+    else if (std::find(vecRTs.begin(), vecRTs.end(), "core.light") != vecRTs.end())
+    {
+        g_foundLightResource = foundResource;
+    }
+
+    // if the found resource is a fan resource
+    else if (std::find(vecRTs.begin(), vecRTs.end(), "core.fan") != vecRTs.end())
+    {
+        g_foundFanResource = foundResource;
+    }
+
+    if (g_foundListResource && g_foundLightResource && g_foundFanResource)
+    {
+        g_discoveryTask->cancel();
+        return;
+    }
+
+    g_cond.notify_all();
+}
+
+void discoverResource()
+{
+    std::cout << "Wait 4 seconds until discovered." << std::endl;
+
+    try
+    {
+        g_discoveryTask
+            = RCSDiscoveryManager::getInstance()->discoverResourceByTypes(RCSAddress::multicast(),
+                    relativetUri, resourceTypes, &onResourceDiscovered);
+    }
+    catch (const RCSPlatformException &e)
+    {
+        std::cout << e.what() << std::endl;
+    }
+    std::unique_lock<std::mutex> lck(g_mtx);
+
+    g_cond.wait_for(lck, std::chrono::seconds(4));
+    return;
+}
+
+int main()
+{
+    configurePlatform();
+
+    try
+    {
+        discoverResource();
+
+        g_currentRun = runCreateRemoteSceneList;
+        g_currentRun();
+    }
+    catch(std::exception &e)
+    {
+        std::cout << e.what() << std::endl;
+        return 0;
+    }
+
+    while (true) { }
+
+    std::cout << "Stopping the scene client" << std::endl;
+
+    return 0;
+}
diff --git a/service/scene-manager/sampleapp/linux/sceneserver.cpp b/service/scene-manager/sampleapp/linux/sceneserver.cpp
new file mode 100755 (executable)
index 0000000..8194d06
--- /dev/null
@@ -0,0 +1,441 @@
+//******************************************************************
+//
+// 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 <condition_variable>
+#include <iostream>
+#include <vector>
+#include <condition_variable>
+
+#include "OCPlatform.h"
+#include "RCSDiscoveryManager.h"
+#include "RCSRemoteResourceObject.h"
+#include "RCSResourceAttributes.h"
+#include "RCSResourceObject.h"
+#include "RCSAddress.h"
+#include "SceneList.h"
+
+using namespace OC;
+using namespace OIC::Service;
+
+constexpr int CREATE_SCENE_LIST = 1;
+
+constexpr int CREATE_SCENE_COLLECTION = 1;
+
+constexpr int CREATE_SCENE = 1;
+
+constexpr int CREATE_SCENE_ACTION = 1;
+
+constexpr int EXECUTE_SCENE_1 = 1;
+constexpr int EXECUTE_SCENE_2 = 2;
+
+typedef void (*DisplayControlMenuFunc)();
+typedef std::function<void()> Run;
+
+std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> discoveryTask;
+Run g_currentRun;
+
+struct CloseApp {};
+
+const std::vector<std::string> resourceTypes{"core.light", "core.fan"};
+const std::string relativetUri = OC_RSRVD_WELL_KNOWN_URI;
+
+std::mutex mtx;
+std::condition_variable cond;
+
+RCSRemoteResourceObject::Ptr g_selectedResource;
+std::shared_ptr<RCSRemoteResourceObject> g_discoveredResources;
+
+std::vector<RCSRemoteResourceObject::Ptr> g_foundResourceList;
+std::vector<RCSResourceObject::Ptr> g_memberResourceList;
+
+SceneCollection::Ptr g_sceneColObj;
+Scene::Ptr g_scene;
+Scene::Ptr g_scene_2;
+SceneAction::Ptr g_sceneAction;
+
+typedef std::function<void(std::shared_ptr<RCSRemoteResourceObject>)> DiscoveryCallback;
+typedef std::function<void (int)> ExecuteCallback;
+
+void onExecute(int /*Code*/)
+{
+    std::cout << __func__ << std::endl;
+}
+
+void configurePlatform()
+{
+    PlatformConfig config
+    {
+        OC::ServiceType::InProc, ModeType::Both, "0.0.0.0", 0, OC::QualityOfService::LowQos
+    };
+    OCPlatform::Configure(config);
+}
+
+int processUserInput(int min, int max)
+{
+    assert(min <= max);
+
+    int input;
+
+    std::cin >> input;
+
+    if (!std::cin.fail())
+    {
+        if(input == max + 1) throw CloseApp();
+        if(min <= input && input <= max) return input;
+    }
+
+    std::cin.clear();
+    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
+
+    throw std::runtime_error("Invalid Input, please try again");
+}
+
+void displayCreateSceneListMenu()
+{
+    std::cout << "========================================================\n";
+    std::cout << CREATE_SCENE_LIST  << ". Create a SceneList                       \n";
+    std::cout << CREATE_SCENE_LIST + 1  << ". Quit                       \n";
+    std::cout << "========================================================\n";
+}
+
+void displayCreateSceneCollectionMenu()
+{
+    std::cout << "========================================================\n";
+    std::cout << CREATE_SCENE_COLLECTION  << ". Create a SceneCollection                       \n";
+    std::cout << CREATE_SCENE_COLLECTION + 1  << ". Quit                       \n";
+    std::cout << "========================================================\n";
+}
+
+void displayCreateSceneMenu()
+{
+    std::cout << "========================================================\n";
+    std::cout << CREATE_SCENE  << ". Create a Scene                       \n";
+    std::cout << CREATE_SCENE + 1  << ". Quit                       \n";
+    std::cout << "========================================================\n";
+}
+
+void displayCreateSceneActionMenu()
+{
+    std::cout << "========================================================\n";
+    std::cout << CREATE_SCENE_ACTION  << ". Create a SceneAction                       \n";
+    std::cout << CREATE_SCENE_ACTION + 1  << ". Quit                       \n";
+    std::cout << "========================================================\n";
+}
+
+void displayExecuteSceneMenu()
+{
+    std::cout << "========================================================\n";
+    std::cout << EXECUTE_SCENE_1  << ". Execute Scene1                       \n";
+    std::cout << EXECUTE_SCENE_2  << ". Execute Scene2                       \n";
+    std::cout << EXECUTE_SCENE_2 + 1  << ". Quit                       \n";
+    std::cout << "========================================================\n";
+}
+
+void displaySceneList()
+{
+    std::cout << "\t" << SceneList::getInstance()->getName();
+    std::cout << "(SceneList)" << std::endl;
+}
+
+void displaySceneCollection()
+{
+    std::cout << "\t\t   |_ _ _ " << g_sceneColObj->getName();
+    std::cout << "(SceneCollection)" << std::endl;
+}
+
+void displayScene()
+{
+    std::cout << "\t\t\t      |_ _ _ " << g_scene->getName();
+    std::cout << "(Scene)" << std::endl;
+    std::cout << "\t\t\t      |_ _ _ " << g_scene_2->getName();
+    std::cout << "(Scene)" << std::endl;
+}
+
+void displayClear(Run runFunc)
+{
+    std::cout << "\nPress Enter to Continue....." << std::endl;
+    std::cin.ignore();
+    if(std::cin.get() == '\n')
+    {
+        auto ret = std::system("/usr/bin/clear");
+        if(ret == -1)
+        {
+            std::cout << "clear error!" << std::endl;
+        }
+        g_currentRun = runFunc;
+    }
+}
+
+void displaySceneAction()
+{
+    std::cout << "\t\t\t      |_ _ _ " << g_scene->getName();
+    std::cout << "(Scene)" << std::endl;
+    auto sceneActionList = g_scene->getSceneActions();
+    for(const auto &it : sceneActionList)
+    {
+        auto attr = it->getExecutionParameter();
+        for(const auto &att : attr)
+        {
+            std::cout << "\t\t\t      |\t\t|_ _ _ ";
+            std::cout << it->getRemoteResourceObject()->getUri() << ":";
+            std::cout << att.key() << " - "  << att.value().toString() << std::endl;
+        }
+    }
+
+    std::cout << "\t\t\t      |_ _ _ " << g_scene_2->getName();
+    std::cout << "(Scene)" << std::endl;
+
+    sceneActionList = g_scene_2->getSceneActions();
+    for(const auto &it : sceneActionList)
+    {
+        auto attr = it->getExecutionParameter();
+        for(const auto &att : attr)
+        {
+            std::cout << "\t\t\t       \t\t|_ _ _ ";
+            std::cout << it->getRemoteResourceObject()->getUri() << ":";
+            std::cout << att.key() << " - "  << att.value().toString() << std::endl;
+        }
+    }
+}
+
+void onResourceDiscovered(std::shared_ptr<RCSRemoteResourceObject> foundResource)
+{
+    std::cout << "onResourceDiscovered callback" << std::endl;
+
+    std::string resourceURI = foundResource->getUri();
+    std::string hostAddress = foundResource->getAddress();
+
+    std::cout << "\t\tResource URI : " << resourceURI << std::endl;
+    std::cout << "\t\tResource Host : " << hostAddress << std::endl;
+
+    g_foundResourceList.push_back(foundResource);
+
+    cond.notify_all();
+}
+
+bool discoverResource()
+{
+    std::cout << "Wait 2 seconds until discovered." << std::endl;
+
+    try
+    {
+        discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByTypes(
+                RCSAddress::multicast(), relativetUri, resourceTypes, &onResourceDiscovered);
+    }
+    catch(const RCSPlatformException& e)
+    {
+         std::cout << e.what() << std::endl;
+    }
+    catch(const RCSException& e)
+    {
+        std::cout << e.what() << std::endl;
+    }
+    std::unique_lock<std::mutex> lck(mtx);
+
+    cond.wait_for(lck, std::chrono::seconds(4));
+    return g_discoveredResources != nullptr;
+}
+
+void createSceneList()
+{
+    SceneList::getInstance()->setName("Home");
+    displaySceneList();
+}
+
+void createSceneCollection()
+{
+    g_sceneColObj = SceneList::getInstance()->addNewSceneCollection();
+    g_sceneColObj->setName("Living Room");
+    displaySceneList();
+    displaySceneCollection();
+}
+
+void createScene()
+{
+    try
+    {
+        g_scene = g_sceneColObj->addNewScene("Going Out");
+        g_scene_2 = g_sceneColObj->addNewScene("TV mode");
+    }
+    catch(const RCSException& e)
+    {
+        std::cout << e.what() << std::endl;
+    }
+
+    displaySceneList();
+    displaySceneCollection();
+    displayScene();
+}
+
+void createSceneAction()
+{
+    try
+    {
+        g_scene->addNewSceneAction(g_foundResourceList.at(0), "power", "off");
+        g_scene->addNewSceneAction(g_foundResourceList.at(1), "speed", "0");
+
+        g_scene_2->addNewSceneAction(g_foundResourceList.at(0), "power", "on");
+        g_scene_2->addNewSceneAction(g_foundResourceList.at(1), "speed", "20");
+    }
+    catch(const RCSException& e)
+    {
+        std::cout << e.what() << std::endl;
+    }
+
+    displaySceneList();
+    displaySceneCollection();
+    displaySceneAction();
+}
+
+void executeScene(int sceneNum)
+{
+    displaySceneList();
+    displaySceneCollection();
+    displaySceneAction();
+
+    switch(sceneNum)
+    {
+        case 1:
+            try
+            {
+                g_scene->execute(onExecute);
+                std::cout << "\t'" << g_scene->getName() << "' is executed!" << std::endl;
+            }
+            catch(const RCSException& e)
+            {
+                std::cout << e.what() <<std::endl;
+            }
+            break;
+        case 2:
+            try
+            {
+                g_scene_2->execute(onExecute);
+                std::cout << "\t'" << g_scene_2->getName() << "' is executed!" << std::endl;
+            }
+            catch(const RCSException& e)
+            {
+                std::cout << e.what() <<std::endl;
+            }
+            break;
+    }
+}
+
+void runExecuteScene()
+{
+    displayExecuteSceneMenu();
+
+    int command = processUserInput(EXECUTE_SCENE_1, EXECUTE_SCENE_2);
+    switch(command)
+    {
+        case EXECUTE_SCENE_1:
+            executeScene(1);
+            break;
+        case EXECUTE_SCENE_2:
+            executeScene(2);
+            break;
+    }
+    displayClear(runExecuteScene);
+}
+
+void runCreateSceneAction()
+{
+    displayCreateSceneActionMenu();
+
+    int command = processUserInput(CREATE_SCENE_ACTION, CREATE_SCENE_ACTION);
+    switch(command)
+    {
+        case CREATE_SCENE_ACTION:
+            createSceneAction();
+            displayClear(runExecuteScene);
+            break;
+    }
+}
+
+void runCreateScene()
+{
+    displayCreateSceneMenu();
+
+    int command = processUserInput(CREATE_SCENE, CREATE_SCENE);
+    switch(command)
+    {
+        case CREATE_SCENE:
+            createScene();
+            displayClear(runCreateSceneAction);
+            break;
+    }
+}
+
+void runCreateSceneCollection()
+{
+    displayCreateSceneCollectionMenu();
+
+    int command = processUserInput(CREATE_SCENE_COLLECTION, CREATE_SCENE_COLLECTION);
+    switch(command)
+    {
+        case CREATE_SCENE_COLLECTION:
+            createSceneCollection();
+            displayClear(runCreateScene);
+            break;
+    }
+}
+
+void runCreateSceneList()
+{
+    displayCreateSceneListMenu();
+
+    int command = processUserInput(CREATE_SCENE_LIST, CREATE_SCENE_LIST);
+    switch(command)
+    {
+        case CREATE_SCENE_LIST:
+            discoveryTask->cancel();
+            createSceneList();
+            displayClear(runCreateSceneCollection);
+            break;
+    }
+}
+
+int main()
+{
+    configurePlatform();
+
+    discoverResource();
+
+    g_currentRun = runCreateSceneList;
+
+    while (true)
+    {
+        try
+        {
+            g_currentRun();
+        }
+        catch (const std::exception& e)
+        {
+            std::cout << e.what() << std::endl;
+        }
+        catch (const CloseApp&)
+        {
+            break;
+        }
+    }
+
+    std::cout << "Stopping the client" << std::endl;
+
+    return 0;
+}
diff --git a/service/scene-manager/src/RemoteScene.cpp b/service/scene-manager/src/RemoteScene.cpp
new file mode 100644 (file)
index 0000000..5956d8b
--- /dev/null
@@ -0,0 +1,195 @@
+//******************************************************************
+//
+// 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 "RemoteScene.h"
+
+#include <utility>
+#include <cassert>
+
+#include "SceneCommons.h"
+#include "SceneCollectionResourceRequestor.h"
+#include "SceneMemberResourceRequestor.h"
+#include "OCPlatform.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+
+        RemoteScene::RemoteScene(
+            const std::string &name, std::shared_ptr< SceneCollectionResourceRequestor > requestor)
+            : m_name{ name }, m_requestor{ requestor }
+        {
+            assert(requestor);
+        }
+
+        void RemoteScene::addNewSceneAction(
+            RCSRemoteResourceObject::Ptr targetResource, const RCSResourceAttributes &attrs,
+            AddNewSceneActionCallback clientCB)
+        {
+            if (targetResource == nullptr)
+            {
+                throw RCSInvalidParameterException("RCSRemoteResoureObject value is null");
+            }
+
+            if (!clientCB)
+            {
+                throw RCSInvalidParameterException{ "addNewSceneAction : Callback is NULL" };
+            }
+
+            SceneCollectionResourceRequestor::InternalAddMemberCallback internalCB
+                = std::bind(&RemoteScene::onSceneActionAdded, this,
+                std::placeholders::_1, targetResource, attrs, std::move(clientCB));
+
+            m_requestor->requestAddSceneMember(
+                targetResource, m_name, attrs, internalCB);
+        }
+
+        void RemoteScene::addNewSceneAction(
+            RCSRemoteResourceObject::Ptr targetResource,
+            const std::string &key, const RCSResourceAttributes::Value &value,
+            AddNewSceneActionCallback clientCB)
+        {
+            RCSResourceAttributes attrs;
+            attrs[key] = RCSResourceAttributes::Value(value);
+
+            addNewSceneAction(targetResource, attrs, clientCB);
+        }
+
+        std::vector< RemoteSceneAction::Ptr > RemoteScene::getRemoteSceneActions() const
+        {
+            std::lock_guard< std::mutex > actionlock(m_sceneActionLock);
+            std::vector< RemoteSceneAction::Ptr > sceneActionList;
+
+            for (auto itrMap : m_remoteSceneActions)
+            {
+                sceneActionList.push_back(itrMap.second);
+            }
+
+            return sceneActionList;
+        }
+
+        RemoteSceneAction::Ptr RemoteScene::getRemoteSceneAction(
+            const RCSRemoteResourceObject::Ptr targetResource) const
+        {
+            if (targetResource == nullptr)
+            {
+                throw RCSInvalidParameterException("RCSRemoteResoureObject value is null");
+            }
+
+            std::lock_guard< std::mutex > actionlock(m_sceneActionLock);
+            auto itr = m_remoteSceneActions.find(
+                targetResource->getAddress() + targetResource->getUri());
+
+            if (itr == m_remoteSceneActions.end())
+            {
+                throw RCSInvalidParameterException("Invalid RCSRemoteResoureObject");
+            }
+
+            return itr->second;
+        }
+
+        std::string RemoteScene::getName() const
+        {
+            return m_name;
+        }
+
+        void RemoteScene::execute(RemoteSceneExecuteCallback clientCB)
+        {
+            if (!clientCB)
+            {
+                throw RCSInvalidParameterException{ "execute : Callback is NULL" };
+            }
+
+            SceneCollectionResourceRequestor::InternalSceneRequestCallback internalCB
+                = std::bind(&RemoteScene::onSceneExecuted, this, std::placeholders::_2,
+                            std::placeholders::_3, std::move(clientCB));
+
+            m_requestor->requestSceneExecution(m_name, internalCB);
+        }
+
+        RemoteSceneAction::Ptr RemoteScene::createRemoteSceneAction(
+            const std::string &targetHref, const RCSResourceAttributes &attrs)
+        {
+            SceneMemberResourceRequestor::Ptr memRequestor
+                = m_requestor->getSceneMemberResourceRequestor(targetHref);
+
+            if (memRequestor == nullptr)
+            {
+                return nullptr;
+            }
+
+            RemoteSceneAction::Ptr newAction(new RemoteSceneAction(memRequestor, m_name, attrs));
+
+            {
+                std::lock_guard< std::mutex > actionlock(m_sceneActionLock);
+                m_remoteSceneActions.insert(
+                    std::make_pair(targetHref, newAction));
+            }
+
+            return newAction;
+        }
+
+        void RemoteScene::addExistingRemoteSceneAction(
+            const std::string &href, const std::string &id, RCSRemoteResourceObject::Ptr target,
+            const std::string &key, const RCSResourceAttributes::Value &value)
+        {
+            std::string targetHref = target->getAddress() + target->getUri();
+
+            SceneMemberResourceRequestor::Ptr foundMemberRequestor
+                = m_requestor->getSceneMemberResourceRequestor(targetHref);
+
+            if (foundMemberRequestor == nullptr)
+                m_requestor->createSceneMemberResourceRequestor(href, id, target);
+
+            RCSResourceAttributes attrs;
+            attrs[key] = RCSResourceAttributes::Value(value);
+
+            createRemoteSceneAction(targetHref, attrs);
+        }
+
+        void RemoteScene::onSceneActionAdded(
+            int eCode, RCSRemoteResourceObject::Ptr target, const RCSResourceAttributes &attrs,
+            const AddNewSceneActionCallback &clientCB)
+        {
+            int result = SCENE_CLIENT_BADREQUEST;
+            RemoteSceneAction::Ptr newAction = nullptr;
+
+            if (eCode == SCENE_RESPONSE_SUCCESS)
+            {
+                std::string targetLink = target->getAddress() + target->getUri();
+
+                newAction = createRemoteSceneAction(targetLink, attrs);
+
+                if (newAction)
+                    result = SCENE_RESPONSE_SUCCESS;
+            }
+
+            clientCB(newAction, result);
+        }
+
+        void RemoteScene::onSceneExecuted(const std::string &sceneName, const int eCode,
+            const RemoteSceneExecuteCallback &clientCB)
+        {
+            clientCB(sceneName, eCode);
+        }
+
+    }
+}
\ No newline at end of file
diff --git a/service/scene-manager/src/RemoteSceneAction.cpp b/service/scene-manager/src/RemoteSceneAction.cpp
new file mode 100644 (file)
index 0000000..314ad16
--- /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 "RemoteSceneAction.h"
+
+#include <cassert>
+
+#include "SceneCommons.h"
+#include "SceneMemberResourceRequestor.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+
+        RemoteSceneAction::RemoteSceneAction(
+            SceneMemberResourceRequestor::Ptr requestor,
+            const std::string &sceneName, const RCSResourceAttributes &attrs)
+                : m_sceneName{ sceneName }, m_attributes{ attrs }, m_requestor{ requestor }
+        {
+            assert(requestor);
+        }
+
+        RemoteSceneAction::RemoteSceneAction(
+            SceneMemberResourceRequestor::Ptr requestor, const std::string &sceneName,
+            const std::string &key, const RCSResourceAttributes::Value &value)
+                : m_sceneName{ sceneName }, m_requestor{ requestor }
+        {
+            assert(requestor);
+            m_attributes[key] = value;
+        }
+
+        void RemoteSceneAction::resetExecutionParameter(const std::string &key,
+                                       const RCSResourceAttributes::Value &value,
+                                       ResetExecutionParameterCallback clientCB)
+        {
+            RCSResourceAttributes attr;
+            attr[key] = RCSResourceAttributes::Value(value);
+
+            resetExecutionParameter(attr, std::move(clientCB));
+        }
+
+        void RemoteSceneAction::resetExecutionParameter(const RCSResourceAttributes &attr,
+            ResetExecutionParameterCallback clientCB)
+        {
+            if (!clientCB)
+            {
+                throw RCSInvalidParameterException{ "resetExecutionParameter : Callback is NULL" };
+            }
+
+            SceneMemberResourceRequestor::InternalAddSceneActionCallback internalCB
+                = std::bind(&RemoteSceneAction::onExecutionParameterSet, this,
+                std::placeholders::_1, attr, std::move(clientCB));
+
+            m_requestor->requestSceneActionCreation(
+                m_sceneName, attr, internalCB);
+        }
+
+        RCSResourceAttributes RemoteSceneAction::getExecutionParameter() const
+        {
+            std::lock_guard< std::mutex > lock(m_attributeLock);
+            return m_attributes;
+        }
+
+        RCSRemoteResourceObject::Ptr RemoteSceneAction::getRemoteResourceObject() const
+        {
+            return m_requestor->getRemoteResourceObject();
+        }
+
+        void RemoteSceneAction::onExecutionParameterSet(int eCode, const RCSResourceAttributes &attr,
+            const ResetExecutionParameterCallback &clientCB)
+        {
+            int result = SCENE_CLIENT_BADREQUEST;
+            if (eCode == SCENE_RESPONSE_SUCCESS)
+            {
+                std::lock_guard< std::mutex > lock(m_attributeLock);
+                m_attributes = attr;
+                result = SCENE_RESPONSE_SUCCESS;
+            }
+
+            clientCB(result);
+        }
+    }
+}
diff --git a/service/scene-manager/src/RemoteSceneCollection.cpp b/service/scene-manager/src/RemoteSceneCollection.cpp
new file mode 100644 (file)
index 0000000..f0ffd05
--- /dev/null
@@ -0,0 +1,212 @@
+//******************************************************************
+//
+// 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 "RemoteSceneCollection.h"
+
+#include <cassert>
+
+#include "SceneCommons.h"
+#include "RemoteSceneUtils.h"
+#include "SceneCollectionResourceRequestor.h"
+#include "OCPlatform.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+
+        RemoteSceneCollection::RemoteSceneCollection(
+            std::shared_ptr< SceneCollectionResourceRequestor > requestor,
+            const std::string &id, const std::string &name)
+            : m_id{ id }, m_name{ name }, m_requestor{ requestor }
+        {
+            assert(requestor);
+        }
+
+        void RemoteSceneCollection::addNewScene
+        (const std::string &name, AddNewSceneCallback clientCB)
+        {
+            if (name.empty())
+            {
+                throw RCSInvalidParameterException("Scene name is an empty string");
+            }
+            if (!clientCB)
+            {
+                throw RCSInvalidParameterException{ "addNewScene : Callback is NULL" };
+            }
+
+            SceneCollectionResourceRequestor::InternalSceneRequestCallback internalCB
+                = std::bind(&RemoteSceneCollection::onSceneAddedRemoved, this,
+                            std::placeholders::_1, std::placeholders::_2,
+                            std::placeholders::_3, std::move(clientCB));
+
+            m_requestor->requestSceneCreation(name, internalCB);
+        }
+
+        std::unordered_map< std::string, RemoteScene::Ptr >
+            RemoteSceneCollection::getRemoteScenes() const
+        {
+            std::lock_guard< std::mutex > scenelock(m_sceneLock);
+            return m_remoteScenes;
+        }
+
+        RemoteScene::Ptr RemoteSceneCollection::getRemoteScene(const std::string &sceneName) const
+        {
+            std::lock_guard< std::mutex > scenelock(m_sceneLock);
+            auto itr = m_remoteScenes.find(sceneName);
+
+            if (itr == m_remoteScenes.end())
+            {
+                throw RCSInvalidParameterException("Invalid scene name");
+            }
+
+            return  itr->second;
+        }
+
+        void RemoteSceneCollection::setName(const std::string &name, SetNameCallback clientCB)
+        {
+            if (!clientCB)
+            {
+                throw RCSInvalidParameterException{ "setName : Callback is NULL" };
+            }
+
+            SceneCollectionResourceRequestor::InternalSetNameCallback internalCB
+                = std::bind(&RemoteSceneCollection::onNameSet, this,
+                            std::placeholders::_1, name, std::move(clientCB));
+
+            m_requestor->requestSetName(name, internalCB);
+        }
+
+        std::string RemoteSceneCollection::getName() const
+        {
+            std::lock_guard< std::mutex > lock(m_nameLock);
+            return m_name;
+        }
+
+        std::string RemoteSceneCollection::getId() const
+        {
+            return m_id;
+        }
+
+        void RemoteSceneCollection::addExistingRemoteScenes(const std::vector< std::string > &scenes)
+        {
+            for (const auto &scenename : scenes)
+            {
+                createRemoteScene(scenename);
+            }
+        }
+
+        void RemoteSceneCollection::initializeRemoteScenes(
+            const std::vector< RCSResourceAttributes > &MemberReps, const std::string &host)
+        {
+            try
+            {
+                for (const auto &attrs : MemberReps)
+                {
+                    for (const auto &mappingInfo :
+                            attrs.at(SCENE_KEY_SCENEMAPPINGS).get
+                                <std::vector< RCSResourceAttributes > >())
+                    {
+                        std::string sceneName
+                            = mappingInfo.at(SCENE_KEY_SCENE).get< std::string >();
+
+                        auto remoteScene = m_remoteScenes.find(sceneName);
+                        if (remoteScene == m_remoteScenes.end()) continue;
+
+                        RemoteScene::Ptr pRemoteScene = m_remoteScenes.at(sceneName);
+
+                        RCSResourceAttributes targetLinkAttrs
+                            = attrs.at(SCENE_KEY_PAYLOAD_LINK).get< RCSResourceAttributes >();
+
+                        RCSRemoteResourceObject::Ptr targetResource
+                            = SceneUtils::createRCSResourceObject(
+                            targetLinkAttrs.at(SCENE_KEY_HREF).get< std::string >(),
+                            SCENE_CONNECTIVITY,
+                            targetLinkAttrs.at(SCENE_KEY_RT).get< std::vector< std::string > >(),
+                            targetLinkAttrs.at(SCENE_KEY_IF).get< std::vector< std::string > >());
+
+                        std::string mappingInfoKey
+                            = mappingInfo.at(SCENE_KEY_MEMBERPROPERTY).get< std::string >();
+                        RCSResourceAttributes::Value mappingInfoValue
+                            = mappingInfo.at(SCENE_KEY_MEMBERVALUE);
+
+                        pRemoteScene->addExistingRemoteSceneAction(
+                            host + attrs.at(SCENE_KEY_URI).get< std::string >(),
+                            attrs.at(SCENE_KEY_ID).get< std::string >(), targetResource,
+                            mappingInfoKey, mappingInfoValue);
+                    }
+                }
+            }
+            catch (const std::exception &e)
+            {
+                SCENE_CLIENT_PRINT_LOG(e.what());
+            }
+        }
+
+        RemoteScene::Ptr RemoteSceneCollection::createRemoteScene(const std::string &name)
+        {
+            std::lock_guard< std::mutex > scenelock(m_sceneLock);
+            RemoteScene::Ptr pNewRemoteScene(new RemoteScene(name, m_requestor));
+
+            m_remoteScenes[name] = pNewRemoteScene;
+
+            return pNewRemoteScene;
+        }
+
+        void RemoteSceneCollection::onSceneAddedRemoved(int reqType,
+            const std::string &name, int eCode,
+            const AddNewSceneCallback &addCB)
+        {
+            switch (reqType)
+            {
+                case SceneCollectionResourceRequestor::REQUEST_TYPE::ADD_SCENE:
+                {
+                    if (eCode == SCENE_RESPONSE_SUCCESS)
+                    {
+                        addCB(createRemoteScene(name), SCENE_RESPONSE_SUCCESS);
+                    }
+                    else
+                    {
+                        addCB(nullptr, SCENE_CLIENT_BADREQUEST);
+                    }
+                }
+                    break;
+
+                case SceneCollectionResourceRequestor::REQUEST_TYPE::REMOVE_SCENE:
+                    break;
+            }
+        }
+
+        void RemoteSceneCollection::onNameSet(int eCode, const std::string &name,
+                                              const SetNameCallback &clientCB)
+        {
+            int result = SCENE_CLIENT_BADREQUEST;
+            if (eCode == SCENE_RESPONSE_SUCCESS)
+            {
+                std::lock_guard< std::mutex > lock(m_nameLock);
+                m_name = name;
+                result = SCENE_RESPONSE_SUCCESS;
+            }
+
+            clientCB(result);
+        }
+
+    }
+}
\ No newline at end of file
diff --git a/service/scene-manager/src/RemoteSceneList.cpp b/service/scene-manager/src/RemoteSceneList.cpp
new file mode 100644 (file)
index 0000000..ac2ad2c
--- /dev/null
@@ -0,0 +1,279 @@
+//******************************************************************
+//
+// 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 "RemoteSceneList.h"
+
+#include <map>
+#include <algorithm>
+
+#include "SceneCommons.h"
+#include "RemoteSceneUtils.h"
+#include "SceneListResourceRequestor.h"
+#include "SceneCollectionResourceRequestor.h"
+#include "OCPlatform.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+
+        RemoteSceneList::RemoteSceneList(SceneListResourceRequestor::Ptr requestor)
+            : m_requestor{ requestor }
+        {
+
+        }
+
+        void RemoteSceneList::createInstance(RCSRemoteResourceObject::Ptr sceneListResource,
+                                             CreateInstanceCallback clientCB)
+        {
+            if (!clientCB)
+            {
+                throw RCSInvalidParameterException{ "createInstance : Callback is NULL" };
+            }
+
+            if (sceneListResource == nullptr)
+            {
+                throw RCSInvalidParameterException("Scene List resource object is null");
+            }
+
+            std::vector< std::string > rts = sceneListResource->getTypes();
+            auto it = std::find(rts.begin(), rts.end(), SCENE_LIST_RT);
+            if (it == rts.end())
+            {
+                throw RCSInvalidParameterException(
+                    "Remote resource object is not a Scene List Resource");
+            }
+
+            SceneListResourceRequestor::Ptr pRequestor =
+                std::make_shared< SceneListResourceRequestor >(sceneListResource);
+
+            std::string requestIf = SCENE_CLIENT_REQ_IF;
+            pRequestor->requestGet(requestIf, std::bind(
+                &RemoteSceneList::onInstanceCreated,
+                std::placeholders::_2, std::placeholders::_3, requestIf,
+                pRequestor, std::move(clientCB)));
+        }
+
+        void RemoteSceneList::addNewSceneCollection(AddNewSceneCollectionCallback clientCB)
+        {
+            if (!clientCB)
+            {
+                throw RCSInvalidParameterException{ "addNewSceneCollection : Callback is NULL" };
+            }
+
+            SceneListResourceRequestor::InternalCreateSceneCollectionCallback internalCB
+                = std::bind(&RemoteSceneList::onSceneCollectionCreated, this,
+                std::placeholders::_1, std::placeholders::_2, std::placeholders::_3,
+                std::placeholders::_4, std::move(clientCB));
+
+            m_requestor->requestSceneCollectionCreation("", internalCB);
+        }
+
+        std::vector< RemoteSceneCollection::Ptr >
+            RemoteSceneList::getRemoteSceneCollections() const
+        {
+            std::lock_guard< std::mutex > collectionlock(m_collectionLock);
+            return m_remoteSceneCollections;
+        }
+
+        void RemoteSceneList::setName(const std::string &name, SetNameCallback clientCB)
+        {
+            if (!clientCB)
+            {
+                throw RCSInvalidParameterException{ "setName : Callback is NULL" };
+            }
+
+            SceneListResourceRequestor::InternalSetNameCallback internalCB
+                = std::bind(&RemoteSceneList::onNameSet, this,
+                std::placeholders::_1, name, std::move(clientCB));
+
+            m_requestor->requestSetName(name, internalCB);
+        }
+
+        std::string RemoteSceneList::getName() const
+        {
+            std::lock_guard< std::mutex > lock(m_nameLock);
+            return m_name;
+        }
+
+        void RemoteSceneList::onInstanceCreated(
+            const RCSRepresentation &rep, int eCode, const std::string &If,
+            SceneListResourceRequestor::Ptr requestor, const CreateInstanceCallback &cb)
+        {
+            if (eCode == OC_STACK_OK)
+            {
+                if (If == OC::DEFAULT_INTERFACE)
+                {
+                    auto retPtr = buildSceneList(requestor, rep.getAttributes());
+                    cb(std::move(retPtr), SCENE_RESPONSE_SUCCESS);
+                }
+                else if (If == OC::BATCH_INTERFACE)
+                {
+                    // TODO build remote scene list instance with batch interface.
+                }
+                else
+                {
+                    // TODO error handle.
+                }
+            }
+        }
+
+        RemoteSceneList::Ptr RemoteSceneList::buildSceneList(
+            SceneListResourceRequestor::Ptr requestor, const RCSResourceAttributes &attrs)
+        {
+            RemoteSceneList::Ptr newList(new RemoteSceneList(requestor));
+            auto collections = newList->parseSceneListFromAttributes(attrs);
+
+            try
+            {
+                newList->m_name = attrs.at(SCENE_KEY_NAME).get< std::string >();
+
+                for (const auto &itr : collections)
+                {
+                    auto collection = itr.first;
+                    auto host = newList->getListResourceRequestor()
+                                    ->getRemoteResourceObject()->getAddress();
+
+                    RemoteSceneCollection::Ptr newCollection
+                        = newList->createRemoteSceneCollection(
+                                    host + collection.at(SCENE_KEY_URI).get< std::string >(),
+                                    collection.at(SCENE_KEY_ID).get< std::string >(),
+                                    collection.at(SCENE_KEY_NAME).get< std::string >());
+
+                    newCollection->addExistingRemoteScenes(
+                        collection.at(SCENE_KEY_SCENEVALUES).get< std::vector< std::string > >());
+
+                    newCollection->initializeRemoteScenes(itr.second, host);
+                }
+            }
+            catch (const std::exception &e)
+            {
+                SCENE_CLIENT_PRINT_LOG(e.what());
+            }
+
+            return std::move(newList);
+        }
+
+        RemoteSceneCollection::Ptr RemoteSceneList::createRemoteSceneCollection(
+            const std::string &link, const std::string &id, const std::string &name)
+        {
+            try
+            {
+                std::vector< std::string > vecRT{ SCENE_COLLECTION_RT };
+                std::vector< std::string > vecIF{ SCENE_CLIENT_REQ_IF };
+
+                RCSRemoteResourceObject::Ptr pResource
+                    = SceneUtils::createRCSResourceObject(link, SCENE_CONNECTIVITY, vecRT, vecIF);
+
+                SceneCollectionResourceRequestor::Ptr pRequestor(
+                    new SceneCollectionResourceRequestor(pResource));
+
+                RemoteSceneCollection::Ptr newCollection(
+                    new RemoteSceneCollection(pRequestor, id, name));
+
+                {
+                    std::lock_guard< std::mutex > collectionlock(m_collectionLock);
+                    m_remoteSceneCollections.push_back(newCollection);
+                }
+
+                return newCollection;
+            }
+            catch (const std::exception &e)
+            {
+                SCENE_CLIENT_PRINT_LOG(e.what());
+                return nullptr;
+            }
+        }
+
+        SceneListResourceRequestor::Ptr RemoteSceneList::getListResourceRequestor() const
+        {
+            return m_requestor;
+        }
+
+        std::vector<std::pair<RCSResourceAttributes, std::vector<RCSResourceAttributes>>>
+            RemoteSceneList::parseSceneListFromAttributes(const RCSResourceAttributes & listAttrs)
+        {
+            std::vector<std::pair<RCSResourceAttributes, std::vector<RCSResourceAttributes>>>
+                retParsed;
+
+            auto collectionsResourceAttrs = getChildrenAttributes(listAttrs);
+
+            for (unsigned int i = 0; i < collectionsResourceAttrs.size(); ++i)
+            {
+                retParsed.push_back(
+                    std::make_pair(
+                        collectionsResourceAttrs[i],
+                        getChildrenAttributes(collectionsResourceAttrs[i])));
+            }
+
+            return retParsed;
+        }
+
+        std::vector<RCSResourceAttributes> RemoteSceneList::getChildrenAttributes(
+            const RCSResourceAttributes & attrs) const
+        {
+            const std::string SCENE_CHILD = "child";
+
+            std::vector<RCSResourceAttributes> retChildren = {};
+
+            if (attrs.contains(SCENE_CHILD))
+            {
+                retChildren
+                    = attrs.at(SCENE_CHILD).get<std::vector<RCSResourceAttributes>>();
+            }
+
+            return retChildren;
+        }
+
+        void RemoteSceneList::onSceneCollectionCreated(
+            const std::string &link, const std::string &id, const std::string &name, int eCode,
+            const AddNewSceneCollectionCallback &clientCB)
+        {
+            int result = SCENE_CLIENT_BADREQUEST;
+            RemoteSceneCollection::Ptr newCollection = nullptr;
+
+            if (eCode == SCENE_RESPONSE_SUCCESS)
+            {
+                newCollection =
+                    createRemoteSceneCollection(link, id, name);
+
+                if (newCollection)
+                    result = SCENE_RESPONSE_SUCCESS;
+            }
+
+            clientCB(newCollection, result);
+        }
+
+        void RemoteSceneList::onNameSet(int eCode, const std::string &name,
+            const SetNameCallback &clientCB)
+        {
+            int result = SCENE_CLIENT_BADREQUEST;
+            if (eCode == SCENE_RESPONSE_SUCCESS)
+            {
+                std::lock_guard< std::mutex > lock(m_nameLock);
+                m_name = name;
+                result = SCENE_RESPONSE_SUCCESS;
+            }
+
+            clientCB(result);
+        }
+
+    }
+}
\ No newline at end of file
diff --git a/service/scene-manager/src/RemoteSceneUtils.h b/service/scene-manager/src/RemoteSceneUtils.h
new file mode 100644 (file)
index 0000000..b85e696
--- /dev/null
@@ -0,0 +1,41 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef REMOTE_SCENE_UTILS_H
+#define REMOTE_SCENE_UTILS_H
+
+#include <cassert>
+
+#include "logger.h"
+
+#define SCENE_CLIENT_PRINT_LOG(strError) \
+        OIC_LOG_V(ERROR, "[SCENE_CLIENT]", "%s:%d %s", __PRETTY_FUNCTION__, __LINE__, strError);
+
+#define SCENE_CLIENT_ASSERT_NOT_NULL(Val) \
+        { \
+            if (!(Val)) \
+            { \
+                SCENE_CLIENT_PRINT_LOG("NULL value"); \
+                assert(Val); \
+                return; \
+            } \
+        }
+
+#endif // REMOTE_SCENE_UTILS_H
\ No newline at end of file
diff --git a/service/scene-manager/src/Scene.cpp b/service/scene-manager/src/Scene.cpp
new file mode 100755 (executable)
index 0000000..ec364cd
--- /dev/null
@@ -0,0 +1,153 @@
+//******************************************************************
+//
+// 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 "Scene.h"
+
+#include "SceneCollectionResource.h"
+
+#include <algorithm>
+
+namespace OIC
+{
+    namespace Service
+    {
+        Scene::Scene(const std::string& sceneName,
+                SceneCollectionResource::Ptr sceneCollectionResource) :
+                m_name(sceneName), m_sceneCollectionResource(sceneCollectionResource) {}
+
+        SceneAction::Ptr Scene::addNewSceneAction(
+               const RCSRemoteResourceObject::Ptr& pRCSRemoteResourceObject,
+               std::string key, RCSResourceAttributes::Value value)
+        {
+            RCSResourceAttributes resAttr;
+            resAttr[key] = value;
+            return addNewSceneAction(pRCSRemoteResourceObject, std::move(resAttr));
+        }
+
+        SceneAction::Ptr Scene::addNewSceneAction(
+                const RCSRemoteResourceObject::Ptr& pRCSRemoteResourceObject,
+                RCSResourceAttributes attr)
+        {
+            if(pRCSRemoteResourceObject == nullptr)
+            {
+                throw RCSInvalidParameterException("pRCSRemoteResourceObject is empty!");
+            }
+
+            SceneMemberResource::Ptr sceneMemberResObj;
+            sceneMemberResObj = SceneMemberResource::createSceneMemberResource(
+                    pRCSRemoteResourceObject);
+            try
+            {
+                m_sceneCollectionResource->addSceneMember(sceneMemberResObj);
+            }
+            catch(RCSBadRequestException& e)
+            {
+                auto sceneMemberRes = m_sceneCollectionResource->findSceneMembers(m_name);
+
+                auto it = std::find_if(sceneMemberRes.begin(), sceneMemberRes.end(),
+                        [&pRCSRemoteResourceObject](const SceneMemberResource::Ptr& member)
+                        {
+                            return member->getRemoteResourceObject() == pRCSRemoteResourceObject;
+                        }
+                );
+
+                if(it != sceneMemberRes.end())
+                {
+                    throw RCSBadRequestException(
+                            "It is already registered member. Please set Execution Parameter!");
+                }
+
+                auto sceneMembers = m_sceneCollectionResource->getSceneMembers();
+                auto memberRes = std::find_if(sceneMembers.begin(), sceneMembers.end(),
+                        [&pRCSRemoteResourceObject](const SceneMemberResource::Ptr& member)
+                        {
+                            return member->getRemoteResourceObject() == pRCSRemoteResourceObject;
+                        }
+                );
+                return SceneAction::Ptr(new SceneAction((*memberRes), m_name, attr));
+            }
+
+            return SceneAction::Ptr(new SceneAction(sceneMemberResObj, m_name, attr));
+        }
+
+        SceneAction::Ptr Scene::getSceneAction(
+                const RCSRemoteResourceObject::Ptr& pRCSRemoteResourceObject) const
+        {
+            auto sceneMemberRes = m_sceneCollectionResource->findSceneMembers(m_name);
+
+            auto it = std::find_if(sceneMemberRes.begin(), sceneMemberRes.end(),
+                    [&pRCSRemoteResourceObject](const SceneMemberResource::Ptr& member)
+                    {
+                        return member->getRemoteResourceObject() == pRCSRemoteResourceObject;
+                    }
+            );
+
+            if(it == sceneMemberRes.end())
+            {
+                throw RCSInvalidParameterException("Unknown Remote Resource!");
+            }
+
+            RCSResourceAttributes actionParam;
+            for(const auto &info : (*it)->findMappingInfos(m_name))
+            {
+                actionParam[info.key] = info.value;
+            }
+
+            return SceneAction::Ptr(new SceneAction((*it), m_name, actionParam));
+        }
+
+        std::vector<SceneAction::Ptr> Scene::getSceneActions() const
+        {
+            std::vector<SceneAction::Ptr> actions;
+            auto sceneMemberRes = m_sceneCollectionResource->findSceneMembers(m_name);
+
+            std::for_each(sceneMemberRes.begin(), sceneMemberRes.end(),
+                [&](const SceneMemberResource::Ptr& member)
+                {
+                    RCSResourceAttributes actionParam;
+
+                    for(const auto &it : member->findMappingInfos(m_name))
+                    {
+                        actionParam[it.key] = it.value;
+                    }
+                    actions.push_back(SceneAction::Ptr(
+                            new SceneAction(member, m_name, actionParam)));
+                }
+            );
+
+            return actions;
+         }
+
+        std::string Scene::getName() const
+        {
+            return m_name;
+        }
+
+        void Scene::execute(ExecuteCallback cb)
+        {
+            if(cb == nullptr)
+            {
+                throw RCSInvalidParameterException("Callback is empty!");
+            }
+
+            m_sceneCollectionResource->execute(m_name, std::move(cb));
+        }
+    } /* namespace Service */
+} /* namespace OIC */
diff --git a/service/scene-manager/src/SceneAction.cpp b/service/scene-manager/src/SceneAction.cpp
new file mode 100755 (executable)
index 0000000..79e5f00
--- /dev/null
@@ -0,0 +1,89 @@
+//******************************************************************
+//
+// 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 "SceneAction.h"
+
+#include "SceneMemberResource.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+        SceneAction::SceneAction(const SceneMemberResource::Ptr SceneMemberResource,
+                const std::string& sceneName, const RCSResourceAttributes& attr) :
+                m_pRemoteResourceObject(SceneMemberResource->getRemoteResourceObject()),
+                m_sceneName(sceneName),
+                m_sceneMemberResource(SceneMemberResource)
+        {
+            for (const auto& it : attr)
+            {
+                m_sceneMemberResource->addMappingInfo(
+                        SceneMemberResource::MappingInfo(m_sceneName, it.key(), it.value()));
+            }
+        }
+
+        SceneAction::SceneAction(const SceneMemberResource::Ptr SceneMemberResource,
+                const std::string& sceneName, const std::string& key,
+                const RCSResourceAttributes::Value& value) :
+                m_pRemoteResourceObject(SceneMemberResource->getRemoteResourceObject()),
+                m_sceneName(sceneName), m_sceneMemberResource(SceneMemberResource)
+        {
+            m_sceneMemberResource->addMappingInfo(
+                                SceneMemberResource::MappingInfo(m_sceneName, key, value));
+        }
+
+        void SceneAction::resetExecutionParameter(const std::string& key,
+                RCSResourceAttributes::Value value)
+        {
+            RCSResourceAttributes attr;
+            attr[key] = value;
+            resetExecutionParameter(attr);
+        }
+
+        void SceneAction::resetExecutionParameter(const RCSResourceAttributes& attr)
+        {
+            for(const auto& it : attr)
+            {
+                m_sceneMemberResource->addMappingInfo(
+                        SceneMemberResource::MappingInfo(m_sceneName, it.key(), it.value()));
+            }
+        }
+
+        RCSResourceAttributes SceneAction::getExecutionParameter() const
+        {
+            RCSResourceAttributes attr;
+            for(const auto& it : m_sceneMemberResource->getMappingInfos())
+            {
+                if(it.sceneName == m_sceneName)
+                {
+                    attr[it.key] = RCSResourceAttributes::Value(it.value);
+                }
+            }
+            return attr;
+        }
+
+        RCSRemoteResourceObject::Ptr SceneAction::getRemoteResourceObject() const
+        {
+            return m_pRemoteResourceObject;
+        }
+
+    } /* namespace Service */
+} /* namespace OIC */
+
diff --git a/service/scene-manager/src/SceneCollection.cpp b/service/scene-manager/src/SceneCollection.cpp
new file mode 100755 (executable)
index 0000000..789c79b
--- /dev/null
@@ -0,0 +1,85 @@
+//******************************************************************
+//
+// 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 "SceneCollection.h"
+
+#include "SceneCollectionResource.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+        SceneCollection::SceneCollection(
+                const SceneCollectionResource::Ptr& sceneCollectionResource) :
+                m_sceneCollectionResource(sceneCollectionResource) {}
+
+        Scene::Ptr SceneCollection::addNewScene(const std::string& sceneName)
+        {
+            if(sceneName.empty())
+            {
+                throw RCSInvalidParameterException("Scene name is an empty string");
+            }
+
+            m_sceneCollectionResource->addScene(sceneName);
+
+            return Scene::Ptr(new Scene(sceneName, m_sceneCollectionResource));
+        }
+
+        std::unordered_map< std::string, Scene::Ptr > SceneCollection::getScenes() const
+        {
+            std::unordered_map< std::string, Scene::Ptr > scenes;
+
+            for(const auto &it : m_sceneCollectionResource->getSceneValues())
+            {
+                Scene::Ptr scenePtr(new Scene(it, m_sceneCollectionResource));
+                scenes.insert(std::pair< std::string, Scene::Ptr >(it, scenePtr));
+            }
+            return scenes;
+        }
+
+        Scene::Ptr SceneCollection::getScene(const std::string& sceneName) const
+        {
+            auto sceneValues = m_sceneCollectionResource->getSceneValues();
+            auto it = std::find(sceneValues.begin(), sceneValues.end(), sceneName);
+            if(it == sceneValues.end())
+            {
+                throw RCSInvalidParameterException("Scene Name is Invalid!");
+            }
+            return Scene::Ptr(new Scene(sceneName, m_sceneCollectionResource));
+        }
+
+        void SceneCollection::setName(const std::string& name)
+        {
+            m_sceneCollectionResource->setName(name);
+        }
+
+        std::string SceneCollection::getName() const
+        {
+            return m_sceneCollectionResource->getName();
+        }
+
+        std::string SceneCollection::getId() const
+        {
+            return m_sceneCollectionResource->getId();
+        }
+
+    } /* namespace Service */
+} /* namespace OIC */
+
diff --git a/service/scene-manager/src/SceneCollectionResource.cpp b/service/scene-manager/src/SceneCollectionResource.cpp
new file mode 100755 (executable)
index 0000000..6467ec9
--- /dev/null
@@ -0,0 +1,468 @@
+//******************************************************************
+//
+// 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 "SceneCollectionResource.h"
+
+#include <atomic>
+#include "OCApi.h"
+#include "RCSRequest.h"
+#include "RCSSeparateResponse.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+        namespace
+        {
+            std::atomic_int g_numOfSceneCollection(0);
+        }
+
+        SceneCollectionResource::SceneCollectionResource()
+        : m_uri(PREFIX_SCENE_COLLECTION_URI + "/" + std::to_string(g_numOfSceneCollection++)),
+          m_address(), m_sceneCollectionResourceObject(), m_requestHandler()
+        {
+            m_sceneCollectionResourceObject = createResourceObject();
+        }
+
+        SceneCollectionResource::Ptr SceneCollectionResource::create()
+        {
+            SceneCollectionResource::Ptr sceneCollectionResource(new SceneCollectionResource());
+
+            sceneCollectionResource->setDefaultAttributes();
+
+            sceneCollectionResource->initSetRequestHandler();
+
+            sceneCollectionResource->m_address = SceneUtils::getNetAddress();
+
+            return sceneCollectionResource;
+        }
+
+        SceneCollectionResource::Ptr SceneCollectionResource::create(
+                const RCSResourceAttributes & inputAttr)
+        {
+            auto sceneCollectionResource = SceneCollectionResource::create();
+            if (inputAttr.contains(SCENE_KEY_NAME))
+            {
+                sceneCollectionResource->setName(inputAttr.at(SCENE_KEY_NAME).get<std::string>());
+            }
+
+            if (inputAttr.contains(SCENE_KEY_SCENEVALUES))
+            {
+                auto sceneValues = inputAttr.at(SCENE_KEY_SCENEVALUES).
+                        get<std::vector<std::string>>();
+                sceneCollectionResource->getRCSResourceObject()->setAttribute(
+                        SCENE_KEY_SCENEVALUES, sceneValues);
+            }
+
+            if (inputAttr.contains(SCENE_KEY_LAST_SCENE))
+            {
+                auto sceneValues = inputAttr.at(SCENE_KEY_LAST_SCENE).get<std::string>();
+                sceneCollectionResource->getRCSResourceObject()->setAttribute(
+                        SCENE_KEY_LAST_SCENE, sceneValues);
+            }
+
+            return sceneCollectionResource;
+        }
+
+        RCSResourceObject::Ptr SceneCollectionResource::createResourceObject()
+        {
+            return RCSResourceObject::Builder(
+                        m_uri, SCENE_COLLECTION_RT, BASELINE_IF).
+                        addInterface(OC::BATCH_INTERFACE).
+                        addInterface(LINK_BATCH).
+                        setDiscoverable(true).setObservable(false).build();
+        }
+
+        void SceneCollectionResource::setDefaultAttributes()
+        {
+            m_sceneCollectionResourceObject->setAttribute(SCENE_KEY_LAST_SCENE, std::string());
+            m_sceneCollectionResourceObject->setAttribute(SCENE_KEY_NAME, std::string());
+            m_sceneCollectionResourceObject->setAttribute(
+                    SCENE_KEY_ID, SceneUtils::OICGenerateUUIDStr());
+            m_sceneCollectionResourceObject->setAttribute(SCENE_KEY_RTS, SCENE_MEMBER_RT);
+            m_sceneCollectionResourceObject->setAttribute(
+                    SCENE_KEY_SCENEVALUES, std::vector<std::string>());
+            m_sceneCollectionResourceObject->setAttribute(SCENE_KEY_URI, m_uri);
+        }
+
+        void SceneCollectionResource::initSetRequestHandler()
+        {
+            m_requestHandler.m_owner
+                = std::weak_ptr<SceneCollectionResource>(shared_from_this());
+
+            m_sceneCollectionResourceObject->setSetRequestHandler(std::bind(
+                    &SceneCollectionResource::SceneCollectionRequestHandler::onSetRequest,
+                    m_requestHandler, std::placeholders::_1, std::placeholders::_2));
+        }
+
+        void SceneCollectionResource::addScene(const std::string & newScene)
+        {
+            addScene(std::string(newScene));
+        }
+
+        void SceneCollectionResource::addScene(std::string && newScene)
+        {
+            auto sceneValues = m_sceneCollectionResourceObject->getAttributeValue(
+                    SCENE_KEY_SCENEVALUES).get< std::vector< std::string > >();
+
+            auto foundScene
+                = std::find(sceneValues.begin(), sceneValues.end(), newScene);
+            if (foundScene == sceneValues.end())
+            {
+                sceneValues.push_back(std::move(newScene));
+
+                m_sceneCollectionResourceObject->setAttribute(SCENE_KEY_SCENEVALUES, sceneValues);
+            }
+            else
+            {
+                throw RCSInvalidParameterException("Scene name is duplicate!");
+            }
+        }
+
+        void SceneCollectionResource::addSceneMember(
+                SceneMemberResource::Ptr newMember)
+        {
+            std::lock_guard<std::mutex> memberlock(m_sceneMemberLock);
+
+            auto foundmember = std::find_if(m_sceneMembers.begin(), m_sceneMembers.end(),
+                    [& newMember](const SceneMemberResource::Ptr & ptr) -> bool
+                    {
+                        return ptr->getTargetUri() == newMember->getTargetUri();
+                    });
+
+            if (foundmember != m_sceneMembers.end())
+            {
+                throw RCSBadRequestException("It is already registered member.");
+            }
+
+            m_sceneMembers.push_back(newMember);
+            m_sceneCollectionResourceObject->bindResource(newMember->getRCSResourceObject());
+        }
+
+        void SceneCollectionResource::execute(std::string && sceneName)
+        {
+            execute(std::move(sceneName), nullptr);
+        }
+
+        void SceneCollectionResource::execute(const std::string & sceneName)
+        {
+            execute(std::string(sceneName));
+        }
+
+        void SceneCollectionResource::execute(
+                const std::string & sceneName, SceneExecuteCallback executeCB)
+        {
+            execute(std::string(sceneName), std::move(executeCB));
+        }
+
+        void SceneCollectionResource::execute(
+                std::string && sceneName, SceneExecuteCallback executeCB)
+        {
+            auto sceneValues = m_sceneCollectionResourceObject->getAttributeValue(
+                    SCENE_KEY_SCENEVALUES).get< std::vector< std::string > >();
+
+            auto foundSceneValue
+                = std::find(sceneValues.begin(), sceneValues.end(), sceneName);
+            if (foundSceneValue == sceneValues.end() && executeCB && !m_sceneMembers.size())
+            {
+                std::thread(std::move(executeCB), SCENE_CLIENT_BADREQUEST).detach();
+                return;
+            }
+
+            m_sceneCollectionResourceObject->setAttribute(
+                    SCENE_KEY_LAST_SCENE, sceneName);
+
+            {
+                std::lock_guard<std::mutex> memberlock(m_sceneMemberLock);
+                auto executeHandler
+                    = SceneExecuteResponseHandler::createExecuteHandler(
+                            shared_from_this(), std::move(executeCB));
+                for (auto & it : m_sceneMembers)
+                {
+                    it->execute(std::move(sceneName), std::bind(
+                            &SceneExecuteResponseHandler::onResponse, executeHandler,
+                            std::placeholders::_1, std::placeholders::_2));
+                }
+            }
+        }
+
+        std::string SceneCollectionResource::getId() const
+        {
+            return m_sceneCollectionResourceObject->getAttributeValue(
+                    SCENE_KEY_ID).get<std::string>();
+        }
+
+        std::string SceneCollectionResource::getUri() const
+        {
+            return m_uri;
+        }
+
+        std::string SceneCollectionResource::getAddress() const
+        {
+            return m_address;
+        }
+
+        std::vector<std::string> SceneCollectionResource::getSceneValues() const
+        {
+            return m_sceneCollectionResourceObject->getAttributeValue(
+                    SCENE_KEY_SCENEVALUES).get<std::vector<std::string>>();
+        }
+
+        std::vector<SceneMemberResource::Ptr> SceneCollectionResource::getSceneMembers() const
+        {
+            std::lock_guard<std::mutex> memberlock(m_sceneMemberLock);
+            return m_sceneMembers;
+        }
+
+        std::vector<SceneMemberResource::Ptr> SceneCollectionResource::findSceneMembers(
+                const std::string & sceneName) const
+        {
+            std::lock_guard<std::mutex> memberlock(m_sceneMemberLock);
+            std::vector<SceneMemberResource::Ptr> retMembers;
+            std::for_each(m_sceneMembers.begin(), m_sceneMembers.end(),
+                    [& retMembers, & sceneName](SceneMemberResource::Ptr pMember)
+                    {
+                        if(pMember->hasSceneValue(sceneName))
+                        {
+                            retMembers.push_back(pMember);
+                        }
+                    });
+            return retMembers;
+        }
+
+        RCSResourceObject::Ptr SceneCollectionResource::getRCSResourceObject() const
+        {
+            return m_sceneCollectionResourceObject;
+        }
+
+        void SceneCollectionResource::setName(std::string && sceneCollectionName)
+        {
+            m_sceneCollectionResourceObject->setAttribute(
+                    SCENE_KEY_NAME, std::move(sceneCollectionName));
+        }
+
+        void SceneCollectionResource::setName(const std::string & sceneCollectionName)
+        {
+            setName(std::string(sceneCollectionName));
+        }
+
+        std::string SceneCollectionResource::getName() const
+        {
+            return m_sceneCollectionResourceObject->getAttributeValue(
+                    SCENE_KEY_NAME).get<std::string>();
+        }
+
+        RCSSetResponse SceneCollectionResource::SceneCollectionRequestHandler::
+        onSetRequest(const RCSRequest & request, RCSResourceAttributes & attributes)
+        {
+            if (request.getInterface() == LINK_BATCH)
+            {
+                return createSceneMemberRequest(request, attributes);
+            }
+
+            if (attributes.contains(SCENE_KEY_SCENEVALUES))
+            {
+                return addSceneRequest(request, attributes);
+            }
+
+            if (attributes.contains(SCENE_KEY_LAST_SCENE))
+            {
+                return executeSceneRequest(request, attributes);
+            }
+
+            if (attributes.contains(SCENE_KEY_NAME))
+            {
+                return setSceneCollectionName(request, attributes);
+            }
+
+            return RCSSetResponse::create(attributes, (int)SCENE_CLIENT_BADREQUEST).
+                    setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
+        }
+
+        RCSSetResponse SceneCollectionResource::SceneCollectionRequestHandler::
+        addSceneRequest(const RCSRequest & /*request*/, RCSResourceAttributes & attributes)
+        {
+            SceneCollectionResource::Ptr ptr = m_owner.lock();
+            if (ptr == nullptr)
+            {
+                return RCSSetResponse::create(attributes, SCENE_CLIENT_BADREQUEST).
+                        setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
+            }
+
+            auto values = attributes.at(SCENE_KEY_SCENEVALUES).get<std::vector<std::string>>();
+
+            auto sizeofValues = values.size();
+            unsigned int sameSize = 0;
+            std::for_each(values.begin(), values.end(),
+                    [& ptr, & sameSize](const std::string & value)
+                    {
+                        try
+                        {
+                            ptr->addScene(value);
+                        } catch (...)
+                        {
+                            sameSize++;
+                        }
+                    });
+
+            int eCode = SCENE_RESPONSE_SUCCESS;
+            if (sameSize == sizeofValues)
+            {
+                eCode = SCENE_CLIENT_BADREQUEST;
+            }
+
+            return RCSSetResponse::create(attributes, eCode).
+                    setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
+        }
+
+        RCSSetResponse SceneCollectionResource::SceneCollectionRequestHandler::
+        executeSceneRequest(const RCSRequest & request, RCSResourceAttributes & attributes)
+        {
+            SceneCollectionResource::Ptr ptr = m_owner.lock();
+            if (ptr == nullptr)
+            {
+                return RCSSetResponse::create(attributes, SCENE_CLIENT_BADREQUEST).
+                        setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
+            }
+
+            auto requestKey = attributes.at(SCENE_KEY_LAST_SCENE).get<std::string>();
+
+            RCSRequest req(request.getResourceObject().lock(), request.getOCRequest());
+  
+            ptr->execute(std::string(requestKey),
+                    [req](int /*eCode*/) 
+                    {
+                        // TODO need to set error code.
+                        // and need to set specific attr' but this attr not to be apply to RCSResourceObject.
+                        RCSSeparateResponse(req).set();
+                    });
+
+            return RCSSetResponse::separate();
+        }
+
+        RCSSetResponse SceneCollectionResource::SceneCollectionRequestHandler::
+        createSceneMemberRequest(const RCSRequest & /*request*/, RCSResourceAttributes & attributes)
+        {
+            int eCode = SCENE_CLIENT_BADREQUEST;
+            SceneCollectionResource::Ptr ptr = m_owner.lock();
+            if (!ptr)
+            {
+                return RCSSetResponse::create(attributes, eCode).
+                        setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
+            }
+
+            RCSResourceAttributes responseAtt(attributes);
+            if (attributes.contains(SCENE_KEY_PAYLOAD_LINK))
+            {
+                auto linkAtt = attributes.at(SCENE_KEY_PAYLOAD_LINK).get<RCSResourceAttributes>();
+                if (linkAtt.contains(SCENE_KEY_HREF) &&
+                        linkAtt.contains(SCENE_KEY_RT) && linkAtt.contains(SCENE_KEY_IF))
+                {
+                    auto memberObj = SceneMemberResource::createSceneMemberResource(linkAtt);
+                    try
+                    {
+                        ptr->addSceneMember(memberObj);
+                    }
+                    catch (...)
+                    {
+                        return RCSSetResponse::create(responseAtt, eCode).
+                                setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
+                    }
+                    eCode = SCENE_RESPONSE_SUCCESS;
+
+                    if (attributes.contains(SCENE_KEY_SCENEMAPPINGS))
+                    {
+                        addMemberInfoFromRemote(memberObj, attributes.at(
+                                SCENE_KEY_SCENEMAPPINGS).get<std::vector<RCSResourceAttributes>>());
+                    }
+                    responseAtt[SCENE_KEY_ID] = RCSResourceAttributes::Value(memberObj->getId());
+                    responseAtt[SCENE_KEY_CREATEDLINK]
+                                = RCSResourceAttributes::Value(memberObj->getFullUri());
+                }
+            }
+
+            return RCSSetResponse::create(responseAtt, eCode).
+                    setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
+        }
+
+        RCSSetResponse
+        SceneCollectionResource::SceneCollectionRequestHandler::setSceneCollectionName(
+                const RCSRequest & /*request*/, RCSResourceAttributes & attr)
+        {
+            int eCode = SCENE_CLIENT_BADREQUEST;
+            SceneCollectionResource::Ptr ptr = m_owner.lock();
+            if (ptr != nullptr)
+            {
+                eCode = SCENE_RESPONSE_SUCCESS;
+                ptr->setName(attr.at(SCENE_KEY_NAME).get<std::string>());
+            }
+
+            return RCSSetResponse::create(attr, eCode).
+                    setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
+        }
+
+        void SceneCollectionResource::SceneCollectionRequestHandler::addMemberInfoFromRemote(
+                SceneMemberResource::Ptr memberObj, std::vector<RCSResourceAttributes> mInfo)
+        {
+            std::for_each(mInfo.begin(), mInfo.end(),
+                    [& memberObj](const RCSResourceAttributes & att)
+                    {
+                        memberObj->addMappingInfo(SceneMemberResource::MappingInfo::create(att));
+                    });
+        }
+
+        void SceneCollectionResource::SceneExecuteResponseHandler::
+        onResponse(const RCSResourceAttributes & /*attributes*/, int errorCode)
+        {
+            m_responseMembers++;
+            if (errorCode != SCENE_RESPONSE_SUCCESS && m_errorCode != errorCode)
+            {
+                m_errorCode = errorCode;
+            }
+            if (m_responseMembers == m_numOfMembers)
+            {
+                m_cb(m_errorCode);
+            }
+        }
+
+        SceneCollectionResource::SceneExecuteResponseHandler::Ptr
+        SceneCollectionResource::SceneExecuteResponseHandler::createExecuteHandler(
+                const SceneCollectionResource::Ptr ptr, SceneExecuteCallback executeCB)
+        {
+            auto executeHandler = std::make_shared<SceneExecuteResponseHandler>();
+
+            executeHandler->m_numOfMembers = ptr->m_sceneMembers.size();
+            executeHandler->m_responseMembers = 0;
+
+            executeHandler->m_cb =
+                    [executeCB](int eCode)
+                    {
+                        std::thread(std::move(executeCB), eCode).detach();
+                    };
+
+            executeHandler->m_owner
+                = std::weak_ptr<SceneCollectionResource>(ptr);
+            executeHandler->m_errorCode  = SCENE_RESPONSE_SUCCESS;
+
+            return executeHandler;
+        }
+
+    }
+}
diff --git a/service/scene-manager/src/SceneCollectionResource.h b/service/scene-manager/src/SceneCollectionResource.h
new file mode 100644 (file)
index 0000000..f625df6
--- /dev/null
@@ -0,0 +1,147 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef SCENE_COLLECTION_RESOURCE_OBJECT_H
+#define SCENE_COLLECTION_RESOURCE_OBJECT_H
+
+#include <list>
+
+#include "RCSResourceObject.h"
+#include "SceneCommons.h"
+#include "SceneMemberResource.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+        class SceneCollectionResource
+                : public std::enable_shared_from_this<SceneCollectionResource>
+        {
+        public:
+            typedef std::shared_ptr< SceneCollectionResource > Ptr;
+            typedef std::function< void(int) > SceneExecuteCallback;
+
+            ~SceneCollectionResource() = default;
+
+            static SceneCollectionResource::Ptr create();
+            static SceneCollectionResource::Ptr create(const RCSResourceAttributes &);
+
+            void addScene(std::string &&);
+            void addScene(const std::string &);
+
+            void addSceneMember(SceneMemberResource::Ptr);
+
+            void execute(std::string &&);
+            void execute(const std::string &);
+            void execute(std::string &&, SceneExecuteCallback);
+            void execute(const std::string &, SceneExecuteCallback);
+
+            void setName(std::string &&);
+            void setName(const std::string &);
+
+            std::vector<std::string> getSceneValues() const;
+
+            std::string getName() const;
+
+            std::string getId() const;
+            std::string getUri() const;
+            std::string getAddress() const;
+
+            std::vector<SceneMemberResource::Ptr> getSceneMembers() const;
+
+            std::vector<SceneMemberResource::Ptr> findSceneMembers(
+                    const std::string & sceneName) const;
+
+            RCSResourceObject::Ptr getRCSResourceObject() const;
+
+        private:
+            class SceneExecuteResponseHandler
+            {
+            public:
+                typedef std::shared_ptr<SceneExecuteResponseHandler> Ptr;
+
+                SceneExecuteResponseHandler()
+                : m_numOfMembers(0), m_responseMembers(0), m_errorCode(0) { }
+                ~SceneExecuteResponseHandler() = default;
+
+                int m_numOfMembers;
+                int m_responseMembers;
+                int m_errorCode;
+                std::weak_ptr<SceneCollectionResource> m_owner;
+                SceneExecuteCallback m_cb;
+
+                static SceneExecuteResponseHandler::Ptr createExecuteHandler(
+                        const SceneCollectionResource::Ptr, SceneExecuteCallback);
+                void onResponse(const RCSResourceAttributes &, int);
+            };
+
+            class SceneCollectionRequestHandler
+            {
+            public:
+                SceneCollectionRequestHandler() = default;
+                ~SceneCollectionRequestHandler() = default;
+
+                std::weak_ptr<SceneCollectionResource> m_owner;
+
+                RCSSetResponse onSetRequest(
+                        const RCSRequest &, RCSResourceAttributes &);
+
+            private:
+                RCSSetResponse addSceneRequest(
+                        const RCSRequest &, RCSResourceAttributes &);
+                RCSSetResponse executeSceneRequest(
+                        const RCSRequest &, RCSResourceAttributes &);
+                RCSSetResponse createSceneMemberRequest(
+                        const RCSRequest &, RCSResourceAttributes &);
+                RCSSetResponse setSceneCollectionName(
+                        const RCSRequest &, RCSResourceAttributes &);
+
+                void addMemberInfoFromRemote(SceneMemberResource::Ptr,
+                        std::vector<RCSResourceAttributes>);
+            };
+
+            std::string m_uri;
+            std::string m_address;
+
+            RCSResourceObject::Ptr m_sceneCollectionResourceObject;
+            mutable std::mutex m_sceneMemberLock;
+            std::vector<SceneMemberResource::Ptr> m_sceneMembers;
+
+            SceneCollectionRequestHandler m_requestHandler;
+
+            SceneCollectionResource();
+
+            SceneCollectionResource(const SceneCollectionResource &) = delete;
+            SceneCollectionResource & operator = (
+                    const SceneCollectionResource &) = delete;
+
+            SceneCollectionResource(SceneCollectionResource &&) = delete;
+            SceneCollectionResource & operator = (
+                    SceneCollectionResource &&) = delete;
+
+            RCSResourceObject::Ptr createResourceObject();
+            void setDefaultAttributes();
+            void initSetRequestHandler();
+        };
+    }
+}
+
+#endif // SCENE_COLLECTION_RESOURCE_OBJECT_H
+
diff --git a/service/scene-manager/src/SceneCollectionResourceRequestor.cpp b/service/scene-manager/src/SceneCollectionResourceRequestor.cpp
new file mode 100644 (file)
index 0000000..f36d3bc
--- /dev/null
@@ -0,0 +1,341 @@
+//******************************************************************
+//
+// 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 "SceneCollectionResourceRequestor.h"
+#include "RemoteSceneUtils.h"
+#include "OCPlatform.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+
+        SceneCollectionResourceRequestor::SceneCollectionResourceRequestor(
+            RCSRemoteResourceObject::Ptr collectionResource)
+                : m_sceneCollectionResource{ collectionResource }
+        {
+            SCENE_CLIENT_ASSERT_NOT_NULL(collectionResource);
+        }
+
+        void SceneCollectionResourceRequestor::requestSceneCreation(
+            const std::string &name, InternalSceneRequestCallback createSceneCB)
+        {
+            RCSResourceAttributes attributesToSet;
+            std::vector< std::string > scenenames{ name };
+            
+            attributesToSet[SCENE_KEY_SCENEVALUES] = scenenames;
+
+            RCSRemoteResourceObject::RemoteAttributesSetCallback setRequestCB
+                = std::bind(&SceneCollectionResourceRequestor::onSetResponseForScene,
+                            std::placeholders::_1, std::placeholders::_2,
+                            name, std::move(createSceneCB), ADD_SCENE,
+                            SceneCollectionResourceRequestor::wPtr(shared_from_this()));
+
+            m_sceneCollectionResource->setRemoteAttributes(
+                std::move(attributesToSet), std::move(setRequestCB));
+        }
+
+        void SceneCollectionResourceRequestor::requestSceneRemoval
+        (const std::string &/* name */, InternalSceneRequestCallback)
+        {
+
+        }
+
+        void SceneCollectionResourceRequestor::requestSceneExecution
+        (const std::string &name, InternalSceneRequestCallback executeSceneCB)
+        {
+            RCSResourceAttributes attributesToSet;
+            attributesToSet[SCENE_KEY_LAST_SCENE] = name;
+
+            RCSRemoteResourceObject::RemoteAttributesSetCallback setRequestCB
+                = std::bind(&SceneCollectionResourceRequestor::onSetResponseForScene,
+                            std::placeholders::_1, std::placeholders::_2,
+                            name, std::move(executeSceneCB), EXECUTE_SCENE,
+                            SceneCollectionResourceRequestor::wPtr(shared_from_this()));
+
+            m_sceneCollectionResource->setRemoteAttributes(
+                std::move(attributesToSet), std::move(setRequestCB));
+        }
+
+        void SceneCollectionResourceRequestor::requestAddSceneMember(
+            RCSRemoteResourceObject::Ptr targetResource, const std::string &sceneName,
+            const RCSResourceAttributes &attr, InternalAddMemberCallback addMemberCB)
+        {
+            SCENE_CLIENT_ASSERT_NOT_NULL(targetResource);
+
+            RCSResourceAttributes attributesToSet, linkAttrs;
+
+            linkAttrs[SCENE_KEY_HREF] = targetResource->getAddress() + targetResource->getUri();
+            linkAttrs[SCENE_KEY_IF] = targetResource->getInterfaces();
+            linkAttrs[SCENE_KEY_RT] = targetResource->getTypes();
+
+            attributesToSet[SCENE_KEY_PAYLOAD_LINK] = linkAttrs;
+
+            if (!attr.empty())
+            {
+                std::vector< RCSResourceAttributes > vecSceneMappings;
+                for (const auto &itr : attr)
+                {
+                    RCSResourceAttributes sceneMappingAttrs;
+                    sceneMappingAttrs[SCENE_KEY_SCENE] = sceneName;
+                    sceneMappingAttrs[SCENE_KEY_MEMBERPROPERTY] = itr.key();
+                    sceneMappingAttrs[SCENE_KEY_MEMBERVALUE] = itr.value();
+
+                    vecSceneMappings.push_back(sceneMappingAttrs);
+                }
+
+                attributesToSet[SCENE_KEY_SCENEMAPPINGS] = vecSceneMappings;
+            }
+
+            RCSRemoteResourceObject::SetCallback setRequestCB
+                = std::bind(&SceneCollectionResourceRequestor::onSceneMemberAdded,
+                            std::placeholders::_2, std::placeholders::_3,
+                            targetResource,
+                            std::move(addMemberCB),
+                            SceneCollectionResourceRequestor::wPtr(shared_from_this()));
+
+            RCSQueryParams queryParams;
+            queryParams.setResourceInterface(LINK_BATCH);
+
+            m_sceneCollectionResource->set(queryParams, std::move(attributesToSet),
+                                              std::move(setRequestCB));
+        }
+
+        void SceneCollectionResourceRequestor::requestSetName
+        (const std::string &name, InternalSetNameCallback internalCB)
+        {
+            RCSResourceAttributes attrs;
+            attrs[SCENE_KEY_NAME] = name;
+
+            RCSRemoteResourceObject::SetCallback setRequestCB
+                = std::bind(&SceneCollectionResourceRequestor::onNameSet,
+                std::placeholders::_2, std::placeholders::_3, name, std::move(internalCB),
+                SceneCollectionResourceRequestor::wPtr(shared_from_this()));
+
+            RCSQueryParams queryParams;
+            queryParams.setResourceInterface(SCENE_CLIENT_REQ_IF);
+
+            m_sceneCollectionResource->set(queryParams, std::move(attrs), std::move(setRequestCB));
+        }
+
+        void SceneCollectionResourceRequestor::requestGet(
+            const std::string &ifType, RCSRemoteResourceObject::GetCallback cb)
+        {
+            RCSQueryParams params;
+            params.setResourceInterface(ifType);
+
+            m_sceneCollectionResource->get(params, cb);
+        }
+
+        RCSRemoteResourceObject::Ptr 
+            SceneCollectionResourceRequestor::getRemoteResourceObject() const
+        {
+            return m_sceneCollectionResource;
+        }
+
+        SceneMemberResourceRequestor::Ptr
+        SceneCollectionResourceRequestor::createSceneMemberResourceRequestor(
+            const std::string &memHref, const std::string &id, RCSRemoteResourceObject::Ptr target)
+        {
+            try
+            {
+                std::vector< std::string > vecRT{ SCENE_MEMBER_RT };
+                std::vector< std::string > vecIF{ SCENE_CLIENT_REQ_IF };
+
+                RCSRemoteResourceObject::Ptr pResource
+                    = SceneUtils::createRCSResourceObject(
+                        memHref, SCENE_CONNECTIVITY, vecRT, vecIF);
+
+                SceneMemberResourceRequestor::Ptr pMemRequestor =
+                    std::make_shared< SceneMemberResourceRequestor >(pResource, id);
+
+                pMemRequestor->setRemoteResourceObject(target);
+                
+                {
+                    std::lock_guard< std::mutex > memberlock(m_memberRequestorLock);
+                    m_memberRequestors[target->getAddress() + target->getUri()] = pMemRequestor;
+                }
+
+                return pMemRequestor;
+            }
+            catch (const std::exception &e)
+            {
+                SCENE_CLIENT_PRINT_LOG(e.what());
+                return nullptr;
+            }
+        }
+
+        SceneMemberResourceRequestor::Ptr
+        SceneCollectionResourceRequestor::getSceneMemberResourceRequestor(
+            const std::string &targetHref) const
+        {
+            std::lock_guard< std::mutex > memberlock(m_memberRequestorLock);
+
+            return m_memberRequestors.find(targetHref) != m_memberRequestors.end() ?
+                m_memberRequestors.at(targetHref) : nullptr;
+        }
+
+        void SceneCollectionResourceRequestor::onSetResponseForScene(
+            const RCSResourceAttributes &attrs, int eCode,
+            const std::string &name, const InternalSceneRequestCallback &cb,
+            REQUEST_TYPE reqType, SceneCollectionResourceRequestor::wPtr ptr)
+        {
+            SceneCollectionResourceRequestor::Ptr collectionPtr = ptr.lock();
+
+            if (collectionPtr)
+            {
+                collectionPtr->onSetResponseForScene_impl(
+                    std::move(attrs), eCode, name, std::move(cb), reqType);
+            }
+        }
+
+        void SceneCollectionResourceRequestor::onSetResponseForScene_impl(
+            const RCSResourceAttributes &attrs, int eCode, const std::string &name,
+            const InternalSceneRequestCallback &internalCB, REQUEST_TYPE reqType)
+        {
+            // TODO error code
+            int resultCode = SCENE_CLIENT_BADREQUEST;
+
+            if (eCode == OC_STACK_OK)
+            {
+                try
+                {
+                    switch (reqType)
+                    {
+                        case ADD_SCENE:
+                            {
+                                auto scenes
+                                    = attrs.at(SCENE_KEY_SCENEVALUES).
+                                        get< std::vector< std::string > >();
+
+                                if ((std::find(scenes.begin(), scenes.end(), name))
+                                    != scenes.end())
+                                {
+                                    resultCode = SCENE_RESPONSE_SUCCESS;
+                                }
+                            }
+                            break;
+
+                        case REMOVE_SCENE:
+                            break;
+
+                        case EXECUTE_SCENE:
+                            {
+                                auto lastScene
+                                    = attrs.at(SCENE_KEY_LAST_SCENE).get< std::string >();
+
+                                if (lastScene.compare(name) == 0)
+                                {
+                                    resultCode = SCENE_RESPONSE_SUCCESS;
+                                }
+                            }
+                            break;
+                    }
+                }
+                catch (const std::exception &e)
+                {
+                    SCENE_CLIENT_PRINT_LOG(e.what());
+                    resultCode = SCENE_SERVER_INTERNALSERVERERROR;
+                }
+            }
+
+            internalCB(reqType, name, resultCode);
+        }
+
+        void SceneCollectionResourceRequestor::onSceneMemberAdded(
+            const RCSRepresentation &rep, int eCode,
+            RCSRemoteResourceObject::Ptr target, const InternalAddMemberCallback &internalCB,
+            SceneCollectionResourceRequestor::wPtr ptr)
+        {
+            SceneCollectionResourceRequestor::Ptr collection = ptr.lock();
+
+            if (collection)
+            {
+                collection->onSceneMemberAdded_impl(
+                    std::move(rep), eCode, target, std::move(internalCB));
+            }
+        }
+
+        void SceneCollectionResourceRequestor::onSceneMemberAdded_impl(
+            const RCSRepresentation &rep, int eCode,
+            RCSRemoteResourceObject::Ptr target, const InternalAddMemberCallback &internalCB)
+        {
+            // TODO error code
+            int result = SCENE_CLIENT_BADREQUEST;
+            SceneMemberResourceRequestor::Ptr memRequestor = nullptr;
+
+            if (eCode == OC_STACK_OK)
+            {
+                try
+                {
+                    RCSResourceAttributes receivedAttrs = rep.getAttributes();
+
+                    memRequestor
+                        = createSceneMemberResourceRequestor(
+                              receivedAttrs.at(SCENE_KEY_CREATEDLINK).get< std::string >(),
+                              receivedAttrs.at(SCENE_KEY_ID).get< std::string >(), target);
+
+                    if (memRequestor)
+                    {
+                        memRequestor->setRemoteResourceObject(target);
+                        result = SCENE_RESPONSE_SUCCESS;
+                    }
+                }
+                catch (const std::exception &e)
+                {
+                    SCENE_CLIENT_PRINT_LOG(e.what());
+                    result = SCENE_SERVER_INTERNALSERVERERROR;
+                }
+            }
+
+            internalCB(result);
+        }
+
+        void SceneCollectionResourceRequestor::onNameSet(const RCSRepresentation &rep, int eCode,
+            const std::string &name, const InternalSetNameCallback &internalCB,
+            SceneCollectionResourceRequestor::wPtr ptr)
+        {
+            SceneCollectionResourceRequestor::Ptr collectionPtr = ptr.lock();
+
+            if (collectionPtr)
+            {
+                collectionPtr->onNameSet_impl(std::move(rep), eCode, name, std::move(internalCB));
+            }
+        }
+
+        void SceneCollectionResourceRequestor::onNameSet_impl(
+            const RCSRepresentation &rep, int eCode, const std::string &name,
+            const InternalSetNameCallback &internalCB)
+        {
+            int result = SCENE_CLIENT_BADREQUEST;
+            if (eCode == OC_STACK_OK)
+            {
+                if (rep.getAttributes().at(SCENE_KEY_NAME).get< std::string >() == name)
+                {
+                    result = SCENE_RESPONSE_SUCCESS;
+                }
+
+            }
+
+            internalCB(result);
+        }
+
+    }
+}
diff --git a/service/scene-manager/src/SceneCollectionResourceRequestor.h b/service/scene-manager/src/SceneCollectionResourceRequestor.h
new file mode 100644 (file)
index 0000000..1975f80
--- /dev/null
@@ -0,0 +1,120 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef SM_SCENECOLLECTION_RESOURCE_REQUESTOR_H_
+#define SM_SCENECOLLECTION_RESOURCE_REQUESTOR_H_
+
+#include <map>
+#include <mutex>
+
+#include "SceneCommons.h"
+#include "RCSRemoteResourceObject.h"
+#include "RCSRepresentation.h"
+#include "SceneMemberResourceRequestor.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+
+        class SceneCollectionResourceRequestor
+            : public std::enable_shared_from_this< SceneCollectionResourceRequestor >
+        {
+            public:
+                typedef std::shared_ptr< SceneCollectionResourceRequestor > Ptr;
+                typedef std::weak_ptr< SceneCollectionResourceRequestor > wPtr;
+
+                enum REQUEST_TYPE
+                {
+                    ADD_SCENE, REMOVE_SCENE, EXECUTE_SCENE
+                };
+
+                typedef std::function< 
+                    void(REQUEST_TYPE, const std::string &name, int eCode) >
+                        InternalSceneRequestCallback;
+
+                typedef std::function < void(int eCode) > InternalAddMemberCallback;
+
+                typedef std::function < void(int eCode) > InternalSetNameCallback;
+
+            public:
+                SceneCollectionResourceRequestor(RCSRemoteResourceObject::Ptr collectionResource);
+                ~SceneCollectionResourceRequestor() = default;
+
+                void requestSceneCreation(const std::string &name, InternalSceneRequestCallback);
+                void requestSceneRemoval(const std::string &name, InternalSceneRequestCallback);
+
+                void requestSceneExecution(const std::string &name, InternalSceneRequestCallback);
+
+                void requestAddSceneMember(RCSRemoteResourceObject::Ptr targetResource,
+                                           const std::string &sceneName,
+                                           const RCSResourceAttributes &attr,
+                                           InternalAddMemberCallback);
+
+                void requestSetName(const std::string &, InternalSetNameCallback);
+
+                void requestGet(const std::string &, RCSRemoteResourceObject::GetCallback);
+
+                RCSRemoteResourceObject::Ptr getRemoteResourceObject() const;
+
+                SceneMemberResourceRequestor::Ptr createSceneMemberResourceRequestor(
+                    const std::string &memHref, const std::string &id,
+                    RCSRemoteResourceObject::Ptr target);
+
+                SceneMemberResourceRequestor::Ptr getSceneMemberResourceRequestor(
+                    const std::string &targetHref) const;
+
+            private:
+                static void onSetResponseForScene(
+                    const RCSResourceAttributes &attrs, int eCode,
+                    const std::string &name, const InternalSceneRequestCallback &,
+                    REQUEST_TYPE, SceneCollectionResourceRequestor::wPtr);
+
+                void onSetResponseForScene_impl(
+                    const RCSResourceAttributes &attrs, int eCode,
+                    const std::string &name, const InternalSceneRequestCallback &,
+                    REQUEST_TYPE);
+
+                static void onSceneMemberAdded(
+                    const RCSRepresentation &, int eCode,
+                    RCSRemoteResourceObject::Ptr, const InternalAddMemberCallback &,
+                    SceneCollectionResourceRequestor::wPtr);
+
+                void onSceneMemberAdded_impl(
+                    const RCSRepresentation &, int eCode,
+                    RCSRemoteResourceObject::Ptr, const InternalAddMemberCallback &);
+
+                static void onNameSet(const RCSRepresentation &, int eCode, const std::string &,
+                    const InternalSetNameCallback &, SceneCollectionResourceRequestor::wPtr);
+
+                void onNameSet_impl(const RCSRepresentation &, int eCode, const std::string &,
+                    const InternalSetNameCallback &);
+
+            private:
+                RCSRemoteResourceObject::Ptr m_sceneCollectionResource;
+                mutable std::mutex m_memberRequestorLock;
+                std::map< std::string, SceneMemberResourceRequestor::Ptr > m_memberRequestors;
+        };
+        
+    }
+}
+
+#endif /* SM_SCENECOLLECTION_RESOURCE_REQUESTOR_H_ */
+
diff --git a/service/scene-manager/src/SceneCommons.h b/service/scene-manager/src/SceneCommons.h
new file mode 100644 (file)
index 0000000..f404bc1
--- /dev/null
@@ -0,0 +1,129 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/**
+ * @file
+ *
+ * This file contains the declaration of SceneUtils class and constant variables.
+ */
+
+#ifndef SCENE_COMMONS_H
+#define SCENE_COMMONS_H
+
+#include <string>
+#include <vector>
+
+#include "OCApi.h"
+#include "RCSRemoteResourceObject.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+        const std::string SCENE_LIST_DEFAULT_NAME = "list of scene Collections";
+
+        const std::string SCENE_KEY_LAST_SCENE = "lastScene";
+        const std::string SCENE_KEY_SCENEVALUES = "sceneValues";
+        const std::string SCENE_KEY_NAME = "n";
+        const std::string SCENE_KEY_ID = "id";
+        const std::string SCENE_KEY_RTS = "rts";
+        const std::string SCENE_KEY_RT = "rt";
+        const std::string SCENE_KEY_IF = "if";
+        const std::string SCENE_KEY_PAYLOAD_LINK = "link";
+        const std::string SCENE_KEY_SCENEMAPPINGS = "sceneMappings";
+        const std::string SCENE_KEY_HREF = "href";
+        const std::string SCENE_KEY_SCENE = "scene";
+        const std::string SCENE_KEY_MEMBERPROPERTY = "memberProperty";
+        const std::string SCENE_KEY_MEMBERVALUE = "memberValue";
+        const std::string SCENE_KEY_CREATEDLINK = "createdlink";
+
+        const std::string SCENE_KEY_URI = "uri";
+        const std::string SCENE_KEY_CHILD = "child";
+
+        const std::string SCENE_LIST_RT = "oic.wk.scenelist";
+        const std::string SCENE_MEMBER_RT = "oic.wk.scenemember";
+        const std::string SCENE_COLLECTION_RT = "oic.wk.scenecollection";
+
+        const std::string COAP_TAG = "coap://";
+        const std::string SCENE_LIST_URI = "/SceneListResURI";
+        const std::string PREFIX_SCENE_COLLECTION_URI = "/a/sceneCollection";
+        const std::string PREFIX_SCENE_MEMBER_URI = "/a/sceneMember";
+
+        const std::string LINK_BATCH = "oic.if.lb";
+        const std::string BASELINE_IF = "oic.if.baseline";
+
+        const OCConnectivityType SCENE_CONNECTIVITY = CT_ADAPTER_IP;
+        const std::string SCENE_CLIENT_REQ_IF = BASELINE_IF;
+        const std::string SCENE_CLIENT_CREATE_REQ_IF = OC::BATCH_INTERFACE;
+
+        const int SCENE_RESPONSE_SUCCESS = 200;
+        const int SCENE_CLIENT_BADREQUEST = 400;
+        const int SCENE_SERVER_INTERNALSERVERERROR = 500;
+
+        class SceneUtils
+        {
+        public:
+            /**
+             * Returns UUID for Scene collection resource and members ID.
+             *
+             * @throw RCSException
+             */
+            static std::string OICGenerateUUIDStr();
+
+            /**
+             * Returns host resource's address and uri from coap address.
+             *
+             * @param address uri of host resource (e.g. coap://192.168.0.2:12345/a/light)
+             * @param[out] host host resource's address (e.g. 192.168.0.2:12345)
+             * @param[out] uri host resource's uri (e.g. /a/light)
+             *
+             * @throw RCSInvalidParameterException
+             */
+            static void getHostUriString(
+                    const std::string address, std::string *host, std::string *uri);
+
+            /**
+             * Returns information of my own network address.
+             *
+             * This functionality use the CA interface for getting network information.
+             * But It has design issue. So, It will should change to other interface.
+             *
+             * @throw RCSException
+             */
+            static std::string getNetAddress();
+
+            /**
+            * Returns RCSRemoteResourceObject pointer created with provided resource information.
+            *
+            * @param address uri of resource (e.g. coap://192.168.0.2:12345/a/light)
+            * @param ct OCConnectivityType type of connectivity indicating the interface
+            * @param vecRT a vector of resource types implemented by the resource
+            * @param vecIF a vector of interfaces that the resource supports/implements
+            *
+            * @throw RCSException
+            */
+            static RCSRemoteResourceObject::Ptr createRCSResourceObject(
+                const std::string &address, const OCConnectivityType ct,
+                const std::vector< std::string > &vecRT, const std::vector< std::string > &vecIF);
+        };
+    }
+}
+
+#endif // SCENE_COMMONS_H
diff --git a/service/scene-manager/src/SceneList.cpp b/service/scene-manager/src/SceneList.cpp
new file mode 100755 (executable)
index 0000000..ec1d096
--- /dev/null
@@ -0,0 +1,71 @@
+//******************************************************************
+//
+// 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 "SceneList.h"
+
+#include "SceneListResource.h"
+#include "SceneCollectionResource.h"
+
+#include "RCSRequest.h"
+#include "PrimitiveResource.h"
+#include "OCPlatform.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+        SceneList * SceneList::getInstance()
+        {
+            static SceneList instance;
+            return &instance;
+        }
+
+        SceneCollection::Ptr SceneList::addNewSceneCollection()
+        {
+            auto sceneCollectionResObj =
+                    SceneCollectionResource::create();
+            SceneListResource::getInstance()->addSceneCollectionResource(sceneCollectionResObj);
+
+            return SceneCollection::Ptr(new SceneCollection(sceneCollectionResObj));
+        }
+
+        std::vector< SceneCollection::Ptr > SceneList::getSceneCollections() const
+        {
+            std::vector<SceneCollection::Ptr> sceneCollections;
+            for(const auto& it : SceneListResource::getInstance()->getSceneCollections())
+            {
+                SceneCollection::Ptr sceneCollectionPtr(new SceneCollection(it));
+                sceneCollections.push_back(sceneCollectionPtr);
+            }
+            return sceneCollections;
+        }
+
+        void SceneList::setName(const std::string& sceneListName)
+        {
+            SceneListResource::getInstance()->setName(sceneListName);
+        }
+
+        std::string SceneList::getName() const
+        {
+            return SceneListResource::getInstance()->getName();
+        }
+    } /* namespace Service */
+} /* namespace OIC */
+
diff --git a/service/scene-manager/src/SceneListResource.cpp b/service/scene-manager/src/SceneListResource.cpp
new file mode 100644 (file)
index 0000000..cf2d4ff
--- /dev/null
@@ -0,0 +1,197 @@
+//******************************************************************
+//
+// 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 "SceneListResource.h"
+
+#include "RCSRequest.h"
+#include "OCApi.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+        SceneListResource::SceneListResource()
+        : m_sceneListObj(createResourceObject())
+        {
+            m_sceneListObj->setAttribute(SCENE_KEY_NAME, SCENE_LIST_DEFAULT_NAME);
+            m_sceneListObj->setAttribute(SCENE_KEY_RTS, SCENE_LIST_RT);
+
+            m_sceneListObj->setSetRequestHandler(&SceneListRequestHandler::onSetRequest);
+            m_sceneListObj->setGetRequestHandler(&SceneListRequestHandler::onGetRequest);
+        }
+
+        SceneListResource * SceneListResource::getInstance()
+        {
+            static SceneListResource instance;
+            return & instance;
+        }
+
+        RCSResourceObject::Ptr SceneListResource::createResourceObject()
+        {
+            return RCSResourceObject::Builder(
+                    SCENE_LIST_URI, SCENE_LIST_RT, BASELINE_IF).
+                            addInterface(OC::BATCH_INTERFACE).
+                            addInterface(LINK_BATCH).
+                            setDiscoverable(true).setObservable(false).build();
+        }
+
+        void SceneListResource::addSceneCollectionResource(
+                SceneCollectionResource::Ptr newObject)
+        {
+            std::lock_guard<std::mutex> collectionlock(m_sceneCollectionLock);
+            m_sceneCollections.push_back(newObject);
+            m_sceneListObj->bindResource(newObject->getRCSResourceObject());
+        }
+
+        std::string SceneListResource::getName() const
+        {
+            return m_sceneListObj->getAttributeValue(SCENE_KEY_NAME).get<std::string>();
+        }
+
+        void SceneListResource::setName(std::string && newName)
+        {
+            m_sceneListObj->setAttribute(SCENE_KEY_NAME, std::move(newName));
+        }
+
+        void SceneListResource::setName(const std::string & newName)
+        {
+            setName(std::string(newName));
+        }
+
+        std::vector<SceneCollectionResource::Ptr> SceneListResource::getSceneCollections() const
+        {
+            std::lock_guard<std::mutex> collectionlock(m_sceneCollectionLock);
+            return m_sceneCollections;
+        }
+
+        RCSResourceObject::Ptr SceneListResource::getResourceObject() const
+        {
+            return m_sceneListObj;
+        }
+
+        std::vector<RCSResourceAttributes> SceneListResource::getChildrenAttributes() const
+        {
+            std::vector<RCSResourceAttributes> childrenAttrs;
+
+            auto sceneCollections = getSceneCollections();
+
+            std::for_each(sceneCollections.begin(), sceneCollections.end(),
+                    [& childrenAttrs](const SceneCollectionResource::Ptr & pCollection)
+                    {
+                        RCSResourceAttributes collectionAttr;
+                        {
+                            RCSResourceObject::LockGuard guard(
+                                    pCollection->getRCSResourceObject());
+                            collectionAttr = pCollection->getRCSResourceObject()->getAttributes();
+                        }
+
+                        auto sceneMembers = pCollection->getSceneMembers();
+                        std::vector<RCSResourceAttributes> membersAttrs;
+
+                        std::for_each(sceneMembers.begin(), sceneMembers.end(),
+                                [& membersAttrs](const SceneMemberResource::Ptr & pMember)
+                                {
+                                    RCSResourceObject::LockGuard guard(pMember->getRCSResourceObject());
+                                    membersAttrs.push_back(pMember->getRCSResourceObject()->getAttributes());
+                                });
+
+                        if (membersAttrs.size())
+                        {
+                            collectionAttr[SCENE_KEY_CHILD] = membersAttrs;
+                        }
+
+                        childrenAttrs.push_back(collectionAttr);
+                    });
+
+            return childrenAttrs;
+        }
+
+        RCSSetResponse SceneListResource::SceneListRequestHandler::onSetRequest(
+                const RCSRequest & request, RCSResourceAttributes & attributes)
+        {
+            RCSResourceAttributes responseAttr;
+            int eCode = SCENE_CLIENT_BADREQUEST;
+
+            if(request.getInterface() == LINK_BATCH)
+            {
+                auto newObject
+                    = SceneCollectionResource::create(attributes);
+
+                SceneListResource::getInstance()->addSceneCollectionResource(newObject);
+
+                auto responseAtt = attributes;
+                responseAtt[SCENE_KEY_NAME] = RCSResourceAttributes::Value(newObject->getName());
+                responseAtt[SCENE_KEY_ID] = RCSResourceAttributes::Value(newObject->getId());
+
+                auto uri = COAP_TAG + newObject->getAddress() + newObject->getUri();
+                responseAtt[SCENE_KEY_PAYLOAD_LINK]
+                            = RCSResourceAttributes::Value(uri);
+
+                responseAttr = responseAtt;
+                eCode = SCENE_RESPONSE_SUCCESS;
+            }
+
+            else if (attributes.contains(SCENE_KEY_NAME))
+            {
+                SceneListResource::getInstance()->setName(
+                        attributes.at(SCENE_KEY_NAME).get<std::string>());
+
+                responseAttr = attributes;
+                eCode = SCENE_RESPONSE_SUCCESS;
+            }
+            else
+            {
+                responseAttr = attributes;
+                eCode = SCENE_CLIENT_BADREQUEST;
+            }
+
+            return RCSSetResponse::create(responseAttr, eCode).
+                    setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
+        }
+
+        RCSGetResponse SceneListResource::SceneListRequestHandler::onGetRequest(
+                const RCSRequest & request, RCSResourceAttributes & /*attributes*/)
+        {
+
+            if(request.getInterface() != OC::DEFAULT_INTERFACE)
+            {
+                return RCSGetResponse::defaultAction();
+            }
+
+            auto childrenAttrs = SceneListResource::getInstance()->getChildrenAttributes();
+
+            RCSResourceAttributes retAttr;
+
+            {
+                RCSResourceObject::LockGuard lock(
+                        SceneListResource::getInstance()->getResourceObject());
+                retAttr = SceneListResource::getInstance()->getResourceObject()->getAttributes();
+            }
+
+            if (childrenAttrs.size())
+            {
+                retAttr[SCENE_KEY_CHILD] = childrenAttrs;
+            }
+
+            return RCSGetResponse::create(retAttr);
+        }
+
+    }
+}
diff --git a/service/scene-manager/src/SceneListResource.h b/service/scene-manager/src/SceneListResource.h
new file mode 100644 (file)
index 0000000..d9e0d03
--- /dev/null
@@ -0,0 +1,110 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/**
+ * @file
+ *
+ * This file contains the declaration of classes and its members related to SceneListResrouceObject
+ */
+
+#ifndef SCENE_LIST_RESOURCE_OBJECT_H
+#define SCENE_LIST_RESOURCE_OBJECT_H
+
+#include <string>
+
+#include "RCSResourceObject.h"
+#include "SceneCollectionResource.h"
+#include "SceneCommons.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+        class SceneListResource
+        {
+        public:
+            /**
+             * Returns Scene List Resource object as single instance.
+             */
+            static SceneListResource * getInstance();
+
+            /**
+             * Add Scene Collection resource object to Scene List Resource.
+             *
+             * @param collectionObj created Scene Collection Resource Object by constructor of SceneCollectionResourceObject class
+             */
+            void addSceneCollectionResource(SceneCollectionResource::Ptr collectionObj);
+
+            /**
+             * Returns Scene List name.
+             */
+            std::string getName() const;
+
+            /**
+             * Sets Scene List name.
+             *
+             * @param name name to set
+             */
+            void setName(std::string && name);
+
+            /**
+             * @overload
+             */
+            void setName(const std::string &);
+
+            /**
+             * Returns all of Scene Collection Resource object.
+             */
+            std::vector<SceneCollectionResource::Ptr> getSceneCollections() const;
+
+            std::vector<RCSResourceAttributes> getChildrenAttributes() const;
+
+            RCSResourceObject::Ptr getResourceObject() const;
+
+        private:
+            class SceneListRequestHandler
+            {
+            public:
+                SceneListRequestHandler() = default;
+                ~SceneListRequestHandler() = default;
+
+                static RCSSetResponse onSetRequest(const RCSRequest &, RCSResourceAttributes &);
+                static RCSGetResponse onGetRequest(const RCSRequest &, RCSResourceAttributes &);
+            };
+
+            RCSResourceObject::Ptr m_sceneListObj;
+            mutable std::mutex m_sceneCollectionLock;
+            std::vector<SceneCollectionResource::Ptr> m_sceneCollections;
+
+            SceneListResource();
+            ~SceneListResource() = default;
+
+            SceneListResource(const SceneListResource &) = delete;
+            SceneListResource & operator = (const SceneListResource &) = delete;
+
+            SceneListResource(SceneListResource &&) = delete;
+            SceneListResource & operator = (SceneListResource &&) = delete;
+
+            RCSResourceObject::Ptr createResourceObject();
+        };
+    }
+}
+
+#endif // SCENE_LIST_RESOURCE_OBJECT_H
diff --git a/service/scene-manager/src/SceneListResourceRequestor.cpp b/service/scene-manager/src/SceneListResourceRequestor.cpp
new file mode 100644 (file)
index 0000000..2776afa
--- /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 "SceneListResourceRequestor.h"
+#include "RemoteSceneUtils.h"
+#include "OCPlatform.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+
+        SceneListResourceRequestor::SceneListResourceRequestor(
+            RCSRemoteResourceObject::Ptr listResource)
+                : m_sceneListResource{ listResource }
+        {
+            SCENE_CLIENT_ASSERT_NOT_NULL(listResource);
+        }
+
+        void SceneListResourceRequestor::requestSceneCollectionCreation(
+            const std::string &name, InternalCreateSceneCollectionCallback internalCB)
+        {
+            RCSResourceAttributes attrs;
+            attrs[SCENE_KEY_NAME] = name;
+
+            RCSRemoteResourceObject::SetCallback setRequestCB
+                = std::bind(&SceneListResourceRequestor::onSceneCollectionCreated,
+                            std::placeholders::_2, std::placeholders::_3,
+                            name, std::move(internalCB),
+                            SceneListResourceRequestor::wPtr(shared_from_this()));
+
+            RCSQueryParams queryParams;
+            queryParams.setResourceInterface(LINK_BATCH);
+
+            m_sceneListResource->set(queryParams, std::move(attrs), std::move(setRequestCB));
+        }
+
+        void SceneListResourceRequestor::requestSetName
+        (const std::string &name, InternalSetNameCallback internalCB)
+        {
+            RCSResourceAttributes attrs;
+            attrs[SCENE_KEY_NAME] = name;
+
+            RCSRemoteResourceObject::SetCallback setRequestCB
+                = std::bind(&SceneListResourceRequestor::onNameSet,
+                std::placeholders::_2, std::placeholders::_3, name, std::move(internalCB),
+                SceneListResourceRequestor::wPtr(shared_from_this()));
+
+            RCSQueryParams queryParams;
+            queryParams.setResourceInterface(SCENE_CLIENT_REQ_IF);
+
+            m_sceneListResource->set(queryParams, std::move(attrs), std::move(setRequestCB));
+        }
+
+        void SceneListResourceRequestor::requestGet(
+            const std::string &ifType, RCSRemoteResourceObject::GetCallback cb)
+        {
+            RCSQueryParams params;
+            params.setResourceInterface(ifType);
+
+            m_sceneListResource->get(params, cb);
+        }
+
+        RCSRemoteResourceObject::Ptr SceneListResourceRequestor::getRemoteResourceObject() const
+        {
+            return m_sceneListResource;
+        }
+
+        void SceneListResourceRequestor::onSceneCollectionCreated(
+            const RCSRepresentation &rep, int eCode,
+            const std::string &name, const InternalCreateSceneCollectionCallback &cb,
+            SceneListResourceRequestor::wPtr ptr)
+        {
+            SceneListResourceRequestor::Ptr listPtr = ptr.lock();
+
+            if (listPtr)
+            {
+                listPtr->onSceneCollectionCreated_impl(std::move(rep), eCode, name, std::move(cb));
+            }
+        }
+
+        void SceneListResourceRequestor::onSceneCollectionCreated_impl(
+            const RCSRepresentation &rep, int eCode,
+            const std::string &name, const InternalCreateSceneCollectionCallback &internalCB)
+        {
+            int result = SCENE_CLIENT_BADREQUEST;
+            std::string link, id;
+
+            if (eCode == OC_STACK_OK)
+            {
+                try
+                {
+                    RCSResourceAttributes attrs = rep.getAttributes();
+
+                    if (attrs.at(SCENE_KEY_NAME).get< std::string >().compare(name) == 0)
+                    {
+                        link = attrs.at(SCENE_KEY_PAYLOAD_LINK).get< std::string >();
+                        id = attrs.at(SCENE_KEY_ID).get< std::string >();
+                        result = SCENE_RESPONSE_SUCCESS;
+                    }
+                }
+                catch (const std::exception &e)
+                {
+                    SCENE_CLIENT_PRINT_LOG(e.what());
+                    result = SCENE_SERVER_INTERNALSERVERERROR;
+                }
+            }
+
+            internalCB(link, id, name, result);
+        }
+
+        void SceneListResourceRequestor::onNameSet(const RCSRepresentation &rep, int eCode,
+            const std::string &name, const InternalSetNameCallback &internalCB,
+            SceneListResourceRequestor::wPtr ptr)
+        {
+            SceneListResourceRequestor::Ptr listPtr = ptr.lock();
+
+            if (listPtr)
+            {
+                listPtr->onNameSet_impl(std::move(rep), eCode, name, std::move(internalCB));
+            }
+        }
+
+        void SceneListResourceRequestor::onNameSet_impl(
+            const RCSRepresentation &rep, int eCode, const std::string &name,
+            const InternalSetNameCallback &internalCB)
+        {
+            int result = SCENE_CLIENT_BADREQUEST;
+            if (eCode == OC_STACK_OK)
+            {
+                if (rep.getAttributes().at(SCENE_KEY_NAME).get< std::string >() == name)
+                {
+                    result = SCENE_RESPONSE_SUCCESS;
+                }
+
+            }
+
+            internalCB(result);
+        }
+
+    }
+}
diff --git a/service/scene-manager/src/SceneListResourceRequestor.h b/service/scene-manager/src/SceneListResourceRequestor.h
new file mode 100644 (file)
index 0000000..eb7a260
--- /dev/null
@@ -0,0 +1,85 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef SM_SCENELIST_RESOURCE_REQUESTOR_H_
+#define SM_SCENELIST_RESOURCE_REQUESTOR_H_
+
+#include "SceneCommons.h"
+#include "RCSRemoteResourceObject.h"
+#include "RCSRepresentation.h"
+#include "RemoteSceneUtils.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+
+        class SceneListResourceRequestor
+            : public std::enable_shared_from_this< SceneListResourceRequestor >
+        {
+            public:
+                typedef std::shared_ptr< SceneListResourceRequestor > Ptr;
+                typedef std::weak_ptr< SceneListResourceRequestor > wPtr;
+
+                typedef std::function<
+                    void(const std::string &link, const std::string &id,
+                            const std::string &name, int eCode) >
+                    InternalCreateSceneCollectionCallback;
+
+                typedef std::function < void(int eCode) > InternalSetNameCallback;
+
+            public:
+                SceneListResourceRequestor(RCSRemoteResourceObject::Ptr listResource);
+                ~SceneListResourceRequestor() = default;
+
+                void requestSceneCollectionCreation(
+                    const std::string &name, InternalCreateSceneCollectionCallback);
+
+                void requestSetName(const std::string &, InternalSetNameCallback);
+
+                void requestGet(const std::string &, RCSRemoteResourceObject::GetCallback);
+
+                RCSRemoteResourceObject::Ptr getRemoteResourceObject() const;
+
+            private:
+                static void onSceneCollectionCreated(
+                    const RCSRepresentation &, int eCode,
+                    const std::string &name, const InternalCreateSceneCollectionCallback &,
+                    SceneListResourceRequestor::wPtr);
+
+                void onSceneCollectionCreated_impl(
+                    const RCSRepresentation &, int eCode,
+                    const std::string &name, const InternalCreateSceneCollectionCallback &);
+
+                static void onNameSet(const RCSRepresentation &, int eCode, const std::string &,
+                    const InternalSetNameCallback &, SceneListResourceRequestor::wPtr);
+
+                void onNameSet_impl(const RCSRepresentation &, int eCode, const std::string &,
+                    const InternalSetNameCallback &);
+
+            private:
+                RCSRemoteResourceObject::Ptr m_sceneListResource;
+        };
+
+    }
+}
+
+#endif /* SM_SCENELIST_RESOURCE_REQUESTOR_H_ */
+
diff --git a/service/scene-manager/src/SceneMemberResource.cpp b/service/scene-manager/src/SceneMemberResource.cpp
new file mode 100644 (file)
index 0000000..0de8d6b
--- /dev/null
@@ -0,0 +1,341 @@
+//******************************************************************
+//
+// 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 "SceneMemberResource.h"
+
+#include <atomic>
+#include "OCPlatform.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+        namespace
+        {
+            std::atomic_int g_numOfSceneMember(0);
+        }
+
+        SceneMemberResource::Ptr
+        SceneMemberResource::createSceneMemberResource(
+                RCSRemoteResourceObject::Ptr remoteObject)
+        {
+            SceneMemberResource::Ptr sceneMemberResource(new SceneMemberResource());
+
+            sceneMemberResource->m_uri = PREFIX_SCENE_MEMBER_URI + "/" +
+                std::to_string(g_numOfSceneMember++);
+
+            sceneMemberResource->m_remoteMemberObj = remoteObject;
+
+            sceneMemberResource->createResourceObject();
+            sceneMemberResource->initSetRequestHandler();
+            sceneMemberResource->setDefaultAttributes();
+
+            return sceneMemberResource;
+        }
+
+        SceneMemberResource::Ptr
+        SceneMemberResource::createSceneMemberResource(const RCSResourceAttributes & link)
+        {
+            return createSceneMemberResource(RCSResourceAttributes(link));
+        }
+
+        SceneMemberResource::Ptr
+        SceneMemberResource::createSceneMemberResource(RCSResourceAttributes && link)
+        {
+            auto href = link.at(SCENE_KEY_HREF).get<std::string>();
+
+            std::string address;
+            std::string uri;
+
+            SceneUtils::getHostUriString(href, &address, &uri);
+
+            auto ocResourcePtr
+                = OC::OCPlatform::constructResourceObject(
+                    address, uri, OCConnectivityType::CT_ADAPTER_IP, false,
+                    link.at(SCENE_KEY_RT).get<std::vector<std::string>>(),
+                    link.at(SCENE_KEY_IF).get<std::vector<std::string>>());
+
+            return createSceneMemberResource(RCSRemoteResourceObject::fromOCResource(ocResourcePtr));
+        }
+
+        void SceneMemberResource::createResourceObject()
+        {
+            m_sceneMemberResourceObj
+                = RCSResourceObject::Builder(
+                        m_uri, SCENE_MEMBER_RT, OC_RSRVD_INTERFACE_DEFAULT).
+                        setDiscoverable(true).setObservable(false).build();
+        }
+
+        void SceneMemberResource::setDefaultAttributes()
+        {
+            m_sceneMemberResourceObj->setAttribute(SCENE_KEY_ID, SceneUtils::OICGenerateUUIDStr());
+            m_sceneMemberResourceObj->setAttribute(SCENE_KEY_NAME, std::string());
+
+            RCSResourceAttributes subAtt;
+            subAtt[SCENE_KEY_HREF]
+                    = RCSResourceAttributes::Value(
+                            m_remoteMemberObj->getAddress() + m_remoteMemberObj->getUri());
+            subAtt[SCENE_KEY_IF] = RCSResourceAttributes::Value(m_remoteMemberObj->getInterfaces());
+            subAtt[SCENE_KEY_RT] = RCSResourceAttributes::Value(m_remoteMemberObj->getTypes());
+            m_sceneMemberResourceObj->setAttribute(SCENE_KEY_PAYLOAD_LINK, subAtt);
+
+            m_sceneMemberResourceObj->setAttribute(
+                    SCENE_KEY_SCENEMAPPINGS, std::vector<RCSResourceAttributes>());
+            m_sceneMemberResourceObj->setAttribute(SCENE_KEY_URI, m_uri);
+        }
+
+        void SceneMemberResource::initSetRequestHandler()
+        {
+            m_requestHandler.m_owner = std::weak_ptr<SceneMemberResource>(shared_from_this());
+            m_sceneMemberResourceObj->setSetRequestHandler(std::bind(
+                    &SceneMemberResource::SceneMemberRequestHandler::onSetRequest,
+                    m_requestHandler, std::placeholders::_1, std::placeholders::_2));
+        }
+
+        void SceneMemberResource::addMappingInfo(MappingInfo && mInfo)
+        {
+            RCSResourceAttributes newAtt;
+            {
+                RCSResourceObject::LockGuard guard(m_sceneMemberResourceObj);
+                newAtt = m_sceneMemberResourceObj->getAttributes();
+            }
+
+            auto mappingInfo = newAtt.at(SCENE_KEY_SCENEMAPPINGS).
+                    get<std::vector<RCSResourceAttributes>>();
+
+            auto foundMInfo = std::find_if(mappingInfo.begin(), mappingInfo.end(),
+                    [& mInfo](const RCSResourceAttributes & att) -> bool
+                    {
+                        return (att.at(SCENE_KEY_SCENE).get<std::string>() == mInfo.sceneName) &&
+                                (att.at(SCENE_KEY_MEMBERPROPERTY).get<std::string>() == mInfo.key);
+                    });
+
+            if (foundMInfo != mappingInfo.end())
+            {
+                mappingInfo.erase(foundMInfo);
+            }
+            RCSResourceAttributes newMapInfo;
+            newMapInfo[SCENE_KEY_SCENE] = RCSResourceAttributes::Value(std::move(mInfo.sceneName));
+            newMapInfo[SCENE_KEY_MEMBERPROPERTY] = RCSResourceAttributes::Value(std::move(mInfo.key));
+            newMapInfo[SCENE_KEY_MEMBERVALUE] = std::move(mInfo.value);
+            mappingInfo.push_back(newMapInfo);
+
+            m_sceneMemberResourceObj->setAttribute(SCENE_KEY_SCENEMAPPINGS, mappingInfo);
+        }
+
+        void SceneMemberResource::addMappingInfo(const MappingInfo & mInfo)
+        {
+            addMappingInfo(MappingInfo(mInfo));
+        }
+
+        std::vector<SceneMemberResource::MappingInfo> SceneMemberResource::getMappingInfos() const
+        {
+            std::vector<MappingInfo> retMInfo;
+
+            auto mInfo = m_sceneMemberResourceObj->getAttributeValue(SCENE_KEY_SCENEMAPPINGS).
+                    get<std::vector<RCSResourceAttributes>>();
+            std::for_each(mInfo.begin(), mInfo.end(),
+                    [& retMInfo](const RCSResourceAttributes & att)
+                    {
+                        retMInfo.push_back(MappingInfo::create(att));
+                    });
+
+            return retMInfo;
+        }
+
+        std::string SceneMemberResource::getId() const
+        {
+            return m_sceneMemberResourceObj->getAttributeValue(SCENE_KEY_ID).get<std::string>();
+        }
+
+        std::string SceneMemberResource::getFullUri() const
+        {
+            return std::string(COAP_TAG + SceneUtils::getNetAddress() + m_uri);
+        }
+
+        std::string SceneMemberResource::getTargetUri() const
+        {
+            return std::string(m_remoteMemberObj->getAddress() + m_remoteMemberObj->getUri());
+        }
+
+        RCSRemoteResourceObject::Ptr SceneMemberResource::getRemoteResourceObject() const
+        {
+            return m_remoteMemberObj;
+        }
+
+        RCSResourceObject::Ptr SceneMemberResource::getRCSResourceObject() const
+        {
+            return m_sceneMemberResourceObj;
+        }
+
+        void SceneMemberResource::execute(std::string && sceneName)
+        {
+            execute(std::move(sceneName), nullptr);
+        }
+
+        void SceneMemberResource::execute(const std::string & sceneName)
+        {
+            execute(std::string(sceneName));
+        }
+
+        void SceneMemberResource::execute(std::string && sceneName, MemberexecuteCallback executeCB)
+        {
+            RCSResourceAttributes setAtt;
+
+            auto mInfo = getMappingInfos();
+            std::for_each(mInfo.begin(), mInfo.end(),
+                    [& setAtt, & sceneName](const MappingInfo & info)
+                    {
+                        if(info.sceneName == sceneName)
+                        {
+                            setAtt[info.key] = info.value;
+                        }
+                    });
+
+            if (setAtt.empty() && executeCB != nullptr)
+            {
+                executeCB(RCSResourceAttributes(), SCENE_RESPONSE_SUCCESS);
+            }
+
+            m_remoteMemberObj->setRemoteAttributes(setAtt, executeCB);
+        }
+
+        void SceneMemberResource::execute(
+                const std::string & sceneName, MemberexecuteCallback executeCB)
+        {
+            execute(std::string(sceneName), std::move(executeCB));
+        }
+
+        void SceneMemberResource::setName(const std::string & name)
+        {
+            setName(std::string(name));
+        }
+
+        void SceneMemberResource::setName(std::string && name)
+        {
+            m_sceneMemberResourceObj->setAttribute(SCENE_KEY_NAME, std::move(name));
+        }
+
+        std::string SceneMemberResource::getName() const
+        {
+            return m_sceneMemberResourceObj->getAttributeValue(SCENE_KEY_NAME).toString();
+        }
+
+        std::vector<SceneMemberResource::MappingInfo> SceneMemberResource::findMappingInfos(
+                const std::string & sceneValue) const
+        {
+            auto mInfo = getMappingInfos();
+            std::vector<MappingInfo> retMInfo;
+
+            std::for_each(mInfo.begin(), mInfo.end(),
+                    [& retMInfo, & sceneValue](const MappingInfo & info)
+                    {
+                        if(info.sceneName == sceneValue)
+                        {
+                            retMInfo.push_back(MappingInfo(info));
+                        }
+                    });
+            return retMInfo;
+        }
+
+        bool SceneMemberResource::hasSceneValue(const std::string & sceneValue) const
+        {
+            auto mInfo = getMappingInfos();
+            if (std::find_if(mInfo.begin(), mInfo.end(),
+                    [& sceneValue](const MappingInfo & info) -> bool
+                    {
+                        return info.sceneName == sceneValue;
+                    }) != mInfo.end())
+            {
+                return true;
+            }
+            return false;
+        }
+
+        SceneMemberResource::MappingInfo
+        SceneMemberResource::MappingInfo::create(const RCSResourceAttributes & att)
+        {
+            return MappingInfo(att.at(SCENE_KEY_SCENE).get<std::string>(),
+                    att.at(SCENE_KEY_MEMBERPROPERTY).get<std::string>(),
+                    att.at(SCENE_KEY_MEMBERVALUE));
+        }
+
+        RCSSetResponse SceneMemberResource::SceneMemberRequestHandler::
+        onSetRequest(const RCSRequest & request, RCSResourceAttributes & attributes)
+        {
+            if (attributes.contains(SCENE_KEY_SCENEMAPPINGS))
+            {
+                addMappingInfos(request, attributes);
+            }
+
+            if (attributes.contains(SCENE_KEY_NAME))
+            {
+                setSceneMemberName(request, attributes);
+            }
+
+            return RCSSetResponse::create(attributes, SCENE_CLIENT_BADREQUEST).
+                    setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
+        }
+
+        RCSSetResponse
+        SceneMemberResource::SceneMemberRequestHandler::addMappingInfos(
+                const RCSRequest & /*request*/, RCSResourceAttributes & attributes)
+        {
+            int eCode = SCENE_RESPONSE_SUCCESS;
+            auto ptr = m_owner.lock();
+            if (!ptr)
+            {
+                eCode = SCENE_CLIENT_BADREQUEST;
+            }
+            else
+            {
+                auto mInfo = attributes.at(SCENE_KEY_SCENEMAPPINGS).
+                        get<std::vector<RCSResourceAttributes>>();
+                std::for_each(mInfo.begin(), mInfo.end(),
+                        [& ptr](const RCSResourceAttributes & att)
+                        {
+                            ptr->addMappingInfo(SceneMemberResource::MappingInfo::create(att));
+                        });
+            }
+
+            return RCSSetResponse::create(attributes, eCode).
+                    setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
+        }
+
+        RCSSetResponse
+        SceneMemberResource::SceneMemberRequestHandler::setSceneMemberName(
+                const RCSRequest & /*request*/, RCSResourceAttributes & attributes)
+        {
+            int eCode = SCENE_RESPONSE_SUCCESS;
+            auto ptr = m_owner.lock();
+            if (!ptr)
+            {
+                eCode = SCENE_CLIENT_BADREQUEST;
+            }
+            else
+            {
+                ptr->setName(attributes.at(SCENE_KEY_NAME).get<std::string>());
+            }
+
+            return RCSSetResponse::create(attributes, eCode).
+                    setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
+        }
+    }
+}
diff --git a/service/scene-manager/src/SceneMemberResource.h b/service/scene-manager/src/SceneMemberResource.h
new file mode 100644 (file)
index 0000000..cac6ebf
--- /dev/null
@@ -0,0 +1,213 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/**
+ * @file
+ *
+ * This file contains the declaration of classes and its members related to SceneMemberResrouceObject
+ */
+
+#ifndef SCENE_MEMBER_RESOURCE_OBJECT_H
+#define SCENE_MEMBER_RESOURCE_OBJECT_H
+
+#include "RCSResourceObject.h"
+#include "RCSRemoteResourceObject.h"
+#include "SceneCommons.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+        class SceneMemberResource
+                : public std::enable_shared_from_this<SceneMemberResource>
+        {
+        public:
+            typedef std::shared_ptr< SceneMemberResource > Ptr;
+
+            /**
+             * Callback definition to be invoked when the response of setRemoteAttribitues is received.
+             *
+             * @param attrs the result attributes
+             * @param eCode the error code received from the resource
+             *
+             * @see RCSRemoteResourceObject::setRemoteAttributes
+             */
+            typedef std::function< void(const RCSResourceAttributes & attrs, int eCode) >
+                MemberexecuteCallback;
+
+            /**
+             * A Mapping information about each scene values.
+             */
+            struct MappingInfo
+            {
+                MappingInfo(
+                        const std::string & scene,
+                        const std::string & keyName,
+                        const RCSResourceAttributes::Value & val)
+                :sceneName(scene), key(keyName), value(val) { }
+
+                MappingInfo(MappingInfo &&) = default;
+                MappingInfo(const MappingInfo &) = default;
+
+                static MappingInfo create(const RCSResourceAttributes &);
+
+                std::string sceneName;              ///< name of scene value
+                std::string key;                    ///< key to set at attributes of remote resource
+                RCSResourceAttributes::Value value; ///< val to set at attributes of remote resource
+            };
+
+            ~SceneMemberResource() = default;
+
+            /**
+             * Register a Scene member resource and return a SceneMemberResourceObject
+             * using link information of remote resource.
+             *
+             * @param attrs information to make scene member resource
+             */
+            static SceneMemberResource::Ptr
+            createSceneMemberResource(RCSResourceAttributes && attrs);
+
+            /**
+             * @overload
+             */
+            static SceneMemberResource::Ptr
+            createSceneMemberResource(const RCSResourceAttributes &);
+
+            /**
+             * Register a Scene member resource and returns a SceneMemberResourceObject
+             * using information of RCSRemoteResourceObject.
+             *
+             * @param remoteObj information to make scene member resource
+             */
+            static SceneMemberResource::Ptr
+            createSceneMemberResource(RCSRemoteResourceObject::Ptr remoteObj);
+
+            /**
+             * Add Scene mapping information at scene member resource.
+             *
+             * @param mappingInfo
+             */
+            void addMappingInfo(MappingInfo && mappingInfo);
+
+            /**
+             * @overload
+             */
+            void addMappingInfo(const MappingInfo &);
+
+            /**
+             * Returns all Mapping information of a scene member resource.
+             */
+            std::vector<MappingInfo> getMappingInfos() const;
+
+            std::vector<MappingInfo> findMappingInfos(const std::string & sceneValue) const;
+
+            bool hasSceneValue(const std::string &) const;
+
+            /**
+             * Returns ID of a Scene member resource.
+             */
+            std::string getId() const;
+
+            /**
+             * Returns Uri of a Scene member resource. (e.g. coap://192.168.0.2.1:12345/SceneMember)
+             */
+            std::string getFullUri() const;
+
+            /**
+             * Returns Uri of a Target resource of scene member. (e.g. coap://192.168.0.2.1:12345/light)
+             */
+            std::string getTargetUri() const;
+
+            /**
+             * Returns RCSRemoteResourceObject about Scene member resource
+             */
+            RCSRemoteResourceObject::Ptr getRemoteResourceObject() const;
+
+            /**
+             * Returns RCSResourceObject of Scene member resource
+             */
+            RCSResourceObject::Ptr getRCSResourceObject() const;
+
+            /**
+             * Execute of Scene Action (with callback for response).
+             *
+             * @param sceneValue scene value to execute
+             * @param cb callback to response
+             */
+            void execute(std::string && sceneValue, MemberexecuteCallback cb);
+
+            /**
+             * @overload
+             */
+            void execute(const std::string &, MemberexecuteCallback);
+
+            /**
+             * Execute of Scene Action (without callback for response).
+             *
+             * @param sceneValue scene value to execute
+             */
+            void execute(std::string && sceneValue);
+
+            /**
+             * @overload
+             */
+            void execute(const std::string &);
+
+            void setName(const std::string &);
+            void setName(std::string &&);
+
+            std::string getName() const;
+
+        private:
+            class SceneMemberRequestHandler
+            {
+            public:
+                SceneMemberRequestHandler() = default;
+                ~SceneMemberRequestHandler() = default;
+
+                std::weak_ptr<SceneMemberResource> m_owner;
+
+                RCSSetResponse onSetRequest(const RCSRequest & , RCSResourceAttributes &);
+
+                RCSSetResponse addMappingInfos(const RCSRequest & , RCSResourceAttributes &);
+                RCSSetResponse setSceneMemberName(const RCSRequest & , RCSResourceAttributes &);
+            };
+
+            std::string m_uri;
+            RCSResourceObject::Ptr m_sceneMemberResourceObj;
+            RCSRemoteResourceObject::Ptr m_remoteMemberObj;
+            SceneMemberRequestHandler m_requestHandler;
+
+            SceneMemberResource() = default;
+
+            SceneMemberResource(const SceneMemberResource &) = delete;
+            SceneMemberResource & operator = (const SceneMemberResource &) = delete;
+
+            SceneMemberResource(SceneMemberResource &&) = delete;
+            SceneMemberResource & operator = (SceneMemberResource &&) = delete;
+
+            void createResourceObject();
+            void setDefaultAttributes();
+            void initSetRequestHandler();
+        };
+    }
+}
+
+#endif // SCENE_MEMBER_RESOURCE_OBJECT_H
diff --git a/service/scene-manager/src/SceneMemberResourceRequestor.cpp b/service/scene-manager/src/SceneMemberResourceRequestor.cpp
new file mode 100644 (file)
index 0000000..3f43719
--- /dev/null
@@ -0,0 +1,149 @@
+//******************************************************************
+//
+// 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 "SceneMemberResourceRequestor.h"
+#include "RemoteSceneUtils.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+
+        SceneMemberResourceRequestor::SceneMemberResourceRequestor(
+            RCSRemoteResourceObject::Ptr memberResource, const std::string &id)
+                : m_id{ id }, m_sceneMemberResource{ memberResource }
+        {
+            SCENE_CLIENT_ASSERT_NOT_NULL(memberResource);
+        }
+
+        void SceneMemberResourceRequestor::requestSceneActionCreation(
+            const std::string &sceneName, const RCSResourceAttributes &attr,
+            InternalAddSceneActionCallback internalCB)
+        {
+            RCSResourceAttributes attributesToSet;
+            std::vector< RCSResourceAttributes > vecSceneMappings;
+
+            for (const auto &itr : attr)
+            {
+                RCSResourceAttributes sceneMappingAttrs;
+                sceneMappingAttrs[SCENE_KEY_SCENE] = sceneName;
+                sceneMappingAttrs[SCENE_KEY_MEMBERPROPERTY] = itr.key();
+                sceneMappingAttrs[SCENE_KEY_MEMBERVALUE] = itr.value();
+
+                vecSceneMappings.push_back(sceneMappingAttrs);
+            }
+
+            attributesToSet[SCENE_KEY_SCENEMAPPINGS] = vecSceneMappings;
+
+            RCSRemoteResourceObject::RemoteAttributesSetCallback setRequestCB
+                = std::bind(&SceneMemberResourceRequestor::onSceneActionCreated,
+                            std::placeholders::_1, std::placeholders::_2,
+                            sceneName, attr, std::move(internalCB),
+                            SceneMemberResourceRequestor::wPtr(shared_from_this()));
+
+            m_sceneMemberResource->setRemoteAttributes(
+                std::move(attributesToSet), std::move(setRequestCB));
+        }
+
+        void SceneMemberResourceRequestor::requestGet(
+            const std::string &ifType, RCSRemoteResourceObject::GetCallback cb)
+        {
+            RCSQueryParams params;
+            params.setResourceInterface(ifType);
+
+            m_sceneMemberResource->get(params, cb);
+        }
+
+        void SceneMemberResourceRequestor::setRemoteResourceObject(
+            RCSRemoteResourceObject::Ptr target)
+        {
+            m_remoteResource = target;
+        }
+
+        RCSRemoteResourceObject::Ptr SceneMemberResourceRequestor::getRemoteResourceObject() const
+        {
+            return m_remoteResource;
+        }
+
+        void SceneMemberResourceRequestor::onSceneActionCreated(
+            const RCSResourceAttributes &attrs, int eCode, const std::string &sceneName,
+            const RCSResourceAttributes &requestedAttrs, const InternalAddSceneActionCallback &cb,
+            SceneMemberResourceRequestor::wPtr ptr)
+        {
+            SceneMemberResourceRequestor::Ptr member = ptr.lock();
+
+            if (member)
+            {
+                member->onSceneActionCreated_impl(
+                    std::move(attrs), eCode, sceneName, std::move(requestedAttrs), std::move(cb));
+            }
+        }
+
+        void SceneMemberResourceRequestor::onSceneActionCreated_impl(
+            const RCSResourceAttributes &attrs, int eCode, const std::string &sceneName,
+            const RCSResourceAttributes &requestedAttrs,
+            const InternalAddSceneActionCallback &internalCB)
+        {
+            // TODO error code
+            int result = SCENE_CLIENT_BADREQUEST;
+
+            if (eCode == OC_STACK_OK)
+            {
+                try
+                {
+                    auto mappings
+                        = attrs.at(SCENE_KEY_SCENEMAPPINGS).get
+                          < std::vector< RCSResourceAttributes > >();
+
+                    // check if the SCENE_MAPPINGS contains requested scene action
+                    int uncreatedActionNum = requestedAttrs.size();
+                    for (const auto &itr : mappings)
+                    {
+                        if (itr.at(SCENE_KEY_SCENE).get< std::string >().compare(sceneName) == 0)
+                        {
+                            std::string key
+                                = itr.at(SCENE_KEY_MEMBERPROPERTY).get< std::string >();
+
+                            if (requestedAttrs.contains(key)
+                                && requestedAttrs.at(key) == itr.at(SCENE_KEY_MEMBERVALUE))
+                            {
+                                uncreatedActionNum--;
+                            }
+                        }
+
+                        if (uncreatedActionNum == 0)
+                        {
+                            result = SCENE_RESPONSE_SUCCESS;
+                            break;
+                        }
+                    }
+                }
+                catch (const std::exception &e)
+                {
+                    SCENE_CLIENT_PRINT_LOG(e.what());
+                    result = SCENE_SERVER_INTERNALSERVERERROR;
+                }
+            }
+
+            internalCB(result);
+        }
+
+    }
+}
\ No newline at end of file
diff --git a/service/scene-manager/src/SceneMemberResourceRequestor.h b/service/scene-manager/src/SceneMemberResourceRequestor.h
new file mode 100644 (file)
index 0000000..76c1b5e
--- /dev/null
@@ -0,0 +1,77 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef SM_SCENEMEMBER_RESOURCE_REQUESTOR_H_
+#define SM_SCENEMEMBER_RESOURCE_REQUESTOR_H_
+
+#include "SceneCommons.h"
+#include "RCSRemoteResourceObject.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+
+        class SceneMemberResourceRequestor
+            : public std::enable_shared_from_this< SceneMemberResourceRequestor >
+        {
+            public:
+                typedef std::shared_ptr< SceneMemberResourceRequestor > Ptr;
+                typedef std::weak_ptr< SceneMemberResourceRequestor > wPtr;
+
+                typedef std::function < void(int eCode) > InternalAddSceneActionCallback;
+
+            public:
+                SceneMemberResourceRequestor(RCSRemoteResourceObject::Ptr memberResource,
+                                             const std::string &id);
+                ~SceneMemberResourceRequestor() = default;
+
+                void requestSceneActionCreation(const std::string &sceneName,
+                                                const RCSResourceAttributes &attr,
+                                                InternalAddSceneActionCallback);
+
+                void requestGet(const std::string &, RCSRemoteResourceObject::GetCallback);
+
+                void setRemoteResourceObject(RCSRemoteResourceObject::Ptr);
+
+                RCSRemoteResourceObject::Ptr getRemoteResourceObject() const;
+
+            private:
+                static void onSceneActionCreated(
+                    const RCSResourceAttributes &, int eCode,
+                    const std::string &sceneName, const RCSResourceAttributes &requestedAttrs,
+                    const InternalAddSceneActionCallback &, SceneMemberResourceRequestor::wPtr);
+
+                void onSceneActionCreated_impl(
+                    const RCSResourceAttributes &, int eCode,
+                    const std::string &sceneName, const RCSResourceAttributes &requestedAttrs,
+                    const InternalAddSceneActionCallback &);
+
+            private:
+                std::string m_id;
+                RCSRemoteResourceObject::Ptr m_remoteResource;
+                RCSRemoteResourceObject::Ptr m_sceneMemberResource;
+        };
+
+    }
+}
+
+#endif /* SM_SCENEMEMBER_RESOURCE_REQUESTOR_H_ */
+
diff --git a/service/scene-manager/src/SceneUtils.cpp b/service/scene-manager/src/SceneUtils.cpp
new file mode 100644 (file)
index 0000000..27eff03
--- /dev/null
@@ -0,0 +1,131 @@
+//******************************************************************
+//
+// 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 "SceneCommons.h"
+
+#include <string>
+#include "ocrandom.h"
+#include "oic_malloc.h"
+#include "RCSException.h"
+#include "cainterface.h"
+#include "OCPlatform.h"
+
+namespace OIC
+{
+    namespace Service
+    {
+        std::string SceneUtils::OICGenerateUUIDStr()
+        {
+            uint8_t uuid[UUID_SIZE] = { 0, };
+            char uuidStr[UUID_STRING_SIZE] = { 0, };
+            if (RAND_UUID_OK == OCGenerateUuid(uuid))
+            {
+                if (RAND_UUID_OK == OCConvertUuidToString(uuid, uuidStr))
+                {
+                    return std::string(uuidStr);
+                }
+            }
+
+            throw RCSException("Failed to generate UUID");
+        }
+
+        void SceneUtils::getHostUriString(
+                const std::string address, std::string *host, std::string *uri)
+        {
+            unsigned int nextStartIndex = 0;
+            int indexOfStr = 3;
+
+            if (address.find(COAP_TAG) == std::string::npos)
+            {
+                indexOfStr = 1;
+            }
+
+            for (int i = 0; i < indexOfStr; i++)
+            {
+                nextStartIndex
+                    = address.find_first_of("/", nextStartIndex);
+                if (nextStartIndex == std::string::npos)
+                {
+                    throw RCSInvalidParameterException("address is invalid");
+                }
+                nextStartIndex += 1;
+            }
+
+            *host = address.substr(0, nextStartIndex - 1);
+            *uri = address.substr(nextStartIndex - 1, std::string::npos);
+        }
+
+        std::string SceneUtils::getNetAddress()
+        {
+            CAEndpoint_t ** netInfo = (CAEndpoint_t **)OICMalloc(sizeof(CAEndpoint_t*)*5);
+
+            if(netInfo == nullptr)
+            {
+                throw RCSException("memory allocation fail");
+            }
+
+            uint32_t size = 0;
+            CAGetNetworkInformation(netInfo, &size);
+
+            if (size == 0)
+            {
+                OICFree(netInfo);
+                throw RCSException("Disabled Network");
+            }
+
+            for (uint32_t i = 0; i < size; ++i)
+            {
+                if (netInfo[i]->adapter == CATransportAdapter_t::CA_ADAPTER_IP)
+                {
+                    std::string retAddress
+                        = std::string(netInfo[i]->addr) + ":" + std::to_string(netInfo[i]->port);
+
+                    OICFree(netInfo);
+                    return retAddress;
+                }
+            }
+
+            OICFree(netInfo);
+            throw RCSException("Not supported Network");
+        }
+
+        RCSRemoteResourceObject::Ptr SceneUtils::createRCSResourceObject(
+            const std::string &address, const OCConnectivityType ct,
+            const std::vector< std::string > &vecRT, const std::vector< std::string > &vecIF)
+        {
+            try
+            {
+                std::string hostaddress, uri;
+                SceneUtils::getHostUriString(address, &hostaddress, &uri);
+
+                OC::OCResource::Ptr pOCResource =
+                    OC::OCPlatform::constructResourceObject(
+                        hostaddress, uri, ct, false, vecRT, vecIF);
+
+                return RCSRemoteResourceObject::fromOCResource(pOCResource);
+            }
+            catch (const std::exception &e)
+            {
+                throw RCSException("Fail to create RCSResourceObject");
+            }
+        }
+
+    }
+}
diff --git a/service/scene-manager/unittests/RemoteSceneActionTest.cpp b/service/scene-manager/unittests/RemoteSceneActionTest.cpp
new file mode 100755 (executable)
index 0000000..a2cc988
--- /dev/null
@@ -0,0 +1,207 @@
+//******************************************************************
+//
+// 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 <mutex>
+#include <condition_variable>
+
+#include "RemoteSceneList.h"
+
+#include "UnitTestHelper.h"
+#include "SceneCommons.h"
+#include "SceneList.h"
+#include "RCSResourceObject.h"
+#include "RCSRemoteResourceObject.h"
+#include "OCPlatform.h"
+
+using namespace std;
+using namespace OIC::Service;
+using namespace OC;
+
+constexpr int DEFAULT_WAITTIME = 2000;
+
+constexpr char RESOURCE_URI[]{ "/a/light" };
+constexpr char RESOURCE_TYPE[]{ "core.light" };
+constexpr char KEY[]{ "power" };
+constexpr char VALUE[]{ "off" };
+
+static int lightNum = 0;
+
+RCSRemoteResourceObject::Ptr pListResource;
+RemoteSceneList::Ptr pSceneList;
+RemoteSceneCollection::Ptr pSceneCollection;
+RemoteScene::Ptr pScene;
+RemoteSceneAction::Ptr pSceneAction;
+RCSRemoteResourceObject::Ptr pLightResource;
+std::condition_variable cond;
+std::mutex g_mutex;
+
+void onRemoteSceneListCreated(RemoteSceneList::Ptr remoteSceneList, int)
+{
+    pSceneList = std::move(remoteSceneList);
+    cond.notify_all();
+}
+
+void onRemoteSceneCollectionCreated(RemoteSceneCollection::Ptr remoteSceneCol, int)
+{
+    pSceneCollection = remoteSceneCol;
+    cond.notify_all();
+}
+
+void onRemoteSceneCreated(RemoteScene::Ptr remoteScene, int)
+{
+    pScene = remoteScene;
+    cond.notify_all();
+}
+
+void onRemoteSceneActionCreated(RemoteSceneAction::Ptr remoteSceneAction, int)
+{
+    pSceneAction = remoteSceneAction;
+    cond.notify_all();
+}
+
+void onActionUpdated(int)
+{
+    cond.notify_all();
+}
+void createListServer()
+{
+    std::vector< std::string > vecRT{ SCENE_LIST_RT };
+    std::vector< std::string > vecIF{ OC_RSRVD_INTERFACE_DEFAULT, OC::BATCH_INTERFACE };
+
+    pListResource = SceneUtils::createRCSResourceObject(
+        "coap://" + SceneUtils::getNetAddress() + SCENE_LIST_URI,
+        SCENE_CONNECTIVITY, vecRT, vecIF);
+}
+
+void waitForCallback(int waitingTime = DEFAULT_WAITTIME)
+{
+    std::unique_lock< std::mutex > lock{ g_mutex };
+    cond.wait_for(lock, std::chrono::milliseconds{ waitingTime });
+}
+
+void setup()
+{
+    SceneList::getInstance()->getName();
+    createListServer();
+
+    RemoteSceneList::createInstance(pListResource, onRemoteSceneListCreated);
+
+    waitForCallback();
+
+    pSceneList->addNewSceneCollection(onRemoteSceneCollectionCreated);
+
+    waitForCallback();
+
+    pSceneCollection->addNewScene("Test Scene", onRemoteSceneCreated);
+
+    waitForCallback();
+}
+
+
+class RemoteSceneActionTest : public TestWithMock
+{
+protected:
+    void SetUp()
+    {
+        TestWithMock::SetUp();
+    }
+
+    void createLightServer()
+    {
+        RCSResourceObject::Ptr pResource = RCSResourceObject::Builder(
+            RESOURCE_URI, RESOURCE_TYPE, DEFAULT_INTERFACE).build();
+        pResource->setAttribute(KEY, RCSResourceAttributes::Value(VALUE));
+
+        pLightResource
+            = SceneUtils::createRCSResourceObject(
+            "coap://" + SceneUtils::getNetAddress() + RESOURCE_URI
+            + "/" + std::to_string(lightNum++),
+            SCENE_CONNECTIVITY, pResource->getTypes(), pResource->getInterfaces());
+    }
+};
+
+TEST_F(RemoteSceneActionTest, createSceneAction)
+{
+    setup();
+    createLightServer();
+
+    pScene->addNewSceneAction(pLightResource, KEY, RCSResourceAttributes::Value(VALUE),
+        onRemoteSceneActionCreated);
+
+    waitForCallback();
+
+    ASSERT_NE(nullptr, pSceneAction);
+}
+
+TEST_F(RemoteSceneActionTest, createSceneActionWithEmptyRCSRemoteResourceObjectPtr)
+{
+    ASSERT_THROW(pScene->addNewSceneAction(nullptr, KEY, RCSResourceAttributes::Value(VALUE),
+        onRemoteSceneActionCreated), RCSInvalidParameterException);
+}
+
+TEST_F(RemoteSceneActionTest, getAllRemoteSceneActions)
+{
+    setup();
+    createLightServer();
+
+    pScene->addNewSceneAction(pLightResource, KEY, RCSResourceAttributes::Value(VALUE),
+        onRemoteSceneActionCreated);
+
+    waitForCallback();
+
+    vector< RemoteSceneAction::Ptr > actions
+        = pScene->getRemoteSceneActions();
+
+    ASSERT_EQ((unsigned int)1, actions.size());
+    ASSERT_TRUE(actions.at(0)->getExecutionParameter().contains(KEY));
+    ASSERT_EQ(VALUE, actions.at(0)->getExecutionParameter().at(KEY).get< string >());
+}
+
+TEST_F(RemoteSceneActionTest, getRemoteSceneAction)
+{
+    createLightServer();
+
+    pScene->addNewSceneAction(pLightResource, KEY, RCSResourceAttributes::Value(VALUE),
+        onRemoteSceneActionCreated);
+
+    waitForCallback();
+
+    RemoteSceneAction::Ptr action = pScene->getRemoteSceneAction(pLightResource);
+
+    ASSERT_TRUE(action->getExecutionParameter().contains(KEY));
+    ASSERT_EQ(VALUE, action->getExecutionParameter().at(KEY).get< string >());
+}
+
+TEST_F(RemoteSceneActionTest, updateSceneAction)
+{
+    createLightServer();
+
+    pScene->addNewSceneAction(pLightResource, KEY, RCSResourceAttributes::Value(VALUE),
+        onRemoteSceneActionCreated);
+
+    waitForCallback();
+
+    pSceneAction->resetExecutionParameter(
+        KEY, RCSResourceAttributes::Value("on"), onActionUpdated);
+
+    waitForCallback();
+
+    ASSERT_EQ("on", pSceneAction->getExecutionParameter().at(KEY).get< string >());
+}
diff --git a/service/scene-manager/unittests/RemoteSceneCollectionTest.cpp b/service/scene-manager/unittests/RemoteSceneCollectionTest.cpp
new file mode 100644 (file)
index 0000000..bcc0888
--- /dev/null
@@ -0,0 +1,165 @@
+//******************************************************************
+//
+// 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 <mutex>
+#include <condition_variable>
+
+#include "RemoteSceneList.h"
+
+#include "UnitTestHelper.h"
+#include "SceneCommons.h"
+#include "SceneList.h"
+#include "RCSResourceObject.h"
+#include "RCSRemoteResourceObject.h"
+#include "OCPlatform.h"
+
+using namespace std;
+using namespace OIC::Service;
+using namespace OC;
+
+constexpr int DEFAULT_WAITTIME = 2000;
+
+class RemoteSceneCollectionTest : public TestWithMock
+{
+protected:
+    void SetUp()
+    {
+        TestWithMock::SetUp();
+
+        SceneList::getInstance()->getName();
+        createListServer();
+
+        RemoteSceneList::createInstance(pListResource, std::bind(
+            &RemoteSceneCollectionTest::onRemoteSceneListCreated, this,
+            placeholders::_1, placeholders::_2));
+
+        waitForCallback();
+    }
+
+    void createListServer()
+    {
+        std::vector< std::string > vecRT{ SCENE_LIST_RT };
+        std::vector< std::string > vecIF{ OC_RSRVD_INTERFACE_DEFAULT, OC::BATCH_INTERFACE };
+
+        pListResource = SceneUtils::createRCSResourceObject(
+            "coap://" + SceneUtils::getNetAddress() + SCENE_LIST_URI,
+            SCENE_CONNECTIVITY, vecRT, vecIF);
+    }
+
+    void waitForCallback(int waitingTime = DEFAULT_WAITTIME)
+    {
+        std::unique_lock< std::mutex > lock{ mutex };
+        cond.wait_for(lock, std::chrono::milliseconds{ waitingTime });
+    }
+
+public:
+    RCSRemoteResourceObject::Ptr pListResource;
+    RemoteSceneList::Ptr pSceneList;
+    RemoteSceneCollection::Ptr pSceneCollection;
+    std::condition_variable cond;
+    std::mutex mutex;
+
+    void onRemoteSceneListCreated(RemoteSceneList::Ptr remoteSceneList, int)
+    {
+        pSceneList = std::move(remoteSceneList);
+        cond.notify_all();
+    }
+
+    void onRemoteSceneCollectionCreated(RemoteSceneCollection::Ptr remoteSceneCol, int)
+    {
+        pSceneCollection = remoteSceneCol;
+        cond.notify_all();
+    }
+
+    void onRemoteSceneCreated(RemoteScene::Ptr, int)
+    {
+        cond.notify_all();
+    }
+
+    void onSetName(int)
+    {
+        cond.notify_all();
+    }
+};
+
+TEST_F(RemoteSceneCollectionTest, addNewRemoteSceneCollection)
+{
+    pSceneList->addNewSceneCollection(std::bind(
+        &RemoteSceneCollectionTest::onRemoteSceneCollectionCreated, this,
+        placeholders::_1, placeholders::_2));
+
+    waitForCallback();
+
+    pSceneCollection->addNewScene("Default", std::bind(
+        &RemoteSceneCollectionTest::onRemoteSceneCreated, this,
+        placeholders::_1, placeholders::_2));
+
+    waitForCallback();
+
+    EXPECT_NE(nullptr, pSceneCollection);
+}
+
+TEST_F(RemoteSceneCollectionTest, getRemoteSceneCollectionList)
+{
+    std::vector< RemoteSceneCollection::Ptr > sceneCollections
+        = pSceneList->getRemoteSceneCollections();
+
+    bool getCollectionsOK = true;
+
+    if (!sceneCollections.empty())
+    {
+        for (const auto &it : sceneCollections)
+        {
+            if (it->getId() == "")
+            {
+                getCollectionsOK = false;
+                break;
+            }
+        }
+    }
+    else
+    {
+        getCollectionsOK = false;
+    }
+
+    ASSERT_TRUE(getCollectionsOK);
+}
+
+TEST_F(RemoteSceneCollectionTest, setAndGetSceneCollectionName)
+{
+    pSceneList->addNewSceneCollection(std::bind(
+        &RemoteSceneCollectionTest::onRemoteSceneCollectionCreated, this,
+        placeholders::_1, placeholders::_2));
+
+    waitForCallback();
+
+    pSceneCollection->addNewScene("Default", std::bind(
+        &RemoteSceneCollectionTest::onRemoteSceneCreated, this,
+        placeholders::_1, placeholders::_2));
+
+    waitForCallback();
+
+    pSceneCollection->setName("Kitchen", std::bind(
+        &RemoteSceneCollectionTest::onSetName, this, placeholders::_1));
+
+    waitForCallback();
+
+    EXPECT_EQ("Kitchen", pSceneCollection->getName());
+}
\ No newline at end of file
diff --git a/service/scene-manager/unittests/RemoteSceneListTest.cpp b/service/scene-manager/unittests/RemoteSceneListTest.cpp
new file mode 100644 (file)
index 0000000..b2575b7
--- /dev/null
@@ -0,0 +1,106 @@
+//******************************************************************
+//
+// 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 <mutex>
+#include <condition_variable>
+
+#include "RemoteSceneList.h"
+
+#include "UnitTestHelper.h"
+#include "SceneCommons.h"
+#include "SceneList.h"
+#include "RCSRemoteResourceObject.h"
+#include "OCPlatform.h"
+
+using namespace std;
+using namespace OIC::Service;
+using namespace OC;
+
+constexpr int DEFAULT_WAITTIME = 2000;
+
+class RemoteSceneListTest : public TestWithMock
+{
+protected:
+    void SetUp()
+    {
+        TestWithMock::SetUp();
+        SceneList::getInstance()->getName();
+    }
+
+    void createListServer()
+    {
+        std::vector< std::string > vecRT{ SCENE_LIST_RT };
+        std::vector< std::string > vecIF{ OC_RSRVD_INTERFACE_DEFAULT, OC::BATCH_INTERFACE };
+
+        pListResource = SceneUtils::createRCSResourceObject(
+                            "coap://" + SceneUtils::getNetAddress() + SCENE_LIST_URI,
+                            SCENE_CONNECTIVITY, vecRT, vecIF);
+    }
+
+    void waitForCallback(int waitingTime = DEFAULT_WAITTIME)
+    {
+        std::unique_lock< std::mutex > lock{ mutex };
+        cond.wait_for(lock, std::chrono::milliseconds{ waitingTime });
+    }
+
+public:
+    RCSRemoteResourceObject::Ptr pListResource;
+    RemoteSceneList::Ptr pSceneList;
+    std::condition_variable cond;
+    std::mutex mutex;
+
+    void onRemoteSceneListCreated(RemoteSceneList::Ptr remoteSceneList, int)
+    {
+        pSceneList = std::move(remoteSceneList);
+        cond.notify_all();
+    }
+
+    void onSetName(int)
+    {
+        cond.notify_all();
+    }
+};
+
+TEST_F(RemoteSceneListTest, createRemoteSceneListInstance)
+{
+    createListServer();
+    RemoteSceneList::createInstance(pListResource, std::bind(
+        &RemoteSceneListTest::onRemoteSceneListCreated, this, placeholders::_1, placeholders::_2));
+
+    waitForCallback();
+
+    EXPECT_NE(nullptr, pSceneList);
+}
+
+TEST_F(RemoteSceneListTest, setAndGetRemoteSceneListName)
+{
+    createListServer();
+    RemoteSceneList::createInstance(pListResource, std::bind(
+        &RemoteSceneListTest::onRemoteSceneListCreated, this, placeholders::_1, placeholders::_2));
+
+    waitForCallback();
+
+    pSceneList->setName("Test Scene List", std::bind(
+        &RemoteSceneListTest::onSetName, this, placeholders::_1));
+
+    waitForCallback();
+
+    EXPECT_EQ("Test Scene List", pSceneList->getName());
+}
\ No newline at end of file
diff --git a/service/scene-manager/unittests/RemoteSceneTest.cpp b/service/scene-manager/unittests/RemoteSceneTest.cpp
new file mode 100644 (file)
index 0000000..c51ed61
--- /dev/null
@@ -0,0 +1,209 @@
+//******************************************************************
+//
+// 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 <mutex>
+#include <condition_variable>
+
+#include "RemoteSceneList.h"
+
+#include "UnitTestHelper.h"
+#include "SceneCommons.h"
+#include "SceneList.h"
+#include "RCSResourceObject.h"
+#include "RCSRemoteResourceObject.h"
+#include "OCPlatform.h"
+
+using namespace std;
+using namespace OIC::Service;
+using namespace OC;
+
+constexpr int DEFAULT_WAITTIME = 2000;
+
+constexpr char RESOURCE_URI[]{ "/a/light" };
+constexpr char RESOURCE_TYPE[]{ "core.light" };
+constexpr char KEY[]{ "power" };
+constexpr char VALUE[]{ "off" };
+
+static int lightNum = 0;
+
+class RemoteSceneTest : public TestWithMock
+{
+protected:
+    void SetUp()
+    {
+        TestWithMock::SetUp();
+        executionSucceeded = false;
+
+        SceneList::getInstance()->getName();
+        createListServer();
+
+        RemoteSceneList::createInstance(pListResource, std::bind(
+            &RemoteSceneTest::onRemoteSceneListCreated, this,
+            placeholders::_1, placeholders::_2));
+
+        waitForCallback();
+
+        pSceneList->addNewSceneCollection(std::bind(
+            &RemoteSceneTest::onRemoteSceneCollectionCreated, this,
+            placeholders::_1, placeholders::_2));
+
+        waitForCallback();
+
+        pSceneCollection->addNewScene("Default", std::bind(
+            &RemoteSceneTest::onRemoteSceneCreated, this,
+            placeholders::_1, placeholders::_2));
+
+        waitForCallback();
+    }
+
+    void createListServer()
+    {
+        std::vector< std::string > vecRT{ SCENE_LIST_RT };
+        std::vector< std::string > vecIF{ OC_RSRVD_INTERFACE_DEFAULT, OC::BATCH_INTERFACE };
+
+        pListResource = SceneUtils::createRCSResourceObject(
+            "coap://" + SceneUtils::getNetAddress() + SCENE_LIST_URI,
+            SCENE_CONNECTIVITY, vecRT, vecIF);
+    }
+
+    void createLightServer()
+    {
+        RCSResourceObject::Ptr pResource = RCSResourceObject::Builder(
+            RESOURCE_URI, RESOURCE_TYPE, DEFAULT_INTERFACE).build();
+        pResource->setAttribute(KEY, RCSResourceAttributes::Value(VALUE));
+
+        pLightResource
+            = SceneUtils::createRCSResourceObject(
+            "coap://" + SceneUtils::getNetAddress() + RESOURCE_URI
+            + "/" + std::to_string(lightNum++),
+            SCENE_CONNECTIVITY, pResource->getTypes(), pResource->getInterfaces());
+    }
+
+    void waitForCallback(int waitingTime = DEFAULT_WAITTIME)
+    {
+        std::unique_lock< std::mutex > lock{ mutex };
+        cond.wait_for(lock, std::chrono::milliseconds{ waitingTime });
+    }
+
+public:
+    RCSRemoteResourceObject::Ptr pListResource;
+    RemoteSceneList::Ptr pSceneList;
+    RemoteSceneCollection::Ptr pSceneCollection;
+    RemoteScene::Ptr pScene;
+    RCSRemoteResourceObject::Ptr pLightResource;
+    bool executionSucceeded;
+    std::condition_variable cond;
+    std::mutex mutex;
+
+    void onRemoteSceneListCreated(RemoteSceneList::Ptr remoteSceneList, int)
+    {
+        pSceneList = std::move(remoteSceneList);
+        cond.notify_all();
+    }
+
+    void onRemoteSceneCollectionCreated(RemoteSceneCollection::Ptr remoteSceneCol, int)
+    {
+        pSceneCollection = remoteSceneCol;
+        cond.notify_all();
+    }
+
+    void onRemoteSceneCreated(RemoteScene::Ptr remoteScene, int)
+    {
+        pScene = remoteScene;
+        cond.notify_all();
+    }
+
+    void onRemoteSceneActionCreated(RemoteSceneAction::Ptr, int)
+    {
+        cond.notify_all();
+    }
+
+    void onRemoteSceneExecuted(string, int)
+    {
+        executionSucceeded = true;
+        cond.notify_all();
+    }
+};
+
+TEST_F(RemoteSceneTest, addNewRemoteScene)
+{
+    pSceneCollection->addNewScene("Test Scene", std::bind(
+        &RemoteSceneTest::onRemoteSceneCreated, this,
+        placeholders::_1, placeholders::_2));
+
+    waitForCallback();
+
+    ASSERT_NE(nullptr, pScene);
+    ASSERT_EQ("Test Scene", pScene->getName());
+}
+
+TEST_F(RemoteSceneTest, createNewRemoteSceneWithEmptyName)
+{
+    ASSERT_THROW(
+        pSceneCollection->addNewScene("", std::bind(
+        &RemoteSceneTest::onRemoteSceneCreated, this,
+        placeholders::_1, placeholders::_2));, RCSInvalidParameterException);
+}
+
+TEST_F(RemoteSceneTest, getRemoteSceneBySceneName)
+{
+    pSceneCollection->addNewScene("Test Scene", std::bind(
+        &RemoteSceneTest::onRemoteSceneCreated, this,
+        placeholders::_1, placeholders::_2));
+
+    waitForCallback();
+
+    auto scene = pSceneCollection->getRemoteScene("Test Scene");
+
+    EXPECT_NE(nullptr, scene);
+    EXPECT_EQ("Test Scene", scene->getName());
+}
+
+TEST_F(RemoteSceneTest, getAllRemoteScenes)
+{
+    pSceneCollection->addNewScene("Test Scene", std::bind(
+        &RemoteSceneTest::onRemoteSceneCreated, this,
+        placeholders::_1, placeholders::_2));
+
+    waitForCallback();
+
+    auto scenes = pSceneCollection->getRemoteScenes();
+
+    ASSERT_EQ((unsigned int)2, scenes.size());
+    ASSERT_NE(scenes.end(), scenes.find("Test Scene"));
+}
+
+TEST_F(RemoteSceneTest, executeRemoteScene)
+{
+    createLightServer();
+
+    pScene->addNewSceneAction(pLightResource, KEY, RCSResourceAttributes::Value(VALUE),
+        std::bind(&RemoteSceneTest::onRemoteSceneActionCreated, this,
+        placeholders::_1, placeholders::_2));
+
+    waitForCallback();
+
+    pScene->execute(std::bind(
+        &RemoteSceneTest::onRemoteSceneExecuted, this, placeholders::_1, placeholders::_2));
+
+    waitForCallback();
+
+    ASSERT_TRUE(executionSucceeded);
+}
\ No newline at end of file
diff --git a/service/scene-manager/unittests/SConscript b/service/scene-manager/unittests/SConscript
new file mode 100755 (executable)
index 0000000..25d65d8
--- /dev/null
@@ -0,0 +1,132 @@
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+##
+# SceneManager Unit Test build script
+##
+
+Import('env')
+
+if env.get('RELEASE'):
+    env.AppendUnique(CCFLAGS = ['-Os'])
+    env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+else:
+    env.AppendUnique(CCFLAGS = ['-g'])
+
+if env.get('LOGGING'):
+    env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+
+######################################################################
+#unit test setting
+######################################################################
+src_dir = lib_env.get('SRC_DIR')
+gtest_dir = src_dir + '/extlibs/gtest/gtest-1.7.0'
+
+scene_test_env = lib_env.Clone()
+target_os = env.get('TARGET_OS')
+
+######################################################################
+# Build flags
+######################################################################
+GTest = File(gtest_dir + '/lib/.libs/libgtest.a')
+GTest_Main = File(gtest_dir + '/lib/.libs/libgtest_main.a')
+
+#scene_test_env.AppendUnique(LIBPATH = [gtest_dir + '/lib/.libs'])
+scene_test_env.AppendUnique(LIBPATH = [lib_env.get('BUILD_DIR')])
+scene_test_env.AppendUnique(LIBS = [
+    'scene_manager', 'rcs_server', 'rcs_client','rcs_common',
+    'oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap',
+    GTest_Main, GTest])
+
+if target_os not in ['windows', 'winrt']:
+    scene_test_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
+
+if target_os == 'linux':
+    scene_test_env.AppendUnique(CXXFLAGS = ['-pthread'])
+    scene_test_env.AppendUnique(LIBS = ['pthread'])
+
+if not env.get('RELEASE'):
+    scene_test_env.PrependUnique(LIBS = ['gcov'])
+    scene_test_env.AppendUnique(CXXFLAGS = ['--coverage'])
+
+scene_test_env.PrependUnique(CPPPATH = [ src_dir + '/extlibs/hippomocks-master',
+                             gtest_dir + '/include'])
+scene_test_env.AppendUnique(CPPPATH = ['../include'])
+scene_test_env.AppendUnique(CPPPATH = ['../src'])
+scene_test_env.AppendUnique(CPPPATH = ['../../resource-encapsulation/include'])
+scene_test_env.AppendUnique(CPPPATH = ['../../resource-encapsulation/src/common/primitiveResource/include'])
+scene_test_env.AppendUnique(CPPPATH = ['../../resource-encapsulation/src/common/utils/include'])
+######################################################################
+# Build Test
+######################################################################
+
+scene_list_test_src = env.Glob('./SceneListTest.cpp')
+scene_list_test = scene_test_env.Program('scene_list_test', scene_list_test_src)
+Alias("scene_list_test", scene_list_test)
+env.AppendTarget('scene_list_test')
+scene_test_env.InstallTarget(scene_list_test, 'scene_list_test')
+
+scene_collection_test_src = env.Glob('./SceneCollectionTest.cpp')
+scene_collection_test = scene_test_env.Program('scene_collection_test', scene_collection_test_src)
+Alias("scene_collection_test", scene_collection_test)
+env.AppendTarget('scene_collection_test')
+scene_test_env.InstallTarget(scene_collection_test, 'scene_collection_test')
+
+scene_test_src = env.Glob('./SceneTest.cpp')
+scene_test = scene_test_env.Program('scene_test', scene_test_src)
+Alias("scene_test", scene_test)
+env.AppendTarget('scene_test')
+scene_test_env.InstallTarget(scene_test, 'scene_test')
+
+scene_action_test_src = env.Glob('./SceneActionTest.cpp')
+scene_action_test = scene_test_env.Program('scene_action_test', scene_action_test_src)
+Alias("scene_action_test", scene_action_test)
+env.AppendTarget('scene_action_test')
+scene_test_env.InstallTarget(scene_action_test, 'scene_action_test')
+
+remote_scene_list_test_src = env.Glob('./RemoteSceneListTest.cpp')
+remote_scene_list_test = scene_test_env.Program('remote_scene_list_test', remote_scene_list_test_src)
+Alias("remote_scene_list_test", remote_scene_list_test)
+env.AppendTarget('remote_scene_list_test')
+
+remote_scene_col_test_src = env.Glob('./RemoteSceneCollectionTest.cpp')
+remote_scene_col_test = scene_test_env.Program('remote_scene_col_test', remote_scene_col_test_src)
+Alias("remote_scene_col_test", remote_scene_col_test)
+env.AppendTarget('remote_scene_col_test')
+
+remote_scene_test_src = env.Glob('./RemoteSceneTest.cpp')
+remote_scene_test = scene_test_env.Program('remote_scene_test', remote_scene_test_src)
+Alias("remote_scene_test", remote_scene_test)
+env.AppendTarget('remote_scene_test')
+
+remote_scene_action_test_src = env.Glob('./RemoteSceneActionTest.cpp')
+remote_scene_action_test = scene_test_env.Program('remote_scene_action_test', remote_scene_action_test_src)
+Alias("remote_scene_action_test", remote_scene_action_test)
+env.AppendTarget('remote_scene_action_test')
+
+#target_os = env.get('TARGET_OS')
+#if target_os == 'linux':
+#        from tools.scons.RunTest import *
+#        run_test(scene_test_env,
+#                 '',
+#                 'service/scene-manager/unittest/scene_test')
\ No newline at end of file
diff --git a/service/scene-manager/unittests/SceneActionTest.cpp b/service/scene-manager/unittests/SceneActionTest.cpp
new file mode 100755 (executable)
index 0000000..33dcc8e
--- /dev/null
@@ -0,0 +1,160 @@
+//******************************************************************
+//
+// 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 <condition_variable>
+#include "UnitTestHelper.h"
+
+#include "SceneList.h"
+#include "RCSResourceObject.h"
+#include "RCSRemoteResourceObject.h"
+#include "SceneCommons.h"
+#include "OCPlatform.h"
+
+using namespace std;
+using namespace OIC::Service;
+using namespace OC;
+
+typedef std::function<void (int)> ExecuteCallback;
+
+constexpr char RESOURCE_URI[]{ "/a/light" };
+constexpr char RESOURCE_TYPE[]{ "core.light" };
+constexpr char RESOURCE_URI2[]{ "/a/fan" };
+constexpr char RESOURCE_TYPE2[]{ "core.fan" };
+constexpr char KEY[]{ "power" };
+constexpr char VALUE[]{ "on" };
+constexpr char KEY_2[]{ "state" };
+constexpr char VALUE_2[]{ "100" };
+
+class SceneActionTest: public TestWithMock
+{
+protected:
+    void SetUp()
+    {
+        TestWithMock::SetUp();
+        pSceneList = SceneList::getInstance();
+    }
+
+    void createServer(const std::string& resourceUri1, const std::string& resourceUri2)
+    {
+        auto pResource1 = RCSResourceObject::Builder(
+                resourceUri1, RESOURCE_TYPE, DEFAULT_INTERFACE).build();
+        pResource1->setAttribute(KEY, VALUE);
+
+        auto ocResourcePtr = OC::OCPlatform::constructResourceObject(
+                "coap://" + SceneUtils::getNetAddress(), resourceUri1,
+                OCConnectivityType::CT_ADAPTER_IP, false,
+                pResource1->getTypes(), pResource1->getInterfaces());
+        pRemoteResource1 = RCSRemoteResourceObject::fromOCResource(ocResourcePtr);
+
+        auto pResource2 = RCSResourceObject::Builder(
+                resourceUri2, RESOURCE_TYPE2, DEFAULT_INTERFACE).build();
+        pResource2->setAttribute(KEY_2, VALUE_2);
+
+        ocResourcePtr = OC::OCPlatform::constructResourceObject(
+                        "coap://" + SceneUtils::getNetAddress(), resourceUri2,
+                        OCConnectivityType::CT_ADAPTER_IP, false,
+                        pResource2->getTypes(), pResource2->getInterfaces());
+        pRemoteResource2 = RCSRemoteResourceObject::fromOCResource(ocResourcePtr);
+    }
+
+    void createSceneCollectionAndScene()
+    {
+        auto pSceneCollection = pSceneList->addNewSceneCollection();
+        pScene1 = pSceneCollection->addNewScene("SceneTestName_1");
+    }
+
+    void createSceneAction()
+    {
+        pSceneAction1 = pScene1->addNewSceneAction(pRemoteResource1, KEY, VALUE);
+        pSceneAction2 = pScene1->addNewSceneAction(pRemoteResource2, KEY_2, VALUE_2);
+    }
+
+public:
+    SceneList* pSceneList;
+    shared_ptr<Scene> pScene1;
+    shared_ptr<Scene> pScene2;
+    shared_ptr<SceneAction> pSceneAction1;
+    shared_ptr<SceneAction> pSceneAction2;
+    RCSRemoteResourceObject::Ptr pRemoteResource1;
+    RCSRemoteResourceObject::Ptr pRemoteResource2;
+
+private:
+    std::condition_variable cond;
+    std::mutex mutex;
+};
+
+TEST_F(SceneActionTest, createSceneActionByEmptyRCSRemoteResourceObjectPtr)
+{
+    createServer("/a/testuri1_1", "/a/testuri1_2");
+    createSceneCollectionAndScene();
+    ASSERT_THROW(pScene1->addNewSceneAction(
+            nullptr, KEY, VALUE), RCSInvalidParameterException);
+}
+
+TEST_F(SceneActionTest, createSceneActionByAlreadyExistedRCSRemoteResourceObjectPtr)
+{
+    createServer("/a/testuri2_1", "/a/testuri2_2");
+    createSceneCollectionAndScene();
+    createSceneAction();
+    ASSERT_THROW(pScene1->addNewSceneAction(
+            pRemoteResource1, KEY, "off"), RCSBadRequestException);
+}
+
+TEST_F(SceneActionTest, getSceneActionInstance)
+{
+    createServer("/a/testuri3_1", "/a/testuri3_2");
+    createSceneCollectionAndScene();
+    createSceneAction();
+
+    for(const auto &it : pSceneAction1->getExecutionParameter())
+    {
+        ASSERT_EQ(it.key(), KEY);
+        ASSERT_EQ(it.value(), VALUE);
+    }
+
+    for(const auto &it: pSceneAction2->getExecutionParameter())
+    {
+        ASSERT_EQ(it.key(), KEY_2);
+        ASSERT_EQ(it.value(), VALUE_2);
+    }
+}
+
+TEST_F(SceneActionTest, updateSceneAction)
+{
+    createServer("/a/testuri4_1", "/a/testuri4_2");
+    createSceneCollectionAndScene();
+    createSceneAction();
+
+    pSceneAction1->resetExecutionParameter(KEY, "off");
+    for(const auto &it : pSceneAction1->getExecutionParameter())
+    {
+        ASSERT_EQ(it.key(), KEY);
+        ASSERT_EQ(it.value(), "off");
+    }
+}
+
+TEST_F(SceneActionTest, getRemoteResourceObject)
+{
+    createServer("/a/testuri5_1", "/a/testuri5_2");
+    createSceneCollectionAndScene();
+    createSceneAction();
+
+    ASSERT_EQ(pSceneAction1->getRemoteResourceObject(), pRemoteResource1);
+}
diff --git a/service/scene-manager/unittests/SceneCollectionTest.cpp b/service/scene-manager/unittests/SceneCollectionTest.cpp
new file mode 100755 (executable)
index 0000000..7c73246
--- /dev/null
@@ -0,0 +1,79 @@
+//******************************************************************
+//
+// 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 "UnitTestHelper.h"
+
+#include "SceneList.h"
+#include "OCPlatform.h"
+
+using namespace std;
+using namespace OIC::Service;
+using namespace OC;
+
+class SceneCollectionTest: public TestWithMock
+{
+protected:
+    void SetUp()
+    {
+        TestWithMock::SetUp();
+        pSceneList = SceneList::getInstance();
+    }
+
+public:
+    SceneList* pSceneList;
+    std::shared_ptr<SceneCollection> pSceneCollection;
+};
+
+TEST_F(SceneCollectionTest, createSceneCollectionInstanceAndSceneCollectionResource)
+{
+    bool isNullPtr = false;
+    pSceneCollection = pSceneList->addNewSceneCollection();
+
+    if(pSceneCollection->getId() == "")
+    {
+        isNullPtr = true;
+    }
+
+    EXPECT_FALSE(isNullPtr);
+}
+
+TEST_F(SceneCollectionTest, getSceneCollectionInstanceAndSceneCollectionResource)
+{
+    auto sceneCollections = pSceneList->getSceneCollections();
+    bool isNullPtr = false;
+
+    for(const auto &it : sceneCollections)
+    {
+        if(it->getId() == "")
+        {
+            isNullPtr = true;
+        }
+        ASSERT_FALSE(isNullPtr);
+    }
+}
+
+TEST_F(SceneCollectionTest, setAndGetSceneCollectionResourceName)
+{
+    pSceneCollection = pSceneList->addNewSceneCollection();
+    pSceneCollection->setName("Kitchen");
+    auto sceneCollectionName = pSceneCollection->getName();
+
+    EXPECT_EQ("Kitchen", sceneCollectionName);
+}
diff --git a/service/scene-manager/unittests/SceneListTest.cpp b/service/scene-manager/unittests/SceneListTest.cpp
new file mode 100755 (executable)
index 0000000..36cb9a9
--- /dev/null
@@ -0,0 +1,49 @@
+//******************************************************************
+//
+// 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 "UnitTestHelper.h"
+
+#include "SceneList.h"
+
+using namespace std;
+using namespace OIC::Service;
+using namespace OC;
+
+class SceneListTest: public TestWithMock
+{
+protected:
+    void SetUp()
+    {
+        TestWithMock::SetUp();
+    }
+};
+
+TEST_F(SceneListTest, sceneListInstance)
+{
+    EXPECT_EQ(SceneList::getInstance(), SceneList::getInstance());
+}
+
+TEST_F(SceneListTest, setAndGetSceneListResourceName)
+{
+    SceneList::getInstance()->setName("House");
+    auto sceneListName = SceneList::getInstance()->getName();
+
+    EXPECT_EQ("House", sceneListName);
+}
diff --git a/service/scene-manager/unittests/SceneTest.cpp b/service/scene-manager/unittests/SceneTest.cpp
new file mode 100755 (executable)
index 0000000..fc1ec4c
--- /dev/null
@@ -0,0 +1,200 @@
+//******************************************************************
+//
+// 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 "UnitTestHelper.h"
+
+#include "SceneList.h"
+
+#include "RCSResourceObject.h"
+#include "RCSRemoteResourceObject.h"
+#include "SceneCommons.h"
+#include "OCPlatform.h"
+
+#include <condition_variable>
+#include <mutex>
+#include <iostream>
+
+using namespace std;
+using namespace OIC::Service;
+using namespace OC;
+
+typedef std::function<void (int)> ExecuteCallback;
+
+constexpr char RESOURCE_URI[]{ "/a/light" };
+constexpr char RESOURCE_TYPE[]{ "core.light" };
+constexpr char RESOURCE_URI2[]{ "/a/fan" };
+constexpr char RESOURCE_TYPE2[]{ "core.fan" };
+constexpr char KEY[]{ "power" };
+constexpr char VALUE[]{ "off" };
+constexpr char KEY_2[]{ "state" };
+constexpr char VALUE_2[]{ "100" };
+
+class SceneTest: public TestWithMock
+{
+protected:
+    void SetUp()
+    {
+        TestWithMock::SetUp();
+        pSceneList = SceneList::getInstance();
+    }
+    void waitForCb(int watingTime)
+    {
+        std::unique_lock< std::mutex > lock{ mutex };
+        cond.wait_for(lock, std::chrono::milliseconds{ watingTime });
+    }
+    void proceed()
+    {
+        cond.notify_all();
+    }
+    void createSceneCollection()
+    {
+        pSceneCollection = pSceneList->addNewSceneCollection();
+    }
+    void createScene()
+    {
+        pScene1 = pSceneCollection->addNewScene("SceneTestName_1");
+        pScene2 = pSceneCollection->addNewScene("SceneTestName_2");
+    }
+    void createServer(const std::string& resourceUri1, const std::string& resourceUri2)
+    {
+        auto pResource1 = RCSResourceObject::Builder(
+                resourceUri1, RESOURCE_TYPE, DEFAULT_INTERFACE).build();
+        pResource1->setAttribute(KEY, VALUE);
+
+        auto ocResourcePtr = OC::OCPlatform::constructResourceObject(
+                "coap://" + SceneUtils::getNetAddress(), resourceUri1,
+                OCConnectivityType::CT_ADAPTER_IP, false,
+                pResource1->getTypes(), pResource1->getInterfaces());
+        pRemoteResource1 = RCSRemoteResourceObject::fromOCResource(ocResourcePtr);
+
+        auto pResource2 = RCSResourceObject::Builder(
+                resourceUri2, RESOURCE_TYPE2, DEFAULT_INTERFACE).build();
+        pResource2->setAttribute(KEY_2, VALUE_2);
+
+        ocResourcePtr = OC::OCPlatform::constructResourceObject(
+                        "coap://" + SceneUtils::getNetAddress(), resourceUri2,
+                        OCConnectivityType::CT_ADAPTER_IP, false,
+                        pResource2->getTypes(), pResource2->getInterfaces());
+        pRemoteResource2 = RCSRemoteResourceObject::fromOCResource(ocResourcePtr);
+    }
+
+public:
+    SceneList* pSceneList;
+    shared_ptr<SceneCollection> pSceneCollection;
+    shared_ptr<Scene> pScene1;
+    shared_ptr<Scene> pScene2;
+    RCSRemoteResourceObject::Ptr pRemoteResource1;
+    RCSRemoteResourceObject::Ptr pRemoteResource2;
+
+private:
+    std::condition_variable cond;
+    std::mutex mutex;
+};
+void executeCallback(int /*code*/) {};
+
+TEST_F(SceneTest, createSceneInstance)
+{
+    createSceneCollection();
+    createScene();
+    ASSERT_EQ("SceneTestName_1", pScene1->getName());
+    ASSERT_EQ("SceneTestName_2", pScene2->getName());
+}
+
+TEST_F(SceneTest, createSceneInstanceByEmptyName)
+{
+    createSceneCollection();
+    ASSERT_THROW(pSceneCollection->addNewScene(""), RCSInvalidParameterException);
+}
+
+TEST_F(SceneTest, getSceneInstanceBySceneName)
+{
+    createSceneCollection();
+    createScene();
+    auto scene = pSceneCollection->getScene("SceneTestName_2");
+    EXPECT_EQ("SceneTestName_2", scene->getName());
+}
+
+TEST_F(SceneTest, getAllSceneInstance)
+{
+    createSceneCollection();
+    createScene();
+
+    vector<string> sceneNames{"SceneTestName_1", "SceneTestName_2"};
+    auto scenes = pSceneCollection->getScenes();
+    int count = 0;
+
+    for(const auto &it : scenes)
+    {
+        ASSERT_EQ(it.first, sceneNames.at(count++));
+    }
+}
+
+TEST_F(SceneTest, getSceneActionUsingRemoteResource)
+{
+    createServer(RESOURCE_URI, RESOURCE_URI2);
+    createSceneCollection();
+    createScene();
+
+    auto pSceneAction1 = pScene1->addNewSceneAction(pRemoteResource1, KEY, VALUE);
+    pSceneAction1->resetExecutionParameter(KEY_2, VALUE_2);
+
+    ASSERT_EQ(pScene1->getSceneAction(pRemoteResource1)->getExecutionParameter(),
+            pSceneAction1->getExecutionParameter());
+}
+
+TEST_F(SceneTest, getSceneActions)
+{
+    createServer("/a/testuri1_1", "/a/testuri1_2");
+    createSceneCollection();
+    createScene();
+
+    auto pSceneAction1 = pScene1->addNewSceneAction(pRemoteResource1, KEY, VALUE);
+    auto pSceneAction2 = pScene1->addNewSceneAction(pRemoteResource2, KEY, VALUE);
+
+    for(const auto & it : pScene1->getSceneActions())
+    {
+        ASSERT_EQ(it->getExecutionParameter(), pSceneAction1->getExecutionParameter());
+    }
+}
+
+TEST_F(SceneTest, executeScene)
+{
+    mocks.ExpectCallFunc(executeCallback).Do([this](int){ proceed(); });
+
+    createServer("/a/testuri2_1", "/a/testuri2_2");
+    createSceneCollection();
+    createScene();
+    pScene1->addNewSceneAction(pRemoteResource1, KEY, "on");
+    pScene1->addNewSceneAction(pRemoteResource2, KEY_2, VALUE_2);
+
+    pScene1->execute(executeCallback);
+    waitForCb(100);
+}
+
+TEST_F(SceneTest, executeSceneUsingEmptyCallback)
+{
+    createServer("/a/testuri3_1", "/a/testuri3_2");
+    createSceneCollection();
+    createScene();
+    pScene1->addNewSceneAction(pRemoteResource1, KEY, "on");
+    pScene1->addNewSceneAction(pRemoteResource2, KEY_2, VALUE_2);
+
+    ASSERT_THROW(pScene1->execute(nullptr), RCSInvalidParameterException);
+}
\ No newline at end of file
old mode 100644 (file)
new mode 100755 (executable)
index efcb2a7..8a03a54
@@ -26,7 +26,8 @@ import os, sys
 Import('env')
 
 lib_env = env.Clone()
-SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+src_dir = env.get('SRC_DIR')
+SConscript(src_dir + '/service/third_party_libs.scons', 'lib_env')
 simulator_env = lib_env.Clone()
 
 #Raml Parser
@@ -36,7 +37,7 @@ target_os = env.get('TARGET_OS')
 ######################################################################
 # Build flags
 ######################################################################
-simulator_env.AppendUnique(CPPPATH = ['inc', 'src/client-controller', 'src/service-provider', 'src/common'])
+simulator_env.AppendUnique(CPPPATH = ['inc', 'src/client', 'src/server', 'src/common'])
 simulator_env.AppendUnique(CPPPATH = [
                '../../resource/include/',
                '../../resource/csdk/stack/include',
@@ -67,11 +68,13 @@ java_headers.append(os.path.join(java_headers[0], 'linux'))
 java_headers.append(os.path.join(java_headers[0], 'solaris'))
 simulator_env.AppendUnique(CPPPATH = java_headers)
 
+simulator_env.Append( RPATH = env.Literal('\\$$ORIGIN'))
+
 simulator_env.AppendUnique(CPPPATH = ['../../extlibs/cjson'])
-simulator_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'libcoap','RamlParser','YamlParser'])
+simulator_env.PrependUnique(LIBS = ['oc', 'octbstack', 'RamlParser'])
 simulator_env.AppendUnique(LIBS = ['pthread'])
 
-simulator_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
+simulator_env.AppendUnique(CXXFLAGS = ['-O2', '-Wall', '-fmessage-length=0', '-std=c++0x'])
 
 ######################################################################
 # Source files and Targets
@@ -82,8 +85,8 @@ simulator_src = [env.Glob('src/*.cpp')
                 ]
 simulatorsdk = simulator_env.SharedLibrary('SimulatorManager', simulator_src)
 
-simulator_env.InstallTarget(simulatorsdk, 'libSimulator')
+simulator_env.InstallTarget(simulatorsdk, 'libSimulatorManager')
 
 #Build sample application
 SConscript('examples/server/SConscript')
-SConscript('examples/client-controller/SConscript')
+SConscript('examples/client/SConscript')
diff --git a/service/simulator/examples/README.txt b/service/simulator/examples/README.txt
deleted file mode 100755 (executable)
index f0ab383..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-Command to run Service Provider with Resource definitions provided throught RAML file :\r
-./simulator-server  PATH-TO-RAML-FILE\r
-\r
diff --git a/service/simulator/examples/client-controller/SConscript b/service/simulator/examples/client-controller/SConscript
deleted file mode 100644 (file)
index 7149b6b..0000000
+++ /dev/null
@@ -1,28 +0,0 @@
-Import('env')
-lib_env = env.Clone()
-SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
-sim_env = lib_env.Clone()
-
-######################################################################
-# Build flags
-######################################################################
-sim_env.AppendUnique(CPPPATH = ['../../../../extlibs/timer'])
-sim_env.AppendUnique(CPPPATH = ['../../inc'])
-sim_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
-sim_env.AppendUnique(CPPDEFINES = ['LINUX'])
-sim_env.AppendUnique(LIBS = ['SimulatorManager'])
-
-sim_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-sim_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
-sim_env.PrependUnique(LIBS = ['SimulatorManager'])
-
-if sim_env.get('SECURED') == '1':
-    sim_env.AppendUnique(LIBS = ['tinydtls'])
-
-######################################################################
-# Source files and Targets
-######################################################################
-clientcontroller = sim_env.Program('client-controller', 'client_controller.cpp')
-
-Alias("clientcontroller", clientcontroller)
-env.AppendTarget('clientcontroller')
diff --git a/service/simulator/examples/client-controller/client_controller.cpp b/service/simulator/examples/client-controller/client_controller.cpp
deleted file mode 100644 (file)
index 18df736..0000000
+++ /dev/null
@@ -1,683 +0,0 @@
-/******************************************************************
- *
- * 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 "simulator_manager.h"
-#include <map>
-#include <mutex>
-
-std::string getOperationStateString(OperationState state)
-{
-    switch (state)
-    {
-        case OP_START: return "OP_START";
-        case OP_COMPLETE: return "OP_COMPLETE";
-        case OP_ABORT: return "OP_ABORT";
-    }
-
-    return "OP_UNKNOWN";
-}
-
-class AppLogger : public ILogger
-{
-    public:
-        void write(std::string time, ILogger::Level level, std::string message)
-        {
-            std::cout << "[APPLogger] " << time << " " << ILogger::getString(level) << " " << message;
-        }
-};
-std::shared_ptr<AppLogger> gAppLogger(new AppLogger());
-
-class ClientController
-{
-    public:
-        void startTest()
-        {
-            printMenu();
-            bool cont = true;
-            while (cont)
-            {
-                int choice = -1;
-                std::cout << "Enter your choice: ";
-                std::cin >> choice;
-                if (choice < 0 || choice > 12)
-                {
-                    std::cout << "Invaild choice !" << std::endl; continue;
-                }
-
-                switch (choice)
-                {
-                    case 1: findResource(); break;
-                    case 2: displayResource(); break;
-                    case 3: observeResource(); break;
-                    case 4: cancelObserving(); break;
-                    case 5: sendGet(); break;
-                    case 6: sendPut(); break;
-                    case 7: sendPost(); break;
-                    case 8: sendAllGETRequests(); break;
-                    case 9: sendAllPUTRequests(); break;
-                    case 10: sendAllPOSTRequests(); break;
-                    case 11: configure(); break;
-                    case 12: printMenu(); break;
-                    case 0: cont = false;
-                }
-            }
-        }
-
-    private:
-        void printMenu()
-        {
-            std::cout << "########### SIMULATOR CLIENT CONTROLLER ###########" << std::endl;
-            std::cout << "1. Find resource" << std::endl;
-            std::cout << "2. Display resource information" << std::endl;
-            std::cout << "3. Observe for resource change" << std::endl;
-            std::cout << "4. Cancel observation" << std::endl;
-            std::cout << "5. Send GET message" << std::endl;
-            std::cout << "6. Send PUT message" << std::endl;
-            std::cout << "7. Send POST message" << std::endl;
-            std::cout << "8. Send All GET requests" << std::endl;
-            std::cout << "9. Send All PUT requests" << std::endl;
-            std::cout << "10. Send All POST requests" << std::endl;
-            std::cout << "11. Configure (using RAML file)" << std::endl;
-            std::cout << "12: Help" << std::endl;
-            std::cout << "0. Exit" << std::endl;
-            std::cout << "###################################################" << std::endl;
-        }
-
-        SimulatorRemoteResourceSP selectResource()
-        {
-            std::lock_guard<std::recursive_mutex> lock(m_mutex);
-            if (0 == m_resList.size())
-            {
-                std::cout << "No resouces!" << std::endl;
-                return nullptr;
-            }
-
-            int index = 1;
-            std::vector<std::string> ids;
-            for (auto & resourceEntry : m_resList)
-            {
-                std::cout << index++ << ": " << (resourceEntry.second)->getURI() << "[" <<
-                          (resourceEntry.second)->getHost()  << "]" << std::endl;
-                ids.push_back((resourceEntry.second)->getID());
-            }
-
-            int choice = -1;
-            std::cout << "Choose the resource: ";
-            std::cin >> choice;
-
-            if (choice < 1 || choice > index - 1)
-            {
-                std::cout << "Invalid choice !" << std::endl;
-                return nullptr;
-            }
-
-            return m_resList[ids[choice - 1]];
-        }
-
-        void findResource()
-        {
-            std::string resourceType;
-            std::cout << "Enter resource type : ";
-            std::cin >> resourceType;
-
-            ResourceFindCallback callback = [this](std::shared_ptr<SimulatorRemoteResource> resource)
-            {
-                std::cout << "Resource found ######" << std::endl;
-                displayResource(resource);
-
-                // Add to local list
-                std::lock_guard<std::recursive_mutex> lock(m_mutex);
-                if (m_resList.end() == m_resList.find(resource->getID()))
-                    m_resList[resource->getID()] = resource;
-                else
-                    std::cout << "Resource with UID: " << resource->getID() << "already exist in the list!" <<
-                              std::endl;
-            };
-
-            try
-            {
-                SimulatorManager::getInstance()->findResource(resourceType, callback);
-                std::cout << "SimulatorManager::findResource is successfull" << std::endl;
-            }
-            catch (InvalidArgsException &e)
-            {
-                std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]"
-                          << std::endl;
-            }
-            catch (SimulatorException &e)
-            {
-                std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" <<
-                          std::endl;
-            }
-        }
-
-        void displayResource()
-        {
-            displayResource(selectResource());
-        }
-
-        void displayResource(SimulatorRemoteResourceSP resource)
-        {
-            if (!resource) return;
-
-            std::cout << "#############################" << std::endl;
-            std::cout << "URI: " << resource->getURI().c_str() << std::endl;
-            std::cout << "Host: " << resource->getHost().c_str() << std::endl;
-            std::cout << "ID: " << resource->getID().c_str() << std::endl;
-            std::cout << "Resource Types: ";
-            for (auto & type : resource->getResourceTypes())
-                std::cout << type << " ";
-            std::cout << "\nInterface Types: ";
-            for (auto & type : resource->getResourceInterfaces())
-                std::cout << type << " ";
-            std::cout << std::boolalpha << "\nisObservable : " << resource->isObservable()
-                    << std::noboolalpha << std::endl;
-            std::cout << "#############################" << std::endl;
-        }
-
-        void observeResource()
-        {
-            SimulatorRemoteResourceSP resource = selectResource();
-            if (!resource) return;
-
-            // callback implementaion
-            SimulatorRemoteResource::ObserveNotificationCallback callback =
-                [](std::string uid, SimulatorResult errorCode, SimulatorResourceModelSP rep, int seq)
-            {
-                std::cout << "\nObserve notification received ###[errorcode:  " << errorCode <<
-                          " seq:  " << seq << "UID: " << uid << "]" << std::endl;
-                std::map<std::string, SimulatorResourceModel::Attribute> attributes = rep->getAttributes();
-                for (auto & attribute : attributes)
-                {
-                    std::cout << (attribute.second).getName() << " :  {" << std::endl;
-                    std::cout << "value: " << (attribute.second).valueToString().c_str() << std::endl;
-                    std::cout << "}" << std::endl;
-                }
-                std::cout << std::endl;
-            };
-
-            try
-            {
-                resource->observe(ObserveType::OBSERVE, callback);
-                std::cout << "Observe is successfull!" << std::endl;
-            }
-            catch (InvalidArgsException &e)
-            {
-                std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
-                        << e.what() << "]" << std::endl;
-            }
-            catch (SimulatorException &e)
-            {
-                std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
-                        e.what() << "]" << std::endl;
-            }
-        }
-
-        void cancelObserving()
-        {
-            SimulatorRemoteResourceSP resource = selectResource();
-            if (!resource) return;
-
-            try
-            {
-                resource->cancelObserve();
-                std::cout << "Cancelling observe is successfull!" << std::endl;
-            }
-            catch (SimulatorException &e)
-            {
-                std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
-                        e.what() << "]" << std::endl;
-            }
-        }
-
-        void sendGet()
-        {
-            SimulatorRemoteResourceSP resource = selectResource();
-            if (!resource) return;
-
-            // callback implementaion
-            SimulatorRemoteResource::ResponseCallback callback =
-                [](std::string uId, SimulatorResult errorCode, SimulatorResourceModelSP rep)
-            {
-                std::cout << "\nGET Response received ### [errorcode:  " << errorCode << "]"
-                        << std::endl;
-                std::cout << "UID is: " << uId << std::endl;
-                std::cout << "Representation is: " << std::endl;
-                std::map<std::string, SimulatorResourceModel::Attribute> attributes =
-                        rep->getAttributes();
-                for (auto & attribute : attributes)
-                {
-                    std::cout << (attribute.second).getName() << " :  {" << std::endl;
-                    std::cout << "value: " << (attribute.second).valueToString().c_str()
-                            << std::endl;
-                    std::cout << "}" << std::endl;
-                }
-                std::cout << std::endl;
-            };
-
-            try
-            {
-                resource->get(std::map <std::string, std::string>(), callback);
-                std::cout << "GET is successfull!" << std::endl;
-            }
-            catch (InvalidArgsException &e)
-            {
-                std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
-                        << e.what() << "]" << std::endl;
-            }
-            catch (NoSupportException &e)
-            {
-                std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " <<
-                        e.what() << "]" << std::endl;
-            }
-            catch (SimulatorException &e)
-            {
-                std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
-                        e.what() << "]" << std::endl;
-            }
-        }
-
-        void sendPut()
-        {
-            SimulatorRemoteResourceSP resource = selectResource();
-            if (!resource) return;
-
-            // callback implementaion
-            SimulatorRemoteResource::ResponseCallback callback =
-                [](std::string uId, SimulatorResult errorCode, SimulatorResourceModelSP rep)
-            {
-                std::cout << "\nPUT Response received ![errorcode:  " << errorCode << "]"
-                        << std::endl;
-                std::cout << "UID is: " << uId << std::endl;
-                std::cout << "Representation is: " << std::endl;
-                std::map<std::string, SimulatorResourceModel::Attribute> attributes =
-                        rep->getAttributes();
-                for (auto & attribute : attributes)
-                {
-                    std::cout << (attribute.second).getName() << " :  {" << std::endl;
-                    std::cout << "value: " << (attribute.second).valueToString().c_str()
-                            << std::endl;
-                    std::cout << "}" << std::endl;
-                }
-                std::cout << std::endl;
-            };
-
-            try
-            {
-                SimulatorResourceModelSP rep = std::make_shared<SimulatorResourceModel>();
-                std::string value = "off";
-                rep->addAttribute("power", value);
-                rep->addAttribute("intensity", 5);
-
-                resource->put(std::map <std::string, std::string>(), rep, callback);
-                std::cout << "PUT is successfull!" << std::endl;
-            }
-            catch (InvalidArgsException &e)
-            {
-                std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
-                        << e.what() << "]" << std::endl;
-            }
-            catch (NoSupportException &e)
-            {
-                std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " <<
-                        e.what() << "]" << std::endl;
-            }
-            catch (SimulatorException &e)
-            {
-                std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
-                        e.what() << "]" << std::endl;
-            }
-        }
-
-        void sendPost()
-        {
-            SimulatorRemoteResourceSP resource = selectResource();
-            if (!resource) return;
-
-            // callback implementaion
-            SimulatorRemoteResource::ResponseCallback callback =
-                [](std::string uId, SimulatorResult errorCode, SimulatorResourceModelSP rep)
-            {
-                std::cout << "\nPOST Response received ![errorcode:  " << errorCode << "]"
-                        << std::endl;
-                std::cout << "UID is: " << uId << std::endl;
-                std::cout << "Representation is: " << std::endl;
-                std::map<std::string, SimulatorResourceModel::Attribute> attributes =
-                        rep->getAttributes();
-                for (auto & attribute : attributes)
-                {
-                    std::cout << (attribute.second).getName() << " :  {" << std::endl;
-                    std::cout << "value: " << (attribute.second).valueToString().c_str()
-                            << std::endl;
-                    std::cout << "}" << std::endl;
-                }
-                std::cout << std::endl;
-            };
-
-            try
-            {
-                SimulatorResourceModelSP rep = std::make_shared<SimulatorResourceModel>();
-                std::string value = "on";
-                rep->addAttribute("power", value);
-                rep->addAttribute("intensity", 7);
-
-                resource->post(std::map <std::string, std::string>(), rep, callback);
-                std::cout << "POST is successfull!" << std::endl;
-            }
-            catch (InvalidArgsException &e)
-            {
-                std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
-                        << e.what() << "]" << std::endl;
-            }
-            catch (NoSupportException &e)
-            {
-                std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " <<
-                        e.what() << "]" << std::endl;
-            }
-            catch (SimulatorException &e)
-            {
-                std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
-                        e.what() << "]" << std::endl;
-            }
-        }
-
-        void sendAllGETRequests()
-        {
-            SimulatorRemoteResourceSP resource = selectResource();
-            if (!resource) return;
-
-            SimulatorRemoteResource::StateCallback callback = [] (std::string uid, int sessionId,
-                    OperationState state)
-            {
-                std::cout << "\nResource verification status received ![id:  " << sessionId <<
-                        "  State: " << getOperationStateString(state) << " UID: " << uid << "]" <<
-                        std::endl;
-            };
-
-            try
-            {
-                int id = resource->startVerification(RequestType::RQ_TYPE_GET, callback);
-                std::cout << "startVerification for GET is successfull!id: " << id << std::endl;
-            }
-            catch (InvalidArgsException &e)
-            {
-                std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
-                        << e.what() << "]" << std::endl;
-            }
-            catch (NoSupportException &e)
-            {
-                std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " <<
-                        e.what() << "]" << std::endl;
-            }
-            catch (SimulatorException &e)
-            {
-                std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
-                        e.what() << "]" << std::endl;
-            }
-        }
-
-        void sendAllPUTRequests()
-        {
-            SimulatorRemoteResourceSP resource = selectResource();
-            if (!resource) return;
-
-            SimulatorRemoteResource::StateCallback callback = [] (std::string uid, int sessionId,
-                    OperationState state)
-            {
-                std::cout << "\nResource verification status received ![id:  " << sessionId <<
-                        "  State: " << getOperationStateString(state) << " UID: " << uid << "]" <<
-                        std::endl;
-            };
-
-            try
-            {
-                int id = resource->startVerification(RequestType::RQ_TYPE_PUT, callback);
-                std::cout << "startVerification for PUT is successfull!id: " << id << std::endl;
-            }
-            catch (InvalidArgsException &e)
-            {
-                std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
-                        << e.what() << "]" << std::endl;
-            }
-            catch (NoSupportException &e)
-            {
-                std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " <<
-                        e.what() << "]" << std::endl;
-            }
-            catch (SimulatorException &e)
-            {
-                std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
-                        e.what() << "]" << std::endl;
-            }
-        }
-
-        void sendAllPOSTRequests()
-        {
-            SimulatorRemoteResourceSP resource = selectResource();
-            if (!resource) return;
-
-            SimulatorRemoteResource::StateCallback callback = [] (std::string uid, int sessionId,
-                    OperationState state)
-            {
-                std::cout << "\nResource verification status received ![id:  " << sessionId <<
-                        "  State: " << getOperationStateString(state) << " UID: " << uid << "]"
-                        << std::endl;
-            };
-
-            try
-            {
-                int id = resource->startVerification(RequestType::RQ_TYPE_POST, callback);
-                std::cout << "startVerification for POST is successfull!id: " << id << std::endl;
-            }
-            catch (InvalidArgsException &e)
-            {
-                std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
-                        << e.what() << "]" << std::endl;
-            }
-            catch (NoSupportException &e)
-            {
-                std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " <<
-                        e.what() << "]" << std::endl;
-            }
-            catch (SimulatorException &e)
-            {
-                std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
-                        e.what() << "]" << std::endl;
-            }
-        }
-
-        void configure()
-        {
-            SimulatorRemoteResourceSP resource = selectResource();
-            if (!resource)
-                return;
-
-            try
-            {
-                std::string configPath;
-                std::cout << "Enter the config path: ";
-                std::cin >> configPath;
-
-                resource->configure(configPath);
-                std::cout << "configuration is successfull!" << std::endl;
-            }
-            catch (InvalidArgsException &e)
-            {
-                std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
-                        << e.what() << "]" << std::endl;
-            }
-            catch (SimulatorException &e)
-            {
-                std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
-                        e.what() << "]" << std::endl;
-            }
-        }
-
-    private:
-        std::recursive_mutex m_mutex;
-        std::map<std::string, SimulatorRemoteResourceSP> m_resList;
-};
-
-void printMainMenu()
-{
-    std::cout << "############### MAIN MENU###############" << std::endl;
-    std::cout << "1. Client Controller Test" << std::endl;
-    std::cout << "2. Get device information" << std::endl;
-    std::cout << "3. Get platform information" << std::endl;
-    std::cout << "4. Set Logger" << std::endl;
-    std::cout << "5. Help" << std::endl;
-    std::cout << "0. Exit" << std::endl;
-    std::cout << "######################################" << std::endl;
-}
-
-void setLogger()
-{
-    std::cout << "1. Default console logger" << std::endl;
-    std::cout << "2. Default file logger" << std::endl;
-    std::cout << "3. custom logger" << std::endl;
-
-    int choice = -1;
-    std::cin >> choice;
-    if (choice <= 0 || choice > 3)
-    {
-        std::cout << "Invalid selection !" << std::endl;
-        return;
-    }
-
-    switch (choice)
-    {
-        case 1:
-            {
-                if (false == SimulatorManager::getInstance()->setConsoleLogger())
-                    std::cout << "Failed to set the default console logger" << std::endl;
-            }
-            break;
-
-        case 2:
-            {
-                std::string filePath;
-                std::cout << "Enter the file path (without file name) : ";
-                std::cin >> filePath;
-                if (false == SimulatorManager::getInstance()->setFileLogger(filePath))
-                    std::cout << "Failed to set default file logger" << std::endl;
-            }
-            break;
-
-        case 3:
-            SimulatorManager::getInstance()->setLogger(gAppLogger);
-    }
-}
-
-int main(void)
-{
-    ClientController clientController;
-    printMainMenu();
-    bool cont = true;
-    while (cont == true)
-    {
-        int choice = -1;
-        std::cout << "Enter your choice: ";
-        std::cin >> choice;
-        if (choice < 0 || choice > 5)
-        {
-            std::cout << "Invaild choice !" << std::endl; continue;
-        }
-
-        switch (choice)
-        {
-            case 1: clientController.startTest();
-                std::cout << "Welcome back to main menu !" << std::endl;
-                break;
-
-            case 2:
-                {
-                    try
-                    {
-                        SimulatorManager::getInstance()->getDeviceInfo(std::bind([](DeviceInfo & deviceInfo)
-                        {
-                            std::cout << "###Device Information received...." << std::endl;
-                            std::ostringstream out;
-                            out << "Device name: " << deviceInfo.getName() << std::endl;
-                            out << "Device ID: " << deviceInfo.getID() << std::endl;
-                            out << "Device Spec version: " << deviceInfo.getSpecVersion() << std::endl;
-                            out << "Device dat model version: " << deviceInfo.getDataModelVersion() << std::endl;
-
-                            std::cout << out.str() << std::endl;
-                        }, std::placeholders::_1));
-                    }
-                    catch (InvalidArgsException &e)
-                    {
-                        std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]"
-                                  << std::endl;
-                    }
-                    catch (SimulatorException &e)
-                    {
-                        std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" <<
-                                  std::endl;
-                    }
-                }
-                break;
-
-            case 3:
-                {
-                    try
-                    {
-                        SimulatorManager::getInstance()->getPlatformInfo(std::bind([](PlatformInfo & platformInfo)
-                        {
-                            std::cout << "###Platform Information received...." << std::endl;
-                            std::ostringstream out;
-                            out << "Platform ID: " << platformInfo.getPlatformID() << std::endl;
-                            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 << "Date of manufacture: " << platformInfo.getDateOfManfacture() << std::endl;
-                            out << "Operatio system version: " << platformInfo.getOSVersion() << std::endl;
-                            out << "Hardware version: " << platformInfo.getHardwareVersion() << std::endl;
-                            out << "Firmware version: " << platformInfo.getFirmwareVersion() << std::endl;
-                            out << "Support url: " << platformInfo.getSupportUrl() << std::endl;
-                            out << "System time: " << platformInfo.getSystemTime() << std::endl;
-
-                            std::cout << out.str() << std::endl;
-                        }, std::placeholders::_1));
-                    }
-                    catch (InvalidArgsException &e)
-                    {
-                        std::cout << "InvalidArgsException occured [code : " << e.code()
-                                << " Detail: " << e.what() << "]" << std::endl;
-                    }
-                    catch (SimulatorException &e)
-                    {
-                        std::cout << "SimulatorException occured [code : " << e.code()
-                                << " Detail: " << e.what() << "]" << std::endl;
-                    }
-                }
-                break;
-
-            case 4: setLogger(); break;
-
-            case 5: printMainMenu(); break;
-
-            case 0: cont = false;
-        }
-    }
-
-    std::cout << "Terminating test !!!" << std::endl;
-}
diff --git a/service/simulator/examples/client/SConscript b/service/simulator/examples/client/SConscript
new file mode 100644 (file)
index 0000000..bcf4ec0
--- /dev/null
@@ -0,0 +1,28 @@
+Import('env')
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+sim_env = lib_env.Clone()
+
+######################################################################
+# Build flags
+######################################################################
+sim_env.AppendUnique(CPPPATH = ['../../../../extlibs/timer'])
+sim_env.AppendUnique(CPPPATH = ['../../inc'])
+sim_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
+sim_env.AppendUnique(CPPDEFINES = ['LINUX'])
+sim_env.AppendUnique(LIBS = ['SimulatorManager'])
+
+sim_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+sim_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
+sim_env.PrependUnique(LIBS = ['SimulatorManager'])
+
+if sim_env.get('SECURED') == '1':
+    sim_env.AppendUnique(LIBS = ['tinydtls'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+client = sim_env.Program('simulator-client', 'simulator_client.cpp')
+
+Alias("simulatorclient", client)
+env.AppendTarget('client')
diff --git a/service/simulator/examples/client/simulator_client.cpp b/service/simulator/examples/client/simulator_client.cpp
new file mode 100644 (file)
index 0000000..a8f9f8f
--- /dev/null
@@ -0,0 +1,662 @@
+/******************************************************************
+ *
+ * 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 "simulator_manager.h"
+#include <map>
+#include <mutex>
+
+std::string getOperationStateString(OperationState state)
+{
+    switch (state)
+    {
+        case OP_START: return "OP_START";
+        case OP_COMPLETE: return "OP_COMPLETE";
+        case OP_ABORT: return "OP_ABORT";
+    }
+
+    return "OP_UNKNOWN";
+}
+
+class AppLogger : public ILogger
+{
+    public:
+        void write(std::string time, ILogger::Level level, std::string message)
+        {
+            std::cout << "[APPLogger] " << time << " " << ILogger::getString(level) << " " << message;
+        }
+};
+std::shared_ptr<AppLogger> gAppLogger(new AppLogger());
+
+class ClientController
+{
+    public:
+        void startTest()
+        {
+            printMenu();
+            bool cont = true;
+            while (cont)
+            {
+                int choice = -1;
+                std::cout << "Enter your choice: ";
+                std::cin >> choice;
+                if (choice < 0 || choice > 14)
+                {
+                    std::cout << "Invaild choice !" << std::endl; continue;
+                }
+
+                switch (choice)
+                {
+                    case 1: findResource(); break;
+                    case 2: displayResource(); break;
+                    case 3: observeResource(); break;
+                    case 4: cancelObserving(); break;
+                    case 5: sendGet(); break;
+                    case 6: sendPut(); break;
+                    case 7: sendPost(); break;
+                    case 8: sendAllGETRequests(); break;
+                    case 9: sendAllPUTRequests(); break;
+                    case 10: sendAllPOSTRequests(); break;
+                    case 11: configure(); break;
+                    case 12: getDeviceInfo(); break;
+                    case 13: getPlatformInfo(); break;
+                    case 14: printMenu(); break;
+                    case 0: cont = false;
+                }
+            }
+        }
+
+    private:
+        void printMenu()
+        {
+            std::cout << "########### SIMULATOR CLIENT CONTROLLER ###########" << std::endl;
+            std::cout << "1. Find resource" << std::endl;
+            std::cout << "2. Display resource information" << std::endl;
+            std::cout << "3. Observe for resource change" << std::endl;
+            std::cout << "4. Cancel observation" << std::endl;
+            std::cout << "5. Send GET message" << std::endl;
+            std::cout << "6. Send PUT message" << std::endl;
+            std::cout << "7. Send POST message" << std::endl;
+            std::cout << "8. Send All GET requests" << std::endl;
+            std::cout << "9. Send All PUT requests" << std::endl;
+            std::cout << "10. Send All POST requests" << std::endl;
+            std::cout << "11. Configure (using RAML file)" << std::endl;
+            std::cout << "12. Get Device Information" << std::endl;
+            std::cout << "13. Get Platform Information" << std::endl;
+            std::cout << "14: Help" << std::endl;
+            std::cout << "0. Exit" << std::endl;
+            std::cout << "###################################################" << std::endl;
+        }
+
+        SimulatorRemoteResourceSP selectResource()
+        {
+            std::lock_guard<std::recursive_mutex> lock(m_mutex);
+            if (0 == m_resList.size())
+            {
+                std::cout << "No resources!" << std::endl;
+                return nullptr;
+            }
+
+            int index = 1;
+            std::vector<std::string> ids;
+            for (auto &resourceEntry : m_resList)
+            {
+                std::cout << index++ << ": " << (resourceEntry.second)->getURI() << "[" <<
+                          (resourceEntry.second)->getHost()  << "]" << std::endl;
+                ids.push_back((resourceEntry.second)->getID());
+            }
+
+            int choice = -1;
+            std::cout << "Choose the resource: ";
+            std::cin >> choice;
+
+            if (choice < 1 || choice > index - 1)
+            {
+                std::cout << "Invalid choice !" << std::endl;
+                return nullptr;
+            }
+
+            return m_resList[ids[choice - 1]];
+        }
+
+        void findResource()
+        {
+            std::string resourceType;
+            std::cout << "Enter resource type : ";
+            std::cin >> resourceType;
+
+            ResourceFindCallback callback = [this](std::shared_ptr<SimulatorRemoteResource> resource)
+            {
+                std::cout << "Resource found ######" << std::endl;
+                displayResource(resource);
+
+                // Add to local list
+                std::lock_guard<std::recursive_mutex> lock(m_mutex);
+                if (m_resList.end() == m_resList.find(resource->getID()))
+                    m_resList[resource->getID()] = resource;
+                else
+                    std::cout << "Resource with UID: " << resource->getID() << "already exist in the list!" <<
+                              std::endl;
+            };
+
+            try
+            {
+                SimulatorManager::getInstance()->findResource(resourceType, callback);
+                std::cout << "SimulatorManager::findResource is successful" << std::endl;
+                m_resList.clear();
+            }
+            catch (InvalidArgsException &e)
+            {
+                std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]"
+                          << std::endl;
+            }
+            catch (SimulatorException &e)
+            {
+                std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" <<
+                          std::endl;
+            }
+        }
+
+        void displayResource()
+        {
+            displayResource(selectResource());
+        }
+
+        void displayResource(SimulatorRemoteResourceSP resource)
+        {
+            if (!resource) return;
+
+            std::cout << "#############################" << std::endl;
+            std::cout << "URI: " << resource->getURI().c_str() << std::endl;
+            std::cout << "Host: " << resource->getHost().c_str() << std::endl;
+            std::cout << "ID: " << resource->getID().c_str() << std::endl;
+            std::cout << "Resource Types: ";
+            for (auto &type : resource->getResourceTypes())
+                std::cout << type << " ";
+            std::cout << "\nInterface Types: ";
+            for (auto &type : resource->getInterface())
+                std::cout << type << " ";
+            std::cout << std::boolalpha << "\nisObservable : " << resource->isObservable()
+                      << std::noboolalpha << std::endl;
+            std::cout << "#############################" << std::endl;
+        }
+
+        void observeResource()
+        {
+            SimulatorRemoteResourceSP resource = selectResource();
+            if (!resource) return;
+
+            // callback implementaion
+            SimulatorRemoteResource::ObserveNotificationCallback callback =
+                [](const std::string & uid, SimulatorResult result,
+                   const SimulatorResourceModel & rep, int seq)
+            {
+                std::cout << "\nObserve notification received ###[errorcode:  " << result <<
+                          " seq:  " << seq << "UID: " << uid << "]" << std::endl;
+
+                std::cout << "Representation is: " << std::endl;
+                std::cout << rep.asString() << std::endl;
+            };
+
+            try
+            {
+                resource->observe(ObserveType::OBSERVE, callback);
+                std::cout << "Observe is successful!" << std::endl;
+            }
+            catch (InvalidArgsException &e)
+            {
+                std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
+                          << e.what() << "]" << std::endl;
+            }
+            catch (SimulatorException &e)
+            {
+                std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
+                          e.what() << "]" << std::endl;
+            }
+        }
+
+        void cancelObserving()
+        {
+            SimulatorRemoteResourceSP resource = selectResource();
+            if (!resource) return;
+
+            try
+            {
+                resource->cancelObserve();
+                std::cout << "Cancelling observe is successful!" << std::endl;
+            }
+            catch (SimulatorException &e)
+            {
+                std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
+                          e.what() << "]" << std::endl;
+            }
+        }
+
+        void sendGet()
+        {
+            SimulatorRemoteResourceSP resource = selectResource();
+            if (!resource) return;
+
+            // callback implementaion
+            SimulatorRemoteResource::ResponseCallback callback =
+                [](const std::string & uid, SimulatorResult result, const SimulatorResourceModel & rep)
+            {
+                std::cout << "\nGET Response received ### [errorcode:  " << result << "]"
+                          << std::endl;
+                std::cout << "UID is: " << uid << std::endl;
+                std::cout << "Representation is: " << std::endl;
+                std::cout << rep.asString() << std::endl;
+            };
+
+            try
+            {
+                resource->get(std::map <std::string, std::string>(), callback);
+                std::cout << "GET is successful!" << std::endl;
+            }
+            catch (InvalidArgsException &e)
+            {
+                std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
+                          << e.what() << "]" << std::endl;
+            }
+            catch (NoSupportException &e)
+            {
+                std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " <<
+                          e.what() << "]" << std::endl;
+            }
+            catch (SimulatorException &e)
+            {
+                std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
+                          e.what() << "]" << std::endl;
+            }
+        }
+
+        void sendPut()
+        {
+            SimulatorRemoteResourceSP resource = selectResource();
+            if (!resource) return;
+
+            // callback implementaion
+            SimulatorRemoteResource::ResponseCallback callback =
+                [](const std::string & uid, SimulatorResult result, const SimulatorResourceModel & rep)
+            {
+                std::cout << "\nPUT Response received ![errorcode:  " << result << "]"
+                          << std::endl;
+                std::cout << "UID is: " << uid << std::endl;
+                std::cout << "Representation is: " << std::endl;
+                std::cout << rep.asString() << std::endl;
+            };
+
+            try
+            {
+                SimulatorResourceModel rep;
+                rep.add("power", false);
+                rep.add("intensity", 15);
+
+                resource->put(rep, callback);
+                std::cout << "PUT is successful!" << std::endl;
+            }
+            catch (InvalidArgsException &e)
+            {
+                std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
+                          << e.what() << "]" << std::endl;
+            }
+            catch (NoSupportException &e)
+            {
+                std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " <<
+                          e.what() << "]" << std::endl;
+            }
+            catch (SimulatorException &e)
+            {
+                std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
+                          e.what() << "]" << std::endl;
+            }
+        }
+
+        void sendPost()
+        {
+            SimulatorRemoteResourceSP resource = selectResource();
+            if (!resource) return;
+
+            // callback implementaion
+            SimulatorRemoteResource::ResponseCallback callback =
+                [](const std::string & uid, SimulatorResult result, const SimulatorResourceModel & rep)
+            {
+                std::cout << "\nPOST Response received ![errorcode:  " << result << "]"
+                          << std::endl;
+                std::cout << "UID is: " << uid << std::endl;
+                std::cout << "Representation is: " << std::endl;
+                std::cout << rep.asString() << std::endl;
+            };
+
+            try
+            {
+                SimulatorResourceModel rep;
+                rep.add("power", true);
+                rep.add("intensity", 17);
+
+                resource->post(rep, callback);
+                std::cout << "POST is successful!" << std::endl;
+            }
+            catch (InvalidArgsException &e)
+            {
+                std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
+                          << e.what() << "]" << std::endl;
+            }
+            catch (NoSupportException &e)
+            {
+                std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " <<
+                          e.what() << "]" << std::endl;
+            }
+            catch (SimulatorException &e)
+            {
+                std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
+                          e.what() << "]" << std::endl;
+            }
+        }
+
+        void sendAllGETRequests()
+        {
+            SimulatorRemoteResourceSP resource = selectResource();
+            if (!resource) return;
+
+            SimulatorRemoteResource::AutoRequestGenerationCallback callback =
+                [] (const std::string & uid, int sessionId, OperationState state)
+            {
+                std::cout << "\nResource verification status received ![id:  " << sessionId <<
+                          "  State: " << getOperationStateString(state) << " UID: " << uid << "]" <<
+                          std::endl;
+            };
+
+            try
+            {
+                int id = resource->startAutoRequesting(RequestType::RQ_TYPE_GET, callback);
+                std::cout << "startVerification for GET is successful!id: " << id << std::endl;
+            }
+            catch (InvalidArgsException &e)
+            {
+                std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
+                          << e.what() << "]" << std::endl;
+            }
+            catch (NoSupportException &e)
+            {
+                std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " <<
+                          e.what() << "]" << std::endl;
+            }
+            catch (SimulatorException &e)
+            {
+                std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
+                          e.what() << "]" << std::endl;
+            }
+        }
+
+        void sendAllPUTRequests()
+        {
+            SimulatorRemoteResourceSP resource = selectResource();
+            if (!resource) return;
+
+            SimulatorRemoteResource::AutoRequestGenerationCallback callback =
+                [] (const std::string & uid, int sessionId, OperationState state)
+            {
+                std::cout << "\nResource verification status received ![id:  " << sessionId <<
+                          "  State: " << getOperationStateString(state) << " UID: " << uid << "]" <<
+                          std::endl;
+            };
+
+            try
+            {
+                int id = resource->startAutoRequesting(RequestType::RQ_TYPE_PUT, callback);
+                std::cout << "startVerification for PUT is successful!id: " << id << std::endl;
+            }
+            catch (InvalidArgsException &e)
+            {
+                std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
+                          << e.what() << "]" << std::endl;
+            }
+            catch (NoSupportException &e)
+            {
+                std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " <<
+                          e.what() << "]" << std::endl;
+            }
+            catch (SimulatorException &e)
+            {
+                std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
+                          e.what() << "]" << std::endl;
+            }
+        }
+
+        void sendAllPOSTRequests()
+        {
+            SimulatorRemoteResourceSP resource = selectResource();
+            if (!resource) return;
+
+            SimulatorRemoteResource::AutoRequestGenerationCallback callback =
+                [] (const std::string & uid, int sessionId, OperationState state)
+            {
+                std::cout << "\nResource verification status received ![id:  " << sessionId <<
+                          "  State: " << getOperationStateString(state) << " UID: " << uid << "]"
+                          << std::endl;
+            };
+
+            try
+            {
+                int id = resource->startAutoRequesting(RequestType::RQ_TYPE_POST, callback);
+                std::cout << "startVerification for POST is successful!id: " << id << std::endl;
+            }
+            catch (InvalidArgsException &e)
+            {
+                std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
+                          << e.what() << "]" << std::endl;
+            }
+            catch (NoSupportException &e)
+            {
+                std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " <<
+                          e.what() << "]" << std::endl;
+            }
+            catch (SimulatorException &e)
+            {
+                std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
+                          e.what() << "]" << std::endl;
+            }
+        }
+
+        void configure()
+        {
+            SimulatorRemoteResourceSP resource = selectResource();
+            if (!resource)
+                return;
+
+            try
+            {
+                std::string configPath;
+                std::cout << "Enter the config path: ";
+                std::cin >> configPath;
+
+                resource->configure(configPath);
+            }
+            catch (InvalidArgsException &e)
+            {
+                std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
+                          << e.what() << "]" << std::endl;
+            }
+            catch (SimulatorException &e)
+            {
+                std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
+                          e.what() << "]" << std::endl;
+            }
+        }
+
+        void getDeviceInfo()
+        {
+            SimulatorRemoteResourceSP resource = selectResource();
+            if (!resource)
+                return;
+
+            try
+            {
+                SimulatorManager::getInstance()->getDeviceInfo(resource->getHost(),
+                        std::bind([](const std::string & host, DeviceInfo & deviceInfo)
+                {
+                    std::cout << "###Device Information received...." << std::endl;
+                    std::ostringstream out;
+                    out << "Host URI: " << host << std::endl;
+                    out << "Device name: " << deviceInfo.getName() << std::endl;
+                    out << "Device ID: " << deviceInfo.getID() << std::endl;
+                    out << "Device Spec version: " << deviceInfo.getSpecVersion() << std::endl;
+                    out << "Device dat model version: " << deviceInfo.getDataModelVersion() << std::endl;
+
+                    std::cout << out.str() << std::endl;
+                }, std::placeholders::_1, std::placeholders::_2));
+            }
+            catch (InvalidArgsException &e)
+            {
+                std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]"
+                          << std::endl;
+            }
+            catch (SimulatorException &e)
+            {
+                std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" <<
+                          std::endl;
+            }
+        }
+
+        void getPlatformInfo()
+        {
+            SimulatorRemoteResourceSP resource = selectResource();
+            if (!resource)
+                return;
+
+            try
+            {
+                SimulatorManager::getInstance()->getPlatformInfo(resource->getHost(),
+                        std::bind([](const std::string & host, PlatformInfo & platformInfo)
+                {
+                    std::cout << "###Platform Information received...." << std::endl;
+                    std::ostringstream out;
+                    out << "Host URI: " << host << std::endl;
+                    out << "Platform ID: " << platformInfo.getPlatformID() << std::endl;
+                    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 << "Date of manufacture: " << platformInfo.getDateOfManfacture() << std::endl;
+                    out << "Operatio system version: " << platformInfo.getOSVersion() << std::endl;
+                    out << "Hardware version: " << platformInfo.getHardwareVersion() << std::endl;
+                    out << "Firmware version: " << platformInfo.getFirmwareVersion() << std::endl;
+                    out << "Support url: " << platformInfo.getSupportUrl() << std::endl;
+                    out << "System time: " << platformInfo.getSystemTime() << std::endl;
+
+                    std::cout << out.str() << std::endl;
+                }, std::placeholders::_1, std::placeholders::_2));
+            }
+            catch (InvalidArgsException &e)
+            {
+                std::cout << "InvalidArgsException occured [code : " << e.code()
+                          << " Detail: " << e.what() << "]" << std::endl;
+            }
+            catch (SimulatorException &e)
+            {
+                std::cout << "SimulatorException occured [code : " << e.code()
+                          << " Detail: " << e.what() << "]" << std::endl;
+            }
+        }
+
+    private:
+        std::recursive_mutex m_mutex;
+        std::map<std::string, SimulatorRemoteResourceSP> m_resList;
+};
+
+void printMainMenu()
+{
+    std::cout << "############### MAIN MENU###############" << std::endl;
+    std::cout << "1. Client Controller Test" << std::endl;
+    std::cout << "2. Set Logger" << std::endl;
+    std::cout << "3. Help" << std::endl;
+    std::cout << "0. Exit" << std::endl;
+    std::cout << "######################################" << std::endl;
+}
+
+void setLogger()
+{
+    std::cout << "1. Default console logger" << std::endl;
+    std::cout << "2. Default file logger" << std::endl;
+    std::cout << "3. custom logger" << std::endl;
+
+    int choice = -1;
+    std::cin >> choice;
+    if (choice <= 0 || choice > 3)
+    {
+        std::cout << "Invalid selection !" << std::endl;
+        return;
+    }
+
+    switch (choice)
+    {
+        case 1:
+            {
+                if (false == SimulatorManager::getInstance()->setConsoleLogger())
+                    std::cout << "Failed to set the default console logger" << std::endl;
+            }
+            break;
+
+        case 2:
+            {
+                std::string filePath;
+                std::cout << "Enter the file path (without file name) : ";
+                std::cin >> filePath;
+                if (false == SimulatorManager::getInstance()->setFileLogger(filePath))
+                    std::cout << "Failed to set default file logger" << std::endl;
+            }
+            break;
+
+        case 3:
+            SimulatorManager::getInstance()->setLogger(gAppLogger);
+    }
+}
+
+int main(void)
+{
+    ClientController clientController;
+    printMainMenu();
+    bool cont = true;
+    while (cont == true)
+    {
+        int choice = -1;
+        std::cout << "Enter your choice: ";
+        std::cin >> choice;
+        if (choice < 0 || choice > 5)
+        {
+            std::cout << "Invaild choice !" << std::endl; continue;
+        }
+
+        switch (choice)
+        {
+            case 1: clientController.startTest();
+                std::cout << "Welcome back to main menu !" << std::endl;
+                break;
+
+            case 2: setLogger(); break;
+
+            case 3: printMainMenu(); break;
+
+            case 0: cont = false;
+        }
+    }
+
+    std::cout << "Terminating test !!!" << std::endl;
+}
index 9a5b38e..cb028dd 100644 (file)
@@ -22,7 +22,7 @@ if sim_env.get('SECURED') == '1':
 ######################################################################
 # Source files and Targets
 ######################################################################
-simulatorserver = sim_env.Program('simulator-server', 'service_provider.cpp')
+server = sim_env.Program('simulator-server', 'simulator_server.cpp')
 
-Alias("simulatorserver", simulatorserver)
-env.AppendTarget('simulatorserver')
+Alias("server", server)
+env.AppendTarget('server')
diff --git a/service/simulator/examples/server/service_provider.cpp b/service/simulator/examples/server/service_provider.cpp
deleted file mode 100644 (file)
index 3cb3c13..0000000
+++ /dev/null
@@ -1,613 +0,0 @@
-/******************************************************************
- *
- * 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 "simulator_manager.h"
-
-class AppLogger : public ILogger
-{
-    public:
-        void write(std::string time, ILogger::Level level, std::string message)
-        {
-            std::cout << "[APPLogger] " << time << " " << ILogger::getString(level) << " "
-                    << message;
-        }
-};
-std::shared_ptr<AppLogger> gAppLogger(new AppLogger());
-
-class SimLightResource
-{
-    public:
-        void startTest()
-        {
-            printMenu();
-            bool cont = true;
-            while (cont)
-            {
-                int choice = -1;
-                std::cout << "Enter your choice: ";
-                std::cin >> choice;
-                if (choice < 0 || choice > 10)
-                {
-                    std::cout << "Invaild choice !" << std::endl; continue;
-                }
-
-                switch (choice)
-                {
-                    case 1 : simulateResource(); break;
-                    case 2 : displayResource(); break;
-                    case 3 : deleteResource(); break;
-                    case 4 : updateAttributePower(); break;
-                    case 5 : updateAttributeIntensity(); break;
-                    case 6 : automateResourceUpdate(); break;
-                    case 7 : automateAttributeUpdate(); break;
-                    case 8 : stopAutomation(); break;
-                    case 9 : getObservers(); break;
-                    case 10: printMenu(); break;
-                    case 0: cont = false;
-                }
-            }
-        }
-
-    private:
-        void printMenu()
-        {
-            std::cout << "########### LIGHT RESOURCE TESTING ###########" << std::endl;
-            std::cout << "1. Simulate resource" << std::endl;
-            std::cout << "2. Display resource information" << std::endl;
-            std::cout << "3. Delete resource" << std::endl;
-            std::cout << "4. Update attribute \"power\"" << std::endl;
-            std::cout << "5. Update attribute \"intensity\"" << std::endl;
-            std::cout << "6. Automate resource update" << std::endl;
-            std::cout << "7. Automate attributes update" << std::endl;
-            std::cout << "8. Stop Automation" << std::endl;
-            std::cout << "9. Get Observers of a resource" << std::endl;
-            std::cout << "10: Help" << std::endl;
-            std::cout << "0. Exit" << std::endl;
-            std::cout << "#######################################" << std::endl;
-        }
-
-        int selectResource()
-        {
-            if (0 == m_resources.size())
-            {
-                std::cout << "No resouces!" << std::endl;
-                return -1;
-            }
-
-            int index = 1;
-            for (auto & resource : m_resources)
-            {
-                std::cout << index++ << ": " << resource->getURI().c_str() << std::endl;
-            }
-
-            int choice = -1;
-            std::cout << "Choose the resource: ";
-            std::cin >> choice;
-
-            if (choice < 1 || choice > index - 1)
-            {
-                std::cout << "Invalid choice !" << std::endl;
-                choice = -1;
-            }
-
-            return choice;
-        }
-
-        void onResourceModelChanged(const std::string &uri,
-                                    const SimulatorResourceModel &resModel)
-        {
-            std::cout << "[callback] Resource model is changed URI: " << uri.c_str()
-                    << " Count : " << resModel.size() << std::endl;
-            std::cout << "#### Modified attributes are ####" << std::endl;
-            for (auto & attribute : resModel.getAttributes())
-            {
-                std::cout << attribute.second.getName() << " :  "
-                        << attribute.second.valueToString().c_str() << std::endl;
-            }
-            std::cout << "########################" << std::endl;
-        }
-
-        void simulateResource()
-        {
-            SimulatorResourceServer::ResourceModelChangedCB callback = std::bind(
-                        &SimLightResource::onResourceModelChanged, this, std::placeholders::_1,
-                        std::placeholders::_2);
-
-            try
-            {
-                std::string configPath;
-                std::cout << "Enter RAML path: ";
-                std::cin>>configPath;
-                SimulatorResourceServerSP resource =
-                        SimulatorManager::getInstance()->createResource(configPath, callback);
-                m_resources.push_back(resource);
-                std::cout << "Resource created successfully! URI= " << resource->getURI().c_str()
-                        << std::endl;
-            }
-            catch (InvalidArgsException &e)
-            {
-                std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
-                        << e.what() << "]" << std::endl;
-            }
-            catch (SimulatorException &e)
-            {
-                std::cout << "SimulatorException occured [code : " << e.code() << " Detail: "
-                        << e.what() << "]" << std::endl;
-            }
-        }
-
-        void deleteResource()
-        {
-            int choice = -1;
-            std::cout << "1. Delete single resource" << std::endl;
-            std::cout << "2. Delete resources on resource types" << std::endl;
-            std::cout << "3. Delete all resources" << std::endl;
-
-            std::cout << "Enter your choice: ";
-            std::cin >> choice;
-            if (choice < 1 || choice > 3)
-            {
-                std::cout << "Invalid choice !" << std::endl;
-                return;
-            }
-
-            switch (choice)
-            {
-                case 1:
-                    {
-                        int index = selectResource();
-                        if (-1 == index)
-                            return;
-
-                        SimulatorManager::getInstance()->deleteResource(m_resources[index - 1]);
-                        std::cout << "Resource deleted successfully! " << std::endl;
-                        m_resources.erase(m_resources.begin() + (index - 1));
-
-                    } break;
-
-                case 2:
-                    {
-                        std::string resourceType;
-                        std::cout  << "Enter resource type:  ";
-                        std::cin >> resourceType;
-                        if (resourceType.empty())
-                        {
-                            std::cout << "Invalid resource type!" << std::endl;
-                            break;
-                        }
-
-                        try
-                        {
-                            SimulatorManager::getInstance()->deleteResource(resourceType);
-                            std::cout << "Resources of type \"" << resourceType << "\"" <<
-                                    " deleted successfully! " << std::endl;
-                            std::vector<SimulatorResourceServerSP>::iterator ite = m_resources.begin();
-                            while (ite != m_resources.end())
-                            {
-                                if (!resourceType.compare((*ite)->getResourceType()))
-                                {
-                                    ite = m_resources.erase(ite);
-                                    continue;
-                                }
-                                ite++;
-                            }
-                        }
-                        catch (InvalidArgsException &e)
-                        {
-                            std::cout << "InvalidArgsException occured [code : " << e.code()
-                                    << " Detail: " << e.what() << "]" << std::endl;
-                        }
-                        catch (SimulatorException &e)
-                        {
-                            std::cout << "SimulatorException occured [code : " << e.code()
-                                    << " Detail: " << e.what() << "]" << std::endl;
-                        }
-                    } break;
-
-                case 3:
-                    {
-                        SimulatorManager::getInstance()->deleteResource();
-                        std::cout << "All resources deleted successfully! " << std::endl;
-                        m_resources.clear();
-                    } break;
-            }
-
-        }
-
-        void updateAttributePower()
-        {
-            int index = selectResource();
-            if (-1 == index)
-                return;
-
-            SimulatorResourceServerSP resource = m_resources[index - 1];
-            SimulatorResourceModel resModel = resource->getModel();
-            SimulatorResourceModel::Attribute powerAttribute;
-            resModel.getAttribute("power", powerAttribute);
-
-            int allowedValuesSize = powerAttribute.getAllowedValuesSize();
-            if (0 == allowedValuesSize)
-            {
-                std::cout << "This attribute does not have allowed values!" << std::endl;
-                return;
-            }
-
-            std::cout << "Setting the new values from allowed values list to power attribute" <<
-                    std::endl;
-            // Update all possible values from allowed values
-            for (int index = 0; index < allowedValuesSize; index++)
-            {
-                // Update the new value and display the resource model after modifying
-                resource->updateFromAllowedValues("power", index);
-                std::cout << "Attribute value is modified ####" << std::endl;
-
-                // Display the resource to user to verify the changed attribute value
-                displayResource(resource);
-                std::cout << std::endl << std::endl;
-
-                // Get user input for continuing this operation
-                if ((index + 1) < allowedValuesSize)
-                {
-                    int choice;
-                    std::cout << "Would you like to change attribute value again ? (1/0): ";
-                    std::cin >> choice;
-                    if (0 == choice)
-                        break;
-                }
-            }
-
-            std::cout << "All the allowed values are tried!" << std::endl;
-        }
-
-        void updateAttributeIntensity()
-        {
-            int index = selectResource();
-            if (-1 == index)
-                return;
-
-            SimulatorResourceServerSP resource = m_resources[index - 1];
-            SimulatorResourceModel resModel = resource->getModel();
-            SimulatorResourceModel::Attribute intensityAttribute;
-            resModel.getAttribute("intensity", intensityAttribute);
-
-            int min, max;
-            intensityAttribute.getRange(min, max);
-            if (!min && !max)
-            {
-                std::cout << "This attribute does not have range!" << std::endl;
-                return;
-            }
-
-            std::cout << "Setting the new values from allowed values list to intensity attribute"
-                    << std::endl;
-            // Update all possible values from allowed values
-            for (int index = min; index <= max; index++)
-            {
-                // Update the new value and display the resource model after modifying
-                resource->updateAttributeValue("intensity", index);
-                std::cout << "Attribute value is modified ####" << std::endl;
-
-                // Display the resource to user to verify the changed attribute value
-                displayResource(resource);
-                std::cout << std::endl << std::endl;
-
-                // Get user input for continuing this operation
-                if ((index + 1) <= max)
-                {
-                    int choice;
-                    std::cout << "Would you like to change attribute value again ? (1/0): ";
-                    std::cin >> choice;
-                    if (0 == choice)
-                        break;
-                }
-            }
-
-            std::cout << "All the allowed values are tried!" << std::endl;
-        }
-
-        void displayResource()
-        {
-            int index = selectResource();
-            if (-1 == index)
-                return;
-
-            SimulatorResourceServerSP resource = m_resources[index - 1];
-            displayResource(resource);
-        }
-
-        void displayResource(SimulatorResourceServerSP resource)
-        {
-            std::cout << "#############################" << std::endl;
-            std::cout << "Name: " << resource->getName().c_str() << std::endl;
-            std::cout << "URI: " << resource->getURI().c_str() << std::endl;
-            std::cout << "R. Type: " << resource->getResourceType().c_str() << std::endl;
-            std::cout << "I. Type: " << resource->getInterfaceType().c_str() << std::endl;
-
-            // Attributes
-            SimulatorResourceModel resModel = resource->getModel();
-            std::map<std::string, SimulatorResourceModel::Attribute> attributes =
-                    resModel.getAttributes();
-            std::cout << "##### Attributes [" << attributes.size() << "]" << std::endl;
-            for (auto & attribute : attributes)
-            {
-                std::cout << (attribute.second).getName() << " :  {" << std::endl;
-                std::cout << "value: " << (attribute.second).valueToString().c_str() << std::endl;
-                int min, max;
-                (attribute.second).getRange(min, max);
-                std::cout << "min: " << min << std::endl;
-                std::cout << "max: " << max << std::endl;
-                std::cout << "allowed values : ";
-                std::cout << "[ ";
-                for (auto & value : (attribute.second).allowedValuesToString())
-                    std::cout << value << " ";
-                std::cout << "]" << std::endl;
-                std::cout << "}" << std::endl << std::endl;
-            }
-            std::cout << "#############################" << std::endl;
-        }
-
-        void onUpdateAutomationCompleted(const std::string &uri,
-                                         const int id)
-        {
-            std::cout << "Update automation is completed [URI: " << uri.c_str()
-                    << "  AutomationID: " << id << "] ###" << std::endl;
-        }
-
-        void automateResourceUpdate()
-        {
-            int index = selectResource();
-            if (-1 == index)
-                return;
-
-            AutomationType type = AutomationType::NORMAL;
-            int choice = 0;
-            std::cout << "Press 1 if you want recurrent automation: ";
-            std::cin >> choice;
-            if (1 == choice)
-                type = AutomationType::RECURRENT;
-
-            try
-            {
-                int id = m_resources[index - 1]->startUpdateAutomation(type, 500,
-                         std::bind(&SimLightResource::onUpdateAutomationCompleted, this,
-                                 std::placeholders::_1, std::placeholders::_2));
-
-                std::cout << "startUpdateAutomation() returned succces : " << id << std::endl;
-            }
-            catch (SimulatorException &e)
-            {
-                std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
-                        e.what() << "]" << std::endl;
-            }
-        }
-
-        void automateAttributeUpdate()
-        {
-            int index = selectResource();
-            if (-1 == index)
-                return;
-
-            SimulatorResourceServerSP resource = m_resources[index - 1];
-            SimulatorResourceModel resModel = resource->getModel();
-            std::map<std::string, SimulatorResourceModel::Attribute> attributes =
-                    resModel.getAttributes();
-            int size = 0;
-            for (auto & attribute : attributes)
-            {
-                std::cout << ++size << ": " << attribute.first.c_str() << std::endl;
-            }
-
-            if (0 == size)
-            {
-                std::cout << "This resource doest not contain any attributes!" << std::endl;
-                return;
-            }
-
-            int choice = -1;
-            std::cout << "Select the attribute which you want to automate for updation: " <<
-                    std::endl;
-            std::cin >> choice;
-            if (choice < 0 || choice > size)
-            {
-                std::cout << "Invalid selection!" << std::endl;
-                return;
-            }
-
-            int count = 0;
-            std::string attributeName;
-            for (auto & attribute : attributes)
-            {
-                if (count == choice - 1)
-                {
-                    attributeName = attribute.first;
-                    break;
-                }
-
-                count++;
-            }
-
-            AutomationType type = AutomationType::NORMAL;
-            std::cout << "Press 1 if you want recurrent automation: ";
-            std::cin >> choice;
-            if (1 == choice)
-                type = AutomationType::RECURRENT;
-
-            std::cout << "Requesting attribute automation for " << attributeName.c_str() <<
-                    std::endl;
-
-            try
-            {
-
-                int id = resource->startUpdateAutomation(attributeName, type, 500,
-                         std::bind(&SimLightResource::onUpdateAutomationCompleted, this,
-                                std::placeholders::_1, std::placeholders::_2));
-                std::cout << "startUpdateAutomation() returned succces : " << id << std::endl;
-            }
-            catch (SimulatorException &e)
-            {
-                std::cout << "SimulatorException occured [Error: " << e.code() << " Details: " <<
-                        e.what() << "]" << std::endl;
-            }
-        }
-
-        void stopAutomation()
-        {
-            int index = selectResource();
-            if (-1 == index)
-                return;
-
-            SimulatorResourceServerSP resource = m_resources[index - 1];
-
-            // Select the automation to stop
-            std::vector<int> ids;
-            {
-                std::vector<int> rids = resource->getResourceAutomationIds();
-                std::vector<int> aids = resource->getAttributeAutomationIds();
-                ids.insert(ids.end(), rids.begin(), rids.end());
-                ids.insert(ids.end(), aids.begin(), aids.end());
-            }
-
-            if (!ids.size())
-            {
-                std::cout << "No automation operation is going on this resource right now!" <<
-                        std::endl;
-                return;
-            }
-
-            for (auto & id : ids)
-                std::cout <<  id  << " ";
-
-            int automationid;
-            std::cout << "\nEnter automation id: " << std::endl;
-            std::cin >> automationid;
-            resource->stopUpdateAutomation(automationid);
-        }
-
-        void onObserverChanged(const std::string &uri, ObservationStatus state,
-                               const ObserverInfo &observerInfo)
-        {
-            std::cout << "[callback] Observer notification received..." << uri.c_str() << std::endl;
-            std::ostringstream out;
-            out << "ID:  " << (int) observerInfo.id << std::endl;
-            out << " [address: " << observerInfo.address << " port: " << observerInfo.port
-                    << "]" << std::endl;
-            std::cout << out.str();
-        }
-
-        void getObservers()
-        {
-            int index = selectResource();
-            if (-1 == index)
-                return;
-
-            SimulatorResourceServerSP resource = m_resources[index - 1];
-
-            SimulatorResourceServer::ObserverCB callback = std::bind(
-                        &SimLightResource::onObserverChanged, this, std::placeholders::_1,
-                        std::placeholders::_2, std::placeholders::_3);
-            resource->setObserverCallback(callback);
-
-            std::vector<ObserverInfo> observersList = resource->getObserversList();
-
-            std::cout << "##### Number of Observers [" << observersList.size() << "]" << std::endl;
-            for (auto & observerInfo : observersList)
-            {
-                std::cout << " ID :  " << (int) observerInfo.id << " [address: " <<
-                        observerInfo.address << " port: " << observerInfo.port << "]" << std::endl;
-            }
-            std::cout << "########################" << std::endl;
-        }
-
-    private:
-        std::vector<SimulatorResourceServerSP> m_resources;
-};
-
-void printMainMenu()
-{
-    std::cout << "############### MAIN MENU###############" << std::endl;
-    std::cout << "1. Test simulation of resource" << std::endl;
-    std::cout << "2. Set Logger" << std::endl;
-    std::cout << "3. Help" << std::endl;
-    std::cout << "0. Exit" << std::endl;
-    std::cout << "######################################" << std::endl;
-}
-
-void setLogger()
-{
-    std::cout << "1. Default console logger" << std::endl;
-    std::cout << "2. Default file logger" << std::endl;
-    std::cout << "3. custom logger" << std::endl;
-
-    int choice = -1;
-    std::cin >> choice;
-    if (choice <= 0 || choice > 3)
-    {
-        std::cout << "Invalid selection !" << std::endl;
-        return;
-    }
-
-    switch (choice)
-    {
-        case 1:
-            {
-                if (false == SimulatorManager::getInstance()->setConsoleLogger())
-                    std::cout << "Failed to set the default console logger" << std::endl;
-            } break;
-        case 2:
-            {
-                std::string filePath;
-                std::cout << "Enter the file path (without file name) : ";
-                std::cin >> filePath;
-                if (false == SimulatorManager::getInstance()->setFileLogger(filePath))
-                    std::cout << "Failed to set default file logger" << std::endl;
-            } break;
-        case 3: SimulatorManager::getInstance()->setLogger(gAppLogger);
-    }
-}
-
-int main(int argc, char *argv[])
-{
-    SimLightResource lightResource;
-
-    printMainMenu();
-    bool cont = true;
-    while (cont == true)
-    {
-        int choice = -1;
-        std::cout << "Enter your choice: ";
-        std::cin >> choice;
-        if (choice < 0 || choice > 3)
-        {
-            std::cout << "Invaild choice !" << std::endl; continue;
-        }
-
-        switch (choice)
-        {
-            case 1: lightResource.startTest();
-                std::cout << "Welcome back to main menu !" << std::endl;
-                break;
-            case 2: setLogger(); break;
-            case 3: printMainMenu(); break;
-            case 0: cont = false;
-        }
-    }
-
-    std::cout << "Terminating test !!!" << std::endl;
-}
diff --git a/service/simulator/examples/server/simulator_server.cpp b/service/simulator/examples/server/simulator_server.cpp
new file mode 100644 (file)
index 0000000..a02c24d
--- /dev/null
@@ -0,0 +1,489 @@
+/******************************************************************
+ *
+ * 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 "simulator_manager.h"
+
+std::vector<SimulatorSingleResourceSP> g_singleResources;
+std::vector<SimulatorCollectionResourceSP> g_collectionResources;
+
+class AppLogger : public ILogger
+{
+    public:
+        void write(std::string time, ILogger::Level level, std::string message)
+        {
+            std::cout << "[APPLogger] " << time << " " << ILogger::getString(level) << " "
+                      << message;
+        }
+};
+std::shared_ptr<AppLogger> gAppLogger(new AppLogger());
+
+int selectResource()
+{
+    if (0 == g_singleResources.size())
+    {
+        std::cout << "No resouces!" << std::endl;
+        return -1;
+    }
+
+    int index = 1;
+    for (auto &resource : g_singleResources)
+    {
+        std::cout << index++ << ": " << resource->getURI().c_str() << std::endl;
+    }
+
+    int choice = -1;
+    std::cout << "Choose the resource: ";
+    std::cin >> choice;
+
+    if (choice < 1 || choice > index - 1)
+    {
+        std::cout << "Invalid choice !" << std::endl;
+        choice = -1;
+    }
+
+    return choice;
+}
+
+void simulateResource()
+{
+    try
+    {
+        // Resource model change callback
+        SimulatorResource::ResourceModelUpdateCallback modelChangeCB =
+            [](const std::string & uri, const SimulatorResourceModel & resModel)
+        {
+            std::cout << "[callback] Resource model is changed URI: " << uri.c_str() << std::endl;
+            std::cout << "#### Modified attributes are ####" << std::endl;
+            std::cout << "#### Updated resource model ####" << std::endl;
+            std::cout << resModel.asString() << std::endl;
+            std::cout << "########################" << std::endl;
+        };
+
+        // Observer added/removed callback
+        SimulatorResource::ObserverCallback observerCB =
+            [] (const std::string & uri, ObservationStatus state, const ObserverInfo & observerInfo)
+        {
+            std::cout << "[callback] Observer notification received..." << uri << std::endl;
+
+            std::ostringstream out;
+            out << "ID:  " << (int) observerInfo.id << std::endl;
+            out << " [address: " << observerInfo.address << " port: " << observerInfo.port
+                << "]" << std::endl;
+            out << "State: " << ((state == ObservationStatus::REGISTER) ? "REGISTER" : "UNREGISTER") <<
+                std::endl;
+            std::cout << out.str();
+        };
+
+        // Get the RAML file path from user
+        std::string configPath;
+        std::cout << "Enter RAML path: ";
+        std::cin >> configPath;
+
+        SimulatorResourceSP resource =
+            SimulatorManager::getInstance()->createResource(configPath);
+
+        // Add resource to appropriate list
+        if (SimulatorResource::Type::SINGLE_RESOURCE == resource->getType())
+        {
+            std::cout << "Single type resource created [URI:  " << resource->getURI() << " ]" << std::endl;
+            SimulatorSingleResourceSP singleRes =
+                std::dynamic_pointer_cast<SimulatorSingleResource>(resource);
+            if (!singleRes)
+            {
+                std::cout << "Error occured while converting SimulatorResource to SimulatorSingleResource!" << std::endl;
+                return;
+            }
+
+            singleRes->setModelChangeCallback(modelChangeCB);
+            singleRes->setObserverCallback(observerCB);
+            g_singleResources.push_back(singleRes);
+        }
+        else
+        {
+            std::cout << "Collection type resource created [URI:  " << resource->getURI() << " ]" << std::endl;
+            SimulatorCollectionResourceSP collectionRes =
+                std::dynamic_pointer_cast<SimulatorCollectionResource>(resource);
+            if (!collectionRes)
+            {
+                std::cout << "Error occured while converting SimulatorResource to SimulatorCollectionResource!" << std::endl;
+                return;
+            }
+
+            collectionRes->setObserverCallback(observerCB);
+            g_collectionResources.push_back(collectionRes);
+        }
+    }
+    catch (InvalidArgsException &e)
+    {
+        std::cout << "InvalidArgsException occured [code : " << e.code() << " Details: "
+                  << e.what() << "]" << std::endl;
+    }
+    catch (SimulatorException &e)
+    {
+        std::cout << "SimulatorException occured [code : " << e.code() << " Details: "
+                  << e.what() << "]" << std::endl;
+    }
+}
+
+void displayResource()
+{
+    int index = selectResource();
+    if (-1 == index)
+        return;
+
+    SimulatorSingleResourceSP resource = g_singleResources[index - 1];
+
+    std::cout << "#############################" << std::endl;
+    std::cout << "Name: " << resource->getName() << std::endl;
+    std::cout << "URI: " << resource->getURI() << std::endl;
+    std::cout << "Resource type: " << resource->getResourceType() << std::endl;
+    std::cout << "Interface type:";
+    for (auto &interfaceType : resource->getInterface())
+        std::cout << " " << interfaceType << std::endl;
+
+    // Attributes
+    std::cout << "##### Representation #####" << std::endl;
+    std::cout << resource->getResourceModel().asString() << std::endl;
+    std::cout << "#############################" << std::endl;
+}
+
+void startResource()
+{
+    int index = selectResource();
+    if (-1 == index)
+        return;
+
+    SimulatorSingleResourceSP resource = g_singleResources[index - 1];
+    resource->start();
+    std::cout << "Resource started!" << std::endl;
+}
+
+void stopResource()
+{
+    int index = selectResource();
+    if (-1 == index)
+        return;
+
+    SimulatorSingleResourceSP resource = g_singleResources[index - 1];
+    resource->stop();
+    std::cout << "Resource stopped!" << std::endl;
+}
+
+void automateResourceUpdate()
+{
+    SimulatorSingleResource::AutoUpdateCompleteCallback callback =
+        [](const std::string & uri, const int id)
+    {
+        std::cout << "Update automation is completed [URI: " << uri
+                  << "  AutomationID: " << id << "] ###" << std::endl;
+    };
+
+    int index = selectResource();
+    if (-1 == index)
+        return;
+
+    AutoUpdateType type = AutoUpdateType::ONE_TIME;
+    int choice = 0;
+    std::cout << "Press 1 if you want recurrent automation: ";
+    std::cin >> choice;
+    if (1 == choice)
+        type = AutoUpdateType::REPEAT;
+
+    try
+    {
+        int id = g_singleResources[index - 1]->startResourceUpdation(type, -1, callback);
+
+        std::cout << "startUpdateAutomation() returned succces : " << id << std::endl;
+    }
+    catch (SimulatorException &e)
+    {
+        std::cout << "SimulatorException occured [code : " << e.code() << " Details: " <<
+                  e.what() << "]" << std::endl;
+    }
+}
+
+void automateAttributeUpdate()
+{
+    SimulatorSingleResource::AutoUpdateCompleteCallback callback =
+        [](const std::string & uri, const int id)
+    {
+        std::cout << "Update automation is completed [URI: " << uri
+                  << "  AutomationID: " << id << "] ###" << std::endl;
+    };
+
+    int index = selectResource();
+    if (-1 == index)
+        return;
+
+    SimulatorSingleResourceSP resource = g_singleResources[index - 1];
+    std::map<std::string, SimulatorResourceAttribute> attributes =
+        resource->getAttributes();
+    int size = 0;
+    for (auto &attributeEntry : attributes)
+    {
+        std::cout << ++size << ": " << attributeEntry.first << std::endl;
+    }
+
+    if (0 == size)
+    {
+        std::cout << "This resource doest not contain any attributes!" << std::endl;
+        return;
+    }
+
+    int choice = -1;
+    std::cout << "Select the attribute which you want to automate for updation: " <<
+              std::endl;
+    std::cin >> choice;
+    if (choice < 0 || choice > size)
+    {
+        std::cout << "Invalid selection!" << std::endl;
+        return;
+    }
+
+    int count = 0;
+    std::string attributeName;
+    for (auto &attributeEntry : attributes)
+    {
+        if (count == choice - 1)
+        {
+            attributeName = attributeEntry.first;
+            break;
+        }
+
+        count++;
+    }
+
+    AutoUpdateType type = AutoUpdateType::ONE_TIME;
+    std::cout << "Press 1 if you want recurrent automation: ";
+    std::cin >> choice;
+    if (1 == choice)
+        type = AutoUpdateType::REPEAT;
+
+    std::cout << "Requesting attribute automation for " << attributeName <<
+              std::endl;
+
+    try
+    {
+        int id = resource->startAttributeUpdation(attributeName, type, -1, callback);
+        std::cout << "startUpdateAutomation() returned succces : " << id << std::endl;
+    }
+    catch (SimulatorException &e)
+    {
+        std::cout << "SimulatorException occured [Error: " << e.code() << " Details: " <<
+                  e.what() << "]" << std::endl;
+    }
+}
+
+void stopAutomation()
+{
+    int index = selectResource();
+    if (-1 == index)
+        return;
+
+    SimulatorSingleResourceSP resource = g_singleResources[index - 1];
+
+    // Select the automation to stop
+    std::vector<int> ids;
+    {
+        std::vector<int> rids = resource->getResourceUpdations();
+        std::vector<int> aids = resource->getAttributeUpdations();
+        ids.insert(ids.end(), rids.begin(), rids.end());
+        ids.insert(ids.end(), aids.begin(), aids.end());
+    }
+
+    if (!ids.size())
+    {
+        std::cout << "No automation operation is going on this resource right now!" <<
+                  std::endl;
+        return;
+    }
+
+    for (auto &id : ids)
+    {
+        std::cout <<  id  << " ";
+        resource->stopUpdation(id);
+    }
+}
+
+void getObservers()
+{
+    int index = selectResource();
+    if (-1 == index)
+        return;
+
+    SimulatorSingleResourceSP resource = g_singleResources[index - 1];
+
+    std::vector<ObserverInfo> observersList = resource->getObservers();
+
+    std::cout << "##### Number of Observers [" << observersList.size() << "]" << std::endl;
+    for (auto &observerInfo : observersList)
+    {
+        std::cout << " ID :  " << (int) observerInfo.id << " [address: " <<
+                  observerInfo.address << " port: " << observerInfo.port << "]" << std::endl;
+    }
+    std::cout << "########################" << std::endl;
+}
+
+void printMainMenu()
+{
+    std::cout << "############### MAIN MENU###############" << std::endl;
+    std::cout << "1. Simulate resource" << std::endl;
+    std::cout << "2. Display resource information" << std::endl;
+    std::cout << "3. Start resource" << std::endl;
+    std::cout << "4. Stop resource" << std::endl;
+    std::cout << "5. Automate resource update" << std::endl;
+    std::cout << "6. Automate attributes update" << std::endl;
+    std::cout << "7. Stop Automation" << std::endl;
+    std::cout << "8. Get Observers of a resource" << std::endl;
+    std::cout << "9. Set Logger" << std::endl;
+    std::cout << "10. Set Device Info" << std::endl;
+    std::cout << "11. Set Platform Info" << std::endl;
+    std::cout << "12. Add Interface" << std::endl;
+    std::cout << "13. Help" << std::endl;
+    std::cout << "0. Exit" << std::endl;
+    std::cout << "######################################" << std::endl;
+}
+
+void setLogger()
+{
+    std::cout << "1. Default console logger" << std::endl;
+    std::cout << "2. Default file logger" << std::endl;
+    std::cout << "3. custom logger" << std::endl;
+
+    int choice = -1;
+    std::cin >> choice;
+    if (choice <= 0 || choice > 3)
+    {
+        std::cout << "Invalid selection !" << std::endl;
+        return;
+    }
+
+    switch (choice)
+    {
+        case 1:
+            {
+                if (false == SimulatorManager::getInstance()->setConsoleLogger())
+                    std::cout << "Failed to set the default console logger" << std::endl;
+            } break;
+        case 2:
+            {
+                std::string filePath;
+                std::cout << "Enter the file path (without file name) : ";
+                std::cin >> filePath;
+                if (false == SimulatorManager::getInstance()->setFileLogger(filePath))
+                    std::cout << "Failed to set default file logger" << std::endl;
+            } break;
+        case 3: SimulatorManager::getInstance()->setLogger(gAppLogger);
+    }
+}
+
+void setDeviceInfo()
+{
+    try
+    {
+        SimulatorManager::getInstance()->setDeviceInfo("IoTivity Simulator Linux Sample");
+        std::cout << "Setting Device Info is successful" << std::endl;
+    }
+    catch (InvalidArgsException &e)
+    {
+        std::cout << "InvalidArgsException occured [code : " << e.code() << " Details: "
+                  << e.what() << "]" << std::endl;
+    }
+    catch (SimulatorException &e)
+    {
+        std::cout << "SimulatorException occured [code : " << e.code() << " Details: "
+                  << e.what() << "]" << std::endl;
+    }
+}
+
+void setPlatformInfo()
+{
+    PlatformInfo pInfo;
+    pInfo.setPlatformID("Samsung Platform Identifier");
+    pInfo.setFirmwareVersion("FirwareVersion01");
+    pInfo.setHardwareVersion("HardwareVersion01");
+    pInfo.setManufacturerName("Samsung");
+    pInfo.setManufacturerUrl("www.samsung.com");
+    pInfo.setModelNumber("Samsung Model Num01");
+    pInfo.setOSVersion("OSVersion01");
+    pInfo.setPlatformVersion("PlatformVersion01");
+    pInfo.setSupportUrl("http://www.samsung.com/support");
+    pInfo.setSystemTime("2015-09-10T11:10:30Z");
+    pInfo.setDateOfManfacture("2015-09-10T11:10:30Z");
+
+    try
+    {
+        SimulatorManager::getInstance()->setPlatformInfo(pInfo);
+        std::cout << "Setting Platform Info is successful" << std::endl;
+    }
+    catch (SimulatorException &e)
+    {
+        std::cout << "SimulatorException occured [code : " << e.code() << " Details: "
+                  << e.what() << "]" << std::endl;
+    }
+}
+
+void addInterface()
+{
+
+    int index = selectResource();
+    if (-1 == index)
+        return;
+
+    SimulatorSingleResourceSP resource = g_singleResources[index - 1];
+    resource->addInterface("oic.if.s");
+    resource->addInterface("oic.if.a");
+}
+
+int main(int argc, char *argv[])
+{
+    printMainMenu();
+    bool cont = true;
+    while (cont == true)
+    {
+        int choice = -1;
+        std::cout << "Enter your choice: ";
+        std::cin >> choice;
+        if (choice < 0 || choice > 14)
+        {
+            std::cout << "Invaild choice !" << std::endl; continue;
+        }
+
+        switch (choice)
+        {
+            case 1 : simulateResource(); break;
+            case 2 : displayResource(); break;
+            case 3 : startResource(); break;
+            case 4 : stopResource(); break;
+            case 5 : automateResourceUpdate(); break;
+            case 6 : automateAttributeUpdate(); break;
+            case 7 : stopAutomation(); break;
+            case 8 : getObservers(); break;
+            case 9 : setLogger(); break;
+            case 10: setDeviceInfo(); break;
+            case 11: setPlatformInfo(); break;
+            case 12: addInterface(); break;
+            case 13: printMainMenu(); break;
+            case 0: cont = false;
+        }
+    }
+
+    std::cout << "Terminating test !!!" << std::endl;
+}
index 21c7faa..8da974e 100644 (file)
@@ -34,6 +34,7 @@ enum class ObserveType
 
 enum class RequestType
 {
+    RQ_TYPE_UNKNOWN,
     RQ_TYPE_GET,
     RQ_TYPE_PUT,
     RQ_TYPE_POST,
diff --git a/service/simulator/inc/simulator_collection_resource.h b/service/simulator/inc/simulator_collection_resource.h
new file mode 100644 (file)
index 0000000..71e8e7c
--- /dev/null
@@ -0,0 +1,78 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file   simulator_collection_resource.h
+ *
+ * @brief   This file provides a class and API to access simulated collection resource.
+ */
+
+#ifndef SIMULATOR_COLLECTION_RESOURCE_H_
+#define SIMULATOR_COLLECTION_RESOURCE_H_
+
+#include "simulator_resource.h"
+
+/**
+ * @class   SimulatorCollectionResource
+ * @brief   This class provides a set of APIs for handling simulated collection resource.
+ */
+class SimulatorCollectionResource : public SimulatorResource
+{
+    public:
+
+        /**
+         * API to get list of resources types which collection supports.
+         *
+         * @return List of supported resources types.
+         */
+        virtual std::vector<std::string> getSupportedResources() = 0;
+
+        /**
+         * API to add a child resource to collection.
+         *
+         * @param resource - SimulatorResource shared object.
+         */
+        virtual void addChildResource(const std::shared_ptr<SimulatorResource> &resource) = 0;
+
+        /**
+         * API to remove a child resource from collection.
+         *
+         * @param resource - SimulatorResource shared object.
+         */
+        virtual void removeChildResource(const std::shared_ptr<SimulatorResource> &resource) = 0;
+
+        /**
+         * API to remove a child resource from collection.
+         *
+         * @param uri - URI of child resource to be removed.
+         */
+        virtual void removeChildResource(const std::string &uri) = 0;
+
+        /**
+         * API to get child resources of collection.
+         *
+         * @return List of child resources of collection.
+         */
+        virtual std::vector<SimulatorResourceSP> getChildResources() = 0;
+};
+
+typedef std::shared_ptr<SimulatorCollectionResource> SimulatorCollectionResourceSP;
+
+#endif
index 76092a2..0bacb54 100644 (file)
@@ -75,6 +75,7 @@ typedef enum
     SIMULATOR_TYPE_MISMATCH,
     SIMULATOR_BAD_VALUE,
     SIMULATOR_BAD_OBJECT,
+    SIMULATOR_BAD_SCHEMA,
     /** Simulator specific error codes - END */
 
     SIMULATOR_ERROR = 255
index 662ea3e..2ebb10a 100644 (file)
 #ifndef SIMULATOR_MANAGER_H_
 #define SIMULATOR_MANAGER_H_
 
-#include "simulator_server_types.h"
 #include "simulator_client_types.h"
 #include "simulator_device_info.h"
 #include "simulator_platform_info.h"
-#include "simulator_resource_server.h"
+#include "simulator_single_resource.h"
+#include "simulator_collection_resource.h"
 #include "simulator_remote_resource.h"
 #include "simulator_exceptions.h"
 #include "simulator_logger.h"
 
-typedef std::function<void(DeviceInfo &deviceInfo)> DeviceInfoCallback;
-typedef std::function<void(PlatformInfo &platformInfo)> PlatformInfoCallback;
+typedef std::function<void(const std::string &hostUri, DeviceInfo &deviceInfo)> DeviceInfoCallback;
+typedef std::function<void(const std::string &hostUri, PlatformInfo &platformInfo)>
+PlatformInfoCallback;
 
 /**
  * @class   SimulatorManager
@@ -57,15 +58,13 @@ class SimulatorManager
          * RAML file.
          *
          * @param configPath - RAML configuration file path.
-         * @param callback - Callback method for receiving notifications when resource model changes.
          *
-         * @return SimulatorResourceServer shared object representing simulated/created resource.
+         * @return SimulatorResource shared object representing simulated/created resource.
          *
          *  NOTE: API would throw @InvalidArgsException when invalid arguments passed, and
           * @SimulatorException if any other error occured.
          */
-        std::shared_ptr<SimulatorResourceServer> createResource(const std::string &configPath,
-                SimulatorResourceServer::ResourceModelChangedCB callback);
+        std::shared_ptr<SimulatorResource> createResource(const std::string &configPath);
 
         /**
          * This method is for creating multiple resources of same type based on the input data
@@ -75,45 +74,46 @@ class SimulatorManager
          * @param count - Number of resource to be created.
          * @param callback - Callback method for receiving notifications when resource model changes.
          *
-         * @return vector of SimulatorResourceServer shared objects representing simulated/created
+         * @return vector of SimulatorResource shared objects representing simulated/created
          * resources.
          *
          * NOTE: API would throw @InvalidArgsException when invalid arguments passed, and
          * @SimulatorException if any other error occured.
          */
-        std::vector<std::shared_ptr<SimulatorResourceServer>> createResource(
-                    const std::string &configPath, unsigned short count,
-                    SimulatorResourceServer::ResourceModelChangedCB callback);
+        std::vector<std::shared_ptr<SimulatorResource>> createResource(
+                    const std::string &configPath, unsigned int count);
 
         /**
-         * This method is for obtaining a list of created resources.
+         * This method is for creating single type resource.
+         *
+         * @param name - Name of resource to be set if resource created successfully.
+         * @param uri - URI on which resource to be created.
+         * @param resourceType - Resource type of resource to be set if resource
+         * created successfully.
          *
-         * @param resourceType - Resource type. Empty value will fetch all resources.
-         *                                          Default value is empty string.
+         * @return shared object of @SimulatorSingleResource.
          *
-         * @return vector of SimulatorResourceServer shared objects representing simulated/created
+         * NOTE: API would throw @InvalidArgsException when invalid arguments passed, and
+         * @SimulatorException if any other error occured.
          */
-        std::vector<std::shared_ptr<SimulatorResourceServer>> getResources(
-                    const std::string &resourceType = "");
-
-        /**
-          * This method is for deleting/unregistering resource.
-          *
-          * @param resource - SimulatorResourceServer shared object.
-          *
-          * NOTE: API would throw @InvalidArgsException when invalid arguments passed
-          */
-        void deleteResource(const std::shared_ptr<SimulatorResourceServer> &resource);
+        std::shared_ptr<SimulatorSingleResource> createSingleResource(
+            const std::string &name, const std::string &uri, const std::string &resourceType);
 
         /**
-          * This method is for deleting multiple resources based on resource type.
-          *
-          * @param resourceType - Resource type. Empty value will delete all the resources.
-          *                                          Default value is empty string.
-          *
-          * NOTE: API would throw @InvalidArgsException when invalid arguments passed
-          */
-        void deleteResource(const std::string &resourceType = "");
+         * This method is for creating collection type resource.
+         *
+         * @param name - Name of resource to be set if resource created successfully.
+         * @param uri - URI on which resource to be created.
+         * @param resourceType - Resource type of resource to be set if resource
+         * created successfully.
+         *
+         * @return shared object of @SimulatorCollectionResource.
+         *
+         * NOTE: API would throw @InvalidArgsException when invalid arguments passed, and
+         * @SimulatorException if any other error occured.
+         */
+        std::shared_ptr<SimulatorCollectionResource> createCollectionResource(
+            const std::string &name, const std::string &uri, const std::string &resourceType);
 
         /**
          * API for discovering all type of resources.
@@ -150,7 +150,7 @@ class SimulatorManager
          *
          * NOTE: API throws @InvalidArgsException and @SimulatorException on error.
          */
-        void getDeviceInfo(DeviceInfoCallback callback);
+        void getDeviceInfo(const std::string &host, DeviceInfoCallback callback);
 
         /**
          * API for registering device information with stack.
@@ -171,7 +171,7 @@ class SimulatorManager
          *
          * NOTE: API throws @InvalidArgsException and @SimulatorException on error.
          */
-        void getPlatformInfo(PlatformInfoCallback callback);
+        void getPlatformInfo(const std::string &host, PlatformInfoCallback callback);
 
         /**
          * API for registering platform information with stack.
index 5388bcc..84da19a 100644 (file)
 
 #include "simulator_client_types.h"
 #include "simulator_resource_model.h"
+#include "simulator_request_model.h"
+#include "simulator_uncopyable.h"
+#include "simulator_exceptions.h"
 
 /**
  * @class   SimulatorRemoteResource
- * @brief   This class provides a set of functions for the client to hande the resources currently running on the servers.
+ * @brief   This class provides a API for handling discovered resources.
  */
-class SimulatorRemoteResource
+class SimulatorRemoteResource : private UnCopyable
 {
     public:
 
         /**
          * Callback method for receiving response for GET, PUT and POST requests.
          *
+         * @param uid - Identifier of remote resource.
+         * @param result - Result of the request mapped to one of the enum value
+         * in @SimulatorResult.
+         * @param resModel - Resource representation model.
          */
-        typedef std::function<void (std::string, SimulatorResult, SimulatorResourceModelSP)>
+        typedef std::function<void (const std::string &uid, SimulatorResult result,
+                                    const SimulatorResourceModel &resModel)>
         ResponseCallback;
 
+        typedef ResponseCallback GetResponseCallback;
+        typedef ResponseCallback PutResponseCallback;
+        typedef ResponseCallback PostResponseCallback;
+        typedef ResponseCallback DeleteResponseCallback;
+
         /**
-         * Callback method for receiving model change notifications from remote resource.
+         * Callback method for receiving representation change notifications from remote resource.
          *
+         * @param uid - Identifier of remote resource.
+         * @param result - Result of the request mapped to one of the enum value
+         * in @SimulatorResult.
+         * @param resModel - Resource representation model.
+         * @param id - Notificaiton sequence id.
          */
-        typedef std::function<void (std::string, SimulatorResult, SimulatorResourceModelSP, int)>
+        typedef std::function<void (const std::string &uid, SimulatorResult result,
+                                    const SimulatorResourceModel &resModel, int id)>
         ObserveNotificationCallback;
 
         /**
          * Callback method for receiving auto request generation and verifiction progress state.
          *
+         * @param uid - Identifier of remote resource.
+         * @param id - Auto request generation id.
+         * @param sate - Auto request generation and validation state.
          */
-        typedef std::function<void(std::string, int, OperationState)>
-        StateCallback;
+        typedef std::function<void(const std::string &uid, int id, OperationState state)>
+        AutoRequestGenerationCallback;
 
         /**
          * API for getting URI of resource.
          *
          * @return URI of resource.
-         *
          */
         virtual std::string getURI() const = 0;
 
@@ -72,7 +93,6 @@ class SimulatorRemoteResource
          * API for getting host address of resource.
          *
          * @return Host address of resource.
-         *
          */
         virtual std::string getHost() const = 0;
 
@@ -80,7 +100,6 @@ class SimulatorRemoteResource
          * API for getting unique id of resource.
          *
          * @return ID of resource.
-         *
          */
         virtual std::string getID() const = 0;
 
@@ -89,7 +108,6 @@ class SimulatorRemoteResource
          * API for getting connectivity type of resource.
          *
          * @return enum SimulatorConnectivityType value
-         *
          */
         virtual SimulatorConnectivityType getConnectivityType() const = 0;
 
@@ -97,7 +115,6 @@ class SimulatorRemoteResource
          * API for getting resource types bound with the resource.
          *
          * @return vector of strings representing resource types.
-         *
          */
         virtual std::vector < std::string > getResourceTypes() const = 0;
 
@@ -105,52 +122,163 @@ class SimulatorRemoteResource
          * API for getting interface types bound with the resource.
          *
          * @return vector of strings representing interface types.
-         *
          */
-        virtual std::vector < std::string > getResourceInterfaces() const = 0;
+        virtual std::vector < std::string > getInterface() const = 0;
 
         /**
          * API to check whether resource can be observed or not.
          *
          * @return true if resource is observable, otherwise false.
-         *
          */
         virtual bool isObservable() const = 0;
 
+        /**
+         * API to send observe request to remote resource.
+         *
+         * @param type - Observe request type.
+         * @param callback - callback for receiving notifications from remote resource
+         * asynchronously.
+         */
         virtual void observe(ObserveType type, ObserveNotificationCallback callback) = 0;
 
+        /**
+         * API to send cancel observe request to remote resource.
+         *
+         */
         virtual void cancelObserve() = 0;
 
+        /**
+         * API to send GET request to remote resource.
+         *
+         * @param callback - callback for receiving response from remote resource
+         * asynchronously.
+         */
+        virtual void get(const GetResponseCallback &callback) = 0;
+
+        /**
+         * API to send GET request to remote resource.
+         *
+         * @param queryParams - Query parameters string.
+         * @param callback - callback for receiving response from remote resource
+         * asynchronously.
+         */
         virtual void get(const std::map<std::string, std::string> &queryParams,
-                         ResponseCallback callback) = 0;
+                         const GetResponseCallback &) = 0;
 
+        /**
+         * API to send GET request to remote resource.
+         *
+         * @param interfaceType - Interace type on which request to be sent.
+         * @param queryParams - Query parameters string.
+         * @param callback - callback for receiving response from remote resource
+         * asynchronously.
+         */
         virtual void get(const std::string &interfaceType,
                          const std::map<std::string, std::string> &queryParams,
-                         ResponseCallback callback) = 0;
+                         const GetResponseCallback &) = 0;
+
+        /**
+         * API to send PUT request to remote resource.
+         *
+         * @param representation - Resource representation to be sent with request.
+         * @param callback - callback for receiving response from remote resource
+         * asynchronously.
+         */
+        virtual void put(const SimulatorResourceModel &representation,
+                         const PutResponseCallback &callback) = 0;
 
+
+        /**
+         * API to send PUT request to remote resource.
+         *
+         * @param queryParams - Query parameters string.
+         * @param representation - Resource representation to be sent with request.
+         * @param callback - callback for receiving response from remote resource
+         * asynchronously.
+         */
         virtual void put(const std::map<std::string, std::string> &queryParams,
-                         SimulatorResourceModelSP representation,
-                         ResponseCallback callback) = 0;
+                         const SimulatorResourceModel &representation,
+                         const PutResponseCallback &callback) = 0;
 
+        /**
+         * API to send PUT request to remote resource.
+         *
+         * @param interfaceType - Interace type on which request to be sent.
+         * @param queryParams - Query parameters string.
+         * @param representation - Resource representation to be sent with request.
+         * @param callback - callback for receiving response from remote resource
+         * asynchronously.
+         */
         virtual void put(const std::string &interfaceType,
                          const std::map<std::string, std::string> &queryParams,
-                         SimulatorResourceModelSP representation,
-                         ResponseCallback callback) = 0;
+                         const SimulatorResourceModel &representation,
+                         const PutResponseCallback &callback) = 0;
 
+        /**
+         * API to send POST request to remote resource.
+         *
+         * @param representation - Resource representation to be sent with request.
+         * @param callback - callback for receiving response from remote resource
+         * asynchronously.
+         */
+        virtual void post(const SimulatorResourceModel &representation,
+                          const PostResponseCallback &callback) = 0;
+
+        /**
+         * API to send POST request to remote resource.
+         *
+         * @param queryParams - Query parameters string.
+         * @param representation - Resource representation to be sent with request.
+         * @param callback - callback for receiving response from remote resource
+         * asynchronously.
+         */
         virtual void post(const std::map<std::string, std::string> &queryParams,
-                          SimulatorResourceModelSP representation,
-                          ResponseCallback callback) = 0;
+                          const SimulatorResourceModel &representation,
+                          const PostResponseCallback &callback) = 0;
 
+        /**
+         * API to send POST request to remote resource.
+         *
+         * @param interfaceType - Interace type on which request to be sent.
+         * @param queryParams - Query parameters string.
+         * @param representation - Resource representation to be sent with request.
+         * @param callback - callback for receiving response from remote resource
+         * asynchronously.
+         */
         virtual void post(const std::string &interfaceType,
                           const std::map<std::string, std::string> &queryParams,
-                          SimulatorResourceModelSP representation,
-                          ResponseCallback callback) = 0;
+                          const SimulatorResourceModel &representation,
+                          const PostResponseCallback &callback) = 0;
 
-        virtual int startVerification(RequestType type, StateCallback callback) = 0;
+        /**
+         * API to configure resource from RAML file.
+         *
+         * @param path - Path to RAML file.
+         *
+         * @return Map of request models representing the format of requests.
+         */
+        virtual std::map<RequestType, SimulatorRequestModel> configure(
+            const std::string &path) = 0;
 
-        virtual void stopVerification(int id) = 0;
+        /**
+         * API to start generating requests and send to remote resource.
+         *
+         * @param type - Request type.
+         * @param callback - callback for receiving progress state of auto request
+         * generation process.
+         *
+         * @return Identifier of auto request generating session. This id should be used
+         * for stopping the same.
+         */
+        virtual int startAutoRequesting(RequestType type,
+                                        AutoRequestGenerationCallback callback) = 0;
 
-        virtual void configure(const std::string &path) = 0;
+        /**
+         * API to stop generating requests and send to remote resource.
+         *
+         * @param id - Identifier of auto request generating session.
+         */
+        virtual void stopAutoRequesting(int id) = 0;
 };
 
 typedef std::shared_ptr<SimulatorRemoteResource> SimulatorRemoteResourceSP;
diff --git a/service/simulator/inc/simulator_request_model.h b/service/simulator/inc/simulator_request_model.h
new file mode 100644 (file)
index 0000000..eb3b2a6
--- /dev/null
@@ -0,0 +1,46 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_REQUEST_MODEL_H_
+#define SIMULATOR_REQUEST_MODEL_H_
+
+#include "simulator_client_types.h"
+#include "simulator_resource_model_schema.h"
+
+class SimulatorRequestModel
+{
+    public:
+        SimulatorRequestModel();
+        SimulatorRequestModel(RequestType type);
+
+        RequestType getType() const;
+        std::map<std::string, std::vector<std::string>> getQueryParams() const;
+        std::shared_ptr<SimulatorResourceModelSchema> getRequestBodySchema() const;
+
+        void setQueryParams(const std::map<std::string, std::vector<std::string>> &queryParams);
+        void setRequestBodySchema(const std::shared_ptr<SimulatorResourceModelSchema> &repSchema);
+
+    private:
+        RequestType m_type;
+        std::map<std::string, std::vector<std::string>> m_queryParams;
+        std::shared_ptr<SimulatorResourceModelSchema> m_reqBodySchema;
+};
+
+#endif
diff --git a/service/simulator/inc/simulator_resource.h b/service/simulator/inc/simulator_resource.h
new file mode 100644 (file)
index 0000000..150873d
--- /dev/null
@@ -0,0 +1,285 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file simulator_resource.h
+ *
+ * @brief This file provides a abstract class SimulatorResource, for representing simulated resource.
+ */
+
+#ifndef SIMULATOR_RESOURCE_H_
+#define SIMULATOR_RESOURCE_H_
+
+#include "simulator_uncopyable.h"
+#include "simulator_resource_model.h"
+#include "simulator_exceptions.h"
+
+enum class ObservationStatus
+{
+    REGISTER,
+    UNREGISTER
+};
+
+typedef struct
+{
+    uint8_t id;
+    std::string address;
+    uint16_t port;
+} ObserverInfo;
+
+/**
+ * @class   SimulatorResource
+ * @brief   Abstract class represents simulated resource.
+ */
+class SimulatorResource : private UnCopyable
+{
+    public:
+        enum class Type
+        {
+            SINGLE_RESOURCE,
+            COLLECTION_RESOURCE
+        };
+
+        /**
+         * Callback method for receiving notifications when resource representation model changes.
+         *
+         * @param uri - URI of resource whose representation model got changed.
+         * @param resModel - Resource model.
+         */
+        typedef std::function<void (const std::string &uri, const SimulatorResourceModel &resModel)>
+        ResourceModelUpdateCallback;
+
+        /**
+         * Callback method for receiving notifications when observer is registered/unregistered
+         * with resource.
+         *
+         * @param uri - Resource URI
+         * @param state - OBSERVE_REGISTER if observer is registered, otherwise OBSERVE_UNREGISTER.
+         * @param observerInfo - Information about observer.
+         */
+        typedef std::function<void (const std::string &uri, ObservationStatus state,
+                                    const ObserverInfo &observerInfo)> ObserverCallback;
+
+        /**
+         * API to get the type which indicates whether resource is single or collection resource.
+         *
+         * @return Type of resource.
+         */
+        virtual bool isCollection() const;
+
+        /**
+         * API to get the type which indicates whether resource is single or collection resource.
+         *
+         * @return Type of resource.
+         */
+        virtual SimulatorResource::Type getType() const;
+
+        /**
+         * API to get the name of the resource.
+         *
+         * @return Resource name.
+         */
+        virtual std::string getName() const;
+
+        /**
+         * API to get the resource URI.
+         *
+         * @return Resource URI.
+         */
+        virtual std::string getURI() const;
+
+        /**
+         * API to get the resource type.
+         *
+         * @return Resource type.
+         */
+        virtual std::string getResourceType() const;
+
+        /**
+         * API to get the interfaces resource is bound with.
+         *
+         * @return Interface type.
+         */
+        virtual std::vector<std::string> getInterface() const;
+
+        /**
+         * API to get the observable state of resource.
+         *
+         * @return bool - true if resource is observable, otherwise false.
+         */
+        virtual bool isObservable() const = 0;
+
+        /**
+         * API to get the discoverable state of resource.
+         *
+         * @return bool - true if resource is discoverable, otherwise false.
+         */
+        virtual bool isDiscoverable() const = 0;
+
+        /**
+         * API to get the start state of resource.
+         *
+         * @return bool - true if resource is started, otherwise false.
+         */
+        virtual bool isStarted() const = 0;
+
+        /**
+         * API to set the name of the resource.
+         *
+         * @param name - Name to be set.
+         *
+         * NOTE: API throws @InvalidArgsException, @SimulatorException exceptions.
+         */
+        virtual void setName(const std::string &name) = 0;
+
+        /**
+         * API to set the resource URI.
+         *
+         * @param uri - URI to be set.
+         *
+         * NOTE: API throws @InvalidArgsException, @SimulatorException exceptions.
+         */
+        virtual void setURI(const std::string &uri) = 0;
+
+        /**
+         * API to set the resource type.
+         *
+         * @param resourceType - resource type string.
+         *
+         * NOTE: API throws @InvalidArgsException, @SimulatorException exceptions.
+         */
+        virtual void setResourceType(const std::string &resourceType) = 0;
+
+        /**
+         * API to set interface to resource.
+         *
+         * @param interfaceType - interface to be set.
+         *
+         * NOTE: API throws @InvalidArgsException, @SimulatorException exceptions.
+         */
+        virtual void setInterface(const std::string &interfaceType) = 0;
+
+        /**
+         * API to set list of interfaces to resource.
+         *
+         * @param interfaceTypes - interfaces to be set.
+         *
+         * NOTE: API throws @InvalidArgsException, @SimulatorException exceptions.
+         */
+        virtual void setInterface(const std::vector<std::string> &interfaceTypes) = 0;
+
+        /**
+         * API to add interface type for resource.
+         *
+         * @param interfaceType - interface to be added for resource.
+         *
+         * NOTE: API throws @InvalidArgsException, @SimulatorException exceptions.
+         */
+        virtual void addInterface(const std::string &interfaceType) = 0;
+
+        /**
+         * API to make the resource observable or non-observable.
+         *
+         * @param state - true for resource to be observable, otherwise false.
+         *
+         * NOTE: API throws @SimulatorException exceptions.
+         */
+        virtual void setObservable(bool state) = 0;
+
+        /**
+         * API to make the resource discoverable or non-discoverable.
+         *
+         * @param state - true for resource to be discoverable, otherwise false.
+         *
+         * NOTE: API throws @SimulatorException exceptions.
+         */
+        virtual void setDiscoverable(bool state) = 0;
+
+        /**
+         * API to set the callback for receiving the notifications when
+         * observer is registered or unregistered with resource.
+         *
+         * @param callback - Callback to be set for receiving the notifications.
+         */
+        virtual void setObserverCallback(ObserverCallback callback) = 0;
+
+        /**
+         * API to set the callback for receiving the notifications when the
+         * resource's representation model changes.
+         *
+         * @param callback - Callback to be set for receiving the notifications.
+         */
+        virtual void setModelChangeCallback(ResourceModelUpdateCallback callback) = 0;
+
+        /**
+         * API to start the resource.
+         *
+         * NOTE: API throws @SimulatorException exception.
+         */
+        virtual void start() = 0;
+
+        /**
+         * API to stop the resource.
+         *
+         * NOTE: API throws @SimulatorException exception.
+         */
+        virtual void stop() = 0;
+
+        /**
+         * API to get SimulatorResourceModel of resource.
+         *
+         * @return Resource model of the resource.
+         */
+        virtual SimulatorResourceModel getResourceModel() = 0;
+
+        /**
+         * API to get observers which are registered with resource.
+         *
+         * @return vector of ObserverInfo.
+         */
+        virtual std::vector<ObserverInfo> getObservers() const = 0;
+
+        /**
+         * API to notify resource's representation to specific observer.
+         *
+         * @param observerID - ID of observer.
+         *
+         * NOTE: API throws @SimulatorException exception.
+         */
+        virtual void notify(int observerID) = 0;
+
+        /**
+         * API to notify resource's representation to all registered observers.
+         *
+         * NOTE: API throws @SimulatorException exception.
+         */
+        virtual void notifyAll() = 0;
+
+    protected:
+        SimulatorResource::Type m_type;
+        std::string m_name;
+        std::string m_uri;
+        std::string m_resourceType;
+        std::vector<std::string> m_interfaces;
+};
+
+typedef std::shared_ptr<SimulatorResource> SimulatorResourceSP;
+
+#endif
index d596ed9..a83028f 100644 (file)
 #ifndef SIMULATOR_RESOURCE_MODEL_H_
 #define SIMULATOR_RESOURCE_MODEL_H_
 
-#include <string>
-#include <vector>
+#include <map>
+#include <set>
+
 #include "OCPlatform.h"
-#include <climits>
+
+class SimulatorResourceModel;
+typedef boost::variant <
+int,
+double,
+bool,
+std::string,
+SimulatorResourceModel,
+
+std::vector<int>,
+std::vector<double>,
+std::vector<bool>,
+std::vector<std::string>,
+std::vector<SimulatorResourceModel>,
+
+std::vector<std::vector<int>>,
+std::vector<std::vector<double>>,
+std::vector<std::vector<bool>>,
+std::vector<std::vector<std::string>>,
+std::vector<std::vector<SimulatorResourceModel>>,
+
+std::vector<std::vector<std::vector<int>>>,
+std::vector<std::vector<std::vector<double>>>,
+std::vector<std::vector<std::vector<bool>>>,
+std::vector<std::vector<std::vector<std::string>>>,
+std::vector<std::vector<std::vector<SimulatorResourceModel>>>
+> AttributeValueVariant;
+
+enum class AttributeValueType
+{
+    UNKNOWN,
+    INTEGER,
+    DOUBLE,
+    BOOLEAN,
+    STRING,
+    RESOURCE_MODEL,
+    VECTOR
+};
+
+class OCRepresentationBuilder;
+class ToStringConverter;
+class AttributeProperty;
 
 /**
  * @class   SimulatorResourceModel
 class SimulatorResourceModel
 {
     public:
-        SimulatorResourceModel() = default;
-        SimulatorResourceModel(const SimulatorResourceModel &) = default;
-        SimulatorResourceModel &operator=(const SimulatorResourceModel &) = default;
-        SimulatorResourceModel(SimulatorResourceModel &&) = default;
-        SimulatorResourceModel &operator=(SimulatorResourceModel && ) = default;
-
-        /**
-          * @class   Attribute
-          * @brief   This class represents a resource attribute whose values can be generic.
-          */
-        class Attribute
+        friend class OCRepresentationBuilder;
+        friend class ToStringConverter;
+
+        class TypeInfo
         {
             public:
-                typedef boost::variant <
-                int,
-                double,
-                bool,
-                std::string
-                > ValueVariant;
-
-                enum class ValueType
-                {
-                    UNKNOWN,
-                    INTEGER,
-                    DOUBLE,
-                    BOOLEAN,
-                    STRING
-                };
-
-                Attribute()
-                {
-                    m_min = INT_MIN;
-                    m_max = INT_MAX;
-                    m_updateInterval = -1;
-                }
+                TypeInfo(AttributeValueType type = AttributeValueType::UNKNOWN,
+                         AttributeValueType baseType = AttributeValueType::UNKNOWN, int depth = 0);
+                AttributeValueType type() const;
+                AttributeValueType baseType() const;
+                int depth() const;
+                bool operator ==(const TypeInfo &rhs) const;
 
-                Attribute(const std::string &attrName)
-                {
-                    m_name = attrName;
-                    m_min = INT_MIN;
-                    m_max = INT_MAX;
-                    m_updateInterval = -1;
-                }
+            private:
+                AttributeValueType m_type;
+                AttributeValueType m_baseType;
+                int m_depth;
+        };
 
-                /**
-                 * API to get attribute's name.
-                 *
-                 * @return Attribute name.
-                 */
-                std::string getName(void) const;
-
-                /**
-                 * API to set the name of attribute.
-                 *
-                 * @param name - Attribute name.
-                 */
-                void setName(const std::string &name);
-
-                /**
-                 * API to get attribute's value.
-                 *
-                 * @return value of attribute.
-                 */
-                template <typename T>
-                T getValue() const
-                {
-                    T val = T();
-                    return boost::get<T>(m_value);
-                }
+        template <typename T>
+        bool add(const std::string &name, T value)
+        {
+            if (!name.empty() && m_attributes.end() == m_attributes.find(name))
+            {
+                AttributeValueVariant newValue = value;
+                m_attributes[name] = value;
+                return true;
+            }
+            return false;
+        }
 
-                /**
-                 * API to get attribute's value.
-                 *
-                 * @return value of attribute as ValueVariant.
-                 */
-                ValueVariant &getValue()
+        template <typename T>
+        T get(const std::string &name) const
+        {
+            T val = T();
+            auto x = m_attributes.find(name);
+            if (x != m_attributes.end())
+            {
+                try
                 {
-                    return m_value;
+                    val = boost::get<T>(x->second);
                 }
-
-                /**
-                 * API to get attribute's value type.
-                 *
-                 * @return ValueType enum.
-                 */
-                ValueType getValueType() const;
-
-                /**
-                 * API to set the attribute's value.
-                 *
-                 * @param value - value to be set.
-                 */
-                template <typename T>
-                void setValue(const T &value)
+                catch (boost::bad_get &e)
                 {
-                    m_value = value;
+                    return val;
                 }
+            }
+            return val;
+        }
 
-                /**
-                 * API to set the attribute's value from allowed values container.
-                 *
-                 * @param allowedValueIndex - Index of value to be set from allowed vaules container.
-                 */
-                void setFromAllowedValue(unsigned int index);
-
-                /**
-                 * API to get range of attribute's value.
-                 */
-                void getRange(int &min, int &max) const;
-
-                /**
-                 * API to set range of attribute's value.
-                 *
-                 * @param min - minimum value could be set as attribute value.
-                 * @param max - maximum value could be set as attribute value.
-                 */
-                void setRange(const int &min, const int &max);
-
-                /**
-                 * API to set the values to allowed values set.
-                 *
-                 * @param values - vector of values which will be set as allowed values.
-                 */
-                template <typename T>
-                bool setAllowedValues(const std::vector<T> &values)
-                {
-                    ValueVariant temp = values.at(0);
-                    if (temp.which() != m_value.which())
-                    {
-                        return false;
-                    }
-
-                    m_allowedValues.addValues(values);
-                    return true;
-                }
+        template <typename T>
+        bool update(const std::string &name, T value)
+        {
+            AttributeValueVariant newValue = value;
+            return updateValue(name, newValue);
+        }
 
-                /**
-                 * API to get the number of values present in allowed values set.
-                 *
-                 * @return Size of the allowed values.
-                 */
-                int getAllowedValuesSize() const;
+        bool remove(const std::string &name);
 
-                /**
-                 * API to get the string representation of the value.
-                 *
-                 * @return Attribute's value as a string.
-                 */
-                std::string valueToString() const;
+        bool contains(const std::string &name) const;
 
-                /**
-                 * API to get the string representation of all the allowed values.
-                 *
-                 * @return All allowed values as a string.
-                 */
-                std::vector<std::string> allowedValuesToString() const;
+        size_t size() const;
 
-                void addValuetoRepresentation(OC::OCRepresentation &rep,
-                                              const std::string &key) const;
+        TypeInfo getType(const std::string &name) const;
 
-                bool compare(Attribute &attribute);
+        std::map<std::string, AttributeValueVariant> getAttributeValues() const;
 
-                std::vector<ValueVariant> getAllowedValues() const;
+        AttributeValueVariant getAttributeValue(const std::string &name) const;
 
-                int getUpdateFrequencyTime() {return m_updateInterval;}
-                void setUpdateFrequencyTime(int interval) {m_updateInterval = interval;}
+        std::set<std::string> getAttributeNameSet() const;
 
-            private:
-                class AllowedValues
-                {
-                    public:
-                        template <typename T>
-                        void addValue(const T &value)
-                        {
-                            ValueVariant temp = value;
-                            m_values.push_back(temp);
-                        }
-
-                        template <typename T>
-                        void addValues(const std::vector<T> &values)
-                        {
-                            for (auto value : values)
-                            {
-                                ValueVariant vValue = value;
-                                m_values.push_back(vValue);
-                            }
-                        }
-
-                        ValueVariant &at(unsigned int index);
-                        int size() const;
-                        std::vector<std::string> toString() const;
-                        std::vector<ValueVariant> getValues() const;
-                    private:
-                        std::vector<ValueVariant> m_values;
-                };
-
-                std::string m_name;
-                ValueVariant m_value;
-                int m_max;
-                int m_min;
-                AllowedValues m_allowedValues;
-                int m_updateInterval;
-        };
+        OC::OCRepresentation asOCRepresentation() const;
 
-        /**
-         * API to get the number of attributes in the resource model.
-         *
-         * @return Number of attributes.
-         */
-        int size() const { return m_attributes.size(); }
-
-        /**
-         * API to get the value of an attribute.
-         *
-         * @param attrName - Attribute name
-         * @param value - Attribute value
-         *
-         * @return true if attribute exists, otherwise false.
-         */
-        bool getAttribute(const std::string &attrName, Attribute &value);
-
-        /**
-         * API to get the entire list of attributes in the form of key-value pair.
-         * Attribute name is the key and an instance of Attribute is the value.
-         *
-         * @return A map of all the attributes
-         */
-        std::map<std::string, Attribute> getAttributes() const;
-
-        /**
-         * API to add new attribute to resource model.
-         *
-         * @param attrName - Attribute name
-         * @param attrValue - Attribute value
-         */
-        template <typename T>
-        void addAttribute(const std::string &attrName, const T &attrValue)
-        {
-            if (m_attributes.end() == m_attributes.find(attrName))
-            {
-                m_attributes[attrName] = Attribute(attrName);
-                m_attributes[attrName].setValue(attrValue);
-            }
-        }
+        std::string asString() const;
 
-        /**
-          * API to add new attribute to resource model.
-          *
-          * @param attr  - Attribute pointer
-          *
-          */
-        void addAttribute(const Attribute &attribute, bool overwrite = false);
-
-        /**
-         * API to set range of attribute value.
-         *
-         * @param attrName - Attribute name.
-         * @param min - Minimum value could be set as attribute value.
-         * @param max - Maximum value could be set as attribute value.
-         */
-        void setRange(const std::string &attrName, const int min, const int max);
-
-        OC::OCRepresentation getOCRepresentation() const;
-        static std::shared_ptr<SimulatorResourceModel> create(const OC::OCRepresentation &ocRep);
+        static SimulatorResourceModel build(const OC::OCRepresentation &ocRep);
 
-        template <typename T>
-        void setAllowedValues(const std::string &attrName, const std::vector<T> &values)
-        {
-            if (m_attributes.end() != m_attributes.find(attrName))
-                m_attributes[attrName].setAllowedValues(values);
-        }
+    private:
+        TypeInfo getTypeInfo(const AttributeValueVariant &value) const;
+        bool updateValue(const std::string &name, const AttributeValueVariant &value);
+
+        std::map<std::string, AttributeValueVariant> m_attributes;
+};
+
+class SimulatorResourceAttribute
+{
+    public:
+        SimulatorResourceAttribute() = default;
+        SimulatorResourceAttribute(const std::string &name);
+        SimulatorResourceAttribute(const std::string &name, const AttributeValueVariant &value);
 
-        bool update(OC::OCRepresentation &ocRep);
+        std::string getName() const;
+        const SimulatorResourceModel::TypeInfo getType() const;
+        std::shared_ptr<AttributeProperty> getProperty() const;
+        AttributeValueVariant getValue() const;
 
-        bool update(std::shared_ptr<SimulatorResourceModel> &repModel);
+        void setName(const std::string &name);
+        void setProperty(const std::shared_ptr<AttributeProperty> &property);
 
         template <typename T>
-        void updateAttribute(const std::string &attrName, const T &value)
+        void setValue(const T &value)
         {
-            if (m_attributes.end() != m_attributes.find(attrName))
-                m_attributes[attrName].setValue(value);
+            m_value = std::make_shared<AttributeValueVariant>(value);
         }
 
-        void updateAttributeFromAllowedValues(const std::string &attrName, unsigned int index);
-
-        void removeAttribute(const std::string &attrName);
-
-        void setUpdateInterval(const std::string &attrName, int interval);
+        std::string asString() const;
 
     private:
-        std::map<std::string, Attribute> m_attributes;
+        std::string m_name;
+        std::shared_ptr<AttributeValueVariant> m_value;
+        std::shared_ptr<AttributeProperty> m_property;
 };
 
 typedef std::shared_ptr<SimulatorResourceModel> SimulatorResourceModelSP;
-typedef std::shared_ptr<SimulatorResourceModel::Attribute> AttributeSP;
 
 #endif
diff --git a/service/simulator/inc/simulator_resource_model_schema.h b/service/simulator/inc/simulator_resource_model_schema.h
new file mode 100644 (file)
index 0000000..cd0bf98
--- /dev/null
@@ -0,0 +1,244 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_RESOURCE_MODEL_SCHEMA_H_
+#define SIMULATOR_RESOURCE_MODEL_SCHEMA_H_
+
+#include <unordered_map>
+#include <memory>
+
+#include "simulator_resource_model.h"
+
+class IntegerProperty;
+class DoubleProperty;
+class BooleanProperty;
+class StringProperty;
+class ArrayProperty;
+class ModelProperty;
+class AttributeProperty
+{
+    public:
+        enum class Type
+        {
+            INTEGER,
+            DOUBLE,
+            BOOLEAN,
+            STRING,
+            MODEL,
+            ARRAY
+        };
+
+        explicit AttributeProperty(Type type);
+        virtual ~AttributeProperty() {};
+
+        Type getType() const;
+        virtual bool isInteger() const { return false; }
+        virtual bool isDouble() const { return false; }
+        virtual bool isBoolean() const { return false; }
+        virtual bool isString() const { return false; }
+        virtual bool isArray() const { return false; }
+        virtual bool isModel() const { return false; }
+        virtual std::shared_ptr<IntegerProperty> asInteger() { return nullptr; }
+        virtual std::shared_ptr<DoubleProperty> asDouble() { return nullptr; }
+        virtual std::shared_ptr<BooleanProperty> asBoolean() { return nullptr; }
+        virtual std::shared_ptr<StringProperty> asString() { return nullptr; }
+        virtual std::shared_ptr<ArrayProperty> asArray() { return nullptr; }
+        virtual std::shared_ptr<ModelProperty> asModel() { return nullptr; }
+
+        virtual bool validate(const AttributeValueVariant &value) = 0;
+        virtual AttributeValueVariant buildValue() = 0;
+
+    private:
+        Type m_type;
+};
+
+class IntegerProperty : public AttributeProperty,
+    public std::enable_shared_from_this<IntegerProperty>
+{
+    public:
+        static std::shared_ptr<IntegerProperty> build(int defaultValue = 0);
+
+        bool isInteger() const;
+        std::shared_ptr<IntegerProperty> asInteger();
+        void setDefaultValue(int value);
+        void setRange(int min, int max);
+        void setValues(const std::vector<int> &values);
+        bool hasRange() const;
+        bool hasValues() const;
+        int getDefaultValue() const;
+        bool getRange(int &min, int &max) const;
+        bool getValues(std::vector<int> &values) const;
+        bool validate(const AttributeValueVariant &value);
+        bool validate(const int &value);
+        AttributeValueVariant buildValue();
+
+    private:
+        explicit IntegerProperty(int defaultValue);
+
+        int m_defaultValue;
+        int m_min;
+        int m_max;
+        std::vector<int> m_values;
+        bool m_hasRange;
+};
+
+class DoubleProperty : public AttributeProperty,
+    public std::enable_shared_from_this<DoubleProperty>
+{
+    public:
+        static std::shared_ptr<DoubleProperty> build(double defaultValue = 0.0);
+
+        bool isDouble() const;
+        std::shared_ptr<DoubleProperty> asDouble();
+        void setDefaultValue(double value);
+        void setRange(double min, double max);
+        void setValues(const std::vector<double> &values);
+        bool hasRange() const;
+        bool hasValues() const;
+        double getDefaultValue() const;
+        bool getRange(double &min, double &max) const;
+        bool getValues(std::vector<double> &values) const;
+        bool validate(const AttributeValueVariant &value);
+        bool validate(const double &value);
+        AttributeValueVariant buildValue();
+
+    private:
+        explicit DoubleProperty(double defaultValue);
+
+        double m_defaultValue;
+        double m_min;
+        double m_max;
+        std::vector<double> m_values;
+        bool m_hasRange;
+};
+
+class BooleanProperty : public AttributeProperty,
+    public std::enable_shared_from_this<BooleanProperty>
+{
+    public:
+        static std::shared_ptr<BooleanProperty> build(bool defaultValue = true);
+
+        bool isBoolean() const;
+        std::shared_ptr<BooleanProperty> asBoolean();
+        void setDefaultValue(bool value);
+        bool getDefaultValue() const;
+        bool validate(const AttributeValueVariant &value);
+        AttributeValueVariant buildValue();
+
+    private:
+        explicit BooleanProperty(bool defaultValue);
+
+        bool m_defaultValue;
+};
+
+class StringProperty : public AttributeProperty,
+    public std::enable_shared_from_this<StringProperty>
+{
+    public:
+        static std::shared_ptr<StringProperty> build(const std::string &defaultValue = "");
+
+        bool isString() const;
+        std::shared_ptr<StringProperty> asString();
+        void setDefaultValue(const std::string &value);
+        void setRange(size_t min, size_t max);
+        void setValues(const std::vector<std::string> &values);
+        bool hasRange() const;
+        bool hasValues() const;
+        std::string getDefaultValue() const;
+        bool getRange(size_t &min, size_t &max) const;
+        bool getValues(std::vector<std::string> &values) const;
+        bool validate(const AttributeValueVariant &value);
+        bool validate(const std::string &value);
+        AttributeValueVariant buildValue();
+
+    private:
+        StringProperty(const std::string &defaultValue);
+
+        std::string m_defaultValue;
+        size_t m_min;
+        size_t m_max;
+        std::vector<std::string> m_values;
+        bool m_hasRange;
+};
+
+class ArrayProperty : public AttributeProperty,
+    public std::enable_shared_from_this<ArrayProperty>
+{
+    public:
+        static std::shared_ptr<ArrayProperty> build();
+
+        bool isArray() const;
+        std::shared_ptr<ArrayProperty> asArray();
+        void setRange(size_t minItems, size_t maxItems);
+        void setVariable(bool state);
+        void setUnique(bool state);
+        bool setElementProperty(const std::shared_ptr<AttributeProperty> &property);
+        bool hasRange() const;
+        bool isVariable() const;
+        bool isUnique() const;
+        size_t getMinItems() const;
+        size_t getMaxItems() const;
+        std::shared_ptr<AttributeProperty> getElementProperty();
+        bool validate(const AttributeValueVariant &value);
+        AttributeValueVariant buildValue();
+
+    private:
+        ArrayProperty();
+        int findDepth(std::shared_ptr<AttributeProperty> &elementProperty);
+
+        size_t m_min;
+        size_t m_max;
+        bool m_isVariableSize;
+        bool m_isUnique;
+        std::shared_ptr<AttributeProperty> m_elementProperty;
+        bool m_hasRange;
+};
+
+class ModelProperty : public AttributeProperty,
+    public std::enable_shared_from_this<ModelProperty>
+{
+    public:
+        static std::shared_ptr<ModelProperty> build();
+
+        bool isModel() const;
+        std::shared_ptr<ModelProperty> asModel();
+        bool add(const std::string &name, const std::shared_ptr<AttributeProperty> &property,
+                 bool required = false);
+        std::shared_ptr<AttributeProperty> get(const std::string &name);
+        std::unordered_map<std::string, std::shared_ptr<AttributeProperty>> getChildProperties();
+        bool isRequired(const std::string &name);
+        void remove(const std::string &name);
+        void setRequired(const std::string &name);
+        void unsetRequired(const std::string &name);
+        SimulatorResourceModel buildResourceModel();
+        bool validate(const AttributeValueVariant &value);
+        bool validate(const SimulatorResourceModel &model);
+        AttributeValueVariant buildValue();
+
+    private:
+        ModelProperty();
+
+        std::unordered_map<std::string, bool> m_requiredAttributes;
+        std::unordered_map<std::string, std::shared_ptr<AttributeProperty>> m_childProperties;
+};
+
+typedef ModelProperty SimulatorResourceModelSchema;
+
+#endif
diff --git a/service/simulator/inc/simulator_resource_server.h b/service/simulator/inc/simulator_resource_server.h
deleted file mode 100644 (file)
index b6f61a1..0000000
+++ /dev/null
@@ -1,290 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-/**
- * @file   simulator_resource_server.h
- *
- * @brief   This file contains a class which represents a simulator resource that provides a set
- *             of functions for operating a resource and performing automation on attribute values.
- */
-
-#ifndef SIMULATOR_RESOURCE_SERVER_H_
-#define SIMULATOR_RESOURCE_SERVER_H_
-
-#include "simulator_server_types.h"
-#include "simulator_resource_model.h"
-#include "simulator_exceptions.h"
-
-enum class ObservationStatus : unsigned char
-{
-    OBSERVE_REGISTER,
-    OBSERVE_UNREGISTER
-};
-
-typedef struct
-{
-    uint8_t id;
-    std::string address;
-    uint16_t port;
-} ObserverInfo;
-
-/**
- * @class   SimulatorResourceServer
- * @brief   This class provides a set of functions for operating and automating a resource.
- */
-class SimulatorResourceServer
-{
-    public:
-        /**
-         * Callback method for receiving notifications when resource model gets changed.
-         *
-         * @param uri - Resource URI
-         * @param resModel - Resource model
-         */
-        typedef std::function<void (const std::string &uri, const SimulatorResourceModel &resModel)>
-        ResourceModelChangedCB;
-
-        /**
-         * Callback method for receiving notifications when observer is registered/unregistered
-         * with resource.
-         *
-         * @param uri - Resource URI
-         * @param state - OBSERVE_REGISTER if observer is registered, otherwise OBSERVE_UNREGISTER.
-         * @param observerInfo - Information about observer.
-         */
-        typedef std::function<void (const std::string &uri, ObservationStatus state, const ObserverInfo &observerInfo)>
-        ObserverCB;
-
-        SimulatorResourceServer();
-
-        virtual ~SimulatorResourceServer() {};
-
-        /**
-         * API to get the resource URI.
-         *
-         * @return Resource URI
-         */
-        std::string getURI() const;
-
-        /**
-         * API to get the resource URI.
-         *
-         * @return Resource Type
-         */
-        std::string getResourceType() const;
-
-        /**
-         * API to get the interface type of the resource.
-         *
-         * @return Interface type of the resource
-         */
-        std::string getInterfaceType() const;
-
-        /**
-         * API to get the name of the resource.
-         *
-         * @return Resource name
-         */
-        std::string getName() const;
-
-        /**
-         * API to add a new attribute to the resource model.
-         *
-         * @param attribute - Attribute to be add to model.
-         */
-        void addAttribute(SimulatorResourceModel::Attribute &attribute);
-
-        /**
-         * API to set the value range of an attribute.
-         * This method is intended to be used for attributes whose values are numbers only.
-         *
-         * @param attrName - Name of the attribute
-         * @param min - Minimum value of the range
-         * @param max - Maximum value of the range
-         */
-        void setRange(const std::string &attrName, const int min, const int max);
-
-        /**
-         * API to set the allowed values of an attribute.
-         *
-         * @param attrName - Name of the attribute
-         * @param values - Allowed values
-         */
-        template <typename T>
-        void setAllowedValues(const std::string &attrName, const std::vector<T> &values)
-        {
-            m_resModel.setAllowedValues(attrName, values);
-        }
-
-        /**
-         * API to set the update interval time for automation.
-         *
-         * @param attrName - Name of the attribute
-         * @param interval - Interval time in miliseconds for attribute value update automation
-         */
-        void setUpdateInterval(const std::string &attrName, int interval);
-
-        /**
-         * API to update the value of an attribute.
-         *
-         * @param attrName - Name of the attribute
-         * @param value - Value of the attribute
-         */
-        template <typename T>
-        void updateAttributeValue(const std::string &attrName, const T &value)
-        {
-            m_resModel.updateAttribute(attrName, value);
-
-            // Notify all the subscribers
-            notifyAll();
-        }
-
-        /**
-         * API to update the attribute's value by taking the index of the value
-         * in the allowed values range.
-         *
-         * @param attrName - Name of the attribute
-         * @param allowedValueIndex - Index of the value in the allowed values range
-         */
-        void updateFromAllowedValues(const std::string &attrName, unsigned int index);
-
-        /**
-          * API to remove an attribute from the resource model.
-          *
-          * @param attName - Name of the attribute to be removed
-          */
-        void removeAttribute(const std::string &attName);
-
-        /**
-         * API to get the object of SimulatorResourceModel.
-         * Attributes of the resource are accessed using this object.
-         *
-         * @return Resource model of the resource.
-         */
-        SimulatorResourceModel getModel() const;
-
-        /**
-         * API to get the observable state of resource.
-         *
-         * @return bool - true if resource is observable, otherwise false.
-         */
-        virtual bool isObservable() const = 0;
-
-        /**
-         * API to start the attribute value automation for all attributes.
-         * Once started, values for the attributes will be selected randomly from their allowed range
-         * and the updated values will be notified to all the observers of the resource.
-         *
-         * @param type - Automation type.
-         * @param callback - Callback to get notifiy when update automation is finished.
-         * @param id - Identifier for automation.
-         *
-         * @return ID representing update automation session.
-         * NOTE: API throws @InvalidArgsException, @SimulatorException exceptions.
-         */
-        virtual int startUpdateAutomation(AutomationType type, int updateInterval,
-                                          updateCompleteCallback callback) = 0;
-
-        /**
-         * This method is used to start the attribute value automation for a specific attribute.
-         * Once started, values for the attribute will be selected randomly from its allowed range
-         * and the updated value will be notified to all the observers of the resource.
-         *
-         * @param attrName - Name of the attribute to be automated.
-         * @param type - Automation type.
-         * @param updateInterval -Interval time in milliseconds for attribute value update automation.
-         * @param callback - Callback to get notifiy when update automation is finished.
-         * @param id - Identifier for automation.
-         *
-         * @return ID representing update automation session.
-         * NOTE: API throws @InvalidArgsException, @SimulatorException exceptions.
-         */
-        virtual int startUpdateAutomation(const std::string &attrName, AutomationType type,
-                                          int updateInterval, updateCompleteCallback callback) = 0;
-
-        /**
-         * API to get the Ids of all ongoing resource update automation .
-         *
-         * @return vector of resource automation ids.
-         */
-        virtual std::vector<int> getResourceAutomationIds() = 0;
-
-        /**
-         * API to get the Ids of all ongoing attribute update automation .
-         *
-         * @return vector of attribute automation ids.
-         */
-        virtual std::vector<int> getAttributeAutomationIds() = 0;
-
-        /**
-        * API to stop the resource/attribute automation.
-        *
-        * @param id - Identifier for automation.
-        */
-        virtual void stopUpdateAutomation(const int id) = 0;
-
-        /**
-         * API to set the callback for receiving the notifications when the
-         * resource model changes.
-         *
-         * @param callback - Callback to be set for receiving the notifications.
-         */
-        virtual void setModelChangeCallback(ResourceModelChangedCB callback) = 0;
-
-        /**
-         * API to set the callback for receiving the notifications when
-         * observer is registered or unregistered with resource.
-         *
-         * @param callback - Callback to be set for receiving the notifications.
-         */
-        virtual void setObserverCallback(ObserverCB callback) = 0;
-
-        /**
-         * API to get observers which are registered with resource.
-         *
-         * @return vector of ObserverInfo.
-         */
-        virtual std::vector<ObserverInfo> getObserversList() = 0;
-
-        /**
-         * API to notify current resource model to specific observer.
-         *
-         * NOTE: API throws @SimulatorException exception.
-         */
-        virtual void notify(uint8_t id) = 0;
-
-        /**
-         * API to notify all registered observers.
-         *
-         * NOTE: API throws @SimulatorException exception.
-         */
-        virtual void notifyAll() = 0;
-
-    protected:
-        std::string m_name;
-        std::string m_uri;
-        std::string m_resourceType;
-        std::string m_interfaceType;
-        SimulatorResourceModel m_resModel;
-};
-
-typedef std::shared_ptr<SimulatorResourceServer> SimulatorResourceServerSP;
-
-#endif
diff --git a/service/simulator/inc/simulator_server_types.h b/service/simulator/inc/simulator_server_types.h
deleted file mode 100644 (file)
index 2449d0a..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-#ifndef SIMULATOR_SERVER_TYPES_H_
-#define SIMULATOR_SERVER_TYPES_H_
-
-#include <iostream>
-#include <functional>
-
-enum class AutomationType
-{
-    NORMAL,
-    RECURRENT
-};
-
-typedef std::function<void (const std::string &, const int)> updateCompleteCallback;
-
-#endif
diff --git a/service/simulator/inc/simulator_single_resource.h b/service/simulator/inc/simulator_single_resource.h
new file mode 100644 (file)
index 0000000..73ead2b
--- /dev/null
@@ -0,0 +1,186 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file   simulator_single_resource.h
+ *
+ * @brief   This file provides a class and API to access simulated resource and to perfrom auto
+ * update operations on simulated resource.
+ */
+
+#ifndef SIMULATOR_SINGLE_RESOURCE_H_
+#define SIMULATOR_SINGLE_RESOURCE_H_
+
+#include "simulator_resource.h"
+
+enum class AutoUpdateType
+{
+    ONE_TIME,
+    REPEAT
+};
+
+/**
+ * @class   SimulatorSingleResource
+ * @brief   This class provides a set of APIs for handling simulated resource.
+ */
+class SimulatorSingleResource : public SimulatorResource
+{
+    public:
+
+        /**
+         * Callback method for receiving notifications when resource/attribute value updation
+         * completes.
+         *
+         * @param uri - URI of resource.
+         * @param id - Update automation identifier.
+         */
+        typedef std::function<void (const std::string &uri, const int id)>
+        AutoUpdateCompleteCallback;
+
+        /**
+         * API to get attribute from resource's resource model.
+         *
+         * @param attrName - Attribute's name.
+         * @param attribute - A attribute of resource's resource model.
+         *
+         * @return bool - true on success, otherwise false.
+         */
+        virtual bool getAttribute(const std::string &attrName,
+                                  SimulatorResourceAttribute &attribute) = 0;
+
+        /**
+         * API to get attribute from resource's resource model.
+         *
+         * @param attrName - Attribute's name.
+         * @param attribute - A attribute of resource's resource model.
+         *
+         * @return bool - true on success, otherwise false.
+         */
+        virtual std::map<std::string, SimulatorResourceAttribute> getAttributes() = 0;
+
+        /**
+         * API to add a new attribute to the resource model.
+         *
+         * @param attribute - Attribute to be add to model.
+         * @param notify - If value is true then notification will be send to observers on success.
+         *                             This flag is set to true by default.
+         *
+         * NOTE: API throws @SimulatorException exceptions on failure.
+         */
+        virtual bool addAttribute(const SimulatorResourceAttribute &attribute,
+                                  bool notify = true) = 0;
+
+        /**
+         * API to remove an attribute from the resource model.
+         *
+         * @param attrName - Name of the attribute to be removed.
+         * @param notify - If value is true then notification will be send to observers on success.
+         *                             This flag is set to true by default.
+         *
+         * @return bool - true on success, otherwise false.
+         */
+        virtual bool removeAttribute(const std::string &attrName, bool notify = true) = 0;
+
+        /**
+         * API to update the value of an attribute.
+         *
+         * @param attrName - Name of the attribute.
+         * @param value - Value of the attribute.
+         * @param notify - If value is true then notification will be send to observers on success.
+         *                             This flag is set to true by default.
+         */
+        template <typename T>
+        bool updateAttributeValue(const std::string &attrName, const T &value, bool notify = true)
+        {
+            SimulatorResourceAttribute attribute(attrName);
+            attribute.setValue(value);
+            return updateAttributeValue(attribute, notify);
+        }
+
+        /**
+         * API to update the value of an attribute.
+         *
+         * @param attribute - A resource model attribute.
+         * @param notify - If value is true then notification will be send to observers on success.
+         *                             This flag is set to true by default.
+         *
+         * @return bool - true on success, otherwise false.
+         */
+        virtual bool updateAttributeValue(const SimulatorResourceAttribute &attribute,
+                                          bool notify = true) = 0;
+
+        /**
+         * API to start the attribute value update automation for all attributes.
+         * Values for the attributes will be selected from their allowed range
+         * and the updated resource model will be notified to all the observers of the resource.
+         *
+         * @param type - Automation type.
+         * @param updateInterval - Time in milliseconds to be set as interval between updating
+         *                                              attribute values.
+         * @param callback - Callback to get notifiy when update automation is finished.
+         *
+         * @return ID representing update automation session.
+         * NOTE: API throws @InvalidArgsException, @SimulatorException exceptions.
+         */
+        virtual int startResourceUpdation(AutoUpdateType type, int updateInterval,
+                                          AutoUpdateCompleteCallback callback) = 0;
+
+        /**
+         * This method is used to start the attribute value update automation for
+         * specific attribute. Values for the attribute will be selected from its allowed range
+         * and the updated resource model will be notified to all the observers of the resource.
+         *
+         * @param attrName - Name of the attribute to be automated.
+         * @param type - Automation type.
+         * @param updateInterval - Time in milliseconds to be set as interval between updating
+         *                                              attribute values.
+         * @param callback - Callback to get notifiy when update automation is finished.
+         *
+         * @return ID representing update automation session.
+         * NOTE: API throws @InvalidArgsException, @SimulatorException exceptions.
+         */
+        virtual int startAttributeUpdation(const std::string &attrName, AutoUpdateType type,
+                                           int updateInterval, AutoUpdateCompleteCallback callback) = 0;
+
+        /**
+         * API to get the Ids of all ongoing resource update automation .
+         *
+         * @return vector of resource automation ids.
+         */
+        virtual std::vector<int> getResourceUpdations() = 0;
+
+        /**
+         * API to get the Ids of all ongoing attribute update automation .
+         *
+         * @return vector of attribute automation ids.
+         */
+        virtual std::vector<int> getAttributeUpdations() = 0;
+
+        /**
+         * API to stop the resource/attribute automation.
+         *
+         * @param id - Identifier for automation.
+         */
+        virtual void stopUpdation(int id) = 0;
+};
+
+typedef std::shared_ptr<SimulatorSingleResource> SimulatorSingleResourceSP;
+
+#endif
diff --git a/service/simulator/inc/simulator_uncopyable.h b/service/simulator/inc/simulator_uncopyable.h
new file mode 100644 (file)
index 0000000..08e9fa3
--- /dev/null
@@ -0,0 +1,44 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file simulator_uncopyable.h
+ *
+ * @brief This file provides a class which makes its derived classes uncopyable.
+ */
+
+#ifndef SIMULATOR_UNCOPYABLE_H_
+#define SIMULATOR_UNCOPYABLE_H_
+
+/**
+ * @class   UnCopyable
+ * @brief   This class removes copy constructor and copy assignment operator so that
+ * its derived classes can not be copied.
+ */
+class UnCopyable
+{
+    public:
+        UnCopyable() = default;
+        UnCopyable(const UnCopyable &) = delete;
+        UnCopyable &operator=(const UnCopyable &) = delete;
+        virtual ~UnCopyable() {};
+};
+
+#endif
index cd0df03..cdbd8da 100644 (file)
@@ -1,8 +1,8 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <classpath>
-       <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
-       <classpathentry kind="src" path="src"/>
-       <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
-       <classpathentry kind="lib" path="libs/Simulator.jar"/>
-       <classpathentry kind="output" path="bin"/>
+    <classpathentry exported="true" kind="lib" path="libs/Simulator.jar"/>
+    <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+    <classpathentry kind="src" path="src"/>
+    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+    <classpathentry kind="output" path="bin"/>
 </classpath>
index 39567c3..f865f6c 100644 (file)
@@ -1,28 +1,28 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <projectDescription>
-       <name>ClientControllerPlugin</name>
-       <comment></comment>
-       <projects>
-       </projects>
-       <buildSpec>
-               <buildCommand>
-                       <name>org.eclipse.jdt.core.javabuilder</name>
-                       <arguments>
-                       </arguments>
-               </buildCommand>
-               <buildCommand>
-                       <name>org.eclipse.pde.ManifestBuilder</name>
-                       <arguments>
-                       </arguments>
-               </buildCommand>
-               <buildCommand>
-                       <name>org.eclipse.pde.SchemaBuilder</name>
-                       <arguments>
-                       </arguments>
-               </buildCommand>
-       </buildSpec>
-       <natures>
-               <nature>org.eclipse.pde.PluginNature</nature>
-               <nature>org.eclipse.jdt.core.javanature</nature>
-       </natures>
+    <name>ClientControllerPlugin</name>
+    <comment></comment>
+    <projects>
+    </projects>
+    <buildSpec>
+        <buildCommand>
+            <name>org.eclipse.jdt.core.javabuilder</name>
+            <arguments>
+            </arguments>
+        </buildCommand>
+        <buildCommand>
+            <name>org.eclipse.pde.ManifestBuilder</name>
+            <arguments>
+            </arguments>
+        </buildCommand>
+        <buildCommand>
+            <name>org.eclipse.pde.SchemaBuilder</name>
+            <arguments>
+            </arguments>
+        </buildCommand>
+    </buildSpec>
+    <natures>
+        <nature>org.eclipse.pde.PluginNature</nature>
+        <nature>org.eclipse.jdt.core.javanature</nature>
+    </natures>
 </projectDescription>
index 6822dfb..4044a58 100644 (file)
@@ -2,12 +2,26 @@ Manifest-Version: 1.0
 Bundle-ManifestVersion: 2
 Bundle-Name: ClientControllerPlugin
 Bundle-SymbolicName: ClientControllerPlugin;singleton:=true
-Bundle-Version: 1.0.0.qualifier
+Bundle-Version: 1.1.0.qualifier
 Bundle-Activator: oic.simulator.clientcontroller.Activator
 Require-Bundle: org.eclipse.ui,
  org.eclipse.core.runtime
 Bundle-RequiredExecutionEnvironment: JavaSE-1.7
 Bundle-ActivationPolicy: lazy
-Bundle-NativeCode: libs/libSimulatorManager.so
+Bundle-NativeCode: libs/linux-x86/liboc_logger.so;
+ libs/linux-x86/liboctbstack.so;
+ libs/linux-x86/libSimulatorManager.so;
+ libs/linux-x86/liboc.so; 
+ libs/linux-x86/libRamlParser.so;
+ osname=linux;
+ processor=x86,
+ libs/linux-x86_64/liboc_logger.so;
+ libs/linux-x86_64/liboctbstack.so;
+ libs/linux-x86_64/libSimulatorManager.so;
+ libs/linux-x86_64/liboc.so; 
+ libs/linux-x86_64/libRamlParser.so;
+ osname=linux;
+ processor=x86-64
 Bundle-ClassPath: libs/Simulator.jar,
  .
+Bundle-Vendor: IoTivity.org
index 100c21d..e1ca3fa 100644 (file)
@@ -4,5 +4,4 @@ bin.includes = META-INF/,\
                .,\
                plugin.xml,\
                icons/,\
-               libs/Simulator.jar,\
-               libs/libSimulatorManager.so
+               libs/
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/light_16x16.png b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/light_16x16.png
deleted file mode 100644 (file)
index 8b3abbd..0000000
Binary files a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/light_16x16.png and /dev/null differ
index 1bc294b..47f7e5d 100644 (file)
             restorable="true">
         </view>
         <view category="oic.simulator.clientcontroller.category"
-            class="oic.simulator.clientcontroller.view.MultiResourceOrchestrationView"
-            icon="icons/oic_logo_16x16.png"
-            id="oic.simulator.clientcontroller.view.orchestration"
-            name="Multi-Resource Automation"
-            restorable="true">
-        </view>
-        <view category="oic.simulator.clientcontroller.category"
             class="oic.simulator.clientcontroller.view.LogView"
             icon="icons/oic_logo_16x16.png"
             id="oic.simulator.clientcontroller.view.log"
@@ -70,9 +63,6 @@
                 id="oic.simulator.clientcontroller.view.attribute">
             </viewShortcut>
             <viewShortcut
-                id="oic.simulator.clientcontroller.view.orchestration">
-            </viewShortcut>
-            <viewShortcut
                 id="oic.simulator.clientcontroller.view.log">
             </viewShortcut>
         </perspectiveExtension>
index 5f22400..61667c8 100644 (file)
 
 package oic.simulator.clientcontroller;
 
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.osgi.framework.BundleContext;
+
 import oic.simulator.clientcontroller.manager.ImageManager;
 import oic.simulator.clientcontroller.manager.LogManager;
 import oic.simulator.clientcontroller.manager.ResourceManager;
 
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.osgi.framework.BundleContext;
-
 /**
  * The activator class controls the plug-in life cycle.
  */
@@ -40,10 +40,6 @@ public class Activator extends AbstractUIPlugin {
 
     private static ImageManager    imageManager;
 
-    static {
-        System.loadLibrary("SimulatorManager");
-    }
-
     public Activator() {
     }
 
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IDevicePlatformInfoUIListener.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IDevicePlatformInfoUIListener.java
new file mode 100644 (file)
index 0000000..58c2e12
--- /dev/null
@@ -0,0 +1,23 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.clientcontroller.listener;
+
+public interface IDevicePlatformInfoUIListener {
+    public void onDeviceInfoFound();
+
+    public void onPlatformInfoFound();
+}
index 0956a68..33b1861 100644 (file)
@@ -16,6 +16,8 @@
 
 package oic.simulator.clientcontroller.listener;
 
+import org.oic.simulator.client.SimulatorRemoteResource.RequestType;
+
 import oic.simulator.clientcontroller.remoteresource.RemoteResource;
 
 /**
@@ -23,9 +25,12 @@ import oic.simulator.clientcontroller.remoteresource.RemoteResource;
  * the UI listeners.
  */
 public interface IVerificationUIListener {
-    public void onVerificationStarted(RemoteResource resource, int autoType);
+    public void onVerificationStarted(RemoteResource resource,
+            RequestType reqType);
 
-    public void onVerificationAborted(RemoteResource resource, int autoType);
+    public void onVerificationAborted(RemoteResource resource,
+            RequestType reqType);
 
-    public void onVerificationCompleted(RemoteResource resource, int autoType);
+    public void onVerificationCompleted(RemoteResource resource,
+            RequestType reqType);
 }
index b0b1f6c..a8a6842 100644 (file)
 
 package oic.simulator.clientcontroller.manager;
 
-import java.net.URL;
-
-import oic.simulator.clientcontroller.Activator;
-import oic.simulator.clientcontroller.utils.Constants;
-
 import org.eclipse.jface.resource.ImageDescriptor;
 import org.eclipse.jface.resource.ImageRegistry;
 import org.eclipse.swt.graphics.Image;
 import org.osgi.framework.Bundle;
 
+import java.net.URL;
+
+import oic.simulator.clientcontroller.Activator;
+import oic.simulator.clientcontroller.utils.Constants;
+
 /**
  * Class which loads the icons/images into the image registry, and has methods
  * to handle the image related requests from other UI modules.
@@ -50,10 +50,6 @@ public class ImageManager {
         r.put(Constants.UNCHECKED, ImageDescriptor.createFromURL(bundle
                 .getEntry("icons/unchecked.gif")));
 
-        // Resource icons based on the resource type
-        r.put(Constants.OIC_R_LIGHT, ImageDescriptor.createFromURL(bundle
-                .getEntry("/icons/light_16x16.png")));
-
         // Log View related icons
         r.put(Constants.DEBUG_LOG, ImageDescriptor.createFromURL(bundle
                 .getEntry("/icons/debug_log.gif")));
index 03700e4..96117c6 100644 (file)
 
 package oic.simulator.clientcontroller.manager;
 
+import org.eclipse.jface.resource.ImageRegistry;
+import org.eclipse.swt.graphics.Image;
+
 import java.util.ArrayList;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.LinkedList;
 
+import org.oic.simulator.ILogger;
+import org.oic.simulator.ILogger.Level;
+import org.oic.simulator.SimulatorManager;
+
 import oic.simulator.clientcontroller.Activator;
 import oic.simulator.clientcontroller.listener.ILogUIListener;
 import oic.simulator.clientcontroller.utils.Constants;
 import oic.simulator.logger.LogEntry;
 import oic.simulator.logger.LoggerCallback;
 
-import org.eclipse.jface.resource.ImageRegistry;
-import org.eclipse.swt.graphics.Image;
-import org.oic.simulator.ILogger;
-import org.oic.simulator.ILogger.Level;
-import org.oic.simulator.SimulatorManager;
-
 /**
  * Class which handles the native logs, maintains log entries and updates the
  * UI.
index c7d225f..5590881 100644 (file)
@@ -16,7 +16,7 @@
 
 package oic.simulator.clientcontroller.manager;
 
-import java.net.URL;
+import java.text.NumberFormat;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Comparator;
@@ -27,42 +27,46 @@ import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.Vector;
+
+import org.oic.simulator.ArrayProperty;
+import org.oic.simulator.AttributeProperty;
+import org.oic.simulator.AttributeProperty.Type;
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.AttributeValue.TypeInfo;
+import org.oic.simulator.AttributeValue.ValueType;
+import org.oic.simulator.BooleanProperty;
+import org.oic.simulator.DeviceInfo;
+import org.oic.simulator.DeviceListener;
+import org.oic.simulator.DoubleProperty;
+import org.oic.simulator.ILogger.Level;
+import org.oic.simulator.IntegerProperty;
+import org.oic.simulator.PlatformInfo;
+import org.oic.simulator.PlatformListener;
+import org.oic.simulator.SimulatorException;
+import org.oic.simulator.SimulatorManager;
+import org.oic.simulator.SimulatorResourceAttribute;
+import org.oic.simulator.SimulatorResourceModel;
+import org.oic.simulator.SimulatorResult;
+import org.oic.simulator.StringProperty;
+import org.oic.simulator.client.FindResourceListener;
+import org.oic.simulator.client.SimulatorRemoteResource;
+import org.oic.simulator.client.SimulatorRemoteResource.GetResponseListener;
+import org.oic.simulator.client.SimulatorRemoteResource.ObserveNotificationListener;
+import org.oic.simulator.client.SimulatorRemoteResource.PostResponseListener;
+import org.oic.simulator.client.SimulatorRemoteResource.PutResponseListener;
+import org.oic.simulator.client.SimulatorRemoteResource.RequestType;
+import org.oic.simulator.client.SimulatorRemoteResource.VerificationListener;
+import org.oic.simulator.client.SimulatorRequestModel;
 
 import oic.simulator.clientcontroller.Activator;
-import oic.simulator.clientcontroller.listener.IConfigurationUpload;
-import oic.simulator.clientcontroller.listener.IFindResourceUIListener;
-import oic.simulator.clientcontroller.listener.IGetUIListener;
-import oic.simulator.clientcontroller.listener.IObserveUIListener;
-import oic.simulator.clientcontroller.listener.IPostUIListener;
-import oic.simulator.clientcontroller.listener.IPutUIListener;
-import oic.simulator.clientcontroller.listener.IResourceSelectionChangedUIListener;
-import oic.simulator.clientcontroller.listener.IVerificationUIListener;
+import oic.simulator.clientcontroller.remoteresource.DeviceAndPlatformInfo;
 import oic.simulator.clientcontroller.remoteresource.MetaProperty;
-import oic.simulator.clientcontroller.remoteresource.PutPostAttributeModel;
 import oic.simulator.clientcontroller.remoteresource.RemoteResource;
-import oic.simulator.clientcontroller.remoteresource.RemoteResourceAttribute;
+import oic.simulator.clientcontroller.utils.AttributeValueStringConverter;
 import oic.simulator.clientcontroller.utils.Constants;
 import oic.simulator.clientcontroller.utils.Utility;
 
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.graphics.Image;
-import org.oic.simulator.ILogger.Level;
-import org.oic.simulator.ResourceAttribute;
-import org.oic.simulator.ResourceAttribute.Range;
-import org.oic.simulator.ResourceAttribute.Type;
-import org.oic.simulator.SimulatorException;
-import org.oic.simulator.SimulatorManager;
-import org.oic.simulator.SimulatorResourceModel;
-import org.oic.simulator.clientcontroller.IFindResourceListener;
-import org.oic.simulator.clientcontroller.IGetListener;
-import org.oic.simulator.clientcontroller.IObserveListener;
-import org.oic.simulator.clientcontroller.IPostListener;
-import org.oic.simulator.clientcontroller.IPutListener;
-import org.oic.simulator.clientcontroller.IVerificationListener;
-import org.oic.simulator.clientcontroller.SimulatorObserveType;
-import org.oic.simulator.clientcontroller.SimulatorRemoteResource;
-import org.oic.simulator.clientcontroller.SimulatorVerificationType;
-
 /**
  * This class acts as an interface between the simulator java SDK and the
  * various UI modules. It maintains all the details of resources and provides
@@ -72,159 +76,262 @@ import org.oic.simulator.clientcontroller.SimulatorVerificationType;
  */
 public class ResourceManager {
 
-    private Set<String>                               lastKnownSearchTypes;
-
-    private RemoteResource                            currentResourceInSelection;
+    private Set<String>                        lastKnownSearchTypes;
 
-    private IFindResourceListener                     findResourceListener;
-    private IGetListener                              getListener;
-    private IPutListener                              putListener;
-    private IPostListener                             postListener;
-    private IObserveListener                          observeListener;
-    private IVerificationListener                     verifyListener;
+    private RemoteResource                     currentResourceInSelection;
 
-    private ResponseSynchronizerThread                synchronizerThread;
+    private FindResourceListener               findResourceListener;
+    private GetResponseListener                getListener;
+    private PutResponseListener                putListener;
+    private PostResponseListener               postListener;
+    private ObserveNotificationListener        observeListener;
+    private VerificationListener               verifyListener;
+    private DeviceListener                     deviceListener;
+    private PlatformListener                   platformListener;
 
-    private Thread                                    threadHandle;
+    private ResponseSynchronizerThread         synchronizerThread;
 
-    private List<IFindResourceUIListener>             findResourceUIListeners;
-    private List<IResourceSelectionChangedUIListener> resourceSelectionChangedUIListeners;
-    private List<IGetUIListener>                      getUIListeners;
-    private List<IPutUIListener>                      putUIListeners;
-    private List<IPostUIListener>                     postUIListeners;
-    private List<IObserveUIListener>                  observeUIListeners;
-    private List<IVerificationUIListener>             verificationUIListeners;
-    private List<IConfigurationUpload>                configUploadUIListeners;
+    private Thread                             threadHandle;
 
     // Map with Server ID as key and the complete object as the value
-    private Map<String, RemoteResource>               resourceMap;
-    private List<RemoteResource>                      favoriteResources;
+    private Map<String, RemoteResource>        resourceMap;
+    private List<RemoteResource>               favoriteResources;
     // Maintaining a list of resource URIs for favorite resources feature.
-    private List<String>                              favoriteURIList;
+    private List<String>                       favoriteURIList;
 
     // Maintaining a list of observed resource URIs.
-    private List<String>                              observedResourceURIList;
+    private List<String>                       observedResourceURIList;
+
+    private Map<String, DeviceAndPlatformInfo> hostDeviceAndPlatformMap;
 
     public ResourceManager() {
         resourceMap = new HashMap<String, RemoteResource>();
         favoriteResources = new ArrayList<RemoteResource>();
         favoriteURIList = new ArrayList<String>();
         observedResourceURIList = new ArrayList<String>();
-        findResourceUIListeners = new ArrayList<IFindResourceUIListener>();
-        resourceSelectionChangedUIListeners = new ArrayList<IResourceSelectionChangedUIListener>();
-        getUIListeners = new ArrayList<IGetUIListener>();
-        putUIListeners = new ArrayList<IPutUIListener>();
-        postUIListeners = new ArrayList<IPostUIListener>();
-        observeUIListeners = new ArrayList<IObserveUIListener>();
-        verificationUIListeners = new ArrayList<IVerificationUIListener>();
-        configUploadUIListeners = new ArrayList<IConfigurationUpload>();
+        hostDeviceAndPlatformMap = new HashMap<String, DeviceAndPlatformInfo>();
 
-        findResourceListener = new IFindResourceListener() {
+        findResourceListener = new FindResourceListener() {
 
             @Override
-            public void onResourceCallback(
-                    final SimulatorRemoteResource resourceN) {
+            public void onResourceFound(final SimulatorRemoteResource resourceN) {
                 synchronizerThread.addToQueue(new Runnable() {
                     @Override
                     public void run() {
-                        System.out.println("onResourceCallback() entry");
                         if (null == resourceN) {
                             return;
                         }
-                        // If resource already exist, then ignore it.
+
+                        // Ignore the response if the resource is a device or
+                        // platform.
+                        Vector<String> resTypes = resourceN.getResourceTypes();
+                        if (null != resTypes
+                                && (resTypes.contains("oic.wk.d") || resTypes
+                                        .contains("oic.wk.p"))) {
+                            return;
+                        }
+
+                        // If id is not available, then it cannot be added to
+                        // the local map as null value should not be allowed as
+                        // key.
                         String uid = resourceN.getId();
                         if (null == uid) {
                             return;
                         }
+
+                        // If resource already exist, then ignore it.
                         boolean exist = isUidExist(uid);
                         if (exist) {
-                            System.out.println("Duplicate resource found: ["
-                                    + uid + "]");
+                            handleExistingResource(resourceN);
                             return;
                         }
 
-                        // Fetch the resource data
-                        RemoteResource resource = fetchResourceDetails(resourceN);
-                        if (null == resource) {
-                            return;
-                        }
+                        RemoteResource resource = new RemoteResource();
+                        resource.setRemoteResourceRef(resourceN);
 
-                        resource.setResource(resourceN);
+                        boolean observeRequestSent = false;
 
-                        String uri = resource.getResourceURI();
-                        if (null != uri) {
+                        String uri = resourceN.getURI();
+                        if (null != uri && uri.trim().length() > 0) {
                             // Add resource to favorite list if it was in
                             // favorites list during find/refresh operation.
-                            if (favoriteURIList.contains(uri)) {
-                                addResourcetoFavorites(resource);
-                            }
-                            // Add resource to observed resources list if it was
-                            // in observe list during find/refresh operation.
-                            if (observedResourceURIList.contains(uri)) {
-                                resource.setObserved(true);
+                            synchronized (favoriteURIList) {
+                                if (favoriteURIList.contains(uri)) {
+                                    addResourcetoFavorites(resource);
+                                }
+                            } // Add resource to observed resources list if it
+                              // was
+                              // in observe list during find/refresh operation.
+                            synchronized (observedResourceURIList) {
+                                if (observedResourceURIList.contains(uri)) {
+                                    observeRequestSent = sendObserveRequest(resource);
+                                }
                             }
+                        } else {
+                            Activator
+                                    .getDefault()
+                                    .getLogManager()
+                                    .log(Level.INFO.ordinal(), new Date(),
+                                            "Found a resource without URI. Ignoring it.");
+                            return;
                         }
 
                         // Add the resource in local data structure
                         addResourceDetails(resource);
 
                         // Notify the UI listener
-                        newResourceFoundNotification(resource);
+                        UiListenerHandler.getInstance()
+                                .newResourceFoundNotification(resource);
+
+                        Activator
+                                .getDefault()
+                                .getLogManager()
+                                .log(Level.INFO.ordinal(),
+                                        new Date(),
+                                        "Resource Found [" + resourceN.getURI()
+                                                + "].");
+
+                        // Send an initial GET request(If observe request has
+                        // not been sent already) to get the resource
+                        // attributes on an interface supported by the resource.
+                        if (!observeRequestSent) {
+                            try {
+                                String ifType = null;
+                                Vector<String> resInterfaces = resourceN
+                                        .getResourceInterfaces();
+                                if (null != resInterfaces) {
+                                    ifType = resInterfaces.get(0);
+                                }
+                                resourceN.get(
+                                        formQueryParameters(ifType, null),
+                                        getListener);
+                            } catch (SimulatorException e) {
+                                Activator
+                                        .getDefault()
+                                        .getLogManager()
+                                        .log(Level.ERROR.ordinal(),
+                                                new Date(),
+                                                Utility.getSimulatorErrorString(
+                                                        e, null));
+                            }
+                        }
 
-                        // Send an initial GET request to get the resource
-                        // attributes
-                        try {
-                            resourceN.get(null, getListener);
-                        } catch (SimulatorException e) {
-                            Activator
-                                    .getDefault()
-                                    .getLogManager()
-                                    .log(Level.ERROR.ordinal(),
-                                            new Date(),
-                                            "[" + e.getClass().getSimpleName()
-                                                    + "]" + e.code().toString()
-                                                    + "-" + e.message());
+                        // Get the device information
+                        if (!isDeviceInfoExist(resourceN.getHost())) {
+                            try {
+                                SimulatorManager.findDevices(resource
+                                        .getRemoteResourceRef().getHost(),
+                                        deviceListener);
+                            } catch (SimulatorException e) {
+                                Activator
+                                        .getDefault()
+                                        .getLogManager()
+                                        .log(Level.ERROR.ordinal(),
+                                                new Date(),
+                                                Utility.getSimulatorErrorString(
+                                                        e, null));
+                            }
+                        }
+
+                        // Get the platform information
+                        if (!isPlatformInfoExist(resourceN.getHost())) {
+                            try {
+                                SimulatorManager.getPlatformInformation(
+                                        resource.getRemoteResourceRef()
+                                                .getHost(), platformListener);
+                            } catch (SimulatorException e) {
+                                Activator
+                                        .getDefault()
+                                        .getLogManager()
+                                        .log(Level.ERROR.ordinal(),
+                                                new Date(),
+                                                Utility.getSimulatorErrorString(
+                                                        e, null));
+                            }
                         }
                     }
                 });
             }
         };
 
-        getListener = new IGetListener() {
+        // Listeners for device and platform information.
+        deviceListener = new DeviceListener() {
+
             @Override
-            public void onGetCompleted(final String uid,
-                    final SimulatorResourceModel resourceModelN) {
+            public void onDeviceFound(final String host,
+                    final DeviceInfo deviceInfo) {
+                if (null == deviceInfo || null == host) {
+                    return;
+                }
                 synchronizerThread.addToQueue(new Runnable() {
                     @Override
                     public void run() {
-                        // Handling the response which includes retrieving the
-                        // attributes and updating the local model.
-                        RemoteResource resource = handleResponse(uid,
-                                resourceModelN);
-                        if (null != resource) {
-                            // Notify the UI listeners
-                            getCompleteNotification(resource);
+                        synchronized (hostDeviceAndPlatformMap) {
+                            DeviceAndPlatformInfo info = hostDeviceAndPlatformMap
+                                    .get(host);
+                            if (null == info) {
+                                info = new DeviceAndPlatformInfo();
+                                info.setHost(host);
+                                hostDeviceAndPlatformMap.put(host, info);
+                            }
+                            info.setDeviceInfo(deviceInfo);
                         }
+
+                        // Notify UI listeners
+                        UiListenerHandler.getInstance()
+                                .deviceInfoReceivedNotification();
                     }
                 });
             }
+        };
+
+        platformListener = new PlatformListener() {
 
             @Override
-            public void onGetFailed(Throwable th) {
+            public void onPlatformFound(final String host,
+                    final PlatformInfo platformInfo) {
+                if (null == platformInfo || null == host) {
+                    return;
+                }
                 synchronizerThread.addToQueue(new Runnable() {
                     @Override
                     public void run() {
+                        synchronized (hostDeviceAndPlatformMap) {
+                            DeviceAndPlatformInfo info = hostDeviceAndPlatformMap
+                                    .get(host);
+                            if (null == info) {
+                                info = new DeviceAndPlatformInfo();
+                                info.setHost(host);
+                                hostDeviceAndPlatformMap.put(host, info);
+                            }
+                            info.setPlatformInfo(platformInfo);
+                        }
+
+                        // Notify UI listeners
+                        UiListenerHandler.getInstance()
+                                .platformInfoReceivedNotification();
                     }
                 });
             }
         };
 
-        putListener = new IPutListener() {
-
+        getListener = new GetResponseListener() {
             @Override
-            public void onPutCompleted(final String uid,
+            public void onGetResponse(final String uid,
+                    final SimulatorResult result,
                     final SimulatorResourceModel resourceModelN) {
-                synchronizerThread.addToQueue(new Thread() {
+                if (result != SimulatorResult.SIMULATOR_OK) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(),
+                                    new Date(),
+                                    "["
+                                            + result.toString()
+                                            + "] Received error response for GET request.");
+                    return;
+                }
+                synchronizerThread.addToQueue(new Runnable() {
                     @Override
                     public void run() {
                         // Handling the response which includes retrieving the
@@ -233,27 +340,32 @@ public class ResourceManager {
                                 resourceModelN);
                         if (null != resource) {
                             // Notify the UI listeners
-                            putCompleteNotification(resource);
+                            UiListenerHandler.getInstance()
+                                    .getCompleteNotification(resource);
                         }
                     }
                 });
             }
-
-            @Override
-            public void onPutFailed(Throwable th) {
-                synchronizerThread.addToQueue(new Runnable() {
-                    @Override
-                    public void run() {
-                    }
-                });
-            }
         };
 
-        postListener = new IPostListener() {
+        putListener = new PutResponseListener() {
+
             @Override
-            public void onPostCompleted(final String uid,
+            public void onPutResponse(final String uid,
+                    final SimulatorResult result,
                     final SimulatorResourceModel resourceModelN) {
-                synchronizerThread.addToQueue(new Runnable() {
+                if (result != SimulatorResult.SIMULATOR_OK) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(),
+                                    new Date(),
+                                    "["
+                                            + result.toString()
+                                            + "] Received error response for PUT request.");
+                    return;
+                }
+                synchronizerThread.addToQueue(new Thread() {
                     @Override
                     public void run() {
                         // Handling the response which includes retrieving the
@@ -262,28 +374,52 @@ public class ResourceManager {
                                 resourceModelN);
                         if (null != resource) {
                             // Notify the UI listeners
-                            postCompleteNotification(resource);
+                            UiListenerHandler.getInstance()
+                                    .putCompleteNotification(resource);
                         }
                     }
                 });
             }
+        };
 
+        postListener = new PostResponseListener() {
             @Override
-            public void onPostFailed(Throwable th) {
+            public void onPostResponse(final String uid,
+                    final SimulatorResult result,
+                    final SimulatorResourceModel resourceModelN) {
+                if (result != SimulatorResult.SIMULATOR_OK) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(),
+                                    new Date(),
+                                    "["
+                                            + result.toString()
+                                            + "] Received error response for POST request.");
+                    return;
+                }
                 synchronizerThread.addToQueue(new Runnable() {
                     @Override
                     public void run() {
+                        // Handling the response which includes retrieving the
+                        // attributes and updating the local model.
+                        RemoteResource resource = handleResponse(uid,
+                                resourceModelN);
+                        if (null != resource) {
+                            // Notify the UI listeners
+                            UiListenerHandler.getInstance()
+                                    .postCompleteNotification(resource);
+                        }
                     }
                 });
             }
         };
 
-        observeListener = new IObserveListener() {
+        observeListener = new ObserveNotificationListener() {
 
             @Override
-            public void onObserveCompleted(final String uid,
+            public void onObserveNotification(final String uid,
                     final SimulatorResourceModel resourceModelN, final int seq) {
-                System.out.println("ResourceManager: onObserveCallback()");
                 synchronizerThread.addToQueue(new Runnable() {
                     @Override
                     public void run() {
@@ -293,23 +429,18 @@ public class ResourceManager {
                                 resourceModelN);
                         if (null != resource) {
                             // Notify the UI listeners
-                            observeCompleteNotification(resource);
+                            UiListenerHandler.getInstance()
+                                    .observeCompleteNotification(resource);
                         }
                     }
                 });
             }
-
-            @Override
-            public void onObserveFailed(Throwable th) {
-                // TODO Auto-generated method stub
-            }
         };
 
-        verifyListener = new IVerificationListener() {
+        verifyListener = new VerificationListener() {
 
             @Override
             public void onVerificationStarted(final String uid, final int autoId) {
-                System.out.println("onVefificationStarted: " + autoId);
                 synchronizerThread.addToQueue(new Runnable() {
                     @Override
                     public void run() {
@@ -320,10 +451,13 @@ public class ResourceManager {
                         // Update the automation status.
                         resource.updateAutomationStatus(autoId, true);
 
-                        int autoType = resource.getAutomationtype(autoId);
+                        RequestType reqType = resource
+                                .getAutomationtype(autoId);
 
                         // Notify the listeners.
-                        verificationStartedNotification(resource, autoType);
+                        UiListenerHandler.getInstance()
+                                .verificationStartedNotification(resource,
+                                        reqType);
                     }
                 });
             }
@@ -331,7 +465,6 @@ public class ResourceManager {
             @Override
             public void onVerificationCompleted(final String uid,
                     final int autoId) {
-                System.out.println("onVefificationCompleted: " + autoId);
                 synchronizerThread.addToQueue(new Runnable() {
                     @Override
                     public void run() {
@@ -342,17 +475,19 @@ public class ResourceManager {
                         // Update the automation status.
                         resource.updateAutomationStatus(autoId, false);
 
-                        int autoType = resource.getAutomationtype(autoId);
+                        RequestType reqType = resource
+                                .getAutomationtype(autoId);
 
                         // Notify the listeners.
-                        verificationCompletedNotification(resource, autoType);
+                        UiListenerHandler.getInstance()
+                                .verificationCompletedNotification(resource,
+                                        reqType);
                     }
                 });
             }
 
             @Override
             public void onVerificationAborted(final String uid, final int autoId) {
-                System.out.println("onVefificationAborted: " + autoId);
                 synchronizerThread.addToQueue(new Runnable() {
                     @Override
                     public void run() {
@@ -363,10 +498,13 @@ public class ResourceManager {
                         // Update the automation status.
                         resource.updateAutomationStatus(autoId, false);
 
-                        int autoType = resource.getAutomationtype(autoId);
+                        RequestType reqType = resource
+                                .getAutomationtype(autoId);
 
                         // Notify the listeners.
-                        verificationAbortedNotification(resource, autoType);
+                        UiListenerHandler.getInstance()
+                                .verificationAbortedNotification(resource,
+                                        reqType);
                     }
                 });
             }
@@ -378,6 +516,154 @@ public class ResourceManager {
         threadHandle.start();
     }
 
+    private void handleExistingResource(
+            final SimulatorRemoteResource newNativeResourceRef) {
+        if (null == newNativeResourceRef) {
+            return;
+        }
+
+        RemoteResource existingResource = getResource(newNativeResourceRef
+                .getId());
+        if (null == existingResource) {
+            return;
+        }
+
+        SimulatorRemoteResource existingNativeResourceRef = existingResource
+                .getRemoteResourceRef();
+        if (null == existingNativeResourceRef) {
+            return;
+        }
+
+        // Compare the resource properties(resource types, interface types and
+        // observable)
+        // of the received resource with the existing resource.
+        // If there is a change, then replace the existing resource properties
+        // and send
+        // a GET request to receive the latest resource representation.
+        boolean change = compareResourceProperties(existingNativeResourceRef,
+                newNativeResourceRef);
+        if (!change) {
+            return;
+        }
+
+        existingResource.setRemoteResourceRef(newNativeResourceRef);
+
+        try {
+            String ifType = null;
+            Vector<String> resInterfaces = newNativeResourceRef
+                    .getResourceInterfaces();
+            if (null != resInterfaces) {
+                ifType = resInterfaces.get(0);
+            }
+            newNativeResourceRef.get(formQueryParameters(ifType, null),
+                    getListener);
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(), new Date(),
+                            Utility.getSimulatorErrorString(e, null));
+        }
+
+        // Notify the UI listener which may be looking for this callback for
+        // further processing.
+        UiListenerHandler.getInstance().newResourceFoundNotification(
+                existingResource);
+
+        // Notify the UI listeners by re-selecting the same resource.
+        // This is just to refresh the resource properties being shown.
+        RemoteResource resourceInSelection = getCurrentResourceInSelection();
+        if (null != resourceInSelection) {
+            if (resourceInSelection.getRemoteResourceRef().getURI()
+                    .equals(newNativeResourceRef.getURI())) {
+                UiListenerHandler.getInstance()
+                        .resourceSelectionChangedUINotification(
+                                existingResource);
+            }
+        }
+    }
+
+    private boolean compareResourceProperties(
+            SimulatorRemoteResource existingNativeResourceRef,
+            SimulatorRemoteResource newNativeResourceRef) {
+        boolean change = false;
+
+        try {
+            // Compare URI.
+            if (!existingNativeResourceRef.getURI().equals(
+                    existingNativeResourceRef.getURI())) {
+                change = true;
+            }
+
+            // Compare ID.
+            if (!change
+                    && !existingNativeResourceRef.getId().equals(
+                            existingNativeResourceRef.getId())) {
+                change = true;
+            }
+
+            // Compare Host.
+            if (!change
+                    && !existingNativeResourceRef.getHost().equals(
+                            existingNativeResourceRef.getHost())) {
+                change = true;
+            }
+
+            // Compare Observable flag.
+            if (!change
+                    && existingNativeResourceRef.isObservable() != existingNativeResourceRef
+                            .isObservable()) {
+                change = true;
+            }
+
+            // Compare Resource Types.
+            Vector<String> existingResTypes = existingNativeResourceRef
+                    .getResourceTypes();
+            Vector<String> newResTypes = newNativeResourceRef
+                    .getResourceTypes();
+
+            if (!change) {
+                if (existingResTypes.size() != newResTypes.size()) {
+                    change = true;
+                } else {
+                    // Compare both lists.
+                    Iterator<String> itr = existingResTypes.iterator();
+                    while (itr.hasNext()) {
+                        if (!newResTypes.contains(itr.next())) {
+                            change = true;
+                            break;
+                        }
+                    }
+                }
+            }
+
+            // Compare Interface Types.
+            Vector<String> existingInterfaceTypes = existingNativeResourceRef
+                    .getResourceInterfaces();
+            Vector<String> newInterfaceTypes = newNativeResourceRef
+                    .getResourceInterfaces();
+
+            if (!change) {
+                if (existingInterfaceTypes.size() != newInterfaceTypes.size()) {
+                    change = true;
+                } else {
+                    // Compare both lists.
+                    Iterator<String> itr = existingInterfaceTypes.iterator();
+                    while (itr.hasNext()) {
+                        if (!newInterfaceTypes.contains(itr.next())) {
+                            change = true;
+                            break;
+                        }
+                    }
+                }
+            }
+        } catch (Exception e) {
+            change = true;
+        }
+
+        return change;
+    }
+
     private RemoteResource handleResponse(String uid,
             SimulatorResourceModel resourceModelN) {
         if (null == uid || null == resourceModelN) {
@@ -391,18 +677,32 @@ public class ResourceManager {
             return null;
         }
 
-        resource.setResourceModel(resourceModelN);
-        Map<String, RemoteResourceAttribute> attributeMap = fetchResourceAttributesFromModel(resourceModelN);
+        resource.setResourceModelRef(resourceModelN);
+        resource.setResourceRepresentation(resourceModelN);
 
-        // TODO: For debugging
-        if (null != attributeMap) {
-            RemoteResourceAttribute.printAttributes(attributeMap);
-            System.out.println("Attributes found: " + (null != attributeMap));
-            System.out.println("No of attributes: " + attributeMap.size());
+        return resource;
+    }
 
-            resource.setResourceAttributesMap(attributeMap);
+    public synchronized boolean isDeviceInfoExist(String host) {
+        DeviceAndPlatformInfo info = hostDeviceAndPlatformMap.get(host);
+        if (null == info) {
+            return false;
         }
-        return resource;
+        if (null == info.getDeviceInfo()) {
+            return false;
+        }
+        return true;
+    }
+
+    public synchronized boolean isPlatformInfoExist(String host) {
+        DeviceAndPlatformInfo info = hostDeviceAndPlatformMap.get(host);
+        if (null == info) {
+            return false;
+        }
+        if (null == info.getPlatformInfo()) {
+            return false;
+        }
+        return true;
     }
 
     private static class ResponseSynchronizerThread implements Runnable {
@@ -446,98 +746,6 @@ public class ResourceManager {
         }
     }
 
-    public void addResourceSelectionChangedUIListener(
-            IResourceSelectionChangedUIListener resourceSelectionChangedUIListener) {
-        synchronized (resourceSelectionChangedUIListeners) {
-            resourceSelectionChangedUIListeners
-                    .add(resourceSelectionChangedUIListener);
-        }
-    }
-
-    public void addGetUIListener(IGetUIListener getUIListener) {
-        synchronized (getUIListeners) {
-            getUIListeners.add(getUIListener);
-        }
-    }
-
-    public void addPutUIListener(IPutUIListener putUIListener) {
-        synchronized (putUIListeners) {
-            putUIListeners.add(putUIListener);
-        }
-    }
-
-    public void addPostUIListener(IPostUIListener postUIListener) {
-        synchronized (postUIListeners) {
-            postUIListeners.add(postUIListener);
-        }
-    }
-
-    public void addObserveUIListener(IObserveUIListener observeUIListener) {
-        synchronized (observeUIListeners) {
-            observeUIListeners.add(observeUIListener);
-        }
-    }
-
-    public void addVerificationUIListener(
-            IVerificationUIListener verificationUIListener) {
-        synchronized (verificationUIListeners) {
-            verificationUIListeners.add(verificationUIListener);
-        }
-    }
-
-    public void addConfigUploadUIListener(IConfigurationUpload configListener) {
-        synchronized (configUploadUIListeners) {
-            configUploadUIListeners.add(configListener);
-        }
-    }
-
-    public void removeResourceSelectionChangedUIListener(
-            IResourceSelectionChangedUIListener listener) {
-        synchronized (resourceSelectionChangedUIListeners) {
-            if (null != listener
-                    && resourceSelectionChangedUIListeners.size() > 0) {
-                resourceSelectionChangedUIListeners.remove(listener);
-            }
-        }
-    }
-
-    public void removeGetUIListener(IGetUIListener getUIListener) {
-        synchronized (getUIListeners) {
-            getUIListeners.remove(getUIListener);
-        }
-    }
-
-    public void removePutUIListener(IPutUIListener putUIListener) {
-        synchronized (putUIListeners) {
-            putUIListeners.remove(putUIListener);
-        }
-    }
-
-    public void removePostUIListener(IPostUIListener postUIListener) {
-        synchronized (postUIListeners) {
-            postUIListeners.remove(postUIListener);
-        }
-    }
-
-    public void removeObserveUIListener(IObserveUIListener observeUIListener) {
-        synchronized (observeUIListeners) {
-            observeUIListeners.remove(observeUIListener);
-        }
-    }
-
-    public void removeVerificationUIListener(
-            IVerificationUIListener verificationUIListener) {
-        synchronized (verificationUIListeners) {
-            verificationUIListeners.remove(verificationUIListener);
-        }
-    }
-
-    public void removeConfigUploadUIListener(IConfigurationUpload configListener) {
-        synchronized (configUploadUIListeners) {
-            configUploadUIListeners.remove(configListener);
-        }
-    }
-
     public void addResourcetoFavorites(RemoteResource resource) {
         if (null == resource) {
             return;
@@ -545,7 +753,6 @@ public class ResourceManager {
         resource.setFavorite(true);
         synchronized (favoriteResources) {
             favoriteResources.add(resource);
-            favoriteURIList.add(resource.getResourceURI());
         }
     }
 
@@ -559,18 +766,28 @@ public class ResourceManager {
         }
     }
 
+    public void addResourceURItoFavorites(RemoteResource resource) {
+        if (null == resource) {
+            return;
+        }
+        synchronized (favoriteURIList) {
+            favoriteURIList.add(resource.getRemoteResourceRef().getURI());
+        }
+    }
+
     public void removeResourceURIFromFavorites(RemoteResource resource) {
         if (null == resource) {
             return;
         }
         synchronized (favoriteURIList) {
-            favoriteURIList.remove(resource.getResourceURI());
+            favoriteURIList.remove(resource.getRemoteResourceRef().getURI());
         }
     }
 
     public void addObservedResourceURI(String resourceURI) {
         synchronized (observedResourceURIList) {
-            observedResourceURIList.add(resourceURI);
+            if (!observedResourceURIList.contains(resourceURI))
+                observedResourceURIList.add(resourceURI);
         }
     }
 
@@ -581,7 +798,7 @@ public class ResourceManager {
     }
 
     public boolean isResourceObserved(String resourceURI) {
-        boolean observed = false;
+        boolean observed;
         synchronized (observedResourceURIList) {
             observed = observedResourceURIList.contains(resourceURI);
         }
@@ -600,47 +817,12 @@ public class ResourceManager {
     private void addResourceDetails(RemoteResource remoteResource) {
         if (null != remoteResource) {
             synchronized (resourceMap) {
-                resourceMap.put(remoteResource.getuId(), remoteResource);
+                resourceMap.put(remoteResource.getRemoteResourceRef().getId(),
+                        remoteResource);
             }
         }
     }
 
-    public void addFindresourceUIListener(IFindResourceUIListener listener) {
-        if (null == listener) {
-            return;
-        }
-        synchronized (findResourceUIListeners) {
-            findResourceUIListeners.add(listener);
-        }
-    }
-
-    public void removeFindresourceUIListener(IFindResourceUIListener listener) {
-        if (null == listener) {
-            return;
-        }
-        synchronized (findResourceUIListeners) {
-            findResourceUIListeners.remove(listener);
-        }
-    }
-
-    private RemoteResource fetchResourceDetails(
-            SimulatorRemoteResource remoteResourceN) {
-        if (null == remoteResourceN) {
-            return null;
-        }
-        RemoteResource remoteResource = new RemoteResource();
-        remoteResource.setuId(remoteResourceN.getId());
-        remoteResource.setResourceURI(remoteResourceN.getUri());
-        remoteResource.setHost(remoteResourceN.getHost());
-        remoteResource.setResourceTypes(remoteResourceN.getResourceTypes());
-        remoteResource.setResourceInterfaces(remoteResourceN
-                .getResourceInterfaces());
-        remoteResource.setConnectivityType(remoteResourceN
-                .getConnectivityType());
-        remoteResource.setObservable(remoteResourceN.getIsObservable());
-        return remoteResource;
-    }
-
     private boolean isUidExist(String uid) {
         boolean exist;
         synchronized (resourceMap) {
@@ -660,333 +842,90 @@ public class ResourceManager {
         return resource;
     }
 
-    private Map<String, RemoteResourceAttribute> fetchResourceAttributesFromModel(
-            SimulatorResourceModel resourceModelN) {
-        Map<String, RemoteResourceAttribute> resourceAttributeMap = null;
-        if (null != resourceModelN) {
-            Map<String, ResourceAttribute> attributeMapN;
+    public synchronized Set<String> getLastKnownSearchTypes() {
+        return lastKnownSearchTypes;
+    }
+
+    public synchronized void setLastKnownSearchTypes(
+            Set<String> lastKnownSearchTypes) {
+        this.lastKnownSearchTypes = lastKnownSearchTypes;
+    }
+
+    public boolean findResourceRequest(Set<String> searchTypes) {
+        boolean result = false;
+        if (null == searchTypes || searchTypes.size() < 1) {
             try {
-                attributeMapN = resourceModelN.getAttributes();
+                SimulatorManager.findResource(findResourceListener);
+                result = true;
             } catch (SimulatorException e) {
                 Activator
                         .getDefault()
                         .getLogManager()
-                        .log(Level.ERROR.ordinal(),
-                                new Date(),
-                                "[" + e.getClass().getSimpleName() + "]"
-                                        + e.code().toString() + "-"
-                                        + e.message());
-                return null;
-            }
-            if (null != attributeMapN) {
-                resourceAttributeMap = new HashMap<String, RemoteResourceAttribute>();
-
-                Set<String> attNameSet = attributeMapN.keySet();
-                String attName;
-                Object attValueObj;
-                ResourceAttribute attributeN;
-                RemoteResourceAttribute attribute;
-                Iterator<String> attNameItr = attNameSet.iterator();
-                while (attNameItr.hasNext()) {
-                    attName = attNameItr.next();
-                    attributeN = attributeMapN.get(attName);
-                    if (null != attributeN) {
-                        attribute = new RemoteResourceAttribute();
-                        attribute.setResourceAttribute(attributeN);
-                        attribute.setAttributeName(attName);
-
-                        attValueObj = attributeN.getValue();
-                        if (null != attValueObj) {
-                            attribute.setAttributeValue(attValueObj);
-                        }
-
-                        // Set the attribute type
-                        attribute.setAttValBaseType(attributeN.getBaseType());
-                        attribute.setAttValType(attributeN.getType());
-
-                        // Set the range and allowed values
-                        Range range = attributeN.getRange();
-                        if (null != range) {
-                            attribute.setMinValue(range.getMin());
-                            attribute.setMaxValue(range.getMax());
-                        } else {
-                            Object[] values = attributeN.getAllowedValues();
-                            if (null != values && values.length > 0) {
-                                List<Object> valueList = new ArrayList<Object>();
-                                for (Object obj : values) {
-                                    valueList.add(obj);
-                                }
-                                attribute.setAllowedValues(valueList);
-                            }
-                            /*
-                             * Type baseType = attribute.getAttValBaseType();
-                             *
-                             * if(baseType == Type.INT) { //int[] values =
-                             * attributeN.getAllowedValues();
-                             * attribute.setAllowedValues
-                             * (attributeN.getAllowedValues()); } else
-                             * if(baseType == Type.DOUBLE) { double[] values =
-                             * attributeN.getAllowedValues();
-                             * attribute.setAllowedValues
-                             * (Utility.converArrayToList(values)); } else
-                             * if(baseType == Type.BOOL) { //boolean[] values =
-                             * attributeN.getAllowedValues(); List<Object> obj =
-                             * new ArrayList<Object>(); obj.add(true);
-                             * obj.add(false); attribute.setAllowedValues(obj);
-                             * } else if(baseType == Type.STRING) { String[]
-                             * values = attributeN.getAllowedValues();
-                             * attribute.
-                             * setAllowedValues(Utility.converArrayToList
-                             * (values)); }
-                             */
-                        }
-                        resourceAttributeMap.put(attName, attribute);
-                    }
-                }
+                        .log(Level.ERROR.ordinal(), new Date(),
+                                Utility.getSimulatorErrorString(e, null));
             }
-        }
-        return resourceAttributeMap;
-    }
-
-    private void newResourceFoundNotification(RemoteResource resource) {
-        synchronized (findResourceUIListeners) {
-            if (findResourceUIListeners.size() > 0) {
-                IFindResourceUIListener listener;
-                Iterator<IFindResourceUIListener> listenerItr = findResourceUIListeners
-                        .iterator();
-                while (listenerItr.hasNext()) {
-                    listener = listenerItr.next();
-                    if (null != listener) {
-                        listener.onNewResourceFound(resource);
-                    }
-                }
-            }
-        }
-    }
-
-    private void resourceSelectionChangedUINotification(RemoteResource resource) {
-        synchronized (resourceSelectionChangedUIListeners) {
-            if (resourceSelectionChangedUIListeners.size() > 0) {
-                IResourceSelectionChangedUIListener listener;
-                Iterator<IResourceSelectionChangedUIListener> listenerItr = resourceSelectionChangedUIListeners
-                        .iterator();
-                while (listenerItr.hasNext()) {
-                    listener = listenerItr.next();
-                    if (null != listener) {
-                        listener.onResourceSelectionChange(resource);
-                    }
-                }
-            }
-        }
-    }
-
-    private void getCompleteNotification(RemoteResource resource) {
-        synchronized (getUIListeners) {
-            if (getUIListeners.size() > 0) {
-                IGetUIListener listener;
-                Iterator<IGetUIListener> listenerItr = getUIListeners
-                        .iterator();
-                while (listenerItr.hasNext()) {
-                    listener = listenerItr.next();
-                    if (null != listener) {
-                        listener.onGetCompleted(resource);
-                    }
-                }
-            }
-        }
-    }
-
-    private void putCompleteNotification(RemoteResource resource) {
-        synchronized (putUIListeners) {
-            if (putUIListeners.size() > 0) {
-                IPutUIListener listener;
-                Iterator<IPutUIListener> listenerItr = putUIListeners
-                        .iterator();
-                while (listenerItr.hasNext()) {
-                    listener = listenerItr.next();
-                    if (null != listener) {
-                        listener.onPutCompleted(resource);
-                    }
-                }
-            }
-        }
-    }
-
-    private void postCompleteNotification(RemoteResource resource) {
-        synchronized (postUIListeners) {
-            if (postUIListeners.size() > 0) {
-                IPostUIListener listener;
-                Iterator<IPostUIListener> listenerItr = postUIListeners
-                        .iterator();
-                while (listenerItr.hasNext()) {
-                    listener = listenerItr.next();
-                    if (null != listener) {
-                        listener.onPostCompleted(resource);
-                    }
-                }
-            }
-        }
-    }
-
-    private void observeCompleteNotification(RemoteResource resource) {
-        synchronized (observeUIListeners) {
-            if (observeUIListeners.size() > 0) {
-                IObserveUIListener listener;
-                Iterator<IObserveUIListener> listenerItr = observeUIListeners
-                        .iterator();
-                while (listenerItr.hasNext()) {
-                    listener = listenerItr.next();
-                    if (null != listener) {
-                        listener.onObserveCompleted(resource);
-                    }
-                }
-            }
-        }
-    }
-
-    private void verificationStartedNotification(RemoteResource resource,
-            int autoType) {
-        synchronized (verificationUIListeners) {
-            if (verificationUIListeners.size() > 0) {
-                IVerificationUIListener listener;
-                Iterator<IVerificationUIListener> listenerItr = verificationUIListeners
-                        .iterator();
-                while (listenerItr.hasNext()) {
-                    listener = listenerItr.next();
-                    if (null != listener) {
-                        listener.onVerificationStarted(resource, autoType);
-                    }
-                }
-            }
-        }
-    }
-
-    private void verificationAbortedNotification(RemoteResource resource,
-            int autoType) {
-        synchronized (verificationUIListeners) {
-            if (verificationUIListeners.size() > 0) {
-                IVerificationUIListener listener;
-                Iterator<IVerificationUIListener> listenerItr = verificationUIListeners
-                        .iterator();
-                while (listenerItr.hasNext()) {
-                    listener = listenerItr.next();
-                    if (null != listener) {
-                        listener.onVerificationAborted(resource, autoType);
-                    }
-                }
-            }
-        }
-    }
-
-    private void verificationCompletedNotification(RemoteResource resource,
-            int autoType) {
-        synchronized (verificationUIListeners) {
-            if (verificationUIListeners.size() > 0) {
-                IVerificationUIListener listener;
-                Iterator<IVerificationUIListener> listenerItr = verificationUIListeners
-                        .iterator();
-                while (listenerItr.hasNext()) {
-                    listener = listenerItr.next();
-                    if (null != listener) {
-                        listener.onVerificationCompleted(resource, autoType);
-                    }
-                }
-            }
-        }
-    }
-
-    private void configUploadedNotification(RemoteResource resource) {
-        synchronized (configUploadUIListeners) {
-            if (configUploadUIListeners.size() > 0) {
-                IConfigurationUpload listener;
-                Iterator<IConfigurationUpload> listenerItr = configUploadUIListeners
-                        .iterator();
-                while (listenerItr.hasNext()) {
-                    listener = listenerItr.next();
-                    if (null != listener) {
-                        listener.onConfigurationUploaded(resource);
-                    }
-                }
-            }
-        }
-    }
-
-    // TODO: Temporarily used to display the resource in the UI
-    public List<String> getURIList() {
-        List<String> list = new ArrayList<String>();
-        synchronized (resourceMap) {
-            /*
-             * Set<String> idSet = resourceMap.keySet(); Iterator<String> idItr
-             * = idSet.iterator(); String sId; RemoteResource resource;
-             * while(idItr.hasNext()) { sId = idItr.next(); resource =
-             * resourceMap.get(sId); if(null == resource) { continue; }
-             * list.add(resource.getResourceURI()); }
-             */
-            Set<String> uriSet = resourceMap.keySet();
-            Iterator<String> uriItr = uriSet.iterator();
-            String uri;
-            while (uriItr.hasNext()) {
-                uri = uriItr.next();
-                if (null != uri) {
-                    list.add(uri);
+        } else {
+            Iterator<String> searchItr = searchTypes.iterator();
+            String rType;
+            while (searchItr.hasNext()) {
+                rType = searchItr.next();
+                try {
+                    SimulatorManager.findResource(rType, findResourceListener);
+                    result = true;
+                } catch (SimulatorException e) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(), new Date(),
+                                    Utility.getSimulatorErrorString(e, null));
                 }
             }
-
-            // Sort the types
-            Collections.sort(list);
-        }
-        return list;
-    }
-
-    public synchronized Set<String> getLastKnownSearchTypes() {
-        return lastKnownSearchTypes;
-    }
-
-    public synchronized void setLastKnownSearchTypes(
-            Set<String> lastKnownSearchTypes) {
-        this.lastKnownSearchTypes = lastKnownSearchTypes;
-    }
-
-    public boolean findResourceRequest(Set<String> searchTypes) {
-        if (null == searchTypes || searchTypes.size() < 1) {
-            return false;
-        }
-        boolean result = false;
-        Iterator<String> searchItr = searchTypes.iterator();
-        String rType;
-        while (searchItr.hasNext()) {
-            rType = searchItr.next();
-            try {
-                SimulatorManager.findResource(rType, findResourceListener);
-                result = true;
-            } catch (SimulatorException e) {
-                Activator
-                        .getDefault()
-                        .getLogManager()
-                        .log(Level.ERROR.ordinal(),
-                                new Date(),
-                                "[" + e.getClass().getSimpleName() + "]"
-                                        + e.code().toString() + "-"
-                                        + e.message());
-            }
         }
         return result;
     }
 
     public void deleteResources(final Set<String> searchTypes) {
-        if (null == searchTypes || searchTypes.size() < 1) {
-            return;
+        synchronized (resourceMap) {
+            if (resourceMap.isEmpty()) {
+                return;
+            }
         }
         new Thread() {
             public void run() {
-                Iterator<String> typeItr = searchTypes.iterator();
-                String resType;
-                while (typeItr.hasNext()) {
-                    resType = typeItr.next();
-                    deleteResourcesByType(resType);
+                if (null == searchTypes || searchTypes.size() < 1) {
+                    synchronized (resourceMap) {
+                        // Stop observing all the resources
+                        Iterator<String> itr = resourceMap.keySet().iterator();
+                        while (itr.hasNext()) {
+                            sendCancelObserveRequest(
+                                    resourceMap.get(itr.next()), false);
+                        }
+                        // Delete all cached details of resources
+                        resourceMap.clear();
+
+                        synchronized (favoriteResources) {
+                            favoriteResources.clear();
+                        }
 
+                        // Clearing the device and platform information
+                        synchronized (hostDeviceAndPlatformMap) {
+                            hostDeviceAndPlatformMap.clear();
+                        }
+                    }
                     // Change the current resource in selection
-                    updateCurrentResourceInSelection(searchTypes);
+                    setCurrentResourceInSelection(null);
+                    UiListenerHandler.getInstance()
+                            .resourceSelectionChangedUINotification(null);
+                } else {
+                    Iterator<String> typeItr = searchTypes.iterator();
+                    String resType;
+                    while (typeItr.hasNext()) {
+                        resType = typeItr.next();
+                        deleteResourcesByType(resType);
+
+                        // Change the current resource in selection
+                        updateCurrentResourceInSelection(searchTypes);
+                    }
                 }
             }
         }.start();
@@ -1000,7 +939,8 @@ public class ResourceManager {
         if (null == resourceInSelection) {
             return;
         }
-        List<String> typesOfSelection = resourceInSelection.getResourceTypes();
+        List<String> typesOfSelection = resourceInSelection
+                .getRemoteResourceRef().getResourceTypes();
         if (null == typesOfSelection || typesOfSelection.size() < 1) {
             return;
         }
@@ -1010,7 +950,8 @@ public class ResourceManager {
             type = itr.next();
             if (searchTypes.contains(type)) {
                 setCurrentResourceInSelection(null);
-                resourceSelectionChangedUINotification(null);
+                UiListenerHandler.getInstance()
+                        .resourceSelectionChangedUINotification(null);
                 break;
             }
         }
@@ -1036,14 +977,21 @@ public class ResourceManager {
                 if (null == resource) {
                     continue;
                 }
-                types = resource.getResourceTypes();
+                types = resource.getRemoteResourceRef().getResourceTypes();
                 if (null != types) {
                     exist = types.contains(resourceType);
                     if (exist) {
-                        // Remove the resource
-                        keyItr.remove();
+                        // Cancel observing the resource.
+                        sendCancelObserveRequest(resource, false);
                         // Remove the resource from favorites list.
                         removeResourceFromFavorites(resource);
+                        // Remove the resource
+                        keyItr.remove();
+                        // Remove the device and platform information
+                        synchronized (hostDeviceAndPlatformMap) {
+                            hostDeviceAndPlatformMap.remove(resource
+                                    .getRemoteResourceRef().getHost());
+                        }
                     }
                 }
             }
@@ -1056,47 +1004,66 @@ public class ResourceManager {
             public void run() {
                 setCurrentResourceInSelection(resource);
                 // Notify all observers for resource selection change event
-                resourceSelectionChangedUINotification(resource);
+                UiListenerHandler.getInstance()
+                        .resourceSelectionChangedUINotification(resource);
             }
         }.start();
     }
 
-    public List<MetaProperty> getMetaProperties(RemoteResource resource) {
+    public List<MetaProperty> getDefaultProperties(RemoteResource resource) {
         if (null != resource) {
             String propName;
-            String propValue;
+            StringBuilder propValue;
 
             List<MetaProperty> metaPropertyList = new ArrayList<MetaProperty>();
 
             for (int index = 0; index < Constants.META_PROPERTY_COUNT; index++) {
                 propName = Constants.META_PROPERTIES[index];
+                propValue = new StringBuilder();
                 if (propName.equals(Constants.RESOURCE_URI)) {
-                    propValue = resource.getResourceURI();
+                    propValue.append(resource.getRemoteResourceRef().getURI());
                 } else if (propName.equals(Constants.CONNECTIVITY_TYPE)) {
-                    propValue = resource.getConnectivityType().toString();
+                    propValue.append(resource.getRemoteResourceRef()
+                            .getConnectivityType().toString());
+                } else if (propName.equals(Constants.ADDRESS)) {
+                    propValue.append(resource.getRemoteResourceRef().getHost());
                 } else if (propName.equals(Constants.OBSERVABLE)) {
-                    propValue = Utility.getObservableInString(resource
-                            .isObservable());
-                    // see in UI
+                    propValue.append(Utility.getObservableInString(resource
+                            .getRemoteResourceRef().isObservable()));
                 } else if (propName.equals(Constants.RESOURCE_TYPES)) {
-                    List<String> types = resource.getResourceTypes();
-                    if (null != types) {
-                        propValue = types.toString();
+                    Vector<String> resTypes = resource.getRemoteResourceRef()
+                            .getResourceTypes();
+                    if (null != resTypes && !resTypes.isEmpty()) {
+                        Iterator<String> itr = resTypes.iterator();
+                        while (itr.hasNext()) {
+                            propValue.append(itr.next());
+                            if (itr.hasNext()) {
+                                propValue.append(", ");
+                            }
+                        }
                     } else {
-                        propValue = Constants.NOT_AVAILABLE;
+                        propValue.append(Constants.NOT_AVAILABLE);
                     }
                 } else if (propName.equals(Constants.RESOURCE_INTERFACES)) {
-                    List<String> interfaces = resource.getResourceInterfaces();
-                    if (null != interfaces) {
-                        propValue = interfaces.toString();
+                    Vector<String> interfaces = resource.getRemoteResourceRef()
+                            .getResourceInterfaces();
+                    if (null != interfaces && !interfaces.isEmpty()) {
+                        Iterator<String> itr = interfaces.iterator();
+                        while (itr.hasNext()) {
+                            propValue.append(itr.next());
+                            if (itr.hasNext()) {
+                                propValue.append(", ");
+                            }
+                        }
                     } else {
-                        propValue = Constants.NOT_AVAILABLE;
+                        propValue.append(Constants.NOT_AVAILABLE);
                     }
                 } else {
                     propValue = null;
                 }
                 if (null != propValue) {
-                    metaPropertyList.add(new MetaProperty(propName, propValue));
+                    metaPropertyList.add(new MetaProperty(propName, propValue
+                            .toString()));
                 }
             }
 
@@ -1105,6 +1072,119 @@ public class ResourceManager {
         return null;
     }
 
+    public List<MetaProperty> getDeviceProperties() {
+        RemoteResource resourceInSelection = getCurrentResourceInSelection();
+        if (null == resourceInSelection) {
+            return null;
+        }
+
+        SimulatorRemoteResource remoteResource = resourceInSelection
+                .getRemoteResourceRef();
+        if (null == remoteResource) {
+            return null;
+        }
+
+        String host = remoteResource.getHost();
+        if (null == host) {
+            return null;
+        }
+
+        if (!isDeviceInfoExist(host)) {
+            // Device Information
+            try {
+                SimulatorManager.findDevices(host, deviceListener);
+            } catch (SimulatorException e) {
+                Activator
+                        .getDefault()
+                        .getLogManager()
+                        .log(Level.ERROR.ordinal(), new Date(),
+                                Utility.getSimulatorErrorString(e, null));
+            }
+            return null;
+        }
+
+        List<MetaProperty> metaProperties = new ArrayList<MetaProperty>();
+        synchronized (hostDeviceAndPlatformMap) {
+            DeviceInfo devInfo = hostDeviceAndPlatformMap.get(host)
+                    .getDeviceInfo();
+            metaProperties.add(new MetaProperty(Constants.DEVICE_ID, devInfo
+                    .getID()));
+            metaProperties.add(new MetaProperty(Constants.DEVICE_NAME, devInfo
+                    .getName()));
+            metaProperties.add(new MetaProperty(Constants.DEVICE_SPEC_VERSION,
+                    devInfo.getSpecVersion()));
+            metaProperties.add(new MetaProperty(Constants.DEVICE_DMV_VERSION,
+                    devInfo.getDataModelVersion()));
+        }
+
+        return metaProperties;
+    }
+
+    public List<MetaProperty> getPlatformProperties() {
+        RemoteResource resourceInSelection = getCurrentResourceInSelection();
+        if (null == resourceInSelection) {
+            return null;
+        }
+
+        SimulatorRemoteResource remoteResource = resourceInSelection
+                .getRemoteResourceRef();
+        if (null == remoteResource) {
+            return null;
+        }
+
+        String host = remoteResource.getHost();
+        if (null == host) {
+            return null;
+        }
+
+        if (!isPlatformInfoExist(host)) {
+            // Platform Information
+            try {
+                SimulatorManager.getPlatformInformation(host, platformListener);
+            } catch (SimulatorException e) {
+                Activator
+                        .getDefault()
+                        .getLogManager()
+                        .log(Level.ERROR.ordinal(), new Date(),
+                                Utility.getSimulatorErrorString(e, null));
+            }
+            return null;
+        }
+
+        List<MetaProperty> metaProperties = new ArrayList<MetaProperty>();
+        synchronized (hostDeviceAndPlatformMap) {
+            PlatformInfo platInfo = hostDeviceAndPlatformMap.get(host)
+                    .getPlatformInfo();
+            metaProperties.add(new MetaProperty(Constants.PLATFORM_ID, platInfo
+                    .getPlatformID()));
+            metaProperties.add(new MetaProperty(
+                    Constants.PLATFORM_MANUFAC_NAME, platInfo
+                            .getManufacturerName()));
+            metaProperties.add(new MetaProperty(Constants.PLATFORM_MANUFAC_URL,
+                    platInfo.getManufacturerUrl()));
+            metaProperties.add(new MetaProperty(Constants.PLATFORM_MODEL_NO,
+                    platInfo.getModelNumber()));
+            metaProperties.add(new MetaProperty(
+                    Constants.PLATFORM_DATE_OF_MANUFAC, platInfo
+                            .getDateOfManufacture()));
+            metaProperties.add(new MetaProperty(Constants.PLATFORM_VERSION,
+                    platInfo.getPlatformVersion()));
+            metaProperties.add(new MetaProperty(Constants.PLATFORM_OS_VERSION,
+                    platInfo.getOperationSystemVersion()));
+            metaProperties.add(new MetaProperty(
+                    Constants.PLATFORM_HARDWARE_VERSION, platInfo
+                            .getHardwareVersion()));
+            metaProperties.add(new MetaProperty(
+                    Constants.PLATFORM_FIRMWARE_VERSION, platInfo
+                            .getFirmwareVersion()));
+            metaProperties.add(new MetaProperty(Constants.PLATFORM_SUPPORT_URL,
+                    platInfo.getSupportUrl()));
+            metaProperties.add(new MetaProperty(Constants.PLATFORM_SYSTEM_TIME,
+                    platInfo.getSystemTime()));
+        }
+        return metaProperties;
+    }
+
     public Map<String, Boolean> getAutomationStatus(RemoteResource resource) {
         if (null == resource) {
             return null;
@@ -1116,13 +1196,6 @@ public class ResourceManager {
         return autoStatus;
     }
 
-    public Map<String, String> getDummyAttributes() {
-        Map<String, String> attributes = new HashMap<String, String>();
-        attributes.put("intensity", "1");
-        attributes.put("power", "off");
-        return attributes;
-    }
-
     public List<RemoteResource> getResourceList() {
         List<RemoteResource> resourceList = new ArrayList<RemoteResource>();
         synchronized (resourceMap) {
@@ -1139,8 +1212,8 @@ public class ResourceManager {
         // Sort the list
         Collections.sort(resourceList, new Comparator<RemoteResource>() {
             public int compare(RemoteResource res1, RemoteResource res2) {
-                String s1 = res1.getResourceURI();
-                String s2 = res2.getResourceURI();
+                String s1 = res1.getRemoteResourceRef().getURI();
+                String s2 = res2.getRemoteResourceRef().getURI();
 
                 String s1Part = s1.replaceAll("\\d", "");
                 String s2Part = s2.replaceAll("\\d", "");
@@ -1169,314 +1242,395 @@ public class ResourceManager {
         return resourceList;
     }
 
-    public String getAttributeValue(RemoteResource res, String attName) {
-        if (null == res || null == attName) {
+    public List<String> getAllValuesOfAttribute(SimulatorResourceAttribute att) {
+        if (null == att) {
             return null;
         }
-        return res.getAttributeValue(attName);
+
+        AttributeValue val = att.value();
+        if (null == val || null == val.get()) {
+            return null;
+        }
+
+        TypeInfo type = val.typeInfo();
+
+        if (type.mBaseType == ValueType.RESOURCEMODEL) {
+            return null;
+        }
+
+        List<String> values = new ArrayList<String>();
+
+        AttributeProperty prop = att.property();
+        if (null == prop) {
+            values.add(new AttributeValueStringConverter(val).toString());
+            return values;
+        }
+
+        if (type.mType == ValueType.ARRAY) {
+            if (type.mDepth == 1) {
+                ArrayProperty arrayProperty = prop.asArray();
+                if (null != arrayProperty) {
+                    AttributeProperty childProp = arrayProperty
+                            .getElementProperty();
+                    switch (childProp.getType()) {
+                        case INTEGER:
+                            IntegerProperty intProperty = childProp.asInteger();
+                            if (null != intProperty) {
+                                values.addAll(getAllValues(att, intProperty,
+                                        Type.INTEGER));
+                            }
+                            break;
+                        case DOUBLE:
+                            DoubleProperty dblProperty = childProp.asDouble();
+                            if (null != dblProperty) {
+                                values.addAll(getAllValues(att, dblProperty,
+                                        Type.DOUBLE));
+                            }
+                            break;
+                        case BOOLEAN:
+                            BooleanProperty boolProperty = childProp
+                                    .asBoolean();
+                            if (null != boolProperty) {
+                                values.addAll(getAllValues(att, boolProperty,
+                                        Type.BOOLEAN));
+                            }
+                            break;
+                        case STRING:
+                            StringProperty stringProperty = childProp
+                                    .asString();
+                            if (null != stringProperty) {
+                                values.addAll(getAllValues(att, stringProperty,
+                                        Type.STRING));
+                            }
+                            break;
+                        default:
+                            break;
+                    }
+                }
+            }
+        } else {
+            switch (prop.getType()) {
+                case INTEGER:
+                    IntegerProperty intProperty = prop.asInteger();
+                    if (null != intProperty) {
+                        values.addAll(getAllValues(att, intProperty,
+                                Type.INTEGER));
+                    }
+                    break;
+                case DOUBLE:
+                    DoubleProperty dblProperty = prop.asDouble();
+                    if (null != dblProperty) {
+                        values.addAll(getAllValues(att, dblProperty,
+                                Type.DOUBLE));
+                    }
+                    break;
+                case BOOLEAN:
+                    BooleanProperty boolProperty = prop.asBoolean();
+                    if (null != boolProperty) {
+                        values.addAll(getAllValues(att, boolProperty,
+                                Type.BOOLEAN));
+                    }
+                    break;
+                case STRING:
+                    StringProperty stringProperty = prop.asString();
+                    if (null != stringProperty) {
+                        values.addAll(getAllValues(att, stringProperty,
+                                Type.STRING));
+                    }
+                    break;
+                default:
+                    break;
+            }
+        }
+
+        return values;
+    }
+
+    public List<String> getAllValues(SimulatorResourceAttribute attribute,
+            IntegerProperty intProperty, AttributeProperty.Type type) {
+        List<String> values = new ArrayList<String>();
+
+        if (intProperty.hasRange()) {
+            int min = (int) intProperty.min();
+            int max = (int) intProperty.max();
+            for (int iVal = min; iVal <= max; iVal++) {
+                values.add(String.valueOf(iVal));
+            }
+        } else if (intProperty.hasValues()) {
+            for (Integer val : intProperty.getValues()) {
+                values.add(String.valueOf(val));
+            }
+        } else {
+            AttributeValue value = attribute.value();
+            if (null != value && null != value.get()) {
+                // Adding the current value of the attribute.
+                values.add(String.valueOf(value.get()));
+            }
+        }
+        return values;
+    }
+
+    public List<String> getAllValues(SimulatorResourceAttribute attribute,
+            DoubleProperty dblProperty, AttributeProperty.Type type) {
+        NumberFormat formatter = NumberFormat.getInstance();
+        List<String> values = new ArrayList<String>();
+
+        if (dblProperty.hasRange()) {
+            double min = (double) dblProperty.min();
+            double max = (double) dblProperty.max();
+            for (double val = min; val <= max; val += 0.1) {
+                formatter.setMaximumFractionDigits(1);
+                formatter.setMinimumFractionDigits(1);
+                values.add(formatter.format(val));
+            }
+        } else if (dblProperty.hasValues()) {
+            for (Double val : dblProperty.getValues()) {
+                values.add(String.valueOf(val));
+            }
+        } else {
+            AttributeValue value = attribute.value();
+            if (null != value && null != value.get()) {
+                // Adding the current value of the attribute.
+                values.add(String.valueOf(value.get()));
+            }
+        }
+        return values;
+    }
+
+    public List<String> getAllValues(SimulatorResourceAttribute attribute,
+            BooleanProperty boolProperty, AttributeProperty.Type type) {
+        List<String> values = new ArrayList<String>();
+        values.add("true");
+        values.add("false");
+        return values;
     }
 
-    public void sendGetRequest(RemoteResource resource) {
+    public List<String> getAllValues(SimulatorResourceAttribute attribute,
+            StringProperty stringProperty, AttributeProperty.Type type) {
+        List<String> values = new ArrayList<String>();
+
+        if (stringProperty.hasValues()) {
+            for (String val : stringProperty.getValues()) {
+                values.add(String.valueOf(val));
+            }
+        } else {
+            AttributeValue value = attribute.value();
+            if (null != value && null != value.get()) {
+                // Adding the current value of the attribute.
+                values.add(String.valueOf(value.get()));
+            }
+        }
+        return values;
+    }
+
+    public void sendGetRequest(String ifType, String query,
+            RemoteResource resource) {
         if (null == resource) {
             return;
         }
-        SimulatorRemoteResource resourceN = resource.getResource();
+        SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
         if (null == resourceN) {
             return;
         }
+
+        Map<String, String> queryParams = formQueryParameters(ifType, query);
         try {
-            resourceN.get(null, getListener);
+            resourceN.get(queryParams, getListener);
         } catch (SimulatorException e) {
             Activator
                     .getDefault()
                     .getLogManager()
-                    .log(Level.ERROR.ordinal(),
-                            new Date(),
-                            "[" + e.getClass().getSimpleName() + "]"
-                                    + e.code().toString() + "-" + e.message());
+                    .log(Level.ERROR.ordinal(), new Date(),
+                            Utility.getSimulatorErrorString(e, null));
         }
     }
 
-    public void sendPutRequest(RemoteResource resource,
-            List<PutPostAttributeModel> putPostModelList) {
-        System.out.println(putPostModelList);
-        System.out.println("ResourceManager: sendPutRequest");
-        if (null == resource) {
+    public void sendPutRequest(String ifType, RemoteResource resource,
+            SimulatorResourceModel model) {
+        if (null == resource || null == model) {
             return;
         }
-        System.out.println("ResourceManager: resource not null");
-        SimulatorRemoteResource resourceN = resource.getResource();
+        SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
         if (null == resourceN) {
             return;
         }
-        System.out.println("ResourceManager: Native resource not null");
-        Map<String, RemoteResourceAttribute> attMap = resource
-                .getResourceAttributesMap();
-        if (null == attMap || attMap.size() < 1) {
-            return;
-        }
-        System.out.println("ResourceManager: attrubutes obtained");
-        SimulatorResourceModel resourceModel = getUpdatedResourceModel(attMap,
-                putPostModelList);
-        System.out.println("ResourceModel exist?:" + (resourceModel != null));
+        Map<String, String> queryParams = formQueryParameters(ifType, null);
         try {
-            resourceN.put(resourceModel, null, putListener);
-        } catch (SimulatorException e) {
+            resourceN.put(queryParams, model, putListener);
+        } catch (Exception e) {
+            String addlInfo;
+            addlInfo = "Invalid Attribute Value. Cannot send PUT request.";
             Activator
                     .getDefault()
                     .getLogManager()
-                    .log(Level.ERROR.ordinal(),
-                            new Date(),
-                            "[" + e.getClass().getSimpleName() + "]"
-                                    + e.code().toString() + "-" + e.message());
+                    .log(Level.ERROR.ordinal(), new Date(),
+                            Utility.getSimulatorErrorString(e, addlInfo));
         }
-        System.out.println("ResourceManager: called native put");
     }
 
-    public void sendPostRequest(RemoteResource resource,
-            List<PutPostAttributeModel> putPostModelList) {
-        System.out.println(putPostModelList);
-        if (null == resource) {
+    public void sendPostRequest(String ifType, RemoteResource resource,
+            SimulatorResourceModel model) {
+        if (null == resource || null == model) {
             return;
         }
-        SimulatorRemoteResource resourceN = resource.getResource();
+        SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
         if (null == resourceN) {
             return;
         }
-        Map<String, RemoteResourceAttribute> attMap = resource
-                .getResourceAttributesMap();
-        if (null == attMap || attMap.size() < 1) {
-            return;
-        }
-        // Filter out the attributes whose modification status is true.
-        Iterator<PutPostAttributeModel> itr = putPostModelList.iterator();
-        PutPostAttributeModel model;
-        while (itr.hasNext()) {
-            model = itr.next();
-            if (!model.isModified()) {
-                itr.remove();
-            }
-        }
-        SimulatorResourceModel resourceModel = getUpdatedResourceModel(attMap,
-                putPostModelList);
+        Map<String, String> queryParams = formQueryParameters(ifType, null);
         try {
-            resourceN.post(resourceModel, null, postListener);
-        } catch (SimulatorException e) {
+            resourceN.post(queryParams, model, postListener);
+        } catch (Exception e) {
+            String addlInfo;
+            addlInfo = "Invalid Attribute Value. Cannot send POST request.";
             Activator
                     .getDefault()
                     .getLogManager()
-                    .log(Level.ERROR.ordinal(),
-                            new Date(),
-                            "[" + e.getClass().getSimpleName() + "]"
-                                    + e.code().toString() + "-" + e.message());
+                    .log(Level.ERROR.ordinal(), new Date(),
+                            Utility.getSimulatorErrorString(e, addlInfo));
         }
     }
 
-    private SimulatorResourceModel getUpdatedResourceModel(
-            Map<String, RemoteResourceAttribute> attMap,
-            List<PutPostAttributeModel> putPostModelList) {
-        String attName;
-        SimulatorResourceModel resourceModel = new SimulatorResourceModel();
-        PutPostAttributeModel model;
-        RemoteResourceAttribute attribute;
-        Type attType;
-        Iterator<PutPostAttributeModel> itr = putPostModelList.iterator();
-        while (itr.hasNext()) {
-            model = itr.next();
-            attName = model.getAttName();
-            attribute = attMap.get(attName);
-            if (null == attribute) {
-                continue;
-            }
-            attType = attribute.getAttValBaseType();
-            if (attType == Type.INT) {
-                int attValue;
-                try {
-                    attValue = Integer.parseInt(model.getAttValue());
-                    resourceModel.addAttributeInt(attName, attValue);
-                } catch (NumberFormatException e) {
-                    Activator
-                            .getDefault()
-                            .getLogManager()
-                            .log(Level.ERROR.ordinal(), new Date(),
-                                    e.getMessage());
-                } catch (SimulatorException e) {
-                    Activator
-                            .getDefault()
-                            .getLogManager()
-                            .log(Level.ERROR.ordinal(),
-                                    new Date(),
-                                    "[" + e.getClass().getSimpleName() + "]"
-                                            + e.code().toString() + "-"
-                                            + e.message());
-                }
-            } else if (attType == Type.DOUBLE) {
-                double attValue;
-                try {
-                    attValue = Double.parseDouble(model.getAttValue());
-                    resourceModel.addAttributeDouble(attName, attValue);
-                } catch (NumberFormatException e) {
-                    Activator
-                            .getDefault()
-                            .getLogManager()
-                            .log(Level.ERROR.ordinal(), new Date(),
-                                    e.getMessage());
-                } catch (SimulatorException e) {
-                    Activator
-                            .getDefault()
-                            .getLogManager()
-                            .log(Level.ERROR.ordinal(),
-                                    new Date(),
-                                    "[" + e.getClass().getSimpleName() + "]"
-                                            + e.code().toString() + "-"
-                                            + e.message());
-                }
-            } else if (attType == Type.BOOL) {
-                boolean attValue;
-                attValue = Boolean.parseBoolean(model.getAttValue());
-                try {
-                    resourceModel.addAttributeBoolean(attName, attValue);
-                } catch (SimulatorException e) {
-                    Activator
-                            .getDefault()
-                            .getLogManager()
-                            .log(Level.ERROR.ordinal(),
-                                    new Date(),
-                                    "[" + e.getClass().getSimpleName() + "]"
-                                            + e.code().toString() + "-"
-                                            + e.message());
-                }
-            } else if (attType == Type.STRING) {
-                String attValue;
-                attValue = model.getAttValue();
-                try {
-                    resourceModel.addAttributeString(attName, attValue);
-                } catch (SimulatorException e) {
-                    Activator
-                            .getDefault()
-                            .getLogManager()
-                            .log(Level.ERROR.ordinal(),
-                                    new Date(),
-                                    "[" + e.getClass().getSimpleName() + "]"
-                                            + e.code().toString() + "-"
-                                            + e.message());
-                }
-            }
-        }
-        return resourceModel;
-    }
-
-    public void sendObserveRequest(RemoteResource resource) {
-        System.out.println("sendObserverRequest() entry");
+    public boolean sendObserveRequest(RemoteResource resource) {
         if (null == resource) {
-            return;
+            return false;
         }
-        System.out.println("Resource is null:" + (resource == null));
-        resource.setObserved(true);
-        SimulatorRemoteResource resourceN = resource.getResource();
+        SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
         if (null == resourceN) {
-            return;
+            return false;
         }
         try {
-            resourceN.startObserve(SimulatorObserveType.OBSERVE, null,
-                    observeListener);
+            resourceN.observe(observeListener);
+            resource.setObserved(true);
             // Add observed resource URI to show the proper status after every
             // find/refresh operations.
-            addObservedResourceURI(resource.getResourceURI());
+            addObservedResourceURI(resource.getRemoteResourceRef().getURI());
         } catch (SimulatorException e) {
             Activator
                     .getDefault()
                     .getLogManager()
-                    .log(Level.ERROR.ordinal(),
-                            new Date(),
-                            "[" + e.getClass().getSimpleName() + "]"
-                                    + e.code().toString() + "-" + e.message());
+                    .log(Level.ERROR.ordinal(), new Date(),
+                            Utility.getSimulatorErrorString(e, null));
+            return false;
         }
-        System.out.println("Observer called.");
+        return true;
     }
 
-    public void sendCancelObserveRequest(RemoteResource resource) {
-        if (null == resource) {
-            return;
+    private Map<String, String> formQueryParameters(String ifType, String query) {
+        Map<String, String> queryParams = new HashMap<String, String>();
+
+        // Including the interface type, if given,
+        if (null != ifType) {
+            ifType = ifType.trim();
+            if (ifType.length() > 0)
+                queryParams.put("if", ifType);
         }
-        resource.setObserved(false);
-        SimulatorRemoteResource resourceN = resource.getResource();
+
+        // Including other queries, if given.
+        if (null != query) {
+            query = query.trim();
+            if (query.length() > 0) {
+                // Parse the query parameters and fill the map.
+                String queries[] = query.split(";");
+                if (queries.length > 0) {
+                    for (String pair : queries) {
+                        String tok[] = pair.split("=");
+                        if (null != tok && tok.length == 2) {
+                            queryParams.put(tok[0].trim(), tok[1].trim());
+                        }
+                    }
+                }
+            }
+        }
+        return queryParams;
+    }
+
+    public boolean sendCancelObserveRequest(RemoteResource resource,
+            boolean removeEntry) {
+        if (null == resource || !resource.isObserved()) {
+            return false;
+        }
+        SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
         if (null == resourceN) {
-            return;
+            return false;
         }
         try {
             resourceN.stopObserve();
+            resource.setObserved(false);
             // Remove observed resource URI to show the proper status after
             // every find/refresh operations.
-            removeObservedResourceURI(resource.getResourceURI());
+            if (removeEntry)
+                removeObservedResourceURI(resource.getRemoteResourceRef()
+                        .getURI());
         } catch (SimulatorException e) {
             Activator
                     .getDefault()
                     .getLogManager()
-                    .log(Level.ERROR.ordinal(),
-                            new Date(),
-                            "[" + e.getClass().getSimpleName() + "]"
-                                    + e.code().toString() + "-" + e.message());
+                    .log(Level.ERROR.ordinal(), new Date(),
+                            Utility.getSimulatorErrorString(e, null));
+            return false;
         }
+        return true;
     }
 
-    public void startAutomationRequest(int reqType, RemoteResource resource) {
+    public void startAutomationRequest(RequestType reqType,
+            RemoteResource resource) {
         if (null == resource) {
             return;
         }
-        SimulatorRemoteResource resourceN = resource.getResource();
+        SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
         if (null == resourceN) {
             return;
         }
-        SimulatorVerificationType type = SimulatorVerificationType
-                .getVerificationType(reqType);
-        if (null == type) {
+        if (null == reqType) {
             return;
         }
-        System.out.println("Before calling startVerification: " + reqType);
         int autoId;
         try {
-            autoId = resourceN.startVerification(type, verifyListener);
-            System.out.println("After calling startVerification: " + autoId);
+            autoId = resourceN.startVerification(reqType, verifyListener);
             if (autoId != -1) {
-                if (reqType == Constants.GET_AUTOMATION_INDEX) {
-                    // resource.setGetAutomtnInProgress(true);
+                if (reqType == RequestType.GET) {
                     resource.setGetAutomtnId(autoId);
-                } else if (reqType == Constants.PUT_AUTOMATION_INDEX) {
-                    // resource.setPutAutomtnInProgress(true);
+                } else if (reqType == RequestType.PUT) {
                     resource.setPutAutomtnId(autoId);
-                } else {// if(reqType == Constants.POST_AUTOMATION_INDEX) {
-                        // resource.setPostAutomtnInProgress(true);
+                } else {
                     resource.setPostAutomtnId(autoId);
                 }
             }
-        } catch (SimulatorException e) {
             Activator
                     .getDefault()
                     .getLogManager()
-                    .log(Level.ERROR.ordinal(),
+                    .log(Level.INFO.ordinal(),
                             new Date(),
-                            "[" + e.getClass().getSimpleName() + "]"
-                                    + e.code().toString() + "-" + e.message());
+                            "[" + reqType.toString()
+                                    + "] Verification Started for \""
+                                    + resourceN.getURI() + "\".");
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(), new Date(),
+                            Utility.getSimulatorErrorString(e, null));
         }
     }
 
-    public void stopAutomationRequest(int reqType, RemoteResource resource) {
+    public void stopAutomationRequest(RequestType reqType,
+            RemoteResource resource) {
         if (null == resource) {
             return;
         }
-        SimulatorRemoteResource resourceN = resource.getResource();
+        SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
         if (null == resourceN) {
             return;
         }
         int autoId;
-        if (reqType == Constants.GET_AUTOMATION_INDEX) {
+        if (reqType == RequestType.GET) {
             resource.setGetAutomtnInProgress(false);
             autoId = resource.getGetAutomtnId();
-        } else if (reqType == Constants.PUT_AUTOMATION_INDEX) {
+        } else if (reqType == RequestType.PUT) {
             resource.setPutAutomtnInProgress(false);
             autoId = resource.getPutAutomtnId();
-        } else {// if(reqType == Constants.POST_AUTOMATION_INDEX) {
+        } else {
             resource.setPostAutomtnInProgress(false);
             autoId = resource.getPostAutomtnId();
         }
@@ -1486,60 +1640,55 @@ public class ResourceManager {
             Activator
                     .getDefault()
                     .getLogManager()
-                    .log(Level.ERROR.ordinal(),
-                            new Date(),
-                            "[" + e.getClass().getSimpleName() + "]"
-                                    + e.code().toString() + "-" + e.message());
+                    .log(Level.ERROR.ordinal(), new Date(),
+                            Utility.getSimulatorErrorString(e, null));
         }
     }
 
-    public void setConfigFilePath(RemoteResource resource, String configFilePath) {
+    public boolean setConfigFilePath(RemoteResource resource,
+            String configFilePath) throws SimulatorException {
+
         if (null == resource) {
-            return;
+            return false;
         }
-        SimulatorRemoteResource resourceN = resource.getResource();
+        SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
         if (null == resourceN) {
-            return;
+            return false;
         }
         try {
-            resourceN.setConfigInfo(configFilePath);
+            Map<RequestType, SimulatorRequestModel> requestModels;
+            requestModels = resourceN.setConfigInfo(configFilePath);
+            if (null == requestModels) {
+                return false;
+            }
+
+            // Store the resource model in the local cache
+            resource.setRequestModels(requestModels);
         } catch (SimulatorException e) {
             Activator
                     .getDefault()
                     .getLogManager()
+                    .log(Level.ERROR.ordinal(), new Date(),
+                            Utility.getSimulatorErrorString(e, null));
+            throw e;
+        } catch (Exception e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
                     .log(Level.ERROR.ordinal(),
                             new Date(),
-                            "[" + e.getClass().getSimpleName() + "]"
-                                    + e.code().toString() + "-" + e.message());
-            return;
+                            Utility.getSimulatorErrorString(e,
+                                    "Error while configuring the attribute properties"));
         }
         // Update the status
         resource.setConfigUploaded(true);
 
         // Notify the UI listeners
-        configUploadedNotification(resource);
-    }
-
-    public Image getImage(String resourceURI) {
-        if (null == resourceURI) {
-            return null;
-        }
-        URL url = Activator.getDefault().getBundle()
-                .getEntry(getImageURL(resourceURI));
-        if (null == url) {
-            return null;
-        }
-        return ImageDescriptor.createFromURL(url).createImage();
-    }
+        UiListenerHandler.getInstance().configUploadedNotification(resource);
 
-    private String getImageURL(String resourceURI) {
-        // TODO: Hard-coding the image file name temporarily.
-        // It will be included in a separate class which manages all image
-        // resources
-        return "/icons/light_16x16.png";
+        return true;
     }
 
     public void shutdown() {
-        // TODO: To be implemented for clean-up activities.
     }
 }
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/manager/UiListenerHandler.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/manager/UiListenerHandler.java
new file mode 100644 (file)
index 0000000..f17fe77
--- /dev/null
@@ -0,0 +1,370 @@
+package oic.simulator.clientcontroller.manager;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import org.oic.simulator.client.SimulatorRemoteResource.RequestType;
+
+import oic.simulator.clientcontroller.listener.IConfigurationUpload;
+import oic.simulator.clientcontroller.listener.IDevicePlatformInfoUIListener;
+import oic.simulator.clientcontroller.listener.IFindResourceUIListener;
+import oic.simulator.clientcontroller.listener.IGetUIListener;
+import oic.simulator.clientcontroller.listener.IObserveUIListener;
+import oic.simulator.clientcontroller.listener.IPostUIListener;
+import oic.simulator.clientcontroller.listener.IPutUIListener;
+import oic.simulator.clientcontroller.listener.IResourceSelectionChangedUIListener;
+import oic.simulator.clientcontroller.listener.IVerificationUIListener;
+import oic.simulator.clientcontroller.remoteresource.RemoteResource;
+
+public class UiListenerHandler {
+    private static UiListenerHandler                  uiHandler;
+
+    private List<IFindResourceUIListener>             findResourceUIListeners;
+    private List<IResourceSelectionChangedUIListener> resourceSelectionChangedUIListeners;
+    private List<IGetUIListener>                      getUIListeners;
+    private List<IPutUIListener>                      putUIListeners;
+    private List<IPostUIListener>                     postUIListeners;
+    private List<IObserveUIListener>                  observeUIListeners;
+    private List<IVerificationUIListener>             verificationUIListeners;
+    private List<IConfigurationUpload>                configUploadUIListeners;
+    private List<IDevicePlatformInfoUIListener>       devicePlatformInfoUIListeners;
+
+    private UiListenerHandler() {
+        findResourceUIListeners = new ArrayList<IFindResourceUIListener>();
+        resourceSelectionChangedUIListeners = new ArrayList<IResourceSelectionChangedUIListener>();
+        getUIListeners = new ArrayList<IGetUIListener>();
+        putUIListeners = new ArrayList<IPutUIListener>();
+        postUIListeners = new ArrayList<IPostUIListener>();
+        observeUIListeners = new ArrayList<IObserveUIListener>();
+        verificationUIListeners = new ArrayList<IVerificationUIListener>();
+        configUploadUIListeners = new ArrayList<IConfigurationUpload>();
+        devicePlatformInfoUIListeners = new ArrayList<IDevicePlatformInfoUIListener>();
+    }
+
+    public static UiListenerHandler getInstance() {
+        if (null == uiHandler) {
+            uiHandler = new UiListenerHandler();
+        }
+        return uiHandler;
+    }
+
+    public void addResourceSelectionChangedUIListener(
+            IResourceSelectionChangedUIListener resourceSelectionChangedUIListener) {
+        synchronized (resourceSelectionChangedUIListeners) {
+            resourceSelectionChangedUIListeners
+                    .add(resourceSelectionChangedUIListener);
+        }
+    }
+
+    public void addGetUIListener(IGetUIListener getUIListener) {
+        synchronized (getUIListeners) {
+            getUIListeners.add(getUIListener);
+        }
+    }
+
+    public void addPutUIListener(IPutUIListener putUIListener) {
+        synchronized (putUIListeners) {
+            putUIListeners.add(putUIListener);
+        }
+    }
+
+    public void addPostUIListener(IPostUIListener postUIListener) {
+        synchronized (postUIListeners) {
+            postUIListeners.add(postUIListener);
+        }
+    }
+
+    public void addObserveUIListener(IObserveUIListener observeUIListener) {
+        synchronized (observeUIListeners) {
+            observeUIListeners.add(observeUIListener);
+        }
+    }
+
+    public void addVerificationUIListener(
+            IVerificationUIListener verificationUIListener) {
+        synchronized (verificationUIListeners) {
+            verificationUIListeners.add(verificationUIListener);
+        }
+    }
+
+    public void addConfigUploadUIListener(IConfigurationUpload configListener) {
+        synchronized (configUploadUIListeners) {
+            configUploadUIListeners.add(configListener);
+        }
+    }
+
+    public void addDevicePlatformInfoUIListener(
+            IDevicePlatformInfoUIListener deviceUIListener) {
+        synchronized (devicePlatformInfoUIListeners) {
+            devicePlatformInfoUIListeners.add(deviceUIListener);
+        }
+    }
+
+    public void removeDevicePlatformInfoUIListener(
+            IDevicePlatformInfoUIListener platformUIListener) {
+        synchronized (devicePlatformInfoUIListeners) {
+            devicePlatformInfoUIListeners.remove(platformUIListener);
+        }
+    }
+
+    public void removeResourceSelectionChangedUIListener(
+            IResourceSelectionChangedUIListener listener) {
+        synchronized (resourceSelectionChangedUIListeners) {
+            if (null != listener
+                    && resourceSelectionChangedUIListeners.size() > 0) {
+                resourceSelectionChangedUIListeners.remove(listener);
+            }
+        }
+    }
+
+    public void removeGetUIListener(IGetUIListener getUIListener) {
+        synchronized (getUIListeners) {
+            getUIListeners.remove(getUIListener);
+        }
+    }
+
+    public void removePutUIListener(IPutUIListener putUIListener) {
+        synchronized (putUIListeners) {
+            putUIListeners.remove(putUIListener);
+        }
+    }
+
+    public void removePostUIListener(IPostUIListener postUIListener) {
+        synchronized (postUIListeners) {
+            postUIListeners.remove(postUIListener);
+        }
+    }
+
+    public void removeObserveUIListener(IObserveUIListener observeUIListener) {
+        synchronized (observeUIListeners) {
+            observeUIListeners.remove(observeUIListener);
+        }
+    }
+
+    public void removeVerificationUIListener(
+            IVerificationUIListener verificationUIListener) {
+        synchronized (verificationUIListeners) {
+            verificationUIListeners.remove(verificationUIListener);
+        }
+    }
+
+    public void removeConfigUploadUIListener(IConfigurationUpload configListener) {
+        synchronized (configUploadUIListeners) {
+            configUploadUIListeners.remove(configListener);
+        }
+    }
+
+    public void addFindresourceUIListener(IFindResourceUIListener listener) {
+        if (null == listener) {
+            return;
+        }
+        synchronized (findResourceUIListeners) {
+            findResourceUIListeners.add(listener);
+        }
+    }
+
+    public void removeFindresourceUIListener(IFindResourceUIListener listener) {
+        if (null == listener) {
+            return;
+        }
+        synchronized (findResourceUIListeners) {
+            findResourceUIListeners.remove(listener);
+        }
+    }
+
+    public void newResourceFoundNotification(RemoteResource resource) {
+        synchronized (findResourceUIListeners) {
+            if (findResourceUIListeners.size() > 0) {
+                IFindResourceUIListener listener;
+                Iterator<IFindResourceUIListener> listenerItr = findResourceUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onNewResourceFound(resource);
+                    }
+                }
+            }
+        }
+    }
+
+    public void resourceSelectionChangedUINotification(RemoteResource resource) {
+        synchronized (resourceSelectionChangedUIListeners) {
+            if (resourceSelectionChangedUIListeners.size() > 0) {
+                IResourceSelectionChangedUIListener listener;
+                Iterator<IResourceSelectionChangedUIListener> listenerItr = resourceSelectionChangedUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onResourceSelectionChange(resource);
+                    }
+                }
+            }
+        }
+    }
+
+    public void getCompleteNotification(RemoteResource resource) {
+        synchronized (getUIListeners) {
+            if (getUIListeners.size() > 0) {
+                IGetUIListener listener;
+                Iterator<IGetUIListener> listenerItr = getUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onGetCompleted(resource);
+                    }
+                }
+            }
+        }
+    }
+
+    public void putCompleteNotification(RemoteResource resource) {
+        synchronized (putUIListeners) {
+            if (putUIListeners.size() > 0) {
+                IPutUIListener listener;
+                Iterator<IPutUIListener> listenerItr = putUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onPutCompleted(resource);
+                    }
+                }
+            }
+        }
+    }
+
+    public void postCompleteNotification(RemoteResource resource) {
+        synchronized (postUIListeners) {
+            if (postUIListeners.size() > 0) {
+                IPostUIListener listener;
+                Iterator<IPostUIListener> listenerItr = postUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onPostCompleted(resource);
+                    }
+                }
+            }
+        }
+    }
+
+    public void observeCompleteNotification(RemoteResource resource) {
+        synchronized (observeUIListeners) {
+            if (observeUIListeners.size() > 0) {
+                IObserveUIListener listener;
+                Iterator<IObserveUIListener> listenerItr = observeUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onObserveCompleted(resource);
+                    }
+                }
+            }
+        }
+    }
+
+    public void verificationStartedNotification(RemoteResource resource,
+            RequestType reqType) {
+        synchronized (verificationUIListeners) {
+            if (verificationUIListeners.size() > 0) {
+                IVerificationUIListener listener;
+                Iterator<IVerificationUIListener> listenerItr = verificationUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onVerificationStarted(resource, reqType);
+                    }
+                }
+            }
+        }
+    }
+
+    public void verificationAbortedNotification(RemoteResource resource,
+            RequestType reqType) {
+        synchronized (verificationUIListeners) {
+            if (verificationUIListeners.size() > 0) {
+                IVerificationUIListener listener;
+                Iterator<IVerificationUIListener> listenerItr = verificationUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onVerificationAborted(resource, reqType);
+                    }
+                }
+            }
+        }
+    }
+
+    public void verificationCompletedNotification(RemoteResource resource,
+            RequestType reqType) {
+        synchronized (verificationUIListeners) {
+            if (verificationUIListeners.size() > 0) {
+                IVerificationUIListener listener;
+                Iterator<IVerificationUIListener> listenerItr = verificationUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onVerificationCompleted(resource, reqType);
+                    }
+                }
+            }
+        }
+    }
+
+    public void configUploadedNotification(RemoteResource resource) {
+        synchronized (configUploadUIListeners) {
+            if (configUploadUIListeners.size() > 0) {
+                IConfigurationUpload listener;
+                Iterator<IConfigurationUpload> listenerItr = configUploadUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onConfigurationUploaded(resource);
+                    }
+                }
+            }
+        }
+    }
+
+    public void deviceInfoReceivedNotification() {
+        synchronized (devicePlatformInfoUIListeners) {
+            if (devicePlatformInfoUIListeners.size() > 0) {
+                IDevicePlatformInfoUIListener listener;
+                Iterator<IDevicePlatformInfoUIListener> listenerItr = devicePlatformInfoUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onDeviceInfoFound();
+                    }
+                }
+            }
+        }
+    }
+
+    public void platformInfoReceivedNotification() {
+        synchronized (devicePlatformInfoUIListeners) {
+            if (devicePlatformInfoUIListeners.size() > 0) {
+                IDevicePlatformInfoUIListener listener;
+                Iterator<IDevicePlatformInfoUIListener> listenerItr = devicePlatformInfoUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onPlatformInfoFound();
+                    }
+                }
+            }
+        }
+    }
+}
index 527e460..1e2ff50 100644 (file)
 
 package oic.simulator.clientcontroller.perspective;
 
+import org.eclipse.ui.IPageLayout;
+import org.eclipse.ui.IPerspectiveFactory;
+
 import oic.simulator.clientcontroller.view.AttributeView;
 import oic.simulator.clientcontroller.view.LogView;
 import oic.simulator.clientcontroller.view.MetaPropertiesView;
-import oic.simulator.clientcontroller.view.MultiResourceOrchestrationView;
 import oic.simulator.clientcontroller.view.ResourceManagerView;
 
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IPerspectiveFactory;
-
 /**
  * This class creates a new eclipse perspective for client controller and
  * positions the different views inside.
@@ -43,15 +42,13 @@ public class PerspectiveFactory implements IPerspectiveFactory {
     }
 
     private void addViews() {
-        factory.addView(ResourceManagerView.VIEW_ID, IPageLayout.LEFT, 0.3f,
+        factory.addView(ResourceManagerView.VIEW_ID, IPageLayout.LEFT, 0.28f,
                 factory.getEditorArea());
-        factory.addView(MetaPropertiesView.VIEW_ID, IPageLayout.BOTTOM, 0.65f,
-                ResourceManagerView.VIEW_ID);
         factory.addView(AttributeView.VIEW_ID, IPageLayout.LEFT, 0.7f,
                 factory.getEditorArea());
         factory.addView(LogView.VIEW_ID, IPageLayout.BOTTOM, 0.65f,
                 AttributeView.VIEW_ID);
-        factory.addView(MultiResourceOrchestrationView.VIEW_ID,
-                IPageLayout.RIGHT, 0.6f, AttributeView.VIEW_ID);
+        factory.addView(MetaPropertiesView.VIEW_ID, IPageLayout.RIGHT, 0.6f,
+                AttributeView.VIEW_ID);
     }
 }
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/AttributeElement.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/AttributeElement.java
new file mode 100644 (file)
index 0000000..ac43c02
--- /dev/null
@@ -0,0 +1,476 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.clientcontroller.remoteresource;
+
+import java.util.Date;
+import java.util.Map;
+import java.util.TreeMap;
+
+import org.oic.simulator.ArrayProperty;
+import org.oic.simulator.AttributeProperty;
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.ILogger.Level;
+import org.oic.simulator.InvalidArgsException;
+import org.oic.simulator.ModelProperty;
+import org.oic.simulator.SimulatorResourceAttribute;
+import org.oic.simulator.SimulatorResourceModel;
+
+import oic.simulator.clientcontroller.Activator;
+import oic.simulator.clientcontroller.utils.AttributeValueStringConverter;
+import oic.simulator.clientcontroller.utils.Utility;
+
+public class AttributeElement {
+    private Object                        mParent          = null;
+    private SimulatorResourceAttribute    mAttribute       = null;
+    private Map<String, AttributeElement> mChildAttributes = new TreeMap<String, AttributeElement>();
+    private boolean                       mPostState       = false;
+
+    public AttributeElement(Object parent, SimulatorResourceAttribute attribute) {
+        mParent = parent;
+        mAttribute = attribute;
+        AttributeValue.TypeInfo typeInfo = attribute.value().typeInfo();
+        if (typeInfo.mType == AttributeValue.ValueType.RESOURCEMODEL) {
+            SimulatorResourceModel resModel = (SimulatorResourceModel) attribute
+                    .value().get();
+            ModelProperty modelProp = null;
+            if (null != attribute.property()) {
+                modelProp = attribute.property().asModel();
+            }
+            String attName;
+            for (Map.Entry<String, AttributeValue> entry : resModel.get()
+                    .entrySet()) {
+                attName = entry.getKey();
+                AttributeProperty prop = null;
+                if (null != modelProp)
+                    prop = modelProp.get(attName);
+                mChildAttributes.put(
+                        attName,
+                        new AttributeElement(this,
+                                new SimulatorResourceAttribute(attName, entry
+                                        .getValue(), prop)));
+            }
+        } else if (typeInfo.mType == AttributeValue.ValueType.ARRAY) {
+            if (typeInfo.mBaseType == AttributeValue.ValueType.RESOURCEMODEL) {
+                if (typeInfo.mDepth == 1) {
+                    SimulatorResourceModel[] resModelArray = (SimulatorResourceModel[]) attribute
+                            .value().get();
+
+                    ModelProperty modelProp = null;
+                    if (null != attribute.property()) {
+                        ArrayProperty arrProp;
+                        arrProp = attribute.property().asArray();
+                        if (null != arrProp
+                                && null != arrProp.getElementProperty()) {
+                            modelProp = arrProp.getElementProperty().asModel();
+                        }
+                    }
+                    for (int i = 0; i < resModelArray.length; i++) {
+                        SimulatorResourceAttribute indexAttribute = new SimulatorResourceAttribute(
+                                "[" + Integer.toString(i) + "]",
+                                new AttributeValue(resModelArray[i]), modelProp);
+                        mChildAttributes.put("[" + Integer.toString(i) + "]",
+                                new AttributeElement(this, indexAttribute));
+                    }
+                } else if (typeInfo.mDepth == 2) {
+                    SimulatorResourceModel[][] resModelArray = (SimulatorResourceModel[][]) attribute
+                            .value().get();
+
+                    ModelProperty modelProp = null;
+                    if (null != attribute.property()) {
+                        ArrayProperty arrProp = attribute.property().asArray();
+                        if (null != arrProp
+                                && null != arrProp.getElementProperty()) {
+                            ArrayProperty arrChildPropLevel1 = arrProp
+                                    .getElementProperty().asArray();
+                            if (null != arrChildPropLevel1
+                                    && null != arrChildPropLevel1
+                                            .getElementProperty()) {
+                                modelProp = arrProp.getElementProperty()
+                                        .asModel();
+                            }
+                        }
+                    }
+
+                    for (int i = 0; i < resModelArray.length; i++) {
+                        SimulatorResourceAttribute indexAttribute = new SimulatorResourceAttribute(
+                                "[" + Integer.toString(i) + "]",
+                                new AttributeValue(resModelArray[i]), modelProp);
+                        mChildAttributes.put("[" + Integer.toString(i) + "]",
+                                new AttributeElement(this, indexAttribute));
+                    }
+                } else if (typeInfo.mDepth == 3) {
+                    SimulatorResourceModel[][][] resModelArray = (SimulatorResourceModel[][][]) attribute
+                            .value().get();
+
+                    ModelProperty modelProp = null;
+                    if (null != attribute.property()) {
+                        ArrayProperty arrProp = attribute.property().asArray();
+                        if (null != arrProp
+                                && null != arrProp.getElementProperty()) {
+                            ArrayProperty arrChildPropLevel1 = arrProp
+                                    .getElementProperty().asArray();
+                            if (null != arrChildPropLevel1
+                                    && null != arrChildPropLevel1
+                                            .getElementProperty()) {
+                                ArrayProperty arrChildPropLevel2 = arrChildPropLevel1
+                                        .getElementProperty().asArray();
+                                if (null != arrChildPropLevel2
+                                        && null != arrChildPropLevel2
+                                                .getElementProperty()) {
+                                    modelProp = arrChildPropLevel2
+                                            .getElementProperty().asModel();
+                                }
+                            }
+                        }
+                    }
+
+                    for (int i = 0; i < resModelArray.length; i++) {
+                        SimulatorResourceAttribute indexAttribute = new SimulatorResourceAttribute(
+                                "[" + Integer.toString(i) + "]",
+                                new AttributeValue(resModelArray[i]), modelProp);
+                        mChildAttributes.put("[" + Integer.toString(i) + "]",
+                                new AttributeElement(this, indexAttribute));
+                    }
+                }
+            }
+        }
+    }
+
+    public Object getParent() {
+        return mParent;
+    }
+
+    public boolean hasChildren() {
+        if (mChildAttributes != null && mChildAttributes.size() > 0)
+            return true;
+        return false;
+    }
+
+    public Map<String, AttributeElement> getChildren() {
+        if (hasChildren() == true)
+            return mChildAttributes;
+        return null;
+    }
+
+    public SimulatorResourceAttribute getSimulatorResourceAttribute() {
+        return mAttribute;
+    }
+
+    public boolean getPostState() {
+        return mPostState;
+    }
+
+    public void setPostState(boolean mPostState) {
+        this.mPostState = mPostState;
+    }
+
+    public void deepSetChildValue(SimulatorResourceAttribute attribute)
+            throws InvalidArgsException {
+        if (null == attribute || null == attribute.name())
+            return;
+
+        AttributeValue.TypeInfo myValuetypeInfo = mAttribute.value().typeInfo();
+        if (myValuetypeInfo.mType == AttributeValue.ValueType.RESOURCEMODEL) {
+            SimulatorResourceModel resModel = (SimulatorResourceModel) mAttribute
+                    .value().get();
+            if (resModel.contains(attribute.name()))
+                resModel.set(attribute.name(), attribute.value());
+            else
+                return;
+        }
+
+        if (mParent instanceof AttributeElement)
+            ((AttributeElement) mParent).deepSetChildValue(mAttribute);
+    }
+
+    public void setAttributeProperty(SimulatorResourceAttribute attribute)
+            throws NullPointerException {
+        if (attribute == null)
+            return;
+
+        AttributeValue.TypeInfo typeInfo = attribute.value().typeInfo();
+        if (typeInfo.mType == AttributeValue.ValueType.RESOURCEMODEL) {
+            SimulatorResourceModel resModel = (SimulatorResourceModel) attribute
+                    .value().get();
+
+            ModelProperty modelProp = attribute.property().asModel();
+            mAttribute.setProperty(modelProp);
+
+            for (Map.Entry<String, AttributeValue> entry : resModel.get()
+                    .entrySet()) {
+                AttributeElement attributeElement = mChildAttributes.get(entry
+                        .getKey());
+                if (attributeElement != null) {
+                    attributeElement
+                            .setAttributeProperty(new SimulatorResourceAttribute(
+                                    entry.getKey(), entry.getValue(), modelProp
+                                            .get(entry.getKey())));
+                } else {
+                    // Display new attribute in UI
+                    AttributeElement newAttribute = new AttributeElement(this,
+                            new SimulatorResourceAttribute(entry.getKey(),
+                                    entry.getValue(), modelProp.get(entry
+                                            .getKey())));
+                    mChildAttributes.put(entry.getKey(), newAttribute);
+                }
+            }
+        } else if (typeInfo.mType == AttributeValue.ValueType.ARRAY
+                && typeInfo.mBaseType == AttributeValue.ValueType.RESOURCEMODEL) {
+
+            ArrayProperty arrayProp = attribute.property().asArray();
+            mAttribute.setProperty(arrayProp);
+
+            ModelProperty elementModelProp = arrayProp.getElementProperty()
+                    .asModel();
+
+            if (typeInfo.mDepth == 1) {
+                SimulatorResourceModel[] resModelArray = (SimulatorResourceModel[]) attribute
+                        .value().get();
+
+                for (int i = 0; i < resModelArray.length; i++) {
+                    SimulatorResourceAttribute indexAttribute = new SimulatorResourceAttribute(
+                            "[" + Integer.toString(i) + "]",
+                            new AttributeValue(resModelArray[i]),
+                            elementModelProp);
+                    AttributeElement attributeElement = mChildAttributes
+                            .get("[" + Integer.toString(i) + "]");
+                    if (attributeElement != null) {
+                        attributeElement.setAttributeProperty(indexAttribute);
+                    } else {
+                        // Display new attribute in UI
+                        AttributeElement newAttribute = new AttributeElement(
+                                this, indexAttribute);
+                        mChildAttributes.put("[" + Integer.toString(i) + "]",
+                                newAttribute);
+                    }
+                }
+            }
+            if (typeInfo.mDepth == 2) {
+                SimulatorResourceModel[][] resModelArray = (SimulatorResourceModel[][]) attribute
+                        .value().get();
+                for (int i = 0; i < resModelArray.length; i++) {
+                    SimulatorResourceAttribute indexAttribute = new SimulatorResourceAttribute(
+                            "[" + Integer.toString(i) + "]",
+                            new AttributeValue(resModelArray[i]),
+                            elementModelProp);
+                    AttributeElement attributeElement = mChildAttributes
+                            .get("[" + Integer.toString(i) + "]");
+                    if (attributeElement != null) {
+                        attributeElement.setAttributeProperty(indexAttribute);
+                    } else {
+                        // Display new attribute in UI
+                        AttributeElement newAttribute = new AttributeElement(
+                                this, indexAttribute);
+                        mChildAttributes.put("[" + Integer.toString(i) + "]",
+                                newAttribute);
+                    }
+                }
+            }
+            if (typeInfo.mDepth == 3) {
+                SimulatorResourceModel[][][] resModelArray = (SimulatorResourceModel[][][]) attribute
+                        .value().get();
+                for (int i = 0; i < resModelArray.length; i++) {
+                    SimulatorResourceAttribute indexAttribute = new SimulatorResourceAttribute(
+                            "[" + Integer.toString(i) + "]",
+                            new AttributeValue(resModelArray[i]),
+                            elementModelProp);
+                    AttributeElement attributeElement = mChildAttributes
+                            .get("[" + Integer.toString(i) + "]");
+                    if (attributeElement != null) {
+                        attributeElement.setAttributeProperty(indexAttribute);
+                    } else {
+                        // Display new attribute in UI
+                        AttributeElement newAttribute = new AttributeElement(
+                                this, indexAttribute);
+                        mChildAttributes.put("[" + Integer.toString(i) + "]",
+                                newAttribute);
+                    }
+                }
+            }
+        } else {
+            mAttribute.setProperty(attribute.property());
+        }
+    }
+
+    public void update(SimulatorResourceAttribute attribute) {
+        if (attribute == null)
+            return;
+
+        AttributeValue.TypeInfo typeInfo = attribute.value().typeInfo();
+        if (typeInfo.mType == AttributeValue.ValueType.RESOURCEMODEL) {
+            SimulatorResourceModel resModel = (SimulatorResourceModel) attribute
+                    .value().get();
+            ModelProperty modelProp = null;
+            if (null != attribute.property()) {
+                modelProp = attribute.property().asModel();
+            }
+            String attName;
+            for (Map.Entry<String, AttributeValue> entry : resModel.get()
+                    .entrySet()) {
+                attName = entry.getKey();
+                AttributeElement attributeElement = mChildAttributes
+                        .get(attName);
+                AttributeProperty prop = null;
+                if (null != modelProp)
+                    prop = modelProp.get(attName);
+
+                if (attributeElement != null) {
+                    attributeElement.update(new SimulatorResourceAttribute(
+                            attName, entry.getValue()));
+                } else {
+                    // Display new attribute in UI
+                    AttributeElement newAttribute = new AttributeElement(this,
+                            new SimulatorResourceAttribute(attName,
+                                    entry.getValue(), prop));
+                    mChildAttributes.put(attName, newAttribute);
+                }
+            }
+        } else if (typeInfo.mType == AttributeValue.ValueType.ARRAY
+                && typeInfo.mBaseType == AttributeValue.ValueType.RESOURCEMODEL) {
+            if (typeInfo.mDepth == 1) {
+                SimulatorResourceModel[] resModelArray = (SimulatorResourceModel[]) attribute
+                        .value().get();
+
+                ModelProperty modelProp = null;
+                if (null != attribute.property()) {
+                    ArrayProperty arrProp = attribute.property().asArray();
+                    if (null != arrProp && null != arrProp.getElementProperty()) {
+                        modelProp = arrProp.getElementProperty().asModel();
+                    }
+                }
+
+                for (int i = 0; i < resModelArray.length; i++) {
+                    SimulatorResourceAttribute indexAttribute = new SimulatorResourceAttribute(
+                            "[" + Integer.toString(i) + "]",
+                            new AttributeValue(resModelArray[i]), modelProp);
+                    AttributeElement attributeElement = mChildAttributes
+                            .get("[" + Integer.toString(i) + "]");
+                    if (attributeElement != null) {
+                        attributeElement.update(indexAttribute);
+                    } else {
+                        // Display new attribute in UI
+                        AttributeElement newAttribute = new AttributeElement(
+                                this, indexAttribute);
+                        mChildAttributes.put("[" + Integer.toString(i) + "]",
+                                newAttribute);
+                    }
+                }
+            }
+            if (typeInfo.mDepth == 2) {
+                SimulatorResourceModel[][] resModelArray = (SimulatorResourceModel[][]) attribute
+                        .value().get();
+
+                ModelProperty modelProp = null;
+                if (null != attribute.property()) {
+                    ArrayProperty arrProp = attribute.property().asArray();
+                    if (null != arrProp && null != arrProp.getElementProperty()) {
+                        ArrayProperty arrChildPropLevel1 = arrProp
+                                .getElementProperty().asArray();
+                        if (null != arrChildPropLevel1
+                                && null != arrChildPropLevel1
+                                        .getElementProperty()) {
+                            modelProp = arrProp.getElementProperty().asModel();
+                        }
+                    }
+                }
+
+                for (int i = 0; i < resModelArray.length; i++) {
+                    SimulatorResourceAttribute indexAttribute = new SimulatorResourceAttribute(
+                            "[" + Integer.toString(i) + "]",
+                            new AttributeValue(resModelArray[i]), modelProp);
+                    AttributeElement attributeElement = mChildAttributes
+                            .get("[" + Integer.toString(i) + "]");
+                    if (attributeElement != null) {
+                        attributeElement.update(indexAttribute);
+                    } else {
+                        // Display new attribute in UI
+                        AttributeElement newAttribute = new AttributeElement(
+                                this, indexAttribute);
+                        mChildAttributes.put("[" + Integer.toString(i) + "]",
+                                newAttribute);
+                    }
+                }
+            }
+            if (typeInfo.mDepth == 3) {
+                SimulatorResourceModel[][][] resModelArray = (SimulatorResourceModel[][][]) attribute
+                        .value().get();
+
+                ModelProperty modelProp = null;
+                if (null != attribute.property()) {
+                    ArrayProperty arrProp = attribute.property().asArray();
+                    if (null != arrProp && null != arrProp.getElementProperty()) {
+                        ArrayProperty arrChildPropLevel1 = arrProp
+                                .getElementProperty().asArray();
+                        if (null != arrChildPropLevel1
+                                && null != arrChildPropLevel1
+                                        .getElementProperty()) {
+                            ArrayProperty arrChildPropLevel2 = arrChildPropLevel1
+                                    .getElementProperty().asArray();
+                            if (null != arrChildPropLevel2
+                                    && null != arrChildPropLevel2
+                                            .getElementProperty()) {
+                                modelProp = arrChildPropLevel2
+                                        .getElementProperty().asModel();
+                            }
+                        }
+                    }
+                }
+
+                for (int i = 0; i < resModelArray.length; i++) {
+                    SimulatorResourceAttribute indexAttribute = new SimulatorResourceAttribute(
+                            "[" + Integer.toString(i) + "]",
+                            new AttributeValue(resModelArray[i]), modelProp);
+                    AttributeElement attributeElement = mChildAttributes
+                            .get("[" + Integer.toString(i) + "]");
+                    if (attributeElement != null) {
+                        attributeElement.update(indexAttribute);
+                    } else {
+                        // Display new attribute in UI
+                        AttributeElement newAttribute = new AttributeElement(
+                                this, indexAttribute);
+                        mChildAttributes.put("[" + Integer.toString(i) + "]",
+                                newAttribute);
+                    }
+                }
+            }
+        } else {
+            String currentValue = new AttributeValueStringConverter(
+                    mAttribute.value()).toString();
+            String newValue = new AttributeValueStringConverter(
+                    attribute.value()).toString();
+            if (!currentValue.equals(newValue)) {
+                mAttribute.setValue(attribute.value());
+                if (mParent instanceof AttributeElement) {
+                    try {
+                        ((AttributeElement) mParent)
+                                .deepSetChildValue(mAttribute);
+                    } catch (InvalidArgsException e) {
+                        Activator
+                                .getDefault()
+                                .getLogManager()
+                                .log(Level.ERROR.ordinal(),
+                                        new Date(),
+                                        "There is an error while updating the resource model.\n"
+                                                + Utility
+                                                        .getSimulatorErrorString(
+                                                                e, null));
+                    }
+                }
+            }
+        }
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/DeviceAndPlatformInfo.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/DeviceAndPlatformInfo.java
new file mode 100644 (file)
index 0000000..fb4e8c1
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.clientcontroller.remoteresource;
+
+import org.oic.simulator.DeviceInfo;
+import org.oic.simulator.PlatformInfo;
+
+public class DeviceAndPlatformInfo {
+    private String       host;
+    private DeviceInfo   deviceInfo;
+    private PlatformInfo platformInfo;
+
+    public String getHost() {
+        return host;
+    }
+
+    public void setHost(String host) {
+        this.host = host;
+    }
+
+    public DeviceInfo getDeviceInfo() {
+        return deviceInfo;
+    }
+
+    public void setDeviceInfo(DeviceInfo deviceInfo) {
+        this.deviceInfo = deviceInfo;
+    }
+
+    public PlatformInfo getPlatformInfo() {
+        return platformInfo;
+    }
+
+    public void setPlatformInfo(PlatformInfo platformInfo) {
+        this.platformInfo = platformInfo;
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/PutPostAttributeModel.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/PutPostAttributeModel.java
deleted file mode 100644 (file)
index 0b566a0..0000000
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * 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.
- */
-
-package oic.simulator.clientcontroller.remoteresource;
-
-import java.util.List;
-
-/**
- * This is a helper class for showing the resource attributes in PUT and POST
- * dialogs.
- */
-public class PutPostAttributeModel {
-
-    private String       attName;
-    private String       attValue;
-    private List<String> values;
-    boolean              modified;
-
-    public String getAttName() {
-        return attName;
-    }
-
-    public void setAttName(String attName) {
-        this.attName = attName;
-    }
-
-    public String getAttValue() {
-        return attValue;
-    }
-
-    public void setAttValue(String attValue) {
-        this.attValue = attValue;
-    }
-
-    public List<String> getValues() {
-        return values;
-    }
-
-    public void setValues(List<String> values) {
-        this.values = values;
-    }
-
-    public boolean isModified() {
-        return modified;
-    }
-
-    public void setModified(boolean modified) {
-        this.modified = modified;
-    }
-
-    public static PutPostAttributeModel getModel(
-            RemoteResourceAttribute attribute) {
-        PutPostAttributeModel putPostModel = null;
-        if (null != attribute) {
-            putPostModel = new PutPostAttributeModel();
-            putPostModel.setAttName(attribute.getAttributeName());
-            putPostModel.setAttValue(String.valueOf(attribute
-                    .getAttributeValue()));
-            putPostModel.setValues(attribute.getAllValues());
-            putPostModel.setModified(false);
-        }
-        return putPostModel;
-    }
-
-    @Override
-    public String toString() {
-        return attName + "," + attValue + "\n";
-    }
-
-}
index 17a052e..00a0b3d 100644 (file)
 
 package oic.simulator.clientcontroller.remoteresource;
 
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
 import java.util.Map;
 
-import oic.simulator.clientcontroller.utils.Constants;
-
 import org.oic.simulator.SimulatorResourceModel;
-import org.oic.simulator.clientcontroller.SimulatorConnectivityType;
-import org.oic.simulator.clientcontroller.SimulatorRemoteResource;
+import org.oic.simulator.client.SimulatorRemoteResource;
+import org.oic.simulator.client.SimulatorRemoteResource.RequestType;
+import org.oic.simulator.client.SimulatorRequestModel;
 
 /**
  * This class represents a remote resource. It maintains all the necessary
  * information about the resource.
  */
 public class RemoteResource {
-    private String                               uId;
-    private String                               resourceURI;
-    private String                               host;
-    private LinkedList<String>                   resourceTypes;
-    private LinkedList<String>                   resourceInterfaces;
-    private SimulatorConnectivityType            connectivityType;
-    private boolean                              isObservable;
 
-    private boolean                              observed;
+    private boolean                                 observed;
 
     // Native object references
-    private SimulatorRemoteResource              resourceN;
-    private SimulatorResourceModel               resourceModel;
-    private Map<String, RemoteResourceAttribute> resourceAttributesMap;
+    private SimulatorRemoteResource                 remoteResourceRef;
+    private SimulatorResourceModel                  resourceModelRef;
+    private Map<RequestType, SimulatorRequestModel> requestModels;
+    private ResourceRepresentation                  mResourceRepresentation;
 
-    private boolean                              configUploaded;
+    private boolean                                 configUploaded;
 
-    private boolean                              getAutomtnInProgress;
-    private boolean                              putAutomtnInProgress;
-    private boolean                              postAutomtnInProgress;
+    private boolean                                 getAutomtnInProgress;
+    private boolean                                 putAutomtnInProgress;
+    private boolean                                 postAutomtnInProgress;
 
-    private int                                  getAutomtnId;
-    private int                                  putAutomtnId;
-    private int                                  postAutomtnId;
+    private int                                     getAutomtnId;
+    private int                                     putAutomtnId;
+    private int                                     postAutomtnId;
 
-    private boolean                              isFavorite;
+    private boolean                                 isFavorite;
 
-    public SimulatorResourceModel getResourceModel() {
-        return resourceModel;
+    public SimulatorResourceModel getResourceModelRef() {
+        return resourceModelRef;
     }
 
-    public void setResourceModel(SimulatorResourceModel resourceModel) {
-        this.resourceModel = resourceModel;
+    public void setResourceModelRef(SimulatorResourceModel resourceModel) {
+        this.resourceModelRef = resourceModel;
     }
 
-    public Map<String, RemoteResourceAttribute> getResourceAttributesMap() {
-        return resourceAttributesMap;
+    public Map<RequestType, SimulatorRequestModel> getRequestModels() {
+        return requestModels;
     }
 
-    public void setResourceAttributesMap(
-            Map<String, RemoteResourceAttribute> resourceAttributesMap) {
-        this.resourceAttributesMap = resourceAttributesMap;
+    public void setRequestModels(
+            Map<RequestType, SimulatorRequestModel> requestModels) {
+        this.requestModels = requestModels;
     }
 
     public int getGetAutomtnId() {
@@ -101,54 +90,6 @@ public class RemoteResource {
         this.postAutomtnId = postAutomtnId;
     }
 
-    public String getResourceURI() {
-        return resourceURI;
-    }
-
-    public void setResourceURI(String resourceURI) {
-        this.resourceURI = resourceURI;
-    }
-
-    public String getHost() {
-        return host;
-    }
-
-    public void setHost(String host) {
-        this.host = host;
-    }
-
-    public LinkedList<String> getResourceTypes() {
-        return resourceTypes;
-    }
-
-    public void setResourceTypes(LinkedList<String> resourceTypes) {
-        this.resourceTypes = resourceTypes;
-    }
-
-    public LinkedList<String> getResourceInterfaces() {
-        return resourceInterfaces;
-    }
-
-    public void setResourceInterfaces(LinkedList<String> resourceInterfaces) {
-        this.resourceInterfaces = resourceInterfaces;
-    }
-
-    public SimulatorConnectivityType getConnectivityType() {
-        return connectivityType;
-    }
-
-    public void setConnectivityType(SimulatorConnectivityType connectivityType) {
-        this.connectivityType = connectivityType;
-    }
-
-    public boolean isObservable() {
-        return isObservable;
-    }
-
-    public void setObservable(boolean isObservable) {
-        this.isObservable = isObservable;
-    }
-
     public boolean isGetAutomtnInProgress() {
         return getAutomtnInProgress;
     }
@@ -181,12 +122,12 @@ public class RemoteResource {
         this.configUploaded = configUploaded;
     }
 
-    public SimulatorRemoteResource getResource() {
-        return resourceN;
+    public SimulatorRemoteResource getRemoteResourceRef() {
+        return remoteResourceRef;
     }
 
-    public void setResource(SimulatorRemoteResource resource) {
-        this.resourceN = resource;
+    public void setRemoteResourceRef(SimulatorRemoteResource resource) {
+        this.remoteResourceRef = resource;
     }
 
     public boolean isObserved() {
@@ -197,50 +138,13 @@ public class RemoteResource {
         this.observed = observed;
     }
 
-    public List<PutPostAttributeModel> getPutPostModel() {
-        Map<String, RemoteResourceAttribute> attMap = getResourceAttributesMap();
-        if (null == attMap || attMap.size() < 1) {
-            return null;
-        }
-        List<PutPostAttributeModel> putPostModelList = new ArrayList<PutPostAttributeModel>();
-        String attName;
-        RemoteResourceAttribute attribute;
-        PutPostAttributeModel putPostModel;
-        Iterator<String> attItr = attMap.keySet().iterator();
-        while (attItr.hasNext()) {
-            attName = attItr.next();
-            attribute = attMap.get(attName);
-            putPostModel = PutPostAttributeModel.getModel(attribute);
-            if (null != putPostModel) {
-                putPostModelList.add(putPostModel);
-            }
-        }
-        return putPostModelList;
-    }
-
-    public String getAttributeValue(String attName) {
-        RemoteResourceAttribute attribute = resourceAttributesMap.get(attName);
-        if (null == attribute) {
-            return null;
-        }
-        return String.valueOf(attribute.getAttributeValue());
-    }
-
-    public String getuId() {
-        return uId;
-    }
-
-    public void setuId(String uId) {
-        this.uId = uId;
-    }
-
-    public int getAutomationtype(int autoId) {
+    public RequestType getAutomationtype(int autoId) {
         if (getAutomtnId == autoId) {
-            return Constants.GET_AUTOMATION_INDEX;
+            return RequestType.GET;
         } else if (putAutomtnId == autoId) {
-            return Constants.PUT_AUTOMATION_INDEX;
-        } else {// if(postAutomtnId == autoId) {
-            return Constants.POST_AUTOMATION_INDEX;
+            return RequestType.PUT;
+        } else {
+            return RequestType.POST;
         }
     }
 
@@ -249,7 +153,7 @@ public class RemoteResource {
             getAutomtnInProgress = status;
         } else if (putAutomtnId == autoId) {
             putAutomtnInProgress = status;
-        } else {// if(postAutomtnId == autoId) {
+        } else {
             postAutomtnInProgress = status;
         }
     }
@@ -261,4 +165,12 @@ public class RemoteResource {
     public void setFavorite(boolean isFavorite) {
         this.isFavorite = isFavorite;
     }
+
+    public void setResourceRepresentation(SimulatorResourceModel resModel) {
+        mResourceRepresentation = new ResourceRepresentation(resModel);
+    }
+
+    public ResourceRepresentation getResourceRepresentation() {
+        return mResourceRepresentation;
+    }
 }
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/RemoteResourceAttribute.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/RemoteResourceAttribute.java
deleted file mode 100644 (file)
index 27cbdc8..0000000
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * 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.
- */
-
-package oic.simulator.clientcontroller.remoteresource;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.oic.simulator.ResourceAttribute;
-import org.oic.simulator.ResourceAttribute.Type;
-
-/**
- * This class represents an attribute in the remote resource.
- */
-public class RemoteResourceAttribute {
-
-    // Native object reference
-    private ResourceAttribute resourceAttribute;
-
-    private String            attributeName;
-    private Object            attributeValue;
-    private Type              attValType;
-    private Type              attValBaseType;
-    private List<Object>      allowedValues;
-
-    private Object            minValue;
-    private Object            maxValue;
-
-    public ResourceAttribute getResourceAttribute() {
-        return resourceAttribute;
-    }
-
-    public void setResourceAttribute(ResourceAttribute resourceAttribute) {
-        this.resourceAttribute = resourceAttribute;
-    }
-
-    public String getAttributeName() {
-        return attributeName;
-    }
-
-    public void setAttributeName(String attributeName) {
-        this.attributeName = attributeName;
-    }
-
-    public Object getAttributeValue() {
-        return attributeValue;
-    }
-
-    public void setAttributeValue(Object attributeValue) {
-        this.attributeValue = attributeValue;
-    }
-
-    public List<Object> getAllowedValues() {
-        return allowedValues;
-    }
-
-    public void setAllowedValues(List<Object> allowedValues) {
-        this.allowedValues = allowedValues;
-    }
-
-    public void setAllowedValues(String[] allowedValues) {
-        List<Object> allowedValueList = null;
-        if (null != allowedValues && allowedValues.length > 0) {
-            allowedValueList = new ArrayList<Object>();
-            for (String value : allowedValues) {
-                allowedValueList.add(value);
-            }
-        }
-        this.allowedValues = allowedValueList;
-    }
-
-    public Object getMinValue() {
-        return minValue;
-    }
-
-    public void setMinValue(Object minValue) {
-        this.minValue = minValue;
-    }
-
-    public Object getMaxValue() {
-        return maxValue;
-    }
-
-    public void setMaxValue(Object maxValue) {
-        this.maxValue = maxValue;
-    }
-
-    public static RemoteResourceAttribute clone(
-            RemoteResourceAttribute attribute) {
-        RemoteResourceAttribute clone = null;
-        if (null != attribute) {
-            clone = new RemoteResourceAttribute();
-            clone.setAttributeName(attribute.getAttributeName());
-            clone.setAttributeValue(attribute.getAttributeValue());
-            clone.setAllowedValues(attribute.getAllowedValues());
-            clone.setAttValBaseType(attribute.getAttValBaseType());
-            clone.setAttValType(attribute.getAttValType());
-            clone.setMinValue(attribute.getMinValue());
-            clone.setMaxValue(attribute.getMaxValue());
-            clone.setResourceAttribute(null);
-        }
-        return clone;
-    }
-
-    // This method gives all known possible values of the attribute in string
-    // format.
-    // It takes allowed values or range of values whichever is available
-    public List<String> getAllValues() {
-        List<String> valueList = new ArrayList<String>();
-        if (null != allowedValues) {
-            Iterator<Object> values = allowedValues.iterator();
-            Object value;
-            while (values.hasNext()) {
-                value = values.next();
-                if (null != value) {
-                    valueList.add(String.valueOf(value));
-                }
-            }
-        } else if (null != minValue && null != maxValue) {
-            if (attributeValue.getClass() == Integer.class) {
-                int min = (Integer) minValue;
-                int max = (Integer) maxValue;
-                for (int value = min; value <= max; value++) {
-                    valueList.add(String.valueOf(value));
-                }
-            } else if (attributeValue.getClass() == Double.class) {
-                double min = (Double) minValue;
-                double max = (Double) maxValue;
-                for (double value = min; value <= max; value++) {
-                    valueList.add(String.valueOf(value));
-                }
-            }
-        }
-        if (valueList.size() < 1 && null != attributeValue) {
-            valueList.add(String.valueOf(attributeValue));
-        }
-        return valueList;
-    }
-
-    public static void printAttributes(
-            Map<String, RemoteResourceAttribute> attributeMap) {
-        Iterator<String> itr = attributeMap.keySet().iterator();
-        String attName;
-        RemoteResourceAttribute att;
-        while (itr.hasNext()) {
-            attName = itr.next();
-            att = attributeMap.get(attName);
-            System.out.println("AttributeName:" + attName);
-            System.out.println("AttributeValue:"
-                    + att.getAttributeValue().toString());
-            System.out.println("Allowed Values:" + att.getAllValues());
-        }
-    }
-
-    public Type getAttValType() {
-        return attValType;
-    }
-
-    public void setAttValType(Type attValType) {
-        this.attValType = attValType;
-    }
-
-    public Type getAttValBaseType() {
-        return attValBaseType;
-    }
-
-    public void setAttValBaseType(Type attValBaseType) {
-        this.attValBaseType = attValBaseType;
-    }
-}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/ResourceRepresentation.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/ResourceRepresentation.java
new file mode 100644 (file)
index 0000000..00f76d8
--- /dev/null
@@ -0,0 +1,147 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.clientcontroller.remoteresource;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.InvalidArgsException;
+import org.oic.simulator.ModelProperty;
+import org.oic.simulator.SimulatorResourceAttribute;
+import org.oic.simulator.SimulatorResourceModel;
+import org.oic.simulator.client.SimulatorRequestModel;
+
+public class ResourceRepresentation {
+    private Map<String, AttributeElement> mAttributes = new HashMap<String, AttributeElement>();
+
+    public ResourceRepresentation(SimulatorResourceModel resourceModel) {
+        if (resourceModel != null && resourceModel.size() > 0) {
+            for (Map.Entry<String, AttributeValue> entry : resourceModel.get()
+                    .entrySet())
+                if (isCoreAttribute(entry.getKey())) {
+                    mAttributes.put(entry.getKey(), new AttributeElement(this,
+                            new SimulatorResourceAttribute(entry.getKey(),
+                                    entry.getValue())));
+                }
+        }
+    }
+
+    public ResourceRepresentation(
+            Map<String, SimulatorResourceAttribute> attributes,
+            boolean onlyCoreAttributes) {
+        if (attributes != null && attributes.size() > 0) {
+            for (Map.Entry<String, SimulatorResourceAttribute> entry : attributes
+                    .entrySet()) {
+                if (onlyCoreAttributes && !isCoreAttribute(entry.getKey())) {
+                    // Skip this attribute.
+                    continue;
+                }
+
+                mAttributes.put(entry.getKey(), new AttributeElement(this,
+                        entry.getValue()));
+            }
+        }
+    }
+
+    private boolean isCoreAttribute(String attName) {
+        if (null == attName || attName.isEmpty()) {
+            return false;
+        }
+
+        if (attName.equalsIgnoreCase("if") || attName.equalsIgnoreCase("rt")
+                || attName.equalsIgnoreCase("p")
+                || attName.equalsIgnoreCase("n")
+                || attName.equalsIgnoreCase("id")) {
+            return false;
+        }
+
+        return true;
+    }
+
+    public Map<String, AttributeElement> getAttributes() {
+        return mAttributes;
+    }
+
+    public boolean updateAttributeProperties(
+            SimulatorRequestModel requestModel,
+            SimulatorResourceModel resourceModelRef)
+            throws NullPointerException {
+        if (null == requestModel || null == resourceModelRef) {
+            return false;
+        }
+
+        ModelProperty modelProp = requestModel.getRequestBodyModel();
+        if (null == modelProp) {
+            return false;
+        }
+
+        for (Map.Entry<String, AttributeValue> entry : resourceModelRef.get()
+                .entrySet()) {
+            if (isCoreAttribute(entry.getKey())) {
+                AttributeElement attributeElement = mAttributes.get(entry
+                        .getKey());
+                if (attributeElement != null) {
+                    attributeElement
+                            .setAttributeProperty(new SimulatorResourceAttribute(
+                                    entry.getKey(), entry.getValue(), modelProp
+                                            .get(entry.getKey())));
+                }
+            }
+        }
+
+        return true;
+    }
+
+    public SimulatorResourceModel getModel() {
+        if (null == mAttributes || mAttributes.isEmpty()) {
+            return null;
+        }
+        SimulatorResourceModel model = new SimulatorResourceModel();
+        for (Map.Entry<String, AttributeElement> entry : mAttributes.entrySet()) {
+            AttributeElement attributeElement = mAttributes.get(entry.getKey());
+            if (attributeElement != null) {
+                try {
+                    model.set(entry.getKey(), attributeElement
+                            .getSimulatorResourceAttribute().value());
+                } catch (InvalidArgsException e) {
+                    e.printStackTrace();
+                }
+            }
+        }
+        return model;
+    }
+
+    public SimulatorResourceModel getSelectedModel() {
+        if (null == mAttributes || mAttributes.isEmpty()) {
+            return null;
+        }
+        SimulatorResourceModel model = new SimulatorResourceModel();
+        for (Map.Entry<String, AttributeElement> entry : mAttributes.entrySet()) {
+            AttributeElement attributeElement = mAttributes.get(entry.getKey());
+            if (attributeElement != null && attributeElement.getPostState()) {
+                try {
+                    model.set(entry.getKey(), attributeElement
+                            .getSimulatorResourceAttribute().value());
+                } catch (InvalidArgsException e) {
+                    e.printStackTrace();
+                }
+            }
+        }
+        return model;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/SerializedClientController.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/SerializedClientController.java
new file mode 100644 (file)
index 0000000..51136a0
--- /dev/null
@@ -0,0 +1,86 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.clientcontroller.remoteresource;
+
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+import java.util.List;
+
+public class SerializedClientController implements Serializable {
+
+    public List<String> getResourceTypes() {
+        return m_resourceTypes;
+    }
+
+    public void setResourceTypes(List<String> resourceTypes) {
+        this.m_resourceTypes = resourceTypes;
+    }
+
+    public List<String> getFavorites() {
+        return m_favorites;
+    }
+
+    public void setFavorites(List<String> favorites) {
+        this.m_favorites = favorites;
+    }
+
+    public void serialize(String filePath) throws FileNotFoundException,
+            IOException {
+        FileOutputStream fileOut = null;
+        ObjectOutputStream out = null;
+        try {
+            fileOut = new FileOutputStream(filePath);
+            out = new ObjectOutputStream(fileOut);
+            out.writeObject(this);
+        } finally {
+            if (null != fileOut)
+                fileOut.close();
+
+            if (null != out)
+                out.close();
+        }
+    }
+
+    public static SerializedClientController deSerialize(String filePath)
+            throws FileNotFoundException, IOException, ClassNotFoundException {
+        FileInputStream fileIn = null;
+        ObjectInputStream in = null;
+        SerializedClientController r = null;
+        try {
+            fileIn = new FileInputStream(filePath);
+            in = new ObjectInputStream(fileIn);
+            r = (SerializedClientController) in.readObject();
+        } finally {
+            if (null != fileIn)
+                fileIn.close();
+
+            if (null != in)
+                in.close();
+        }
+
+        return r;
+    }
+
+    private List<String> m_resourceTypes;
+    private List<String> m_favorites;
+
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/utils/AttributeValueBuilder.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/utils/AttributeValueBuilder.java
new file mode 100644 (file)
index 0000000..7816faa
--- /dev/null
@@ -0,0 +1,349 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.clientcontroller.utils;
+
+import java.util.Vector;
+
+import org.oic.simulator.AttributeValue;
+
+public class AttributeValueBuilder {
+    public static AttributeValue build(String valueString,
+            AttributeValue.ValueType valueType) throws NullPointerException {
+        int depth = findDepth(valueString);
+        if (0 == depth) {
+            return handleDepth0(valueString, valueType);
+        } else if (1 == depth) {
+            return handleDepth1(valueString, valueType);
+        } else if (2 == depth) {
+            return handleDepth2(valueString, valueType);
+        } else if (3 == depth) {
+            return handleDepth3(valueString, valueType);
+        }
+
+        return null;
+    }
+
+    private static int findDepth(String value) {
+        int depth = 0;
+        for (char ch : value.toCharArray()) {
+            if (ch == '[')
+                depth++;
+            else
+                break;
+        }
+
+        return depth;
+    }
+
+    private static boolean isValidSyntax(String value) {
+        int count = 0;
+        for (char ch : value.toCharArray()) {
+            if (ch == '[')
+                count++;
+            if (ch == ']')
+                count--;
+        }
+
+        if (count == 0)
+            return true;
+        return false;
+
+    }
+
+    private static AttributeValue handleDepth0(String valueString,
+            AttributeValue.ValueType valueType) {
+        valueString = valueString.trim();
+        if (0 != findDepth(valueString))
+            return null;
+
+        try {
+            if (valueType == AttributeValue.ValueType.INTEGER)
+                return new AttributeValue(Integer.parseInt(valueString));
+            else if (valueType == AttributeValue.ValueType.DOUBLE) {
+                Double value = Double.parseDouble(valueString);
+                if (!value.isInfinite()) {
+                    return new AttributeValue(value);
+                }
+            } else if (valueType == AttributeValue.ValueType.BOOLEAN) {
+                if (valueString.equalsIgnoreCase("true")
+                        || valueString.equalsIgnoreCase("false"))
+                    return new AttributeValue(Boolean.parseBoolean(valueString));
+            } else if (valueType == AttributeValue.ValueType.STRING)
+                return new AttributeValue(valueString);
+        } catch (Exception e) {
+            return null;
+        }
+        return null;
+    }
+
+    private static String[] splitIntoArrays(String valueString) {
+        Vector<String> values = new Vector<String>();
+        valueString = valueString.substring(valueString.indexOf('[') + 1,
+                valueString.lastIndexOf(']'));
+
+        int count = 0;
+        int startPos = 0;
+        char[] charArray = valueString.toCharArray();
+        for (int index = 0; index < charArray.length; index++) {
+            if (charArray[index] == '[' && 0 == count++) {
+                startPos = index;
+            }
+
+            if (charArray[index] == ']' && 0 == --count) {
+                values.add(valueString.substring(startPos, index + 1));
+            }
+        }
+
+        String[] result = new String[values.size()];
+        values.toArray(result);
+        return result;
+    }
+
+    private static AttributeValue handleDepth1(String valueString,
+            AttributeValue.ValueType valueType) {
+        valueString = valueString.trim();
+        if (1 != findDepth(valueString) || false == isValidSyntax(valueString))
+            return null;
+
+        valueString = valueString.substring(valueString.indexOf('[') + 1,
+                valueString.lastIndexOf(']'));
+        String[] valuesString = valueString.split(",");
+        if (null == valuesString || 0 == valuesString.length)
+            return null;
+
+        if (valueType == AttributeValue.ValueType.INTEGER) {
+            if (1 == valuesString.length && valuesString[0].isEmpty()) {
+                return new AttributeValue(new Integer[0]);
+            }
+
+            Integer[] result = new Integer[valuesString.length];
+            for (int index = 0; index < valuesString.length; index++) {
+                if (null != valuesString[index]
+                        && !valuesString[index].isEmpty()) {
+                    AttributeValue attValue = handleDepth0(valuesString[index],
+                            valueType);
+                    if (null == attValue)
+                        return null;
+
+                    Integer value = (Integer) attValue.get();
+                    if (null == value)
+                        return null;
+                    result[index] = value;
+                }
+            }
+            return new AttributeValue(result);
+        } else if (valueType == AttributeValue.ValueType.DOUBLE) {
+            if (1 == valuesString.length && valuesString[0].isEmpty()) {
+                return new AttributeValue(new Double[0]);
+            }
+
+            Double[] result = new Double[valuesString.length];
+            for (int index = 0; index < valuesString.length; index++) {
+                if (null != valuesString[index]
+                        && !valuesString[index].isEmpty()) {
+                    AttributeValue attValue = handleDepth0(valuesString[index],
+                            valueType);
+                    if (null == attValue)
+                        return null;
+
+                    Double value = (Double) attValue.get();
+                    if (null == value)
+                        return null;
+                    result[index] = value;
+                }
+            }
+            return new AttributeValue(result);
+        } else if (valueType == AttributeValue.ValueType.BOOLEAN) {
+            if (1 == valuesString.length && valuesString[0].isEmpty()) {
+                return new AttributeValue(new Boolean[0]);
+            }
+
+            Boolean[] result = new Boolean[valuesString.length];
+            for (int index = 0; index < valuesString.length; index++) {
+                if (null != valuesString[index]
+                        && !valuesString[index].isEmpty()) {
+                    AttributeValue attValue = handleDepth0(valuesString[index],
+                            valueType);
+                    if (null == attValue)
+                        return null;
+
+                    Boolean value = (Boolean) attValue.get();
+                    if (null == value)
+                        return null;
+                    result[index] = value;
+                }
+            }
+            return new AttributeValue(result);
+        } else if (valueType == AttributeValue.ValueType.STRING) {
+            if (1 == valuesString.length && valuesString[0].isEmpty()) {
+                return new AttributeValue(new String[0]);
+            }
+
+            for (int index = 0; index < valuesString.length; index++) {
+                if (null != valuesString[index]
+                        && !valuesString[index].isEmpty()) {
+                    valuesString[index] = valuesString[index].trim();
+                }
+            }
+            return new AttributeValue(valuesString);
+        }
+
+        return null;
+    }
+
+    private static AttributeValue handleDepth2(String valueString,
+            AttributeValue.ValueType valueType) {
+        valueString = valueString.trim();
+        if (2 != findDepth(valueString) || false == isValidSyntax(valueString))
+            return null;
+
+        String[] valuesString = splitIntoArrays(valueString);
+        if (null == valuesString || 0 == valuesString.length)
+            return null;
+
+        if (valueType == AttributeValue.ValueType.INTEGER) {
+            Integer[][] result = new Integer[valuesString.length][];
+            for (int index = 0; index < valuesString.length; index++) {
+                AttributeValue attValue = handleDepth1(valuesString[index],
+                        valueType);
+                if (null == attValue)
+                    return null;
+
+                Integer[] value = (Integer[]) attValue.get();
+                if (null == value)
+                    return null;
+                result[index] = value;
+            }
+            return new AttributeValue(result);
+        } else if (valueType == AttributeValue.ValueType.DOUBLE) {
+            Double[][] result = new Double[valuesString.length][];
+            for (int index = 0; index < valuesString.length; index++) {
+                AttributeValue attValue = handleDepth1(valuesString[index],
+                        valueType);
+                if (null == attValue)
+                    return null;
+
+                Double[] value = (Double[]) attValue.get();
+                if (null == value)
+                    return null;
+                result[index] = value;
+            }
+            return new AttributeValue(result);
+        } else if (valueType == AttributeValue.ValueType.BOOLEAN) {
+            Boolean[][] result = new Boolean[valuesString.length][];
+            for (int index = 0; index < valuesString.length; index++) {
+                AttributeValue attValue = handleDepth1(valuesString[index],
+                        valueType);
+                if (null == attValue)
+                    return null;
+
+                Boolean[] value = (Boolean[]) attValue.get();
+                if (null == value)
+                    return null;
+                result[index] = value;
+            }
+            return new AttributeValue(result);
+        } else if (valueType == AttributeValue.ValueType.STRING) {
+            String[][] result = new String[valuesString.length][];
+            for (int index = 0; index < valuesString.length; index++) {
+                AttributeValue attValue = handleDepth1(valuesString[index],
+                        valueType);
+                if (null == attValue)
+                    return null;
+
+                String[] value = (String[]) attValue.get();
+                if (null == value)
+                    return null;
+                result[index] = value;
+            }
+            return new AttributeValue(result);
+        }
+
+        return null;
+    }
+
+    public static AttributeValue handleDepth3(String valueString,
+            AttributeValue.ValueType valueType) {
+        valueString = valueString.trim();
+        if (3 != findDepth(valueString) || false == isValidSyntax(valueString))
+            return null;
+
+        String[] valuesString = splitIntoArrays(valueString);
+        if (null == valuesString || 0 == valuesString.length)
+            return null;
+
+        if (valueType == AttributeValue.ValueType.INTEGER) {
+            Integer[][][] result = new Integer[valuesString.length][][];
+            for (int index = 0; index < valuesString.length; index++) {
+                AttributeValue attValue = handleDepth2(valuesString[index],
+                        valueType);
+                if (null == attValue)
+                    return null;
+
+                Integer[][] value = (Integer[][]) attValue.get();
+                if (null == value)
+                    return null;
+                result[index] = value;
+            }
+            return new AttributeValue(result);
+        } else if (valueType == AttributeValue.ValueType.DOUBLE) {
+            Double[][][] result = new Double[valuesString.length][][];
+            for (int index = 0; index < valuesString.length; index++) {
+                AttributeValue attValue = handleDepth2(valuesString[index],
+                        valueType);
+                if (null == attValue)
+                    return null;
+
+                Double[][] value = (Double[][]) attValue.get();
+                if (null == value)
+                    return null;
+                result[index] = value;
+            }
+            return new AttributeValue(result);
+        } else if (valueType == AttributeValue.ValueType.BOOLEAN) {
+            Boolean[][][] result = new Boolean[valuesString.length][][];
+            for (int index = 0; index < valuesString.length; index++) {
+                AttributeValue attValue = handleDepth2(valuesString[index],
+                        valueType);
+                if (null == attValue)
+                    return null;
+
+                Boolean[][] value = (Boolean[][]) attValue.get();
+                if (null == value)
+                    return null;
+                result[index] = value;
+            }
+            return new AttributeValue(result);
+        } else if (valueType == AttributeValue.ValueType.STRING) {
+            String[][][] result = new String[valuesString.length][][];
+            for (int index = 0; index < valuesString.length; index++) {
+                AttributeValue attValue = handleDepth2(valuesString[index],
+                        valueType);
+                if (null == attValue)
+                    return null;
+
+                String[][] value = (String[][]) attValue.get();
+                if (null == value)
+                    return null;
+                result[index] = value;
+            }
+            return new AttributeValue(result);
+        }
+
+        return null;
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/utils/AttributeValueStringConverter.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/utils/AttributeValueStringConverter.java
new file mode 100644 (file)
index 0000000..78e0e81
--- /dev/null
@@ -0,0 +1,341 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.clientcontroller.utils;
+
+import java.util.Map;
+
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.AttributeValueVisitor;
+import org.oic.simulator.SimulatorResourceModel;
+
+public class AttributeValueStringConverter implements
+        AttributeValueVisitor.VisitingMethods<String> {
+
+    private AttributeValue mValue;
+
+    public AttributeValueStringConverter(AttributeValue value) {
+        mValue = value;
+    }
+
+    @Override
+    public String toString() {
+        AttributeValueVisitor visitor = new AttributeValueVisitor(mValue, this);
+        return (String) visitor.visit();
+    }
+
+    @Override
+    public String visitingValue(Integer value) {
+        return value.toString();
+    }
+
+    @Override
+    public String visitingValue(Double value) {
+        return value.toString();
+    }
+
+    @Override
+    public String visitingValue(Boolean value) {
+        return value.toString();
+    }
+
+    @Override
+    public String visitingValue(String value) {
+        return value;
+    }
+
+    @Override
+    public String visitingValue(SimulatorResourceModel value) {
+        StringBuilder result = new StringBuilder();
+        result.append("{");
+        boolean first = true;
+        for (Map.Entry<String, AttributeValue> entry : value.get().entrySet()) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            result.append("\"" + entry.getKey() + "\":");
+            AttributeValue attributeValue = entry.getValue();
+            result.append(new AttributeValueStringConverter(attributeValue)
+                    .toString());
+        }
+
+        result.append("}");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(Integer[] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (Integer value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            result.append(value.toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(Double[] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (Double value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            result.append(value.toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(Boolean[] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (Boolean value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            result.append(value.toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(String[] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (String value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            result.append(value);
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(SimulatorResourceModel[] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (SimulatorResourceModel value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            AttributeValue attributeValue = new AttributeValue(value);
+            result.append(new AttributeValueStringConverter(attributeValue)
+                    .toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(Integer[][] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (Integer[] value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            AttributeValue attributeValue = new AttributeValue(value);
+            result.append(new AttributeValueStringConverter(attributeValue)
+                    .toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(Double[][] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (Double[] value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            AttributeValue attributeValue = new AttributeValue(value);
+            result.append(new AttributeValueStringConverter(attributeValue)
+                    .toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(Boolean[][] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (Boolean[] value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            AttributeValue attributeValue = new AttributeValue(value);
+            result.append(new AttributeValueStringConverter(attributeValue)
+                    .toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(String[][] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (String[] value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            AttributeValue attributeValue = new AttributeValue(value);
+            result.append(new AttributeValueStringConverter(attributeValue)
+                    .toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(SimulatorResourceModel[][] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (SimulatorResourceModel[] value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            AttributeValue attributeValue = new AttributeValue(value);
+            result.append(new AttributeValueStringConverter(attributeValue)
+                    .toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(Integer[][][] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (Integer[][] value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            AttributeValue attributeValue = new AttributeValue(value);
+            result.append(new AttributeValueStringConverter(attributeValue)
+                    .toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(Double[][][] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (Double[][] value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            AttributeValue attributeValue = new AttributeValue(value);
+            result.append(new AttributeValueStringConverter(attributeValue)
+                    .toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(Boolean[][][] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (Boolean[][] value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            AttributeValue attributeValue = new AttributeValue(value);
+            result.append(new AttributeValueStringConverter(attributeValue)
+                    .toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(String[][][] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (String[][] value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            AttributeValue attributeValue = new AttributeValue(value);
+            result.append(new AttributeValueStringConverter(attributeValue)
+                    .toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(SimulatorResourceModel[][][] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (SimulatorResourceModel[][] value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            AttributeValue attributeValue = new AttributeValue(value);
+            result.append(new AttributeValueStringConverter(attributeValue)
+                    .toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+}
index 3fe81ac..a23926e 100644 (file)
 
 package oic.simulator.clientcontroller.utils;
 
-import org.oic.simulator.serviceprovider.AutomationType;
-
 /**
  * This class maintains all constants which are used throughout the client
  * controller plug-in.
  */
 public class Constants {
-    public static final String         FIND_PAGE_TITLE               = "Find Resources";
-
-    public static final String         FIND_PAGE_MESSAGE             = "Select the resource type of the resources to be discovered";
-
-    public static final int            FIND_RESOURCES_TIMEOUT        = 10;
-
-    public static final String         RESOURCE_URI                  = "Resource URI";
-    public static final String         CONNECTIVITY_TYPE             = "Connectivity Type";
-    public static final String         OBSERVABLE                    = "Observable";
-    public static final String         RESOURCE_TYPES                = "Resource Types";
-    public static final String         RESOURCE_INTERFACES           = "Resource Interfaces";
-
-    public static final String[]       META_PROPERTIES               = {
-            RESOURCE_URI, CONNECTIVITY_TYPE, OBSERVABLE, RESOURCE_TYPES,
-            RESOURCE_INTERFACES                                     };
-
-    public static final int            META_PROPERTY_COUNT           = META_PROPERTIES.length;
-
-    public static final AutomationType DEFAULT_AUTOMATION_TYPE       = AutomationType.NORMAL;
-
-    public static final int            DEFAULT_AUTOMATION_INTERVAL   = 500;
-
-    public static final String         YES                           = "Yes";
-    public static final String         NO                            = "No";
-
-    public static final String         GET                           = "Get";
-    public static final String         PUT                           = "Put";
-    public static final String         POST                          = "Post";
-
-    public static final String         ENABLE                        = "Enable";
-    public static final String         DISABLE                       = "Disable";
-    public static final String         ENABLED                       = "Enabled";
-    public static final String         DISABLED                      = "Disabled";
-
-    public static final String         NOT_AVAILABLE                 = "Not Available";
-
-    public static final int            PROPER_LOG_TIME_TOKEN_LENGTH  = 3;
-
-    public static final int            LOG_SIZE                      = 1000;
-
-    public static final String         INFO_LOG                      = "info_log";
-    public static final String         WARNING_LOG                   = "warning_log";
-    public static final String         ERROR_LOG                     = "error_log";
-    public static final String         DEBUG_LOG                     = "debug_log";
-    public static final String         UNKNOWN_LOG                   = "unknown_log";
-
-    public static final String         CHECKED                       = "Checked";
-    public static final String         UNCHECKED                     = "Unchecked";
-
-    public static final String         INFO                          = "Info";
-    public static final String         WARNING                       = "Warning";
-    public static final String         ERROR                         = "Error";
-    public static final String         DEBUG                         = "Debug";
-    public static final String         UNKNOWN                       = "Unknown";
-
-    public static final String[]       BROWSE_RAML_FILTER_EXTENSIONS = new String[] {
-            "*.raml", "*"                                           };
-    public static final String[]       SAVE_LOG_FILTER_EXTENSIONS    = new String[] {
-            "*.log", "*"                                            };
-
-    public static final int            GET_AUTOMATION_INDEX          = 0;
-    public static final int            PUT_AUTOMATION_INDEX          = 1;
-    public static final int            POST_AUTOMATION_INDEX         = 2;
-    public static final int            DELETE_AUTOMATION_INDEX       = 3;
-
-    public static final String         OIC_R_LIGHT                   = "oic.r.light";
+    public static final String   FIND_PAGE_TITLE               = "Find Resources";
+
+    public static final String   FIND_PAGE_MESSAGE             = "Select the resource type of the resources to be discovered";
+
+    public static final int      FIND_RESOURCES_TIMEOUT        = 10;
+
+    public static final String   RESOURCE_URI                  = "Resource URI";
+    public static final String   ADDRESS                       = "Address";
+    public static final String   CONNECTIVITY_TYPE             = "Connectivity Type";
+    public static final String   OBSERVABLE                    = "Observable";
+    public static final String   RESOURCE_TYPES                = "Resource Types";
+    public static final String   RESOURCE_INTERFACES           = "Resource Interfaces";
+
+    public static final String[] META_PROPERTIES               = {
+            RESOURCE_URI, ADDRESS, CONNECTIVITY_TYPE, OBSERVABLE,
+            RESOURCE_TYPES, RESOURCE_INTERFACES               };
+
+    public static final int      META_PROPERTY_COUNT           = META_PROPERTIES.length;
+
+    public static final String   YES                           = "Yes";
+    public static final String   NO                            = "No";
+
+    public static final String   GET                           = "Get";
+    public static final String   PUT                           = "Put";
+    public static final String   POST                          = "Post";
+    public static final String   OBSERVE                       = "Observe";
+    public static final String   STOP_OBSERVE                  = "Stop Observe";
+
+    public static final String   ENABLE                        = "Enable";
+    public static final String   DISABLE                       = "Disable";
+    public static final String   ENABLED                       = "Enabled";
+    public static final String   DISABLED                      = "Disabled";
+
+    public static final String   NOT_AVAILABLE                 = "Not Available";
+
+    public static final int      PROPER_LOG_TIME_TOKEN_LENGTH  = 3;
+
+    public static final int      LOG_SIZE                      = 1000;
+
+    public static final String   INFO_LOG                      = "info_log";
+    public static final String   WARNING_LOG                   = "warning_log";
+    public static final String   ERROR_LOG                     = "error_log";
+    public static final String   DEBUG_LOG                     = "debug_log";
+    public static final String   UNKNOWN_LOG                   = "unknown_log";
+
+    public static final String   CHECKED                       = "Checked";
+    public static final String   UNCHECKED                     = "Unchecked";
+
+    public static final String   INFO                          = "Info";
+    public static final String   WARNING                       = "Warning";
+    public static final String   ERROR                         = "Error";
+    public static final String   DEBUG                         = "Debug";
+    public static final String   UNKNOWN                       = "Unknown";
+
+    public static final String[] BROWSE_RAML_FILTER_EXTENSIONS = new String[] { "*.raml" };
+    public static final String[] SAVE_LOG_FILTER_EXTENSIONS    = new String[] {
+            "*.log", "*"                                      };
+
+    public static final int      GET_AUTOMATION_INDEX          = 0;
+    public static final int      PUT_AUTOMATION_INDEX          = 1;
+    public static final int      POST_AUTOMATION_INDEX         = 2;
+    public static final int      DELETE_AUTOMATION_INDEX       = 3;
+
+    // Device information
+    public static final String   DEVICE_NAME                   = "Name";
+    public static final String   DEVICE_ID                     = "Id";
+    public static final String   DEVICE_SPEC_VERSION           = "Spec Version";
+    public static final String   DEVICE_DMV_VERSION            = "DMV Version";
+
+    // Platform information
+    public static final String   PLATFORM_ID                   = "Id";
+    public static final String   PLATFORM_MANUFAC_NAME         = "Manufacturer Name";
+    public static final String   PLATFORM_MANUFAC_URL          = "Manufacturer URL";
+    public static final String   PLATFORM_MODEL_NO             = "Model Number";
+    public static final String   PLATFORM_DATE_OF_MANUFAC      = "Date of Manufacture";
+    public static final String   PLATFORM_VERSION              = "Version";
+    public static final String   PLATFORM_OS_VERSION           = "OS Version";
+    public static final String   PLATFORM_HARDWARE_VERSION     = "HardWare Version";
+    public static final String   PLATFORM_FIRMWARE_VERSION     = "Firmware Version";
+    public static final String   PLATFORM_SUPPORT_URL          = "Support URL";
+    public static final String   PLATFORM_SYSTEM_TIME          = "System Time";
+
+    public static final String   BASELINE_INTERFACE            = "oic.if.baseline";
+    public static final String   LINKS_LIST_INTERFACE          = "oic.if.ll";
+    public static final String   BATCH_INTERFACE               = "oic.if.b";
+    public static final String   LINK_BATCH_INTERFACE          = "oic.if.lb";
+    public static final String   READ_ONLY_INTERFACE           = "oic.if.r";
+    public static final String   READ_WRITE_INTERFACE          = "oic.if.rw";
+    public static final String   ACTUATOR_INTERFACE            = "oic.if.a";
+    public static final String   SENSOR_INTERFACE              = "oic.if.s";
 }
index 8baed7c..f3e3cdb 100644 (file)
 package oic.simulator.clientcontroller.utils;
 
 import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
+import java.util.Map;
 import java.util.Set;
 
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.AttributeValue.TypeInfo;
+import org.oic.simulator.AttributeValue.ValueType;
+import org.oic.simulator.InvalidArgsException;
+import org.oic.simulator.SimulatorException;
+import org.oic.simulator.SimulatorResourceModel;
+
+import oic.simulator.clientcontroller.remoteresource.AttributeElement;
+
 /**
  * This class has common utility methods.
  */
@@ -55,25 +68,212 @@ public class Utility {
         return strArr;
     }
 
-    /*
-     * public static List<Object> converArrayToList(int[] arr) { if(null == arr
-     * || arr.length < 1) { return null; } List<Object> valueList = new
-     * ArrayList<Object>(); for(Object val:arr) { valueList.add(val); } return
-     * valueList; }
-     * 
-     * public static List<Object> converArrayToList(double[] arr) { if(null ==
-     * arr || arr.length < 1) { return null; } List<Object> valueList = new
-     * ArrayList<Object>(); for(Object val:arr) { valueList.add(val); } return
-     * valueList; }
-     * 
-     * public static List<Object> converArrayToList(boolean[] arr) { if(null ==
-     * arr || arr.length < 1) { return null; } List<Object> valueList = new
-     * ArrayList<Object>(); for(Object val:arr) { valueList.add(val); } return
-     * valueList; }
-     * 
-     * public static List<Object> converArrayToList(String[] arr) { if(null ==
-     * arr || arr.length < 1) { return null; } List<Object> valueList = new
-     * ArrayList<Object>(); for(Object val:arr) { valueList.add(val); } return
-     * valueList; }
-     */
+    public static Set<String> splitStringByComma(String text) {
+        Set<String> tokenSet = null;
+        if (null != text) {
+            String[] token = text.split(",");
+            if (null != token) {
+                tokenSet = new HashSet<String>();
+                for (String tok : token) {
+                    tok = tok.trim();
+                    if (tok.length() > 0) {
+                        tokenSet.add(tok);
+                    }
+                }
+            }
+        }
+        return tokenSet;
+    }
+
+    public static String getSimulatorErrorString(Exception e, String info) {
+        if (null == e) {
+            return null;
+        }
+        String detail;
+        if (e instanceof SimulatorException) {
+            SimulatorException simEx = (SimulatorException) e;
+            detail = simEx.message() + "\n";
+            detail += "Exception Type: " + simEx.getClass().getSimpleName()
+                    + "\n";
+            detail += "Error code: " + simEx.code().toString();
+        } else {
+            detail = info + "\n";
+            detail += "Exception Type: " + e.getClass().getSimpleName() + "\n";
+            detail += "Message: " + e.getMessage();
+        }
+        return detail;
+    }
+
+    public static Comparator<AttributeElement> attributeComparator = new Comparator<AttributeElement>() {
+                                                                       public int compare(
+                                                                               AttributeElement att1,
+                                                                               AttributeElement att2) {
+                                                                           String s1 = att1
+                                                                                   .getSimulatorResourceAttribute()
+                                                                                   .name();
+                                                                           String s2 = att2
+                                                                                   .getSimulatorResourceAttribute()
+                                                                                   .name();
+
+                                                                           String s1Part = s1
+                                                                                   .replaceAll(
+                                                                                           "\\d",
+                                                                                           "");
+                                                                           String s2Part = s2
+                                                                                   .replaceAll(
+                                                                                           "\\d",
+                                                                                           "");
+
+                                                                           if (s1Part
+                                                                                   .equalsIgnoreCase(s2Part)) {
+                                                                               return extractInt(s1)
+                                                                                       - extractInt(s2);
+                                                                           }
+                                                                           return s1
+                                                                                   .compareTo(s2);
+                                                                       }
+
+                                                                       int extractInt(
+                                                                               String s) {
+                                                                           String num = s
+                                                                                   .replaceAll(
+                                                                                           "\\D",
+                                                                                           "");
+
+                                                                           // Return
+                                                                           // 0
+                                                                           // if
+                                                                           // no
+                                                                           // digits
+                                                                           // found
+                                                                           return num
+                                                                                   .isEmpty() ? 0
+                                                                                   : Integer
+                                                                                           .parseInt(num);
+                                                                       }
+                                                                   };
+
+    // This method only works for attributes whose values are of type int,
+    // double, bool, string and 1-D array of primitive types
+    public static String getAttributeValueAsString(AttributeValue val) {
+        if (null == val) {
+            return null;
+        }
+
+        Object value = val.get();
+        if (null == value) {
+            return null;
+        }
+
+        TypeInfo type = val.typeInfo();
+        if (type.mBaseType == ValueType.RESOURCEMODEL
+                || (type.mType == ValueType.ARRAY && type.mDepth > 1)) {
+            return null;
+        }
+
+        AttributeValueStringConverter converter = new AttributeValueStringConverter(
+                val);
+        return converter.toString();
+    }
+
+    public static Map<String, String> getResourceInterfaces() {
+        Map<String, String> ifTypes = new HashMap<String, String>();
+        ifTypes.put(Constants.BASELINE_INTERFACE, "Baseline");
+        ifTypes.put(Constants.LINKS_LIST_INTERFACE, "Links List");
+        ifTypes.put(Constants.BATCH_INTERFACE, "Batch");
+        ifTypes.put(Constants.LINK_BATCH_INTERFACE, "Link Batch");
+        ifTypes.put(Constants.READ_ONLY_INTERFACE, "Read-Only");
+        ifTypes.put(Constants.READ_WRITE_INTERFACE, "Read-Write");
+        ifTypes.put(Constants.ACTUATOR_INTERFACE, "Actuator");
+        ifTypes.put(Constants.SENSOR_INTERFACE, "Sensor");
+        return ifTypes;
+    }
+
+    public static String removeWhiteSpacesInArrayValues(String value) {
+        if (null == value || value.isEmpty())
+            return null;
+
+        value = value.trim();
+
+        String token[] = value.split(",");
+        StringBuilder result = new StringBuilder();
+        for (int i = 0; i < token.length; i++) {
+            result.append(token[i].trim());
+            if (i + 1 < token.length) {
+                result.append(",");
+            }
+        }
+
+        return result.toString();
+    }
+
+    public static AttributeValue cloneAttributeValue(AttributeValue value)
+            throws InvalidArgsException, NullPointerException {
+        AttributeValue clone = null;
+
+        AttributeValue.TypeInfo typeInfo = value.typeInfo();
+
+        if (typeInfo.mType == AttributeValue.ValueType.RESOURCEMODEL) {
+            SimulatorResourceModel resModel = (SimulatorResourceModel) value
+                    .get();
+            SimulatorResourceModel modelCopy = new SimulatorResourceModel();
+
+            for (Map.Entry<String, AttributeValue> entry : resModel.get()
+                    .entrySet()) {
+                String attName = entry.getKey();
+                AttributeValue attValue = entry.getValue();
+                modelCopy.set(attName, cloneAttributeValue(attValue));
+            }
+            clone = new AttributeValue(modelCopy);
+        } else if (typeInfo.mType == AttributeValue.ValueType.ARRAY
+                && typeInfo.mBaseType == AttributeValue.ValueType.RESOURCEMODEL) {
+            if (typeInfo.mDepth == 1) {
+                SimulatorResourceModel[] resModelArray = (SimulatorResourceModel[]) value
+                        .get();
+                SimulatorResourceModel[] modelArrayCopy = new SimulatorResourceModel[resModelArray.length];
+                for (int i = 0; i < resModelArray.length; i++) {
+                    AttributeValue attValue = cloneAttributeValue(new AttributeValue(
+                            resModelArray[i]));
+                    if (null != attValue) {
+                        modelArrayCopy[i] = (SimulatorResourceModel) attValue
+                                .get();
+                    }
+                }
+                clone = new AttributeValue(modelArrayCopy);
+            } else if (typeInfo.mDepth == 2) {
+                SimulatorResourceModel[][] resModelArray = (SimulatorResourceModel[][]) value
+                        .get();
+                SimulatorResourceModel[][] modelArrayCopy = new SimulatorResourceModel[resModelArray.length][];
+                for (int i = 0; i < resModelArray.length; i++) {
+                    AttributeValue attValue = cloneAttributeValue(new AttributeValue(
+                            resModelArray[i]));
+                    if (null != attValue) {
+                        modelArrayCopy[i] = (SimulatorResourceModel[]) attValue
+                                .get();
+                    }
+                }
+                clone = new AttributeValue(modelArrayCopy);
+            } else if (typeInfo.mDepth == 3) {
+                SimulatorResourceModel[][][] resModelArray = (SimulatorResourceModel[][][]) value
+                        .get();
+                SimulatorResourceModel[][][] modelArrayCopy = new SimulatorResourceModel[resModelArray.length][][];
+                for (int i = 0; i < resModelArray.length; i++) {
+                    AttributeValue attValue = cloneAttributeValue(new AttributeValue(
+                            resModelArray[i]));
+                    if (null != attValue) {
+                        modelArrayCopy[i] = (SimulatorResourceModel[][]) attValue
+                                .get();
+                    }
+                }
+                clone = new AttributeValue(modelArrayCopy);
+            }
+        } else {
+            String attValueInString = new AttributeValueStringConverter(value)
+                    .toString();
+            clone = AttributeValueBuilder.build(attValueInString,
+                    typeInfo.mBaseType);
+        }
+
+        return clone;
+    }
 }
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/AttributeEditingSupport.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/AttributeEditingSupport.java
new file mode 100644 (file)
index 0000000..b61469f
--- /dev/null
@@ -0,0 +1,465 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.clientcontroller.view;
+
+import org.eclipse.jface.dialogs.TitleAreaDialog;
+import org.eclipse.jface.viewers.CellEditor;
+import org.eclipse.jface.viewers.CheckboxCellEditor;
+import org.eclipse.jface.viewers.ComboBoxCellEditor;
+import org.eclipse.jface.viewers.EditingSupport;
+import org.eclipse.jface.viewers.TextCellEditor;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.jface.window.Window;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.CCombo;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.MessageBox;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeItem;
+
+import java.util.Date;
+import java.util.List;
+
+import org.oic.simulator.ArrayProperty;
+import org.oic.simulator.AttributeProperty;
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.AttributeValue.TypeInfo;
+import org.oic.simulator.AttributeValue.ValueType;
+import org.oic.simulator.ILogger.Level;
+import org.oic.simulator.InvalidArgsException;
+import org.oic.simulator.SimulatorResourceAttribute;
+
+import oic.simulator.clientcontroller.Activator;
+import oic.simulator.clientcontroller.manager.ResourceManager;
+import oic.simulator.clientcontroller.remoteresource.AttributeElement;
+import oic.simulator.clientcontroller.remoteresource.RemoteResource;
+import oic.simulator.clientcontroller.remoteresource.ResourceRepresentation;
+import oic.simulator.clientcontroller.utils.AttributeValueBuilder;
+import oic.simulator.clientcontroller.utils.Utility;
+import oic.simulator.clientcontroller.view.dialogs.PostRequestDialog;
+import oic.simulator.clientcontroller.view.dialogs.UpdatePrimitiveArrayAttributeDialog;
+
+/**
+ * This class provides editing support to the resources attributes table in the
+ * attributes view.
+ */
+public class AttributeEditingSupport {
+
+    private AttributeValueEditor attValueEditor;
+    private PostSelectionEditor  postSelectionEditor;
+
+    public AttributeValueEditor createAttributeValueEditor(TreeViewer viewer,
+            TitleAreaDialog dialog) {
+        attValueEditor = new AttributeValueEditor(viewer, dialog);
+        return attValueEditor;
+    }
+
+    public PostSelectionEditor createPostSelectionEditor(TreeViewer viewer) {
+        postSelectionEditor = new PostSelectionEditor(viewer);
+        return postSelectionEditor;
+    }
+
+    class AttributeValueEditor extends EditingSupport {
+
+        private final TreeViewer viewer;
+        private CCombo           comboBox;
+        private TitleAreaDialog  dialog;
+
+        public AttributeValueEditor(TreeViewer viewer, TitleAreaDialog dialog) {
+            super(viewer);
+            this.viewer = viewer;
+            this.dialog = dialog;
+        }
+
+        @Override
+        protected boolean canEdit(Object arg0) {
+            return true;
+        }
+
+        @Override
+        protected CellEditor getCellEditor(final Object element) {
+            ResourceManager resourceManager = Activator.getDefault()
+                    .getResourceManager();
+
+            RemoteResource res = resourceManager
+                    .getCurrentResourceInSelection();
+            if (null == res) {
+                return null;
+            }
+
+            final SimulatorResourceAttribute attribute;
+            if (!(element instanceof AttributeElement)) {
+                return null;
+            }
+
+            final AttributeElement attributeElement = ((AttributeElement) element);
+            attribute = attributeElement.getSimulatorResourceAttribute();
+            if (null == attribute) {
+                return null;
+            }
+
+            final AttributeValue val = attribute.value();
+            if (null == val) {
+                return null;
+            }
+
+            final TypeInfo type = val.typeInfo();
+            if (type.mBaseType == ValueType.RESOURCEMODEL) {
+                return null;
+            }
+
+            CellEditor editor;
+            if (type.mType == ValueType.ARRAY && res.isConfigUploaded()
+                    && isArrayAttributeValid(attribute)) {
+                editor = new TextCellEditor(viewer.getTree());
+                editor.setStyle(SWT.READ_ONLY);
+                final Text txt = (Text) editor.getControl();
+                txt.addModifyListener(new ModifyListener() {
+                    @Override
+                    public void modifyText(ModifyEvent e) {
+                        UpdatePrimitiveArrayAttributeDialog dialog = new UpdatePrimitiveArrayAttributeDialog(
+                                Display.getDefault().getActiveShell(),
+                                attribute);
+                        if (dialog.open() == Window.OK) {
+                            updateAttributeValue(attributeElement, attribute,
+                                    dialog.getNewValueObj());
+                        }
+
+                        // Update the viewer in a separate UI thread.
+                        Display.getDefault().asyncExec(new Runnable() {
+                            @Override
+                            public void run() {
+                                // Set the post state of the top-level
+                                // attribute.
+                                AttributeElement rootElement = getRootElement(attributeElement);
+                                rootElement.setPostState(true);
+                                viewer.refresh(rootElement, true);
+                            }
+                        });
+                    }
+                });
+            } else {
+                String values[] = null;
+                List<String> valueSet = resourceManager
+                        .getAllValuesOfAttribute(attribute);
+                values = convertListToStringArray(valueSet);
+
+                editor = new ComboBoxCellEditor(viewer.getTree(), values);
+                comboBox = (CCombo) editor.getControl();
+                comboBox.addModifyListener(new ModifyListener() {
+
+                    @Override
+                    public void modifyText(ModifyEvent event) {
+                        // Set the post state of the top-level attribute.
+                        AttributeElement rootElement = getRootElement(attributeElement);
+                        rootElement.setPostState(true);
+                        if (AttributeValueEditor.this.dialog instanceof PostRequestDialog) {
+                            viewer.update(rootElement, null);
+                        }
+                    }
+                });
+            }
+            return editor;
+        }
+
+        @Override
+        protected Object getValue(Object element) {
+            int indexOfItem = 0;
+            SimulatorResourceAttribute att = null;
+
+            if (element instanceof AttributeElement) {
+                att = ((AttributeElement) element)
+                        .getSimulatorResourceAttribute();
+            }
+
+            if (att == null) {
+                return 0;
+            }
+
+            final AttributeValue val = att.value();
+            if (null == val) {
+                return null;
+            }
+
+            final TypeInfo type = val.typeInfo();
+            if (type.mBaseType == ValueType.RESOURCEMODEL) {
+                return null;
+            }
+
+            String valueString = Utility.getAttributeValueAsString(att.value());
+            if (null == valueString) {
+                valueString = "";
+            }
+
+            if (type.mType == ValueType.ARRAY) {
+                ResourceManager resourceManager = Activator.getDefault()
+                        .getResourceManager();
+
+                RemoteResource res = resourceManager
+                        .getCurrentResourceInSelection();
+                if (null != res && res.isConfigUploaded()
+                        && isArrayAttributeValid(att)) {
+                    return valueString;
+                }
+            }
+
+            List<String> valueSet = Activator.getDefault().getResourceManager()
+                    .getAllValuesOfAttribute(att);
+            if (null != valueSet) {
+                indexOfItem = valueSet.indexOf(valueString);
+            }
+            if (indexOfItem == -1) {
+                indexOfItem = 0;
+            }
+            return indexOfItem;
+        }
+
+        @Override
+        protected void setValue(Object element, Object value) {
+            SimulatorResourceAttribute att = null;
+            if (element instanceof AttributeElement) {
+                att = ((AttributeElement) element)
+                        .getSimulatorResourceAttribute();
+            }
+
+            if (att == null) {
+                return;
+            }
+
+            AttributeValue val = att.value();
+            if (null == val) {
+                return;
+            }
+
+            TypeInfo type = val.typeInfo();
+
+            if (type.mBaseType == ValueType.RESOURCEMODEL) {
+                return;
+            }
+
+            if (type.mType == ValueType.ARRAY) {
+                ResourceManager resourceManager = Activator.getDefault()
+                        .getResourceManager();
+
+                RemoteResource res = resourceManager
+                        .getCurrentResourceInSelection();
+                if (null != res && res.isConfigUploaded()
+                        && isArrayAttributeValid(att)) {
+                    return;
+                }
+            }
+
+            String oldValue = String.valueOf(Utility
+                    .getAttributeValueAsString(val));
+            if (null == oldValue) {
+                oldValue = "";
+            }
+
+            String newValue = comboBox.getText();
+
+            if (type.mType == ValueType.ARRAY
+                    && type.mBaseType != ValueType.RESOURCEMODEL) {
+                newValue = Utility.removeWhiteSpacesInArrayValues(newValue);
+            }
+
+            if (!oldValue.equals(newValue)) {
+                boolean invalid = false;
+
+                // Get the AttriuteValue from the string
+                AttributeValue attValue = null;
+                try {
+                    attValue = AttributeValueBuilder.build(newValue,
+                            type.mBaseType);
+                } catch (Exception e) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(),
+                                    new Date(),
+                                    "There is an error while creating the new attribute value.\n"
+                                            + Utility.getSimulatorErrorString(
+                                                    e, null));
+                }
+                if (null == attValue) {
+                    invalid = true;
+                } else {
+                    TypeInfo resTypeInfo = attValue.typeInfo();
+                    if (type.mDepth != resTypeInfo.mDepth
+                            || type.mType != resTypeInfo.mType
+                            || type.mBaseType != resTypeInfo.mBaseType) {
+                        invalid = true;
+                    }
+                }
+                if (invalid) {
+                    MessageBox dialog = new MessageBox(viewer.getTree()
+                            .getShell(), SWT.ICON_ERROR | SWT.OK);
+                    dialog.setText("Invalid Value");
+                    dialog.setMessage("Given value is invalid");
+                    dialog.open();
+                } else {
+                    updateAttributeValue((AttributeElement) element, att,
+                            attValue);
+                }
+            }
+
+            viewer.update(element, null);
+        }
+
+        private boolean isArrayAttributeValid(
+                SimulatorResourceAttribute attribute) {
+            if (null == attribute)
+                return false;
+
+            AttributeValue val = attribute.value();
+            if (null == val)
+                return false;
+
+            AttributeProperty prop = attribute.property();
+            if (null == prop || !prop.isArray())
+                return false;
+
+            ArrayProperty arrProp = prop.asArray();
+            if (null == arrProp)
+                return false;
+
+            AttributeProperty elementProp = arrProp.getElementProperty();
+            if (null == elementProp)
+                return false;
+
+            TypeInfo info = val.typeInfo();
+            if (info.mBaseType == ValueType.RESOURCEMODEL)
+                return false;
+
+            return true;
+        }
+
+        public String[] convertListToStringArray(List<String> values) {
+            String[] strArr;
+            if (null != values && values.size() > 0) {
+                strArr = values.toArray(new String[1]);
+            } else {
+                strArr = new String[1];
+            }
+            return strArr;
+        }
+
+        public void updateAttributeValue(AttributeElement attributeElement,
+                SimulatorResourceAttribute att, AttributeValue value) {
+            // Update the post status.
+            Object parent = attributeElement.getParent();
+            AttributeElement rootElement = attributeElement;
+            while (parent != null && parent instanceof AttributeElement) {
+                rootElement = (AttributeElement) parent;
+                parent = ((AttributeElement) parent).getParent();
+            }
+            rootElement.setPostState(true);
+
+            // Set the attribute value.
+            attributeElement.getSimulatorResourceAttribute().setValue(value);
+
+            // Update the hierarchy.
+            parent = attributeElement.getParent();
+            if (null != parent && parent instanceof AttributeElement) {
+                try {
+                    ((AttributeElement) parent).deepSetChildValue(att);
+                } catch (InvalidArgsException e) {
+                    e.printStackTrace();
+                }
+            }
+        }
+    }
+
+    private static class PostSelectionEditor extends EditingSupport {
+
+        private final TreeViewer viewer;
+
+        public PostSelectionEditor(TreeViewer viewer) {
+            super(viewer);
+            this.viewer = viewer;
+        }
+
+        @Override
+        protected boolean canEdit(Object arg0) {
+            return true;
+        }
+
+        @Override
+        protected CellEditor getCellEditor(Object element) {
+            if (element instanceof AttributeElement
+                    && ((AttributeElement) element).getParent() instanceof ResourceRepresentation) {
+                return new CheckboxCellEditor(null, SWT.CHECK | SWT.READ_ONLY);
+            }
+
+            return null;
+        }
+
+        @Override
+        protected Object getValue(Object element) {
+            if (element instanceof AttributeElement) {
+                return ((AttributeElement) element).getPostState();
+            }
+
+            return false;
+        }
+
+        @Override
+        protected void setValue(Object element, Object value) {
+            if (!(element instanceof AttributeElement)) {
+                return;
+            }
+
+            boolean status = (Boolean) value;
+            ((AttributeElement) element).setPostState(status);
+            viewer.update(element, null);
+
+            Tree t = viewer.getTree();
+            TreeItem item = t.getSelection()[0];
+            if (null == item) {
+                return;
+            }
+
+            // Update the post state of the top-most parent of this attribute.
+            TreeItem parent = item.getParentItem();
+            if (null != parent) {
+                while (parent.getParentItem() != null) {
+                    parent = parent.getParentItem();
+                }
+                Object data = parent.getData();
+                ((AttributeElement) data).setPostState(status);
+            }
+        }
+    }
+
+    private AttributeElement getRootElement(AttributeElement element) {
+        AttributeElement root = null;
+
+        Object parent = element.getParent();
+        if (parent instanceof ResourceRepresentation) {
+            return element;
+        }
+
+        while (!(parent instanceof ResourceRepresentation)) {
+            root = (AttributeElement) parent;
+            parent = ((AttributeElement) parent).getParent();
+        }
+
+        return root;
+    }
+}
index 255d9f1..7f0ac99 100644 (file)
 
 package oic.simulator.clientcontroller.view;
 
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.ILabelProviderListener;
+import org.eclipse.jface.viewers.ITableLabelProvider;
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.window.Window;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeColumn;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.part.ViewPart;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
 import java.util.List;
 import java.util.Map;
 
+import org.oic.simulator.AttributeValue.ValueType;
+import org.oic.simulator.ILogger.Level;
+import org.oic.simulator.SimulatorResourceAttribute;
+import org.oic.simulator.client.SimulatorRemoteResource;
+import org.oic.simulator.client.SimulatorRemoteResource.RequestType;
+
 import oic.simulator.clientcontroller.Activator;
 import oic.simulator.clientcontroller.listener.IConfigurationUpload;
 import oic.simulator.clientcontroller.listener.IGetUIListener;
@@ -28,36 +60,17 @@ import oic.simulator.clientcontroller.listener.IPutUIListener;
 import oic.simulator.clientcontroller.listener.IResourceSelectionChangedUIListener;
 import oic.simulator.clientcontroller.listener.IVerificationUIListener;
 import oic.simulator.clientcontroller.manager.ResourceManager;
-import oic.simulator.clientcontroller.remoteresource.PutPostAttributeModel;
+import oic.simulator.clientcontroller.manager.UiListenerHandler;
+import oic.simulator.clientcontroller.remoteresource.AttributeElement;
 import oic.simulator.clientcontroller.remoteresource.RemoteResource;
-import oic.simulator.clientcontroller.remoteresource.RemoteResourceAttribute;
+import oic.simulator.clientcontroller.remoteresource.ResourceRepresentation;
 import oic.simulator.clientcontroller.utils.Constants;
+import oic.simulator.clientcontroller.utils.Utility;
+import oic.simulator.clientcontroller.view.dialogs.GetRequestDialog;
 import oic.simulator.clientcontroller.view.dialogs.PostRequestDialog;
 import oic.simulator.clientcontroller.view.dialogs.PutRequestDialog;
 import oic.simulator.clientcontroller.view.dialogs.VerificationDialog;
 
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.StyledCellLabelProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerCell;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.part.ViewPart;
-
 /**
  * This class manages and shows the attribute view in the perspective.
  */
@@ -65,7 +78,7 @@ public class AttributeView extends ViewPart {
 
     public static final String                  VIEW_ID        = "oic.simulator.clientcontroller.view.attribute";
 
-    private TableViewer                         attTblViewer;
+    private TreeViewer                          attViewer;
 
     private Button                              getButton;
     private Button                              putButton;
@@ -100,24 +113,19 @@ public class AttributeView extends ViewPart {
 
                     @Override
                     public void run() {
-                        System.out
-                                .println("AttributeView: onResourceSelectionChange");
                         resourceInSelection = resource;
 
                         // Set visibility of manual and automation controls
                         setVisibility((resource == null) ? false : true);
 
                         // Update the attribute table
-                        if (null != attTblViewer
-                                && !attTblViewer.getControl().isDisposed()) {
-                            System.out.println("viewer is alive");
-                            updateViewer(getData(resource));
+                        if (null != attViewer
+                                && !attViewer.getControl().isDisposed()) {
+                            updateViewer(resource);
                         }
 
                         // Update the observe status
                         updateObserve(resource);
-
-                        // Update the pay-load details if any
                     }
                 });
             }
@@ -131,30 +139,20 @@ public class AttributeView extends ViewPart {
 
                     @Override
                     public void run() {
-
-                        System.out.println("AttributeView: onGetCompleted");
                         if (null == resource) {
                             return;
                         }
                         // Update the attribute table
                         if (resourceInSelection != resource) {
-                            System.out
-                                    .println("AttributeView: get response arrived for a different resource");
                             return;
                         }
-                        updateViewer(getData(resource));
+                        updateViewer(resource);
 
                         // Update the observe status
                         updateObserve(resource);
-
-                        // Update the pay-load details if any
                     }
                 });
             }
-
-            @Override
-            public void onGetFailed(RemoteResource resource) {
-            }
         };
 
         putUIListener = new IPutUIListener() {
@@ -165,30 +163,20 @@ public class AttributeView extends ViewPart {
 
                     @Override
                     public void run() {
-
-                        System.out.println("AttributeView: onPutCompleted");
                         if (null == resource) {
                             return;
                         }
                         // Update the attribute table
                         if (resourceInSelection != resource) {
-                            System.out
-                                    .println("AttributeView: put response arrived for a different resource");
                             return;
                         }
-                        updateViewer(getData(resource));
+                        updateViewer(resource);
 
                         // Update the observe status
                         updateObserve(resource);
-
-                        // Update the pay-load details if any
                     }
                 });
             }
-
-            @Override
-            public void onPutFailed(RemoteResource resource) {
-            }
         };
 
         postUIListener = new IPostUIListener() {
@@ -199,30 +187,20 @@ public class AttributeView extends ViewPart {
 
                     @Override
                     public void run() {
-
-                        System.out.println("AttributeView: onPostCompleted");
                         if (null == resource) {
                             return;
                         }
                         // Update the attribute table
                         if (resourceInSelection != resource) {
-                            System.out
-                                    .println("AttributeView: post response arrived for a different resource");
                             return;
                         }
-                        updateViewer(getData(resource));
+                        updateViewer(resource);
 
                         // Update the observe status
                         updateObserve(resource);
-
-                        // Update the pay-load details if any
                     }
                 });
             }
-
-            @Override
-            public void onPostFailed(RemoteResource resource) {
-            }
         };
 
         observeUIListener = new IObserveUIListener() {
@@ -233,66 +211,88 @@ public class AttributeView extends ViewPart {
 
                     @Override
                     public void run() {
-
-                        System.out.println("AttributeView: onObserveCompleted");
                         if (null == resource) {
                             return;
                         }
                         // Update the attribute table
                         if (resourceInSelection != resource) {
-                            System.out
-                                    .println("AttributeView: observe response arrived for a different resource");
                             return;
                         }
-                        updateViewer(getData(resource));
+                        updateViewer(resource);
 
                         // Update the observe status
                         updateObserve(resource);
-
-                        // Update the pay-load details if any
                     }
                 });
             }
-
-            @Override
-            public void onObserveFailed(RemoteResource resource) {
-            }
         };
 
         verificationUIListener = new IVerificationUIListener() {
 
             @Override
             public void onVerificationStarted(final RemoteResource resource,
-                    final int autoType) {
-                Display.getDefault().asyncExec(new Runnable() {
-
-                    @Override
-                    public void run() {
-                        changeReqBtnVisibility(autoType, false);
-                    }
-                });
+                    final RequestType reqType) {
+                // Do Nothing. For Future Use.
             }
 
             @Override
             public void onVerificationCompleted(final RemoteResource resource,
-                    final int autoType) {
+                    final RequestType reqType) {
+
+                if (null == resource) {
+                    return;
+                }
+
                 Display.getDefault().asyncExec(new Runnable() {
 
                     @Override
                     public void run() {
-                        changeReqBtnVisibility(autoType, true);
+                        SimulatorRemoteResource remoteResource = resource
+                                .getRemoteResourceRef();
+                        if (null == remoteResource) {
+                            return;
+                        }
+                        Activator
+                                .getDefault()
+                                .getLogManager()
+                                .log(Level.INFO.ordinal(),
+                                        new Date(),
+                                        "["
+                                                + reqType.toString()
+                                                + "] Verification is successful for \""
+                                                + remoteResource.getURI()
+                                                + "\".");
                     }
                 });
             }
 
             @Override
             public void onVerificationAborted(final RemoteResource resource,
-                    final int autoType) {
+                    final RequestType reqType) {
+
+                if (null == resource) {
+                    return;
+                }
+
                 Display.getDefault().asyncExec(new Runnable() {
 
                     @Override
                     public void run() {
-                        changeReqBtnVisibility(autoType, true);
+                        SimulatorRemoteResource remoteResource = resource
+                                .getRemoteResourceRef();
+                        if (null == remoteResource) {
+                            return;
+                        }
+                        Activator
+                                .getDefault()
+                                .getLogManager()
+                                .log(Level.INFO.ordinal(),
+                                        new Date(),
+                                        "["
+                                                + reqType
+                                                + "] Verification is failed for \""
+                                                + remoteResource.getURI()
+                                                + "\".");
                     }
                 });
             }
@@ -306,15 +306,10 @@ public class AttributeView extends ViewPart {
 
                     @Override
                     public void run() {
-
-                        System.out
-                                .println("AttributeView: onConfigurationUploaded");
                         if (null == resource) {
                             return;
                         }
                         if (resourceInSelection != resource) {
-                            System.out
-                                    .println("AttributeView: config upload response arrived for a different resource");
                             return;
                         }
                         if (!automateButton.isDisposed()) {
@@ -326,56 +321,34 @@ public class AttributeView extends ViewPart {
         };
     }
 
-    private void changeReqBtnVisibility(int reqType, boolean visibility) {
-        if (reqType == Constants.GET_AUTOMATION_INDEX) {
-            if (!getButton.isDisposed()) {
-                getButton.setEnabled(visibility);
-            }
-        } else if (reqType == Constants.PUT_AUTOMATION_INDEX) {
-            if (!putButton.isDisposed()) {
-                putButton.setEnabled(visibility);
-            }
-        } else {// if(reqType == Constants.POST_AUTOMATION_INDEX) {
-            if (!postButton.isDisposed()) {
-                postButton.setEnabled(visibility);
-            }
-        }
-    }
-
-    private Map<String, RemoteResourceAttribute> getData(RemoteResource resource) {
-        if (null == resource) {
-            return null;
+    private void updateViewer(RemoteResource resource) {
+        if (null == attViewer) {
+            return;
         }
-        Map<String, RemoteResourceAttribute> attMap = resource
-                .getResourceAttributesMap();
-        System.out.println("AttributeView: \n" + attMap);
-        return attMap;
-    }
-
-    private void updateViewer(Map<String, RemoteResourceAttribute> attMap) {
-        if (null != attTblViewer) {
-            Table tbl = attTblViewer.getTable();
-            if (null != attMap) {
-                attTblViewer.setInput(attMap.entrySet().toArray());
-                if (!tbl.isDisposed()) {
-                    tbl.setLinesVisible(true);
-                }
-            } else {
-                if (!tbl.isDisposed()) {
-                    tbl.removeAll();
-                    tbl.setLinesVisible(false);
-                }
+        Tree tree = attViewer.getTree();
+        if (null != resource) {
+            attViewer.setInput(resource.getResourceRepresentation());
+            attViewer.expandAll();
+            if (!tree.isDisposed()) {
+                tree.setLinesVisible(true);
+            }
+        } else {
+            if (!tree.isDisposed()) {
+                tree.removeAll();
+                tree.setLinesVisible(false);
             }
         }
     }
 
     private void updateObserve(RemoteResource resource) {
-        if (null == resource) {
+        if (null == resource || observeResButton.isDisposed()) {
             return;
         }
         boolean observed = resource.isObserved();
-        if (!observeResButton.isDisposed()) {
-            observeResButton.setSelection(observed);
+        if (observed) {
+            observeResButton.setText(Constants.STOP_OBSERVE);
+        } else {
+            observeResButton.setText(Constants.OBSERVE);
         }
     }
 
@@ -383,7 +356,7 @@ public class AttributeView extends ViewPart {
     public void createPartControl(Composite parent) {
         Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
 
-        parent.setLayout(new GridLayout(2, false));
+        parent.setLayout(new GridLayout());
         GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
         parent.setLayoutData(gd);
 
@@ -402,9 +375,7 @@ public class AttributeView extends ViewPart {
 
         setupAttributeTable(attGroup);
 
-        setupMessageArea(parent);
-
-        setupResourceLevelOpsArea(parent);
+        setupRequestControls(parent);
 
         setUIListeners();
 
@@ -413,26 +384,24 @@ public class AttributeView extends ViewPart {
         setVisibility(false);
 
         // Updating the data in the UI as per the resource in selection.
-        if (null != attTblViewer && !attTblViewer.getControl().isDisposed()) {
-            updateViewer(getData(resourceManager
-                    .getCurrentResourceInSelection()));
+        if (null != attViewer && !attViewer.getControl().isDisposed()) {
+            updateViewer(resourceManager.getCurrentResourceInSelection());
         }
     }
 
-    private void setupMessageArea(Composite parent) {
+    private void setupRequestControls(Composite parent) {
         GridData gd;
         Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
-        Group msgTypesGrp = new Group(parent, SWT.NONE);
+        Composite opsComp = new Composite(parent, SWT.NONE);
         gd = new GridData();
         gd.grabExcessHorizontalSpace = true;
         gd.horizontalAlignment = SWT.FILL;
-        msgTypesGrp.setLayoutData(gd);
-        GridLayout grid = new GridLayout(3, false);
-        msgTypesGrp.setLayout(grid);
-        msgTypesGrp.setText("Request Types");
-        msgTypesGrp.setBackground(color);
+        opsComp.setLayoutData(gd);
+        GridLayout grid = new GridLayout(5, false);
+        opsComp.setLayout(grid);
+        opsComp.setBackground(color);
 
-        getButton = new Button(msgTypesGrp, SWT.PUSH);
+        getButton = new Button(opsComp, SWT.PUSH);
         getButton.setText("GET");
         gd = new GridData();
         gd.grabExcessHorizontalSpace = true;
@@ -440,7 +409,7 @@ public class AttributeView extends ViewPart {
         gd.widthHint = 50;
         getButton.setLayoutData(gd);
 
-        putButton = new Button(msgTypesGrp, SWT.PUSH);
+        putButton = new Button(opsComp, SWT.PUSH);
         putButton.setText("PUT");
         gd = new GridData();
         gd.grabExcessHorizontalSpace = true;
@@ -448,95 +417,58 @@ public class AttributeView extends ViewPart {
         gd.widthHint = 50;
         putButton.setLayoutData(gd);
 
-        postButton = new Button(msgTypesGrp, SWT.PUSH);
+        postButton = new Button(opsComp, SWT.PUSH);
         postButton.setText("POST");
         gd = new GridData();
         gd.grabExcessHorizontalSpace = true;
         gd.horizontalAlignment = SWT.FILL;
         gd.widthHint = 50;
         postButton.setLayoutData(gd);
-    }
 
-    private void setupResourceLevelOpsArea(Composite parent) {
-        GridData gd;
-        Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
-        Group resOpsGrp = new Group(parent, SWT.NONE);
+        observeResButton = new Button(opsComp, SWT.PUSH);
+        observeResButton.setText(Constants.OBSERVE);
         gd = new GridData();
         gd.grabExcessHorizontalSpace = true;
         gd.horizontalAlignment = SWT.FILL;
-        resOpsGrp.setLayoutData(gd);
-        GridLayout grid = new GridLayout(2, false);
-        resOpsGrp.setLayout(grid);
-        resOpsGrp.setText("Resource-Level Operations");
-        resOpsGrp.setBackground(color);
+        observeResButton.setLayoutData(gd);
 
-        automateButton = new Button(resOpsGrp, SWT.PUSH);
+        automateButton = new Button(opsComp, SWT.PUSH);
         automateButton.setText("Automation");
         gd = new GridData();
         gd.grabExcessHorizontalSpace = true;
         gd.horizontalAlignment = SWT.FILL;
         automateButton.setLayoutData(gd);
-
-        observeResButton = new Button(resOpsGrp, SWT.CHECK);
-        observeResButton.setText("Observe");
-        gd = new GridData();
-        gd.grabExcessHorizontalSpace = true;
-        gd.horizontalAlignment = SWT.FILL;
-        observeResButton.setLayoutData(gd);
     }
 
     private void setupAttributeTable(Group attGroup) {
-        attTblViewer = new TableViewer(attGroup, SWT.SINGLE | SWT.H_SCROLL
-                | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
+        Tree addressTree = new Tree(attGroup, SWT.SINGLE | SWT.BORDER
+                | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
+        addressTree.setHeaderVisible(true);
+
+        attViewer = new TreeViewer(addressTree);
 
-        createAttributeColumns(attTblViewer);
+        createAttributeColumns(attViewer);
 
         // make lines and header visible
-        Table table = attTblViewer.getTable();
-        table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-        table.setHeaderVisible(true);
-        table.setLinesVisible(true);
+        Tree tree = attViewer.getTree();
+        tree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+        tree.setHeaderVisible(true);
+        tree.setLinesVisible(true);
 
-        attTblViewer.setContentProvider(new AttributeContentProvider());
+        attViewer.setContentProvider(new AttributeContentProvider());
+        attViewer.setLabelProvider(new AttributeLabelProvider());
     }
 
-    public void createAttributeColumns(TableViewer tableViewer) {
+    public void createAttributeColumns(TreeViewer viewer) {
+        Tree tree = viewer.getTree();
 
-        TableViewerColumn attName = new TableViewerColumn(tableViewer, SWT.NONE);
-        attName.getColumn().setWidth(attTblColWidth[0]);
-        attName.getColumn().setText(attTblHeaders[0]);
-        attName.setLabelProvider(new StyledCellLabelProvider() {
-            @Override
-            public void update(ViewerCell cell) {
-                Object element = cell.getElement();
-                if (element instanceof Map.Entry) {
-                    @SuppressWarnings("unchecked")
-                    Map.Entry<String, RemoteResourceAttribute> entry = (Map.Entry<String, RemoteResourceAttribute>) element;
-                    cell.setText(entry.getKey());
-                }
-            }
-        });
+        TreeColumn attName = new TreeColumn(tree, SWT.NONE);
+        attName.setWidth(attTblColWidth[0]);
+        attName.setText(attTblHeaders[0]);
 
-        TableViewerColumn attValue = new TableViewerColumn(tableViewer,
-                SWT.NONE);
-        attValue.getColumn().setWidth(attTblColWidth[1]);
-        attValue.getColumn().setText(attTblHeaders[1]);
-        attValue.setLabelProvider(new StyledCellLabelProvider() {
-            @Override
-            public void update(ViewerCell cell) {
-                Object element = cell.getElement();
-                if (element instanceof Map.Entry) {
-                    @SuppressWarnings("unchecked")
-                    Map.Entry<String, RemoteResourceAttribute> entry = (Map.Entry<String, RemoteResourceAttribute>) element;
-                    Object value = entry.getValue().getAttributeValue();
-                    if (null == value) {
-                        cell.setText("");
-                    } else {
-                        cell.setText(String.valueOf(value));
-                    }
-                }
-            }
-        });
+        TreeColumn attValue = new TreeColumn(tree, SWT.NONE);
+        attValue.setWidth(attTblColWidth[1]);
+        attValue.setText(attTblHeaders[1]);
     }
 
     private void setUIListeners() {
@@ -544,14 +476,20 @@ public class AttributeView extends ViewPart {
         getButton.addSelectionListener(new SelectionAdapter() {
             @Override
             public void widgetSelected(SelectionEvent e) {
-                if (resourceInSelection.isGetAutomtnInProgress()) {
-                    MessageDialog
-                            .openInformation(Display.getDefault()
-                                    .getActiveShell(), "GET Request",
-                                    "GET Automation is in progress. Please wait or stop the automation.");
-                } else {
-                    resourceManager.sendGetRequest(resourceInSelection);
-                }
+                PlatformUI.getWorkbench().getDisplay().syncExec(new Thread() {
+                    @Override
+                    public void run() {
+                        GetRequestDialog getDialog = new GetRequestDialog(
+                                Display.getDefault().getActiveShell());
+                        if (getDialog.open() == Window.OK) {
+                            // Call the native GET method
+                            String query = getDialog.getOtherFilters();
+                            String ifType = getDialog.getIfType();
+                            resourceManager.sendGetRequest(ifType, query,
+                                    resourceInSelection);
+                        }
+                    }
+                });
             }
         });
 
@@ -561,30 +499,37 @@ public class AttributeView extends ViewPart {
                 PlatformUI.getWorkbench().getDisplay().syncExec(new Thread() {
                     @Override
                     public void run() {
-                        if (resourceInSelection.isPutAutomtnInProgress()) {
-                            MessageDialog
-                                    .openInformation(Display.getDefault()
-                                            .getActiveShell(), "PUT Request",
-                                            "PUT Automation is in progress. Please wait or stop the automation.");
-                            return;
+                        boolean attributesExist = false;
+                        ResourceRepresentation rep = resourceInSelection
+                                .getResourceRepresentation();
+                        if (null != rep) {
+                            Map<String, AttributeElement> attributes = rep
+                                    .getAttributes();
+                            if (null != attributes && !attributes.isEmpty()) {
+                                attributesExist = true;
+                            }
                         }
-                        List<PutPostAttributeModel> putPostModelList;
-                        putPostModelList = resourceInSelection
-                                .getPutPostModel();
-                        if (null == putPostModelList) {
-                            MessageDialog
-                                    .openInformation(Display.getDefault()
-                                            .getActiveShell(), "PUT Request",
-                                            "No attributes exist in the resource model.");
-                            return;
-                        }
-                        PutRequestDialog putDialog = new PutRequestDialog(
-                                Display.getDefault().getActiveShell(),
-                                putPostModelList);
-                        if (putDialog.open() == Window.OK) {
-                            // Call the native PUT method
-                            resourceManager.sendPutRequest(resourceInSelection,
-                                    putPostModelList);
+                        if (attributesExist) {
+                            PutRequestDialog putDialog = new PutRequestDialog(
+                                    Display.getDefault().getActiveShell());
+                            if (putDialog.open() == Window.OK) {
+                                // Call the native PUT method
+                                String ifType = putDialog.getIfType();
+                                ResourceRepresentation updatedRepresentation = putDialog
+                                        .getUpdatedRepresentation();
+                                if (null != updatedRepresentation) {
+                                    resourceManager.sendPutRequest(ifType,
+                                            resourceInSelection,
+                                            updatedRepresentation.getModel());
+                                    return;
+                                }
+
+                                MessageDialog
+                                        .openInformation(Display.getDefault()
+                                                .getActiveShell(),
+                                                "PUT Request",
+                                                "No attributes exist in the resource model.");
+                            }
                         }
                     }
                 });
@@ -597,31 +542,38 @@ public class AttributeView extends ViewPart {
                 PlatformUI.getWorkbench().getDisplay().syncExec(new Thread() {
                     @Override
                     public void run() {
-                        if (resourceInSelection.isPostAutomtnInProgress()) {
-                            MessageDialog
-                                    .openInformation(Display.getDefault()
-                                            .getActiveShell(), "POST Request",
-                                            "POST Automation is in progress. Please wait or stop the automation.");
-                            return;
-                        }
-                        List<PutPostAttributeModel> putPostModelList;
-                        putPostModelList = resourceInSelection
-                                .getPutPostModel();
-                        if (null == putPostModelList) {
-                            MessageDialog
-                                    .openInformation(Display.getDefault()
-                                            .getActiveShell(), "PUT Request",
-                                            "No attributes exist in the resource model.");
-                            return;
+                        boolean attributesExist = false;
+                        ResourceRepresentation rep = resourceInSelection
+                                .getResourceRepresentation();
+                        if (null != rep) {
+                            Map<String, AttributeElement> attributes = rep
+                                    .getAttributes();
+                            if (null != attributes && !attributes.isEmpty()) {
+                                attributesExist = true;
+                            }
                         }
-
-                        PostRequestDialog postDialog = new PostRequestDialog(
-                                Display.getDefault().getActiveShell(),
-                                putPostModelList);
-                        if (postDialog.open() == Window.OK) {
-                            // Call the native POST method
-                            resourceManager.sendPostRequest(
-                                    resourceInSelection, putPostModelList);
+                        if (attributesExist) {
+                            PostRequestDialog postDialog = new PostRequestDialog(
+                                    Display.getDefault().getActiveShell());
+                            if (postDialog.open() == Window.OK) {
+                                // Call the native POST method
+                                String ifType = postDialog.getIfType();
+                                ResourceRepresentation updatedRepresentation = postDialog
+                                        .getUpdatedRepresentation();
+                                if (null != updatedRepresentation) {
+                                    resourceManager.sendPostRequest(ifType,
+                                            resourceInSelection,
+                                            updatedRepresentation
+                                                    .getSelectedModel());
+                                    return;
+                                }
+
+                                MessageDialog
+                                        .openInformation(Display.getDefault()
+                                                .getActiveShell(),
+                                                "POST Request",
+                                                "No attributes exist in the resource model.");
+                            }
                         }
                     }
                 });
@@ -631,12 +583,29 @@ public class AttributeView extends ViewPart {
         observeResButton.addSelectionListener(new SelectionAdapter() {
             @Override
             public void widgetSelected(SelectionEvent e) {
-                boolean checked = observeResButton.getSelection();
-                if (checked) {
-                    resourceManager.sendObserveRequest(resourceInSelection);
+                boolean result;
+                if (observeResButton.getText().equals(Constants.OBSERVE)) {
+                    result = resourceManager
+                            .sendObserveRequest(resourceInSelection);
+                    if (result) {
+                        observeResButton.setText(Constants.STOP_OBSERVE);
+                    } else {
+                        MessageDialog.openError(Display.getDefault()
+                                .getActiveShell(), "Observe failed",
+                                "Failed to observe the resource. Try again.");
+                    }
                 } else {
-                    resourceManager
-                            .sendCancelObserveRequest(resourceInSelection);
+                    result = resourceManager.sendCancelObserveRequest(
+                            resourceInSelection, true);
+                    if (result) {
+                        observeResButton.setText(Constants.OBSERVE);
+                    } else {
+                        MessageDialog
+                                .openError(Display.getDefault()
+                                        .getActiveShell(),
+                                        "Cancel Observe failed",
+                                        "Failed to stop observing the resource. Try again.");
+                    }
                 }
             }
         });
@@ -657,24 +626,130 @@ public class AttributeView extends ViewPart {
                         if (null == autoStatus) {
                             return;
                         }
+
+                        int startCount = 0;
+                        int stopCount = 0;
+                        boolean startGet, startPut, startPost;
+                        boolean stopGet, stopPut, stopPost;
+                        startGet = startPut = startPost = false;
+                        stopGet = stopPut = stopPost = false;
+                        String status = null;
+                        String startMsg = "Verification will be started for: ";
+                        String stopMsg = "Verification will be stopped for: ";
                         VerificationDialog ad = new VerificationDialog(Display
                                 .getDefault().getActiveShell(), autoStatus);
-                        ad.open();
+                        if (ad.open() == Window.OK) {
+                            Map<String, Boolean> oldStatus = resourceManager
+                                    .getAutomationStatus(resource);
+                            if (null == oldStatus || oldStatus.size() < 1) {
+                                status = "Failed to perform the requested operation.";
+                            } else {
+                                // GET
+                                if (!oldStatus.get(Constants.GET).equals(
+                                        autoStatus.get(Constants.GET))) {
+                                    if (autoStatus.get(Constants.GET)) {
+                                        startMsg += Constants.GET;
+                                        startCount++;
+                                        startGet = true;
+                                    } else {
+                                        stopMsg += Constants.GET;
+                                        stopCount++;
+                                        stopGet = true;
+                                    }
+                                }
+                                // PUT
+                                if (!oldStatus.get(Constants.PUT).equals(
+                                        autoStatus.get(Constants.PUT))) {
+                                    if (autoStatus.get(Constants.PUT)) {
+                                        if (startCount == 1) {
+                                            startMsg += ", ";
+                                        }
+                                        startMsg += Constants.PUT;
+                                        startCount++;
+                                        startPut = true;
+                                    } else {
+                                        if (stopCount == 1) {
+                                            stopMsg += ", ";
+                                        }
+                                        stopMsg += Constants.PUT;
+                                        stopCount++;
+                                        stopPut = true;
+                                    }
+
+                                }
+                                // POST
+                                if (!oldStatus.get(Constants.POST).equals(
+                                        autoStatus.get(Constants.POST))) {
+                                    if (autoStatus.get(Constants.POST)) {
+                                        if (startCount > 0) {
+                                            startMsg += ", ";
+                                        }
+                                        startMsg += Constants.POST;
+                                        startCount++;
+                                        startPost = true;
+                                    } else {
+                                        if (stopCount > 0) {
+                                            stopMsg += ", ";
+                                        }
+                                        stopMsg += Constants.POST;
+                                        stopCount++;
+                                        stopPost = true;
+                                    }
+                                }
+                                if (startCount > 0) {
+                                    status = startMsg + ".";
+                                }
+                                if (stopCount > 0) {
+                                    if (startCount <= 0) {
+                                        status = stopMsg;
+                                    } else {
+                                        status += "\n" + stopMsg + ".";
+                                    }
+                                }
+                            }
+                            if (!(startCount == 0 && stopCount == 0)) {
+                                boolean answer = MessageDialog.openQuestion(
+                                        Display.getDefault().getActiveShell(),
+                                        "Verification", status
+                                                + "\nDo you want to proceed?");
+                                if (answer) {
+                                    if (startGet || stopGet)
+                                        automate(RequestType.GET,
+                                                autoStatus.get(Constants.GET));
+                                    if (startPut || stopPut)
+                                        automate(RequestType.PUT,
+                                                autoStatus.get(Constants.PUT));
+                                    if (startPost || stopPost)
+                                        automate(RequestType.POST,
+                                                autoStatus.get(Constants.POST));
+                                }
+                            }
+                        }
                     }
                 });
             }
         });
     }
 
+    private void automate(RequestType type, boolean start) {
+        if (start) {
+            resourceManager.startAutomationRequest(type, resourceInSelection);
+        } else {
+            resourceManager.stopAutomationRequest(type, resourceInSelection);
+        }
+    }
+
     private void addManagerListeners() {
-        resourceManager
-                .addResourceSelectionChangedUIListener(resourceSelectionChangedListener);
-        resourceManager.addGetUIListener(getUIListener);
-        resourceManager.addPutUIListener(putUIListener);
-        resourceManager.addPostUIListener(postUIListener);
-        resourceManager.addObserveUIListener(observeUIListener);
-        resourceManager.addVerificationUIListener(verificationUIListener);
-        resourceManager.addConfigUploadUIListener(configUploadUIListener);
+        UiListenerHandler.getInstance().addResourceSelectionChangedUIListener(
+                resourceSelectionChangedListener);
+        UiListenerHandler.getInstance().addGetUIListener(getUIListener);
+        UiListenerHandler.getInstance().addPutUIListener(putUIListener);
+        UiListenerHandler.getInstance().addPostUIListener(postUIListener);
+        UiListenerHandler.getInstance().addObserveUIListener(observeUIListener);
+        UiListenerHandler.getInstance().addVerificationUIListener(
+                verificationUIListener);
+        UiListenerHandler.getInstance().addConfigUploadUIListener(
+                configUploadUIListener);
     }
 
     private void setVisibility(boolean visibility) {
@@ -696,34 +771,131 @@ public class AttributeView extends ViewPart {
             observeResButton.setEnabled(visibility);
     }
 
-    class AttributeContentProvider implements IStructuredContentProvider {
+    private static class AttributeContentProvider implements
+            ITreeContentProvider {
 
         @Override
         public void dispose() {
         }
 
         @Override
-        public void inputChanged(Viewer viewer, Object arg1, Object arg2) {
+        public void inputChanged(Viewer viewer, Object oldAttribute,
+                Object newAttribute) {
         }
 
         @Override
-        public Object[] getElements(Object element) {
-            return (Object[]) element;
+        public Object[] getChildren(Object attribute) {
+            if (attribute instanceof AttributeElement) {
+                List<AttributeElement> attElementList = new ArrayList<AttributeElement>();
+                Map<String, AttributeElement> children = ((AttributeElement) attribute)
+                        .getChildren();
+                if (null != children) {
+                    attElementList.addAll(children.values());
+                    Collections.sort(attElementList,
+                            Utility.attributeComparator);
+                    return attElementList.toArray();
+                }
+            }
+
+            return new Object[0];
+        }
+
+        @Override
+        public Object getParent(Object attribute) {
+            if (attribute instanceof AttributeElement)
+                return ((AttributeElement) attribute).getParent();
+            return null;
+        }
+
+        @Override
+        public boolean hasChildren(Object attribute) {
+            if (attribute instanceof AttributeElement)
+                return ((AttributeElement) attribute).hasChildren();
+            return false;
+        }
+
+        @Override
+        public Object[] getElements(Object resourceModel) {
+            if (resourceModel instanceof ResourceRepresentation) {
+                return ((ResourceRepresentation) resourceModel).getAttributes()
+                        .values().toArray();
+            }
+
+            return new Object[0];
         }
+    }
+
+    private static class AttributeLabelProvider implements ITableLabelProvider {
 
+        @Override
+        public void addListener(ILabelProviderListener arg0) {
+        }
+
+        @Override
+        public void dispose() {
+        }
+
+        @Override
+        public boolean isLabelProperty(Object arg0, String arg1) {
+            return false;
+        }
+
+        @Override
+        public void removeListener(ILabelProviderListener arg0) {
+
+        }
+
+        @Override
+        public Image getColumnImage(Object element, int col) {
+            return null;
+        }
+
+        @Override
+        public String getColumnText(Object element, int column) {
+            if (element instanceof AttributeElement) {
+                AttributeElement attrElement = (AttributeElement) element;
+                switch (column) {
+                    case 0: // Attribute name column
+                    {
+                        SimulatorResourceAttribute attribute = attrElement
+                                .getSimulatorResourceAttribute();
+                        return attribute.name();
+                    }
+
+                    case 1: // Attribute value column
+                    {
+                        SimulatorResourceAttribute attribute = attrElement
+                                .getSimulatorResourceAttribute();
+
+                        if (attribute.value().typeInfo().mBaseType != ValueType.RESOURCEMODEL) {
+                            String value = Utility
+                                    .getAttributeValueAsString(attribute
+                                            .value());
+                            if (null == value) {
+                                value = "";
+                            }
+                            return value;
+                        }
+                        return null;
+                    }
+                }
+            }
+            return null;
+        }
     }
 
     @Override
     public void dispose() {
         // Unregister the selection listener
         if (null != resourceSelectionChangedListener) {
-            resourceManager
-                    .removeResourceSelectionChangedUIListener(resourceSelectionChangedListener);
+            UiListenerHandler.getInstance()
+                    .removeResourceSelectionChangedUIListener(
+                            resourceSelectionChangedListener);
         }
 
         // Unregister the GET listener
         if (null != getUIListener) {
-            resourceManager.removeGetUIListener(getUIListener);
+            UiListenerHandler.getInstance().removeGetUIListener(getUIListener);
         }
 
         super.dispose();
index 3c4d76e..c1642d2 100644 (file)
 
 package oic.simulator.clientcontroller.view;
 
-import java.io.BufferedWriter;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.HashMap;
-import java.util.List;
-
-import oic.simulator.clientcontroller.Activator;
-import oic.simulator.clientcontroller.listener.ILogUIListener;
-import oic.simulator.clientcontroller.manager.LogManager;
-import oic.simulator.clientcontroller.utils.Constants;
-import oic.simulator.clientcontroller.view.dialogs.FilterDialog;
-import oic.simulator.clientcontroller.view.dialogs.LogDetailsDialog;
-import oic.simulator.logger.LogContentProvider;
-import oic.simulator.logger.LogEntry;
-import oic.simulator.logger.LogLabelProvider;
-
 import org.eclipse.jface.action.Action;
 import org.eclipse.jface.action.IAction;
 import org.eclipse.jface.action.IContributionItem;
@@ -72,8 +54,29 @@ import org.eclipse.ui.IWorkbenchPage;
 import org.eclipse.ui.dialogs.FilteredTree;
 import org.eclipse.ui.dialogs.PatternFilter;
 import org.eclipse.ui.part.ViewPart;
+
+import java.io.BufferedWriter;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+
 import org.oic.simulator.ILogger.Level;
 
+import oic.simulator.clientcontroller.Activator;
+import oic.simulator.clientcontroller.listener.ILogUIListener;
+import oic.simulator.clientcontroller.manager.LogManager;
+import oic.simulator.clientcontroller.utils.Constants;
+import oic.simulator.clientcontroller.view.dialogs.FilterDialog;
+import oic.simulator.clientcontroller.view.dialogs.LogDetailsDialog;
+import oic.simulator.logger.LogContentProvider;
+import oic.simulator.logger.LogEntry;
+import oic.simulator.logger.LogLabelProvider;
+
 /**
  * This class manages and shows the log view in the perspective.
  */
@@ -429,9 +432,10 @@ public class LogView extends ViewPart {
                 String data = sb.toString();
                 BufferedWriter out = null;
                 try {
-                    out = new BufferedWriter(new FileWriter(name));
+                    out = new BufferedWriter(new OutputStreamWriter(
+                            new FileOutputStream(name), "UTF-8"));
                     out.write(data);
-                } catch (IOException e) {
+                } catch (Exception e) {
                     e.printStackTrace();
                     MessageDialog.openError(
                             Display.getDefault().getActiveShell(),
@@ -444,7 +448,13 @@ public class LogView extends ViewPart {
                             out.close();
                         }
                     } catch (IOException e) {
-                        System.out.println("Error occurred during close.");
+                        Activator
+                                .getDefault()
+                                .getLogManager()
+                                .log(Level.ERROR.ordinal(),
+                                        new Date(),
+                                        "[" + e.getClass().getSimpleName()
+                                                + "]" + e.getMessage());
                     }
                 }
             }
index ae9fa40..7f4ec41 100644 (file)
 
 package oic.simulator.clientcontroller.view;
 
-import java.util.List;
-
-import oic.simulator.clientcontroller.Activator;
-import oic.simulator.clientcontroller.listener.IResourceSelectionChangedUIListener;
-import oic.simulator.clientcontroller.manager.ResourceManager;
-import oic.simulator.clientcontroller.remoteresource.MetaProperty;
-import oic.simulator.clientcontroller.remoteresource.RemoteResource;
-
 import org.eclipse.jface.viewers.ColumnLabelProvider;
 import org.eclipse.jface.viewers.IStructuredContentProvider;
 import org.eclipse.jface.viewers.TableViewer;
 import org.eclipse.jface.viewers.TableViewerColumn;
 import org.eclipse.jface.viewers.Viewer;
 import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.CTabFolder;
+import org.eclipse.swt.custom.CTabItem;
+import org.eclipse.swt.graphics.Color;
 import org.eclipse.swt.layout.GridData;
 import org.eclipse.swt.layout.GridLayout;
 import org.eclipse.swt.widgets.Composite;
 import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Group;
 import org.eclipse.swt.widgets.Table;
 import org.eclipse.ui.part.ViewPart;
 
+import java.util.List;
+
+import oic.simulator.clientcontroller.Activator;
+import oic.simulator.clientcontroller.listener.IDevicePlatformInfoUIListener;
+import oic.simulator.clientcontroller.listener.IResourceSelectionChangedUIListener;
+import oic.simulator.clientcontroller.manager.ResourceManager;
+import oic.simulator.clientcontroller.manager.UiListenerHandler;
+import oic.simulator.clientcontroller.remoteresource.MetaProperty;
+import oic.simulator.clientcontroller.remoteresource.RemoteResource;
+
 /**
  * This class manages and shows the meta properties view in the perspective.
  */
@@ -44,7 +50,9 @@ public class MetaPropertiesView extends ViewPart {
 
     public static final String                  VIEW_ID       = "oic.simulator.clientcontroller.view.metaproperties";
 
-    private TableViewer                         tableViewer;
+    private TableViewer                         defaultTblViewer;
+    private TableViewer                         deviceTblViewer;
+    private TableViewer                         platformTblViewer;
 
     private final String[]                      columnHeaders = { "Property",
             "Value"                                          };
@@ -52,9 +60,15 @@ public class MetaPropertiesView extends ViewPart {
     private final Integer[]                     columnWidth   = { 150, 150 };
 
     private IResourceSelectionChangedUIListener resourceSelectionChangedListener;
+    private IDevicePlatformInfoUIListener       devicePlatformInfoUIListener;
 
     private ResourceManager                     resourceManager;
 
+    private CTabFolder                          folder;
+    private CTabItem                            defaultPropTab;
+    private CTabItem                            devicePropTab;
+    private CTabItem                            platformPropTab;
+
     public MetaPropertiesView() {
 
         resourceManager = Activator.getDefault().getResourceManager();
@@ -67,8 +81,37 @@ public class MetaPropertiesView extends ViewPart {
 
                     @Override
                     public void run() {
-                        if (null != tableViewer) {
-                            updateViewer(getData(resource));
+                        updateUI(resource);
+                    }
+                });
+            }
+        };
+
+        devicePlatformInfoUIListener = new IDevicePlatformInfoUIListener() {
+
+            @Override
+            public void onPlatformInfoFound() {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        if (null != platformTblViewer) {
+                            updateViewer(platformTblViewer,
+                                    getPlatformPropData());
+                        }
+                    }
+                });
+
+            }
+
+            @Override
+            public void onDeviceInfoFound() {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        if (null != deviceTblViewer) {
+                            updateViewer(deviceTblViewer, getDevicePropData());
                         }
                     }
                 });
@@ -76,48 +119,164 @@ public class MetaPropertiesView extends ViewPart {
         };
     }
 
+    private void updateUI(final RemoteResource resource) {
+        if (null != defaultTblViewer) {
+            updateViewer(defaultTblViewer, getDefaultPropData(resource));
+        }
+        if (null != deviceTblViewer) {
+            updateViewer(deviceTblViewer, getDevicePropData());
+        }
+        if (null != platformTblViewer) {
+            updateViewer(platformTblViewer, getPlatformPropData());
+        }
+    }
+
     @Override
     public void createPartControl(Composite parent) {
-        parent.setLayout(new GridLayout(1, false));
+        parent.setLayout(new GridLayout());
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        parent.setLayoutData(gd);
+
+        // Create a Tab Folder.
+        folder = new CTabFolder(parent, SWT.BORDER);
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        folder.setLayoutData(gd);
+        folder.setSimple(false);
+        folder.setUnselectedCloseVisible(false);
+        folder.setUnselectedImageVisible(false);
+
+        createDefaultPropertiesTab();
+
+        createDevicePropertiesTab();
+
+        createPlatformPropertiesTab();
 
-        tableViewer = new TableViewer(parent, SWT.SINGLE | SWT.H_SCROLL
+        folder.setSelection(defaultPropTab);
+
+        addManagerListeners();
+
+        // Check whether there is any resource selected already
+        updateUI(null);
+    }
+
+    private void createDefaultPropertiesTab() {
+        defaultPropTab = new CTabItem(folder, SWT.NULL);
+        defaultPropTab.setText("Default");
+
+        // Adding the group to the folder.
+        Group propGroup = new Group(folder, SWT.NONE);
+
+        Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
+        propGroup.setBackground(color);
+
+        propGroup.setLayout(new GridLayout());
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        propGroup.setLayoutData(gd);
+
+        defaultTblViewer = new TableViewer(propGroup, SWT.SINGLE | SWT.H_SCROLL
                 | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
 
-        createColumns(tableViewer);
+        createColumns(defaultTblViewer);
 
-        // make lines and header visible
-        final Table table = tableViewer.getTable();
+        // Make lines and header visible
+        final Table table = defaultTblViewer.getTable();
         table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
         table.setHeaderVisible(true);
         table.setLinesVisible(true);
 
-        tableViewer.setContentProvider(new PropertycontentProvider());
+        defaultTblViewer.setContentProvider(new PropertycontentProvider());
 
-        addManagerListeners();
+        defaultPropTab.setControl(propGroup);
+    }
 
-        // Check whether there is any resource selected already
-        List<MetaProperty> propertyList = getData(null);
-        if (null != propertyList) {
-            updateViewer(propertyList);
-        }
+    private void createDevicePropertiesTab() {
+        devicePropTab = new CTabItem(folder, SWT.NULL);
+        devicePropTab.setText("Device");
+
+        // Adding the group to the folder.
+        Group propGroup = new Group(folder, SWT.NONE);
+
+        Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
+        propGroup.setBackground(color);
+
+        propGroup.setLayout(new GridLayout());
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        propGroup.setLayoutData(gd);
+
+        deviceTblViewer = new TableViewer(propGroup, SWT.SINGLE | SWT.H_SCROLL
+                | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
+
+        createColumns(deviceTblViewer);
+
+        // Make lines and header visible
+        final Table table = deviceTblViewer.getTable();
+        table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+        table.setHeaderVisible(true);
+        table.setLinesVisible(true);
 
+        deviceTblViewer.setContentProvider(new PropertycontentProvider());
+
+        devicePropTab.setControl(propGroup);
     }
 
-    private List<MetaProperty> getData(RemoteResource resource) {
+    private void createPlatformPropertiesTab() {
+        platformPropTab = new CTabItem(folder, SWT.NULL);
+        platformPropTab.setText("Platform");
+
+        // Adding the group to the folder.
+        Group propGroup = new Group(folder, SWT.NONE);
+
+        Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
+        propGroup.setBackground(color);
+
+        propGroup.setLayout(new GridLayout());
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        propGroup.setLayoutData(gd);
+
+        platformTblViewer = new TableViewer(propGroup, SWT.SINGLE
+                | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
+
+        createColumns(platformTblViewer);
+
+        // Make lines and header visible
+        final Table table = platformTblViewer.getTable();
+        table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+        table.setHeaderVisible(true);
+        table.setLinesVisible(true);
+
+        platformTblViewer.setContentProvider(new PropertycontentProvider());
+
+        platformPropTab.setControl(propGroup);
+    }
+
+    private List<MetaProperty> getDefaultPropData(RemoteResource resource) {
         if (null == resource) {
             resource = Activator.getDefault().getResourceManager()
                     .getCurrentResourceInSelection();
         }
         List<MetaProperty> metaPropertyList = resourceManager
-                .getMetaProperties(resource);
+                .getDefaultProperties(resource);
+        return metaPropertyList;
+    }
+
+    private List<MetaProperty> getDevicePropData() {
+        List<MetaProperty> metaPropertyList = resourceManager
+                .getDeviceProperties();
         return metaPropertyList;
     }
 
-    private void updateViewer(List<MetaProperty> metaPropertyList) {
-        if (null != tableViewer) {
-            Table tbl = tableViewer.getTable();
+    private List<MetaProperty> getPlatformPropData() {
+        List<MetaProperty> metaPropertyList = resourceManager
+                .getPlatformProperties();
+        return metaPropertyList;
+    }
+
+    private void updateViewer(TableViewer tblViewer,
+            List<MetaProperty> metaPropertyList) {
+        if (null != tblViewer) {
+            Table tbl = tblViewer.getTable();
             if (null != metaPropertyList) {
-                tableViewer.setInput(metaPropertyList.toArray());
+                tblViewer.setInput(metaPropertyList.toArray());
                 if (!tbl.isDisposed()) {
                     tbl.setLinesVisible(true);
                 }
@@ -165,11 +324,14 @@ public class MetaPropertiesView extends ViewPart {
     }
 
     private void addManagerListeners() {
-        resourceManager
-                .addResourceSelectionChangedUIListener(resourceSelectionChangedListener);
+        UiListenerHandler.getInstance().addResourceSelectionChangedUIListener(
+                resourceSelectionChangedListener);
+        UiListenerHandler.getInstance().addDevicePlatformInfoUIListener(
+                devicePlatformInfoUIListener);
     }
 
-    class PropertycontentProvider implements IStructuredContentProvider {
+    private static class PropertycontentProvider implements
+            IStructuredContentProvider {
 
         @Override
         public void dispose() {
@@ -183,15 +345,15 @@ public class MetaPropertiesView extends ViewPart {
         public Object[] getElements(Object element) {
             return (Object[]) element;
         }
-
     }
 
     @Override
     public void dispose() {
         // Unregister the listener
         if (null != resourceSelectionChangedListener) {
-            resourceManager
-                    .removeResourceSelectionChangedUIListener(resourceSelectionChangedListener);
+            UiListenerHandler.getInstance()
+                    .removeResourceSelectionChangedUIListener(
+                            resourceSelectionChangedListener);
         }
         super.dispose();
     }
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/MultiResourceOrchestrationView.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/MultiResourceOrchestrationView.java
deleted file mode 100644 (file)
index 67ae7ce..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * 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.
- */
-
-package oic.simulator.clientcontroller.view;
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.part.ViewPart;
-
-/**
- * This class manages and shows the multi-resource automation view in the
- * perspective.
- */
-public class MultiResourceOrchestrationView extends ViewPart {
-
-    public static final String VIEW_ID = "oic.simulator.clientcontroller.view.orchestration";
-
-    @Override
-    public void createPartControl(Composite arg0) {
-        // TODO Auto-generated method stub
-
-    }
-
-    @Override
-    public void setFocus() {
-        // TODO Auto-generated method stub
-
-    }
-
-}
index 2082a42..1f70ccb 100644 (file)
 
 package oic.simulator.clientcontroller.view;
 
-import java.util.List;
-import java.util.Set;
-
-import oic.simulator.clientcontroller.Activator;
-import oic.simulator.clientcontroller.listener.IFindResourceUIListener;
-import oic.simulator.clientcontroller.manager.ResourceManager;
-import oic.simulator.clientcontroller.remoteresource.RemoteResource;
-import oic.simulator.clientcontroller.utils.Constants;
-import oic.simulator.clientcontroller.view.dialogs.FindResourceWizard;
-import oic.simulator.clientcontroller.view.dialogs.LoadRAMLDialog;
-import oic.simulator.clientcontroller.view.dialogs.ResourceWizardDialog;
-
 import org.eclipse.jface.dialogs.MessageDialog;
 import org.eclipse.jface.viewers.ISelectionChangedListener;
 import org.eclipse.jface.viewers.IStructuredSelection;
@@ -61,6 +49,21 @@ import org.eclipse.ui.dialogs.FilteredTree;
 import org.eclipse.ui.dialogs.PatternFilter;
 import org.eclipse.ui.part.ViewPart;
 
+import java.util.List;
+import java.util.Set;
+
+import org.oic.simulator.SimulatorException;
+
+import oic.simulator.clientcontroller.Activator;
+import oic.simulator.clientcontroller.listener.IFindResourceUIListener;
+import oic.simulator.clientcontroller.manager.ResourceManager;
+import oic.simulator.clientcontroller.manager.UiListenerHandler;
+import oic.simulator.clientcontroller.remoteresource.RemoteResource;
+import oic.simulator.clientcontroller.utils.Constants;
+import oic.simulator.clientcontroller.view.dialogs.FindResourceWizard;
+import oic.simulator.clientcontroller.view.dialogs.LoadRAMLDialog;
+import oic.simulator.clientcontroller.view.dialogs.ResourceWizardDialog;
+
 /**
  * This class manages and shows the resource manager view in the perspective.
  */
@@ -97,7 +100,6 @@ public class ResourceManagerView extends ViewPart {
 
             @Override
             public void onNewResourceFound(final RemoteResource resource) {
-                System.out.println("View: onNewResourceFound");
                 if (null == resource) {
                     return;
                 }
@@ -123,16 +125,12 @@ public class ResourceManagerView extends ViewPart {
 
                         // Close the find dialog
                         if (null != findDialog) {
-                            boolean status = findDialog.close();
-                            System.out
-                                    .println("dialog close status: " + status);
+                            findDialog.close();
                         }
 
                         // Close the refresh dialog
                         if (null != refreshDialog) {
-                            boolean status = refreshDialog.close();
-                            System.out
-                                    .println("dialog close status: " + status);
+                            refreshDialog.close();
                         }
                     }
                 });
@@ -182,11 +180,6 @@ public class ResourceManagerView extends ViewPart {
         folder.addSelectionListener(new SelectionAdapter() {
             @Override
             public void widgetSelected(SelectionEvent e) {
-                /*
-                 * CTabItem selectedTab = folder.getSelection(); if(selectedTab
-                 * == foundResTab) { System.out.println("Found resources tab");
-                 * } else { System.out.println("Favorite resources tab"); }
-                 */
                 // Tab is switched.
                 treeViewer.setSelection(null);
                 favTreeViewer.setSelection(null);
@@ -276,68 +269,10 @@ public class ResourceManagerView extends ViewPart {
                         for (int index = 0; index < items.length; index++) {
                             items[index].dispose();
                         }
-                        MenuItem uploadRAMLItem = new MenuItem(menu, SWT.NONE);
-                        uploadRAMLItem.setText("Upload RAML Configuration");
-                        uploadRAMLItem
-                                .addSelectionListener(new SelectionAdapter() {
-                                    @Override
-                                    public void widgetSelected(SelectionEvent e) {
-                                        // Open the RAML configuration dialog if
-                                        // RAML file is not yet uploaded for the
-                                        // currently selected resource
-                                        RemoteResource resource = resourceManager
-                                                .getCurrentResourceInSelection();
-                                        if (null == resource) {
-                                            return;
-                                        }
-                                        if (!resource.isConfigUploaded()) {
-                                            // Open the dialog in a separate
-                                            // UI thread.
-                                            PlatformUI.getWorkbench()
-                                                    .getDisplay()
-                                                    .syncExec(new Thread() {
-                                                        @Override
-                                                        public void run() {
-                                                            LoadRAMLDialog ramlDialog = new LoadRAMLDialog(
-                                                                    Display.getDefault()
-                                                                            .getActiveShell());
-                                                            if (ramlDialog
-                                                                    .open() != Window.OK) {
-                                                                return;
-                                                            }
-                                                            String configFilePath = ramlDialog
-                                                                    .getConfigFilePath();
-                                                            if (null == configFilePath
-                                                                    || configFilePath
-                                                                            .length() < 1) {
-                                                                MessageDialog
-                                                                        .openInformation(
-                                                                                Display.getDefault()
-                                                                                        .getActiveShell(),
-                                                                                "Invalid RAML Config path",
-                                                                                "Configuration file path is invalid.");
-                                                                return;
-                                                            }
-                                                            resourceManager
-                                                                    .setConfigFilePath(
-                                                                            resourceManager
-                                                                                    .getCurrentResourceInSelection(),
-                                                                            configFilePath);
-                                                        }
-                                                    });
-                                        } else {
-                                            MessageDialog
-                                                    .openInformation(Display
-                                                            .getDefault()
-                                                            .getActiveShell(),
-                                                            "Already Uploaded",
-                                                            "Configuration file for the selected resource is already uploaded");
-                                        }
-                                    }
-                                });
+                        setupUploadRamlMenuItem(menu);
 
-                        RemoteResource resource = resourceManager
-                                .getCurrentResourceInSelection();
+                        final RemoteResource resource = (RemoteResource) ((IStructuredSelection) treeViewer
+                                .getSelection()).getFirstElement();
                         if (null == resource) {
                             return;
                         }
@@ -349,17 +284,11 @@ public class ResourceManagerView extends ViewPart {
                                 .addSelectionListener(new SelectionAdapter() {
                                     @Override
                                     public void widgetSelected(SelectionEvent e) {
-                                        RemoteResource resource = (RemoteResource) ((IStructuredSelection) treeViewer
-                                                .getSelection())
-                                                .getFirstElement();
-                                        if (null == resource) {
-                                            return;
-                                        }
-                                        System.out.println("Selected resource:"
-                                                + resource.getResourceURI());
                                         if (!resource.isFavorite()) {
                                             resourceManager
                                                     .addResourcetoFavorites(resource);
+                                            resourceManager
+                                                    .addResourceURItoFavorites(resource);
                                         } else {
                                             resourceManager
                                                     .removeResourceFromFavorites(resource);
@@ -422,6 +351,9 @@ public class ResourceManagerView extends ViewPart {
                         for (int index = 0; index < items.length; index++) {
                             items[index].dispose();
                         }
+
+                        setupUploadRamlMenuItem(menu);
+
                         MenuItem addToFavMenuItem = new MenuItem(menu, SWT.NONE);
                         addToFavMenuItem.setText("Remove from favorites");
                         addToFavMenuItem
@@ -447,6 +379,73 @@ public class ResourceManagerView extends ViewPart {
         }
     }
 
+    private void setupUploadRamlMenuItem(Menu menu) {
+        MenuItem uploadRAMLItem = new MenuItem(menu, SWT.NONE);
+        uploadRAMLItem.setText("Upload RAML Configuration");
+        uploadRAMLItem.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                // Open the RAML configuration dialog if
+                // RAML file is not yet uploaded for the
+                // currently selected resource
+                RemoteResource resource = resourceManager
+                        .getCurrentResourceInSelection();
+                if (null == resource) {
+                    return;
+                }
+                if (resource.isConfigUploaded()) {
+                    boolean answer = MessageDialog
+                            .openQuestion(
+                                    Display.getDefault().getActiveShell(),
+                                    "Upload Another RAML",
+                                    "This resource is already configured with RAML.\n"
+                                            + "Do you want to upload a new configuration?");
+                    if (!answer) {
+                        return;
+                    }
+                }
+                // Open the dialog in a separate
+                // UI thread.
+                PlatformUI.getWorkbench().getDisplay().syncExec(new Thread() {
+                    @Override
+                    public void run() {
+                        LoadRAMLDialog ramlDialog = new LoadRAMLDialog(Display
+                                .getDefault().getActiveShell());
+                        if (ramlDialog.open() != Window.OK) {
+                            return;
+                        }
+                        String configFilePath = ramlDialog.getConfigFilePath();
+                        if (null == configFilePath
+                                || configFilePath.length() < 1) {
+                            MessageDialog.openInformation(Display.getDefault()
+                                    .getActiveShell(),
+                                    "Invalid RAML Config path",
+                                    "Configuration file path is invalid.");
+                            return;
+                        }
+                        try {
+                            boolean result = resourceManager.setConfigFilePath(
+                                    resourceManager
+                                            .getCurrentResourceInSelection(),
+                                    configFilePath);
+                            if (!result) {
+                                MessageDialog
+                                        .openInformation(Display.getDefault()
+                                                .getActiveShell(),
+                                                "Operation failed",
+                                                "Failed to obtain the details from the given RAML.");
+                            }
+                        } catch (SimulatorException e) {
+                            MessageDialog.openInformation(Display.getDefault()
+                                    .getActiveShell(), "Invalid RAML",
+                                    "Given configuration file is invalid.");
+                        }
+                    }
+                });
+            }
+        });
+    }
+
     private void addUIListeners() {
         findResButton.addSelectionListener(new SelectionAdapter() {
             @Override
@@ -467,38 +466,37 @@ public class ResourceManagerView extends ViewPart {
 
                             Set<String> searchTypes = findWizard
                                     .getSearchTypes();
-                            if (null != searchTypes) {
-                                System.out.println(searchTypes);
-                                // Call native method to clear existing
-                                // resources of
-                                // the given search types.
-                                resourceManager.deleteResources(searchTypes);
-
-                                // Update the tree
-                                treeViewer.refresh();
-                                favTreeViewer.refresh();
-
-                                // Call native method to find Resources
-                                boolean result = resourceManager
-                                        .findResourceRequest(searchTypes);
-                                if (result) {
-                                    searchUIOperation(false);
-                                } else {
-                                    MessageDialog
-                                            .openError(Display.getDefault()
-                                                    .getActiveShell(),
-                                                    "Find Resource status",
-                                                    "Operation failed due to some problems in core layer.");
-                                }
-
-                                // Store this information for refresh
-                                // functionality
-                                resourceManager
-                                        .setLastKnownSearchTypes(searchTypes);
+                            // Delete cached details of resources based on the
+                            // given search types.
+                            // If there are no resource types to search, then
+                            // all resources
+                            // will be deleted.
+                            resourceManager.deleteResources(searchTypes);
+
+                            // Update the tree
+                            treeViewer.refresh();
+                            favTreeViewer.refresh();
 
-                                // Change the refresh visibility
-                                refreshButton.setEnabled(true);
+                            // Call native method to find Resources
+                            boolean result = resourceManager
+                                    .findResourceRequest(searchTypes);
+                            if (result) {
+                                searchUIOperation(false);
+                            } else {
+                                MessageDialog
+                                        .openError(Display.getDefault()
+                                                .getActiveShell(),
+                                                "Find Resource status",
+                                                "Operation failed due to some problems in core layer.");
                             }
+
+                            // Store this information for refresh
+                            // functionality
+                            resourceManager
+                                    .setLastKnownSearchTypes(searchTypes);
+
+                            // Change the refresh visibility
+                            refreshButton.setEnabled(true);
                         }
                     }
                 });
@@ -510,13 +508,12 @@ public class ResourceManagerView extends ViewPart {
             public void widgetSelected(SelectionEvent e) {
                 Set<String> searchTypes = resourceManager
                         .getLastKnownSearchTypes();
-                if (null == searchTypes) {
-                    return;
-                }
                 setFoundResource(false);
 
-                // Call native method to clear existing resources of the given
-                // search types.
+                // Delete cached details of resources based on the given search
+                // types.
+                // If there are no resource types to search, then all resources
+                // will be deleted.
                 resourceManager.deleteResources(searchTypes);
 
                 // Update the tree
@@ -554,8 +551,6 @@ public class ResourceManagerView extends ViewPart {
                     if (null == resource) {
                         return;
                     }
-                    System.out.println("Selected resource: "
-                            + resource.getResourceURI());
                     resourceManager.resourceSelectionChanged(resource);
                 }
             }
@@ -608,7 +603,6 @@ public class ResourceManagerView extends ViewPart {
                         try {
                             Thread.sleep(Constants.FIND_RESOURCES_TIMEOUT * 1000);
                         } catch (InterruptedException e) {
-                            System.out.println("Interrupted during sleep.");
                             return;
                         }
 
@@ -649,14 +643,15 @@ public class ResourceManagerView extends ViewPart {
     }
 
     private void addManagerListeners() {
-        resourceManager.addFindresourceUIListener(findListener);
+        UiListenerHandler.getInstance().addFindresourceUIListener(findListener);
     }
 
     @Override
     public void dispose() {
         // Unregister the listener
         if (null != findListener) {
-            resourceManager.removeFindresourceUIListener(findListener);
+            UiListenerHandler.getInstance().removeFindresourceUIListener(
+                    findListener);
             resourceManager.resourceSelectionChanged(null);
         }
         super.dispose();
@@ -664,8 +659,6 @@ public class ResourceManagerView extends ViewPart {
 
     @Override
     public void setFocus() {
-        // TODO Auto-generated method stub
-
     }
 
     public synchronized void setFoundResource(boolean value) {
@@ -695,7 +688,6 @@ class TreeContentProvider implements ITreeContentProvider {
 
     @Override
     public Object[] getElements(Object parent) {
-        System.out.println("Inside getElements()");
         List<RemoteResource> resourceList = Activator.getDefault()
                 .getResourceManager().getResourceList();
         return resourceList.toArray();
@@ -731,7 +723,6 @@ class FavTreeContentProvider implements ITreeContentProvider {
 
     @Override
     public Object[] getElements(Object parent) {
-        System.out.println("Inside getElements()");
         List<RemoteResource> resourceList = Activator.getDefault()
                 .getResourceManager().getFavResourceList();
         return resourceList.toArray();
@@ -753,14 +744,11 @@ class TreeLabelProvider extends LabelProvider {
     @Override
     public String getText(Object element) {
         RemoteResource resource = (RemoteResource) element;
-        return resource.getResourceURI();
+        return resource.getRemoteResourceRef().getURI();
     }
 
     @Override
     public Image getImage(Object element) {
-        RemoteResource resource = (RemoteResource) element;
-        ResourceManager resourceManager = Activator.getDefault()
-                .getResourceManager();
-        return resourceManager.getImage(resource.getResourceURI());
+        return null;
     }
 }
\ No newline at end of file
index c9626e2..b1f211b 100644 (file)
 
 package oic.simulator.clientcontroller.view.dialogs;
 
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Map;
-
-import oic.simulator.clientcontroller.manager.LogManager;
-
 import org.eclipse.jface.dialogs.TrayDialog;
 import org.eclipse.swt.SWT;
 import org.eclipse.swt.events.SelectionAdapter;
@@ -34,6 +28,12 @@ import org.eclipse.swt.widgets.Control;
 import org.eclipse.swt.widgets.Group;
 import org.eclipse.swt.widgets.Shell;
 
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Map;
+
+import oic.simulator.clientcontroller.manager.LogManager;
+
 /**
  * This class shows a dialog for filtering logs based on severity levels.
  */
index 6316674..7a46d7e 100644 (file)
 
 package oic.simulator.clientcontroller.view.dialogs;
 
-import java.util.HashSet;
-import java.util.Set;
-
-import oic.simulator.clientcontroller.utils.Constants;
-
 import org.eclipse.jface.wizard.WizardPage;
 import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.CCombo;
 import org.eclipse.swt.events.ModifyEvent;
 import org.eclipse.swt.events.ModifyListener;
 import org.eclipse.swt.events.SelectionAdapter;
@@ -36,29 +30,29 @@ import org.eclipse.swt.widgets.Group;
 import org.eclipse.swt.widgets.Label;
 import org.eclipse.swt.widgets.Text;
 
+import java.util.Set;
+
+import oic.simulator.clientcontroller.utils.Constants;
+import oic.simulator.clientcontroller.utils.Utility;
+
 /**
  * This class shows UI for finding resources.
  */
 public class FindResourcePage extends WizardPage {
 
-    private Button      stdResTypeRbtn;
-    private CCombo      resourceTypeCmb;
-    private Button      cusResTypeRbtn;
+    private Button      allRbtn;
+    private Button      resTypeRbtn;
     private Text        resTypeTxt;
-    private Label       stdRTypeLbl;
-    private Label       cusRTypeLbl;
+    private Label       resTypeLbl;
 
     private Set<String> typesToSearch;
 
-    private String      dummyRType;
-
     protected FindResourcePage() {
         super("Find Resource");
     }
 
     @Override
     public void createControl(Composite parent) {
-        setPageComplete(false);
         setTitle(Constants.FIND_PAGE_TITLE);
         setMessage(Constants.FIND_PAGE_MESSAGE);
 
@@ -69,7 +63,7 @@ public class FindResourcePage extends WizardPage {
         compContent.setLayoutData(gd);
 
         Group configGroup = new Group(compContent, SWT.NONE);
-        gridLayout = new GridLayout(1, false);
+        gridLayout = new GridLayout(2, false);
         gridLayout.verticalSpacing = 10;
         gridLayout.marginTop = 5;
         configGroup.setLayout(gridLayout);
@@ -79,41 +73,26 @@ public class FindResourcePage extends WizardPage {
         configGroup.setLayoutData(gd);
         configGroup.setText("Resource Type");
 
-        stdResTypeRbtn = new Button(configGroup, SWT.RADIO);
-        stdResTypeRbtn.setText("Standard OIC Resources");
-
-        Composite stdConfigComp = new Composite(configGroup, SWT.NONE);
-        stdConfigComp.setLayout(new GridLayout(2, false));
+        allRbtn = new Button(configGroup, SWT.RADIO);
+        allRbtn.setText("All");
         gd = new GridData();
-        gd.horizontalAlignment = SWT.FILL;
-        gd.grabExcessHorizontalSpace = true;
-        stdConfigComp.setLayoutData(gd);
-
-        stdRTypeLbl = new Label(stdConfigComp, SWT.NONE);
-        stdRTypeLbl.setText("ResourceType:");
-        stdRTypeLbl.setEnabled(false);
+        gd.horizontalSpan = 2;
+        allRbtn.setLayoutData(gd);
+        allRbtn.setSelection(true);
 
-        resourceTypeCmb = new CCombo(stdConfigComp, SWT.READ_ONLY | SWT.BORDER);
+        resTypeRbtn = new Button(configGroup, SWT.RADIO);
+        resTypeRbtn.setText("Specific Resource types (seperated by commas)");
         gd = new GridData();
-        gd.widthHint = 150;
-        resourceTypeCmb.setLayoutData(gd);
-        resourceTypeCmb.setEnabled(false);
+        gd.horizontalSpan = 2;
+        resTypeRbtn.setLayoutData(gd);
 
-        cusResTypeRbtn = new Button(configGroup, SWT.RADIO);
-        cusResTypeRbtn.setText("Custom Resources");
+        resTypeLbl = new Label(configGroup, SWT.NONE);
+        resTypeLbl.setText("Resource Types:");
+        resTypeLbl.setEnabled(false);
 
-        Composite cusConfigComp = new Composite(configGroup, SWT.NONE);
-        cusConfigComp.setLayout(new GridLayout(2, false));
-        gd = new GridData();
-        gd.horizontalAlignment = SWT.FILL;
-        gd.grabExcessHorizontalSpace = true;
-        cusConfigComp.setLayoutData(gd);
-
-        cusRTypeLbl = new Label(cusConfigComp, SWT.NONE);
-        cusRTypeLbl.setText("Enter ResourceType:");
-        cusRTypeLbl.setEnabled(false);
-
-        resTypeTxt = new Text(cusConfigComp, SWT.BORDER);
+        resTypeTxt = new Text(configGroup, SWT.BORDER);
+        resTypeTxt.setToolTipText("Ex: sample.light, hall.fridge");
+        resTypeTxt.setMessage("Ex: sample.light, hall.fridge");
         gd = new GridData();
         gd.minimumWidth = 200;
         gd.horizontalAlignment = SWT.FILL;
@@ -121,143 +100,58 @@ public class FindResourcePage extends WizardPage {
         resTypeTxt.setLayoutData(gd);
         resTypeTxt.setEnabled(false);
 
-        populateDataInUI();
-
         addUIListeners();
 
         setControl(compContent);
     }
 
-    private void populateDataInUI() {
-        // Populate Standard resource-types in Combo
-        populateResourceTypeCombo();
-    }
-
-    private void populateResourceTypeCombo() {
-        /*
-         * List<String> configList; configList =
-         * Activator.getDefault().getManager().getResourceConfigurationList();
-         * if(null != configList) { Iterator<String> itr =
-         * configList.iterator(); while(itr.hasNext()) {
-         * resourceTypeCmb.add(itr.next()); } }
-         */
-
-        // TODO: Temporarily adding a resourceType for testing
-        // resourceTypeCmb.add("oic.r.light");
-        // Currently for standard resources we are using resource type as sample.light.
-        resourceTypeCmb.add("sample.light");
-
-        // By default, selecting the first item in the resourceType combo
-        if (resourceTypeCmb.getItemCount() > 0) {
-            resourceTypeCmb.select(0);
-            // TODO: Get the RAML configuration file path of the selected
-            // resource
-            // configFilePath =
-            // Activator.getManager().getConfigFilePath(resourceTypeCmb.getItem(0));
-        }
-    }
-
     private void addUIListeners() {
-        stdResTypeRbtn.addSelectionListener(new SelectionAdapter() {
+        allRbtn.addSelectionListener(new SelectionAdapter() {
             @Override
             public void widgetSelected(SelectionEvent e) {
-                // Clear the existing items from the search list
-                if (null != typesToSearch)
-                    typesToSearch.clear();
-
-                // Set the configFilePath to the first item in the combo
-                if (resourceTypeCmb.getItemCount() > 0) {
-                    resourceTypeCmb.select(0);
-                    addSearchType(resourceTypeCmb.getText());
-                }
-
-                setPageComplete(isSelectionDone());
-
+                typesToSearch = null;
+                setPageComplete(true);
                 // Change the visibility of widgets
-                changeVisibility(true);
+                changeVisibility(false);
             }
         });
 
-        cusResTypeRbtn.addSelectionListener(new SelectionAdapter() {
+        resTypeRbtn.addSelectionListener(new SelectionAdapter() {
             @Override
             public void widgetSelected(SelectionEvent e) {
-                // Clear the existing items from the search list
-                if (null != typesToSearch)
-                    typesToSearch.clear();
-
-                addSearchType(resTypeTxt.getText());
-
-                setPageComplete(isSelectionDone());
+                String typeText = resTypeTxt.getText();
+                if (null != typeText && typeText.length() > 0) {
+                    typesToSearch = Utility.splitStringByComma(typeText);
+                }
 
+                if (null != typesToSearch && typesToSearch.size() > 0) {
+                    setPageComplete(true);
+                } else {
+                    setPageComplete(false);
+                }
                 // Change the visibility of widgets
-                changeVisibility(false);
-
+                changeVisibility(true);
                 resTypeTxt.setFocus();
             }
         });
 
-        resourceTypeCmb.addSelectionListener(new SelectionAdapter() {
-            @Override
-            public void widgetSelected(SelectionEvent e) {
-                int index = resourceTypeCmb.getSelectionIndex();
-                if (index < 0) {
-                    return;
-                }
-                String resourceType = resourceTypeCmb.getItem(index);
-                addSearchType(resourceType);
-                setPageComplete(isSelectionDone());
-            }
-        });
-
         resTypeTxt.addModifyListener(new ModifyListener() {
             @Override
             public void modifyText(ModifyEvent e) {
-                String resourceType = resTypeTxt.getText();
-                if (null != dummyRType) {
-                    removeSearchType(dummyRType);
+                String typeText = resTypeTxt.getText();
+                typesToSearch = Utility.splitStringByComma(typeText);
+                if (null != typesToSearch && typesToSearch.size() > 0) {
+                    setPageComplete(true);
+                } else {
+                    setPageComplete(false);
                 }
-                dummyRType = resourceType;
-                addSearchType(resourceType);
-                setPageComplete(isSelectionDone());
             }
         });
     }
 
     private void changeVisibility(boolean standard) {
-        stdRTypeLbl.setEnabled(standard);
-        resourceTypeCmb.setEnabled(standard);
-        cusRTypeLbl.setEnabled(!standard);
-        resTypeTxt.setEnabled(!standard);
-    }
-
-    private boolean isSelectionDone() {
-        if (null == typesToSearch || typesToSearch.size() < 1) {
-            return false;
-        }
-        return true;
-    }
-
-    private void addSearchType(String resourceType) {
-        if (null == resourceType)
-            return;
-        resourceType = resourceType.trim();
-        if (resourceType.length() < 1) {
-            return;
-        }
-        if (null == typesToSearch) {
-            typesToSearch = new HashSet<String>();
-        }
-        typesToSearch.add(resourceType);
-    }
-
-    private void removeSearchType(String resourceType) {
-        if (null == resourceType || null == typesToSearch)
-            return;
-        resourceType = resourceType.trim();
-        if (resourceType.length() < 1) {
-            return;
-        }
-        typesToSearch.remove(resourceType);
+        resTypeLbl.setEnabled(standard);
+        resTypeTxt.setEnabled(standard);
     }
 
     public Set<String> getSearchTypes() {
index 9c70526..13dd429 100644 (file)
 
 package oic.simulator.clientcontroller.view.dialogs;
 
-import java.net.URL;
-import java.util.Set;
-
-import oic.simulator.clientcontroller.Activator;
-
 import org.eclipse.core.runtime.FileLocator;
 import org.eclipse.core.runtime.IPath;
 import org.eclipse.core.runtime.Path;
 import org.eclipse.jface.resource.ImageDescriptor;
 import org.eclipse.jface.wizard.Wizard;
 
+import java.net.URL;
+import java.util.Set;
+
+import oic.simulator.clientcontroller.Activator;
+
 /**
  * This class creates a UI wizard for find resource operation.
  */
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/GetRequestDialog.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/GetRequestDialog.java
new file mode 100644 (file)
index 0000000..c134e7b
--- /dev/null
@@ -0,0 +1,193 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.clientcontroller.view.dialogs;
+
+import org.eclipse.jface.dialogs.IDialogConstants;
+import org.eclipse.jface.dialogs.TitleAreaDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Vector;
+
+import oic.simulator.clientcontroller.Activator;
+import oic.simulator.clientcontroller.remoteresource.RemoteResource;
+import oic.simulator.clientcontroller.utils.Constants;
+import oic.simulator.clientcontroller.utils.Utility;
+
+/**
+ * This dialog is used for generating a PUT request.
+ */
+public class GetRequestDialog extends TitleAreaDialog {
+    private Text                queryTxt;
+    private Combo               ifTypesCmb;
+
+    private String              otherFilters;
+    private String              ifType;
+
+    private Map<String, String> ifTypes;
+
+    public GetRequestDialog(Shell parentShell) {
+        super(parentShell);
+    }
+
+    @Override
+    public void create() {
+        super.create();
+        setTitle("Generate GET Request");
+        setMessage("Dialog which takes query filters and generates a GET request.");
+    }
+
+    @Override
+    protected Control createDialogArea(Composite parent) {
+        Composite compLayout = (Composite) super.createDialogArea(parent);
+
+        Group paramsGrp = new Group(compLayout, SWT.NONE);
+        paramsGrp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+        GridLayout layout = new GridLayout(2, false);
+        layout.verticalSpacing = 10;
+        layout.marginTop = 10;
+        paramsGrp.setLayout(layout);
+
+        Label ifTypeLbl = new Label(paramsGrp, SWT.NONE);
+        ifTypeLbl.setText("Interface Type");
+
+        ifTypesCmb = new Combo(paramsGrp, SWT.NULL);
+        GridData gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        ifTypesCmb.setLayoutData(gd);
+        ifTypesCmb.addModifyListener(new ModifyListener() {
+            @Override
+            public void modifyText(ModifyEvent e) {
+                ifType = ifTypesCmb.getText();
+            }
+        });
+
+        RemoteResource resource = Activator.getDefault().getResourceManager()
+                .getCurrentResourceInSelection();
+
+        // Set the interface types in combo box.
+        Map<String, String> ifTypes = Utility.getResourceInterfaces();
+        this.ifTypes = new HashMap<String, String>();
+        String key;
+        for (Map.Entry<String, String> entry : ifTypes.entrySet()) {
+            key = entry.getValue() + " (" + entry.getKey() + ")";
+            this.ifTypes.put(key, entry.getKey());
+            ifTypesCmb.add(key);
+        }
+
+        // Select the default value to be shown in the interface types combo.
+        Vector<String> ifTypesSupportedByResource = resource
+                .getRemoteResourceRef().getResourceInterfaces();
+        if (null != ifTypesSupportedByResource) {
+            int index = -1;
+            if (ifTypesSupportedByResource
+                    .contains(Constants.BASELINE_INTERFACE)
+                    && ifTypes.containsKey(Constants.BASELINE_INTERFACE)) {
+                // Baseline interface is given preference to be shown in the if
+                // types combo.
+                String value = ifTypes.get(Constants.BASELINE_INTERFACE);
+                index = ifTypesCmb.indexOf(value + " ("
+                        + Constants.BASELINE_INTERFACE + ")");
+                if (index != -1)
+                    ifTypesCmb.select(index);
+            }
+            if (index == -1) {
+                // Baseline interface is not selected so selecting some other
+                // interface supported by the resource.
+                Iterator<String> itr = ifTypesSupportedByResource.iterator();
+                while (itr.hasNext() && index == -1) {
+                    key = itr.next();
+                    if (ifTypes.containsKey(key)) {
+                        String value = ifTypes.get(key);
+                        index = ifTypesCmb.indexOf(value + " (" + key + ")");
+                        if (index != -1) {
+                            ifTypesCmb.select(index);
+                            break;
+                        }
+                    }
+                }
+                if (index == -1 && !ifTypesSupportedByResource.isEmpty()) {
+                    // Resource has custom interfaces.
+                    ifTypesCmb.setText(ifTypesSupportedByResource.get(0));
+                }
+            }
+        }
+
+        Label otherFilterLbl = new Label(paramsGrp, SWT.NONE);
+        otherFilterLbl.setText("Other filters");
+
+        queryTxt = new Text(paramsGrp, SWT.BORDER);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        queryTxt.setLayoutData(gd);
+        queryTxt.addModifyListener(new ModifyListener() {
+            @Override
+            public void modifyText(ModifyEvent e) {
+                otherFilters = queryTxt.getText();
+            }
+        });
+
+        return compLayout;
+    }
+
+    @Override
+    protected boolean isResizable() {
+        return true;
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+
+    @Override
+    protected Button createButton(Composite parent, int id, String label,
+            boolean defaultButton) {
+        if (id == IDialogConstants.OK_ID) {
+            label = "GET";
+        }
+        return super.createButton(parent, id, label, defaultButton);
+    }
+
+    public String getOtherFilters() {
+        return otherFilters;
+    }
+
+    public String getIfType() {
+        if (ifTypes.containsKey(ifType)) {
+            return ifTypes.get(ifType);
+        }
+        return ifType;
+    }
+
+}
index d19e1d4..8fa457b 100644 (file)
@@ -16,8 +16,7 @@
 
 package oic.simulator.clientcontroller.view.dialogs;
 
-import oic.simulator.clientcontroller.utils.Constants;
-
+import org.eclipse.jface.dialogs.MessageDialog;
 import org.eclipse.jface.dialogs.TitleAreaDialog;
 import org.eclipse.swt.SWT;
 import org.eclipse.swt.events.SelectionAdapter;
@@ -33,6 +32,16 @@ import org.eclipse.swt.widgets.Shell;
 import org.eclipse.swt.widgets.Text;
 import org.eclipse.ui.PlatformUI;
 
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.util.Date;
+
+import org.oic.simulator.ILogger.Level;
+
+import oic.simulator.clientcontroller.Activator;
+import oic.simulator.clientcontroller.utils.Constants;
+import oic.simulator.clientcontroller.utils.Utility;
+
 /**
  * This dialog is used for loading the RAML file.
  */
@@ -100,10 +109,11 @@ public class LoadRAMLDialog extends TitleAreaDialog {
                         .getWorkbench().getDisplay().getActiveShell(), SWT.NONE);
                 fileDialog
                         .setFilterExtensions(Constants.BROWSE_RAML_FILTER_EXTENSIONS);
-                configFilePath = fileDialog.open();
-                if (null == configFilePath) {
-                    System.out.println("Config file path is null");
+                String path = fileDialog.open();
+                if (null == path) {
                     configFilePath = "";
+                } else {
+                    configFilePath = path;
                 }
                 locationTxt.setText(configFilePath);
             }
@@ -115,6 +125,40 @@ public class LoadRAMLDialog extends TitleAreaDialog {
     }
 
     @Override
+    protected void okPressed() {
+        configFilePath = locationTxt.getText();
+        if (null == configFilePath) {
+            return;
+        }
+
+        FileInputStream fileStream = null;
+        try {
+            fileStream = new FileInputStream(configFilePath);
+        } catch (Exception e) {
+            MessageDialog
+                    .openError(getShell(), "Invalid File",
+                            "File doesn't exist. Either the file path or file name is invalid.");
+            return;
+        } finally {
+            if (null != fileStream) {
+                try {
+                    fileStream.close();
+                } catch (IOException e) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(),
+                                    new Date(),
+                                    "There is an error while closing the file stream.\n"
+                                            + Utility.getSimulatorErrorString(
+                                                    e, null));
+                }
+            }
+        }
+        close();
+    }
+
+    @Override
     public boolean isHelpAvailable() {
         return false;
     }
index 12d0c59..491c74c 100644 (file)
@@ -16,9 +16,6 @@
 
 package oic.simulator.clientcontroller.view.dialogs;
 
-import java.text.DateFormat;
-import java.util.Date;
-
 import org.eclipse.jface.dialogs.Dialog;
 import org.eclipse.jface.dialogs.IDialogConstants;
 import org.eclipse.swt.SWT;
@@ -34,6 +31,9 @@ import org.eclipse.swt.widgets.Label;
 import org.eclipse.swt.widgets.Shell;
 import org.eclipse.swt.widgets.Text;
 
+import java.text.DateFormat;
+import java.util.Date;
+
 /**
  * This class shows detailed information about a log. The dialog will be opened
  * on double-clicking a log entry in the log view.
@@ -108,7 +108,8 @@ public class LogDetailsDialog extends Dialog {
         gd.grabExcessHorizontalSpace = true;
         l5.setLayoutData(gd);
 
-        new Label(container, SWT.NONE); // separator
+        Label seperator = new Label(container, SWT.NONE); // separator
+        seperator.setText("");
 
         Label l6 = new Label(container, SWT.NONE);
         l6.setText("Message details");
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/ModelArrayAddItemDialog.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/ModelArrayAddItemDialog.java
new file mode 100644 (file)
index 0000000..58c110b
--- /dev/null
@@ -0,0 +1,295 @@
+/*
+ * 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 oic.simulator.clientcontroller.view.dialogs;
+
+import org.eclipse.jface.dialogs.TitleAreaDialog;
+import org.eclipse.jface.viewers.ILabelProviderListener;
+import org.eclipse.jface.viewers.ITableLabelProvider;
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.jface.viewers.TreeViewerColumn;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeColumn;
+
+import java.util.Map;
+
+import org.oic.simulator.AttributeValue.ValueType;
+import org.oic.simulator.SimulatorResourceAttribute;
+
+import oic.simulator.clientcontroller.Activator;
+import oic.simulator.clientcontroller.manager.ResourceManager;
+import oic.simulator.clientcontroller.remoteresource.AttributeElement;
+import oic.simulator.clientcontroller.remoteresource.RemoteResource;
+import oic.simulator.clientcontroller.remoteresource.ResourceRepresentation;
+import oic.simulator.clientcontroller.utils.Utility;
+import oic.simulator.clientcontroller.view.AttributeEditingSupport;
+
+/**
+ * This class manages and shows the automation settings dialog from the
+ * attribute view.
+ */
+public class ModelArrayAddItemDialog extends TitleAreaDialog {
+
+    private TreeViewer              attViewer;
+
+    private AttributeEditingSupport attributeEditor;
+
+    private final String[]          attTblHeaders  = { "Attribute Name",
+            "Attribute Value"                     };
+    private final Integer[]         attTblColWidth = { 200, 300 };
+
+    private ResourceManager         resourceManager;
+
+    private ResourceRepresentation  representation;
+
+    private TitleAreaDialog         dialog;
+
+    public ModelArrayAddItemDialog(Shell parentShell, TitleAreaDialog dialog,
+            ResourceRepresentation representation) {
+        super(parentShell);
+        resourceManager = Activator.getDefault().getResourceManager();
+        this.dialog = dialog;
+        this.representation = representation;
+    }
+
+    @Override
+    public void create() {
+        super.create();
+        setTitle("Add Items To Complex Array");
+        setMessage("Add one or more items in the complex array type attribute");
+    }
+
+    @Override
+    protected Control createDialogArea(Composite parent) {
+        Composite compLayout = (Composite) super.createDialogArea(parent);
+
+        compLayout.setLayout(new GridLayout());
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        compLayout.setLayoutData(gd);
+
+        Group attGroup = new Group(compLayout, SWT.NONE);
+        attGroup.setLayout(new GridLayout());
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        attGroup.setLayoutData(gd);
+        attGroup.setText("Attributes");
+
+        Tree addressTree = new Tree(attGroup, SWT.SINGLE | SWT.BORDER
+                | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
+        addressTree.setHeaderVisible(true);
+
+        attViewer = new TreeViewer(addressTree);
+
+        createAttributeColumns(attViewer);
+
+        // make lines and header visible
+        Tree tree = attViewer.getTree();
+        tree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+        tree.setHeaderVisible(true);
+        tree.setLinesVisible(true);
+
+        attViewer.setContentProvider(new AttributeContentProvider());
+        attViewer.setLabelProvider(new AttributeLabelProvider());
+
+        // Check whether there is any resource selected already
+        RemoteResource resource = resourceManager
+                .getCurrentResourceInSelection();
+        if (resource != null) {
+            attViewer.setInput(representation);
+            attViewer.expandAll();
+        }
+
+        return compLayout;
+    }
+
+    public void createAttributeColumns(TreeViewer viewer) {
+        Tree tree = viewer.getTree();
+
+        attributeEditor = new AttributeEditingSupport();
+
+        TreeColumn attName = new TreeColumn(tree, SWT.NONE);
+        attName.setWidth(attTblColWidth[0]);
+        attName.setText(attTblHeaders[0]);
+
+        TreeColumn attValue = new TreeColumn(tree, SWT.NONE);
+        attValue.setWidth(attTblColWidth[1]);
+        attValue.setText(attTblHeaders[1]);
+
+        TreeViewerColumn attValueVwrCol = new TreeViewerColumn(attViewer,
+                attValue);
+        attValueVwrCol.setEditingSupport(attributeEditor
+                .createAttributeValueEditor(attViewer, dialog));
+
+        addColumnListeners();
+    }
+
+    private void addColumnListeners() {
+        TreeColumn[] columns = attViewer.getTree().getColumns();
+        for (TreeColumn column : columns) {
+            column.addSelectionListener(new SelectionAdapter() {
+                @Override
+                public void widgetSelected(SelectionEvent e) {
+                    // Refreshing the viewer. If combo list is open,
+                    // then click events on other parts of the view or outside
+                    // the combo should hide the editor.
+                    // Refreshing the viewer hides the combo and other editors
+                    // which are active.
+                    attViewer.refresh();
+                }
+            });
+        }
+    }
+
+    private static class AttributeContentProvider implements
+            ITreeContentProvider {
+
+        @Override
+        public void dispose() {
+        }
+
+        @Override
+        public void inputChanged(Viewer viewer, Object oldAttribute,
+                Object newAttribute) {
+        }
+
+        @Override
+        public Object[] getChildren(Object attribute) {
+            if (attribute instanceof AttributeElement) {
+                Map<String, AttributeElement> children = ((AttributeElement) attribute)
+                        .getChildren();
+                if (null != children) {
+                    return children.values().toArray();
+                }
+            }
+
+            return new Object[0];
+        }
+
+        @Override
+        public Object getParent(Object attribute) {
+            if (attribute instanceof AttributeElement)
+                return ((AttributeElement) attribute).getParent();
+            return null;
+        }
+
+        @Override
+        public boolean hasChildren(Object attribute) {
+            if (attribute instanceof AttributeElement)
+                return ((AttributeElement) attribute).hasChildren();
+            return false;
+        }
+
+        @Override
+        public Object[] getElements(Object resourceModel) {
+            if (resourceModel instanceof ResourceRepresentation) {
+                return ((ResourceRepresentation) resourceModel).getAttributes()
+                        .values().toArray();
+            }
+
+            return new Object[0];
+        }
+    }
+
+    private static class AttributeLabelProvider implements ITableLabelProvider {
+
+        @Override
+        public void addListener(ILabelProviderListener arg0) {
+        }
+
+        @Override
+        public void dispose() {
+        }
+
+        @Override
+        public boolean isLabelProperty(Object arg0, String arg1) {
+            return false;
+        }
+
+        @Override
+        public void removeListener(ILabelProviderListener arg0) {
+
+        }
+
+        @Override
+        public Image getColumnImage(Object element, int col) {
+            return null;
+        }
+
+        @Override
+        public String getColumnText(Object element, int column) {
+            if (element instanceof AttributeElement) {
+                AttributeElement attrElement = (AttributeElement) element;
+                switch (column) {
+                    case 0: // Attribute name column
+                    {
+                        SimulatorResourceAttribute attribute = attrElement
+                                .getSimulatorResourceAttribute();
+                        return attribute.name();
+                    }
+
+                    case 1: // Attribute value column
+                    {
+                        SimulatorResourceAttribute attribute = attrElement
+                                .getSimulatorResourceAttribute();
+
+                        if (attribute.value().typeInfo().mBaseType != ValueType.RESOURCEMODEL) {
+                            String value = Utility
+                                    .getAttributeValueAsString(attribute
+                                            .value());
+                            if (null == value) {
+                                value = "";
+                            }
+                            return value;
+                        }
+                        return null;
+                    }
+                }
+            }
+
+            return null;
+        }
+
+    }
+
+    @Override
+    protected Point getInitialSize() {
+        Point initialPoint = super.getInitialSize();
+        initialPoint.y += 100;
+        return initialPoint;
+    }
+
+    @Override
+    protected boolean isResizable() {
+        return true;
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+}
index 26c11b4..8d694bb 100644 (file)
 
 package oic.simulator.clientcontroller.view.dialogs;
 
-import java.util.List;
-
-import oic.simulator.clientcontroller.Activator;
-import oic.simulator.clientcontroller.remoteresource.PutPostAttributeModel;
-import oic.simulator.clientcontroller.utils.Constants;
-
 import org.eclipse.jface.dialogs.IDialogConstants;
+import org.eclipse.jface.dialogs.MessageDialog;
 import org.eclipse.jface.dialogs.TitleAreaDialog;
-import org.eclipse.jface.viewers.CellEditor;
-import org.eclipse.jface.viewers.CheckboxCellEditor;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.EditingSupport;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.ILabelProviderListener;
 import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StyledCellLabelProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.TextCellEditor;
+import org.eclipse.jface.viewers.ITableLabelProvider;
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.jface.viewers.TreeViewerColumn;
 import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerCell;
+import org.eclipse.jface.window.Window;
 import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.MenuAdapter;
+import org.eclipse.swt.events.MenuEvent;
 import org.eclipse.swt.events.ModifyEvent;
 import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
 import org.eclipse.swt.graphics.Image;
 import org.eclipse.swt.layout.GridData;
 import org.eclipse.swt.layout.GridLayout;
 import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Combo;
 import org.eclipse.swt.widgets.Composite;
 import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.swt.widgets.MenuItem;
+import org.eclipse.swt.widgets.MessageBox;
 import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.Text;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeColumn;
+import org.eclipse.swt.widgets.TreeItem;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+
+import org.oic.simulator.ArrayProperty;
+import org.oic.simulator.AttributeProperty;
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.AttributeValue.TypeInfo;
+import org.oic.simulator.AttributeValue.ValueType;
+import org.oic.simulator.ILogger.Level;
+import org.oic.simulator.ModelProperty;
+import org.oic.simulator.SimulatorResourceAttribute;
+import org.oic.simulator.SimulatorResourceModel;
+import org.oic.simulator.client.SimulatorRemoteResource.RequestType;
+
+import oic.simulator.clientcontroller.Activator;
+import oic.simulator.clientcontroller.remoteresource.AttributeElement;
+import oic.simulator.clientcontroller.remoteresource.RemoteResource;
+import oic.simulator.clientcontroller.remoteresource.ResourceRepresentation;
+import oic.simulator.clientcontroller.utils.Constants;
+import oic.simulator.clientcontroller.utils.Utility;
+import oic.simulator.clientcontroller.view.AttributeEditingSupport;
 
 /**
  * This dialog is used for generating a POST request.
  */
 public class PostRequestDialog extends TitleAreaDialog {
 
-    private TableViewer                 attTblViewer;
+    private TreeViewer              attViewer;
+    private Combo                   ifTypesCmb;
+
+    private String                  ifType;
+
+    private Map<String, String>     ifTypes;
+
+    private AttributeEditingSupport attributeEditor;
+
+    private ResourceRepresentation  updatedRepresentation;
 
-    private final String[]              attTblHeaders  = { "Name", "Value",
-            "Select"                                  };
-    private final Integer[]             attTblColWidth = { 200, 200, 50 };
+    private final String[]          attTblHeaders  = { "Name", "Value",
+            "Select"                              };
+    private final Integer[]         attTblColWidth = { 200, 200, 50 };
 
-    private List<PutPostAttributeModel> modelList      = null;
-    
-    public PostRequestDialog(Shell parentShell,
-            List<PutPostAttributeModel> modelList) {
+    public PostRequestDialog(Shell parentShell) {
         super(parentShell);
-        this.modelList = modelList;
     }
 
     @Override
@@ -78,220 +114,699 @@ public class PostRequestDialog extends TitleAreaDialog {
     @Override
     protected Control createDialogArea(Composite parent) {
         Composite compLayout = (Composite) super.createDialogArea(parent);
-        Composite container = new Composite(compLayout, SWT.NONE);
+
+        Composite rootContainer = new Composite(compLayout, SWT.NONE);
+        GridLayout layout = new GridLayout();
+        rootContainer.setLayout(layout);
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        rootContainer.setLayoutData(gd);
+
+        Group paramsGrp = new Group(rootContainer, SWT.NONE);
+        gd = new GridData();
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        gd.minimumHeight = 50;
+        paramsGrp.setLayoutData(gd);
+        layout = new GridLayout(2, false);
+        layout.verticalSpacing = 10;
+        layout.marginTop = 10;
+        paramsGrp.setLayout(layout);
+
+        Label ifTypeLbl = new Label(paramsGrp, SWT.NONE);
+        ifTypeLbl.setText("Interface Type");
+
+        ifTypesCmb = new Combo(paramsGrp, SWT.NULL);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        ifTypesCmb.setLayoutData(gd);
+        ifTypesCmb.addModifyListener(new ModifyListener() {
+            @Override
+            public void modifyText(ModifyEvent e) {
+                ifType = ifTypesCmb.getText();
+            }
+        });
+
+        RemoteResource resource = Activator.getDefault().getResourceManager()
+                .getCurrentResourceInSelection();
+
+        // Set the interface types in combo box.
+        Map<String, String> ifTypes = Utility.getResourceInterfaces();
+        this.ifTypes = new HashMap<String, String>();
+        String key;
+        for (Map.Entry<String, String> entry : ifTypes.entrySet()) {
+            key = entry.getValue() + " (" + entry.getKey() + ")";
+            this.ifTypes.put(key, entry.getKey());
+            ifTypesCmb.add(key);
+        }
+
+        // Select the default value to be shown in the interface types combo.
+        Vector<String> ifTypesSupportedByResource = resource
+                .getRemoteResourceRef().getResourceInterfaces();
+        if (null != ifTypesSupportedByResource) {
+            int index = -1;
+            if (ifTypesSupportedByResource
+                    .contains(Constants.BASELINE_INTERFACE)
+                    && ifTypes.containsKey(Constants.BASELINE_INTERFACE)) {
+                // Baseline interface is given preference to be shown in the if
+                // types combo.
+                String value = ifTypes.get(Constants.BASELINE_INTERFACE);
+                index = ifTypesCmb.indexOf(value + " ("
+                        + Constants.BASELINE_INTERFACE + ")");
+                if (index != -1)
+                    ifTypesCmb.select(index);
+            }
+            if (index == -1) {
+                // Baseline interface is not selected so selecting some other
+                // interface supported by the resource.
+                Iterator<String> itr = ifTypesSupportedByResource.iterator();
+                while (itr.hasNext() && index == -1) {
+                    key = itr.next();
+                    if (ifTypes.containsKey(key)) {
+                        String value = ifTypes.get(key);
+                        index = ifTypesCmb.indexOf(value + " (" + key + ")");
+                        if (index != -1) {
+                            ifTypesCmb.select(index);
+                            break;
+                        }
+                    }
+                }
+                if (index == -1 && !ifTypesSupportedByResource.isEmpty()) {
+                    // Resource has custom interfaces.
+                    ifTypesCmb.setText(ifTypesSupportedByResource.get(0));
+                }
+            }
+        }
+
+        Composite container = new Composite(rootContainer, SWT.NONE);
         container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-        GridLayout layout = new GridLayout(1, false);
+        layout = new GridLayout(1, false);
         layout.verticalSpacing = 10;
         layout.marginTop = 10;
         container.setLayout(layout);
 
-        createTableViewer(container);
+        createTreeViewer(container);
+
+        // Clone the resource model for maintaining a local copy of attributes
+        // for POST requests.
+        SimulatorResourceModel resourceModel = null;
+        try {
+            AttributeValue attValue = Utility
+                    .cloneAttributeValue(new AttributeValue(resource
+                            .getResourceModelRef()));
+            if (null != attValue)
+                resourceModel = (SimulatorResourceModel) attValue.get();
+        } catch (Exception e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "There is an error while forming an instance of the attribute value.\n"
+                                    + Utility.getSimulatorErrorString(e, null));
+        }
+
+        if (null == resourceModel) {
+            // Failed to clone. So taking the base copy and continuing the
+            // operation.
+            resourceModel = resource.getResourceModelRef();
+        }
+
+        updatedRepresentation = new ResourceRepresentation(resourceModel);
+
+        if (resource.isConfigUploaded()) {
+            try {
+                // Request Type needs to be changed to PUT.
+                updatedRepresentation.updateAttributeProperties(resource
+                        .getRequestModels().get(RequestType.POST),
+                        resourceModel);
+            } catch (Exception e) {
+                Activator
+                        .getDefault()
+                        .getLogManager()
+                        .log(Level.ERROR.ordinal(),
+                                new Date(),
+                                "There is an error while forming an instance of the attribute value.\n"
+                                        + Utility.getSimulatorErrorString(e,
+                                                null));
+            }
+        }
+
+        attViewer.setInput(updatedRepresentation);
 
-        attTblViewer.setInput(modelList.toArray());
+        attViewer.expandAll();
 
         return compLayout;
     }
 
-    private void createTableViewer(Composite parent) {
-        attTblViewer = new TableViewer(parent, SWT.SINGLE | SWT.H_SCROLL
-                | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
+    private void createTreeViewer(Composite parent) {
+        Tree addressTree = new Tree(parent, SWT.SINGLE | SWT.BORDER
+                | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
+        addressTree.setHeaderVisible(true);
+
+        attViewer = new TreeViewer(addressTree);
 
-        createAttributeColumns(attTblViewer);
+        createAttributeColumns(attViewer);
 
         // make lines and header visible
-        Table table = attTblViewer.getTable();
-        table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-        table.setHeaderVisible(true);
-        table.setLinesVisible(true);
+        Tree tree = attViewer.getTree();
+        tree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+        tree.setHeaderVisible(true);
+        tree.setLinesVisible(true);
 
-        attTblViewer.setContentProvider(new AttributeContentProvider());
+        attViewer.setContentProvider(new AttributeContentProvider());
+        attViewer.setLabelProvider(new AttributeLabelProvider());
     }
 
-    public void createAttributeColumns(TableViewer tableViewer) {
+    public void createAttributeColumns(TreeViewer viewer) {
+        Tree tree = viewer.getTree();
 
-        // attributeEditor = new AttributeEditingSupport();
+        attributeEditor = new AttributeEditingSupport();
 
-        TableViewerColumn attName = new TableViewerColumn(tableViewer, SWT.NONE);
-        attName.getColumn().setWidth(attTblColWidth[0]);
-        attName.getColumn().setText(attTblHeaders[0]);
-        attName.setLabelProvider(new StyledCellLabelProvider() {
-            @Override
-            public void update(ViewerCell cell) {
-                Object element = cell.getElement();
-                if (element instanceof PutPostAttributeModel) {
-                    PutPostAttributeModel entry = (PutPostAttributeModel) element;
-                    cell.setText(entry.getAttName());
-                }
+        TreeColumn attName = new TreeColumn(tree, SWT.NONE);
+        attName.setWidth(attTblColWidth[0]);
+        attName.setText(attTblHeaders[0]);
+
+        TreeColumn attValue = new TreeColumn(tree, SWT.NONE);
+        attValue.setWidth(attTblColWidth[1]);
+        attValue.setText(attTblHeaders[1]);
+        TreeViewerColumn attValueVwrCol = new TreeViewerColumn(attViewer,
+                attValue);
+        attValueVwrCol.setEditingSupport(attributeEditor
+                .createAttributeValueEditor(attViewer, this));
+
+        TreeColumn updateColumn = new TreeColumn(tree, SWT.NONE);
+        updateColumn.setWidth(attTblColWidth[2]);
+        updateColumn.setText(attTblHeaders[2]);
+        TreeViewerColumn updateVwrCol = new TreeViewerColumn(attViewer,
+                updateColumn);
+        updateVwrCol.setEditingSupport(attributeEditor
+                .createPostSelectionEditor(attViewer));
+
+        addMenuItems();
+    }
+
+    private void addMenuItems() {
+        if (null != attViewer) {
+            final Tree resourceTreeHead = attViewer.getTree();
+            if (null != resourceTreeHead) {
+                // Below code creates menu entries and shows them on right
+                // clicking a resource
+                final Menu menu = new Menu(resourceTreeHead);
+                resourceTreeHead.setMenu(menu);
+                menu.addMenuListener(new MenuAdapter() {
+                    @Override
+                    public void menuShown(MenuEvent e) {
+                        // Clear existing menu items
+                        MenuItem[] items = menu.getItems();
+                        for (int index = 0; index < items.length; index++) {
+                            items[index].dispose();
+                        }
+
+                        IStructuredSelection selection = ((IStructuredSelection) attViewer
+                                .getSelection());
+                        final AttributeElement attElement = (AttributeElement) selection
+                                .getFirstElement();
+                        if (null == attElement) {
+                            return;
+                        }
+
+                        // Check the type of attribute.
+                        SimulatorResourceAttribute attribute = attElement
+                                .getSimulatorResourceAttribute();
+                        if (null == attribute) {
+                            return;
+                        }
+
+                        AttributeValue value = attribute.value();
+                        if (null == value || null == value.get()) {
+                            return;
+                        }
+
+                        TypeInfo type = value.typeInfo();
+
+                        final Object parent = attElement.getParent();
+
+                        if ((type.mType == ValueType.ARRAY
+                                && type.mBaseType == ValueType.RESOURCEMODEL && type.mDepth == 1)
+                                && (null == parent || parent instanceof ResourceRepresentation)) {
+                            addMenuToOneDimensionalTopLevelModelAttributes(menu);
+                            return;
+                        }
+
+                        if (null != parent
+                                && parent instanceof AttributeElement) {
+                            Object grandParent = ((AttributeElement) parent)
+                                    .getParent();
+                            if (null == grandParent
+                                    || grandParent instanceof ResourceRepresentation) {
+                                AttributeElement parentElement = (AttributeElement) parent;
+
+                                // Check the type of attribute.
+                                SimulatorResourceAttribute parentAttribute = parentElement
+                                        .getSimulatorResourceAttribute();
+                                if (null != parentAttribute
+                                        && null != parentAttribute.value()
+                                        && null != parentAttribute.value()
+                                                .get()) {
+                                    AttributeValue parentValue = parentAttribute
+                                            .value();
+
+                                    TypeInfo parentType = parentValue
+                                            .typeInfo();
+                                    if (parentType.mType == ValueType.ARRAY
+                                            && parentType.mBaseType == ValueType.RESOURCEMODEL
+                                            && parentType.mDepth == 1) {
+                                        addDeleteMenuToArrayItemsOfOneDimensionalModelAttribute(
+                                                menu, attElement, parentElement);
+                                        return;
+                                    }
+                                }
+                            }
+                        }
+                    }
+                });
             }
-        });
+        }
+    }
 
-        TableViewerColumn attValue = new TableViewerColumn(tableViewer,
-                SWT.NONE);
-        attValue.getColumn().setWidth(attTblColWidth[1]);
-        attValue.getColumn().setText(attTblHeaders[1]);
-        attValue.setLabelProvider(new StyledCellLabelProvider() {
+    private void addMenuToOneDimensionalTopLevelModelAttributes(Menu menu) {
+        // Menu to add items to the array.
+        MenuItem addItems = new MenuItem(menu, SWT.NONE);
+        addItems.setText("Add Items");
+        addItems.addSelectionListener(new SelectionAdapter() {
             @Override
-            public void update(ViewerCell cell) {
-                Object element = cell.getElement();
-                if (element instanceof PutPostAttributeModel) {
-                    PutPostAttributeModel entry = (PutPostAttributeModel) element;
-                    cell.setText(entry.getAttValue());
+            public void widgetSelected(SelectionEvent e) {
+                // Get the attributes.
+                ResourceRepresentation representation;
+                representation = getRepresentationForOneDimensionTopLevelAttribute();
+                if (null == representation) {
+                    MessageDialog
+                            .openError(Display.getDefault().getActiveShell(),
+                                    "Unable to perform the operation.",
+                                    "Failed to obtain the required data. Operation cannot be performed.");
+                } else {
+                    ModelArrayAddItemDialog dialog = new ModelArrayAddItemDialog(
+                            Display.getDefault().getActiveShell(),
+                            PostRequestDialog.this, representation);
+                    if (Window.OK == dialog.open()) {
+                        // Add the new item to the local resource
+                        // representation.
+                        AttributeElement newElement = (AttributeElement) representation
+                                .getAttributes().values().toArray()[0];
+                        SimulatorResourceAttribute newAttribute = newElement
+                                .getSimulatorResourceAttribute();
+                        SimulatorResourceModel newModel = (SimulatorResourceModel) newAttribute
+                                .value().get();
+
+                        AttributeElement attElement = getSelectedElement();
+                        if (null == attElement) {
+                            MessageDialog
+                                    .openError(Display.getDefault()
+                                            .getActiveShell(),
+                                            "Unable to perform the operation.",
+                                            "Failed to obtain the required data. Operation cannot be performed.");
+                            return;
+                        }
+
+                        SimulatorResourceAttribute attribute = attElement
+                                .getSimulatorResourceAttribute();
+                        SimulatorResourceModel[] modelArray = (SimulatorResourceModel[]) attribute
+                                .value().get();
+                        SimulatorResourceModel[] newModelArray = new SimulatorResourceModel[modelArray.length + 1];
+
+                        int i;
+                        for (i = 0; i < modelArray.length; i++) {
+                            newModelArray[i] = modelArray[i];
+                        }
+                        newModelArray[i] = newModel;
+
+                        AttributeValue newValue = new AttributeValue(
+                                newModelArray);
+
+                        newAttribute.setValue(newValue);
+
+                        newAttribute.setProperty(attribute.property());
+
+                        attribute.setValue(newValue);
+
+                        attElement.update(newAttribute);
+
+                        attElement.setPostState(true);
+
+                        attViewer.refresh(attElement);
+
+                        attViewer.expandAll();
+                    }
                 }
             }
         });
-        attValue.setEditingSupport(new AttributeValueEditor(attTblViewer));
+    }
 
-        TableViewerColumn updateColumn = new TableViewerColumn(tableViewer,
-                SWT.NONE);
-        updateColumn.getColumn().setWidth(attTblColWidth[2]);
-        updateColumn.getColumn().setText(attTblHeaders[2]);
-        updateColumn.setLabelProvider(new ColumnLabelProvider() {
+    private void addDeleteMenuToArrayItemsOfOneDimensionalModelAttribute(
+            final Menu menu, final AttributeElement elementToDelete,
+            final AttributeElement parentElement) {
+        // Menu to add items to the array.
+        MenuItem addItems = new MenuItem(menu, SWT.NONE);
+        addItems.setText("Delete Item");
+        addItems.addSelectionListener(new SelectionAdapter() {
             @Override
-            public String getText(Object element) {
-                return "";
-            }
+            public void widgetSelected(SelectionEvent e) {
+                MessageBox dialog = new MessageBox(menu.getShell(),
+                        SWT.ICON_QUESTION | SWT.OK | SWT.CANCEL);
+                dialog.setText("Confirm action");
+                dialog.setMessage("Do you want to delete this item from the array?");
+                int retval = dialog.open();
+                if (retval != SWT.OK) {
+                    return;
+                }
 
-            @Override
-            public Image getImage(Object element) {
-                PutPostAttributeModel model = (PutPostAttributeModel) element;
-                if (model.isModified()) {
-                    return Activator.getDefault().getImageRegistry()
-                            .get(Constants.CHECKED);
+                // Removing the element from the attribute value.
+                SimulatorResourceAttribute parentSRA = parentElement
+                        .getSimulatorResourceAttribute();
+                AttributeValue value = parentSRA.value();
+                SimulatorResourceModel[] modelArray = (SimulatorResourceModel[]) value
+                        .get();
+
+                String elementIndexName = elementToDelete
+                        .getSimulatorResourceAttribute().name();
+                int elementIndex = Integer.parseInt(elementIndexName.substring(
+                        elementIndexName.indexOf('[') + 1,
+                        elementIndexName.indexOf(']')));
+
+                SimulatorResourceModel[] newModelArray = new SimulatorResourceModel[modelArray.length - 1];
+                int sIndex = 0, dIndex = 0;
+                for (SimulatorResourceModel model : modelArray) {
+                    if (sIndex != elementIndex)
+                        newModelArray[dIndex++] = model;
+                    sIndex++;
+                }
+
+                // Setting the new model array in the attribute.
+                AttributeValue newValue = new AttributeValue(newModelArray);
+                parentSRA.setValue(newValue);
+
+                // Removing the element from the child map.
+                Map<String, AttributeElement> elements = parentElement
+                        .getChildren();
+                if (null == elements) {
+                    MessageDialog
+                            .openError(Display.getDefault().getActiveShell(),
+                                    "Operation failed.",
+                                    "There is an error while removing the array items.");
+                    return;
+                }
+
+                List<AttributeElement> attElementList = new ArrayList<AttributeElement>();
+                attElementList.addAll(elements.values());
+                Collections.sort(attElementList, Utility.attributeComparator);
+
+                // Renaming the index of the elements.
+                AttributeElement[] attElementArray = attElementList
+                        .toArray(new AttributeElement[0]);
+                boolean deleted = false;
+                int index, newIndex;
+                for (index = 0, newIndex = 0; index < attElementArray.length; index++) {
+                    if (index == elementIndex) {
+                        elements.remove(elementIndexName);
+                        deleted = true;
+                    } else {
+                        if (deleted) {
+                            AttributeElement element = attElementArray[index];
+                            String curIndexStr = "[" + index + "]";
+                            String newIndexStr = "[" + newIndex + "]";
+
+                            element.getSimulatorResourceAttribute().setName(
+                                    newIndexStr);
+
+                            elements.remove(curIndexStr);
+                            elements.put(newIndexStr, element);
+                        }
+                        newIndex++;
+                    }
                 }
-                return Activator.getDefault().getImageRegistry()
-                        .get(Constants.UNCHECKED);
+
+                parentElement.setPostState(true);
+
+                attViewer.refresh(parentElement);
             }
         });
-        updateColumn.setEditingSupport(new UpdateEditor(attTblViewer));
     }
 
-    @Override
-    protected boolean isResizable() {
-        return true;
-    }
+    private ResourceRepresentation getRepresentationForOneDimensionTopLevelAttribute() {
+        ResourceRepresentation representation;
 
-    @Override
-    public boolean isHelpAvailable() {
-        return false;
-    }
+        AttributeValue value;
+        ModelProperty property = null;
 
-    @Override
-    protected Button createButton(Composite parent, int id, String label,
-            boolean defaultButton) {
-        if (id == IDialogConstants.OK_ID) {
-            label = "POST";
+        AttributeElement element = getSelectedElement();
+        if (null == element)
+            return null;
+
+        SimulatorResourceAttribute modelArrayAtt = element
+                .getSimulatorResourceAttribute();
+        if (null == modelArrayAtt) {
+            return null;
         }
-        return super.createButton(parent, id, label, defaultButton);
+
+        AttributeValue attValue = modelArrayAtt.value();
+        if (null == attValue) {
+            return null;
+        }
+
+        TypeInfo type = attValue.typeInfo();
+
+        if (!(type.mType == ValueType.ARRAY
+                && type.mBaseType == ValueType.RESOURCEMODEL && type.mDepth == 1)) {
+            return null;
+        }
+
+        SimulatorResourceModel[] modelValue = (SimulatorResourceModel[]) attValue
+                .get();
+        if (null == modelValue || modelValue.length < 0) {
+            return null;
+        }
+
+        // Clone an instance of model value.
+        try {
+            value = Utility.cloneAttributeValue(new AttributeValue(
+                    modelValue[0]));
+        } catch (Exception e) {
+            return null;
+        }
+
+        if (null == value) {
+            return null;
+        }
+
+        // Get the model property of the model value instance.
+        AttributeProperty attProperty = modelArrayAtt.property();
+        if (null != attProperty && attProperty instanceof ArrayProperty) {
+            ArrayProperty prop = attProperty.asArray();
+            if (null != prop) {
+                AttributeProperty elementProperty = prop.getElementProperty();
+                if (null != elementProperty && elementProperty.isModel()) {
+                    property = elementProperty.asModel();
+                }
+            }
+        }
+
+        SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                modelArrayAtt.name(), value, property);
+        Map<String, SimulatorResourceAttribute> attributes = new HashMap<String, SimulatorResourceAttribute>();
+        attributes.put(modelArrayAtt.name(), attribute);
+        representation = new ResourceRepresentation(attributes, false);
+
+        return representation;
     }
 
-    class AttributeContentProvider implements IStructuredContentProvider {
+    private AttributeElement getSelectedElement() {
+        IStructuredSelection selection = (IStructuredSelection) attViewer
+                .getSelection();
+        if (null == selection) {
+            return null;
+        }
 
-        @Override
-        public void dispose() {
+        Object obj = selection.getFirstElement();
+        if (null == obj) {
+            return null;
         }
 
-        @Override
-        public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
+        Tree t = attViewer.getTree();
+        TreeItem item = t.getSelection()[0];
+        if (null == item) {
+            return null;
         }
 
-        @Override
-        public Object[] getElements(Object element) {
-            return (Object[]) element;
+        if (!(item.getData() instanceof AttributeElement)) {
+            return null;
         }
 
+        return (AttributeElement) item.getData();
     }
 
-    class AttributeValueEditor extends EditingSupport {
-        private final TableViewer viewer;
-        private final CellEditor  editor;
-        private final Text txt;
-        public AttributeValueEditor(TableViewer viewer) {
-            super(viewer);
-            this.viewer = viewer;
-            editor = new TextCellEditor(viewer.getTable());
-            txt = (Text)editor.getControl();
-            if(null != txt) {
-                txt.addModifyListener(new ModifyListener() {
-                    @Override
-                    public void modifyText(ModifyEvent e) {                 
-                        IStructuredSelection selection = (IStructuredSelection)AttributeValueEditor.this.viewer.getSelection();
-                        PutPostAttributeModel att = (PutPostAttributeModel)selection.getFirstElement();             
-                        if(null == att) {
-                            return;
-                        }
-                        String newValue = txt.getText();
-                        if(null != newValue && !newValue.isEmpty()) {
-                            att.setModified(true);
-                        }
-                        else {
-                            att.setModified(false);
-                        }
-                        AttributeValueEditor.this.viewer.update(att, null);
-                    }
-                });
-              
-            }
+    private static class AttributeContentProvider implements
+            ITreeContentProvider {
+
+        @Override
+        public void dispose() {
         }
 
         @Override
-        protected boolean canEdit(Object arg0) {
-            return true;
+        public void inputChanged(Viewer viewer, Object oldAttribute,
+                Object newAttribute) {
         }
 
         @Override
-        protected CellEditor getCellEditor(Object element) {
-            return editor;
+        public Object[] getChildren(Object attribute) {
+            if (attribute instanceof AttributeElement) {
+                List<AttributeElement> attElementList = new ArrayList<AttributeElement>();
+                Map<String, AttributeElement> children = ((AttributeElement) attribute)
+                        .getChildren();
+                if (null != children) {
+                    attElementList.addAll(children.values());
+                    Collections.sort(attElementList,
+                            Utility.attributeComparator);
+                    return attElementList.toArray();
+                }
+            }
+
+            return new Object[0];
+        }
+
+        @Override
+        public Object getParent(Object attribute) {
+            if (attribute instanceof AttributeElement)
+                return ((AttributeElement) attribute).getParent();
+            return null;
         }
 
         @Override
-        protected Object getValue(Object element) {
-            PutPostAttributeModel model = (PutPostAttributeModel) element;
-            return model.getAttValue();
+        public boolean hasChildren(Object attribute) {
+            if (attribute instanceof AttributeElement)
+                return ((AttributeElement) attribute).hasChildren();
+            return false;
         }
 
         @Override
-        protected void setValue(Object element, Object value) {
-            PutPostAttributeModel model = (PutPostAttributeModel) element;
-            // Compare the actual value and the new value
-            // If there is a change, then its corresponding check box should be
-            // checked.
-            String newValue = String.valueOf(value);
-            model.setAttValue(newValue);
-            viewer.update(element, null);
+        public Object[] getElements(Object resourceModel) {
+            if (resourceModel instanceof ResourceRepresentation) {
+                return ((ResourceRepresentation) resourceModel).getAttributes()
+                        .values().toArray();
+            }
+
+            return new Object[0];
         }
     }
 
-    class UpdateEditor extends EditingSupport {
+    private static class AttributeLabelProvider implements ITableLabelProvider {
 
-        private final TableViewer viewer;
+        @Override
+        public void addListener(ILabelProviderListener arg0) {
+        }
 
-        public UpdateEditor(TableViewer viewer) {
-            super(viewer);
-            this.viewer = viewer;
+        @Override
+        public void dispose() {
         }
 
         @Override
-        protected boolean canEdit(Object arg0) {
-            return true;
+        public boolean isLabelProperty(Object arg0, String arg1) {
+            return false;
         }
 
         @Override
-        protected CellEditor getCellEditor(Object element) {
-            return new CheckboxCellEditor(null, SWT.CHECK | SWT.READ_ONLY);
+        public void removeListener(ILabelProviderListener arg0) {
+
         }
 
         @Override
-        protected Object getValue(Object element) {
-            PutPostAttributeModel model = (PutPostAttributeModel) element;
-            return model.isModified();
+        public Image getColumnImage(Object element, int col) {
+            if (col == 2) {
+                if (element instanceof AttributeElement) {
+
+                    AttributeElement attrElement = (AttributeElement) element;
+                    Object parent = attrElement.getParent();
+                    if (null == parent
+                            || parent instanceof ResourceRepresentation) {
+                        if (attrElement.getPostState()) {
+                            return Activator.getDefault().getImageRegistry()
+                                    .get(Constants.CHECKED);
+                        } else {
+                            return Activator.getDefault().getImageRegistry()
+                                    .get(Constants.UNCHECKED);
+                        }
+                    }
+                }
+            }
+
+            return null;
         }
 
         @Override
-        protected void setValue(Object element, Object value) {
-            PutPostAttributeModel model = (PutPostAttributeModel) element;
-            boolean status = (boolean) value;
-            model.setModified(status);
-            viewer.update(element, null);
+        public String getColumnText(Object element, int column) {
+            if (element instanceof AttributeElement) {
+                AttributeElement attrElement = (AttributeElement) element;
+                switch (column) {
+                    case 0: // Attribute name column
+                    {
+                        SimulatorResourceAttribute attribute = attrElement
+                                .getSimulatorResourceAttribute();
+                        return attribute.name();
+                    }
+
+                    case 1: // Attribute value column
+                    {
+                        SimulatorResourceAttribute attribute = attrElement
+                                .getSimulatorResourceAttribute();
+
+                        if (attribute.value().typeInfo().mBaseType != ValueType.RESOURCEMODEL) {
+                            String value = Utility
+                                    .getAttributeValueAsString(attribute
+                                            .value());
+                            if (null == value) {
+                                value = "";
+                            }
+                            return value;
+                        }
+                        return null;
+                    }
+
+                    case 2: {
+                        return "";
+                    }
+                }
+            }
+            return null;
+        }
+    }
+
+    @Override
+    protected boolean isResizable() {
+        return true;
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+
+    @Override
+    protected Button createButton(Composite parent, int id, String label,
+            boolean defaultButton) {
+        if (id == IDialogConstants.OK_ID) {
+            label = "POST";
+        }
+        return super.createButton(parent, id, label, defaultButton);
+    }
+
+    public ResourceRepresentation getUpdatedRepresentation() {
+        return updatedRepresentation;
+    }
+
+    public String getIfType() {
+        if (ifTypes.containsKey(ifType)) {
+            return ifTypes.get(ifType);
         }
+        return ifType;
     }
 }
index 3ba0c87..a5ccdb2 100644 (file)
 
 package oic.simulator.clientcontroller.view.dialogs;
 
-import java.util.List;
-
-import oic.simulator.clientcontroller.remoteresource.PutPostAttributeModel;
-
 import org.eclipse.jface.dialogs.IDialogConstants;
+import org.eclipse.jface.dialogs.MessageDialog;
 import org.eclipse.jface.dialogs.TitleAreaDialog;
-import org.eclipse.jface.viewers.CellEditor;
-import org.eclipse.jface.viewers.EditingSupport;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.StyledCellLabelProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.TextCellEditor;
+import org.eclipse.jface.viewers.ILabelProviderListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.ITableLabelProvider;
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.jface.viewers.TreeViewerColumn;
 import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerCell;
+import org.eclipse.jface.window.Window;
 import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.MenuAdapter;
+import org.eclipse.swt.events.MenuEvent;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.graphics.Image;
 import org.eclipse.swt.layout.GridData;
 import org.eclipse.swt.layout.GridLayout;
 import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Combo;
 import org.eclipse.swt.widgets.Composite;
 import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.swt.widgets.MenuItem;
+import org.eclipse.swt.widgets.MessageBox;
 import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeColumn;
+import org.eclipse.swt.widgets.TreeItem;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+
+import org.oic.simulator.ArrayProperty;
+import org.oic.simulator.AttributeProperty;
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.AttributeValue.TypeInfo;
+import org.oic.simulator.AttributeValue.ValueType;
+import org.oic.simulator.ILogger.Level;
+import org.oic.simulator.ModelProperty;
+import org.oic.simulator.SimulatorResourceAttribute;
+import org.oic.simulator.SimulatorResourceModel;
+import org.oic.simulator.client.SimulatorRemoteResource.RequestType;
+
+import oic.simulator.clientcontroller.Activator;
+import oic.simulator.clientcontroller.remoteresource.AttributeElement;
+import oic.simulator.clientcontroller.remoteresource.RemoteResource;
+import oic.simulator.clientcontroller.remoteresource.ResourceRepresentation;
+import oic.simulator.clientcontroller.utils.Constants;
+import oic.simulator.clientcontroller.utils.Utility;
+import oic.simulator.clientcontroller.view.AttributeEditingSupport;
 
 /**
  * This dialog is used for generating a PUT request.
  */
 public class PutRequestDialog extends TitleAreaDialog {
 
-    private TableViewer                 attTblViewer;
+    private TreeViewer              attViewer;
+    private Combo                   ifTypesCmb;
+
+    private String                  ifType;
+
+    private Map<String, String>     ifTypes;
+
+    private AttributeEditingSupport attributeEditor;
 
-    private final String[]              attTblHeaders  = { "Name", "Value" };
-    private final Integer[]             attTblColWidth = { 200, 200 };
+    private ResourceRepresentation  updatedRepresentation;
 
-    private List<PutPostAttributeModel> modelList      = null;
+    private final String[]          attTblHeaders  = { "Name", "Value" };
+    private final Integer[]         attTblColWidth = { 200, 200 };
 
-    public PutRequestDialog(Shell parentShell,
-            List<PutPostAttributeModel> modelList) {
+    public PutRequestDialog(Shell parentShell) {
         super(parentShell);
-        this.modelList = modelList;
     }
 
     @Override
@@ -68,120 +113,638 @@ public class PutRequestDialog extends TitleAreaDialog {
     @Override
     protected Control createDialogArea(Composite parent) {
         Composite compLayout = (Composite) super.createDialogArea(parent);
-        Composite container = new Composite(compLayout, SWT.NONE);
-        container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-        GridLayout layout = new GridLayout(1, false);
+
+        Composite rootContainer = new Composite(compLayout, SWT.NONE);
+        GridLayout layout = new GridLayout();
+        rootContainer.setLayout(layout);
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        rootContainer.setLayoutData(gd);
+
+        Group paramsGrp = new Group(rootContainer, SWT.NONE);
+        gd = new GridData();
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        gd.minimumHeight = 50;
+        paramsGrp.setLayoutData(gd);
+        layout = new GridLayout(2, false);
+        layout.verticalSpacing = 10;
+        layout.marginTop = 10;
+        paramsGrp.setLayout(layout);
+
+        Label ifTypeLbl = new Label(paramsGrp, SWT.NONE);
+        ifTypeLbl.setText("Interface Type");
+
+        ifTypesCmb = new Combo(paramsGrp, SWT.NULL);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        ifTypesCmb.setLayoutData(gd);
+        ifTypesCmb.addModifyListener(new ModifyListener() {
+            @Override
+            public void modifyText(ModifyEvent e) {
+                ifType = ifTypesCmb.getText();
+            }
+        });
+
+        RemoteResource resource = Activator.getDefault().getResourceManager()
+                .getCurrentResourceInSelection();
+
+        // Set the interface types in combo box.
+        Map<String, String> ifTypes = Utility.getResourceInterfaces();
+        this.ifTypes = new HashMap<String, String>();
+        String key;
+        for (Map.Entry<String, String> entry : ifTypes.entrySet()) {
+            key = entry.getValue() + " (" + entry.getKey() + ")";
+            this.ifTypes.put(key, entry.getKey());
+            ifTypesCmb.add(key);
+        }
+
+        // Select the default value to be shown in the interface types combo.
+        Vector<String> ifTypesSupportedByResource = resource
+                .getRemoteResourceRef().getResourceInterfaces();
+        if (null != ifTypesSupportedByResource) {
+            int index = -1;
+            if (ifTypesSupportedByResource
+                    .contains(Constants.BASELINE_INTERFACE)
+                    && ifTypes.containsKey(Constants.BASELINE_INTERFACE)) {
+                // Baseline interface is given preference to be shown in the if
+                // types combo.
+                String value = ifTypes.get(Constants.BASELINE_INTERFACE);
+                index = ifTypesCmb.indexOf(value + " ("
+                        + Constants.BASELINE_INTERFACE + ")");
+                if (index != -1)
+                    ifTypesCmb.select(index);
+            }
+            if (index == -1) {
+                // Baseline interface is not selected so selecting some other
+                // interface supported by the resource.
+                Iterator<String> itr = ifTypesSupportedByResource.iterator();
+                while (itr.hasNext() && index == -1) {
+                    key = itr.next();
+                    if (ifTypes.containsKey(key)) {
+                        String value = ifTypes.get(key);
+                        index = ifTypesCmb.indexOf(value + " (" + key + ")");
+                        if (index != -1) {
+                            ifTypesCmb.select(index);
+                            break;
+                        }
+                    }
+                }
+                if (index == -1 && !ifTypesSupportedByResource.isEmpty()) {
+                    // Resource has custom interfaces.
+                    ifTypesCmb.setText(ifTypesSupportedByResource.get(0));
+                }
+            }
+        }
+
+        Composite container = new Composite(rootContainer, SWT.NONE);
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        container.setLayoutData(gd);
+        layout = new GridLayout(1, false);
         layout.verticalSpacing = 10;
         layout.marginTop = 10;
         container.setLayout(layout);
 
-        createTableViewer(container);
+        createTreeViewer(container);
+
+        // Clone the resource model for maintaining a local copy of attributes
+        // for PUT requests.
+        SimulatorResourceModel resourceModel = null;
+        try {
+            AttributeValue attValue = Utility
+                    .cloneAttributeValue(new AttributeValue(resource
+                            .getResourceModelRef()));
+            if (null != attValue)
+                resourceModel = (SimulatorResourceModel) attValue.get();
+        } catch (Exception e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "There is an error while forming an instance of the attribute value.\n"
+                                    + Utility.getSimulatorErrorString(e, null));
+        }
 
-        attTblViewer.setInput(modelList.toArray());
+        if (null == resourceModel) {
+            // Failed to clone. So taking the base copy and continuing the
+            // operation.
+            resourceModel = resource.getResourceModelRef();
+        }
+
+        updatedRepresentation = new ResourceRepresentation(resourceModel);
+
+        if (resource.isConfigUploaded()) {
+            try {
+                // Request Type needs to be changed to PUT.
+                updatedRepresentation.updateAttributeProperties(resource
+                        .getRequestModels().get(RequestType.POST),
+                        resourceModel);
+            } catch (Exception e) {
+                Activator
+                        .getDefault()
+                        .getLogManager()
+                        .log(Level.ERROR.ordinal(),
+                                new Date(),
+                                "There is an error while forming an instance of the attribute value.\n"
+                                        + Utility.getSimulatorErrorString(e,
+                                                null));
+            }
+        }
+
+        attViewer.setInput(updatedRepresentation);
+
+        attViewer.expandAll();
 
         return compLayout;
     }
 
-    private void createTableViewer(Composite parent) {
-        attTblViewer = new TableViewer(parent, SWT.SINGLE | SWT.H_SCROLL
-                | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
+    private void createTreeViewer(Composite parent) {
+        Tree addressTree = new Tree(parent, SWT.SINGLE | SWT.BORDER
+                | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
+        addressTree.setHeaderVisible(true);
+
+        attViewer = new TreeViewer(addressTree);
 
-        createAttributeColumns(attTblViewer);
+        createAttributeColumns(attViewer);
 
         // make lines and header visible
-        Table table = attTblViewer.getTable();
-        table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-        table.setHeaderVisible(true);
-        table.setLinesVisible(true);
+        Tree tree = attViewer.getTree();
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        tree.setLayoutData(gd);
+        tree.setHeaderVisible(true);
+        tree.setLinesVisible(true);
+
+        attViewer.setContentProvider(new AttributeContentProvider());
+        attViewer.setLabelProvider(new AttributeLabelProvider());
+    }
+
+    public void createAttributeColumns(TreeViewer viewer) {
+        Tree tree = viewer.getTree();
+
+        attributeEditor = new AttributeEditingSupport();
 
-        attTblViewer.setContentProvider(new AttributeContentProvider());
+        TreeColumn attName = new TreeColumn(tree, SWT.NONE);
+        attName.setWidth(attTblColWidth[0]);
+        attName.setText(attTblHeaders[0]);
+
+        TreeColumn attValue = new TreeColumn(tree, SWT.NONE);
+        attValue.setWidth(attTblColWidth[1]);
+        attValue.setText(attTblHeaders[1]);
+        TreeViewerColumn attValueVwrCol = new TreeViewerColumn(attViewer,
+                attValue);
+        attValueVwrCol.setEditingSupport(attributeEditor
+                .createAttributeValueEditor(attViewer, this));
+
+        addMenuItems();
     }
 
-    public void createAttributeColumns(TableViewer tableViewer) {
+    private void addMenuItems() {
+        if (null != attViewer) {
+            final Tree resourceTreeHead = attViewer.getTree();
+            if (null != resourceTreeHead) {
+                // Below code creates menu entries and shows them on right
+                // clicking a resource
+                final Menu menu = new Menu(resourceTreeHead);
+                resourceTreeHead.setMenu(menu);
+                menu.addMenuListener(new MenuAdapter() {
+                    @Override
+                    public void menuShown(MenuEvent e) {
+                        // Clear existing menu items
+                        MenuItem[] items = menu.getItems();
+                        for (int index = 0; index < items.length; index++) {
+                            items[index].dispose();
+                        }
+
+                        IStructuredSelection selection = ((IStructuredSelection) attViewer
+                                .getSelection());
+                        final AttributeElement attElement = (AttributeElement) selection
+                                .getFirstElement();
+                        if (null == attElement) {
+                            return;
+                        }
+
+                        // Check the type of attribute.
+                        SimulatorResourceAttribute attribute = attElement
+                                .getSimulatorResourceAttribute();
+                        if (null == attribute) {
+                            return;
+                        }
+
+                        AttributeValue value = attribute.value();
+                        if (null == value || null == value.get()) {
+                            return;
+                        }
+
+                        TypeInfo type = value.typeInfo();
+
+                        final Object parent = attElement.getParent();
+
+                        if ((type.mType == ValueType.ARRAY
+                                && type.mBaseType == ValueType.RESOURCEMODEL && type.mDepth == 1)
+                                && (null == parent || parent instanceof ResourceRepresentation)) {
+                            addMenuToOneDimensionalTopLevelModelAttributes(menu);
+                            return;
+                        }
+
+                        if (null != parent
+                                && parent instanceof AttributeElement) {
+                            Object grandParent = ((AttributeElement) parent)
+                                    .getParent();
+                            if (null == grandParent
+                                    || grandParent instanceof ResourceRepresentation) {
+                                AttributeElement parentElement = (AttributeElement) parent;
+
+                                // Check the type of attribute.
+                                SimulatorResourceAttribute parentAttribute = parentElement
+                                        .getSimulatorResourceAttribute();
+                                if (null != parentAttribute
+                                        && null != parentAttribute.value()
+                                        && null != parentAttribute.value()
+                                                .get()) {
+                                    AttributeValue parentValue = parentAttribute
+                                            .value();
+
+                                    TypeInfo parentType = parentValue
+                                            .typeInfo();
+                                    if (parentType.mType == ValueType.ARRAY
+                                            && parentType.mBaseType == ValueType.RESOURCEMODEL
+                                            && parentType.mDepth == 1) {
+                                        addDeleteMenuToArrayItemsOfOneDimensionalModelAttribute(
+                                                menu, attElement, parentElement);
+                                        return;
+                                    }
+                                }
+                            }
+                        }
+                    }
+                });
+            }
+        }
+    }
 
-        TableViewerColumn attName = new TableViewerColumn(tableViewer, SWT.NONE);
-        attName.getColumn().setWidth(attTblColWidth[0]);
-        attName.getColumn().setText(attTblHeaders[0]);
-        attName.setLabelProvider(new StyledCellLabelProvider() {
+    private void addMenuToOneDimensionalTopLevelModelAttributes(Menu menu) {
+        // Menu to add items to the array.
+        MenuItem addItems = new MenuItem(menu, SWT.NONE);
+        addItems.setText("Add Items");
+        addItems.addSelectionListener(new SelectionAdapter() {
             @Override
-            public void update(ViewerCell cell) {
-                Object element = cell.getElement();
-                if (element instanceof PutPostAttributeModel) {
-                    PutPostAttributeModel entry = (PutPostAttributeModel) element;
-                    cell.setText(entry.getAttName());
+            public void widgetSelected(SelectionEvent e) {
+                // Get the attributes.
+                ResourceRepresentation representation;
+                representation = getRepresentationForOneDimensionTopLevelAttribute();
+                if (null == representation) {
+                    MessageDialog
+                            .openError(Display.getDefault().getActiveShell(),
+                                    "Unable to perform the operation.",
+                                    "Failed to obtain the required data. Operation cannot be performed.");
+                } else {
+                    ModelArrayAddItemDialog dialog = new ModelArrayAddItemDialog(
+                            Display.getDefault().getActiveShell(),
+                            PutRequestDialog.this, representation);
+                    if (Window.OK == dialog.open()) {
+                        // Add the new item to the local resource
+                        // representation.
+                        AttributeElement newElement = (AttributeElement) representation
+                                .getAttributes().values().toArray()[0];
+                        SimulatorResourceAttribute newAttribute = newElement
+                                .getSimulatorResourceAttribute();
+                        SimulatorResourceModel newModel = (SimulatorResourceModel) newAttribute
+                                .value().get();
+
+                        AttributeElement attElement = getSelectedElement();
+                        if (null == attElement) {
+                            MessageDialog
+                                    .openError(Display.getDefault()
+                                            .getActiveShell(),
+                                            "Unable to perform the operation.",
+                                            "Failed to obtain the required data. Operation cannot be performed.");
+                            return;
+                        }
+
+                        SimulatorResourceAttribute attribute = attElement
+                                .getSimulatorResourceAttribute();
+                        SimulatorResourceModel[] modelArray = (SimulatorResourceModel[]) attribute
+                                .value().get();
+                        SimulatorResourceModel[] newModelArray = new SimulatorResourceModel[modelArray.length + 1];
+
+                        int i;
+                        for (i = 0; i < modelArray.length; i++) {
+                            newModelArray[i] = modelArray[i];
+                        }
+                        newModelArray[i] = newModel;
+
+                        AttributeValue newValue = new AttributeValue(
+                                newModelArray);
+
+                        newAttribute.setValue(newValue);
+
+                        newAttribute.setProperty(attribute.property());
+
+                        attribute.setValue(newValue);
+
+                        attElement.update(newAttribute);
+
+                        attViewer.refresh(attElement);
+
+                        attViewer.expandAll();
+                    }
                 }
             }
         });
+    }
 
-        TableViewerColumn attValue = new TableViewerColumn(tableViewer,
-                SWT.NONE);
-        attValue.getColumn().setWidth(attTblColWidth[1]);
-        attValue.getColumn().setText(attTblHeaders[1]);
-        attValue.setLabelProvider(new StyledCellLabelProvider() {
+    private void addDeleteMenuToArrayItemsOfOneDimensionalModelAttribute(
+            final Menu menu, final AttributeElement elementToDelete,
+            final AttributeElement parentElement) {
+        // Menu to add items to the array.
+        MenuItem addItems = new MenuItem(menu, SWT.NONE);
+        addItems.setText("Delete Item");
+        addItems.addSelectionListener(new SelectionAdapter() {
             @Override
-            public void update(ViewerCell cell) {
-                Object element = cell.getElement();
-                if (element instanceof PutPostAttributeModel) {
-                    PutPostAttributeModel entry = (PutPostAttributeModel) element;
-                    cell.setText(entry.getAttValue());
+            public void widgetSelected(SelectionEvent e) {
+                MessageBox dialog = new MessageBox(menu.getShell(),
+                        SWT.ICON_QUESTION | SWT.OK | SWT.CANCEL);
+                dialog.setText("Confirm action");
+                dialog.setMessage("Do you want to delete this item from the array?");
+                int retval = dialog.open();
+                if (retval != SWT.OK) {
+                    return;
                 }
+
+                // Removing the element from the attribute value.
+                SimulatorResourceAttribute parentSRA = parentElement
+                        .getSimulatorResourceAttribute();
+                AttributeValue value = parentSRA.value();
+                SimulatorResourceModel[] modelArray = (SimulatorResourceModel[]) value
+                        .get();
+
+                String elementIndexName = elementToDelete
+                        .getSimulatorResourceAttribute().name();
+                int elementIndex = Integer.parseInt(elementIndexName.substring(
+                        elementIndexName.indexOf('[') + 1,
+                        elementIndexName.indexOf(']')));
+
+                SimulatorResourceModel[] newModelArray = new SimulatorResourceModel[modelArray.length - 1];
+                int sIndex = 0, dIndex = 0;
+                for (SimulatorResourceModel model : modelArray) {
+                    if (sIndex != elementIndex)
+                        newModelArray[dIndex++] = model;
+                    sIndex++;
+                }
+
+                // Setting the new model array in the attribute.
+                AttributeValue newValue = new AttributeValue(newModelArray);
+                parentSRA.setValue(newValue);
+
+                // Removing the element from the child map.
+                Map<String, AttributeElement> elements = parentElement
+                        .getChildren();
+                if (null == elements) {
+                    MessageDialog
+                            .openError(Display.getDefault().getActiveShell(),
+                                    "Operation failed.",
+                                    "There is an error while removing the array items.");
+                    return;
+                }
+
+                List<AttributeElement> attElementList = new ArrayList<AttributeElement>();
+                attElementList.addAll(elements.values());
+                Collections.sort(attElementList, Utility.attributeComparator);
+
+                // Renaming the index of the elements.
+                AttributeElement[] attElementArray = attElementList
+                        .toArray(new AttributeElement[0]);
+                boolean deleted = false;
+                int index, newIndex;
+                for (index = 0, newIndex = 0; index < attElementArray.length; index++) {
+                    if (index == elementIndex) {
+                        elements.remove(elementIndexName);
+                        deleted = true;
+                    } else {
+                        if (deleted) {
+                            AttributeElement element = attElementArray[index];
+                            String curIndexStr = "[" + index + "]";
+                            String newIndexStr = "[" + newIndex + "]";
+
+                            element.getSimulatorResourceAttribute().setName(
+                                    newIndexStr);
+
+                            elements.remove(curIndexStr);
+                            elements.put(newIndexStr, element);
+                        }
+                        newIndex++;
+                    }
+                }
+
+                attViewer.refresh(parentElement);
             }
         });
-        attValue.setEditingSupport(new AttributeValueEditor(attTblViewer));
     }
 
-    class AttributeContentProvider implements IStructuredContentProvider {
+    private ResourceRepresentation getRepresentationForOneDimensionTopLevelAttribute() {
+        ResourceRepresentation representation;
+
+        AttributeValue value;
+        ModelProperty property = null;
+
+        AttributeElement element = getSelectedElement();
+        if (null == element)
+            return null;
+
+        SimulatorResourceAttribute modelArrayAtt = element
+                .getSimulatorResourceAttribute();
+        if (null == modelArrayAtt) {
+            return null;
+        }
+
+        AttributeValue attValue = modelArrayAtt.value();
+        if (null == attValue) {
+            return null;
+        }
+
+        TypeInfo type = attValue.typeInfo();
+
+        if (!(type.mType == ValueType.ARRAY
+                && type.mBaseType == ValueType.RESOURCEMODEL && type.mDepth == 1)) {
+            return null;
+        }
+
+        SimulatorResourceModel[] modelValue = (SimulatorResourceModel[]) attValue
+                .get();
+        if (null == modelValue || modelValue.length < 0) {
+            return null;
+        }
+
+        // Clone an instance of model value.
+        try {
+            value = Utility.cloneAttributeValue(new AttributeValue(
+                    modelValue[0]));
+        } catch (Exception e) {
+            return null;
+        }
+
+        if (null == value) {
+            return null;
+        }
+
+        // Get the model property of the model value instance.
+        AttributeProperty attProperty = modelArrayAtt.property();
+        if (null != attProperty && attProperty instanceof ArrayProperty) {
+            ArrayProperty prop = attProperty.asArray();
+            if (null != prop) {
+                AttributeProperty elementProperty = prop.getElementProperty();
+                if (null != elementProperty && elementProperty.isModel()) {
+                    property = elementProperty.asModel();
+                }
+            }
+        }
+
+        SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                modelArrayAtt.name(), value, property);
+        Map<String, SimulatorResourceAttribute> attributes = new HashMap<String, SimulatorResourceAttribute>();
+        attributes.put(modelArrayAtt.name(), attribute);
+        representation = new ResourceRepresentation(attributes, false);
+
+        return representation;
+    }
+
+    private AttributeElement getSelectedElement() {
+        IStructuredSelection selection = (IStructuredSelection) attViewer
+                .getSelection();
+        if (null == selection) {
+            return null;
+        }
+
+        Object obj = selection.getFirstElement();
+        if (null == obj) {
+            return null;
+        }
+
+        Tree t = attViewer.getTree();
+        TreeItem item = t.getSelection()[0];
+        if (null == item) {
+            return null;
+        }
+
+        if (!(item.getData() instanceof AttributeElement)) {
+            return null;
+        }
+
+        return (AttributeElement) item.getData();
+    }
+
+    private static class AttributeContentProvider implements
+            ITreeContentProvider {
 
         @Override
         public void dispose() {
         }
 
         @Override
-        public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
+        public void inputChanged(Viewer viewer, Object oldAttribute,
+                Object newAttribute) {
+        }
+
+        @Override
+        public Object[] getChildren(Object attribute) {
+            if (attribute instanceof AttributeElement) {
+                List<AttributeElement> attElementList = new ArrayList<AttributeElement>();
+                Map<String, AttributeElement> children = ((AttributeElement) attribute)
+                        .getChildren();
+                if (null != children) {
+                    attElementList.addAll(children.values());
+                    Collections.sort(attElementList,
+                            Utility.attributeComparator);
+                    return attElementList.toArray();
+                }
+            }
+
+            return new Object[0];
+        }
+
+        @Override
+        public Object getParent(Object attribute) {
+            if (attribute instanceof AttributeElement)
+                return ((AttributeElement) attribute).getParent();
+            return null;
         }
 
         @Override
-        public Object[] getElements(Object element) {
-            return (Object[]) element;
+        public boolean hasChildren(Object attribute) {
+            if (attribute instanceof AttributeElement)
+                return ((AttributeElement) attribute).hasChildren();
+            return false;
+        }
+
+        @Override
+        public Object[] getElements(Object resourceModel) {
+            if (resourceModel instanceof ResourceRepresentation) {
+                return ((ResourceRepresentation) resourceModel).getAttributes()
+                        .values().toArray();
+            }
+
+            return new Object[0];
         }
     }
 
-    class AttributeValueEditor extends EditingSupport {
-        private final TableViewer viewer;
-        private final CellEditor  editor;
+    private static class AttributeLabelProvider implements ITableLabelProvider {
 
-        public AttributeValueEditor(TableViewer viewer) {
-            super(viewer);
-            this.viewer = viewer;
-            editor = new TextCellEditor(viewer.getTable());
+        @Override
+        public void addListener(ILabelProviderListener arg0) {
         }
 
         @Override
-        protected boolean canEdit(Object arg0) {
-            return true;
+        public void dispose() {
         }
 
         @Override
-        protected CellEditor getCellEditor(Object element) {
-            return editor;
+        public boolean isLabelProperty(Object arg0, String arg1) {
+            return false;
         }
 
         @Override
-        protected Object getValue(Object element) {
-            PutPostAttributeModel model = (PutPostAttributeModel) element;
-            return model.getAttValue();
+        public void removeListener(ILabelProviderListener arg0) {
+
         }
 
         @Override
-        protected void setValue(Object element, Object value) {
-            PutPostAttributeModel model = (PutPostAttributeModel) element;
-            model.setAttValue(String.valueOf(value));
-            viewer.update(element, null);
+        public Image getColumnImage(Object element, int col) {
+            return null;
         }
-    }
 
-    public List<PutPostAttributeModel> getUpdatedModel() {
-        return modelList;
+        @Override
+        public String getColumnText(Object element, int column) {
+            if (element instanceof AttributeElement) {
+                AttributeElement attrElement = (AttributeElement) element;
+                switch (column) {
+                    case 0: // Attribute name column
+                    {
+                        SimulatorResourceAttribute attribute = attrElement
+                                .getSimulatorResourceAttribute();
+                        return attribute.name();
+                    }
+
+                    case 1: // Attribute value column
+                    {
+                        SimulatorResourceAttribute attribute = attrElement
+                                .getSimulatorResourceAttribute();
+
+                        if (attribute.value().typeInfo().mBaseType != ValueType.RESOURCEMODEL) {
+                            String value = Utility
+                                    .getAttributeValueAsString(attribute
+                                            .value());
+                            if (null == value) {
+                                value = "";
+                            }
+                            return value;
+                        }
+                        return null;
+                    }
+                }
+            }
+            return null;
+        }
     }
 
     @Override
@@ -202,4 +765,16 @@ public class PutRequestDialog extends TitleAreaDialog {
         }
         return super.createButton(parent, id, label, defaultButton);
     }
+
+    public ResourceRepresentation getUpdatedRepresentation() {
+        return updatedRepresentation;
+    }
+
+    public String getIfType() {
+        if (ifTypes.containsKey(ifType)) {
+            return ifTypes.get(ifType);
+        }
+        return ifType;
+    }
+
 }
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/UpdatePrimitiveArrayAttributeDialog.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/UpdatePrimitiveArrayAttributeDialog.java
new file mode 100644 (file)
index 0000000..ddb6f4c
--- /dev/null
@@ -0,0 +1,398 @@
+/*
+ * 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 oic.simulator.clientcontroller.view.dialogs;
+
+import org.eclipse.jface.dialogs.TitleAreaDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.MessageBox;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+
+import java.util.Date;
+
+import org.oic.simulator.ArrayProperty;
+import org.oic.simulator.AttributeProperty;
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.DoubleProperty;
+import org.oic.simulator.ILogger.Level;
+import org.oic.simulator.IntegerProperty;
+import org.oic.simulator.SimulatorResourceAttribute;
+import org.oic.simulator.StringProperty;
+
+import oic.simulator.clientcontroller.Activator;
+import oic.simulator.clientcontroller.utils.AttributeValueBuilder;
+import oic.simulator.clientcontroller.utils.AttributeValueStringConverter;
+import oic.simulator.clientcontroller.utils.Utility;
+
+/**
+ * This class manages and shows the automation settings dialog from the
+ * attribute view.
+ */
+public class UpdatePrimitiveArrayAttributeDialog extends TitleAreaDialog {
+
+    private Text                       attNameTxt;
+    private Text                       currentValueTxt;
+    private Text                       newValueTxt;
+    private Text                       allowedValuesTxt;
+    private Text                       minRangeTxt;
+    private Text                       maxRangeTxt;
+    private Text                       allowDuplicatesTxt;
+    private Text                       additionalItemsTxt;
+    private SimulatorResourceAttribute attribute;
+    private String                     newValue;
+
+    private AttributeValue             newAttValueObj;
+
+    public UpdatePrimitiveArrayAttributeDialog(Shell parentShell,
+            SimulatorResourceAttribute attribute) {
+        super(parentShell);
+        this.attribute = attribute;
+    }
+
+    @Override
+    public void create() {
+        super.create();
+        setTitle("Modify Attribute's Value");
+        setMessage("Change the value of the array type attribute");
+    }
+
+    @Override
+    protected Control createDialogArea(Composite parent) {
+        Composite compLayout = (Composite) super.createDialogArea(parent);
+
+        Composite container = new Composite(compLayout, SWT.NONE);
+        container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+        GridLayout layout = new GridLayout(2, false);
+        layout.verticalSpacing = 10;
+        layout.marginTop = 10;
+        container.setLayout(layout);
+
+        GridData gd;
+
+        Label attNameLbl = new Label(container, SWT.NONE);
+        attNameLbl.setText("Attribute Name");
+
+        attNameTxt = new Text(container, SWT.READ_ONLY | SWT.BORDER);
+        attNameTxt.setBackground(container.getBackground());
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        attNameTxt.setLayoutData(gd);
+
+        Group subGroup = new Group(container, SWT.NONE);
+        subGroup.setText("Array Properties");
+        layout = new GridLayout(2, true);
+        subGroup.setLayout(layout);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.horizontalSpan = 2;
+        subGroup.setLayoutData(gd);
+
+        Composite minRangeContainer = new Composite(subGroup, SWT.NONE);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        minRangeContainer.setLayoutData(gd);
+        layout = new GridLayout(2, true);
+        minRangeContainer.setLayout(layout);
+
+        Label minRangeLbl = new Label(minRangeContainer, SWT.NONE);
+        minRangeLbl.setText("Minimum Items");
+
+        minRangeTxt = new Text(minRangeContainer, SWT.BORDER | SWT.READ_ONLY);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        minRangeTxt.setLayoutData(gd);
+        minRangeTxt.setBackground(container.getBackground());
+
+        Composite maxRangeContainer = new Composite(subGroup, SWT.NONE);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        maxRangeContainer.setLayoutData(gd);
+        layout = new GridLayout(2, true);
+        maxRangeContainer.setLayout(layout);
+
+        Label maxRangeLbl = new Label(maxRangeContainer, SWT.NONE);
+        maxRangeLbl.setText("Maximum Items");
+
+        maxRangeTxt = new Text(maxRangeContainer, SWT.BORDER | SWT.READ_ONLY);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        maxRangeTxt.setLayoutData(gd);
+        maxRangeTxt.setBackground(container.getBackground());
+
+        Composite uniqueContainer = new Composite(subGroup, SWT.NONE);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        uniqueContainer.setLayoutData(gd);
+        layout = new GridLayout(2, true);
+        uniqueContainer.setLayout(layout);
+
+        Label uniqueLbl = new Label(uniqueContainer, SWT.NONE);
+        uniqueLbl.setText("Allow Duplicates");
+
+        allowDuplicatesTxt = new Text(uniqueContainer, SWT.BORDER
+                | SWT.READ_ONLY);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        allowDuplicatesTxt.setLayoutData(gd);
+        allowDuplicatesTxt.setBackground(container.getBackground());
+
+        Composite addlItemsContainer = new Composite(subGroup, SWT.NONE);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        addlItemsContainer.setLayoutData(gd);
+        layout = new GridLayout(2, true);
+        addlItemsContainer.setLayout(layout);
+
+        Label addlItemsLbl = new Label(addlItemsContainer, SWT.NONE);
+        addlItemsLbl.setText("Allow Extra Items");
+
+        additionalItemsTxt = new Text(addlItemsContainer, SWT.BORDER
+                | SWT.READ_ONLY);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        additionalItemsTxt.setLayoutData(gd);
+        additionalItemsTxt.setBackground(container.getBackground());
+
+        Group elementPropGroup = new Group(container, SWT.NONE);
+        elementPropGroup.setText("Element Property");
+        layout = new GridLayout(2, false);
+        elementPropGroup.setLayout(layout);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.horizontalSpan = 2;
+        elementPropGroup.setLayoutData(gd);
+
+        Label allowedValuesLbl = new Label(elementPropGroup, SWT.NONE);
+        allowedValuesLbl.setText("Allowed Values");
+
+        allowedValuesTxt = new Text(elementPropGroup, SWT.MULTI | SWT.READ_ONLY
+                | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
+        allowedValuesTxt.setBackground(container.getBackground());
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessVerticalSpace = true;
+        gd.verticalAlignment = SWT.FILL;
+        gd.minimumHeight = 30;
+        allowedValuesTxt.setLayoutData(gd);
+
+        Label curValueLbl = new Label(container, SWT.NONE);
+        curValueLbl.setText("Current Value");
+
+        currentValueTxt = new Text(container, SWT.MULTI | SWT.READ_ONLY
+                | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
+        currentValueTxt.setBackground(container.getBackground());
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessVerticalSpace = true;
+        gd.verticalAlignment = SWT.FILL;
+        gd.minimumHeight = 30;
+        currentValueTxt.setLayoutData(gd);
+
+        Label attNewValue = new Label(container, SWT.NONE);
+        attNewValue.setText("New Value");
+
+        newValueTxt = new Text(container, SWT.MULTI | SWT.BORDER | SWT.WRAP
+                | SWT.V_SCROLL);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessVerticalSpace = true;
+        gd.verticalAlignment = SWT.FILL;
+        gd.minimumHeight = 60;
+        newValueTxt.setLayoutData(gd);
+        newValueTxt.setFocus();
+
+        Group hintGroup = new Group(container, SWT.NONE);
+        hintGroup.setText("Note");
+        layout = new GridLayout();
+        hintGroup.setLayout(layout);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.horizontalSpan = 2;
+        hintGroup.setLayoutData(gd);
+
+        Label hint = new Label(hintGroup, SWT.NULL);
+        hint.setText("Array values should be comma-seperated and surrounded by square brackets.\n"
+                + "Ex: \"[value]\", \"[value1,value2]\", \"[[value1], [value2]]\"");
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.horizontalSpan = 2;
+        gd.horizontalIndent = 40;
+        hint.setLayoutData(gd);
+
+        populateData();
+
+        return compLayout;
+    }
+
+    private void populateData() {
+        // Set the Attribute Name.
+        attNameTxt.setText(attribute.name());
+
+        // Set the allowed values.
+        ArrayProperty arrProp = attribute.property().asArray();
+        AttributeProperty elementProp = arrProp.getElementProperty();
+
+        StringBuilder values = new StringBuilder();
+        String value = "";
+        if (elementProp.isInteger()) {
+            IntegerProperty intProp = elementProp.asInteger();
+            if (intProp.hasRange()) {
+                value = intProp.min() + " - " + intProp.max();
+            } else if (intProp.hasValues()) {
+                int[] arr = intProp.getValues();
+                for (int i = 0; i < arr.length; i++) {
+                    values.append(arr[i]);
+                    if (i + 1 < arr.length) {
+                        values.append(", ");
+                    }
+                }
+
+                if (!values.toString().isEmpty()) {
+                    value = "[" + values + "]";
+                }
+            }
+        } else if (elementProp.isDouble()) {
+            DoubleProperty dblProp = elementProp.asDouble();
+            if (dblProp.hasRange()) {
+                value = dblProp.min() + " - " + dblProp.max();
+            } else if (dblProp.hasValues()) {
+                double[] arr = dblProp.getValues();
+                for (int i = 0; i < arr.length; i++) {
+                    values.append(arr[i]);
+                    if (i + 1 < arr.length) {
+                        values.append(", ");
+                    }
+                }
+
+                if (!values.toString().isEmpty()) {
+                    value = "[" + values + "]";
+                }
+            }
+        } else if (elementProp.isBoolean()) {
+            value = "[true, false]";
+        } else if (elementProp.isString()) {
+            StringProperty strProp = elementProp.asString();
+            if (strProp.hasValues()) {
+                String[] arr = strProp.getValues();
+                for (int i = 0; i < arr.length; i++) {
+                    values.append(arr[i]);
+                    if (i + 1 < arr.length) {
+                        values.append(", ");
+                    }
+                }
+
+                if (!values.toString().isEmpty()) {
+                    value = "[" + values + "]";
+                }
+            }
+        }
+
+        allowedValuesTxt.setText(value);
+
+        // Set the current value.
+        currentValueTxt.setText(new AttributeValueStringConverter(attribute
+                .value()).toString());
+
+        minRangeTxt.setText(String.valueOf(arrProp.minItems()));
+
+        maxRangeTxt.setText(String.valueOf(arrProp.maxItems()));
+
+        allowDuplicatesTxt.setText(!arrProp.isUnique() ? "Yes" : "No");
+
+        additionalItemsTxt.setText(arrProp.isVariable() ? "Yes" : "No");
+    }
+
+    public String getNewValue() {
+        return newValue;
+    }
+
+    public AttributeValue getNewValueObj() {
+        return newAttValueObj;
+    }
+
+    @Override
+    protected void okPressed() {
+        // Validate the value
+        newValue = newValueTxt.getText();
+        if (null == newValue || newValue.isEmpty()) {
+            return;
+        }
+
+        try {
+            String value = Utility.removeWhiteSpacesInArrayValues(newValue);
+            if (null != value && value.startsWith("[") && value.endsWith("]")) {
+                newAttValueObj = AttributeValueBuilder.build(value, attribute
+                        .value().typeInfo().mBaseType);
+                if (null != newAttValueObj) {
+                    close();
+                    return;
+                }
+            }
+        } catch (Exception e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "There is an error while building the new attribute value.\n"
+                                    + Utility.getSimulatorErrorString(e, null));
+        }
+
+        MessageBox dialog = new MessageBox(Display.getDefault()
+                .getActiveShell(), SWT.ICON_ERROR | SWT.OK);
+        dialog.setText("Invalid Value");
+        dialog.setMessage("Either the value of its format is invalid.\n"
+                + "Format: Array values should be comma-seperated and surrounded by square brackets.\n"
+                + "Ex: \"[value]\", \"[value1,value2]\", \"[[value1], [value2]]\"");
+        dialog.open();
+
+        newValueTxt.setFocus();
+    }
+
+    @Override
+    protected boolean isResizable() {
+        return true;
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+}
index a221760..1170e5b 100644 (file)
 
 package oic.simulator.clientcontroller.view.dialogs;
 
-import java.util.ArrayList;
-import java.util.Map;
-import java.util.Set;
-
-import oic.simulator.clientcontroller.Activator;
-import oic.simulator.clientcontroller.manager.ResourceManager;
-import oic.simulator.clientcontroller.utils.Constants;
-
 import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialog;
 import org.eclipse.jface.dialogs.TrayDialog;
 import org.eclipse.swt.SWT;
 import org.eclipse.swt.events.SelectionAdapter;
@@ -35,10 +26,15 @@ import org.eclipse.swt.layout.GridLayout;
 import org.eclipse.swt.widgets.Button;
 import org.eclipse.swt.widgets.Composite;
 import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
 import org.eclipse.swt.widgets.Group;
 import org.eclipse.swt.widgets.Shell;
 
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Set;
+
+import oic.simulator.clientcontroller.utils.Constants;
+
 /**
  * Dialog for starting and stopping the automatic verifications.
  */
@@ -89,38 +85,18 @@ public class VerificationDialog extends TrayDialog {
 
                 @Override
                 public void widgetSelected(SelectionEvent e) {
-                    boolean checked = checkbox.getSelection();
-                    boolean answer = MessageDialog.openQuestion(Display
-                            .getDefault().getActiveShell(), "Verification",
-                            "Do you want to "
-                                    + (checked ? "enable" : "disable")
-                                    + " the verification?");
-                    if (!answer) {
-                        checkbox.setSelection(!checked);
-                        checked = !checked;
-                    } else {
-                        ResourceManager resourceManager = Activator
-                                .getDefault().getResourceManager();
-                        String reqTypeTxt = checkbox.getText();
-                        int reqType;
-                        if (reqTypeTxt.equals("Get")) {
-                            reqType = Constants.GET_AUTOMATION_INDEX;
-                        } else if (reqTypeTxt.equals("Put")) {
-                            reqType = Constants.PUT_AUTOMATION_INDEX;
-                        } else {// if(reqTypeTxt.equals("Post")) {
-                            reqType = Constants.POST_AUTOMATION_INDEX;
-                        }
-                        if (checked) {
-                            resourceManager.startAutomationRequest(reqType,
-                                    resourceManager
-                                            .getCurrentResourceInSelection());
-                        } else {
-                            resourceManager.stopAutomationRequest(reqType,
-                                    resourceManager
-                                            .getCurrentResourceInSelection());
-                        }
+                    Button btn = (Button) e.getSource();
+                    if (null == btn) {
+                        return;
+                    }
+                    String btnText = btn.getText();
+                    if (btnText.equalsIgnoreCase(Constants.GET)) {
+                        automationStatus.put(Constants.GET, btn.getSelection());
+                    } else if (btnText.equalsIgnoreCase(Constants.PUT)) {
+                        automationStatus.put(Constants.PUT, btn.getSelection());
+                    } else if (btnText.equalsIgnoreCase(Constants.POST)) {
+                        automationStatus.put(Constants.POST, btn.getSelection());
                     }
-                    automationStatus.put(str, checked);
                 }
             });
         }
@@ -139,4 +115,8 @@ public class VerificationDialog extends TrayDialog {
     public boolean isHelpAvailable() {
         return false;
     }
+
+    public Map<String, Boolean> getAutomationStatus() {
+        return automationStatus;
+    }
 }
index c782557..fc1429e 100644 (file)
 
 package oic.simulator.logger;
 
-import java.util.ArrayList;
-import java.util.List;
-
 import org.eclipse.jface.viewers.ITreeContentProvider;
 import org.eclipse.jface.viewers.Viewer;
 
+import java.util.ArrayList;
+import java.util.List;
+
 /**
  * Maintains simulator log entries and provides content to the log view.
  */
index ca80ad1..f7c40c3 100644 (file)
 
 package oic.simulator.logger;
 
+import org.eclipse.jface.viewers.ITableLabelProvider;
+import org.eclipse.jface.viewers.LabelProvider;
+import org.eclipse.swt.graphics.Image;
+
 import java.text.DateFormat;
 import java.text.SimpleDateFormat;
 
 import oic.simulator.clientcontroller.manager.LogManager;
 
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.swt.graphics.Image;
-
 /**
  * Label provider which determines what data has to be shown in the log view.
  */
@@ -50,7 +50,14 @@ public class LogLabelProvider extends LabelProvider implements
         } else if (columnIndex == 1) {
             return dateFormat.format(entry.getDate());
         } else {
-            return entry.getMessage();
+            String msg = entry.getMessage();
+            if (null != msg) {
+                int pos = msg.indexOf('\n');
+                if (pos != -1) {
+                    msg = msg.substring(0, pos);
+                }
+            }
+            return msg;
         }
     }
 
index 81110b0..2c6393f 100644 (file)
@@ -19,11 +19,11 @@ package oic.simulator.logger;
 import java.util.Calendar;
 import java.util.Date;
 
+import org.oic.simulator.ILogger;
+
 import oic.simulator.clientcontroller.Activator;
 import oic.simulator.clientcontroller.utils.Constants;
 
-import org.oic.simulator.ILogger;
-
 /**
  * Class which provides a callback method to receive log from native layer.
  */
@@ -58,7 +58,7 @@ public class LoggerCallback implements ILogger {
 
                 Calendar calendar;
                 calendar = Calendar.getInstance();
-                calendar.set(Calendar.HOUR, h);
+                calendar.set(Calendar.HOUR_OF_DAY, h);
                 calendar.set(Calendar.MINUTE, m);
                 calendar.set(Calendar.SECOND, s);
 
index f79c607..046db29 100644 (file)
@@ -1,26 +1,68 @@
 Eclipse plug-in
+-----------------
 
-Pre-requisites
---------------
-    1.Build the IoTivity project for linux:
-        Run the "scons" command in iotivity home directory.
-        It generates the libraries in ~/iotivity/out/linux/<arch>/release directory.
-    2.Copy the libraries mentioned below into the libs folder of the plug-in project.
-        Required libraries: libSimulatorManager.so, liboc.so, liboctbstack.so, and liboc_logger.so
-    3.Import the Simulator Java SDK project from ~/iotivity/service/simulator/java/sdk/ into Eclipse IDE as given below.
-        File -> Import -> Select 'Existing projects into Workspace' under General category -> click next -> Browse to the above mentioned location ->
-        click Finish.
-      Export the sdk project as JAR file.
-        Right click the project -> Export -> select 'JAR file' option under Java -> Next -> Finish.
-      Copy the JAR file into the libs folder of the plug-in project.
-
-Steps to run the plug-in
-------------------------
-    1.Import the plug-in project from ~/iotivity/service/simulator/java/eclipse-plugin/ into Eclipse IDE as given below.
-        File -> Import -> Select 'Existing projects into Workspace' under General category -> click next -> Browse to the above mentioned location ->
-        click Finish.
-    2.Set the LD_LIBRARY_PATH environment variable
-        Right click the project -> Properties -> Run/Debug Settings -> Edit -> select 'Environment' tab -> click on 'Select' -> check LD_LIBRARY_PATH option -> Ok.
-        Edit the LD_LIBRARY_PATH and add the complete path to the libs folder of the plug-in project -> Apply -> OK.
-        Then Apply -> OK to close the properties window.
-    3.Right click the project -> Run As Eclipse Application.
\ No newline at end of file
+
+Pre-requisites to launch Eclipse plug-in
+------------------------------------------
+
+1.Eclipse IDE with PDE(Plug-in Development Environment) support.
+
+2.Execute the "scons SIMULATOR=1" command from the IoTivity home
+directory in the terminal to build Simulator specific libraries along
+with the iotivity native libraries.
+
+3.Simulator application requires liboc.so, liboctbstack.so and
+liboc_logger.so native libraries and libSimulatorManager.so,
+libRamlParser.so simulator specific libraries, all of which are
+generated in ~/iotivity/out/linux/<arch>/release directory.
+
+
+Setting up and launching the Eclipse plug-in projects
+--------------------------------------------------------
+
+1. Import the below projects into Eclipse IDE using File -> Import ->
+Select 'Existing projects into Workspace' under General category -> click
+next -> Browse to the location as given below -> Click Finish.
+
+i)   Service Provider Plugin:
+~/iotivity/service/simulator/java/eclipse-plugin/ServiceProviderPlugin
+
+ii)  Client Controller Plugin:
+~/iotivity/service/simulator/java/eclipse-plugin/ClientControllerPlugin
+
+iii) Simulator Java SDK: ~/iotivity/service/simulator/java/sdk
+
+
+2. Right click the Simulator Java SDK project -> Export -> select
+'JAR file' option under Java -> Next -> Select the export destination as
+ClientControllerPlugin\libs\Simulator.jar and ServiceProviderPlugin\libs\Simulator.jar -> Finish.
+
+
+3. Copy the libraries libSimulatorManager.so, libRamlParser.so, liboc.so,
+liboctbstack.so, and liboc_logger.so generated previously in
+~/iotivity/out/linux/<arch>/release directory into the libs folder of both the plug-in projects.
+
+
+4. Set the LD_LIBRARY_PATH environment variable. Right click any plug-in project -> Properties ->
+Run/Debug Settings. To configure the LD_LIBRARY_PATH, there needs to be a launch configuration.
+We may choose to use the existing launch configuration or create a new launch configuration.
+If no launch configurations exist, then a new one has to be created.
+To create a new launch configuration, select 'New' from Run/Debug settings ->
+select 'Eclipse Application' as the configuration type -> OK. It opens a new window for editing
+the launch configuration -> Change the launch configuration name(optional) -> Apply -> OK to close
+the Edit Configuration window.
+
+From Run/Debug settings, Choose a launch configuration and press Edit -> select 'Environment' tab
+-> Click on 'Select' -> check LD_LIBRARY_PATH option -> OK. Edit the LD_LIBRARY_PATH and add the
+complete path upto the libs folder of the plug-in project
+( ~/iotivity/service/simulator/java/eclipse-plugin/ClientControllerPlugin/libs)
+-> Apply -> OK. Then Apply -> OK to close the properties window.
+
+
+5. Right click the project -> Run as Eclipse Application -> If it prompts for a configuration,
+then select the one which was configured in the LD_LIBRARY_PATH in the previous step.
+
+
+Note: To switch the iotivity stack for conformance, need to build the latest iotivity code and
+replace liboc.so, liboctbstack.so, and liboc_logger.so native libraries in libs folder of
+respective plug-in applications.
index ad84a71..4e3db96 100644 (file)
@@ -1,8 +1,8 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <classpath>
-    <classpathentry kind="lib" path="libs/Simulator.jar"/>
-    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
     <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
     <classpathentry kind="src" path="src"/>
+    <classpathentry kind="lib" path="libs/Simulator.jar"/>
     <classpathentry kind="output" path="bin"/>
 </classpath>
index 08798e4..f91f396 100644 (file)
@@ -2,12 +2,26 @@ Manifest-Version: 1.0
 Bundle-ManifestVersion: 2
 Bundle-Name: ServiceProviderPlugin
 Bundle-SymbolicName: ServiceProviderPlugin;singleton:=true
-Bundle-Version: 1.0.0.qualifier
+Bundle-Version: 1.1.0.qualifier
 Bundle-Activator: oic.simulator.serviceprovider.Activator
 Require-Bundle: org.eclipse.ui,
  org.eclipse.core.runtime
 Bundle-RequiredExecutionEnvironment: JavaSE-1.7
 Bundle-ActivationPolicy: lazy
-Bundle-NativeCode: libs/libSimulatorManager.so
+Bundle-NativeCode: libs/linux-x86/liboc_logger.so;
+ libs/linux-x86/liboctbstack.so;
+ libs/linux-x86/libSimulatorManager.so;
+ libs/linux-x86/liboc.so; 
+ libs/linux-x86/libRamlParser.so;
+ osname=linux;
+ processor=x86,
+ libs/linux-x86_64/liboc_logger.so;
+ libs/linux-x86_64/liboctbstack.so;
+ libs/linux-x86_64/libSimulatorManager.so;
+ libs/linux-x86_64/liboc.so; 
+ libs/linux-x86_64/libRamlParser.so;
+ osname=linux;
+ processor=x86-64
 Bundle-ClassPath: libs/Simulator.jar,
  .
+Bundle-Vendor: IoTivity.org
index 3db1138..b522aba 100644 (file)
@@ -4,6 +4,5 @@ bin.includes = META-INF/,\
                .,\
                icons/,\
                plugin.xml,\
-               libs/,\
-               resource/
+               libs/
 
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/single_resource.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/single_resource.gif
new file mode 100644 (file)
index 0000000..0f07692
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/single_resource.gif differ
index 52ec74b..8fe0d3a 100644 (file)
             restorable="true">
          </view>
          <view category="oic.simulator.serviceprovider.category"
-            class="oic.simulator.serviceprovider.view.MultiResourceOrchestrationView"
+            class="oic.simulator.serviceprovider.view.DevicePlatformInfoView"
             icon="icons/oic_logo_16x16.png"
-            id="oic.simulator.serviceprovider.view.orchestration"
-            name="Multi-Resource Automation"
+            id="oic.simulator.serviceprovider.view.devplatinfo"
+            name="Device/Platform Info"
             restorable="true">
          </view>
          <view category="oic.simulator.serviceprovider.category"
@@ -76,7 +76,7 @@
                id="oic.simulator.serviceprovider.view.attribute">
          </viewShortcut>
          <viewShortcut
-               id="oic.simulator.serviceprovider.view.orchestration">
+               id="oic.simulator.serviceprovider.view.devplatinfo">
          </viewShortcut>
          <viewShortcut
                id="oic.simulator.serviceprovider.view.log">
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/resource/Light/simple-light-error.json b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/resource/Light/simple-light-error.json
deleted file mode 100644 (file)
index ceea4eb..0000000
+++ /dev/null
@@ -1,23 +0,0 @@
-{
-  "id": "simple.light#",
-  "$schema": "http://json-schema.org/draft-04/schema#",
-  "title": "Simple Light",
-  "$ref": "#/definitions/light",
-  "definitions": {
-    "light": {
-      "type": "object",
-      "properties": {
-               "resourceType": {
-          "type": "string",
-          "description": "Description about resource type",
-          "default": "sample.light"
-        },
-        "intensity":  {
-          "type": "string",
-          "description": "ReadOnly, Comma separated min,max values for intensity on this device",
-          "default": "1,20"
-        }
-      }
-    }
-  }
-}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/resource/Light/simple-light.json b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/resource/Light/simple-light.json
deleted file mode 100644 (file)
index e850b70..0000000
+++ /dev/null
@@ -1,34 +0,0 @@
-{
-  "id": "simple.light#",
-  "$schema": "http://json-schema.org/schema#",
-  "title": "Simple Light",
-  "$ref": "#/definitions/light",
-  "definitions": {
-    "light": {
-      "type": "object",
-      "properties": {
-               "resourceType": {
-          "type": "string",
-          "description": "Description about resource type",
-          "default": "sample.light"
-        },
-               "power": {
-                 "type": "string",
-                 "description": "Light status",
-                 "default": "on",
-                 "enum": ["on","off"],
-                 "update_frequency": 1000
-                 },
-               "intensity": {
-                 "type": "integer",
-                 "description": "brightness of the light",
-                 "default": 1,
-                 "minimum": 1,
-          "maximum": 20,                 
-                 "update_frequency": 1001
-                 }
-                }
-               }
-       },      
-  "required": [ "resourceType", "power" ]
-}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/resource/Light/simple-light.raml b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/resource/Light/simple-light.raml
deleted file mode 100644 (file)
index 3725c6b..0000000
+++ /dev/null
@@ -1,81 +0,0 @@
-#%RAML 0.8
-title: Simple Light
-version: v1.0-20150910
-schemas:
-  - LightSchema: !include simple-light.json
-    LightSchemaError: !include simple-light-error.json
-
-/sample/light:
-  description: Resource to be exposed by any Simple Device that can act as Light.
-  displayName: Simple Light
-  get:
-    responses:
-      200:
-        body:
-          application/json:
-            schema: LightSchema
-            example: |
-              {
-                "resourceType": "sample.light",
-                "power":  "off"
-              }
-  put:
-    body:
-      application/json:
-        schema: LightSchema
-        example: |
-          {
-            "power":  "off",
-            "intensity": 5
-          }
-    responses:
-      200:
-        body:
-          application/json:
-            schema: LightSchema
-            example: |
-              {
-                "power":  "off",
-                "intensity": 5
-              }
-      403:
-        description: |
-          This response is generated by the Server when the client sends:
-            An update with an out of range property value for intensity.
-          The server responds with the range property illustrating the error.
-        body:
-          application/json:
-            schema: LightSchemaError
-            example: |
-              {
-                "range":  "1,20"
-              }
-  post:
-    body:
-      application/json:
-        schema: LightSchema
-        example: |
-          {
-            "power":  "off"
-          }
-    responses:
-      200:
-        body:
-          application/json:
-            schema: LightSchema
-            example: |
-              {
-                "power":  "off"
-              }
-      403:
-        description: |
-          This response is generated by the Server when the client sends:
-            An update with an out of range property value for intensity.
-          The server responds with the range property illustrating the error.
-        body:
-          application/json:
-            schema: LightSchemaError
-            example: |
-              {
-                "range":  "1,20"
-              }
index c782557..fc1429e 100644 (file)
 
 package oic.simulator.logger;
 
-import java.util.ArrayList;
-import java.util.List;
-
 import org.eclipse.jface.viewers.ITreeContentProvider;
 import org.eclipse.jface.viewers.Viewer;
 
+import java.util.ArrayList;
+import java.util.List;
+
 /**
  * Maintains simulator log entries and provides content to the log view.
  */
index f392bc8..a775ef4 100644 (file)
 
 package oic.simulator.logger;
 
+import org.eclipse.jface.viewers.ITableLabelProvider;
+import org.eclipse.jface.viewers.LabelProvider;
+import org.eclipse.swt.graphics.Image;
+
 import java.text.DateFormat;
 import java.text.SimpleDateFormat;
 
 import oic.simulator.serviceprovider.manager.LogManager;
 
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.swt.graphics.Image;
-
 /**
  * Label provider which determines what data has to be shown in the log view.
  */
@@ -50,7 +50,14 @@ public class LogLabelProvider extends LabelProvider implements
         } else if (columnIndex == 1) {
             return dateFormat.format(entry.getDate());
         } else {
-            return entry.getMessage();
+            String msg = entry.getMessage();
+            if (null != msg) {
+                int pos = msg.indexOf('\n');
+                if (pos != -1) {
+                    msg = msg.substring(0, pos);
+                }
+            }
+            return msg;
         }
     }
 
index 83d02fa..a130f19 100644 (file)
@@ -19,11 +19,11 @@ package oic.simulator.logger;
 import java.util.Calendar;
 import java.util.Date;
 
+import org.oic.simulator.ILogger;
+
 import oic.simulator.serviceprovider.Activator;
 import oic.simulator.serviceprovider.utils.Constants;
 
-import org.oic.simulator.ILogger;
-
 /**
  * Class which provides a callback method to receive log from native layer.
  */
index f9816d3..e49f523 100644 (file)
 
 package oic.simulator.serviceprovider;
 
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.osgi.framework.BundleContext;
+
 import oic.simulator.serviceprovider.manager.ImageManager;
 import oic.simulator.serviceprovider.manager.LogManager;
 import oic.simulator.serviceprovider.manager.ResourceManager;
 
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.osgi.framework.BundleContext;
-
 /**
  * The activator class controls the plug-in life cycle.
  */
@@ -40,10 +40,6 @@ public class Activator extends AbstractUIPlugin {
 
     private static ImageManager    imageManager;
 
-    static {
-        System.loadLibrary("SimulatorManager");
-    }
-
     public Activator() {
     }
 
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IAutomationListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IAutomationListener.java
new file mode 100644 (file)
index 0000000..9d566e9
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.listener;
+
+import oic.simulator.serviceprovider.model.SingleResource;
+
+/**
+ * Interface through which the automation events are notified to the UI
+ * listeners.
+ */
+public interface IAutomationListener {
+    public void onResourceAutomationStart(SingleResource resource);
+
+    public void onAutomationComplete(SingleResource resource, String attName);
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IAutomationUIListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IAutomationUIListener.java
deleted file mode 100644 (file)
index 215fb5f..0000000
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * 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.
- */
-
-package oic.simulator.serviceprovider.listener;
-
-/**
- * Interface through which the automation events are notified to the UI
- * listeners.
- */
-public interface IAutomationUIListener {
-    public void onResourceAutomationStart(String resourceURI);
-
-    public void onAutomationComplete(String resourceURI, String attName);
-}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IDataChangeListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IDataChangeListener.java
new file mode 100644 (file)
index 0000000..552ddc6
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.listener;
+
+import oic.simulator.serviceprovider.model.AttributeElement;
+
+public interface IDataChangeListener {
+    public void add(AttributeElement attribute);
+
+    public void remove(AttributeElement attribute);
+
+    public void update(AttributeElement attribute);
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IDeviceInfoListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IDeviceInfoListener.java
new file mode 100644 (file)
index 0000000..cf79433
--- /dev/null
@@ -0,0 +1,21 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.listener;
+
+public interface IDeviceInfoListener {
+    public void onDeviceInfoFound();
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/ILogListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/ILogListener.java
new file mode 100644 (file)
index 0000000..c13986b
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.listener;
+
+import java.util.List;
+
+import oic.simulator.logger.LogEntry;
+
+/**
+ * Interface through which the log events are sent to the UI listeners.
+ */
+public interface ILogListener {
+    public void logAdded(LogEntry added);
+
+    public void logChanged(List<LogEntry> entry);
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/ILogUIListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/ILogUIListener.java
deleted file mode 100644 (file)
index 8a3a2f8..0000000
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * 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.
- */
-
-package oic.simulator.serviceprovider.listener;
-
-import java.util.List;
-
-import oic.simulator.logger.LogEntry;
-
-/**
- * Interface through which the log events are sent to the UI listeners.
- */
-public interface ILogUIListener {
-    public void logAdded(LogEntry added);
-
-    public void logChanged(List<LogEntry> entry);
-}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IObserverListChangedListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IObserverListChangedListener.java
new file mode 100644 (file)
index 0000000..56a5f07
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.listener;
+
+import oic.simulator.serviceprovider.model.Resource;
+
+/**
+ * Interface through which the resource observer events are sent to the UI
+ * listeners.
+ */
+public interface IObserverListChangedListener {
+    public void onObserverListChanged(Resource resource);
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IObserverListChangedUIListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IObserverListChangedUIListener.java
deleted file mode 100644 (file)
index 3beb52a..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * 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.
- */
-
-package oic.simulator.serviceprovider.listener;
-
-/**
- * Interface through which the resource observer events are sent to the UI
- * listeners.
- */
-public interface IObserverListChangedUIListener {
-    public void onObserverListChanged(String resourceURI);
-}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IPropertiesChangedListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IPropertiesChangedListener.java
new file mode 100644 (file)
index 0000000..d45dca5
--- /dev/null
@@ -0,0 +1,25 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.listener;
+
+/**
+ * Interface through which the resource property change UI events are sent to
+ * the other UI listeners.
+ */
+public interface IPropertiesChangedListener {
+    public void onResourcePropertyChange();
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceListChangedListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceListChangedListener.java
new file mode 100644 (file)
index 0000000..0e716a6
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.listener;
+
+import oic.simulator.serviceprovider.model.ResourceType;
+
+/**
+ * Interface through which the resource creation/deletion events are sent to the
+ * UI listeners.
+ */
+public interface IResourceListChangedListener {
+    public void onResourceCreation(ResourceType type);
+
+    public void onResourceDeletion(ResourceType type);
+
+    public void onResourceListUpdate(ResourceType type);
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceListChangedUIListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceListChangedUIListener.java
deleted file mode 100644 (file)
index b5eb331..0000000
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * 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.
- */
-
-package oic.simulator.serviceprovider.listener;
-
-/**
- * Interface through which the resource creation/deletion events are sent to the
- * UI listeners.
- */
-public interface IResourceListChangedUIListener {
-    public void onResourceCreation();
-
-    public void onResourceDeletion();
-}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceModelChangedUIListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceModelChangedUIListener.java
deleted file mode 100644 (file)
index b778e0e..0000000
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * 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.
- */
-
-package oic.simulator.serviceprovider.listener;
-
-import java.util.Set;
-
-import oic.simulator.serviceprovider.resource.ModelChangeNotificationType;
-import oic.simulator.serviceprovider.resource.LocalResourceAttribute;
-
-/**
- * Interface through which the resource model change events are sent to the UI
- * listeners.
- */
-public interface IResourceModelChangedUIListener {
-    public void onResourceModelChange(
-            ModelChangeNotificationType notificationType, String resourceURI,
-            Set<LocalResourceAttribute> valueChangeSet);
-}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceSelectionChangedUIListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceSelectionChangedUIListener.java
deleted file mode 100644 (file)
index dc891da..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * 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.
- */
-
-package oic.simulator.serviceprovider.listener;
-
-/**
- * Interface through which the resource selection UI event is sent to the other
- * UI listeners.
- */
-public interface IResourceSelectionChangedUIListener {
-    public void onResourceSelectionChange();
-}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/ISelectionChangedListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/ISelectionChangedListener.java
new file mode 100644 (file)
index 0000000..8276767
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.listener;
+
+import oic.simulator.serviceprovider.model.Resource;
+
+/**
+ * Interface through which the resource selection UI event is sent to the other
+ * UI listeners.
+ */
+public interface ISelectionChangedListener {
+    public void onResourceSelectionChange(Resource resource);
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/Data.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/Data.java
new file mode 100644 (file)
index 0000000..b8a4674
--- /dev/null
@@ -0,0 +1,134 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.manager;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.model.SingleResource;
+
+public class Data {
+    private Map<String, SingleResource> singleResourceMap;
+
+    public Data() {
+        singleResourceMap = new HashMap<String, SingleResource>();
+    }
+
+    public synchronized void addResource(Resource resource) {
+        if (null == resource) {
+            return;
+        }
+        if (resource instanceof SingleResource) {
+            singleResourceMap.put(resource.getResourceURI(),
+                    (SingleResource) resource);
+        }
+    }
+
+    public synchronized void deleteResource(Resource resource) {
+        if (null == resource) {
+            return;
+        }
+        if (resource instanceof SingleResource) {
+            singleResourceMap.remove(resource.getResourceURI());
+        }
+    }
+
+    public List<SingleResource> getSingleResources() {
+        List<SingleResource> resources;
+        synchronized (singleResourceMap) {
+            if (singleResourceMap.isEmpty()) {
+                return null;
+            }
+            resources = new ArrayList<SingleResource>();
+            Set<String> uriSet = singleResourceMap.keySet();
+            Iterator<String> itr = uriSet.iterator();
+            while (itr.hasNext()) {
+                resources.add(singleResourceMap.get(itr.next()));
+            }
+        }
+        return resources;
+    }
+
+    public List<Resource> getResources() {
+        if (singleResourceMap.isEmpty()) {
+            return null;
+        }
+        List<Resource> resourceList = new ArrayList<Resource>();
+        synchronized (singleResourceMap) {
+            Set<String> uriSet = singleResourceMap.keySet();
+            Iterator<String> itr = uriSet.iterator();
+            while (itr.hasNext()) {
+                resourceList.add(singleResourceMap.get(itr.next()));
+            }
+        }
+        return resourceList;
+    }
+
+    public synchronized boolean isResourceExist(String resourceURI) {
+        if (null == resourceURI || resourceURI.isEmpty()) {
+            return false;
+        }
+        if ((null != singleResourceMap && singleResourceMap
+                .containsKey(resourceURI))) {
+            return true;
+        }
+        return false;
+    }
+
+    public synchronized boolean isAnyResourceExist() {
+        return ((null != singleResourceMap && !singleResourceMap.isEmpty()));
+    }
+
+    public void changeResourceURI(Resource resource, String curURI,
+            String newURI) {
+        if (null == resource || null == curURI || null == newURI) {
+            return;
+        }
+        if (resource instanceof SingleResource) {
+            synchronized (singleResourceMap) {
+                singleResourceMap.remove(curURI);
+                singleResourceMap.put(newURI, (SingleResource) resource);
+            }
+        }
+        resource.setResourceURI(newURI);
+    }
+
+    public SingleResource getSingleResourceByURI(String resourceURI) {
+        if (null == resourceURI) {
+            return null;
+        }
+        SingleResource res;
+        synchronized (singleResourceMap) {
+            res = singleResourceMap.get(resourceURI);
+        }
+        return res;
+    }
+
+    public Resource getResourceByURI(String resourceURI) {
+        Resource res = getSingleResourceByURI(resourceURI);
+        return res;
+    }
+
+    public synchronized int getResourceCount() {
+        return singleResourceMap.size();
+    }
+}
index ee700d1..c054533 100644 (file)
 
 package oic.simulator.serviceprovider.manager;
 
-import java.net.URL;
-
-import oic.simulator.serviceprovider.Activator;
-import oic.simulator.serviceprovider.utils.Constants;
-
 import org.eclipse.jface.resource.ImageDescriptor;
 import org.eclipse.jface.resource.ImageRegistry;
 import org.eclipse.swt.graphics.Image;
 import org.osgi.framework.Bundle;
 
+import java.net.URL;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.utils.Constants;
+
 /**
  * Class which loads the icons/images into the image registry, and has methods
  * to handle the image related requests from other UI modules.
@@ -56,8 +56,8 @@ public class ImageManager {
                 .createFromURL(bundle.getEntry("icons/button_pressed.PNG")));
 
         // Resource icons based on the resource type
-        r.put(Constants.SAMPLE_LIGHT, ImageDescriptor.createFromURL(bundle
-                .getEntry("/icons/light_16x16.png")));
+        r.put(Constants.SINGLE_RESOURCE, ImageDescriptor.createFromURL(bundle
+                .getEntry("/icons/single_resource.gif")));
 
         // Log View related icons
         r.put(Constants.DEBUG_LOG, ImageDescriptor.createFromURL(bundle
index e7ca9a9..5c35db6 100644 (file)
 
 package oic.simulator.serviceprovider.manager;
 
+import org.eclipse.jface.resource.ImageRegistry;
+import org.eclipse.swt.graphics.Image;
+
 import java.util.ArrayList;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.LinkedList;
 
+import org.oic.simulator.ILogger;
+import org.oic.simulator.ILogger.Level;
+import org.oic.simulator.SimulatorManager;
+
 import oic.simulator.logger.LogEntry;
 import oic.simulator.logger.LoggerCallback;
 import oic.simulator.serviceprovider.Activator;
-import oic.simulator.serviceprovider.listener.ILogUIListener;
+import oic.simulator.serviceprovider.listener.ILogListener;
 import oic.simulator.serviceprovider.utils.Constants;
 
-import org.eclipse.jface.resource.ImageRegistry;
-import org.eclipse.swt.graphics.Image;
-import org.oic.simulator.ILogger;
-import org.oic.simulator.ILogger.Level;
-import org.oic.simulator.SimulatorManager;
-
 /**
  * Class which handles the native logs, maintains log entries and updates the
  * UI.
  */
 public class LogManager {
     private LinkedList<LogEntry>         entries           = new LinkedList<LogEntry>();
-    private ArrayList<ILogUIListener>    listeners         = new ArrayList<ILogUIListener>();
+    private ArrayList<ILogListener>      listeners         = new ArrayList<ILogListener>();
     private LinkedList<LogEntry>         visibleEntries    = new LinkedList<LogEntry>();
     private HashMap<Integer, Boolean>    visibleSeverities = new HashMap<Integer, Boolean>();
 
@@ -154,13 +155,13 @@ public class LogManager {
     }
 
     private void notifyListeners() {
-        for (ILogUIListener l : listeners) {
+        for (ILogListener l : listeners) {
             l.logChanged(new ArrayList<LogEntry>(visibleEntries));
         }
     }
 
     private void notifyListeners(LogEntry added) {
-        for (ILogUIListener l : listeners) {
+        for (ILogListener l : listeners) {
             l.logAdded(added);
         }
     }
@@ -199,7 +200,7 @@ public class LogManager {
         }
     }
 
-    public void addLogListener(final ILogUIListener listener) {
+    public void addLogListener(final ILogListener listener) {
         synchronizerThread.addToQueue(new Runnable() {
             @Override
             public void run() {
@@ -210,7 +211,7 @@ public class LogManager {
         });
     }
 
-    public void removeLogListener(final ILogUIListener listener) {
+    public void removeLogListener(final ILogListener listener) {
         synchronizerThread.addToQueue(new Runnable() {
             @Override
             public void run() {
index e6cca32..dc11654 100644 (file)
 
 package oic.simulator.serviceprovider.manager;
 
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.swt.widgets.Display;
+
+import java.text.NumberFormat;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Date;
-import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
-
-import oic.simulator.serviceprovider.Activator;
-import oic.simulator.serviceprovider.listener.IAutomationUIListener;
-import oic.simulator.serviceprovider.listener.IObserverListChangedUIListener;
-import oic.simulator.serviceprovider.listener.IResourceListChangedUIListener;
-import oic.simulator.serviceprovider.listener.IResourceModelChangedUIListener;
-import oic.simulator.serviceprovider.listener.IResourceSelectionChangedUIListener;
-import oic.simulator.serviceprovider.resource.LocalResourceAttribute;
-import oic.simulator.serviceprovider.resource.MetaProperty;
-import oic.simulator.serviceprovider.resource.ModelChangeNotificationType;
-import oic.simulator.serviceprovider.resource.SimulatorResource;
-import oic.simulator.serviceprovider.resource.StandardConfiguration;
-import oic.simulator.serviceprovider.utils.Constants;
-import oic.simulator.serviceprovider.utils.Utility;
-
-import org.eclipse.swt.graphics.Image;
-import org.oic.simulator.IAutomation;
+import java.util.Vector;
+
+import org.oic.simulator.ArrayProperty;
+import org.oic.simulator.AttributeProperty;
+import org.oic.simulator.AttributeProperty.Type;
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.AttributeValue.TypeInfo;
+import org.oic.simulator.AttributeValue.ValueType;
+import org.oic.simulator.BooleanProperty;
+import org.oic.simulator.DeviceInfo;
+import org.oic.simulator.DeviceListener;
+import org.oic.simulator.DoubleProperty;
 import org.oic.simulator.ILogger.Level;
-import org.oic.simulator.ResourceAttribute;
-import org.oic.simulator.ResourceAttribute.Range;
-import org.oic.simulator.ResourceAttribute.Type;
+import org.oic.simulator.IntegerProperty;
+import org.oic.simulator.PlatformInfo;
 import org.oic.simulator.SimulatorException;
 import org.oic.simulator.SimulatorManager;
+import org.oic.simulator.SimulatorResourceAttribute;
 import org.oic.simulator.SimulatorResourceModel;
-import org.oic.simulator.serviceprovider.AutomationType;
-import org.oic.simulator.serviceprovider.IObserver;
-import org.oic.simulator.serviceprovider.IResourceModelChangedListener;
-import org.oic.simulator.serviceprovider.ObserverInfo;
-import org.oic.simulator.serviceprovider.SimulatorResourceServer;
+import org.oic.simulator.StringProperty;
+import org.oic.simulator.server.Observer;
+import org.oic.simulator.server.SimulatorResource;
+import org.oic.simulator.server.SimulatorResource.AutoUpdateListener;
+import org.oic.simulator.server.SimulatorResource.AutoUpdateType;
+import org.oic.simulator.server.SimulatorResource.ObserverListener;
+import org.oic.simulator.server.SimulatorResource.ResourceModelChangeListener;
+import org.oic.simulator.server.SimulatorSingleResource;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.model.AttributeElement;
+import oic.simulator.serviceprovider.model.MetaProperty;
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.model.ResourceType;
+import oic.simulator.serviceprovider.model.SingleResource;
+import oic.simulator.serviceprovider.utils.AttributeValueStringConverter;
+import oic.simulator.serviceprovider.utils.Constants;
+import oic.simulator.serviceprovider.utils.Utility;
 
 /**
  * This class acts as an interface between the simulator java SDK and the
@@ -65,49 +76,59 @@ import org.oic.simulator.serviceprovider.SimulatorResourceServer;
  */
 public class ResourceManager {
 
-    private Map<String, Map<String, SimulatorResource>> resourceMap;
-
-    private Map<String, ArrayList<String>>              orderedResourceUriMap;
-
-    private Map<String, String>                         displayNameMap;
+    private Data                           data;
 
-    private StandardConfiguration                       stdConfig;
+    private Resource                       currentResourceInSelection;
 
-    private SimulatorResource                           currentResourceInSelection;
+    private ResourceModelChangeListener    resourceModelChangeListener;
 
-    private List<IResourceListChangedUIListener>        resourceListChangedUIListeners;
+    private AutoUpdateListener             automationListener;
 
-    private List<IResourceSelectionChangedUIListener>   resourceSelectionChangedUIListeners;
+    private ObserverListener               observer;
 
-    private List<IResourceModelChangedUIListener>       resourceModelChangedUIListeners;
+    private DeviceListener                 deviceListener;
 
-    private List<IAutomationUIListener>                 automationUIListeners;
+    private NotificationSynchronizerThread synchronizerThread;
 
-    private List<IObserverListChangedUIListener>        observerUIListeners;
+    private Thread                         threadHandle;
 
-    private IResourceModelChangedListener               resourceModelChangeListener;
+    private DeviceInfo                     deviceInfo;
+    private PlatformInfo                   platformInfo;
 
-    private IAutomation                                 automationListener;
+    private String                         deviceName;
 
-    private IObserver                                   observer;
-
-    private NotificationSynchronizerThread              synchronizerThread;
+    public ResourceManager() {
+        data = new Data();
 
-    private Thread                                      threadHandle;
+        deviceListener = new DeviceListener() {
 
-    public ResourceManager() {
-        resourceMap = new HashMap<String, Map<String, SimulatorResource>>();
-        orderedResourceUriMap = new HashMap<String, ArrayList<String>>();
-        displayNameMap = new HashMap<String, String>();
-        stdConfig = new StandardConfiguration();
+            @Override
+            public void onDeviceFound(final String host,
+                    final DeviceInfo deviceInfo) {
+                if (null != ResourceManager.this.deviceInfo
+                        || null == deviceInfo || null == host) {
+                    return;
+                }
+                synchronizerThread.addToQueue(new Runnable() {
+                    @Override
+                    public void run() {
+                        String rcvdDeviceName = deviceInfo.getName();
+                        if (null == rcvdDeviceName) {
+                            return;
+                        }
+                        if (deviceName.equalsIgnoreCase(rcvdDeviceName)) {
+                            ResourceManager.this.deviceInfo = deviceInfo;
 
-        resourceListChangedUIListeners = new ArrayList<IResourceListChangedUIListener>();
-        resourceSelectionChangedUIListeners = new ArrayList<IResourceSelectionChangedUIListener>();
-        resourceModelChangedUIListeners = new ArrayList<IResourceModelChangedUIListener>();
-        automationUIListeners = new ArrayList<IAutomationUIListener>();
-        observerUIListeners = new ArrayList<IObserverListChangedUIListener>();
+                            // Notify the UI Listeners
+                            UiListenerHandler.getInstance()
+                                    .deviceInfoReceivedNotification();
+                        }
+                    }
+                });
+            }
+        };
 
-        resourceModelChangeListener = new IResourceModelChangedListener() {
+        resourceModelChangeListener = new ResourceModelChangeListener() {
 
             @Override
             public void onResourceModelChanged(final String resourceURI,
@@ -119,59 +140,46 @@ public class ResourceManager {
                         if (null == resourceURI || null == resourceModelN) {
                             return;
                         }
-                        SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
-                        if (null == resource) {
-                            return;
-                        }
-
-                        ModelChangeNotificationType notificationType;
-                        // Fetch the resource attributes
-                        Map<String, LocalResourceAttribute> resourceAttributeMapNew;
-                        resourceAttributeMapNew = fetchResourceAttributesFromModel(resourceModelN);
-                        if (null == resourceAttributeMapNew) {
-                            resource.setResourceAttributesMap(null);
-                            resourceModelChangedUINotification(
-                                    ModelChangeNotificationType.NO_ATTRIBUTES_IN_MODEL,
-                                    resourceURI, null);
-                            return;
-                        }
 
-                        // Update the resource with new model data
-                        Map<String, LocalResourceAttribute> resourceAttributeMapOld;
-                        resourceAttributeMapOld = resource
-                                .getResourceAttributesMap();
-                        if (null == resourceAttributeMapOld) {
-                            resource.setResourceAttributesMap(resourceAttributeMapNew);
-                            resourceModelChangedUINotification(
-                                    ModelChangeNotificationType.ATTRIBUTE_ADDED,
-                                    resourceURI, null);
-                            return;
-                        }
-                        Set<LocalResourceAttribute> valueChangeSet = new HashSet<LocalResourceAttribute>();
-                        notificationType = compareAndUpdateLocalAttributes(
-                                resourceAttributeMapOld,
-                                resourceAttributeMapNew, valueChangeSet);
-                        if (notificationType != ModelChangeNotificationType.NONE) {
-                            // Update the UI listeners
-                            resourceModelChangedUINotification(
-                                    notificationType, resourceURI,
-                                    valueChangeSet);
-                        }
+                        Display.getDefault().asyncExec(new Runnable() {
+                            @Override
+                            public void run() {
+                                Resource resource = data
+                                        .getResourceByURI(resourceURI);
+                                if (null != resource) {
+                                    try {
+                                        resource.updateResourceRepresentation(resourceModelN);
+                                    } catch (NumberFormatException e) {
+                                        Activator
+                                                .getDefault()
+                                                .getLogManager()
+                                                .log(Level.ERROR.ordinal(),
+                                                        new Date(),
+                                                        "Error while trying to update the attributes.\n"
+                                                                + Utility
+                                                                        .getSimulatorErrorString(
+                                                                                e,
+                                                                                null));
+                                    }
+                                }
+                            }
+                        });
                     }
                 });
             }
         };
 
-        automationListener = new IAutomation() {
+        automationListener = new AutoUpdateListener() {
 
             @Override
-            public void onAutomationComplete(final String resourceURI,
+            public void onUpdateComplete(final String resourceURI,
                     final int automationId) {
                 synchronizerThread.addToQueue(new Runnable() {
 
                     @Override
                     public void run() {
-                        SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
+                        SingleResource resource = data
+                                .getSingleResourceByURI(resourceURI);
                         if (null == resource) {
                             return;
                         }
@@ -180,40 +188,38 @@ public class ResourceManager {
                         if (resource.isResourceAutomationInProgress()) {
                             changeResourceLevelAutomationStatus(resource, false);
                             // Notify the UI listeners
-                            automationCompleteUINotification(resourceURI, null);
+                            UiListenerHandler.getInstance()
+                                    .automationCompleteUINotification(resource,
+                                            null);
                         } else if (resource.isAttributeAutomationInProgress()) {
                             // Find the attribute with the given automation id
-                            LocalResourceAttribute attribute;
-                            attribute = getAttributeWithGivenAutomationId(
+                            final AttributeElement attribute = getAttributeWithGivenAutomationId(
                                     resource, automationId);
                             if (null != attribute) {
-                                attribute.setAutomationInProgress(false);
+                                attribute.setAutoUpdateState(false);
                                 resource.setAttributeAutomationInProgress(isAnyAttributeInAutomation(resource));
-                                // Notify the UI listeners
-                                automationCompleteUINotification(resourceURI,
-                                        attribute.getAttributeName());
+                            } else {
+                                // Setting the attribute automation status to
+                                // false.
+                                resource.setAttributeAutomationInProgress(false);
                             }
-                        } else {
-                            // Ignoring the notification as there are no
-                            // known automation for the current resource.
                         }
                     }
                 });
             }
         };
 
-        observer = new IObserver() {
+        observer = new ObserverListener() {
 
-            @Override
             public void onObserverChanged(final String resourceURI,
-                    final int status, final ObserverInfo observer) {
+                    final int status, final Observer observer) {
                 new Thread() {
                     @Override
                     public void run() {
                         if (null == resourceURI || null == observer) {
                             return;
                         }
-                        SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
+                        Resource resource = data.getResourceByURI(resourceURI);
                         if (null == resource) {
                             return;
                         }
@@ -224,16 +230,79 @@ public class ResourceManager {
                             resource.removeObserverInfo(observer);
                         }
                         // Notify the UI listeners
-                        observerListChangedUINotification(resourceURI);
+                        UiListenerHandler.getInstance()
+                                .observerListChangedUINotification(resource);
                     }
                 }.start();
             }
+
+            @Override
+            public void onObserverAdded(String resourceURI, Observer observer) {
+                onObserverChanged(resourceURI, 0, observer);
+            }
+
+            @Override
+            public void onObserverRemoved(String resourceURI, Observer observer) {
+                onObserverChanged(resourceURI, 1, observer);
+            }
         };
 
         synchronizerThread = new NotificationSynchronizerThread();
         threadHandle = new Thread(synchronizerThread);
         threadHandle.setName("Simulator service provider event queue");
         threadHandle.start();
+
+        // Set the default device name.
+        deviceName = "IoTivity Simulator";
+        try {
+            SimulatorManager.setDeviceInfo(deviceName);
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "Error while registering the device info.\n"
+                                    + Utility.getSimulatorErrorString(e, null));
+        }
+
+        // Set the default platform information.
+        platformInfo = new PlatformInfo();
+        platformInfo.setPlatformID("Samsung Platform Identifier");
+        platformInfo.setManufacturerName("Samsung");
+        platformInfo.setManufacturerUrl("www.samsung.com");
+        platformInfo.setModelNumber("Samsung Model Num01");
+        platformInfo.setDateOfManufacture("2015-09-10T11:10:30Z");
+        platformInfo.setPlatformVersion("PlatformVersion01");
+        platformInfo.setOperationSystemVersion("OSVersion01");
+        platformInfo.setHardwareVersion("HardwareVersion01");
+        platformInfo.setFirmwareVersion("FirwareVersion01");
+        platformInfo.setSupportUrl("http://www.samsung.com/support");
+        platformInfo.setSystemTime("2015-09-10T11:10:30Z");
+        try {
+            SimulatorManager.setPlatformInfo(platformInfo);
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "Error while registering the platform info.\n"
+                                    + Utility.getSimulatorErrorString(e, null));
+        }
+
+        // Get the device information to show other details of the device in UI.
+        try {
+            SimulatorManager.findDevices("", deviceListener);
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "Failed to get the local device information.\n"
+                                    + Utility.getSimulatorErrorString(e, null));
+        }
     }
 
     private static class NotificationSynchronizerThread implements Runnable {
@@ -277,1079 +346,1037 @@ public class ResourceManager {
         }
     }
 
-    // This method gives a list of available RAML resource configurations.
-    public Map<String, String> getResourceConfigurationList() {
-        return stdConfig.getStandardResourceConfigurationList();
-    }
-
-    public String getConfigFilePath(String fileName) {
-        return stdConfig.getFilePath(fileName);
-    }
-
-    public void addResourceListChangedUIListener(
-            IResourceListChangedUIListener resourceListChangedUIListener) {
-        synchronized (resourceListChangedUIListeners) {
-            resourceListChangedUIListeners.add(resourceListChangedUIListener);
+    public void setDeviceInfo(List<MetaProperty> metaProperties) {
+        if (null == metaProperties || metaProperties.size() < 1) {
+            return;
         }
-    }
-
-    public void addResourceSelectionChangedUIListener(
-            IResourceSelectionChangedUIListener resourceSelectionChangedUIListener) {
-        synchronized (resourceSelectionChangedUIListeners) {
-            resourceSelectionChangedUIListeners
-                    .add(resourceSelectionChangedUIListener);
+        Iterator<MetaProperty> itr = metaProperties.iterator();
+        MetaProperty prop;
+        String propName;
+        String propValue;
+        boolean found = false;
+        while (itr.hasNext()) {
+            prop = itr.next();
+            propName = prop.getPropName();
+            propValue = prop.getPropValue();
+            if (propName.equals(Constants.DEVICE_NAME)) {
+                this.deviceName = propValue;
+                found = true;
+                break;
+            }
         }
-    }
 
-    public void addResourceModelChangedUIListener(
-            IResourceModelChangedUIListener resourceModelChangedUIListener) {
-        synchronized (resourceModelChangedUIListeners) {
-            resourceModelChangedUIListeners.add(resourceModelChangedUIListener);
+        if (!found) {
+            return;
         }
-    }
 
-    public void addAutomationUIListener(
-            IAutomationUIListener automationUIListener) {
-        synchronized (automationUIListeners) {
-            automationUIListeners.add(automationUIListener);
+        try {
+            SimulatorManager.setDeviceInfo(deviceName);
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "Error while registering the device info.\n"
+                                    + Utility.getSimulatorErrorString(e, null));
         }
     }
 
-    public void addObserverListChangedUIListener(
-            IObserverListChangedUIListener observerListChangedUIListener) {
-        synchronized (observerUIListeners) {
-            observerUIListeners.add(observerListChangedUIListener);
+    public boolean isDeviceInfoValid(List<MetaProperty> metaProperties) {
+        if (null == metaProperties || metaProperties.size() < 1) {
+            return false;
         }
-    }
 
-    public void removeResourceListChangedUIListener(
-            IResourceListChangedUIListener listener) {
-        synchronized (resourceListChangedUIListeners) {
-            if (null != listener && resourceListChangedUIListeners.size() > 0) {
-                resourceListChangedUIListeners.remove(listener);
+        Iterator<MetaProperty> itr = metaProperties.iterator();
+        MetaProperty prop;
+        String propName;
+        String propValue;
+        while (itr.hasNext()) {
+            prop = itr.next();
+            propName = prop.getPropName();
+            propValue = prop.getPropValue();
+            if (propName.equals(Constants.DEVICE_NAME)) {
+                if (null == propValue || propValue.length() < 1) {
+                    return false;
+                }
+                break;
             }
         }
+        return true;
     }
 
-    public void removeResourceSelectionChangedUIListener(
-            IResourceSelectionChangedUIListener listener) {
-        synchronized (resourceSelectionChangedUIListeners) {
-            if (null != listener
-                    && resourceSelectionChangedUIListeners.size() > 0) {
-                resourceSelectionChangedUIListeners.remove(listener);
-            }
+    public List<MetaProperty> getDeviceInfo() {
+        List<MetaProperty> metaProperties = new ArrayList<MetaProperty>();
+        metaProperties.add(new MetaProperty(Constants.DEVICE_NAME, deviceName));
+        if (null != deviceInfo) {
+            metaProperties.add(new MetaProperty(Constants.DEVICE_ID, deviceInfo
+                    .getID()));
+            metaProperties.add(new MetaProperty(Constants.DEVICE_SPEC_VERSION,
+                    deviceInfo.getSpecVersion()));
+            metaProperties.add(new MetaProperty(Constants.DEVICE_DMV,
+                    deviceInfo.getDataModelVersion()));
+        }
+        return metaProperties;
+    }
+
+    public List<MetaProperty> getPlatformInfo() {
+        List<MetaProperty> metaProperties = new ArrayList<MetaProperty>();
+        metaProperties.add(new MetaProperty(Constants.PLATFORM_ID, platformInfo
+                .getPlatformID()));
+        metaProperties.add(new MetaProperty(Constants.PLATFORM_MANUFAC_NAME,
+                platformInfo.getManufacturerName()));
+        metaProperties.add(new MetaProperty(Constants.PLATFORM_MANUFAC_URL,
+                platformInfo.getManufacturerUrl()));
+        metaProperties.add(new MetaProperty(Constants.PLATFORM_MODEL_NO,
+                platformInfo.getModelNumber()));
+        metaProperties.add(new MetaProperty(Constants.PLATFORM_DATE_OF_MANUFAC,
+                platformInfo.getDateOfManufacture()));
+        metaProperties.add(new MetaProperty(Constants.PLATFORM_VERSION,
+                platformInfo.getPlatformVersion()));
+        metaProperties.add(new MetaProperty(Constants.PLATFORM_OS_VERSION,
+                platformInfo.getOperationSystemVersion()));
+        metaProperties.add(new MetaProperty(
+                Constants.PLATFORM_HARDWARE_VERSION, platformInfo
+                        .getHardwareVersion()));
+        metaProperties.add(new MetaProperty(
+                Constants.PLATFORM_FIRMWARE_VERSION, platformInfo
+                        .getFirmwareVersion()));
+        metaProperties.add(new MetaProperty(Constants.PLATFORM_SUPPORT_URL,
+                platformInfo.getSupportUrl()));
+        metaProperties.add(new MetaProperty(Constants.PLATFORM_SYSTEM_TIME,
+                platformInfo.getSystemTime()));
+        return metaProperties;
+    }
+
+    public void setPlatformInfo(List<MetaProperty> metaProperties) {
+        if (null == metaProperties || metaProperties.size() < 1) {
+            return;
         }
-    }
-
-    public void removeResourceModelChangedUIListener(
-            IResourceModelChangedUIListener listener) {
-        synchronized (resourceModelChangedUIListeners) {
-            if (null != listener && resourceModelChangedUIListeners.size() > 0) {
-                resourceModelChangedUIListeners.remove(listener);
+        Iterator<MetaProperty> itr = metaProperties.iterator();
+        MetaProperty prop;
+        String propName;
+        String propValue;
+        while (itr.hasNext()) {
+            prop = itr.next();
+            propName = prop.getPropName();
+            propValue = prop.getPropValue();
+            if (propName.equals(Constants.PLATFORM_ID)) {
+                platformInfo.setPlatformID(propValue);
+            } else if (propName.equals(Constants.PLATFORM_MANUFAC_NAME)) {
+                platformInfo.setManufacturerName(propValue);
+            } else if (propName.equals(Constants.PLATFORM_MANUFAC_URL)) {
+                platformInfo.setManufacturerUrl(propValue);
+            } else if (propName.equals(Constants.PLATFORM_MODEL_NO)) {
+                platformInfo.setModelNumber(propValue);
+            } else if (propName.equals(Constants.PLATFORM_DATE_OF_MANUFAC)) {
+                platformInfo.setDateOfManufacture(propValue);
+            } else if (propName.equals(Constants.PLATFORM_VERSION)) {
+                platformInfo.setPlatformVersion(propValue);
+            } else if (propName.equals(Constants.PLATFORM_OS_VERSION)) {
+                platformInfo.setOperationSystemVersion(propValue);
+            } else if (propName.equals(Constants.PLATFORM_HARDWARE_VERSION)) {
+                platformInfo.setHardwareVersion(propValue);
+            } else if (propName.equals(Constants.PLATFORM_FIRMWARE_VERSION)) {
+                platformInfo.setFirmwareVersion(propValue);
+            } else if (propName.equals(Constants.PLATFORM_SUPPORT_URL)) {
+                platformInfo.setSupportUrl(propValue);
+            } else if (propName.equals(Constants.PLATFORM_SYSTEM_TIME)) {
+                platformInfo.setSystemTime(propValue);
             }
         }
-    }
-
-    public void removeAutomationUIListener(IAutomationUIListener listener) {
-        synchronized (automationUIListeners) {
-            if (null != listener && automationUIListeners.size() > 0) {
-                automationUIListeners.remove(listener);
-            }
+        try {
+            SimulatorManager.setPlatformInfo(platformInfo);
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "Error while registering the platform info.\n"
+                                    + Utility.getSimulatorErrorString(e, null));
         }
     }
 
-    public void removeObserverListChangedUIListener(
-            IObserverListChangedUIListener listener) {
-        synchronized (observerUIListeners) {
-            if (null != listener && observerUIListeners.size() > 0) {
-                observerUIListeners.remove(listener);
+    public boolean isPlatformInfoValid(List<MetaProperty> metaProperties) {
+        if (null == metaProperties || metaProperties.size() < 1) {
+            return false;
+        }
+        Iterator<MetaProperty> itr = metaProperties.iterator();
+        MetaProperty prop;
+        String propValue;
+        while (itr.hasNext()) {
+            prop = itr.next();
+            propValue = prop.getPropValue();
+            if (null == propValue || propValue.length() < 1) {
+                return false;
             }
         }
+        return true;
     }
 
-    public synchronized SimulatorResource getCurrentResourceInSelection() {
+    public synchronized Resource getCurrentResourceInSelection() {
         return currentResourceInSelection;
     }
 
-    public synchronized void setCurrentResourceInSelection(
-            SimulatorResource resource) {
+    public synchronized void setCurrentResourceInSelection(Resource resource) {
         this.currentResourceInSelection = resource;
     }
 
-    private void addResourceUriToOrderedMap(String resourceType,
-            String resourceURI) {
-        if (null != resourceURI && null != resourceType) {
-            synchronized (orderedResourceUriMap) {
-                ArrayList<String> uriListForType = orderedResourceUriMap
-                        .get(resourceType);
-                if (null == uriListForType) {
-                    uriListForType = new ArrayList<String>();
-                    orderedResourceUriMap.put(resourceType, uriListForType);
-                }
-                uriListForType.add(resourceURI);
-            }
-        }
+    public boolean isResourceExist(String resourceURI) {
+        return data.isResourceExist(resourceURI);
     }
 
-    private void removeResourceUriFromOrderedMap(String resourceType,
-            String resourceURI) {
-        synchronized (orderedResourceUriMap) {
-            if (null != resourceURI && null != resourceType) {
-                ArrayList<String> uriListForType = orderedResourceUriMap
-                        .get(resourceType);
-                if (null != uriListForType) {
-                    uriListForType.remove(resourceURI);
-                    if (uriListForType.size() < 1) {
-                        orderedResourceUriMap.remove(resourceType);
-                    }
+    public boolean isAnyResourceExist() {
+        return data.isAnyResourceExist();
+    }
+
+    public boolean createSingleResource(SingleResource resource,
+            Map<String, SimulatorResourceAttribute> attributes)
+            throws SimulatorException {
+        if (null == resource) {
+            return false;
+        }
+
+        try {
+            // Create the resource.
+            SimulatorResource jSimulatorResource = SimulatorManager
+                    .createResource(SimulatorResource.Type.SINGLE,
+                            resource.getResourceName(),
+                            resource.getResourceURI(),
+                            resource.getResourceType());
+            if (null == jSimulatorResource
+                    || !(jSimulatorResource instanceof SimulatorSingleResource)) {
+                return false;
+            }
+            SimulatorSingleResource jSimulatorSingleResource = (SimulatorSingleResource) jSimulatorResource;
+            resource.setSimulatorResource(jSimulatorSingleResource);
+
+            // Cancel discoverable property if requested by user.
+            if (!resource.isDiscoverable()) {
+                jSimulatorSingleResource.setDiscoverable(false);
+            }
+
+            // Cancel observable property if requested by user.
+            if (!resource.isObservable()) {
+                jSimulatorSingleResource.setObservable(false);
+            }
+
+            // Set the model change listener.
+            jSimulatorSingleResource
+                    .setResourceModelChangeListener(resourceModelChangeListener);
+
+            // Set the observer listener if the resource is observable.
+            if (resource.isObservable()) {
+                jSimulatorSingleResource.setObserverListener(observer);
+            }
+
+            // Add attributes.
+            if (null != attributes && !attributes.isEmpty()) {
+                SimulatorResourceAttribute value;
+                for (Map.Entry<String, SimulatorResourceAttribute> entry : attributes
+                        .entrySet()) {
+                    value = entry.getValue();
+                    if (null != value)
+                        jSimulatorSingleResource.addAttribute(value);
                 }
-            } else if (null != resourceType) {
-                orderedResourceUriMap.remove(resourceType);
-            } else {
-                orderedResourceUriMap.clear();
+
+                // Get the resource model java object reference.
+                resource.setResourceModel(jSimulatorSingleResource
+                        .getResourceModel());
+
+                resource.createResourceRepresentation(jSimulatorSingleResource
+                        .getAttributes());
             }
+
+            // Set the resource interfaces.
+            jSimulatorSingleResource
+                    .setInterface(Utility.convertSetToVectorString(resource
+                            .getResourceInterfaces()));
+
+            // Register the resource with the platform.
+            jSimulatorSingleResource.start();
+            resource.setStarted(true);
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(), new Date(),
+                            Utility.getSimulatorErrorString(e, null));
+            throw e;
         }
+
+        // Add to local cache.
+        data.addResource(resource);
+
+        // Update UI listeners
+        UiListenerHandler.getInstance().resourceCreatedUINotification(
+                ResourceType.SINGLE);
+
+        Activator
+                .getDefault()
+                .getLogManager()
+                .log(Level.INFO.ordinal(), new Date(),
+                        "Resource created [" + resource.getResourceURI() + "].");
+
+        return true;
     }
 
-    private void addResourceToMap(SimulatorResource simulatorResource) {
-        if (null != simulatorResource) {
-            synchronized (resourceMap) {
-                Map<String, SimulatorResource> resourceTypeMap;
-                resourceTypeMap = resourceMap.get(simulatorResource
-                        .getResourceType());
-                if (null == resourceTypeMap) {
-                    resourceTypeMap = new HashMap<String, SimulatorResource>();
-                    resourceMap.put(simulatorResource.getResourceType(),
-                            resourceTypeMap);
-                }
-                resourceTypeMap.put(simulatorResource.getResourceURI(),
-                        simulatorResource);
+    public Resource createResourceByRAML(String configFilePath)
+            throws SimulatorException {
+        SimulatorResource jSimulatorResource;
+        try {
+            // Create the resource
+            jSimulatorResource = SimulatorManager
+                    .createResource(configFilePath);
+            if (null == jSimulatorResource) {
+                return null;
             }
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(), new Date(),
+                            Utility.getSimulatorErrorString(e, null));
+            throw e;
+        }
+
+        if (!(jSimulatorResource instanceof SimulatorSingleResource)) {
+            return null;
+        }
+
+        Resource resource = new SingleResource();
+        resource.setSimulatorResource(jSimulatorResource);
+
+        // Fetch and locally store the resource name and uri.
+        String uri = jSimulatorResource.getURI();
+        if (null == uri || uri.trim().isEmpty()) {
+            return null;
+        }
+        resource.setResourceURI(uri.trim());
+
+        String name = jSimulatorResource.getName();
+        if (null == name || name.trim().isEmpty()) {
+            return null;
         }
+
+        resource.setResourceName(name.trim());
+
+        return resource;
     }
 
-    private void addResourceToMap(String resourceType,
-            Map<String, SimulatorResource> newResourceTypeMap) {
-        if (null != resourceType && null != newResourceTypeMap) {
-            synchronized (resourceMap) {
-                Map<String, SimulatorResource> resourceTypeMap = resourceMap
-                        .get(resourceType);
-                if (null != resourceTypeMap) {
-                    resourceTypeMap.putAll(newResourceTypeMap);
-                } else {
-                    resourceMap.put(resourceType, newResourceTypeMap);
+    /**
+     * This method can set/change the resource uri and name of an already
+     * created resource which is not yet registered with the platform. This
+     * method registers the model change and observer listeners, registers the
+     * resource, fetches the resource attributes, updates the local cache and
+     * notifies the UI listeners.
+     */
+    public boolean completeSingleResourceCreationByRAML(Resource resource,
+            String uri, String name, boolean multiInstance)
+            throws SimulatorException {
+        if (null == resource || !(resource instanceof SingleResource)) {
+            return false;
+        }
+        try {
+            SingleResource singleRes = (SingleResource) resource;
+
+            SimulatorSingleResource jSimulatorSingleResource = (SimulatorSingleResource) resource
+                    .getSimulatorResource();
+            if (null == jSimulatorSingleResource) {
+                return false;
+            }
+
+            // Update resource URI and Name if they are changed.
+            String newUri = uri.trim();
+            String newName = name.trim();
+
+            if (multiInstance) {
+                singleRes.setResourceURI(newUri);
+                singleRes.setResourceName(newName);
+            } else {
+                if (!singleRes.getResourceURI().equals(newUri)) {
+                    jSimulatorSingleResource.setURI(newUri);
+                    singleRes.setResourceURI(newUri);
                 }
+                if (!singleRes.getResourceName().equals(newName)) {
+                    jSimulatorSingleResource.setName(newName);
+                    singleRes.setResourceName(newName);
+                }
+            }
+
+            // Set the model change listener.
+            jSimulatorSingleResource
+                    .setResourceModelChangeListener(resourceModelChangeListener);
+
+            // Set the observer listener if the resource is observable.
+            if (jSimulatorSingleResource.isObservable()) {
+                jSimulatorSingleResource.setObserverListener(observer);
+                singleRes.setObservable(true);
             }
+
+            // Fetch the resource model.
+            SimulatorResourceModel jResModel = jSimulatorSingleResource
+                    .getResourceModel();
+            if (null == jResModel) {
+                return false;
+            }
+            singleRes.setResourceModel(jResModel);
+
+            // Fetch the basic details of the resource.
+            singleRes.setResourceType(jSimulatorSingleResource
+                    .getResourceType());
+            singleRes
+                    .setResourceInterfaces(Utility
+                            .convertVectorToSet(jSimulatorSingleResource
+                                    .getInterface()));
+
+            // Fetch the resource attributes.
+            singleRes.createResourceRepresentation(jSimulatorSingleResource
+                    .getAttributes());
+
+            // Register the resource with the platform.
+            jSimulatorSingleResource.start();
+            singleRes.setStarted(true);
+
+            // Add to local cache.
+            data.addResource(singleRes);
+
+            // Update UI listeners for single instance creation
+            if (!multiInstance)
+                UiListenerHandler.getInstance().resourceCreatedUINotification(
+                        ResourceType.SINGLE);
+        } catch (Exception e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(), new Date(),
+                            Utility.getSimulatorErrorString(e, null));
+            throw e;
         }
+
+        Activator
+                .getDefault()
+                .getLogManager()
+                .log(Level.INFO.ordinal(), new Date(),
+                        "Resource created [" + resource.getResourceURI() + "].");
+        return true;
     }
 
-    private void removeResourceFromMap(String resourceType, String resourceURI) {
-        if (null != resourceURI && null != resourceType) {
-            synchronized (resourceMap) {
-                Map<String, SimulatorResource> resourceTypeMap = resourceMap
-                        .get(resourceType);
-                if (null != resourceTypeMap) {
-                    resourceTypeMap.remove(resourceURI);
-                    if (resourceTypeMap.size() < 1) {
-                        resourceMap.remove(resourceType);
+    public Set<SingleResource> createSingleResourceMultiInstances(
+            String configFile, int count, IProgressMonitor progressMonitor)
+            throws SimulatorException {
+        Set<SingleResource> resultSet;
+        try {
+            resultSet = new HashSet<SingleResource>();
+            Vector<SimulatorResource> jSimulatorResources = SimulatorManager
+                    .createResource(configFile, count);
+            if (null == jSimulatorResources || jSimulatorResources.size() < 1) {
+                return null;
+            }
+            SimulatorSingleResource jResource;
+            SingleResource resource;
+            boolean result;
+            for (SimulatorResource jSimulatorResource : jSimulatorResources) {
+                // If the resource creation progress is canceled, then stop the
+                // creation and stop/delete
+                // the resources created already.
+                if (progressMonitor.isCanceled()) {
+                    removeSingleResources(resultSet);
+                    return null;
+                }
+                jResource = (SimulatorSingleResource) jSimulatorResource;
+                resource = new SingleResource();
+                resource.setSimulatorResource(jResource);
+                try {
+                    result = completeSingleResourceCreationByRAML(resource,
+                            jResource.getURI(), jResource.getName(), true);
+                    if (result) {
+                        resultSet.add(resource);
                     }
+                } catch (SimulatorException eInner) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(),
+                                    new Date(),
+                                    Utility.getSimulatorErrorString(eInner,
+                                            null));
                 }
+                progressMonitor.worked(1);
             }
+        } catch (SimulatorException eOuter) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(), new Date(),
+                            Utility.getSimulatorErrorString(eOuter, null));
+            throw eOuter;
         }
+        return resultSet;
     }
 
-    public boolean isResourceExist(String resourceURI) {
-        boolean result = false;
-        if (null != resourceURI) {
-            SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
-            if (null != resource) {
-                result = true;
-            }
+    public List<Resource> getResourceList() {
+        List<Resource> resourceList = data.getResources();
+        if (null == resourceList) {
+            return null;
         }
-        return result;
+        // Sort the list
+        Collections.sort(resourceList, Utility.resourceComparator);
+
+        return resourceList;
     }
 
-    public void addResourceDisplayName(String displayName, String completeURI) {
-        synchronized (displayNameMap) {
-            displayNameMap.put(displayName, completeURI);
+    public List<SingleResource> getSingleResourceList() {
+        List<SingleResource> resourceList = data.getSingleResources();
+        if (null == resourceList) {
+            return null;
         }
+        // Sort the list
+        Collections.sort(resourceList, Utility.singleResourceComparator);
+
+        return resourceList;
     }
 
-    public void removeResourceDisplayName(String displayName) {
-        synchronized (displayNameMap) {
-            displayNameMap.remove(displayName);
+    public void removeSingleResources(Set<SingleResource> resources)
+            throws SimulatorException {
+        if (null == resources) {
+            return;
+        }
+        Iterator<SingleResource> itr = resources.iterator();
+        while (itr.hasNext()) {
+            removeResource(itr.next());
         }
     }
 
-    public boolean isDisplayName(String displayName) {
-        boolean exist = false;
-        synchronized (displayNameMap) {
-            exist = displayNameMap.containsKey(displayName);
+    public void removeResource(Resource res) throws SimulatorException {
+        // Unregister the resource from the platform.
+        SimulatorResource simRes = res.getSimulatorResource();
+        try {
+            simRes.stop();
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(), new Date(),
+                            Utility.getSimulatorErrorString(e, null));
+            throw e;
         }
-        return exist;
+
+        // Delete this resource
+        data.deleteResource(res);
+
+        Activator
+                .getDefault()
+                .getLogManager()
+                .log(Level.INFO.ordinal(), new Date(),
+                        "Resource deleted [" + res.getResourceURI() + "].");
     }
 
-    public String getCompleteUriFromDisplayName(String displayName) {
-        String completeURI = null;
-        synchronized (displayNameMap) {
-            completeURI = displayNameMap.get(displayName);
+    public boolean isUriUnique(List<MetaProperty> properties) {
+        if (null == properties) {
+            return false;
         }
-        return completeURI;
+        MetaProperty prop;
+        Iterator<MetaProperty> itr = properties.iterator();
+        while (itr.hasNext()) {
+            prop = itr.next();
+            if (prop.getPropName().equals(Constants.RESOURCE_URI)) {
+                String uri = prop.getPropValue();
+                return !data.isResourceExist(uri);
+            }
+        }
+        return false;
     }
 
-    public void createResource(final String configFilePath) {
+    public void resourceSelectionChanged(final Resource selectedResource) {
         new Thread() {
             @Override
             public void run() {
-                SimulatorResourceServer resourceServerN;
-                try {
-                    resourceServerN = SimulatorManager.createResource(
-                            configFilePath, resourceModelChangeListener);
-                } catch (SimulatorException e) {
-                    Activator
-                            .getDefault()
-                            .getLogManager()
-                            .log(Level.ERROR.ordinal(),
-                                    new Date(),
-                                    "[" + e.getClass().getSimpleName() + "]"
-                                            + e.code().toString() + "-"
-                                            + e.message());
-                    return;
-                }
-                SimulatorResource simulatorResource;
-                simulatorResource = fetchResourceData(resourceServerN);
-                if (null != simulatorResource) {
-                    String uri = simulatorResource.getResourceURI();
-                    addResourceToMap(simulatorResource);
-                    addResourceUriToOrderedMap(
-                            simulatorResource.getResourceType(), uri);
-                    resourceCreatedUINotification();
-
-                    // Form the display URI
-                    String displayName = Utility.uriToDisplayName(uri);
-                    if (null != displayName) {
-                        addResourceDisplayName(displayName, uri);
-                    } else {
-                        Activator
-                                .getDefault()
-                                .getLogManager()
-                                .log(Level.ERROR.ordinal(),
-                                        new Date(),
-                                        "Converting the URI to display format for "
-                                                + uri + "failed!");
-                    }
-
-                    // Set the observer for the created resource
-                    try {
-                        resourceServerN.setObserverCallback(observer);
-                    } catch (SimulatorException e) {
-                        Activator
-                                .getDefault()
-                                .getLogManager()
-                                .log(Level.ERROR.ordinal(),
-                                        new Date(),
-                                        "[" + e.getClass().getSimpleName()
-                                                + "]" + e.code().toString()
-                                                + "-" + e.message());
-                    }
-
-                    // Print the resource data
-                    simulatorResource.printResourceInfo();
+                if (null != selectedResource) {
+                    setCurrentResourceInSelection(selectedResource);
+                } else {
+                    setCurrentResourceInSelection(null);
                 }
+                // Notify all observers for resource selection change event
+                UiListenerHandler.getInstance()
+                        .resourceSelectionChangedUINotification(
+                                selectedResource);
             }
         }.start();
     }
 
-    public void createResource(final String configFilePath,
-            final int noOfInstances) {
-        new Thread() {
-            @Override
-            public void run() {
-                Map<String, SimulatorResource> resourceTypeMap;
-                SimulatorResourceServer[] simulatorResourceServers = null;
-                try {
-                    simulatorResourceServers = SimulatorManager.createResource(
-                            configFilePath, noOfInstances,
-                            resourceModelChangeListener);
-                } catch (SimulatorException e) {
-                    Activator
-                            .getDefault()
-                            .getLogManager()
-                            .log(Level.ERROR.ordinal(),
-                                    new Date(),
-                                    "[" + e.getClass().getSimpleName() + "]"
-                                            + e.code().toString() + "-"
-                                            + e.message());
-                    return;
-                }
-                if (null == simulatorResourceServers) {
-                    return;
-                }
-                resourceTypeMap = new HashMap<String, SimulatorResource>();
-                SimulatorResource resource;
-                String uri;
-                String displayName;
-                for (SimulatorResourceServer resourceServerN : simulatorResourceServers) {
-                    resource = fetchResourceData(resourceServerN);
-                    if (null != resource) {
-                        uri = resource.getResourceURI();
-                        resourceTypeMap.put(uri, resource);
-                        addResourceUriToOrderedMap(resource.getResourceType(),
-                                uri);
-
-                        // Form the display URI
-                        displayName = Utility.uriToDisplayName(uri);
-                        if (null != displayName) {
-                            addResourceDisplayName(displayName, uri);
-                        } else {
-                            Activator
-                                    .getDefault()
-                                    .getLogManager()
-                                    .log(Level.ERROR.ordinal(),
-                                            new Date(),
-                                            "Converting the URI to display format for "
-                                                    + uri + "failed!");
-                        }
-                    }
-                    // Set the observer for the created resource
-                    try {
-                        resourceServerN.setObserverCallback(observer);
-                    } catch (SimulatorException e) {
-                        Activator
-                                .getDefault()
-                                .getLogManager()
-                                .log(Level.ERROR.ordinal(),
-                                        new Date(),
-                                        "[" + e.getClass().getSimpleName()
-                                                + "]" + e.code().toString()
-                                                + "-" + e.message());
-                    }
-                }
+    public List<MetaProperty> getMetaProperties(Resource resource) {
+        if (null != resource) {
+            String propName;
+            StringBuilder propValue;
+            List<MetaProperty> metaPropertyList = new ArrayList<MetaProperty>();
 
-                // Find the resourceType and add it to the local data
-                // structure and notify UI Listeners
-                if (resourceTypeMap.size() > 0) {
-                    String resourceType;
-                    Set<String> uriSet = resourceTypeMap.keySet();
-                    Iterator<String> itr = uriSet.iterator();
-                    if (itr.hasNext()) {
-                        SimulatorResource simResource = resourceTypeMap.get(itr
-                                .next());
-                        if (null != simResource) {
-                            resourceType = simResource.getResourceType();
-
-                            addResourceToMap(resourceType, resourceTypeMap);
-                            resourceCreatedUINotification();
+            for (int index = 0; index < Constants.META_PROPERTY_COUNT; index++) {
+                propName = Constants.META_PROPERTIES[index];
+                propValue = new StringBuilder();
+                if (propName.equals(Constants.RESOURCE_NAME)) {
+                    propValue.append(resource.getResourceName());
+                } else if (propName.equals(Constants.RESOURCE_URI)) {
+                    propValue.append(resource.getResourceURI());
+                } else if (propName.equals(Constants.RESOURCE_TYPE)) {
+                    propValue.append(resource.getResourceType());
+                } else if (propName.equals(Constants.INTERFACE_TYPES)) {
+                    Set<String> ifTypes = resource.getResourceInterfaces();
+                    if (null != ifTypes && !ifTypes.isEmpty()) {
+                        Iterator<String> itr = ifTypes.iterator();
+                        while (itr.hasNext()) {
+                            propValue.append(itr.next());
+                            if (itr.hasNext()) {
+                                propValue.append(", ");
+                            }
                         }
+                    } else {
+                        propValue = null;
                     }
+                } else {
+                    propValue = null;
                 }
-            }
-        }.start();
-    }
-
-    private SimulatorResource fetchResourceData(
-            SimulatorResourceServer resourceServerN) {
-        SimulatorResource simulatorResource = null;
-        if (null != resourceServerN) {
-            simulatorResource = new SimulatorResource();
-            simulatorResource.setResourceServer(resourceServerN);
-            simulatorResource.setResourceURI(resourceServerN.getURI());
-            simulatorResource
-                    .setResourceType(resourceServerN.getResourceType());
-            simulatorResource.setResourceName(resourceServerN.getName());
-            simulatorResource.setResourceInterface(resourceServerN
-                    .getInterfaceType());
-
-            SimulatorResourceModel resourceModelN;
-            try {
-                resourceModelN = resourceServerN.getModel();
-            } catch (SimulatorException e) {
-                Activator
-                        .getDefault()
-                        .getLogManager()
-                        .log(Level.ERROR.ordinal(),
-                                new Date(),
-                                "[" + e.getClass().getSimpleName() + "]"
-                                        + e.code().toString() + "-"
-                                        + e.message());
-                return null;
-            }
-            if (null != resourceModelN) {
-                simulatorResource.setResourceModel(resourceModelN);
-
-                // Fetch the resource attributes
-                Map<String, LocalResourceAttribute> resourceAttributeMap;
-                resourceAttributeMap = fetchResourceAttributesFromModel(resourceModelN);
-                if (null != resourceAttributeMap) {
-                    simulatorResource
-                            .setResourceAttributesMap(resourceAttributeMap);
+                if (null != propValue) {
+                    metaPropertyList.add(new MetaProperty(propName, propValue
+                            .toString()));
                 }
             }
+            return metaPropertyList;
         }
-        return simulatorResource;
+        return null;
     }
 
-    private Map<String, LocalResourceAttribute> fetchResourceAttributesFromModel(
-            SimulatorResourceModel resourceModelN) {
-        Map<String, LocalResourceAttribute> resourceAttributeMap = null;
-        if (null != resourceModelN) {
-            Map<String, ResourceAttribute> attributeMapN;
-            try {
-                attributeMapN = resourceModelN.getAttributes();
-            } catch (SimulatorException e) {
-                Activator
-                        .getDefault()
-                        .getLogManager()
-                        .log(Level.ERROR.ordinal(),
-                                new Date(),
-                                "[" + e.getClass().getSimpleName() + "]"
-                                        + e.code().toString() + "-"
-                                        + e.message());
-                return null;
-            }
-            if (null != attributeMapN) {
-                resourceAttributeMap = new HashMap<String, LocalResourceAttribute>();
-
-                Set<String> attNameSet = attributeMapN.keySet();
-                String attName;
-                ResourceAttribute attributeN;
-                LocalResourceAttribute attribute;
-                Iterator<String> attNameItr = attNameSet.iterator();
-                while (attNameItr.hasNext()) {
-                    attName = attNameItr.next();
-                    attributeN = attributeMapN.get(attName);
-                    if (null != attributeN) {
-                        attribute = new LocalResourceAttribute();
-                        attribute.setResourceAttribute(attributeN);
-
-                        // Set the attribute value
-                        Object valueObj = attributeN.getValue();
-                        if (null != valueObj) {
-                            attribute.setAttributeValue(valueObj);
-                        }
-
-                        // Set the attribute value list.
-                        attribute.setAttValues(getValueList(attributeN));
-
-                        // Initially disabling the automation
-                        attribute.setAutomationInProgress(false);
-
-                        // TODO: Temporarily setting the interval to 500.
-                        // This value should come from the native layer.
-                        // Native implementation is in progress.
-                        attribute
-                                .setAutomationUpdateInterval(Constants.DEFAULT_AUTOMATION_INTERVAL);
-
-                        // Setting the default automation type
-                        attribute
-                                .setAutomationType(Constants.DEFAULT_AUTOMATION_TYPE);
-
-                        resourceAttributeMap.put(attName, attribute);
-                    }
-                }
-            }
+    public boolean startResource(Resource resource) throws SimulatorException {
+        if (null == resource) {
+            return false;
+        }
+        SimulatorResource server = resource.getSimulatorResource();
+        if (null == server) {
+            return false;
+        }
+        try {
+            server.start();
+            resource.setStarted(true);
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "There is an error while starting the resource.\n"
+                                    + Utility.getSimulatorErrorString(e, null));
+            throw e;
         }
-        return resourceAttributeMap;
+        return true;
     }
 
-    // This method gives all known possible values of the attribute in string
-    // format. It takes allowed values or range of values whichever is available
-    private List<String> getValueList(ResourceAttribute attributeN) {
-        Object[] allowedValues = attributeN.getAllowedValues();
-        List<String> valueList = new ArrayList<String>();
-        if (null != allowedValues && allowedValues.length > 0) {
-            for (Object value : allowedValues) {
-                if (null != value) {
-                    valueList.add(String.valueOf(value));
-                }
-            }
-        } else {
-            Type valueType = attributeN.getBaseType();
-            Range range = attributeN.getRange();
-            if (null != range) {
-                Object min = range.getMin();
-                Object max = range.getMax();
-                if (valueType == Type.INT) {
-                    int minI = (Integer) min;
-                    int maxI = (Integer) max;
-                    for (int value = minI; value <= maxI; value++) {
-                        valueList.add(String.valueOf(value));
-                    }
-                } else if (valueType == Type.DOUBLE) {
-                    double minD = (Double) min;
-                    double maxD = (Double) max;
-                    for (double value = minD; value <= maxD; value++) {
-                        valueList.add(String.valueOf(value));
-                    }
-                }
-            }
+    public boolean stopResource(Resource resource) throws SimulatorException {
+        if (null == resource) {
+            return false;
         }
-        Object attValue = attributeN.getValue();
-        if (valueList.size() < 1 && null != attValue) {
-            valueList.add(String.valueOf(attValue));
+        SimulatorResource server = resource.getSimulatorResource();
+        if (null == server) {
+            return false;
+        }
+        try {
+            server.stop();
+            resource.setStarted(false);
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "There is an error while stopping the resource.\n"
+                                    + Utility.getSimulatorErrorString(e, null));
+            throw e;
         }
-        return valueList;
+        return true;
     }
 
-    public void deleteResourceByURI(final String resourceURI) {
-        if (null != resourceURI) {
-            new Thread() {
-                @Override
-                public void run() {
-                    SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
-                    if (null != resource) {
-                        String resourceType = resource.getResourceType();
-
-                        // Unregister the resource from the platform
-                        deleteResource(resource);
-
-                        // Delete from the local data structure
-                        deleteLocalResourceDetails(resourceType, resourceURI);
-
-                        // Notify the UI listener for removing this resource
-                        // from UI
-                        resourceDeletedUINotification();
-
-                        if (null != currentResourceInSelection
-                                && resource == currentResourceInSelection) {
-                            // Listeners might query the resource being deleted
-                            // if exists. So set the currently selection to
-                            // null.
-                            setCurrentResourceInSelection(null);
-
-                            // Notify all observers for resource selection
-                            // change event
-                            resourceSelectionChangedUINotification();
-                        }
-                    }
-                }
-            }.start();
+    public boolean changeResourceName(Resource resource, String newName)
+            throws SimulatorException {
+        if (null == resource || null == newName) {
+            return false;
         }
-    }
 
-    private SimulatorResource getSimulatorResourceByURI(String resourceURI) {
-        SimulatorResource resource = null;
-        if (null != resourceURI) {
-            synchronized (resourceMap) {
-                Set<String> typeSet = resourceMap.keySet();
-                Iterator<String> typeItr = typeSet.iterator();
-                String resourceType;
-                Map<String, SimulatorResource> resourceTypeMap;
-                while (typeItr.hasNext()) {
-                    resourceType = typeItr.next();
-                    resourceTypeMap = resourceMap.get(resourceType);
-                    if (null != resourceTypeMap) {
-                        resource = resourceTypeMap.get(resourceURI);
-                        if (null != resource) {
-                            break;
-                        }
-                    }
-                }
-            }
+        if (!stopResource(resource)) {
+            return false;
         }
-        return resource;
-    }
 
-    private void deleteResource(SimulatorResource resource) {
-        if (null != resource) {
-            SimulatorResourceServer resourceServerN = resource
-                    .getResourceServer();
-            if (null != resourceServerN) {
-                try {
-                    SimulatorManager.deleteResource(resourceServerN);
-                } catch (SimulatorException e) {
-                    Activator
-                            .getDefault()
-                            .getLogManager()
-                            .log(Level.ERROR.ordinal(),
-                                    new Date(),
-                                    "[" + e.getClass().getSimpleName() + "]"
-                                            + e.code().toString() + "-"
-                                            + e.message());
-                }
-            }
+        SimulatorResource server = resource.getSimulatorResource();
+        try {
+            server.setName(newName);
+            resource.setResourceName(newName);
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "There is an error while changing the resource name.\n"
+                                    + Utility.getSimulatorErrorString(e, null));
+            throw e;
         }
-    }
 
-    public void deleteResourceByType(final String resourceType) {
-        if (null != resourceType) {
-            new Thread() {
-                @Override
-                public void run() {
-                    // Unregister the resources from the platform
-                    deleteResource(resourceType);
-
-                    // Delete from the local data structure
-                    deleteLocalResourceDetails(resourceType, null);
-
-                    // Notify the UI listener for removing this resource from UI
-                    resourceDeletedUINotification();
-
-                    if (null != currentResourceInSelection
-                            && resourceType.equals(currentResourceInSelection
-                                    .getResourceType())) {
-                        // Listeners might query the resource being deleted if
-                        // exists. So set the currently selection to null.
-                        setCurrentResourceInSelection(null);
-
-                        // Notify all observers for resource selection change
-                        // event
-                        resourceSelectionChangedUINotification();
-                    }
-                }
-            }.start();
+        if (!startResource(resource)) {
+            return false;
         }
+
+        return true;
     }
 
-    private void deleteResource(String resourceType) {
-        if (null != resourceType) {
-            try {
-                SimulatorManager.deleteResources(resourceType);
-            } catch (SimulatorException e) {
-                Activator
-                        .getDefault()
-                        .getLogManager()
-                        .log(Level.ERROR.ordinal(),
-                                new Date(),
-                                "[" + e.getClass().getSimpleName() + "]"
-                                        + e.code().toString() + "-"
-                                        + e.message());
+    public boolean changeResourceURI(Resource resource, String newURI)
+            throws SimulatorException {
+        if (null == resource || null == newURI) {
+            return false;
+        }
+
+        if (!stopResource(resource)) {
+            return false;
+        }
+
+        String curURI = resource.getResourceURI();
+        setResourceURI(resource, newURI);
+
+        try {
+            if (!startResource(resource)) {
+                return false;
             }
+        } catch (SimulatorException e) {
+            setResourceURI(resource, curURI);
         }
-    }
 
-    public void deleteAllResources() {
-        new Thread() {
-            @Override
-            public void run() {
-                // Unregister the resources from the platform
-                deleteResource();
+        return true;
+    }
 
-                // Delete from the local data structure
-                deleteLocalResourceDetails(null, null);
+    public boolean changeResourceType(Resource resource, String newResourceType)
+            throws SimulatorException {
+        if (null == resource || null == newResourceType) {
+            return false;
+        }
 
-                // Notify the UI listener for removing this resource from UI
-                resourceDeletedUINotification();
+        if (!stopResource(resource)) {
+            return false;
+        }
 
-                // Listeners might query the resource being deleted if exists.
-                // So set the currently selection to null.
-                setCurrentResourceInSelection(null);
+        String curResourceType = resource.getResourceType();
+        setResourceType(resource, newResourceType);
 
-                // Notify all observers for resource selection change event
-                resourceSelectionChangedUINotification();
+        try {
+            if (!startResource(resource)) {
+                return false;
             }
-        }.start();
+        } catch (SimulatorException e) {
+            setResourceType(resource, curResourceType);
+        }
+
+        return true;
     }
 
-    private void deleteResource() {
+    public void setResourceURI(Resource resource, String newURI)
+            throws SimulatorException {
+        String curURI = resource.getResourceURI();
+        SimulatorResource server = resource.getSimulatorResource();
         try {
-            SimulatorManager.deleteResources(null);
+            server.setURI(newURI);
+            data.changeResourceURI(resource, curURI, newURI);
         } catch (SimulatorException e) {
             Activator
                     .getDefault()
                     .getLogManager()
                     .log(Level.ERROR.ordinal(),
                             new Date(),
-                            "[" + e.getClass().getSimpleName() + "]"
-                                    + e.code().toString() + "-" + e.message());
+                            "There is an error while changing the resource URI.\n"
+                                    + Utility.getSimulatorErrorString(e, null));
+            throw e;
         }
     }
 
-    private void deleteLocalResourceDetails(String resourceType,
-            String resourceURI) {
-        if (null != resourceType && null != resourceURI) {
-            removeResourceFromMap(resourceType, resourceURI);
-            removeResourceUriFromOrderedMap(resourceType, resourceURI);
-        } else {
-            synchronized (resourceMap) {
-                if (null != resourceType) {
-                    removeResourceUriFromOrderedMap(resourceType, null);
-                    resourceMap.remove(resourceType);
-                } else {
-                    resourceMap.clear();
-                    removeResourceUriFromOrderedMap(null, null);
-                }
-            }
-        }
-        // Remove the display name from the map
-        if (null != resourceURI) {
-            String dispName = Utility.uriToDisplayName(resourceURI);
-            if (null != dispName)
-                removeResourceDisplayName(dispName);
+    public void setResourceType(Resource resource, String newResourceType)
+            throws SimulatorException {
+        SimulatorResource server = resource.getSimulatorResource();
+        try {
+            server.setResourceType(newResourceType);
+            resource.setResourceType(newResourceType);
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "There is an error while changing the resource Type.\n"
+                                    + Utility.getSimulatorErrorString(e, null));
+            throw e;
         }
     }
 
-    private void resourceCreatedUINotification() {
-        synchronized (resourceListChangedUIListeners) {
-            if (resourceListChangedUIListeners.size() > 0) {
-                IResourceListChangedUIListener listener;
-                Iterator<IResourceListChangedUIListener> listenerItr = resourceListChangedUIListeners
-                        .iterator();
-                while (listenerItr.hasNext()) {
-                    listener = listenerItr.next();
-                    if (null != listener) {
-                        listener.onResourceCreation();
-                    }
-                }
-            }
+    public boolean updateResourceProperties(Resource resource,
+            List<MetaProperty> properties, boolean uriChanged,
+            boolean nameChanged, boolean resTypeChanged)
+            throws SimulatorException {
+        if (null == resource || null == properties) {
+            return false;
         }
-    }
 
-    private void resourceDeletedUINotification() {
-        synchronized (resourceListChangedUIListeners) {
-            if (resourceListChangedUIListeners.size() > 0) {
-                IResourceListChangedUIListener listener;
-                Iterator<IResourceListChangedUIListener> listenerItr = resourceListChangedUIListeners
-                        .iterator();
-                while (listenerItr.hasNext()) {
-                    listener = listenerItr.next();
-                    if (null != listener) {
-                        listener.onResourceDeletion();
-                    }
-                }
+        // Updating the properties
+        Iterator<MetaProperty> itr = properties.iterator();
+        MetaProperty property;
+        String propName;
+        String propValue;
+        String resName = null;
+        String resURI = null;
+        String resType = null;
+        while (itr.hasNext()) {
+            property = itr.next();
+            if (null == property) {
+                continue;
             }
-        }
-    }
-
-    private void resourceSelectionChangedUINotification() {
-        synchronized (resourceSelectionChangedUIListeners) {
-            if (resourceSelectionChangedUIListeners.size() > 0) {
-                IResourceSelectionChangedUIListener listener;
-                Iterator<IResourceSelectionChangedUIListener> listenerItr = resourceSelectionChangedUIListeners
-                        .iterator();
-                while (listenerItr.hasNext()) {
-                    listener = listenerItr.next();
-                    if (null != listener) {
-                        listener.onResourceSelectionChange();
-                    }
-                }
+            propName = property.getPropName();
+            propValue = property.getPropValue();
+            if (propName.equals(Constants.RESOURCE_NAME)) {
+                resName = propValue;
+            } else if (propName.equals(Constants.RESOURCE_URI)) {
+                resURI = propValue;
+            } else if (propName.equals(Constants.RESOURCE_TYPE)) {
+                resType = propValue;
             }
         }
-    }
 
-    private void resourceModelChangedUINotification(
-            ModelChangeNotificationType notificationType, String resourceURI,
-            Set<LocalResourceAttribute> valueChangeSet) {
-        synchronized (resourceModelChangedUIListeners) {
-            if (resourceModelChangedUIListeners.size() > 0
-                    && notificationType != ModelChangeNotificationType.NONE
-                    && null != resourceURI) {
-                IResourceModelChangedUIListener listener;
-                Iterator<IResourceModelChangedUIListener> listenerItr = resourceModelChangedUIListeners
-                        .iterator();
-                while (listenerItr.hasNext()) {
-                    listener = listenerItr.next();
-                    if (null != listener) {
-                        listener.onResourceModelChange(notificationType,
-                                resourceURI, valueChangeSet);
-                    }
-                }
+        if (nameChanged) {
+            if (!changeResourceName(resource, resName)) {
+                return false;
             }
+
+            // Notify UI Listeners
+            UiListenerHandler.getInstance().propertiesChangedUINotification(
+                    Resource.class);
         }
-    }
 
-    private void resourceAutomationStartedUINotification(String resourceURI) {
-        synchronized (automationUIListeners) {
-            if (automationUIListeners.size() > 0 && null != resourceURI) {
-                IAutomationUIListener listener;
-                Iterator<IAutomationUIListener> listenerItr = automationUIListeners
-                        .iterator();
-                while (listenerItr.hasNext()) {
-                    listener = listenerItr.next();
-                    if (null != listener) {
-                        listener.onResourceAutomationStart(resourceURI);
-                    }
-                }
+        if (uriChanged) {
+            if (!changeResourceURI(resource, resURI)) {
+                return false;
             }
         }
-    }
 
-    private void automationCompleteUINotification(String resourceURI,
-            String attName) {
-        synchronized (automationUIListeners) {
-            if (automationUIListeners.size() > 0 && null != resourceURI) {
-                IAutomationUIListener listener;
-                Iterator<IAutomationUIListener> listenerItr = automationUIListeners
-                        .iterator();
-                while (listenerItr.hasNext()) {
-                    listener = listenerItr.next();
-                    if (null != listener) {
-                        listener.onAutomationComplete(resourceURI, attName);
-                    }
-                }
+        if (resTypeChanged) {
+            if (!changeResourceType(resource, resType)) {
+                return false;
             }
         }
+
+        return true;
     }
 
-    private void observerListChangedUINotification(String resourceURI) {
-        synchronized (observerUIListeners) {
-            if (observerUIListeners.size() > 0 && null != resourceURI) {
-                IObserverListChangedUIListener listener;
-                Iterator<IObserverListChangedUIListener> listenerItr = observerUIListeners
-                        .iterator();
-                while (listenerItr.hasNext()) {
-                    listener = listenerItr.next();
-                    if (null != listener) {
-                        listener.onObserverListChanged(resourceURI);
-                    }
-                }
-            }
+    public boolean updateResourceInterfaces(Resource resource,
+            Set<String> newIfSet) throws SimulatorException {
+        if (null == resource || null == newIfSet || newIfSet.isEmpty()) {
+            return false;
         }
-    }
 
-    public List<String> getResourceTypeList() {
-        List<String> typeList = null;
-        synchronized (resourceMap) {
-            if (resourceMap.size() > 0) {
-                typeList = new ArrayList<String>();
-                Set<String> typeSet = resourceMap.keySet();
-                Iterator<String> typeItr = typeSet.iterator();
-                while (typeItr.hasNext()) {
-                    typeList.add(typeItr.next());
-                }
-            }
+        SimulatorResource jResource = resource.getSimulatorResource();
+        if (null == jResource) {
+            return false;
         }
-        return typeList;
-    }
 
-    public boolean isTypeExist(String resType) {
-        synchronized (resourceMap) {
-            if (resourceMap.containsKey(resType)) {
-                return true;
-            }
+        Set<String> curIfSet = resource.getResourceInterfaces();
+        if (null == curIfSet || curIfSet.isEmpty()) {
+            return false;
         }
-        return false;
-    }
 
-    public List<String> getURIList() {
-        List<String> list = null;
-        synchronized (orderedResourceUriMap) {
-            Set<String> typeSet = orderedResourceUriMap.keySet();
-            List<String> typeList = Utility.convertSetToList(typeSet);
-            if (null == typeList || typeList.size() < 1) {
-                return list;
+        Iterator<String> itr = curIfSet.iterator();
+        String interfaceType;
+        boolean resourceRestartRequired = false;
+        while (itr.hasNext()) {
+            interfaceType = itr.next();
+            if (!newIfSet.contains(interfaceType)) {
+                resourceRestartRequired = true;
+                break;
             }
-            list = new ArrayList<String>();
-
-            // Sort the types
-            Collections.sort(typeList);
+        }
 
-            // Add all URIs to the output list
-            Iterator<String> typeItr = typeList.iterator();
-            while (typeItr.hasNext()) {
-                List<String> l = orderedResourceUriMap.get(typeItr.next());
-                if (null != l) {
-                    list.addAll(l);
+        try {
+            // As there is no support from native layer for interface removal,
+            // supporting it from the simulator requires restarting the resource
+            // if any existing interfaces are removed.
+
+            if (resourceRestartRequired) {
+                stopResource(resource);
+                jResource.setInterface(Utility
+                        .convertSetToVectorString(newIfSet));
+                startResource(resource);
+            } else {
+                // Existing interfaces are not removed.
+                itr = newIfSet.iterator();
+                while (itr.hasNext()) {
+                    interfaceType = itr.next();
+                    if (!curIfSet.contains(interfaceType)) {
+                        jResource.addInterface(interfaceType);
+                    }
                 }
             }
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "There is an error while changing the interface types."
+                                    + Utility.getSimulatorErrorString(e, null));
+            throw e;
         }
-        return list;
+
+        // Set the resource interfaces.
+        resource.setResourceInterfaces(newIfSet);
+
+        return true;
     }
 
-    public void resourceSelectionChanged(final String selectedItem) {
-        new Thread() {
-            @Override
-            public void run() {
-                // Check whether the item selected is a resource or resource
-                // category
-                if (isTypeExist(selectedItem)) {
-                    // Given item is a resource Type
-                    setCurrentResourceInSelection(null);
-                } else {
-                    // Given item is a resource URI
-                    SimulatorResource resource = getSimulatorResourceByURI(selectedItem);
-                    if (null != resource) {
-                        setCurrentResourceInSelection(resource);
-                    } else {
-                        setCurrentResourceInSelection(null);
-                    }
+    public boolean attributeValueUpdated(SingleResource resource,
+            String attributeName, AttributeValue value) {
+        if (null != resource && null != attributeName && null != value) {
+            SimulatorSingleResource simRes = (SimulatorSingleResource) resource
+                    .getSimulatorResource();
+            if (null != simRes) {
+                try {
+                    simRes.updateAttribute(attributeName, value);
+                    return true;
+                } catch (SimulatorException e) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(), new Date(),
+                                    Utility.getSimulatorErrorString(e, null));
                 }
-                // Notify all observers for resource selection change event
-                resourceSelectionChangedUINotification();
             }
-        }.start();
+        }
+        return false;
     }
 
-    public List<MetaProperty> getMetaProperties(SimulatorResource resource) {
-        if (null != resource) {
-            String propName;
-            String propValue;
-
-            List<MetaProperty> metaPropertyList = new ArrayList<MetaProperty>();
+    public boolean isResourceStarted(Resource resource) {
+        if (null == resource) {
+            return false;
+        }
+        return resource.isStarted();
+    }
 
-            for (int index = 0; index < Constants.META_PROPERTY_COUNT; index++) {
-                propName = Constants.META_PROPERTIES[index];
+    public boolean isPropertyValueInvalid(Resource resource,
+            List<MetaProperty> properties, String propName) {
+        if (null == resource || null == properties || null == propName) {
+            return false;
+        }
+        boolean invalid = false;
+        MetaProperty prop;
+        Iterator<MetaProperty> itr = properties.iterator();
+        while (itr.hasNext()) {
+            prop = itr.next();
+            if (prop.getPropName().equals(propName)) {
+                String value = prop.getPropValue();
                 if (propName.equals(Constants.RESOURCE_URI)) {
-                    propValue = resource.getResourceURI();
+                    if (!Utility.isUriValid(value)) {
+                        invalid = true;
+                    }
                 } else if (propName.equals(Constants.RESOURCE_TYPE)) {
-                    propValue = resource.getResourceType();
-                } else if (propName.equals(Constants.CONNECTIVITY_TYPE)) {
-                    // TODO: Temporarily ignoring till the implementation.
-                    propValue = null;
+                    if (!Utility.isResourceTypeValid(value)) {
+                        invalid = true;
+                    }
                 } else {
-                    propValue = null;
-                }
-                if (null != propValue) {
-                    metaPropertyList.add(new MetaProperty(propName, propValue));
+                    if (null == value || value.trim().isEmpty()) {
+                        invalid = true;
+                    }
                 }
             }
-
-            return metaPropertyList;
         }
-        return null;
+        return invalid;
     }
 
-    public List<LocalResourceAttribute> getAttributes(SimulatorResource resource) {
-        List<LocalResourceAttribute> attList = null;
-        if (null != resource) {
-            Map<String, LocalResourceAttribute> attMap = resource
-                    .getResourceAttributesMap();
-            if (null != attMap && attMap.size() > 0) {
-                attList = new ArrayList<LocalResourceAttribute>();
-                Set<String> attNameSet = attMap.keySet();
-                String attName;
-                LocalResourceAttribute attribute;
-                Iterator<String> attNameItr = attNameSet.iterator();
-                while (attNameItr.hasNext()) {
-                    attName = attNameItr.next();
-                    attribute = attMap.get(attName);
-                    if (null != attribute) {
-                        attList.add(attribute);
-                    }
+    public boolean isPropValueChanged(Resource resource,
+            List<MetaProperty> properties, String propName) {
+        if (null == resource || null == properties || null == propName) {
+            return false;
+        }
+        boolean changed = false;
+        MetaProperty prop;
+        String oldValue;
+        Iterator<MetaProperty> itr = properties.iterator();
+        while (itr.hasNext()) {
+            prop = itr.next();
+            if (prop.getPropName().equals(propName)) {
+                oldValue = getPropertyValueFromResource(resource, propName);
+                if (null != oldValue && !prop.getPropValue().equals(oldValue)) {
+                    changed = true;
                 }
+                break;
             }
         }
-        return attList;
+        return changed;
     }
 
-    public void attributeValueUpdated(SimulatorResource resource,
-            String attributeName, String value) {
-        if (null != resource && null != attributeName && null != value) {
-            SimulatorResourceServer server = resource.getResourceServer();
-            if (null != server) {
-                LocalResourceAttribute att = resource
-                        .getAttribute(attributeName);
-                if (null == att) {
-                    return;
-                }
-                Type baseType = att.getAttValBaseType();
-                try {
-                    if (baseType == Type.STRING) {
-                        server.updateAttributeString(attributeName, value);
-                    } else if (baseType == Type.INT) {
-                        int val;
-                        try {
-                            val = Integer.parseInt(value);
-                            server.updateAttributeInteger(attributeName, val);
-                        } catch (NumberFormatException nfe) {
-                            return;
-                        }
-                    } else if (baseType == Type.DOUBLE) {
-                        double val;
-                        try {
-                            val = Double.parseDouble(value);
-                            server.updateAttributeDouble(attributeName, val);
-                        } catch (NumberFormatException nfe) {
-                            return;
-                        }
-                    } else if (baseType == Type.BOOL) {
-                        boolean val;
-                        val = Boolean.parseBoolean(value);
-                        server.updateAttributeBoolean(attributeName, val);
-                    }
-                } catch (SimulatorException e) {
-                    Activator
-                            .getDefault()
-                            .getLogManager()
-                            .log(Level.ERROR.ordinal(),
-                                    new Date(),
-                                    "[" + e.getClass().getSimpleName() + "]"
-                                            + e.code().toString() + "-"
-                                            + e.message());
-                }
-            }
+    private String getPropertyValueFromResource(Resource resource,
+            String propName) {
+        if (null == resource || null == propName) {
+            return null;
+        }
+        if (propName.equals(Constants.RESOURCE_URI)) {
+            return resource.getResourceURI();
+        } else if (propName.equals(Constants.RESOURCE_NAME)) {
+            return resource.getResourceName();
+        } else if (propName.equals(Constants.RESOURCE_TYPE)) {
+            return resource.getResourceType();
+        } else {
+            return null;
         }
     }
 
-    private ModelChangeNotificationType compareAndUpdateLocalAttributes(
-            Map<String, LocalResourceAttribute> resourceAttributeMapOld,
-            Map<String, LocalResourceAttribute> resourceAttributeMapNew,
-            Set<LocalResourceAttribute> valueChangeSet) {
-        ModelChangeNotificationType notificationType = ModelChangeNotificationType.NONE;
-        if (null != resourceAttributeMapOld && null != resourceAttributeMapNew) {
-            Set<String> oldMapKeySet = resourceAttributeMapOld.keySet();
-            Iterator<String> attributeMapOldItr = oldMapKeySet.iterator();
-            String attName;
-            LocalResourceAttribute attributeOld;
-            LocalResourceAttribute attributeNew;
-            Object attValueOld;
-            Object attValueNew;
-            String oldValueStr;
-            String newValueStr;
-            while (attributeMapOldItr.hasNext()) {
-                attName = attributeMapOldItr.next();
-                if (resourceAttributeMapNew.containsKey(attName)) {
-                    attributeOld = resourceAttributeMapOld.get(attName);
-                    attributeNew = resourceAttributeMapNew.get(attName);
-                    // Copy the attribute value from new to old if the value
-                    // has been changed
-                    // Comparing only the attribute's value considering the
-                    // fact that only the value can be changed
-                    if (null != attributeOld && null != attributeNew) {
-                        attValueOld = attributeOld.getAttributeValue();
-                        attValueNew = attributeNew.getAttributeValue();
-
-                        oldValueStr = String.valueOf(attValueOld);
-                        newValueStr = String.valueOf(attValueNew);
-
-                        if (null != oldValueStr && null != newValueStr) {
-                            if (!oldValueStr.equals(newValueStr)) {
-                                attributeOld.setAttributeValue(attValueNew);
-                                notificationType = ModelChangeNotificationType.ATTRIBUTE_VALUE_CHANGED;
-                                valueChangeSet.add(attributeOld);
-                            }
-                        }
-                    }
-                    resourceAttributeMapNew.remove(attName);
-                } else {
-                    // Attribute doesn't exist in the new model. Hence
-                    // removing it from the model.
-                    resourceAttributeMapOld.remove(attName);
-                    notificationType = ModelChangeNotificationType.ATTRIBUTE_REMOVED;
-                }
+    public boolean isAttHasRangeOrAllowedValues(SimulatorResourceAttribute att) {
+        if (null == att) {
+            return false;
+        }
+        AttributeProperty prop = att.property();
+        if (null == prop) {
+            return false;
+        }
+
+        if (prop.getType() == Type.INTEGER) {
+            IntegerProperty intProperty = prop.asInteger();
+            if (null != intProperty) {
+                return (intProperty.hasRange() || intProperty.hasValues());
+            } else {
+                return false;
             }
-            // Check for new attributes in the new model
-            if (resourceAttributeMapNew.size() > 0) {
-                Set<String> remainingAttSet = resourceAttributeMapNew.keySet();
-                Iterator<String> remainingAttItr = remainingAttSet.iterator();
-                LocalResourceAttribute attribute;
-                while (remainingAttItr.hasNext()) {
-                    attName = remainingAttItr.next();
-                    if (null != attName) {
-                        attribute = resourceAttributeMapNew.get(attName);
-                        if (null != attribute) {
-                            resourceAttributeMapOld.put(attName, attribute);
-                        }
-                    }
-                }
-                notificationType = ModelChangeNotificationType.ATTRIBUTE_ADDED;
+        } else if (prop.getType() == Type.DOUBLE) {
+            DoubleProperty dblProperty = prop.asDouble();
+            if (null != dblProperty) {
+                return (dblProperty.hasRange() || dblProperty.hasValues());
+            } else {
+                return false;
+            }
+        } else if (prop.getType() == Type.STRING) {
+            StringProperty stringProperty = prop.asString();
+            if (null != stringProperty) {
+                return stringProperty.hasValues();
+            } else {
+                return false;
             }
         }
-        return notificationType;
+
+        return true;
     }
 
-    public int startAutomation(SimulatorResource resource,
-            LocalResourceAttribute attribute, AutomationType autoType,
+    public int startAutomation(SingleResource resource,
+            AttributeElement attribute, AutoUpdateType autoType,
             int autoUpdateInterval) {
         int autoId = -1;
         if (null != resource && null != attribute) {
-            SimulatorResourceServer resourceServerN = resource
-                    .getResourceServer();
-            if (null != resourceServerN) {
-                String attrName = attribute.getAttributeName();
+            SimulatorSingleResource server = (SimulatorSingleResource) resource
+                    .getSimulatorResource();
+            if (null != server) {
+                String attrName = attribute.getSimulatorResourceAttribute()
+                        .name();
                 try {
-                    autoId = resourceServerN.startAttributeAutomation(attrName,
-                            autoType, autoUpdateInterval, automationListener);
+                    autoId = server.startAttributeUpdation(attrName, autoType,
+                            autoUpdateInterval, automationListener);
                 } catch (SimulatorException e) {
                     Activator
                             .getDefault()
@@ -1362,27 +1389,25 @@ public class ResourceManager {
                     return -1;
                 }
                 if (-1 != autoId) {
-                    attribute.setAutomationId(autoId);
-                    attribute.setAutomationType(autoType);
-                    attribute.setAutomationUpdateInterval(autoUpdateInterval);
-                    attribute.setAutomationInProgress(true);
+                    attribute.setAutoUpdateId(autoId);
+                    attribute.setAutoUpdateType(autoType);
+                    attribute.setAutoUpdateInterval(autoUpdateInterval);
+                    attribute.setAutoUpdateState(true);
                     resource.setAttributeAutomationInProgress(true);
-                } else {
-                    attribute.setAutomationInProgress(false);
                 }
             }
         }
         return autoId;
     }
 
-    public void stopAutomation(SimulatorResource resource,
-            LocalResourceAttribute att, int autoId) {
+    public void stopAutomation(SingleResource resource, AttributeElement att,
+            int autoId) {
         if (null != resource) {
-            SimulatorResourceServer resourceServerN = resource
-                    .getResourceServer();
-            if (null != resourceServerN) {
+            SimulatorSingleResource server = (SimulatorSingleResource) resource
+                    .getSimulatorResource();
+            if (null != server) {
                 try {
-                    resourceServerN.stopAutomation(autoId);
+                    server.stopUpdation(autoId);
                 } catch (SimulatorException e) {
                     Activator
                             .getDefault()
@@ -1395,119 +1420,58 @@ public class ResourceManager {
                     return;
                 }
                 // Change the automation status
-                att.setAutomationInProgress(false);
+                att.setAutoUpdateState(false);
                 resource.setAttributeAutomationInProgress(isAnyAttributeInAutomation(resource));
             }
         }
     }
 
-    private boolean isAnyAttributeInAutomation(SimulatorResource resource) {
+    public boolean startResourceAutomationUIRequest(AutoUpdateType autoType,
+            int autoUpdateInterval, final SingleResource resource) {
         if (null == resource) {
             return false;
         }
-        Map<String, LocalResourceAttribute> attMap = resource
-                .getResourceAttributesMap();
-        if (null == attMap) {
-            return false;
-        }
         boolean status = false;
-        Set<String> keySet = attMap.keySet();
-        Iterator<String> attItr = keySet.iterator();
-        while (attItr.hasNext()) {
-            LocalResourceAttribute attribute = attMap.get(attItr.next());
-            if (attribute.isAutomationInProgress()) {
-                status = true;
-                break;
+        // Invoke the native automation method
+        SimulatorSingleResource resourceServer = (SimulatorSingleResource) resource
+                .getSimulatorResource();
+        if (null != resourceServer) {
+            int autoId = -1;
+            try {
+                autoId = resourceServer.startResourceUpdation(autoType,
+                        autoUpdateInterval, automationListener);
+            } catch (SimulatorException e) {
+                Activator
+                        .getDefault()
+                        .getLogManager()
+                        .log(Level.ERROR.ordinal(), new Date(),
+                                Utility.getSimulatorErrorString(e, null));
+                autoId = -1;
             }
-        }
-        return status;
-    }
+            if (-1 != autoId) {
+                // Automation request accepted.
+                changeResourceLevelAutomationStatus(resource, true);
 
-    private LocalResourceAttribute getAttributeWithGivenAutomationId(
-            SimulatorResource resource, int automationId) {
-        LocalResourceAttribute targetAttribute = null;
-        if (null != resource) {
-            Map<String, LocalResourceAttribute> attributeMap = resource
-                    .getResourceAttributesMap();
-            if (null != attributeMap) {
-                Set<String> attNameSet = attributeMap.keySet();
-                Iterator<String> attNameItr = attNameSet.iterator();
-                String attName;
-                LocalResourceAttribute attribute;
-                while (attNameItr.hasNext()) {
-                    attName = attNameItr.next();
-                    if (null != attName) {
-                        attribute = attributeMap.get(attName);
-                        if (null != attribute) {
-                            if (attribute.isAutomationInProgress()
-                                    && (attribute.getAutomationId() == automationId)) {
-                                targetAttribute = attribute;
-                                break;
-                            }
-                        }
-                    }
-                }
-            }
-        }
-        return targetAttribute;
-    }
+                resource.setAutomationId(autoId);
 
-    public boolean startResourceAutomationUIRequest(final String resourceURI) {
-        if (null == resourceURI) {
-            return false;
-        }
-        boolean status = false;
-        SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
-        if (null != resource) {
-            changeResourceLevelAutomationStatus(resource, true);
-
-            // Invoke the native automation method
-            SimulatorResourceServer resourceServer = resource
-                    .getResourceServer();
-            if (null != resourceServer) {
-                // TODO: Temporarily handling the normal one-time automation for
-                // resources
-                int autoId = -1;
-                try {
-                    autoId = resourceServer.startResourceAutomation(
-                            AutomationType.NORMAL, 500, automationListener);
-                } catch (SimulatorException e) {
-                    Activator
-                            .getDefault()
-                            .getLogManager()
-                            .log(Level.ERROR.ordinal(),
-                                    new Date(),
-                                    "[" + e.getClass().getSimpleName() + "]"
-                                            + e.code().toString() + "-"
-                                            + e.message());
-                    autoId = -1;
-                }
-                if (-1 == autoId) {
-                    // Automation request failed and hence status is being
-                    // rolled back
-                    changeResourceLevelAutomationStatus(resource, false);
-                } else {
-                    // Automation request accepted.
-                    resource.setAutomationId(autoId);
-
-                    // Notify the UI listeners in a different thread.
-                    Thread notifyThread = new Thread() {
-                        public void run() {
-                            resourceAutomationStartedUINotification(resourceURI);
-                        };
+                // Notify the UI listeners in a different thread.
+                Thread notifyThread = new Thread() {
+                    public void run() {
+                        UiListenerHandler.getInstance()
+                                .resourceAutomationStartedUINotification(
+                                        resource);
                     };
-                    notifyThread.setPriority(Thread.MAX_PRIORITY);
-                    notifyThread.start();
+                };
+                notifyThread.setPriority(Thread.MAX_PRIORITY);
+                notifyThread.start();
 
-                    status = true;
-                }
+                status = true;
             }
         }
         return status;
     }
 
-    public boolean stopResourceAutomationUIRequest(final String resourceURI) {
-        SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
+    public boolean stopResourceAutomationUIRequest(final SingleResource resource) {
         if (null == resource) {
             return false;
         }
@@ -1515,129 +1479,309 @@ public class ResourceManager {
         if (-1 == autoId) {
             return false;
         }
-        SimulatorResourceServer resourceServer = resource.getResourceServer();
+        SimulatorSingleResource resourceServer = (SimulatorSingleResource) resource
+                .getSimulatorResource();
         if (null == resourceServer) {
             return false;
         }
         // Call native method
         try {
-            resourceServer.stopAutomation(autoId);
+            resourceServer.stopUpdation(autoId);
         } catch (SimulatorException e) {
             Activator
                     .getDefault()
                     .getLogManager()
-                    .log(Level.ERROR.ordinal(),
-                            new Date(),
-                            "[" + e.getClass().getSimpleName() + "]"
-                                    + e.code().toString() + "-" + e.message());
+                    .log(Level.ERROR.ordinal(), new Date(),
+                            Utility.getSimulatorErrorString(e, null));
             return false;
         }
 
         // Notify the UI Listeners. Invoke the automation complete callback.
         Thread stopThread = new Thread() {
             public void run() {
-                automationListener.onAutomationComplete(resourceURI, autoId);
+                automationListener.onUpdateComplete(resource.getResourceURI(),
+                        autoId);
             }
         };
         stopThread.start();
         return true;
     }
 
+    private boolean isAnyAttributeInAutomation(SingleResource resource) {
+        if (null == resource || null == resource.getResourceRepresentation()) {
+            return false;
+        }
+
+        Map<String, AttributeElement> attributes = resource
+                .getResourceRepresentation().getAttributes();
+        if (null == attributes || 0 == attributes.size())
+            return false;
+
+        for (Map.Entry<String, AttributeElement> entry : attributes.entrySet()) {
+            if (entry.getValue().isAutoUpdateInProgress())
+                return true;
+        }
+
+        return false;
+    }
+
     // Changes the automation state of the resource and its attributes
-    private void changeResourceLevelAutomationStatus(
-            SimulatorResource resource, boolean status) {
-
-        Map<String, LocalResourceAttribute> attributeMap = resource
-                .getResourceAttributesMap();
-        if (null != attributeMap) {
-            Set<String> attrNameSet = attributeMap.keySet();
-            Iterator<String> attrNameItr = attrNameSet.iterator();
-            String attrName;
-            LocalResourceAttribute attribute;
-            while (attrNameItr.hasNext()) {
-                attrName = attrNameItr.next();
-                attribute = attributeMap.get(attrName);
-                if (null != attribute) {
-                    attribute.setAutomationInProgress(status);
-                }
-            }
+    private void changeResourceLevelAutomationStatus(SingleResource resource,
+            boolean status) {
+
+        if (null == resource || null == resource.getResourceRepresentation()) {
+            return;
         }
+
+        Map<String, AttributeElement> attributes = resource
+                .getResourceRepresentation().getAttributes();
+        if (null == attributes || 0 == attributes.size())
+            return;
+
+        for (Map.Entry<String, AttributeElement> entry : attributes.entrySet()) {
+            entry.getValue().setAutoUpdateState(status);
+        }
+
         resource.setResourceAutomationInProgress(status);
     }
 
-    public boolean isResourceAutomationStarted(String resourceURI) {
-        boolean status = false;
-        if (null == resourceURI) {
-            return status;
+    private AttributeElement getAttributeWithGivenAutomationId(
+            SingleResource resource, int automationId) {
+        if (null == resource || null == resource.getResourceRepresentation()) {
+            return null;
         }
 
-        SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
-        if (null != resource) {
-            status = resource.isResourceAutomationInProgress();
+        Map<String, AttributeElement> attributes = resource
+                .getResourceRepresentation().getAttributes();
+        if (null == attributes || 0 == attributes.size())
+            return null;
+
+        for (Map.Entry<String, AttributeElement> entry : attributes.entrySet()) {
+            if (automationId == entry.getValue().getAutoUpdateId())
+                return entry.getValue();
         }
-        return status;
+
+        return null;
     }
 
-    public boolean isAttributeAutomationStarted(String resourceURI) {
+    public boolean isResourceAutomationStarted(SingleResource resource) {
         boolean status = false;
-        if (null == resourceURI) {
-            return status;
-        }
-        SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
         if (null != resource) {
-            status = resource.isAttributeAutomationInProgress();
+            status = resource.isResourceAutomationInProgress();
         }
         return status;
     }
 
-    public LocalResourceAttribute getAttributeByResourceURI(String uri,
-            String attName) {
-        if (null == uri || null == attName) {
-            return null;
-        }
-        SimulatorResource resource = getSimulatorResourceByURI(uri);
+    public boolean isAttributeAutomationStarted(SingleResource resource) {
         if (null == resource) {
-            return null;
-        }
-        Map<String, LocalResourceAttribute> attMap = resource
-                .getResourceAttributesMap();
-        if (null == attMap) {
-            return null;
+            return false;
         }
-        return attMap.get(attName);
+        return resource.isAttributeAutomationInProgress();
     }
 
-    public void notifyObserverRequest(SimulatorResource res, int observerId) {
-        if (null == res) {
+    public void notifyObserverRequest(Resource resource, int observerId) {
+        if (null == resource) {
             return;
         }
-        SimulatorResourceServer server = res.getResourceServer();
-        if (null == server) {
+        SimulatorResource simulatorResource = resource.getSimulatorResource();
+        if (null == simulatorResource) {
             return;
         }
         try {
-            server.notifyObserver(observerId);
+            simulatorResource.notifyObserver(observerId);
         } catch (SimulatorException e) {
             Activator
                     .getDefault()
                     .getLogManager()
-                    .log(Level.ERROR.ordinal(),
-                            new Date(),
-                            "[" + e.getClass().getSimpleName() + "]"
-                                    + e.code().toString() + "-" + e.message());
+                    .log(Level.ERROR.ordinal(), new Date(),
+                            Utility.getSimulatorErrorString(e, null));
         }
     }
 
-    public Image getImage(String resourceURI) {
-        if (null == resourceURI) {
+    public List<String> getAllValuesOfAttribute(SimulatorResourceAttribute att) {
+        if (null == att) {
             return null;
         }
-        SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
-        if (null == resource) {
+
+        AttributeValue value = att.value();
+        if (null == value || null == value.get()) {
             return null;
         }
-        return Activator.getDefault().getImageRegistry()
-                .get(resource.getResourceType());
+
+        TypeInfo type = value.typeInfo();
+
+        if (type.mBaseType == ValueType.RESOURCEMODEL) {
+            return null;
+        }
+
+        List<String> values = new ArrayList<String>();
+
+        AttributeProperty prop = att.property();
+        if (null == prop) {
+            // Adding the current value of the attribute.
+            values.add(new AttributeValueStringConverter(value).toString());
+            return values;
+        }
+
+        if (type.mType == ValueType.ARRAY) {
+            if (type.mDepth == 1) {
+                ArrayProperty arrayProperty = prop.asArray();
+                if (null != arrayProperty) {
+                    AttributeProperty childProp = arrayProperty
+                            .getElementProperty();
+                    switch (childProp.getType()) {
+                        case INTEGER:
+                            IntegerProperty intProperty = childProp.asInteger();
+                            if (null != intProperty) {
+                                values.addAll(getAllValues(att, intProperty,
+                                        Type.INTEGER));
+                            }
+                            break;
+                        case DOUBLE:
+                            DoubleProperty dblProperty = childProp.asDouble();
+                            if (null != dblProperty) {
+                                values.addAll(getAllValues(att, dblProperty,
+                                        Type.DOUBLE));
+                            }
+                            break;
+                        case BOOLEAN:
+                            BooleanProperty boolProperty = childProp
+                                    .asBoolean();
+                            if (null != boolProperty) {
+                                values.addAll(getAllValues(att, boolProperty,
+                                        Type.BOOLEAN));
+                            }
+                            break;
+                        case STRING:
+                            StringProperty stringProperty = childProp
+                                    .asString();
+                            if (null != stringProperty) {
+                                values.addAll(getAllValues(att, stringProperty,
+                                        Type.STRING));
+                            }
+                            break;
+                        default:
+                            break;
+                    }
+                }
+            }
+        } else {
+            switch (prop.getType()) {
+                case INTEGER:
+                    IntegerProperty intProperty = prop.asInteger();
+                    if (null != intProperty) {
+                        values.addAll(getAllValues(att, intProperty,
+                                Type.INTEGER));
+                    }
+                    break;
+                case DOUBLE:
+                    DoubleProperty dblProperty = prop.asDouble();
+                    if (null != dblProperty) {
+                        values.addAll(getAllValues(att, dblProperty,
+                                Type.DOUBLE));
+                    }
+                    break;
+                case BOOLEAN:
+                    BooleanProperty boolProperty = prop.asBoolean();
+                    if (null != boolProperty) {
+                        values.addAll(getAllValues(att, boolProperty,
+                                Type.BOOLEAN));
+                    }
+                    break;
+                case STRING:
+                    StringProperty stringProperty = prop.asString();
+                    if (null != stringProperty) {
+                        values.addAll(getAllValues(att, stringProperty,
+                                Type.STRING));
+                    }
+                    break;
+                default:
+                    break;
+            }
+        }
+
+        return values;
+    }
+
+    public List<String> getAllValues(SimulatorResourceAttribute attribute,
+            IntegerProperty intProperty, AttributeProperty.Type type) {
+        List<String> values = new ArrayList<String>();
+
+        if (intProperty.hasRange()) {
+            int min = (int) intProperty.min();
+            int max = (int) intProperty.max();
+            for (int iVal = min; iVal <= max; iVal++) {
+                values.add(String.valueOf(iVal));
+            }
+        } else if (intProperty.hasValues()) {
+            for (Integer val : intProperty.getValues()) {
+                values.add(String.valueOf(val));
+            }
+        } else {
+            AttributeValue value = attribute.value();
+            if (null != value && null != value.get()) {
+                // Adding the current value of the attribute.
+                values.add(String.valueOf(value.get()));
+            }
+        }
+        return values;
+    }
+
+    public List<String> getAllValues(SimulatorResourceAttribute attribute,
+            DoubleProperty dblProperty, AttributeProperty.Type type) {
+        NumberFormat formatter = NumberFormat.getInstance();
+        List<String> values = new ArrayList<String>();
+
+        if (dblProperty.hasRange()) {
+            double min = (double) dblProperty.min();
+            double max = (double) dblProperty.max();
+            for (double val = min; val <= max; val += 0.1) {
+                formatter.setMaximumFractionDigits(1);
+                formatter.setMinimumFractionDigits(1);
+                values.add(formatter.format(val));
+            }
+        } else if (dblProperty.hasValues()) {
+            for (Double val : dblProperty.getValues()) {
+                values.add(String.valueOf(val));
+            }
+        } else {
+            AttributeValue value = attribute.value();
+            if (null != value && null != value.get()) {
+                // Adding the current value of the attribute.
+                values.add(String.valueOf(value.get()));
+            }
+        }
+        return values;
+    }
+
+    public List<String> getAllValues(SimulatorResourceAttribute attribute,
+            BooleanProperty boolProperty, AttributeProperty.Type type) {
+        List<String> values = new ArrayList<String>();
+        values.add("true");
+        values.add("false");
+        return values;
+    }
+
+    public List<String> getAllValues(SimulatorResourceAttribute attribute,
+            StringProperty stringProperty, AttributeProperty.Type type) {
+        List<String> values = new ArrayList<String>();
+
+        if (stringProperty.hasValues()) {
+            for (String val : stringProperty.getValues()) {
+                values.add(String.valueOf(val));
+            }
+        } else {
+            AttributeValue value = attribute.value();
+            if (null != value && null != value.get()) {
+                // Adding the current value of the attribute.
+                values.add(String.valueOf(value.get()));
+            }
+        }
+        return values;
+    }
+
+    public int getResourceCount() {
+        return data.getResourceCount();
     }
 
     public void shutdown() {
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/UiListenerHandler.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/UiListenerHandler.java
new file mode 100644 (file)
index 0000000..1ed1cfc
--- /dev/null
@@ -0,0 +1,367 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.manager;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import oic.simulator.serviceprovider.listener.IAutomationListener;
+import oic.simulator.serviceprovider.listener.IDataChangeListener;
+import oic.simulator.serviceprovider.listener.IDeviceInfoListener;
+import oic.simulator.serviceprovider.listener.IObserverListChangedListener;
+import oic.simulator.serviceprovider.listener.IPropertiesChangedListener;
+import oic.simulator.serviceprovider.listener.IResourceListChangedListener;
+import oic.simulator.serviceprovider.listener.ISelectionChangedListener;
+import oic.simulator.serviceprovider.model.AttributeElement;
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.model.ResourceType;
+import oic.simulator.serviceprovider.model.SingleResource;
+
+public class UiListenerHandler {
+
+    private static UiListenerHandler           uiHandler;
+
+    private List<IResourceListChangedListener> resourceListChangedUIListeners;
+
+    private List<ISelectionChangedListener>    selectionChangedUIListeners;
+
+    private List<IAutomationListener>          automationUIListeners;
+
+    private List<IObserverListChangedListener> observerUIListeners;
+
+    private List<IPropertiesChangedListener>   propertiesChangedUIListeners;
+
+    private List<IDeviceInfoListener>          deviceInfoUIListeners;
+
+    private List<IDataChangeListener>          dataChangeListeners;
+
+    private UiListenerHandler() {
+        resourceListChangedUIListeners = new ArrayList<IResourceListChangedListener>();
+        selectionChangedUIListeners = new ArrayList<ISelectionChangedListener>();
+        automationUIListeners = new ArrayList<IAutomationListener>();
+        observerUIListeners = new ArrayList<IObserverListChangedListener>();
+        propertiesChangedUIListeners = new ArrayList<IPropertiesChangedListener>();
+        deviceInfoUIListeners = new ArrayList<IDeviceInfoListener>();
+        dataChangeListeners = new ArrayList<IDataChangeListener>();
+    }
+
+    public static UiListenerHandler getInstance() {
+        if (null == uiHandler) {
+            uiHandler = new UiListenerHandler();
+        }
+        return uiHandler;
+    }
+
+    public void addResourceListChangedUIListener(
+            IResourceListChangedListener resourceListChangedUIListener) {
+        synchronized (resourceListChangedUIListeners) {
+            resourceListChangedUIListeners.add(resourceListChangedUIListener);
+        }
+    }
+
+    public void addResourceSelectionChangedUIListener(
+            ISelectionChangedListener resourceSelectionChangedUIListener) {
+        synchronized (selectionChangedUIListeners) {
+            selectionChangedUIListeners.add(resourceSelectionChangedUIListener);
+        }
+    }
+
+    public void addAutomationUIListener(IAutomationListener automationUIListener) {
+        synchronized (automationUIListeners) {
+            automationUIListeners.add(automationUIListener);
+        }
+    }
+
+    public void addObserverListChangedUIListener(
+            IObserverListChangedListener observerListChangedUIListener) {
+        synchronized (observerUIListeners) {
+            observerUIListeners.add(observerListChangedUIListener);
+        }
+    }
+
+    public void addResourcePropertiesChangedUIListener(
+            IPropertiesChangedListener resourcePropertiesChangedUIListener) {
+        synchronized (propertiesChangedUIListeners) {
+            propertiesChangedUIListeners
+                    .add(resourcePropertiesChangedUIListener);
+        }
+    }
+
+    public void addDataChangeListener(IDataChangeListener dataChangeListener) {
+        synchronized (dataChangeListeners) {
+            dataChangeListeners.add(dataChangeListener);
+        }
+    }
+
+    public void removeResourceListChangedUIListener(
+            IResourceListChangedListener listener) {
+        synchronized (resourceListChangedUIListeners) {
+            if (null != listener && resourceListChangedUIListeners.size() > 0) {
+                resourceListChangedUIListeners.remove(listener);
+            }
+        }
+    }
+
+    public void removeResourceSelectionChangedUIListener(
+            ISelectionChangedListener listener) {
+        synchronized (selectionChangedUIListeners) {
+            if (null != listener && selectionChangedUIListeners.size() > 0) {
+                selectionChangedUIListeners.remove(listener);
+            }
+        }
+    }
+
+    public void removeAutomationUIListener(IAutomationListener listener) {
+        synchronized (automationUIListeners) {
+            if (null != listener && automationUIListeners.size() > 0) {
+                automationUIListeners.remove(listener);
+            }
+        }
+    }
+
+    public void removeObserverListChangedUIListener(
+            IObserverListChangedListener listener) {
+        synchronized (observerUIListeners) {
+            if (null != listener && observerUIListeners.size() > 0) {
+                observerUIListeners.remove(listener);
+            }
+        }
+    }
+
+    public void removeResourcePropertiesChangedUIListener(
+            IPropertiesChangedListener resourcePropertiesChangedUIListener) {
+        synchronized (propertiesChangedUIListeners) {
+            propertiesChangedUIListeners
+                    .remove(resourcePropertiesChangedUIListener);
+        }
+    }
+
+    public void removeDataChangeListener(IDataChangeListener dataChangeListener) {
+        synchronized (dataChangeListeners) {
+            dataChangeListeners.remove(dataChangeListener);
+        }
+    }
+
+    public void addDeviceInfoUIListener(IDeviceInfoListener deviceUIListener) {
+        synchronized (deviceInfoUIListeners) {
+            deviceInfoUIListeners.add(deviceUIListener);
+        }
+    }
+
+    public void removeDeviceInfoUIListener(
+            IDeviceInfoListener platformUIListener) {
+        synchronized (deviceInfoUIListeners) {
+            deviceInfoUIListeners.remove(platformUIListener);
+        }
+    }
+
+    public void resourceCreatedUINotification(ResourceType type) {
+        synchronized (resourceListChangedUIListeners) {
+            if (resourceListChangedUIListeners.size() > 0) {
+                IResourceListChangedListener listener;
+                Iterator<IResourceListChangedListener> listenerItr = resourceListChangedUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onResourceCreation(type);
+                    }
+                }
+            }
+        }
+    }
+
+    public void resourceDeletedUINotification(ResourceType type) {
+        synchronized (resourceListChangedUIListeners) {
+            if (resourceListChangedUIListeners.size() > 0) {
+                IResourceListChangedListener listener;
+                Iterator<IResourceListChangedListener> listenerItr = resourceListChangedUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onResourceDeletion(type);
+                    }
+                }
+            }
+        }
+    }
+
+    public void resourceListUpdateUINotification(ResourceType type) {
+        synchronized (resourceListChangedUIListeners) {
+            if (resourceListChangedUIListeners.size() > 0) {
+                IResourceListChangedListener listener;
+                Iterator<IResourceListChangedListener> listenerItr = resourceListChangedUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onResourceListUpdate(type);
+                    }
+                }
+            }
+        }
+    }
+
+    public void resourceSelectionChangedUINotification(Resource resource) {
+        synchronized (selectionChangedUIListeners) {
+            if (selectionChangedUIListeners.size() > 0) {
+                ISelectionChangedListener listener;
+                Iterator<ISelectionChangedListener> listenerItr = selectionChangedUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onResourceSelectionChange(resource);
+                    }
+                }
+            }
+        }
+    }
+
+    public void attributeUpdatedUINotification(AttributeElement attribute) {
+        synchronized (dataChangeListeners) {
+            if (dataChangeListeners.size() > 0 && null != attribute) {
+                IDataChangeListener listener;
+                Iterator<IDataChangeListener> listenerItr = dataChangeListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.update(attribute);
+                    }
+                }
+            }
+        }
+    }
+
+    public void attributeAddedUINotification(AttributeElement attribute) {
+        synchronized (dataChangeListeners) {
+            if (dataChangeListeners.size() > 0 && null != attribute) {
+                IDataChangeListener listener;
+                Iterator<IDataChangeListener> listenerItr = dataChangeListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.add(attribute);
+                    }
+                }
+            }
+        }
+    }
+
+    public void attributeRemovedUINotification(AttributeElement attribute) {
+        synchronized (dataChangeListeners) {
+            if (dataChangeListeners.size() > 0 && null != attribute) {
+                IDataChangeListener listener;
+                Iterator<IDataChangeListener> listenerItr = dataChangeListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.remove(attribute);
+                    }
+                }
+            }
+        }
+    }
+
+    public void resourceAutomationStartedUINotification(SingleResource resource) {
+        synchronized (automationUIListeners) {
+            if (automationUIListeners.size() > 0 && null != resource) {
+                IAutomationListener listener;
+                Iterator<IAutomationListener> listenerItr = automationUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onResourceAutomationStart(resource);
+                    }
+                }
+            }
+        }
+    }
+
+    public void automationCompleteUINotification(SingleResource resource,
+            String attName) {
+        synchronized (automationUIListeners) {
+            if (automationUIListeners.size() > 0 && null != resource) {
+                IAutomationListener listener;
+                Iterator<IAutomationListener> listenerItr = automationUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onAutomationComplete(resource, attName);
+                    }
+                }
+            }
+        }
+    }
+
+    public void observerListChangedUINotification(Resource resource) {
+        synchronized (observerUIListeners) {
+            if (observerUIListeners.size() > 0 && null != resource) {
+                IObserverListChangedListener listener;
+                Iterator<IObserverListChangedListener> listenerItr = observerUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onObserverListChanged(resource);
+                    }
+                }
+            }
+        }
+    }
+
+    public void propertiesChangedUINotification(Class<?> targetClass) {
+        synchronized (propertiesChangedUIListeners) {
+            if (propertiesChangedUIListeners.size() > 0) {
+                IPropertiesChangedListener listener;
+                Iterator<IPropertiesChangedListener> listenerItr = propertiesChangedUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        if (targetClass == Resource.class) {
+                            listener.onResourcePropertyChange();
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    public void deviceInfoReceivedNotification() {
+        synchronized (deviceInfoUIListeners) {
+            if (deviceInfoUIListeners.size() > 0) {
+                IDeviceInfoListener listener;
+                Iterator<IDeviceInfoListener> listenerItr = deviceInfoUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onDeviceInfoFound();
+                    }
+                }
+            }
+        }
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/AttributeElement.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/AttributeElement.java
new file mode 100644 (file)
index 0000000..e98e678
--- /dev/null
@@ -0,0 +1,535 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.model;
+
+import java.util.Date;
+import java.util.Map;
+import java.util.TreeMap;
+
+import org.oic.simulator.ArrayProperty;
+import org.oic.simulator.AttributeProperty;
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.DoubleProperty;
+import org.oic.simulator.ILogger.Level;
+import org.oic.simulator.IntegerProperty;
+import org.oic.simulator.InvalidArgsException;
+import org.oic.simulator.ModelProperty;
+import org.oic.simulator.SimulatorResourceAttribute;
+import org.oic.simulator.SimulatorResourceModel;
+import org.oic.simulator.StringProperty;
+import org.oic.simulator.server.SimulatorResource.AutoUpdateType;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.manager.UiListenerHandler;
+import oic.simulator.serviceprovider.utils.AttributeValueStringConverter;
+import oic.simulator.serviceprovider.utils.Constants;
+import oic.simulator.serviceprovider.utils.Utility;
+
+public class AttributeElement {
+    private Object                        mParent             = null;
+    private SimulatorResourceAttribute    mAttribute          = null;
+    private Map<String, AttributeElement> mChildAttributes    = new TreeMap<String, AttributeElement>();
+    private boolean                       mAutoUpdateSupport  = false;
+    private int                           mAutoUpdateId       = -1;
+    private boolean                       mAutoUpdateState    = false;
+    private int                           mAutoUpdateInterval = Constants.DEFAULT_AUTOMATION_INTERVAL;
+    private AutoUpdateType                mAutoUpdateType     = Constants.DEFAULT_AUTOMATION_TYPE;
+    private boolean                       mEditLock           = false;
+
+    public AttributeElement(Object parent,
+            SimulatorResourceAttribute attribute, boolean autoUpdateSupport)
+            throws NullPointerException {
+        mParent = parent;
+        mAttribute = attribute;
+        mAutoUpdateSupport = autoUpdateSupport;
+        AttributeValue.TypeInfo typeInfo = attribute.value().typeInfo();
+        if (typeInfo.mType == AttributeValue.ValueType.RESOURCEMODEL) {
+            mAutoUpdateSupport = false;
+            SimulatorResourceModel resModel = (SimulatorResourceModel) attribute
+                    .value().get();
+            ModelProperty modelProp = null;
+            if (null != attribute.property()) {
+                modelProp = attribute.property().asModel();
+            }
+            String attName;
+            for (Map.Entry<String, AttributeValue> entry : resModel.get()
+                    .entrySet()) {
+                attName = entry.getKey();
+                AttributeProperty prop = null;
+                if (null != modelProp)
+                    prop = modelProp.get(attName);
+                mChildAttributes.put(
+                        attName,
+                        new AttributeElement(this,
+                                new SimulatorResourceAttribute(attName, entry
+                                        .getValue(), prop), false));
+            }
+        } else if (typeInfo.mType == AttributeValue.ValueType.ARRAY) {
+            mAutoUpdateSupport = false;
+            if (typeInfo.mBaseType == AttributeValue.ValueType.RESOURCEMODEL) {
+                if (typeInfo.mDepth == 1) {
+                    SimulatorResourceModel[] resModelArray = (SimulatorResourceModel[]) attribute
+                            .value().get();
+
+                    ModelProperty modelProp = null;
+                    if (null != attribute.property()) {
+                        ArrayProperty arrProp = attribute.property().asArray();
+                        if (null != arrProp
+                                && null != arrProp.getElementProperty()) {
+                            modelProp = arrProp.getElementProperty().asModel();
+                        }
+                    }
+                    for (int i = 0; i < resModelArray.length; i++) {
+                        SimulatorResourceAttribute indexAttribute = new SimulatorResourceAttribute(
+                                "[" + Integer.toString(i) + "]",
+                                new AttributeValue(resModelArray[i]), modelProp);
+                        mChildAttributes.put("[" + Integer.toString(i) + "]",
+                                new AttributeElement(this, indexAttribute,
+                                        false));
+                    }
+                } else if (typeInfo.mDepth == 2) {
+                    SimulatorResourceModel[][] resModelArray = (SimulatorResourceModel[][]) attribute
+                            .value().get();
+
+                    ModelProperty modelProp = null;
+                    if (null != attribute.property()) {
+                        ArrayProperty arrProp = attribute.property().asArray();
+                        if (null != arrProp
+                                && null != arrProp.getElementProperty()) {
+                            ArrayProperty arrChildPropLevel1 = arrProp
+                                    .getElementProperty().asArray();
+                            if (null != arrChildPropLevel1
+                                    && null != arrChildPropLevel1
+                                            .getElementProperty()) {
+                                modelProp = arrProp.getElementProperty()
+                                        .asModel();
+                            }
+                        }
+                    }
+
+                    for (int i = 0; i < resModelArray.length; i++) {
+                        SimulatorResourceAttribute indexAttribute = new SimulatorResourceAttribute(
+                                "[" + Integer.toString(i) + "]",
+                                new AttributeValue(resModelArray[i]), modelProp);
+                        mChildAttributes.put("[" + Integer.toString(i) + "]",
+                                new AttributeElement(this, indexAttribute,
+                                        false));
+                    }
+                } else if (typeInfo.mDepth == 3) {
+                    SimulatorResourceModel[][][] resModelArray = (SimulatorResourceModel[][][]) attribute
+                            .value().get();
+
+                    ModelProperty modelProp = null;
+                    if (null != attribute.property()) {
+                        ArrayProperty arrProp = attribute.property().asArray();
+                        if (null != arrProp
+                                && null != arrProp.getElementProperty()) {
+                            ArrayProperty arrChildPropLevel1 = arrProp
+                                    .getElementProperty().asArray();
+                            if (null != arrChildPropLevel1
+                                    && null != arrChildPropLevel1
+                                            .getElementProperty()) {
+                                ArrayProperty arrChildPropLevel2 = arrChildPropLevel1
+                                        .getElementProperty().asArray();
+                                if (null != arrChildPropLevel2
+                                        && null != arrChildPropLevel2
+                                                .getElementProperty()) {
+                                    modelProp = arrChildPropLevel2
+                                            .getElementProperty().asModel();
+                                }
+                            }
+                        }
+                    }
+
+                    for (int i = 0; i < resModelArray.length; i++) {
+                        SimulatorResourceAttribute indexAttribute = new SimulatorResourceAttribute(
+                                "[" + Integer.toString(i) + "]",
+                                new AttributeValue(resModelArray[i]), modelProp);
+                        mChildAttributes.put("[" + Integer.toString(i) + "]",
+                                new AttributeElement(this, indexAttribute,
+                                        false));
+                    }
+                }
+            }
+        }
+    }
+
+    public Object getParent() {
+        return mParent;
+    }
+
+    public boolean hasChildren() {
+        if (mChildAttributes != null && mChildAttributes.size() > 0)
+            return true;
+        return false;
+    }
+
+    public Map<String, AttributeElement> getChildren() {
+        if (hasChildren() == true)
+            return mChildAttributes;
+        return null;
+    }
+
+    public SimulatorResourceAttribute getSimulatorResourceAttribute() {
+        return mAttribute;
+    }
+
+    public int getAutoUpdateId() {
+        return mAutoUpdateId;
+    }
+
+    public void setAutoUpdateId(int id) {
+        mAutoUpdateId = id;
+    }
+
+    public boolean isAutoUpdateInProgress() {
+        return mAutoUpdateState;
+    }
+
+    public void setAutoUpdateState(boolean state) {
+        if (mAutoUpdateState != state) {
+            mAutoUpdateState = state;
+
+            UiListenerHandler.getInstance()
+                    .attributeUpdatedUINotification(this);
+        }
+    }
+
+    public int getAutoUpdateInterval() {
+        return mAutoUpdateInterval;
+    }
+
+    public void setAutoUpdateInterval(int interval) {
+        mAutoUpdateInterval = interval;
+    }
+
+    public AutoUpdateType getAutoUpdateType() {
+        return mAutoUpdateType;
+    }
+
+    public void setAutoUpdateType(AutoUpdateType type) {
+        mAutoUpdateType = type;
+    }
+
+    public boolean isAutoUpdateSupport() {
+        return mAutoUpdateSupport;
+    }
+
+    public boolean isReadOnly() {
+        AttributeProperty prop = mAttribute.property();
+        if (null == prop) {
+            return true;
+        }
+
+        if (prop.isInteger()) {
+            IntegerProperty intProperty = prop.asInteger();
+            return !(intProperty.hasRange() || intProperty.hasValues());
+        }
+
+        if (prop.isDouble()) {
+            DoubleProperty dblProperty = prop.asDouble();
+            return !(dblProperty.hasRange() || dblProperty.hasValues());
+        }
+
+        if (prop.isBoolean()) {
+            return false;
+        }
+
+        if (prop.isString()) {
+            StringProperty strProperty = prop.asString();
+            return !(strProperty.hasValues());
+        }
+
+        return true;
+    }
+
+    public synchronized boolean getEditLock() {
+        return mEditLock;
+    }
+
+    public synchronized void setEditLock(boolean editLock) {
+        this.mEditLock = editLock;
+    }
+
+    public void update(SimulatorResourceAttribute attribute) {
+        if (attribute == null)
+            return;
+
+        AttributeValue.TypeInfo typeInfo = attribute.value().typeInfo();
+        if (typeInfo.mType == AttributeValue.ValueType.RESOURCEMODEL) {
+            SimulatorResourceModel resModel = (SimulatorResourceModel) attribute
+                    .value().get();
+            String attName;
+            for (Map.Entry<String, AttributeValue> entry : resModel.get()
+                    .entrySet()) {
+                attName = entry.getKey();
+                AttributeElement attributeElement = mChildAttributes
+                        .get(attName);
+
+                if (attributeElement != null) {
+                    attributeElement.update(new SimulatorResourceAttribute(
+                            attName, entry.getValue()));
+                } else {
+                    // Get the property from the newly received attribute.
+                    ModelProperty modelProp = null;
+                    if (null != attribute.property()) {
+                        modelProp = attribute.property().asModel();
+                    }
+
+                    AttributeProperty prop = null;
+                    if (null != modelProp)
+                        prop = modelProp.get(attName);
+
+                    AttributeElement newAttribute = new AttributeElement(this,
+                            new SimulatorResourceAttribute(attName,
+                                    entry.getValue(), prop), false);
+
+                    // Update the attribute's value (Adding the new child
+                    // attribute).
+                    AttributeValue currentValue = mAttribute.value();
+                    SimulatorResourceModel curModel = (SimulatorResourceModel) currentValue
+                            .get();
+                    if (null != curModel) {
+                        try {
+                            curModel.set(attName, entry.getValue());
+                        } catch (InvalidArgsException e) {
+                            Activator
+                                    .getDefault()
+                                    .getLogManager()
+                                    .log(Level.ERROR.ordinal(),
+                                            new Date(),
+                                            "There is an error while updating the resource model.\n"
+                                                    + Utility
+                                                            .getSimulatorErrorString(
+                                                                    e, null));
+                        }
+
+                        mChildAttributes.put(attName, newAttribute);
+
+                        // Refresh UI to display the new attribute.
+                        UiListenerHandler.getInstance()
+                                .attributeAddedUINotification(newAttribute);
+                    }
+                }
+            }
+        } else if (typeInfo.mType == AttributeValue.ValueType.ARRAY
+                && typeInfo.mBaseType == AttributeValue.ValueType.RESOURCEMODEL) {
+            if (typeInfo.mDepth == 1) {
+                SimulatorResourceModel[] resModelArray = (SimulatorResourceModel[]) attribute
+                        .value().get();
+
+                ModelProperty modelProp = null;
+                if (null != mAttribute.property()) {
+                    ArrayProperty arrProp = mAttribute.property().asArray();
+                    if (null != arrProp && null != arrProp.getElementProperty()) {
+                        modelProp = arrProp.getElementProperty().asModel();
+                    }
+                }
+
+                mChildAttributes.clear();
+
+                SimulatorResourceModel[] newModelArray = new SimulatorResourceModel[resModelArray.length];
+
+                for (int i = 0; i < resModelArray.length; i++) {
+                    SimulatorResourceAttribute indexAttribute = new SimulatorResourceAttribute(
+                            "[" + Integer.toString(i) + "]",
+                            new AttributeValue(resModelArray[i]), modelProp);
+
+                    // Update the attribute's value (Adding the new child
+                    // attribute).
+                    AttributeElement newAttributeElement = new AttributeElement(
+                            this, indexAttribute, false);
+
+                    newModelArray[i] = resModelArray[i];
+
+                    mChildAttributes.put("[" + Integer.toString(i) + "]",
+                            newAttributeElement);
+                }
+
+                // Changing the value of the model array attribute. Property
+                // remains the same.
+                mAttribute.setValue(new AttributeValue(newModelArray));
+
+                // Refresh UI to display the new attribute.
+                UiListenerHandler.getInstance().attributeAddedUINotification(
+                        this);
+            }
+            if (typeInfo.mDepth == 2) {
+                SimulatorResourceModel[][] resModelArray = (SimulatorResourceModel[][]) attribute
+                        .value().get();
+
+                ModelProperty modelProp = null;
+                if (null != mAttribute.property()) {
+                    ArrayProperty arrProp = mAttribute.property().asArray();
+                    if (null != arrProp && null != arrProp.getElementProperty()) {
+                        ArrayProperty arrChildPropLevel1 = arrProp
+                                .getElementProperty().asArray();
+                        if (null != arrChildPropLevel1
+                                && null != arrChildPropLevel1
+                                        .getElementProperty()) {
+                            modelProp = arrProp.getElementProperty().asModel();
+                        }
+                    }
+                }
+
+                for (int i = 0; i < resModelArray.length; i++) {
+                    SimulatorResourceAttribute indexAttribute = new SimulatorResourceAttribute(
+                            "[" + Integer.toString(i) + "]",
+                            new AttributeValue(resModelArray[i]));
+                    AttributeElement attributeElement = mChildAttributes
+                            .get("[" + Integer.toString(i) + "]");
+                    if (attributeElement != null) {
+                        attributeElement.update(indexAttribute);
+                    } else {
+                        indexAttribute.setProperty(modelProp);
+
+                        // Update the attribute's value (Adding the new child
+                        // attribute).
+                        AttributeElement newAttribute = new AttributeElement(
+                                this, indexAttribute, false);
+                        AttributeValue currentValue = mAttribute.value();
+
+                        SimulatorResourceModel[][] curModelArray = (SimulatorResourceModel[][]) currentValue
+                                .get();
+                        SimulatorResourceModel[][] newModelArray = new SimulatorResourceModel[curModelArray.length + 1][];
+
+                        int j = 0;
+                        for (SimulatorResourceModel[] modelArray : curModelArray) {
+                            newModelArray[j++] = modelArray;
+                        }
+                        newModelArray[j] = resModelArray[i];
+
+                        mAttribute.setValue(new AttributeValue(newModelArray));
+                        mChildAttributes.put("[" + Integer.toString(i) + "]",
+                                newAttribute);
+
+                        // Refresh UI to display the new attribute.
+                        UiListenerHandler.getInstance()
+                                .attributeAddedUINotification(newAttribute);
+                    }
+                }
+            }
+            if (typeInfo.mDepth == 3) {
+                SimulatorResourceModel[][][] resModelArray = (SimulatorResourceModel[][][]) attribute
+                        .value().get();
+
+                ModelProperty modelProp = null;
+                if (null != mAttribute.property()) {
+                    ArrayProperty arrProp = mAttribute.property().asArray();
+                    if (null != arrProp && null != arrProp.getElementProperty()) {
+                        ArrayProperty arrChildPropLevel1 = arrProp
+                                .getElementProperty().asArray();
+                        if (null != arrChildPropLevel1
+                                && null != arrChildPropLevel1
+                                        .getElementProperty()) {
+                            ArrayProperty arrChildPropLevel2 = arrChildPropLevel1
+                                    .getElementProperty().asArray();
+                            if (null != arrChildPropLevel2
+                                    && null != arrChildPropLevel2
+                                            .getElementProperty()) {
+                                modelProp = arrChildPropLevel2
+                                        .getElementProperty().asModel();
+                            }
+                        }
+                    }
+                }
+
+                for (int i = 0; i < resModelArray.length; i++) {
+                    SimulatorResourceAttribute indexAttribute = new SimulatorResourceAttribute(
+                            "[" + Integer.toString(i) + "]",
+                            new AttributeValue(resModelArray[i]));
+                    AttributeElement attributeElement = mChildAttributes
+                            .get("[" + Integer.toString(i) + "]");
+                    if (attributeElement != null) {
+                        attributeElement.update(indexAttribute);
+                    } else {
+                        indexAttribute.setProperty(modelProp);
+
+                        // Update the attribute's value (Adding the new child
+                        // attribute).
+                        AttributeElement newAttribute = new AttributeElement(
+                                this, indexAttribute, false);
+                        AttributeValue currentValue = mAttribute.value();
+
+                        SimulatorResourceModel[][][] curModelArray = (SimulatorResourceModel[][][]) currentValue
+                                .get();
+                        SimulatorResourceModel[][][] newModelArray = new SimulatorResourceModel[curModelArray.length + 1][][];
+
+                        int j = 0;
+                        for (SimulatorResourceModel[][] modelArray : curModelArray) {
+                            newModelArray[j++] = modelArray;
+                        }
+                        newModelArray[j] = resModelArray[i];
+
+                        mAttribute.setValue(new AttributeValue(newModelArray));
+                        mChildAttributes.put("[" + Integer.toString(i) + "]",
+                                newAttribute);
+
+                        // Refresh UI to display the new attribute.
+                        UiListenerHandler.getInstance()
+                                .attributeAddedUINotification(newAttribute);
+                    }
+                }
+            }
+        } else {
+            String currentValue = new AttributeValueStringConverter(
+                    mAttribute.value()).toString();
+            String newValue = new AttributeValueStringConverter(
+                    attribute.value()).toString();
+            if (!currentValue.equals(newValue)) {
+                mAttribute.setValue(attribute.value());
+                if (mParent instanceof AttributeElement) {
+                    try {
+                        ((AttributeElement) mParent)
+                                .deepSetChildValue(mAttribute);
+                    } catch (InvalidArgsException e) {
+                        Activator
+                                .getDefault()
+                                .getLogManager()
+                                .log(Level.ERROR.ordinal(),
+                                        new Date(),
+                                        "There is an error while updating the resource model.\n"
+                                                + Utility
+                                                        .getSimulatorErrorString(
+                                                                e, null));
+                    }
+                }
+                UiListenerHandler.getInstance().attributeUpdatedUINotification(
+                        this);
+            }
+        }
+    }
+
+    public void deepSetChildValue(SimulatorResourceAttribute attribute)
+            throws InvalidArgsException {
+        if (null == attribute || null == attribute.name())
+            return;
+
+        AttributeValue.TypeInfo myValuetypeInfo = mAttribute.value().typeInfo();
+        if (myValuetypeInfo.mType == AttributeValue.ValueType.RESOURCEMODEL) {
+            SimulatorResourceModel resModel = (SimulatorResourceModel) mAttribute
+                    .value().get();
+            if (resModel.contains(attribute.name()))
+                resModel.set(attribute.name(), attribute.value());
+            else
+                return;
+        }
+
+        if (mParent instanceof AttributeElement)
+            ((AttributeElement) mParent).deepSetChildValue(mAttribute);
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/AttributeHelper.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/AttributeHelper.java
new file mode 100644 (file)
index 0000000..7329569
--- /dev/null
@@ -0,0 +1,417 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.model;
+
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+import org.oic.simulator.AttributeProperty;
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.AttributeValue.ValueType;
+import org.oic.simulator.BooleanProperty;
+import org.oic.simulator.DoubleProperty;
+import org.oic.simulator.IntegerProperty;
+import org.oic.simulator.SimulatorResourceAttribute;
+import org.oic.simulator.StringProperty;
+
+import oic.simulator.serviceprovider.utils.Constants;
+import oic.simulator.serviceprovider.utils.Utility;
+
+public class AttributeHelper {
+    private String      attributeName;
+    private String      attributeType;
+    private String      min;
+    private String      max;
+    private Set<String> allowedValues;
+    private String      attributeDflValue;
+
+    public enum ValidValuesType {
+        RANGE, VALUESET, UNKNOWN
+    }
+
+    private ValidValuesType validValuesType;
+
+    public AttributeHelper() {
+        allowedValues = new HashSet<String>();
+        setValidValuesType(ValidValuesType.UNKNOWN);
+        min = max = "";
+    }
+
+    public AttributeHelper clone() {
+        AttributeHelper att = new AttributeHelper();
+        att.setAttributeName(attributeName);
+        att.setAttributeType(attributeType);
+        att.setMin(min);
+        att.setMax(max);
+        if (null != allowedValues) {
+            Set<String> values = new HashSet<String>();
+            values.addAll(allowedValues);
+            att.setAllowedValues(values);
+        }
+        att.setAttributeDflValue(attributeDflValue);
+        att.setValidValuesType(validValuesType);
+        return att;
+    }
+
+    public String toString() {
+        return attributeName + "," + attributeType + "," + attributeDflValue
+                + "," + validValuesType + ",(" + min + max + "),("
+                + allowedValues + ")";
+    }
+
+    public String getAttributeName() {
+        return attributeName;
+    }
+
+    public void setAttributeName(String attributeName) {
+        this.attributeName = attributeName;
+    }
+
+    public String getAttributeType() {
+        return attributeType;
+    }
+
+    public void setAttributeType(String attributeType) {
+        this.attributeType = attributeType;
+    }
+
+    public String getMin() {
+        return min;
+    }
+
+    public void setMin(String min) {
+        this.min = min;
+    }
+
+    public String getMax() {
+        return max;
+    }
+
+    public void setMax(String max) {
+        this.max = max;
+    }
+
+    public Set<String> getAllowedValues() {
+        return allowedValues;
+    }
+
+    public void setAllowedValues(Set<String> allowedValues) {
+        this.allowedValues = allowedValues;
+    }
+
+    public void addValueToAllowedValues(String value) {
+        if (null != value && value.trim().length() > 0) {
+            if (null == allowedValues) {
+                allowedValues = new HashSet<String>();
+            }
+            allowedValues.add(value);
+        }
+    }
+
+    public void removeValueFromAllowedValues(String value) {
+        if (null != allowedValues && null != value && value.trim().length() > 0) {
+            allowedValues.remove(value);
+        }
+    }
+
+    public void removeAllCustomValues() {
+        allowedValues.clear();
+    }
+
+    public String getAttributeDflValue() {
+        return attributeDflValue;
+    }
+
+    public void setAttributeDflValue(String attributeDflValue) {
+        this.attributeDflValue = attributeDflValue;
+    }
+
+    public ValidValuesType getValidValuesType() {
+        return validValuesType;
+    }
+
+    public void setValidValuesType(ValidValuesType validValuesType) {
+        this.validValuesType = validValuesType;
+    }
+
+    public boolean isValueValid(String value, String type) {
+        if (null == value || value.trim().length() < 1 || null == type
+                || type.trim().length() < 1)
+            return false;
+        if (type.equalsIgnoreCase(Constants.INT)) {
+            return isIntValue(value);
+        } else if (type.equalsIgnoreCase(Constants.DOUBLE)) {
+            return isDoubleValue(value);
+        } else if (type.equalsIgnoreCase(Constants.BOOL)) {
+            return isBoolValue(value);
+        }
+        return true;
+    }
+
+    public boolean isBoolValue(String value) {
+        boolean isBool = false;
+        if (null != value
+                && (value.equalsIgnoreCase("true") || value
+                        .equalsIgnoreCase("false"))) {
+            isBool = true;
+        }
+        return isBool;
+    }
+
+    public boolean isIntValue(String value) {
+        boolean isInt = true;
+        try {
+            Integer.parseInt(value);
+        } catch (Exception e) {
+            isInt = false;
+        }
+        return isInt;
+    }
+
+    public boolean isDoubleValue(String value) {
+        boolean isDouble = true;
+        try {
+            Double.parseDouble(value);
+        } catch (Exception e) {
+            isDouble = false;
+        }
+        return isDouble;
+    }
+
+    public boolean isRangeValid(String minStr, String maxStr, String type) {
+        if (null == type || type.trim().isEmpty()) {
+            return false;
+        }
+        boolean result = true;
+        if (type.equals(Constants.INT)) {
+            int min, max;
+            try {
+                min = Integer.parseInt(minStr);
+                max = Integer.parseInt(maxStr);
+                if (max <= min) {
+                    result = false;
+                }
+            } catch (Exception e) {
+                result = false;
+            }
+        } else if (type.equals(Constants.DOUBLE)) {
+            double min, max;
+            try {
+                min = Double.parseDouble(minStr);
+                max = Double.parseDouble(maxStr);
+                if (max <= min) {
+                    result = false;
+                }
+            } catch (Exception e) {
+                result = false;
+            }
+        }
+        return result;
+    }
+
+    public boolean isDefaultValueValid(String value) {
+        if (null == attributeType || attributeType.trim().isEmpty()) {
+            return false;
+        }
+        boolean result = true;
+        if (attributeType.equals(Constants.STRING)) {
+            if (validValuesType == ValidValuesType.VALUESET
+                    && null != allowedValues) {
+                result = allowedValues.contains(value);
+            } else {
+                result = true;
+            }
+        } else if (attributeType.equals(Constants.BOOL)) {
+            String val = value.toLowerCase();
+            if (!(val.equals("true") || val.equals("false"))) {
+                result = false;
+            }
+        } else {
+            if (validValuesType == ValidValuesType.RANGE) {
+                if (attributeType.equals(Constants.INT)) {
+                    int min, max, dflValue;
+                    try {
+                        min = Integer.parseInt(this.min);
+                        max = Integer.parseInt(this.max);
+                        dflValue = Integer.parseInt(value);
+                        if (dflValue < min || dflValue > max) {
+                            result = false;
+                        }
+                    } catch (Exception e) {
+                        result = false;
+                    }
+                } else if (attributeType.equals(Constants.DOUBLE)) {
+                    double min, max, dflValue;
+                    try {
+                        min = Double.parseDouble(this.min);
+                        max = Double.parseDouble(this.max);
+                        dflValue = Double.parseDouble(value);
+                        boolean found = false;
+                        for (double val = min; val <= max; val += 1.0) {
+                            if (Double.compare(dflValue, val) == 0) {
+                                found = true;
+                                break;
+                            }
+                        }
+                        if (!found) {
+                            result = false;
+                        }
+                    } catch (Exception e) {
+                        result = false;
+                    }
+                }
+            } else if (validValuesType == ValidValuesType.VALUESET
+                    && null != allowedValues && !allowedValues.isEmpty()) {
+                boolean found = false;
+                if (attributeType.equals(Constants.INT)) {
+                    Iterator<String> itr = allowedValues.iterator();
+                    while (itr.hasNext()) {
+                        String val = itr.next();
+                        int v1 = Integer.parseInt(val);
+                        int v2 = Integer.parseInt(value);
+                        if (v1 == v2) {
+                            found = true;
+                            break;
+                        }
+                    }
+                } else {
+                    Iterator<String> itr = allowedValues.iterator();
+                    while (itr.hasNext()) {
+                        String val = itr.next();
+                        double v1 = Double.parseDouble(val);
+                        double v2 = Double.parseDouble(value);
+                        if (Double.compare(v1, v2) == 0) {
+                            found = true;
+                            break;
+                        }
+                    }
+                }
+                if (!found) {
+                    result = false;
+                }
+            }
+        }
+        return result;
+    }
+
+    public void setAllowedValuesByArray(String[] cusItems) {
+        if (null == cusItems) {
+            return;
+        }
+        for (String item : cusItems) {
+            addValueToAllowedValues(item);
+        }
+    }
+
+    public boolean isAllowedValueExist(String[] items, String value) {
+        if (null == items || items.length < 1 || null == value
+                || value.isEmpty())
+            return false;
+        for (String item : items) {
+            if (value.equalsIgnoreCase(item)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    public SimulatorResourceAttribute convertToSimulatorResourceAttribute() {
+        AttributeValue attValue = null;
+        AttributeProperty attProperty = null;
+        SimulatorResourceAttribute simResAtt;
+
+        ValueType valueType = Utility.getAttributeTypeEnum(attributeType);
+        switch (valueType) {
+            case INTEGER:
+                IntegerProperty.Builder intPropertyBuilder = new IntegerProperty.Builder();
+                attValue = new AttributeValue(
+                        Integer.parseInt(attributeDflValue));
+
+                // Set default value.
+                intPropertyBuilder.setDefaultValue(Integer
+                        .parseInt(attributeDflValue));
+
+                if (validValuesType == ValidValuesType.VALUESET) {
+                    // Set allowed values.
+                    intPropertyBuilder.setValues(Utility
+                            .convertSetToArrayInt(Utility
+                                    .convertSetStringToSetObject(allowedValues,
+                                            valueType)));
+                } else if (validValuesType == ValidValuesType.RANGE) {
+                    // Set Range.
+                    intPropertyBuilder.setRange(Integer.parseInt(min),
+                            Integer.parseInt(max));
+                }
+                attProperty = intPropertyBuilder.build();
+                break;
+            case DOUBLE:
+                DoubleProperty.Builder dblPropertyBuilder = new DoubleProperty.Builder();
+                attValue = new AttributeValue(
+                        Double.parseDouble(attributeDflValue));
+
+                // Set default value.
+                dblPropertyBuilder.setDefaultValue(Double
+                        .parseDouble(attributeDflValue));
+
+                if (validValuesType == ValidValuesType.VALUESET) {
+                    // Set allowed values.
+                    dblPropertyBuilder.setValues(Utility
+                            .convertSetToArrayDouble(Utility
+                                    .convertSetStringToSetObject(allowedValues,
+                                            valueType)));
+                } else if (validValuesType == ValidValuesType.RANGE) {
+                    // Set Range.
+                    dblPropertyBuilder.setRange(Double.parseDouble(min),
+                            Double.parseDouble(max));
+                }
+                attProperty = dblPropertyBuilder.build();
+                break;
+            case BOOLEAN:
+                attValue = new AttributeValue(
+                        Boolean.parseBoolean(attributeDflValue));
+                BooleanProperty.Builder boolPropertyBuilder = new BooleanProperty.Builder();
+                // Set Default Value.
+                boolPropertyBuilder.setDefaultValue(Boolean
+                        .parseBoolean(attributeDflValue));
+
+                attProperty = boolPropertyBuilder.build();
+                break;
+            case STRING:
+                attValue = new AttributeValue(attributeDflValue);
+                StringProperty.Builder stringPropertyBuilder = new StringProperty.Builder();
+
+                // Set Default Value.
+                stringPropertyBuilder.setDefaultValue(attributeDflValue);
+
+                if (validValuesType == ValidValuesType.VALUESET) {
+                    // Set Allowed Values.
+                    stringPropertyBuilder.setValues(Utility
+                            .convertSetToArrayString(Utility
+                                    .convertSetStringToSetObject(allowedValues,
+                                            valueType)));
+                }
+                attProperty = stringPropertyBuilder.build();
+                break;
+            default:
+                break;
+        }
+        simResAtt = new SimulatorResourceAttribute(attributeName, attValue,
+                attProperty);
+        return simResAtt;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/AutomationSettingHelper.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/AutomationSettingHelper.java
new file mode 100644 (file)
index 0000000..b531ba7
--- /dev/null
@@ -0,0 +1,128 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.model;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import org.oic.simulator.server.SimulatorResource.AutoUpdateType;
+
+import oic.simulator.serviceprovider.utils.Constants;
+
+/**
+ * This is a helper class for providing the automation settings information to
+ * UI.
+ */
+public class AutomationSettingHelper {
+    private String       settingID;
+    private String       settingValue;
+    private List<String> allowedValues;
+
+    public String getSettingID() {
+        return settingID;
+    }
+
+    public void setSettingID(String settingID) {
+        this.settingID = settingID;
+    }
+
+    public String getSettingValue() {
+        return settingValue;
+    }
+
+    public void setSettingValue(String settingValue) {
+        this.settingValue = settingValue;
+    }
+
+    public List<String> getAllowedValues() {
+        return allowedValues;
+    }
+
+    public void setAllowedValues(List<String> allowedValues) {
+        this.allowedValues = allowedValues;
+    }
+
+    public void addAllowedValue(String newText) {
+        if (null != allowedValues) {
+            allowedValues.add(newText);
+        }
+    }
+
+    public static List<AutomationSettingHelper> getAutomationSettings(
+            AttributeElement attribute) {
+        boolean invalidSetting;
+        List<AutomationSettingHelper> settingList = new ArrayList<AutomationSettingHelper>();
+        for (int count = 0; count < Constants.AUTOMATION_SETTINGS_COUNT; count++) {
+            invalidSetting = false;
+            AutomationSettingHelper setting = new AutomationSettingHelper();
+            if (Constants.AUTOMATION_SETTINGS[count]
+                    .equals(Constants.AUTOMATION_TYPE)) {
+                setting.setSettingID(Constants.AUTOMATION_TYPE);
+                if (null != attribute) {
+                    setting.setSettingValue(attribute.getAutoUpdateType()
+                            .toString());
+                } else {
+                    setting.setSettingValue(AutoUpdateType.ONE_TIME.toString());
+                }
+                List<String> valueList = new ArrayList<String>();
+                valueList.add(AutoUpdateType.ONE_TIME.toString());
+                valueList.add(AutoUpdateType.REPEAT.toString());
+                setting.setAllowedValues(valueList);
+            } else if (Constants.AUTOMATION_SETTINGS[count]
+                    .equals(Constants.UPDATE_INTERVAL_IN_MS)) {
+                setting.setSettingID(Constants.UPDATE_INTERVAL_IN_MS);
+                if (null != attribute) {
+                    setting.setSettingValue(String.valueOf(attribute
+                            .getAutoUpdateInterval()));
+                } else {
+                    setting.setSettingValue(String
+                            .valueOf(Constants.DEFAULT_AUTOMATION_INTERVAL));
+                }
+                List<String> valueList = new ArrayList<String>();
+                for (int index = 1; index <= 10; index++) {
+                    valueList.add(String.valueOf(index * 500));
+                }
+                setting.setAllowedValues(valueList);
+            } else {
+                invalidSetting = true;
+            }
+            if (!invalidSetting) {
+                settingList.add(setting);
+            }
+        }
+        return settingList;
+    }
+
+    public static void updateAutomationStatus(
+            List<AutomationSettingHelper> localSettingList, String status) {
+        if (null != localSettingList && null != status) {
+            Iterator<AutomationSettingHelper> settingItr = localSettingList
+                    .iterator();
+            AutomationSettingHelper setting;
+            while (settingItr.hasNext()) {
+                setting = settingItr.next();
+                if (null != setting) {
+                    if (setting.getSettingID().equals(Constants.AUTOMATION)) {
+                        setting.setSettingValue(status);
+                        break;
+                    }
+                }
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/MetaProperty.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/MetaProperty.java
new file mode 100644 (file)
index 0000000..6dd4c7b
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.model;
+
+/**
+ * This is a helper class for showing the meta properties of resources such as
+ * resource type, resource uri, etc.
+ */
+public class MetaProperty {
+    private String propName;
+    private String propValue;
+
+    public MetaProperty(String propName, String propValue) {
+        this.propName = propName;
+        this.propValue = propValue;
+    }
+
+    public String getPropValue() {
+        return propValue;
+    }
+
+    public void setPropValue(String propValue) {
+        this.propValue = propValue;
+    }
+
+    public String getPropName() {
+        return propName;
+    }
+
+    public void setPropName(String propName) {
+        this.propName = propName;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/ObserverDetail.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/ObserverDetail.java
new file mode 100644 (file)
index 0000000..63e1568
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.model;
+
+import org.oic.simulator.server.Observer;
+
+/**
+ * This class holds observer details of resources.
+ */
+public class ObserverDetail {
+
+    private Observer observerInfo;
+    private boolean  isClicked;
+
+    public Observer getObserverInfo() {
+        return observerInfo;
+    }
+
+    public void setObserverInfo(Observer observerInfo) {
+        this.observerInfo = observerInfo;
+    }
+
+    public boolean isClicked() {
+        return isClicked;
+    }
+
+    public void setClicked(boolean isClicked) {
+        this.isClicked = isClicked;
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/Resource.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/Resource.java
new file mode 100644 (file)
index 0000000..31ae1b1
--- /dev/null
@@ -0,0 +1,188 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.model;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import org.oic.simulator.SimulatorResourceAttribute;
+import org.oic.simulator.SimulatorResourceModel;
+import org.oic.simulator.server.Observer;
+import org.oic.simulator.server.SimulatorResource;
+
+public abstract class Resource {
+
+    // Java SDK object reference
+    SimulatorResource                    simulatorResource;
+    private SimulatorResourceModel       resourceModel;
+    private ResourceRepresentation       mResourceRepresentation;
+
+    private String                       resourceURI;
+    private String                       resourceName;
+    private String                       resourceType;
+    private Set<String>                  resourceInterfaces;
+    private boolean                      started;
+    private boolean                      observable;
+    private boolean                      discoverable;
+
+    private Map<Integer, ObserverDetail> observers;
+
+    public Resource() {
+        resourceInterfaces = new HashSet<String>();
+        observers = new HashMap<Integer, ObserverDetail>();
+    }
+
+    public SimulatorResource getSimulatorResource() {
+        return simulatorResource;
+    }
+
+    public void setSimulatorResource(SimulatorResource simulatorResource) {
+        this.simulatorResource = simulatorResource;
+    }
+
+    public SimulatorResourceModel getResourceModel() {
+        return resourceModel;
+    }
+
+    public void setResourceModel(SimulatorResourceModel resourceModel) {
+        this.resourceModel = resourceModel;
+    }
+
+    public String getResourceURI() {
+        return resourceURI;
+    }
+
+    public void setResourceURI(String resourceURI) {
+        this.resourceURI = resourceURI;
+    }
+
+    public String getResourceName() {
+        return resourceName;
+    }
+
+    public void setResourceName(String resourceName) {
+        this.resourceName = resourceName;
+    }
+
+    public String getResourceType() {
+        return resourceType;
+    }
+
+    public void setResourceType(String resourceType) {
+        this.resourceType = resourceType;
+    }
+
+    public Set<String> getResourceInterfaces() {
+        if (null != resourceInterfaces) {
+            return new HashSet<String>(resourceInterfaces);
+        }
+        return null;
+    }
+
+    public void setResourceInterfaces(Set<String> resourceInterfaces) {
+        this.resourceInterfaces = resourceInterfaces;
+    }
+
+    public boolean isStarted() {
+        return started;
+    }
+
+    public void setStarted(boolean started) {
+        this.started = started;
+    }
+
+    public boolean isObservable() {
+        return observable;
+    }
+
+    public void setObservable(boolean observable) {
+        this.observable = observable;
+    }
+
+    public boolean isDiscoverable() {
+        return discoverable;
+    }
+
+    public void setDiscoverable(boolean discoverable) {
+        this.discoverable = discoverable;
+    }
+
+    public void addInterfaceType(String ifType) {
+        if (null == ifType) {
+            return;
+        }
+        if (null == resourceInterfaces) {
+            resourceInterfaces = new HashSet<String>();
+        }
+        resourceInterfaces.add(ifType);
+    }
+
+    public void removeInterfaceType(String ifType) {
+        if (null == ifType || null == resourceInterfaces) {
+            return;
+        }
+        resourceInterfaces.remove(ifType);
+    }
+
+    public boolean isInterfaceTypeExist(String ifType) {
+        if (null == ifType || null == resourceInterfaces) {
+            return false;
+        }
+        return resourceInterfaces.contains(ifType);
+    }
+
+    public Map<Integer, ObserverDetail> getObserver() {
+        return observers;
+    }
+
+    public void addObserverInfo(Observer observer) {
+        if (null == observer) {
+            return;
+        }
+        int id = observer.getId();
+        if (!observers.containsKey(id)) {
+            ObserverDetail obsDetail = new ObserverDetail();
+            obsDetail.setObserverInfo(observer);
+            observers.put(id, obsDetail);
+        }
+    }
+
+    public void removeObserverInfo(Observer observer) {
+        if (null == observer) {
+            return;
+        }
+        observers.remove(observer.getId());
+    }
+
+    public void createResourceRepresentation(
+            Map<String, SimulatorResourceAttribute> attributes)
+            throws NullPointerException {
+        if (mResourceRepresentation == null)
+            mResourceRepresentation = new ResourceRepresentation(attributes);
+    }
+
+    public void updateResourceRepresentation(SimulatorResourceModel model)
+            throws NullPointerException {
+        mResourceRepresentation.update(model);
+    }
+
+    public ResourceRepresentation getResourceRepresentation() {
+        return mResourceRepresentation;
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/ResourceRepresentation.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/ResourceRepresentation.java
new file mode 100644 (file)
index 0000000..1c75cf6
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.model;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.SimulatorResourceAttribute;
+import org.oic.simulator.SimulatorResourceModel;
+
+import oic.simulator.serviceprovider.manager.UiListenerHandler;
+
+public class ResourceRepresentation {
+    private Map<String, AttributeElement> mAttributes = new HashMap<String, AttributeElement>();
+
+    public ResourceRepresentation(
+            Map<String, SimulatorResourceAttribute> attributes)
+            throws NullPointerException {
+        if (attributes != null && attributes.size() > 0) {
+            for (Map.Entry<String, SimulatorResourceAttribute> entry : attributes
+                    .entrySet()) {
+                mAttributes.put(entry.getKey(), new AttributeElement(this,
+                        entry.getValue(), true));
+            }
+        }
+    }
+
+    public Map<String, AttributeElement> getAttributes() {
+        return mAttributes;
+    }
+
+    public void update(SimulatorResourceModel model) {
+        if (null == model)
+            return;
+
+        for (Map.Entry<String, AttributeValue> entry : model.get().entrySet()) {
+            AttributeElement attributeElement = mAttributes.get(entry.getKey());
+            if (null != attributeElement) {
+                if (!attributeElement.getEditLock())
+                    attributeElement.update(new SimulatorResourceAttribute(
+                            entry.getKey(), entry.getValue()));
+            } else {
+                // Display new attribute in UI
+                AttributeElement newAttribute = new AttributeElement(this,
+                        new SimulatorResourceAttribute(entry.getKey(),
+                                entry.getValue()), true);
+                mAttributes.put(entry.getKey(), newAttribute);
+
+                UiListenerHandler.getInstance().attributeAddedUINotification(
+                        newAttribute);
+            }
+        }
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/ResourceType.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/ResourceType.java
new file mode 100644 (file)
index 0000000..3d2de74
--- /dev/null
@@ -0,0 +1,21 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.model;
+
+public enum ResourceType {
+    SINGLE
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/SerializedServiceProvider.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/SerializedServiceProvider.java
new file mode 100644 (file)
index 0000000..777605f
--- /dev/null
@@ -0,0 +1,172 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.model;
+
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+import java.util.List;
+import java.util.Map;
+
+public class SerializedServiceProvider implements Serializable {
+
+    public static class SerializedAttribute implements Serializable {
+
+        public String getName() {
+            return m_name;
+        }
+
+        public void setName(String name) {
+            this.m_name = name;
+        }
+
+        public Object getValue() {
+            return m_value;
+        }
+
+        public void setValue(Object value) {
+            this.m_value = value;
+        }
+
+        public String getType() {
+            return m_type;
+        }
+
+        public void setType(String type) {
+            this.m_type = type;
+        }
+
+        public int getMin() {
+            return m_min;
+        }
+
+        public void setMin(int min) {
+            this.m_min = min;
+        }
+
+        public int getMax() {
+            return m_max;
+        }
+
+        public void setMax(int max) {
+            this.m_max = max;
+        }
+
+        public Object getAllowedValues() {
+            return m_AllowedValues;
+        }
+
+        public void setAllowedValues(Object allowedValues) {
+            this.m_AllowedValues = allowedValues;
+        }
+
+        private String m_name          = null;
+        private Object m_value         = null;
+        private String m_type          = null;
+        private int    m_min           = 0;
+        private int    m_max           = 0;
+        private Object m_AllowedValues = null;
+    }
+
+    public String getResourceName() {
+        return m_resourceName;
+    }
+
+    public void setResourceName(String resourceName) {
+        this.m_resourceName = resourceName;
+    }
+
+    public String getUri() {
+        return m_uri;
+    }
+
+    public void setUri(String uri) {
+        this.m_uri = uri;
+    }
+
+    public String getResourceType() {
+        return m_resourceType;
+    }
+
+    public void setResourceType(String resourceType) {
+        this.m_resourceType = resourceType;
+    }
+
+    public List<String> getInterfaceType() {
+        return m_interfaceType;
+    }
+
+    public void setInterfaceType(List<String> interfaceType) {
+        this.m_interfaceType = interfaceType;
+    }
+
+    public Map<String, SerializedAttribute> getResourceAttributesMap() {
+        return m_resourceAttributesMap;
+    }
+
+    public void setResourceAttributesMap(
+            Map<String, SerializedAttribute> resourceAttributesMap) {
+        this.m_resourceAttributesMap = resourceAttributesMap;
+    }
+
+    public void serialize(String filePath) throws FileNotFoundException,
+            IOException {
+        FileOutputStream fileOut = null;
+        ObjectOutputStream out = null;
+        try {
+            fileOut = new FileOutputStream(filePath);
+            out = new ObjectOutputStream(fileOut);
+            out.writeObject(this);
+        } finally {
+            if (null != fileOut)
+                fileOut.close();
+
+            if (null != out)
+                out.close();
+        }
+    }
+
+    public static SerializedServiceProvider deSerialize(String filePath)
+            throws FileNotFoundException, IOException, ClassNotFoundException {
+        FileInputStream fileIn = null;
+        ObjectInputStream in = null;
+        SerializedServiceProvider r;
+        try {
+            fileIn = new FileInputStream(filePath);
+            in = new ObjectInputStream(fileIn);
+            r = (SerializedServiceProvider) in.readObject();
+        } finally {
+            if (null != fileIn)
+                fileIn.close();
+
+            if (null != in)
+                in.close();
+        }
+        return r;
+    }
+
+    private String                           m_resourceName;
+    private String                           m_uri;
+    private String                           m_resourceType;
+    private List<String>                     m_interfaceType;
+    private Map<String, SerializedAttribute> m_resourceAttributesMap;
+
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/SingleResource.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/SingleResource.java
new file mode 100644 (file)
index 0000000..fcbbf3c
--- /dev/null
@@ -0,0 +1,107 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.model;
+
+import org.oic.simulator.server.SimulatorResource.AutoUpdateType;
+
+/**
+ * This class represents a simulated resource. It maintains all the necessary
+ * information about the resource.
+ */
+public class SingleResource extends Resource {
+    private boolean        getAllowed;
+
+    private boolean        putAllowed;
+
+    private boolean        postAllowed;
+
+    private int            automationId;
+
+    private boolean        resourceAutomationInProgress;
+
+    private boolean        attributeAutomationInProgress;
+
+    private int            automationUpdateInterval;
+
+    private AutoUpdateType automationType;
+
+    public boolean isGetAllowed() {
+        return getAllowed;
+    }
+
+    public void setGetAllowed(boolean getAllowed) {
+        this.getAllowed = getAllowed;
+    }
+
+    public boolean isPutAllowed() {
+        return putAllowed;
+    }
+
+    public void setPutAllowed(boolean putAllowed) {
+        this.putAllowed = putAllowed;
+    }
+
+    public boolean isPostAllowed() {
+        return postAllowed;
+    }
+
+    public void setPostAllowed(boolean postAllowed) {
+        this.postAllowed = postAllowed;
+    }
+
+    public int getAutomationUpdateInterval() {
+        return automationUpdateInterval;
+    }
+
+    public void setAutomationUpdateInterval(int automationUpdateInterval) {
+        this.automationUpdateInterval = automationUpdateInterval;
+    }
+
+    public AutoUpdateType getAutomationType() {
+        return automationType;
+    }
+
+    public void setAutomationType(AutoUpdateType automationType) {
+        this.automationType = automationType;
+    }
+
+    public int getAutomationId() {
+        return automationId;
+    }
+
+    public void setAutomationId(int automationId) {
+        this.automationId = automationId;
+    }
+
+    public boolean isResourceAutomationInProgress() {
+        return resourceAutomationInProgress;
+    }
+
+    public void setResourceAutomationInProgress(
+            boolean resourceAutomationInProgress) {
+        this.resourceAutomationInProgress = resourceAutomationInProgress;
+    }
+
+    public boolean isAttributeAutomationInProgress() {
+        return attributeAutomationInProgress;
+    }
+
+    public void setAttributeAutomationInProgress(
+            boolean attributeAutomationInProgress) {
+        this.attributeAutomationInProgress = attributeAutomationInProgress;
+    }
+}
\ No newline at end of file
index 079f645..323db9f 100644 (file)
 
 package oic.simulator.serviceprovider.perspective;
 
+import org.eclipse.ui.IFolderLayout;
+import org.eclipse.ui.IPageLayout;
+import org.eclipse.ui.IPerspectiveFactory;
+
 import oic.simulator.serviceprovider.view.AttributeView;
+import oic.simulator.serviceprovider.view.DevicePlatformInfoView;
 import oic.simulator.serviceprovider.view.LogView;
 import oic.simulator.serviceprovider.view.MetaPropertiesView;
-import oic.simulator.serviceprovider.view.MultiResourceOrchestrationView;
 import oic.simulator.serviceprovider.view.ResourceManagerView;
 import oic.simulator.serviceprovider.view.ResourceObserverView;
 
-import org.eclipse.ui.IFolderLayout;
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IPerspectiveFactory;
-
 /**
  * This class creates a new eclipse perspective for service provider and
  * positions the different views inside.
@@ -58,7 +58,7 @@ public class PerspectiveFactory implements IPerspectiveFactory {
                 factory.getEditorArea());
         factory.addView(LogView.VIEW_ID, IPageLayout.BOTTOM, 0.65f,
                 AttributeView.VIEW_ID);
-        factory.addView(MultiResourceOrchestrationView.VIEW_ID,
-                IPageLayout.RIGHT, 0.6f, AttributeView.VIEW_ID);
+        factory.addView(DevicePlatformInfoView.VIEW_ID, IPageLayout.RIGHT,
+                0.6f, AttributeView.VIEW_ID);
     }
 }
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/AutomationSettingHelper.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/AutomationSettingHelper.java
deleted file mode 100644 (file)
index 0136296..0000000
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * 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.
- */
-
-package oic.simulator.serviceprovider.resource;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import oic.simulator.serviceprovider.utils.Constants;
-
-import org.oic.simulator.serviceprovider.AutomationType;
-
-/**
- * This is a helper class for providing the automation settings information to
- * UI.
- */
-public class AutomationSettingHelper {
-    private String       settingID;
-    private String       settingValue;
-    private List<String> allowedValues;
-
-    public String getSettingID() {
-        return settingID;
-    }
-
-    public void setSettingID(String settingID) {
-        this.settingID = settingID;
-    }
-
-    public String getSettingValue() {
-        return settingValue;
-    }
-
-    public void setSettingValue(String settingValue) {
-        this.settingValue = settingValue;
-    }
-
-    public List<String> getAllowedValues() {
-        return allowedValues;
-    }
-
-    public void setAllowedValues(List<String> allowedValues) {
-        this.allowedValues = allowedValues;
-    }
-
-    public void addAllowedValue(String newText) {
-        if (null != allowedValues) {
-            allowedValues.add(newText);
-        }
-    }
-
-    public static List<AutomationSettingHelper> getAutomationSettings(
-            LocalResourceAttribute attribute) {
-        List<AutomationSettingHelper> settingList = null;
-        boolean invalidSetting;
-        if (null != attribute) {
-            settingList = new ArrayList<AutomationSettingHelper>();
-            for (int count = 0; count < Constants.AUTOMATION_SETTINGS_COUNT; count++) {
-                invalidSetting = false;
-                AutomationSettingHelper setting = new AutomationSettingHelper();
-                if (Constants.AUTOMATION_SETTINGS[count]
-                        .equals(Constants.AUTOMATION_TYPE)) {
-                    setting.setSettingID(Constants.AUTOMATION_TYPE);
-                    setting.setSettingValue(attribute.getAutomationType()
-                            .toString());
-                    List<String> valueList = new ArrayList<String>();
-                    valueList.add(AutomationType.NORMAL.toString());
-                    valueList.add(AutomationType.RECURRENT.toString());
-                    setting.setAllowedValues(valueList);
-                } else if (Constants.AUTOMATION_SETTINGS[count]
-                        .equals(Constants.UPDATE_INTERVAL_IN_MS)) {
-                    setting.setSettingID(Constants.UPDATE_INTERVAL_IN_MS);
-                    setting.setSettingValue(String.valueOf(attribute
-                            .getAutomationUpdateInterval()));
-                    List<String> valueList = new ArrayList<String>();
-                    for (int index = 1; index <= 10; index++) {
-                        valueList.add(String.valueOf(index * 500));
-                    }
-                    setting.setAllowedValues(valueList);
-                } else {
-                    invalidSetting = true;
-                }
-                if (!invalidSetting) {
-                    settingList.add(setting);
-                }
-            }
-        }
-        return settingList;
-    }
-
-    public static void updateAutomationStatus(
-            List<AutomationSettingHelper> localSettingList, String status) {
-        if (null != localSettingList && null != status) {
-            Iterator<AutomationSettingHelper> settingItr = localSettingList
-                    .iterator();
-            AutomationSettingHelper setting;
-            while (settingItr.hasNext()) {
-                setting = settingItr.next();
-                if (null != setting) {
-                    if (setting.getSettingID().equals(Constants.AUTOMATION)) {
-                        setting.setSettingValue(status);
-                        break;
-                    }
-                }
-            }
-        }
-    }
-}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/DeleteCategory.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/DeleteCategory.java
deleted file mode 100644 (file)
index 336d82d..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * 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.
- */
-
-package oic.simulator.serviceprovider.resource;
-
-/**
- * Enumerates different types of supported delete operations.
- */
-public enum DeleteCategory {
-    ALL, BY_TYPE, BY_URI, NONE
-}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/LocalResourceAttribute.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/LocalResourceAttribute.java
deleted file mode 100644 (file)
index c04b07e..0000000
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * 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.
- */
-
-package oic.simulator.serviceprovider.resource;
-
-import java.util.List;
-
-import org.oic.simulator.ResourceAttribute;
-import org.oic.simulator.ResourceAttribute.Range;
-import org.oic.simulator.ResourceAttribute.Type;
-import org.oic.simulator.serviceprovider.AutomationType;
-
-/**
- * This class represents an attribute in the simulated resource.
- */
-public class LocalResourceAttribute {
-
-    // Native object reference
-    private ResourceAttribute resourceAttribute;
-
-    private Object            attributeValue;
-    private List<String>      attValues;
-
-    private int               automationId;
-
-    private boolean           automationInProgress;
-
-    private int               automationUpdateInterval;
-
-    private AutomationType    automationType;
-
-    public ResourceAttribute getResourceAttribute() {
-        return resourceAttribute;
-    }
-
-    public void setResourceAttribute(ResourceAttribute resourceAttribute) {
-        this.resourceAttribute = resourceAttribute;
-    }
-
-    public String getAttributeName() {
-        return resourceAttribute.getName();
-    }
-
-    public Object getAttributeValue() {
-        return attributeValue;
-    }
-
-    public void setAttributeValue(Object attributeValue) {
-        this.attributeValue = attributeValue;
-    }
-
-    public Object[] getAllowedValues() {
-        return resourceAttribute.getAllowedValues();
-    }
-
-    public Object getMinValue() {
-        return resourceAttribute.getRange().getMin();
-    }
-
-    public Object getMaxValue() {
-        return resourceAttribute.getRange().getMax();
-    }
-
-    public boolean isAutomationInProgress() {
-        return automationInProgress;
-    }
-
-    public void setAutomationInProgress(boolean automationInProgress) {
-        this.automationInProgress = automationInProgress;
-    }
-
-    public int getAutomationUpdateInterval() {
-        return automationUpdateInterval;
-    }
-
-    public void setAutomationUpdateInterval(int automationUpdateInterval) {
-        this.automationUpdateInterval = automationUpdateInterval;
-    }
-
-    public AutomationType getAutomationType() {
-        return automationType;
-    }
-
-    public void setAutomationType(AutomationType automationType) {
-        this.automationType = automationType;
-    }
-
-    public int getAutomationId() {
-        return automationId;
-    }
-
-    public void setAutomationId(int automationId) {
-        this.automationId = automationId;
-    }
-
-    public Type getAttValType() {
-        return resourceAttribute.getType();
-    }
-
-    public Type getAttValBaseType() {
-        return resourceAttribute.getBaseType();
-    }
-
-    public List<String> getAttValues() {
-        return attValues;
-    }
-
-    public void setAttValues(List<String> attValues) {
-        this.attValues = attValues;
-    }
-
-    public void printAttributeDetails() {
-        System.out.println("Attribute Name:" + resourceAttribute.getName());
-        System.out.println("Attribute Value:" + resourceAttribute.getValue());
-        System.out.println("Attribute Base Type:"
-                + resourceAttribute.getBaseType());
-        System.out.println("Attribute Type:" + resourceAttribute.getType());
-        System.out.print("Allowed Values:");
-        Object[] values = getAllowedValues();
-        for (Object obj : values) {
-            System.out.print(obj);
-        }
-        Range range = resourceAttribute.getRange();
-        if (null != range) {
-            System.out.println("Range:" + range.getMin() + " to "
-                    + range.getMax());
-        }
-    }
-}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/MetaProperty.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/MetaProperty.java
deleted file mode 100644 (file)
index 61881b1..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * 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.
- */
-
-package oic.simulator.serviceprovider.resource;
-
-/**
- * This is a helper class for showing the meta properties of resources such as
- * resource type, resource uri, etc.
- */
-public class MetaProperty {
-    private String propName;
-    private String propValue;
-
-    public MetaProperty(String propName, String propValue) {
-        this.propName = propName;
-        this.propValue = propValue;
-    }
-
-    public String getPropValue() {
-        return propValue;
-    }
-
-    public void setPropValue(String propValue) {
-        this.propValue = propValue;
-    }
-
-    public String getPropName() {
-        return propName;
-    }
-
-    public void setPropName(String propName) {
-        this.propName = propName;
-    }
-}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/ModelChangeNotificationType.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/ModelChangeNotificationType.java
deleted file mode 100644 (file)
index 0a1b17a..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * 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.
- */
-
-package oic.simulator.serviceprovider.resource;
-
-/**
- * Enumerates the different types of operations for model change notifications.
- */
-public enum ModelChangeNotificationType {
-    ATTRIBUTE_ADDED, ATTRIBUTE_REMOVED, ATTRIBUTE_VALUE_CHANGED, NONE, NO_ATTRIBUTES_IN_MODEL
-}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/ObserverDetail.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/ObserverDetail.java
deleted file mode 100644 (file)
index b581a6e..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * 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.
- */
-
-package oic.simulator.serviceprovider.resource;
-
-import org.oic.simulator.serviceprovider.ObserverInfo;
-
-/**
- * This class holds observer details of resources.
- */
-public class ObserverDetail {
-
-    private ObserverInfo observerInfo;
-    private boolean      isClicked;
-
-    public ObserverInfo getObserverInfo() {
-        return observerInfo;
-    }
-
-    public void setObserverInfo(ObserverInfo observerInfo) {
-        this.observerInfo = observerInfo;
-    }
-
-    public boolean isClicked() {
-        return isClicked;
-    }
-
-    public void setClicked(boolean isClicked) {
-        this.isClicked = isClicked;
-    }
-}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/SimulatorResource.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/SimulatorResource.java
deleted file mode 100644 (file)
index 38d9730..0000000
+++ /dev/null
@@ -1,205 +0,0 @@
-/*
- * 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.
- */
-
-package oic.simulator.serviceprovider.resource;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.oic.simulator.SimulatorResourceModel;
-import org.oic.simulator.serviceprovider.AutomationType;
-import org.oic.simulator.serviceprovider.ObserverInfo;
-import org.oic.simulator.serviceprovider.SimulatorResourceServer;
-
-/**
- * This class represents a simulated resource. It maintains all the necessary
- * information about the resource.
- */
-public class SimulatorResource {
-    private String                              resourceURI;
-    private String                              resourceName;
-    private String                              resourceType;
-    private String                              resourceInterface;
-
-    // Native Object references
-    private SimulatorResourceServer             resourceServer;
-    private SimulatorResourceModel              resourceModel;
-
-    private int                                 automationId;
-
-    private boolean                             resourceAutomationInProgress;
-
-    private boolean                             attributeAutomationInProgress;
-
-    private int                                 automationUpdateInterval;
-
-    private AutomationType                      automationType;
-
-    private Map<String, LocalResourceAttribute> resourceAttributesMap;
-
-    private Map<Integer, ObserverDetail>        observers;
-
-    public SimulatorResource() {
-        observers = new HashMap<Integer, ObserverDetail>();
-    }
-
-    public String getResourceURI() {
-        return resourceURI;
-    }
-
-    public void setResourceURI(String resourceURI) {
-        this.resourceURI = resourceURI;
-    }
-
-    public String getResourceName() {
-        return resourceName;
-    }
-
-    public void setResourceName(String resourceName) {
-        this.resourceName = resourceName;
-    }
-
-    public String getResourceType() {
-        return resourceType;
-    }
-
-    public void setResourceType(String resourceType) {
-        this.resourceType = resourceType;
-    }
-
-    public String getResourceInterface() {
-        return resourceInterface;
-    }
-
-    public void setResourceInterface(String resourceInterface) {
-        this.resourceInterface = resourceInterface;
-    }
-
-    public SimulatorResourceServer getResourceServer() {
-        return resourceServer;
-    }
-
-    public void setResourceServer(SimulatorResourceServer resourceServer) {
-        this.resourceServer = resourceServer;
-    }
-
-    public SimulatorResourceModel getResourceModel() {
-        return resourceModel;
-    }
-
-    public void setResourceModel(SimulatorResourceModel resourceModel) {
-        this.resourceModel = resourceModel;
-    }
-
-    public Map<String, LocalResourceAttribute> getResourceAttributesMap() {
-        return resourceAttributesMap;
-    }
-
-    public void setResourceAttributesMap(
-            Map<String, LocalResourceAttribute> resourceAttributesMap) {
-        this.resourceAttributesMap = resourceAttributesMap;
-    }
-
-    public int getAutomationUpdateInterval() {
-        return automationUpdateInterval;
-    }
-
-    public void setAutomationUpdateInterval(int automationUpdateInterval) {
-        this.automationUpdateInterval = automationUpdateInterval;
-    }
-
-    public AutomationType getAutomationType() {
-        return automationType;
-    }
-
-    public void setAutomationType(AutomationType automationType) {
-        this.automationType = automationType;
-    }
-
-    public int getAutomationId() {
-        return automationId;
-    }
-
-    public void setAutomationId(int automationId) {
-        this.automationId = automationId;
-    }
-
-    public boolean isResourceAutomationInProgress() {
-        return resourceAutomationInProgress;
-    }
-
-    public void setResourceAutomationInProgress(
-            boolean resourceAutomationInProgress) {
-        this.resourceAutomationInProgress = resourceAutomationInProgress;
-    }
-
-    public boolean isAttributeAutomationInProgress() {
-        return attributeAutomationInProgress;
-    }
-
-    public void setAttributeAutomationInProgress(
-            boolean attributeAutomationInProgress) {
-        this.attributeAutomationInProgress = attributeAutomationInProgress;
-    }
-
-    public Map<Integer, ObserverDetail> getObserver() {
-        return observers;
-    }
-
-    public void addObserverInfo(ObserverInfo observer) {
-        if (null == observer) {
-            return;
-        }
-        int id = observer.getId();
-        if (!observers.containsKey(id)) {
-            ObserverDetail obsDetail = new ObserverDetail();
-            obsDetail.setObserverInfo(observer);
-            observers.put(id, obsDetail);
-        }
-    }
-
-    public void removeObserverInfo(ObserverInfo observer) {
-        if (null == observer) {
-            return;
-        }
-        observers.remove(observer.getId());
-    }
-
-    public void printResourceInfo() {
-        System.out.println("Resource URI: " + resourceURI);
-        System.out.println("Resource Name: " + resourceName);
-        System.out.println("Resource type: " + resourceType);
-        System.out.println("Resource Interface: " + resourceInterface);
-        System.out.println("Resource Attributes:-");
-        if (null != resourceAttributesMap) {
-            Iterator<String> attItr = resourceAttributesMap.keySet().iterator();
-            while (attItr.hasNext()) {
-                resourceAttributesMap.get(attItr.next())
-                        .printAttributeDetails();;
-            }
-        }
-    }
-
-    public LocalResourceAttribute getAttribute(String attributeName) {
-        if (null == attributeName || null == resourceAttributesMap
-                || resourceAttributesMap.size() < 1) {
-            return null;
-        }
-        return resourceAttributesMap.get(attributeName);
-    }
-
-}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/StandardConfiguration.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/StandardConfiguration.java
deleted file mode 100644 (file)
index 4a3035c..0000000
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * 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.
- */
-
-package oic.simulator.serviceprovider.resource;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.util.Date;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Map;
-
-import oic.simulator.serviceprovider.Activator;
-import oic.simulator.serviceprovider.utils.Constants;
-
-import org.eclipse.core.runtime.FileLocator;
-import org.oic.simulator.ILogger.Level;
-
-/**
- * Class which loads and maintains the standard RAML configuration file list.
- */
-public class StandardConfiguration {
-
-    // A map of filename of standard resources as the key and the complete
-    // location of the file(including the filename) as the value.
-    Map<String, String> stdConfigFiles;
-
-    public StandardConfiguration() {
-        stdConfigFiles = new HashMap<String, String>();
-        populateStandardConfigurationList();
-    }
-
-    private void populateStandardConfigurationList() {
-        Enumeration<URL> fileList = Activator.getDefault().getBundle()
-                .findEntries(Constants.CONFIG_DIRECTORY_PATH, "*", true);
-        if (null == fileList) {
-            Activator
-                    .getDefault()
-                    .getLogManager()
-                    .log(Level.ERROR.ordinal(), new Date(),
-                            "No configuration files exist.");
-            return;
-        }
-        URL url;
-        URL resolvedURL;
-        URI resolvedURI;
-        File file;
-        String relPath;
-        String absPath;
-        while (fileList.hasMoreElements()) {
-            url = (URL) fileList.nextElement();
-            relPath = url.getPath();
-            System.out.println(url.getPath());
-            try {
-                resolvedURL = FileLocator.toFileURL(url);
-                if (relPath.toLowerCase().endsWith(
-                        Constants.RAML_FILE_EXTENSION)) {
-                    resolvedURI = new URI(resolvedURL.getProtocol(),
-                            resolvedURL.getPath(), null);
-                    file = new File(resolvedURI);
-                    absPath = file.getAbsolutePath();
-                    stdConfigFiles.put(relPath, absPath);
-                    System.out.println("File path:" + absPath);
-                }
-            } catch (URISyntaxException | IOException e) {
-                Activator.getDefault().getLogManager()
-                        .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
-            }
-        }
-    }
-
-    public Map<String, String> getStandardResourceConfigurationList() {
-        return stdConfigFiles;
-    }
-
-    public void setStandardResourceConfigurationList(
-            Map<String, String> stdConfigFiles) {
-        this.stdConfigFiles = stdConfigFiles;
-    }
-
-    public String getFilePath(String fileName) {
-        return stdConfigFiles.get(fileName);
-    }
-}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/AttributeValueBuilder.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/AttributeValueBuilder.java
new file mode 100644 (file)
index 0000000..4c640e3
--- /dev/null
@@ -0,0 +1,349 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.utils;
+
+import java.util.Vector;
+
+import org.oic.simulator.AttributeValue;
+
+public class AttributeValueBuilder {
+    public static AttributeValue build(String valueString,
+            AttributeValue.ValueType valueType) throws NullPointerException {
+        int depth = findDepth(valueString);
+        if (0 == depth) {
+            return handleDepth0(valueString, valueType);
+        } else if (1 == depth) {
+            return handleDepth1(valueString, valueType);
+        } else if (2 == depth) {
+            return handleDepth2(valueString, valueType);
+        } else if (3 == depth) {
+            return handleDepth3(valueString, valueType);
+        }
+
+        return null;
+    }
+
+    private static int findDepth(String value) {
+        int depth = 0;
+        for (char ch : value.toCharArray()) {
+            if (ch == '[')
+                depth++;
+            else
+                break;
+        }
+
+        return depth;
+    }
+
+    private static boolean isValidSyntax(String value) {
+        int count = 0;
+        for (char ch : value.toCharArray()) {
+            if (ch == '[')
+                count++;
+            if (ch == ']')
+                count--;
+        }
+
+        if (count == 0)
+            return true;
+        return false;
+
+    }
+
+    private static AttributeValue handleDepth0(String valueString,
+            AttributeValue.ValueType valueType) {
+        valueString = valueString.trim();
+        if (0 != findDepth(valueString))
+            return null;
+
+        try {
+            if (valueType == AttributeValue.ValueType.INTEGER)
+                return new AttributeValue(Integer.parseInt(valueString));
+            else if (valueType == AttributeValue.ValueType.DOUBLE) {
+                Double value = Double.parseDouble(valueString);
+                if (!value.isInfinite()) {
+                    return new AttributeValue(value);
+                }
+            } else if (valueType == AttributeValue.ValueType.BOOLEAN) {
+                if (valueString.equalsIgnoreCase("true")
+                        || valueString.equalsIgnoreCase("false"))
+                    return new AttributeValue(Boolean.parseBoolean(valueString));
+            } else if (valueType == AttributeValue.ValueType.STRING)
+                return new AttributeValue(valueString);
+        } catch (Exception e) {
+            return null;
+        }
+        return null;
+    }
+
+    private static String[] splitIntoArrays(String valueString) {
+        Vector<String> values = new Vector<String>();
+        valueString = valueString.substring(valueString.indexOf('[') + 1,
+                valueString.lastIndexOf(']'));
+
+        int count = 0;
+        int startPos = 0;
+        char[] charArray = valueString.toCharArray();
+        for (int index = 0; index < charArray.length; index++) {
+            if (charArray[index] == '[' && 0 == count++) {
+                startPos = index;
+            }
+
+            if (charArray[index] == ']' && 0 == --count) {
+                values.add(valueString.substring(startPos, index + 1));
+            }
+        }
+
+        String[] result = new String[values.size()];
+        values.toArray(result);
+        return result;
+    }
+
+    private static AttributeValue handleDepth1(String valueString,
+            AttributeValue.ValueType valueType) {
+        valueString = valueString.trim();
+        if (1 != findDepth(valueString) || false == isValidSyntax(valueString))
+            return null;
+
+        valueString = valueString.substring(valueString.indexOf('[') + 1,
+                valueString.lastIndexOf(']'));
+        String[] valuesString = valueString.split(",");
+        if (null == valuesString || 0 == valuesString.length)
+            return null;
+
+        if (valueType == AttributeValue.ValueType.INTEGER) {
+            if (1 == valuesString.length && valuesString[0].isEmpty()) {
+                return new AttributeValue(new Integer[0]);
+            }
+
+            Integer[] result = new Integer[valuesString.length];
+            for (int index = 0; index < valuesString.length; index++) {
+                if (null != valuesString[index]
+                        && !valuesString[index].isEmpty()) {
+                    AttributeValue attValue = handleDepth0(valuesString[index],
+                            valueType);
+                    if (null == attValue)
+                        return null;
+
+                    Integer value = (Integer) attValue.get();
+                    if (null == value)
+                        return null;
+                    result[index] = value;
+                }
+            }
+            return new AttributeValue(result);
+        } else if (valueType == AttributeValue.ValueType.DOUBLE) {
+            if (1 == valuesString.length && valuesString[0].isEmpty()) {
+                return new AttributeValue(new Double[0]);
+            }
+
+            Double[] result = new Double[valuesString.length];
+            for (int index = 0; index < valuesString.length; index++) {
+                if (null != valuesString[index]
+                        && !valuesString[index].isEmpty()) {
+                    AttributeValue attValue = handleDepth0(valuesString[index],
+                            valueType);
+                    if (null == attValue)
+                        return null;
+
+                    Double value = (Double) attValue.get();
+                    if (null == value)
+                        return null;
+                    result[index] = value;
+                }
+            }
+            return new AttributeValue(result);
+        } else if (valueType == AttributeValue.ValueType.BOOLEAN) {
+            if (1 == valuesString.length && valuesString[0].isEmpty()) {
+                return new AttributeValue(new Boolean[0]);
+            }
+
+            Boolean[] result = new Boolean[valuesString.length];
+            for (int index = 0; index < valuesString.length; index++) {
+                if (null != valuesString[index]
+                        && !valuesString[index].isEmpty()) {
+                    AttributeValue attValue = handleDepth0(valuesString[index],
+                            valueType);
+                    if (null == attValue)
+                        return null;
+
+                    Boolean value = (Boolean) attValue.get();
+                    if (null == value)
+                        return null;
+                    result[index] = value;
+                }
+            }
+            return new AttributeValue(result);
+        } else if (valueType == AttributeValue.ValueType.STRING) {
+            if (1 == valuesString.length && valuesString[0].isEmpty()) {
+                return new AttributeValue(new String[0]);
+            }
+
+            for (int index = 0; index < valuesString.length; index++) {
+                if (null != valuesString[index]
+                        && !valuesString[index].isEmpty()) {
+                    valuesString[index] = valuesString[index].trim();
+                }
+            }
+            return new AttributeValue(valuesString);
+        }
+
+        return null;
+    }
+
+    private static AttributeValue handleDepth2(String valueString,
+            AttributeValue.ValueType valueType) {
+        valueString = valueString.trim();
+        if (2 != findDepth(valueString) || false == isValidSyntax(valueString))
+            return null;
+
+        String[] valuesString = splitIntoArrays(valueString);
+        if (null == valuesString || 0 == valuesString.length)
+            return null;
+
+        if (valueType == AttributeValue.ValueType.INTEGER) {
+            Integer[][] result = new Integer[valuesString.length][];
+            for (int index = 0; index < valuesString.length; index++) {
+                AttributeValue attValue = handleDepth1(valuesString[index],
+                        valueType);
+                if (null == attValue)
+                    return null;
+
+                Integer[] value = (Integer[]) attValue.get();
+                if (null == value)
+                    return null;
+                result[index] = value;
+            }
+            return new AttributeValue(result);
+        } else if (valueType == AttributeValue.ValueType.DOUBLE) {
+            Double[][] result = new Double[valuesString.length][];
+            for (int index = 0; index < valuesString.length; index++) {
+                AttributeValue attValue = handleDepth1(valuesString[index],
+                        valueType);
+                if (null == attValue)
+                    return null;
+
+                Double[] value = (Double[]) attValue.get();
+                if (null == value)
+                    return null;
+                result[index] = value;
+            }
+            return new AttributeValue(result);
+        } else if (valueType == AttributeValue.ValueType.BOOLEAN) {
+            Boolean[][] result = new Boolean[valuesString.length][];
+            for (int index = 0; index < valuesString.length; index++) {
+                AttributeValue attValue = handleDepth1(valuesString[index],
+                        valueType);
+                if (null == attValue)
+                    return null;
+
+                Boolean[] value = (Boolean[]) attValue.get();
+                if (null == value)
+                    return null;
+                result[index] = value;
+            }
+            return new AttributeValue(result);
+        } else if (valueType == AttributeValue.ValueType.STRING) {
+            String[][] result = new String[valuesString.length][];
+            for (int index = 0; index < valuesString.length; index++) {
+                AttributeValue attValue = handleDepth1(valuesString[index],
+                        valueType);
+                if (null == attValue)
+                    return null;
+
+                String[] value = (String[]) attValue.get();
+                if (null == value)
+                    return null;
+                result[index] = value;
+            }
+            return new AttributeValue(result);
+        }
+
+        return null;
+    }
+
+    public static AttributeValue handleDepth3(String valueString,
+            AttributeValue.ValueType valueType) {
+        valueString = valueString.trim();
+        if (3 != findDepth(valueString) || false == isValidSyntax(valueString))
+            return null;
+
+        String[] valuesString = splitIntoArrays(valueString);
+        if (null == valuesString || 0 == valuesString.length)
+            return null;
+
+        if (valueType == AttributeValue.ValueType.INTEGER) {
+            Integer[][][] result = new Integer[valuesString.length][][];
+            for (int index = 0; index < valuesString.length; index++) {
+                AttributeValue attValue = handleDepth2(valuesString[index],
+                        valueType);
+                if (null == attValue)
+                    return null;
+
+                Integer[][] value = (Integer[][]) attValue.get();
+                if (null == value)
+                    return null;
+                result[index] = value;
+            }
+            return new AttributeValue(result);
+        } else if (valueType == AttributeValue.ValueType.DOUBLE) {
+            Double[][][] result = new Double[valuesString.length][][];
+            for (int index = 0; index < valuesString.length; index++) {
+                AttributeValue attValue = handleDepth2(valuesString[index],
+                        valueType);
+                if (null == attValue)
+                    return null;
+
+                Double[][] value = (Double[][]) attValue.get();
+                if (null == value)
+                    return null;
+                result[index] = value;
+            }
+            return new AttributeValue(result);
+        } else if (valueType == AttributeValue.ValueType.BOOLEAN) {
+            Boolean[][][] result = new Boolean[valuesString.length][][];
+            for (int index = 0; index < valuesString.length; index++) {
+                AttributeValue attValue = handleDepth2(valuesString[index],
+                        valueType);
+                if (null == attValue)
+                    return null;
+
+                Boolean[][] value = (Boolean[][]) attValue.get();
+                if (null == value)
+                    return null;
+                result[index] = value;
+            }
+            return new AttributeValue(result);
+        } else if (valueType == AttributeValue.ValueType.STRING) {
+            String[][][] result = new String[valuesString.length][][];
+            for (int index = 0; index < valuesString.length; index++) {
+                AttributeValue attValue = handleDepth2(valuesString[index],
+                        valueType);
+                if (null == attValue)
+                    return null;
+
+                String[][] value = (String[][]) attValue.get();
+                if (null == value)
+                    return null;
+                result[index] = value;
+            }
+            return new AttributeValue(result);
+        }
+
+        return null;
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/AttributeValueStringConverter.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/AttributeValueStringConverter.java
new file mode 100644 (file)
index 0000000..54bff47
--- /dev/null
@@ -0,0 +1,341 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.utils;
+
+import java.util.Map;
+
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.AttributeValueVisitor;
+import org.oic.simulator.SimulatorResourceModel;
+
+public class AttributeValueStringConverter implements
+        AttributeValueVisitor.VisitingMethods<String> {
+
+    private AttributeValue mValue;
+
+    public AttributeValueStringConverter(AttributeValue value) {
+        mValue = value;
+    }
+
+    @Override
+    public String toString() {
+        AttributeValueVisitor visitor = new AttributeValueVisitor(mValue, this);
+        return (String) visitor.visit();
+    }
+
+    @Override
+    public String visitingValue(Integer value) {
+        return value.toString();
+    }
+
+    @Override
+    public String visitingValue(Double value) {
+        return value.toString();
+    }
+
+    @Override
+    public String visitingValue(Boolean value) {
+        return value.toString();
+    }
+
+    @Override
+    public String visitingValue(String value) {
+        return value;
+    }
+
+    @Override
+    public String visitingValue(SimulatorResourceModel value) {
+        StringBuilder result = new StringBuilder();
+        result.append("{");
+        boolean first = true;
+        for (Map.Entry<String, AttributeValue> entry : value.get().entrySet()) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            result.append("\"" + entry.getKey() + "\":");
+            AttributeValue attributeValue = entry.getValue();
+            result.append(new AttributeValueStringConverter(attributeValue)
+                    .toString());
+        }
+
+        result.append("}");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(Integer[] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (Integer value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            result.append(value.toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(Double[] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (Double value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            result.append(value.toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(Boolean[] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (Boolean value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            result.append(value.toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(String[] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (String value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            result.append(value);
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(SimulatorResourceModel[] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (SimulatorResourceModel value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            AttributeValue attributeValue = new AttributeValue(value);
+            result.append(new AttributeValueStringConverter(attributeValue)
+                    .toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(Integer[][] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (Integer[] value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            AttributeValue attributeValue = new AttributeValue(value);
+            result.append(new AttributeValueStringConverter(attributeValue)
+                    .toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(Double[][] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (Double[] value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            AttributeValue attributeValue = new AttributeValue(value);
+            result.append(new AttributeValueStringConverter(attributeValue)
+                    .toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(Boolean[][] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (Boolean[] value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            AttributeValue attributeValue = new AttributeValue(value);
+            result.append(new AttributeValueStringConverter(attributeValue)
+                    .toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(String[][] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (String[] value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            AttributeValue attributeValue = new AttributeValue(value);
+            result.append(new AttributeValueStringConverter(attributeValue)
+                    .toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(SimulatorResourceModel[][] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (SimulatorResourceModel[] value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            AttributeValue attributeValue = new AttributeValue(value);
+            result.append(new AttributeValueStringConverter(attributeValue)
+                    .toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(Integer[][][] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (Integer[][] value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            AttributeValue attributeValue = new AttributeValue(value);
+            result.append(new AttributeValueStringConverter(attributeValue)
+                    .toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(Double[][][] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (Double[][] value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            AttributeValue attributeValue = new AttributeValue(value);
+            result.append(new AttributeValueStringConverter(attributeValue)
+                    .toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(Boolean[][][] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (Boolean[][] value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            AttributeValue attributeValue = new AttributeValue(value);
+            result.append(new AttributeValueStringConverter(attributeValue)
+                    .toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(String[][][] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (String[][] value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            AttributeValue attributeValue = new AttributeValue(value);
+            result.append(new AttributeValueStringConverter(attributeValue)
+                    .toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+    @Override
+    public String visitingValue(SimulatorResourceModel[][][] values) {
+        StringBuilder result = new StringBuilder();
+        result.append("[");
+        boolean first = true;
+        for (SimulatorResourceModel[][] value : values) {
+            if (!first)
+                result.append(", ");
+            first = false;
+            AttributeValue attributeValue = new AttributeValue(value);
+            result.append(new AttributeValueStringConverter(attributeValue)
+                    .toString());
+        }
+
+        result.append("]");
+        return result.toString();
+    }
+
+}
index 09fecfc..5dcf743 100644 (file)
@@ -16,7 +16,7 @@
 
 package oic.simulator.serviceprovider.utils;
 
-import org.oic.simulator.serviceprovider.AutomationType;
+import org.oic.simulator.server.SimulatorResource.AutoUpdateType;
 
 /**
  * This class maintains all constants which are used throughout the service
@@ -24,84 +24,166 @@ import org.oic.simulator.serviceprovider.AutomationType;
  */
 public class Constants {
 
-    public static final String         CONFIG_DIRECTORY_PATH            = "/resource";
+    public static final String         INT                                        = "Int";
+    public static final String         DOUBLE                                     = "Double";
+    public static final String         BOOL                                       = "Boolean";
+    public static final String         STRING                                     = "String";
+    public static final String         UNKNOWN                                    = "Unknown";
 
-    public static final String         UNDERSCORE                       = "_";
-    public static final String         FORWARD_SLASH                    = "/";
+    public static final String         CONFIG_DIRECTORY_PATH                      = "/resource";
 
-    public static final String         OIC_PREFIX                       = "/oic/r";
-    public static final String         SIMULATOR                        = "simulator";
+    public static final String         UNDERSCORE                                 = "_";
+    public static final String         FORWARD_SLASH                              = "/";
 
-    public static final String         RESOURCE_URI                     = "Resource URI";
-    public static final String         RESOURCE_TYPE                    = "Resource Type";
-    public static final String         RESOURCE_UID                     = "Resource ID";
-    public static final String         CONNECTIVITY_TYPE                = "Connectivity Type";
+    public static final String         OIC_PREFIX                                 = "/oic/r";
+    public static final String         SIMULATOR                                  = "simulator";
 
-    public static final String[]       META_PROPERTIES                  = {
-            RESOURCE_URI, RESOURCE_TYPE, CONNECTIVITY_TYPE             };
+    public static final String         RESOURCE_URI                               = "Resource URI";
+    public static final String         RESOURCE_TYPE                              = "Resource Type";
+    public static final String         RESOURCE_TYPES                             = "Resource Types";
+    public static final String         RESOURCE_NAME                              = "Resource Name";
+    public static final String         RESOURCE_UID                               = "Resource ID";
+    public static final String         CONNECTIVITY_TYPE                          = "Connectivity Type";
+    public static final String         INTERFACE_TYPES                            = "Interface Types";
 
-    public static final int            META_PROPERTY_COUNT              = META_PROPERTIES.length;
+    public static final String[]       META_PROPERTIES                            = {
+            RESOURCE_NAME, RESOURCE_URI, RESOURCE_TYPE, INTERFACE_TYPES          };
 
-    public static final String         ENABLE                           = "Enable";
-    public static final String         DISABLE                          = "Disable";
-    public static final String         ENABLED                          = "Enabled";
-    public static final String         DISABLED                         = "Disabled";
+    public static final int            META_PROPERTY_COUNT                        = META_PROPERTIES.length;
 
-    public static final String         AUTOMATION                       = "Automation";
-    public static final String         AUTOMATION_TYPE                  = "Automation Type";
-    public static final String         UPDATE_INTERVAL_IN_MS            = "Update Interval(ms)";
+    public static final String         ENABLE                                     = "Enable";
+    public static final String         DISABLE                                    = "Disable";
+    public static final String         ENABLED                                    = "Enabled";
+    public static final String         DISABLED                                   = "Disabled";
 
-    public static final String[]       AUTOMATION_SETTINGS              = {
-            AUTOMATION_TYPE, UPDATE_INTERVAL_IN_MS                     };
+    public static final String         AUTOMATION                                 = "Automation";
+    public static final String         AUTOMATION_TYPE                            = "Automation Type";
+    public static final String         UPDATE_INTERVAL_IN_MS                      = "Update Interval(ms)";
 
-    public static final int            AUTOMATION_SETTINGS_COUNT        = AUTOMATION_SETTINGS.length;
+    public static final String[]       AUTOMATION_SETTINGS                        = {
+            AUTOMATION_TYPE, UPDATE_INTERVAL_IN_MS                               };
 
-    public static final String         START_RESOURCE_AUTOMATION        = "Start Automation";
-    public static final String         STOP_RESOURCE_AUTOMATION         = "Stop Automation";
+    public static final int            AUTOMATION_SETTINGS_COUNT                  = AUTOMATION_SETTINGS.length;
 
-    public static final int            DISPLAY_RESOURCE_URI_TOKEN_COUNT = 2;
+    public static final String         START_RESOURCE_AUTOMATION                  = "Start Automation";
+    public static final String         STOP_RESOURCE_AUTOMATION                   = "Stop Automation";
 
-    public static final AutomationType DEFAULT_AUTOMATION_TYPE          = AutomationType.NORMAL;
+    public static final int            DISPLAY_RESOURCE_URI_TOKEN_COUNT           = 2;
 
-    public static final int            DEFAULT_AUTOMATION_INTERVAL      = 500;
+    public static final AutoUpdateType DEFAULT_AUTOMATION_TYPE                    = AutoUpdateType.ONE_TIME;
 
-    public static final int            PROPER_LOG_TIME_TOKEN_LENGTH     = 3;
+    public static final int            DEFAULT_AUTOMATION_INTERVAL                = 500;
 
-    public static final String[]       BROWSE_RAML_FILTER_EXTENSIONS    = new String[] { "*.raml" };
-    public static final String[]       SAVE_LOG_FILTER_EXTENSIONS       = new String[] {
-            "*.log", "*"                                               };
+    public static final int            PROPER_LOG_TIME_TOKEN_LENGTH               = 3;
 
-    public static final int            LOG_SIZE                         = 1000;
+    public static final String[]       BROWSE_RAML_FILTER_EXTENSIONS              = new String[] { "*.raml" };
+    public static final String[]       SAVE_LOG_FILTER_EXTENSIONS                 = new String[] {
+            "*.log", "*"                                                         };
 
-    public static final String         INFO_LOG                         = "info_log";
-    public static final String         WARNING_LOG                      = "warning_log";
-    public static final String         ERROR_LOG                        = "error_log";
-    public static final String         DEBUG_LOG                        = "debug_log";
-    public static final String         UNKNOWN_LOG                      = "unknown_log";
+    public static final int            LOG_SIZE                                   = 1000;
 
-    public static final String         INFO                             = "Info";
-    public static final String         WARNING                          = "Warning";
-    public static final String         ERROR                            = "Error";
-    public static final String         DEBUG                            = "Debug";
-    public static final String         UNKNOWN                          = "Unknown";
+    public static final String         INFO_LOG                                   = "info_log";
+    public static final String         WARNING_LOG                                = "warning_log";
+    public static final String         ERROR_LOG                                  = "error_log";
+    public static final String         DEBUG_LOG                                  = "debug_log";
+    public static final String         UNKNOWN_LOG                                = "unknown_log";
 
-    public static final String         CHECKED                          = "Checked";
-    public static final String         UNCHECKED                        = "Unchecked";
-    public static final String         NOTIFY_BUTTON_SELECTED           = "Notify_Selected";
-    public static final String         NOTIFY_BUTTON_UNSELECTED         = "Notify_Unselected";
+    public static final String         INFO                                       = "Info";
+    public static final String         WARNING                                    = "Warning";
+    public static final String         ERROR                                      = "Error";
+    public static final String         DEBUG                                      = "Debug";
 
-    public static final String         CREATE_PAGE_TITLE                = "Create Resource";
-    public static final String         CREATE_PAGE_MESSAGE              = "Select a standard resource or custom resource to be created";
+    public static final String         CHECKED                                    = "Checked";
+    public static final String         UNCHECKED                                  = "Unchecked";
+    public static final String         NOTIFY_BUTTON_SELECTED                     = "Notify_Selected";
+    public static final String         NOTIFY_BUTTON_UNSELECTED                   = "Notify_Unselected";
 
-    public static final String         DELETE_PAGE_TITLE                = "Delete Resource";
-    public static final String         DELETE_PAGE_MESSAGE              = "Select the resource(s) to be deleted";
+    public static final String         CREATE_PAGE_TITLE                          = "Create Resource";
+    public static final String         CREATE_PAGE_MESSAGE                        = "Create a resource from RAML file";
 
-    public static final String         RAML_FILE_PREFIX                 = "/resource/";
+    public static final String         DELETE_PAGE_TITLE                          = "Delete Resource";
+    public static final String         DELETE_PAGE_MESSAGE                        = "Select the resource(s) to be deleted";
 
-    public static final String         RAML_FILE_EXTENSION              = ".raml";
-    public static final String         JSON_FILE_EXTENSION              = ".json";
+    public static final String         RAML_FILE_PREFIX                           = "/resource/";
 
-    public static final String         SPLIT_BY_DOT_PATTERN             = "\\.";
+    public static final String         RAML_FILE_EXTENSION                        = ".raml";
+    public static final String         JSON_FILE_EXTENSION                        = ".json";
+
+    public static final String         SPLIT_BY_DOT_PATTERN                       = "\\.";
+
+    // Platform information
+    public static final String         PLATFORM_ID                                = "Id";
+    public static final String         PLATFORM_MANUFAC_NAME                      = "Manufacturer Name";
+    public static final String         PLATFORM_MANUFAC_URL                       = "Manufacturer URL";
+    public static final String         PLATFORM_MODEL_NO                          = "Model Number";
+    public static final String         PLATFORM_DATE_OF_MANUFAC                   = "Date of Manufacture";
+    public static final String         PLATFORM_VERSION                           = "Version";
+    public static final String         PLATFORM_OS_VERSION                        = "OS Version";
+    public static final String         PLATFORM_HARDWARE_VERSION                  = "HardWare Version";
+    public static final String         PLATFORM_FIRMWARE_VERSION                  = "Firmware Version";
+    public static final String         PLATFORM_SUPPORT_URL                       = "Support URL";
+    public static final String         PLATFORM_SYSTEM_TIME                       = "System Time";
+
+    // Device information
+    public static final String         DEVICE_NAME                                = "Device Name";
+    public static final String         DEVICE_ID                                  = "Device ID";
+    public static final String         DEVICE_SPEC_VERSION                        = "Spec Version";
+    public static final String         DEVICE_DMV                                 = "Data Model Version";
+
+    public static final String         SAMPLE_LIGHT                               = "sample.light";
+
+    public static final String         UPDATE_PROP_PAGE_TITLE                     = "Update Properties";
+    public static final String         UPDATE_PROP_PAGE_MESSAGE                   = "Update the default values of resource properties";
+
+    public static final String         START_STOP_PAGE_TITLE                      = "Start/Stop Resource";
+    public static final String         START_STOP_PAGE_MESSAGE                    = "This page allows to start or stop the created resource(s)";
+
+    public static final String         START_RESOURCE                             = "Start Resource";
+    public static final String         STOP_RESOURCE                              = "Stop Resource";
+
+    public static final String         DELETE_RESOURCE                            = "Delete Resource";
+
+    public static final String         MAIN_PAGE_TITLE                            = "Create Resource";
+    public static final String         MAIN_PAGE_MESSAGE                          = "Create a Simple resource";
+
+    public static final String         SIMPLE_PAGE_TITLE                          = "Create Simple Resource";
+    public static final String         SIMPLE_PAGE_MESSAGE                        = "Either manually or from RAML file";
+
+    public static final String         SIMPLE_RESOURCE_BASIC_DETAILS_PAGE_TITLE   = "Create Simple Resource(Step 1 of 3)";
+    public static final String         SIMPLE_RESOURCE_BASIC_DETAILS_PAGE_MESSAGE = "Fill basic details of the resource";
+
+    public static final String         SIMPLE_RESOURCE_ADD_ATTRIBUTE_PAGE_TITLE   = "Create Simple Resource(Step 2 of 3)";
+    public static final String         SIMPLE_RESOURCE_ADD_ATTRIBUTE_PAGE_MESSAGE = "Add attributes to the resource";
+
+    public static final String         SIMPLE_RESOURCE_OTHER_DETAILS_PAGE_TITLE   = "Create Simple Resource(Step 3 of 3)";
+    public static final String         SIMPLE_RESOURCE_OTHER_DETAILS_PAGE_MESSAGE = "Fill other details of the resource";
+
+    public static final String         SINGLE_RESOURCE                            = "Single Resource";
+    public static final String         INVALID_URI_MESSAGE                        = "Resource URI should start with a '/'."
+                                                                                          + "\nIt should be 2 to 63 chars long.\n"
+                                                                                          + "It should not contain # or ? or % or "
+                                                                                          + "consecutive '/' or '/./' or "
+                                                                                          + "'/..'(more than one dot following a slash).";
+
+    public static final String         INVALID_RESOURCE_TYPE_MESSAGE              = "Resource Type should start with an alphabet.\n"
+                                                                                          + "It should contain only lowercase alphabets, "
+                                                                                          + "numbers(0-9), dot(.) and hyphen(-).";
+
+    public static final String         RESOURCE_LIMIT_EXCEEDED_MSG                = "A maximum of 200 resources can exist in the server.";
+
+    public static final int            TREE_EXPANSION_LEVEL                       = 10;
+
+    public static final String         BASELINE_INTERFACE                         = "oic.if.baseline";
+    public static final String         LINKS_LIST_INTERFACE                       = "oic.if.ll";
+    public static final String         BATCH_INTERFACE                            = "oic.if.b";
+    public static final String         LINK_BATCH_INTERFACE                       = "oic.if.lb";
+    public static final String         READ_ONLY_INTERFACE                        = "oic.if.r";
+    public static final String         READ_WRITE_INTERFACE                       = "oic.if.rw";
+    public static final String         ACTUATOR_INTERFACE                         = "oic.if.a";
+    public static final String         SENSOR_INTERFACE                           = "oic.if.s";
+
+    public static final String         DEFAULT_SINGLE_RESOURCE_INTERFACE          = "oic.if.baseline";
+
+    public static final int            MAX_RESOURCE_COUNT                         = 200;
 
-    public static final String         SAMPLE_LIGHT                      = "sample.light";
 }
\ No newline at end of file
index 4c053d3..a662874 100644 (file)
 package oic.simulator.serviceprovider.utils;
 
 import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Date;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
+import java.util.Map;
 import java.util.Set;
+import java.util.Vector;
+
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.AttributeValue.TypeInfo;
+import org.oic.simulator.AttributeValue.ValueType;
+import org.oic.simulator.ILogger.Level;
+import org.oic.simulator.InvalidArgsException;
+import org.oic.simulator.SimulatorException;
+import org.oic.simulator.SimulatorResourceModel;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.model.AttributeElement;
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.model.SingleResource;
 
 /**
  * This class has common utility methods.
  */
 public class Utility {
 
-    public static String uriToDisplayName(String uri) {
-        String result = null;
-        if (null != uri) {
-            String tokens[] = uri.split(Constants.FORWARD_SLASH);
-            if (null != tokens && tokens.length > 2) {
-                result = tokens[tokens.length - 3] + Constants.UNDERSCORE
-                        + tokens[tokens.length - 1];
-            }
-        }
-        return result;
-    }
-
-    public static String fileNameToDisplay(String fileName) {
-        if (null == fileName || fileName.length() < 1) {
-            return null;
-        }
-        // Remove the RAML file standard prefix
-        int len = Constants.RAML_FILE_PREFIX.length();
-        if (len > 0) {
-            if (fileName.startsWith(Constants.RAML_FILE_PREFIX)) {
-                fileName = fileName.substring(len);
-            }
-        }
-
-        // Removing the file extension
-        int index = fileName.lastIndexOf('.');
-        fileName = fileName.substring(0, index);
-        return fileName;
-    }
-
-    public static String displayToFileName(String displayName) {
-        if (null == displayName || displayName.length() < 1) {
-            return null;
-        }
-        String fileName;
-        // Adding the prefix
-        fileName = Constants.RAML_FILE_PREFIX + displayName;
-
-        // Adding the file extension
-        fileName = fileName + Constants.RAML_FILE_EXTENSION;
-
-        return fileName;
-    }
-
     public static String getAutomationStatus(boolean status) {
         if (status) {
             return Constants.ENABLED;
@@ -100,9 +76,18 @@ public class Utility {
         if (null != value) {
             try {
                 result = Integer.parseInt(value);
-            } catch (NumberFormatException nfe) {
-                System.out
-                        .println("Getting UpdateInterval from string failed!");
+            } catch (NumberFormatException e) {
+                Activator
+                        .getDefault()
+                        .getLogManager()
+                        .log(Level.ERROR.ordinal(),
+                                new Date(),
+                                getSimulatorErrorString(
+                                        e,
+                                        "Update interval convertion failed."
+                                                + "Taking the default value("
+                                                + Constants.DEFAULT_AUTOMATION_INTERVAL
+                                                + ")"));
             }
         }
         return result;
@@ -119,4 +104,573 @@ public class Utility {
         }
         return list;
     }
+
+    public static List<SingleResource> getSingleResourceListFromSet(
+            Set<SingleResource> resources) {
+        if (null == resources) {
+            return null;
+        }
+        List<SingleResource> list = new ArrayList<SingleResource>();
+        Iterator<SingleResource> typeItr = resources.iterator();
+        while (typeItr.hasNext()) {
+            list.add(typeItr.next());
+        }
+        return list;
+    }
+
+    public static Set<String> convertVectorToSet(Vector<String> vector) {
+        if (null == vector || vector.isEmpty()) {
+            return null;
+        }
+        Set<String> resultSet = new HashSet<String>();
+        Enumeration<String> e = vector.elements();
+        while (e.hasMoreElements()) {
+            resultSet.add(e.nextElement());
+        }
+        return resultSet;
+    }
+
+    public static String getSimulatorErrorString(Exception e, String info) {
+        if (null == e) {
+            return null;
+        }
+        String detail;
+        if (e instanceof SimulatorException) {
+            SimulatorException simEx = (SimulatorException) e;
+            detail = simEx.message() + "\n";
+            detail += "Exception Type: " + simEx.getClass().getSimpleName()
+                    + "\n";
+            detail += "Error code: " + simEx.code().toString();
+        } else {
+            if (null != info && !info.isEmpty())
+                detail = info + "\n";
+            else
+                detail = "Description not available\n";
+            detail += "Exception Type: " + e.getClass().getSimpleName() + "\n";
+            String msg = e.getMessage();
+            if (null != msg && !msg.isEmpty()) {
+                detail += "Message: " + e.getMessage();
+            }
+        }
+        return detail;
+    }
+
+    public static Set<String> getAttributeTypes() {
+        Set<String> attTypes = new HashSet<String>();
+        ValueType[] types = ValueType.values();
+        if (null != types) {
+            attTypes.add(Constants.INT);
+            attTypes.add(Constants.DOUBLE);
+            attTypes.add(Constants.BOOL);
+            attTypes.add(Constants.STRING);
+        }
+        return attTypes;
+    }
+
+    public static ValueType getAttributeTypeEnum(String type) {
+        if (null != type && type.trim().length() > 0) {
+            if (type.equalsIgnoreCase(Constants.INT)) {
+                return ValueType.INTEGER;
+            }
+            if (type.equalsIgnoreCase(Constants.DOUBLE)) {
+                return ValueType.DOUBLE;
+            }
+            if (type.equalsIgnoreCase(Constants.BOOL)) {
+                return ValueType.BOOLEAN;
+            }
+            if (type.equalsIgnoreCase(Constants.STRING)) {
+                return ValueType.STRING;
+            }
+        }
+        return ValueType.UNKNOWN;
+    }
+
+    public static int[] convertSetToArrayInt(Set<Object> allowedValues) {
+        if (null == allowedValues || allowedValues.size() < 1) {
+            return null;
+        }
+        int[] arr = new int[allowedValues.size()];
+        Iterator<Object> itr = allowedValues.iterator();
+        try {
+            int i = 0;
+            while (itr.hasNext()) {
+                arr[i++] = (int) itr.next();
+            }
+        } catch (Exception e) {
+            return null;
+        }
+        return arr;
+    }
+
+    public static double[] convertSetToArrayDouble(Set<Object> allowedValues) {
+        if (null == allowedValues || allowedValues.size() < 1) {
+            return null;
+        }
+        double[] arr = new double[allowedValues.size()];
+        Iterator<Object> itr = allowedValues.iterator();
+        try {
+            int i = 0;
+            while (itr.hasNext()) {
+                arr[i++] = (double) itr.next();
+            }
+        } catch (Exception e) {
+            return null;
+        }
+        return arr;
+    }
+
+    public static boolean[] convertSetToArrayBoolean(Set<Object> allowedValues) {
+        if (null == allowedValues || allowedValues.size() < 1) {
+            return null;
+        }
+        boolean[] arr = new boolean[allowedValues.size()];
+        Iterator<Object> itr = allowedValues.iterator();
+        try {
+            int i = 0;
+            while (itr.hasNext()) {
+                arr[i++] = (boolean) itr.next();
+            }
+        } catch (Exception e) {
+            return null;
+        }
+        return arr;
+    }
+
+    public static String[] convertSetToArrayString(Set<Object> allowedValues) {
+        if (null == allowedValues || allowedValues.size() < 1) {
+            return null;
+        }
+        String[] arr = new String[allowedValues.size()];
+        Iterator<Object> itr = allowedValues.iterator();
+        try {
+            int i = 0;
+            while (itr.hasNext()) {
+                arr[i++] = (String) itr.next();
+            }
+        } catch (Exception e) {
+            return null;
+        }
+        return arr;
+    }
+
+    public static Vector<Integer> convertSetToVectorInt(
+            Set<Object> allowedValues) {
+        if (null == allowedValues || allowedValues.size() < 1) {
+            return null;
+        }
+        Vector<Integer> resultVec = new Vector<Integer>();
+        Iterator<Object> itr = allowedValues.iterator();
+        try {
+            while (itr.hasNext()) {
+                resultVec.add((Integer) itr.next());
+            }
+        } catch (Exception e) {
+            return null;
+        }
+        return resultVec;
+    }
+
+    public static Vector<Double> convertSetToVectorDouble(
+            Set<Object> allowedValues) {
+        if (null == allowedValues || allowedValues.size() < 1) {
+            return null;
+        }
+        Vector<Double> resultVec = new Vector<Double>();
+        Iterator<Object> itr = allowedValues.iterator();
+        try {
+            while (itr.hasNext()) {
+                resultVec.add((Double) itr.next());
+            }
+        } catch (Exception e) {
+            return null;
+        }
+        return resultVec;
+    }
+
+    public static Vector<String> convertSetToVectorString(
+            Set<String> allowedValues) {
+        if (null == allowedValues || allowedValues.size() < 1) {
+            return null;
+        }
+        Vector<String> resultVec = new Vector<String>();
+        Iterator<String> itr = allowedValues.iterator();
+        try {
+            while (itr.hasNext()) {
+                resultVec.add((String) itr.next());
+            }
+        } catch (Exception e) {
+            return null;
+        }
+        return resultVec;
+    }
+
+    public static Set<Object> convertSetStringToSetObject(Set<String> values,
+            ValueType type) {
+        if (null == values || values.isEmpty()) {
+            return null;
+        }
+        Set<Object> resultSet = new HashSet<Object>();
+        if (AttributeValue.ValueType.INTEGER == type) {
+            int val;
+            Iterator<String> itr = values.iterator();
+            while (itr.hasNext()) {
+                try {
+                    val = Integer.parseInt(itr.next());
+                    resultSet.add(val);
+                } catch (NumberFormatException nfe) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(),
+                                    new Date(),
+                                    "There is an error while doing internal convertion(string set to object set).\n"
+                                            + Utility.getSimulatorErrorString(
+                                                    nfe, null));
+                }
+            }
+        } else if (AttributeValue.ValueType.DOUBLE == type) {
+            double val;
+            Iterator<String> itr = values.iterator();
+            while (itr.hasNext()) {
+                try {
+                    val = Double.parseDouble(itr.next());
+                    resultSet.add(val);
+                } catch (NumberFormatException nfe) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(),
+                                    new Date(),
+                                    "There is an error while doing internal convertion(string set to object set).\n"
+                                            + Utility.getSimulatorErrorString(
+                                                    nfe, null));
+                }
+            }
+        } else if (AttributeValue.ValueType.BOOLEAN == type) {
+            resultSet.add(true);
+            resultSet.add(false);
+        } else if (AttributeValue.ValueType.STRING == type) {
+            Iterator<String> itr = values.iterator();
+            while (itr.hasNext()) {
+                resultSet.add(itr.next());
+            }
+        }
+        return resultSet;
+    }
+
+    public static List<Resource> convertSingleTypeResourceListToBaseType(
+            List<SingleResource> resources) {
+        if (null == resources || resources.isEmpty()) {
+            return null;
+        }
+        List<Resource> resultSet = new ArrayList<Resource>();
+        Iterator<SingleResource> itr = resources.iterator();
+        while (itr.hasNext()) {
+            resultSet.add(itr.next());
+        }
+        return resultSet;
+    }
+
+    public static String[] convertListToStringArray(List<String> valueList) {
+        String[] strArr;
+        if (null != valueList && valueList.size() > 0) {
+            strArr = valueList.toArray(new String[1]);
+        } else {
+            strArr = new String[1];
+        }
+        return strArr;
+    }
+
+    public static Comparator<Resource>         resourceComparator       = new Comparator<Resource>() {
+                                                                            public int compare(
+                                                                                    Resource res1,
+                                                                                    Resource res2) {
+                                                                                String s1 = res1
+                                                                                        .getResourceName();
+                                                                                String s2 = res2
+                                                                                        .getResourceName();
+
+                                                                                String s1Part = s1
+                                                                                        .replaceAll(
+                                                                                                "\\d",
+                                                                                                "");
+                                                                                String s2Part = s2
+                                                                                        .replaceAll(
+                                                                                                "\\d",
+                                                                                                "");
+
+                                                                                if (s1Part
+                                                                                        .equalsIgnoreCase(s2Part)) {
+                                                                                    return extractInt(s1)
+                                                                                            - extractInt(s2);
+                                                                                }
+                                                                                return s1
+                                                                                        .compareTo(s2);
+                                                                            }
+
+                                                                            int extractInt(
+                                                                                    String s) {
+                                                                                String num = s
+                                                                                        .replaceAll(
+                                                                                                "\\D",
+                                                                                                "");
+                                                                                // return
+                                                                                // 0
+                                                                                // if
+                                                                                // no
+                                                                                // digits
+                                                                                // found
+                                                                                return num
+                                                                                        .isEmpty() ? 0
+                                                                                        : Integer
+                                                                                                .parseInt(num);
+                                                                            }
+                                                                        };
+
+    public static Comparator<SingleResource>   singleResourceComparator = new Comparator<SingleResource>() {
+                                                                            public int compare(
+                                                                                    SingleResource res1,
+                                                                                    SingleResource res2) {
+                                                                                String s1 = res1
+                                                                                        .getResourceName();
+                                                                                String s2 = res2
+                                                                                        .getResourceName();
+
+                                                                                String s1Part = s1
+                                                                                        .replaceAll(
+                                                                                                "\\d",
+                                                                                                "");
+                                                                                String s2Part = s2
+                                                                                        .replaceAll(
+                                                                                                "\\d",
+                                                                                                "");
+
+                                                                                if (s1Part
+                                                                                        .equalsIgnoreCase(s2Part)) {
+                                                                                    return extractInt(s1)
+                                                                                            - extractInt(s2);
+                                                                                }
+                                                                                return s1
+                                                                                        .compareTo(s2);
+                                                                            }
+
+                                                                            int extractInt(
+                                                                                    String s) {
+                                                                                String num = s
+                                                                                        .replaceAll(
+                                                                                                "\\D",
+                                                                                                "");
+                                                                                // return
+                                                                                // 0
+                                                                                // if
+                                                                                // no
+                                                                                // digits
+                                                                                // found
+                                                                                return num
+                                                                                        .isEmpty() ? 0
+                                                                                        : Integer
+                                                                                                .parseInt(num);
+                                                                            }
+                                                                        };
+
+    public static Comparator<AttributeElement> attributeComparator      = new Comparator<AttributeElement>() {
+                                                                            public int compare(
+                                                                                    AttributeElement att1,
+                                                                                    AttributeElement att2) {
+                                                                                String s1 = att1
+                                                                                        .getSimulatorResourceAttribute()
+                                                                                        .name();
+                                                                                String s2 = att2
+                                                                                        .getSimulatorResourceAttribute()
+                                                                                        .name();
+
+                                                                                String s1Part = s1
+                                                                                        .replaceAll(
+                                                                                                "\\d",
+                                                                                                "");
+                                                                                String s2Part = s2
+                                                                                        .replaceAll(
+                                                                                                "\\d",
+                                                                                                "");
+
+                                                                                if (s1Part
+                                                                                        .equalsIgnoreCase(s2Part)) {
+                                                                                    return extractInt(s1)
+                                                                                            - extractInt(s2);
+                                                                                }
+                                                                                return s1
+                                                                                        .compareTo(s2);
+                                                                            }
+
+                                                                            int extractInt(
+                                                                                    String s) {
+                                                                                String num = s
+                                                                                        .replaceAll(
+                                                                                                "\\D",
+                                                                                                "");
+
+                                                                                // Return
+                                                                                // 0
+                                                                                // if
+                                                                                // no
+                                                                                // digits
+                                                                                // found
+                                                                                return num
+                                                                                        .isEmpty() ? 0
+                                                                                        : Integer
+                                                                                                .parseInt(num);
+                                                                            }
+                                                                        };
+
+    // This method only works for attributes whose values are of type int,
+    // double, bool, string and 1-D array of primitive types
+    public static String getAttributeValueAsString(AttributeValue val) {
+        if (null == val) {
+            return null;
+        }
+
+        Object value = val.get();
+        if (null == value) {
+            return null;
+        }
+
+        TypeInfo type = val.typeInfo();
+        if (type.mBaseType == ValueType.RESOURCEMODEL
+                || (type.mType == ValueType.ARRAY && type.mDepth > 1)) {
+            return null;
+        }
+
+        AttributeValueStringConverter converter = new AttributeValueStringConverter(
+                val);
+        return converter.toString();
+    }
+
+    public static boolean isUriValid(String resURI) {
+        if (null == resURI || resURI.length() < 2 || resURI.length() > 63
+                || !resURI.startsWith("/") || resURI.endsWith("/")
+                || resURI.contains("/..") || resURI.contains("//")
+                || resURI.contains("/./") || resURI.contains("?")
+                || resURI.contains("#") || resURI.contains("%")) {
+            return false;
+        }
+        return true;
+    }
+
+    public static boolean isResourceTypeValid(String resType) {
+        if (null == resType || resType.isEmpty()) {
+            return false;
+        }
+
+        char[] ch = resType.toCharArray();
+        for (char c : ch) {
+            if (c != '.' && c != '-' && (c < 'a' || c > 'z')
+                    && (c < '0' || c > '9')) {
+                return false;
+            }
+        }
+
+        return true;
+    }
+
+    public static Map<String, String> getResourceInterfaces(
+            Class<? extends Resource> resourceClass) {
+        Map<String, String> ifTypes = null;
+        if (resourceClass == SingleResource.class) {
+            ifTypes = new HashMap<String, String>();
+            ifTypes.put(Constants.BASELINE_INTERFACE, "Baseline");
+            ifTypes.put(Constants.READ_ONLY_INTERFACE, "Read-Only");
+            ifTypes.put(Constants.READ_WRITE_INTERFACE, "Read-Write");
+            ifTypes.put(Constants.ACTUATOR_INTERFACE, "Actuator");
+            ifTypes.put(Constants.SENSOR_INTERFACE, "Sensor");
+        }
+        return ifTypes;
+    }
+
+    public static String removeWhiteSpacesInArrayValues(String value) {
+        if (null == value || value.isEmpty())
+            return null;
+
+        value = value.trim();
+
+        String token[] = value.split(",");
+        StringBuilder result = new StringBuilder();
+        for (int i = 0; i < token.length; i++) {
+            result.append(token[i].trim());
+            if (i + 1 < token.length) {
+                result.append(",");
+            }
+        }
+
+        return result.toString();
+    }
+
+    public static AttributeValue cloneAttributeValue(AttributeValue value)
+            throws InvalidArgsException, NullPointerException {
+        AttributeValue clone = null;
+
+        AttributeValue.TypeInfo typeInfo = value.typeInfo();
+
+        if (typeInfo.mType == AttributeValue.ValueType.RESOURCEMODEL) {
+            SimulatorResourceModel resModel = (SimulatorResourceModel) value
+                    .get();
+            SimulatorResourceModel modelCopy = new SimulatorResourceModel();
+
+            for (Map.Entry<String, AttributeValue> entry : resModel.get()
+                    .entrySet()) {
+                String attName = entry.getKey();
+                AttributeValue attValue = entry.getValue();
+                modelCopy.set(attName, cloneAttributeValue(attValue));
+            }
+            clone = new AttributeValue(modelCopy);
+        } else if (typeInfo.mType == AttributeValue.ValueType.ARRAY
+                && typeInfo.mBaseType == AttributeValue.ValueType.RESOURCEMODEL) {
+            if (typeInfo.mDepth == 1) {
+                SimulatorResourceModel[] resModelArray = (SimulatorResourceModel[]) value
+                        .get();
+                SimulatorResourceModel[] modelArrayCopy = new SimulatorResourceModel[resModelArray.length];
+                for (int i = 0; i < resModelArray.length; i++) {
+                    AttributeValue attValue = cloneAttributeValue(new AttributeValue(
+                            resModelArray[i]));
+                    if (null != attValue) {
+                        modelArrayCopy[i] = (SimulatorResourceModel) attValue
+                                .get();
+                    }
+                }
+                clone = new AttributeValue(modelArrayCopy);
+            } else if (typeInfo.mDepth == 2) {
+                SimulatorResourceModel[][] resModelArray = (SimulatorResourceModel[][]) value
+                        .get();
+                SimulatorResourceModel[][] modelArrayCopy = new SimulatorResourceModel[resModelArray.length][];
+                for (int i = 0; i < resModelArray.length; i++) {
+                    AttributeValue attValue = cloneAttributeValue(new AttributeValue(
+                            resModelArray[i]));
+                    if (null != attValue) {
+                        modelArrayCopy[i] = (SimulatorResourceModel[]) attValue
+                                .get();
+                    }
+                }
+                clone = new AttributeValue(modelArrayCopy);
+            } else if (typeInfo.mDepth == 3) {
+                SimulatorResourceModel[][][] resModelArray = (SimulatorResourceModel[][][]) value
+                        .get();
+                SimulatorResourceModel[][][] modelArrayCopy = new SimulatorResourceModel[resModelArray.length][][];
+                for (int i = 0; i < resModelArray.length; i++) {
+                    AttributeValue attValue = cloneAttributeValue(new AttributeValue(
+                            resModelArray[i]));
+                    if (null != attValue) {
+                        modelArrayCopy[i] = (SimulatorResourceModel[][]) attValue
+                                .get();
+                    }
+                }
+                clone = new AttributeValue(modelArrayCopy);
+            }
+        } else {
+            String attValueInString = new AttributeValueStringConverter(value)
+                    .toString();
+            clone = AttributeValueBuilder.build(attValueInString,
+                    typeInfo.mBaseType);
+        }
+
+        return clone;
+    }
 }
\ No newline at end of file
index 5b8e299..ee52592 100644 (file)
 
 package oic.simulator.serviceprovider.view;
 
-import java.util.List;
-
-import oic.simulator.serviceprovider.Activator;
-import oic.simulator.serviceprovider.manager.ResourceManager;
-import oic.simulator.serviceprovider.resource.AutomationSettingHelper;
-import oic.simulator.serviceprovider.resource.LocalResourceAttribute;
-import oic.simulator.serviceprovider.resource.SimulatorResource;
-import oic.simulator.serviceprovider.utils.Utility;
-import oic.simulator.serviceprovider.view.dialogs.AutomationSettingDialog;
-
 import org.eclipse.jface.dialogs.MessageDialog;
 import org.eclipse.jface.viewers.CellEditor;
 import org.eclipse.jface.viewers.CheckboxCellEditor;
 import org.eclipse.jface.viewers.ComboBoxCellEditor;
 import org.eclipse.jface.viewers.EditingSupport;
-import org.eclipse.jface.viewers.TableViewer;
+import org.eclipse.jface.viewers.TextCellEditor;
+import org.eclipse.jface.viewers.TreeViewer;
 import org.eclipse.jface.window.Window;
 import org.eclipse.swt.SWT;
 import org.eclipse.swt.custom.CCombo;
@@ -39,7 +30,34 @@ import org.eclipse.swt.events.ModifyEvent;
 import org.eclipse.swt.events.ModifyListener;
 import org.eclipse.swt.widgets.Display;
 import org.eclipse.swt.widgets.MessageBox;
-import org.oic.simulator.serviceprovider.AutomationType;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeItem;
+import org.eclipse.ui.IPartListener2;
+import org.eclipse.ui.IWorkbenchPartReference;
+
+import java.util.Date;
+import java.util.List;
+
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.AttributeValue.TypeInfo;
+import org.oic.simulator.AttributeValue.ValueType;
+import org.oic.simulator.ILogger.Level;
+import org.oic.simulator.InvalidArgsException;
+import org.oic.simulator.SimulatorResourceAttribute;
+import org.oic.simulator.server.SimulatorResource.AutoUpdateType;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.manager.ResourceManager;
+import oic.simulator.serviceprovider.model.AttributeElement;
+import oic.simulator.serviceprovider.model.AutomationSettingHelper;
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.model.ResourceRepresentation;
+import oic.simulator.serviceprovider.model.SingleResource;
+import oic.simulator.serviceprovider.utils.AttributeValueBuilder;
+import oic.simulator.serviceprovider.utils.Utility;
+import oic.simulator.serviceprovider.view.dialogs.AutomationSettingDialog;
+import oic.simulator.serviceprovider.view.dialogs.UpdatePrimitiveArrayAttributeDialog;
 
 /**
  * This class provides editing support to the resources attributes table in the
@@ -50,25 +68,176 @@ public class AttributeEditingSupport {
     private AttributeValueEditor attValueEditor;
     private AutomationEditor     automationEditor;
 
-    public AttributeValueEditor createAttributeValueEditor(TableViewer viewer) {
-        attValueEditor = new AttributeValueEditor(viewer);
+    private static class SyncValueUpdate {
+        private Boolean valueChangeInProgress;
+
+        public boolean isValueChangeInProgress() {
+            return valueChangeInProgress;
+        }
+
+        public void setValueChangeInProgress(boolean value) {
+            valueChangeInProgress = value;
+        }
+    }
+
+    private final SyncValueUpdate syncValueChange = new SyncValueUpdate();
+
+    public AttributeValueEditor createAttributeValueEditor(TreeViewer viewer,
+            Boolean nativeUpdateValueCall) {
+        attValueEditor = new AttributeValueEditor(viewer, nativeUpdateValueCall);
+        syncValueChange.setValueChangeInProgress(false);
         return attValueEditor;
     }
 
-    public AutomationEditor createAutomationEditor(TableViewer viewer) {
+    public AutomationEditor createAutomationEditor(TreeViewer viewer) {
         automationEditor = new AutomationEditor(viewer);
         return automationEditor;
     }
 
     class AttributeValueEditor extends EditingSupport {
 
-        private final TableViewer      viewer;
-        private LocalResourceAttribute attributeInSelection;
-        private CCombo                 comboBox;
+        private final TreeViewer viewer;
+        private CCombo           comboBox;
+
+        private Boolean          callNativeUpdateValue;
 
-        public AttributeValueEditor(TableViewer viewer) {
+        public AttributeValueEditor(TreeViewer viewer,
+                Boolean nativeUpdateValueCall) {
             super(viewer);
             this.viewer = viewer;
+            callNativeUpdateValue = nativeUpdateValueCall;
+            // Using the part listener to refresh the viewer on various part
+            // events.
+            // If combo list is open, then click events on other parts of the
+            // view or outside the combo should hide the editor.
+            // Refreshing the viewer hides the combo and other editors which are
+            // active.
+            IPartListener2 partListener;
+            partListener = new IPartListener2() {
+
+                @Override
+                public void partVisible(IWorkbenchPartReference partRef) {
+                }
+
+                @Override
+                public void partOpened(IWorkbenchPartReference partRef) {
+                }
+
+                @Override
+                public void partInputChanged(IWorkbenchPartReference partRef) {
+                }
+
+                @Override
+                public void partHidden(IWorkbenchPartReference partRef) {
+                }
+
+                @Override
+                public void partDeactivated(IWorkbenchPartReference partRef) {
+                    String viewId = partRef.getId();
+                    if (viewId.equals(AttributeView.VIEW_ID)) {
+                        synchronized (syncValueChange) {
+                            updateUnSavedData();
+                        }
+                    }
+                }
+
+                @Override
+                public void partClosed(IWorkbenchPartReference partRef) {
+                }
+
+                @Override
+                public void partBroughtToTop(IWorkbenchPartReference partRef) {
+                }
+
+                @Override
+                public void partActivated(IWorkbenchPartReference partRef) {
+                    String viewId = partRef.getId();
+                    if (viewId.equals(AttributeView.VIEW_ID)) {
+                        if (null == AttributeValueEditor.this.viewer)
+                            return;
+
+                        Tree tree = AttributeValueEditor.this.viewer.getTree();
+                        if (null == tree || tree.isDisposed())
+                            return;
+
+                        AttributeValueEditor.this.viewer.refresh();
+                    }
+                }
+            };
+
+            try {
+                Activator.getDefault().getWorkbench()
+                        .getActiveWorkbenchWindow().getActivePage()
+                        .addPartListener(partListener);
+            } catch (Exception e) {
+                Activator
+                        .getDefault()
+                        .getLogManager()
+                        .log(Level.ERROR.ordinal(),
+                                new Date(),
+                                "There is an error while configuring the listener for UI.\n"
+                                        + Utility.getSimulatorErrorString(e,
+                                                null));
+            }
+        }
+
+        public void updateUnSavedData() {
+            if (null == viewer || null == comboBox)
+                return;
+
+            Tree tree = viewer.getTree();
+            if (null == tree || tree.isDisposed())
+                return;
+
+            TreeItem[] selectedItems = tree.getSelection();
+            if (null == selectedItems || 1 != selectedItems.length)
+                return;
+
+            Object element = selectedItems[0].getData();
+            if (null == element || !(element instanceof AttributeElement))
+                return;
+
+            AttributeElement attElement = (AttributeElement) element;
+            SimulatorResourceAttribute att = attElement
+                    .getSimulatorResourceAttribute();
+            if (null == att)
+                return;
+
+            if (Activator.getDefault().getResourceManager()
+                    .isAttHasRangeOrAllowedValues(att)) {
+                viewer.refresh();
+                return;
+            }
+
+            synchronized (syncValueChange) {
+                if (!syncValueChange.isValueChangeInProgress()) {
+
+                    AttributeValue value = att.value();
+                    if (value == null)
+                        return;
+
+                    TypeInfo type = value.typeInfo();
+
+                    if (type.mBaseType == ValueType.RESOURCEMODEL
+                            || type.mType == ValueType.ARRAY) {
+                        return;
+                    }
+
+                    if (null == value.get()) {
+                        return;
+                    }
+
+                    String oldValue = String.valueOf(Utility
+                            .getAttributeValueAsString(value));
+
+                    attElement.setEditLock(true);
+                    compareAndUpdateAttribute(oldValue, comboBox.getText(),
+                            (AttributeElement) element, att, type);
+                    attElement.setEditLock(false);
+
+                    viewer.refresh();
+                }
+            }
         }
 
         @Override
@@ -77,62 +246,205 @@ public class AttributeEditingSupport {
         }
 
         @Override
-        protected CellEditor getCellEditor(Object element) {
-            attributeInSelection = (LocalResourceAttribute) element;
+        protected CellEditor getCellEditor(final Object element) {
+            ResourceManager resourceManager = Activator.getDefault()
+                    .getResourceManager();
+
+            Resource res = resourceManager.getCurrentResourceInSelection();
+            if (null == res) {
+                return null;
+            }
+
+            // If selected resource is not a single resource, then editor
+            // support is not required.
+            if (!(res instanceof SingleResource)) {
+                return null;
+            }
+
+            final SimulatorResourceAttribute attribute;
+            if (!(element instanceof AttributeElement)) {
+                return null;
+            }
+
+            final AttributeElement attributeElement = ((AttributeElement) element);
+            attribute = attributeElement.getSimulatorResourceAttribute();
+            if (null == attribute) {
+                return null;
+            }
 
             // CellEditor is not required as the automation is in progress.
-            if (attributeInSelection.isAutomationInProgress()) {
+            if (attributeElement.isAutoUpdateInProgress()) {
                 return null;
             }
 
-            String values[] = null;
-            List<String> valueSet = attributeInSelection.getAttValues();
-            values = convertListToStringArray(valueSet);
+            final AttributeValue val = attribute.value();
+            if (null == val) {
+                return null;
+            }
 
-            ComboBoxCellEditor comboEditor = new ComboBoxCellEditor(
-                    viewer.getTable(), values, SWT.READ_ONLY);
-            comboBox = (CCombo) comboEditor.getControl();
-            comboBox.addModifyListener(new ModifyListener() {
+            final TypeInfo type = val.typeInfo();
+            if (type.mBaseType == ValueType.RESOURCEMODEL) {
+                return null;
+            }
 
-                @Override
-                public void modifyText(ModifyEvent event) {
-                    String oldValue = String.valueOf(attributeInSelection
-                            .getAttributeValue());
-                    String newValue = comboBox.getText();
-                    if (!oldValue.equals(newValue)) {
-                        attributeInSelection.setAttributeValue(newValue);
-                        MessageBox dialog = new MessageBox(viewer.getTable()
-                                .getShell(), SWT.ICON_QUESTION | SWT.OK
-                                | SWT.CANCEL);
-                        dialog.setText("Confirm action");
-                        dialog.setMessage("Do you want to modify the value?");
-                        int retval = dialog.open();
-                        if (retval != SWT.OK) {
-                            attributeInSelection.setAttributeValue(oldValue);
-                        } else {
-                            ResourceManager resourceManager;
-                            resourceManager = Activator.getDefault()
-                                    .getResourceManager();
-                            SimulatorResource resource = resourceManager
-                                    .getCurrentResourceInSelection();
-                            resourceManager.attributeValueUpdated(resource,
-                                    attributeInSelection.getAttributeName(),
-                                    newValue);
+            synchronized (syncValueChange) {
+                syncValueChange.setValueChangeInProgress(false);
+            }
+
+            CellEditor editor;
+            if (type.mType == ValueType.ARRAY) {
+                editor = new TextCellEditor(viewer.getTree());
+                editor.setStyle(SWT.READ_ONLY);
+                final Text txt = (Text) editor.getControl();
+                txt.addModifyListener(new ModifyListener() {
+                    @Override
+                    public void modifyText(ModifyEvent e) {
+                        String currentAttValue = txt.getText();
+                        UpdatePrimitiveArrayAttributeDialog dialog = new UpdatePrimitiveArrayAttributeDialog(
+                                Display.getDefault().getActiveShell(),
+                                attribute);
+                        if (dialog.open() == Window.OK) {
+                            updateAttributeValue(attributeElement, attribute,
+                                    dialog.getNewValueObj());
+
+                            if (callNativeUpdateValue) {
+                                ResourceManager resourceManager;
+                                resourceManager = Activator.getDefault()
+                                        .getResourceManager();
+
+                                Resource resource = resourceManager
+                                        .getCurrentResourceInSelection();
+
+                                SimulatorResourceAttribute result = getResultantAttribute(attributeElement);
+                                if (null == result) {
+                                    Activator
+                                            .getDefault()
+                                            .getLogManager()
+                                            .log(Level.ERROR.ordinal(),
+                                                    new Date(),
+                                                    "There is an error while updating the attribute value.\n");
+                                    return;
+                                }
+
+                                boolean updated = resourceManager
+                                        .attributeValueUpdated(
+                                                (SingleResource) resource,
+                                                result.name(), result.value());
+                                if (!updated) {
+                                    try {
+                                        updateAttributeValue(attributeElement,
+                                                attribute,
+                                                AttributeValueBuilder.build(
+                                                        currentAttValue,
+                                                        type.mBaseType));
+                                    } catch (Exception ex) {
+                                        Activator
+                                                .getDefault()
+                                                .getLogManager()
+                                                .log(Level.ERROR.ordinal(),
+                                                        new Date(),
+                                                        "There is an error while updating the attribute value.\n"
+                                                                + Utility
+                                                                        .getSimulatorErrorString(
+                                                                                ex,
+                                                                                null));
+                                    }
+                                    MessageDialog
+                                            .openInformation(Display
+                                                    .getDefault()
+                                                    .getActiveShell(),
+                                                    "Operation failed",
+                                                    "Failed to update the attribute value.");
+                                }
+                            }
                         }
-                        viewer.update(attributeInSelection, null);
-                        comboBox.setVisible(false);
+
+                        // Update the viewer in a separate UI thread.
+                        Display.getDefault().asyncExec(new Runnable() {
+                            @Override
+                            public void run() {
+                                viewer.refresh(element, true);
+                            }
+                        });
                     }
+                });
+            } else {
+                String values[] = null;
+                List<String> valueSet = resourceManager
+                        .getAllValuesOfAttribute(attribute);
+                values = Utility.convertListToStringArray(valueSet);
+
+                boolean hasValueSet = resourceManager
+                        .isAttHasRangeOrAllowedValues(attribute);
+
+                if (hasValueSet) {
+                    editor = new ComboBoxCellEditor(viewer.getTree(), values,
+                            SWT.READ_ONLY);
+                } else {
+                    editor = new ComboBoxCellEditor(viewer.getTree(), values);
                 }
-            });
-            return comboEditor;
+
+                comboBox = (CCombo) editor.getControl();
+                if (hasValueSet) {
+                    comboBox.addModifyListener(new ModifyListener() {
+
+                        @Override
+                        public void modifyText(ModifyEvent event) {
+                            String oldValue = String.valueOf(Utility
+                                    .getAttributeValueAsString(val));
+                            if (null == oldValue) {
+                                oldValue = "";
+                            }
+                            String newValue = comboBox.getText();
+
+                            attributeElement.setEditLock(true);
+                            compareAndUpdateAttribute(oldValue, newValue,
+                                    (AttributeElement) element, attribute, type);
+                            attributeElement.setEditLock(false);
+
+                            comboBox.setVisible(false);
+                        }
+                    });
+                }
+            }
+            return editor;
         }
 
         @Override
         protected Object getValue(Object element) {
             int indexOfItem = 0;
-            LocalResourceAttribute att = (LocalResourceAttribute) element;
-            String valueString = String.valueOf(att.getAttributeValue());
-            List<String> valueSet = att.getAttValues();
+            SimulatorResourceAttribute att = null;
+
+            if (element instanceof AttributeElement) {
+                att = ((AttributeElement) element)
+                        .getSimulatorResourceAttribute();
+            }
+
+            if (att == null) {
+                return 0;
+            }
+
+            final AttributeValue val = att.value();
+            if (null == val) {
+                return null;
+            }
+
+            final TypeInfo type = val.typeInfo();
+            if (type.mBaseType == ValueType.RESOURCEMODEL) {
+                return null;
+            }
+
+            String valueString = Utility.getAttributeValueAsString(att.value());
+            if (null == valueString) {
+                valueString = "";
+            }
+
+            if (type.mType == ValueType.ARRAY) {
+                return valueString;
+            }
+
+            List<String> valueSet = Activator.getDefault().getResourceManager()
+                    .getAllValuesOfAttribute(att);
             if (null != valueSet) {
                 indexOfItem = valueSet.indexOf(valueString);
             }
@@ -144,30 +456,229 @@ public class AttributeEditingSupport {
 
         @Override
         protected void setValue(Object element, Object value) {
-            Object valueObj = attributeInSelection.getAttributeValue();
-            if (null == valueObj)
+            synchronized (syncValueChange) {
+                if (syncValueChange.isValueChangeInProgress()) {
+                    return;
+                }
+
+                SimulatorResourceAttribute att = null;
+                if (element instanceof AttributeElement) {
+                    att = ((AttributeElement) element)
+                            .getSimulatorResourceAttribute();
+                }
+
+                if (att == null) {
+                    return;
+                }
+
+                if (Activator.getDefault().getResourceManager()
+                        .isAttHasRangeOrAllowedValues(att)) {
+                    return;
+                }
+
+                AttributeValue val = att.value();
+                if (null == val) {
+                    return;
+                }
+
+                TypeInfo type = val.typeInfo();
+
+                String oldValue = String.valueOf(Utility
+                        .getAttributeValueAsString(val));
+                if (null == oldValue) {
+                    oldValue = "";
+                }
+
+                String newValue = comboBox.getText();
+
+                ((AttributeElement) element).setEditLock(true);
+                compareAndUpdateAttribute(oldValue, newValue,
+                        (AttributeElement) element, att, type);
+                ((AttributeElement) element).setEditLock(false);
+
+            }
+
+        }
+
+        public void compareAndUpdateAttribute(String oldValue, String newValue,
+                AttributeElement attElement, SimulatorResourceAttribute att,
+                TypeInfo type) {
+            if (null == oldValue || null == newValue || null == attElement
+                    || null == att || null == type) {
+                return;
+            }
+
+            synchronized (syncValueChange) {
+                syncValueChange.setValueChangeInProgress(true);
+            }
+
+            if (!oldValue.equals(newValue)) {
+                boolean invalid = false;
+
+                // Get the AttriuteValue from the string
+                AttributeValue attValue = null;
+                try {
+                    attValue = AttributeValueBuilder.build(newValue,
+                            type.mBaseType);
+                } catch (Exception e) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(),
+                                    new Date(),
+                                    "There is an error while creating the new attribute value.\n"
+                                            + Utility.getSimulatorErrorString(
+                                                    e, null));
+                }
+
+                if (null == attValue) {
+                    invalid = true;
+                } else {
+                    TypeInfo resTypeInfo = attValue.typeInfo();
+                    if (type.mDepth != resTypeInfo.mDepth
+                            || type.mType != resTypeInfo.mType
+                            || type.mBaseType != resTypeInfo.mBaseType) {
+                        invalid = true;
+                    }
+                }
+                if (invalid) {
+                    MessageBox dialog = new MessageBox(viewer.getTree()
+                            .getShell(), SWT.ICON_ERROR | SWT.OK);
+                    dialog.setText("Invalid Value");
+                    dialog.setMessage("Given value is invalid");
+                    dialog.open();
+                } else {
+
+                    // To show the new value till decision made.
+                    updateAttributeValue(attElement, att, attValue);
+                    viewer.update(attElement, null);
+
+                    if (callNativeUpdateValue) {
+                        MessageBox dialog = new MessageBox(viewer.getTree()
+                                .getShell(), SWT.ICON_QUESTION | SWT.OK
+                                | SWT.CANCEL);
+                        dialog.setText("Confirm action");
+                        dialog.setMessage("Do you want to modify the value?");
+                        int retval = dialog.open();
+                        if (retval != SWT.OK) {
+                            try {
+                                attValue = AttributeValueBuilder.build(
+                                        oldValue, type.mBaseType);
+                                updateAttributeValue(attElement, att, attValue);
+                            } catch (Exception e) {
+                                Activator
+                                        .getDefault()
+                                        .getLogManager()
+                                        .log(Level.ERROR.ordinal(),
+                                                new Date(),
+                                                "There is an error while updating the attribute value.\n"
+                                                        + Utility
+                                                                .getSimulatorErrorString(
+                                                                        e, null));
+                            }
+                        } else {
+                            ResourceManager resourceManager;
+                            resourceManager = Activator.getDefault()
+                                    .getResourceManager();
+
+                            Resource resource = resourceManager
+                                    .getCurrentResourceInSelection();
+
+                            SimulatorResourceAttribute result = getResultantAttribute(attElement);
+                            if (null == result) {
+                                Activator
+                                        .getDefault()
+                                        .getLogManager()
+                                        .log(Level.ERROR.ordinal(), new Date(),
+                                                "There is an error while updating the attribute value.\n");
+                                return;
+                            }
+
+                            boolean updated = resourceManager
+                                    .attributeValueUpdated(
+                                            (SingleResource) resource,
+                                            result.name(), result.value());
+                            if (!updated) {
+                                try {
+                                    attValue = AttributeValueBuilder.build(
+                                            oldValue, type.mBaseType);
+                                    updateAttributeValue(attElement, att,
+                                            attValue);
+                                } catch (Exception e) {
+                                    Activator
+                                            .getDefault()
+                                            .getLogManager()
+                                            .log(Level.ERROR.ordinal(),
+                                                    new Date(),
+                                                    "There is an error while updating the attribute value.\n"
+                                                            + Utility
+                                                                    .getSimulatorErrorString(
+                                                                            e,
+                                                                            null));
+                                }
+                                MessageDialog
+                                        .openInformation(Display.getDefault()
+                                                .getActiveShell(),
+                                                "Operation failed",
+                                                "Failed to update the attribute value.");
+                            }
+                        }
+                    }
+                }
+            }
+            viewer.update(attElement, null);
+        }
+
+        public void updateAttributeValue(AttributeElement attributeElement,
+                SimulatorResourceAttribute att, AttributeValue value) {
+            if (null == attributeElement || null == att || null == value) {
                 return;
-            String attValue = String.valueOf(valueObj);
-            ((LocalResourceAttribute) element).setAttributeValue(attValue);
-            viewer.update(element, null);
+            }
+
+            attributeElement.getSimulatorResourceAttribute().setValue(value);
+
+            Object parent = attributeElement.getParent();
+            if (null != parent && parent instanceof AttributeElement) {
+                AttributeElement parentElement = (AttributeElement) parent;
+                try {
+                    parentElement.deepSetChildValue(att);
+                } catch (InvalidArgsException e) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(),
+                                    new Date(),
+                                    "There is an error while updating the attribute value.\n"
+                                            + Utility.getSimulatorErrorString(
+                                                    e, null));
+                }
+            }
         }
 
-        public String[] convertListToStringArray(List<String> valueList) {
-            String[] strArr;
-            if (null != valueList && valueList.size() > 0) {
-                strArr = valueList.toArray(new String[1]);
-            } else {
-                strArr = new String[1];
+        public SimulatorResourceAttribute getResultantAttribute(
+                AttributeElement attElement) {
+            if (null == attElement) {
+                return null;
+            }
+
+            SimulatorResourceAttribute result;
+            Object parent = attElement.getParent();
+
+            while (parent != null && parent instanceof AttributeElement) {
+                attElement = (AttributeElement) parent;
+                parent = ((AttributeElement) parent).getParent();
             }
-            return strArr;
+            result = attElement.getSimulatorResourceAttribute();
+
+            return result;
         }
     }
 
-    class AutomationEditor extends EditingSupport {
+    private static class AutomationEditor extends EditingSupport {
 
-        private final TableViewer viewer;
+        private final TreeViewer viewer;
 
-        public AutomationEditor(TableViewer viewer) {
+        public AutomationEditor(TreeViewer viewer) {
             super(viewer);
             this.viewer = viewer;
         }
@@ -182,33 +693,78 @@ public class AttributeEditingSupport {
             // CellEditor is not required as the automation is in progress.
             ResourceManager resourceManager = Activator.getDefault()
                     .getResourceManager();
-            SimulatorResource resource = resourceManager
-                    .getCurrentResourceInSelection();
-            if (null != resource && resource.isResourceAutomationInProgress()) {
+            Resource resource = resourceManager.getCurrentResourceInSelection();
+
+            if (null == resource) {
                 return null;
             }
+
+            if (!(resource instanceof SingleResource)) {
+                return null;
+            }
+            if (((SingleResource) resource).isResourceAutomationInProgress()) {
+                return null;
+            }
+
+            SimulatorResourceAttribute att = null;
+            if (element instanceof AttributeElement) {
+                att = ((AttributeElement) element)
+                        .getSimulatorResourceAttribute();
+            }
+
+            if (null == att) {
+                return null;
+            }
+
+            AttributeValue val = att.value();
+            if (null == val) {
+                return null;
+            }
+
+            TypeInfo type = val.typeInfo();
+
+            if (type.mType == ValueType.RESOURCEMODEL
+                    || type.mType == ValueType.ARRAY) {
+                return null;
+            }
+
+            Object parent = ((AttributeElement) element).getParent();
+            if (null != parent && !(parent instanceof ResourceRepresentation)) {
+                return null;
+            }
+
+            if (((AttributeElement) element).isReadOnly()) {
+                return null;
+            }
+
             return new CheckboxCellEditor(null, SWT.CHECK | SWT.READ_ONLY);
         }
 
         @Override
         protected Object getValue(Object element) {
-            LocalResourceAttribute att = (LocalResourceAttribute) element;
-            return att.isAutomationInProgress();
+            if (element instanceof AttributeElement) {
+                return ((AttributeElement) element).isAutoUpdateInProgress();
+            }
+
+            return false;
         }
 
         @Override
         protected void setValue(Object element, Object value) {
+            if (!(element instanceof AttributeElement)) {
+                return;
+            }
+
             ResourceManager resourceManager = Activator.getDefault()
                     .getResourceManager();
             // As automation depends on the current resource in selection, its
             // presence is being checked.
-            SimulatorResource resource = resourceManager
-                    .getCurrentResourceInSelection();
+            Resource resource = resourceManager.getCurrentResourceInSelection();
             if (null == resource) {
                 return;
             }
 
-            LocalResourceAttribute att = (LocalResourceAttribute) element;
+            AttributeElement att = (AttributeElement) element;
             boolean checked = (Boolean) value;
             if (checked) {
                 // Start the automation
@@ -219,34 +775,28 @@ public class AttributeEditingSupport {
 
                 // Open the settings dialog
                 AutomationSettingDialog dialog = new AutomationSettingDialog(
-                        viewer.getTable().getShell(), automationSettings);
+                        viewer.getTree().getShell(), automationSettings);
                 dialog.create();
                 if (dialog.open() == Window.OK) {
                     String automationType = dialog.getAutomationType();
                     String updateFreq = dialog.getUpdateFrequency();
 
-                    AutomationType autoType = AutomationType
+                    AutoUpdateType autoType = AutoUpdateType
                             .valueOf(automationType);
                     int updFreq = Utility
                             .getUpdateIntervalFromString(updateFreq);
-                    int autoId = resourceManager.startAutomation(resource, att,
-                            autoType, updFreq);
+                    int autoId = resourceManager.startAutomation(
+                            (SingleResource) resource, att, autoType, updFreq);
                     if (autoId == -1) {
                         MessageDialog.openInformation(Display.getDefault()
                                 .getActiveShell(), "Automation Status",
                                 "Automation start failed!!");
-                    } else {
-                        viewer.update(element, null);
                     }
                 }
             } else {
                 // Stop the automation
-                resourceManager.stopAutomation(resource, att,
-                        att.getAutomationId());
-                MessageDialog.openInformation(Display.getDefault()
-                        .getActiveShell(), "Automation Status",
-                        "Automation stopped.");
-                viewer.update(element, null);
+                resourceManager.stopAutomation((SingleResource) resource, att,
+                        att.getAutoUpdateId());
             }
         }
     }
index d4443b4..f3e2e53 100644 (file)
 
 package oic.simulator.serviceprovider.view;
 
-import java.util.List;
-import java.util.Set;
-
-import oic.simulator.serviceprovider.Activator;
-import oic.simulator.serviceprovider.listener.IAutomationUIListener;
-import oic.simulator.serviceprovider.listener.IResourceModelChangedUIListener;
-import oic.simulator.serviceprovider.listener.IResourceSelectionChangedUIListener;
-import oic.simulator.serviceprovider.manager.ResourceManager;
-import oic.simulator.serviceprovider.resource.LocalResourceAttribute;
-import oic.simulator.serviceprovider.resource.ModelChangeNotificationType;
-import oic.simulator.serviceprovider.resource.SimulatorResource;
-import oic.simulator.serviceprovider.utils.Constants;
-
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.StyledCellLabelProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.ILabelProviderListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.ITableLabelProvider;
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.jface.viewers.TreeViewerColumn;
 import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerCell;
+import org.eclipse.jface.window.Window;
 import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.MenuAdapter;
+import org.eclipse.swt.events.MenuEvent;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
 import org.eclipse.swt.graphics.Color;
 import org.eclipse.swt.graphics.Image;
 import org.eclipse.swt.layout.GridData;
@@ -44,56 +38,103 @@ import org.eclipse.swt.layout.GridLayout;
 import org.eclipse.swt.widgets.Composite;
 import org.eclipse.swt.widgets.Display;
 import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.swt.widgets.MenuItem;
+import org.eclipse.swt.widgets.MessageBox;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeColumn;
+import org.eclipse.swt.widgets.TreeItem;
 import org.eclipse.ui.part.ViewPart;
 
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.oic.simulator.ArrayProperty;
+import org.oic.simulator.AttributeProperty;
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.AttributeValue.TypeInfo;
+import org.oic.simulator.AttributeValue.ValueType;
+import org.oic.simulator.ILogger.Level;
+import org.oic.simulator.ModelProperty;
+import org.oic.simulator.SimulatorResourceAttribute;
+import org.oic.simulator.SimulatorResourceModel;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.listener.IAutomationListener;
+import oic.simulator.serviceprovider.listener.IDataChangeListener;
+import oic.simulator.serviceprovider.listener.ISelectionChangedListener;
+import oic.simulator.serviceprovider.manager.ResourceManager;
+import oic.simulator.serviceprovider.manager.UiListenerHandler;
+import oic.simulator.serviceprovider.model.AttributeElement;
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.model.ResourceRepresentation;
+import oic.simulator.serviceprovider.model.SingleResource;
+import oic.simulator.serviceprovider.utils.Constants;
+import oic.simulator.serviceprovider.utils.Utility;
+import oic.simulator.serviceprovider.view.dialogs.ModelArrayAddItemDialog;
+
 /**
  * This class manages and shows the attribute view in the perspective.
  */
 public class AttributeView extends ViewPart {
 
-    public static final String                  VIEW_ID        = "oic.simulator.serviceprovider.view.attribute";
+    public static final String        VIEW_ID        = "oic.simulator.serviceprovider.view.attribute";
 
-    private TableViewer                         attTblViewer;
+    private TreeViewer                attViewer;
 
-    private AttributeEditingSupport             attributeEditor;
+    private AttributeEditingSupport   attributeEditor;
 
-    private IResourceSelectionChangedUIListener resourceSelectionChangedListener;
-    private IResourceModelChangedUIListener     resourceModelChangedUIListener;
-    private IAutomationUIListener               automationUIListener;
+    private ISelectionChangedListener resourceSelectionChangedListener;
+    private IAutomationListener       automationUIListener;
+    private IDataChangeListener       dataChangeListener;
 
-    private final String[]                      attTblHeaders  = { "Name",
-            "Value", "Automation"                             };
-    private final Integer[]                     attTblColWidth = { 150, 190,
-            150                                               };
+    private final String[]            attTblHeaders  = { "Name", "Value",
+            "Automation"                            };
+    private final Integer[]           attTblColWidth = { 150, 190, 150 };
 
-    private ResourceManager                     resourceManager;
+    private ResourceManager           resourceManager;
 
     public AttributeView() {
 
         resourceManager = Activator.getDefault().getResourceManager();
 
-        resourceSelectionChangedListener = new IResourceSelectionChangedUIListener() {
+        resourceSelectionChangedListener = new ISelectionChangedListener() {
 
             @Override
-            public void onResourceSelectionChange() {
+            public void onResourceSelectionChange(final Resource resource) {
                 Display.getDefault().asyncExec(new Runnable() {
-
                     @Override
                     public void run() {
-                        if (null != attTblViewer) {
-                            updateViewer(getData());
-                            SimulatorResource resource = resourceManager
-                                    .getCurrentResourceInSelection();
-                            Table tbl = attTblViewer.getTable();
-                            if (!tbl.isDisposed()) {
-                                if (null != resource
-                                        && resource
-                                                .isResourceAutomationInProgress()) {
-                                    tbl.setEnabled(false);
-                                } else {
-                                    tbl.setEnabled(true);
-                                }
+                        if (null != attViewer) {
+                            Tree tree = attViewer.getTree();
+                            if (null == tree || tree.isDisposed()) {
+                                return;
+                            }
+
+                            // Enabling/disabling the tree based on the resource
+                            // and automation status.
+                            if (resource instanceof SingleResource)
+                                if (((SingleResource) resource)
+                                        .isResourceAutomationInProgress())
+                                    tree.setEnabled(false);
+                                else
+                                    tree.setEnabled(true);
+
+                            if (null != resource
+                                    && null != resource
+                                            .getResourceRepresentation()) {
+                                attViewer.setInput(resource
+                                        .getResourceRepresentation());
+                                attViewer.expandAll();
+                                tree.setLinesVisible(true);
+
+                            } else {
+                                attViewer.setInput(null);
+                                tree.setLinesVisible(false);
                             }
                         }
                     }
@@ -101,80 +142,69 @@ public class AttributeView extends ViewPart {
             }
         };
 
-        resourceModelChangedUIListener = new IResourceModelChangedUIListener() {
+        dataChangeListener = new IDataChangeListener() {
 
             @Override
-            public void onResourceModelChange(
-                    final ModelChangeNotificationType notificationType,
-                    final String resourceURI,
-                    final Set<LocalResourceAttribute> valueChangeSet) {
+            public void add(final AttributeElement attribute) {
                 Display.getDefault().asyncExec(new Runnable() {
                     @Override
                     public void run() {
-                        // Handle the notification only if it is for the current
-                        // resource in selection
-                        SimulatorResource resource = resourceManager
-                                .getCurrentResourceInSelection();
-                        if (null == resource) {
-                            return;
-                        }
-                        if (!resourceURI.equals(resource.getResourceURI())) {
-                            // This notification is for a different resource
-                            // whose attributes are not
-                            // currently not being shown in UI. So ignoring this
-                            // notification.
-                            return;
-                        }
-                        // Refresh the table viewers which will display
-                        // the updated values
-                        if (null != attTblViewer) {
-                            if (notificationType == ModelChangeNotificationType.ATTRIBUTE_ADDED
-                                    || notificationType == ModelChangeNotificationType.ATTRIBUTE_REMOVED) {
-                                updateViewer(getData());
-                            } else if (notificationType == ModelChangeNotificationType.NO_ATTRIBUTES_IN_MODEL) {
-                                attTblViewer.setInput(null);
-                            } else if (notificationType == ModelChangeNotificationType.ATTRIBUTE_VALUE_CHANGED) {
-                                if (null != valueChangeSet) {
-                                    attTblViewer.update(
-                                            valueChangeSet.toArray(), null);
-                                }
-                            }
-                        }
+                        attViewer.refresh(attribute.getParent());
+                        attViewer.expandAll();
+                    }
+                });
+            }
+
+            @Override
+            public void remove(final AttributeElement attribute) {
+                Display.getDefault().asyncExec(new Runnable() {
+                    @Override
+                    public void run() {
+                        attViewer.refresh(attribute.getParent());
+                        attViewer.expandAll();
+                    }
+                });
+            }
+
+            @Override
+            public void update(final AttributeElement attribute) {
+                Display.getDefault().asyncExec(new Runnable() {
+                    @Override
+                    public void run() {
+                        attViewer.update(attribute, null);
+                        attViewer.expandAll();
                     }
                 });
             }
         };
 
-        automationUIListener = new IAutomationUIListener() {
+        automationUIListener = new IAutomationListener() {
 
             @Override
-            public void onResourceAutomationStart(final String resourceURI) {
+            public void onResourceAutomationStart(final SingleResource resource) {
                 Display.getDefault().asyncExec(new Runnable() {
 
                     @Override
                     public void run() {
-                        if (null == resourceURI) {
+                        if (null == resource || null == attViewer) {
                             return;
                         }
-                        SimulatorResource resource = resourceManager
+                        Resource resourceInSelection = resourceManager
                                 .getCurrentResourceInSelection();
-                        if (null == resource) {
+                        if (null == resourceInSelection) {
                             return;
                         }
-                        String uri = resource.getResourceURI();
                         // Checking whether attributes view is currently
                         // displaying the attributes of the
                         // resource whose automation has just started
-                        if (null != uri && uri.equals(resourceURI)) {
-                            Table tbl;
-                            tbl = attTblViewer.getTable();
-                            if (!tbl.isDisposed()) {
-                                attTblViewer.refresh();
-
+                        if (resource == resourceInSelection) {
+                            Tree tree;
+                            tree = attViewer.getTree();
+                            if (!tree.isDisposed()) {
                                 // Disabling the table to prevent interactions
                                 // during the automation
-                                tbl.setEnabled(false);
-                                tbl.deselectAll();
+                                tree.setEnabled(false);
+                                tree.deselectAll();
                             }
                         }
                     }
@@ -182,7 +212,7 @@ public class AttributeView extends ViewPart {
             }
 
             @Override
-            public void onAutomationComplete(final String resourceURI,
+            public void onAutomationComplete(final SingleResource resource,
                     final String attName) {
                 // This method notifies the completion of attribute level
                 // automation.
@@ -190,41 +220,21 @@ public class AttributeView extends ViewPart {
 
                     @Override
                     public void run() {
-                        if (null == resourceURI) {
+                        if (null == resource) {
                             return;
                         }
                         // Check if the given resourceURI is the uri of the
                         // resource whose attributes are currently being
                         // displayed by this view.
-                        SimulatorResource resource = resourceManager
+                        Resource resourceInSelection = resourceManager
                                 .getCurrentResourceInSelection();
-                        if (null == resource) {
+                        if (resource != resourceInSelection) {
                             return;
                         }
-                        String uri = resource.getResourceURI();
-                        if (null == uri || !uri.equals(resourceURI)) {
-                            return;
-                        }
-                        Table tbl;
-                        tbl = attTblViewer.getTable();
-                        if (!tbl.isDisposed()) {
-                            if (null != attName) {
-                                // Attribute level automation has stopped
-                                LocalResourceAttribute att = resourceManager
-                                        .getAttributeByResourceURI(resourceURI,
-                                                attName);
-                                if (null == att) {
-                                    return;
-                                } else {
-                                    attTblViewer.update(att, null);
-                                }
-                            } else {
-                                // Resource level automation has stopped
-                                // Enabling the table which was disabled at the
-                                // beginning of automation
-                                tbl.setEnabled(true);
-                                attTblViewer.refresh();
-                            }
+                        Tree tree;
+                        tree = attViewer.getTree();
+                        if (!tree.isDisposed()) {
+                            tree.setEnabled(true);
                         }
                     }
                 });
@@ -247,154 +257,673 @@ public class AttributeView extends ViewPart {
         attGroup.setText("Attributes");
         attGroup.setBackground(color);
 
-        attTblViewer = new TableViewer(attGroup, SWT.SINGLE | SWT.H_SCROLL
-                | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
+        Tree addressTree = new Tree(attGroup, SWT.SINGLE | SWT.BORDER
+                | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
+        addressTree.setHeaderVisible(true);
 
-        createAttributeColumns(attTblViewer);
+        attViewer = new TreeViewer(addressTree);
+
+        createAttributeColumns(attViewer);
 
         // make lines and header visible
-        Table table = attTblViewer.getTable();
-        table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-        table.setHeaderVisible(true);
-        table.setLinesVisible(true);
+        Tree tree = attViewer.getTree();
+        tree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+        tree.setHeaderVisible(true);
+        tree.setLinesVisible(true);
 
-        attTblViewer.setContentProvider(new AttributeContentProvider());
+        attViewer.setContentProvider(new AttributeContentProvider());
+        attViewer.setLabelProvider(new AttributeLabelProvider());
 
         addManagerListeners();
 
         // Check whether there is any resource selected already
-        List<LocalResourceAttribute> propertyList = getData();
-        if (null != propertyList) {
-            updateViewer(propertyList);
+        Resource resource = resourceManager.getCurrentResourceInSelection();
+        if (resource != null) {
+            attViewer.setInput(resource.getResourceRepresentation());
         }
     }
 
-    public void createAttributeColumns(TableViewer tableViewer) {
+    public void createAttributeColumns(TreeViewer viewer) {
+        Tree tree = viewer.getTree();
 
         attributeEditor = new AttributeEditingSupport();
 
-        TableViewerColumn attName = new TableViewerColumn(tableViewer, SWT.NONE);
-        attName.getColumn().setWidth(attTblColWidth[0]);
-        attName.getColumn().setText(attTblHeaders[0]);
-        attName.setLabelProvider(new StyledCellLabelProvider() {
-            @Override
-            public void update(ViewerCell cell) {
-                Object element = cell.getElement();
-                if (element instanceof LocalResourceAttribute) {
-                    LocalResourceAttribute attribute = (LocalResourceAttribute) element;
-                    if (null != attribute) {
-                        cell.setText(attribute.getAttributeName());
-                    }
+        TreeColumn attName = new TreeColumn(tree, SWT.NONE);
+        attName.setWidth(attTblColWidth[0]);
+        attName.setText(attTblHeaders[0]);
+
+        TreeColumn attValue = new TreeColumn(tree, SWT.NONE);
+        attValue.setWidth(attTblColWidth[1]);
+        attValue.setText(attTblHeaders[1]);
+
+        TreeViewerColumn attValueVwrCol = new TreeViewerColumn(attViewer,
+                attValue);
+        attValueVwrCol.setEditingSupport(attributeEditor
+                .createAttributeValueEditor(attViewer, true));
+
+        TreeColumn automation = new TreeColumn(tree, SWT.NONE);
+        automation.setWidth(attTblColWidth[2]);
+        automation.setText(attTblHeaders[2]);
+        TreeViewerColumn automationVwrCol = new TreeViewerColumn(attViewer,
+                automation);
+        automationVwrCol.setEditingSupport(attributeEditor
+                .createAutomationEditor(attViewer));
+
+        addColumnListeners();
+
+        addMenuItems();
+    }
+
+    private void addColumnListeners() {
+        TreeColumn[] columns = attViewer.getTree().getColumns();
+        for (TreeColumn column : columns) {
+            column.addSelectionListener(new SelectionAdapter() {
+                @Override
+                public void widgetSelected(SelectionEvent e) {
+                    // Refreshing the viewer. If combo list is open,
+                    // then click events on other parts of the view or outside
+                    // the combo should hide the editor.
+                    // Refreshing the viewer hides the combo and other editors
+                    // which are active.
+                    attViewer.refresh();
                 }
+            });
+        }
+    }
+
+    private void addMenuItems() {
+        if (null != attViewer) {
+            final Tree resourceTreeHead = attViewer.getTree();
+            if (null != resourceTreeHead) {
+                // Below code creates menu entries and shows them on right
+                // clicking a resource
+                final Menu menu = new Menu(resourceTreeHead);
+                resourceTreeHead.setMenu(menu);
+                menu.addMenuListener(new MenuAdapter() {
+                    @Override
+                    public void menuShown(MenuEvent e) {
+                        // Clear existing menu items
+                        MenuItem[] items = menu.getItems();
+                        for (int index = 0; index < items.length; index++) {
+                            items[index].dispose();
+                        }
+
+                        IStructuredSelection selection = ((IStructuredSelection) attViewer
+                                .getSelection());
+                        final AttributeElement attElement = (AttributeElement) selection
+                                .getFirstElement();
+                        if (null == attElement) {
+                            return;
+                        }
+
+                        // Check the type of attribute.
+                        SimulatorResourceAttribute attribute = attElement
+                                .getSimulatorResourceAttribute();
+                        if (null == attribute) {
+                            return;
+                        }
+
+                        AttributeValue value = attribute.value();
+                        if (null == value || null == value.get()) {
+                            return;
+                        }
+
+                        TypeInfo type = value.typeInfo();
+
+                        final Object parent = attElement.getParent();
+
+                        if ((type.mType == ValueType.ARRAY
+                                && type.mBaseType == ValueType.RESOURCEMODEL && type.mDepth == 1)
+                                && (null == parent || parent instanceof ResourceRepresentation)) {
+                            addMenuToOneDimensionalTopLevelModelAttributes(menu);
+                            return;
+                        }
+
+                        if (null != parent
+                                && parent instanceof AttributeElement) {
+                            Object grandParent = ((AttributeElement) parent)
+                                    .getParent();
+                            if (null == grandParent
+                                    || grandParent instanceof ResourceRepresentation) {
+                                AttributeElement parentElement = (AttributeElement) parent;
+
+                                // Check the type of attribute.
+                                SimulatorResourceAttribute parentAttribute = parentElement
+                                        .getSimulatorResourceAttribute();
+                                if (null != parentAttribute
+                                        && null != parentAttribute.value()
+                                        && null != parentAttribute.value()
+                                                .get()) {
+                                    AttributeValue parentValue = parentAttribute
+                                            .value();
+
+                                    TypeInfo parentType = parentValue
+                                            .typeInfo();
+                                    if (parentType.mType == ValueType.ARRAY
+                                            && parentType.mBaseType == ValueType.RESOURCEMODEL
+                                            && parentType.mDepth == 1) {
+                                        addDeleteMenuToArrayItemsOfOneDimensionalModelAttribute(
+                                                menu, attElement, parentElement);
+                                        return;
+                                    }
+                                }
+                            }
+                        }
+
+                    }
+                });
             }
-        });
+        }
+    }
 
-        TableViewerColumn attValue = new TableViewerColumn(tableViewer,
-                SWT.NONE);
-        attValue.getColumn().setWidth(attTblColWidth[1]);
-        attValue.getColumn().setText(attTblHeaders[1]);
-        attValue.setLabelProvider(new ColumnLabelProvider() {
+    private void addMenuToOneDimensionalTopLevelModelAttributes(Menu menu) {
+        // Menu to add items to the array.
+        MenuItem addItems = new MenuItem(menu, SWT.NONE);
+        addItems.setText("Add Items");
+        addItems.addSelectionListener(new SelectionAdapter() {
             @Override
-            public String getText(Object element) {
-                if (element instanceof LocalResourceAttribute) {
-                    LocalResourceAttribute attribute = (LocalResourceAttribute) element;
-                    if (null != attribute) {
-                        Object val = attribute.getAttributeValue();
-                        if (null != val) {
-                            return String.valueOf(val);
+            public void widgetSelected(SelectionEvent e) {
+                // Get the attributes.
+                ResourceRepresentation representation;
+                representation = getRepresentationForOneDimensionTopLevelAttribute();
+                if (null == representation) {
+                    MessageDialog
+                            .openError(Display.getDefault().getActiveShell(),
+                                    "Unable to perform the operation.",
+                                    "Failed to obtain the required data. Operation cannot be performed.");
+                } else {
+                    // Check whether a new item can be added to the array by
+                    // checking
+                    // the array property of the current attribute in
+                    // selection(Model Array type attribute).
+                    AttributeElement attElement = getSelectedElement();
+                    if (null == attElement) {
+                        MessageDialog
+                                .openError(Display.getDefault()
+                                        .getActiveShell(),
+                                        "Unable to perform the operation.",
+                                        "Failed to obtain the required data. Operation cannot be performed.");
+                        return;
+                    }
+
+                    SimulatorResourceAttribute attribute = attElement
+                            .getSimulatorResourceAttribute();
+
+                    AttributeValue attValue = attribute.value();
+                    AttributeProperty attProperty = attribute.property();
+                    if (null != attProperty
+                            && attProperty instanceof ArrayProperty) {
+                        ArrayProperty prop = attProperty.asArray();
+                        if (null != prop && !prop.isVariable()) {
+                            SimulatorResourceModel[] model = (SimulatorResourceModel[]) attValue
+                                    .get();
+                            if (null != model
+                                    && model.length >= prop.maxItems()) {
+                                MessageDialog
+                                        .openError(
+                                                Display.getDefault()
+                                                        .getActiveShell(),
+                                                "Unable to perform the operation.",
+                                                "Exceeding the maximum number of array elements allowed for this attribute.\n"
+                                                        + "Maximum number of allowed array element(s): "
+                                                        + prop.maxItems());
+                                return;
+                            }
+                        }
+                    }
+
+                    ModelArrayAddItemDialog dialog = new ModelArrayAddItemDialog(
+                            Display.getDefault().getActiveShell(),
+                            representation);
+                    if (Window.OK == dialog.open()) {
+                        // Add the new item to the local resource
+                        // representation.
+                        AttributeElement newElement = (AttributeElement) representation
+                                .getAttributes().values().toArray()[0];
+                        SimulatorResourceAttribute newAttribute = newElement
+                                .getSimulatorResourceAttribute();
+                        SimulatorResourceModel newModel = (SimulatorResourceModel) newAttribute
+                                .value().get();
+
+                        SimulatorResourceModel[] modelArray = (SimulatorResourceModel[]) attribute
+                                .value().get();
+                        SimulatorResourceModel[] newModelArray = new SimulatorResourceModel[modelArray.length + 1];
+
+                        int i;
+                        for (i = 0; i < modelArray.length; i++) {
+                            newModelArray[i] = modelArray[i];
+                        }
+                        newModelArray[i] = newModel;
+
+                        AttributeValue newValue = new AttributeValue(
+                                newModelArray);
+
+                        newAttribute.setValue(newValue);
+
+                        newAttribute.setProperty(attribute.property());
+
+                        attElement.update(newAttribute);
+
+                        boolean updated = resourceManager.attributeValueUpdated(
+                                (SingleResource) resourceManager
+                                        .getCurrentResourceInSelection(),
+                                attribute.name(), newValue);
+
+                        if (!updated) {
+                            attribute.setValue(new AttributeValue(modelArray));
+                            attElement.update(newAttribute);
+
+                            MessageDialog
+                                    .openInformation(Display.getDefault()
+                                            .getActiveShell(),
+                                            "Operation failed",
+                                            "Failed to insert a new item in the array.");
+                        } else {
+                            // Highlight the newly added item.
+                            if (attElement.hasChildren()) {
+                                AttributeElement addedElement = attElement
+                                        .getChildren().get("[" + i + "]");
+                                attViewer.setSelection(new StructuredSelection(
+                                        addedElement), true);
+                            }
                         }
                     }
                 }
-                return "";
             }
         });
-        attValue.setEditingSupport(attributeEditor
-                .createAttributeValueEditor(attTblViewer));
-
-        TableViewerColumn automation = new TableViewerColumn(tableViewer,
-                SWT.NONE);
-        automation.getColumn().setWidth(attTblColWidth[2]);
-        automation.getColumn().setText(attTblHeaders[2]);
-        automation.setLabelProvider(new ColumnLabelProvider() {
+    }
+
+    private void addDeleteMenuToArrayItemsOfOneDimensionalModelAttribute(
+            final Menu menu, final AttributeElement elementToDelete,
+            final AttributeElement parentElement) {
+        // Menu to add items to the array.
+        MenuItem addItems = new MenuItem(menu, SWT.NONE);
+        addItems.setText("Delete Item");
+        addItems.addSelectionListener(new SelectionAdapter() {
             @Override
-            public String getText(Object element) {
-                LocalResourceAttribute att = (LocalResourceAttribute) element;
-                if (att.isAutomationInProgress()) {
-                    return Constants.ENABLED;
+            public void widgetSelected(SelectionEvent e) {
+                // Check whether any existing item can be removed from the array
+                // by checking
+                // the array property of the current attribute in
+                // selection(Model Array type attribute).
+                SimulatorResourceAttribute parentSRA = parentElement
+                        .getSimulatorResourceAttribute();
+                AttributeValue value = parentSRA.value();
+                AttributeProperty attProperty = parentSRA.property();
+                if (null != attProperty && attProperty instanceof ArrayProperty) {
+                    ArrayProperty prop = attProperty.asArray();
+                    if (null != prop) {
+                        SimulatorResourceModel[] model = (SimulatorResourceModel[]) value
+                                .get();
+                        if (null != model && model.length <= prop.minItems()) {
+                            MessageDialog
+                                    .openError(
+                                            Display.getDefault()
+                                                    .getActiveShell(),
+                                            "Unable to perform the operation.",
+                                            "Violating the minimum number of array elements allowed for this attribute.\n"
+                                                    + "Minimum number of allowed array element(s): "
+                                                    + prop.minItems());
+                            return;
+                        }
+                    }
                 }
-                return Constants.DISABLED;
-            }
 
-            @Override
-            public Image getImage(Object element) {
-                LocalResourceAttribute att = (LocalResourceAttribute) element;
-                if (att.isAutomationInProgress()) {
-                    return Activator.getDefault().getImageRegistry()
-                            .get(Constants.CHECKED);
-                } else {
-                    return Activator.getDefault().getImageRegistry()
-                            .get(Constants.UNCHECKED);
+                MessageBox dialog = new MessageBox(menu.getShell(),
+                        SWT.ICON_QUESTION | SWT.OK | SWT.CANCEL);
+                dialog.setText("Confirm action");
+                dialog.setMessage("Do you want to delete this item from the array?");
+                int retval = dialog.open();
+                if (retval != SWT.OK) {
+                    return;
+                }
+
+                // Removing the element from the attribute value.
+                SimulatorResourceModel[] modelArray = (SimulatorResourceModel[]) value
+                        .get();
+
+                String elementIndexName = elementToDelete
+                        .getSimulatorResourceAttribute().name();
+                int elementIndex = Integer.parseInt(elementIndexName.substring(
+                        elementIndexName.indexOf('[') + 1,
+                        elementIndexName.indexOf(']')));
+
+                SimulatorResourceModel[] newModelArray = new SimulatorResourceModel[modelArray.length - 1];
+                int sIndex = 0, dIndex = 0;
+                for (SimulatorResourceModel model : modelArray) {
+                    if (sIndex != elementIndex)
+                        newModelArray[dIndex++] = model;
+                    sIndex++;
+                }
+
+                // Setting the new model array in the attribute.
+                AttributeValue newValue = new AttributeValue(newModelArray);
+                parentSRA.setValue(newValue);
+
+                // Removing the element from the child map.
+                Map<String, AttributeElement> elements = parentElement
+                        .getChildren();
+                if (null == elements) {
+                    MessageDialog
+                            .openError(Display.getDefault().getActiveShell(),
+                                    "Operation failed.",
+                                    "There is an error while removing the array items.");
+                    return;
+                }
+
+                List<AttributeElement> attElementList = new ArrayList<AttributeElement>();
+                attElementList.addAll(elements.values());
+                Collections.sort(attElementList, Utility.attributeComparator);
+
+                // Renaming the index of the elements.
+                AttributeElement[] attElementArray = attElementList
+                        .toArray(new AttributeElement[0]);
+                boolean deleted = false;
+                int index, newIndex;
+                for (index = 0, newIndex = 0; index < attElementArray.length; index++) {
+                    if (index == elementIndex) {
+                        elements.remove(elementIndexName);
+                        deleted = true;
+                    } else {
+                        if (deleted) {
+                            AttributeElement element = attElementArray[index];
+                            String curIndexStr = "[" + index + "]";
+                            String newIndexStr = "[" + newIndex + "]";
+
+                            element.getSimulatorResourceAttribute().setName(
+                                    newIndexStr);
+
+                            elements.remove(curIndexStr);
+                            elements.put(newIndexStr, element);
+                        }
+                        newIndex++;
+                    }
                 }
+
+                resourceManager.attributeValueUpdated(
+                        (SingleResource) resourceManager
+                                .getCurrentResourceInSelection(), parentSRA
+                                .name(), newValue);
+
+                attViewer.refresh(parentElement);
             }
         });
-        automation.setEditingSupport(attributeEditor
-                .createAutomationEditor(attTblViewer));
     }
 
-    private void addManagerListeners() {
-        resourceManager
-                .addResourceSelectionChangedUIListener(resourceSelectionChangedListener);
-        resourceManager
-                .addResourceModelChangedUIListener(resourceModelChangedUIListener);
-        resourceManager.addAutomationUIListener(automationUIListener);
+    private ResourceRepresentation getRepresentationForOneDimensionTopLevelAttribute() {
+        ResourceRepresentation representation;
+
+        AttributeValue value = null;
+        ModelProperty property = null;
+        SimulatorResourceAttribute attribute;
+
+        AttributeElement element = getSelectedElement();
+        if (null == element)
+            return null;
+
+        SimulatorResourceAttribute modelArrayAtt = element
+                .getSimulatorResourceAttribute();
+        if (null == modelArrayAtt) {
+            return null;
+        }
+
+        AttributeValue attValue = modelArrayAtt.value();
+        if (null == attValue) {
+            return null;
+        }
+
+        TypeInfo type = attValue.typeInfo();
+
+        if (!(type.mType == ValueType.ARRAY
+                && type.mBaseType == ValueType.RESOURCEMODEL && type.mDepth == 1)) {
+            return null;
+        }
+
+        SimulatorResourceModel[] modelValue = (SimulatorResourceModel[]) attValue
+                .get();
+        if (null == modelValue || modelValue.length < 0) {
+            return null;
+        }
+
+        // Clone an instance of model value.
+        try {
+            value = Utility.cloneAttributeValue(new AttributeValue(
+                    modelValue[0]));
+        } catch (Exception e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "There is an error while creating an instance of the model element.\n"
+                                    + Utility.getSimulatorErrorString(e, null));
+        }
+
+        if (null == value) {
+            return null;
+        }
+
+        // Get the model property of the model value instance.
+        AttributeProperty attProperty = modelArrayAtt.property();
+        if (null != attProperty && attProperty instanceof ArrayProperty) {
+            ArrayProperty prop = attProperty.asArray();
+            if (null != prop) {
+                AttributeProperty elementProperty = prop.getElementProperty();
+                if (null != elementProperty && elementProperty.isModel()) {
+                    property = elementProperty.asModel();
+                }
+            }
+        }
+
+        attribute = new SimulatorResourceAttribute(modelArrayAtt.name(), value,
+                property);
+
+        Map<String, SimulatorResourceAttribute> attributes = new HashMap<String, SimulatorResourceAttribute>();
+        attributes.put(attribute.name(), attribute);
+
+        representation = new ResourceRepresentation(attributes);
+
+        return representation;
     }
 
-    private List<LocalResourceAttribute> getData() {
-        SimulatorResource resourceInSelection = resourceManager
-                .getCurrentResourceInSelection();
-        if (null != resourceInSelection) {
-            List<LocalResourceAttribute> attList = resourceManager
-                    .getAttributes(resourceInSelection);
-            return attList;
-        } else {
+    private AttributeElement getSelectedElement() {
+        IStructuredSelection selection = (IStructuredSelection) attViewer
+                .getSelection();
+        if (null == selection) {
+            return null;
+        }
+
+        Object obj = selection.getFirstElement();
+        if (null == obj) {
             return null;
         }
+
+        Tree t = attViewer.getTree();
+        TreeItem item = t.getSelection()[0];
+        if (null == item) {
+            return null;
+        }
+
+        if (!(item.getData() instanceof AttributeElement)) {
+            return null;
+        }
+
+        return (AttributeElement) item.getData();
     }
 
-    private void updateViewer(List<LocalResourceAttribute> attList) {
-        Table tbl;
-        if (null != attList) {
-            tbl = attTblViewer.getTable();
-            if (null != tbl && !tbl.isDisposed()) {
-                tbl.setLinesVisible(true);
-                attTblViewer.setInput(attList.toArray());
-            }
-        } else {
-            // Clear the attributes table viewer
-            if (null != attTblViewer) {
-                tbl = attTblViewer.getTable();
-                if (null != tbl && !tbl.isDisposed()) {
-                    // tbl.deselectAll();
-                    tbl.removeAll();
-                    tbl.setLinesVisible(false);
+    private void addManagerListeners() {
+        UiListenerHandler.getInstance().addResourceSelectionChangedUIListener(
+                resourceSelectionChangedListener);
+        UiListenerHandler.getInstance().addDataChangeListener(
+                dataChangeListener);
+        UiListenerHandler.getInstance().addAutomationUIListener(
+                automationUIListener);
+    }
+
+    private static class AttributeContentProvider implements
+            ITreeContentProvider {
+
+        @Override
+        public void dispose() {
+        }
+
+        @Override
+        public void inputChanged(Viewer viewer, Object oldAttribute,
+                Object newAttribute) {
+        }
+
+        @Override
+        public Object[] getChildren(Object attribute) {
+            if (attribute instanceof AttributeElement) {
+                List<AttributeElement> attElementList = new ArrayList<AttributeElement>();
+                Map<String, AttributeElement> children = ((AttributeElement) attribute)
+                        .getChildren();
+                if (null != children) {
+                    attElementList.addAll(children.values());
+                    Collections.sort(attElementList,
+                            Utility.attributeComparator);
+                    return attElementList.toArray();
                 }
             }
+
+            return new Object[0];
+        }
+
+        @Override
+        public Object getParent(Object attribute) {
+            if (attribute instanceof AttributeElement)
+                return ((AttributeElement) attribute).getParent();
+            return null;
+        }
+
+        @Override
+        public boolean hasChildren(Object attribute) {
+            if (attribute instanceof AttributeElement)
+                return ((AttributeElement) attribute).hasChildren();
+            return false;
+        }
+
+        @Override
+        public Object[] getElements(Object resourceModel) {
+            if (resourceModel instanceof ResourceRepresentation) {
+                return ((ResourceRepresentation) resourceModel).getAttributes()
+                        .values().toArray();
+            }
+
+            return new Object[0];
         }
     }
 
-    class AttributeContentProvider implements IStructuredContentProvider {
+    class AttributeLabelProvider implements ITableLabelProvider {
+
+        @Override
+        public void addListener(ILabelProviderListener arg0) {
+        }
 
         @Override
         public void dispose() {
         }
 
         @Override
-        public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
+        public boolean isLabelProperty(Object arg0, String arg1) {
+            return false;
+        }
+
+        @Override
+        public void removeListener(ILabelProviderListener arg0) {
+
+        }
+
+        @Override
+        public Image getColumnImage(Object element, int col) {
+            if (col == 2) {
+                if (element instanceof AttributeElement) {
+                    // Ignore for non-single resource
+                    Resource res = resourceManager
+                            .getCurrentResourceInSelection();
+                    if (res instanceof SingleResource) {
+                        AttributeElement attrElement = (AttributeElement) element;
+                        if (attrElement.isAutoUpdateSupport()
+                                && !attrElement.isReadOnly()) {
+                            if (attrElement.isAutoUpdateInProgress()) {
+                                return Activator.getDefault()
+                                        .getImageRegistry()
+                                        .get(Constants.CHECKED);
+                            } else {
+                                return Activator.getDefault()
+                                        .getImageRegistry()
+                                        .get(Constants.UNCHECKED);
+                            }
+                        }
+                    }
+                }
+            }
+            return null;
         }
 
         @Override
-        public Object[] getElements(Object element) {
-            return (Object[]) element;
+        public String getColumnText(Object element, int column) {
+            if (element instanceof AttributeElement) {
+                AttributeElement attrElement = (AttributeElement) element;
+                switch (column) {
+                    case 0: // Attribute name column
+                    {
+                        SimulatorResourceAttribute attribute = attrElement
+                                .getSimulatorResourceAttribute();
+                        return attribute.name();
+                    }
+
+                    case 1: // Attribute value column
+                    {
+                        SimulatorResourceAttribute attribute = attrElement
+                                .getSimulatorResourceAttribute();
+
+                        if (attribute.value().typeInfo().mBaseType != ValueType.RESOURCEMODEL) {
+                            String value = Utility
+                                    .getAttributeValueAsString(attribute
+                                            .value());
+                            if (null == value) {
+                                value = "";
+                            }
+                            return value;
+                        }
+                        return null;
+                    }
+
+                    case 2: {
+                        // Ignore for non-single resource
+                        Resource res = resourceManager
+                                .getCurrentResourceInSelection();
+                        if (res instanceof SingleResource) {
+                            SimulatorResourceAttribute attribute = attrElement
+                                    .getSimulatorResourceAttribute();
+                            TypeInfo type = attribute.value().typeInfo();
+                            if (type.mType == AttributeValue.ValueType.ARRAY) {
+                                if (type.mBaseType != AttributeValue.ValueType.RESOURCEMODEL) {
+                                    return "NA";
+                                }
+                            } else if (type.mType != AttributeValue.ValueType.RESOURCEMODEL) {
+                                Object parent = attrElement.getParent();
+                                if (null != parent
+                                        && !(parent instanceof ResourceRepresentation)) {
+                                    return "NA";
+                                } else if (attrElement.isReadOnly()) {
+                                    return "NA";
+                                } else if (attrElement.isAutoUpdateSupport()) {
+                                    if (attrElement.isAutoUpdateInProgress())
+                                        return Constants.ENABLED;
+                                    else
+                                        return Constants.DISABLED;
+                                }
+                            }
+                        }
+
+                        return "";
+                    }
+                }
+            }
+
+            return null;
         }
 
     }
@@ -403,19 +932,21 @@ public class AttributeView extends ViewPart {
     public void dispose() {
         // Unregister the selection listener
         if (null != resourceSelectionChangedListener) {
-            resourceManager
-                    .removeResourceSelectionChangedUIListener(resourceSelectionChangedListener);
+            UiListenerHandler.getInstance()
+                    .removeResourceSelectionChangedUIListener(
+                            resourceSelectionChangedListener);
         }
 
-        // Unregister the model change listener
-        if (null != resourceModelChangedUIListener) {
-            resourceManager
-                    .removeResourceModelChangedUIListener(resourceModelChangedUIListener);
+        // Unregister the data model change listener
+        if (null != dataChangeListener) {
+            UiListenerHandler.getInstance().removeDataChangeListener(
+                    dataChangeListener);
         }
 
         // Unregister the automation complete listener
         if (null != automationUIListener) {
-            resourceManager.removeAutomationUIListener(automationUIListener);
+            UiListenerHandler.getInstance().removeAutomationUIListener(
+                    automationUIListener);
         }
 
         super.dispose();
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/DevicePlatformInfoView.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/DevicePlatformInfoView.java
new file mode 100644 (file)
index 0000000..c5357ac
--- /dev/null
@@ -0,0 +1,447 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.view;
+
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.CellEditor;
+import org.eclipse.jface.viewers.ColumnLabelProvider;
+import org.eclipse.jface.viewers.EditingSupport;
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.StyledCellLabelProvider;
+import org.eclipse.jface.viewers.TableViewer;
+import org.eclipse.jface.viewers.TableViewerColumn;
+import org.eclipse.jface.viewers.TextCellEditor;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerCell;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.CTabFolder;
+import org.eclipse.swt.custom.CTabItem;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.ui.part.ViewPart;
+
+import java.util.List;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.listener.IDeviceInfoListener;
+import oic.simulator.serviceprovider.manager.UiListenerHandler;
+import oic.simulator.serviceprovider.model.MetaProperty;
+import oic.simulator.serviceprovider.utils.Constants;
+
+/**
+ * This class is used to set the platform and device information. The
+ * information is only one per stack and hence only one instance can be
+ * stored/used at a time.
+ */
+public class DevicePlatformInfoView extends ViewPart {
+
+    public static final String VIEW_ID       = "oic.simulator.serviceprovider.view.devplatinfo";
+
+    private final String[]     columnHeaders = { "Property", "Value" };
+
+    private final Integer[]    columnWidth   = { 150, 150 };
+
+    enum PropertiesType {
+        DEVICE, PLATFORM
+    }
+
+    private List<MetaProperty>  deviceProperties;
+    private List<MetaProperty>  platformProperties;
+
+    private boolean             enableDeviceEdit;
+    private boolean             enablePlatformEdit;
+
+    private Button              devEditBtn;
+    private Button              devCancelBtn;
+    private Button              platEditBtn;
+    private Button              platCancelBtn;
+
+    private TableViewer         platformTblViewer;
+    private TableViewer         deviceTblViewer;
+
+    private CTabFolder          folder;
+    private CTabItem            devicePropTab;
+    private CTabItem            platformPropTab;
+
+    private IDeviceInfoListener deviceInfoUIListener;
+
+    public DevicePlatformInfoView() {
+        deviceInfoUIListener = new IDeviceInfoListener() {
+
+            @Override
+            public void onDeviceInfoFound() {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        if (null != deviceTblViewer) {
+                            updateViewer(deviceTblViewer, getDevicePropData());
+                        }
+                    }
+                });
+            }
+        };
+
+        addManagerListeners();
+    }
+
+    @Override
+    public void createPartControl(Composite parent) {
+        parent.setLayout(new GridLayout());
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        parent.setLayoutData(gd);
+
+        // Create a Tab Folder.
+        folder = new CTabFolder(parent, SWT.BORDER);
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        folder.setLayoutData(gd);
+        folder.setSimple(false);
+        folder.setUnselectedCloseVisible(false);
+        folder.setUnselectedImageVisible(false);
+
+        createDevicePropertiesTab();
+
+        createPlatformPropertiesTab();
+
+        folder.setSelection(devicePropTab);
+
+        platformProperties = getPlatformPropData();
+
+        updateViewer(platformTblViewer, platformProperties);
+
+        deviceProperties = getDevicePropData();
+
+        updateViewer(deviceTblViewer, deviceProperties);
+    }
+
+    private void addManagerListeners() {
+        UiListenerHandler.getInstance().addDeviceInfoUIListener(
+                deviceInfoUIListener);
+    }
+
+    private void createDevicePropertiesTab() {
+        devicePropTab = new CTabItem(folder, SWT.NULL);
+        devicePropTab.setText("Device");
+
+        // Adding the group to the folder.
+        Group propGroup = new Group(folder, SWT.NONE);
+
+        Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
+        propGroup.setBackground(color);
+
+        propGroup.setLayout(new GridLayout(2, false));
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        propGroup.setLayoutData(gd);
+
+        deviceTblViewer = new TableViewer(propGroup, SWT.SINGLE | SWT.H_SCROLL
+                | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
+
+        createColumns(deviceTblViewer, PropertiesType.DEVICE);
+
+        // Make lines and header visible
+        final Table table = deviceTblViewer.getTable();
+        table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+        table.setHeaderVisible(true);
+        table.setLinesVisible(true);
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        gd.horizontalSpan = 2;
+        table.setLayoutData(gd);
+
+        deviceTblViewer.setContentProvider(new PropertycontentProvider());
+
+        devEditBtn = new Button(propGroup, SWT.PUSH);
+        devEditBtn.setText("Edit");
+        gd = new GridData();
+        gd.widthHint = 50;
+        devEditBtn.setLayoutData(gd);
+        devEditBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                if (devEditBtn.getText().equals("Edit")) {
+                    devCancelBtn.setEnabled(true);
+                    devEditBtn.setText("Save");
+                    enableDeviceEdit = true;
+                } else {
+                    if (Activator.getDefault().getResourceManager()
+                            .isDeviceInfoValid(deviceProperties)) {
+                        Activator.getDefault().getResourceManager()
+                                .setDeviceInfo(deviceProperties);
+                        devCancelBtn.setEnabled(false);
+                        devEditBtn.setText("Edit");
+                        enableDeviceEdit = false;
+                    } else {
+                        MessageDialog.openError(Display.getDefault()
+                                .getActiveShell(), "Invalid value",
+                                "Property value cannot be empty.");
+                    }
+                }
+            }
+        });
+
+        devCancelBtn = new Button(propGroup, SWT.PUSH);
+        devCancelBtn.setText("Cancel");
+        devCancelBtn.setEnabled(false);
+        gd = new GridData();
+        gd.widthHint = 70;
+        devCancelBtn.setLayoutData(gd);
+        devCancelBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                deviceProperties = getDevicePropData();
+                updateViewer(deviceTblViewer, deviceProperties);
+
+                devCancelBtn.setEnabled(false);
+                devEditBtn.setText("Edit");
+                enableDeviceEdit = false;
+            }
+        });
+
+        devicePropTab.setControl(propGroup);
+    }
+
+    private void createPlatformPropertiesTab() {
+        platformPropTab = new CTabItem(folder, SWT.NULL);
+        platformPropTab.setText("Platform");
+
+        // Adding the group to the folder.
+        Group propGroup = new Group(folder, SWT.NONE);
+
+        Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
+        propGroup.setBackground(color);
+
+        propGroup.setLayout(new GridLayout(2, false));
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        propGroup.setLayoutData(gd);
+
+        platformTblViewer = new TableViewer(propGroup, SWT.SINGLE
+                | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
+
+        createColumns(platformTblViewer, PropertiesType.PLATFORM);
+
+        // Make lines and header visible
+        final Table table = platformTblViewer.getTable();
+        table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+        table.setHeaderVisible(true);
+        table.setLinesVisible(true);
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        gd.horizontalSpan = 2;
+        table.setLayoutData(gd);
+
+        platformTblViewer.setContentProvider(new PropertycontentProvider());
+
+        platEditBtn = new Button(propGroup, SWT.PUSH);
+        platEditBtn.setText("Edit");
+        gd = new GridData();
+        gd.widthHint = 50;
+        platEditBtn.setLayoutData(gd);
+        platEditBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                if (platEditBtn.getText().equals("Edit")) {
+                    platCancelBtn.setEnabled(true);
+                    platEditBtn.setText("Save");
+                    enablePlatformEdit = true;
+                } else {
+                    if (Activator.getDefault().getResourceManager()
+                            .isPlatformInfoValid(platformProperties)) {
+                        Activator.getDefault().getResourceManager()
+                                .setPlatformInfo(platformProperties);
+                        platCancelBtn.setEnabled(false);
+                        platEditBtn.setText("Edit");
+                        enablePlatformEdit = false;
+                    } else {
+                        MessageDialog.openError(Display.getDefault()
+                                .getActiveShell(), "Invalid value",
+                                "Property value cannot be empty.");
+                    }
+                }
+            }
+        });
+
+        platCancelBtn = new Button(propGroup, SWT.PUSH);
+        platCancelBtn.setText("Cancel");
+        platCancelBtn.setEnabled(false);
+        gd = new GridData();
+        gd.widthHint = 70;
+        platCancelBtn.setLayoutData(gd);
+        platCancelBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                platformProperties = getPlatformPropData();
+                updateViewer(platformTblViewer, platformProperties);
+
+                platCancelBtn.setEnabled(false);
+                platEditBtn.setText("Edit");
+                enablePlatformEdit = false;
+            }
+        });
+
+        platformPropTab.setControl(propGroup);
+    }
+
+    public void createColumns(TableViewer tableViewer, PropertiesType propType) {
+        TableViewerColumn propName = new TableViewerColumn(tableViewer,
+                SWT.NONE);
+        propName.getColumn().setWidth(columnWidth[0]);
+        propName.getColumn().setText(columnHeaders[0]);
+        propName.setLabelProvider(new StyledCellLabelProvider() {
+            @Override
+            public void update(ViewerCell cell) {
+                MetaProperty prop = (MetaProperty) cell.getElement();
+                cell.setText(prop.getPropName());
+                super.update(cell);
+            }
+        });
+
+        TableViewerColumn propValue = new TableViewerColumn(tableViewer,
+                SWT.NONE);
+        propValue.getColumn().setWidth(columnWidth[1]);
+        propValue.getColumn().setText(columnHeaders[1]);
+        propValue.setLabelProvider(new ColumnLabelProvider() {
+            @Override
+            public String getText(Object element) {
+                MetaProperty prop = (MetaProperty) element;
+                if (null != prop) {
+                    return prop.getPropValue();
+                } else {
+                    return "";
+                }
+            }
+        });
+        if (propType == PropertiesType.DEVICE) {
+            propValue.setEditingSupport(new PropValueEditor(deviceTblViewer,
+                    propType));
+        } else {
+            propValue.setEditingSupport(new PropValueEditor(platformTblViewer,
+                    propType));
+        }
+    }
+
+    private static class PropertycontentProvider implements
+            IStructuredContentProvider {
+
+        @Override
+        public void dispose() {
+        }
+
+        @Override
+        public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
+        }
+
+        @Override
+        public Object[] getElements(Object element) {
+            return (Object[]) element;
+        }
+    }
+
+    private List<MetaProperty> getPlatformPropData() {
+        List<MetaProperty> metaPropertyList = Activator.getDefault()
+                .getResourceManager().getPlatformInfo();
+        return metaPropertyList;
+    }
+
+    private List<MetaProperty> getDevicePropData() {
+        List<MetaProperty> metaPropertyList = Activator.getDefault()
+                .getResourceManager().getDeviceInfo();
+        return metaPropertyList;
+    }
+
+    private void updateViewer(TableViewer tableViewer,
+            List<MetaProperty> metaPropertyList) {
+        if (null != tableViewer) {
+            Table tbl = tableViewer.getTable();
+            if (null != metaPropertyList) {
+                tableViewer.setInput(metaPropertyList.toArray());
+                if (!tbl.isDisposed()) {
+                    tbl.setLinesVisible(true);
+                }
+            } else {
+                if (!tbl.isDisposed()) {
+                    tbl.removeAll();
+                    tbl.setLinesVisible(false);
+                }
+            }
+        }
+    }
+
+    class PropValueEditor extends EditingSupport {
+
+        private final TableViewer    viewer;
+
+        private final PropertiesType propType;
+
+        public PropValueEditor(TableViewer viewer, PropertiesType propType) {
+            super(viewer);
+            this.viewer = viewer;
+            this.propType = propType;
+        }
+
+        @Override
+        protected boolean canEdit(Object element) {
+            return true;
+        }
+
+        @Override
+        protected CellEditor getCellEditor(Object element) {
+            String propName = ((MetaProperty) element).getPropName();
+            if (null == propName) {
+                return null;
+            }
+
+            if (propType == PropertiesType.DEVICE) {
+                if (!enableDeviceEdit)
+                    return null;
+                // Only device name property is editable
+                if (!propName.equals(Constants.DEVICE_NAME)) {
+                    return null;
+                }
+            } else {
+                if (!enablePlatformEdit) {
+                    return null;
+                }
+            }
+
+            CellEditor editor = new TextCellEditor(viewer.getTable());
+            return editor;
+        }
+
+        @Override
+        protected Object getValue(Object element) {
+            return ((MetaProperty) element).getPropValue();
+        }
+
+        @Override
+        protected void setValue(Object element, Object value) {
+            MetaProperty prop = (MetaProperty) element;
+            prop.setPropValue(String.valueOf(value));
+            viewer.update(element, null);
+        }
+
+    }
+
+    @Override
+    public void setFocus() {
+    }
+}
\ No newline at end of file
index aa686b0..4098cbb 100644 (file)
 
 package oic.simulator.serviceprovider.view;
 
-import java.io.BufferedWriter;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.HashMap;
-import java.util.List;
-
-import oic.simulator.logger.LogContentProvider;
-import oic.simulator.logger.LogEntry;
-import oic.simulator.logger.LogLabelProvider;
-import oic.simulator.serviceprovider.Activator;
-import oic.simulator.serviceprovider.listener.ILogUIListener;
-import oic.simulator.serviceprovider.manager.LogManager;
-import oic.simulator.serviceprovider.utils.Constants;
-import oic.simulator.serviceprovider.view.dialogs.FilterDialog;
-import oic.simulator.serviceprovider.view.dialogs.LogDetailsDialog;
-
 import org.eclipse.jface.action.Action;
 import org.eclipse.jface.action.IAction;
 import org.eclipse.jface.action.IContributionItem;
@@ -72,8 +54,28 @@ import org.eclipse.ui.IWorkbenchPage;
 import org.eclipse.ui.dialogs.FilteredTree;
 import org.eclipse.ui.dialogs.PatternFilter;
 import org.eclipse.ui.part.ViewPart;
+
+import java.io.BufferedWriter;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.HashMap;
+import java.util.List;
+
 import org.oic.simulator.ILogger.Level;
 
+import oic.simulator.logger.LogContentProvider;
+import oic.simulator.logger.LogEntry;
+import oic.simulator.logger.LogLabelProvider;
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.listener.ILogListener;
+import oic.simulator.serviceprovider.manager.LogManager;
+import oic.simulator.serviceprovider.utils.Constants;
+import oic.simulator.serviceprovider.view.dialogs.FilterDialog;
+import oic.simulator.serviceprovider.view.dialogs.LogDetailsDialog;
+
 /**
  * This class manages and shows the log view in the perspective.
  */
@@ -82,7 +84,7 @@ public class LogView extends ViewPart {
     public static final String        VIEW_ID              = "oic.simulator.serviceprovider.view.log";
 
     private LogManager                logManager;
-    private ILogUIListener            logListener;
+    private ILogListener              logListener;
 
     private LogContentProvider        treeContentProvider;
 
@@ -136,7 +138,7 @@ public class LogView extends ViewPart {
 
     public LogView() {
 
-        logListener = new ILogUIListener() {
+        logListener = new ILogListener() {
 
             @Override
             public void logChanged(final List<LogEntry> entry) {
@@ -429,9 +431,10 @@ public class LogView extends ViewPart {
                 String data = sb.toString();
                 BufferedWriter out = null;
                 try {
-                    out = new BufferedWriter(new FileWriter(name));
+                    out = new BufferedWriter(new OutputStreamWriter(
+                            new FileOutputStream(name), "UTF-8"));
                     out.write(data);
-                } catch (IOException e) {
+                } catch (Exception e) {
                     e.printStackTrace();
                     MessageDialog.openError(
                             Display.getDefault().getActiveShell(),
index 8f8ff18..d5fd2d6 100644 (file)
 
 package oic.simulator.serviceprovider.view;
 
-import java.util.List;
-
-import oic.simulator.serviceprovider.Activator;
-import oic.simulator.serviceprovider.listener.IResourceSelectionChangedUIListener;
-import oic.simulator.serviceprovider.manager.ResourceManager;
-import oic.simulator.serviceprovider.resource.MetaProperty;
-import oic.simulator.serviceprovider.resource.SimulatorResource;
-
-import org.eclipse.jface.viewers.ColumnLabelProvider;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.CellEditor;
+import org.eclipse.jface.viewers.EditingSupport;
 import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.StyledCellLabelProvider;
 import org.eclipse.jface.viewers.TableViewer;
 import org.eclipse.jface.viewers.TableViewerColumn;
+import org.eclipse.jface.viewers.TextCellEditor;
 import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerCell;
+import org.eclipse.jface.window.Window;
 import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
 import org.eclipse.swt.layout.GridData;
 import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
 import org.eclipse.swt.widgets.Composite;
 import org.eclipse.swt.widgets.Display;
 import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.Text;
 import org.eclipse.ui.part.ViewPart;
 
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.oic.simulator.SimulatorException;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.listener.ISelectionChangedListener;
+import oic.simulator.serviceprovider.manager.ResourceManager;
+import oic.simulator.serviceprovider.manager.UiListenerHandler;
+import oic.simulator.serviceprovider.model.MetaProperty;
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.model.SingleResource;
+import oic.simulator.serviceprovider.utils.Constants;
+import oic.simulator.serviceprovider.utils.Utility;
+import oic.simulator.serviceprovider.view.dialogs.UpdateResourceInterfaceDialog;
+
 /**
  * This class manages and shows the meta properties view in the perspective.
  */
 public class MetaPropertiesView extends ViewPart {
 
-    public static final String                  VIEW_ID       = "oic.simulator.serviceprovider.view.metaproperties";
+    public static final String        VIEW_ID       = "oic.simulator.serviceprovider.view.metaproperties";
+
+    private TableViewer               tableViewer;
 
-    private TableViewer                         tableViewer;
+    private final String[]            columnHeaders = { "Property", "Value" };
 
-    private final String[]                      columnHeaders = { "Property",
-            "Value"                                          };
+    private final Integer[]           columnWidth   = { 150, 150 };
 
-    private final Integer[]                     columnWidth   = { 150, 150 };
+    private ISelectionChangedListener resourceSelectionChangedListener;
 
-    private IResourceSelectionChangedUIListener resourceSelectionChangedListener;
+    private ResourceManager           resourceManagerRef;
 
-    private ResourceManager                     resourceManagerRef;
+    private Set<String>               updatedIfSet;
+
+    private List<MetaProperty>        properties;
+
+    private boolean                   enable_edit;
+    private Button                    editBtn;
+    private Button                    cancelBtn;
+
+    private Map<String, String>       ifTypes;
 
     public MetaPropertiesView() {
 
         resourceManagerRef = Activator.getDefault().getResourceManager();
 
-        resourceSelectionChangedListener = new IResourceSelectionChangedUIListener() {
+        resourceSelectionChangedListener = new ISelectionChangedListener() {
 
             @Override
-            public void onResourceSelectionChange() {
+            public void onResourceSelectionChange(final Resource resource) {
                 Display.getDefault().asyncExec(new Runnable() {
 
                     @Override
                     public void run() {
                         if (null != tableViewer) {
-                            updateViewer(getData());
+                            properties = getData(resource);
+                            updateViewer(properties);
                         }
+                        updateEditControls(resource);
                     }
                 });
             }
@@ -77,8 +111,8 @@ public class MetaPropertiesView extends ViewPart {
     }
 
     @Override
-    public void createPartControl(Composite parent) {
-        parent.setLayout(new GridLayout(1, false));
+    public void createPartControl(final Composite parent) {
+        parent.setLayout(new GridLayout(2, false));
 
         tableViewer = new TableViewer(parent, SWT.SINGLE | SWT.H_SCROLL
                 | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
@@ -87,28 +121,245 @@ public class MetaPropertiesView extends ViewPart {
 
         // Make lines and header visible
         final Table table = tableViewer.getTable();
-        table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        gd.horizontalSpan = 2;
+        table.setLayoutData(gd);
         table.setHeaderVisible(true);
         table.setLinesVisible(true);
 
         tableViewer.setContentProvider(new PropertycontentProvider());
 
+        editBtn = new Button(parent, SWT.PUSH);
+        editBtn.setText("Edit");
+        gd = new GridData();
+        gd.widthHint = 50;
+        editBtn.setLayoutData(gd);
+        editBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                if (editBtn.getText().equals("Edit")) {
+                    cancelBtn.setEnabled(true);
+                    editBtn.setText("Save");
+                    setEnableEdit(true);
+
+                    Resource resource = resourceManagerRef
+                            .getCurrentResourceInSelection();
+                    if (null != resource) {
+                        updatedIfSet = resource.getResourceInterfaces();
+                    }
+                } else {
+                    Resource resourceInSelection = resourceManagerRef
+                            .getCurrentResourceInSelection();
+                    if (null != resourceInSelection) {
+
+                        // Null Check
+                        boolean result = resourceManagerRef
+                                .isPropertyValueInvalid(resourceInSelection,
+                                        properties, Constants.RESOURCE_URI);
+                        if (result) {
+                            MessageDialog.openError(parent.getShell(),
+                                    "Invalid Resource URI.",
+                                    Constants.INVALID_URI_MESSAGE);
+                            return;
+                        }
+
+                        result = resourceManagerRef.isPropertyValueInvalid(
+                                resourceInSelection, properties,
+                                Constants.RESOURCE_NAME);
+                        if (result) {
+                            MessageDialog.openError(parent.getShell(),
+                                    "Invalid Input",
+                                    "Resource Name is invalid.");
+                            return;
+                        }
+
+                        result = resourceManagerRef.isPropertyValueInvalid(
+                                resourceInSelection, properties,
+                                Constants.RESOURCE_TYPE);
+                        if (result) {
+                            MessageDialog.openError(parent.getShell(),
+                                    "Invalid Resource Type.",
+                                    Constants.INVALID_RESOURCE_TYPE_MESSAGE);
+                            return;
+                        }
+
+                        boolean update = false;
+                        boolean uriChange = false;
+                        boolean typeChange = false;
+                        boolean nameChange = false;
+                        boolean interfaceChange = false;
+
+                        if (resourceManagerRef.isPropValueChanged(
+                                resourceInSelection, properties,
+                                Constants.RESOURCE_NAME)) {
+                            update = true;
+                            nameChange = true;
+                        }
+
+                        if (resourceManagerRef.isPropValueChanged(
+                                resourceInSelection, properties,
+                                Constants.RESOURCE_URI)) {
+                            // Check whether the new URI is unique.
+                            if (!resourceManagerRef.isUriUnique(properties)) {
+                                MessageDialog.openError(parent.getShell(),
+                                        "Resource URI in use",
+                                        "Resource URI is in use. Please try a different URI.");
+                                return;
+                            }
+
+                            update = true;
+                            uriChange = true;
+                        }
+
+                        if (resourceManagerRef.isPropValueChanged(
+                                resourceInSelection, properties,
+                                Constants.RESOURCE_TYPE)) {
+                            update = true;
+                            typeChange = true;
+                        }
+                        // Checking whether any changes made in resource
+                        // interfaces by
+                        // comparing the current interface set and updated
+                        // interface set.
+                        Set<String> curIfSet = resourceInSelection
+                                .getResourceInterfaces();
+                        if (null != curIfSet && null != updatedIfSet) {
+                            if (curIfSet.size() != updatedIfSet.size()) {
+                                update = true;
+                                interfaceChange = true;
+                            } else {
+                                Iterator<String> itr = updatedIfSet.iterator();
+                                while (itr.hasNext()) {
+                                    if (!curIfSet.contains(itr.next())) {
+                                        update = true;
+                                        interfaceChange = true;
+                                        break;
+                                    }
+                                }
+                            }
+                        }
+                        if (update) {
+                            if (uriChange || typeChange || interfaceChange) {
+                                if (resourceManagerRef
+                                        .isResourceStarted(resourceInSelection)) {
+                                    update = MessageDialog.openQuestion(
+                                            parent.getShell(),
+                                            "Save Details",
+                                            "Resource will be restarted to take the changes."
+                                                    + " Do you want to continue?");
+                                    if (!update) {
+                                        return;
+                                    }
+                                }
+                            }
+                            try {
+                                if (uriChange || nameChange || typeChange)
+                                    result = Activator
+                                            .getDefault()
+                                            .getResourceManager()
+                                            .updateResourceProperties(
+                                                    resourceManagerRef
+                                                            .getCurrentResourceInSelection(),
+                                                    properties, uriChange,
+                                                    nameChange, typeChange);
+                                if (interfaceChange)
+                                    result = Activator
+                                            .getDefault()
+                                            .getResourceManager()
+                                            .updateResourceInterfaces(
+                                                    resourceInSelection,
+                                                    updatedIfSet);
+
+                            } catch (SimulatorException ex) {
+                                result = false;
+                            }
+                            if (!result) {
+                                MessageDialog.openInformation(
+                                        parent.getShell(), "Operation status",
+                                        "Failed to update the resource properties.");
+
+                                // Reset the old property values.
+                                properties = getData(resourceManagerRef
+                                        .getCurrentResourceInSelection());
+                                updateViewer(properties);
+                            }
+                        }
+                    }
+                    cancelBtn.setEnabled(false);
+                    editBtn.setText("Edit");
+                    setEnableEdit(false);
+                }
+            }
+        });
+
+        cancelBtn = new Button(parent, SWT.PUSH);
+        cancelBtn.setText("Cancel");
+        cancelBtn.setEnabled(false);
+        gd = new GridData();
+        gd.widthHint = 70;
+        cancelBtn.setLayoutData(gd);
+        cancelBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                Resource res = resourceManagerRef
+                        .getCurrentResourceInSelection();
+                if (null != res) {
+                    properties = getData(res);
+                }
+                updateViewer(properties);
+
+                cancelBtn.setEnabled(false);
+                editBtn.setText("Edit");
+                setEnableEdit(false);
+                if (null != updatedIfSet)
+                    updatedIfSet.clear();
+            }
+        });
+
+        // Get the supported interfaces.
+        Map<String, String> ifTypesSupported = Utility
+                .getResourceInterfaces(SingleResource.class);
+        if (null != ifTypesSupported && !ifTypesSupported.isEmpty()) {
+            ifTypes = new HashMap<String, String>();
+            String key;
+            for (Map.Entry<String, String> entry : ifTypesSupported.entrySet()) {
+                key = entry.getValue() + " (" + entry.getKey() + ")";
+                ifTypes.put(key, entry.getKey());
+            }
+        }
+
         addManagerListeners();
 
         // Check whether there is any resource selected already
-        List<MetaProperty> propertyList = getData();
-        if (null != propertyList) {
-            updateViewer(propertyList);
+        Resource resource = resourceManagerRef.getCurrentResourceInSelection();
+        properties = getData(resource);
+        if (null != properties) {
+            updateViewer(properties);
         }
+        updateEditControls(resource);
+    }
 
+    private void updateEditControls(Object obj) {
+        if (!editBtn.isDisposed() && !cancelBtn.isDisposed()) {
+
+            if (editBtn.getText().equals("Save")) {
+                editBtn.setText("Edit");
+                setEnableEdit(false);
+            }
+
+            if (null == obj) {
+                editBtn.setEnabled(false);
+            } else {
+                editBtn.setEnabled(true);
+            }
+            cancelBtn.setEnabled(false);
+        }
     }
 
-    private List<MetaProperty> getData() {
-        SimulatorResource resourceInSelection = resourceManagerRef
-                .getCurrentResourceInSelection();
-        if (null != resourceInSelection) {
+    private List<MetaProperty> getData(Resource resource) {
+        if (null != resource) {
             List<MetaProperty> metaPropertyList = resourceManagerRef
-                    .getMetaProperties(resourceInSelection);
+                    .getMetaProperties(resource);
             return metaPropertyList;
         } else {
             return null;
@@ -118,34 +369,30 @@ public class MetaPropertiesView extends ViewPart {
     private void updateViewer(List<MetaProperty> metaPropertyList) {
         if (null != tableViewer) {
             Table tbl = tableViewer.getTable();
+            if (tbl.isDisposed()) {
+                return;
+            }
             if (null != metaPropertyList) {
                 tableViewer.setInput(metaPropertyList.toArray());
-                if (!tbl.isDisposed()) {
-                    tbl.setLinesVisible(true);
-                }
+                tbl.setLinesVisible(true);
             } else {
-                if (!tbl.isDisposed()) {
-                    tbl.removeAll();
-                    tbl.setLinesVisible(false);
-                }
+                tbl.removeAll();
+                tbl.setLinesVisible(false);
             }
         }
     }
 
-    public void createColumns(TableViewer tableViewer) {
+    public void createColumns(final TableViewer tableViewer) {
         TableViewerColumn propName = new TableViewerColumn(tableViewer,
                 SWT.NONE);
         propName.getColumn().setWidth(columnWidth[0]);
         propName.getColumn().setText(columnHeaders[0]);
-        propName.setLabelProvider(new ColumnLabelProvider() {
+        propName.setLabelProvider(new StyledCellLabelProvider() {
             @Override
-            public String getText(Object element) {
-                MetaProperty prop = (MetaProperty) element;
-                if (null != prop) {
-                    return prop.getPropName();
-                } else {
-                    return "";
-                }
+            public void update(ViewerCell cell) {
+                MetaProperty prop = (MetaProperty) cell.getElement();
+                cell.setText(prop.getPropName());
+                super.update(cell);
             }
         });
 
@@ -153,25 +400,24 @@ public class MetaPropertiesView extends ViewPart {
                 SWT.NONE);
         propValue.getColumn().setWidth(columnWidth[1]);
         propValue.getColumn().setText(columnHeaders[1]);
-        propValue.setLabelProvider(new ColumnLabelProvider() {
+        propValue.setLabelProvider(new StyledCellLabelProvider() {
             @Override
-            public String getText(Object element) {
-                MetaProperty prop = (MetaProperty) element;
-                if (null != prop) {
-                    return prop.getPropValue();
-                } else {
-                    return "";
-                }
+            public void update(ViewerCell cell) {
+                MetaProperty prop = (MetaProperty) cell.getElement();
+                cell.setText(prop.getPropValue());
+                super.update(cell);
             }
         });
+        propValue.setEditingSupport(new PropValueEditor(tableViewer));
     }
 
     private void addManagerListeners() {
-        resourceManagerRef
-                .addResourceSelectionChangedUIListener(resourceSelectionChangedListener);
+        UiListenerHandler.getInstance().addResourceSelectionChangedUIListener(
+                resourceSelectionChangedListener);
     }
 
-    class PropertycontentProvider implements IStructuredContentProvider {
+    private static class PropertycontentProvider implements
+            IStructuredContentProvider {
 
         @Override
         public void dispose() {
@@ -185,19 +431,120 @@ public class MetaPropertiesView extends ViewPart {
         public Object[] getElements(Object element) {
             return (Object[]) element;
         }
-
     }
 
     @Override
     public void dispose() {
         // Unregister the listener
         if (null != resourceSelectionChangedListener) {
-            resourceManagerRef
-                    .removeResourceSelectionChangedUIListener(resourceSelectionChangedListener);
+            UiListenerHandler.getInstance()
+                    .removeResourceSelectionChangedUIListener(
+                            resourceSelectionChangedListener);
         }
         super.dispose();
     }
 
+    class PropValueEditor extends EditingSupport {
+
+        private final TableViewer viewer;
+
+        public PropValueEditor(TableViewer viewer) {
+            super(viewer);
+            this.viewer = viewer;
+        }
+
+        @Override
+        protected boolean canEdit(Object element) {
+            return true;
+        }
+
+        @Override
+        protected CellEditor getCellEditor(final Object element) {
+            if (!getEnableEdit()) {
+                return null;
+            }
+            String propName = ((MetaProperty) element).getPropName();
+            CellEditor editor = new TextCellEditor(viewer.getTable());
+            if (null != propName && propName.equals(Constants.INTERFACE_TYPES)) {
+                editor.setStyle(SWT.READ_ONLY);
+                final Text txt = (Text) editor.getControl();
+                txt.addModifyListener(new ModifyListener() {
+                    @Override
+                    public void modifyText(ModifyEvent e) {
+                        if (null == updatedIfSet) {
+                            return;
+                        }
+                        // Form the result set of interfaces with check-box that
+                        // will be shown in the dialog for editing.
+                        Map<String, String> curResInterfaces = new HashMap<String, String>();
+                        for (Map.Entry<String, String> entry : ifTypes
+                                .entrySet()) {
+                            if (updatedIfSet.contains(entry.getValue())) {
+                                curResInterfaces.put(entry.getKey(),
+                                        entry.getValue());
+                            }
+                        }
+
+                        // Show the dialog for editing the resource interfaces.
+                        UpdateResourceInterfaceDialog ad = new UpdateResourceInterfaceDialog(
+                                Display.getDefault().getActiveShell(),
+                                curResInterfaces, ifTypes);
+                        if (ad.open() == Window.OK) {
+                            // Update the local copy of the current resource
+                            // interfaces to keep the state for save operation.
+                            updatedIfSet.clear();
+                            StringBuilder newPropValue = new StringBuilder();
+                            for (Map.Entry<String, String> entry : curResInterfaces
+                                    .entrySet()) {
+                                if (!newPropValue.toString().isEmpty()) {
+                                    newPropValue.append(", ");
+                                }
+                                String value = ifTypes.get(entry.getKey());
+                                newPropValue.append(value);
+
+                                updatedIfSet.add(value);
+                            }
+                            // Update the model
+                            MetaProperty prop = (MetaProperty) element;
+                            prop.setPropValue(newPropValue.toString());
+                            // Update the viewer in a separate UI thread.
+                            Display.getDefault().asyncExec(new Runnable() {
+                                @Override
+                                public void run() {
+                                    viewer.refresh(element, true);
+                                }
+                            });
+                        }
+                    }
+                });
+            }
+            return editor;
+        }
+
+        @Override
+        protected Object getValue(Object element) {
+            return ((MetaProperty) element).getPropValue();
+        }
+
+        @Override
+        protected void setValue(Object element, Object value) {
+            MetaProperty prop = (MetaProperty) element;
+            if (prop.getPropName().equals(Constants.INTERFACE_TYPES)) {
+                return;
+            }
+            prop.setPropValue(String.valueOf(value));
+            viewer.update(element, null);
+        }
+    }
+
+    private synchronized Boolean getEnableEdit() {
+        return enable_edit;
+    }
+
+    private synchronized void setEnableEdit(boolean value) {
+        enable_edit = value;
+    }
+
     @Override
     public void setFocus() {
     }
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/MultiResourceOrchestrationView.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/MultiResourceOrchestrationView.java
deleted file mode 100644 (file)
index ac26bb0..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * 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.
- */
-
-package oic.simulator.serviceprovider.view;
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.part.ViewPart;
-
-/**
- * This class manages and shows the multi-resource automation view in the
- * perspective.
- */
-public class MultiResourceOrchestrationView extends ViewPart {
-
-    public static final String VIEW_ID = "oic.simulator.serviceprovider.view.orchestration";
-
-    @Override
-    public void createPartControl(Composite arg0) {
-        // TODO: To be done
-    }
-
-    @Override
-    public void setFocus() {
-        // TODO To be done
-    }
-}
\ No newline at end of file
index a9abf80..ecbec24 100644 (file)
 
 package oic.simulator.serviceprovider.view;
 
-import java.util.ArrayList;
-import java.util.List;
-
-import oic.simulator.serviceprovider.Activator;
-import oic.simulator.serviceprovider.listener.IResourceListChangedUIListener;
-import oic.simulator.serviceprovider.manager.ResourceManager;
-import oic.simulator.serviceprovider.resource.DeleteCategory;
-import oic.simulator.serviceprovider.utils.Constants;
-import oic.simulator.serviceprovider.utils.Utility;
-import oic.simulator.serviceprovider.view.dialogs.CreateResourceWizard;
-import oic.simulator.serviceprovider.view.dialogs.DeleteResourceWizard;
-import oic.simulator.serviceprovider.view.dialogs.ResourceWizardDialog;
-
 import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
 import org.eclipse.jface.viewers.ITreeContentProvider;
 import org.eclipse.jface.viewers.LabelProvider;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.jface.viewers.StructuredSelection;
 import org.eclipse.jface.viewers.TreeViewer;
 import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.window.Window;
 import org.eclipse.jface.wizard.WizardDialog;
 import org.eclipse.swt.SWT;
 import org.eclipse.swt.events.MenuAdapter;
@@ -51,42 +43,71 @@ import org.eclipse.swt.widgets.Group;
 import org.eclipse.swt.widgets.Menu;
 import org.eclipse.swt.widgets.MenuItem;
 import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeItem;
 import org.eclipse.ui.PlatformUI;
 import org.eclipse.ui.dialogs.FilteredTree;
 import org.eclipse.ui.dialogs.PatternFilter;
 import org.eclipse.ui.part.ViewPart;
 
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+import org.oic.simulator.ILogger.Level;
+import org.oic.simulator.SimulatorException;
+import org.oic.simulator.server.SimulatorResource.AutoUpdateType;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.listener.IPropertiesChangedListener;
+import oic.simulator.serviceprovider.listener.IResourceListChangedListener;
+import oic.simulator.serviceprovider.manager.ResourceManager;
+import oic.simulator.serviceprovider.manager.UiListenerHandler;
+import oic.simulator.serviceprovider.model.AutomationSettingHelper;
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.model.ResourceType;
+import oic.simulator.serviceprovider.model.SingleResource;
+import oic.simulator.serviceprovider.utils.Constants;
+import oic.simulator.serviceprovider.utils.Utility;
+import oic.simulator.serviceprovider.view.dialogs.AutomationSettingDialog;
+import oic.simulator.serviceprovider.view.dialogs.CreateResourceWizard;
+import oic.simulator.serviceprovider.view.dialogs.DeleteResourceWizard;
+import oic.simulator.serviceprovider.view.dialogs.MainPage;
+import oic.simulator.serviceprovider.view.dialogs.MainPage.Option;
+import oic.simulator.serviceprovider.view.dialogs.ResourceWizardDialog;
+
 /**
  * This class manages and shows the resource manager view in the perspective.
  */
 public class ResourceManagerView extends ViewPart {
 
-    public static final String             VIEW_ID = "oic.simulator.serviceprovider.view.resourcemanager";
+    public static final String           VIEW_ID = "oic.simulator.serviceprovider.view.resourcemanager";
+
+    private Button                       createButton;
+    private Button                       deleteButton;
 
-    private Button                         createButton;
-    private Button                         deleteButton;
+    private TreeViewer                   singleResTreeViewer;
 
-    private TreeViewer                     treeViewer;
+    private IResourceListChangedListener resourceListChangedListener;
 
-    private IResourceListChangedUIListener resourceListChangedListener;
+    private IPropertiesChangedListener   resourcePropertiesChangedListener;
 
-    private ResourceManager                resourceManager;
+    private ResourceManager              resourceManager;
 
     public ResourceManagerView() {
 
         resourceManager = Activator.getDefault().getResourceManager();
 
-        resourceListChangedListener = new IResourceListChangedUIListener() {
+        resourceListChangedListener = new IResourceListChangedListener() {
 
             @Override
-            public void onResourceCreation() {
-                Display.getDefault().asyncExec(new Runnable() {
+            public void onResourceCreation(final ResourceType type) {
+                Display.getDefault().syncExec(new Runnable() {
 
                     @Override
                     public void run() {
-                        if (null != treeViewer) {
-                            treeViewer.refresh();
+                        if (type == ResourceType.SINGLE) {
+                            if (null != singleResTreeViewer) {
+                                singleResTreeViewer.refresh();
+                            }
                         }
 
                         // Trigger the visibility of delete button
@@ -96,13 +117,16 @@ public class ResourceManagerView extends ViewPart {
             }
 
             @Override
-            public void onResourceDeletion() {
+            public void onResourceDeletion(final ResourceType type) {
                 Display.getDefault().asyncExec(new Runnable() {
 
                     @Override
                     public void run() {
-                        if (null != treeViewer) {
-                            treeViewer.refresh();
+                        switch (type) {
+                            case SINGLE:
+                                if (null != singleResTreeViewer)
+                                    singleResTreeViewer.refresh();
+                                break;
                         }
 
                         // Trigger the visibility of delete button
@@ -110,20 +134,41 @@ public class ResourceManagerView extends ViewPart {
                     }
                 });
             }
+
+            @Override
+            public void onResourceListUpdate(final ResourceType type) {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        switch (type) {
+                            case SINGLE:
+                                if (null != singleResTreeViewer)
+                                    singleResTreeViewer.refresh();
+                                break;
+                        }
+                    }
+                });
+            }
+        };
+
+        resourcePropertiesChangedListener = new IPropertiesChangedListener() {
+
+            @Override
+            public void onResourcePropertyChange() {
+                Display.getDefault().asyncExec(new Runnable() {
+                    @Override
+                    public void run() {
+                        if (null != singleResTreeViewer)
+                            singleResTreeViewer.refresh();
+                    }
+                });
+            }
         };
     }
 
     public void changeDeleteVisibility() {
-        if (null == treeViewer) {
-            return;
-        }
-        boolean visibility;
-        Tree tree = treeViewer.getTree();
-        if (null != tree && !tree.isDisposed() && tree.getItemCount() > 0) {
-            visibility = true;
-        } else {
-            visibility = false;
-        }
+        boolean visibility = resourceManager.isAnyResourceExist();
         if (null != deleteButton && !deleteButton.isDisposed()) {
             deleteButton.setEnabled(visibility);
         }
@@ -163,33 +208,195 @@ public class ResourceManagerView extends ViewPart {
         gd.widthHint = 90;
         deleteButton.setLayoutData(gd);
 
+        createSimpleResourcesArea(compContent);
+
+        addUIListeners();
+
+        addManagerListeners();
+
+        // If there is at least one resource exist, then enable the delete
+        // resource button
+        changeDeleteVisibility();
+    }
+
+    private void createSimpleResourcesArea(Composite compContent) {
+        // Create a group to show all the discovered resources.
+        // Adding the group to the folder.
         Group resourceGroup = new Group(compContent, SWT.NONE);
-        resourceGroup.setText("Created Resources");
 
         Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
         resourceGroup.setBackground(color);
 
         resourceGroup.setLayout(new GridLayout(1, false));
-        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
         resourceGroup.setLayoutData(gd);
 
         PatternFilter filter = new PatternFilter();
         FilteredTree filteredTree = new FilteredTree(resourceGroup,
                 SWT.H_SCROLL | SWT.V_SCROLL | SWT.SINGLE, filter, true);
-        treeViewer = filteredTree.getViewer();
-        treeViewer.getTree().setLayoutData(
+        singleResTreeViewer = filteredTree.getViewer();
+        singleResTreeViewer.getTree().setLayoutData(
                 new GridData(SWT.FILL, SWT.FILL, true, true));
-        treeViewer.setContentProvider(new TreeContentProvider());
-        treeViewer.setLabelProvider(new TreeLabelProvider());
-        treeViewer.setInput(new Object());
+        singleResTreeViewer
+                .setContentProvider(new SingleResourceContentProvider());
+        singleResTreeViewer.setLabelProvider(new TreeLabelProvider());
+        singleResTreeViewer.setInput(new Object());
 
-        addUIListeners();
+        singleResTreeViewer
+                .addSelectionChangedListener(new ISelectionChangedListener() {
+                    @Override
+                    public void selectionChanged(SelectionChangedEvent e) {
+                        IStructuredSelection selection = (IStructuredSelection) e
+                                .getSelection();
+                        if (null == selection) {
+                            return;
+                        }
 
-        addManagerListeners();
+                        Resource res = null;
+                        int size = selection.size();
+                        if (size == 1) {
+                            res = (Resource) selection.getFirstElement();
+                        }
+                        resourceManager.resourceSelectionChanged(res);
+                    }
+                });
 
-        // If there is at least one resource exist, then enable the delete
-        // resource button
-        changeDeleteVisibility();
+        addMenuToSimpleResources();
+    }
+
+    private void addMenuToSimpleResources() {
+        if (null != singleResTreeViewer) {
+            final Tree resourceTreeHead = singleResTreeViewer.getTree();
+            if (null != resourceTreeHead) {
+                // Below code creates menu entries and shows them on right
+                // clicking a resource
+                final Menu menu = new Menu(resourceTreeHead);
+                resourceTreeHead.setMenu(menu);
+                menu.addMenuListener(new MenuAdapter() {
+                    @Override
+                    public void menuShown(MenuEvent e) {
+                        // Clear existing menu items
+                        MenuItem[] items = menu.getItems();
+                        for (int index = 0; index < items.length; index++) {
+                            items[index].dispose();
+                        }
+
+                        IStructuredSelection selection = ((IStructuredSelection) singleResTreeViewer
+                                .getSelection());
+                        final SingleResource resource = (SingleResource) selection
+                                .getFirstElement();
+                        if (null == resource) {
+                            return;
+                        }
+
+                        addAutomationMenu(menu, resource);
+
+                        // Menu to remove the resource.
+                        MenuItem deleteResource = new MenuItem(menu, SWT.NONE);
+                        deleteResource.setText("Delete");
+                        deleteResource
+                                .addSelectionListener(new SelectionAdapter() {
+                                    @Override
+                                    public void widgetSelected(SelectionEvent e) {
+                                        try {
+                                            resourceManager
+                                                    .removeResource(resource);
+                                            singleResTreeViewer.refresh();
+
+                                            resourceManager
+                                                    .resourceSelectionChanged(null);
+                                        } catch (SimulatorException e1) {
+                                            MessageDialog
+                                                    .openInformation(Display
+                                                            .getDefault()
+                                                            .getActiveShell(),
+                                                            "Deletion Failed",
+                                                            "Failed to delete the resource.");
+                                        }
+                                        changeDeleteVisibility();
+                                    }
+                                });
+                    }
+                });
+            }
+        }
+    }
+
+    private void addAutomationMenu(final Menu menu,
+            final SingleResource selectedResource) {
+        MenuItem startItem = new MenuItem(menu, SWT.NONE);
+        startItem.setText(Constants.START_RESOURCE_AUTOMATION);
+        startItem.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                // Block starting resource level
+                // automation if any attribute level
+                // automation is in progress for the
+                // selected resource
+                boolean started = resourceManager
+                        .isAttributeAutomationStarted(selectedResource);
+                if (started) {
+                    MessageDialog
+                            .openInformation(
+                                    Display.getDefault().getActiveShell(),
+                                    "Attribute automation is in progress",
+                                    "Attribute level automation for this resource is already in progress!!!\nPlease stop all "
+                                            + "running attribute level automations to start resource level automation.");
+                } else {
+                    // Start the automation
+                    // Fetch the settings data
+                    List<AutomationSettingHelper> automationSettings;
+                    automationSettings = AutomationSettingHelper
+                            .getAutomationSettings(null);
+
+                    // Open the settings dialog
+                    AutomationSettingDialog dialog = new AutomationSettingDialog(
+                            Activator.getDefault().getWorkbench()
+                                    .getActiveWorkbenchWindow().getShell(),
+                            automationSettings);
+                    dialog.create();
+                    if (dialog.open() == Window.OK) {
+                        String automationType = dialog.getAutomationType();
+                        String updateFreq = dialog.getUpdateFrequency();
+
+                        AutoUpdateType autoType = AutoUpdateType
+                                .valueOf(automationType);
+                        int updFreq = Utility
+                                .getUpdateIntervalFromString(updateFreq);
+                        boolean status = resourceManager
+                                .startResourceAutomationUIRequest(autoType,
+                                        updFreq, selectedResource);
+                        if (!status) {
+                            String statusMsg = "Automation request failed!!!";
+                            MessageDialog.openInformation(Display.getDefault()
+                                    .getActiveShell(), "Automation Status",
+                                    statusMsg);
+                        }
+                    }
+                }
+            }
+        });
+
+        MenuItem stopItem = new MenuItem(menu, SWT.NONE);
+        stopItem.setText(Constants.STOP_RESOURCE_AUTOMATION);
+        stopItem.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                boolean status = resourceManager
+                        .stopResourceAutomationUIRequest(selectedResource);
+                if (!status) {
+                    String statusMsg = "Automation stop failed.";
+                    MessageDialog.openInformation(Display.getDefault()
+                            .getActiveShell(), "Automation Status", statusMsg);
+                }
+            }
+        });
+
+        // Set the initial visibility of menu items
+        boolean status = resourceManager
+                .isResourceAutomationStarted(selectedResource);
+        startItem.setEnabled(!status);
+        stopItem.setEnabled(status);
     }
 
     private void addUIListeners() {
@@ -197,33 +404,60 @@ public class ResourceManagerView extends ViewPart {
         createButton.addSelectionListener(new SelectionAdapter() {
             @Override
             public void widgetSelected(SelectionEvent e) {
+                if (resourceManager.getResourceCount() >= Constants.MAX_RESOURCE_COUNT) {
+                    MessageDialog.openInformation(Display.getDefault()
+                            .getActiveShell(), "Resource limit exceeded",
+                            Constants.RESOURCE_LIMIT_EXCEEDED_MSG);
+                    return;
+                }
                 PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
 
                     @Override
                     public void run() {
                         CreateResourceWizard createWizard = new CreateResourceWizard();
                         ResourceWizardDialog wizardDialog = new ResourceWizardDialog(
-                                PlatformUI.getWorkbench().getDisplay()
-                                        .getActiveShell(), createWizard);
+                                Display.getDefault().getActiveShell(),
+                                createWizard);
+                        createWizard.setWizardDialog(wizardDialog);
                         int open = wizardDialog.open();
-                        if (open == WizardDialog.OK) {
-                            String configFilePath;
-                            int count;
-                            configFilePath = createWizard.getConfigFilePath();
-                            System.out.println("Resultant config file path is "
-                                    + configFilePath);
-                            count = createWizard.getResourceCount();
-                            if (count > 0) {
-                                if (count == 1) {
-                                    // Single resource creation
-                                    resourceManager
-                                            .createResource(configFilePath);
-                                } else {
-                                    // Multi-resource creation
-                                    resourceManager.createResource(
-                                            configFilePath, count);
+                        if (open == WizardDialog.OK
+                                || createWizard.isDlgForceClosed()) {
+
+                            MainPage mainPage = createWizard.getMainPage();
+                            if (null == mainPage) {
+                                Activator
+                                        .getDefault()
+                                        .getLogManager()
+                                        .log(Level.ERROR.ordinal(), new Date(),
+                                                "There is an error while creating the wizard.\n");
+                                return;
+                            }
+
+                            Option option = mainPage.getOption();
+                            if (option == Option.SIMPLE_FROM_RAML
+                                    || option == Option.SIMPLE) {
+                                SingleResource res = (SingleResource) createWizard
+                                        .getCreatedResource();
+                                if (null != res) {
+                                    boolean canSelect = true;
+                                    if (option == Option.SIMPLE_FROM_RAML
+                                            && createWizard.getResourceCount() > 1) {
+                                        canSelect = false;
+                                    }
+                                    if (canSelect) {
+                                        singleResTreeViewer.setSelection(
+                                                new StructuredSelection(res),
+                                                true);
+                                        resourceManager
+                                                .resourceSelectionChanged(res);
+                                    }
                                 }
                             }
+
+                            MessageDialog.openInformation(Display.getDefault()
+                                    .getActiveShell(),
+                                    "Resource Creation Status", createWizard
+                                            .getStatus());
                         }
                     }
                 });
@@ -237,138 +471,38 @@ public class ResourceManagerView extends ViewPart {
 
                     @Override
                     public void run() {
+                        boolean exist = resourceManager.isAnyResourceExist();
+                        if (!exist) {
+                            return;
+                        }
                         DeleteResourceWizard deleteWizard = new DeleteResourceWizard();
                         ResourceWizardDialog wizardDialog = new ResourceWizardDialog(
                                 PlatformUI.getWorkbench().getDisplay()
                                         .getActiveShell(), deleteWizard);
                         int open = wizardDialog.open();
-                        if (open == WizardDialog.OK) {
-                            DeleteCategory deleteCategory = deleteWizard
-                                    .getDeleteCategory();
-                            if (deleteCategory == DeleteCategory.BY_URI) {
-                                String uri = deleteWizard.getDeleteCandidate();
-                                if (null != uri) {
-                                    boolean dispName = Activator.getDefault()
-                                            .getResourceManager()
-                                            .isDisplayName(uri);
-                                    if (dispName) {
-                                        uri = Activator
-                                                .getDefault()
-                                                .getResourceManager()
-                                                .getCompleteUriFromDisplayName(
-                                                        uri);
-                                    }
-                                    resourceManager.deleteResourceByURI(uri);
-                                }
-                            } else if (deleteCategory == DeleteCategory.BY_TYPE) {
-                                resourceManager
-                                        .deleteResourceByType(deleteWizard
-                                                .getDeleteCandidate());
-                            } else if (deleteCategory == DeleteCategory.ALL) {
-                                resourceManager.deleteAllResources();
+                        if (open == Window.OK) {
+                            singleResTreeViewer.refresh();
+
+                            if (!deleteWizard.getStatus()) {
+                                MessageDialog
+                                        .openInformation(Display.getDefault()
+                                                .getActiveShell(),
+                                                "Resource Deletion Failed",
+                                                "Failed to delete the resources. Please try again.");
                             }
+                            changeDeleteVisibility();
                         }
                     }
                 });
             }
         });
-
-        if (null != treeViewer) {
-            final Tree resourceTreeHead = treeViewer.getTree();
-            if (null != resourceTreeHead) {
-                // Below code adds a listener to the tree for selection changes
-                // and notifies the resource manager
-                resourceTreeHead.addSelectionListener(new SelectionAdapter() {
-                    @Override
-                    public void widgetSelected(SelectionEvent e) {
-                        TreeItem selectedItem = (TreeItem) e.item;
-                        if (null != selectedItem) {
-                            String selectedItemText = selectedItem.getText();
-                            selectedItemText = resourceManager
-                                    .getCompleteUriFromDisplayName(selectedItemText);
-                            // Propagate this selection change event to manager
-                            resourceManager
-                                    .resourceSelectionChanged(selectedItemText);
-                        }
-                    }
-                });
-                // Below code creates menu entries and shows them on right
-                // clicking a resource
-                final Menu menu = new Menu(resourceTreeHead);
-                resourceTreeHead.setMenu(menu);
-                menu.addMenuListener(new MenuAdapter() {
-                    @Override
-                    public void menuShown(MenuEvent e) {
-                        // Clear existing menu items
-                        MenuItem[] items = menu.getItems();
-                        for (int index = 0; index < items.length; index++) {
-                            items[index].dispose();
-                        }
-                        final String selectedItem = resourceTreeHead
-                                .getSelection()[0].getText();
-                        MenuItem startItem = new MenuItem(menu, SWT.NONE);
-                        startItem.setText(Constants.START_RESOURCE_AUTOMATION);
-                        startItem.addSelectionListener(new SelectionAdapter() {
-                            @Override
-                            public void widgetSelected(SelectionEvent e) {
-                                // Block starting resource level
-                                // automation if any attribute level
-                                // automation is in progress for the
-                                // selected resource
-                                boolean started = resourceManager
-                                        .isAttributeAutomationStarted(resourceManager
-                                                .getCompleteUriFromDisplayName(selectedItem));
-                                if (started) {
-                                    MessageDialog
-                                            .openInformation(
-                                                    Display.getDefault()
-                                                            .getActiveShell(),
-                                                    "Attribute automation is in progress",
-                                                    "Attribute level automation for this resource is already in progress!!!\nPlease stop all "
-                                                            + "running attribute level automations to start resource level automation.");
-                                } else {
-                                    boolean status = resourceManager
-                                            .startResourceAutomationUIRequest(resourceManager
-                                                    .getCompleteUriFromDisplayName(selectedItem));
-                                    String statusMsg = status ? "Automation started successfully!!!"
-                                            : "Automation request failed!!!";
-                                    MessageDialog.openInformation(Display
-                                            .getDefault().getActiveShell(),
-                                            "Automation Status", statusMsg);
-                                }
-                            }
-                        });
-
-                        MenuItem stopItem = new MenuItem(menu, SWT.NONE);
-                        stopItem.setText(Constants.STOP_RESOURCE_AUTOMATION);
-                        stopItem.addSelectionListener(new SelectionAdapter() {
-                            @Override
-                            public void widgetSelected(SelectionEvent e) {
-                                boolean status = resourceManager
-                                        .stopResourceAutomationUIRequest(resourceManager
-                                                .getCompleteUriFromDisplayName(selectedItem));
-                                String statusMsg = status ? "Automation stop requested!!!"
-                                        : "Automation stop failed.";
-                                MessageDialog.openInformation(Display
-                                        .getDefault().getActiveShell(),
-                                        "Automation Status", statusMsg);
-                            }
-                        });
-
-                        // Set the initial visibility of menu items
-                        boolean status = resourceManager.isResourceAutomationStarted(resourceManager
-                                .getCompleteUriFromDisplayName(selectedItem));
-                        startItem.setEnabled(!status);
-                        stopItem.setEnabled(status);
-                    }
-                });
-            }
-        }
     }
 
     public void addManagerListeners() {
-        resourceManager
-                .addResourceListChangedUIListener(resourceListChangedListener);
+        UiListenerHandler.getInstance().addResourceListChangedUIListener(
+                resourceListChangedListener);
+        UiListenerHandler.getInstance().addResourcePropertiesChangedUIListener(
+                resourcePropertiesChangedListener);
     }
 
     @Override
@@ -379,15 +513,21 @@ public class ResourceManagerView extends ViewPart {
     public void dispose() {
         // Unregister the listener
         if (null != resourceListChangedListener) {
-            resourceManager
-                    .removeResourceListChangedUIListener(resourceListChangedListener);
+            UiListenerHandler.getInstance()
+                    .removeResourceListChangedUIListener(
+                            resourceListChangedListener);
             resourceManager.resourceSelectionChanged(null);
         }
+        if (null != resourcePropertiesChangedListener) {
+            UiListenerHandler.getInstance()
+                    .removeResourcePropertiesChangedUIListener(
+                            resourcePropertiesChangedListener);
+        }
         super.dispose();
     }
 }
 
-class TreeContentProvider implements ITreeContentProvider {
+class SingleResourceContentProvider implements ITreeContentProvider {
 
     @Override
     public void dispose() {
@@ -404,12 +544,13 @@ class TreeContentProvider implements ITreeContentProvider {
 
     @Override
     public Object[] getElements(Object parent) {
-        List<String> uriList;
-        uriList = Activator.getDefault().getResourceManager().getURIList();
-        if (null == uriList) {
-            uriList = new ArrayList<String>();
+        List<SingleResource> resList;
+        resList = Activator.getDefault().getResourceManager()
+                .getSingleResourceList();
+        if (null == resList) {
+            resList = new ArrayList<SingleResource>();
         }
-        return uriList.toArray();
+        return resList.toArray();
     }
 
     @Override
@@ -426,15 +567,19 @@ class TreeContentProvider implements ITreeContentProvider {
 class TreeLabelProvider extends LabelProvider {
     @Override
     public String getText(Object element) {
-        String value = (String) element;
-        value = Utility.uriToDisplayName(value);
-        return value;
+        if (element instanceof Resource) {
+            Resource res = (Resource) element;
+            return res.getResourceName();
+        }
+        return null;
     }
 
     @Override
     public Image getImage(Object element) {
-        ResourceManager resourceManager = Activator.getDefault()
-                .getResourceManager();
-        return resourceManager.getImage((String) element);
+        if (element instanceof SingleResource) {
+            return Activator.getDefault().getImageRegistry()
+                    .get(Constants.SINGLE_RESOURCE);
+        }
+        return null;
     }
 }
\ No newline at end of file
index 5e9361f..4fd8238 100644 (file)
 
 package oic.simulator.serviceprovider.view;
 
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-
-import oic.simulator.serviceprovider.Activator;
-import oic.simulator.serviceprovider.listener.IObserverListChangedUIListener;
-import oic.simulator.serviceprovider.listener.IResourceSelectionChangedUIListener;
-import oic.simulator.serviceprovider.manager.ResourceManager;
-import oic.simulator.serviceprovider.resource.ObserverDetail;
-import oic.simulator.serviceprovider.resource.SimulatorResource;
-import oic.simulator.serviceprovider.utils.Constants;
-
 import org.eclipse.jface.viewers.CellEditor;
 import org.eclipse.jface.viewers.CheckboxCellEditor;
 import org.eclipse.jface.viewers.ColumnLabelProvider;
@@ -47,64 +35,76 @@ import org.eclipse.swt.widgets.Display;
 import org.eclipse.swt.widgets.Table;
 import org.eclipse.ui.part.ViewPart;
 
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.listener.IObserverListChangedListener;
+import oic.simulator.serviceprovider.listener.ISelectionChangedListener;
+import oic.simulator.serviceprovider.manager.ResourceManager;
+import oic.simulator.serviceprovider.manager.UiListenerHandler;
+import oic.simulator.serviceprovider.model.ObserverDetail;
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.utils.Constants;
+
 /**
  * This class manages and shows the resource observer view in the perspective.
  */
 public class ResourceObserverView extends ViewPart {
-    public static final String                  VIEW_ID       = "oic.simulator.serviceprovider.view.observer";
+    public static final String           VIEW_ID       = "oic.simulator.serviceprovider.view.observer";
 
-    private TableViewer                         tblViewer;
+    private TableViewer                  tblViewer;
 
-    private final String[]                      columnHeaders = {
-            "Client Address", "Port", "Notify"               };
+    private final String[]               columnHeaders = { "Client Address",
+            "Port", "Notify"                          };
 
-    private final Integer[]                     columnWidth   = { 150, 75, 50 };
+    private final Integer[]              columnWidth   = { 150, 75, 50 };
 
-    private IResourceSelectionChangedUIListener resourceSelectionChangedListener;
+    private ISelectionChangedListener    resourceSelectionChangedListener;
 
-    private IObserverListChangedUIListener      resourceObserverListChangedListener;
+    private IObserverListChangedListener resourceObserverListChangedListener;
 
-    private ResourceManager                     resourceManagerRef;
+    private ResourceManager              resourceManagerRef;
 
     public ResourceObserverView() {
 
         resourceManagerRef = Activator.getDefault().getResourceManager();
 
-        resourceSelectionChangedListener = new IResourceSelectionChangedUIListener() {
+        resourceSelectionChangedListener = new ISelectionChangedListener() {
 
             @Override
-            public void onResourceSelectionChange() {
+            public void onResourceSelectionChange(final Resource resource) {
                 Display.getDefault().asyncExec(new Runnable() {
 
                     @Override
                     public void run() {
                         if (null != tblViewer) {
                             changeButtonStatus();
-                            updateViewer(getData(resourceManagerRef
-                                    .getCurrentResourceInSelection()));
+                            updateViewer(getData(resource));
                         }
                     }
                 });
             }
         };
 
-        resourceObserverListChangedListener = new IObserverListChangedUIListener() {
+        resourceObserverListChangedListener = new IObserverListChangedListener() {
 
             @Override
-            public void onObserverListChanged(final String resourceURI) {
+            public void onObserverListChanged(final Resource resource) {
                 Display.getDefault().asyncExec(new Runnable() {
 
                     @Override
                     public void run() {
-                        if (null == resourceURI) {
+                        if (null == resource) {
                             return;
                         }
-                        SimulatorResource resource = resourceManagerRef
+                        Resource resourceInSelection = resourceManagerRef
                                 .getCurrentResourceInSelection();
-                        if (null == resource) {
+                        if (null == resourceInSelection) {
                             return;
                         }
-                        if (resource.getResourceURI().equals(resourceURI)) {
+                        if (resource == resourceInSelection) {
                             if (null != tblViewer) {
                                 updateViewer(getData(resource));
                             }
@@ -116,7 +116,7 @@ public class ResourceObserverView extends ViewPart {
         };
     }
 
-    private Map<Integer, ObserverDetail> getData(SimulatorResource resource) {
+    private Map<Integer, ObserverDetail> getData(Resource resource) {
         if (null == resource) {
             return null;
         }
@@ -149,7 +149,7 @@ public class ResourceObserverView extends ViewPart {
 
         createColumns(tblViewer);
 
-        // make lines and header visible
+        // Make lines and header visible
         final Table table = tblViewer.getTable();
         table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
         table.setHeaderVisible(true);
@@ -229,13 +229,14 @@ public class ResourceObserverView extends ViewPart {
     }
 
     private void addManagerListeners() {
-        resourceManagerRef
-                .addResourceSelectionChangedUIListener(resourceSelectionChangedListener);
-        resourceManagerRef
-                .addObserverListChangedUIListener(resourceObserverListChangedListener);
+        UiListenerHandler.getInstance().addResourceSelectionChangedUIListener(
+                resourceSelectionChangedListener);
+        UiListenerHandler.getInstance().addObserverListChangedUIListener(
+                resourceObserverListChangedListener);
     }
 
-    class ObserverContentProvider implements IStructuredContentProvider {
+    private static class ObserverContentProvider implements
+            IStructuredContentProvider {
 
         @Override
         public void dispose() {
@@ -273,7 +274,6 @@ public class ResourceObserverView extends ViewPart {
 
         @Override
         protected Object getValue(Object element) {
-            System.out.println("getValue()");
             @SuppressWarnings("unchecked")
             Map.Entry<Integer, ObserverDetail> observer = (Map.Entry<Integer, ObserverDetail>) element;
             return observer.getValue().isClicked();
@@ -281,7 +281,6 @@ public class ResourceObserverView extends ViewPart {
 
         @Override
         protected void setValue(Object element, Object value) {
-            System.out.println("setValue()");
             // Change the button status of all the resources
             changeButtonStatus();
 
@@ -298,8 +297,7 @@ public class ResourceObserverView extends ViewPart {
     }
 
     private void changeButtonStatus() {
-        SimulatorResource resource = resourceManagerRef
-                .getCurrentResourceInSelection();
+        Resource resource = resourceManagerRef.getCurrentResourceInSelection();
         if (null == resource) {
             return;
         }
@@ -318,13 +316,15 @@ public class ResourceObserverView extends ViewPart {
     public void dispose() {
         // Unregister the listener
         if (null != resourceSelectionChangedListener) {
-            resourceManagerRef
-                    .removeResourceSelectionChangedUIListener(resourceSelectionChangedListener);
+            UiListenerHandler.getInstance()
+                    .removeResourceSelectionChangedUIListener(
+                            resourceSelectionChangedListener);
         }
 
         if (null != resourceObserverListChangedListener) {
-            resourceManagerRef
-                    .removeObserverListChangedUIListener(resourceObserverListChangedListener);
+            UiListenerHandler.getInstance()
+                    .removeObserverListChangedUIListener(
+                            resourceObserverListChangedListener);
         }
         super.dispose();
     }
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddAttributeDialog.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddAttributeDialog.java
new file mode 100644 (file)
index 0000000..6dd56fa
--- /dev/null
@@ -0,0 +1,709 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.view.dialogs;
+
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.dialogs.TitleAreaDialog;
+import org.eclipse.jface.window.Window;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.CCombo;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.graphics.Rectangle;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.List;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+
+import java.util.Iterator;
+import java.util.Set;
+
+import oic.simulator.serviceprovider.model.AttributeHelper;
+import oic.simulator.serviceprovider.model.AttributeHelper.ValidValuesType;
+import oic.simulator.serviceprovider.utils.Constants;
+
+public class AddAttributeDialog extends TitleAreaDialog {
+
+    private Text                 attNameTxt;
+    private Text                 minRangeTxt;
+    private Text                 maxRangeTxt;
+    private CCombo               attTypeCmb;
+    private Text                 dflValueTxt;
+    private Button               rangeBtn;
+    private Button               cusValuesBtn;
+    private Button               noneBtn;
+    private Button               addBtn;
+    private Button               remBtn;
+    private Label                minLbl;
+    private Label                maxLbl;
+    private List                 customValuesList;
+    private Text                 detail;
+
+    private AttributeHelper      attHelper;
+
+    private AttributeHelper      attClone;
+
+    private Set<AttributeHelper> attributes;
+
+    private static final String  defaultMessage   = "Name, Type, and Default Value fields "
+                                                          + "are mandatory.\n\nRange and custom fields allow to set the valid "
+                                                          + "values of the attribute.\n\n";
+    private static final String  msgForBoolType   = "Possible attribute values of Bool are "
+                                                          + "true and false.\nSo range and custom options are disabled.";
+    private static final String  msgForIntType    = "Valid values for Int type can either be "
+                                                          + "of range type (Ex: 1 - 10) or custom values (Ex: 10, 20, 50, and 100).\n";
+    private static final String  msgForDoubleType = "Valid values for Double type can either be "
+                                                          + "of range type (Ex: 18.0 - 22.0) or custom values (Ex: 1.5, 2.5, 3.9, 4.8, etc).\n";
+    private static final String  msgForStringType = "For String type, range option is not"
+                                                          + "applicable. Hence it is disabled.\n\n"
+                                                          + "Custom option is available to provide the valid values.\n\n"
+                                                          + "Ex: low, mid, high, etc.";
+
+    private Set<String>          attValueTypes;
+
+    private boolean              editOperation;
+
+    public AddAttributeDialog(Shell parentShell, AttributeHelper att,
+            Set<String> attValueTypes, Set<AttributeHelper> attributes) {
+        super(parentShell);
+        if (null == att) {
+            att = new AttributeHelper();
+        } else {
+            attClone = att.clone();
+            editOperation = true;
+        }
+        attHelper = att;
+        this.attValueTypes = attValueTypes;
+        this.attributes = attributes;
+    }
+
+    @Override
+    public void create() {
+        super.create();
+        setTitle("Add Attribute");
+        setMessage("Fill the details for creating an attribute");
+    }
+
+    @Override
+    protected Control createDialogArea(Composite parent) {
+        Composite compLayout = (Composite) super.createDialogArea(parent);
+        Composite container = new Composite(compLayout, SWT.NONE);
+        container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+        GridLayout layout = new GridLayout(5, false);
+        container.setLayout(layout);
+
+        Label attNameLbl = new Label(container, SWT.NULL);
+        attNameLbl.setText("Attribute Name:");
+
+        attNameTxt = new Text(container, SWT.BORDER);
+        GridData gd = new GridData();
+        gd.horizontalAlignment = SWT.FILL;
+        gd.horizontalSpan = 4;
+        gd.grabExcessHorizontalSpace = true;
+        attNameTxt.setLayoutData(gd);
+
+        Label attTypeLbl = new Label(container, SWT.NULL);
+        attTypeLbl.setText("Attribute Type:");
+
+        attTypeCmb = new CCombo(container, SWT.READ_ONLY | SWT.BORDER);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalSpan = 4;
+        gd.horizontalAlignment = SWT.FILL;
+        attTypeCmb.setLayoutData(gd);
+        initTypes();
+
+        Group valuesGrp = new Group(container, SWT.NULL);
+        valuesGrp.setText("Attribute Values");
+        gd = new GridData();
+        gd.verticalIndent = 10;
+        gd.horizontalSpan = 3;
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessVerticalSpace = true;
+        gd.verticalAlignment = SWT.FILL;
+        valuesGrp.setLayoutData(gd);
+        layout = new GridLayout(4, false);
+        valuesGrp.setLayout(layout);
+
+        rangeBtn = new Button(valuesGrp, SWT.RADIO);
+        rangeBtn.setText("Range");
+        gd = new GridData();
+        gd.horizontalSpan = 4;
+        rangeBtn.setLayoutData(gd);
+
+        minLbl = new Label(valuesGrp, SWT.NONE);
+        minLbl.setText("Min:");
+        gd = new GridData();
+        gd.horizontalIndent = 25;
+        minLbl.setLayoutData(gd);
+
+        minRangeTxt = new Text(valuesGrp, SWT.BORDER);
+        gd = new GridData();
+        gd.widthHint = 70;
+        minRangeTxt.setLayoutData(gd);
+
+        maxLbl = new Label(valuesGrp, SWT.NONE);
+        maxLbl.setText("Max:");
+        gd = new GridData();
+        gd.horizontalIndent = 25;
+        maxLbl.setLayoutData(gd);
+
+        maxRangeTxt = new Text(valuesGrp, SWT.BORDER);
+        gd = new GridData();
+        gd.widthHint = 70;
+        maxRangeTxt.setLayoutData(gd);
+
+        cusValuesBtn = new Button(valuesGrp, SWT.RADIO);
+        cusValuesBtn.setText("Custom");
+        gd = new GridData();
+        gd.horizontalSpan = 4;
+        cusValuesBtn.setLayoutData(gd);
+
+        Composite cusValuesComp = new Composite(valuesGrp, SWT.NONE);
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        gd.horizontalSpan = 4;
+        cusValuesComp.setLayoutData(gd);
+        layout = new GridLayout(2, false);
+        cusValuesComp.setLayout(layout);
+
+        customValuesList = new List(cusValuesComp, SWT.BORDER | SWT.MULTI
+                | SWT.V_SCROLL);
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        gd.heightHint = 75;
+        gd.horizontalIndent = 25;
+        customValuesList.setLayoutData(gd);
+
+        Composite cusValuesActionsComp = new Composite(cusValuesComp, SWT.NONE);
+        layout = new GridLayout();
+        cusValuesActionsComp.setLayout(layout);
+        gd = new GridData();
+        gd.verticalAlignment = SWT.TOP;
+        cusValuesActionsComp.setLayoutData(gd);
+
+        addBtn = new Button(cusValuesActionsComp, SWT.PUSH);
+        addBtn.setText("Add");
+        gd = new GridData();
+        gd.widthHint = 70;
+        addBtn.setLayoutData(gd);
+
+        remBtn = new Button(cusValuesActionsComp, SWT.PUSH);
+        remBtn.setText("Remove");
+        gd = new GridData();
+        gd.widthHint = 70;
+        remBtn.setLayoutData(gd);
+        remBtn.setEnabled(false);
+
+        noneBtn = new Button(valuesGrp, SWT.RADIO);
+        noneBtn.setText("None");
+        gd = new GridData();
+        gd.horizontalSpan = 4;
+        noneBtn.setLayoutData(gd);
+
+        Composite detailsComp = new Composite(container, SWT.NULL);
+        detailsComp.setLayout(new GridLayout());
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        gd.horizontalSpan = 2;
+        gd.widthHint = 100;
+        detailsComp.setLayoutData(gd);
+
+        Label lbl = new Label(detailsComp, SWT.NULL);
+        lbl.setText("Details");
+
+        Group detailsGrp = new Group(detailsComp, SWT.NULL);
+        detailsGrp.setLayout(new GridLayout());
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        detailsGrp.setLayoutData(gd);
+
+        detail = new Text(detailsGrp, SWT.MULTI | SWT.READ_ONLY | SWT.BORDER
+                | SWT.WRAP | SWT.V_SCROLL);
+        detail.setBackground(detailsGrp.getBackground());
+        detail.setText(defaultMessage);
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        detail.setLayoutData(gd);
+
+        Label dflValueLbl = new Label(container, SWT.NULL);
+        dflValueLbl.setText("Default value");
+
+        dflValueTxt = new Text(container, SWT.BORDER);
+        gd = new GridData();
+        gd.horizontalSpan = 4;
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        dflValueTxt.setLayoutData(gd);
+
+        setUiListeners();
+
+        if (editOperation) {
+            initData();
+            attNameTxt.setFocus();
+        } else {
+            setInitialSelection();
+        }
+
+        return compLayout;
+    }
+
+    private void initTypes() {
+        if (null != attValueTypes && attValueTypes.size() > 0) {
+            Iterator<String> itr = attValueTypes.iterator();
+            while (itr.hasNext()) {
+                attTypeCmb.add(itr.next());
+            }
+        }
+    }
+
+    private void setInitialSelection() {
+        enable(false);
+        rangeOptionSelected(false);
+        customOptionSelected(false);
+    }
+
+    private void initData() {
+        if (editOperation) {
+            // Populate the UI controls with the data.
+            attNameTxt.setText(attHelper.getAttributeName());
+            attTypeCmb.select(attTypeCmb.indexOf(attHelper.getAttributeType()));
+            updateControls();
+            dflValueTxt.setText(attHelper.getAttributeDflValue());
+            ValidValuesType valuesType = attHelper.getValidValuesType();
+            if (valuesType == ValidValuesType.RANGE) {
+                rangeBtn.setSelection(true);
+                noneBtn.setSelection(false);
+                rangeOptionSelected(true);
+                minRangeTxt.setText(attHelper.getMin());
+                maxRangeTxt.setText(attHelper.getMax());
+            } else if (valuesType == ValidValuesType.VALUESET) {
+                cusValuesBtn.setSelection(true);
+                noneBtn.setSelection(false);
+                customOptionSelected(true);
+                Set<String> allowedValues = attHelper.getAllowedValues();
+                customValuesList.setItems(allowedValues.toArray(new String[1]));
+            }
+        }
+    }
+
+    private void setUiListeners() {
+        rangeBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                rangeOptionSelected(true);
+                customOptionSelected(false);
+                minRangeTxt.setFocus();
+            }
+        });
+
+        cusValuesBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                addBtn.setFocus();
+                rangeOptionSelected(false);
+                customOptionSelected(true);
+            }
+        });
+
+        noneBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                rangeOptionSelected(false);
+                customOptionSelected(false);
+            }
+        });
+
+        attTypeCmb.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                updateControls();
+            }
+        });
+
+        minRangeTxt.addListener(SWT.Verify, new Listener() {
+            @Override
+            public void handleEvent(Event e) {
+                String string = e.text;
+                char[] chars = new char[string.length()];
+                string.getChars(0, chars.length, chars, 0);
+                for (int i = 0; i < chars.length; i++) {
+                    if (!(('0' <= chars[i] && chars[i] <= '9')
+                            || chars[i] == '-' || chars[i] == '+')) {
+                        if (attTypeCmb.getText().equals(Constants.INT)) {
+                            e.doit = false;
+                            return;
+                        } else if (attTypeCmb.getText()
+                                .equals(Constants.DOUBLE)) {
+                            if (!(chars[i] == '.')) {
+                                e.doit = false;
+                                return;
+                            }
+                        }
+                    }
+                }
+            }
+        });
+
+        maxRangeTxt.addListener(SWT.Verify, new Listener() {
+            @Override
+            public void handleEvent(Event e) {
+                String string = e.text;
+                char[] chars = new char[string.length()];
+                string.getChars(0, chars.length, chars, 0);
+                for (int i = 0; i < chars.length; i++) {
+                    if (!(('0' <= chars[i] && chars[i] <= '9')
+                            || chars[i] == '-' || chars[i] == '+')) {
+                        if (attTypeCmb.getText().equals(Constants.INT)) {
+                            e.doit = false;
+                            return;
+                        } else if (attTypeCmb.getText()
+                                .equals(Constants.DOUBLE)) {
+                            if (!(chars[i] == '.')) {
+                                e.doit = false;
+                                return;
+                            }
+                        }
+                    }
+                }
+            }
+        });
+
+        addBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                SingleTextInputDialog dialog = new SingleTextInputDialog(
+                        getShell(), "Add Attribute Value", "Attribute Value");
+                if (dialog.open() == Window.OK) {
+                    String value = dialog.getValue();
+                    String type = attTypeCmb.getText();
+                    if (!attHelper.isValueValid(value, type)) {
+                        MessageDialog.openError(getParentShell(),
+                                "Invalid value", "Attribute value is invalid.");
+                    } else if (attHelper.isAllowedValueExist(
+                            customValuesList.getItems(), value)) {
+                        MessageDialog.openError(getParentShell(),
+                                "Duplicate value",
+                                "Attribute value already exists.");
+                    } else {
+                        customValuesList.add(value);
+                        customValuesList.deselectAll();
+                        customValuesList.select(customValuesList.getItemCount() - 1);
+                        customValuesList.showSelection();
+                        remBtn.setEnabled(true);
+                    }
+                }
+            }
+        });
+
+        remBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                int[] selection = customValuesList.getSelectionIndices();
+                if (null != selection && selection.length > 0) {
+                    customValuesList.remove(selection);
+                }
+
+                changeRemBtnVisibility();
+            }
+        });
+
+        customValuesList.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                changeRemBtnVisibility();
+            }
+        });
+    }
+
+    private void updateControls() {
+        rangeBtn.setSelection(false);
+        cusValuesBtn.setSelection(false);
+        noneBtn.setSelection(true);
+
+        cleanRangeAndCustomValues();
+        dflValueTxt.setText("");
+
+        String selected = attTypeCmb.getText();
+
+        if (selected.equals(Constants.INT)) {
+            enable(true);
+            rangeOptionSelected(false);
+            customOptionSelected(false);
+            detail.setText(defaultMessage + msgForIntType);
+        } else if (selected.equals(Constants.DOUBLE)) {
+            enable(true);
+            rangeOptionSelected(false);
+            customOptionSelected(false);
+            detail.setText(defaultMessage + msgForDoubleType);
+        } else if (selected.equals(Constants.BOOL)) {
+            enable(false);
+            rangeOptionSelected(false);
+            customOptionSelected(false);
+            detail.setText(defaultMessage + msgForBoolType);
+        } else if (selected.equals(Constants.STRING)) {
+            rangeBtn.setEnabled(false);
+            rangeOptionSelected(false);
+            cusValuesBtn.setEnabled(true);
+            noneBtn.setEnabled(true);
+            detail.setText(defaultMessage + msgForStringType);
+        } else {
+            enable(false);
+            rangeOptionSelected(false);
+            customOptionSelected(false);
+            detail.setText(defaultMessage);
+        }
+    }
+
+    private void changeRemBtnVisibility() {
+        if (cusValuesBtn.isEnabled() && cusValuesBtn.getSelection()) {
+            int[] selection = customValuesList.getSelectionIndices();
+            if (null != selection && selection.length > 0) {
+                remBtn.setEnabled(true);
+            } else {
+                remBtn.setEnabled(false);
+            }
+        } else {
+            remBtn.setEnabled(false);
+        }
+    }
+
+    private void enable(boolean enable) {
+        rangeBtn.setEnabled(enable);
+        cusValuesBtn.setEnabled(enable);
+        noneBtn.setEnabled(enable);
+    }
+
+    private void rangeOptionSelected(boolean enable) {
+        minRangeTxt.setEnabled(enable);
+        maxRangeTxt.setEnabled(enable);
+        minLbl.setEnabled(enable);
+        maxLbl.setEnabled(enable);
+    }
+
+    private void customOptionSelected(boolean enable) {
+        customValuesList.setEnabled(enable);
+        addBtn.setEnabled(enable);
+        changeRemBtnVisibility();
+    }
+
+    private void cleanRangeAndCustomValues() {
+        cleanRangeValues();
+        cleanCustomValues();
+    }
+
+    private void cleanRangeValues() {
+        minRangeTxt.setText("");
+        maxRangeTxt.setText("");
+    }
+
+    private void cleanCustomValues() {
+        customValuesList.removeAll();
+    }
+
+    public AttributeHelper getAttHelper() {
+        return attHelper;
+    }
+
+    public AttributeHelper getAttClone() {
+        return attClone;
+    }
+
+    @Override
+    protected void okPressed() {
+        // Attribute Name
+        String attName = attNameTxt.getText();
+        if (null == attName || attName.isEmpty()) {
+            MessageDialog.openError(getParentShell(),
+                    "Mandatory field is empty",
+                    "Please fill the attribute name.");
+            attNameTxt.setFocus();
+            return;
+        }
+        attName = attName.trim();
+        if (attName.length() < 1) {
+            MessageDialog.openError(getParentShell(),
+                    "Mandatory field is empty", "Attribute name is invalid.");
+            attNameTxt.setFocus();
+            return;
+        }
+        attHelper.setAttributeName(attName);
+
+        // Duplicate check for attribute name if this is not editing operation
+        if (!editOperation) {
+            if (!attributes.isEmpty()) {
+                Iterator<AttributeHelper> itr = attributes.iterator();
+                AttributeHelper att;
+                while (itr.hasNext()) {
+                    att = itr.next();
+                    if (att.getAttributeName().equals(attName)) {
+                        MessageDialog
+                                .openError(
+                                        getParentShell(),
+                                        "Duplicate Attribute",
+                                        "Another attribute with the same attribute name exist. Please enter a new attribute name.");
+                        attNameTxt.setFocus();
+                        return;
+                    }
+                }
+            }
+        }
+
+        // Attribute Type
+        String attType = attTypeCmb.getText();
+        if (null == attType || attType.isEmpty()) {
+            MessageDialog.openError(getParentShell(),
+                    "Mandatory field is empty",
+                    "Please select an attribute type.");
+            return;
+        }
+        attHelper.setAttributeType(attType);
+
+        // Attribute values
+        if (rangeBtn.isEnabled() && rangeBtn.getSelection()) { // Range option
+            String min = minRangeTxt.getText();
+            String max = maxRangeTxt.getText();
+            if (null == min && null == max) {
+                MessageDialog
+                        .openError(getParentShell(), "Range is empty",
+                                "Please enter the minimum and maximum value of the range.");
+                minRangeTxt.setFocus();
+                return;
+            }
+            if (null == min || null == max) {
+                String msg;
+                msg = "Please enter the "
+                        + ((null == min) ? "minimum value" : "maximum value")
+                        + "of the range.";
+                MessageDialog
+                        .openError(getParentShell(), "Range is empty", msg);
+                ((null == min) ? minRangeTxt : maxRangeTxt).setFocus();
+                return;
+            }
+            if (min.isEmpty() && max.isEmpty()) {
+                MessageDialog
+                        .openError(getParentShell(), "Range is empty",
+                                "Please enter the minimum and maximum value of the range.");
+                minRangeTxt.setFocus();
+                return;
+            }
+            if (min.isEmpty()) {
+                MessageDialog.openError(getParentShell(), "Range is empty",
+                        "Please enter the minimum value for the range.");
+                minRangeTxt.setFocus();
+                return;
+            }
+            if (max.isEmpty()) {
+                MessageDialog.openError(getParentShell(), "Range is empty",
+                        "Please enter the maximum value for the range.");
+                maxRangeTxt.setFocus();
+                return;
+            }
+
+            if (!min.isEmpty() && !max.isEmpty()
+                    && !attHelper.isRangeValid(min, max, attType)) {
+                MessageDialog.openError(getParentShell(), "Invalid range",
+                        "Range is invalid.");
+                maxRangeTxt.setFocus();
+                return;
+            }
+            attHelper.setValidValuesType(ValidValuesType.RANGE);
+            attHelper.setMin(min);
+            attHelper.setMax(max);
+
+            if (editOperation) {
+                // Remove all existing custom values
+                attHelper.setAllowedValues(null);
+            }
+        } else if (cusValuesBtn.isEnabled() && cusValuesBtn.getSelection()) {
+            String[] cusItems = customValuesList.getItems();
+            if (null == cusItems || cusItems.length < 1) {
+                MessageDialog.openError(getParentShell(),
+                        "Custom list is empty.",
+                        "No values are added to the custom list.");
+                maxRangeTxt.setFocus();
+                return;
+            }
+            attHelper.setValidValuesType(ValidValuesType.VALUESET);
+            attHelper.setAllowedValuesByArray(cusItems);
+
+            if (editOperation) {
+                // Remove min and max values
+                attHelper.setMin(null);
+                attHelper.setMax(null);
+            }
+        } else if (noneBtn.isEnabled() && noneBtn.getSelection()) {
+            attHelper.setValidValuesType(ValidValuesType.UNKNOWN);
+            if (editOperation) {
+                // Remove min, max and custom values
+                attHelper.setAllowedValues(null);
+                attHelper.setMin(null);
+                attHelper.setMax(null);
+            }
+        }
+
+        // Attribute Default Value
+        String attDflValue = dflValueTxt.getText();
+        if (null == attDflValue || attDflValue.isEmpty()) {
+            MessageDialog.openError(getParentShell(),
+                    "Mandatory field is empty",
+                    "Please enter a default value for the attribute.");
+            dflValueTxt.setFocus();
+            return;
+        }
+        attDflValue = attDflValue.trim();
+        if (attDflValue.length() < 1
+                || !attHelper.isValueValid(attDflValue, attType)) {
+            MessageDialog.openError(getParentShell(), "Invalid value",
+                    "Default value is invalid.");
+            dflValueTxt.setFocus();
+            return;
+        }
+        if (!attHelper.isDefaultValueValid(attDflValue)) {
+            MessageDialog.openError(getParentShell(), "Invalid value",
+                    "Default value is not in the valid values.");
+            dflValueTxt.setFocus();
+            return;
+        }
+
+        attHelper.setAttributeDflValue(attDflValue.toLowerCase());
+
+        close();
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+
+    @Override
+    protected Point getInitialLocation(Point initialSize) {
+        Rectangle shellBounds = Display.getDefault().getActiveShell()
+                .getBounds();
+        Point dialogSize = getInitialSize();
+
+        return new Point(
+                shellBounds.x + (shellBounds.width - dialogSize.x) / 2,
+                shellBounds.y + (shellBounds.height - dialogSize.y) / 2);
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddInterfaceTypeDialog.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddInterfaceTypeDialog.java
new file mode 100644 (file)
index 0000000..ccdd612
--- /dev/null
@@ -0,0 +1,96 @@
+/*
+ * 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 oic.simulator.serviceprovider.view.dialogs;
+
+import org.eclipse.jface.dialogs.TrayDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+
+import java.util.List;
+
+/**
+ * This class shows a dialog for filtering logs based on severity levels.
+ */
+public class AddInterfaceTypeDialog extends TrayDialog {
+
+    private Combo        ifTypesCmb;
+    private String       value;
+    private List<String> ifTypes;
+
+    public AddInterfaceTypeDialog(Shell shell, List<String> ifTypes) {
+        super(shell);
+        this.ifTypes = ifTypes;
+    }
+
+    @Override
+    protected void configureShell(Shell shell) {
+        super.configureShell(shell);
+    }
+
+    @Override
+    protected Control createDialogArea(Composite parent) {
+        Composite composite = (Composite) super.createDialogArea(parent);
+        getShell().setText("Add Interface Type");
+
+        Composite content = new Composite(parent, SWT.NULL);
+        GridLayout gridLayout = new GridLayout();
+        content.setLayout(gridLayout);
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        content.setLayoutData(gd);
+
+        Label lbl = new Label(content, SWT.NONE);
+        lbl.setText("Select Interface Type");
+
+        ifTypesCmb = new Combo(content, SWT.NULL);
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        ifTypesCmb.setLayoutData(gd);
+
+        ifTypesCmb.addModifyListener(new ModifyListener() {
+            @Override
+            public void modifyText(ModifyEvent e) {
+                value = ifTypesCmb.getText();
+            }
+        });
+
+        initList();
+
+        return composite;
+    }
+
+    private void initList() {
+        if (null != ifTypesCmb && null != ifTypes && !ifTypes.isEmpty()) {
+            ifTypesCmb.setItems(ifTypes.toArray(new String[1]));
+        }
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+
+    public String getValue() {
+        return value;
+    }
+}
index e2bb48f..80ab2a3 100644 (file)
 
 package oic.simulator.serviceprovider.view.dialogs;
 
-import java.util.Iterator;
-import java.util.List;
-
-import oic.simulator.serviceprovider.resource.AutomationSettingHelper;
-import oic.simulator.serviceprovider.utils.Constants;
-
 import org.eclipse.jface.dialogs.TitleAreaDialog;
 import org.eclipse.swt.SWT;
 import org.eclipse.swt.custom.CCombo;
@@ -34,6 +28,12 @@ import org.eclipse.swt.widgets.Control;
 import org.eclipse.swt.widgets.Label;
 import org.eclipse.swt.widgets.Shell;
 
+import java.util.Iterator;
+import java.util.List;
+
+import oic.simulator.serviceprovider.model.AutomationSettingHelper;
+import oic.simulator.serviceprovider.utils.Constants;
+
 /**
  * This class manages and shows the automation settings dialog from the
  * attribute view.
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/CreateResourcePage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/CreateResourcePage.java
deleted file mode 100644 (file)
index dc44ad6..0000000
+++ /dev/null
@@ -1,331 +0,0 @@
-/*
- * 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.
- */
-
-package oic.simulator.serviceprovider.view.dialogs;
-
-import java.util.Iterator;
-import java.util.Map;
-
-import oic.simulator.serviceprovider.Activator;
-import oic.simulator.serviceprovider.utils.Constants;
-import oic.simulator.serviceprovider.utils.Utility;
-
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.CCombo;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-
-/**
- * This class shows UI for creating resources.
- */
-public class CreateResourcePage extends WizardPage {
-
-    private Button stdResourceRbtn;
-    private CCombo resourceTypeCmb;
-    private Button cusResourceRbtn;
-    private Text   locationTxt;
-    private Button btnBrowse;
-    private Text   noOfInstancesText;
-    private Label  resourceTypeLbl;
-    private Label  noOfInstancesLbl;
-    private Label  locationLbl;
-
-    private String configFilePath = null;
-    private int    resourceCount;
-
-    protected CreateResourcePage() {
-        super("Create Resource");
-        resourceCount = -1;
-    }
-
-    @Override
-    public void createControl(Composite parent) {
-        setPageComplete(false);
-        setTitle(Constants.CREATE_PAGE_TITLE);
-        setMessage(Constants.CREATE_PAGE_MESSAGE);
-        Composite compContent = new Composite(parent, SWT.NONE);
-        GridLayout gridLayout = new GridLayout(1, false);
-        compContent.setLayout(gridLayout);
-        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
-        compContent.setLayoutData(gd);
-
-        Group configGroup = new Group(compContent, SWT.NONE);
-        gridLayout = new GridLayout(1, false);
-        gridLayout.verticalSpacing = 10;
-        gridLayout.marginTop = 5;
-        configGroup.setLayout(gridLayout);
-        gd = new GridData();
-        gd.horizontalAlignment = SWT.FILL;
-        gd.grabExcessHorizontalSpace = true;
-        configGroup.setLayoutData(gd);
-        configGroup.setText("Configuration File Type");
-
-        stdResourceRbtn = new Button(configGroup, SWT.RADIO);
-        stdResourceRbtn.setText("Standard Configuration");
-
-        Composite stdConfigComp = new Composite(configGroup, SWT.NONE);
-        stdConfigComp.setLayout(new GridLayout(2, false));
-        gd = new GridData();
-        gd.horizontalAlignment = SWT.FILL;
-        gd.grabExcessHorizontalSpace = true;
-        stdConfigComp.setLayoutData(gd);
-
-        resourceTypeLbl = new Label(stdConfigComp, SWT.NONE);
-        resourceTypeLbl.setText("ResourceType:");
-        resourceTypeLbl.setEnabled(false);
-
-        resourceTypeCmb = new CCombo(stdConfigComp, SWT.READ_ONLY | SWT.BORDER);
-        gd = new GridData();
-        gd.widthHint = 150;
-        resourceTypeCmb.setLayoutData(gd);
-        resourceTypeCmb.setEnabled(false);
-
-        cusResourceRbtn = new Button(configGroup, SWT.RADIO);
-        cusResourceRbtn.setText("Custom Configuration");
-
-        Composite cusConfigComp = new Composite(configGroup, SWT.NONE);
-        cusConfigComp.setLayout(new GridLayout(3, false));
-        gd = new GridData();
-        gd.horizontalAlignment = SWT.FILL;
-        gd.grabExcessHorizontalSpace = true;
-        cusConfigComp.setLayoutData(gd);
-
-        locationLbl = new Label(cusConfigComp, SWT.NONE);
-        locationLbl.setText("Location:");
-        locationLbl.setEnabled(false);
-
-        locationTxt = new Text(cusConfigComp, SWT.BORDER);
-        gd = new GridData();
-        gd.minimumWidth = 300;
-        gd.horizontalAlignment = SWT.FILL;
-        gd.grabExcessHorizontalSpace = true;
-        locationTxt.setLayoutData(gd);
-        locationTxt.setEnabled(false);
-
-        btnBrowse = new Button(cusConfigComp, SWT.NONE);
-        btnBrowse.setText("Browse");
-        gd = new GridData();
-        gd.widthHint = 80;
-        gd.horizontalAlignment = SWT.FILL;
-        btnBrowse.setLayoutData(gd);
-        btnBrowse.setEnabled(false);
-
-        Composite instanceComp = new Composite(compContent, SWT.NONE);
-        instanceComp.setLayout(new GridLayout(2, false));
-        gd = new GridData();
-        gd.horizontalAlignment = SWT.FILL;
-        gd.grabExcessHorizontalSpace = true;
-        instanceComp.setLayoutData(gd);
-
-        noOfInstancesLbl = new Label(instanceComp, SWT.NONE);
-        noOfInstancesLbl.setText("Number of Instances");
-
-        noOfInstancesText = new Text(instanceComp, SWT.BORDER);
-        gd = new GridData();
-        gd.widthHint = 50;
-        gd.horizontalAlignment = SWT.FILL;
-        noOfInstancesText.setLayoutData(gd);
-
-        // Adding the default value. It can be changed by the user.
-        noOfInstancesText.setText("1");
-
-        populateDataInUI();
-
-        addUIListeners();
-
-        setControl(compContent);
-    }
-
-    private void populateDataInUI() {
-        // Populate Resource-type in Combo
-        populateResourceTypeCombo();
-    }
-
-    private void populateResourceTypeCombo() {
-        Map<String, String> configMap;
-        configMap = Activator.getDefault().getResourceManager()
-                .getResourceConfigurationList();
-        if (null != configMap) {
-            Iterator<String> itr = configMap.keySet().iterator();
-            String fileName;
-            String shortName;
-            while (itr.hasNext()) {
-                fileName = itr.next();
-                shortName = Utility.fileNameToDisplay(fileName);
-                if (null == shortName) {
-                    continue;
-                }
-                resourceTypeCmb.add(shortName);
-            }
-        }
-
-        // By default, selecting the first item in the resourceType combo
-        selectInitialItem();
-    }
-
-    private void addUIListeners() {
-        stdResourceRbtn.addSelectionListener(new SelectionAdapter() {
-            @Override
-            public void widgetSelected(SelectionEvent e) {
-
-                // Set the configFilePath to the first item in the combo
-                selectInitialItem();
-
-                setPageComplete(isSelectionDone());
-
-                // Change the visibility of widgets
-                resourceTypeLbl.setEnabled(true);
-                resourceTypeCmb.setEnabled(true);
-                locationLbl.setEnabled(false);
-                locationTxt.setEnabled(false);
-                btnBrowse.setEnabled(false);
-
-            }
-        });
-
-        cusResourceRbtn.addSelectionListener(new SelectionAdapter() {
-            @Override
-            public void widgetSelected(SelectionEvent e) {
-                setPageComplete(isSelectionDone());
-
-                // Change the visibility of widgets
-                locationLbl.setEnabled(true);
-                locationTxt.setEnabled(true);
-                btnBrowse.setEnabled(true);
-                resourceTypeLbl.setEnabled(false);
-                resourceTypeCmb.setEnabled(false);
-
-            }
-        });
-
-        btnBrowse.addSelectionListener(new SelectionAdapter() {
-            @Override
-            public void widgetSelected(SelectionEvent e) {
-                FileDialog fileDialog = new FileDialog(PlatformUI
-                        .getWorkbench().getDisplay().getActiveShell(), SWT.NONE);
-                fileDialog
-                        .setFilterExtensions(Constants.BROWSE_RAML_FILTER_EXTENSIONS);
-                String configFileAbsolutePath = fileDialog.open();
-                locationTxt.setText(configFileAbsolutePath);
-            }
-        });
-
-        resourceTypeCmb.addSelectionListener(new SelectionAdapter() {
-            @Override
-            public void widgetSelected(SelectionEvent e) {
-                int index = resourceTypeCmb.getSelectionIndex();
-                if (index >= 0) {
-                    String selectedItem = resourceTypeCmb.getItem(index);
-                    if (null != selectedItem) {
-                        // Convert the selectedItem to the fully qualified file
-                        // name.
-                        selectedItem = Utility.displayToFileName(selectedItem);
-
-                        // Get the RAML configuration file path of the selected
-                        // resource
-                        configFilePath = Activator.getDefault()
-                                .getResourceManager()
-                                .getConfigFilePath(selectedItem);
-
-                        setPageComplete(isSelectionDone());
-                    }
-                }
-            }
-        });
-
-        locationTxt.addModifyListener(new ModifyListener() {
-            @Override
-            public void modifyText(ModifyEvent e) {
-                configFilePath = locationTxt.getText();
-                setPageComplete(isSelectionDone());
-            }
-        });
-
-        noOfInstancesText.addListener(SWT.Verify, new Listener() {
-            @Override
-            public void handleEvent(Event e) {
-                String string = e.text;
-                char[] chars = new char[string.length()];
-                string.getChars(0, chars.length, chars, 0);
-                for (int i = 0; i < chars.length; i++) {
-                    if (!('0' <= chars[i] && chars[i] <= '9')) {
-                        e.doit = false;
-                        return;
-                    }
-                }
-            }
-        });
-
-        noOfInstancesText.addKeyListener(new KeyAdapter() {
-            @Override
-            public void keyReleased(KeyEvent e) {
-                setPageComplete(isSelectionDone());
-            }
-        });
-    }
-
-    private void selectInitialItem() {
-        if (resourceTypeCmb.getItemCount() > 0) {
-            resourceTypeCmb.select(0);
-            String fileName = Utility.displayToFileName(resourceTypeCmb
-                    .getText());
-            configFilePath = Activator.getDefault().getResourceManager()
-                    .getConfigFilePath(fileName);
-        }
-    }
-
-    private boolean isSelectionDone() {
-        boolean done = false;
-        try {
-            resourceCount = Integer.parseInt(noOfInstancesText.getText());
-        } catch (Exception e) {
-            resourceCount = -1;
-        }
-        if (cusResourceRbtn.getSelection()) {
-            configFilePath = locationTxt.getText();
-        }
-
-        if (null != configFilePath && configFilePath.length() > 0
-                && resourceCount >= 1) {
-            done = true;
-        }
-        return done;
-    }
-
-    public String getConfigFilePath() {
-        return configFilePath;
-    }
-
-    public int getResourceCount() {
-        return resourceCount;
-    }
-}
\ No newline at end of file
index 5a11cc0..f45afec 100644 (file)
 
 package oic.simulator.serviceprovider.view.dialogs;
 
-import java.net.URL;
-
-import oic.simulator.serviceprovider.Activator;
-
 import org.eclipse.core.runtime.FileLocator;
 import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.IProgressMonitor;
 import org.eclipse.core.runtime.Path;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.operation.IRunnableWithProgress;
 import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.wizard.IWizardPage;
 import org.eclipse.jface.wizard.Wizard;
+import org.eclipse.jface.wizard.WizardDialog;
+import org.eclipse.swt.widgets.Display;
+
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.net.URL;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+
+import org.oic.simulator.ILogger.Level;
+import org.oic.simulator.SimulatorException;
+import org.oic.simulator.SimulatorResourceAttribute;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.manager.UiListenerHandler;
+import oic.simulator.serviceprovider.model.AttributeHelper;
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.model.ResourceType;
+import oic.simulator.serviceprovider.model.SingleResource;
+import oic.simulator.serviceprovider.utils.Constants;
+import oic.simulator.serviceprovider.utils.Utility;
+import oic.simulator.serviceprovider.view.dialogs.MainPage.Option;
 
 /**
  * This class creates a UI wizard for create resource operation.
  */
 public class CreateResourceWizard extends Wizard {
 
-    private CreateResourcePage page;
+    private MainPage                       mainPage;
+    private SimpleResourceBasicDetailsPage simpleResourceBasicDetailsPage;
+    private SimpleResourceAddAttributePage simpleResourceAddAttributePage;
+    private SimpleResourceOtherDetailsPage simpleResourceOtherDetailsPage;
+    private LoadRamlPage                   loadRamlPage;
+    private UpdatePropertiesPage           updatePropPage;
+
+    private String                         status;
+
+    private WizardDialog                   wizDialog;
+    private boolean                        dlgForceClosed;
+
+    private Resource                       createdResource;
+
+    private IProgressMonitor               progressMonitor;
 
     public CreateResourceWizard() {
         setWindowTitle("Create resources");
@@ -39,30 +80,389 @@ public class CreateResourceWizard extends Wizard {
         URL find = FileLocator.find(Activator.getDefault().getBundle(), path,
                 null);
         setDefaultPageImageDescriptor(ImageDescriptor.createFromURL(find));
+
+        setNeedsProgressMonitor(true);
     }
 
     @Override
     public void addPages() {
-        page = new CreateResourcePage();
-        addPage(page);
+        mainPage = new MainPage();
+        simpleResourceBasicDetailsPage = new SimpleResourceBasicDetailsPage();
+        simpleResourceAddAttributePage = new SimpleResourceAddAttributePage();
+        simpleResourceOtherDetailsPage = new SimpleResourceOtherDetailsPage();
+        loadRamlPage = new LoadRamlPage();
+        updatePropPage = new UpdatePropertiesPage();
+
+        addPage(mainPage);
+        addPage(simpleResourceBasicDetailsPage);
+        addPage(simpleResourceAddAttributePage);
+        addPage(simpleResourceOtherDetailsPage);
+        addPage(loadRamlPage);
+        addPage(updatePropPage);
+    }
+
+    public void setWizardDialog(WizardDialog dlg) {
+        wizDialog = dlg;
+    }
+
+    public WizardDialog getWizardDialog() {
+        return wizDialog;
+    }
+
+    public boolean isDlgForceClosed() {
+        return dlgForceClosed;
+    }
+
+    public void setDlgForceClosed(boolean dlgForceClosed) {
+        this.dlgForceClosed = dlgForceClosed;
     }
 
     public String getConfigFilePath() {
-        if (null == page) {
+        if (null == loadRamlPage) {
             return null;
         }
-        return page.getConfigFilePath();
+        return loadRamlPage.getConfigFilePath();
     }
 
     public int getResourceCount() {
-        if (null == page) {
+        if (null == loadRamlPage) {
             return 0;
         }
-        return page.getResourceCount();
+        return loadRamlPage.getResourceCount();
+    }
+
+    public Resource getCreatedResource() {
+        return createdResource;
+    }
+
+    @Override
+    public boolean canFinish() {
+        IWizardPage curPage = this.getContainer().getCurrentPage();
+        if ((curPage == updatePropPage && ((mainPage.getOption() == Option.SIMPLE_FROM_RAML) || !Activator
+                .getDefault().getResourceManager().isAnyResourceExist()))
+                || curPage == simpleResourceAddAttributePage
+                || (curPage == loadRamlPage && loadRamlPage.isSelectionDone() && loadRamlPage
+                        .isMultiResourceCreation())) {
+            return true;
+        }
+        return false;
     }
 
     @Override
     public boolean performFinish() {
+        final IWizardPage curPage = this.getContainer().getCurrentPage();
+        // Handling Simple Resource Creation without RAML
+        if (curPage == simpleResourceAddAttributePage) {
+            try {
+                getContainer().run(true, false, new IRunnableWithProgress() {
+
+                    @Override
+                    public void run(IProgressMonitor monitor)
+                            throws InvocationTargetException,
+                            InterruptedException {
+                        try {
+                            monitor.beginTask(
+                                    "Single Resource Creation Without RAML", 2);
+                            monitor.worked(1);
+                            createSingleResourceWithoutRAML();
+                        } finally {
+                            monitor.done();
+                        }
+                    }
+                });
+            } catch (InvocationTargetException e) {
+                Activator.getDefault().getLogManager()
+                        .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
+                e.printStackTrace();
+            } catch (InterruptedException e) {
+                Activator.getDefault().getLogManager()
+                        .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
+                e.printStackTrace();
+            }
+        } else if (curPage == loadRamlPage) {
+            // Validate the file path.
+            FileInputStream fileStream = null;
+            try {
+                fileStream = new FileInputStream(
+                        loadRamlPage.getConfigFilePath());
+            } catch (FileNotFoundException e) {
+                MessageDialog
+                        .openError(getShell(), "Invalid File",
+                                "File doesn't exist. Either the file path or file name is invalid.");
+                return false;
+            } finally {
+                if (null != fileStream) {
+                    try {
+                        fileStream.close();
+                    } catch (IOException e) {
+                        Activator
+                                .getDefault()
+                                .getLogManager()
+                                .log(Level.ERROR.ordinal(), new Date(),
+                                        "There is an error while closing the file stream.\n");
+                    }
+                }
+            }
+
+            // Handling multiple instance creation of simple resource with RAML
+            if ((loadRamlPage.getResourceCount() + Activator.getDefault()
+                    .getResourceManager().getResourceCount()) > Constants.MAX_RESOURCE_COUNT) {
+                MessageDialog.openInformation(Display.getDefault()
+                        .getActiveShell(), "Resource limit exceeded",
+                        Constants.RESOURCE_LIMIT_EXCEEDED_MSG);
+                return false;
+            }
+
+            final int[] resCreatedCount = new int[1];
+            try {
+                getContainer().run(true, true, new IRunnableWithProgress() {
+
+                    @Override
+                    public void run(final IProgressMonitor monitor)
+                            throws InvocationTargetException,
+                            InterruptedException {
+                        progressMonitor = monitor;
+                        try {
+                            monitor.beginTask(
+                                    "Single Resource Creation(multi-instance) With RAML",
+                                    loadRamlPage.getResourceCount());
+                            resCreatedCount[0] = createMultiInstanceSingleResourceWithoutRAML();
+
+                        } finally {
+                            monitor.done();
+                        }
+                    }
+                });
+            } catch (InvocationTargetException e) {
+                Activator.getDefault().getLogManager()
+                        .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
+                e.printStackTrace();
+            } catch (InterruptedException e) {
+                Activator.getDefault().getLogManager()
+                        .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
+                e.printStackTrace();
+            }
+            boolean canceled = false;
+            if (null != progressMonitor && progressMonitor.isCanceled()
+                    && 0 == resCreatedCount[0]) {
+                canceled = true;
+            }
+            progressMonitor = null;
+            if (canceled) {
+                return false;
+            } else {
+                if (resCreatedCount[0] > 0) {
+                    UiListenerHandler.getInstance()
+                            .resourceCreatedUINotification(ResourceType.SINGLE);
+                }
+            }
+        } else if (curPage == updatePropPage) {
+            // Handling the single instance
+            String resName = updatePropPage.getResName();
+            String resURI = updatePropPage.getResURI();
+            if (null == resName || resName.trim().length() < 1) {
+                MessageDialog.openError(Display.getDefault().getActiveShell(),
+                        "Invalid Resource Name.", "Resource name is invalid");
+                return false;
+            }
+            if (!Utility.isUriValid(resURI)) {
+                MessageDialog.openError(Display.getDefault().getActiveShell(),
+                        "Invalid Resource URI.", Constants.INVALID_URI_MESSAGE);
+                return false;
+            }
+            // Creation of simple resource with RAML
+            // Checking whether the URI is used by any other resource.
+            if (Activator.getDefault().getResourceManager()
+                    .isResourceExist(updatePropPage.getResURI())) {
+                MessageDialog
+                        .openError(getShell(), "Resource URI in use",
+                                "Entered resource URI is in use. Please try a different one.");
+                return false;
+            }
+
+            try {
+                getContainer().run(true, false, new IRunnableWithProgress() {
+
+                    @Override
+                    public void run(IProgressMonitor monitor)
+                            throws InvocationTargetException,
+                            InterruptedException {
+                        try {
+                            monitor.beginTask("Completing Resource Creation", 2);
+                            monitor.worked(1);
+                            completeResourceCreationWithRAML();
+                            monitor.worked(1);
+                        } finally {
+                            monitor.done();
+                        }
+                    }
+                });
+            } catch (InvocationTargetException e) {
+                Activator.getDefault().getLogManager()
+                        .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
+                e.printStackTrace();
+            } catch (InterruptedException e) {
+                Activator.getDefault().getLogManager()
+                        .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
+                e.printStackTrace();
+            }
+        }
         return true;
     }
+
+    public MainPage getMainPage() {
+        return mainPage;
+    }
+
+    public SimpleResourceBasicDetailsPage getSimpleResourceBasicDetailsPage() {
+        return simpleResourceBasicDetailsPage;
+    }
+
+    public SimpleResourceAddAttributePage getSimpleResourceAddAttributePage() {
+        return simpleResourceAddAttributePage;
+    }
+
+    public SimpleResourceOtherDetailsPage getSimpleResourceOtherDetailsPage() {
+        return simpleResourceOtherDetailsPage;
+    }
+
+    public LoadRamlPage getLoadRamlPage() {
+        return loadRamlPage;
+    }
+
+    public UpdatePropertiesPage getUpdatePropPage() {
+        return updatePropPage;
+    }
+
+    public void setStatus(String status) {
+        this.status = status;
+    }
+
+    public String getStatus() {
+        return status;
+    }
+
+    private void createSingleResourceWithoutRAML() {
+        SingleResource resource = new SingleResource();
+        // Basic resource details
+        resource.setResourceURI(simpleResourceBasicDetailsPage.getResURI());
+        resource.setResourceName(simpleResourceBasicDetailsPage.getResName());
+        resource.setResourceType(simpleResourceBasicDetailsPage.getResType());
+        resource.setObservable(simpleResourceBasicDetailsPage.isObservable());
+        resource.setDiscoverable(simpleResourceBasicDetailsPage
+                .isDiscoverable());
+        resource.setResourceInterfaces(simpleResourceBasicDetailsPage
+                .getInterfaceTypes());
+
+        // Resource Attributes
+        Map<String, SimulatorResourceAttribute> attributes = new HashMap<String, SimulatorResourceAttribute>();
+        Set<AttributeHelper> attributeSet = simpleResourceAddAttributePage
+                .getAttributes();
+        if (null != attributeSet && !attributeSet.isEmpty()) {
+            Iterator<AttributeHelper> itr = attributeSet.iterator();
+            AttributeHelper attHelper;
+            SimulatorResourceAttribute attribute;
+            while (itr.hasNext()) {
+                attHelper = itr.next();
+                if (null != attHelper) {
+                    attribute = attHelper.convertToSimulatorResourceAttribute();
+                    attributes.put(attribute.name(), attribute);
+                }
+            }
+        }
+
+        // Request types
+        resource.setGetAllowed(simpleResourceOtherDetailsPage.isGetChecked());
+        resource.setPutAllowed(simpleResourceOtherDetailsPage.isPutChecked());
+        resource.setPostAllowed(simpleResourceOtherDetailsPage.isPostChecked());
+
+        // Call method of ResourceManager and update the response in the status
+        // string.
+        try {
+            boolean result = Activator.getDefault().getResourceManager()
+                    .createSingleResource(resource, attributes);
+            if (result) {
+                status = "Resource created.";
+                createdResource = resource;
+            } else {
+                status = "Failed to create resource.";
+                createdResource = null;
+            }
+        } catch (Exception e) {
+            status = "Failed to create resource.\n"
+                    + Utility.getSimulatorErrorString(e, null);
+            createdResource = null;
+        }
+    }
+
+    private void completeResourceCreationWithRAML() {
+        try {
+            boolean result = false;
+            Resource res = loadRamlPage.getResource();
+            if (res instanceof SingleResource) {
+                result = Activator
+                        .getDefault()
+                        .getResourceManager()
+                        .completeSingleResourceCreationByRAML(res,
+                                updatePropPage.getResURI(),
+                                updatePropPage.getResName(), false);
+            }
+
+            if (result) {
+                status = "Resource created.";
+                createdResource = res;
+            } else {
+                status = "Failed to create resource.";
+                createdResource = null;
+            }
+        } catch (Exception e) {
+            status = "Failed to create resource.\n"
+                    + Utility.getSimulatorErrorString(e, null);
+            createdResource = null;
+        }
+    }
+
+    private int createMultiInstanceSingleResourceWithoutRAML() {
+        int toCreateCount = loadRamlPage.getResourceCount();
+        int resCreatedCount = 0;
+        Set<SingleResource> resources;
+        try {
+            resources = Activator
+                    .getDefault()
+                    .getResourceManager()
+                    .createSingleResourceMultiInstances(
+                            loadRamlPage.getConfigFilePath(), toCreateCount,
+                            progressMonitor);
+            if (null != progressMonitor && progressMonitor.isCanceled()) {
+                try {
+                    Activator.getDefault().getResourceManager()
+                            .removeSingleResources(resources);
+                } catch (SimulatorException e) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(),
+                                    new Date(),
+                                    "There is an error while updating the resource model.\n"
+                                            + Utility.getSimulatorErrorString(
+                                                    e, null));
+                }
+                return 0;
+            }
+            if (null != resources)
+                resCreatedCount = resources.size();
+            if (resCreatedCount > 0) {
+                status = "[" + resCreatedCount + " out of " + toCreateCount
+                        + "]";
+                status += ((resCreatedCount == 1) ? "resource" : "resources")
+                        + " created successfully.";
+            } else {
+                status = "Failed to create resources.";
+            }
+        } catch (SimulatorException e) {
+            status = "Failed to create resource.\n"
+                    + Utility.getSimulatorErrorString(e, null);
+        }
+        return resCreatedCount;
+    }
 }
\ No newline at end of file
index be7dae8..b5bd831 100644 (file)
 
 package oic.simulator.serviceprovider.view.dialogs;
 
-import java.util.Iterator;
-import java.util.List;
-
-import oic.simulator.serviceprovider.Activator;
-import oic.simulator.serviceprovider.resource.DeleteCategory;
-import oic.simulator.serviceprovider.utils.Constants;
-
+import org.eclipse.jface.viewers.CheckStateChangedEvent;
+import org.eclipse.jface.viewers.CheckboxTreeViewer;
+import org.eclipse.jface.viewers.ICheckStateListener;
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.LabelProvider;
+import org.eclipse.jface.viewers.TreeNodeContentProvider;
+import org.eclipse.jface.viewers.Viewer;
 import org.eclipse.jface.wizard.WizardPage;
 import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.CCombo;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Image;
 import org.eclipse.swt.layout.GridData;
 import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
 import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
 import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Text;
+import org.eclipse.swt.widgets.Label;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.model.SingleResource;
+import oic.simulator.serviceprovider.utils.Constants;
 
 /**
  * This class shows UI for deleting resources.
  */
 public class DeleteResourcePage extends WizardPage {
 
-    private Button         allRbtn;
-    private Button         byTypeRbtn;
-    private Button         byUriRbtn;
-
-    private CCombo         resourceTypeCmb;
-    private Text           resourceUriTxt;
+    private CheckboxTreeViewer    singleTreeViewer;
 
-    private DeleteCategory deleteCategory;
+    private List<SingleResource>  singleSourceList;
 
-    // It will hold either the resource type or resource uri
-    private String         deleteCandidate;
+    private TreeViewContentHelper singleTreeViewContentHelper;
 
     protected DeleteResourcePage() {
-        super("Delete Resource");
+        super("Delete Resources");
+
+        singleSourceList = Activator.getDefault().getResourceManager()
+                .getSingleResourceList();
     }
 
     @Override
     public void createControl(Composite parent) {
         setPageComplete(false);
-        setTitle(Constants.DELETE_PAGE_TITLE);
-        setMessage(Constants.DELETE_PAGE_MESSAGE);
+        setTitle("Delete Resources");
+        setMessage("Select one or more simple resources for deletion.");
+
+        Composite container = new Composite(parent, SWT.NONE);
+        container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+        GridLayout layout = new GridLayout(4, true);
+        container.setLayout(layout);
+
+        createSingleResourcesArea(container);
 
-        Composite compContent = new Composite(parent, SWT.NONE);
-        compContent.setLayout(new GridLayout(1, false));
+        setControl(container);
+    }
+
+    private void createSingleResourcesArea(Composite container) {
+        Composite singleContainer = new Composite(container, SWT.NONE);
         GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
-        compContent.setLayoutData(gd);
-
-        Group group = new Group(compContent, SWT.NONE);
-        group.setText("Select Category");
-        GridLayout gridLayout = new GridLayout(2, false);
-        gridLayout.verticalSpacing = 15;
-        gridLayout.marginTop = 10;
-        gridLayout.marginLeft = 10;
-        group.setLayout(gridLayout);
+        gd.horizontalSpan = 4;
+        singleContainer.setLayoutData(gd);
+        GridLayout layout = new GridLayout();
+        singleContainer.setLayout(layout);
+
+        Label lbl = new Label(singleContainer, SWT.NONE);
+        lbl.setText("Simple Resources:");
         gd = new GridData(SWT.FILL, SWT.FILL, true, true);
-        group.setLayoutData(gd);
+        lbl.setLayoutData(gd);
 
-        allRbtn = new Button(group, SWT.RADIO);
-        allRbtn.setText("All resources");
-        gd = new GridData();
-        gd.horizontalSpan = 2;
-        gd.widthHint = 200;
-        allRbtn.setLayoutData(gd);
+        Group resourceGroup = new Group(singleContainer, SWT.NONE);
 
-        byTypeRbtn = new Button(group, SWT.RADIO);
-        byTypeRbtn.setText("All (By resource type)");
-        gd = new GridData();
-        gd.widthHint = 200;
-        byTypeRbtn.setLayoutData(gd);
+        Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
 
-        resourceTypeCmb = new CCombo(group, SWT.READ_ONLY | SWT.BORDER);
+        resourceGroup.setLayout(new GridLayout());
         gd = new GridData();
-        gd.widthHint = 200;
-        resourceTypeCmb.setLayoutData(gd);
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.heightHint = 300;
+        gd.horizontalSpan = 2;
+        resourceGroup.setLayoutData(gd);
 
-        byUriRbtn = new Button(group, SWT.RADIO);
-        byUriRbtn.setText("By Resource URI");
-        gd = new GridData();
-        gd.widthHint = 200;
-        byUriRbtn.setLayoutData(gd);
+        if (null == singleSourceList || singleSourceList.isEmpty()) {
+            return;
+        }
 
-        resourceUriTxt = new Text(group, SWT.BORDER);
+        singleTreeViewer = new CheckboxTreeViewer(resourceGroup);
+        singleTreeViewer.getTree().setBackground(color);
         gd = new GridData();
-        gd.widthHint = 300;
-        resourceUriTxt.setLayoutData(gd);
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessVerticalSpace = true;
+        gd.verticalAlignment = SWT.FILL;
+
+        singleTreeViewer.getTree().setLayoutData(gd);
+        singleTreeViewer
+                .setContentProvider(new SingleResourceContentProvider());
+        singleTreeViewer.setLabelProvider(new TreeLabelProvider());
+        singleTreeViewer.setInput(new TreeNodeContentProvider());
+        singleTreeViewer.addCheckStateListener(new ICheckStateListener() {
 
-        // Setting the initial visibility of controls
-        allRbtn.setSelection(false);
-        byTypeRbtn.setSelection(false);
-        byUriRbtn.setSelection(false);
-
-        resourceTypeCmb.setEnabled(false);
-        resourceUriTxt.setEnabled(false);
-
-        deleteCategory = DeleteCategory.NONE;
+            @Override
+            public void checkStateChanged(CheckStateChangedEvent e) {
+                Object element = e.getElement();
+                if (element instanceof TreeViewContentHelper) {
+                    singleTreeViewer.setGrayed(singleTreeViewContentHelper,
+                            false);
+                    singleTreeViewer.setChecked(singleTreeViewContentHelper,
+                            e.getChecked());
+                    singleTreeViewer.setSubtreeChecked(element, e.getChecked());
+                } else {
+                    Object obj[] = singleTreeViewer.getCheckedElements();
+                    if (null != obj && obj.length > 0) {
+                        int checkedCount = obj.length;
+                        boolean isParentGrayed = singleTreeViewer
+                                .getChecked(singleTreeViewContentHelper);
+                        boolean isParentChecked = singleTreeViewer
+                                .getChecked(singleTreeViewContentHelper);
+                        if (isParentChecked || isParentGrayed) {
+                            checkedCount--;
+                        }
+                        if (checkedCount == singleSourceList.size()) {
+                            singleTreeViewer.setGrayed(
+                                    singleTreeViewContentHelper, false);
+                            singleTreeViewer.setChecked(
+                                    singleTreeViewContentHelper, true);
+                        } else {
+                            if (checkedCount > 0) {
+                                singleTreeViewer.setGrayed(
+                                        singleTreeViewContentHelper, true);
+                                singleTreeViewer.setChecked(
+                                        singleTreeViewContentHelper, true);
+                            } else {
+                                singleTreeViewer.setGrayed(
+                                        singleTreeViewContentHelper, false);
+                                singleTreeViewer.setChecked(
+                                        singleTreeViewContentHelper, false);
+                            }
+                        }
+                    }
+                }
+                setPageComplete(isSelectionDone());
+            }
+        });
+        singleTreeViewer.expandAll();
 
-        populateDataInUI();
+    }
 
-        addUIListeners();
+    public Set<SingleResource> getSelectedSingleResourcesList() {
+        final Set<SingleResource> singles = new HashSet<SingleResource>();
+        Display.getDefault().syncExec(new Runnable() {
 
-        setControl(compContent);
+            @Override
+            public void run() {
+                if (null == singleTreeViewer) {
+                    return;
+                }
+                Object selection[] = singleTreeViewer.getCheckedElements();
+                if (null == selection || selection.length < 1) {
+                    return;
+                }
+                for (Object obj : selection) {
+                    if (obj instanceof SingleResource) {
+                        singles.add((SingleResource) obj);
+                    }
+                }
+            }
+        });
+        return singles;
     }
 
-    private void populateDataInUI() {
-        // Populate Resourcetype in Combo
-        populateResourceTypeCombo();
-    }
+    class SingleResourceContentProvider implements ITreeContentProvider {
 
-    private void populateResourceTypeCombo() {
-        List<String> resourceTypeList;
-        resourceTypeList = Activator.getDefault().getResourceManager()
-                .getResourceTypeList();
-        if (null != resourceTypeList) {
-            Iterator<String> itr = resourceTypeList.iterator();
-            while (itr.hasNext()) {
-                resourceTypeCmb.add(itr.next());
-            }
+        @Override
+        public void dispose() {
         }
 
-        // By default, select the first item in the combo
-        if (resourceTypeCmb.getItemCount() > 0) {
-            resourceTypeCmb.select(0);
-            deleteCandidate = resourceTypeCmb.getText();
+        @Override
+        public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
         }
-    }
 
-    public void addUIListeners() {
-        allRbtn.addSelectionListener(new SelectionAdapter() {
-            @Override
-            public void widgetSelected(SelectionEvent e) {
-                // Update the visibility of controls
-                resourceTypeCmb.setEnabled(false);
-                resourceUriTxt.setEnabled(false);
-
-                deleteCategory = DeleteCategory.ALL;
-                deleteCandidate = null;
-                setPageComplete(isSelectionDone());
+        @Override
+        public Object[] getChildren(Object parent) {
+            if (parent instanceof TreeViewContentHelper) {
+                return ((TreeViewContentHelper) parent).getResources()
+                        .toArray();
             }
-        });
-
-        byTypeRbtn.addSelectionListener(new SelectionAdapter() {
-            @Override
-            public void widgetSelected(SelectionEvent e) {
-                // Update the visibility of controls
-                resourceTypeCmb.setEnabled(true);
-                resourceUriTxt.setEnabled(false);
+            return null;
+        }
 
-                deleteCategory = DeleteCategory.BY_TYPE;
-                setPageComplete(isSelectionDone());
-            }
-        });
+        @Override
+        public Object[] getElements(Object parent) {
+            Object obj[] = new Object[1];
+            singleTreeViewContentHelper = new TreeViewContentHelper(
+                    singleSourceList);
+            obj[0] = singleTreeViewContentHelper;
+            return obj;
+        }
 
-        byUriRbtn.addSelectionListener(new SelectionAdapter() {
-            @Override
-            public void widgetSelected(SelectionEvent e) {
-                // Update the visibility of controls
-                resourceUriTxt.setEnabled(true);
-                resourceUriTxt.setFocus();
-                resourceTypeCmb.setEnabled(false);
+        @Override
+        public Object getParent(Object child) {
+            return null;
+        }
 
-                deleteCategory = DeleteCategory.BY_URI;
-                setPageComplete(isSelectionDone());
+        @Override
+        public boolean hasChildren(Object parent) {
+            if (parent instanceof TreeViewContentHelper) {
+                return true;
             }
-        });
+            return false;
+        }
+    }
 
-        resourceTypeCmb.addModifyListener(new ModifyListener() {
-            @Override
-            public void modifyText(ModifyEvent arg0) {
-                setPageComplete(isSelectionDone());
+    private static class TreeLabelProvider extends LabelProvider {
+        @Override
+        public String getText(Object element) {
+            if (element instanceof TreeViewContentHelper) {
+                return "All";
             }
-        });
+            Resource res = (Resource) element;
+            return res.getResourceName() + " (" + res.getResourceURI() + ")";
+        }
 
-        resourceUriTxt.addModifyListener(new ModifyListener() {
-            @Override
-            public void modifyText(ModifyEvent arg0) {
-                setPageComplete(isSelectionDone());
+        @Override
+        public Image getImage(Object element) {
+            if (element instanceof SingleResource) {
+                return Activator.getDefault().getImageRegistry()
+                        .get(Constants.SINGLE_RESOURCE);
+            } else {
+                return null;
             }
-        });
+        }
     }
 
-    public boolean isSelectionDone() {
-        boolean done = false;
-        if (deleteCategory == DeleteCategory.ALL) {
-            done = true;
-        } else if (deleteCategory == DeleteCategory.BY_TYPE) {
-            deleteCandidate = resourceTypeCmb.getText();
-            if (null != deleteCandidate && deleteCandidate.length() > 0) {
-                done = true;
-            }
-        } else if (deleteCategory == DeleteCategory.BY_URI) {
-            deleteCandidate = resourceUriTxt.getText();
-            if (null != deleteCandidate && deleteCandidate.length() > 0) {
-                done = true;
-            }
+    private static class TreeViewContentHelper {
+        List<? extends Resource> resources;
+
+        public TreeViewContentHelper(List<? extends Resource> resources) {
+            this.resources = resources;
         }
-        return done;
-    }
 
-    public DeleteCategory getDeleteCategory() {
-        return deleteCategory;
-    }
+        public void setResources(List<? extends Resource> resources) {
+            this.resources = resources;
+        }
 
-    public String getDeleteCandidate() {
-        return deleteCandidate;
+        public List<? extends Resource> getResources() {
+            return resources;
+        }
     }
 
-    public void setFocusToTextBox() {
-        resourceUriTxt.setFocus();
+    public boolean isSelectionDone() {
+        if (null != singleTreeViewer) {
+            Object obj[] = singleTreeViewer.getCheckedElements();
+            if (null != obj && obj.length > 0) {
+                return true;
+            }
+        }
+        return false;
     }
 }
\ No newline at end of file
index 4d079eb..c81078a 100644 (file)
 
 package oic.simulator.serviceprovider.view.dialogs;
 
-import java.net.URL;
-
-import oic.simulator.serviceprovider.Activator;
-import oic.simulator.serviceprovider.resource.DeleteCategory;
-
 import org.eclipse.core.runtime.FileLocator;
 import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.IProgressMonitor;
 import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.operation.IRunnableWithProgress;
 import org.eclipse.jface.resource.ImageDescriptor;
 import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
+
+import java.lang.reflect.InvocationTargetException;
+import java.net.URL;
+import java.util.Date;
+import java.util.Set;
+
+import org.oic.simulator.ILogger.Level;
+import org.oic.simulator.SimulatorException;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.manager.ResourceManager;
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.model.SingleResource;
 
 /**
  * This class creates a UI wizard for delete resource operation.
@@ -37,12 +44,16 @@ public class DeleteResourceWizard extends Wizard {
 
     private DeleteResourcePage page;
 
+    private boolean            success;
+
     public DeleteResourceWizard() {
         setWindowTitle("Delete resources");
         IPath path = new Path("/icons/oic_logo_64x64.png");
         URL find = FileLocator.find(Activator.getDefault().getBundle(), path,
                 null);
         setDefaultPageImageDescriptor(ImageDescriptor.createFromURL(find));
+
+        setNeedsProgressMonitor(true);
     }
 
     @Override
@@ -56,45 +67,54 @@ public class DeleteResourceWizard extends Wizard {
         if (null == page) {
             return false;
         }
-        // Check the existence of the resource if the user has entered the uri
-        if (page.getDeleteCategory() == DeleteCategory.BY_URI) {
-            // Check whether the uri is in full form or short form
-            // If it is in short form, expand it to its full form.
-            String uri = page.getDeleteCandidate();
-            boolean dispName = Activator.getDefault().getResourceManager()
-                    .isDisplayName(uri);
-            if (dispName) {
-                uri = Activator.getDefault().getResourceManager()
-                        .getCompleteUriFromDisplayName(uri);
-            }
-            boolean exist = Activator.getDefault().getResourceManager()
-                    .isResourceExist(uri);
-            if (!exist) {
-                Shell activeShell = PlatformUI.getWorkbench().getDisplay()
-                        .getActiveShell();
-                MessageDialog dialog = new MessageDialog(activeShell,
-                        "Resource Not Found", null,
-                        "No resource exist with the given URI.",
-                        MessageDialog.INFORMATION, new String[] { "OK" }, 0);
-                dialog.open();
-                page.setFocusToTextBox();
-                return false;
-            }
-        }
-        return true;
-    }
+        try {
+            getContainer().run(true, false, new IRunnableWithProgress() {
 
-    public DeleteCategory getDeleteCategory() {
-        if (null == page) {
-            return DeleteCategory.NONE;
+                @Override
+                public void run(IProgressMonitor monitor)
+                        throws InvocationTargetException, InterruptedException {
+                    ResourceManager resourceManager = Activator.getDefault()
+                            .getResourceManager();
+                    try {
+                        monitor.beginTask("Resource Deletion", 2);
+                        monitor.worked(1);
+                        Set<SingleResource> singleResources = page
+                                .getSelectedSingleResourcesList();
+                        if (null != singleResources
+                                && singleResources.size() > 0) {
+                            Activator.getDefault().getResourceManager()
+                                    .removeSingleResources(singleResources);
+
+                            Resource res = resourceManager
+                                    .getCurrentResourceInSelection();
+                            if (null != res && res instanceof SingleResource) {
+                                if (singleResources
+                                        .contains((SingleResource) res)) {
+                                    resourceManager
+                                            .resourceSelectionChanged(null);
+                                }
+                            }
+                        }
+                        monitor.worked(1);
+                        success = true;
+                    } catch (SimulatorException e) {
+                        success = false;
+                    } finally {
+                        monitor.done();
+                    }
+                }
+            });
+        } catch (InvocationTargetException e) {
+            Activator.getDefault().getLogManager()
+                    .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
+        } catch (InterruptedException e) {
+            Activator.getDefault().getLogManager()
+                    .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
         }
-        return page.getDeleteCategory();
+        return true;
     }
 
-    public String getDeleteCandidate() {
-        if (null == page) {
-            return null;
-        }
-        return page.getDeleteCandidate();
+    public boolean getStatus() {
+        return success;
     }
 }
\ No newline at end of file
index b43d4cc..48be0a3 100644 (file)
 
 package oic.simulator.serviceprovider.view.dialogs;
 
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Map;
-
-import oic.simulator.serviceprovider.manager.LogManager;
-
 import org.eclipse.jface.dialogs.TrayDialog;
 import org.eclipse.swt.SWT;
 import org.eclipse.swt.events.SelectionAdapter;
@@ -34,6 +28,12 @@ import org.eclipse.swt.widgets.Control;
 import org.eclipse.swt.widgets.Group;
 import org.eclipse.swt.widgets.Shell;
 
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Map;
+
+import oic.simulator.serviceprovider.manager.LogManager;
+
 /**
  * This class shows a dialog for filtering logs based on severity levels.
  */
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/LoadRamlPage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/LoadRamlPage.java
new file mode 100644 (file)
index 0000000..0a253eb
--- /dev/null
@@ -0,0 +1,353 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.view.dialogs;
+
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.operation.IRunnableWithProgress;
+import org.eclipse.jface.wizard.IWizardPage;
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.KeyAdapter;
+import org.eclipse.swt.events.KeyEvent;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.ui.PlatformUI;
+
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.util.Date;
+
+import org.oic.simulator.ILogger.Level;
+import org.oic.simulator.SimulatorException;
+import org.oic.simulator.server.SimulatorResource;
+import org.oic.simulator.server.SimulatorResource.Type;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.model.SingleResource;
+import oic.simulator.serviceprovider.utils.Constants;
+import oic.simulator.serviceprovider.utils.Utility;
+import oic.simulator.serviceprovider.view.dialogs.MainPage.Option;
+
+/**
+ * This class shows UI for creating resources.
+ */
+public class LoadRamlPage extends WizardPage {
+
+    private Text                   locationTxt;
+    private Button                 btnBrowse;
+    private Text                   noOfInstancesText;
+    private Label                  noOfInstancesLbl;
+    private Label                  locationLbl;
+
+    private String                 configFilePath = null;
+    private int                    resourceCount;
+
+    private Resource               resource;
+
+    private SimulatorResource.Type typeOfResource;
+
+    protected LoadRamlPage() {
+        super("Create Resource");
+        resourceCount = -1;
+    }
+
+    public void initialSetup(SimulatorResource.Type type) {
+        this.typeOfResource = type;
+        if (!noOfInstancesLbl.isDisposed()) {
+            noOfInstancesLbl.setVisible(type == Type.SINGLE);
+        }
+        if (!noOfInstancesText.isDisposed()) {
+            noOfInstancesText.setVisible(type == Type.SINGLE);
+        }
+    }
+
+    @Override
+    public void createControl(Composite parent) {
+        setPageComplete(false);
+        setTitle(Constants.CREATE_PAGE_TITLE);
+        setMessage(Constants.CREATE_PAGE_MESSAGE);
+        Composite compContent = new Composite(parent, SWT.NONE);
+        GridLayout gridLayout = new GridLayout();
+        compContent.setLayout(gridLayout);
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        compContent.setLayoutData(gd);
+
+        Group configGroup = new Group(compContent, SWT.NONE);
+        gridLayout = new GridLayout(1, false);
+        gridLayout.verticalSpacing = 10;
+        gridLayout.marginTop = 5;
+        configGroup.setLayout(gridLayout);
+        gd = new GridData();
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        configGroup.setLayoutData(gd);
+        configGroup.setText("Load RAML File");
+
+        Composite cusConfigComp = new Composite(configGroup, SWT.NONE);
+        cusConfigComp.setLayout(new GridLayout(3, false));
+        gd = new GridData();
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        cusConfigComp.setLayoutData(gd);
+
+        locationLbl = new Label(cusConfigComp, SWT.NONE);
+        locationLbl.setText("Location:");
+
+        locationTxt = new Text(cusConfigComp, SWT.BORDER);
+        gd = new GridData();
+        gd.minimumWidth = 300;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        locationTxt.setLayoutData(gd);
+
+        btnBrowse = new Button(cusConfigComp, SWT.NONE);
+        btnBrowse.setText("Browse");
+        gd = new GridData();
+        gd.widthHint = 80;
+        gd.horizontalAlignment = SWT.FILL;
+        btnBrowse.setLayoutData(gd);
+        btnBrowse.setFocus();
+
+        Composite instanceComp = new Composite(compContent, SWT.NONE);
+        instanceComp.setLayout(new GridLayout(2, false));
+        gd = new GridData();
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        instanceComp.setLayoutData(gd);
+
+        noOfInstancesLbl = new Label(instanceComp, SWT.NONE);
+        noOfInstancesLbl.setText("Number of Instances");
+
+        noOfInstancesText = new Text(instanceComp, SWT.BORDER);
+        gd = new GridData();
+        gd.widthHint = 50;
+        gd.horizontalAlignment = SWT.FILL;
+        noOfInstancesText.setLayoutData(gd);
+
+        // Adding the default value. It can be changed by the user.
+        noOfInstancesText.setText("1");
+
+        addUIListeners();
+
+        setControl(compContent);
+    }
+
+    private void addUIListeners() {
+        btnBrowse.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                FileDialog fileDialog = new FileDialog(PlatformUI
+                        .getWorkbench().getDisplay().getActiveShell(), SWT.NONE);
+                fileDialog
+                        .setFilterExtensions(Constants.BROWSE_RAML_FILTER_EXTENSIONS);
+                String configFileAbsolutePath = fileDialog.open();
+                if (null != configFileAbsolutePath)
+                    locationTxt.setText(configFileAbsolutePath);
+            }
+        });
+
+        locationTxt.addModifyListener(new ModifyListener() {
+            @Override
+            public void modifyText(ModifyEvent e) {
+                configFilePath = locationTxt.getText();
+                getWizard().getContainer().updateButtons();
+            }
+        });
+
+        noOfInstancesText.addListener(SWT.Verify, new Listener() {
+            @Override
+            public void handleEvent(Event e) {
+                String string = e.text;
+                char[] chars = new char[string.length()];
+                string.getChars(0, chars.length, chars, 0);
+                for (int i = 0; i < chars.length; i++) {
+                    if (!('0' <= chars[i] && chars[i] <= '9')) {
+                        e.doit = false;
+                        return;
+                    }
+                }
+            }
+        });
+
+        noOfInstancesText.addKeyListener(new KeyAdapter() {
+            @Override
+            public void keyReleased(KeyEvent e) {
+                getWizard().getContainer().updateButtons();
+            }
+        });
+    }
+
+    @Override
+    public boolean canFlipToNextPage() {
+        boolean done = false;
+        try {
+            resourceCount = Integer.parseInt(noOfInstancesText.getText());
+        } catch (Exception e) {
+            resourceCount = -1;
+        }
+        if (null != configFilePath && configFilePath.trim().length() > 0) {
+            if (resourceCount == 1) {
+                done = true;
+            }
+        }
+        return done;
+    }
+
+    public boolean isSelectionDone() {
+        boolean done = false;
+        try {
+            resourceCount = Integer.parseInt(noOfInstancesText.getText());
+        } catch (Exception e) {
+            resourceCount = -1;
+        }
+        if (null != configFilePath && configFilePath.trim().length() > 0) {
+            if (resourceCount >= 1) {
+                done = true;
+            }
+        }
+        return done;
+    }
+
+    public boolean isMultiResourceCreation() {
+        if (typeOfResource == Type.SINGLE && resourceCount > 1) {
+            return true;
+        }
+        return false;
+    }
+
+    @Override
+    public IWizardPage getNextPage() {
+        // Validate the file path.
+        FileInputStream fileStream = null;
+        try {
+            fileStream = new FileInputStream(configFilePath);
+        } catch (FileNotFoundException e) {
+            MessageDialog
+                    .openError(getShell(), "Invalid File",
+                            "File doesn't exist. Either the file path or file name is invalid.");
+            return null;
+        } finally {
+            if (null != fileStream)
+                try {
+                    fileStream.close();
+                } catch (IOException e) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(),
+                                    new Date(),
+                                    "There is an error while closing the file stream.\n"
+                                            + Utility.getSimulatorErrorString(
+                                                    e, null));
+                }
+        }
+
+        // Checking the resource count
+        if ((Activator.getDefault().getResourceManager().getResourceCount() + resourceCount) > Constants.MAX_RESOURCE_COUNT) {
+            MessageDialog
+                    .openInformation(Display.getDefault().getActiveShell(),
+                            "Resource limit exceeded",
+                            "Exceeded the limit of resources that can exist in the server.");
+            return null;
+        }
+
+        final CreateResourceWizard wizard = ((CreateResourceWizard) getWizard());
+
+        try {
+            getContainer().run(true, false, new IRunnableWithProgress() {
+                @Override
+                public void run(IProgressMonitor monitor)
+                        throws InvocationTargetException, InterruptedException {
+                    try {
+                        monitor.beginTask("Resource Creation With RAML", 2);
+                        monitor.worked(1);
+                        resource = Activator.getDefault().getResourceManager()
+                                .createResourceByRAML(configFilePath);
+                        monitor.worked(1);
+                    } catch (SimulatorException e) {
+                        wizard.setStatus("Failed to create resource.\n"
+                                + Utility.getSimulatorErrorString(e, null));
+                    } finally {
+                        monitor.done();
+                    }
+                }
+            });
+        } catch (InvocationTargetException e) {
+            Activator.getDefault().getLogManager()
+                    .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
+            e.printStackTrace();
+        } catch (InterruptedException e) {
+            Activator.getDefault().getLogManager()
+                    .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
+            e.printStackTrace();
+        }
+        if (null == resource) {
+            wizard.setStatus("Failed to create Resource.");
+            wizard.getWizardDialog().close();
+            return null;
+        } else {
+            // Checking whether the resource is of type single.
+            Option intendedResource = wizard.getMainPage().getOption();
+            if ((intendedResource == Option.SIMPLE_FROM_RAML && !(resource instanceof SingleResource))) {
+                MessageDialog
+                        .openError(
+                                getShell(),
+                                "Invalid RAML",
+                                "Uploaded RAML is not of simple type. "
+                                        + "Please upload the proper RAML of simple type.");
+                return null;
+            }
+        }
+        UpdatePropertiesPage updatePageRef = wizard.getUpdatePropPage();
+        updatePageRef.setResName(resource.getResourceName());
+        updatePageRef.setResURI(resource.getResourceURI());
+        return updatePageRef;
+    }
+
+    public String getConfigFilePath() {
+        return configFilePath;
+    }
+
+    public int getResourceCount() {
+        return resourceCount;
+    }
+
+    public Resource getResource() {
+        return resource;
+    }
+
+    public void setResource(Resource resource) {
+        this.resource = resource;
+    }
+}
\ No newline at end of file
index 81c1f6a..4549360 100644 (file)
@@ -16,9 +16,6 @@
 
 package oic.simulator.serviceprovider.view.dialogs;
 
-import java.text.DateFormat;
-import java.util.Date;
-
 import org.eclipse.jface.dialogs.Dialog;
 import org.eclipse.jface.dialogs.IDialogConstants;
 import org.eclipse.swt.SWT;
@@ -34,6 +31,9 @@ import org.eclipse.swt.widgets.Label;
 import org.eclipse.swt.widgets.Shell;
 import org.eclipse.swt.widgets.Text;
 
+import java.text.DateFormat;
+import java.util.Date;
+
 /**
  * This class shows detailed information about a log. The dialog will be opened
  * on double-clicking a log entry in the log view.
@@ -108,7 +108,8 @@ public class LogDetailsDialog extends Dialog {
         gd.grabExcessHorizontalSpace = true;
         l5.setLayoutData(gd);
 
-        new Label(container, SWT.NONE); // separator
+        Label seperator = new Label(container, SWT.NONE); // separator
+        seperator.setText("");
 
         Label l6 = new Label(container, SWT.NONE);
         l6.setText("Message details");
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/MainPage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/MainPage.java
new file mode 100644 (file)
index 0000000..60c90ac
--- /dev/null
@@ -0,0 +1,141 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.view.dialogs;
+
+import org.eclipse.jface.wizard.IWizardPage;
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Text;
+
+import org.oic.simulator.server.SimulatorResource.Type;
+
+import oic.simulator.serviceprovider.utils.Constants;
+
+public class MainPage extends WizardPage {
+
+    private Button simpleBtn;
+    private Button simpleFromRamlBtn;
+    private Text   description;
+
+    public enum Option {
+        SIMPLE, SIMPLE_FROM_RAML
+    }
+
+    private Option option;
+
+    protected MainPage() {
+        super("Main Page");
+    }
+
+    @Override
+    public void createControl(Composite parent) {
+        setPageComplete(false);
+        setTitle(Constants.MAIN_PAGE_TITLE);
+        setMessage(Constants.MAIN_PAGE_MESSAGE);
+        Composite compContent = new Composite(parent, SWT.NONE);
+        GridLayout gridLayout = new GridLayout();
+        compContent.setLayout(gridLayout);
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        compContent.setLayoutData(gd);
+
+        simpleBtn = new Button(compContent, SWT.RADIO);
+        simpleBtn.setText("Simple resource");
+
+        simpleFromRamlBtn = new Button(compContent, SWT.RADIO);
+        simpleFromRamlBtn.setText("Simple resource(From RAML)");
+
+        Label lbl = new Label(compContent, SWT.NULL);
+        lbl.setText("Details:");
+        gd = new GridData();
+        gd.verticalIndent = 20;
+        lbl.setLayoutData(gd);
+
+        description = new Text(compContent, SWT.MULTI | SWT.READ_ONLY
+                | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
+        description.setBackground(compContent.getBackground());
+        description.setText("[Select an option to view more details]");
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        description.setLayoutData(gd);
+
+        addUIListeners();
+
+        setControl(compContent);
+    }
+
+    private void addUIListeners() {
+        simpleBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                description
+                        .setText("Create a simple resource by manually entering all the details given below.\n"
+                                + "\t1. Basic resource details: URI, Name, Resource Type, and Interface types.\n"
+                                + "\t2. Options such as Observable and Discoverable.\n"
+                                + "\t3. Adding simple attributes.");
+                option = Option.SIMPLE;
+                getWizard().getContainer().updateButtons();
+            }
+        });
+
+        simpleFromRamlBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                description
+                        .setText("Create a simple resource from RAML configuration file.\n"
+                                + "\t1. Resource details, attributes, and other properties will be read from RAML.\n"
+                                + "\t2. Supports multi-instance creation.\n"
+                                + "\t3. For single instance creation, allows editing the URI and Name of the resource.");
+                option = Option.SIMPLE_FROM_RAML;
+                getWizard().getContainer().updateButtons();
+            }
+        });
+    }
+
+    @Override
+    public boolean canFlipToNextPage() {
+        return true;
+    }
+
+    @Override
+    public IWizardPage getPreviousPage() {
+        return null;
+    }
+
+    @Override
+    public IWizardPage getNextPage() {
+        CreateResourceWizard createWizard = (CreateResourceWizard) getWizard();
+        if (simpleBtn.getSelection()) {
+            return createWizard.getSimpleResourceBasicDetailsPage();
+        }
+        if (simpleFromRamlBtn.getSelection()) {
+            LoadRamlPage page = createWizard.getLoadRamlPage();
+            page.initialSetup(Type.SINGLE);
+            return page;
+        }
+        return null;
+    }
+
+    public Option getOption() {
+        return option;
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/ModelArrayAddItemDialog.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/ModelArrayAddItemDialog.java
new file mode 100644 (file)
index 0000000..85bc7a4
--- /dev/null
@@ -0,0 +1,293 @@
+/*
+ * 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 oic.simulator.serviceprovider.view.dialogs;
+
+import org.eclipse.jface.dialogs.TitleAreaDialog;
+import org.eclipse.jface.viewers.ILabelProviderListener;
+import org.eclipse.jface.viewers.ITableLabelProvider;
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.jface.viewers.TreeViewerColumn;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeColumn;
+
+import java.util.Map;
+
+import org.oic.simulator.AttributeValue.ValueType;
+import org.oic.simulator.SimulatorResourceAttribute;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.manager.ResourceManager;
+import oic.simulator.serviceprovider.model.AttributeElement;
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.model.ResourceRepresentation;
+import oic.simulator.serviceprovider.utils.Utility;
+import oic.simulator.serviceprovider.view.AttributeEditingSupport;
+
+/**
+ * This class manages and shows the automation settings dialog from the
+ * attribute view.
+ */
+public class ModelArrayAddItemDialog extends TitleAreaDialog {
+
+    private TreeViewer              attViewer;
+
+    private AttributeEditingSupport attributeEditor;
+
+    private final String[]          attTblHeaders  = { "Attribute Name",
+            "Attribute Value"                     };
+    private final Integer[]         attTblColWidth = { 200, 300 };
+
+    private ResourceManager         resourceManager;
+
+    private ResourceRepresentation  representation;
+
+    public ModelArrayAddItemDialog(Shell parentShell,
+            ResourceRepresentation representation) {
+        super(parentShell);
+        resourceManager = Activator.getDefault().getResourceManager();
+        this.representation = representation;
+    }
+
+    @Override
+    public void create() {
+        super.create();
+        setTitle("Add Items To Complex Array");
+        setMessage("Add one or more items in the complex array type attribute");
+    }
+
+    @Override
+    protected Control createDialogArea(Composite parent) {
+        Composite compLayout = (Composite) super.createDialogArea(parent);
+
+        compLayout.setLayout(new GridLayout());
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        compLayout.setLayoutData(gd);
+
+        Group attGroup = new Group(compLayout, SWT.NONE);
+        attGroup.setLayout(new GridLayout());
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        attGroup.setLayoutData(gd);
+        attGroup.setText("Attributes");
+
+        Tree addressTree = new Tree(attGroup, SWT.SINGLE | SWT.BORDER
+                | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
+        addressTree.setHeaderVisible(true);
+
+        attViewer = new TreeViewer(addressTree);
+
+        createAttributeColumns(attViewer);
+
+        // make lines and header visible
+        Tree tree = attViewer.getTree();
+        tree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+        tree.setHeaderVisible(true);
+        tree.setLinesVisible(true);
+
+        attViewer.setContentProvider(new AttributeContentProvider());
+        attViewer.setLabelProvider(new AttributeLabelProvider());
+
+        // Check whether there is any resource selected already
+        Resource resource = resourceManager.getCurrentResourceInSelection();
+        if (resource != null) {
+            attViewer.setInput(representation);
+            attViewer.expandAll();
+        }
+
+        return compLayout;
+    }
+
+    public void createAttributeColumns(TreeViewer viewer) {
+        Tree tree = viewer.getTree();
+
+        attributeEditor = new AttributeEditingSupport();
+
+        TreeColumn attName = new TreeColumn(tree, SWT.NONE);
+        attName.setWidth(attTblColWidth[0]);
+        attName.setText(attTblHeaders[0]);
+
+        TreeColumn attValue = new TreeColumn(tree, SWT.NONE);
+        attValue.setWidth(attTblColWidth[1]);
+        attValue.setText(attTblHeaders[1]);
+
+        TreeViewerColumn attValueVwrCol = new TreeViewerColumn(attViewer,
+                attValue);
+        attValueVwrCol.setEditingSupport(attributeEditor
+                .createAttributeValueEditor(attViewer, false));
+
+        addColumnListeners();
+    }
+
+    private void addColumnListeners() {
+        TreeColumn[] columns = attViewer.getTree().getColumns();
+        for (TreeColumn column : columns) {
+            column.addSelectionListener(new SelectionAdapter() {
+                @Override
+                public void widgetSelected(SelectionEvent e) {
+                    // Refreshing the viewer. If combo list is open,
+                    // then click events on other parts of the view or outside
+                    // the combo should hide the editor.
+                    // Refreshing the viewer hides the combo and other editors
+                    // which are active.
+                    attViewer.refresh();
+                }
+            });
+        }
+    }
+
+    private static class AttributeContentProvider implements
+            ITreeContentProvider {
+
+        @Override
+        public void dispose() {
+        }
+
+        @Override
+        public void inputChanged(Viewer viewer, Object oldAttribute,
+                Object newAttribute) {
+        }
+
+        @Override
+        public Object[] getChildren(Object attribute) {
+            if (attribute instanceof AttributeElement) {
+                Map<String, AttributeElement> childs = ((AttributeElement) attribute)
+                        .getChildren();
+                if (null == childs) {
+                    return new Object[0];
+                }
+
+                return childs.values().toArray();
+            }
+
+            return new Object[0];
+        }
+
+        @Override
+        public Object getParent(Object attribute) {
+            if (attribute instanceof AttributeElement)
+                return ((AttributeElement) attribute).getParent();
+            return null;
+        }
+
+        @Override
+        public boolean hasChildren(Object attribute) {
+            if (attribute instanceof AttributeElement)
+                return ((AttributeElement) attribute).hasChildren();
+            return false;
+        }
+
+        @Override
+        public Object[] getElements(Object resourceModel) {
+            if (resourceModel instanceof ResourceRepresentation) {
+                return ((ResourceRepresentation) resourceModel).getAttributes()
+                        .values().toArray();
+            }
+
+            return new Object[0];
+        }
+    }
+
+    private static class AttributeLabelProvider implements ITableLabelProvider {
+
+        @Override
+        public void addListener(ILabelProviderListener arg0) {
+        }
+
+        @Override
+        public void dispose() {
+        }
+
+        @Override
+        public boolean isLabelProperty(Object arg0, String arg1) {
+            return false;
+        }
+
+        @Override
+        public void removeListener(ILabelProviderListener arg0) {
+
+        }
+
+        @Override
+        public Image getColumnImage(Object element, int col) {
+            return null;
+        }
+
+        @Override
+        public String getColumnText(Object element, int column) {
+            if (element instanceof AttributeElement) {
+                AttributeElement attrElement = (AttributeElement) element;
+                switch (column) {
+                    case 0: // Attribute name column
+                    {
+                        SimulatorResourceAttribute attribute = attrElement
+                                .getSimulatorResourceAttribute();
+                        return attribute.name();
+                    }
+
+                    case 1: // Attribute value column
+                    {
+                        SimulatorResourceAttribute attribute = attrElement
+                                .getSimulatorResourceAttribute();
+
+                        if (attribute.value().typeInfo().mBaseType != ValueType.RESOURCEMODEL) {
+                            String value = Utility
+                                    .getAttributeValueAsString(attribute
+                                            .value());
+                            if (null == value) {
+                                value = "";
+                            }
+                            return value;
+                        }
+                        return null;
+                    }
+                }
+            }
+
+            return null;
+        }
+
+    }
+
+    @Override
+    protected Point getInitialSize() {
+        Point initialPoint = super.getInitialSize();
+        initialPoint.y += 100;
+        return initialPoint;
+    }
+
+    @Override
+    protected boolean isResizable() {
+        return true;
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+}
index 09f95fe..df8b03d 100644 (file)
 
 package oic.simulator.serviceprovider.view.dialogs;
 
-import org.eclipse.jface.dialogs.IDialogConstants;
 import org.eclipse.jface.wizard.IWizard;
+import org.eclipse.jface.wizard.IWizardPage;
 import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
 import org.eclipse.swt.widgets.Shell;
 
 /**
@@ -28,8 +26,11 @@ import org.eclipse.swt.widgets.Shell;
  */
 public class ResourceWizardDialog extends WizardDialog {
 
+    private IWizard wizard;
+
     public ResourceWizardDialog(Shell parentShell, IWizard newWizard) {
         super(parentShell, newWizard);
+        wizard = newWizard;
     }
 
     @Override
@@ -43,11 +44,37 @@ public class ResourceWizardDialog extends WizardDialog {
     }
 
     @Override
-    protected void createButtonsForButtonBar(Composite parent) {
-        super.createButtonsForButtonBar(parent);
-        Button finishButton = getButton(IDialogConstants.FINISH_ID);
-        if (finishButton != null) {
-            finishButton.setText(IDialogConstants.OK_LABEL);
+    protected void backPressed() {
+        if (wizard.getClass() == CreateResourceWizard.class) {
+            CreateResourceWizard createWizard = (CreateResourceWizard) wizard;
+
+            MainPage mainPage = createWizard.getMainPage();
+            SimpleResourceBasicDetailsPage simpleResourceBasicDetailsPage = createWizard
+                    .getSimpleResourceBasicDetailsPage();
+            SimpleResourceOtherDetailsPage simpleResourceOtherDetailsPage = createWizard
+                    .getSimpleResourceOtherDetailsPage();
+            SimpleResourceAddAttributePage simpleResourceAddAttributesPage = createWizard
+                    .getSimpleResourceAddAttributePage();
+            LoadRamlPage loadRamlPage = createWizard.getLoadRamlPage();
+            UpdatePropertiesPage updatePropPage = createWizard
+                    .getUpdatePropPage();
+
+            IWizardPage curPage = wizard.getContainer().getCurrentPage();
+            IWizardPage prevPage = null;
+
+            if (curPage == loadRamlPage
+                    || curPage == simpleResourceBasicDetailsPage) {
+                prevPage = mainPage;
+            } else if (curPage == updatePropPage) {
+                loadRamlPage.setResource(null);
+                prevPage = loadRamlPage;
+            } else if (curPage == simpleResourceAddAttributesPage) {
+                prevPage = simpleResourceBasicDetailsPage;
+            } else if (curPage == simpleResourceOtherDetailsPage) {
+                prevPage = simpleResourceAddAttributesPage;
+            }
+            if (null != prevPage)
+                showPage(prevPage);
         }
     }
 }
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourceAddAttributePage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourceAddAttributePage.java
new file mode 100644 (file)
index 0000000..b1eefba
--- /dev/null
@@ -0,0 +1,392 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.view.dialogs;
+
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.jface.viewers.StyledCellLabelProvider;
+import org.eclipse.jface.viewers.TableViewer;
+import org.eclipse.jface.viewers.TableViewerColumn;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerCell;
+import org.eclipse.jface.window.Window;
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Table;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+import oic.simulator.serviceprovider.model.AttributeHelper;
+import oic.simulator.serviceprovider.model.AttributeHelper.ValidValuesType;
+import oic.simulator.serviceprovider.utils.Constants;
+import oic.simulator.serviceprovider.utils.Utility;
+
+public class SimpleResourceAddAttributePage extends WizardPage {
+
+    private TableViewer          attTblViewer;
+    private Button               addBtn;
+    private Button               remBtn;
+    private Button               editBtn;
+
+    private final String[]       attTblHeaders  = { "Name", "Type", "Range",
+            "Allowed Values", "Default Value"  };
+    private final Integer[]      attTblColWidth = { 90, 75, 75, 150, 75 };
+
+    private Set<AttributeHelper> attributes;
+
+    protected SimpleResourceAddAttributePage() {
+        super("Add Attributes");
+        attributes = new HashSet<AttributeHelper>();
+    }
+
+    @Override
+    public void createControl(Composite parent) {
+        setPageComplete(false);
+        setTitle(Constants.SIMPLE_RESOURCE_ADD_ATTRIBUTE_PAGE_TITLE);
+        setMessage(Constants.SIMPLE_RESOURCE_ADD_ATTRIBUTE_PAGE_MESSAGE);
+        Composite compContent = new Composite(parent, SWT.NONE);
+        GridLayout gridLayout = new GridLayout(2, false);
+        compContent.setLayout(gridLayout);
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        compContent.setLayoutData(gd);
+
+        Label lbl = new Label(compContent, SWT.NULL);
+        lbl.setText("Attributes:");
+        gd = new GridData();
+        gd.horizontalSpan = 2;
+        lbl.setLayoutData(gd);
+
+        setupAttributeTable(compContent);
+
+        setupAttributeControls(compContent);
+
+        setUiListeners(compContent);
+
+        setControl(compContent);
+    }
+
+    private void setupAttributeTable(Composite attComp) {
+        attTblViewer = new TableViewer(attComp, SWT.MULTI | SWT.H_SCROLL
+                | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
+
+        createAttributeColumns(attTblViewer);
+
+        // Make lines and header visible
+        Table table = attTblViewer.getTable();
+        table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+        table.setHeaderVisible(true);
+        table.setLinesVisible(true);
+
+        attTblViewer.setContentProvider(new AttributeContentProvider());
+    }
+
+    public void createAttributeColumns(TableViewer tableViewer) {
+
+        TableViewerColumn attName = new TableViewerColumn(tableViewer, SWT.NONE);
+        attName.getColumn().setWidth(attTblColWidth[0]);
+        attName.getColumn().setText(attTblHeaders[0]);
+        attName.setLabelProvider(new StyledCellLabelProvider() {
+            @Override
+            public void update(ViewerCell cell) {
+                Object e = cell.getElement();
+                if (null == e) {
+                    return;
+                }
+                AttributeHelper att = (AttributeHelper) e;
+                cell.setText(att.getAttributeName());
+
+            }
+        });
+
+        TableViewerColumn attType = new TableViewerColumn(tableViewer, SWT.NONE);
+        attType.getColumn().setWidth(attTblColWidth[1]);
+        attType.getColumn().setText(attTblHeaders[1]);
+        attType.setLabelProvider(new StyledCellLabelProvider() {
+            @Override
+            public void update(ViewerCell cell) {
+                Object e = cell.getElement();
+                if (null == e) {
+                    return;
+                }
+                AttributeHelper att = (AttributeHelper) e;
+                cell.setText(att.getAttributeType());
+            }
+        });
+
+        TableViewerColumn attRange = new TableViewerColumn(tableViewer,
+                SWT.NONE);
+        attRange.getColumn().setWidth(attTblColWidth[2]);
+        attRange.getColumn().setText(attTblHeaders[2]);
+        attRange.setLabelProvider(new StyledCellLabelProvider() {
+            @Override
+            public void update(ViewerCell cell) {
+                Object e = cell.getElement();
+                if (null == e) {
+                    return;
+                }
+                AttributeHelper att = (AttributeHelper) e;
+                if (att.getValidValuesType() != ValidValuesType.RANGE) {
+                    cell.setText("Nil");
+                } else {
+                    String min = att.getMin();
+                    String max = att.getMax();
+                    if (null != min && null != max) {
+                        cell.setText("[" + att.getMin() + " to " + att.getMax()
+                                + "]");
+                    } else {
+                        cell.setText("Nil");
+                    }
+                }
+            }
+        });
+
+        TableViewerColumn attAllwdValues = new TableViewerColumn(tableViewer,
+                SWT.NONE);
+        attAllwdValues.getColumn().setWidth(attTblColWidth[3]);
+        attAllwdValues.getColumn().setText(attTblHeaders[3]);
+        attAllwdValues.setLabelProvider(new StyledCellLabelProvider() {
+            @Override
+            public void update(ViewerCell cell) {
+                Object e = cell.getElement();
+                if (null == e) {
+                    return;
+                }
+                AttributeHelper att = (AttributeHelper) e;
+                if (att.getValidValuesType() != ValidValuesType.VALUESET) {
+                    cell.setText("Nil");
+                } else {
+                    cell.setText(att.getAllowedValues().toString());
+                }
+            }
+        });
+
+        TableViewerColumn attDflValue = new TableViewerColumn(tableViewer,
+                SWT.NONE);
+        attDflValue.getColumn().setWidth(attTblColWidth[4]);
+        attDflValue.getColumn().setText(attTblHeaders[4]);
+        attDflValue.setLabelProvider(new StyledCellLabelProvider() {
+            @Override
+            public void update(ViewerCell cell) {
+                Object e = cell.getElement();
+                if (null == e) {
+                    return;
+                }
+                AttributeHelper att = (AttributeHelper) e;
+                cell.setText(att.getAttributeDflValue());
+            }
+        });
+    }
+
+    private void setupAttributeControls(Composite compContent) {
+
+        Composite innerComp = new Composite(compContent, SWT.NULL);
+        innerComp.setLayout(new GridLayout());
+        GridData gd = new GridData();
+        gd.verticalAlignment = SWT.TOP;
+        innerComp.setLayoutData(gd);
+
+        addBtn = new Button(innerComp, SWT.PUSH);
+        addBtn.setText("Add");
+        gd = new GridData();
+        gd.widthHint = 70;
+        addBtn.setLayoutData(gd);
+
+        editBtn = new Button(innerComp, SWT.PUSH);
+        editBtn.setText("Edit");
+        editBtn.setEnabled(false);
+        gd = new GridData();
+        gd.widthHint = 70;
+        editBtn.setLayoutData(gd);
+
+        remBtn = new Button(innerComp, SWT.PUSH);
+        remBtn.setText("Remove");
+        remBtn.setEnabled(false);
+        gd = new GridData();
+        gd.widthHint = 70;
+        remBtn.setLayoutData(gd);
+    }
+
+    private void setUiListeners(Composite compContent) {
+        addBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                Set<String> rTypes = Utility.getAttributeTypes();
+                AddAttributeDialog dialog = new AddAttributeDialog(Display
+                        .getDefault().getActiveShell(), null, rTypes,
+                        attributes);
+                if (dialog.open() == Window.OK) {
+                    AttributeHelper att = dialog.getAttHelper();
+                    attributes.add(att);
+                    remBtn.setEnabled(true);
+                    AttributeContentProvider provider = (AttributeContentProvider) attTblViewer
+                            .getContentProvider();
+                    provider.addAttribute(att);
+                    attTblViewer.add(att);
+                    attTblViewer.getTable().deselectAll();
+                    attTblViewer.getTable().select(
+                            attTblViewer.getTable().getItemCount() - 1);
+                    editBtn.setEnabled(true);
+                }
+            }
+        });
+
+        editBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                IStructuredSelection selection = (IStructuredSelection) attTblViewer
+                        .getSelection();
+                if (null == selection) {
+                    editBtn.setEnabled(false);
+                    return;
+                }
+                AttributeHelper att = (AttributeHelper) selection
+                        .getFirstElement();
+                if (null == att) {
+                    editBtn.setEnabled(false);
+                    return;
+                }
+                // Opening the dialog for edit operation.
+                // Passing the attribute to populate UI controls with data.
+                Set<String> rTypes = Utility.getAttributeTypes();
+                AddAttributeDialog dialog = new AddAttributeDialog(Display
+                        .getDefault().getActiveShell(), att, rTypes, attributes);
+                if (dialog.open() != Window.OK) {
+                    AttributeHelper newAtt = dialog.getAttClone();
+                    if (null != newAtt) {
+                        att.setAttributeName(newAtt.getAttributeName());
+                        att.setAttributeType(newAtt.getAttributeType());
+                        att.setAttributeDflValue(newAtt.getAttributeDflValue());
+                        att.setValidValuesType(newAtt.getValidValuesType());
+                        att.setMin(newAtt.getMin());
+                        att.setMax(newAtt.getMax());
+                        att.setAllowedValues(newAtt.getAllowedValues());
+                    }
+                }
+                attTblViewer.update(att, null);
+            }
+        });
+
+        remBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                IStructuredSelection selection = (IStructuredSelection) attTblViewer
+                        .getSelection();
+                if (null != selection) {
+                    Iterator<?> itr = selection.iterator();
+                    while (itr.hasNext()) {
+                        AttributeHelper att = (AttributeHelper) itr.next();
+                        attTblViewer.remove(att);
+                        attributes.remove(att);
+                        AttributeContentProvider provider = (AttributeContentProvider) attTblViewer
+                                .getContentProvider();
+                        provider.removeAttribute(att);
+                    }
+                    if (attributes.size() < 1) {
+                        remBtn.setEnabled(false);
+                    }
+                    editBtn.setEnabled(false);
+                }
+            }
+        });
+
+        attTblViewer
+                .addSelectionChangedListener(new ISelectionChangedListener() {
+
+                    @Override
+                    public void selectionChanged(SelectionChangedEvent event) {
+                        remBtn.setEnabled(true);
+                        IStructuredSelection selection = (IStructuredSelection) event
+                                .getSelection();
+                        if (null == selection) {
+                            return;
+                        }
+                        if (selection.size() > 1) {
+                            editBtn.setEnabled(false);
+                        } else {
+                            editBtn.setEnabled(true);
+                        }
+                    }
+                });
+    }
+
+    private static class AttributeContentProvider implements
+            ITreeContentProvider {
+
+        List<AttributeHelper> attList = new ArrayList<AttributeHelper>();
+
+        @SuppressWarnings("unchecked")
+        @Override
+        public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+            attList = (List<AttributeHelper>) newInput;
+        }
+
+        @Override
+        public Object[] getChildren(Object element) {
+            return new Object[0];
+        }
+
+        @Override
+        public Object[] getElements(Object input) {
+            return attList.toArray();
+        }
+
+        @Override
+        public Object getParent(Object element) {
+            return null;
+        }
+
+        @Override
+        public boolean hasChildren(Object element) {
+            return false;
+        }
+
+        @Override
+        public void dispose() {
+        }
+
+        public synchronized void addAttribute(AttributeHelper newElement) {
+            attList.add(newElement);
+        }
+
+        public synchronized void removeAttribute(AttributeHelper element) {
+            attList.remove(element);
+        }
+    }
+
+    @Override
+    public boolean canFlipToNextPage() {
+        return false;
+    }
+
+    public Set<AttributeHelper> getAttributes() {
+        return attributes;
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourceBasicDetailsPage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourceBasicDetailsPage.java
new file mode 100644 (file)
index 0000000..db4a61e
--- /dev/null
@@ -0,0 +1,381 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.view.dialogs;
+
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.window.Window;
+import org.eclipse.jface.wizard.IWizardPage;
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.List;
+import org.eclipse.swt.widgets.Text;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.model.SingleResource;
+import oic.simulator.serviceprovider.utils.Constants;
+import oic.simulator.serviceprovider.utils.Utility;
+
+public class SimpleResourceBasicDetailsPage extends WizardPage {
+
+    private Text                resNameTxt;
+    private Text                resUriTxt;
+    private Text                resTypeTxt;
+
+    private Button              observeBtn;
+    private Button              discoverBtn;
+    private Button              addIfTypeBtn;
+    private Button              removeIfTypeBtn;
+
+    private List                ifTypesList;
+
+    private String              resName;
+    private String              resURI;
+    private String              resType;
+    private boolean             observable;
+    private boolean             discoverable;
+    private Map<String, String> ifTypes;
+    private Set<String>         selectedIfTypes;
+
+    protected SimpleResourceBasicDetailsPage() {
+        super("Basic Details");
+        selectedIfTypes = new HashSet<String>();
+    }
+
+    @Override
+    public void createControl(Composite parent) {
+        setPageComplete(false);
+        setTitle(Constants.SIMPLE_RESOURCE_BASIC_DETAILS_PAGE_TITLE);
+        setMessage(Constants.SIMPLE_RESOURCE_BASIC_DETAILS_PAGE_MESSAGE);
+
+        Composite container = new Composite(parent, SWT.NONE);
+        GridLayout gridLayout = new GridLayout();
+        container.setLayout(gridLayout);
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        container.setLayoutData(gd);
+
+        Group resDetGrp = new Group(container, SWT.NONE);
+        resDetGrp.setText("Resource Details");
+        gridLayout = new GridLayout(4, false);
+        resDetGrp.setLayout(gridLayout);
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        resDetGrp.setLayoutData(gd);
+
+        Label resNameLbl = new Label(resDetGrp, SWT.NULL);
+        resNameLbl.setText(Constants.RESOURCE_NAME);
+        gd = new GridData();
+        resNameLbl.setLayoutData(gd);
+
+        resNameTxt = new Text(resDetGrp, SWT.BORDER);
+        gd = new GridData();
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalSpan = 3;
+        resNameTxt.setLayoutData(gd);
+        resNameTxt.setFocus();
+
+        Label resUriLbl = new Label(resDetGrp, SWT.NULL);
+        resUriLbl.setText(Constants.RESOURCE_URI);
+
+        resUriTxt = new Text(resDetGrp, SWT.BORDER);
+        gd = new GridData();
+        gd.horizontalSpan = 3;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        resUriTxt.setLayoutData(gd);
+
+        Label resTypeLbl = new Label(resDetGrp, SWT.NULL);
+        resTypeLbl.setText(Constants.RESOURCE_TYPE);
+
+        resTypeTxt = new Text(resDetGrp, SWT.BORDER);
+        gd = new GridData();
+        gd.horizontalSpan = 3;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        resTypeTxt.setLayoutData(gd);
+
+        Label ifTypesLbl = new Label(resDetGrp, SWT.NULL);
+        ifTypesLbl.setText(Constants.INTERFACE_TYPES);
+        gd = new GridData();
+        ifTypesLbl.setLayoutData(gd);
+
+        ifTypesList = new List(resDetGrp, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL
+                | SWT.H_SCROLL);
+        gd = new GridData();
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalSpan = 2;
+        ifTypesList.setLayoutData(gd);
+        ifTypesList.setBackground(Display.getDefault().getSystemColor(
+                SWT.COLOR_WHITE));
+
+        Composite ifTypesOpComp = new Composite(resDetGrp, SWT.NONE);
+        gridLayout = new GridLayout();
+        ifTypesOpComp.setLayout(gridLayout);
+        gd = new GridData();
+        gd.verticalAlignment = SWT.TOP;
+        ifTypesOpComp.setLayoutData(gd);
+
+        addIfTypeBtn = new Button(ifTypesOpComp, SWT.PUSH);
+        addIfTypeBtn.setText("Add");
+        gd = new GridData();
+        gd.widthHint = 70;
+        addIfTypeBtn.setLayoutData(gd);
+
+        removeIfTypeBtn = new Button(ifTypesOpComp, SWT.PUSH);
+        removeIfTypeBtn.setText("Remove");
+        gd = new GridData();
+        gd.widthHint = 70;
+        removeIfTypeBtn.setLayoutData(gd);
+        removeIfTypeBtn.setEnabled(false);
+
+        Group otherOptionsGrp = new Group(container, SWT.NONE);
+        otherOptionsGrp.setText("Other options");
+        gridLayout = new GridLayout();
+        otherOptionsGrp.setLayout(gridLayout);
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        otherOptionsGrp.setLayoutData(gd);
+
+        discoverBtn = new Button(otherOptionsGrp, SWT.CHECK);
+        discoverBtn.setText("Discoverable");
+        discoverBtn.setSelection(true);
+        discoverable = true;
+
+        observeBtn = new Button(otherOptionsGrp, SWT.CHECK);
+        observeBtn.setText("Observable");
+        observeBtn.setSelection(true);
+        observable = true;
+
+        addUiListeners();
+
+        // Set the interface types.
+        Map<String, String> ifTypes = Utility
+                .getResourceInterfaces(SingleResource.class);
+        if (null != ifTypes && !ifTypes.isEmpty()) {
+            this.ifTypes = new HashMap<String, String>();
+            String key;
+            for (Map.Entry<String, String> entry : ifTypes.entrySet()) {
+                key = entry.getValue() + " (" + entry.getKey() + ")";
+                this.ifTypes.put(key, entry.getKey());
+            }
+        }
+
+        setControl(container);
+    }
+
+    private void addUiListeners() {
+
+        resUriTxt.addModifyListener(new ModifyListener() {
+            @Override
+            public void modifyText(ModifyEvent arg0) {
+                resURI = resUriTxt.getText();
+                if (null == resURI) {
+                    return;
+                }
+
+                getWizard().getContainer().updateButtons();
+            }
+        });
+
+        resNameTxt.addModifyListener(new ModifyListener() {
+            @Override
+            public void modifyText(ModifyEvent arg0) {
+                resName = resNameTxt.getText();
+                getWizard().getContainer().updateButtons();
+            }
+        });
+
+        resTypeTxt.addModifyListener(new ModifyListener() {
+            @Override
+            public void modifyText(ModifyEvent arg0) {
+                resType = resTypeTxt.getText();
+                getWizard().getContainer().updateButtons();
+            }
+        });
+
+        discoverBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                discoverable = discoverBtn.getSelection();
+            }
+        });
+
+        observeBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                observable = observeBtn.getSelection();
+            }
+        });
+
+        addIfTypeBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                boolean addAll = false;
+                int itemsAddedCount = ifTypesList.getItemCount();
+                if (itemsAddedCount < ifTypes.size()) {
+                    String key;
+                    ArrayList<String> pendingItems = new ArrayList<String>();
+                    if (0 == itemsAddedCount) {
+                        addAll = true;
+                    }
+                    for (Map.Entry<String, String> entry : ifTypes.entrySet()) {
+                        key = entry.getKey();
+                        if (addAll || -1 == ifTypesList.indexOf(key)) {
+                            pendingItems.add(key);
+                        }
+                    }
+
+                    AddInterfaceTypeDialog addIfTypeDlg = new AddInterfaceTypeDialog(
+                            getShell(), pendingItems);
+                    if (Window.CANCEL == addIfTypeDlg.open()) {
+                        return;
+                    }
+                    String ifType = addIfTypeDlg.getValue();
+                    ifTypesList.add(ifType);
+                    ifTypesList.deselectAll();
+                    ifTypesList.select(ifTypesList.getItemCount() - 1);
+                    ifTypesList.showSelection();
+                    removeIfTypeBtn.setEnabled(true);
+
+                    if (itemsAddedCount + 1 == ifTypes.size()) {
+                        addIfTypeBtn.setEnabled(false);
+                    }
+                }
+            }
+        });
+
+        removeIfTypeBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                int[] selection = ifTypesList.getSelectionIndices();
+                if (null != selection && selection.length > 0) {
+                    ifTypesList.remove(selection);
+                }
+
+                removeIfTypeBtn.setEnabled(false);
+                addIfTypeBtn.setEnabled(true);
+            }
+        });
+
+        ifTypesList.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                int[] selection = ifTypesList.getSelectionIndices();
+                if (null != selection && selection.length > 0) {
+                    removeIfTypeBtn.setEnabled(true);
+                }
+            }
+        });
+    }
+
+    @Override
+    public boolean canFlipToNextPage() {
+        if (null == resName || null == resURI || null == resType) {
+            return false;
+        }
+        resName = resName.trim();
+        resURI = resURI.trim();
+        resType = resType.trim();
+        if (resName.length() < 1 || resURI.length() < 1 || resType.length() < 1) {
+            return false;
+        }
+        return true;
+    }
+
+    @Override
+    public IWizardPage getNextPage() {
+        if (!Utility.isUriValid(resURI)) {
+            MessageDialog.openError(Display.getDefault().getActiveShell(),
+                    "Invalid Resource URI.", Constants.INVALID_URI_MESSAGE);
+            return null;
+        }
+
+        if (!Utility.isResourceTypeValid(resType)) {
+            MessageDialog.openError(Display.getDefault().getActiveShell(),
+                    "Invalid Resource Type.",
+                    Constants.INVALID_RESOURCE_TYPE_MESSAGE);
+            return null;
+        }
+
+        // Checking whether the uri is used by any other resource.
+        if (Activator.getDefault().getResourceManager().isResourceExist(resURI)) {
+            MessageDialog
+                    .openError(getShell(), "Resource URI in use",
+                            "Entered resource URI is in use. Please try a different one.");
+            return null;
+        }
+
+        String[] items = ifTypesList.getItems();
+        if (null == items || items.length == 0) {
+            MessageDialog
+                    .openInformation(
+                            getShell(),
+                            "Default Interface Type Selection",
+                            "As no interface types are added, the resource will be "
+                                    + "configured with the default interface type(oic.if.baseline).");
+            ifTypesList.add("Baseline" + " ("
+                    + Constants.DEFAULT_SINGLE_RESOURCE_INTERFACE + ")");
+        }
+        selectedIfTypes.clear();
+        for (String item : ifTypesList.getItems()) {
+            selectedIfTypes.add(ifTypes.get(item));
+        }
+
+        return ((CreateResourceWizard) getWizard())
+                .getSimpleResourceAddAttributePage();
+    }
+
+    public String getResName() {
+        return resName;
+    }
+
+    public String getResURI() {
+        return resURI;
+    }
+
+    public String getResType() {
+        return resType;
+    }
+
+    public Set<String> getInterfaceTypes() {
+        return selectedIfTypes;
+    }
+
+    public boolean isObservable() {
+        return observable;
+    }
+
+    public boolean isDiscoverable() {
+        return discoverable;
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourceOtherDetailsPage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourceOtherDetailsPage.java
new file mode 100644 (file)
index 0000000..97c7216
--- /dev/null
@@ -0,0 +1,135 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.view.dialogs;
+
+import org.eclipse.jface.wizard.IWizardPage;
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Text;
+
+import oic.simulator.serviceprovider.utils.Constants;
+
+public class SimpleResourceOtherDetailsPage extends WizardPage {
+
+    private Button getBtn;
+    private Button putBtn;
+    private Button postBtn;
+
+    public boolean getChecked;
+    public boolean putChecked;
+    public boolean postChecked;
+
+    protected SimpleResourceOtherDetailsPage() {
+        super("Allowed Request Types");
+    }
+
+    @Override
+    public void createControl(Composite parent) {
+        setPageComplete(false);
+        setTitle(Constants.SIMPLE_RESOURCE_OTHER_DETAILS_PAGE_TITLE);
+        setMessage(Constants.SIMPLE_RESOURCE_OTHER_DETAILS_PAGE_MESSAGE);
+
+        Composite container = new Composite(parent, SWT.NONE);
+        GridLayout gridLayout = new GridLayout();
+        container.setLayout(gridLayout);
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        container.setLayoutData(gd);
+
+        Group resDetGrp = new Group(container, SWT.NONE);
+        resDetGrp.setText("Allowed Request Types");
+        gridLayout = new GridLayout();
+        resDetGrp.setLayout(gridLayout);
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        resDetGrp.setLayoutData(gd);
+
+        getBtn = new Button(resDetGrp, SWT.CHECK);
+        getBtn.setText("GET Request");
+
+        putBtn = new Button(resDetGrp, SWT.CHECK);
+        putBtn.setText("PUT Request");
+
+        postBtn = new Button(resDetGrp, SWT.CHECK);
+        postBtn.setText("POST Request");
+
+        Label lbl = new Label(container, SWT.NULL);
+        lbl.setText("Details:");
+        gd = new GridData();
+        gd.verticalIndent = 20;
+        lbl.setLayoutData(gd);
+
+        Text desc = new Text(container, SWT.MULTI | SWT.READ_ONLY | SWT.BORDER
+                | SWT.WRAP | SWT.V_SCROLL);
+        desc.setBackground(container.getBackground());
+        desc.setText("Shows the different types of request that can be used by the clients on the resource.\n"
+                + "Resource will handle only the request types which are selected here.");
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        desc.setLayoutData(gd);
+
+        addUiListeners();
+
+        setControl(container);
+    }
+
+    private void addUiListeners() {
+        getBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                getChecked = getBtn.getSelection();
+            }
+        });
+
+        putBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                putChecked = putBtn.getSelection();
+            }
+        });
+
+        postBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                postChecked = postBtn.getSelection();
+            }
+        });
+    }
+
+    @Override
+    public IWizardPage getNextPage() {
+        return null;
+    }
+
+    public boolean isGetChecked() {
+        return getChecked;
+    }
+
+    public boolean isPutChecked() {
+        return putChecked;
+    }
+
+    public boolean isPostChecked() {
+        return postChecked;
+    }
+
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SingleTextInputDialog.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SingleTextInputDialog.java
new file mode 100644 (file)
index 0000000..860d31d
--- /dev/null
@@ -0,0 +1,100 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.view.dialogs;
+
+import org.eclipse.jface.dialogs.TrayDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+
+/**
+ * This class shows a dialog for filtering logs based on severity levels.
+ */
+public class SingleTextInputDialog extends TrayDialog {
+
+    private Text   txt;
+    private String value;
+    private String lblTxt;
+    private String shellTitle;
+
+    public SingleTextInputDialog(Shell shell, String title, String lblTxt) {
+        super(shell);
+        shellTitle = title;
+        this.lblTxt = lblTxt;
+    }
+
+    @Override
+    protected void configureShell(Shell shell) {
+        super.configureShell(shell);
+    }
+
+    @Override
+    protected Control createDialogArea(Composite parent) {
+        Composite composite = (Composite) super.createDialogArea(parent);
+        getShell().setText(shellTitle);
+
+        Composite content = new Composite(parent, SWT.NULL);
+        GridLayout gridLayout = new GridLayout();
+        content.setLayout(gridLayout);
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        content.setLayoutData(gd);
+
+        Label lbl = new Label(content, SWT.NONE);
+        lbl.setText(lblTxt);
+
+        txt = new Text(content, SWT.BORDER);
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        txt.setLayoutData(gd);
+        txt.addModifyListener(new ModifyListener() {
+
+            @Override
+            public void modifyText(ModifyEvent e) {
+                value = txt.getText();
+            }
+        });
+
+        return composite;
+    }
+
+    @Override
+    protected void okPressed() {
+        if (null != value) {
+            value = value.trim();
+            if (value.length() > 0) {
+                close();
+                return;
+            }
+        }
+        txt.setFocus();
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+
+    public String getValue() {
+        return value;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/UpdatePrimitiveArrayAttributeDialog.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/UpdatePrimitiveArrayAttributeDialog.java
new file mode 100644 (file)
index 0000000..def171e
--- /dev/null
@@ -0,0 +1,399 @@
+/*
+ * 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 oic.simulator.serviceprovider.view.dialogs;
+
+import org.eclipse.jface.dialogs.TitleAreaDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.MessageBox;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+
+import java.util.Date;
+
+import org.oic.simulator.ArrayProperty;
+import org.oic.simulator.AttributeProperty;
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.DoubleProperty;
+import org.oic.simulator.ILogger.Level;
+import org.oic.simulator.IntegerProperty;
+import org.oic.simulator.SimulatorResourceAttribute;
+import org.oic.simulator.StringProperty;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.utils.AttributeValueBuilder;
+import oic.simulator.serviceprovider.utils.AttributeValueStringConverter;
+import oic.simulator.serviceprovider.utils.Utility;
+
+/**
+ * This class manages and shows the automation settings dialog from the
+ * attribute view.
+ */
+public class UpdatePrimitiveArrayAttributeDialog extends TitleAreaDialog {
+
+    private Text                       attNameTxt;
+    private Text                       currentValueTxt;
+    private Text                       newValueTxt;
+    private Text                       allowedValuesTxt;
+    private Text                       minRangeTxt;
+    private Text                       maxRangeTxt;
+    private Text                       allowDuplicatesTxt;
+    private Text                       additionalItemsTxt;
+    private SimulatorResourceAttribute attribute;
+    private String                     newValue;
+
+    private AttributeValue             newAttValueObj;
+
+    public UpdatePrimitiveArrayAttributeDialog(Shell parentShell,
+            SimulatorResourceAttribute attribute) {
+        super(parentShell);
+        this.attribute = attribute;
+    }
+
+    @Override
+    public void create() {
+        super.create();
+        setTitle("Modify Attribute's Value");
+        setMessage("Change the value of the array type attribute");
+    }
+
+    @Override
+    protected Control createDialogArea(Composite parent) {
+        Composite compLayout = (Composite) super.createDialogArea(parent);
+
+        Composite container = new Composite(compLayout, SWT.NONE);
+        container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+        GridLayout layout = new GridLayout(2, false);
+        layout.verticalSpacing = 10;
+        layout.marginTop = 10;
+        container.setLayout(layout);
+
+        GridData gd;
+
+        Label attNameLbl = new Label(container, SWT.NONE);
+        attNameLbl.setText("Attribute Name");
+
+        attNameTxt = new Text(container, SWT.READ_ONLY | SWT.BORDER);
+        attNameTxt.setBackground(container.getBackground());
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        attNameTxt.setLayoutData(gd);
+
+        Group subGroup = new Group(container, SWT.NONE);
+        subGroup.setText("Array Properties");
+        layout = new GridLayout(2, true);
+        subGroup.setLayout(layout);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.horizontalSpan = 2;
+        subGroup.setLayoutData(gd);
+
+        Composite minRangeContainer = new Composite(subGroup, SWT.NONE);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        minRangeContainer.setLayoutData(gd);
+        layout = new GridLayout(2, true);
+        minRangeContainer.setLayout(layout);
+
+        Label minRangeLbl = new Label(minRangeContainer, SWT.NONE);
+        minRangeLbl.setText("Minimum Items");
+
+        minRangeTxt = new Text(minRangeContainer, SWT.BORDER | SWT.READ_ONLY);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        minRangeTxt.setLayoutData(gd);
+        minRangeTxt.setBackground(container.getBackground());
+
+        Composite maxRangeContainer = new Composite(subGroup, SWT.NONE);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        maxRangeContainer.setLayoutData(gd);
+        layout = new GridLayout(2, true);
+        maxRangeContainer.setLayout(layout);
+
+        Label maxRangeLbl = new Label(maxRangeContainer, SWT.NONE);
+        maxRangeLbl.setText("Maximum Items");
+
+        maxRangeTxt = new Text(maxRangeContainer, SWT.BORDER | SWT.READ_ONLY);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        maxRangeTxt.setLayoutData(gd);
+        maxRangeTxt.setBackground(container.getBackground());
+
+        Composite uniqueContainer = new Composite(subGroup, SWT.NONE);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        uniqueContainer.setLayoutData(gd);
+        layout = new GridLayout(2, true);
+        uniqueContainer.setLayout(layout);
+
+        Label uniqueLbl = new Label(uniqueContainer, SWT.NONE);
+        uniqueLbl.setText("Allow Duplicates");
+
+        allowDuplicatesTxt = new Text(uniqueContainer, SWT.BORDER
+                | SWT.READ_ONLY);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        allowDuplicatesTxt.setLayoutData(gd);
+        allowDuplicatesTxt.setBackground(container.getBackground());
+
+        Composite addlItemsContainer = new Composite(subGroup, SWT.NONE);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        addlItemsContainer.setLayoutData(gd);
+        layout = new GridLayout(2, true);
+        addlItemsContainer.setLayout(layout);
+
+        Label addlItemsLbl = new Label(addlItemsContainer, SWT.NONE);
+        addlItemsLbl.setText("Allow Extra Items");
+
+        additionalItemsTxt = new Text(addlItemsContainer, SWT.BORDER
+                | SWT.READ_ONLY);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        additionalItemsTxt.setLayoutData(gd);
+        additionalItemsTxt.setBackground(container.getBackground());
+
+        Group elementPropGroup = new Group(container, SWT.NONE);
+        elementPropGroup.setText("Element Property");
+        layout = new GridLayout(2, false);
+        elementPropGroup.setLayout(layout);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.horizontalSpan = 2;
+        elementPropGroup.setLayoutData(gd);
+
+        Label allowedValuesLbl = new Label(elementPropGroup, SWT.NONE);
+        allowedValuesLbl.setText("Allowed Values");
+
+        allowedValuesTxt = new Text(elementPropGroup, SWT.MULTI | SWT.READ_ONLY
+                | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
+        allowedValuesTxt.setBackground(container.getBackground());
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessVerticalSpace = true;
+        gd.verticalAlignment = SWT.FILL;
+        gd.minimumHeight = 30;
+        allowedValuesTxt.setLayoutData(gd);
+
+        Label curValueLbl = new Label(container, SWT.NONE);
+        curValueLbl.setText("Current Value");
+
+        currentValueTxt = new Text(container, SWT.MULTI | SWT.READ_ONLY
+                | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
+        currentValueTxt.setBackground(container.getBackground());
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessVerticalSpace = true;
+        gd.verticalAlignment = SWT.FILL;
+        gd.minimumHeight = 30;
+        currentValueTxt.setLayoutData(gd);
+
+        Label attNewValue = new Label(container, SWT.NONE);
+        attNewValue.setText("New Value");
+
+        newValueTxt = new Text(container, SWT.MULTI | SWT.BORDER | SWT.WRAP
+                | SWT.V_SCROLL);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessVerticalSpace = true;
+        gd.verticalAlignment = SWT.FILL;
+        gd.minimumHeight = 60;
+        newValueTxt.setLayoutData(gd);
+        newValueTxt.setFocus();
+
+        Group hintGroup = new Group(container, SWT.NONE);
+        hintGroup.setText("Note");
+        layout = new GridLayout();
+        hintGroup.setLayout(layout);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.horizontalSpan = 2;
+        hintGroup.setLayoutData(gd);
+
+        Label hint = new Label(hintGroup, SWT.NULL);
+        hint.setText("Array values should be comma-seperated and surrounded by square brackets.\n"
+                + "Ex: \"[value]\", \"[value1,value2]\", \"[[value1], [value2]]\"");
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.horizontalSpan = 2;
+        gd.horizontalIndent = 40;
+        hint.setLayoutData(gd);
+
+        populateData();
+
+        return compLayout;
+    }
+
+    private void populateData() {
+        // Set the Attribute Name.
+        attNameTxt.setText(attribute.name());
+
+        // Set the allowed values.
+        ArrayProperty arrProp = attribute.property().asArray();
+        AttributeProperty elementProp = arrProp.getElementProperty();
+
+        StringBuilder values = new StringBuilder();
+        String value = "";
+        if (elementProp.isInteger()) {
+            IntegerProperty intProp = elementProp.asInteger();
+            if (intProp.hasRange()) {
+                value = intProp.min() + " - " + intProp.max();
+            } else if (intProp.hasValues()) {
+                int[] arr = intProp.getValues();
+                for (int i = 0; i < arr.length; i++) {
+                    values.append(arr[i]);
+                    if (i + 1 < arr.length) {
+                        values.append(", ");
+                    }
+                }
+
+                if (!values.toString().isEmpty()) {
+                    value = "[" + values + "]";
+                }
+            }
+        } else if (elementProp.isDouble()) {
+            DoubleProperty dblProp = elementProp.asDouble();
+            if (dblProp.hasRange()) {
+                value = dblProp.min() + " - " + dblProp.max();
+            } else if (dblProp.hasValues()) {
+                double[] arr = dblProp.getValues();
+                for (int i = 0; i < arr.length; i++) {
+                    values.append(arr[i]);
+                    if (i + 1 < arr.length) {
+                        values.append(", ");
+                    }
+                }
+
+                if (!values.toString().isEmpty()) {
+                    value = "[" + values + "]";
+                }
+            }
+        } else if (elementProp.isBoolean()) {
+            value = "[true, false]";
+        } else if (elementProp.isString()) {
+            StringProperty strProp = elementProp.asString();
+            if (strProp.hasValues()) {
+                String[] arr = strProp.getValues();
+                for (int i = 0; i < arr.length; i++) {
+                    values.append(arr[i]);
+                    if (i + 1 < arr.length) {
+                        values.append(", ");
+                    }
+                }
+
+                if (!values.toString().isEmpty()) {
+                    value = "[" + values + "]";
+                }
+            }
+        }
+
+        allowedValuesTxt.setText(value);
+
+        // Set the current value.
+        currentValueTxt.setText(new AttributeValueStringConverter(attribute
+                .value()).toString());
+
+        minRangeTxt.setText(String.valueOf(arrProp.minItems()));
+
+        maxRangeTxt.setText(String.valueOf(arrProp.maxItems()));
+
+        allowDuplicatesTxt.setText(!arrProp.isUnique() ? "Yes" : "No");
+
+        additionalItemsTxt.setText(arrProp.isVariable() ? "Yes" : "No");
+    }
+
+    public String getNewValue() {
+        return newValue;
+    }
+
+    public AttributeValue getNewValueObj() {
+        return newAttValueObj;
+    }
+
+    @Override
+    protected void okPressed() {
+        // Validate the value
+        newValue = newValueTxt.getText();
+        if (null == newValue || newValue.isEmpty()) {
+            return;
+        }
+
+        ArrayProperty arrProp = attribute.property().asArray();
+        try {
+            String value = Utility.removeWhiteSpacesInArrayValues(newValue);
+            if (null != value && value.startsWith("[") && value.endsWith("]")) {
+                newAttValueObj = AttributeValueBuilder.build(value, attribute
+                        .value().typeInfo().mBaseType);
+                if (null != newAttValueObj && arrProp.validate(newAttValueObj)) {
+                    close();
+                    return;
+                }
+            }
+        } catch (Exception e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "There is an error while building the new attribute value.\n"
+                                    + Utility.getSimulatorErrorString(e, null));
+        }
+
+        MessageBox dialog = new MessageBox(Display.getDefault()
+                .getActiveShell(), SWT.ICON_ERROR | SWT.OK);
+        dialog.setText("Invalid Value");
+        dialog.setMessage("Given value is invalid.\nEither the entered value(s) are not in the allowed values or in improper format.\n"
+                + "Format: Array values should be comma-seperated and surrounded by square brackets.\n"
+                + "Ex: \"[value]\", \"[value1,value2]\", \"[[value1], [value2]]\"");
+        dialog.open();
+
+        newValueTxt.setFocus();
+    }
+
+    @Override
+    protected boolean isResizable() {
+        return true;
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/UpdatePropertiesPage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/UpdatePropertiesPage.java
new file mode 100644 (file)
index 0000000..b7628a6
--- /dev/null
@@ -0,0 +1,172 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.view.dialogs;
+
+import org.eclipse.jface.wizard.IWizardPage;
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Text;
+
+import oic.simulator.serviceprovider.utils.Constants;
+
+public class UpdatePropertiesPage extends WizardPage {
+
+    private Text   resNameTxt;
+    private Text   resUriTxt;
+
+    private String resName;
+    private String resURI;
+
+    protected UpdatePropertiesPage() {
+        super("Update Properties");
+    }
+
+    @Override
+    public void createControl(Composite parent) {
+        setPageComplete(true);
+        setTitle(Constants.UPDATE_PROP_PAGE_TITLE);
+        setMessage(Constants.UPDATE_PROP_PAGE_MESSAGE);
+
+        Composite comp = new Composite(parent, SWT.NONE);
+        GridLayout gridLayout = new GridLayout();
+        comp.setLayout(gridLayout);
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        comp.setLayoutData(gd);
+
+        Group grp = new Group(comp, SWT.NONE);
+        gridLayout = new GridLayout(2, false);
+        grp.setLayout(gridLayout);
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        grp.setLayoutData(gd);
+
+        Label resNameLbl = new Label(grp, SWT.NULL);
+        resNameLbl.setText("Resource Name");
+        gd = new GridData();
+        gd.verticalIndent = 20;
+        resNameLbl.setLayoutData(gd);
+
+        resNameTxt = new Text(grp, SWT.BORDER);
+        resNameTxt.setFocus();
+        gd = new GridData();
+        gd.widthHint = 300;
+        gd.verticalIndent = 20;
+        resNameTxt.setLayoutData(gd);
+
+        Label resUriLbl = new Label(grp, SWT.NULL);
+        resUriLbl.setText("Resource URI");
+        gd = new GridData();
+        gd.verticalIndent = 10;
+        resUriLbl.setLayoutData(gd);
+
+        resUriTxt = new Text(grp, SWT.BORDER);
+        gd = new GridData();
+        gd.widthHint = 300;
+        gd.verticalIndent = 10;
+        resUriTxt.setLayoutData(gd);
+
+        Label descLbl = new Label(comp, SWT.NONE);
+        descLbl.setText("Description:");
+        gd = new GridData();
+        descLbl.setLayoutData(gd);
+
+        final Text text = new Text(comp, SWT.MULTI | SWT.READ_ONLY | SWT.BORDER
+                | SWT.WRAP | SWT.V_SCROLL);
+        text.setText("These properties can be changed later from properties view.");
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        text.setLayoutData(gd);
+
+        addUIListeners();
+
+        // Initialize data
+        if (resUriTxt.getText().length() < 1 && null != resURI) {
+            resUriTxt.setText(resURI);
+        }
+        if (resNameTxt.getText().length() < 1 && null != resName) {
+            resNameTxt.setText(resName);
+        }
+
+        setControl(comp);
+    }
+
+    private void addUIListeners() {
+        resNameTxt.addModifyListener(new ModifyListener() {
+            @Override
+            public void modifyText(ModifyEvent e) {
+                resName = resNameTxt.getText();
+                setPageComplete(isSelectionDone());
+            }
+        });
+
+        resUriTxt.addModifyListener(new ModifyListener() {
+            @Override
+            public void modifyText(ModifyEvent e) {
+                resURI = resUriTxt.getText();
+                if (null == resURI) {
+                    return;
+                }
+
+                setPageComplete(isSelectionDone());
+            }
+        });
+    }
+
+    @Override
+    public boolean canFlipToNextPage() {
+        return false;
+    }
+
+    public boolean isSelectionDone() {
+        boolean done = false;
+        if (null != resName && resName.trim().length() > 0 && null != resURI
+                && resURI.trim().length() > 0) {
+            done = true;
+        }
+        return done;
+    }
+
+    @Override
+    public IWizardPage getNextPage() {
+        return null;
+    }
+
+    public void setResName(String resName) {
+        this.resName = resName;
+        if (!resNameTxt.isDisposed())
+            resNameTxt.setText(resName);
+    }
+
+    public void setResURI(String resURI) {
+        this.resURI = resURI;
+        if (!resUriTxt.isDisposed())
+            resUriTxt.setText(resURI);
+    }
+
+    public String getResName() {
+        return resName;
+    }
+
+    public String getResURI() {
+        return resURI;
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/UpdateResourceInterfaceDialog.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/UpdateResourceInterfaceDialog.java
new file mode 100644 (file)
index 0000000..4fe07b5
--- /dev/null
@@ -0,0 +1,240 @@
+/*
+ * 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.
+ */
+
+package oic.simulator.serviceprovider.view.dialogs;
+
+import org.eclipse.jface.dialogs.IDialogConstants;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.dialogs.TrayDialog;
+import org.eclipse.jface.window.Window;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.List;
+import org.eclipse.swt.widgets.Shell;
+
+import java.util.ArrayList;
+import java.util.Map;
+
+import oic.simulator.serviceprovider.utils.Constants;
+
+/**
+ * Dialog for starting and stopping the automatic verifications.
+ */
+public class UpdateResourceInterfaceDialog extends TrayDialog {
+
+    private Button              addIfTypeBtn;
+    private Button              removeIfTypeBtn;
+
+    private List                ifTypesList;
+
+    private Map<String, String> supportedResInterfaces;
+    private Map<String, String> updatedResInterfaces;
+
+    public UpdateResourceInterfaceDialog(Shell shell,
+            Map<String, String> updatedResInterfaces,
+            Map<String, String> supportedResInterfaces) {
+        super(shell);
+        this.updatedResInterfaces = updatedResInterfaces;
+        this.supportedResInterfaces = supportedResInterfaces;
+    }
+
+    @Override
+    protected void configureShell(Shell shell) {
+        super.configureShell(shell);
+    }
+
+    @Override
+    protected Control createDialogArea(Composite parent) {
+        Composite composite = (Composite) super.createDialogArea(parent);
+        getShell().setText("Resource Interfaces");
+
+        Composite content = new Composite(parent, SWT.NULL);
+        GridLayout gridLayout = new GridLayout(3, false);
+        content.setLayout(gridLayout);
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        content.setLayoutData(gd);
+
+        ifTypesList = new List(content, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL
+                | SWT.H_SCROLL);
+        gd = new GridData();
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        gd.verticalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalSpan = 2;
+        ifTypesList.setLayoutData(gd);
+        ifTypesList.setBackground(Display.getDefault().getSystemColor(
+                SWT.COLOR_WHITE));
+
+        Composite ifTypesOpComp = new Composite(content, SWT.NONE);
+        gridLayout = new GridLayout();
+        ifTypesOpComp.setLayout(gridLayout);
+        gd = new GridData();
+        gd.verticalAlignment = SWT.TOP;
+        ifTypesOpComp.setLayoutData(gd);
+
+        addIfTypeBtn = new Button(ifTypesOpComp, SWT.PUSH);
+        addIfTypeBtn.setText("Add");
+        gd = new GridData();
+        gd.widthHint = 70;
+        addIfTypeBtn.setLayoutData(gd);
+        if (null != updatedResInterfaces && null != supportedResInterfaces
+                && updatedResInterfaces.size() == supportedResInterfaces.size()) {
+            addIfTypeBtn.setEnabled(false);
+        }
+
+        removeIfTypeBtn = new Button(ifTypesOpComp, SWT.PUSH);
+        removeIfTypeBtn.setText("Remove");
+        gd = new GridData();
+        gd.widthHint = 70;
+        removeIfTypeBtn.setLayoutData(gd);
+        removeIfTypeBtn.setEnabled(false);
+
+        initInterfaceList();
+
+        addUiListeners();
+
+        return composite;
+    }
+
+    private void initInterfaceList() {
+        if (null != updatedResInterfaces) {
+            for (Map.Entry<String, String> entry : updatedResInterfaces
+                    .entrySet()) {
+                ifTypesList.add(entry.getKey());
+            }
+        }
+    }
+
+    private void addUiListeners() {
+        addIfTypeBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                boolean addAll = false;
+                int itemsAddedCount = ifTypesList.getItemCount();
+                if (itemsAddedCount < supportedResInterfaces.size()) {
+                    String key;
+                    ArrayList<String> pendingItems = new ArrayList<String>();
+                    if (0 == itemsAddedCount) {
+                        addAll = true;
+                    }
+                    for (Map.Entry<String, String> entry : supportedResInterfaces
+                            .entrySet()) {
+                        key = entry.getKey();
+                        if (addAll || -1 == ifTypesList.indexOf(key)) {
+                            pendingItems.add(key);
+                        }
+                    }
+
+                    AddInterfaceTypeDialog addIfTypeDlg = new AddInterfaceTypeDialog(
+                            getShell(), pendingItems);
+                    if (Window.CANCEL == addIfTypeDlg.open()) {
+                        return;
+                    }
+                    String ifType = addIfTypeDlg.getValue();
+                    if (null == ifType || ifType.isEmpty()) {
+                        return;
+                    }
+
+                    ifTypesList.add(ifType);
+                    ifTypesList.deselectAll();
+                    ifTypesList.select(ifTypesList.getItemCount() - 1);
+                    ifTypesList.showSelection();
+                    removeIfTypeBtn.setEnabled(true);
+
+                    if (itemsAddedCount + 1 == supportedResInterfaces.size()) {
+                        addIfTypeBtn.setEnabled(false);
+                    }
+                }
+            }
+        });
+
+        removeIfTypeBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                int[] selection = ifTypesList.getSelectionIndices();
+                if (null != selection && selection.length > 0) {
+                    ifTypesList.remove(selection);
+                }
+
+                ifTypesList.deselectAll();
+                removeIfTypeBtn.setEnabled(false);
+                addIfTypeBtn.setEnabled(true);
+            }
+        });
+
+        ifTypesList.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                int[] selection = ifTypesList.getSelectionIndices();
+                if (null != selection && selection.length > 0) {
+                    removeIfTypeBtn.setEnabled(true);
+                }
+            }
+        });
+    }
+
+    @Override
+    protected void okPressed() {
+        String[] items = ifTypesList.getItems();
+        if (null == items || items.length == 0) {
+            MessageDialog
+                    .openInformation(
+                            getShell(),
+                            "Default Interface Type Selection",
+                            "As no interface types are added, the resource will be "
+                                    + "configured with the default interface type(oic.if.baseline).");
+            ifTypesList.add("Baseline" + " ("
+                    + Constants.DEFAULT_SINGLE_RESOURCE_INTERFACE + ")");
+        }
+
+        // Clearing the map to freshly add selected items.
+        updatedResInterfaces.clear();
+        for (String item : ifTypesList.getItems()) {
+            String value = supportedResInterfaces.get(item);
+            updatedResInterfaces.put(item, value);
+        }
+        close();
+    }
+
+    @Override
+    protected Point getInitialSize() {
+        Point actualSize = super.getInitialSize();
+        return new Point(actualSize.x + 100, actualSize.y);
+    }
+
+    @Override
+    protected Button createButton(Composite parent, int id, String label,
+            boolean defaultButton) {
+        if (id == IDialogConstants.CANCEL_ID) {
+            return null;
+        }
+        return super.createButton(parent, id, label, defaultButton);
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+}
diff --git a/service/simulator/java/jni/jni_listener_holder.h b/service/simulator/java/jni/jni_listener_holder.h
new file mode 100644 (file)
index 0000000..092dfe7
--- /dev/null
@@ -0,0 +1,53 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef JNI_LISTENER_HOLDER_H_
+#define JNI_LISTENER_HOLDER_H_
+
+class JniListenerHolder
+{
+    public:
+        ~JniListenerHolder()
+        {
+            JNIEnv *env = GetEnv();
+            if (!env)
+                return;
+            env->DeleteGlobalRef(m_listener);
+            ReleaseEnv();
+        }
+
+        jobject get()
+        {
+            return m_listener;
+        }
+
+        static std::shared_ptr<JniListenerHolder> create(JNIEnv *env, jobject &listener)
+        {
+            return std::shared_ptr<JniListenerHolder>(new JniListenerHolder(env, listener));
+        }
+
+    private:
+        JniListenerHolder(JNIEnv *env, jobject &listener)
+            : m_listener(env->NewGlobalRef(listener)) {}
+
+        jobject m_listener;
+};
+
+#endif
diff --git a/service/simulator/java/jni/jni_map.cpp b/service/simulator/java/jni/jni_map.cpp
new file mode 100644 (file)
index 0000000..e14ec5f
--- /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_map.h"
+#include "simulator_utils_jni.h"
+
+JniMap::JniMap(JNIEnv *env)
+{
+    m_env = env;
+
+    static jmethodID mapCtor = env->GetMethodID(
+                                   gSimulatorClassRefs.hashMapCls, "<init>", "()V");
+    m_hashMap = env->NewObject(gSimulatorClassRefs.hashMapCls, mapCtor);
+}
+
+void JniMap::put(jobject jKey, jobject jValue)
+{
+    static jmethodID putMethod = m_env->GetMethodID(gSimulatorClassRefs.hashMapCls,
+                                 "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
+    m_env->CallObjectMethod(m_hashMap, putMethod, jKey, jValue);
+}
+
+jobject JniMap::get()
+{
+    return m_hashMap;
+}
diff --git a/service/simulator/java/jni/jni_map.h b/service/simulator/java/jni/jni_map.h
new file mode 100644 (file)
index 0000000..a94db78
--- /dev/null
@@ -0,0 +1,38 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef JNI_MAP_H_
+#define JNI_MAP_H_
+
+#include <jni.h>
+
+class JniMap
+{
+    public:
+        JniMap(JNIEnv *env);
+        void put(jobject jKey, jobject jValue);
+        jobject get();
+
+    private:
+        JNIEnv *m_env;
+        jobject m_hashMap;
+};
+
+#endif
diff --git a/service/simulator/java/jni/jni_queryparam.cpp b/service/simulator/java/jni/jni_queryparam.cpp
new file mode 100644 (file)
index 0000000..af6f142
--- /dev/null
@@ -0,0 +1,68 @@
+/******************************************************************
+ *
+ * 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 "jni_queryparam.h"
+#include "jni_string.h"
+#include "simulator_utils_jni.h"
+
+JniQueryParameter::JniQueryParameter(JNIEnv *env) : m_env(env) {}
+
+std::map<std::string, std::string> JniQueryParameter::toCpp(jobject jQueryParams)
+{
+    std::map<std::string, std::string> result;
+    if (!jQueryParams)
+        return result;
+
+    static jmethodID entrySetMethodID = m_env->GetMethodID(gSimulatorClassRefs.mapCls, "entrySet",
+                                        "()Ljava/util/Set;");
+    static jmethodID iteratorMethodID = m_env->GetMethodID(gSimulatorClassRefs.setCls, "iterator",
+                                        "()Ljava/util/Iterator;");
+    static jmethodID hasNextMethodID = m_env->GetMethodID(gSimulatorClassRefs.iteratorCls, "hasNext",
+                                       "()Z");
+    static jmethodID nextMethodID = m_env->GetMethodID(gSimulatorClassRefs.iteratorCls, "next",
+                                    "()Ljava/lang/Object;");
+    static jmethodID getKeyMethodID = m_env->GetMethodID(gSimulatorClassRefs.mapEntryCls, "getKey",
+                                      "()Ljava/lang/Object;");
+    static jmethodID getValueMethodID = m_env->GetMethodID(gSimulatorClassRefs.mapEntryCls, "getValue",
+                                        "()Ljava/lang/Object;");
+
+    jobject entrySet = m_env->CallObjectMethod(jQueryParams, entrySetMethodID);
+    jobject iterator = m_env->CallObjectMethod(entrySet, iteratorMethodID);
+    if (!entrySet || !iterator || m_env->ExceptionCheck())
+        return result;
+
+    while (m_env->CallBooleanMethod(iterator, hasNextMethodID))
+    {
+        jobject entry = m_env->CallObjectMethod(iterator, nextMethodID);
+        jstring key = (jstring) m_env->CallObjectMethod(entry, getKeyMethodID);
+        jstring value = (jstring) m_env->CallObjectMethod(entry, getValueMethodID);
+
+        JniString jniKey(m_env, key);
+        JniString jniValue(m_env, value);
+
+        result[jniKey.get()] = jniValue.get();
+
+        m_env->DeleteLocalRef(entry);
+        m_env->DeleteLocalRef(key);
+        m_env->DeleteLocalRef(value);
+    }
+
+    return result;
+}
diff --git a/service/simulator/java/jni/jni_queryparam.h b/service/simulator/java/jni/jni_queryparam.h
new file mode 100644 (file)
index 0000000..dcdc44b
--- /dev/null
@@ -0,0 +1,38 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef JNI_QUERY_PARAM_H_
+#define JNI_QUERY_PARAM_H_
+
+#include <jni.h>
+#include <map>
+#include <string>
+
+class JniQueryParameter
+{
+    public:
+        JniQueryParameter(JNIEnv *env);
+        std::map<std::string, std::string> toCpp(jobject jQueryParams);
+
+    private:
+        JNIEnv *m_env;
+};
+
+#endif
\ No newline at end of file
diff --git a/service/simulator/java/jni/jni_sharedobject_holder.h b/service/simulator/java/jni/jni_sharedobject_holder.h
new file mode 100644 (file)
index 0000000..46756fd
--- /dev/null
@@ -0,0 +1,49 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef JNI_SHARED_OBJECT_HOLDER_H_
+#define JNI_SHARED_OBJECT_HOLDER_H_
+
+#include <memory>
+
+template <typename T>
+class JniSharedObjectHolder
+{
+    public:
+        std::shared_ptr<T> get()
+        {
+            return m_sharedObject;
+        }
+
+        static JniSharedObjectHolder *create(std::shared_ptr<T> &sharedObject)
+        {
+            return new JniSharedObjectHolder(sharedObject);
+        }
+
+    private:
+        JniSharedObjectHolder(std::shared_ptr<T> &sharedObject)
+        {
+            m_sharedObject = sharedObject;
+        }
+
+        std::shared_ptr<T> m_sharedObject;
+};
+
+#endif
diff --git a/service/simulator/java/jni/jni_string.cpp b/service/simulator/java/jni/jni_string.cpp
new file mode 100644 (file)
index 0000000..1c7ba83
--- /dev/null
@@ -0,0 +1,45 @@
+/******************************************************************
+ *
+ * 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 "jni_string.h"
+
+JniString::JniString(JNIEnv *env, jstring &string)
+    :   m_env(nullptr), m_string(nullptr), m_cStr("")
+{
+    m_env = env;
+    m_string = string;
+    if (m_string)
+    {
+        m_cStr = env->GetStringUTFChars(m_string, nullptr);
+    }
+}
+
+JniString::~JniString()
+{
+    if (m_string && m_cStr)
+    {
+        m_env->ReleaseStringUTFChars(m_string, m_cStr);
+    }
+}
+
+std::string JniString::get()
+{
+    return std::string(m_cStr);
+}
diff --git a/service/simulator/java/jni/jni_string.h b/service/simulator/java/jni/jni_string.h
new file mode 100644 (file)
index 0000000..ba14d43
--- /dev/null
@@ -0,0 +1,40 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef JNI_STRING_H_
+#define JNI_STRING_H_
+
+#include <jni.h>
+#include <string>
+
+class JniString
+{
+    public:
+        JniString(JNIEnv *env, jstring &string);
+        ~JniString();
+        std::string get();
+
+    private:
+        JNIEnv *m_env;
+        jstring m_string;
+        const char *m_cStr;
+};
+
+#endif
diff --git a/service/simulator/java/jni/jni_vector.cpp b/service/simulator/java/jni/jni_vector.cpp
new file mode 100644 (file)
index 0000000..386a801
--- /dev/null
@@ -0,0 +1,101 @@
+/******************************************************************
+ *
+ * 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 "jni_vector.h"
+#include "jni_string.h"
+#include "simulator_utils_jni.h"
+
+JniVector::JniVector(JNIEnv *env) : m_env(env) {}
+
+jobject JniVector::toJava()
+{
+    static jmethodID vectorCtor = m_env->GetMethodID(gSimulatorClassRefs.vectorCls,
+                                  "<init>", "()V");
+    return m_env->NewObject(gSimulatorClassRefs.vectorCls, vectorCtor);
+}
+
+jobject JniVector::toJava(std::vector<std::string> &cppVector)
+{
+    static jmethodID addMethod = m_env->GetMethodID(gSimulatorClassRefs.vectorCls,
+                                 "add", "(Ljava/lang/Object;)Z");
+
+    jobject vectorObject = toJava();
+    if (!vectorObject)
+        return nullptr;
+
+    for (size_t index = 0; index < cppVector.size(); index++)
+    {
+        jstring element = m_env->NewStringUTF(cppVector[index].c_str());
+        m_env->CallBooleanMethod(vectorObject, addMethod, element);
+        m_env->DeleteLocalRef(element);
+    }
+
+    return vectorObject;
+}
+
+int JniVector::getSize(jobject jVector)
+{
+    static jmethodID sizeMethodID = m_env->GetMethodID(gSimulatorClassRefs.vectorCls,
+                                    "size", "()I");
+    return m_env->CallIntMethod(jVector, sizeMethodID);
+}
+
+void JniVector::addElementsCpp(jobject vector, int size, std::vector<int> &result)
+{
+    static jmethodID getMethod = m_env->GetMethodID(gSimulatorClassRefs.vectorCls,
+                                 "get", "(I)Ljava/lang/Object;");
+    static jmethodID intValueMethod = m_env->GetMethodID(gSimulatorClassRefs.integerCls,
+                                      "intValue", "()I");
+
+    for (int index = 0; index < size; index++)
+    {
+        jobject intObject = m_env->CallObjectMethod(vector, getMethod, index);
+        int value = m_env->CallIntMethod(intObject, intValueMethod);
+        result.push_back(value);
+    }
+}
+
+void JniVector::addElementsCpp(jobject vector, int size, std::vector<double> &result)
+{
+    static jmethodID getMethod = m_env->GetMethodID(gSimulatorClassRefs.vectorCls,
+                                 "get", "(I)Ljava/lang/Object;");
+    static jmethodID doubleValueMethod = m_env->GetMethodID(gSimulatorClassRefs.doubleCls,
+                                         "doubleValue", "()D");
+
+    for (int index = 0; index < size; index++)
+    {
+        jobject doubleObject = m_env->CallObjectMethod(vector, getMethod, index);
+        double value = m_env->CallDoubleMethod(doubleObject, doubleValueMethod);
+        result.push_back(value);
+    }
+}
+
+void JniVector::addElementsCpp(jobject vector, int size, std::vector<std::string> &result)
+{
+    static jmethodID getMethodID = m_env->GetMethodID(gSimulatorClassRefs.vectorCls,
+                                   "get", "(I)Ljava/lang/Object;");
+
+    for (int index = 0; index < size; index++)
+    {
+        jstring stringObject = (jstring) m_env->CallObjectMethod(vector, getMethodID, index);
+        JniString value(m_env, stringObject);
+        result.push_back(value.get());
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/jni/jni_vector.h b/service/simulator/java/jni/jni_vector.h
new file mode 100644 (file)
index 0000000..9e1903d
--- /dev/null
@@ -0,0 +1,53 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef JNI_VECTOR_H_
+#define JNI_VECTOR_H_
+
+#include <jni.h>
+#include <vector>
+#include <string>
+
+class JniVector
+{
+    public:
+        JniVector(JNIEnv *env);
+
+        template <typename TYPE>
+        std::vector<TYPE> toCpp(jobject jVector)
+        {
+            std::vector<TYPE> result;
+            addElementsCpp(jVector, getSize(jVector), result);
+            return result;
+        }
+
+        jobject toJava(std::vector<std::string> &cppVector);
+        jobject toJava();
+
+    private:
+        int getSize(jobject jVector);
+        void addElementsCpp(jobject vector, int size, std::vector<int> &result);
+        void addElementsCpp(jobject vector, int size, std::vector<double> &result);
+        void addElementsCpp(jobject vector, int size, std::vector<std::string> &result);
+
+        JNIEnv *m_env;
+};
+
+#endif
diff --git a/service/simulator/java/jni/resource_attributes_jni.cpp b/service/simulator/java/jni/resource_attributes_jni.cpp
deleted file mode 100644 (file)
index 5732eff..0000000
+++ /dev/null
@@ -1,246 +0,0 @@
-/******************************************************************
- *
- * 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 "resource_attributes_jni.h"
-#include "simulator_resource_model.h"
-#include "simulator_common_jni.h"
-#include "simulator_error_codes.h"
-#include <climits>
-
-extern SimulatorClassRefs gSimulatorClassRefs;
-
-class attribute_value_visitor : public boost::static_visitor<jobject>
-{
-    public:
-        attribute_value_visitor(JNIEnv *env) : m_Env(env) {}
-
-        // Integer type value conversion
-        jobject operator ()(const int &value) const
-        {
-            jobject result = m_Env->NewObject(gSimulatorClassRefs.classInteger,
-                                              gSimulatorClassRefs.classIntegerCtor, value);
-            return result;
-        }
-
-        // Double type value conversion
-        jobject operator ()(const double &value) const
-        {
-            jobject result = m_Env->NewObject(gSimulatorClassRefs.classDouble,
-                                              gSimulatorClassRefs.classDoubleCtor, value);
-            return result;
-        }
-
-        // String type value conversion
-        jobject operator ()(const std::string &value) const
-        {
-            jstring str = m_Env->NewStringUTF(value.c_str());
-            return static_cast<jobject>(str);
-        }
-
-        // Boolean type value conversion
-        jobject operator ()(const bool &value) const
-        {
-            jobject result = m_Env->NewObject(gSimulatorClassRefs.classBoolean,
-                                              gSimulatorClassRefs.classBooleanCtor, value);
-            return result;
-        }
-#if 0
-        // SimulatorResourceModel::Attribute type value conversion
-        jobject operator ()(const SimulatorResourceModel::Attribute &value) const
-        {
-            JResourceAttributeConverter converter(value);
-            return converter.toJava();
-        }
-#endif
-
-    private:
-        JNIEnv *m_Env;
-};
-
-jobject JResourceAttributeConverter::toJava(JNIEnv *env)
-{
-    // Create an object of ResourceAttribute java class
-    jobject jattributeObj = (jobject) env->NewObject(gSimulatorClassRefs.classResourceAttribute,
-                            gSimulatorClassRefs.classResourceAttributeCtor);
-    if (env->ExceptionCheck() || !jattributeObj)
-    {
-        return nullptr;
-    }
-
-    // Set attribute name
-    if (!setName(env, jattributeObj))
-    {
-        return nullptr;
-    }
-
-    // Set types
-    if (!setType(env, jattributeObj))
-    {
-        return nullptr;
-    }
-
-    // Set value
-    if (!setValue(env, jattributeObj))
-    {
-        return nullptr;
-    }
-
-    // Set Range
-    if (!setRange(env, jattributeObj))
-    {
-        return nullptr;
-    }
-
-    // Set Allowed values
-    if (!setAllowedValues(env, jattributeObj))
-    {
-        return nullptr;
-    }
-
-    return jattributeObj;
-}
-
-bool JResourceAttributeConverter::setName(JNIEnv *env, jobject &jattributeObj)
-{
-    // Get field reference to "ResourceAttribute::m_name"
-    static jfieldID fidName = env->GetFieldID(gSimulatorClassRefs.classResourceAttribute, "m_name",
-                              "Ljava/lang/String;");
-    if (!fidName)
-    {
-        return false;
-    }
-
-    // Set the attribute name
-    std::string name = m_attribute.getName();
-    jstring jname = env->NewStringUTF(name.c_str());
-    env->SetObjectField(jattributeObj, fidName, jname);
-    if (env->ExceptionCheck())
-    {
-        return false;
-    }
-
-    return true;
-}
-
-bool JResourceAttributeConverter::setType(JNIEnv *env, jobject &jattributeObj)
-{
-    // Get class refs to ResourceAttribute::Type class
-    static jclass clsType = env->FindClass("org/oic/simulator/ResourceAttribute$Type");
-    if (!clsType)
-    {
-        return false;
-    }
-
-    // Get method ref to static method to ResourceAttribute::Type::getType
-    static jmethodID midGetType = env->GetStaticMethodID(clsType, "getType",
-                                  "(I)Lorg/oic/simulator/ResourceAttribute$Type;");
-    if (!midGetType)
-    {
-        return false;
-    }
-
-    // Get field reference to "ResourceAttribute::m_type"
-    static jfieldID fidType = env->GetFieldID(gSimulatorClassRefs.classResourceAttribute,
-                              "m_type", "Lorg/oic/simulator/ResourceAttribute$Type;");
-    if (!fidType)
-    {
-        return false;
-    }
-
-    int type = static_cast<int>(m_attribute.getValueType());
-    jobject jtype = env->CallStaticObjectMethod(clsType, midGetType, type);
-    if (env->ExceptionCheck())
-    {
-        return false;
-    }
-
-    env->SetObjectField(jattributeObj, fidType, jtype);
-    if (env->ExceptionCheck())
-    {
-        return false;
-    }
-
-    return true;
-}
-
-bool JResourceAttributeConverter::setValue(JNIEnv *env, jobject &jattributeObj)
-{
-    // Get field reference to "ResourceAttribute::m_value"
-    static jfieldID fidValue = env->GetFieldID(gSimulatorClassRefs.classResourceAttribute,
-                               "m_value", "Ljava/lang/Object;");
-    if (!fidValue)
-    {
-        return false;
-    }
-    jobject jvalue = boost::apply_visitor(attribute_value_visitor(env), m_attribute.getValue());
-    env->SetObjectField(jattributeObj, fidValue, jvalue);
-    return true;
-}
-
-bool JResourceAttributeConverter::setRange(JNIEnv *env, jobject &jattributeObj)
-{
-    int min = INT_MIN;
-    int max = INT_MAX;
-    m_attribute.getRange(min, max);
-    if (INT_MIN == min || INT_MAX == max)
-    {
-        return true;
-    }
-    env->CallVoidMethod(jattributeObj, gSimulatorClassRefs.classResourceAttributeSetRange, min, max);
-    if (env->ExceptionCheck())
-    {
-        return false;
-    }
-
-    return true;
-}
-
-bool JResourceAttributeConverter::setAllowedValues(JNIEnv *env, jobject &jattributeObj)
-{
-    // Get field reference to "ResourceAttribute::m_AllowedValues"
-    static jfieldID fidAllowedValues = env->GetFieldID(gSimulatorClassRefs.classResourceAttribute,
-                                       "m_AllowedValues", "Ljava/lang/Object;");
-    if (!fidAllowedValues)
-    {
-        return false;
-    }
-
-    jobjectArray jallowedValues = env->NewObjectArray(m_attribute.getAllowedValuesSize(),
-                                  gSimulatorClassRefs.classObject, NULL);
-    if (!jallowedValues)
-    {
-        return false;
-    }
-
-    int index = 0;
-    for (auto & value : m_attribute.getAllowedValues())
-    {
-        jobject jvalue = boost::apply_visitor(attribute_value_visitor(env), value);
-        env->SetObjectArrayElement(jallowedValues, index++, jvalue);
-    }
-
-    env->SetObjectField(jattributeObj, fidAllowedValues, jallowedValues);
-    if (env->ExceptionCheck())
-    {
-        return false;
-    }
-
-    return true;
-}
\ No newline at end of file
diff --git a/service/simulator/java/jni/resource_attributes_jni.h b/service/simulator/java/jni/resource_attributes_jni.h
deleted file mode 100644 (file)
index 3c34cf1..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-#ifndef RESOURCE_ATTRIBUTE_JNI_H_
-#define RESOURCE_ATTRIBUTE_JNI_H_
-
-#include <jni.h>
-#include "simulator_resource_model.h"
-
-class JResourceAttributeConverter
-{
-    public:
-        JResourceAttributeConverter(SimulatorResourceModel::Attribute &attribute) {m_attribute = attribute;}
-        JResourceAttributeConverter(const JResourceAttributeConverter &) = delete;
-        JResourceAttributeConverter &operator=(const JResourceAttributeConverter &) = delete;
-        JResourceAttributeConverter(const JResourceAttributeConverter &&) = delete;
-        JResourceAttributeConverter &operator=(const JResourceAttributeConverter && ) = delete;
-        jobject toJava(JNIEnv *env);
-
-    private:
-        bool setName(JNIEnv *env, jobject &jaAttributeObj);
-        bool setType(JNIEnv *env, jobject &jaAttributeObj);
-        bool setValue(JNIEnv *env, jobject &jaAttributeObj);
-        bool setRange(JNIEnv *env, jobject &jaAttributeObj);
-        bool setAllowedValues(JNIEnv *env, jobject &jaAttributeObj);
-
-        SimulatorResourceModel::Attribute m_attribute;
-};
-
-#endif //SIMULATOR_RESOURCE_ATTRIBUTE_JNI_H_
diff --git a/service/simulator/java/jni/simulator_collection_resource_jni.cpp b/service/simulator/java/jni/simulator_collection_resource_jni.cpp
new file mode 100644 (file)
index 0000000..36e7a68
--- /dev/null
@@ -0,0 +1,154 @@
+/******************************************************************
+ *
+ * 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 "simulator_exceptions_jni.h"
+#include "simulator_resource_utils_jni.h"
+#include "simulator_utils_jni.h"
+#include "jni_sharedobject_holder.h"
+#include "jni_string.h"
+#include "jni_vector.h"
+
+#include "simulator_collection_resource.h"
+
+#define VALIDATE_OBJECT(ENV, OBJECT) if (!OBJECT){ThrowBadObjectException(ENV, "No corresponsing native object!"); return;}
+#define VALIDATE_OBJECT_RET(ENV, OBJECT, RET) if (!OBJECT){ThrowBadObjectException(ENV, "No corresponsing native object!"); return RET;}
+
+extern SimulatorResourceSP SimulatorResourceToCpp(JNIEnv *env, jobject object);
+
+static SimulatorCollectionResourceSP simulatorCollectionResourceToCpp(JNIEnv *env, jobject object)
+{
+    JniSharedObjectHolder<SimulatorCollectionResource> *jniResource =
+        getHandle<JniSharedObjectHolder<SimulatorCollectionResource>>(env, object);
+    if (jniResource)
+        return jniResource->get();
+    return nullptr;
+}
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_server_SimulatorCollectionResource_nativeGetSupportedResources
+(JNIEnv *env, jobject object)
+{
+    auto collectionResource = simulatorCollectionResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, collectionResource, nullptr)
+
+    std::vector<std::string> supportedTypes = collectionResource->getSupportedResources();
+    return JniVector(env).toJava(supportedTypes);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorCollectionResource_nativeAddChildResource
+(JNIEnv *env, jobject object, jobject resource)
+{
+    VALIDATE_INPUT(env, !resource, "Child resource is null!")
+
+    auto childResource = SimulatorResourceToCpp(env, resource);
+    VALIDATE_INPUT(env, !childResource, "No corresponding native object of child resource!")
+
+    auto collectionResource = simulatorCollectionResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, collectionResource)
+
+    try
+    {
+        collectionResource->addChildResource(childResource);
+    }
+    catch (InvalidArgsException &e)
+    {
+        ThrowInvalidArgsException(env, e.code(), e.what());
+    }
+    catch (SimulatorException &e)
+    {
+        ThrowSimulatorException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorCollectionResource_nativeRemoveChildResource
+(JNIEnv *env, jobject object, jobject resource)
+{
+    VALIDATE_INPUT(env, !resource, "Child resource is null!")
+
+    auto childResource = SimulatorResourceToCpp(env, resource);
+    VALIDATE_INPUT(env, !childResource, "No corresponding native object of child resource!")
+
+    auto collectionResource = simulatorCollectionResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, collectionResource)
+
+    try
+    {
+        collectionResource->removeChildResource(childResource);
+    }
+    catch (InvalidArgsException &e)
+    {
+        ThrowInvalidArgsException(env, e.code(), e.what());
+    }
+    catch (SimulatorException &e)
+    {
+        ThrowSimulatorException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorCollectionResource_nativeRemoveChildResourceByUri
+(JNIEnv *env, jobject object, jstring uri)
+{
+    auto collectionResource = simulatorCollectionResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, collectionResource)
+
+    try
+    {
+        JniString jniUri(env, uri);
+        collectionResource->removeChildResource(jniUri.get());
+    }
+    catch (InvalidArgsException &e)
+    {
+        ThrowInvalidArgsException(env, e.code(), e.what());
+    }
+    catch (SimulatorException &e)
+    {
+        ThrowSimulatorException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_server_SimulatorCollectionResource_nativeGetChildResources
+(JNIEnv *env, jobject object)
+{
+    auto collectionResource = simulatorCollectionResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, collectionResource, nullptr)
+
+    std::vector<SimulatorResourceSP> childResources = collectionResource->getChildResources();
+    return CreateSimulatorResourceVector(env,  childResources);
+}
+
+JNIEXPORT void JNICALL Java_org_oic_simulator_server_SimulatorCollectionResource_nativeDispose
+(JNIEnv *env, jobject object)
+{
+    JniSharedObjectHolder<SimulatorCollectionResource> *resource =
+        getHandle<JniSharedObjectHolder<SimulatorCollectionResource>>(env, object);
+    delete resource;
+}
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/service/simulator/java/jni/simulator_common_jni.h b/service/simulator/java/jni/simulator_common_jni.h
deleted file mode 100644 (file)
index b0fd74b..0000000
+++ /dev/null
@@ -1,107 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-#ifndef SIMULATOR_COMMON_JNI_H_
-#define SIMULATOR_COMMON_JNI_H_
-
-#include <jni.h>
-
-typedef struct
-{
-    jclass classObject;
-    jclass classInteger;
-    jclass classDouble;
-    jclass classBoolean;
-    jclass classString;
-    jclass classHashMap;
-    jclass classVector;
-    jclass classMap;
-    jclass classMapEntry;
-    jclass classSet;
-    jclass classIterator;
-    jclass classLinkedList;
-
-    jclass classSimulatorResource;
-    jclass classSimulatorResourceModel;
-    jclass classResourceAttribute;
-    jclass classSimulatorRemoteResource;
-    jclass classSimulatorCallback;
-    jclass classObserverInfo;
-    jclass classDeviceInfo;
-    jclass classPlatformInfo;
-    jclass classSimulatorException;
-    jclass classInvalidArgsException;
-    jclass classNoSupportException;
-    jclass classOperationInProgressException;
-
-    jmethodID classIntegerCtor;
-    jmethodID classDoubleCtor;
-    jmethodID classBooleanCtor;
-    jmethodID classHashMapCtor;
-    jmethodID classHashMapPut;
-    jmethodID classVectorCtor;
-    jmethodID classVectorAddElement;
-    jmethodID classMapEntrySet;
-    jmethodID classMapGetKey;
-    jmethodID classMapGetValue;
-    jmethodID classIteratorId;
-    jmethodID classHasNextId;
-    jmethodID classNextId;
-    jmethodID classLinkedListCtor;
-    jmethodID classLinkedListAddObject;
-
-    jmethodID classSimulatorResourceCtor;
-    jmethodID classSimulatorResourceModelCtor;
-    jmethodID classResourceAttributeCtor;
-    jmethodID classResourceAttributeSetRange;
-    jmethodID classSimulatorResourceModelId;
-    jmethodID classObserverInfoCtor;
-    jmethodID classSimulatorExceptionCtor;
-    jmethodID classInvalidArgsExceptionCtor;
-    jmethodID classNoSupportExceptionCtor;
-    jmethodID classOperationInProgressExceptionCtor;
-
-} SimulatorClassRefs;
-
-static jfieldID GetHandleField(JNIEnv *env, jobject jobj)
-{
-    jclass cls = env->GetObjectClass(jobj);
-    return env->GetFieldID(cls, "nativeHandle", "J");
-}
-
-template <typename T>
-static T *GetHandle(JNIEnv *env, jobject jobj)
-{
-    jlong handle = env->GetLongField(jobj, GetHandleField(env, jobj));
-    return reinterpret_cast<T *>(handle);
-}
-
-template <typename T>
-static void SetHandle(JNIEnv *env, jobject jobj, T *type)
-{
-    jlong handle = reinterpret_cast<jlong>(type);
-
-    env->SetLongField(jobj, GetHandleField(env, jobj), handle);
-}
-
-JNIEnv *getEnv();
-void releaseEnv();
-
-#endif
index c954a97..1eb4cb0 100644 (file)
  ******************************************************************/
 
 #include "simulator_device_info_jni.h"
-#include "simulator_common_jni.h"
+#include "simulator_utils_jni.h"
 
 extern SimulatorClassRefs gSimulatorClassRefs;
-jobject JDeviceInfo::toJava(DeviceInfo &deviceInfo)
+
+jobject JniDeviceInfo::toJava(DeviceInfo &deviceInfo)
 {
     if (!m_env)
         return nullptr;
 
-    jmethodID deviceInfoMId = m_env->GetMethodID(gSimulatorClassRefs.classDeviceInfo, "<init>", "(V)V");
-    if (!deviceInfoMId)
-        return nullptr;
-
-    jobject jDeviceInfo = (jobject) m_env->NewObject(gSimulatorClassRefs.classDeviceInfo, deviceInfoMId);
-    if (!jDeviceInfo)
-        return nullptr;
-
+    static jmethodID deviceInfoCtor = m_env->GetMethodID(gSimulatorClassRefs.deviceInfoCls, "<init>",
+                                      "()V");
+    jobject jDeviceInfo = m_env->NewObject(gSimulatorClassRefs.deviceInfoCls, deviceInfoCtor);
     setFieldValue(jDeviceInfo, "mName", deviceInfo.getName());
     setFieldValue(jDeviceInfo, "mID", deviceInfo.getID());
     setFieldValue(jDeviceInfo, "mSpecVersion", deviceInfo.getSpecVersion());
@@ -43,60 +39,11 @@ jobject JDeviceInfo::toJava(DeviceInfo &deviceInfo)
     return jDeviceInfo;
 }
 
-void JDeviceInfo::setFieldValue(jobject jDeviceInfo, const std::string &fieldName,
-                                const std::string &value)
+void JniDeviceInfo::setFieldValue(jobject jDeviceInfo, const std::string &fieldName,
+                                  const std::string &value)
 {
-    jfieldID fieldID = m_env->GetFieldID(gSimulatorClassRefs.classDeviceInfo, fieldName.c_str(),
+    jfieldID fieldID = m_env->GetFieldID(m_env->GetObjectClass(jDeviceInfo), fieldName.c_str(),
                                          "Ljava/lang/String;");
     jstring valueStr = m_env->NewStringUTF(value.c_str());
     m_env->SetObjectField(jDeviceInfo, fieldID, valueStr);
 }
-
-void JniDeviceInfoListener::onDeviceInfoReceived(DeviceInfo &deviceInfo)
-{
-    // Get the environment
-    JNIEnv *env = getEnv();
-    if (!env)
-        return;
-
-    jobject listener = env->NewLocalRef(m_listener);
-    if (!listener)
-    {
-        releaseEnv();
-        return;
-    }
-
-    jclass listenerCls = env->GetObjectClass(listener);
-    if (!listenerCls)
-    {
-        releaseEnv();
-        return;
-    }
-
-    jmethodID listenerMId = env->GetMethodID(listenerCls, "onDeviceFound",
-                            "(Lorg/oic/simulator/DeviceInfo;)V");
-    if (!listenerMId)
-    {
-        releaseEnv();
-        return;
-    }
-
-    // Convert CPP to Java DeviceInfo object
-    jobject jDeviceInfo = JDeviceInfo(env).toJava(deviceInfo);
-    if (!jDeviceInfo)
-    {
-        releaseEnv();
-        return;
-    }
-
-    // Invoke java listener with DeviceInfo
-    env->CallVoidMethod(listener, listenerMId, jDeviceInfo);
-    if (env->ExceptionCheck())
-    {
-        releaseEnv();
-        return;
-    }
-
-    releaseEnv();
-}
-
index ac53867..acb1495 100644 (file)
 #ifndef SIMULATOR_DEVICE_INFO_JNI_H_
 #define SIMULATOR_DEVICE_INFO_JNI_H_
 
-#include "simulator_device_info.h"
 #include <jni.h>
 
-class JDeviceInfo
+#include "simulator_device_info.h"
+
+class JniDeviceInfo
 {
     public:
-        JDeviceInfo(JNIEnv *env) : m_env(env) {}
-        JDeviceInfo(const JDeviceInfo &) = delete;
-        JDeviceInfo &operator=(const JDeviceInfo &) = delete;
-        JDeviceInfo(const JDeviceInfo &&) = delete;
-        JDeviceInfo &operator=(const JDeviceInfo && ) = delete;
+        JniDeviceInfo(JNIEnv *env) : m_env(env) {}
+        JniDeviceInfo(const JniDeviceInfo &) = delete;
+        JniDeviceInfo &operator=(const JniDeviceInfo &) = delete;
+        JniDeviceInfo(const JniDeviceInfo &&) = delete;
+        JniDeviceInfo &operator=(const JniDeviceInfo && ) = delete;
         jobject toJava(DeviceInfo &deviceInfo);
 
     private:
@@ -41,18 +42,4 @@ class JDeviceInfo
         JNIEnv *m_env;
 };
 
-class JniDeviceInfoListener
-{
-    public:
-        JniDeviceInfoListener(JNIEnv *env, jobject listener)
-        {
-            m_listener = env->NewWeakGlobalRef(listener);
-        }
-
-        void onDeviceInfoReceived(DeviceInfo &deviceInfo);
-
-    private:
-        jweak m_listener;
-};
-
 #endif
diff --git a/service/simulator/java/jni/simulator_exceptions_jni.cpp b/service/simulator/java/jni/simulator_exceptions_jni.cpp
new file mode 100644 (file)
index 0000000..5739364
--- /dev/null
@@ -0,0 +1,89 @@
+/******************************************************************
+ *
+ * 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 "simulator_exceptions_jni.h"
+#include "simulator_utils_jni.h"
+
+extern SimulatorClassRefs gSimulatorClassRefs;
+
+void ThrowSimulatorException(JNIEnv *env, SimulatorResult code, const char *message)
+{
+    static jmethodID simulatorExceptionCtor = env->GetMethodID(
+                gSimulatorClassRefs.simulatorExceptionCls, "<init>", "(ILjava/lang/String;)V");
+
+    jobject exceptionObject = env->NewObject(gSimulatorClassRefs.simulatorExceptionCls,
+                              simulatorExceptionCtor, code, env->NewStringUTF(message));
+    if (exceptionObject)
+    {
+        env->Throw((jthrowable) exceptionObject);
+    }
+}
+
+void ThrowInvalidArgsException(JNIEnv *env, SimulatorResult code, const char *message)
+{
+    static jmethodID invalidArgsExceptionCtor = env->GetMethodID(
+                gSimulatorClassRefs.invalidArgsExceptionCls, "<init>", "(ILjava/lang/String;)V");
+
+    jobject exceptionObject = env->NewObject(gSimulatorClassRefs.invalidArgsExceptionCls,
+                              invalidArgsExceptionCtor, code, env->NewStringUTF(message));
+    if (exceptionObject)
+    {
+        env->Throw((jthrowable) exceptionObject);
+    }
+}
+
+void ThrowNoSupportException(JNIEnv *env, const char *message)
+{
+    static jmethodID noSupportExceptionCtor = env->GetMethodID(
+                gSimulatorClassRefs.noSupportExceptionCls, "<init>", "(Ljava/lang/String;)V");
+
+    jobject exceptionObject = env->NewObject(gSimulatorClassRefs.noSupportExceptionCls,
+                              noSupportExceptionCtor, env->NewStringUTF(message));
+    if (exceptionObject)
+    {
+        env->Throw((jthrowable) exceptionObject);
+    }
+}
+
+void ThrowOperationInProgressException(JNIEnv *env, const char *message)
+{
+    static jmethodID operationInProgressExceptionCtor = env->GetMethodID(
+                gSimulatorClassRefs.operationInProgressExceptionCls, "<init>", "(Ljava/lang/String;)V");
+
+    jobject exceptionObject = env->NewObject(gSimulatorClassRefs.operationInProgressExceptionCls,
+                              operationInProgressExceptionCtor, env->NewStringUTF(message));
+    if (exceptionObject)
+    {
+        env->Throw((jthrowable) exceptionObject);
+    }
+}
+
+void ThrowBadObjectException(JNIEnv *env, const char *message)
+{
+    static jmethodID simulatorExceptionCtor = env->GetMethodID(
+                gSimulatorClassRefs.simulatorExceptionCls, "<init>", "(ILjava/lang/String;)V");
+
+    jobject exceptionObject = env->NewObject(gSimulatorClassRefs.simulatorExceptionCls,
+                              simulatorExceptionCtor, SIMULATOR_BAD_OBJECT, env->NewStringUTF(message));
+    if (exceptionObject)
+    {
+        env->Throw((jthrowable) exceptionObject);
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/jni/simulator_exceptions_jni.h b/service/simulator/java/jni/simulator_exceptions_jni.h
new file mode 100644 (file)
index 0000000..4add306
--- /dev/null
@@ -0,0 +1,45 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file   simulator_jni_util.h
+ *
+ * @brief  This file contains the utility functions for conversions from java to CPP
+ * and viceversa
+ */
+
+#ifndef SIMULATOR_EXCEPTIONS_JNI_H_
+#define SIMULATOR_EXCEPTIONS_JNI_H_
+
+#include <jni.h>
+
+#include "simulator_error_codes.h"
+
+void ThrowSimulatorException(JNIEnv *env, SimulatorResult code, const char *message);
+
+void ThrowInvalidArgsException(JNIEnv *env, SimulatorResult code, const char *message);
+
+void ThrowNoSupportException(JNIEnv *env, const char *message);
+
+void ThrowOperationInProgressException(JNIEnv *env, const char *message);
+
+void ThrowBadObjectException(JNIEnv *env, const char *message);
+
+#endif
diff --git a/service/simulator/java/jni/simulator_init_jni.cpp b/service/simulator/java/jni/simulator_init_jni.cpp
new file mode 100644 (file)
index 0000000..cb34eba
--- /dev/null
@@ -0,0 +1,299 @@
+/******************************************************************
+ *
+ * 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 "simulator_utils_jni.h"
+#include <mutex>
+
+#define OBJECT_CLS "java/lang/Object"
+#define INTEGER_CLS "java/lang/Integer"
+#define DOUBLE_CLS "java/lang/Double"
+#define BOOLEAN_CLS "java/lang/Boolean"
+#define STRING_CLS "java/lang/String"
+#define VECTOR_CLS "java/util/Vector"
+#define HASHMAP_CLS "java/util/HashMap"
+#define MAP_CLS "java/util/Map"
+#define MAP_ENTRY_CLS "java/util/Map$Entry"
+#define SET_CLS "java/util/Set"
+#define ITERATOR_CLS "java/util/Iterator"
+
+#define SIMULATOR_RESOURCE_CLS "org/oic/simulator/server/SimulatorResource"
+#define SIMULATOR_RESOURCE_TYPE_CLS "org/oic/simulator/server/SimulatorResource$Type"
+#define SIMULATOR_SINGLE_RESOURCE_CLS "org/oic/simulator/server/SimulatorSingleResource"
+#define SIMULATOR_COLLECTION_RESOURCE_CLS "org/oic/simulator/server/SimulatorCollectionResource"
+#define SIMULATOR_RESOURCE_MODEL_CLS "org/oic/simulator/SimulatorResourceModel"
+#define SIMULATOR_RESOURCE_ATTRIBUTE_CLS "org/oic/simulator/SimulatorResourceAttribute"
+#define ATTRIBUTE_VALUE_CLS "org/oic/simulator/AttributeValue"
+#define ATTRIBUTE_VALUE_TYPE_CLS "org/oic/simulator/AttributeValue$ValueType"
+#define ATTRIBUTE_TYPE_INFO_CLS "org/oic/simulator/AttributeValue$TypeInfo"
+#define ATTRIBUTE_PROPERTY_CLS "org/oic/simulator/AttributeProperty"
+#define ATTRIBUTE_PROPERTY_TYPE_CLS "org/oic/simulator/AttributeProperty$Type"
+#define AUTO_UPDATE_TYPE_CLS "org/oic/simulator/server/SimulatorResource$AutoUpdateType"
+
+#define SIMULATOR_REMOTE_RESOURCE_CLS "org/oic/simulator/client/SimulatorRemoteResource"
+#define REQUEST_TYPE_CLS "org/oic/simulator/client/SimulatorRemoteResource$RequestType"
+#define OBSERVER_CLS "org/oic/simulator/server/Observer"
+#define DEVICE_INFO_CLS "org/oic/simulator/DeviceInfo"
+#define PLATFORM_INFO_CLS "org/oic/simulator/PlatformInfo"
+#define SIMULATOR_REQUEST_MODEL_CLS "org/oic/simulator/client/SimulatorRequestModel"
+
+#define SIMULATOR_EXCEPTION_CLS "org/oic/simulator/SimulatorException"
+#define INVALID_ARGS_EXCEPTION_CLS "org/oic/simulator/InvalidArgsException"
+#define NO_SUPPORT_EXCEPTION_CLS "org/oic/simulator/NoSupportException"
+#define OPERATION_IN_PROGRESS_EXCEPTION_CLS "org/oic/simulator/OperationInProgressException"
+#define SIMULATOR_RESULT_CLS "org/oic/simulator/SimulatorResult"
+
+#define INTEGER_PROPERTY "org/oic/simulator/IntegerProperty"
+#define INTEGER_PROPERTY_BUILDER "org/oic/simulator/IntegerProperty$Builder"
+#define DOUBLE_PROPERTY "org/oic/simulator/DoubleProperty"
+#define DOUBLE_PROPERTY_BUILDER "org/oic/simulator/DoubleProperty$Builder"
+#define BOOLEAN_PROPERTY "org/oic/simulator/BooleanProperty"
+#define BOOLEAN_PROPERTY_BUILDER "org/oic/simulator/BooleanProperty$Builder"
+#define STRING_PROPERTY "org/oic/simulator/StringProperty"
+#define STRING_PROPERTY_BUILDER "org/oic/simulator/StringProperty$Builder"
+#define ARRAY_PROPERTY "org/oic/simulator/ArrayProperty"
+#define ARRAY_PROPERTY_BUILDER "org/oic/simulator/ArrayProperty$Builder"
+#define MODEL_PROPERTY "org/oic/simulator/ModelProperty"
+
+#define INTEGER_1D_ARRAY "[Ljava/lang/Integer;"
+#define INTEGER_2D_ARRAY "[[Ljava/lang/Integer;"
+#define INTEGER_3D_ARRAY "[[Ljava/lang/Integer;"
+#define DOUBLE_1D_ARRAY "[Ljava/lang/Double;"
+#define DOUBLE_2D_ARRAY "[[Ljava/lang/Double;"
+#define DOUBLE_3D_ARRAY "[[Ljava/lang/Double;"
+#define BOOLEAN_1D_ARRAY "[Ljava/lang/Boolean;"
+#define BOOLEAN_2D_ARRAY "[[Ljava/lang/Boolean;"
+#define BOOLEAN_3D_ARRAY "[[Ljava/lang/Boolean;"
+#define STRING_1D_ARRAY "[Ljava/lang/String;"
+#define STRING_2D_ARRAY "[[Ljava/lang/String;"
+#define STRING_3D_ARRAY "[[Ljava/lang/String;"
+#define SIMULATOR_RESOURCE_MODEL_1D_ARRAY "[Lorg/oic/simulator/SimulatorResourceModel;"
+#define SIMULATOR_RESOURCE_MODEL_2D_ARRAY "[[Lorg/oic/simulator/SimulatorResourceModel;"
+#define SIMULATOR_RESOURCE_MODEL_3D_ARRAY "[[Lorg/oic/simulator/SimulatorResourceModel;"
+
+SimulatorClassRefs gSimulatorClassRefs;
+static std::mutex gJvmMutex;
+static JavaVM *gJavaVM;
+
+JNIEnv *GetEnv()
+{
+    std::unique_lock<std::mutex> lock(gJvmMutex);
+    if (!gJavaVM)
+        return nullptr;
+
+    JNIEnv *env = nullptr;
+    jint ret = gJavaVM->GetEnv((void **)&env, JNI_VERSION_1_6);
+    switch (ret)
+    {
+        case JNI_OK:
+            return env;
+        case JNI_EDETACHED:
+            if (!gJavaVM->AttachCurrentThread((void **)&env, NULL))
+                return env;
+    }
+
+    return nullptr;
+}
+
+void ReleaseEnv()
+{
+    std::unique_lock<std::mutex> lock(gJvmMutex);
+    if (!gJavaVM)
+        return;
+    gJavaVM->DetachCurrentThread();
+}
+
+static void getClassRef(JNIEnv *env, const char *className, jclass &classRef)
+{
+    jclass localRef = env->FindClass(className);
+    if (localRef)
+    {
+        classRef = (jclass) env->NewGlobalRef(localRef);
+        env->DeleteLocalRef(localRef);
+    }
+}
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void * /*reserved*/)
+{
+    if (!vm)
+        return JNI_ERR;
+
+    JNIEnv *env = nullptr;
+    if (JNI_OK != vm->GetEnv((void **) &env, JNI_VERSION_1_6))
+        return JNI_ERR;
+
+    // Get the class references
+    getClassRef(env, OBJECT_CLS, gSimulatorClassRefs.objectCls);
+    getClassRef(env, INTEGER_CLS, gSimulatorClassRefs.integerCls);
+    getClassRef(env, DOUBLE_CLS, gSimulatorClassRefs.doubleCls);
+    getClassRef(env, BOOLEAN_CLS, gSimulatorClassRefs.booleanCls);
+    getClassRef(env, STRING_CLS, gSimulatorClassRefs.stringCls);
+    getClassRef(env, VECTOR_CLS, gSimulatorClassRefs.vectorCls);
+    getClassRef(env, HASHMAP_CLS, gSimulatorClassRefs.hashMapCls);
+    getClassRef(env, MAP_CLS, gSimulatorClassRefs.mapCls);
+    getClassRef(env, MAP_ENTRY_CLS, gSimulatorClassRefs.mapEntryCls);
+    getClassRef(env, SET_CLS, gSimulatorClassRefs.setCls);
+    getClassRef(env, ITERATOR_CLS, gSimulatorClassRefs.iteratorCls);
+
+    getClassRef(env, SIMULATOR_RESOURCE_CLS, gSimulatorClassRefs.simulatorResourceCls);
+    getClassRef(env, SIMULATOR_RESOURCE_TYPE_CLS, gSimulatorClassRefs.simulatorResourceTypeCls);
+    getClassRef(env, SIMULATOR_SINGLE_RESOURCE_CLS, gSimulatorClassRefs.simulatorSingleResourceCls);
+    getClassRef(env, SIMULATOR_COLLECTION_RESOURCE_CLS,
+                gSimulatorClassRefs.simulatorCollectionResourceCls);
+    getClassRef(env, SIMULATOR_RESOURCE_MODEL_CLS, gSimulatorClassRefs.simulatorResourceModelCls);
+    getClassRef(env, SIMULATOR_RESOURCE_ATTRIBUTE_CLS,
+                gSimulatorClassRefs.simulatorResourceAttributeCls);
+    getClassRef(env, ATTRIBUTE_VALUE_CLS, gSimulatorClassRefs.attributeValueCls);
+    getClassRef(env, ATTRIBUTE_VALUE_TYPE_CLS, gSimulatorClassRefs.attributeValueTypeCls);
+    getClassRef(env, ATTRIBUTE_TYPE_INFO_CLS, gSimulatorClassRefs.attributeTypeInfoCls);
+    getClassRef(env, ATTRIBUTE_PROPERTY_CLS, gSimulatorClassRefs.attributePropertyCls);
+    getClassRef(env, ATTRIBUTE_PROPERTY_TYPE_CLS, gSimulatorClassRefs.attributePropertyTypeCls);
+    getClassRef(env, INTEGER_PROPERTY, gSimulatorClassRefs.integerPropertyCls);
+    getClassRef(env, INTEGER_PROPERTY_BUILDER, gSimulatorClassRefs.integerPropertyBuilderCls);
+    getClassRef(env, DOUBLE_PROPERTY, gSimulatorClassRefs.doublePropertyCls);
+    getClassRef(env, DOUBLE_PROPERTY_BUILDER, gSimulatorClassRefs.doublePropertyBuilderCls);
+    getClassRef(env, BOOLEAN_PROPERTY, gSimulatorClassRefs.booleanPropertyCls);
+    getClassRef(env, BOOLEAN_PROPERTY_BUILDER, gSimulatorClassRefs.booleanPropertyBuilderCls);
+    getClassRef(env, STRING_PROPERTY, gSimulatorClassRefs.stringPropertyCls);
+    getClassRef(env, STRING_PROPERTY_BUILDER, gSimulatorClassRefs.stringPropertyBuilderCls);
+    getClassRef(env, ARRAY_PROPERTY, gSimulatorClassRefs.arrayPropertyCls);
+    getClassRef(env, ARRAY_PROPERTY_BUILDER, gSimulatorClassRefs.arrayPropertyBuilderCls);
+    getClassRef(env, MODEL_PROPERTY, gSimulatorClassRefs.modelPropertyCls);
+    getClassRef(env, AUTO_UPDATE_TYPE_CLS, gSimulatorClassRefs.autoUpdateTypeCls);
+
+    getClassRef(env, SIMULATOR_REMOTE_RESOURCE_CLS,
+                gSimulatorClassRefs.simulatorRemoteResourceCls);
+    getClassRef(env, REQUEST_TYPE_CLS, gSimulatorClassRefs.requestTypeCls);
+    getClassRef(env, OBSERVER_CLS, gSimulatorClassRefs.observerCls);
+    getClassRef(env, DEVICE_INFO_CLS, gSimulatorClassRefs.deviceInfoCls);
+    getClassRef(env, PLATFORM_INFO_CLS, gSimulatorClassRefs.platformInfoCls);
+    getClassRef(env, SIMULATOR_REQUEST_MODEL_CLS, gSimulatorClassRefs.simulatorRequestModelCls);
+
+    getClassRef(env, SIMULATOR_EXCEPTION_CLS, gSimulatorClassRefs.simulatorExceptionCls);
+    getClassRef(env, INVALID_ARGS_EXCEPTION_CLS, gSimulatorClassRefs.invalidArgsExceptionCls);
+    getClassRef(env, NO_SUPPORT_EXCEPTION_CLS, gSimulatorClassRefs.noSupportExceptionCls);
+    getClassRef(env, OPERATION_IN_PROGRESS_EXCEPTION_CLS,
+                gSimulatorClassRefs.operationInProgressExceptionCls);
+    getClassRef(env, SIMULATOR_RESULT_CLS, gSimulatorClassRefs.simulatorResultCls);
+
+    getClassRef(env, INTEGER_1D_ARRAY, gSimulatorClassRefs.integer1DArrayCls);
+    getClassRef(env, INTEGER_2D_ARRAY, gSimulatorClassRefs.integer2DArrayCls);
+    getClassRef(env, INTEGER_3D_ARRAY, gSimulatorClassRefs.integer3DArrayCls);
+    getClassRef(env, DOUBLE_1D_ARRAY, gSimulatorClassRefs.double1DArrayCls);
+    getClassRef(env, DOUBLE_2D_ARRAY, gSimulatorClassRefs.double2DArrayCls);
+    getClassRef(env, DOUBLE_3D_ARRAY, gSimulatorClassRefs.double3DArrayCls);
+    getClassRef(env, BOOLEAN_1D_ARRAY, gSimulatorClassRefs.boolean1DArrayCls);
+    getClassRef(env, BOOLEAN_2D_ARRAY, gSimulatorClassRefs.boolean2DArrayCls);
+    getClassRef(env, BOOLEAN_3D_ARRAY, gSimulatorClassRefs.boolean3DArrayCls);
+    getClassRef(env, STRING_1D_ARRAY, gSimulatorClassRefs.string1DArrayCls);
+    getClassRef(env, STRING_2D_ARRAY, gSimulatorClassRefs.string2DArrayCls);
+    getClassRef(env, STRING_3D_ARRAY, gSimulatorClassRefs.string3DArrayCls);
+    getClassRef(env, SIMULATOR_RESOURCE_MODEL_1D_ARRAY,
+                gSimulatorClassRefs.simulatorResModel1DArrayCls);
+    getClassRef(env, SIMULATOR_RESOURCE_MODEL_2D_ARRAY,
+                gSimulatorClassRefs.simulatorResModel2DArrayCls);
+    getClassRef(env, SIMULATOR_RESOURCE_MODEL_3D_ARRAY,
+                gSimulatorClassRefs.simulatorResModel3DArrayCls);
+
+    gJavaVM = vm;
+    return JNI_VERSION_1_6;
+}
+
+JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void * /*reserved*/)
+{
+    if (!vm)
+        return;
+
+    JNIEnv *env = nullptr;
+    if (JNI_OK != vm->GetEnv((void **) &env, JNI_VERSION_1_6))
+        return;
+
+    // Release the class global references
+    env->DeleteGlobalRef(gSimulatorClassRefs.objectCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.integerCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.doubleCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.booleanCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.stringCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.hashMapCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.vectorCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.mapCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.mapEntryCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.setCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.iteratorCls);
+
+    env->DeleteGlobalRef(gSimulatorClassRefs.simulatorResourceCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.simulatorSingleResourceCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.simulatorCollectionResourceCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.simulatorResourceModelCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.simulatorResourceAttributeCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.attributeValueCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.attributeValueTypeCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.attributeTypeInfoCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.attributePropertyCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.attributePropertyTypeCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.integerPropertyCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.integerPropertyBuilderCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.doublePropertyCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.doublePropertyBuilderCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.booleanPropertyCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.booleanPropertyBuilderCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.stringPropertyCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.stringPropertyBuilderCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.arrayPropertyCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.arrayPropertyBuilderCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.modelPropertyCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.autoUpdateTypeCls);
+
+    env->DeleteGlobalRef(gSimulatorClassRefs.simulatorRemoteResourceCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.requestTypeCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.observerCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.deviceInfoCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.platformInfoCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.simulatorRequestModelCls);
+
+    env->DeleteGlobalRef(gSimulatorClassRefs.simulatorExceptionCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.invalidArgsExceptionCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.noSupportExceptionCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.operationInProgressExceptionCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.simulatorResultCls);
+
+    env->DeleteGlobalRef(gSimulatorClassRefs.integer1DArrayCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.integer2DArrayCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.integer3DArrayCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.double1DArrayCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.double2DArrayCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.double3DArrayCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.boolean1DArrayCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.boolean2DArrayCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.boolean3DArrayCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.string1DArrayCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.string2DArrayCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.string3DArrayCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.simulatorResModel1DArrayCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.simulatorResModel2DArrayCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.simulatorResModel3DArrayCls);
+}
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/service/simulator/java/jni/simulator_jni_utils.cpp b/service/simulator/java/jni/simulator_jni_utils.cpp
deleted file mode 100644 (file)
index 0274d63..0000000
+++ /dev/null
@@ -1,71 +0,0 @@
-/******************************************************************
- *
- * 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 "simulator_jni_utils.h"
-#include "simulator_common_jni.h"
-
-extern SimulatorClassRefs gSimulatorClassRefs;
-
-void throwSimulatorException(JNIEnv *env, SimulatorResult errCode, const char *errMessage)
-{
-    jobject ex = env->NewObject(gSimulatorClassRefs.classSimulatorException,
-                                gSimulatorClassRefs.classSimulatorExceptionCtor, errCode,
-                                env->NewStringUTF(errMessage));
-    if (!ex)
-    {
-        return;
-    }
-    env->Throw((jthrowable)ex);
-}
-
-void throwInvalidArgsException(JNIEnv *env, SimulatorResult errCode, const char *errMessage)
-{
-    jobject ex = env->NewObject(gSimulatorClassRefs.classInvalidArgsException,
-                                gSimulatorClassRefs.classInvalidArgsExceptionCtor, errCode,
-                                env->NewStringUTF(errMessage));
-    if (!ex)
-    {
-        return;
-    }
-    env->Throw((jthrowable)ex);
-}
-
-void throwNoSupportException(JNIEnv *env, SimulatorResult errCode, const char *errMessage)
-{
-    jobject ex = env->NewObject(gSimulatorClassRefs.classNoSupportException,
-                                gSimulatorClassRefs.classNoSupportExceptionCtor, errCode,
-                                env->NewStringUTF(errMessage));
-    if (!ex)
-    {
-        return;
-    }
-    env->Throw((jthrowable)ex);
-}
-
-void throwOperationInProgressException(JNIEnv *env, SimulatorResult errCode, const char *errMessage)
-{
-    jobject ex = env->NewObject(gSimulatorClassRefs.classOperationInProgressException,
-                                gSimulatorClassRefs.classOperationInProgressExceptionCtor, errCode,
-                                env->NewStringUTF(errMessage));
-    if (!ex)
-    {
-        return;
-    }
-    env->Throw((jthrowable)ex);
-}
diff --git a/service/simulator/java/jni/simulator_jni_utils.h b/service/simulator/java/jni/simulator_jni_utils.h
deleted file mode 100644 (file)
index 4815a04..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-/**
- * @file   simulator_jni_util.h
- *
- * @brief  This file contains the utility functions for conversions from java to CPP
- * and viceversa
- */
-
-#ifndef __SIMULATOR_JNI_UTILS_H_
-#define __SIMULATOR_JNI_UTILS_H_
-
-#include <jni.h>
-#include "simulator_error_codes.h"
-
-void throwSimulatorException(JNIEnv *env, SimulatorResult errCode, const char *errMessage);
-
-void throwInvalidArgsException(JNIEnv *env, SimulatorResult errCode, const char *errMessage);
-
-void throwNoSupportException(JNIEnv *env, SimulatorResult errCode, const char *errMessage);
-
-void throwOperationInProgressException(JNIEnv *env, SimulatorResult errCode,
-                                       const char *errMessage);
-
-#endif //__SIMULATOR_JNI_UTILS_H_
index 0fc5796..a5b135e 100644 (file)
  *
  ******************************************************************/
 
-#include "simulator_manager_jni.h"
-#include "simulator_resource_server_jni.h"
-#include "simulator_common_jni.h"
-#include "simulator_manager.h"
-#include "simulator_remote_resource_jni.h"
 #include "simulator_resource_model_jni.h"
 #include "simulator_device_info_jni.h"
 #include "simulator_platform_info_jni.h"
-#include "simulator_resource_jni_util.h"
-#include "simulator_jni_utils.h"
-
-SimulatorClassRefs gSimulatorClassRefs;
-std::mutex gEnvMutex;
-JavaVM *gvm;
-
-JNIEnv *getEnv()
-{
-    std::unique_lock<std::mutex> lock(gEnvMutex);
-    if (nullptr == gvm)
-        return NULL;
-
-    JNIEnv *env = NULL;
-    jint ret = gvm->GetEnv((void **)&env, JNI_VERSION_1_6);
-    switch (ret)
-    {
-        case JNI_OK:
-            return env;
-        case JNI_EDETACHED:
-            if (0 == gvm->AttachCurrentThread((void **)&env, NULL))
-                return env;
-    }
-
-    return NULL;
-}
+#include "simulator_exceptions_jni.h"
+#include "simulator_resource_utils_jni.h"
+#include "simulator_utils_jni.h"
+#include "jni_sharedobject_holder.h"
+#include "jni_listener_holder.h"
+#include "jni_string.h"
 
-void releaseEnv()
-{
-    std::unique_lock<std::mutex> lock(gEnvMutex);
-    if (nullptr == gvm)
-        return;
-    gvm->DetachCurrentThread();
-}
+#include "simulator_manager.h"
 
 class JNILogger : public ILogger
 {
@@ -71,21 +40,21 @@ class JNILogger : public ILogger
 
         void write(std::string time, ILogger::Level level, std::string message)
         {
-            JNIEnv *env = getEnv();
+            JNIEnv *env = GetEnv();
             if (nullptr == env)
                 return;
 
             jobject logger = env->NewLocalRef(m_logger);
             if (!logger)
             {
-                releaseEnv();
+                ReleaseEnv();
                 return;
             }
 
             jclass loggerCls = env->GetObjectClass(logger);
             if (!loggerCls)
             {
-                releaseEnv();
+                ReleaseEnv();
                 return;
             }
 
@@ -93,7 +62,7 @@ class JNILogger : public ILogger
                                                   "(Ljava/lang/String;ILjava/lang/String;)V");
             if (!writeMId)
             {
-                releaseEnv();
+                ReleaseEnv();
                 return;
             }
 
@@ -102,867 +71,343 @@ class JNILogger : public ILogger
             env->CallVoidMethod(logger, writeMId, timeStr, static_cast<jint>(level), msg);
             env->DeleteLocalRef(msg);
             env->DeleteLocalRef(timeStr);
-            releaseEnv();
+            ReleaseEnv();
         }
 
     private:
         jweak m_logger;
 };
 
-
-jobject SimulatorRemoteResourceToJava(JNIEnv *env, jlong resource)
+static void onResourceFound(jobject listener, SimulatorRemoteResourceSP remoteResource)
 {
-    jmethodID constructor = env->GetMethodID(gSimulatorClassRefs.classSimulatorRemoteResource, "<init>",
-                            "(J)V");
-    if (NULL == constructor)
-    {
-        return NULL;
-    }
+    JNIEnv *env = GetEnv();
+    if (!env)
+        return;
 
-    jobject resourceObj = (jobject) env->NewObject(gSimulatorClassRefs.classSimulatorRemoteResource,
-                          constructor, resource);
-    if (NULL == resourceObj)
-    {
-        return NULL;
-    }
+    jclass listenerCls = env->GetObjectClass(listener);
+    jmethodID callbackMethod = env->GetMethodID(listenerCls, "onResourceFound",
+                               "(Lorg/oic/simulator/client/SimulatorRemoteResource;)V");
+
+    jobject resource = CreateSimulatorRemoteResource(env, remoteResource);
+    if (!resource)
+        return;
 
-    return resourceObj;
+    env->CallVoidMethod(listener, callbackMethod, resource);
+    ReleaseEnv();
 }
 
-class JNIFoundResourceListener
+static void onDeviceInfoReceived(jobject listener, const std::string &hostUri,
+                                 DeviceInfo &deviceInfo)
 {
-    public:
-        void setJavaFoundResourceListener(JNIEnv *env, jobject listener)
-        {
-            m_listener = env->NewWeakGlobalRef(listener);
-        }
-
-        void onFoundResource(std::shared_ptr<SimulatorRemoteResource> resource)
-        {
-            JNIEnv *env = getEnv();
-            if (nullptr == env)
-                return;
-
-            jobject foundResourceListener = env->NewLocalRef(m_listener);
-            if (!foundResourceListener)
-            {
-                releaseEnv();
-                return;
-            }
-
-            jclass foundResourceCls = env->GetObjectClass(foundResourceListener);
-            if (!foundResourceCls)
-            {
-                releaseEnv();
-                return;
-            }
-
-            jmethodID foundResourceMId = env->GetMethodID(foundResourceCls, "onResourceCallback",
-                                         "(Lorg/oic/simulator/clientcontroller/SimulatorRemoteResource;)V");
-            if (!foundResourceMId)
-            {
-                releaseEnv();
-                return;
-            }
-
-            JniSimulatorRemoteResource *jniSimulatorResource = new JniSimulatorRemoteResource(resource);
-            if (!jniSimulatorResource)
-            {
-                releaseEnv();
-                return;
-            }
-
-            jobject simulatorResource = SimulatorRemoteResourceToJava(env,
-                                        reinterpret_cast<jlong>(jniSimulatorResource));
-
-            jfieldID fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorRemoteResource, "mUri",
-                                               "Ljava/lang/String;");
-            jstring jUri = env->NewStringUTF(resource->getURI().c_str());
-            env->SetObjectField(simulatorResource, fieldID, jUri);
-
-            fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorRemoteResource, "mConnType", "I");
-            jint jConnType = resource->getConnectivityType();
-            env->SetIntField(simulatorResource, fieldID, jConnType);
-
-            fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorRemoteResource, "mHost",
-                                      "Ljava/lang/String;");
-            jstring jHost = env->NewStringUTF(resource->getHost().c_str());
-            env->SetObjectField(simulatorResource, fieldID, jHost);
-
-            fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorRemoteResource, "mId",
-                                      "Ljava/lang/String;");
-            jstring jUid = env->NewStringUTF(resource->getID().c_str());
-            env->SetObjectField(simulatorResource, fieldID, jUid);
-
-            fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorRemoteResource, "mResTypes",
-                                      "Ljava/util/LinkedList;");
-            std::vector<std::string> resourceTypes = resource->getResourceTypes();
-            jobject jResTypes = convertStringVectorToJavaList(env, resourceTypes);
-            env->SetObjectField(simulatorResource, fieldID, jResTypes);
-
-            fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorRemoteResource, "mResInterfaces",
-                                      "Ljava/util/LinkedList;");
-            std::vector<std::string> interfaceTypes = resource->getResourceInterfaces();
-            jobject jResInterfaces = convertStringVectorToJavaList(env, interfaceTypes);
-            env->SetObjectField(simulatorResource, fieldID, jResInterfaces);
-
-            fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorRemoteResource, "mIsObservable", "Z");
-            env->SetBooleanField(simulatorResource, fieldID, resource->isObservable());
-
-            env->CallVoidMethod(foundResourceListener, foundResourceMId, simulatorResource);
-            if ((env)->ExceptionCheck())
-            {
-                delete jniSimulatorResource;
-                releaseEnv();
-                return;
-            }
-
-            releaseEnv();
-        }
-
-    private:
-        jweak m_listener;
+    JNIEnv *env = GetEnv();
+    if (!env)
+        return;
 
-};
+    jclass listenerCls = env->GetObjectClass(listener);
+    jmethodID listenerMethodId = env->GetMethodID(listenerCls, "onDeviceFound",
+                                 "(Ljava/lang/String;Lorg/oic/simulator/DeviceInfo;)V");
 
-void onResourceModelChange(jweak jlistenerRef, const std::string &uri,
-                           const SimulatorResourceModel &resModel)
-{
-    JNIEnv *env = getEnv();
-    if (nullptr == env)
-        return;
 
-    jobject modelChangeListener = env->NewLocalRef(jlistenerRef);
-    if (!modelChangeListener)
+    jstring jHostUri = env->NewStringUTF(hostUri.c_str());
+    jobject jDeviceInfo = JniDeviceInfo(env).toJava(deviceInfo);
+    if (!jDeviceInfo)
     {
-        releaseEnv();
+        ReleaseEnv();
         return;
     }
 
-    jclass modelChangeCls = env->GetObjectClass(modelChangeListener);
-    if (!modelChangeCls)
+    env->CallVoidMethod(listener, listenerMethodId, jHostUri, jDeviceInfo);
+    if (env->ExceptionCheck())
     {
-        releaseEnv();
+        ReleaseEnv();
         return;
     }
 
-    jmethodID foundModelChangeMId = env->GetMethodID(modelChangeCls, "onResourceModelChanged",
-                                    "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;)V");
-    if (!foundModelChangeMId)
-    {
-        releaseEnv();
+    ReleaseEnv();
+}
+
+static void onPlatformInfoReceived(jobject listener, const std::string &hostUri,
+                                   PlatformInfo &platformInfo)
+{
+    JNIEnv *env = GetEnv();
+    if (!env)
         return;
-    }
 
-    JSimulatorResourceModel *jniModel = new JSimulatorResourceModel(resModel);
-    if (!jniModel)
+    jclass listenerCls = env->GetObjectClass(listener);
+    jmethodID listenerMethodId = env->GetMethodID(listenerCls, "onPlatformFound",
+                                 "(Ljava/lang/String;Lorg/oic/simulator/PlatformInfo;)V");
+
+    jstring jHostUri = env->NewStringUTF(hostUri.c_str());
+    jobject jPlatformInfo = JniPlatformInfo(env).toJava(platformInfo);
+    if (!jPlatformInfo)
     {
-        releaseEnv();
+        ReleaseEnv();
         return;
     }
 
-    jobject jModel = JSimulatorResourceModel::toJava(env, reinterpret_cast<jlong>(jniModel));
-    jstring jUri = env->NewStringUTF(uri.c_str());
-    env->CallVoidMethod(modelChangeListener, foundModelChangeMId, jUri, jModel);
-    if ((env)->ExceptionCheck())
+    env->CallVoidMethod(listener, listenerMethodId, jHostUri, jPlatformInfo);
+    if (env->ExceptionCheck())
     {
-        delete jniModel;
-        releaseEnv();
+        ReleaseEnv();
         return;
     }
 
-    env->DeleteLocalRef(jUri);
-
-    releaseEnv();
+    ReleaseEnv();
 }
 
+#ifdef __cplusplus
+extern "C" {
+#endif
 
 JNIEXPORT jobject JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_createResource
-(JNIEnv *env, jclass object, jstring configPath, jobject listener)
+Java_org_oic_simulator_SimulatorManager_nativeCreateResource
+(JNIEnv *env, jobject /*object*/, jstring jConfigPath)
 {
-    if (!configPath)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM,
-                                  "Configuration file path is empty!");
-        return nullptr;
-    }
-
-    if (!listener)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK,
-                                  "Resource model change callback not set!");
-        return nullptr;
-    }
+    VALIDATE_INPUT_RET(env, !jConfigPath, "Path is null!", nullptr)
 
-    jweak jlistenerRef = env->NewWeakGlobalRef(listener);
-    SimulatorResourceServer::ResourceModelChangedCB callback =  [jlistenerRef](const std::string & uri,
-            const SimulatorResourceModel & resModel)
-    {
-        onResourceModelChange(jlistenerRef, uri, resModel);
-    };
-
-    const char *configPathCStr = env->GetStringUTFChars(configPath, NULL);
-    SimulatorResourceServerSP resource = NULL;
     try
     {
-        resource = SimulatorManager::getInstance()->createResource(
-                       configPathCStr, callback);
-        if (nullptr == resource)
-        {
-            if (configPathCStr)
-                env->ReleaseStringUTFChars(configPath, configPathCStr);
-            return NULL;
-        }
+        JniString jniPath(env, jConfigPath);
+        SimulatorResourceSP resource = SimulatorManager::getInstance()->createResource(
+                                           jniPath.get());
+        return CreateSimulatorResource(env, resource);
     }
     catch (InvalidArgsException &e)
     {
-        throwInvalidArgsException(env, e.code(), e.what());
-        return nullptr;
+        ThrowInvalidArgsException(env, e.code(), e.what());
     }
     catch (SimulatorException &e)
     {
-        throwSimulatorException(env, e.code(), e.what());
-        return nullptr;
+        ThrowSimulatorException(env, e.code(), e.what());
     }
-    catch (...)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
-        return nullptr;
-    }
-
-    JniSimulatorResource *jniSimResource = new JniSimulatorResource(resource);
-    jobject jSimulatorResource = JniSimulatorResource::toJava(env,
-                                 reinterpret_cast<jlong>(jniSimResource));
-
-    jniSimResource->setResourceInfo(env, jSimulatorResource);
 
-    if (configPathCStr)
-        env->ReleaseStringUTFChars(configPath, configPathCStr);
-    return jSimulatorResource;
+    return nullptr;
 }
 
-JNIEXPORT jobjectArray JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_createResources
-(JNIEnv *env, jclass object, jstring configPath, jint count, jobject listener)
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_SimulatorManager_nativeCreateResources
+(JNIEnv *env, jobject /*object*/, jstring jConfigPath, jint jCount)
 {
-    if (!configPath)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM,
-                                  "Configuration file path is empty!");
-        return nullptr;
-    }
-
-    if (!listener)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK,
-                                  "Resource model change callback not set!");
-        return nullptr;
-    }
-
-    jweak jlistenerRef = env->NewWeakGlobalRef(listener);
-    SimulatorResourceServer::ResourceModelChangedCB callback =  [jlistenerRef](const std::string & uri,
-            const SimulatorResourceModel & resModel)
-    {
-        onResourceModelChange(jlistenerRef, uri, resModel);
-    };
+    VALIDATE_INPUT_RET(env, !jConfigPath, "Path is null!", nullptr)
+    VALIDATE_INPUT_RET(env, !jConfigPath || jCount < 0, "Invalid count value!", nullptr)
 
-    const char *configPathCStr = env->GetStringUTFChars(configPath, NULL);
-    std::vector<SimulatorResourceServerSP> resources;
     try
     {
-        resources = SimulatorManager::getInstance()->createResource(configPathCStr, count, callback);
+        JniString jniPath(env, jConfigPath);
+        std::vector<SimulatorResourceSP> resources =
+            SimulatorManager::getInstance()->createResource(jniPath.get(), jCount);
+        return CreateSimulatorResourceVector(env, resources);
     }
     catch (InvalidArgsException &e)
     {
-        throwInvalidArgsException(env, e.code(), e.what());
-        return nullptr;
+        ThrowInvalidArgsException(env, e.code(), e.what());
     }
     catch (SimulatorException &e)
     {
-        throwSimulatorException(env, e.code(), e.what());
-        return nullptr;
-    }
-    catch (...)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
-        return nullptr;
-    }
-
-    // Construct the object array and send it java layer
-    jobjectArray resourceArray = env->NewObjectArray(resources.size(),
-                                 gSimulatorClassRefs.classSimulatorResource, NULL);
-    if (resourceArray)
-    {
-        for (size_t i = 0; i < resources.size(); i++)
-        {
-            JniSimulatorResource *jniSimResource = new JniSimulatorResource(resources[i]);
-            jobject jSimulatorResource = JniSimulatorResource::toJava(env,
-                                         reinterpret_cast<jlong>(jniSimResource));
-            jniSimResource->setResourceInfo(env, jSimulatorResource);
-            env->SetObjectArrayElement(resourceArray, i, jSimulatorResource);
-        }
+        ThrowSimulatorException(env, e.code(), e.what());
     }
 
-    if (configPathCStr)
-        env->ReleaseStringUTFChars(configPath, configPathCStr);
-    return resourceArray;
+    return nullptr;
 }
 
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_deleteResource
-(JNIEnv *env, jclass object, jobject jResource)
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_SimulatorManager_nativeCreateSingleResource
+(JNIEnv *env, jobject /*object*/, jstring jName, jstring jUri, jstring jResourceType)
 {
-    if (!jResource)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM,
-                                  "No resource has been passed!");
-        return;
-    }
-
-    SimulatorResourceServerSP resource =
-        JniSimulatorResource::getJniSimulatorResourceSP(env, jResource);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT,
-                                "Simulator resource not found!");
-        return;
-    }
+    VALIDATE_INPUT_RET(env, !jName, "Name is null!", nullptr)
+    VALIDATE_INPUT_RET(env, !jUri, "URI is null!", nullptr)
+    VALIDATE_INPUT_RET(env, !jResourceType, "Resource type is null!", nullptr)
 
     try
     {
-        SimulatorManager::getInstance()->deleteResource(resource);
+        JniString jniName(env, jName);
+        JniString jniUri(env, jUri);
+        JniString jniResourceType(env, jResourceType);
+
+        SimulatorSingleResourceSP resource = SimulatorManager::getInstance()->createSingleResource(
+                jniName.get(), jniUri.get(), jniResourceType.get());
+        return CreateSimulatorResource(env, std::dynamic_pointer_cast<SimulatorResource>(resource));
     }
     catch (InvalidArgsException &e)
     {
-        throwInvalidArgsException(env, e.code(), e.what());
+        ThrowInvalidArgsException(env, e.code(), e.what());
     }
-    catch (...)
+    catch (SimulatorException &e)
     {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+        ThrowSimulatorException(env, e.code(), e.what());
     }
+
+    return nullptr;
 }
 
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_deleteResources
-(JNIEnv *env, jclass object, jstring resourceType)
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_SimulatorManager_nativeCreateCollectionResource
+(JNIEnv *env, jobject /*object*/, jstring jName, jstring jUri, jstring jResourceType)
 {
-    std::string type;
-    const char *typeCStr = NULL;
-    if (resourceType)
-    {
-        typeCStr = env->GetStringUTFChars(resourceType, NULL);
-        type = typeCStr;
-    }
+    VALIDATE_INPUT_RET(env, !jName, "Name is null!", nullptr)
+    VALIDATE_INPUT_RET(env, !jUri, "URI is null!", nullptr)
+    VALIDATE_INPUT_RET(env, !jResourceType, "Resource type is null!", nullptr)
 
     try
     {
-        SimulatorManager::getInstance()->deleteResource(type);
+        JniString jniName(env, jName);
+        JniString jniUri(env, jUri);
+        JniString jniResourceType(env, jResourceType);
+
+        SimulatorCollectionResourceSP resource = SimulatorManager::getInstance()->createCollectionResource(
+                    jniName.get(), jniUri.get(), jniResourceType.get());
+        return CreateSimulatorResource(env, std::dynamic_pointer_cast<SimulatorResource>(resource));
     }
-    catch (...)
+    catch (InvalidArgsException &e)
     {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
-        return;
+        ThrowInvalidArgsException(env, e.code(), e.what());
+    }
+    catch (SimulatorException &e)
+    {
+        ThrowSimulatorException(env, e.code(), e.what());
     }
 
-    if (typeCStr)
-        env->ReleaseStringUTFChars(resourceType, typeCStr);
+    return nullptr;
 }
 
 JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_findResource
-(JNIEnv *env, jobject object, jstring jResourceType, jobject jListener)
+Java_org_oic_simulator_SimulatorManager_nativeSearchResource
+(JNIEnv *env, jobject /*object*/, jstring jResourceType, jobject jListener)
 {
-    if (!jListener)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-        return;
-    }
+    VALIDATE_CALLBACK(env, jListener)
 
-    const char *typeCStr = NULL;
-    std::string resourceType;
-    if (jResourceType)
+    ResourceFindCallback callback =  std::bind([](
+                                         std::shared_ptr<SimulatorRemoteResource> resource,
+                                         const std::shared_ptr<JniListenerHolder> &listenerRef)
     {
-        typeCStr = env->GetStringUTFChars(jResourceType, NULL);
-        resourceType = typeCStr;
-    }
-
-    JNIFoundResourceListener *resourceListener = new JNIFoundResourceListener();
-    resourceListener->setJavaFoundResourceListener(env, jListener);
+        onResourceFound(listenerRef->get(), resource);
+    }, std::placeholders::_1, JniListenerHolder::create(env, jListener));
 
     try
     {
         if (!jResourceType)
         {
-            SimulatorManager::getInstance()->findResource(
-                std::bind(&JNIFoundResourceListener::onFoundResource,
-                          resourceListener, std::placeholders::_1));
+            SimulatorManager::getInstance()->findResource(callback);
         }
         else
         {
-            SimulatorManager::getInstance()->findResource(resourceType,
-                    std::bind(&JNIFoundResourceListener::onFoundResource,
-                              resourceListener, std::placeholders::_1));
+            JniString type(env, jResourceType);
+            SimulatorManager::getInstance()->findResource(type.get(), callback);
         }
 
     }
     catch (InvalidArgsException &e)
     {
-        throwInvalidArgsException(env, e.code(), e.what());
-        return;
+        ThrowInvalidArgsException(env, e.code(), e.what());
     }
     catch (SimulatorException &e)
     {
-        throwSimulatorException(env, e.code(), e.what());
-        return;
-    }
-    catch (...)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
-        return;
+        ThrowSimulatorException(env, e.code(), e.what());
     }
-
-    if (typeCStr)
-        env->ReleaseStringUTFChars(jResourceType, typeCStr);
-}
-
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_setLogger
-(JNIEnv *env, jclass object, jobject logger)
-{
-    static std::shared_ptr<JNILogger> target(new JNILogger());
-    target->setJavaLogger(env, logger);
-    SimulatorManager::getInstance()->setLogger(target);
 }
 
 JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_setDeviceInfo
-(JNIEnv *env, jobject interfaceObject, jstring deviceInfo)
+Java_org_oic_simulator_SimulatorManager_nativeSetDeviceInfo
+(JNIEnv *env, jobject /*object*/, jstring jDeviceName)
 {
-    if (!deviceInfo)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid device info!");
-        return;
-    }
-
-    const char *deviceName = env->GetStringUTFChars(deviceInfo, NULL);
+    VALIDATE_INPUT(env, !jDeviceName, "Device name is null!")
 
     try
     {
-        SimulatorManager::getInstance()->setDeviceInfo(deviceName);
+        JniString jniDeviceName(env, jDeviceName);
+        SimulatorManager::getInstance()->setDeviceInfo(jniDeviceName.get());
     }
     catch (InvalidArgsException &e)
     {
-        throwInvalidArgsException(env, e.code(), e.what());
+        ThrowInvalidArgsException(env, e.code(), e.what());
     }
     catch (SimulatorException &e)
     {
-        throwSimulatorException(env, e.code(), e.what());
-    }
-    catch (...)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
-        return;
+        ThrowSimulatorException(env, e.code(), e.what());
     }
-
-    env->ReleaseStringUTFChars(deviceInfo, deviceName);
 }
 
 JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_getDeviceInfo
-(JNIEnv *env, jobject interfaceObject, jobject jListener)
+Java_org_oic_simulator_SimulatorManager_nativeFindDevices
+(JNIEnv *env, jobject /*object*/, jstring jHostUri, jobject jListener)
 {
-    if (!jListener)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-        return;
-    }
+    VALIDATE_CALLBACK(env, jListener)
 
-    JniDeviceInfoListener *deviceInfoListener = new JniDeviceInfoListener(env, jListener);
-    DeviceInfoCallback callback = std::bind([deviceInfoListener](DeviceInfo & deviceInfo)
+    DeviceInfoCallback callback =  std::bind([](const std::string & host, DeviceInfo & deviceInfo,
+                                   const std::shared_ptr<JniListenerHolder> &listenerRef)
     {
-        deviceInfoListener->onDeviceInfoReceived(deviceInfo);
-        delete deviceInfoListener;
-    }, std::placeholders::_1);
+        onDeviceInfoReceived(listenerRef->get(), host, deviceInfo);
+    }, std::placeholders::_1, std::placeholders::_2, JniListenerHolder::create(env, jListener));
 
     try
     {
-        SimulatorManager::getInstance()->getDeviceInfo(callback);
+        JniString jniHostUri(env, jHostUri);
+        SimulatorManager::getInstance()->getDeviceInfo(jniHostUri.get(), callback);
     }
     catch (InvalidArgsException &e)
     {
-        throwInvalidArgsException(env, e.code(), e.what());
+        ThrowInvalidArgsException(env, e.code(), e.what());
     }
     catch (SimulatorException &e)
     {
-        throwSimulatorException(env, e.code(), e.what());
-    }
-    catch (...)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
-        return;
+        ThrowSimulatorException(env, e.code(), e.what());
     }
 }
 
 JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_setPlatformInfo
-(JNIEnv *env, jobject interfaceObject, jobject jPlatformInfo)
+Java_org_oic_simulator_SimulatorManager_nativeSetPlatformInfo
+(JNIEnv *env, jobject /*object*/, jobject jPlatformInfo)
 {
-    if (!jPlatformInfo)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid platform info!");
-        return;
-    }
+    VALIDATE_INPUT(env, !jPlatformInfo, "Platform info is null!")
 
-    JPlatformInfo jniPlatformInfo(env);
     try
     {
-        PlatformInfo platformInfo = jniPlatformInfo.toCPP(jPlatformInfo);
-        SimulatorManager::getInstance()->setPlatformInfo(platformInfo);
+        PlatformInfo info = JniPlatformInfo(env).toCpp(jPlatformInfo);
+        SimulatorManager::getInstance()->setPlatformInfo(info);
     }
     catch (SimulatorException &e)
     {
-        throwSimulatorException(env, e.code(), e.what());
-    }
-    catch (...)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
-        return;
+        ThrowSimulatorException(env, e.code(), e.what());
     }
 }
 
 JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_getPlatformInfo
-(JNIEnv *env, jobject interfaceObject, jobject jListener)
+Java_org_oic_simulator_SimulatorManager_nativeGetPlatformInformation
+(JNIEnv *env, jobject /*object*/, jstring jHostUri, jobject jListener)
 {
-    if (!jListener)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-        return;
-    }
+    VALIDATE_CALLBACK(env, jListener)
 
-    JniPlatformInfoListener *platformInfoListener = new JniPlatformInfoListener(env, jListener);
-    PlatformInfoCallback callback = std::bind([platformInfoListener](PlatformInfo & platformInfo)
+    PlatformInfoCallback callback =  std::bind([](const std::string & host,
+                                     PlatformInfo & platformInfo,
+                                     const std::shared_ptr<JniListenerHolder> &listenerRef)
     {
-        platformInfoListener->onPlatformInfoReceived(platformInfo);
-        delete platformInfoListener;
-    }, std::placeholders::_1);
+        onPlatformInfoReceived(listenerRef->get(), host, platformInfo);
+    }, std::placeholders::_1, std::placeholders::_2, JniListenerHolder::create(env, jListener));
 
     try
     {
-        SimulatorManager::getInstance()->getPlatformInfo(callback);
+        JniString jniHostUri(env, jHostUri);
+        SimulatorManager::getInstance()->getPlatformInfo(jniHostUri.get(), callback);
     }
     catch (InvalidArgsException &e)
     {
-        throwInvalidArgsException(env, e.code(), e.what());
+        ThrowInvalidArgsException(env, e.code(), e.what());
     }
     catch (SimulatorException &e)
     {
-        throwSimulatorException(env, e.code(), e.what());
-    }
-    catch (...)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
-        return;
+        ThrowSimulatorException(env, e.code(), e.what());
     }
 }
 
-static bool getClassRef(JNIEnv *env, const char *className, jclass &classRef)
-{
-    jclass localClassRef = nullptr;
-    localClassRef = env->FindClass(className);
-    if (!localClassRef)
-        return false;
-
-    classRef = (jclass)env->NewGlobalRef(localClassRef);
-    env->DeleteLocalRef(localClassRef);
-    return true;
-}
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
-{
-    if (!vm)
-    {
-        return JNI_ERR;
-    }
-
-    JNIEnv *env = NULL;
-    if (JNI_OK != vm->GetEnv((void **) &env, JNI_VERSION_1_6))
-    {
-        return JNI_ERR;
-    }
-
-    // Get the class references
-    if (false == getClassRef(env, "java/lang/Object", gSimulatorClassRefs.classObject))
-    {
-        return JNI_ERR;
-    }
-
-    if (false == getClassRef(env, "java/lang/Integer", gSimulatorClassRefs.classInteger))
-    {
-        return JNI_ERR;
-    }
-
-    if (false == getClassRef(env, "java/lang/Double", gSimulatorClassRefs.classDouble))
-    {
-        return JNI_ERR;
-    }
-
-    if (false == getClassRef(env, "java/lang/Boolean", gSimulatorClassRefs.classBoolean))
-    {
-        return JNI_ERR;
-    }
-
-    if (false == getClassRef(env, "java/lang/String", gSimulatorClassRefs.classString))
-    {
-        return JNI_ERR;
-    }
-
-    if (false == getClassRef(env, "java/util/HashMap", gSimulatorClassRefs.classHashMap))
-    {
-        return JNI_ERR;
-    }
-
-    if (false == getClassRef(env, "java/util/Vector", gSimulatorClassRefs.classVector))
-    {
-        return JNI_ERR;
-    }
-
-    if (false == getClassRef(env, "java/util/Map", gSimulatorClassRefs.classMap))
-    {
-        return JNI_ERR;
-    }
-
-    if (false == getClassRef(env, "java/util/Map$Entry", gSimulatorClassRefs.classMapEntry))
-    {
-        return JNI_ERR;
-    }
-
-    if (false == getClassRef(env, "java/util/Set", gSimulatorClassRefs.classSet))
-    {
-        return JNI_ERR;
-    }
-
-    if (false == getClassRef(env, "java/util/Iterator", gSimulatorClassRefs.classIterator))
-    {
-        return JNI_ERR;
-    }
-
-    if (false == getClassRef(env, "java/util/LinkedList", gSimulatorClassRefs.classLinkedList))
-    {
-        return JNI_ERR;
-    }
-
-    if (false == getClassRef(env, "org/oic/simulator/serviceprovider/SimulatorResourceServer",
-                             gSimulatorClassRefs.classSimulatorResource))
-    {
-        return JNI_ERR;
-    }
-
-    if (false == getClassRef(env, "org/oic/simulator/SimulatorResourceModel",
-                             gSimulatorClassRefs.classSimulatorResourceModel))
-    {
-        return JNI_ERR;
-    }
-
-    if (false == getClassRef(env, "org/oic/simulator/ResourceAttribute",
-                             gSimulatorClassRefs.classResourceAttribute))
-    {
-        return JNI_ERR;
-    }
-
-    if (false == getClassRef(env, "org/oic/simulator/clientcontroller/SimulatorRemoteResource",
-                             gSimulatorClassRefs.classSimulatorRemoteResource))
-    {
-        return JNI_ERR;
-    }
-
-    if (false == getClassRef(env, "org/oic/simulator/serviceprovider/ObserverInfo",
-                             gSimulatorClassRefs.classObserverInfo))
-    {
-        return JNI_ERR;
-    }
-
-    if (false == getClassRef(env, "org/oic/simulator/DeviceInfo",
-                             gSimulatorClassRefs.classDeviceInfo))
-    {
-        return JNI_ERR;
-    }
-
-    if (false == getClassRef(env, "org/oic/simulator/PlatformInfo",
-                             gSimulatorClassRefs.classPlatformInfo))
-    {
-        return JNI_ERR;
-    }
-
-    if (false == getClassRef(env, "org/oic/simulator/SimulatorException",
-                             gSimulatorClassRefs.classSimulatorException))
-    {
-        return JNI_ERR;
-    }
-
-    if (false == getClassRef(env, "org/oic/simulator/InvalidArgsException",
-                             gSimulatorClassRefs.classInvalidArgsException))
-    {
-        return JNI_ERR;
-    }
-
-    if (false == getClassRef(env, "org/oic/simulator/NoSupportException",
-                             gSimulatorClassRefs.classNoSupportException))
-    {
-        return JNI_ERR;
-    }
-
-    if (false == getClassRef(env, "org/oic/simulator/OperationInProgressException",
-                             gSimulatorClassRefs.classOperationInProgressException))
-    {
-        return JNI_ERR;
-    }
-
-    // Get the reference to methods
-    gSimulatorClassRefs.classIntegerCtor = env->GetMethodID(gSimulatorClassRefs.classInteger, "<init>",
-                                           "(I)V");
-    if (!gSimulatorClassRefs.classIntegerCtor)
-        return JNI_ERR;
-
-    gSimulatorClassRefs.classDoubleCtor = env->GetMethodID(gSimulatorClassRefs.classDouble, "<init>",
-                                          "(D)V");
-    if (!gSimulatorClassRefs.classDoubleCtor)
-        return JNI_ERR;
-
-    gSimulatorClassRefs.classBooleanCtor= env->GetMethodID(gSimulatorClassRefs.classBoolean, "<init>",
-                                          "(Z)V");
-    if (!gSimulatorClassRefs.classBooleanCtor)
-        return JNI_ERR;
-
-    gSimulatorClassRefs.classHashMapCtor = env->GetMethodID(gSimulatorClassRefs.classHashMap, "<init>",
-                                           "()V");
-    if (!gSimulatorClassRefs.classHashMapCtor)
-        return JNI_ERR;
-
-    gSimulatorClassRefs.classHashMapPut = env->GetMethodID(gSimulatorClassRefs.classHashMap, "put",
-                                          "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
-    if (!gSimulatorClassRefs.classHashMapPut)
-        return JNI_ERR;
-
-    gSimulatorClassRefs.classVectorCtor = env->GetMethodID(gSimulatorClassRefs.classVector, "<init>",
-                                          "()V");
-    if (!gSimulatorClassRefs.classVectorCtor)
-        return JNI_ERR;
-
-    gSimulatorClassRefs.classVectorAddElement = env->GetMethodID(gSimulatorClassRefs.classVector,
-            "addElement",
-            "(Ljava/lang/Object;)V");
-    if (!gSimulatorClassRefs.classVectorAddElement)
-        return JNI_ERR;
-
-    gSimulatorClassRefs.classMapEntrySet = env->GetMethodID(
-            gSimulatorClassRefs.classMap, "entrySet", "()Ljava/util/Set;");
-    if (!gSimulatorClassRefs.classMapEntrySet)
-        return JNI_ERR;
-
-    gSimulatorClassRefs.classMapGetKey = env->GetMethodID(
-            gSimulatorClassRefs.classMapEntry, "getKey", "()Ljava/lang/Object;");
-    if (!gSimulatorClassRefs.classMapGetKey)
-        return JNI_ERR;
-
-    gSimulatorClassRefs.classMapGetValue = env->GetMethodID(
-            gSimulatorClassRefs.classMapEntry, "getValue", "()Ljava/lang/Object;");
-    if (!gSimulatorClassRefs.classMapGetValue)
-        return JNI_ERR;
-
-    gSimulatorClassRefs.classIteratorId = env->GetMethodID(
-            gSimulatorClassRefs.classSet, "iterator", "()Ljava/util/Iterator;");
-    if (!gSimulatorClassRefs.classIteratorId)
-        return JNI_ERR;
-
-    gSimulatorClassRefs.classHasNextId = env->GetMethodID(
-            gSimulatorClassRefs.classIterator, "hasNext", "()Z");
-    if (!gSimulatorClassRefs.classHasNextId)
-        return JNI_ERR;
-
-    gSimulatorClassRefs.classNextId = env->GetMethodID(
-                                          gSimulatorClassRefs.classIterator, "next", "()Ljava/lang/Object;");
-    if (!gSimulatorClassRefs.classNextId)
-        return JNI_ERR;
-
-    gSimulatorClassRefs.classLinkedListCtor = env->GetMethodID(gSimulatorClassRefs.classLinkedList,
-            "<init>", "()V");
-    if (!gSimulatorClassRefs.classLinkedListCtor)
-        return JNI_ERR;
-
-    gSimulatorClassRefs.classLinkedListAddObject = env->GetMethodID(gSimulatorClassRefs.classLinkedList,
-            "add", "(Ljava/lang/Object;)Z");
-    if (!gSimulatorClassRefs.classLinkedListAddObject)
-        return JNI_ERR;
-
-    gSimulatorClassRefs.classSimulatorResourceCtor = env->GetMethodID(
-                gSimulatorClassRefs.classSimulatorResource, "<init>", "(J)V");
-    if (!gSimulatorClassRefs.classSimulatorResourceCtor)
-        return JNI_ERR;
-
-    gSimulatorClassRefs.classSimulatorResourceModelCtor = env->GetMethodID(
-                gSimulatorClassRefs.classSimulatorResourceModel, "<init>", "(J)V");
-    if (!gSimulatorClassRefs.classSimulatorResourceModelCtor)
-        return JNI_ERR;
-
-    gSimulatorClassRefs.classResourceAttributeCtor = env->GetMethodID(
-                gSimulatorClassRefs.classResourceAttribute, "<init>", "()V");
-    if (!gSimulatorClassRefs.classResourceAttributeCtor)
-        return JNI_ERR;
-
-    gSimulatorClassRefs.classResourceAttributeSetRange = env->GetMethodID(
-                gSimulatorClassRefs.classResourceAttribute, "setRange", "(II)V");
-    if (!gSimulatorClassRefs.classResourceAttributeSetRange)
-        return JNI_ERR;
-
-    gSimulatorClassRefs.classSimulatorResourceModelId = env->GetMethodID(
-                gSimulatorClassRefs.classSimulatorResourceModel, "<init>", "(J)V");
-    if (!gSimulatorClassRefs.classSimulatorResourceModelId)
-        return JNI_ERR;
-
-    gSimulatorClassRefs.classObserverInfoCtor = env->GetMethodID(
-                gSimulatorClassRefs.classObserverInfo, "<init>",
-                "(ILjava/lang/String;I)V");
-    if (!gSimulatorClassRefs.classObserverInfoCtor)
-        return JNI_ERR;
-
-    gSimulatorClassRefs.classSimulatorExceptionCtor = env->GetMethodID(
-                gSimulatorClassRefs.classSimulatorException, "<init>",
-                "(ILjava/lang/String;)V");
-    if (!gSimulatorClassRefs.classSimulatorExceptionCtor)
-        return JNI_ERR;
-
-    gSimulatorClassRefs.classInvalidArgsExceptionCtor = env->GetMethodID(
-                gSimulatorClassRefs.classInvalidArgsException, "<init>",
-                "(ILjava/lang/String;)V");
-    if (!gSimulatorClassRefs.classInvalidArgsExceptionCtor)
-        return JNI_ERR;
-
-    gSimulatorClassRefs.classNoSupportExceptionCtor = env->GetMethodID(
-                gSimulatorClassRefs.classNoSupportException, "<init>",
-                "(ILjava/lang/String;)V");
-    if (!gSimulatorClassRefs.classNoSupportExceptionCtor)
-        return JNI_ERR;
-
-    gSimulatorClassRefs.classOperationInProgressExceptionCtor = env->GetMethodID(
-                gSimulatorClassRefs.classOperationInProgressException, "<init>",
-                "(ILjava/lang/String;)V");
-    if (!gSimulatorClassRefs.classOperationInProgressExceptionCtor)
-        return JNI_ERR;
-
-    gvm = vm;
-    return JNI_VERSION_1_6;
-}
-
-JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorManager_nativeSetLogger
+(JNIEnv *env, jobject /*object*/, jobject jLogger)
 {
+    static std::shared_ptr<JNILogger> target(new JNILogger());
+    target->setJavaLogger(env, jLogger);
+    SimulatorManager::getInstance()->setLogger(target);
 }
 
 #ifdef __cplusplus
 }
-#endif
+#endif
\ No newline at end of file
diff --git a/service/simulator/java/jni/simulator_manager_jni.h b/service/simulator/java/jni/simulator_manager_jni.h
deleted file mode 100644 (file)
index 2a71031..0000000
+++ /dev/null
@@ -1,74 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-#ifndef SIMULATOR_MANAGER_JNI_H_
-#define SIMULATOR_MANAGER_JNI_H_
-
-#include <jni.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-JNIEXPORT jobject JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_createResource
-(JNIEnv *env, jclass object, jstring jConfigPath, jobject jListener);
-
-JNIEXPORT jobjectArray JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_createResources
-(JNIEnv *env, jclass object, jstring jConfigPath, jint count, jobject jListener);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_deleteResource
-(JNIEnv *env, jclass object, jobject jResource);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_deleteResources
-(JNIEnv *env, jclass object, jstring resourceType);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_findResource
-(JNIEnv *env, jobject interfaceObject, jstring jResourceType, jobject jListener);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_setDeviceInfo
-(JNIEnv *env, jobject interfaceObject, jstring deviceInfo);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_getDeviceInfo
-(JNIEnv *env, jobject interfaceObject, jobject jListener);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_setPlatformInfo
-(JNIEnv *env, jobject interfaceObject, jobject platformInfo);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_getPlatformInfo
-(JNIEnv *env, jobject interfaceObject, jobject jListener);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_setLogger
-(JNIEnv *env, jclass object, jobject logger);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif //SIMULATOR_MANAGER_JNI_H_
index f3be763..05b3383 100644 (file)
  ******************************************************************/
 
 #include "simulator_platform_info_jni.h"
-#include "simulator_common_jni.h"
+#include "simulator_utils_jni.h"
+#include "jni_string.h"
 
 extern SimulatorClassRefs gSimulatorClassRefs;
-jobject JPlatformInfo::toJava(PlatformInfo &platformInfo)
+
+jobject JniPlatformInfo::toJava(PlatformInfo &platformInfo)
 {
     if (!m_env)
         return nullptr;
 
-    jmethodID constr = m_env->GetMethodID(gSimulatorClassRefs.classPlatformInfo, "<init>", "(V)V");
-    if (constr)
-        return nullptr;
-
-    jobject jPlatformInfo = (jobject) m_env->NewObject(gSimulatorClassRefs.classPlatformInfo, constr);
-    if (jPlatformInfo)
-        return nullptr;
-
+    static jmethodID platformInfoCtor = m_env->GetMethodID(gSimulatorClassRefs.platformInfoCls,
+                                        "<init>", "()V");
+    jobject jPlatformInfo = (jobject) m_env->NewObject(gSimulatorClassRefs.platformInfoCls,
+                            platformInfoCtor);
     setFieldValue(jPlatformInfo, "mPlatformId", platformInfo.getPlatformID());
-    setFieldValue(jPlatformInfo, "m_manufacturerName", platformInfo.getManufacturerName());
-    setFieldValue(jPlatformInfo, "m_manufacturerUrl", platformInfo.getManufacturerUrl());
-    setFieldValue(jPlatformInfo, "m_modelNumber", platformInfo.getModelNumber());
-    setFieldValue(jPlatformInfo, "m_dateOfManufacture", platformInfo.getDateOfManfacture());
-    setFieldValue(jPlatformInfo, "m_platformVersion", platformInfo.getPlatformVersion());
-    setFieldValue(jPlatformInfo, "m_operationSystemVersion", platformInfo.getOSVersion());
-    setFieldValue(jPlatformInfo, "m_hardwareVersion", platformInfo.getHardwareVersion());
-    setFieldValue(jPlatformInfo, "m_firmwareVersion", platformInfo.getFirmwareVersion());
-    setFieldValue(jPlatformInfo, "m_supportUrl", platformInfo.getSupportUrl());
-    setFieldValue(jPlatformInfo, "m_systemTime", platformInfo.getSystemTime());
+    setFieldValue(jPlatformInfo, "mManufacturerName", platformInfo.getManufacturerName());
+    setFieldValue(jPlatformInfo, "mManufacturerUrl", platformInfo.getManufacturerUrl());
+    setFieldValue(jPlatformInfo, "mModelNumber", platformInfo.getModelNumber());
+    setFieldValue(jPlatformInfo, "mDateOfManufacture", platformInfo.getDateOfManfacture());
+    setFieldValue(jPlatformInfo, "mPlatformVersion", platformInfo.getPlatformVersion());
+    setFieldValue(jPlatformInfo, "mOperationSystemVersion", platformInfo.getOSVersion());
+    setFieldValue(jPlatformInfo, "mHardwareVersion", platformInfo.getHardwareVersion());
+    setFieldValue(jPlatformInfo, "mFirmwareVersion", platformInfo.getFirmwareVersion());
+    setFieldValue(jPlatformInfo, "mSupportUrl", platformInfo.getSupportUrl());
+    setFieldValue(jPlatformInfo, "mSystemTime", platformInfo.getSystemTime());
 
     return jPlatformInfo;
 }
 
-PlatformInfo JPlatformInfo::toCPP(jobject jPlatformInfo)
+PlatformInfo JniPlatformInfo::toCpp(jobject jPlatformInfo)
 {
     PlatformInfo platformInfo;
     if (!m_env || !jPlatformInfo)
         return platformInfo;
 
     platformInfo.setPlatformID(getFieldValue(jPlatformInfo, "mPlatformId"));
-    platformInfo.setManufacturerName(getFieldValue(jPlatformInfo, "m_manufacturerName"));
-    platformInfo.setManufacturerUrl(getFieldValue(jPlatformInfo, "m_manufacturerUrl"));
-    platformInfo.setModelNumber(getFieldValue(jPlatformInfo, "m_modelNumber"));
-    platformInfo.setDateOfManfacture(getFieldValue(jPlatformInfo, "m_dateOfManufacture"));
-    platformInfo.setPlatformVersion(getFieldValue(jPlatformInfo, "m_platformVersion"));
-    platformInfo.setOSVersion(getFieldValue(jPlatformInfo, "m_operationSystemVersion"));
-    platformInfo.setHardwareVersion(getFieldValue(jPlatformInfo, "m_hardwareVersion"));
-    platformInfo.setFirmwareVersion(getFieldValue(jPlatformInfo, "m_firmwareVersion"));
-    platformInfo.setSupportUrl(getFieldValue(jPlatformInfo, "m_supportUrl"));
-    platformInfo.setSystemTime(getFieldValue(jPlatformInfo, "m_systemTime"));
+    platformInfo.setManufacturerName(getFieldValue(jPlatformInfo, "mManufacturerName"));
+    platformInfo.setManufacturerUrl(getFieldValue(jPlatformInfo, "mManufacturerUrl"));
+    platformInfo.setModelNumber(getFieldValue(jPlatformInfo, "mModelNumber"));
+    platformInfo.setDateOfManfacture(getFieldValue(jPlatformInfo, "mDateOfManufacture"));
+    platformInfo.setPlatformVersion(getFieldValue(jPlatformInfo, "mPlatformVersion"));
+    platformInfo.setOSVersion(getFieldValue(jPlatformInfo, "mOperationSystemVersion"));
+    platformInfo.setHardwareVersion(getFieldValue(jPlatformInfo, "mHardwareVersion"));
+    platformInfo.setFirmwareVersion(getFieldValue(jPlatformInfo, "mFirmwareVersion"));
+    platformInfo.setSupportUrl(getFieldValue(jPlatformInfo, "mSupportUrl"));
+    platformInfo.setSystemTime(getFieldValue(jPlatformInfo, "mSystemTime"));
 
     return std::move(platformInfo);
 }
 
-void JPlatformInfo::setFieldValue(jobject jPlatformInfo, const std::string &fieldName,
-                                  const std::string &value)
+void JniPlatformInfo::setFieldValue(jobject jPlatformInfo, const std::string &fieldName,
+                                    const std::string &value)
 {
-    jfieldID fieldID = m_env->GetFieldID(gSimulatorClassRefs.classPlatformInfo, fieldName.c_str(),
+    jfieldID fieldID = m_env->GetFieldID(m_env->GetObjectClass(jPlatformInfo), fieldName.c_str(),
                                          "Ljava/lang/String;");
     jstring valueStr = m_env->NewStringUTF(value.c_str());
     m_env->SetObjectField(jPlatformInfo, fieldID, valueStr);
 }
 
-std::string JPlatformInfo::getFieldValue(jobject jPlatformInfo, const std::string &fieldName)
+std::string JniPlatformInfo::getFieldValue(jobject jPlatformInfo, const std::string &fieldName)
 {
-    jfieldID fieldID = m_env->GetFieldID(gSimulatorClassRefs.classPlatformInfo, fieldName.c_str(),
+    jfieldID fieldID = m_env->GetFieldID(m_env->GetObjectClass(jPlatformInfo), fieldName.c_str(),
                                          "Ljava/lang/String;");
     jstring jvalue = (jstring) m_env->GetObjectField(jPlatformInfo, fieldID);
-    const char *valueCStr = m_env->GetStringUTFChars(jvalue, NULL);
-    if (valueCStr)
-        return std::string(valueCStr);
-    return std::string();
+    JniString value(m_env, jvalue);
+    return value.get();
 }
-
-void JniPlatformInfoListener::onPlatformInfoReceived(PlatformInfo &platformInfo)
-{
-    // Get the environment
-    JNIEnv *env = getEnv();
-    if (!env)
-        return;
-
-    jobject listener = env->NewLocalRef(m_listener);
-    if (!listener)
-    {
-        releaseEnv();
-        return;
-    }
-
-    jclass listenerCls = env->GetObjectClass(listener);
-    if (!listenerCls)
-    {
-        releaseEnv();
-        return;
-    }
-
-    jmethodID listenerMId = env->GetMethodID(listenerCls, "onPlatformFound",
-                            "(Lorg/oic/simulator/PlatformInfo;)V");
-    if (!listenerMId)
-    {
-        releaseEnv();
-        return;
-    }
-
-    // Convert CPP to Java DeviceInfo object
-    jobject jPlatformInfo = JPlatformInfo(env).toJava(platformInfo);
-    if (!jPlatformInfo)
-    {
-        releaseEnv();
-        return;
-    }
-
-    // Invoke java listener with DeviceInfo
-    env->CallVoidMethod(listener, listenerMId, jPlatformInfo);
-    if (env->ExceptionCheck())
-    {
-        releaseEnv();
-        return;
-    }
-
-    releaseEnv();
-}
-
index e623b81..b8398fd 100644 (file)
 #include "simulator_platform_info.h"
 #include <jni.h>
 
-class JPlatformInfo
+class JniPlatformInfo
 {
     public:
-        JPlatformInfo(JNIEnv *env) : m_env(env) {}
-        JPlatformInfo(const JPlatformInfo &) = delete;
-        JPlatformInfo &operator=(const JPlatformInfo &) = delete;
-        JPlatformInfo(const JPlatformInfo &&) = delete;
-        JPlatformInfo &operator=(const JPlatformInfo && ) = delete;
+        JniPlatformInfo(JNIEnv *env) : m_env(env) {}
+        JniPlatformInfo(const JniPlatformInfo &) = delete;
+        JniPlatformInfo &operator=(const JniPlatformInfo &) = delete;
+        JniPlatformInfo(const JniPlatformInfo &&) = delete;
+        JniPlatformInfo &operator=(const JniPlatformInfo && ) = delete;
         jobject toJava(PlatformInfo &platformInfo);
-        PlatformInfo toCPP(jobject jPlatformInfo);
+        PlatformInfo toCpp(jobject jPlatformInfo);
 
     private:
         void setFieldValue(jobject jPlatformInfo, const std::string &fieldName,
@@ -43,18 +43,4 @@ class JPlatformInfo
         JNIEnv *m_env;
 };
 
-class JniPlatformInfoListener
-{
-    public:
-        JniPlatformInfoListener(JNIEnv *env, jobject listener)
-        {
-            m_listener = env->NewWeakGlobalRef(listener);
-        }
-
-        void onPlatformInfoReceived(PlatformInfo &platformInfo);
-
-    private:
-        jweak m_listener;
-};
-
 #endif
index 63215b6..f033f2c 100644 (file)
  *
  ******************************************************************/
 
-#include "simulator_remote_resource_jni.h"
-#include "simulator_common_jni.h"
-#include "simulator_error_codes.h"
-#include "simulator_resource_jni_util.h"
 #include "simulator_resource_model_jni.h"
-#include "simulator_client_types.h"
-#include "simulator_exceptions.h"
-#include "simulator_jni_utils.h"
-
-extern SimulatorClassRefs gSimulatorClassRefs;
-
-SimulatorRemoteResourceSP JniSimulatorRemoteResource::getResourceHandle
-(JNIEnv *env, jobject object)
+#include "simulator_resource_model_schema_jni.h"
+#include "simulator_exceptions_jni.h"
+#include "simulator_utils_jni.h"
+#include "jni_sharedobject_holder.h"
+#include "jni_listener_holder.h"
+#include "jni_queryparam.h"
+#include "jni_string.h"
+#include "jni_vector.h"
+#include "jni_map.h"
+
+#include "simulator_remote_resource.h"
+
+#define VALIDATE_OBJECT(ENV, OBJECT) if (!OBJECT){ThrowBadObjectException(ENV, "No corresponsing native object!"); return;}
+#define VALIDATE_OBJECT_RET(ENV, OBJECT, RET) if (!OBJECT){ThrowBadObjectException(ENV, "No corresponsing native object!"); return RET;}
+
+static SimulatorRemoteResourceSP simulatorRemoteResourceToCpp(
+    JNIEnv *env, jobject object)
 {
-    JniSimulatorRemoteResource *jniResource = GetHandle<JniSimulatorRemoteResource>(env, object);
-    if (env->ExceptionCheck() || !jniResource)
-    {
-        return nullptr;
-    }
-
-    return jniResource->m_resource;
+    JniSharedObjectHolder<SimulatorRemoteResource> *jniResource =
+        getHandle<JniSharedObjectHolder<SimulatorRemoteResource>>(env, object);
+    if (jniResource)
+        return jniResource->get();
+    return nullptr;
 }
 
-class JNIOnObserveListener
+static void onObserveCallback(jobject listener, const std::string &uid, SimulatorResult /*result*/,
+                              const SimulatorResourceModel &representation, const int seq)
 {
-    public:
-        void setJavaOnObserveListener(JNIEnv *env, jobject listener)
-        {
-            m_listener = env->NewWeakGlobalRef(listener);
-        }
+    JNIEnv *env = GetEnv();
+    if (!env)
+        return;
 
-        void onObserveCallback(const std::string &uId, const int errorCode,
-                               SimulatorResourceModelSP representation,
-                               const int seqNumber)
-        {
-            JNIEnv *env = getEnv();
-            if (nullptr == env)
-                return;
+    jclass listenerCls = env->GetObjectClass(listener);
+    jmethodID listenerMethodId = env->GetMethodID(listenerCls, "onObserveNotification",
+                                 "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;I)V");
 
-            jobject onObserveListener = env->NewLocalRef(m_listener);
-            if (!onObserveListener)
-            {
-                releaseEnv();
-                return;
-            }
+    jobject jResModel = SimulatorResourceModelToJava(env, representation);
+    jstring jUid = env->NewStringUTF(uid.c_str());
+    env->CallVoidMethod(listener, listenerMethodId, jUid, jResModel, seq);
+    ReleaseEnv();
+}
 
-            jclass onObserveCls = env->GetObjectClass(onObserveListener);
-            if (!onObserveCls)
-            {
-                releaseEnv();
-                return;
-            }
+static void onGetCallback(jobject listener, const std::string &uid, SimulatorResult result,
+                          const SimulatorResourceModel &representation)
+{
+    JNIEnv *env = GetEnv();
+    if (!env)
+        return;
 
-            if (OC_STACK_OK != errorCode && OC_STACK_RESOURCE_CREATED != errorCode
-                && OC_STACK_RESOURCE_DELETED != errorCode)
-            {
-                jmethodID midL = env->GetMethodID(onObserveCls, "onObserveFailed", "(Ljava/lang/Throwable;)V");
-                if (!midL)
-                {
-                    releaseEnv();
-                    return;
-                }
-                env->CallVoidMethod(onObserveListener, midL);
-            }
-            else
-            {
-                JSimulatorResourceModel *jniModel = new JSimulatorResourceModel(representation);
-                if (!jniModel)
-                {
-                    releaseEnv();
-                    return;
-                }
-
-                jobject jRepresentation = JSimulatorResourceModel::toJava(env,
-                        reinterpret_cast<jlong>(jniModel));
-                if (!jRepresentation)
-                {
-                    delete jniModel;
-                    releaseEnv();
-                    return;
-                }
-
-                jmethodID midL = env->GetMethodID(onObserveCls, "onObserveCompleted",
-                        "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;I)V");
-                if (!midL)
-                {
-                    delete jniModel;
-                    releaseEnv();
-                    return;
-                }
-
-                jstring jUid = env->NewStringUTF(uId.c_str());
-
-                env->CallVoidMethod(onObserveListener, midL, jUid, jRepresentation,
-                                    static_cast<jint>(seqNumber));
-                if (env->ExceptionCheck())
-                {
-                    delete jniModel;
-                    releaseEnv();
-                }
-            }
-        }
+    jclass listenerCls = env->GetObjectClass(listener);
+    jmethodID listenerMethodId = env->GetMethodID(listenerCls, "onGetResponse",
+                                 "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResult;Lorg/oic/simulator/SimulatorResourceModel;)V");
 
-    private:
-        jweak m_listener;
-};
+    jobject jResModel = SimulatorResourceModelToJava(env, representation);
+    jstring jUid = env->NewStringUTF(uid.c_str());
+    env->CallVoidMethod(listener, listenerMethodId, jUid,
+                        SimulatorResultToJava(env, result), jResModel);
 
-class JNIOnGetListener
+    ReleaseEnv();
+}
+
+static void onPutCallback(jobject listener, const std::string &uid, SimulatorResult result,
+                          const SimulatorResourceModel &representation)
 {
-    public:
-        void setJavaOnGetListener(JNIEnv *env, jobject listener)
-        {
-            m_listener = env->NewWeakGlobalRef(listener);
-        }
+    JNIEnv *env = GetEnv();
+    if (!env)
+        return;
 
-        void onGetCallback(const std::string &uId, int errorCode,
-                           SimulatorResourceModelSP representation)
-        {
-            JNIEnv *env = getEnv();
-            if (nullptr == env)
-                return;
+    jclass listenerCls = env->GetObjectClass(listener);
+    jmethodID listenerMethodId = env->GetMethodID(listenerCls, "onPutResponse",
+                                 "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResult;Lorg/oic/simulator/SimulatorResourceModel;)V");
 
-            jobject onGetListener = env->NewLocalRef(m_listener);
-            if (!onGetListener)
-            {
-                releaseEnv();
-                return;
-            }
+    jobject jResModel = SimulatorResourceModelToJava(env, representation);
+    jstring jUid = env->NewStringUTF(uid.c_str());
+    env->CallVoidMethod(listener, listenerMethodId, jUid,
+                        SimulatorResultToJava(env, result), jResModel);
 
-            jclass onGetCls = env->GetObjectClass(onGetListener);
-            if (!onGetCls)
-            {
-                releaseEnv();
-                return;
-            }
+    ReleaseEnv();
+}
 
-            // TODO: Revisit is it required?
-            if (OC_STACK_OK != errorCode && OC_STACK_RESOURCE_CREATED != errorCode
-                && OC_STACK_RESOURCE_DELETED != errorCode)
-            {
-                jmethodID midL = env->GetMethodID(onGetCls, "onGetFailed", "(Ljava/lang/Throwable;)V");
-                if (!midL)
-                {
-                    releaseEnv();
-                    return;
-                }
-                env->CallVoidMethod(onGetListener, midL);
-            }
-            else
-            {
-                JSimulatorResourceModel *jniModel = new JSimulatorResourceModel(representation);
-                if (!jniModel)
-                {
-                    releaseEnv();
-                    return;
-                }
-
-                jobject jRepresentation = JSimulatorResourceModel::toJava(env, reinterpret_cast<jlong>(jniModel));
-                if (!jRepresentation)
-                {
-                    delete jniModel;
-                    releaseEnv();
-                    return;
-                }
-
-                jmethodID midL = env->GetMethodID(onGetCls, "onGetCompleted",
-                                                  "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;)V");
-                if (!midL)
-                {
-                    delete jniModel;
-                    releaseEnv();
-                    return;
-                }
-
-                jstring jUid = env->NewStringUTF(uId.c_str());
-                env->CallVoidMethod(onGetListener, midL, jUid, jRepresentation);
-                if (env->ExceptionCheck())
-                {
-                    delete jniModel;
-                    releaseEnv();
-                }
-            }
-        }
+static void onPostCallback(jobject listener, const std::string &uid, SimulatorResult result,
+                           const SimulatorResourceModel &representation)
+{
+    JNIEnv *env = GetEnv();
+    if (!env)
+        return;
 
-    private:
-        jweak m_listener;
-};
+    jclass listenerCls = env->GetObjectClass(listener);
+    jmethodID listenerMethodId = env->GetMethodID(listenerCls, "onPostResponse",
+                                 "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResult;Lorg/oic/simulator/SimulatorResourceModel;)V");
 
-class JNIOnPutListener
-{
-    public:
-        void setJavaOnPutListener(JNIEnv *env, jobject listener)
-        {
-            m_listener = env->NewWeakGlobalRef(listener);
-        }
+    jobject jResModel = SimulatorResourceModelToJava(env, representation);
+    jstring jUid = env->NewStringUTF(uid.c_str());
+    env->CallVoidMethod(listener, listenerMethodId, jUid,
+                        SimulatorResultToJava(env, result), jResModel);
 
-        void onPutCallback(const std::string &uId, int errorCode,
-                           SimulatorResourceModelSP representation)
-        {
-            JNIEnv *env = getEnv();
-            if (nullptr == env)
-                return;
+    ReleaseEnv();
+}
 
-            jobject onPutListener = env->NewLocalRef(m_listener);
-            if (!onPutListener)
-            {
-                releaseEnv();
-                return;
-            }
+static void onVerificationCallback(jobject listener, const std::string &uid, int id,
+                                   OperationState opState)
+{
+    JNIEnv *env = GetEnv();
+    if (!env)
+        return;
 
-            jclass onGetCls = env->GetObjectClass(onPutListener);
-            if (!onGetCls)
-            {
-                releaseEnv();
-                return;
-            }
+    jclass listenerCls = env->GetObjectClass(listener);
+    jmethodID listenerMethodId = nullptr;
+    if (OP_START == opState)
+    {
+        listenerMethodId = env->GetMethodID(listenerCls, "onVerificationStarted", "(Ljava/lang/String;I)V");
+    }
+    else if (OP_COMPLETE == opState)
+    {
+        listenerMethodId = env->GetMethodID(listenerCls, "onVerificationCompleted",
+                                            "(Ljava/lang/String;I)V");
+    }
+    else if (OP_ABORT == opState)
+    {
+        listenerMethodId = env->GetMethodID(listenerCls, "onVerificationAborted", "(Ljava/lang/String;I)V");
+    }
 
-            // TODO: Revisit is it required?
-            if (OC_STACK_OK != errorCode && OC_STACK_RESOURCE_CREATED != errorCode
-                && OC_STACK_RESOURCE_DELETED != errorCode)
-            {
-                jmethodID midL = env->GetMethodID(onGetCls, "onPutFailed", "(Ljava/lang/Throwable;)V");
-                if (!midL)
-                {
-                    releaseEnv();
-                    return;
-                }
-                env->CallVoidMethod(onPutListener, midL);
-            }
-            else
-            {
-                JSimulatorResourceModel *jniModel = new JSimulatorResourceModel(representation);
-                if (!jniModel)
-                {
-                    releaseEnv();
-                    return;
-                }
-
-                jobject jRepresentation = JSimulatorResourceModel::toJava(env,
-                        reinterpret_cast<jlong>(jniModel));
-                if (!jRepresentation)
-                {
-                    delete jniModel;
-                    releaseEnv();
-                    return;
-                }
-
-                jmethodID midL = env->GetMethodID(onGetCls, "onPutCompleted",
-                            "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;)V");
-                if (!midL)
-                {
-                    delete jniModel;
-                    releaseEnv();
-                    return;
-                }
-
-                jstring jUid = env->NewStringUTF(uId.c_str());
-                env->CallVoidMethod(onPutListener, midL, jUid, jRepresentation);
-                if (env->ExceptionCheck())
-                {
-                    delete jniModel;
-                    releaseEnv();
-                }
-            }
-        }
+    // Invoke java callback method
+    if (nullptr != listenerMethodId)
+    {
+        jstring jUid = env->NewStringUTF(uid.c_str());
+        env->CallVoidMethod(listener, listenerMethodId, jUid, id);
+    }
 
-    private:
-        jweak m_listener;
-};
+    if (OP_COMPLETE == opState || OP_ABORT == opState)
+        env->DeleteGlobalRef(listener);
+    ReleaseEnv();
+}
 
-class JNIOnPostListener
+class JniRequestType
 {
     public:
-        void setJavaOnPostListener(JNIEnv *env, jobject listener)
-        {
-            m_listener = env->NewWeakGlobalRef(listener);
-        }
-
-        void onPostCallback(const std::string &uId, int errorCode,
-                            SimulatorResourceModelSP representation)
+        static jobject toJava(JNIEnv *env, RequestType requestType)
         {
-            JNIEnv *env = getEnv();
-            if (nullptr == env)
-                return;
-
-            jobject onPostListener = env->NewLocalRef(m_listener);
-            if (!onPostListener)
+            switch (requestType)
             {
-                releaseEnv();
-                return;
+                case RequestType::RQ_TYPE_GET:
+                    {
+                        static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.requestTypeCls,
+                                                  "GET",
+                                                  "Lorg/oic/simulator/client/SimulatorRemoteResource$RequestType;");
+                        return env->GetStaticObjectField(gSimulatorClassRefs.requestTypeCls, fieldID);
+                    }
+
+                case RequestType::RQ_TYPE_PUT:
+                    {
+                        static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.requestTypeCls,
+                                                  "PUT",
+                                                  "Lorg/oic/simulator/client/SimulatorRemoteResource$RequestType;");
+                        return env->GetStaticObjectField(gSimulatorClassRefs.requestTypeCls, fieldID);
+                    }
+
+                case RequestType::RQ_TYPE_POST:
+                    {
+                        static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.requestTypeCls,
+                                                  "POST",
+                                                  "Lorg/oic/simulator/client/SimulatorRemoteResource$RequestType;");
+                        return env->GetStaticObjectField(gSimulatorClassRefs.requestTypeCls, fieldID);
+                    }
+
+                case RequestType::RQ_TYPE_DELETE:
+                    {
+                        static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.requestTypeCls,
+                                                  "DELETE",
+                                                  "Lorg/oic/simulator/client/SimulatorRemoteResource$RequestType;");
+                        return env->GetStaticObjectField(gSimulatorClassRefs.requestTypeCls, fieldID);
+                    }
+
+                default:
+                    break;
             }
 
-            jclass onGetCls = env->GetObjectClass(onPostListener);
-            if (!onGetCls)
-            {
-                releaseEnv();
-                return;
-            }
-
-            // TODO: Revisit is it required?
-            if (OC_STACK_OK != errorCode && OC_STACK_RESOURCE_CREATED != errorCode
-                && OC_STACK_RESOURCE_DELETED != errorCode)
-            {
-                jmethodID midL = env->GetMethodID(onGetCls, "onPostFailed", "(Ljava/lang/Throwable;)V");
-                if (!midL)
-                {
-                    releaseEnv();
-                    return;
-                }
-                env->CallVoidMethod(onPostListener, midL);
-            }
-            else
-            {
-                JSimulatorResourceModel *jniModel = new JSimulatorResourceModel(representation);
-                if (!jniModel)
-                {
-                    releaseEnv();
-                    return;
-                }
-
-                jobject jRepresentation = JSimulatorResourceModel::toJava(env,
-                        reinterpret_cast<jlong>(jniModel));
-                if (!jRepresentation)
-                {
-                    delete jniModel;
-                    releaseEnv();
-                    return;
-                }
-
-                jmethodID midL = env->GetMethodID(onGetCls, "onPostCompleted",
-                        "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;)V");
-                if (!midL)
-                {
-                    delete jniModel;
-                    releaseEnv();
-                    return;
-                }
-
-                jstring jUid = env->NewStringUTF(uId.c_str());
-
-                env->CallVoidMethod(onPostListener, midL, jUid, jRepresentation);
-                if (env->ExceptionCheck())
-                {
-                    delete jniModel;
-                    releaseEnv();
-                }
-            }
+            static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.requestTypeCls,
+                                      "UKNOWN",
+                                      "Lorg/oic/simulator/client/SimulatorRemoteResource$RequestType;");
+            return env->GetStaticObjectField(gSimulatorClassRefs.requestTypeCls, fieldID);
         }
 
-    private:
-        jweak m_listener;
-
+        static RequestType toCpp(JNIEnv *env, jobject jRequestType)
+        {
+            static jmethodID ordinalMID = env->GetMethodID(
+                                              gSimulatorClassRefs.requestTypeCls, "ordinal", "()I");
+            int ordinal = env->CallIntMethod(jRequestType, ordinalMID);
+            return RequestType(ordinal);
+        }
 };
 
-class JNIOnVerificationListener
+class JniSimulatorRequestModel
 {
     public:
-        void setJavaOnVerificationListener(JNIEnv *env, jobject listener)
+        static jobject toJava(JNIEnv *env, const SimulatorRequestModel &requestModel)
         {
-            m_listener = env->NewWeakGlobalRef(listener);
-        }
-
-        void onVerificationCallback(const std::string &uId, int id, OperationState opState)
-        {
-            JNIEnv *env = getEnv();
-            if (nullptr == env)
-                return;
+            // Convert RequestType
+            jobject jRequestType = JniRequestType::toJava(env, requestModel.getType());
 
-            jobject onVerificationListener = env->NewLocalRef(m_listener);
-            if (!onVerificationListener)
+            // Convert Query Parameters
+            JniMap jQueryParams(env);
+            for (auto &qpEntry : requestModel.getQueryParams())
             {
-                releaseEnv();
-                return;
-            }
+                jstring jQueryParamName = env->NewStringUTF((qpEntry.first).c_str());
+                jobject jQueryParamValues = JniVector(env).toJava(qpEntry.second);
 
-            jclass onVerificationCls = env->GetObjectClass(onVerificationListener);
-            if (!onVerificationCls)
-            {
-                releaseEnv();
-                return;
+                jQueryParams.put(jQueryParamName, jQueryParamValues);
             }
 
-            jmethodID midL;
+            // Convert Request body model
+            jobject jRequestBodyModel  =
+                AttributePropertyToJava(env, requestModel.getRequestBodySchema());
 
-            if (OP_START == opState)
-            {
-                midL = env->GetMethodID(onVerificationCls, "onVerificationStarted", "(Ljava/lang/String;I)V");
-            }
-            else if (OP_COMPLETE == opState)
-            {
-                midL = env->GetMethodID(onVerificationCls, "onVerificationCompleted", "(Ljava/lang/String;I)V");
-            }
-            else
-            {
-                midL = env->GetMethodID(onVerificationCls, "onVerificationAborted", "(Ljava/lang/String;I)V");
-            }
-
-            if (!midL)
-            {
-                releaseEnv();
-                return;
-            }
-
-            jstring jUid = env->NewStringUTF(uId.c_str());
+            // Create Java SimulatorResourceModel object
+            static jmethodID simulatorRequestModelCtor = env->GetMethodID(
+                        gSimulatorClassRefs.simulatorRequestModelCls, "<init>",
+                        "(Lorg/oic/simulator/client/SimulatorRemoteResource$RequestType;"
+                        "Ljava/util/Map;Lorg/oic/simulator/ModelProperty;)V");
 
-            env->CallVoidMethod(onVerificationListener, midL, jUid, (jint)id);
-
-            if (env->ExceptionCheck())
-            {
-                releaseEnv();
-            }
+            return env->NewObject(gSimulatorClassRefs.simulatorRequestModelCls,
+                                  simulatorRequestModelCtor, jRequestType,
+                                  jQueryParams.get(), jRequestBodyModel);
         }
-
-    private:
-        jweak m_listener;
-
 };
 
+#ifdef __cplusplus
+extern "C" {
+#endif
 
 JNIEXPORT void JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_startObserve
-(JNIEnv *env, jobject thiz, jint observeType, jobject jQueryParamsMap, jobject jListener)
+Java_org_oic_simulator_client_SimulatorRemoteResource_nativeGet
+(JNIEnv *env, jobject object, jstring jResInterface, jobject jQueryParams, jobject jListener)
 {
-    if (!jListener)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-        return;
-    }
-
-    SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
-                                         thiz);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
-
-    std::map<std::string, std::string> queryParams;
-    if (jQueryParamsMap)
-        convertJavaMapToQueryParamsMap(env, jQueryParamsMap, queryParams);
+    VALIDATE_CALLBACK(env, jListener)
 
-    ObserveType type = ObserveType::OBSERVE;
-    if (1 == observeType)
-        type = ObserveType::OBSERVE_ALL;
-
-    JNIOnObserveListener *onObserveListener = new JNIOnObserveListener();
-    onObserveListener->setJavaOnObserveListener(env, jListener);
+    SimulatorRemoteResourceSP resource = simulatorRemoteResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
 
     try
     {
-        resource->observe(type,
-                          std::bind(&JNIOnObserveListener::onObserveCallback,
-                                    onObserveListener, std::placeholders::_1,
-                                    std::placeholders::_2, std::placeholders::_3,
-                                    std::placeholders::_4));
+        JniString jniInterface(env, jResInterface);
+        std::map<std::string, std::string> queryParams =
+            JniQueryParameter(env).toCpp(jQueryParams);
+
+        SimulatorRemoteResource::ResponseCallback callback =  std::bind([](
+                    const std::string & uid, SimulatorResult result,
+                    const SimulatorResourceModel & resModel,
+                    const std::shared_ptr<JniListenerHolder> &listenerRef)
+        {
+            onGetCallback(listenerRef->get(), uid, result, resModel);
+        }, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3,
+        JniListenerHolder::create(env, jListener));
+
+        resource->get(jniInterface.get(), queryParams, callback);
     }
     catch (InvalidArgsException &e)
     {
-        throwInvalidArgsException(env, e.code(), e.what());
-    }
-    catch (SimulatorException &e)
-    {
-        throwSimulatorException(env, e.code(), e.what());
-    }
-    catch (...)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+        ThrowInvalidArgsException(env, e.code(), e.what());
     }
-}
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_stopObserve
-(JNIEnv *env, jobject thiz)
-{
-    SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
-                                         thiz);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
-
-    try
+    catch (NoSupportException &e)
     {
-        resource->cancelObserve();
+        ThrowNoSupportException(env, e.what());
     }
     catch (SimulatorException &e)
     {
-        throwSimulatorException(env, e.code(), e.what());
-    }
-    catch (...)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+        ThrowSimulatorException(env, e.code(), e.what());
     }
 }
 
 JNIEXPORT void JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_nativeGet
-(JNIEnv *env, jobject thiz, jstring jResourceInterface,
- jobject jQueryParamsMap, jobject jListener)
+Java_org_oic_simulator_client_SimulatorRemoteResource_nativePut
+(JNIEnv *env, jobject object, jstring jResInterface, jobject jQueryParams,
+ jobject jRepresentation, jobject jListener)
 {
-    if (!jListener)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-        return;
-    }
+    VALIDATE_CALLBACK(env, jListener)
 
-    SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
-                                         thiz);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
+    SimulatorRemoteResourceSP resource = simulatorRemoteResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
 
-    // Interface type
-    const char *interfaceCStr = NULL;
-    std::string interfaceType;
-    if (jResourceInterface)
+    try
     {
-        interfaceCStr = env->GetStringUTFChars(jResourceInterface, NULL);
-        interfaceType = interfaceCStr;
-    }
+        JniString jniInterface(env, jResInterface);
+        std::map<std::string, std::string> queryParams =
+            JniQueryParameter(env).toCpp(jQueryParams);
 
-    // Query parameters
-    std::map<std::string, std::string> queryParams;
-    if (jQueryParamsMap)
-        convertJavaMapToQueryParamsMap(env, jQueryParamsMap, queryParams);
+        SimulatorResourceModel resModel;
+        SimulatorResourceModelToCpp(env, jRepresentation, resModel);
 
-    // Create listener
-    JNIOnGetListener *onGetListener = new JNIOnGetListener();
-    onGetListener->setJavaOnGetListener(env, jListener);
+        SimulatorRemoteResource::ResponseCallback callback =  std::bind([](
+                    const std::string & uid, SimulatorResult result,
+                    const SimulatorResourceModel & resModel,
+                    const std::shared_ptr<JniListenerHolder> &listenerRef)
+        {
+            onPutCallback(listenerRef->get(), uid, result, resModel);
+        }, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3,
+        JniListenerHolder::create(env, jListener));
 
-    try
-    {
-        resource->get(interfaceType,
-                      queryParams,
-                      std::bind(&JNIOnGetListener::onGetCallback,
-                                onGetListener, std::placeholders::_1,
-                                std::placeholders::_2, std::placeholders::_3));
+        resource->put(jniInterface.get(), queryParams, resModel, callback);
     }
     catch (InvalidArgsException &e)
     {
-        throwInvalidArgsException(env, e.code(), e.what());
-        return;
+        ThrowInvalidArgsException(env, e.code(), e.what());
     }
     catch (NoSupportException &e)
     {
-        throwNoSupportException(env, e.code(), e.what());
-        return;
+        ThrowNoSupportException(env, e.what());
     }
     catch (SimulatorException &e)
     {
-        throwSimulatorException(env, e.code(), e.what());
-        return;
+        ThrowSimulatorException(env, e.code(), e.what());
     }
-    catch (...)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
-        return;
-    }
-
-    if (interfaceCStr)
-        env->ReleaseStringUTFChars(jResourceInterface, interfaceCStr);
 }
 
 JNIEXPORT void JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_nativePut
-(JNIEnv *env, jobject thiz, jstring jResourceInterface,
- jobject jRepresentation, jobject jQueryParamsMap, jobject jListener)
+Java_org_oic_simulator_client_SimulatorRemoteResource_nativePost
+(JNIEnv *env, jobject object, jstring jResInterface, jobject jQueryParams,
+ jobject jRepresentation, jobject jListener)
 {
-    if (!jListener)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-        return;
-    }
+    VALIDATE_CALLBACK(env, jListener)
 
-    SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
-                                         thiz);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
+    SimulatorRemoteResourceSP resource = simulatorRemoteResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
 
-    // Interface type
-    const char *interfaceCStr = NULL;
-    std::string interfaceType;
-    if (jResourceInterface)
+    try
     {
-        interfaceCStr = env->GetStringUTFChars(jResourceInterface, NULL);
-        interfaceType = interfaceCStr;
-    }
+        JniString jniInterface(env, jResInterface);
+        std::map<std::string, std::string> queryParams =
+            JniQueryParameter(env).toCpp(jQueryParams);
 
-    // Query parameters
-    std::map<std::string, std::string> queryParams;
-    if (jQueryParamsMap)
-        convertJavaMapToQueryParamsMap(env, jQueryParamsMap, queryParams);
+        SimulatorResourceModel resModel;
+        SimulatorResourceModelToCpp(env, jRepresentation, resModel);
 
-    SimulatorResourceModelSP resourceModel =
-        JSimulatorResourceModel::getResourceModelPtr(env, jRepresentation);
-
-    // Create listener
-    JNIOnPutListener *onPutListener = new JNIOnPutListener();
-    onPutListener->setJavaOnPutListener(env, jListener);
+        SimulatorRemoteResource::ResponseCallback callback =  std::bind([](
+                    const std::string & uid, SimulatorResult result,
+                    const SimulatorResourceModel & resModel,
+                    const std::shared_ptr<JniListenerHolder> &listenerRef)
+        {
+            onPostCallback(listenerRef->get(), uid, result, resModel);
+        }, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3,
+        JniListenerHolder::create(env, jListener));
 
-    try
-    {
-        resource->put(interfaceType,
-                      queryParams,
-                      resourceModel,
-                      std::bind(&JNIOnPutListener::onPutCallback,
-                                onPutListener, std::placeholders::_1,
-                                std::placeholders::_2, std::placeholders::_3));
+        resource->post(jniInterface.get(), queryParams, resModel, callback);
     }
     catch (InvalidArgsException &e)
     {
-        throwInvalidArgsException(env, e.code(), e.what());
-        return;
+        ThrowInvalidArgsException(env, e.code(), e.what());
     }
     catch (NoSupportException &e)
     {
-        throwNoSupportException(env, e.code(), e.what());
-        return;
+        ThrowNoSupportException(env, e.what());
     }
     catch (SimulatorException &e)
     {
-        throwSimulatorException(env, e.code(), e.what());
-        return;
-    }
-    catch (...)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
-        return;
+        ThrowSimulatorException(env, e.code(), e.what());
     }
-
-    if (interfaceCStr)
-        env->ReleaseStringUTFChars(jResourceInterface, interfaceCStr);
 }
 
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_nativePost
-(JNIEnv *env, jobject thiz, jstring jResourceInterface,
- jobject jRepresentation, jobject jQueryParamsMap, jobject jListener)
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_client_SimulatorRemoteResource_nativeSetConfigInfo
+(JNIEnv *env, jobject object, jstring jConfigPath)
 {
-    if (!jListener)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-        return;
-    }
+    VALIDATE_INPUT_RET(env, !jConfigPath, "Path is null!", nullptr)
 
-    SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
-                                         thiz);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
+    SimulatorRemoteResourceSP resource = simulatorRemoteResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, resource, nullptr)
 
-    // Interface type
-    const char *interfaceCStr = NULL;
-    std::string interfaceType;
-    if (jResourceInterface)
+    try
     {
-        interfaceCStr = env->GetStringUTFChars(jResourceInterface, NULL);
-        interfaceType = interfaceCStr;
-    }
+        JniString jniConfigPath(env, jConfigPath);
+        std::map<RequestType, SimulatorRequestModel> requestModels =
+            resource->configure(jniConfigPath.get());
 
-    // Query parameters
-    std::map<std::string, std::string> queryParams;
-    if (jQueryParamsMap)
-        convertJavaMapToQueryParamsMap(env, jQueryParamsMap, queryParams);
+        JniMap jRequestModelsMap(env);
 
-    SimulatorResourceModelSP resourceModel =
-        JSimulatorResourceModel::getResourceModelPtr(env, jRepresentation);
+        // Add entry to map
+        for (auto &requestModelEntry : requestModels)
+        {
+            jobject jRequestType = JniRequestType::toJava(env, requestModelEntry.first);
+            jobject jRequestModel = JniSimulatorRequestModel::toJava(env, requestModelEntry.second);
 
-    // Create listener
-    JNIOnPostListener *onPostListener = new JNIOnPostListener();
-    onPostListener->setJavaOnPostListener(env, jListener);
+            jRequestModelsMap.put(jRequestType, jRequestModel);
+        }
 
-    try
-    {
-        resource->post(interfaceType,
-                       queryParams,
-                       resourceModel,
-                       std::bind(&JNIOnPostListener::onPostCallback,
-                                 onPostListener, std::placeholders::_1,
-                                 std::placeholders::_2, std::placeholders::_3));
+        return jRequestModelsMap.get();
     }
     catch (InvalidArgsException &e)
     {
-        throwInvalidArgsException(env, e.code(), e.what());
-        return;
-    }
-    catch (NoSupportException &e)
-    {
-        throwNoSupportException(env, e.code(), e.what());
-        return;
-    }
-    catch (SimulatorException &e)
-    {
-        throwSimulatorException(env, e.code(), e.what());
-        return;
-    }
-    catch (...)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
-        return;
+        ThrowInvalidArgsException(env, e.code(), e.what());
     }
 
-    if (interfaceCStr)
-        env->ReleaseStringUTFChars(jResourceInterface, interfaceCStr);
+    return nullptr;
 }
 
 JNIEXPORT void JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_setConfigInfo
-(JNIEnv *env, jobject thiz, jstring jConfigPath)
+Java_org_oic_simulator_client_SimulatorRemoteResource_nativeStartObserve
+(JNIEnv *env, jobject object, jobject jQueryParams, jobject jListener)
 {
-    if (!jConfigPath)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM,
-                                  "Configuration file path is null!");
-        return;
-    }
-
-    SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
-                                         thiz);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
+    VALIDATE_CALLBACK(env, jListener)
 
-    // Interface type
-    const char *configCStr = NULL;
-    std::string configPath;
-    if (jConfigPath)
-    {
-        configCStr = env->GetStringUTFChars(jConfigPath, NULL);
-        configPath = configCStr;
-    }
+    SimulatorRemoteResourceSP resource = simulatorRemoteResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
 
     try
     {
-        resource->configure(configPath);
+        std::map<std::string, std::string> queryParams =
+            JniQueryParameter(env).toCpp(jQueryParams);
+
+        SimulatorRemoteResource::ObserveNotificationCallback callback =  std::bind([](
+                    const std::string & uid, SimulatorResult result,
+                    const SimulatorResourceModel & representation, const int seq,
+                    const std::shared_ptr<JniListenerHolder> &listenerRef)
+        {
+            onObserveCallback(listenerRef->get(), uid, result, representation, seq);
+        }, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3,
+        std::placeholders::_4, JniListenerHolder::create(env, jListener));
+
+        resource->observe(ObserveType::OBSERVE, callback);
     }
     catch (InvalidArgsException &e)
     {
-        throwInvalidArgsException(env, e.code(), e.what());
-        return;
+        ThrowInvalidArgsException(env, e.code(), e.what());
     }
-    catch (...)
+    catch (SimulatorException &e)
     {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
-        return;
+        ThrowSimulatorException(env, e.code(), e.what());
     }
-
-    if (configCStr)
-        env->ReleaseStringUTFChars(jConfigPath, configCStr);
 }
 
-JNIEXPORT jint JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_startVerification
-(JNIEnv *env, jobject thiz, jint jReqType, jobject jListener)
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_client_SimulatorRemoteResource_nativeStopObserve
+(JNIEnv *env, jobject object)
 {
-    if (!jListener)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-        return SIMULATOR_INVALID_CALLBACK;
-    }
+    SimulatorRemoteResourceSP resource = simulatorRemoteResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
 
-    SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
-                                         thiz);
-    if (!resource)
+    try
     {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return SIMULATOR_BAD_OBJECT;
+        resource->cancelObserve();
     }
-
-    // Convert RequestType
-    RequestType reqType;
-
-    switch (jReqType)
+    catch (SimulatorException &e)
     {
-        case 0:
-            reqType = RequestType::RQ_TYPE_GET;
-            break;
-
-        case 1:
-            reqType = RequestType::RQ_TYPE_PUT;
-            break;
-
-        case 2:
-            reqType = RequestType::RQ_TYPE_POST;
-            break;
-
-        case 3:
-            reqType = RequestType::RQ_TYPE_DELETE;
-            break;
-
-        default:
-            return -1;
+        ThrowSimulatorException(env, e.code(), e.what());
     }
+}
 
-    // Create listener
-    JNIOnVerificationListener *onVerificationListener = new JNIOnVerificationListener();
-    onVerificationListener->setJavaOnVerificationListener(env, jListener);
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_client_SimulatorRemoteResource_nativeStartAutoRequesting
+(JNIEnv *env, jobject object, jobject jRequestType, jobject jListener)
+{
+    VALIDATE_CALLBACK_RET(env, jListener, -1)
 
-    int automationId = -1;
+    SimulatorRemoteResourceSP resource = simulatorRemoteResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, resource, -1)
 
     try
     {
-        automationId = resource->startVerification(reqType,
-                       std::bind(&JNIOnVerificationListener::onVerificationCallback,
-                                 onVerificationListener, std::placeholders::_1,
-                                 std::placeholders::_2, std::placeholders::_3));
+        RequestType type = JniRequestType::toCpp(env, jRequestType);
+        SimulatorRemoteResource::AutoRequestGenerationCallback callback =  std::bind([](
+                    const std::string & uid, int id, OperationState opState,
+                    const std::shared_ptr<JniListenerHolder> &listenerRef)
+        {
+            onVerificationCallback(listenerRef->get(), uid, id, opState);
+        }, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3,
+        JniListenerHolder::create(env, jListener));
+
+        return resource->startAutoRequesting(type, callback);
     }
     catch (InvalidArgsException &e)
     {
-        throwInvalidArgsException(env, e.code(), e.what());
+        ThrowInvalidArgsException(env, e.code(), e.what());
     }
     catch (NoSupportException &e)
     {
-        throwNoSupportException(env, e.code(), e.what());
+        ThrowNoSupportException(env, e.what());
     }
     catch (OperationInProgressException &e)
     {
-        throwOperationInProgressException(env, e.code(), e.what());
+        ThrowOperationInProgressException(env, e.what());
     }
     catch (SimulatorException &e)
     {
-        throwSimulatorException(env, e.code(), e.what());
-    }
-    catch (...)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+        ThrowSimulatorException(env, e.code(), e.what());
     }
 
-    return automationId;
+    return -1;
 }
 
 JNIEXPORT void JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_stopVerification
-(JNIEnv *env, jobject thiz, jint jId)
+Java_org_oic_simulator_client_SimulatorRemoteResource_nativeStopAutoRequesting
+(JNIEnv *env, jobject object, jint id)
 {
-    SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
-                                         thiz);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
+    SimulatorRemoteResourceSP resource = simulatorRemoteResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
 
     try
     {
-        resource->stopVerification((int)jId);
+        resource->stopAutoRequesting(id);
     }
     catch (InvalidArgsException &e)
     {
-        throwInvalidArgsException(env, e.code(), e.what());
+        ThrowInvalidArgsException(env, e.code(), e.what());
     }
     catch (NoSupportException &e)
     {
-        throwNoSupportException(env, e.code(), e.what());
-    }
-    catch (...)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+        ThrowNoSupportException(env, e.what());
     }
 }
 
-JNIEXPORT void JNICALL Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_dispose
-(JNIEnv *env, jobject thiz)
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_client_SimulatorRemoteResource_nativeDispose
+(JNIEnv *env, jobject object)
 {
-    JniSimulatorRemoteResource *resource = GetHandle<JniSimulatorRemoteResource>(env, thiz);
+    JniSharedObjectHolder<SimulatorRemoteResource> *resource =
+        getHandle<JniSharedObjectHolder<SimulatorRemoteResource>>(env, object);
     delete resource;
-}
\ No newline at end of file
+}
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/service/simulator/java/jni/simulator_remote_resource_jni.h b/service/simulator/java/jni/simulator_remote_resource_jni.h
deleted file mode 100644 (file)
index b1fbecd..0000000
+++ /dev/null
@@ -1,85 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-#ifndef SIMULATOR_REMOTE_RESOURCE_JNI_H_
-#define SIMULATOR_REMOTE_RESOURCE_JNI_H_
-
-#include <jni.h>
-#include "simulator_remote_resource.h"
-
-class JniSimulatorRemoteResource
-{
-    public:
-        JniSimulatorRemoteResource(SimulatorRemoteResourceSP &resource)
-            : m_resource(resource) {};
-        static SimulatorRemoteResourceSP getResourceHandle(JNIEnv *env, jobject object);
-    private:
-        SimulatorRemoteResourceSP m_resource;
-};
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_startObserve
-(JNIEnv *env, jobject thiz, jint observeType, jobject jQueryParamsMap, jobject jListener);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_stopObserve
-(JNIEnv *env, jobject thiz);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_nativeGet
-(JNIEnv *env, jobject thiz, jstring jResourceInterface,
- jobject jQueryParamsMap, jobject jListener);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_nativePut
-(JNIEnv *env, jobject thiz, jstring jResourceInterface,
- jobject jRepresentation, jobject jQueryParamsMap, jobject jListener);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_nativePost
-(JNIEnv *env, jobject thiz, jstring jResourceInterface,
- jobject jRepresentation, jobject jQueryParamsMap, jobject jListener);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_setConfigInfo
-(JNIEnv *env, jobject thiz, jstring jConfigPath);
-
-JNIEXPORT jint JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_startVerification
-(JNIEnv *env, jobject thiz, jint jReqType, jobject jListener);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_stopVerification
-(JNIEnv *env, jobject thiz, jint jId);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_dispose
-(JNIEnv *, jobject);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
-
diff --git a/service/simulator/java/jni/simulator_resource_attribute_jni.cpp b/service/simulator/java/jni/simulator_resource_attribute_jni.cpp
new file mode 100644 (file)
index 0000000..49c2188
--- /dev/null
@@ -0,0 +1,93 @@
+/******************************************************************
+ *
+ * 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 "simulator_resource_attribute_jni.h"
+#include "simulator_resource_model_jni.h"
+#include "simulator_resource_model_schema_jni.h"
+#include "simulator_utils_jni.h"
+#include "jni_string.h"
+#include "jni_map.h"
+
+jobject SimulatorResourceAttributeToJava(JNIEnv *env,
+        const SimulatorResourceAttribute &attribute)
+{
+    static jmethodID simulatorResAttributeCtor = env->GetMethodID(
+                gSimulatorClassRefs.simulatorResourceAttributeCls, "<init>",
+                "(Ljava/lang/String;Lorg/oic/simulator/AttributeValue;Lorg/oic/simulator/AttributeProperty;)V");
+
+    jstring jAttrName = env->NewStringUTF(attribute.getName().c_str());
+    jobject jAttrValue = AttributeValueToJava(env, attribute.getValue());
+    jobject jAttrProperty = AttributePropertyToJava(env, attribute.getProperty());
+
+    return env->NewObject(gSimulatorClassRefs.simulatorResourceAttributeCls,
+                          simulatorResAttributeCtor, jAttrName, jAttrValue, jAttrProperty);
+}
+
+bool SimulatorResourceAttributeToCpp(JNIEnv *env, jobject jAttribute,
+                                     SimulatorResourceAttribute &attribute)
+{
+    if (!jAttribute)
+        return false;
+
+    static jfieldID nameFID = env->GetFieldID(gSimulatorClassRefs.simulatorResourceAttributeCls,
+                              "mName", "Ljava/lang/String;");
+    static jfieldID valueFID = env->GetFieldID(gSimulatorClassRefs.simulatorResourceAttributeCls,
+                               "mValue", "Lorg/oic/simulator/AttributeValue;");
+    static jfieldID propertyFID = env->GetFieldID(gSimulatorClassRefs.simulatorResourceAttributeCls,
+                                  "mProperty", "Lorg/oic/simulator/AttributeProperty;");
+
+    jstring jAttrName = (jstring) env->GetObjectField(jAttribute, nameFID);
+    jobject jAttrValue = env->GetObjectField(jAttribute, valueFID);
+    jobject jAttrProperty = env->GetObjectField(jAttribute, propertyFID);
+
+    if (!jAttrName || !jAttrValue)
+        return false;
+
+    JniString attrName(env, jAttrName);
+    AttributeValueVariant value;
+    AttributeValueToCpp(env, jAttrValue, value);
+
+    attribute.setName(attrName.get());
+    attribute.setValue(value);
+    if (jAttrProperty)
+    {
+        std::shared_ptr<AttributeProperty> property = AttributePropertyToCpp(env, jAttrProperty);
+        attribute.setProperty(property);
+    }
+
+    return true;
+}
+
+jobject SimulatorResourceAttributesToJava(JNIEnv *env,
+        const std::map<std::string, SimulatorResourceAttribute> &attributes)
+{
+    JniMap jAttributesMap(env);
+
+    // Add attribute values for Attributes table
+    for (auto &attributeEntry : attributes)
+    {
+        jstring jAttrName = env->NewStringUTF((attributeEntry.first).c_str());
+        jobject jAttribute = SimulatorResourceAttributeToJava(env, attributeEntry.second);
+
+        jAttributesMap.put(jAttrName, jAttribute);
+    }
+
+    return jAttributesMap.get();
+}
\ No newline at end of file
diff --git a/service/simulator/java/jni/simulator_resource_attribute_jni.h b/service/simulator/java/jni/simulator_resource_attribute_jni.h
new file mode 100644 (file)
index 0000000..b33ed48
--- /dev/null
@@ -0,0 +1,36 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_RESOURCE_ATTRIBUTE_JNI_H_
+#define SIMULATOR_RESOURCE_ATTRIBUTE_JNI_H_
+
+#include <jni.h>
+#include "simulator_resource_model.h"
+
+jobject SimulatorResourceAttributeToJava(JNIEnv *env,
+        const SimulatorResourceAttribute &attribute);
+
+bool SimulatorResourceAttributeToCpp(JNIEnv *env, jobject jAttribute,
+                                     SimulatorResourceAttribute &attribute);
+
+jobject SimulatorResourceAttributesToJava(JNIEnv *env,
+        const std::map<std::string, SimulatorResourceAttribute> &attributes);
+
+#endif
diff --git a/service/simulator/java/jni/simulator_resource_jni.cpp b/service/simulator/java/jni/simulator_resource_jni.cpp
new file mode 100644 (file)
index 0000000..ca6094f
--- /dev/null
@@ -0,0 +1,518 @@
+/******************************************************************
+ *
+ * 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 "simulator_resource_model_jni.h"
+#include "simulator_exceptions_jni.h"
+#include "simulator_utils_jni.h"
+#include "jni_sharedobject_holder.h"
+#include "jni_listener_holder.h"
+#include "jni_string.h"
+#include "jni_vector.h"
+
+#include "simulator_resource.h"
+
+#define VALIDATE_OBJECT(ENV, OBJECT) if (!OBJECT){ThrowBadObjectException(ENV, "No corresponsing native object!"); return;}
+#define VALIDATE_OBJECT_RET(ENV, OBJECT, RET) if (!OBJECT){ThrowBadObjectException(ENV, "No corresponsing native object!"); return RET;}
+
+SimulatorResourceSP SimulatorResourceToCpp(JNIEnv *env, jobject object)
+{
+    JniSharedObjectHolder<SimulatorResource> *jniResource =
+        getHandle<JniSharedObjectHolder<SimulatorResource>>(env, object);
+    if (jniResource)
+        return jniResource->get();
+    return nullptr;
+}
+
+static jobject createObserverInfo(JNIEnv *env, const ObserverInfo &observerInfo)
+{
+    static jmethodID observerInfoCtor = env->GetMethodID(gSimulatorClassRefs.observerCls,
+                                        "<init>", "(ILjava/lang/String;I)V");
+
+    jstring address = env->NewStringUTF(observerInfo.address.c_str());
+    jobject observer = (jobject) env->NewObject(gSimulatorClassRefs.observerCls,
+                       observerInfoCtor, observerInfo.id, address, observerInfo.port);
+    env->DeleteLocalRef(address);
+
+    return observer;
+}
+
+static jobject createObserverInfoVector(JNIEnv *env,
+                                        const std::vector<ObserverInfo> observersList)
+{
+    jobject vectorObject = JniVector(env).toJava();
+    if (!vectorObject)
+        return nullptr;
+
+    static jmethodID addMethod = env->GetMethodID(gSimulatorClassRefs.vectorCls,
+                                 "add", "(Ljava/lang/Object;)Z");
+
+    for (auto &observer : observersList)
+        env->CallBooleanMethod(vectorObject, addMethod, createObserverInfo(env, observer));
+
+    return vectorObject;
+}
+
+static void onObserverChange(jobject listener, const std::string &uri,
+                             ObservationStatus state, const ObserverInfo &observerInfo)
+{
+    JNIEnv *env = GetEnv();
+    if (!env)
+        return;
+
+    jclass listenerCls = env->GetObjectClass(listener);
+    jmethodID listenerMethod = nullptr;
+    if (ObservationStatus::REGISTER == state)
+    {
+        listenerMethod = env->GetMethodID(listenerCls, "onObserverAdded",
+                                          "(Ljava/lang/String;Lorg/oic/simulator/server/Observer;)V");
+    }
+    else
+    {
+        listenerMethod = env->GetMethodID(listenerCls, "onObserverRemoved",
+                                          "(Ljava/lang/String;Lorg/oic/simulator/server/Observer;)V");
+    }
+
+    jstring jUri = env->NewStringUTF(uri.c_str());
+    jobject jobserver = createObserverInfo(env, observerInfo);
+
+    env->CallVoidMethod(listener, listenerMethod, jUri, jobserver);
+    ReleaseEnv();
+}
+
+static void onResourceModelChange(jobject listener, const std::string &uri,
+                                  const SimulatorResourceModel &resModel)
+{
+    JNIEnv *env = GetEnv();
+    if (!env)
+        return;
+
+    jclass listenerCls = env->GetObjectClass(listener);
+    jmethodID listenerMethod = env->GetMethodID(listenerCls, "onResourceModelChanged",
+                               "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;)V");
+
+    jobject jResModel = SimulatorResourceModelToJava(env, resModel);
+    jstring jUri = env->NewStringUTF(uri.c_str());
+    env->CallVoidMethod(listener, listenerMethod, jUri, jResModel);
+    ReleaseEnv();
+}
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+JNIEXPORT jstring JNICALL
+Java_org_oic_simulator_server_SimulatorResource_nativeGetName
+(JNIEnv *env, jobject object)
+{
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, resource, nullptr)
+
+    return env->NewStringUTF(resource->getName().c_str());
+}
+
+JNIEXPORT jstring JNICALL
+Java_org_oic_simulator_server_SimulatorResource_nativeGetURI
+(JNIEnv *env, jobject object)
+{
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, resource, nullptr)
+
+    return env->NewStringUTF(resource->getURI().c_str());
+}
+
+JNIEXPORT jstring JNICALL
+Java_org_oic_simulator_server_SimulatorResource_nativeGetResourceType
+(JNIEnv *env, jobject object)
+{
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, resource, nullptr)
+
+    return env->NewStringUTF(resource->getResourceType().c_str());
+}
+
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_server_SimulatorResource_nativeGetInterface
+(JNIEnv *env, jobject object)
+{
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, resource, nullptr)
+
+    std::vector<std::string> interfaces = resource->getInterface();
+    return JniVector(env).toJava(interfaces);
+}
+
+JNIEXPORT jboolean JNICALL
+Java_org_oic_simulator_server_SimulatorResource_nativeIsObservable
+(JNIEnv *env, jobject object)
+{
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, resource, false)
+
+    return resource->isObservable();
+}
+
+JNIEXPORT jboolean JNICALL
+Java_org_oic_simulator_server_SimulatorResource_nativeIsDiscoverable
+(JNIEnv *env, jobject object)
+{
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, resource, false)
+
+    return resource->isDiscoverable();
+}
+
+JNIEXPORT jboolean JNICALL
+Java_org_oic_simulator_server_SimulatorResource_nativeIsStarted
+(JNIEnv *env, jobject object)
+{
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, resource, false)
+
+    return resource->isStarted();
+}
+
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_server_SimulatorResource_nativeGetResourceModel
+(JNIEnv *env, jobject object)
+{
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, resource, nullptr)
+
+    SimulatorResourceModel resModel = resource->getResourceModel();
+    return SimulatorResourceModelToJava(env, resModel);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorResource_nativeSetName
+(JNIEnv *env, jobject object, jstring jName)
+{
+    VALIDATE_INPUT(env, !jName, "Name is null!")
+
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
+
+    try
+    {
+        JniString jniName(env, jName);
+        resource->setName(jniName.get());
+    }
+    catch (InvalidArgsException &e)
+    {
+        ThrowInvalidArgsException(env, e.code(), e.what());
+    }
+    catch (SimulatorException &e)
+    {
+        ThrowSimulatorException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorResource_nativeSetURI
+(JNIEnv *env, jobject object, jstring jUri)
+{
+    VALIDATE_INPUT(env, !jUri, "Uri is null!")
+
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
+
+    try
+    {
+        JniString jniUri(env, jUri);
+        resource->setURI(jniUri.get());
+    }
+    catch (InvalidArgsException &e)
+    {
+        ThrowInvalidArgsException(env, e.code(), e.what());
+    }
+    catch (SimulatorException &e)
+    {
+        ThrowSimulatorException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorResource_nativeSetResourceType
+(JNIEnv *env, jobject object, jstring jResourceType)
+{
+    VALIDATE_INPUT(env, !jResourceType, "Resource type is null!")
+
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
+
+    try
+    {
+        JniString jniType(env, jResourceType);
+        resource->setResourceType(jniType.get());
+    }
+    catch (InvalidArgsException &e)
+    {
+        ThrowInvalidArgsException(env, e.code(), e.what());
+    }
+    catch (SimulatorException &e)
+    {
+        ThrowSimulatorException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorResource_nativeSetInterface
+(JNIEnv *env, jobject object, jstring jInterfaceType)
+{
+    VALIDATE_INPUT(env, !jInterfaceType, "Interface type is null!")
+
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
+
+    try
+    {
+        JniString jniInterfaceType(env, jInterfaceType);
+        resource->setInterface(jniInterfaceType.get());
+    }
+    catch (InvalidArgsException &e)
+    {
+        ThrowInvalidArgsException(env, e.code(), e.what());
+    }
+    catch (SimulatorException &e)
+    {
+        ThrowSimulatorException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorResource_nativeSetInterfaces
+(JNIEnv *env, jobject object, jobject jInterfaceTypes)
+{
+    VALIDATE_INPUT(env, !jInterfaceTypes, "Interface type is null!")
+
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
+
+    std::vector<std::string> interfaceList = JniVector(env).toCpp<std::string>(jInterfaceTypes);
+
+    try
+    {
+        resource->setInterface(interfaceList);
+    }
+    catch (InvalidArgsException &e)
+    {
+        ThrowInvalidArgsException(env, e.code(), e.what());
+    }
+    catch (SimulatorException &e)
+    {
+        ThrowSimulatorException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorResource_nativeAddInterface
+(JNIEnv *env, jobject object, jstring jInterfaceType)
+{
+    VALIDATE_INPUT(env, !jInterfaceType, "Interface type is null!")
+
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
+
+    try
+    {
+        JniString jniInterfaceType(env, jInterfaceType);
+        resource->addInterface(jniInterfaceType.get());
+    }
+    catch (InvalidArgsException &e)
+    {
+        ThrowInvalidArgsException(env, e.code(), e.what());
+    }
+    catch (NoSupportException &e)
+    {
+        ThrowNoSupportException(env, e.what());
+    }
+    catch (SimulatorException &e)
+    {
+        ThrowSimulatorException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorResource_nativeSetObservable
+(JNIEnv *env, jobject object, jboolean jState)
+{
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
+
+    try
+    {
+        resource->setObservable(static_cast<bool>(jState));
+    }
+    catch (SimulatorException &e)
+    {
+        ThrowSimulatorException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorResource_nativeSetDiscoverable
+(JNIEnv *env, jobject object, jboolean jState)
+{
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
+
+    try
+    {
+        resource->setDiscoverable(static_cast<bool>(jState));
+    }
+    catch (SimulatorException &e)
+    {
+        ThrowSimulatorException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorResource_nativeSetObserverListener
+(JNIEnv *env, jobject object, jobject jListener)
+{
+    VALIDATE_CALLBACK(env, jListener)
+
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
+
+    SimulatorResource::ObserverCallback callback =  std::bind([](const std::string & uri,
+            ObservationStatus state, const ObserverInfo & observerInfo,
+            const std::shared_ptr<JniListenerHolder> &listenerRef)
+    {
+        onObserverChange(listenerRef->get(), uri, state, observerInfo);
+    }, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3,
+    JniListenerHolder::create(env, jListener));
+
+    try
+    {
+        resource->setObserverCallback(callback);
+    }
+    catch (InvalidArgsException &e)
+    {
+        ThrowInvalidArgsException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorResource_nativeSetResourceModelChangeListener
+(JNIEnv *env, jobject object, jobject jListener)
+{
+    VALIDATE_CALLBACK(env, jListener)
+
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
+
+    SimulatorResource::ResourceModelUpdateCallback callback =  std::bind(
+                [](const std::string & uri, const SimulatorResourceModel & resModel,
+                   const std::shared_ptr<JniListenerHolder> &listenerRef)
+    {
+        onResourceModelChange(listenerRef->get(), uri, resModel);
+    }, std::placeholders::_1, std::placeholders::_2, JniListenerHolder::create(env, jListener));
+
+    try
+    {
+        resource->setModelChangeCallback(callback);
+    }
+    catch (InvalidArgsException &e)
+    {
+        ThrowInvalidArgsException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorResource_nativeStart
+(JNIEnv *env, jobject object)
+{
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
+
+    try
+    {
+        resource->start();
+    }
+    catch (SimulatorException &e)
+    {
+        ThrowSimulatorException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorResource_nativeStop
+(JNIEnv *env, jobject object)
+{
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
+
+    try
+    {
+        resource->stop();
+    }
+    catch (SimulatorException &e)
+    {
+        ThrowSimulatorException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_server_SimulatorResource_nativeGetObservers
+(JNIEnv *env, jobject object)
+{
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, resource, nullptr)
+
+    return createObserverInfoVector(env, resource->getObservers());
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorResource_nativeNotify
+(JNIEnv *env, jobject object, jint id)
+{
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
+
+    try
+    {
+        resource->notify(id);
+    }
+    catch (SimulatorException &e)
+    {
+        ThrowSimulatorException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorResource_nativeNotifyAll
+(JNIEnv *env, jobject object)
+{
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
+
+    try
+    {
+        resource->notifyAll();
+    }
+    catch (SimulatorException &e)
+    {
+        ThrowSimulatorException(env, e.code(), e.what());
+    }
+}
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/service/simulator/java/jni/simulator_resource_jni_util.cpp b/service/simulator/java/jni/simulator_resource_jni_util.cpp
deleted file mode 100644 (file)
index de2952b..0000000
+++ /dev/null
@@ -1,206 +0,0 @@
-/******************************************************************
- *
- * 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 "simulator_resource_jni_util.h"
-#include "simulator_common_jni.h"
-
-extern SimulatorClassRefs gSimulatorClassRefs;
-
-std::vector<int> convertIntegerVector(JNIEnv *env, jobject jVectorInt)
-{
-    std::vector<int> vectorInt;
-
-    jclass vectorClass = env->FindClass("java/util/Vector");
-    if (!vectorClass)
-    {
-        return vectorInt;
-    }
-
-    jmethodID size = env->GetMethodID(vectorClass, "size", "()I");
-    if (NULL == size)
-    {
-        return vectorInt;
-    }
-
-    jmethodID get = env->GetMethodID(vectorClass, "get", "(I)""Ljava/lang/Object;");
-    if (NULL == get)
-    {
-        return vectorInt;
-    }
-
-    jint jSize = env->CallIntMethod(jVectorInt, size);
-    int sizeOfVector = jSize;
-
-    for (int index = 0; index < sizeOfVector; index++)
-    {
-        jint jIndex = index;
-        jint jValue = env->CallIntMethod(jVectorInt, get, jIndex);
-        vectorInt.push_back((int)jValue);
-    }
-
-    return vectorInt;
-}
-
-std::vector<double> convertDoubleVector(JNIEnv *env, jobject jVectorDouble)
-{
-    std::vector<double> vectorDouble;
-
-    jclass vectorClass = env->FindClass("java/util/Vector");
-    if (!vectorClass)
-    {
-        return vectorDouble;
-    }
-
-    jmethodID size = env->GetMethodID(vectorClass, "size", "()I");
-    if (NULL == size)
-    {
-        return vectorDouble;
-    }
-
-    jmethodID get = env->GetMethodID(vectorClass, "get", "(I)""Ljava/lang/Object;");
-    if (NULL == get)
-    {
-        return vectorDouble;
-    }
-
-    jint jSize = env->CallIntMethod(jVectorDouble, size);
-    int sizeOfVector = jSize;
-
-    for (int index = 0; index < sizeOfVector; index++)
-    {
-        jint jIndex = index;
-        jdouble jValue = env->CallDoubleMethod(jVectorDouble, get, jIndex);
-        vectorDouble.push_back((double)jValue);
-    }
-
-    return vectorDouble;
-}
-
-std::vector<std::string> convertStringVector(JNIEnv *env, jobject jVectorString)
-{
-    std::vector<std::string> vectorString;
-
-    jclass vectorClass = env->FindClass("java/util/Vector");
-    if (!vectorClass)
-    {
-        return vectorString;
-    }
-
-    jmethodID size = env->GetMethodID(vectorClass, "size", "()I");
-    if (NULL == size)
-    {
-        return vectorString;
-    }
-
-    jmethodID get = env->GetMethodID(vectorClass, "get", "(I)""Ljava/lang/Object;");
-    if (NULL == get)
-    {
-        return vectorString;
-    }
-
-    jint jSize = env->CallIntMethod(jVectorString, size);
-    int sizeOfVector = jSize;
-
-    for (int index = 0; index < sizeOfVector; index++)
-    {
-        jint jIndex = index;
-        jstring jContactInfoObj = (jstring)env->CallObjectMethod(jVectorString, get, jIndex);
-        if (jContactInfoObj == NULL)
-        {
-            return vectorString;
-        }
-        const char *buff = env->GetStringUTFChars(jContactInfoObj, 0);
-        if (NULL != buff)
-        {
-            std::string tempString = buff;
-            vectorString.push_back(tempString);
-        }
-
-        env->ReleaseStringUTFChars(jContactInfoObj, buff);
-    }
-
-    return vectorString;
-}
-
-void convertJavaMapToQueryParamsMap(JNIEnv *env, jobject hashMap,
-                                    std::map<std::string, std::string> &queryParams)
-{
-    if (!hashMap) return;
-
-    jobject jEntrySet = env->CallObjectMethod(hashMap, gSimulatorClassRefs.classMapEntrySet);
-    jobject jIterator = env->CallObjectMethod(jEntrySet, gSimulatorClassRefs.classIteratorId);
-    if (!jEntrySet || !jIterator || env->ExceptionCheck()) return;
-
-    while (env->CallBooleanMethod(jIterator, gSimulatorClassRefs.classHasNextId))
-    {
-        jobject jEntry = env->CallObjectMethod(jIterator, gSimulatorClassRefs.classNextId);
-        if (!jEntry) return;
-        jstring jKey = (jstring)env->CallObjectMethod(jEntry, gSimulatorClassRefs.classMapGetKey);
-        if (!jKey) return;
-        jstring jValue = (jstring)env->CallObjectMethod(jEntry, gSimulatorClassRefs.classMapGetValue);
-        if (!jValue) return;
-
-        queryParams.insert(std::make_pair(env->GetStringUTFChars(jKey, NULL),
-                                          env->GetStringUTFChars(jValue, NULL)));
-
-        if (env->ExceptionCheck()) return;
-        env->DeleteLocalRef(jEntry);
-        env->DeleteLocalRef(jKey);
-        env->DeleteLocalRef(jValue);
-    }
-}
-
-jobject convertHashMapToJavaMap(JNIEnv *env,
-                                const std::map<std::string, uint8_t> &observersList)
-{
-    if (observersList.empty())
-    {
-        return NULL;
-    }
-
-    jobject jObserverListMap = env->NewObject(gSimulatorClassRefs.classHashMap,
-                               gSimulatorClassRefs.classHashMapCtor);
-
-    for (auto it = observersList.begin(); it != observersList.end(); ++it)
-    {
-        jstring key = (*env).NewStringUTF( (*it).first.c_str() );
-        jint value = (*it).second;
-        env->CallObjectMethod(jObserverListMap, gSimulatorClassRefs.classHashMapPut, key, value);
-    }
-
-    return jObserverListMap;
-}
-
-jobject convertStringVectorToJavaList(JNIEnv *env, std::vector<std::string> &vector)
-{
-    jobject jList = env->NewObject(gSimulatorClassRefs.classLinkedList,
-                                   gSimulatorClassRefs.classLinkedListCtor);
-    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;
-        env->CallBooleanMethod(jList, gSimulatorClassRefs.classLinkedListAddObject, jStr);
-        if (env->ExceptionCheck()) return nullptr;
-        env->DeleteLocalRef(jStr);
-    }
-    return jList;
-}
-
-
diff --git a/service/simulator/java/jni/simulator_resource_jni_util.h b/service/simulator/java/jni/simulator_resource_jni_util.h
deleted file mode 100644 (file)
index d3c7e70..0000000
+++ /dev/null
@@ -1,77 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-/**
- * @file   simulator_resource_jni_util.h
- *
- * @brief  This file contains the utility functions for conversions from java to CPP
- * and viceversa
- */
-
-#ifndef __SIMULATOR_RESOURCE_JNI_UTIL_H_
-#define __SIMULATOR_RESOURCE_JNI_UTIL_H_
-
-#include <jni.h>
-#include <iostream>
-#include <vector>
-#include <map>
-
-#include "simulator_remote_resource.h"
-
-/**
-  * Utility function for converting a Java Vector of Strings to CPP Vector of Strings
-  *
-  * @param env - Default JNI Environment pointer
-  * @param jVectorString - Java Vector of Strings
-  *
-  * @return void
-  */
-std::vector<int> convertIntegerVector(JNIEnv *env, jobject jVectorInt);
-
-/**
-  * Utility function for converting a Java Vector of Strings to CPP Vector of Strings
-  *
-  * @param env - Default JNI Environment pointer
-  * @param jVectorString - Java Vector of Strings
-  *
-  * @return void
-  */
-std::vector<double> convertDoubleVector(JNIEnv *env, jobject jVectorDouble);
-
-/**
-  * Utility function for converting a Java Vector of Strings to CPP Vector of Strings
-  *
-  * @param env - Default JNI Environment pointer
-  * @param jVectorString - Java Vector of Strings
-  *
-  * @return void
-  */
-std::vector<std::string> convertStringVector(JNIEnv *env, jobject jVectorString);
-
-void convertJavaMapToQueryParamsMap(JNIEnv *env, jobject hashMap,
-                                    std::map<std::string, std::string> &map);
-
-jobject convertHashMapToJavaMap(JNIEnv *env,
-                                const std::map<std::string, uint8_t> &observersList);
-
-jobject convertStringVectorToJavaList(JNIEnv *env, std::vector<std::string> &vector);
-
-#endif //__SIMULATOR_RESOURCE_JNI_UTIL_H_
-
index 65b9d9d..a186d76 100644 (file)
  ******************************************************************/
 
 #include "simulator_resource_model_jni.h"
-#include "simulator_common_jni.h"
-#include "resource_attributes_jni.h"
-#include "simulator_error_codes.h"
-#include "simulator_jni_utils.h"
+#include "simulator_utils_jni.h"
+#include "jni_string.h"
+#include "jni_map.h"
 
-using namespace std;
-
-extern SimulatorClassRefs gSimulatorClassRefs;
-
-JSimulatorResourceModel::JSimulatorResourceModel(SimulatorResourceModel resModel)
-    : m_resourceModel(resModel)
-{}
-
-JSimulatorResourceModel::JSimulatorResourceModel(SimulatorResourceModelSP resModel)
-    : m_resModelPtr(resModel)
-{}
-
-bool JSimulatorResourceModel::getResourceModel(JNIEnv *env, jobject thiz,
-        SimulatorResourceModel &resModel)
+class JniTypeInfo
 {
-    JSimulatorResourceModel *resource = GetHandle<JSimulatorResourceModel>(env, thiz);
-    if (env->ExceptionCheck())
-    {
-        return false;
-    }
-
-    if (nullptr != resource->m_resModelPtr)
-        resModel = *(resource->m_resModelPtr.get());
-    else
-        resModel = resource->m_resourceModel;
-    return true;
-}
-
-SimulatorResourceModelSP JSimulatorResourceModel::getResourceModelPtr(JNIEnv *env, jobject thiz)
+    public:
+        JniTypeInfo(JNIEnv *env) : m_env(env) {}
+
+        SimulatorResourceModel::TypeInfo toCpp(jobject jAttributeValue)
+        {
+            static jmethodID typeInfoMID = m_env->GetMethodID(gSimulatorClassRefs.attributeValueCls,
+                                           "typeInfo", "()Lorg/oic/simulator/AttributeValue$TypeInfo;");
+            static jfieldID typeFID = m_env->GetFieldID(gSimulatorClassRefs.attributeTypeInfoCls,
+                                      "mType", "Lorg/oic/simulator/AttributeValue$ValueType;");
+            static jfieldID baseTypeFID = m_env->GetFieldID(gSimulatorClassRefs.attributeTypeInfoCls,
+                                          "mBaseType", "Lorg/oic/simulator/AttributeValue$ValueType;");
+            static jfieldID depthFID = m_env->GetFieldID(gSimulatorClassRefs.attributeTypeInfoCls,
+                                       "mDepth", "I");
+
+            jobject jTypeInfo = m_env->CallObjectMethod(jAttributeValue, typeInfoMID);
+            jobject jType = m_env->GetObjectField(jTypeInfo, typeFID);
+            jobject jBaseType = m_env->GetObjectField(jTypeInfo, baseTypeFID);
+            jint jDepth = m_env->GetIntField(jTypeInfo, depthFID);
+
+            return SimulatorResourceModel::TypeInfo(getValueType(jType),
+                                                    getValueType(jBaseType), jDepth);
+        }
+
+    private:
+        AttributeValueType getValueType(jobject jValueType)
+        {
+            static jmethodID ordinalMID = m_env->GetMethodID(
+                                              gSimulatorClassRefs.attributeValueTypeCls, "ordinal", "()I");
+
+            int ordinal = m_env->CallIntMethod(jValueType, ordinalMID);
+            return AttributeValueType(ordinal);
+        }
+
+        JNIEnv *m_env;
+};
+
+class ValueConverterJava : public boost::static_visitor<jobject>
 {
-    JSimulatorResourceModel *resource = GetHandle<JSimulatorResourceModel>(env, thiz);
-    if (env->ExceptionCheck())
-    {
-        return nullptr;
-    }
-
-    if (nullptr != resource->m_resModelPtr)
-        return resource->m_resModelPtr;
-    return nullptr;
-}
-
-jobject JSimulatorResourceModel::toJava(JNIEnv *env, jlong nativeHandle)
+    public:
+        ValueConverterJava(JNIEnv *env) : m_env(env) {}
+
+        jobject operator ()(const int &value)
+        {
+            static jmethodID integerCtor =
+                m_env->GetMethodID(gSimulatorClassRefs.integerCls, "<init>", "(I)V");
+            return m_env->NewObject(gSimulatorClassRefs.integerCls,
+                                    integerCtor, value);
+        }
+
+        jobject operator ()(const double &value)
+        {
+            static jmethodID doubleCtor =
+                m_env->GetMethodID(gSimulatorClassRefs.doubleCls, "<init>", "(D)V");
+            return m_env->NewObject(gSimulatorClassRefs.doubleCls,
+                                    doubleCtor, value);
+        }
+
+        jobject operator ()(const bool &value)
+        {
+            static jmethodID booleanCtor =
+                m_env->GetMethodID(gSimulatorClassRefs.booleanCls, "<init>", "(Z)V");
+            return m_env->NewObject(gSimulatorClassRefs.booleanCls,
+                                    booleanCtor, value);
+        }
+
+        jobject operator ()(const std::string &value)
+        {
+            jstring stringValue = m_env->NewStringUTF(value.c_str());
+            return static_cast<jobject>(stringValue);
+        }
+
+        jobject operator ()(const SimulatorResourceModel &value)
+        {
+            return SimulatorResourceModelToJava(m_env, const_cast<SimulatorResourceModel &>(value));
+        }
+
+        template <typename T>
+        jobject operator ()(const std::vector<T> &values)
+        {
+            jobjectArray jArray = m_env->NewObjectArray(values.size(), getClass(values), nullptr);
+            if (!jArray)
+                return nullptr;
+
+            for (size_t index = 0; index < values.size(); index++)
+            {
+                jobject element = operator()(values[index]);
+                m_env->SetObjectArrayElement(jArray, index, element);
+            }
+
+            return jArray;
+        }
+
+        template <typename T>
+        jobject operator ()(const std::vector<std::vector<T>> &values)
+        {
+            jobjectArray jArray = m_env->NewObjectArray(values.size(), getClass(values), nullptr);
+            if (!jArray)
+                return nullptr;
+
+            for (size_t index = 0; index < values.size(); index++)
+            {
+                jobject element = operator()(values[index]);
+                m_env->SetObjectArrayElement(jArray, index, element);
+            }
+
+            return jArray;
+        }
+
+        template <typename T>
+        jobject operator ()(const std::vector<std::vector<std::vector<T>>> &values)
+        {
+            jobjectArray jArray = m_env->NewObjectArray(values.size(), getClass(values), nullptr);
+            if (!jArray)
+                return nullptr;
+
+            for (size_t index = 0; index < values.size(); index++)
+            {
+                jobject element = operator()(values[index]);
+                m_env->SetObjectArrayElement(jArray, index, element);
+            }
+
+            return jArray;
+        }
+
+    private:
+        jclass getClass(const std::vector<int> &)
+        {
+            return gSimulatorClassRefs.integerCls;
+        }
+
+        jclass getClass(const std::vector<std::vector<int>> &)
+        {
+            return gSimulatorClassRefs.integer1DArrayCls;
+        }
+
+        jclass getClass(const std::vector<std::vector<std::vector<int>>> &)
+        {
+            return gSimulatorClassRefs.integer2DArrayCls;
+        }
+
+        jclass getClass(const std::vector<double> &)
+        {
+            return gSimulatorClassRefs.doubleCls;
+        }
+
+        jclass getClass(const std::vector<std::vector<double>> &)
+        {
+            return gSimulatorClassRefs.double1DArrayCls;
+        }
+
+        jclass getClass(const std::vector<std::vector<std::vector<double>>> &)
+        {
+            return gSimulatorClassRefs.double2DArrayCls;
+        }
+
+        jclass getClass(const std::vector<bool> &)
+        {
+            return gSimulatorClassRefs.booleanCls;
+        }
+
+        jclass getClass(const std::vector<std::vector<bool>> &)
+        {
+            return gSimulatorClassRefs.boolean1DArrayCls;
+        }
+
+        jclass getClass(const std::vector<std::vector<std::vector<bool>>> &)
+        {
+            return gSimulatorClassRefs.boolean2DArrayCls;
+        }
+
+        jclass getClass(const std::vector<std::string> &)
+        {
+            return gSimulatorClassRefs.stringCls;
+        }
+
+        jclass getClass(const std::vector<std::vector<std::string>> &)
+        {
+            return gSimulatorClassRefs.string1DArrayCls;
+        }
+
+        jclass getClass(const std::vector<std::vector<std::vector<std::string>>> &)
+        {
+            return gSimulatorClassRefs.string2DArrayCls;
+        }
+
+        jclass getClass(const std::vector<SimulatorResourceModel> &)
+        {
+            return gSimulatorClassRefs.simulatorResourceModelCls;
+        }
+
+        jclass getClass(const std::vector<std::vector<SimulatorResourceModel>> &)
+        {
+            return gSimulatorClassRefs.simulatorResModel1DArrayCls;
+        }
+
+        jclass getClass(const std::vector<std::vector<std::vector<SimulatorResourceModel>>> &)
+        {
+            return gSimulatorClassRefs.simulatorResModel2DArrayCls;
+        }
+
+        JNIEnv *m_env;
+};
+
+class ValueConverterCpp
 {
-    jobject resourceObj = (jobject) env->NewObject(gSimulatorClassRefs.classSimulatorResourceModel,
-                          gSimulatorClassRefs.classSimulatorResourceModelCtor, nativeHandle);
-    if (!resourceObj)
-    {
-        return NULL;
-    }
-    return resourceObj;
-}
-
-void JSimulatorResourceModel::toJava(JNIEnv *env, jobject thiz, jlong nativeHandle)
+    public:
+        ValueConverterCpp(JNIEnv *env, SimulatorResourceModel::TypeInfo &typeInfo,
+                          jobject &value) : m_env(env), m_typeInfo(typeInfo), m_value(value) {}
+
+        void convert()
+        {
+            switch (m_typeInfo.baseType())
+            {
+                case AttributeValueType::INTEGER:
+                    return handleByDepth<int>();
+                case AttributeValueType::DOUBLE:
+                    return handleByDepth<double>();
+                case AttributeValueType::BOOLEAN:
+                    return handleByDepth<bool>();
+                case AttributeValueType::STRING:
+                    return handleByDepth<std::string>();
+                case AttributeValueType::RESOURCE_MODEL:
+                    return handleByDepth<SimulatorResourceModel>();
+                case AttributeValueType::VECTOR:
+                case AttributeValueType::UNKNOWN:
+                    break;
+            }
+        }
+
+        AttributeValueVariant get()
+        {
+            return std::move(m_result);
+        }
+
+    private:
+        template <typename T>
+        void handleByDepth()
+        {
+            if (0 == m_typeInfo.depth())
+            {
+                T value;
+                getValue(m_value, value);
+                m_result = value;
+            }
+            else if (1 == m_typeInfo.depth())
+            {
+                std::vector<T> value;
+                getValue(m_value, value);
+                m_result = value;
+            }
+            else if (2 == m_typeInfo.depth())
+            {
+                std::vector<std::vector<T>> value;
+                getValue(m_value, value);
+                m_result = value;
+            }
+            else if (3 == m_typeInfo.depth())
+            {
+                std::vector<std::vector<std::vector<T>>> value;
+                getValue(m_value, value);
+                m_result = value;
+            }
+        }
+
+        void getValue(jobject &jValue, int &value)
+        {
+            static jmethodID intValueMID = m_env->GetMethodID(
+                                               gSimulatorClassRefs.integerCls, "intValue", "()I");
+
+            jint temp = m_env->CallIntMethod(jValue, intValueMID);
+            value = temp;
+        }
+
+        void getValue(jobject &jValue, std::vector<int> &value)
+        {
+            jobjectArray array = (jobjectArray) jValue;
+            size_t length = m_env->GetArrayLength(array);
+            for (size_t i = 0; i < length; i++)
+            {
+                jobject jElement = m_env->GetObjectArrayElement(array, i);
+
+                int element;
+                getValue(jElement, element);
+                value.push_back(element);
+            }
+        }
+
+        void getValue(jobject &jValue, std::vector<std::vector<int>> &value)
+        {
+            jobjectArray array = (jobjectArray) jValue;
+            size_t length = m_env->GetArrayLength(array);
+            for (size_t i = 0; i < length; i++)
+            {
+                jobject jElement = m_env->GetObjectArrayElement(array, i);
+
+                std::vector<int> element;
+                getValue(jElement, element);
+                value.push_back(element);
+            }
+        }
+
+        void getValue(jobject &jValue, std::vector<std::vector<std::vector<int>>> &value)
+        {
+            jobjectArray array = (jobjectArray) jValue;
+            size_t length = m_env->GetArrayLength(array);
+            for (size_t i = 0; i < length; i++)
+            {
+                jobject jElement = m_env->GetObjectArrayElement(array, i);
+
+                std::vector<std::vector<int>> element;
+                getValue(jElement, element);
+                value.push_back(element);
+            }
+        }
+
+        void getValue(jobject &jValue, double &value)
+        {
+            static jmethodID doubleValueMID = m_env->GetMethodID(
+                                                  gSimulatorClassRefs.doubleCls, "doubleValue", "()D");
+
+            value = m_env->CallDoubleMethod(jValue, doubleValueMID);
+        }
+
+        void getValue(jobject &jValue, std::vector<double> &value)
+        {
+            jobjectArray array = (jobjectArray) jValue;
+            size_t length = m_env->GetArrayLength(array);
+            for (size_t i = 0; i < length; i++)
+            {
+                jobject jElement = m_env->GetObjectArrayElement(array, i);
+
+                double element;
+                getValue(jElement, element);
+                value.push_back(element);
+            }
+        }
+
+        void getValue(jobject &jValue, std::vector<std::vector<double>> &value)
+        {
+            jobjectArray array = (jobjectArray) jValue;
+            size_t length = m_env->GetArrayLength(array);
+            for (size_t i = 0; i < length; i++)
+            {
+                jobject jElement = m_env->GetObjectArrayElement(array, i);
+
+                std::vector<double> element;
+                getValue(jElement, element);
+                value.push_back(element);
+            }
+        }
+
+        void getValue(jobject &jValue, std::vector<std::vector<std::vector<double>>> &value)
+        {
+            jobjectArray array = (jobjectArray) jValue;
+            size_t length = m_env->GetArrayLength(array);
+            for (size_t i = 0; i < length; i++)
+            {
+                jobject jElement = m_env->GetObjectArrayElement(array, i);
+
+                std::vector<std::vector<double>> element;
+                getValue(jElement, element);
+                value.push_back(element);
+            }
+        }
+
+        void getValue(jobject &jValue, bool &value)
+        {
+            static jmethodID boolValueMID = m_env->GetMethodID(
+                                                gSimulatorClassRefs.booleanCls, "booleanValue", "()Z");
+
+            value = m_env->CallBooleanMethod(jValue, boolValueMID);
+        }
+
+        void getValue(jobject &jValue, std::vector<bool> &value)
+        {
+            jobjectArray array = (jobjectArray) jValue;
+            size_t length = m_env->GetArrayLength(array);
+            for (size_t i = 0; i < length; i++)
+            {
+                jobject jElement = m_env->GetObjectArrayElement(array, i);
+
+                bool element;
+                getValue(jElement, element);
+                value.push_back(element);
+            }
+        }
+
+        void getValue(jobject &jValue, std::vector<std::vector<bool>> &value)
+        {
+            jobjectArray array = (jobjectArray) jValue;
+            size_t length = m_env->GetArrayLength(array);
+            for (size_t i = 0; i < length; i++)
+            {
+                jobject jElement = m_env->GetObjectArrayElement(array, i);
+
+                std::vector<bool> element;
+                getValue(jElement, element);
+                value.push_back(element);
+            }
+        }
+
+        void getValue(jobject &jValue, std::vector<std::vector<std::vector<bool>>> &value)
+        {
+            jobjectArray array = (jobjectArray) jValue;
+            size_t length = m_env->GetArrayLength(array);
+            for (size_t i = 0; i < length; i++)
+            {
+                jobject jElement = m_env->GetObjectArrayElement(array, i);
+
+                std::vector<std::vector<bool>> element;
+                getValue(jElement, element);
+                value.push_back(element);
+            }
+        }
+
+        void getValue(jobject &jValue, std::string &value)
+        {
+            jstring stringValue = (jstring) jValue;
+            JniString jniValue(m_env, stringValue);
+            value = jniValue.get();
+        }
+
+        void getValue(jobject jValue, std::vector<std::string> &value)
+        {
+            jobjectArray array = (jobjectArray) jValue;
+            size_t length = m_env->GetArrayLength(array);
+            for (size_t i = 0; i < length; i++)
+            {
+                jobject jElement = m_env->GetObjectArrayElement(array, i);
+
+                std::string element;
+                getValue(jElement, element);
+                value.push_back(element);
+            }
+        }
+
+        void getValue(jobject &jValue, std::vector<std::vector<std::string>> &value)
+        {
+            jobjectArray array = (jobjectArray) jValue;
+            size_t length = m_env->GetArrayLength(array);
+            for (size_t i = 0; i < length; i++)
+            {
+                jobject jElement = m_env->GetObjectArrayElement(array, i);
+
+                std::vector<std::string> element;
+                getValue(jElement, element);
+                value.push_back(element);
+            }
+        }
+
+        void getValue(jobject &jValue, std::vector<std::vector<std::vector<std::string>>> &value)
+        {
+            jobjectArray array = (jobjectArray) jValue;
+            size_t length = m_env->GetArrayLength(array);
+            for (size_t i = 0; i < length; i++)
+            {
+                jobject jElement = m_env->GetObjectArrayElement(array, i);
+
+                std::vector<std::vector<std::string>> element;
+                getValue(jElement, element);
+                value.push_back(element);
+            }
+        }
+
+        void getValue(jobject &jValue, SimulatorResourceModel &value)
+        {
+            SimulatorResourceModelToCpp(m_env, jValue, value);
+        }
+
+        void getValue(jobject &jValue, std::vector<SimulatorResourceModel> &value)
+        {
+            jobjectArray array = (jobjectArray) jValue;
+            size_t length = m_env->GetArrayLength(array);
+            std::vector<SimulatorResourceModel> result(length);
+            for (size_t i = 0; i < length; i++)
+            {
+                jobject jElement = m_env->GetObjectArrayElement(array, i);
+
+                SimulatorResourceModel element;
+                getValue(jElement, element);
+                result[i] = element;
+            }
+
+            value = result;
+        }
+
+        void getValue(jobject &jValue, std::vector<std::vector<SimulatorResourceModel>> &value)
+        {
+            jobjectArray array = (jobjectArray) jValue;
+            size_t length = m_env->GetArrayLength(array);
+            std::vector<std::vector<SimulatorResourceModel>> result(length);
+            for (size_t i = 0; i < length; i++)
+            {
+                jobject jElement = m_env->GetObjectArrayElement(array, i);
+
+                std::vector<SimulatorResourceModel> childArray;
+                getValue(jElement, childArray);
+                value[i] = childArray;
+            }
+
+            value = result;
+        }
+
+        void getValue(jobject &jValue, std::vector<std::vector<std::vector<SimulatorResourceModel>>> &value)
+        {
+            jobjectArray array = (jobjectArray) jValue;
+            size_t length = m_env->GetArrayLength(array);
+            std::vector<std::vector<std::vector<SimulatorResourceModel>>> result(length);
+            for (size_t i = 0; i < length; i++)
+            {
+                jobject jElement = m_env->GetObjectArrayElement(array, i);
+
+                std::vector<std::vector<SimulatorResourceModel>> childArray;
+                getValue(jElement, childArray);
+                value[i] = childArray;
+            }
+
+            value = result;
+        }
+
+        JNIEnv *m_env;
+        SimulatorResourceModel::TypeInfo &m_typeInfo;
+        jobject &m_value;
+        AttributeValueVariant m_result;
+};
+
+class JniAttributeValue
 {
-    if (env && thiz && nativeHandle)
-    {
-        env->SetLongField(thiz, GetHandleField(env, thiz), nativeHandle);
-    }
-}
-
-static jobject createHashMap(JNIEnv *env)
+    public:
+        static jobject toJava(JNIEnv *env, const SimulatorResourceAttribute &attribute)
+        {
+            return toJava(env, attribute.getValue());
+        }
+
+        static jobject toJava(JNIEnv *env, const AttributeValueVariant &value)
+        {
+            ValueConverterJava converter(env);
+            jobject jValue =  boost::apply_visitor(converter, value);
+
+            static jmethodID attrValueCtor = env->GetMethodID(
+                                                 gSimulatorClassRefs.attributeValueCls, "<init>", "(Ljava/lang/Object;)V");
+
+            return env->NewObject(gSimulatorClassRefs.attributeValueCls, attrValueCtor, jValue);
+        }
+
+        static AttributeValueVariant toCpp(JNIEnv *env, jobject &jAttributeValue)
+        {
+            static jmethodID getMID = env->GetMethodID(gSimulatorClassRefs.attributeValueCls,
+                                      "get", "()Ljava/lang/Object;");
+
+            SimulatorResourceModel::TypeInfo typeInfo = JniTypeInfo(env).toCpp(jAttributeValue);
+            jobject jValue = env->CallObjectMethod(jAttributeValue, getMID);
+
+            ValueConverterCpp converter(env, typeInfo, jValue);
+            converter.convert();
+            return converter.get();
+        }
+};
+
+jobject SimulatorResourceModelToJava(JNIEnv *env, const SimulatorResourceModel &resModel)
 {
-    jobject mapobj = env->NewObject(gSimulatorClassRefs.classHashMap,
-                                    gSimulatorClassRefs.classHashMapCtor);
-    return mapobj;
-}
+    JniMap jAttributesMap(env);
 
-static void addEntryToHashMap(JNIEnv *env, jobject mapobj, jobject key, jobject value)
-{
-    if (!mapobj || !key || !value)
+    // Add attribute values for HashMap
+    for (auto &attributeEntry : resModel.getAttributeValues())
     {
-        return;
-    }
-
-    env->CallObjectMethod(mapobj, gSimulatorClassRefs.classHashMapPut, key, value);
-}
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorResourceModel_create
-(JNIEnv *env, jobject thiz)
-{
-    SimulatorResourceModelSP resModel = std::make_shared<SimulatorResourceModel>();
-    JSimulatorResourceModel *jresModel = new JSimulatorResourceModel(resModel);
-    JSimulatorResourceModel::toJava(env, thiz, reinterpret_cast<jlong>(jresModel));
-}
-
-JNIEXPORT jint JNICALL
-Java_org_oic_simulator_SimulatorResourceModel_size
-(JNIEnv *env, jobject thiz)
-{
-    SimulatorResourceModel resourceModel;
-    bool result = JSimulatorResourceModel::getResourceModel(env, thiz, resourceModel);
-    if (!result)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "Resource model not found!");
-        return SIMULATOR_BAD_OBJECT;
-    }
-
-    return resourceModel.size();
-}
-
-JNIEXPORT jobject JNICALL
-Java_org_oic_simulator_SimulatorResourceModel_getAttributes
-(JNIEnv *env, jobject thiz)
-{
-    SimulatorResourceModel resourceModel;
-    bool result = JSimulatorResourceModel::getResourceModel(env, thiz, resourceModel);
-    if (!result)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "Resource model not found!");
-        return nullptr;
-    }
-
-    map<string, SimulatorResourceModel::Attribute> attributesMap = resourceModel.getAttributes();
-
-    // Create Java HashMap object
-    jobject jHashMap = NULL;
-    jHashMap = createHashMap(env);
-    if (!jHashMap)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Java map creation failed!");
-        return nullptr;
-    }
-
-    for (auto & attributeEntry : attributesMap)
-    {
-        SimulatorResourceModel::Attribute attribute(attributeEntry.second);
-
-        // Create a object of ResourceAttribute java class
-        JResourceAttributeConverter converter(attribute);
-        jobject jAttribute = converter.toJava(env);
-
-        // Add an entry with attribute.first and javaSimualatorResourceAttribute to the HashMap
         jstring jAttrName = env->NewStringUTF((attributeEntry.first).c_str());
-        addEntryToHashMap(env, jHashMap, static_cast<jobject>(jAttrName), jAttribute);
-        env->DeleteLocalRef(jAttrName);
-    }
-
-    return jHashMap;
-}
-
-JNIEXPORT jobject JNICALL
-Java_org_oic_simulator_SimulatorResourceModel_getAttribute
-(JNIEnv *env, jobject thiz, jstring jAttrName)
-{
-    if (!jAttrName)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid attribute name!");
-        return nullptr;
-    }
+        jobject jAttributeValue = JniAttributeValue::toJava(env, attributeEntry.second);
 
-    const char *attrName = env->GetStringUTFChars(jAttrName, NULL);
-    if (!attrName)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "String error!");
-        return nullptr;
-    }
-
-    SimulatorResourceModel resourceModel;
-    bool result = JSimulatorResourceModel::getResourceModel(env, thiz, resourceModel);
-    if (!result)
-    {
-        env->ReleaseStringUTFChars(jAttrName, attrName);
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "Resource model not found!");
-        return nullptr;
+        jAttributesMap.put(jAttrName, jAttributeValue);
     }
 
-    SimulatorResourceModel::Attribute attribute;
-    bool found = resourceModel.getAttribute(attrName, attribute);
-    if (!found)
-    {
-        env->ReleaseStringUTFChars(jAttrName, attrName);
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Attribute does not exist!");
-        return nullptr;
-    }
+    // Create Java SimulatorResourceModel object
+    static jmethodID simulatorResourceModelCtor = env->GetMethodID(
+                gSimulatorClassRefs.simulatorResourceModelCls, "<init>", "(Ljava/util/Map;)V");
 
-    env->ReleaseStringUTFChars(jAttrName, attrName);
-
-    // Create a object of ResourceAttribute java class
-    JResourceAttributeConverter converter(attribute);
-    return converter.toJava(env);
+    return env->NewObject(gSimulatorClassRefs.simulatorResourceModelCls,
+                          simulatorResourceModelCtor, jAttributesMap.get());
 }
 
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorResourceModel_addAttributeInt
-(JNIEnv *env, jobject thiz, jstring jname, jint jvalue)
+bool SimulatorResourceModelToCpp(JNIEnv *env, jobject jResModel, SimulatorResourceModel &resModel)
 {
-    if (!jname)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid attribute name!");
-        return;
-    }
-
-    SimulatorResourceModelSP resModelPtr;
-    resModelPtr = JSimulatorResourceModel::getResourceModelPtr(env, thiz);
-    if (!resModelPtr)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "Resource model not found!");
-        return;
-    }
+    if (!jResModel)
+        return false;
 
-    const char *nameCstr = env->GetStringUTFChars(jname, NULL);
-    if (!nameCstr)
+    static jfieldID valuesFID = env->GetFieldID(gSimulatorClassRefs.simulatorResourceModelCls,
+                                "mValues", "Ljava/util/Map;");
+    static jmethodID entrySetMID = env->GetMethodID(gSimulatorClassRefs.mapCls, "entrySet",
+                                   "()Ljava/util/Set;");
+    static jmethodID iteratorMID = env->GetMethodID(gSimulatorClassRefs.setCls, "iterator",
+                                   "()Ljava/util/Iterator;");
+    static jmethodID hasNextMID = env->GetMethodID(gSimulatorClassRefs.iteratorCls, "hasNext",
+                                  "()Z");
+    static jmethodID nextMID = env->GetMethodID(gSimulatorClassRefs.iteratorCls, "next",
+                               "()Ljava/lang/Object;");
+    static jmethodID getKeyMID = env->GetMethodID(gSimulatorClassRefs.mapEntryCls, "getKey",
+                                 "()Ljava/lang/Object;");
+    static jmethodID getValueMID = env->GetMethodID(gSimulatorClassRefs.mapEntryCls, "getValue",
+                                   "()Ljava/lang/Object;");
+
+    jobject jValues = env->GetObjectField(jResModel, valuesFID);
+    if (jValues)
     {
-        throwSimulatorException(env, SIMULATOR_ERROR, "String error!");
-        return;
+        jobject entrySet = env->CallObjectMethod(jValues, entrySetMID);
+        jobject iterator = env->CallObjectMethod(entrySet, iteratorMID);
+        if (entrySet && iterator)
+        {
+            while (env->CallBooleanMethod(iterator, hasNextMID))
+            {
+                jobject entry = env->CallObjectMethod(iterator, nextMID);
+                jstring key = (jstring) env->CallObjectMethod(entry, getKeyMID);
+                jobject value = env->CallObjectMethod(entry, getValueMID);
+                resModel.add(JniString(env, key).get(), JniAttributeValue::toCpp(env, value));
+
+                env->DeleteLocalRef(entry);
+                env->DeleteLocalRef(key);
+                env->DeleteLocalRef(value);
+            }
+        }
     }
 
-    std::string attrName(nameCstr);
-    int value = static_cast<int>(jvalue);
-    resModelPtr->addAttribute(attrName, value);
-
-    // Release created c string
-    env->ReleaseStringUTFChars(jname, nameCstr);
+    return true;
 }
 
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorResourceModel_addAttributeDouble
-(JNIEnv *env, jobject thiz, jstring jname, jdouble jvalue)
+jobject AttributeValueToJava(JNIEnv *env,
+                             const AttributeValueVariant &value)
 {
-    if (!jname)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid attribute name!");
-        return;
-    }
-
-    SimulatorResourceModelSP resModelPtr;
-    resModelPtr = JSimulatorResourceModel::getResourceModelPtr(env, thiz);
-    if (!resModelPtr)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "Resource model not found!");
-        return;
-    }
-
-    const char *nameCstr = env->GetStringUTFChars(jname, NULL);
-    if (!nameCstr)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "String error!");
-        return;
-    }
-
-    std::string attrName(nameCstr);
-    double value = static_cast<double>(jvalue);
-    resModelPtr->addAttribute(attrName, value);
-
-    // Release created c string
-    env->ReleaseStringUTFChars(jname, nameCstr);
+    return JniAttributeValue::toJava(env, value);
 }
 
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorResourceModel_addAttributeBoolean
-(JNIEnv *env, jobject thiz, jstring jname, jboolean jvalue)
+bool AttributeValueToCpp(JNIEnv *env, jobject jAttributeValue,
+                         AttributeValueVariant &jValue)
 {
-    if (!jname)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid attribute name!");
-        return;
-    }
-
-    SimulatorResourceModelSP resModelPtr;
-    resModelPtr = JSimulatorResourceModel::getResourceModelPtr(env, thiz);
-    if (!resModelPtr)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "Resource model not found!");
-        return;
-    }
-
-    const char *nameCstr = env->GetStringUTFChars(jname, NULL);
-    if (!nameCstr)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "String error!");
-        return;
-    }
-
-    std::string attrName(nameCstr);
-    bool value = static_cast<bool>(jvalue);
-    resModelPtr->addAttribute(attrName, value);
-
-    // Release created c string
-    env->ReleaseStringUTFChars(jname, nameCstr);
-}
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorResourceModel_addAttributeString
-(JNIEnv *env, jobject thiz, jstring jname, jstring jvalue)
-{
-    if (!jname)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid attribute name!");
-        return;
-    }
-
-    if (!jvalue)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Attribute value cannot be null!");
-        return;
-    }
-
-    SimulatorResourceModelSP resModelPtr;
-    resModelPtr = JSimulatorResourceModel::getResourceModelPtr(env, thiz);
-    if (!resModelPtr)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "Resource model not found!");
-        return;
-    }
-
-    const char *nameCstr = env->GetStringUTFChars(jname, NULL);
-    if (!nameCstr)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "String error!");
-        return;
-    }
-
-    const char *valueCstr = env->GetStringUTFChars(jvalue, NULL);
-    if (!valueCstr)
-    {
-        env->ReleaseStringUTFChars(jname, nameCstr);
-        throwSimulatorException(env, SIMULATOR_ERROR, "String error!");
-        return;
-    }
-
-    std::string attrName(nameCstr);
-    std::string value(valueCstr);
-    resModelPtr->addAttribute(attrName, value);
+    if (!jAttributeValue)
+        return false;
 
-    // Release created c string
-    env->ReleaseStringUTFChars(jname, nameCstr);
-    env->ReleaseStringUTFChars(jvalue, valueCstr);
+    jValue = JniAttributeValue::toCpp(env, jAttributeValue);
+    return true;
 }
 
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorResourceModel_dispose
-(JNIEnv *env, jobject thiz)
-{
-    JSimulatorResourceModel *resourceModel = GetHandle<JSimulatorResourceModel>(env, thiz);
-    delete resourceModel;
-}
index 2e4d35d..489c787 100644 (file)
 #define SIMULATOR_RESOURCE_MODEL_JNI_H_
 
 #include <jni.h>
-#include "simulator_resource_model.h"
-
-class JSimulatorResourceModel
-{
-    public:
-        JSimulatorResourceModel(SimulatorResourceModel resModel);
-        JSimulatorResourceModel(SimulatorResourceModelSP resModel);
-
-        static jobject toJava(JNIEnv *env, jlong nativeHandle);
-        static void toJava(JNIEnv *env, jobject thiz, jlong nativeHandle);
-        static bool getResourceModel(JNIEnv *env, jobject thiz, SimulatorResourceModel &resModel);
-        static SimulatorResourceModelSP getResourceModelPtr(JNIEnv *env, jobject thiz);
-
-    private:
-        SimulatorResourceModel m_resourceModel;
-        SimulatorResourceModelSP m_resModelPtr;
-};
-
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorResourceModel_create
-(JNIEnv *, jobject);
 
-JNIEXPORT jint JNICALL
-Java_org_oic_simulator_SimulatorResourceModel_size
-(JNIEnv *, jobject);
-
-JNIEXPORT jobject JNICALL
-Java_org_oic_simulator_SimulatorResourceModel_getAttributes
-(JNIEnv *, jobject);
-
-JNIEXPORT jobject JNICALL
-Java_org_oic_simulator_SimulatorResourceModel_getAttribute
-(JNIEnv *, jobject, jstring);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorResourceModel_addAttributeInt
-(JNIEnv *, jobject, jstring, jint);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorResourceModel_addAttributeDouble
-(JNIEnv *, jobject, jstring, jdouble);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorResourceModel_addAttributeBoolean
-(JNIEnv *, jobject, jstring, jboolean);
+#include "simulator_resource_model.h"
 
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorResourceModel_addAttributeString
-(JNIEnv *, jobject, jstring, jstring);
+jobject SimulatorResourceModelToJava(JNIEnv *env,
+                                     const SimulatorResourceModel &resModel);
 
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorResourceModel_dispose
-(JNIEnv *, jobject);
+bool SimulatorResourceModelToCpp(JNIEnv *env, jobject jResModel,
+                                 SimulatorResourceModel &resModel);
 
+jobject AttributeValueToJava(JNIEnv *env, const AttributeValueVariant &value);
 
-#ifdef __cplusplus
-}
-#endif
+bool AttributeValueToCpp(JNIEnv *env, jobject jAttributeValue,
+                         AttributeValueVariant &jValue);
 
 #endif
diff --git a/service/simulator/java/jni/simulator_resource_model_schema_jni.cpp b/service/simulator/java/jni/simulator_resource_model_schema_jni.cpp
new file mode 100644 (file)
index 0000000..d7e42a1
--- /dev/null
@@ -0,0 +1,609 @@
+/******************************************************************
+ *
+ * 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 "simulator_resource_model_schema_jni.h"
+#include "simulator_utils_jni.h"
+#include "jni_string.h"
+
+static AttributeProperty::Type getType(JNIEnv *env, jobject &jProperty)
+{
+    static jmethodID getTypeMID = env->GetMethodID(
+                                      gSimulatorClassRefs.attributePropertyCls, "getType",
+                                      "()Lorg/oic/simulator/AttributeProperty$Type;");
+
+    static jmethodID ordinalMID = env->GetMethodID(
+                                      gSimulatorClassRefs.attributePropertyTypeCls, "ordinal", "()I");
+
+    jobject jType = env->CallObjectMethod(jProperty, getTypeMID);
+    int ordinal = env->CallIntMethod(jType, ordinalMID);
+    return AttributeProperty::Type(ordinal);
+}
+
+class JniIntegerProperty
+{
+    public:
+        static jobject toJava(JNIEnv *env, const std::shared_ptr<IntegerProperty> &property)
+        {
+            if (!property)
+                return nullptr;
+
+            // Create Java IntegerProperty.Builder object
+            jobject jPropertyBuilder = nullptr;
+            static jmethodID builderCtor = env->GetMethodID(
+                                               gSimulatorClassRefs.integerPropertyBuilderCls, "<init>", "()V");
+            jPropertyBuilder = env->NewObject(gSimulatorClassRefs.integerPropertyBuilderCls, builderCtor);
+
+            // Set default value
+            static jmethodID setDefaultValueMID = env->GetMethodID(
+                    gSimulatorClassRefs.integerPropertyBuilderCls, "setDefaultValue", "(I)V");
+            env->CallVoidMethod(jPropertyBuilder, setDefaultValueMID, property->getDefaultValue());
+
+            // Set Range or enum value set
+            if (property->hasRange())
+            {
+                int min = 0;
+                int max = 0;
+                property->getRange(min, max);
+
+                static jmethodID setRangeMID = env->GetMethodID(
+                                                   gSimulatorClassRefs.integerPropertyBuilderCls, "setRange", "(II)V");
+                env->CallVoidMethod(jPropertyBuilder, setRangeMID, min, max);
+            }
+            else if (property->hasValues())
+            {
+                std::vector<int> values;
+                property->getValues(values);
+                jintArray jIntArray = env->NewIntArray(values.size());
+                env->SetIntArrayRegion(jIntArray, 0, values.size(), reinterpret_cast<const jint *>(&values[0]));
+
+                static jmethodID setValuesMID = env->GetMethodID(
+                                                    gSimulatorClassRefs.integerPropertyBuilderCls, "setValues", "([I)V");
+                env->CallVoidMethod(jPropertyBuilder, setValuesMID, jIntArray);
+            }
+
+            // Create Java IntegerProperty object
+            static jmethodID buildMID = env->GetMethodID(
+                                            gSimulatorClassRefs.integerPropertyBuilderCls, "build", "()Lorg/oic/simulator/IntegerProperty;");
+            return env->CallObjectMethod(jPropertyBuilder, buildMID);
+        }
+
+        static std::shared_ptr<IntegerProperty> toCpp(JNIEnv *env, jobject &jProperty)
+        {
+            static jfieldID defaultValueFID = env->GetFieldID(gSimulatorClassRefs.integerPropertyCls,
+                                              "mDefaultValue", "I");
+            static jfieldID hasRangeFID = env->GetFieldID(gSimulatorClassRefs.integerPropertyCls,
+                                          "mHasRange", "Z");
+
+            jint defaultValue = env->GetIntField(jProperty, defaultValueFID);
+            jboolean hasRange = env->GetBooleanField(jProperty, hasRangeFID);
+
+            std::shared_ptr<IntegerProperty> integerProperty =
+                IntegerProperty::build(defaultValue);
+
+            if (hasRange)
+            {
+                static jfieldID minFID = env->GetFieldID(gSimulatorClassRefs.integerPropertyCls,
+                                         "mMin", "I");
+                static jfieldID maxFID = env->GetFieldID(gSimulatorClassRefs.integerPropertyCls,
+                                         "mMax", "I");
+
+                jint min = env->GetIntField(jProperty, minFID);
+                jint max = env->GetIntField(jProperty, maxFID);
+                integerProperty->setRange(min, max);
+            }
+            else
+            {
+                static jfieldID valuesFID = env->GetFieldID(gSimulatorClassRefs.integerPropertyCls,
+                                            "mValues", "[I");
+                jintArray jValues = (jintArray) env->GetObjectField(jProperty, valuesFID);
+                if (jValues)
+                {
+                    std::vector<int> values;
+                    jint *jIntArray = env->GetIntArrayElements(jValues, NULL);
+                    size_t length = env->GetArrayLength(jValues);
+                    for (size_t index = 0; index < length; index++)
+                    {
+                        values.push_back(jIntArray[index]);
+                    }
+                    integerProperty->setValues(values);
+
+                    env->ReleaseIntArrayElements(jValues, jIntArray, 0);
+                }
+            }
+
+            return integerProperty;
+        }
+};
+
+class JniDoubleProperty
+{
+    public:
+        static jobject toJava(JNIEnv *env, const std::shared_ptr<DoubleProperty> &property)
+        {
+            if (!property)
+                return nullptr;
+
+            // Create Java DoubleProperty.Builder object
+            jobject jPropertyBuilder = nullptr;
+            static jmethodID builderCtor = env->GetMethodID(
+                                               gSimulatorClassRefs.doublePropertyBuilderCls, "<init>", "()V");
+            jPropertyBuilder = env->NewObject(gSimulatorClassRefs.doublePropertyBuilderCls, builderCtor);
+
+            // Set default value
+            static jmethodID setDefaultValueMID = env->GetMethodID(
+                    gSimulatorClassRefs.doublePropertyBuilderCls, "setDefaultValue", "(D)V");
+            env->CallVoidMethod(jPropertyBuilder, setDefaultValueMID, property->getDefaultValue());
+
+            // Set Range or enum value set
+            if (property->hasRange())
+            {
+                double min = 0.0;
+                double max = 0.0;
+                property->getRange(min, max);
+
+                static jmethodID setRangeMID = env->GetMethodID(
+                                                   gSimulatorClassRefs.doublePropertyBuilderCls, "setRange", "(DD)V");
+                env->CallVoidMethod(jPropertyBuilder, setRangeMID, min, max);
+            }
+            else if (property->hasValues())
+            {
+                std::vector<double> values;
+                property->getValues(values);
+                jdoubleArray jDoubleArray = env->NewDoubleArray(values.size());
+                env->SetDoubleArrayRegion(jDoubleArray, 0, values.size(),
+                                          reinterpret_cast<const jdouble *>(&values[0]));
+
+                static jmethodID setValuesMID = env->GetMethodID(
+                                                    gSimulatorClassRefs.doublePropertyBuilderCls, "setValues", "([D)V");
+                env->CallVoidMethod(jPropertyBuilder, setValuesMID, jDoubleArray);
+            }
+
+            // Create Java DoubleProperty object
+            static jmethodID buildMID = env->GetMethodID(
+                                            gSimulatorClassRefs.doublePropertyBuilderCls, "build", "()Lorg/oic/simulator/DoubleProperty;");
+            return env->CallObjectMethod(jPropertyBuilder, buildMID);
+        }
+
+        static std::shared_ptr<DoubleProperty> toCpp(JNIEnv *env, jobject &jProperty)
+        {
+            static jfieldID defaultValueFID = env->GetFieldID(gSimulatorClassRefs.doublePropertyCls,
+                                              "mDefaultValue", "D");
+            static jfieldID hasRangeFID = env->GetFieldID(gSimulatorClassRefs.doublePropertyCls,
+                                          "mHasRange", "Z");
+
+            jdouble defaultValue = env->GetDoubleField(jProperty, defaultValueFID);
+            jboolean hasRange = env->GetBooleanField(jProperty, hasRangeFID);
+
+            std::shared_ptr<DoubleProperty> doubleProperty =
+                DoubleProperty::build(defaultValue);
+
+            if (hasRange)
+            {
+                static jfieldID minFID = env->GetFieldID(gSimulatorClassRefs.doublePropertyCls,
+                                         "mMin", "D");
+                static jfieldID maxFID = env->GetFieldID(gSimulatorClassRefs.doublePropertyCls,
+                                         "mMax", "D");
+
+                jdouble min = env->GetDoubleField(jProperty, minFID);
+                jdouble max = env->GetDoubleField(jProperty, maxFID);
+                doubleProperty->setRange(min, max);
+            }
+            else
+            {
+                static jfieldID valuesFID = env->GetFieldID(gSimulatorClassRefs.doublePropertyCls,
+                                            "mValues", "[D");
+                jdoubleArray jValues = (jdoubleArray) env->GetObjectField(jProperty, valuesFID);
+                if (jValues)
+                {
+                    std::vector<double> values;
+                    jdouble *jDoubleArray = env->GetDoubleArrayElements(jValues, NULL);
+                    size_t length = env->GetArrayLength(jValues);
+                    for (size_t index = 0; index < length; index++)
+                    {
+                        values.push_back(jDoubleArray[index]);
+                    }
+                    doubleProperty->setValues(values);
+
+                    env->ReleaseDoubleArrayElements(jValues, jDoubleArray, 0);
+                }
+            }
+
+            return doubleProperty;
+        }
+};
+
+class JniBooleanProperty
+{
+    public:
+        static jobject toJava(JNIEnv *env, const std::shared_ptr<BooleanProperty> &property)
+        {
+            if (!property)
+                return nullptr;
+
+            // Create Java BooleanProperty.Builder object
+            jobject jPropertyBuilder = nullptr;
+            static jmethodID builderCtor = env->GetMethodID(
+                                               gSimulatorClassRefs.booleanPropertyBuilderCls, "<init>", "()V");
+            jPropertyBuilder = env->NewObject(gSimulatorClassRefs.booleanPropertyBuilderCls, builderCtor);
+
+            // Set default value
+            static jmethodID setDefaultValueMID = env->GetMethodID(
+                    gSimulatorClassRefs.booleanPropertyBuilderCls, "setDefaultValue", "(Z)V");
+            env->CallVoidMethod(jPropertyBuilder, setDefaultValueMID, property->getDefaultValue());
+
+            // Create Java BooleanProperty object
+            static jmethodID buildMID = env->GetMethodID(
+                                            gSimulatorClassRefs.booleanPropertyBuilderCls, "build", "()Lorg/oic/simulator/BooleanProperty;");
+            return env->CallObjectMethod(jPropertyBuilder, buildMID);
+        }
+
+        static std::shared_ptr<BooleanProperty> toCpp(JNIEnv *env, jobject &jProperty)
+        {
+            static jfieldID defaultValueFID = env->GetFieldID(gSimulatorClassRefs.booleanPropertyCls,
+                                              "mDefaultValue", "Z");
+
+            jboolean defaultValue = env->GetBooleanField(jProperty, defaultValueFID);
+            return BooleanProperty::build(defaultValue);
+        }
+};
+
+class JniStringProperty
+{
+    public:
+        static jobject toJava(JNIEnv *env, const std::shared_ptr<StringProperty> &property)
+        {
+            if (!property)
+                return nullptr;
+
+            // Create Java StringProperty.Builder object
+            jobject jPropertyBuilder = nullptr;
+            static jmethodID builderCtor = env->GetMethodID(
+                                               gSimulatorClassRefs.stringPropertyBuilderCls, "<init>", "()V");
+            jPropertyBuilder = env->NewObject(gSimulatorClassRefs.stringPropertyBuilderCls, builderCtor);
+
+            // Set default value
+            static jmethodID setDefaultValueMID = env->GetMethodID(
+                    gSimulatorClassRefs.stringPropertyBuilderCls, "setDefaultValue", "(Ljava/lang/String;)V");
+            jstring jDefaultValue = env->NewStringUTF(property->getDefaultValue().c_str());
+            env->CallVoidMethod(jPropertyBuilder, setDefaultValueMID, jDefaultValue);
+
+            // Set Range or enum value set
+            if (property->hasRange())
+            {
+                size_t min = 0;
+                size_t max = 0;
+                property->getRange(min, max);
+
+                static jmethodID setRangeMID = env->GetMethodID(
+                                                   gSimulatorClassRefs.stringPropertyBuilderCls, "setRange", "(II)V");
+                env->CallVoidMethod(jPropertyBuilder, setRangeMID, static_cast<jint>(min),
+                                    static_cast<jint>(max));
+            }
+            else if (property->hasValues())
+            {
+                std::vector<std::string> values;
+                property->getValues(values);
+                jobjectArray jStringArray = env->NewObjectArray(values.size(), gSimulatorClassRefs.stringCls,
+                                            nullptr);
+
+                for (size_t index = 0; index < values.size(); index++)
+                {
+                    jstring element = env->NewStringUTF(values[index].c_str());
+                    env->SetObjectArrayElement(jStringArray, index, element);
+                }
+
+                static jmethodID setValuesMID = env->GetMethodID(
+                                                    gSimulatorClassRefs.stringPropertyBuilderCls, "setValues", "([Ljava/lang/String;)V");
+                env->CallVoidMethod(jPropertyBuilder, setValuesMID, jStringArray);
+            }
+
+            // Create Java StringProperty object
+            static jmethodID buildMID = env->GetMethodID(
+                                            gSimulatorClassRefs.stringPropertyBuilderCls, "build", "()Lorg/oic/simulator/StringProperty;");
+            return env->CallObjectMethod(jPropertyBuilder, buildMID);
+        }
+
+        static std::shared_ptr<StringProperty> toCpp(JNIEnv *env, jobject &jProperty)
+        {
+            static jfieldID defaultValueFID = env->GetFieldID(gSimulatorClassRefs.stringPropertyCls,
+                                              "mDefaultValue", "Ljava/lang/String;");
+            static jfieldID hasRangeFID = env->GetFieldID(gSimulatorClassRefs.stringPropertyCls,
+                                          "mHasRange", "Z");
+
+            jstring defaultValue = (jstring) env->GetObjectField(jProperty, defaultValueFID);
+            jboolean hasRange = env->GetBooleanField(jProperty, hasRangeFID);
+
+            std::shared_ptr<StringProperty> stringProperty =
+                StringProperty::build(JniString(env, defaultValue).get());
+
+            if (hasRange)
+            {
+                static jfieldID minFID = env->GetFieldID(gSimulatorClassRefs.stringPropertyCls,
+                                         "mMin", "I");
+                static jfieldID maxFID = env->GetFieldID(gSimulatorClassRefs.stringPropertyCls,
+                                         "mMax", "I");
+
+                jint min = env->GetIntField(jProperty, minFID);
+                jint max = env->GetIntField(jProperty, maxFID);
+                if (min >= 0 && max >= 0)
+                    stringProperty->setRange(static_cast<size_t>(min), static_cast<size_t>(max));
+            }
+            else
+            {
+                static jfieldID valuesFID = env->GetFieldID(gSimulatorClassRefs.stringPropertyCls,
+                                            "mValues", "[Ljava/lang/String;");
+                jobjectArray jValues = (jobjectArray) env->GetObjectField(jProperty, valuesFID);
+                if (jValues)
+                {
+                    std::vector<std::string> values;
+                    size_t length = env->GetArrayLength(jValues);
+                    for (size_t index = 0; index < length; index++)
+                    {
+                        jstring jValue = (jstring) env->GetObjectArrayElement(jValues, index);
+                        values.push_back(JniString(env, jValue).get());
+                    }
+                    stringProperty->setValues(values);
+                }
+            }
+
+            return stringProperty;
+        }
+};
+
+class JniArrayProperty
+{
+    public:
+        static jobject toJava(JNIEnv *env, const std::shared_ptr<ArrayProperty> &property)
+        {
+            if (!property)
+                return nullptr;
+
+            // Create Java ArrayProperty.Builder object
+            jobject jPropertyBuilder = nullptr;
+            static jmethodID builderCtor = env->GetMethodID(
+                                               gSimulatorClassRefs.arrayPropertyBuilderCls, "<init>", "()V");
+            jPropertyBuilder = env->NewObject(gSimulatorClassRefs.arrayPropertyBuilderCls, builderCtor);
+
+            // Set variable size propety
+            if (property->isVariable())
+            {
+                static jmethodID setVariableMID = env->GetMethodID(
+                                                      gSimulatorClassRefs.arrayPropertyBuilderCls, "setVariableSize", "(Z)V");
+                env->CallVoidMethod(jPropertyBuilder, setVariableMID, property->isVariable());
+            }
+
+            // Set unique propety
+            if (property->isUnique())
+            {
+                static jmethodID setUniqueMID = env->GetMethodID(
+                                                    gSimulatorClassRefs.arrayPropertyBuilderCls, "setUnique", "(Z)V");
+                env->CallVoidMethod(jPropertyBuilder, setUniqueMID, property->isUnique());
+            }
+
+            // Set range property
+            if (property->hasRange())
+            {
+                size_t min = property->getMinItems();
+                size_t max = property->getMaxItems();
+
+                static jmethodID setRangeMID = env->GetMethodID(
+                                                   gSimulatorClassRefs.arrayPropertyBuilderCls, "setRange", "(II)V");
+                env->CallVoidMethod(jPropertyBuilder, setRangeMID, static_cast<jint>(min),
+                                    static_cast<jint>(max));
+            }
+
+            // Set element property
+            jobject jElementProperty = AttributePropertyToJava(env, property->getElementProperty());
+            static jmethodID setElementPropertyMID = env->GetMethodID(
+                        gSimulatorClassRefs.arrayPropertyBuilderCls, "setElementProperty",
+                        "(Lorg/oic/simulator/AttributeProperty;)V");
+            env->CallVoidMethod(jPropertyBuilder, setElementPropertyMID, jElementProperty);
+
+            // Create Java ArrayProperty object
+            static jmethodID buildMID = env->GetMethodID(
+                                            gSimulatorClassRefs.arrayPropertyBuilderCls, "build", "()Lorg/oic/simulator/ArrayProperty;");
+            return env->CallObjectMethod(jPropertyBuilder, buildMID);
+        }
+
+        static std::shared_ptr<ArrayProperty> toCpp(JNIEnv *env, jobject &jProperty)
+        {
+            static jfieldID hasRangeFID = env->GetFieldID(gSimulatorClassRefs.arrayPropertyCls,
+                                          "mHasRange", "Z");
+            static jfieldID variableFID = env->GetFieldID(gSimulatorClassRefs.arrayPropertyCls,
+                                          "mIsVariableSize", "Z");
+            static jfieldID uniqueFID = env->GetFieldID(gSimulatorClassRefs.arrayPropertyCls,
+                                        "mIsUnique", "Z");
+            static jfieldID elementPropertyFID = env->GetFieldID(gSimulatorClassRefs.arrayPropertyCls,
+                                                 "mElementProperty", "Lorg/oic/simulator/AttributeProperty;");
+
+            jboolean hasRange = env->GetBooleanField(jProperty, hasRangeFID);
+            jboolean isVariable = env->GetBooleanField(jProperty, variableFID);
+            jboolean isUnique = env->GetBooleanField(jProperty, uniqueFID);
+            jobject jElementProperty = env->GetObjectField(jProperty, elementPropertyFID);
+
+            std::shared_ptr<ArrayProperty> arrayProperty = ArrayProperty::build();
+
+            arrayProperty->setVariable(isVariable);
+            arrayProperty->setUnique(isUnique);
+
+            if (hasRange)
+            {
+                static jfieldID minFID = env->GetFieldID(gSimulatorClassRefs.arrayPropertyCls,
+                                         "mMin", "I");
+                static jfieldID maxFID = env->GetFieldID(gSimulatorClassRefs.arrayPropertyCls,
+                                         "mMax", "I");
+
+                jint min = env->GetIntField(jProperty, minFID);
+                jint max = env->GetIntField(jProperty, maxFID);
+                if (min >= 0 && max >= 0)
+                    arrayProperty->setRange(static_cast<size_t>(min), static_cast<size_t>(max));
+            }
+
+            if (jElementProperty)
+            {
+                arrayProperty->setElementProperty(AttributePropertyToCpp(env, jElementProperty));
+            }
+
+            return arrayProperty;
+        }
+};
+
+class JniModelProperty
+{
+    public:
+        static jobject toJava(JNIEnv *env, const std::shared_ptr<ModelProperty> &property)
+        {
+            if (!property)
+                return nullptr;
+
+            // Create Java ModelProperty object
+            jobject jModelProperty = nullptr;
+            static jmethodID modelPropertyCtor = env->GetMethodID(
+                    gSimulatorClassRefs.modelPropertyCls, "<init>", "()V");
+            jModelProperty = env->NewObject(gSimulatorClassRefs.modelPropertyCls, modelPropertyCtor);
+
+            // Set child propeties
+            for (auto &propertyEntry : property->getChildProperties())
+            {
+                jstring jAttrName = env->NewStringUTF(propertyEntry.first.c_str());
+                jobject jProperty = AttributePropertyToJava(env, propertyEntry.second);
+                jboolean required = property->isRequired(propertyEntry.first);
+
+                static jmethodID addMID = env->GetMethodID(
+                                              gSimulatorClassRefs.modelPropertyCls, "add",
+                                              "(Ljava/lang/String;Lorg/oic/simulator/AttributeProperty;Z)Z");
+                env->CallBooleanMethod(jModelProperty, addMID, jAttrName, jProperty, required);
+            }
+
+            return jModelProperty;
+        }
+
+        static std::shared_ptr<ModelProperty> toCpp(JNIEnv *env, jobject &jProperty)
+        {
+            static jfieldID childPropertiesFID = env->GetFieldID(gSimulatorClassRefs.modelPropertyCls,
+                                                 "mChildProperties", "Ljava/util/Map;");
+            static jmethodID isRequiredMID = env->GetMethodID(gSimulatorClassRefs.modelPropertyCls,
+                                             "isRequired", "()Z");
+            static jmethodID entrySetMID = env->GetMethodID(gSimulatorClassRefs.mapCls,
+                                           "entrySet", "()Ljava/util/Set;");
+            static jmethodID iteratorMID = env->GetMethodID(gSimulatorClassRefs.setCls,
+                                           "iterator", "()Ljava/util/Iterator;");
+            static jmethodID hasNextMID = env->GetMethodID(gSimulatorClassRefs.iteratorCls,
+                                          "hasNext", "()Z");
+            static jmethodID nextMID = env->GetMethodID(gSimulatorClassRefs.iteratorCls,
+                                       "next", "()Ljava/lang/Object;");
+            static jmethodID getKeyMID = env->GetMethodID(gSimulatorClassRefs.mapEntryCls,
+                                         "getKey", "()Ljava/lang/Object;");
+            static jmethodID getValueMID = env->GetMethodID(gSimulatorClassRefs.mapEntryCls,
+                                           "getValue", "()Ljava/lang/Object;");
+
+            std::shared_ptr<ModelProperty> modelProperty = ModelProperty::build();
+            jobject jChildProperties = env->GetObjectField(jProperty, childPropertiesFID);
+            if (jChildProperties)
+            {
+                jobject entrySet = env->CallObjectMethod(jChildProperties, entrySetMID);
+                jobject iterator = env->CallObjectMethod(entrySet, iteratorMID);
+                if (entrySet && iterator)
+                {
+                    while (env->CallBooleanMethod(iterator, hasNextMID))
+                    {
+                        jobject entry = env->CallObjectMethod(iterator, nextMID);
+                        jstring key = (jstring) env->CallObjectMethod(entry, getKeyMID);
+                        jobject value = env->CallObjectMethod(entry, getValueMID);
+                        jboolean isRequired = env->CallBooleanMethod(jProperty, isRequiredMID, key);
+
+                        modelProperty->add(JniString(env, key).get(),
+                                           AttributePropertyToCpp(env, value), isRequired);
+
+                        env->DeleteLocalRef(entry);
+                        env->DeleteLocalRef(key);
+                        env->DeleteLocalRef(value);
+                    }
+                }
+            }
+
+            return modelProperty;
+        }
+};
+
+jobject AttributePropertyToJava(JNIEnv *env,
+                                const std::shared_ptr<AttributeProperty> &property)
+{
+    if (!property)
+        return nullptr;
+
+    if (property->isInteger())
+    {
+        return JniIntegerProperty::toJava(env, property->asInteger());
+    }
+    else if (property->isDouble())
+    {
+        return JniDoubleProperty::toJava(env, property->asDouble());
+    }
+    else if (property->isBoolean())
+    {
+        return JniBooleanProperty::toJava(env, property->asBoolean());
+    }
+    else if (property->isString())
+    {
+        return JniStringProperty::toJava(env, property->asString());
+    }
+    else if (property->isArray())
+    {
+        return JniArrayProperty::toJava(env, property->asArray());
+    }
+    else if (property->isModel())
+    {
+        return JniModelProperty::toJava(env, property->asModel());
+    }
+
+    return nullptr; // Control should never reach here
+}
+
+std::shared_ptr<AttributeProperty> AttributePropertyToCpp(JNIEnv *env,
+        jobject &jProperty)
+{
+    if (!jProperty)
+        return nullptr;
+
+    switch (getType(env, jProperty))
+    {
+        case AttributeProperty::Type::INTEGER:
+            return JniIntegerProperty::toCpp(env, jProperty);
+
+        case AttributeProperty::Type::DOUBLE:
+            return JniDoubleProperty::toCpp(env, jProperty);
+
+        case AttributeProperty::Type::BOOLEAN:
+            return JniBooleanProperty::toCpp(env, jProperty);
+
+        case AttributeProperty::Type::STRING:
+            return JniStringProperty::toCpp(env, jProperty);
+
+        case AttributeProperty::Type::ARRAY:
+            return JniArrayProperty::toCpp(env, jProperty);
+
+        case AttributeProperty::Type::MODEL:
+            return JniModelProperty::toCpp(env, jProperty);
+    }
+
+    return nullptr; // Control should never reach here
+}
+
diff --git a/service/simulator/java/jni/simulator_resource_model_schema_jni.h b/service/simulator/java/jni/simulator_resource_model_schema_jni.h
new file mode 100644 (file)
index 0000000..2c26a3b
--- /dev/null
@@ -0,0 +1,34 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_RESOURCE_MODEL_SCHEMA_JNI_H_
+#define SIMULATOR_RESOURCE_MODEL_SCHEMA_JNI_H_
+
+#include <jni.h>
+
+#include "simulator_resource_model_schema.h"
+
+jobject AttributePropertyToJava(JNIEnv *env,
+                                const std::shared_ptr<AttributeProperty> &property);
+
+std::shared_ptr<AttributeProperty> AttributePropertyToCpp(JNIEnv *env,
+        jobject &jProperty);
+
+#endif
diff --git a/service/simulator/java/jni/simulator_resource_server_jni.cpp b/service/simulator/java/jni/simulator_resource_server_jni.cpp
deleted file mode 100644 (file)
index 209ef47..0000000
+++ /dev/null
@@ -1,840 +0,0 @@
-/******************************************************************
- *
- * 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 "simulator_resource_server_jni.h"
-#include "simulator_resource_jni_util.h"
-#include "simulator_common_jni.h"
-#include "simulator_resource_model_jni.h"
-#include "simulator_jni_utils.h"
-#include "simulator_logger.h"
-#include "simulator_jni_utils.h"
-
-extern SimulatorClassRefs gSimulatorClassRefs;
-
-JniSimulatorResource::JniSimulatorResource(SimulatorResourceServerSP &resource)
-    : m_sharedResource(resource) {}
-
-SimulatorResourceServerSP JniSimulatorResource::getJniSimulatorResourceSP(JNIEnv *env,
-        jobject thiz)
-{
-    JniSimulatorResource *resource = GetHandle<JniSimulatorResource>(env, thiz);
-    if (env->ExceptionCheck())
-    {
-        return NULL;
-    }
-    return resource->m_sharedResource;
-}
-
-jobject JniSimulatorResource::toJava(JNIEnv *env, jlong resource)
-{
-    jobject resourceObj = (jobject) env->NewObject(gSimulatorClassRefs.classSimulatorResource,
-                          gSimulatorClassRefs.classSimulatorResourceCtor, resource);
-    if (NULL == resourceObj)
-    {
-        return NULL;
-    }
-    return resourceObj;
-}
-
-void JniSimulatorResource::setResourceInfo(JNIEnv *env, jobject jobj)
-{
-    if (!env || !jobj)
-        return;
-
-    std::string uri = m_sharedResource->getURI();
-    std::string resourceType = m_sharedResource->getResourceType();
-    std::string name = m_sharedResource->getName();
-    std::string interfaceType = m_sharedResource->getInterfaceType();
-
-    jfieldID fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorResource, "resourceURI",
-                                       "Ljava/lang/String;");
-    jstring jUri = env->NewStringUTF(uri.c_str());
-    env->SetObjectField(jobj, fieldID, jUri);
-
-    fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorResource, "resourceName",
-                              "Ljava/lang/String;");
-    jstring jName = env->NewStringUTF(name.c_str());
-    env->SetObjectField(jobj, fieldID, jName);
-
-    fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorResource, "resourceType",
-                              "Ljava/lang/String;");
-    jstring jResourceType = env->NewStringUTF(resourceType.c_str());
-    env->SetObjectField(jobj, fieldID, jResourceType);
-
-    fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorResource, "interfaceType",
-                              "Ljava/lang/String;");
-    jstring jInterfaceType = env->NewStringUTF(interfaceType.c_str());
-    env->SetObjectField(jobj, fieldID, jInterfaceType);
-
-    env->DeleteLocalRef(jUri);
-    env->DeleteLocalRef(jName);
-    env->DeleteLocalRef(jResourceType);
-    env->DeleteLocalRef(jInterfaceType);
-}
-
-void onAutomationComplete(jweak jlistenerRef, const std::string &uri,
-                          const int automationID)
-{
-    JNIEnv *env = getEnv();
-    if (nullptr == env)
-        return;
-
-    jobject autoCompleteListener = env->NewLocalRef(jlistenerRef);
-    if (!autoCompleteListener)
-    {
-        releaseEnv();
-        return;
-    }
-
-    jclass autoCompleteCls = env->GetObjectClass(autoCompleteListener);
-    if (!autoCompleteCls)
-    {
-        releaseEnv();
-        return;
-    }
-
-    jmethodID autoCompleteMId = env->GetMethodID(autoCompleteCls, "onAutomationComplete",
-                                "(Ljava/lang/String;I)V");
-    if (!autoCompleteMId)
-    {
-        releaseEnv();
-        return;
-    }
-
-    jstring jUri = env->NewStringUTF(uri.c_str());
-
-    env->CallVoidMethod(autoCompleteListener, autoCompleteMId, jUri, automationID);
-    if ((env)->ExceptionCheck())
-    {
-        releaseEnv();
-        return;
-    }
-
-    env->DeleteLocalRef(jUri);
-
-    releaseEnv();
-}
-
-JNIEXPORT jobject JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_getModel
-(JNIEnv *env, jobject object)
-{
-    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return nullptr;
-    }
-
-    SimulatorResourceModel resModel = resource->getModel();
-    JSimulatorResourceModel *model = new JSimulatorResourceModel(resModel);
-    jobject jModel = JSimulatorResourceModel::toJava(env, reinterpret_cast<jlong>(model));
-    return jModel;
-}
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeInteger
-(JNIEnv *env, jobject jobject, jstring jKey, jint jValue)
-{
-    if (!jKey)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!");
-        return;
-    }
-
-    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
-                                         jobject);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
-
-    std::string str = env->GetStringUTFChars(jKey, NULL);
-    SimulatorResourceModel::Attribute att;
-    att.setName(str);
-    att.setValue(static_cast<int>(jValue));
-    resource->addAttribute(att);
-}
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeDouble
-(JNIEnv *env, jobject jobject, jstring jKey, jdouble jValue)
-{
-    if (!jKey)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!");
-        return;
-    }
-
-    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
-                                         jobject);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
-
-    std::string str = env->GetStringUTFChars(jKey, NULL);
-    SimulatorResourceModel::Attribute att;
-    att.setName(str);
-    att.setValue(static_cast<double>(jValue));
-    resource->addAttribute(att);
-}
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeBoolean
-(JNIEnv *env, jobject jobject, jstring jKey, jboolean jValue)
-{
-    if (!jKey)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!");
-        return;
-    }
-
-    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
-                                         jobject);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
-
-    std::string str = env->GetStringUTFChars(jKey, NULL);
-    SimulatorResourceModel::Attribute att;
-    att.setName(str);
-    att.setValue(static_cast<bool>(jValue));
-    resource->addAttribute(att);
-}
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeString
-(JNIEnv *env, jobject jobject, jstring jKey, jstring jValue)
-{
-    if (!jKey)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!");
-        return;
-    }
-
-    if (!jValue)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Attribute value cannot be null!");
-        return;
-    }
-
-    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
-                                         jobject);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
-
-    std::string key = env->GetStringUTFChars(jKey, NULL);
-    std::string value = env->GetStringUTFChars(jValue, NULL);
-    SimulatorResourceModel::Attribute att;
-    att.setName(key);
-    att.setValue(value);
-    resource->addAttribute(att);
-}
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeInteger
-(JNIEnv *env, jobject jobject, jstring jKey, jint jValue)
-{
-    if (!jKey)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!");
-        return;
-    }
-
-    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
-                                         jobject);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
-
-    std::string str = env->GetStringUTFChars(jKey, NULL);
-    resource->updateAttributeValue(str, static_cast<int>(jValue));
-}
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeDouble
-(JNIEnv *env, jobject jobject, jstring jKey, jdouble jValue)
-{
-    if (!jKey)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!");
-        return;
-    }
-
-    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
-                                         jobject);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
-
-    std::string str = env->GetStringUTFChars(jKey, NULL);
-    resource->updateAttributeValue(str, static_cast<double>(jValue));
-}
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeBoolean
-(JNIEnv *env, jobject jobject, jstring jKey, jboolean jValue)
-{
-    if (!jKey)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!");
-        return;
-    }
-
-    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
-                                         jobject);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
-
-    std::string str = env->GetStringUTFChars(jKey, NULL);
-    resource->updateAttributeValue(str, static_cast<bool>(jValue));
-}
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeString
-(JNIEnv *env, jobject jobject, jstring jKey, jstring jValue)
-{
-    if (!jKey)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!");
-        return;
-    }
-
-    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
-                                         jobject);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
-
-    std::string key = env->GetStringUTFChars(jKey, NULL);
-    std::string value = env->GetStringUTFChars(jValue, NULL);
-
-    resource->updateAttributeValue(key, value);
-}
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeFromAllowedValues
-(JNIEnv *env, jobject object, jstring attrName, jint index)
-{
-    if (!attrName || index < 0)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid parameter!");
-        return;
-    }
-
-    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
-
-    const char *attrNameCStr = env->GetStringUTFChars(attrName, NULL);
-    if (!attrNameCStr)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "String error!");
-        return;
-    }
-
-    resource->updateAttributeValue(attrNameCStr, static_cast<int>(index));
-    env->ReleaseStringUTFChars(attrName, attrNameCStr);
-}
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setRange
-(JNIEnv *env, jobject object, jstring attrName, jint min, jint max)
-{
-    if (!attrName)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid parameter!");
-        return;
-    }
-
-    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
-
-    const char *attrNameCStr = env->GetStringUTFChars(attrName, NULL);
-    if (!attrNameCStr)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "String error!");
-        return;
-    }
-
-    resource->setRange(attrNameCStr, static_cast<int>(min), static_cast<int>(max));
-    env->ReleaseStringUTFChars(attrName, attrNameCStr);
-}
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setAllowedValuesInteger
-(JNIEnv *env, jobject object, jstring jKey, jobject jAllowedValues)
-{
-    if (!jKey || !jAllowedValues)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid parameter!");
-        return;
-    }
-
-    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
-
-    const char *keyCStr = env->GetStringUTFChars(jKey, NULL);
-    if (!keyCStr)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "String error!");
-        return;
-    }
-
-    resource->setAllowedValues(keyCStr, convertIntegerVector(env, jAllowedValues));
-    env->ReleaseStringUTFChars(jKey, keyCStr);
-}
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setAllowedValuesDouble
-(JNIEnv *env, jobject object, jstring jKey, jobject jAllowedValues)
-{
-    if (!jKey || !jAllowedValues)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid parameter!");
-        return;
-    }
-
-    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
-
-    const char *keyCStr = env->GetStringUTFChars(jKey, NULL);
-    if (!keyCStr)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "String error!");
-        return;
-    }
-
-    resource->setAllowedValues(keyCStr, convertDoubleVector(env, jAllowedValues));
-    env->ReleaseStringUTFChars(jKey, keyCStr);
-}
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setAllowedValuesString
-(JNIEnv *env, jobject object, jstring jKey, jobject jAllowedValues)
-{
-    if (!jKey || !jAllowedValues)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid parameter!");
-        return;
-    }
-
-    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
-
-    const char *keyCStr = env->GetStringUTFChars(jKey, NULL);
-    if (!keyCStr)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "String error!");
-        return;
-    }
-
-    resource->setAllowedValues(keyCStr, convertStringVector(env, jAllowedValues));
-    env->ReleaseStringUTFChars(jKey, keyCStr);
-}
-
-JNIEXPORT jint JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startResourceAutomation
-(JNIEnv *env, jobject object, jint automationType, jint updateInterval, jobject listener)
-{
-    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return SIMULATOR_BAD_OBJECT;
-    }
-
-    if (!listener)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK,
-                                  "Start Resource Automation failed! Callback not set");
-        return SIMULATOR_INVALID_CALLBACK;
-    }
-
-    jweak jlistenerRef = env->NewWeakGlobalRef(listener);
-    updateCompleteCallback callback =  [jlistenerRef](const std::string & uri, const int automationID)
-    {
-        onAutomationComplete(jlistenerRef, uri, automationID);
-    };
-
-    AutomationType type = AutomationType::NORMAL;
-    if (1 == automationType)
-    {
-        type = AutomationType::RECURRENT;
-    }
-
-    int automationId = -1;
-
-    try
-    {
-        automationId = resource->startUpdateAutomation(type, updateInterval, callback);
-    }
-    catch (InvalidArgsException &e)
-    {
-        throwInvalidArgsException(env, e.code(), e.what());
-    }
-    catch (SimulatorException &e)
-    {
-        throwSimulatorException(env, e.code(), e.what());
-    }
-    catch (...)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
-    }
-    return automationId;
-}
-
-JNIEXPORT jint JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startAttributeAutomation
-(JNIEnv *env, jobject object, jstring attrName, jint automationType, jint updateInterval, jobject listener)
-{
-    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return SIMULATOR_BAD_OBJECT;
-    }
-
-    if (!attrName)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!");
-        return SIMULATOR_INVALID_PARAM;
-    }
-
-    if (!listener)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK,
-                                  "Start Attribute Automation failed! Callback not set");
-        return SIMULATOR_INVALID_CALLBACK;
-    }
-
-    jweak jlistenerRef = env->NewWeakGlobalRef(listener);
-    updateCompleteCallback callback =  [jlistenerRef](const std::string & uri, const int automationID)
-    {
-        onAutomationComplete(jlistenerRef, uri, automationID);
-    };
-
-    const char *attrNamePtr = env->GetStringUTFChars(attrName, NULL);
-
-    AutomationType type = AutomationType::NORMAL;
-    if (1 == automationType)
-    {
-        type = AutomationType::RECURRENT;
-    }
-
-    int automationId = -1;
-    try
-    {
-        automationId = resource->startUpdateAutomation(attrNamePtr, type, updateInterval, callback);
-    }
-    catch (InvalidArgsException &e)
-    {
-        throwInvalidArgsException(env, e.code(), e.what());
-        return -1;
-    }
-    catch (SimulatorException &e)
-    {
-        throwSimulatorException(env, e.code(), e.what());
-        return -1;
-    }
-    catch (...)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
-        return -1;
-    }
-    env->ReleaseStringUTFChars(attrName, attrNamePtr);
-    return automationId;
-}
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_stopAutomation
-(JNIEnv *env, jobject object, jint automationId)
-{
-    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
-
-    try
-    {
-        resource->stopUpdateAutomation(automationId);
-    }
-    catch (SimulatorException &e)
-    {
-        throwSimulatorException(env, e.code(), e.what());
-    }
-    catch (...)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
-    }
-
-    SIM_LOG(ILogger::INFO, "Automation has been forcibly stopped.")
-}
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_removeAttribute
-(JNIEnv *env, jobject jobject, jstring jKey)
-{
-    if (!jKey)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!");
-        return;
-    }
-
-    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
-                                         jobject);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
-
-    std::string str = env->GetStringUTFChars(jKey, NULL);
-    try
-    {
-        resource->removeAttribute(str);
-    }
-    catch (InvalidArgsException &e)
-    {
-        throwInvalidArgsException(env, e.code(), e.what());
-        return;
-    }
-    catch (SimulatorException &e)
-    {
-        throwSimulatorException(env, e.code(), e.what());
-        return;
-    }
-    catch (...)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
-        return;
-    }
-}
-
-JNIEXPORT jobjectArray JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_getObserversList
-(JNIEnv *env, jobject object)
-{
-    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return nullptr;
-    }
-
-    std::vector<ObserverInfo> observersList;
-    observersList = resource->getObserversList();
-
-    // Construct the object array and send it java layer
-    jobjectArray jobserversArray = env->NewObjectArray(observersList.size(),
-                                   gSimulatorClassRefs.classObserverInfo, NULL);
-    if (jobserversArray)
-    {
-        for (size_t i = 0; i < observersList.size(); i++)
-        {
-            jstring jaddress = env->NewStringUTF(observersList[i].address.c_str());
-            jobject jobserver = (jobject) env->NewObject(gSimulatorClassRefs.classObserverInfo,
-                                gSimulatorClassRefs.classObserverInfoCtor, observersList[i].id,
-                                jaddress, observersList[i].port);
-
-            env->SetObjectArrayElement(jobserversArray, i, jobserver);
-            env->DeleteLocalRef(jaddress);
-        }
-    }
-
-    return jobserversArray;
-}
-
-void onObserverChange(jweak jlistenerRef, const std::string &uri,
-                      ObservationStatus state, const ObserverInfo &observerInfo)
-{
-    JNIEnv *env = getEnv();
-    if (nullptr == env)
-        return;
-
-    jobject observerChangeListener = env->NewLocalRef(jlistenerRef);
-    if (!observerChangeListener)
-    {
-        releaseEnv();
-        return;
-    }
-
-    jclass observerChangeCls = env->GetObjectClass(observerChangeListener);
-    if (!observerChangeCls)
-    {
-        releaseEnv();
-        return;
-    }
-
-    jmethodID observerChangeMId = env->GetMethodID(observerChangeCls, "onObserverChanged",
-                                  "(Ljava/lang/String;ILorg/oic/simulator/serviceprovider/ObserverInfo;)V");
-    if (!observerChangeMId)
-    {
-        releaseEnv();
-        return;
-    }
-
-    // Convert URI
-    jstring jUri = env->NewStringUTF(uri.c_str());
-
-    // Convert state
-    jint jstate = (state == ObservationStatus::OBSERVE_REGISTER) ? 0 : 1;
-
-    // Construct the java object of observerinfo
-    jstring jaddress = env->NewStringUTF(observerInfo.address.c_str());
-    jobject jobserver = (jobject) env->NewObject(gSimulatorClassRefs.classObserverInfo,
-                        gSimulatorClassRefs.classObserverInfoCtor, observerInfo.id,
-                        jaddress, observerInfo.port);
-
-    env->CallVoidMethod(observerChangeListener, observerChangeMId, jUri, jstate, jobserver);
-    env->DeleteLocalRef(jaddress);
-    if ((env)->ExceptionCheck())
-    {
-        releaseEnv();
-        return;
-    }
-
-    env->DeleteLocalRef(jUri);
-
-    releaseEnv();
-}
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setObserverCallback
-(JNIEnv *env, jobject object, jobject jcallback)
-{
-    if (!jcallback)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Callback not set");
-        return;
-    }
-
-    jweak jlistenerRef = env->NewWeakGlobalRef(jcallback);
-    SimulatorResourceServer::ObserverCB callback =  [jlistenerRef](const std::string & uri,
-            ObservationStatus state, const ObserverInfo & observerInfo)
-    {
-        onObserverChange(jlistenerRef, uri, state, observerInfo);
-    };
-
-    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
-
-    resource->setObserverCallback(callback);
-}
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_notifyObserver
-(JNIEnv *env, jobject object, jint jId)
-{
-    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
-
-    try
-    {
-        resource->notify(jId);
-    }
-    catch (SimulatorException &e)
-    {
-        throwSimulatorException(env, e.code(), e.what());
-    }
-    catch (...)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
-    }
-}
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_notifyAllObservers
-(JNIEnv *env, jobject object)
-{
-    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
-
-    try
-    {
-        resource->notifyAll();
-    }
-    catch (SimulatorException &e)
-    {
-        throwSimulatorException(env, e.code(), e.what());
-    }
-    catch (...)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
-    }
-}
-
-JNIEXPORT void JNICALL Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_dispose
-(JNIEnv *env, jobject thiz)
-{
-    JniSimulatorResource *resource = GetHandle<JniSimulatorResource>(env, thiz);
-    delete resource;
-}
-
diff --git a/service/simulator/java/jni/simulator_resource_server_jni.h b/service/simulator/java/jni/simulator_resource_server_jni.h
deleted file mode 100644 (file)
index 298071a..0000000
+++ /dev/null
@@ -1,137 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-#ifndef SIMULATOR_RESOURCE_JNI_H_
-#define SIMULATOR_RESOURCE_JNI_H_
-
-#include <jni.h>
-#include "simulator_resource_server.h"
-
-class JniSimulatorResource
-{
-    public:
-        JniSimulatorResource(SimulatorResourceServerSP &resource);
-
-        static jobject toJava(JNIEnv *env, jlong resource);
-        void setResourceInfo(JNIEnv *env, jobject jobj);
-        static SimulatorResourceServerSP getJniSimulatorResourceSP(JNIEnv *env, jobject thiz);
-    private:
-        SimulatorResourceServerSP m_sharedResource;
-};
-
-
-#ifdef __cplusplus
-extern "C" {
-
-JNIEXPORT jobject JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_getModel
-(JNIEnv *, jobject);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeInteger
-(JNIEnv *, jobject, jstring, jint);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeDouble
-(JNIEnv *, jobject, jstring, jdouble);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeBoolean
-(JNIEnv *, jobject, jstring, jboolean);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeString
-(JNIEnv *, jobject, jstring, jstring);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeInteger
-(JNIEnv *, jobject, jstring, jint);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeDouble
-(JNIEnv *, jobject, jstring, jdouble);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeBoolean
-(JNIEnv *, jobject, jstring, jboolean);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeString
-(JNIEnv *, jobject, jstring, jstring);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeFromAllowedValues
-(JNIEnv *, jobject, jstring, jint);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setRange
-(JNIEnv *, jobject, jstring, jint, jint);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setAllowedValuesInteger
-(JNIEnv *, jobject, jstring, jobject);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setAllowedValuesDouble
-(JNIEnv *, jobject, jstring, jobject);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setAllowedValuesString
-(JNIEnv *, jobject, jstring, jobject);
-
-JNIEXPORT jint JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startResourceAutomation
-(JNIEnv *, jobject, jint, jint, jobject);
-
-JNIEXPORT jint JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startAttributeAutomation
-(JNIEnv *, jobject, jstring, jint, jint, jobject);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_stopAutomation
-(JNIEnv *, jobject, jint);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_removeAttribute
-(JNIEnv *, jobject, jstring);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setObserverCallback
-(JNIEnv *env, jobject object, jobject observer);
-
-JNIEXPORT jobjectArray JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_getObserversList
-(JNIEnv *env, jobject object);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_notifyObserver
-(JNIEnv *env, jobject object, jint jId);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_notifyAllObservers
-(JNIEnv *env, jobject object);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_dispose
-(JNIEnv *, jobject);
-
-}
-#endif
-#endif //SIMULATOR_RESOURCE_JNI_H_
diff --git a/service/simulator/java/jni/simulator_resource_utils_jni.cpp b/service/simulator/java/jni/simulator_resource_utils_jni.cpp
new file mode 100644 (file)
index 0000000..10eee4c
--- /dev/null
@@ -0,0 +1,158 @@
+/******************************************************************
+ *
+ * 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 "simulator_resource_utils_jni.h"
+#include "simulator_utils_jni.h"
+#include "jni_sharedobject_holder.h"
+#include "jni_vector.h"
+
+jobject CreateSingleResource(JNIEnv *env, SimulatorResourceSP singleResource)
+{
+    if (!singleResource)
+        return nullptr;
+
+    auto *objectHolder = JniSharedObjectHolder<SimulatorResource>::create(singleResource);
+    if (!objectHolder)
+        return nullptr;
+
+    static jmethodID simulatorSingleResourceCtor = env->GetMethodID(
+                gSimulatorClassRefs.simulatorSingleResourceCls, "<init>", "(J)V");
+
+    jobject resource = (jobject) env->NewObject(gSimulatorClassRefs.simulatorSingleResourceCls,
+                       simulatorSingleResourceCtor, reinterpret_cast<jlong>(objectHolder));
+    if (!resource)
+    {
+        delete objectHolder;
+        return nullptr;
+    }
+
+    return resource;
+}
+
+jobject CreateCollectionResource(JNIEnv *env, SimulatorResourceSP collectionResource)
+{
+    if (!collectionResource)
+        return nullptr;
+
+    auto *objectHolder = JniSharedObjectHolder<SimulatorResource>::create(collectionResource);
+    if (!objectHolder)
+        return nullptr;
+
+    static jmethodID simulatorCollectionResourceCtor = env->GetMethodID(
+                gSimulatorClassRefs.simulatorCollectionResourceCls, "<init>", "(J)V");
+    jobject resource = (jobject) env->NewObject(gSimulatorClassRefs.simulatorCollectionResourceCls,
+                       simulatorCollectionResourceCtor, reinterpret_cast<jlong>(objectHolder));
+    if (!resource)
+    {
+        delete objectHolder;
+        return nullptr;
+    }
+
+    return resource;
+}
+
+jobject CreateSimulatorResource(JNIEnv *env, SimulatorResourceSP resource)
+{
+    if (!resource)
+        return nullptr;
+
+    if (SimulatorResource::Type::COLLECTION_RESOURCE == resource->getType())
+        return CreateCollectionResource(env, resource);
+    return CreateSingleResource(env, resource);
+}
+
+jobject CreateSimulatorResourceVector(JNIEnv *env, std::vector<SimulatorResourceSP> &resources)
+{
+    if (!resources.size())
+        return nullptr;
+
+    jobject vectorObject = JniVector(env).toJava();
+    if (!vectorObject)
+        return nullptr;
+
+    static jmethodID addMethod = env->GetMethodID(gSimulatorClassRefs.vectorCls,
+                                 "add", "(Ljava/lang/Object;)Z");
+
+    for (auto &resource : resources)
+        env->CallBooleanMethod(vectorObject, addMethod, CreateSimulatorResource(env, resource));
+
+    return vectorObject;
+}
+
+jobject CreateSimulatorRemoteResource(JNIEnv *env, SimulatorRemoteResourceSP &remoteResource)
+{
+    if (!remoteResource)
+        return nullptr;
+
+    auto *objectHolder = JniSharedObjectHolder<SimulatorRemoteResource>::create(remoteResource);
+    if (!objectHolder)
+        return nullptr;
+
+    static jmethodID simulatorRemoteResourceCtor = env->GetMethodID(
+                gSimulatorClassRefs.simulatorRemoteResourceCls, "<init>", "(J)V");
+
+    jobject resource = (jobject) env->NewObject(gSimulatorClassRefs.simulatorRemoteResourceCls,
+                       simulatorRemoteResourceCtor, reinterpret_cast<jlong>(objectHolder));
+    if (!resource)
+    {
+        delete objectHolder;
+        return nullptr;
+    }
+
+    // Setting all required fields
+    static jfieldID uriID = env->GetFieldID(gSimulatorClassRefs.simulatorRemoteResourceCls,
+                                            "mUri", "Ljava/lang/String;");
+    static jfieldID connTypeID = env->GetFieldID(gSimulatorClassRefs.simulatorRemoteResourceCls,
+                                 "mConnType", "I");
+    static jfieldID hostID = env->GetFieldID(gSimulatorClassRefs.simulatorRemoteResourceCls,
+                             "mHost", "Ljava/lang/String;");
+    static jfieldID uidID = env->GetFieldID(gSimulatorClassRefs.simulatorRemoteResourceCls,
+                                            "mId", "Ljava/lang/String;");
+    static jfieldID resTypesID = env->GetFieldID(gSimulatorClassRefs.simulatorRemoteResourceCls,
+                                 "mResTypes", "Ljava/util/Vector;");
+    static jfieldID interfacesID = env->GetFieldID(gSimulatorClassRefs.simulatorRemoteResourceCls,
+                                   "mResInterfaces", "Ljava/util/Vector;");
+    static jfieldID isObservableID = env->GetFieldID(gSimulatorClassRefs.simulatorRemoteResourceCls,
+                                     "mIsObservable", "Z");
+
+    jstring uri = env->NewStringUTF(remoteResource->getURI().c_str());
+    env->SetObjectField(resource, uriID, uri);
+
+    jint connType = remoteResource->getConnectivityType();
+    env->SetIntField(resource, connTypeID, connType);
+
+    jstring host = env->NewStringUTF(remoteResource->getHost().c_str());
+    env->SetObjectField(resource, hostID, host);
+
+    jstring uid = env->NewStringUTF(remoteResource->getID().c_str());
+    env->SetObjectField(resource, uidID, uid);
+
+    std::vector<std::string> resourceTypes = remoteResource->getResourceTypes();
+    jobject ResTypes = JniVector(env).toJava(resourceTypes);
+    env->SetObjectField(resource, resTypesID, ResTypes);
+
+    std::vector<std::string> interfaceTypes = remoteResource->getInterface();
+    jobject resInterfaces = JniVector(env).toJava(interfaceTypes);
+    env->SetObjectField(resource, interfacesID, resInterfaces);
+
+    env->SetBooleanField(resource, isObservableID, remoteResource->isObservable());
+
+    return resource;
+}
\ No newline at end of file
diff --git a/service/simulator/java/jni/simulator_resource_utils_jni.h b/service/simulator/java/jni/simulator_resource_utils_jni.h
new file mode 100644 (file)
index 0000000..49a2e8d
--- /dev/null
@@ -0,0 +1,35 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_RESOURCE_UTILS_JNI_H_
+#define SIMULATOR_RESOURCE_UTILS_JNI_H_
+
+#include <jni.h>
+#include "simulator_single_resource.h"
+#include "simulator_collection_resource.h"
+#include "simulator_remote_resource.h"
+
+jobject CreateSingleResource(JNIEnv *env, SimulatorResourceSP singleResource);
+jobject CreateCollectionResource(JNIEnv *env, SimulatorResourceSP collectionResource);
+jobject CreateSimulatorResource(JNIEnv *env, SimulatorResourceSP resource);
+jobject CreateSimulatorResourceVector(JNIEnv *env, std::vector<SimulatorResourceSP> &resources);
+jobject CreateSimulatorRemoteResource(JNIEnv *env, SimulatorRemoteResourceSP &remoteResource);
+
+#endif
diff --git a/service/simulator/java/jni/simulator_single_resource_jni.cpp b/service/simulator/java/jni/simulator_single_resource_jni.cpp
new file mode 100644 (file)
index 0000000..a2dc1a1
--- /dev/null
@@ -0,0 +1,261 @@
+/******************************************************************
+ *
+ * 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 "simulator_resource_model_jni.h"
+#include "simulator_resource_attribute_jni.h"
+#include "simulator_exceptions_jni.h"
+#include "simulator_utils_jni.h"
+#include "jni_sharedobject_holder.h"
+#include "jni_listener_holder.h"
+#include "jni_string.h"
+#include "jni_vector.h"
+
+#include "simulator_single_resource.h"
+
+#define VALIDATE_OBJECT(ENV, OBJECT) if (!OBJECT){ThrowBadObjectException(ENV, "No corresponsing native object!"); return;}
+#define VALIDATE_OBJECT_RET(ENV, OBJECT, RET) if (!OBJECT){ThrowBadObjectException(ENV, "No corresponsing native object!"); return RET;}
+
+static SimulatorSingleResourceSP simulatorSingleResourceToCpp(JNIEnv *env, jobject object)
+{
+    JniSharedObjectHolder<SimulatorSingleResource> *jniResource =
+        getHandle<JniSharedObjectHolder<SimulatorSingleResource>>(env, object);
+    if (jniResource)
+        return jniResource->get();
+    return nullptr;
+}
+
+static AutoUpdateType autoUpdateTypeToCpp(JNIEnv *env, jobject jType)
+{
+    static jmethodID ordinalMID = env->GetMethodID(
+                                      gSimulatorClassRefs.autoUpdateTypeCls, "ordinal", "()I");
+
+    int ordinal = env->CallIntMethod(jType, ordinalMID);
+    return AutoUpdateType(ordinal);
+}
+
+static void onAutoUpdationComplete(jobject listener, const std::string &uri, const int id)
+{
+    JNIEnv *env = GetEnv();
+    if (!env)
+        return;
+
+    jclass listenerCls = env->GetObjectClass(listener);
+    jmethodID listenerMethod = env->GetMethodID(listenerCls, "onUpdateComplete",
+                               "(Ljava/lang/String;I)V");
+
+    jstring jUri = env->NewStringUTF(uri.c_str());
+    env->CallVoidMethod(listener, listenerMethod, jUri, id);
+    ReleaseEnv();
+}
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_server_SimulatorSingleResource_nativeGetAttribute
+(JNIEnv *env, jobject object, jstring jAttrName)
+{
+    VALIDATE_INPUT_RET(env, !jAttrName, "Attribute name is null!", nullptr)
+
+    SimulatorSingleResourceSP singleResource = simulatorSingleResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, singleResource, nullptr)
+
+    JniString jniAttrName(env, jAttrName);
+    SimulatorResourceAttribute attribute;
+    if (singleResource->getAttribute(jniAttrName.get(), attribute))
+        return SimulatorResourceAttributeToJava(env, attribute);
+    return nullptr;
+}
+
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_server_SimulatorSingleResource_nativeGetAttributes
+(JNIEnv *env, jobject object)
+{
+    SimulatorSingleResourceSP singleResource = simulatorSingleResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, singleResource, nullptr)
+
+    return SimulatorResourceAttributesToJava(env, singleResource->getAttributes());
+}
+
+JNIEXPORT jboolean JNICALL
+Java_org_oic_simulator_server_SimulatorSingleResource_nativeAddAttribute
+(JNIEnv *env, jobject object, jobject jResAttribute)
+{
+    VALIDATE_INPUT_RET(env, !jResAttribute, "Resource attribute is null!", false)
+
+    SimulatorSingleResourceSP singleResource = simulatorSingleResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, singleResource, false)
+
+    try
+    {
+        SimulatorResourceAttribute attribute;
+        if (!SimulatorResourceAttributeToCpp(env, jResAttribute, attribute))
+        {
+            ThrowSimulatorException(env, SIMULATOR_ERROR,
+                                    "Failed to covnert SimulatorResourceAttribute java object!");
+            return false;
+        }
+        return singleResource->addAttribute(attribute);
+    }
+    catch (SimulatorException &e)
+    {
+        ThrowSimulatorException(env, e.code(), e.what());
+    }
+
+    return false;
+}
+
+JNIEXPORT jboolean JNICALL
+Java_org_oic_simulator_server_SimulatorSingleResource_nativeUpdateAttribute
+(JNIEnv *env, jobject object, jstring jAttrName, jobject jAttrValue)
+{
+    VALIDATE_INPUT_RET(env, !jAttrName, "Attribute name is null!", false)
+    VALIDATE_INPUT_RET(env, !jAttrValue, "Attribute value is null!", false)
+
+    SimulatorSingleResourceSP singleResource = simulatorSingleResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, singleResource, false)
+
+    AttributeValueVariant value;
+    if (!AttributeValueToCpp(env, jAttrValue, value))
+    {
+        ThrowSimulatorException(env, SIMULATOR_ERROR,
+                                "Failed to covnert AttributeValue java object!");
+        return false;
+    }
+
+    SimulatorResourceAttribute attribute(JniString(env, jAttrName).get());
+    attribute.setValue(value);
+    return singleResource->updateAttributeValue(attribute);
+}
+
+JNIEXPORT jboolean JNICALL
+Java_org_oic_simulator_server_SimulatorSingleResource_nativeRemoveAttribute
+(JNIEnv *env, jobject object, jstring jAttrName)
+{
+    VALIDATE_INPUT_RET(env, !jAttrName, "Attribute name is null!", false)
+
+    SimulatorSingleResourceSP singleResource = simulatorSingleResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, singleResource, false)
+
+    try
+    {
+        JniString jniAttrName(env, jAttrName);
+        return singleResource->removeAttribute(jniAttrName.get());
+    }
+    catch (InvalidArgsException &e)
+    {
+        ThrowInvalidArgsException(env, e.code(), e.what());
+    }
+
+    return false;
+}
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_server_SimulatorSingleResource_nativeStartResourceUpdation
+(JNIEnv *env, jobject object, jobject jType, jint jInterval, jobject jListener)
+{
+    VALIDATE_CALLBACK_RET(env, jListener, -1)
+
+    SimulatorSingleResourceSP singleResource = simulatorSingleResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, singleResource, -1)
+
+    jobject listenerRef = env->NewGlobalRef(jListener);
+    SimulatorSingleResource::AutoUpdateCompleteCallback callback =  [listenerRef](
+                const std::string & uri, const int id)
+    {
+        onAutoUpdationComplete(listenerRef, uri, id);
+    };
+
+    try
+    {
+        AutoUpdateType autoUpdateType = autoUpdateTypeToCpp(env, jType);
+        return singleResource->startResourceUpdation(autoUpdateType, jInterval, callback);
+    }
+    catch (InvalidArgsException &e)
+    {
+        ThrowInvalidArgsException(env, e.code(), e.what());
+    }
+    catch (SimulatorException &e)
+    {
+        ThrowSimulatorException(env, e.code(), e.what());
+    }
+
+    return -1;
+}
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_server_SimulatorSingleResource_nativeStartAttributeUpdation
+(JNIEnv *env, jobject object, jstring jAttrName, jobject jType, jint jInterval, jobject jListener)
+{
+    VALIDATE_INPUT_RET(env, !jAttrName, "Attribute name is null!", -1)
+    VALIDATE_CALLBACK_RET(env, jListener, -1)
+
+    SimulatorSingleResourceSP singleResource = simulatorSingleResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, singleResource, -1)
+
+    jobject listenerRef = env->NewGlobalRef(jListener);
+    SimulatorSingleResource::AutoUpdateCompleteCallback callback =
+        [listenerRef](const std::string & uri, const int id)
+    {
+        onAutoUpdationComplete(listenerRef, uri, id);
+    };
+
+    try
+    {
+        JniString jniAttrName(env, jAttrName);
+        AutoUpdateType autoUpdateType = autoUpdateTypeToCpp(env, jType);
+        return singleResource->startAttributeUpdation(jniAttrName.get(), autoUpdateType,
+                jInterval, callback);
+    }
+    catch (InvalidArgsException &e)
+    {
+        ThrowInvalidArgsException(env, e.code(), e.what());
+    }
+    catch (SimulatorException &e)
+    {
+        ThrowSimulatorException(env, e.code(), e.what());
+    }
+
+    return -1;
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorSingleResource_nativeStopUpdation
+(JNIEnv *env, jobject object, jint id)
+{
+    SimulatorSingleResourceSP singleResource = simulatorSingleResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, singleResource)
+
+    singleResource->stopUpdation(id);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorSingleResource_nativeDispose
+(JNIEnv *env, jobject object)
+{
+    JniSharedObjectHolder<SimulatorSingleResource> *resource =
+        getHandle<JniSharedObjectHolder<SimulatorSingleResource>>(env, object);
+    delete resource;
+}
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/service/simulator/java/jni/simulator_utils_jni.cpp b/service/simulator/java/jni/simulator_utils_jni.cpp
new file mode 100644 (file)
index 0000000..ce154f7
--- /dev/null
@@ -0,0 +1,301 @@
+/******************************************************************
+ *
+ * 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 "simulator_utils_jni.h"
+
+jobject SimulatorResultToJava(JNIEnv *env, SimulatorResult errorCode)
+{
+    switch (errorCode)
+    {
+        case SIMULATOR_OK:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_OK", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_RESOURCE_CREATED:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_RESOURCE_CREATED", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_RESOURCE_DELETED:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_RESOURCE_DELETED", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_CONTINUE:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_CONTINUE", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_INVALID_URI:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_INVALID_URI", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_INVALID_QUERY:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_INVALID_QUERY", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_INVALID_IP:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_INVALID_IP", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_INVALID_PORT:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_INVALID_PORT", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_INVALID_CALLBACK:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_INVALID_CALLBACK", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_INVALID_METHOD:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_INVALID_METHOD", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_INVALID_PARAM:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_INVALID_PARAM", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_INVALID_OBSERVE_PARAM:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_INVALID_OBSERVE_PARAM", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_NO_MEMORY:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_NO_MEMORY", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_COMM_ERROR:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_COMM_ERROR", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_TIMEOUT:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_TIMEOUT", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_ADAPTER_NOT_ENABLED:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_ADAPTER_NOT_ENABLED", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_NOTIMPL:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_NOTIMPL", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_NO_RESOURCE:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_NO_RESOURCE", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_RESOURCE_ERROR:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_RESOURCE_ERROR", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_SLOW_RESOURCE:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_SLOW_RESOURCE", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_DUPLICATE_REQUEST:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_DUPLICATE_REQUEST", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_NO_OBSERVERS:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_NO_OBSERVERS", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_OBSERVER_NOT_FOUND:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_OBSERVER_NOT_FOUND", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_VIRTUAL_DO_NOT_HANDLE:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_VIRTUAL_DO_NOT_HANDLE", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_INVALID_OPTION:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_INVALID_OPTION", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_MALFORMED_RESPONSE:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_MALFORMED_RESPONSE", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_PERSISTENT_BUFFER_REQUIRED:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_PERSISTENT_BUFFER_REQUIRED", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_INVALID_REQUEST_HANDLE:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_INVALID_REQUEST_HANDLE", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_INVALID_DEVICE_INFO:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_INVALID_DEVICE_INFO", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_INVALID_JSON:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_INVALID_JSON", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_UNAUTHORIZED_REQ:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_UNAUTHORIZED_REQ", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+#ifdef WITH_PRESENCE
+        case SIMULATOR_PRESENCE_STOPPED:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_PRESENCE_STOPPED", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_PRESENCE_TIMEOUT:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_PRESENCE_TIMEOUT", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_PRESENCE_DO_NOT_HANDLE:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_PRESENCE_DO_NOT_HANDLE", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+#endif
+        case SIMULATOR_INVALID_TYPE:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_INVALID_TYPE", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_NOT_SUPPORTED:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_NOT_SUPPORTED", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_OPERATION_NOT_ALLOWED:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_OPERATION_NOT_ALLOWED", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_OPERATION_IN_PROGRESS:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_OPERATION_IN_PROGRESS", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_INVALID_RESPONSE_CODE:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_INVALID_RESPONSE_CODE", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_UKNOWN_PROPERTY:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_UKNOWN_PROPERTY", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_TYPE_MISMATCH:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_TYPE_MISMATCH", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_BAD_VALUE:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_BAD_VALUE", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_BAD_OBJECT:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_BAD_OBJECT", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        case SIMULATOR_BAD_SCHEMA:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                                          "SIMULATOR_BAD_SCHEMA", "Lorg/oic/simulator/SimulatorResult;");
+                return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+            }
+        default:
+            break;
+    }
+
+    static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls,
+                              "SIMULATOR_ERROR", "Lorg/oic/simulator/SimulatorResult;");
+    return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID);
+}
+
diff --git a/service/simulator/java/jni/simulator_utils_jni.h b/service/simulator/java/jni/simulator_utils_jni.h
new file mode 100644 (file)
index 0000000..85aa4a4
--- /dev/null
@@ -0,0 +1,127 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_UTILS_JNI_H_
+#define SIMULATOR_UTILS_JNI_H_
+
+#include <jni.h>
+#include "simulator_error_codes.h"
+
+typedef struct
+{
+    jclass objectCls;
+    jclass integerCls;
+    jclass doubleCls;
+    jclass booleanCls;
+    jclass stringCls;
+    jclass hashMapCls;
+    jclass vectorCls;
+    jclass mapCls;
+    jclass mapEntryCls;
+    jclass setCls;
+    jclass iteratorCls;
+
+    jclass simulatorResourceCls;
+    jclass simulatorResourceTypeCls;
+    jclass simulatorSingleResourceCls;
+    jclass simulatorCollectionResourceCls;
+    jclass simulatorResourceModelCls;
+    jclass simulatorResourceAttributeCls;
+    jclass attributeValueCls;
+    jclass attributeValueTypeCls;
+    jclass attributeTypeInfoCls;
+    jclass attributePropertyCls;
+    jclass attributePropertyTypeCls;
+    jclass integerPropertyCls;
+    jclass integerPropertyBuilderCls;
+    jclass doublePropertyCls;
+    jclass doublePropertyBuilderCls;
+    jclass booleanPropertyCls;
+    jclass booleanPropertyBuilderCls;
+    jclass stringPropertyCls;
+    jclass stringPropertyBuilderCls;
+    jclass arrayPropertyCls;
+    jclass arrayPropertyBuilderCls;
+    jclass modelPropertyCls;
+    jclass autoUpdateTypeCls;
+
+    jclass simulatorRemoteResourceCls;
+    jclass requestTypeCls;
+    jclass observerCls;
+    jclass deviceInfoCls;
+    jclass platformInfoCls;
+    jclass simulatorRequestModelCls;
+
+    jclass simulatorExceptionCls;
+    jclass invalidArgsExceptionCls;
+    jclass noSupportExceptionCls;
+    jclass operationInProgressExceptionCls;
+    jclass simulatorResultCls;
+
+    jclass integer1DArrayCls;
+    jclass integer2DArrayCls;
+    jclass integer3DArrayCls;
+    jclass double1DArrayCls;
+    jclass double2DArrayCls;
+    jclass double3DArrayCls;
+    jclass boolean1DArrayCls;
+    jclass boolean2DArrayCls;
+    jclass boolean3DArrayCls;
+    jclass string1DArrayCls;
+    jclass string2DArrayCls;
+    jclass string3DArrayCls;
+    jclass simulatorResModel1DArrayCls;
+    jclass simulatorResModel2DArrayCls;
+    jclass simulatorResModel3DArrayCls;
+} SimulatorClassRefs;
+
+#define VALIDATE_INPUT(ENV, CONDITION, MSG) if (CONDITION) {ThrowInvalidArgsException(ENV, SIMULATOR_INVALID_PARAM, MSG); return;}
+#define VALIDATE_INPUT_RET(ENV, CONDITION, MSG, RET) if (CONDITION) {ThrowInvalidArgsException(ENV, SIMULATOR_INVALID_PARAM, MSG); return RET;}
+
+#define VALIDATE_CALLBACK(ENV, CALLBACK) if (!CALLBACK){ThrowInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); return;}
+#define VALIDATE_CALLBACK_RET(ENV, CALLBACK, RET) if (!CALLBACK){ThrowInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); return RET;}
+
+static jfieldID getHandleField(JNIEnv *env, jobject jobj)
+{
+    jclass cls = env->GetObjectClass(jobj);
+    return env->GetFieldID(cls, "mNativeHandle", "J");
+}
+
+template <typename T>
+static T *getHandle(JNIEnv *env, jobject jobj)
+{
+    jlong handle = env->GetLongField(jobj, getHandleField(env, jobj));
+    return reinterpret_cast<T *>(handle);
+}
+
+template <typename T>
+static void setHandle(JNIEnv *env, jobject jobj, T *type)
+{
+    jlong handle = reinterpret_cast<jlong>(type);
+    env->SetLongField(jobj, getHandleField(env, jobj), handle);
+}
+
+extern JNIEnv *GetEnv();
+extern void ReleaseEnv();
+extern SimulatorClassRefs gSimulatorClassRefs;
+
+jobject SimulatorResultToJava(JNIEnv *env, SimulatorResult errorCode);
+
+#endif
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/ArrayProperty.java b/service/simulator/java/sdk/src/org/oic/simulator/ArrayProperty.java
new file mode 100644 (file)
index 0000000..cf90e61
--- /dev/null
@@ -0,0 +1,123 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator;
+
+public class ArrayProperty extends AttributeProperty {
+
+    private int               mMin;
+    private int               mMax;
+    private boolean           mIsVariableSize;
+    private boolean           mIsUnique;
+    private AttributeProperty mElementProperty;
+    private boolean           mHasRange = false;
+
+    private ArrayProperty(int min, int max, boolean variableSize,
+            boolean unique, AttributeProperty elementProperty) {
+        super(Type.ARRAY);
+        mMin = min;
+        mMax = max;
+        mIsVariableSize = variableSize;
+        mIsUnique = unique;
+        mElementProperty = elementProperty;
+        mHasRange = true;
+    }
+
+    private ArrayProperty(boolean variableSize, boolean unique,
+            AttributeProperty elementProperty) {
+        super(Type.ARRAY);
+        mIsVariableSize = variableSize;
+        mIsUnique = unique;
+        mElementProperty = elementProperty;
+    }
+
+    @Override
+    public boolean isArray() {
+        return true;
+    }
+
+    @Override
+    public ArrayProperty asArray() {
+        return this;
+    }
+
+    public boolean hasRange() {
+        return mHasRange;
+    }
+
+    public int minItems() {
+        return mMin;
+    }
+
+    public int maxItems() {
+        return mMax;
+    }
+
+    public boolean isVariable() {
+        return mIsVariableSize;
+    }
+
+    public boolean isUnique() {
+        return mIsUnique;
+    }
+
+    public AttributeProperty getElementProperty() {
+        return mElementProperty;
+    }
+
+    @Override
+    public boolean validate(AttributeValue value) {
+        return new ArrayValueValidator(this).validate(value);
+    }
+
+    public static class Builder {
+        private int               mMin;
+        private int               mMax;
+        private boolean           mIsVariableSize  = false;
+        private boolean           mIsUnique        = false;
+        private AttributeProperty mElementProperty = null;
+        private boolean           mHasRange        = false;
+
+        public void setRange(int minItems, int maxItems) {
+            mMin = minItems;
+            mMax = maxItems;
+            mHasRange = true;
+        }
+
+        public void setVariableSize(boolean state) {
+            mIsVariableSize = state;
+        }
+
+        public void setUnique(boolean state) {
+            mIsUnique = state;
+        }
+
+        public void setElementProperty(AttributeProperty property) {
+            mElementProperty = property;
+        }
+
+        public ArrayProperty build() {
+            if (null == mElementProperty)
+                return null;
+
+            if (mHasRange)
+                return new ArrayProperty(mMin, mMax, mIsVariableSize,
+                        mIsUnique, mElementProperty);
+            return new ArrayProperty(mIsVariableSize, mIsUnique,
+                    mElementProperty);
+        }
+    }
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/ArrayValueValidator.java b/service/simulator/java/sdk/src/org/oic/simulator/ArrayValueValidator.java
new file mode 100644 (file)
index 0000000..d4bbdb3
--- /dev/null
@@ -0,0 +1,545 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator;
+
+import java.util.HashSet;
+import java.util.Set;
+
+class ArrayValueValidator implements
+        AttributeValueVisitor.VisitingMethods<Boolean> {
+
+    private ArrayProperty mProperty = null;
+
+    ArrayValueValidator(ArrayProperty property) {
+        mProperty = property;
+    }
+
+    public boolean validate(AttributeValue value) {
+        AttributeValueVisitor visitor = new AttributeValueVisitor(value, this);
+        return (Boolean) visitor.visit();
+    }
+
+    @Override
+    public Boolean visitingValue(Integer value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Double value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Boolean value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(String value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(SimulatorResourceModel value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Integer[] values) {
+        if (null == mProperty)
+            return false;
+
+        // Validating length of array
+        if (mProperty.hasRange()) {
+            if (values.length < mProperty.minItems()
+                    || (values.length > mProperty.maxItems() && !mProperty
+                            .isVariable())) {
+                return false;
+            }
+        }
+
+        // Validating elements of array
+        AttributeProperty elementProperty = mProperty.getElementProperty();
+        if (!elementProperty.isInteger()) {
+            return false;
+        }
+
+        Set<Integer> uniqueSet = new HashSet<Integer>();
+        for (Integer value : values) {
+            if (mProperty.isUnique() && uniqueSet.add(value) == false) {
+                return false;
+            }
+
+            IntegerProperty intProperty = elementProperty.asInteger();
+            if (null == intProperty) {
+                return false;
+            }
+
+            if (false == intProperty.validate(value))
+                return false;
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(Double[] values) {
+        if (null == mProperty)
+            return false;
+
+        // Validating length of array
+        if (mProperty.hasRange()) {
+            if (values.length < mProperty.minItems()
+                    || (values.length > mProperty.maxItems() && !mProperty
+                            .isVariable())) {
+                return false;
+            }
+        }
+
+        // Validating elements of array
+        AttributeProperty elementProperty = mProperty.getElementProperty();
+        if (!elementProperty.isDouble()) {
+            return false;
+        }
+
+        Set<Double> uniqueSet = new HashSet<Double>();
+        for (Double value : values) {
+            if (mProperty.isUnique() && uniqueSet.add(value) == false) {
+                return false;
+            }
+
+            DoubleProperty dblProperty = elementProperty.asDouble();
+            if (null == dblProperty) {
+                return false;
+            }
+
+            if (false == dblProperty.validate(value))
+                return false;
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(Boolean[] values) {
+        if (null == mProperty)
+            return false;
+
+        // Validating length of array
+        if (mProperty.hasRange()) {
+            if (values.length < mProperty.minItems()
+                    || (values.length > mProperty.maxItems() && !mProperty
+                            .isVariable())) {
+                return false;
+            }
+        }
+
+        // Validating elements of array
+        AttributeProperty elementProperty = mProperty.getElementProperty();
+        if (!elementProperty.isBoolean()) {
+            return false;
+        }
+
+        Set<Boolean> uniqueSet = new HashSet<Boolean>();
+        for (Boolean value : values) {
+            if (mProperty.isUnique() && uniqueSet.add(value) == false) {
+                return false;
+            }
+
+            BooleanProperty boolProperty = elementProperty.asBoolean();
+            if (null == boolProperty) {
+                return false;
+            }
+
+            if (false == boolProperty.validate(value))
+                return false;
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(String[] values) {
+        if (null == mProperty)
+            return false;
+
+        // Validating length of array
+        if (mProperty.hasRange()) {
+            if (values.length < mProperty.minItems()
+                    || (values.length > mProperty.maxItems() && !mProperty
+                            .isVariable())) {
+                return false;
+            }
+        }
+
+        // Validating elements of array
+        AttributeProperty elementProperty = mProperty.getElementProperty();
+        if (!elementProperty.isString()) {
+            return false;
+        }
+
+        Set<String> uniqueSet = new HashSet<String>();
+        for (String value : values) {
+            if (mProperty.isUnique() && uniqueSet.add(value) == false) {
+                return false;
+            }
+
+            StringProperty stringProperty = elementProperty.asString();
+            if (null == stringProperty) {
+                return false;
+            }
+
+            if (false == stringProperty.validate(value))
+                return false;
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(SimulatorResourceModel[] values) {
+        if (null == mProperty)
+            return false;
+
+        // Validating length of array
+        if (mProperty.hasRange()) {
+            if (values.length < mProperty.minItems()
+                    || (values.length > mProperty.maxItems() && !mProperty
+                            .isVariable())) {
+                return false;
+            }
+        }
+
+        // Validating elements of array
+        AttributeProperty elementProperty = mProperty.getElementProperty();
+        if (!elementProperty.isInteger()) {
+            return false;
+        }
+
+        for (SimulatorResourceModel value : values) {
+            ModelProperty modelProperty = elementProperty.asModel();
+            if (null == modelProperty) {
+                return false;
+            }
+
+            if (false == modelProperty.validate(value))
+                return false;
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(Integer[][] values) {
+        if (null == mProperty)
+            return false;
+
+        // Validating length of array
+        if (mProperty.hasRange()) {
+            if (values.length < mProperty.minItems()
+                    || (values.length > mProperty.maxItems() && !mProperty
+                            .isVariable())) {
+                return false;
+            }
+        }
+
+        // Validating elements of array
+        AttributeProperty elementProperty = mProperty.getElementProperty();
+        if (!elementProperty.isArray()) {
+            return false;
+        }
+
+        ArrayValueValidator validator = new ArrayValueValidator(
+                elementProperty.asArray());
+        for (Integer[] value : values) {
+            if (false == validator.visitingValue(value))
+                return false;
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(Double[][] values) {
+        if (null == mProperty)
+            return false;
+
+        // Validating length of array
+        if (mProperty.hasRange()) {
+            if (values.length < mProperty.minItems()
+                    || (values.length > mProperty.maxItems() && !mProperty
+                            .isVariable())) {
+                return false;
+            }
+        }
+
+        // Validating elements of array
+        AttributeProperty elementProperty = mProperty.getElementProperty();
+        if (!elementProperty.isArray()) {
+            return false;
+        }
+
+        ArrayValueValidator validator = new ArrayValueValidator(
+                elementProperty.asArray());
+        for (Double[] value : values) {
+            if (false == validator.visitingValue(value))
+                return false;
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(Boolean[][] values) {
+        if (null == mProperty)
+            return false;
+
+        // Validating length of array
+        if (mProperty.hasRange()) {
+            if (values.length < mProperty.minItems()
+                    || (values.length > mProperty.maxItems() && !mProperty
+                            .isVariable())) {
+                return false;
+            }
+        }
+
+        // Validating elements of array
+        AttributeProperty elementProperty = mProperty.getElementProperty();
+        if (!elementProperty.isArray()) {
+            return false;
+        }
+
+        ArrayValueValidator validator = new ArrayValueValidator(
+                elementProperty.asArray());
+        for (Boolean[] value : values) {
+            if (false == validator.visitingValue(value))
+                return false;
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(String[][] values) {
+        if (null == mProperty)
+            return false;
+
+        // Validating length of array
+        if (mProperty.hasRange()) {
+            if (values.length < mProperty.minItems()
+                    || (values.length > mProperty.maxItems() && !mProperty
+                            .isVariable())) {
+                return false;
+            }
+        }
+
+        // Validating elements of array
+        AttributeProperty elementProperty = mProperty.getElementProperty();
+        if (!elementProperty.isArray()) {
+            return false;
+        }
+
+        ArrayValueValidator validator = new ArrayValueValidator(
+                elementProperty.asArray());
+        for (String[] value : values) {
+            if (false == validator.visitingValue(value))
+                return false;
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(SimulatorResourceModel[][] values) {
+        if (null == mProperty)
+            return false;
+
+        // Validating length of array
+        if (mProperty.hasRange()) {
+            if (values.length < mProperty.minItems()
+                    || (values.length > mProperty.maxItems() && !mProperty
+                            .isVariable())) {
+                return false;
+            }
+        }
+
+        // Validating elements of array
+        AttributeProperty elementProperty = mProperty.getElementProperty();
+        if (!elementProperty.isArray()) {
+            return false;
+        }
+
+        ArrayValueValidator validator = new ArrayValueValidator(
+                elementProperty.asArray());
+        for (SimulatorResourceModel[] value : values) {
+            if (false == validator.visitingValue(value))
+                return false;
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(Integer[][][] values) {
+        if (null == mProperty)
+            return false;
+
+        // Validating length of array
+        if (mProperty.hasRange()) {
+            if (values.length < mProperty.minItems()
+                    || (values.length > mProperty.maxItems() && !mProperty
+                            .isVariable())) {
+                return false;
+            }
+        }
+
+        // Validating elements of array
+        AttributeProperty elementProperty = mProperty.getElementProperty();
+        if (!elementProperty.isArray()) {
+            return false;
+        }
+
+        ArrayValueValidator validator = new ArrayValueValidator(
+                elementProperty.asArray());
+        for (Integer[][] value : values) {
+            if (false == validator.visitingValue(value))
+                return false;
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(Double[][][] values) {
+        if (null == mProperty)
+            return false;
+
+        // Validating length of array
+        if (mProperty.hasRange()) {
+            if (values.length < mProperty.minItems()
+                    || (values.length > mProperty.maxItems() && !mProperty
+                            .isVariable())) {
+                return false;
+            }
+        }
+
+        // Validating elements of array
+        AttributeProperty elementProperty = mProperty.getElementProperty();
+        if (!elementProperty.isArray()) {
+            return false;
+        }
+
+        ArrayValueValidator validator = new ArrayValueValidator(
+                elementProperty.asArray());
+        for (Double[][] value : values) {
+            if (false == validator.visitingValue(value))
+                return false;
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(Boolean[][][] values) {
+        if (null == mProperty)
+            return false;
+
+        // Validating length of array
+        if (mProperty.hasRange()) {
+            if (values.length < mProperty.minItems()
+                    || (values.length > mProperty.maxItems() && !mProperty
+                            .isVariable())) {
+                return false;
+            }
+        }
+
+        // Validating elements of array
+        AttributeProperty elementProperty = mProperty.getElementProperty();
+        if (!elementProperty.isArray()) {
+            return false;
+        }
+
+        ArrayValueValidator validator = new ArrayValueValidator(
+                elementProperty.asArray());
+        for (Boolean[][] value : values) {
+            if (false == validator.visitingValue(value))
+                return false;
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(String[][][] values) {
+        if (null == mProperty)
+            return false;
+
+        // Validating length of array
+        if (mProperty.hasRange()) {
+            if (values.length < mProperty.minItems()
+                    || (values.length > mProperty.maxItems() && !mProperty
+                            .isVariable())) {
+                return false;
+            }
+        }
+
+        // Validating elements of array
+        AttributeProperty elementProperty = mProperty.getElementProperty();
+        if (!elementProperty.isArray()) {
+            return false;
+        }
+
+        ArrayValueValidator validator = new ArrayValueValidator(
+                elementProperty.asArray());
+        for (String[][] value : values) {
+            if (false == validator.visitingValue(value))
+                return false;
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(SimulatorResourceModel[][][] values) {
+        if (null == mProperty)
+            return false;
+
+        // Validating length of array
+        if (mProperty.hasRange()) {
+            if (values.length < mProperty.minItems()
+                    || (values.length > mProperty.maxItems() && !mProperty
+                            .isVariable())) {
+                return false;
+            }
+        }
+
+        // Validating elements of array
+        AttributeProperty elementProperty = mProperty.getElementProperty();
+        if (!elementProperty.isArray()) {
+            return false;
+        }
+
+        ArrayValueValidator validator = new ArrayValueValidator(
+                elementProperty.asArray());
+        for (SimulatorResourceModel[][] value : values) {
+            if (false == validator.visitingValue(value))
+                return false;
+        }
+
+        return true;
+    }
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/AttributeProperty.java b/service/simulator/java/sdk/src/org/oic/simulator/AttributeProperty.java
new file mode 100644 (file)
index 0000000..3015214
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator;
+
+/**
+ * This class represents the resource attribute's value property.
+ */
+public abstract class AttributeProperty {
+
+    public enum Type {
+        INTEGER, DOUBLE, BOOLEAN, STRING, MODEL, ARRAY
+    }
+
+    private Type mType;
+
+    protected AttributeProperty(Type type) {
+        mType = type;
+    }
+
+    public Type getType() {
+        return mType;
+    }
+
+    public boolean isInteger() {
+        return false;
+    }
+
+    public boolean isDouble() {
+        return false;
+    }
+
+    public boolean isBoolean() {
+        return false;
+    }
+
+    public boolean isString() {
+        return false;
+    }
+
+    public boolean isArray() {
+        return false;
+    }
+
+    public boolean isModel() {
+        return false;
+    }
+
+    public IntegerProperty asInteger() {
+        return null;
+    }
+
+    public DoubleProperty asDouble() {
+        return null;
+    }
+
+    public BooleanProperty asBoolean() {
+        return null;
+    }
+
+    public StringProperty asString() {
+        return null;
+    }
+
+    public ArrayProperty asArray() {
+        return null;
+    }
+
+    public ModelProperty asModel() {
+        return null;
+    }
+
+    public abstract boolean validate(AttributeValue value);
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/AttributeValue.java b/service/simulator/java/sdk/src/org/oic/simulator/AttributeValue.java
new file mode 100644 (file)
index 0000000..9298ed9
--- /dev/null
@@ -0,0 +1,503 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator;
+
+/**
+ * This class accommodate different type of values as Object.
+ */
+public class AttributeValue {
+
+    private Object mValue = null;
+
+    /**
+     * Enum to represent value type.
+     */
+    public enum ValueType {
+        UNKNOWN, INTEGER, DOUBLE, BOOLEAN, STRING, RESOURCEMODEL, ARRAY
+    }
+
+    /**
+     * Class which provides the value type information in detail.
+     */
+    public static class TypeInfo {
+        public ValueType mType;
+        public ValueType mBaseType;
+        public int       mDepth;
+
+        /**
+         * Constructs {@link AttributeValue.TypeInfo} with default values.
+         */
+        TypeInfo() {
+            mType = ValueType.UNKNOWN;
+            mBaseType = ValueType.UNKNOWN;
+            mDepth = 0;
+        }
+
+        /**
+         * Constructs {@link AttributeValue.TypeInfo} with given
+         * {AttributeValue.ValueType}.
+         *
+         * @param type
+         *            Value type.
+         */
+        TypeInfo(ValueType type) {
+            mType = type;
+            mBaseType = type;
+            mDepth = 0;
+        }
+
+        /**
+         * Constructs {@link AttributeValue.TypeInfo} with given
+         * {AttributeValue.ValueType}s and depth information.
+         *
+         * @param type
+         *            Value type.
+         * @param baseType
+         *            Value base type. This type is useful when value is of
+         *            array type.
+         * @param depth
+         *            Depth of array type value. This is useful when value is of
+         *            array type.
+         */
+        TypeInfo(ValueType type, ValueType baseType, int depth) {
+            mType = type;
+            mBaseType = baseType;
+            mDepth = depth;
+        }
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with int type value.
+     *
+     * @param value
+     *            int type value.
+     */
+    public AttributeValue(int value) {
+        mValue = new Integer(value);
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with double type value.
+     *
+     * @param value
+     *            double type value.
+     */
+    public AttributeValue(double value) {
+        mValue = new Double(value);
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with boolean type value.
+     *
+     * @param value
+     *            boolean type value.
+     */
+    public AttributeValue(boolean value) {
+        mValue = Boolean.valueOf(value);
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with string type value.
+     *
+     * @param value
+     *            String type value.
+     */
+    public AttributeValue(String value) {
+        mValue = value;
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with SimulatorResourceModel type value.
+     *
+     * @param value
+     *            SimulatorResourceModel type value.
+     */
+    public AttributeValue(SimulatorResourceModel value) {
+        mValue = value;
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with array of int type values.
+     *
+     * @param values
+     *            Array of int type values.
+     */
+    public AttributeValue(int[] values) {
+        Integer[] newValues = new Integer[values.length];
+        for (int i = 0; i < values.length; i++)
+            newValues[i] = Integer.valueOf(values[i]);
+        mValue = newValues;
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with array of Integer type values.
+     *
+     * @param values
+     *            Array of Integer type values.
+     */
+    public AttributeValue(Integer[] values) {
+        mValue = values;
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with array of double type values.
+     *
+     * @param values
+     *            Array of double type values.
+     */
+    public AttributeValue(double[] values) {
+        Double[] newValues = new Double[values.length];
+        for (int i = 0; i < values.length; i++)
+            newValues[i] = Double.valueOf(values[i]);
+        mValue = newValues;
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with array of Double type values.
+     *
+     * @param values
+     *            Array of Double type values.
+     */
+    public AttributeValue(Double[] values) {
+        mValue = values;
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with array of boolean type values.
+     *
+     * @param values
+     *            Array of boolean type values.
+     */
+    public AttributeValue(boolean[] values) {
+        Boolean[] newValues = new Boolean[values.length];
+        for (int i = 0; i < values.length; i++)
+            newValues[i] = Boolean.valueOf(values[i]);
+        mValue = newValues;
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with array of Boolean type values.
+     *
+     * @param values
+     *            Array of Boolean type values.
+     */
+    public AttributeValue(Boolean[] values) {
+        mValue = values;
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with array of String type values.
+     *
+     * @param values
+     *            Array of String type values.
+     */
+    public AttributeValue(String[] values) {
+        mValue = values;
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with array of SimulatorResourceModel
+     * type values.
+     *
+     * @param values
+     *            Array of SimulatorResourceModel type values.
+     */
+    public AttributeValue(SimulatorResourceModel[] values) {
+        mValue = values;
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with 2 dimensional array of int type
+     * values.
+     *
+     * @param values
+     *            2 dimensional array of int type values.
+     */
+    public AttributeValue(int[][] values) {
+        Integer[][] newValues = new Integer[values.length][];
+        for (int i = 0; i < values.length; i++) {
+            newValues[i] = new Integer[values[i].length];
+            for (int j = 0; j < values[i].length; j++) {
+                newValues[i][j] = Integer.valueOf(values[i][j]);
+            }
+        }
+        mValue = newValues;
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with 2 dimensional array of Integer
+     * type values.
+     *
+     * @param values
+     *            2 dimensional array of Integer type values.
+     */
+    public AttributeValue(Integer[][] values) {
+        mValue = values;
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with 2 dimensional array of double type
+     * values.
+     *
+     * @param values
+     *            2 dimensional array of double type values.
+     */
+    public AttributeValue(double[][] values) {
+        Double[][] newValues = new Double[values.length][];
+        for (int i = 0; i < values.length; i++) {
+            newValues[i] = new Double[values[i].length];
+            for (int j = 0; j < values[i].length; j++) {
+                newValues[i][j] = Double.valueOf(values[i][j]);
+            }
+        }
+        mValue = newValues;
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with 2 dimensional array of Double type
+     * values.
+     *
+     * @param values
+     *            2 dimensional array of Double type values.
+     */
+    public AttributeValue(Double[][] values) {
+        mValue = values;
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with 2 dimensional array of boolean
+     * type values.
+     *
+     * @param values
+     *            2 dimensional array of boolean type values.
+     */
+    public AttributeValue(boolean[][] values) {
+        Boolean[][] newValues = new Boolean[values.length][];
+        for (int i = 0; i < values.length; i++) {
+            newValues[i] = new Boolean[values[i].length];
+            for (int j = 0; j < values[i].length; j++) {
+                newValues[i][j] = Boolean.valueOf(values[i][j]);
+            }
+        }
+        mValue = newValues;
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with 2 dimensional array of Boolean
+     * type values.
+     *
+     * @param values
+     *            2 dimensional array of Boolean type values.
+     */
+    public AttributeValue(Boolean[][] values) {
+        mValue = values;
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with 2 dimensional array of String type
+     * values.
+     *
+     * @param values
+     *            2 dimensional array of String type values.
+     */
+    public AttributeValue(String[][] values) {
+        mValue = values;
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with 2 dimensional array of
+     * SimulatorResourceModel type values.
+     *
+     * @param values
+     *            2 dimensional array of SimulatorResourceModel type values.
+     */
+    public AttributeValue(SimulatorResourceModel[][] values) {
+        mValue = values;
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with 3 dimensional array of int type
+     * values.
+     *
+     * @param values
+     *            3 dimensional array of int type values.
+     */
+    public AttributeValue(int[][][] values) {
+        Integer[][][] newValues = new Integer[values.length][][];
+        for (int i = 0; i < values.length; i++) {
+            newValues[i] = new Integer[values[i].length][];
+            for (int j = 0; j < values[i].length; j++) {
+                newValues[i][j] = new Integer[values[i][j].length];
+                for (int k = 0; k < values[j].length; k++) {
+                    newValues[i][j][k] = Integer.valueOf(values[i][j][k]);
+                }
+            }
+        }
+        mValue = newValues;
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with 3 dimensional array of Integer
+     * type values.
+     *
+     * @param values
+     *            3 dimensional array of Integer type values.
+     */
+    public AttributeValue(Integer[][][] values) {
+        mValue = values;
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with 3 dimensional array of double type
+     * values.
+     *
+     * @param values
+     *            3 dimensional array of double type values.
+     */
+    public AttributeValue(double[][][] values) {
+        Double[][][] newValues = new Double[values.length][][];
+        for (int i = 0; i < values.length; i++) {
+            newValues[i] = new Double[values[i].length][];
+            for (int j = 0; j < values[i].length; j++) {
+                newValues[i][j] = new Double[values[i][j].length];
+                for (int k = 0; k < values[j].length; k++) {
+                    newValues[i][j][k] = Double.valueOf(values[i][j][k]);
+                }
+            }
+        }
+        mValue = newValues;
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with 3 dimensional array of Double type
+     * values.
+     *
+     * @param values
+     *            3 dimensional array of Double type values.
+     */
+    public AttributeValue(Double[][][] values) {
+        mValue = values;
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with 3 dimensional array of boolean
+     * type values.
+     *
+     * @param values
+     *            3 dimensional array of boolean type values.
+     */
+    public AttributeValue(boolean[][][] values) {
+        Boolean[][][] newValues = new Boolean[values.length][][];
+        for (int i = 0; i < values.length; i++) {
+            newValues[i] = new Boolean[values[i].length][];
+            for (int j = 0; j < values[i].length; j++) {
+                newValues[i][j] = new Boolean[values[i][j].length];
+                for (int k = 0; k < values[j].length; k++) {
+                    newValues[i][j][k] = Boolean.valueOf(values[i][j][k]);
+                }
+            }
+        }
+        mValue = newValues;
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with 3 dimensional array of Boolean
+     * type values.
+     *
+     * @param values
+     *            3 dimensional array of Boolean type values.
+     */
+    public AttributeValue(Boolean[][][] values) {
+        mValue = values;
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with 3 dimensional array of String type
+     * values.
+     *
+     * @param values
+     *            3 dimensional array of String type values.
+     */
+    public AttributeValue(String[][][] values) {
+        mValue = values;
+    }
+
+    /**
+     * Constructs {@link AttributeValue} with 3 dimensional array of
+     * SimulatorResourceModel type values.
+     *
+     * @param values
+     *            3 dimensional array of SimulatorResourceModel type values.
+     */
+    public AttributeValue(SimulatorResourceModel[][][] values) {
+        mValue = values;
+    }
+
+    /**
+     * API to get value type information.
+     *
+     * @return {@link AttributeValue.TypeInfo}.
+     */
+    public TypeInfo typeInfo() {
+        return createTypeInfo(mValue);
+    }
+
+    /**
+     * API to get value as Object.
+     *
+     * @return Value as Object.
+     */
+    public Object get() {
+        return mValue;
+    }
+
+    private AttributeValue(Object value) {
+        mValue = value;
+    }
+
+    private TypeInfo createTypeInfo(Object value) {
+        TypeInfo typeInfo = new TypeInfo();
+        String className = value.getClass().getName();
+        if (className.contains(Integer.class.getName())) {
+            typeInfo.mBaseType = ValueType.INTEGER;
+            typeInfo.mType = ValueType.INTEGER;
+        } else if (className.contains(Double.class.getName())) {
+            typeInfo.mBaseType = ValueType.DOUBLE;
+            typeInfo.mType = ValueType.DOUBLE;
+        } else if (className.contains(Boolean.class.getName())) {
+            typeInfo.mBaseType = ValueType.BOOLEAN;
+            typeInfo.mType = ValueType.BOOLEAN;
+        } else if (className.contains(String.class.getName())) {
+            typeInfo.mBaseType = ValueType.STRING;
+            typeInfo.mType = ValueType.STRING;
+        } else if (className.contains(SimulatorResourceModel.class.getName())) {
+            typeInfo.mBaseType = ValueType.RESOURCEMODEL;
+            typeInfo.mType = ValueType.RESOURCEMODEL;
+        }
+
+        // For array types
+        if (value.getClass().isArray()) {
+            typeInfo.mType = ValueType.ARRAY;
+            for (char ch : className.toCharArray()) {
+                if (ch == '[')
+                    typeInfo.mDepth++;
+            }
+        }
+
+        return typeInfo;
+    }
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/AttributeValueVisitor.java b/service/simulator/java/sdk/src/org/oic/simulator/AttributeValueVisitor.java
new file mode 100644 (file)
index 0000000..1dac15b
--- /dev/null
@@ -0,0 +1,164 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator;
+
+/**
+ * This class visits the given attribute value and invokes the right method
+ * based on the type of the attribute value.
+ */
+public class AttributeValueVisitor {
+    private AttributeValue  mValue;
+    private VisitingMethods mListener;
+
+    public interface VisitingMethods<T extends Object> {
+        public T visitingValue(Integer value);
+
+        public T visitingValue(Double value);
+
+        public T visitingValue(Boolean value);
+
+        public T visitingValue(String value);
+
+        public T visitingValue(SimulatorResourceModel value);
+
+        public T visitingValue(Integer[] values);
+
+        public T visitingValue(Double[] values);
+
+        public T visitingValue(Boolean[] values);
+
+        public T visitingValue(String[] values);
+
+        public T visitingValue(SimulatorResourceModel[] values);
+
+        public T visitingValue(Integer[][] values);
+
+        public T visitingValue(Double[][] values);
+
+        public T visitingValue(Boolean[][] values);
+
+        public T visitingValue(String[][] values);
+
+        public T visitingValue(SimulatorResourceModel[][] values);
+
+        public T visitingValue(Integer[][][] values);
+
+        public T visitingValue(Double[][][] values);
+
+        public T visitingValue(Boolean[][][] values);
+
+        public T visitingValue(String[][][] values);
+
+        public T visitingValue(SimulatorResourceModel[][][] values);
+    }
+
+    /**
+     * Constructs {@link AttributeValueVisitor} from the given
+     * {@link AttributeValue} and the implementation of the
+     * {@link VisitingMethods} interface.
+     *
+     * @param value
+     *            {@link AttributeValue} object.
+     * @param listener
+     *            Implementation of {@link VisitingMethods} interface.
+     */
+    public AttributeValueVisitor(AttributeValue value, VisitingMethods listener) {
+        mValue = value;
+        mListener = listener;
+    }
+
+    /**
+     * API which processes an {@link AttributeValue} to find its value type and
+     * convert the Object to the appropriate type for invoking the right
+     * visitor(method) in the {@link VisitingMethods} interface.
+     *
+     * @return Object which holds the value returned by the visitor method.
+     */
+    public Object visit() {
+        if (null == mValue || null == mListener)
+            return null;
+
+        AttributeValue.TypeInfo typeInfo = mValue.typeInfo();
+        if (AttributeValue.ValueType.INTEGER == typeInfo.mBaseType) {
+            if (AttributeValue.ValueType.INTEGER == typeInfo.mType)
+                return mListener.visitingValue((Integer) mValue.get());
+            else if (AttributeValue.ValueType.ARRAY == typeInfo.mType) {
+                if (1 == typeInfo.mDepth)
+                    return mListener.visitingValue((Integer[]) mValue.get());
+                if (2 == typeInfo.mDepth)
+                    return mListener.visitingValue((Integer[][]) mValue.get());
+                if (3 == typeInfo.mDepth)
+                    return mListener
+                            .visitingValue((Integer[][][]) mValue.get());
+            }
+        } else if (AttributeValue.ValueType.DOUBLE == typeInfo.mBaseType) {
+            if (AttributeValue.ValueType.DOUBLE == typeInfo.mType)
+                return mListener.visitingValue((Double) mValue.get());
+            else if (AttributeValue.ValueType.ARRAY == typeInfo.mType) {
+                if (1 == typeInfo.mDepth)
+                    return mListener.visitingValue((Double[]) mValue.get());
+                if (2 == typeInfo.mDepth)
+                    return mListener.visitingValue((Double[][]) mValue.get());
+                if (3 == typeInfo.mDepth)
+                    return mListener.visitingValue((Double[][][]) mValue.get());
+            }
+        } else if (AttributeValue.ValueType.BOOLEAN == typeInfo.mBaseType) {
+            if (AttributeValue.ValueType.BOOLEAN == typeInfo.mType)
+                return mListener.visitingValue((Boolean) mValue.get());
+            else if (AttributeValue.ValueType.ARRAY == typeInfo.mType) {
+                if (1 == typeInfo.mDepth)
+                    return mListener.visitingValue((Boolean[]) mValue.get());
+                if (2 == typeInfo.mDepth)
+                    return mListener.visitingValue((Boolean[][]) mValue.get());
+                if (3 == typeInfo.mDepth)
+                    return mListener
+                            .visitingValue((Boolean[][][]) mValue.get());
+            }
+        } else if (AttributeValue.ValueType.STRING == typeInfo.mBaseType) {
+            if (AttributeValue.ValueType.STRING == typeInfo.mType)
+                return mListener.visitingValue((String) mValue.get());
+            else if (AttributeValue.ValueType.ARRAY == typeInfo.mType) {
+                if (1 == typeInfo.mDepth)
+                    return mListener.visitingValue((String[]) mValue.get());
+                if (2 == typeInfo.mDepth)
+                    return mListener.visitingValue((String[][]) mValue.get());
+                if (3 == typeInfo.mDepth)
+                    return mListener.visitingValue((String[][][]) mValue.get());
+            }
+        } else if (AttributeValue.ValueType.RESOURCEMODEL == typeInfo.mBaseType) {
+            if (AttributeValue.ValueType.RESOURCEMODEL == typeInfo.mType)
+                return mListener.visitingValue((SimulatorResourceModel) mValue
+                        .get());
+            else if (AttributeValue.ValueType.ARRAY == typeInfo.mType) {
+                if (1 == typeInfo.mDepth)
+                    return mListener
+                            .visitingValue((SimulatorResourceModel[]) mValue
+                                    .get());
+                if (2 == typeInfo.mDepth)
+                    return mListener
+                            .visitingValue((SimulatorResourceModel[][]) mValue
+                                    .get());
+                if (3 == typeInfo.mDepth)
+                    return mListener
+                            .visitingValue((SimulatorResourceModel[][][]) mValue
+                                    .get());
+            }
+        }
+
+        return null;
+    }
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/BooleanProperty.java b/service/simulator/java/sdk/src/org/oic/simulator/BooleanProperty.java
new file mode 100644 (file)
index 0000000..913e825
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator;
+
+public class BooleanProperty extends AttributeProperty {
+    private boolean mDefaultValue;
+
+    private BooleanProperty(boolean value) {
+        super(Type.BOOLEAN);
+        mDefaultValue = value;
+    }
+
+    @Override
+    public boolean isBoolean() {
+        return true;
+    }
+
+    @Override
+    public BooleanProperty asBoolean() {
+        return this;
+    }
+
+    public boolean getDefaultValue() {
+        return mDefaultValue;
+    }
+
+    @Override
+    public boolean validate(AttributeValue value) {
+        if (value.typeInfo().mType == AttributeValue.ValueType.BOOLEAN)
+            return true;
+        return false;
+    }
+
+    public boolean validate(boolean value) {
+        return true;
+    }
+
+    public static class Builder {
+        private boolean mDefaultValue = true;
+
+        public void setDefaultValue(boolean value) {
+            mDefaultValue = value;
+        }
+
+        public BooleanProperty build() {
+            return new BooleanProperty(mDefaultValue);
+        }
+    }
+}
\ No newline at end of file
index 49e8e39..66a45ce 100644 (file)
@@ -17,7 +17,7 @@
 package org.oic.simulator;
 
 /**
- * This class contains remote device information and provides APIs to access it.
+ * This class contains remote device information.
  */
 public class DeviceInfo {
     private String mName;
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/DeviceListener.java b/service/simulator/java/sdk/src/org/oic/simulator/DeviceListener.java
new file mode 100644 (file)
index 0000000..1e24bcd
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator;
+
+/**
+ * Interface for receiving device information.
+ */
+public interface DeviceListener {
+    /**
+     * Method which provides remote device information.
+     *
+     * @param hostUri
+     *            Holds the address detail.
+     * @param devInfo
+     *            {@link DeviceInfo} object holding the device information.
+     */
+    public void onDeviceFound(String hostUri, DeviceInfo devInfo);
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/DoubleProperty.java b/service/simulator/java/sdk/src/org/oic/simulator/DoubleProperty.java
new file mode 100644 (file)
index 0000000..2daff28
--- /dev/null
@@ -0,0 +1,127 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator;
+
+import java.util.Arrays;
+
+public class DoubleProperty extends AttributeProperty {
+
+    private double   mDefaultValue;
+    private double   mMin;
+    private double   mMax;
+    private double[] mValues;
+    private boolean  mHasRange = false;
+
+    private DoubleProperty(double value) {
+        super(Type.DOUBLE);
+        mDefaultValue = value;
+    }
+
+    private DoubleProperty(double value, double min, double max) {
+        super(Type.DOUBLE);
+        mDefaultValue = value;
+        mMin = min;
+        mMax = max;
+        mHasRange = true;
+    }
+
+    private DoubleProperty(double value, double[] values) {
+        super(Type.DOUBLE);
+        mDefaultValue = value;
+        mValues = Arrays.copyOf(values, values.length);
+        Arrays.sort(mValues);
+    }
+
+    @Override
+    public boolean isDouble() {
+        return true;
+    }
+
+    @Override
+    public DoubleProperty asDouble() {
+        return this;
+    }
+
+    public double getDefaultValue() {
+        return mDefaultValue;
+    }
+
+    public boolean hasRange() {
+        return mHasRange;
+    }
+
+    public double min() {
+        return mMin;
+    }
+
+    public double max() {
+        return mMax;
+    }
+
+    public boolean hasValues() {
+        return (null != mValues && (mValues.length > 0));
+    }
+
+    public double[] getValues() {
+        return mValues;
+    }
+
+    @Override
+    public boolean validate(AttributeValue value) {
+        return new DoubleValueValidator(this).validate(value);
+    }
+
+    public boolean validate(double value) {
+        if (mHasRange && (value < mMin || value > mMax)) {
+            return false;
+        } else if (hasValues() && 0 > Arrays.binarySearch(mValues, value)) {
+            return false;
+        }
+
+        return true;
+    }
+
+    public static class Builder {
+        private double   mDefaultValue = 0;
+        private double   mMin;
+        private double   mMax;
+        private double[] mValues;
+        private boolean  mHasRange     = false;
+
+        public void setDefaultValue(double value) {
+            mDefaultValue = value;
+        }
+
+        public void setRange(double min, double max) {
+            mMin = min;
+            mMax = max;
+            mHasRange = true;
+        }
+
+        public void setValues(double[] values) {
+            mValues = values;
+        }
+
+        public DoubleProperty build() {
+            if (mHasRange)
+                return new DoubleProperty(mDefaultValue, mMin, mMax);
+            if (null != mValues && (0 != mValues.length))
+                return new DoubleProperty(mDefaultValue, mValues);
+            return new DoubleProperty(mDefaultValue);
+        }
+    }
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/DoubleValueValidator.java b/service/simulator/java/sdk/src/org/oic/simulator/DoubleValueValidator.java
new file mode 100644 (file)
index 0000000..e4111b8
--- /dev/null
@@ -0,0 +1,134 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator;
+
+class DoubleValueValidator implements
+        AttributeValueVisitor.VisitingMethods<Boolean> {
+
+    private DoubleProperty mProperty = null;
+
+    DoubleValueValidator(DoubleProperty property) {
+        mProperty = property;
+    }
+
+    public boolean validate(AttributeValue value) {
+        AttributeValueVisitor visitor = new AttributeValueVisitor(value, this);
+        return (Boolean) visitor.visit();
+    }
+
+    @Override
+    public Boolean visitingValue(Integer value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Double value) {
+        if (null != mProperty)
+            return mProperty.validate(value);
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Boolean value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(String value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(SimulatorResourceModel value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Integer[] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Double[] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Boolean[] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(String[] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(SimulatorResourceModel[] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Integer[][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Double[][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Boolean[][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(String[][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(SimulatorResourceModel[][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Integer[][][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Double[][][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Boolean[][][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(String[][][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(SimulatorResourceModel[][][] value) {
+        return false;
+    }
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/IAutomation.java b/service/simulator/java/sdk/src/org/oic/simulator/IAutomation.java
deleted file mode 100644 (file)
index 1338fd5..0000000
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator;
-
-/**
- * Interface for receiving notifications on completion of automation.
- */
-public interface IAutomation {
-    /**
-     * Callback method for receiving automation complete notifications.
-     *
-     * @param resourceURI
-     *            URI of the resource on which the automation has occurred.
-     * @param automationId
-     *            Unique Id of the automation.
-     */
-    public void onAutomationComplete(String resourceURI, int automationId);
-}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/IDeviceInfo.java b/service/simulator/java/sdk/src/org/oic/simulator/IDeviceInfo.java
deleted file mode 100644 (file)
index cb541ad..0000000
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator;
-
-/**
- * Interface for getting device information.
- */
-public interface IDeviceInfo {
-    /**
-     * Callback method which provides remote device information.
-     *
-     * @param devInfo
-     *            {@link DeviceInfo} object holding the device information.
-     */
-    public void onDeviceFound(DeviceInfo devInfo);
-}
index 082e59e..eedc935 100644 (file)
@@ -28,8 +28,7 @@ public interface ILogger {
     }
 
     /**
-     * This callback method will be called to notify the application about the
-     * status or problems along with their severity.
+     * This method will be used to deliver the log messages from native layer.
      *
      * @param time
      *            Local time information when action/event logged.
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/IPlatformInfo.java b/service/simulator/java/sdk/src/org/oic/simulator/IPlatformInfo.java
deleted file mode 100644 (file)
index 120ec01..0000000
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator;
-
-/**
- * Interface for getting platform information.
- */
-public interface IPlatformInfo {
-    /**
-     * Callback method which provides remote device platform information.
-     *
-     * @param platformInfo
-     *            {@link PlatformInfo} object holding the platform information.
-     */
-    public void onPlatformFound(PlatformInfo platformInfo);
-}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/IntegerProperty.java b/service/simulator/java/sdk/src/org/oic/simulator/IntegerProperty.java
new file mode 100644 (file)
index 0000000..2448c2e
--- /dev/null
@@ -0,0 +1,126 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator;
+
+import java.util.Arrays;
+
+public class IntegerProperty extends AttributeProperty {
+    private int     mDefaultValue;
+    private int     mMin;
+    private int     mMax;
+    private int[]   mValues;
+    private boolean mHasRange = false;
+
+    private IntegerProperty(int value) {
+        super(Type.INTEGER);
+        mDefaultValue = value;
+    }
+
+    private IntegerProperty(int value, int min, int max) {
+        super(Type.INTEGER);
+        mDefaultValue = value;
+        mMin = min;
+        mMax = max;
+        mHasRange = true;
+    }
+
+    private IntegerProperty(int value, int[] values) {
+        super(Type.INTEGER);
+        mDefaultValue = value;
+        mValues = Arrays.copyOf(values, values.length);
+        Arrays.sort(mValues);
+    }
+
+    @Override
+    public boolean isInteger() {
+        return true;
+    }
+
+    @Override
+    public IntegerProperty asInteger() {
+        return this;
+    }
+
+    public int getDefaultValue() {
+        return mDefaultValue;
+    }
+
+    public boolean hasRange() {
+        return mHasRange;
+    }
+
+    public int min() {
+        return mMin;
+    }
+
+    public int max() {
+        return mMax;
+    }
+
+    public boolean hasValues() {
+        return (null != mValues && (mValues.length > 0));
+    }
+
+    public int[] getValues() {
+        return mValues;
+    }
+
+    @Override
+    public boolean validate(AttributeValue value) {
+        return new IntegerValueValidator(this).validate(value);
+    }
+
+    public boolean validate(int value) {
+        if (mHasRange && (value < mMin || value > mMax)) {
+            return false;
+        } else if (hasValues() && 0 > Arrays.binarySearch(mValues, value)) {
+            return false;
+        }
+
+        return true;
+    }
+
+    public static class Builder {
+        private int     mDefaultValue = 0;
+        private int     mMin;
+        private int     mMax;
+        private int[]   mValues;
+        private boolean mHasRange     = false;
+
+        public void setDefaultValue(int value) {
+            mDefaultValue = value;
+        }
+
+        public void setRange(int min, int max) {
+            mMin = min;
+            mMax = max;
+            mHasRange = true;
+        }
+
+        public void setValues(int[] values) {
+            mValues = values;
+        }
+
+        public IntegerProperty build() {
+            if (mHasRange)
+                return new IntegerProperty(mDefaultValue, mMin, mMax);
+            if (null != mValues && (0 != mValues.length))
+                return new IntegerProperty(mDefaultValue, mValues);
+            return new IntegerProperty(mDefaultValue);
+        }
+    }
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/IntegerValueValidator.java b/service/simulator/java/sdk/src/org/oic/simulator/IntegerValueValidator.java
new file mode 100644 (file)
index 0000000..787396f
--- /dev/null
@@ -0,0 +1,134 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator;
+
+class IntegerValueValidator implements
+        AttributeValueVisitor.VisitingMethods<Boolean> {
+
+    private IntegerProperty mProperty = null;
+
+    IntegerValueValidator(IntegerProperty property) {
+        mProperty = property;
+    }
+
+    public boolean validate(AttributeValue value) {
+        AttributeValueVisitor visitor = new AttributeValueVisitor(value, this);
+        return (Boolean) visitor.visit();
+    }
+
+    @Override
+    public Boolean visitingValue(Integer value) {
+        if (null != mProperty)
+            return mProperty.validate(value);
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Double value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Boolean value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(String value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(SimulatorResourceModel value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Integer[] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Double[] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Boolean[] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(String[] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(SimulatorResourceModel[] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Integer[][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Double[][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Boolean[][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(String[][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(SimulatorResourceModel[][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Integer[][][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Double[][][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Boolean[][][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(String[][][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(SimulatorResourceModel[][][] value) {
+        return false;
+    }
+}
index d62fbdd..ca1ac83 100644 (file)
@@ -21,7 +21,41 @@ package org.oic.simulator;
  */
 @SuppressWarnings("serial")
 public class InvalidArgsException extends SimulatorException {
-    public InvalidArgsException(int errorCode, String errMessage) {
-        super(errorCode, errMessage);
+
+    /**
+     * Constructs {@link InvalidArgsException} with the given ordinal
+     * representing the error code and description.
+     *
+     * @param code
+     *            Ordinal of an error code.
+     * @param message
+     *            Error description.
+     */
+    public InvalidArgsException(int code, String message) {
+        super(code, message);
+    }
+
+    /**
+     * Constructs {@link InvalidArgsException} with the given error code and
+     * description.
+     *
+     * @param code
+     *            {@link SimulatorResult} enum constant representing the error
+     *            code.
+     * @param message
+     *            Error description.
+     */
+    public InvalidArgsException(SimulatorResult code, String message) {
+        super(code, message);
+    }
+
+    /**
+     * Constructs {@link InvalidArgsException} with the given error message.
+     *
+     * @param message
+     *            Error description.
+     */
+    public InvalidArgsException(String message) {
+        super(SimulatorResult.SIMULATOR_INVALID_PARAM, message);
     }
 }
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/ModelProperty.java b/service/simulator/java/sdk/src/org/oic/simulator/ModelProperty.java
new file mode 100644 (file)
index 0000000..e62faa2
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class ModelProperty extends AttributeProperty {
+
+    private Map<String, Boolean>           mRequiredAttributes;
+    private Map<String, AttributeProperty> mChildProperties;
+
+    ModelProperty() {
+        super(Type.MODEL);
+        mRequiredAttributes = new HashMap<>();
+        mChildProperties = new HashMap<>();
+    }
+
+    @Override
+    public boolean isModel() {
+        return true;
+    }
+
+    @Override
+    public ModelProperty asModel() {
+        return this;
+    }
+
+    public boolean add(String name, AttributeProperty property, boolean required) {
+        if (null == name || null == property) {
+            return false;
+        }
+
+        mChildProperties.put(name, property);
+        mRequiredAttributes.put(name, required);
+        return true;
+    }
+
+    public void remove(String name) {
+        mChildProperties.remove(name);
+        mRequiredAttributes.remove(name);
+    }
+
+    public AttributeProperty get(String name) {
+        return mChildProperties.get(name);
+    }
+
+    public Map<String, AttributeProperty> getChildProperties() {
+        return mChildProperties;
+    }
+
+    public boolean isRequired(String name) {
+        return mRequiredAttributes.get(name);
+    }
+
+    @Override
+    public boolean validate(AttributeValue value) {
+        return new ModelValueValidator(this).validate(value);
+    }
+
+    public boolean validate(SimulatorResourceModel model) {
+        for (Map.Entry<String, AttributeValue> attributeEntry : model.get()
+                .entrySet()) {
+            AttributeProperty childProperty = get(attributeEntry.getKey());
+            if (null != childProperty
+                    && !childProperty.validate(attributeEntry.getValue())) {
+                return false;
+            }
+        }
+
+        return true;
+    }
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/ModelValueValidator.java b/service/simulator/java/sdk/src/org/oic/simulator/ModelValueValidator.java
new file mode 100644 (file)
index 0000000..93e7ecc
--- /dev/null
@@ -0,0 +1,134 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator;
+
+class ModelValueValidator implements
+        AttributeValueVisitor.VisitingMethods<Boolean> {
+
+    private ModelProperty mProperty = null;
+
+    ModelValueValidator(ModelProperty property) {
+        mProperty = property;
+    }
+
+    public boolean validate(AttributeValue value) {
+        AttributeValueVisitor visitor = new AttributeValueVisitor(value, this);
+        return (Boolean) visitor.visit();
+    }
+
+    @Override
+    public Boolean visitingValue(Integer value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Double value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Boolean value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(String value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(SimulatorResourceModel value) {
+        if (null != mProperty)
+            return mProperty.validate(value);
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Integer[] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Double[] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Boolean[] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(String[] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(SimulatorResourceModel[] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Integer[][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Double[][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Boolean[][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(String[][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(SimulatorResourceModel[][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Integer[][][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Double[][][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Boolean[][][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(String[][][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(SimulatorResourceModel[][][] value) {
+        return false;
+    }
+}
index 914641f..60fb7ab 100644 (file)
@@ -21,7 +21,28 @@ package org.oic.simulator;
  */
 @SuppressWarnings("serial")
 public class NoSupportException extends SimulatorException {
-    public NoSupportException(int errorCode, String errMessage) {
-        super(errorCode, errMessage);
+
+    /**
+     * Constructs {@link NoSupportException} with the given error message.
+     *
+     * @param message
+     *            Error description.
+     */
+    public NoSupportException(String message) {
+        super(SimulatorResult.SIMULATOR_NOT_SUPPORTED, message);
+    }
+
+    /**
+     * Constructs {@link NoSupportException} with the given error code and
+     * description.
+     *
+     * @param code
+     *            {@link SimulatorResult} enum constant representing the error
+     *            code.
+     * @param message
+     *            Error description.
+     */
+    public NoSupportException(SimulatorResult code, String message) {
+        super(code, message);
     }
 }
\ No newline at end of file
index c9127b5..20086e7 100644 (file)
@@ -22,7 +22,29 @@ package org.oic.simulator;
  */
 @SuppressWarnings("serial")
 public class OperationInProgressException extends SimulatorException {
-    public OperationInProgressException(int errorCode, String errMessage) {
-        super(errorCode, errMessage);
+
+    /**
+     * Constructs {@link OperationInProgressException} with the given error
+     * message.
+     *
+     * @param message
+     *            Error description.
+     */
+    public OperationInProgressException(String message) {
+        super(SimulatorResult.SIMULATOR_OPERATION_IN_PROGRESS, message);
+    }
+
+    /**
+     * Constructs {@link OperationInProgressException} with the given error code
+     * and description.
+     *
+     * @param code
+     *            {@link SimulatorResult} enum constant representing the error
+     *            code.
+     * @param message
+     *            Error description.
+     */
+    public OperationInProgressException(SimulatorResult code, String message) {
+        super(code, message);
     }
 }
index 7956e92..756e565 100644 (file)
 package org.oic.simulator;
 
 /**
- * This class contains remote device platform information and provide APIs
- * access it.
+ * This class contains remote device platform information and provide APIs to
+ * access and update it.
  */
 public class PlatformInfo {
     private String mPlatformId;
-    private String m_manufacturerName;
-    private String m_manufacturerUrl;
-    private String m_modelNumber;
-    private String m_dateOfManufacture;
-    private String m_platformVersion;
-    private String m_operationSystemVersion;
-    private String m_hardwareVersion;
-    private String m_firmwareVersion;
-    private String m_supportUrl;
-    private String m_systemTime;
+    private String mManufacturerName;
+    private String mManufacturerUrl;
+    private String mModelNumber;
+    private String mDateOfManufacture;
+    private String mPlatformVersion;
+    private String mOperationSystemVersion;
+    private String mHardwareVersion;
+    private String mFirmwareVersion;
+    private String mSupportUrl;
+    private String mSystemTime;
 
     /**
      * This method is for getting platform id.
@@ -58,7 +58,7 @@ public class PlatformInfo {
      * @return Manufacturer name.
      */
     public String getManufacturerName() {
-        return m_manufacturerName;
+        return mManufacturerName;
     }
 
     /**
@@ -68,7 +68,7 @@ public class PlatformInfo {
      *            Manufacturer name.
      */
     public void setManufacturerName(String m_manufacturerName) {
-        this.m_manufacturerName = m_manufacturerName;
+        this.mManufacturerName = m_manufacturerName;
     }
 
     /**
@@ -77,7 +77,7 @@ public class PlatformInfo {
      * @return Manufacturer URL.
      */
     public String getManufacturerUrl() {
-        return m_manufacturerUrl;
+        return mManufacturerUrl;
     }
 
     /**
@@ -87,7 +87,7 @@ public class PlatformInfo {
      *            Manufacturer URL.
      */
     public void setManufacturerUrl(String m_manufacturerUrl) {
-        this.m_manufacturerUrl = m_manufacturerUrl;
+        this.mManufacturerUrl = m_manufacturerUrl;
     }
 
     /**
@@ -96,7 +96,7 @@ public class PlatformInfo {
      * @return Model number.
      */
     public String getModelNumber() {
-        return m_modelNumber;
+        return mModelNumber;
     }
 
     /**
@@ -106,7 +106,7 @@ public class PlatformInfo {
      *            Model number.
      */
     public void setModelNumber(String m_modelNumber) {
-        this.m_modelNumber = m_modelNumber;
+        this.mModelNumber = m_modelNumber;
     }
 
     /**
@@ -115,7 +115,7 @@ public class PlatformInfo {
      * @return Date of manufacture.
      */
     public String getDateOfManufacture() {
-        return m_dateOfManufacture;
+        return mDateOfManufacture;
     }
 
     /**
@@ -125,7 +125,7 @@ public class PlatformInfo {
      *            Date of manufacture.
      */
     public void setDateOfManufacture(String m_dateOfManufacture) {
-        this.m_dateOfManufacture = m_dateOfManufacture;
+        this.mDateOfManufacture = m_dateOfManufacture;
     }
 
     /**
@@ -134,7 +134,7 @@ public class PlatformInfo {
      * @return Platform version.
      */
     public String getPlatformVersion() {
-        return m_platformVersion;
+        return mPlatformVersion;
     }
 
     /**
@@ -144,7 +144,7 @@ public class PlatformInfo {
      *            Platform version.
      */
     public void setPlatformVersion(String m_platformVersion) {
-        this.m_platformVersion = m_platformVersion;
+        this.mPlatformVersion = m_platformVersion;
     }
 
     /**
@@ -153,7 +153,7 @@ public class PlatformInfo {
      * @return Operation system version.
      */
     public String getOperationSystemVersion() {
-        return m_operationSystemVersion;
+        return mOperationSystemVersion;
     }
 
     /**
@@ -163,7 +163,7 @@ public class PlatformInfo {
      *            Operation system version.
      */
     public void setOperationSystemVersion(String m_operationSystemVersion) {
-        this.m_operationSystemVersion = m_operationSystemVersion;
+        this.mOperationSystemVersion = m_operationSystemVersion;
     }
 
     /**
@@ -172,7 +172,7 @@ public class PlatformInfo {
      * @return Hardware version.
      */
     public String getHardwareVersion() {
-        return m_hardwareVersion;
+        return mHardwareVersion;
     }
 
     /**
@@ -182,7 +182,7 @@ public class PlatformInfo {
      *            Hardware version.
      */
     public void setHardwareVersion(String m_hardwareVersion) {
-        this.m_hardwareVersion = m_hardwareVersion;
+        this.mHardwareVersion = m_hardwareVersion;
     }
 
     /**
@@ -191,7 +191,7 @@ public class PlatformInfo {
      * @return Firmware version.
      */
     public String getFirmwareVersion() {
-        return m_firmwareVersion;
+        return mFirmwareVersion;
     }
 
     /**
@@ -201,7 +201,7 @@ public class PlatformInfo {
      *            Firmware version.
      */
     public void setFirmwareVersion(String m_firmwareVersion) {
-        this.m_firmwareVersion = m_firmwareVersion;
+        this.mFirmwareVersion = m_firmwareVersion;
     }
 
     /**
@@ -210,7 +210,7 @@ public class PlatformInfo {
      * @return URL of support link.
      */
     public String getSupportUrl() {
-        return m_supportUrl;
+        return mSupportUrl;
     }
 
     /**
@@ -220,7 +220,7 @@ public class PlatformInfo {
      *            URL of support link.
      */
     public void setSupportUrl(String m_supportUrl) {
-        this.m_supportUrl = m_supportUrl;
+        this.mSupportUrl = m_supportUrl;
     }
 
     /**
@@ -229,7 +229,7 @@ public class PlatformInfo {
      * @return System time.
      */
     public String getSystemTime() {
-        return m_systemTime;
+        return mSystemTime;
     }
 
     /**
@@ -239,6 +239,6 @@ public class PlatformInfo {
      *            System time.
      */
     public void setSystemTime(String m_systemTime) {
-        this.m_systemTime = m_systemTime;
+        this.mSystemTime = m_systemTime;
     }
 }
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/PlatformListener.java b/service/simulator/java/sdk/src/org/oic/simulator/PlatformListener.java
new file mode 100644 (file)
index 0000000..900c647
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator;
+
+/**
+ * Interface for receiving platform information.
+ */
+public interface PlatformListener {
+    /**
+     * Method which provides remote device platform information.
+     *
+     * @param hostUri
+     *            Holds the address detail.
+     * @param platformInfo
+     *            {@link PlatformInfo} object holding the platform information.
+     */
+    public void onPlatformFound(String hostUri, PlatformInfo platformInfo);
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/ResourceAttribute.java b/service/simulator/java/sdk/src/org/oic/simulator/ResourceAttribute.java
deleted file mode 100644 (file)
index 0822e76..0000000
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator;
-
-/**
- * This class represents an attribute of a resource. It has a set of native
- * methods for getting the attribute's information.
- */
-public class ResourceAttribute {
-    /**
-     * Type of attribute value.
-     */
-    public enum Type {
-        UNKNOWN, INT, DOUBLE, BOOL, STRING;
-
-        private static Type[] m_cvalues = Type.values();
-
-        @SuppressWarnings("unused")
-        private static Type getType(int x) {
-            return m_cvalues[x];
-        }
-    };
-
-    /**
-     * Class contains range property in min and max value.
-     */
-    public class Range {
-        public int getMin() {
-            return m_min;
-        }
-
-        public int getMax() {
-            return m_max;
-        }
-
-        private Range(int min, int max) {
-            m_min = min;
-            m_max = max;
-        }
-
-        private int m_min;
-        private int m_max;
-    }
-
-    @SuppressWarnings("unused")
-    private void setRange(int min, int max) {
-        m_range = new Range(min, max);
-    }
-
-    /**
-     * This generic API is used to get the value of an attribute whose type is
-     * given by the caller of the method.
-     *
-     * @param <T>
-     *            This specifies the type in which the value has to be returned.
-     *
-     * @return The attribute's value in a specified type.
-     */
-    public <T> T getValue() {
-        @SuppressWarnings("unchecked")
-        T t = (T) m_value;
-        return t;
-    }
-
-    /**
-     * Method for getting the attribute's name.
-     *
-     * @return Attribute's name
-     */
-    public String getName() {
-        return m_name;
-    }
-
-    /**
-     * Method for getting the attribute's value type.
-     *
-     * @return Attribute's value type as {@link Type}
-     */
-    public Type getType() {
-        return m_type;
-    }
-
-    /**
-     * Method for getting the attribute's value base type. For example If the
-     * attribute value object is of type Vector of {@link Integer} then its type
-     * is Vector and base type is INT.
-     *
-     * @return Attribute's value type as {@link Type}
-     */
-    public Type getBaseType() {
-        return m_type;
-    }
-
-    /**
-     * Method for getting the attribute's range property. Range will be valid
-     * only for Integer type.
-     *
-     * @return Attribute's value range as {@link Range}.
-     */
-    public Range getRange() {
-        return m_range;
-    }
-
-    /**
-     * Method for getting the attribute's allowed values property. Allowed
-     * values property will be valid only for Integer, Double, String types.
-     *
-     * @param <T>
-     *            Attribute's allowed values whose type is given by the caller
-     *            of the method.
-     *
-     * @return Attribute's value range as {@link Range}.
-     */
-    public <T> T getAllowedValues() {
-        @SuppressWarnings("unchecked")
-        T t = (T) m_AllowedValues;
-        return t;
-    }
-
-    private String m_name          = null;
-    private Object m_value         = null;
-    private Type   m_type          = Type.STRING;
-    private Range  m_range         = null;
-    private Object m_AllowedValues = null;
-}
\ No newline at end of file
index 7b4c5c8..c9a7ba9 100644 (file)
@@ -23,19 +23,54 @@ package org.oic.simulator;
 @SuppressWarnings("serial")
 public class SimulatorException extends Exception {
 
-    private SimulatorResult errorCode;
-    private String          errorMessage;
+    private SimulatorResult code;
+    private String          message;
 
-    public SimulatorException(int errorCode, String errMessage) {
-        this.errorCode = SimulatorResult.get(errorCode);
-        this.errorMessage = errMessage;
+    /**
+     * Constructs {@link SimulatorException} with the given ordinal representing
+     * the error code and description.
+     *
+     * @param code
+     *            Ordinal of an error code.
+     * @param message
+     *            Error description.
+     */
+    public SimulatorException(int code, String message) {
+        this.code = SimulatorResult.get(code);
+        this.message = message;
     }
 
+    /**
+     * Constructs {@link SimulatorException} with the given error code and
+     * description.
+     *
+     * @param code
+     *            {@link SimulatorResult} enum constant representing the error
+     *            code.
+     * @param message
+     *            Error description.
+     */
+    public SimulatorException(SimulatorResult code, String message) {
+        this.code = code;
+        this.message = message;
+    }
+
+    /**
+     * API to get the error code.
+     *
+     * @return {@link SimulatorResult} enum constant representing the error
+     *         code.
+     */
     public SimulatorResult code() {
-        return errorCode;
+        return code;
     }
 
+    /**
+     * API to get the error description.
+     *
+     * @return Error description.
+     */
     public String message() {
-        return errorMessage;
+        return message;
     }
 }
\ No newline at end of file
index a16ce67..a1d93d7 100644 (file)
 
 package org.oic.simulator;
 
-import org.oic.simulator.clientcontroller.IFindResourceListener;
-import org.oic.simulator.serviceprovider.IResourceModelChangedListener;
-import org.oic.simulator.serviceprovider.SimulatorResourceServer;
+import java.util.Vector;
+
+import org.oic.simulator.client.FindResourceListener;
+import org.oic.simulator.server.SimulatorResource;
 
 /**
  * This class provides a set of methods for creation, discovery and deletion of
@@ -26,17 +27,21 @@ import org.oic.simulator.serviceprovider.SimulatorResourceServer;
  */
 public class SimulatorManager {
 
+    static {
+        System.loadLibrary("oc_logger");
+        System.loadLibrary("octbstack");
+        System.loadLibrary("oc");
+        System.loadLibrary("RamlParser");
+        System.loadLibrary("SimulatorManager");
+    }
+
     /**
-     * API for creating a resource from a RAML configuration file whose path is
-     * given as a parameter.
+     * API for creating a resource from a RAML configuration file.
      *
      * @param configPath
      *            Path to RAML configuration file.
-     * @param listener
-     *            Listener for receiving notifications whenever there is a
-     *            change in the resource model.
      *
-     * @return {@link SimulatorResourceServer} - Created resource on success,
+     * @return {@link SimulatorResource} - Created resource on success,
      *         otherwise null.
      *
      * @throws InvalidArgsException
@@ -44,84 +49,61 @@ public class SimulatorManager {
      * @throws SimulatorException
      *             Thrown for other errors.
      */
-    public static SimulatorResourceServer createResource(String configPath,
-            IResourceModelChangedListener listener)
+    public static SimulatorResource createResource(String configPath)
             throws InvalidArgsException, SimulatorException {
-        if (configPath.isEmpty() || null == listener)
-            throw new InvalidArgsException(
-                    SimulatorResult.SIMULATOR_INVALID_PARAM.ordinal(),
-                    "Parameter passed in invalid");
-        SimulatorResourceServer simulatorResourceServerObj;
-        simulatorResourceServerObj = SimulatorManagerNativeInterface
-                .createResource(configPath, listener);
-        return simulatorResourceServerObj;
+        return nativeCreateResource(configPath);
     }
 
     /**
-     * API for creating a set of resources from a RAML configuration file whose
-     * path is given as a parameter.
+     * API for creating a set of resources from a RAML configuration file.
      *
      * @param configPath
      *            Path to RAML configuration file.
      * @param count
      *            Number of resources to be created.
-     * @param listener
-     *            Listener for receiving notifications whenever there is a
-     *            change in the resource model.
      *
-     * @return Returns an array of {@link SimulatorResourceServer} objects one
-     *         for each created resource on success, otherwise null.
+     * @return Returns an array of {@link SimulatorResource} objects one for
+     *         each created resource on success, otherwise null.
      *
      * @throws InvalidArgsException
      *             Thrown if the input parameters are empty.
      * @throws SimulatorException
      *             Thrown for other errors.
      */
-    public static SimulatorResourceServer[] createResource(String configPath,
-            int count, IResourceModelChangedListener listener)
-            throws InvalidArgsException, SimulatorException {
-        if (configPath.isEmpty() || count < 0 || null == listener)
-            throw new InvalidArgsException(
-                    SimulatorResult.SIMULATOR_INVALID_PARAM.ordinal(),
-                    "Parameter passed in invalid");
-        SimulatorResourceServer[] simulatorResourceServers;
-        simulatorResourceServers = SimulatorManagerNativeInterface
-                .createResources(configPath, count, listener);
-        return simulatorResourceServers;
-    }
+    public static Vector<SimulatorResource> createResource(String configPath,
+            int count) throws InvalidArgsException, SimulatorException {
+        return nativeCreateResources(configPath, count);
+    };
 
     /**
-     * API for deleting a specific resource.
+     * API for creating a resource either single or collection type.
      *
-     * @param resource
-     *            {@link SimulatorResourceServer} object of the resource to be
-     *            deleted.
+     * @param type
+     *            Indicates whether single or collection type.
+     * @param name
+     *            Resource Name.
+     * @param uri
+     *            Resource URI.
+     * @param resourceType
+     *            Resource Type.
+     *
+     * @return {@link SimulatorResource} - Created resource on success,
+     *         otherwise null.
      *
      * @throws InvalidArgsException
-     *             Thrown if the input parameter is empty.
+     *             Thrown if the input parameters are empty.
      * @throws SimulatorException
      *             Thrown for other errors.
      */
-    public static void deleteResource(SimulatorResourceServer resource)
+    public static SimulatorResource createResource(SimulatorResource.Type type,
+            String name, String uri, String resourceType)
             throws InvalidArgsException, SimulatorException {
-        SimulatorManagerNativeInterface.deleteResource(resource);
-    }
-
-    /**
-     * API for deleting either all the resources or resources of a specific
-     * type. Ex: If resourceType is oic.light, all resources of oic.light type
-     * will be deleted. If resourceType is null, then all of the resources will
-     * be deleted.
-     *
-     * @param resourceType
-     *            Type of resource to be deleted.
-     *
-     * @throws SimulatorException
-     *             Thrown for other errors.
-     */
-    public static void deleteResources(String resourceType)
-            throws SimulatorException {
-        SimulatorManagerNativeInterface.deleteResources(resourceType);
+        SimulatorResource resource;
+        if (type == SimulatorResource.Type.SINGLE)
+            resource = nativeCreateSingleResource(name, uri, resourceType);
+        else
+            resource = nativeCreateCollectionResource(name, uri, resourceType);
+        return resource;
     }
 
     /**
@@ -136,9 +118,9 @@ public class SimulatorManager {
      * @throws SimulatorException
      *             Thrown for other errors.
      */
-    public static void findResource(IFindResourceListener listener)
+    public static void findResource(FindResourceListener listener)
             throws InvalidArgsException, SimulatorException {
-        SimulatorManagerNativeInterface.findResource(null, listener);
+        nativeSearchResource(null, listener);
     }
 
     /**
@@ -146,7 +128,7 @@ public class SimulatorManager {
      * is called when a resource is discovered in the network.
      *
      * @param resourceType
-     *            Required resource type
+     *            Required resource type.
      * @param listener
      *            Interface to receive the discovered remote resources.
      *
@@ -156,24 +138,15 @@ public class SimulatorManager {
      *             Thrown for other errors.
      */
     public static void findResource(String resourceType,
-            IFindResourceListener listener) throws InvalidArgsException,
+            FindResourceListener listener) throws InvalidArgsException,
             SimulatorException {
         if (null == resourceType || resourceType.isEmpty()) {
             throw new InvalidArgsException(
-                    SimulatorResult.SIMULATOR_INVALID_PARAM.ordinal(),
-                    "Resource type is empty");
+                    SimulatorResult.SIMULATOR_INVALID_PARAM,
+                    "Invalid resource type!");
         }
-        SimulatorManagerNativeInterface.findResource(resourceType, listener);
-    }
 
-    /**
-     * API to set the listener for receiving log messages.
-     *
-     * @param logger
-     *            {@link ILogger} to receive the log messages.
-     */
-    public static void setLogger(ILogger logger) {
-        SimulatorManagerNativeInterface.setLogger(logger);
+        nativeSearchResource(resourceType, listener);
     }
 
     /**
@@ -181,20 +154,33 @@ public class SimulatorManager {
      *
      * @param deviceInfo
      *            Device information.
+     *
+     * @throws InvalidArgsException
+     *             Thrown if the input parameter is empty.
+     * @throws SimulatorException
+     *             Thrown for other errors.
      */
-    public static void setDeviceInfo(String deviceInfo) {
-        SimulatorManagerNativeInterface.setDeviceInfo(deviceInfo);
+    public static void setDeviceInfo(String deviceInfo)
+            throws InvalidArgsException, SimulatorException {
+        nativeSetDeviceInfo(deviceInfo);
     }
 
     /**
-     * API to get the device information asynchronously via callback
-     * using {@link IDeviceInfo}.
+     * API to search for devices on the given host in the network.
      *
+     * @param hostUri
+     *            URI of the host device.
      * @param listener
-     *            Interface for receiving the device information.
+     *            Listener for receiving the device information.
+     *
+     * @throws InvalidArgsException
+     *             Thrown if the input parameter is empty.
+     * @throws SimulatorException
+     *             Thrown for other errors.
      */
-    public static void getDeviceInfo(IDeviceInfo listener) {
-        SimulatorManagerNativeInterface.getDeviceInfo(listener);
+    public static void findDevices(String hostUri, DeviceListener listener)
+            throws InvalidArgsException, SimulatorException {
+        nativeFindDevices(hostUri, listener);
     }
 
     /**
@@ -202,19 +188,73 @@ public class SimulatorManager {
      *
      * @param platformInfo
      *            {@link PlatformInfo} - Platform information.
+     *
+     * @throws InvalidArgsException
+     *             Thrown if the input parameter is empty.
+     * @throws SimulatorException
+     *             Thrown for other errors.
      */
-    public static void setPlatformInfo(PlatformInfo platformInfo) {
-        SimulatorManagerNativeInterface.setPlatformInfo(platformInfo);
+    public static void setPlatformInfo(PlatformInfo platformInfo)
+            throws InvalidArgsException, SimulatorException {
+        nativeSetPlatformInfo(platformInfo);
     }
 
     /**
-     * API to get the platform information asynchronously via callback
-     * using {@link IPlatformInfo}..
+     * API to find the platform information of the given host in the network.
      *
+     * @param hostUri
+     *            URI of the host device.
      * @param listener
-     *            Interface for receiving the platform information.
+     *            Listener for receiving the platform information.
+     *
+     * @throws InvalidArgsException
+     *             Thrown if the input parameter is empty.
+     * @throws SimulatorException
+     *             Thrown for other errors.
+     */
+    public static void getPlatformInformation(String hostUri,
+            PlatformListener listener) throws InvalidArgsException,
+            SimulatorException {
+        nativeGetPlatformInformation(hostUri, listener);
+    }
+
+    /**
+     * API to set the listener for receiving log messages.
+     *
+     * @param logger
+     *            {@link ILogger} to receive the log messages.
      */
-    public static void getPlatformInfo(IPlatformInfo listener) {
-        SimulatorManagerNativeInterface.getPlatformInfo(listener);
+    public static void setLogger(ILogger logger) {
+        nativeSetLogger(logger);
     }
+
+    private SimulatorManager() {
+    }
+
+    private static native SimulatorResource nativeCreateResource(
+            String configPath);
+
+    private static native Vector<SimulatorResource> nativeCreateResources(
+            String configPath, int count);
+
+    private static native SimulatorResource nativeCreateSingleResource(
+            String name, String uri, String resourceType);
+
+    private static native SimulatorResource nativeCreateCollectionResource(
+            String name, String uri, String resourceType);
+
+    private static native void nativeSearchResource(String resourceType,
+            FindResourceListener listener);
+
+    private static native void nativeSetDeviceInfo(String deviceInfo);
+
+    private static native void nativeFindDevices(String hostUri,
+            DeviceListener listener);
+
+    private static native void nativeSetPlatformInfo(PlatformInfo platformInfo);
+
+    private static native void nativeGetPlatformInformation(String hostUri,
+            PlatformListener listener);
+
+    private static native void nativeSetLogger(ILogger logger);
 }
\ No newline at end of file
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/SimulatorManagerNativeInterface.java b/service/simulator/java/sdk/src/org/oic/simulator/SimulatorManagerNativeInterface.java
deleted file mode 100644 (file)
index 5fd2185..0000000
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator;
-
-import org.oic.simulator.clientcontroller.IFindResourceListener;
-import org.oic.simulator.serviceprovider.IResourceModelChangedListener;
-import org.oic.simulator.serviceprovider.SimulatorResourceServer;
-
-/**
- * This class provides a set of native functions for creation, discovery and
- * deletion of resources.
- */
-class SimulatorManagerNativeInterface {
-
-    /**
-     * Native function for creating a resource.
-     *
-     * @param configPath
-     *            Path to RAML configuration file.
-     * @param listener
-     *            Listener for receiving notifications whenever there is a
-     *            change in the resource model.
-     *
-     * @return {@link SimulatorResourceServer} object on success, otherwise
-     *         null.
-     *
-     * @throws InvalidArgsException
-     *             Thrown if the input parameters are empty.
-     * @throws SimulatorException
-     *             Thrown for other errors.
-     */
-    public static native SimulatorResourceServer createResource(
-            String configPath, IResourceModelChangedListener listener)
-            throws InvalidArgsException, SimulatorException;
-
-    /**
-     * Native function for creating several resources.
-     *
-     * @param configPath
-     *            Path to RAML configuration file.
-     * @param count
-     *            Number of instances.
-     * @param listener
-     *            Listener for receiving notifications whenever there is a
-     *            change in the resource model.
-     *
-     * @return An array of {@link SimulatorResourceServer} objects on success,
-     *         otherwise null.
-     *
-     * @throws InvalidArgsException
-     *             Thrown if the input parameters are empty.
-     * @throws SimulatorException
-     *             Thrown for other errors.
-     */
-    public static native SimulatorResourceServer[] createResources(
-            String configPath, int count, IResourceModelChangedListener listener)
-            throws InvalidArgsException, SimulatorException;
-
-    /**
-     * Native function to delete a specific resource.
-     *
-     * @param resource
-     *            {@link SimulatorResourceServer} object of the resource to be
-     *            deleted.
-     *
-     * @throws InvalidArgsException
-     *             Thrown if the input parameter is empty.
-     * @throws SimulatorException
-     *             Thrown for other errors.
-     */
-    public static native void deleteResource(SimulatorResourceServer resource)
-            throws InvalidArgsException, SimulatorException;
-
-    /**
-     * Native function to delete all resources or resources of a specific type.
-     *
-     * @param resourceType
-     *            Type of the resource.
-     *
-     * @throws InvalidArgsException
-     *             Thrown if the input parameter is empty.
-     * @throws SimulatorException
-     *             Thrown for other errors.
-     */
-    public static native void deleteResources(String resourceType)
-            throws SimulatorException;
-
-    /**
-     * Native function for discovering resources.
-     *
-     * @param resourceType
-     *            required resource type
-     * @param listener
-     *            Interface to receive the discovered remote resources.
-     *
-     * @throws InvalidArgsException
-     *             Thrown if the input parameter is empty.
-     * @throws SimulatorException
-     *             Thrown for other errors.
-     */
-    public static native void findResource(String resourceType,
-            IFindResourceListener listener) throws InvalidArgsException,
-            SimulatorException;
-
-    /**
-     * Native function to set the logger listener for receiving the log messages
-     * from native layer.
-     *
-     * @param logger
-     *            Interface to receive log.
-     */
-    public static native void setLogger(ILogger logger);
-
-    /**
-     * Native function to set the device information.
-     *
-     * @param deviceInfo
-     *            Device information.
-     */
-    public static native void setDeviceInfo(String deviceInfo);
-
-    /**
-     * Native function to get the device information asynchronously via the
-     * listener.
-     *
-     * @param listener
-     *            Interface for receiving the device information.
-     */
-    public static native void getDeviceInfo(IDeviceInfo listener);
-
-    /**
-     * Native function to set the platform information.
-     *
-     * @param platformInfo
-     *            Platform information.
-     */
-    public static native void setPlatformInfo(PlatformInfo platformInfo);
-
-    /**
-     * Native function to get the platform information asynchronously via the
-     * listener.
-     *
-     * @param listener
-     *            Interface for receiving the platform information.
-     */
-    public static native void getPlatformInfo(IPlatformInfo listener);
-}
\ No newline at end of file
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/SimulatorResourceAttribute.java b/service/simulator/java/sdk/src/org/oic/simulator/SimulatorResourceAttribute.java
new file mode 100644 (file)
index 0000000..f997444
--- /dev/null
@@ -0,0 +1,119 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator;
+
+/**
+ * This class represents the resource attribute which contains attribute value
+ * and its property.
+ */
+public class SimulatorResourceAttribute {
+
+    private String            mName     = null;
+    private AttributeValue    mValue    = null;
+    private AttributeProperty mProperty = null;
+
+    /**
+     * Constructs {@link SimulatorResourceAttribute} with the given attribute
+     * name, value and its property.
+     *
+     * @param name
+     *            Name of the attribute.
+     * @param value
+     *            Value of the attribute.
+     * @param property
+     *            Property of attribute value.
+     */
+    public SimulatorResourceAttribute(String name, AttributeValue value,
+            AttributeProperty property) {
+        mName = name;
+        mValue = value;
+        mProperty = property;
+    }
+
+    /**
+     * Constructs {@link SimulatorResourceAttribute} with the given attribute
+     * name and value.
+     *
+     * @param name
+     *            Name of the attribute.
+     * @param value
+     *            Value of the attribute.
+     */
+    public SimulatorResourceAttribute(String name, AttributeValue value) {
+        mName = name;
+        mValue = value;
+        mProperty = null;
+    }
+
+    /**
+     * API to get name of attribute.
+     *
+     * @return Attribute's name.
+     */
+    public String name() {
+        return mName;
+    }
+
+    /**
+     * API to get value of attribute.
+     *
+     * @return Attribute's value {@link AttributeValue}.
+     */
+    public AttributeValue value() {
+        return mValue;
+    }
+
+    /**
+     * API to get property of attribute's value.
+     *
+     * @return Attribute's value property {@link AttributeProperty
+     * }.
+     */
+    public AttributeProperty property() {
+        return mProperty;
+    }
+
+    /**
+     * API to set the name of attribute.
+     *
+     * @param name
+     *            Name of the attribute.
+     */
+    public void setName(String name) {
+        this.mName = name;
+    }
+
+    /**
+     * API to set the value of attribute.
+     *
+     * @param value
+     *            Value of the attribute.
+     */
+    public void setValue(AttributeValue value) {
+        this.mValue = value;
+    }
+
+    /**
+     * API to set the property of attribute.
+     *
+     * @param property
+     *            Property of the attribute.
+     */
+    public void setProperty(AttributeProperty property) {
+        this.mProperty = property;
+    }
+}
index 63961e9..1f1b959 100644 (file)
 
 package org.oic.simulator;
 
-import org.oic.simulator.ResourceAttribute;
+import java.util.HashMap;
 import java.util.Map;
 
 /**
- * This class represents the resource model of a resource and it provides a set
- * of native methods for accessing the resource model.
+ * This class represents the resource model of a resource. A resource model
+ * contains a set of attributes. It also represents the complex value type of an
+ * attribute.
  */
 public class SimulatorResourceModel {
 
+    private Map<String, AttributeValue> mValues = null;
+
     /**
-     * Constructor for creating a native resource model object. Client requests
-     * such as PUT and POST uses this method for passing the new/updated
-     * resource model.
+     * Constructs new {@link SimulatorResourceModel} object.
      */
     public SimulatorResourceModel() {
-        create();
+        mValues = new HashMap<>();
     }
 
     /**
-     * API to add an attribute of type integer.
+     * API to set an attribute to resource model. If an attribute exists with
+     * the given name, then it overwrites the existing value. Otherwise creates
+     * a new attribute.
      *
-     * @param name
-     *            Name of the attribute
+     * @param attrName
+     *            Name of the attribute.
      * @param value
-     *            Value of the attribute
+     *            Value of the attribute.
      *
      * @throws InvalidArgsException
-     *             This exception will be thrown if the attribute name is
-     *             invalid.
-     * @throws SimulatorException
-     *             This exception will be thrown either if the resource model is
-     *             not found or for some general errors.
+     *             This exception will be thrown on invalid input.
      */
-    public native void addAttributeInt(String name, int value)
-            throws InvalidArgsException, SimulatorException;
+    public void set(String attrName, AttributeValue value)
+            throws InvalidArgsException {
+        if (null == attrName || attrName.isEmpty())
+            throw new InvalidArgsException("Invalid attribute name!");
+
+        if (null == value)
+            throw new InvalidArgsException("Attribute value is null!");
+
+        mValues.put(attrName, value);
+    }
 
     /**
-     * API to add an attribute of type double.
+     * API to remove attribute from resource model.
      *
-     * @param name
-     *            Name of the attribute
-     * @param value
-     *            Value of the attribute
+     * @param attrName
+     *            Name of the attribute.
      *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if the attribute name is
-     *             invalid.
-     * @throws SimulatorException
-     *             This exception will be thrown either if the resource model is
-     *             not found or for some general errors.
+     * @return true if resource model has an attribute with the given name,
+     *         otherwise false.
      */
-    public native void addAttributeDouble(String name, double value)
-            throws InvalidArgsException, SimulatorException;
+    public boolean remove(String attrName) {
+        if (mValues.containsKey(attrName)) {
+            mValues.remove(attrName);
+            return true;
+        }
+
+        return false;
+    }
 
     /**
-     * API to add an attribute of type boolean.
+     * API to get attribute by name.
      *
-     * @param name
-     *            Name of the attribute
-     * @param value
-     *            Value of the attribute
+     * @param attrName
+     *            Name of the attribute.
      *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if the attribute name is
-     *             invalid.
-     * @throws SimulatorException
-     *             This exception will be thrown either if the resource model is
-     *             not found or for some general errors.
+     * @return {@link SimulatorResourceAttribute}.
      */
-    public native void addAttributeBoolean(String name, boolean value)
-            throws InvalidArgsException, SimulatorException;
+    public AttributeValue get(String attrName) {
+        if (mValues.containsKey(attrName)) {
+            return mValues.get(attrName);
+        }
+
+        return null;
+    }
 
     /**
-     * API to add an attribute of type string.
-     *
-     * @param name
-     *            Name of the attribute
-     * @param value
-     *            Value of the attribute
+     * API to get all attributes of the model.
      *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if the attribute name is
-     *             invalid.
-     * @throws SimulatorException
-     *             This exception will be thrown either if the resource model is
-     *             not found or for some general errors.
+     * @return A map of {@link AttributeValue} objects with attribute name as
+     *         the key.
      */
-    public native void addAttributeString(String name, String value)
-            throws InvalidArgsException, SimulatorException;
+    public Map<String, AttributeValue> get() {
+        return mValues;
+    }
 
     /**
-     * API to get number of attributes for this model.
+     * API to check whether resource model has an attribute with given name.
      *
-     * @return Number of attributes.
+     * @param attrName
+     *            Name of the attribute.
      *
-     * @throws SimulatorException
-     *             This exception will be thrown either if the resource model is
-     *             not found or for some general errors.
+     * @return true if resource model has an attribute with given name,
+     *         otherwise false.
      */
-    public native int size() throws SimulatorException;
+    public boolean contains(String attrName) {
+        if (mValues.containsKey(attrName))
+            return true;
+        return false;
+    }
 
     /**
-     * API for getting all attributes.
+     * API to get value type information of attribute.
      *
-     * @return Map of attributes with attribute name as the key and its
-     *         corresponding {@link ResourceAttribute} object as the value.
+     * @param attrName
+     *            Name of the attribute.
      *
-     * @throws SimulatorException
-     *             This exception will be thrown either if the resource model is
-     *             not found or for some general errors.
+     * @return Attribute value type information {@link AttributeValue.TypeInfo
+     *
+     * }.
      */
-    public native Map<String, ResourceAttribute> getAttributes()
-            throws SimulatorException;
+    public AttributeValue.TypeInfo getType(String attrName) {
+        if (mValues.containsKey(attrName))
+            return mValues.get(attrName).typeInfo();
+        return null;
+    }
 
     /**
-     * API to get attribute by its name.
-     *
-     * @param name
-     *            Name of the attribute
-     *
-     * @return An object of {@link ResourceAttribute}.
+     * API to get number of attributes present in resource model.
      *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if the attribute does not
-     *             exist.
-     *
-     * @throws SimulatorException
-     *             This exception will be thrown either if the resource model is
-     *             not found or for some general errors.
+     * @return Number of attributes present in resource model.
      */
-    public native ResourceAttribute getAttribute(String name)
-            throws InvalidArgsException, SimulatorException;
-
-    private SimulatorResourceModel(long nativeHandle) {
-        this.nativeHandle = nativeHandle;
+    public int size() {
+        return mValues.size();
     }
 
-    @Override
-    protected void finalize() throws Throwable {
-        try {
-            dispose();
-        } finally {
-            super.finalize();
-        }
+    private SimulatorResourceModel(Map<String, AttributeValue> values) {
+        mValues = values;
     }
-
-    private native void create();
-
-    private native void dispose();
-
-    private long nativeHandle;
-}
\ No newline at end of file
+}
index 8e4b9eb..96de7e3 100644 (file)
@@ -21,57 +21,27 @@ package org.oic.simulator;
  */
 public enum SimulatorResult {
     /** STACK error codes - START */
-    SIMULATOR_OK,
-    SIMULATOR_RESOURCE_CREATED,
-    SIMULATOR_RESOURCE_DELETED,
-    SIMULATOR_CONTINUE,
-    SIMULATOR_INVALID_URI,
-    SIMULATOR_INVALID_QUERY,
-    SIMULATOR_INVALID_IP,
-    SIMULATOR_INVALID_PORT,
-    SIMULATOR_INVALID_CALLBACK,
-    SIMULATOR_INVALID_METHOD,
-    SIMULATOR_INVALID_PARAM,
-    SIMULATOR_INVALID_OBSERVE_PARAM,
-    SIMULATOR_NO_MEMORY,
-    SIMULATOR_COMM_ERROR,
-    SIMULATOR_TIMEOUT,
-    SIMULATOR_ADAPTER_NOT_ENABLED,
-    SIMULATOR_NOTIMPL,
-    SIMULATOR_NO_RESOURCE,
-    SIMULATOR_RESOURCE_ERROR,
-    SIMULATOR_SLOW_RESOURCE,
-    SIMULATOR_DUPLICATE_REQUEST,
-    SIMULATOR_NO_OBSERVERS,
-    SIMULATOR_OBSERVER_NOT_FOUND,
-    SIMULATOR_VIRTUAL_DO_NOT_HANDLE,
-    SIMULATOR_INVALID_OPTION,
-    SIMULATOR_MALFORMED_RESPONSE,
-    SIMULATOR_PERSISTENT_BUFFER_REQUIRED,
-    SIMULATOR_INVALID_REQUEST_HANDLE,
-    SIMULATOR_INVALID_DEVICE_INFO,
-    SIMULATOR_INVALID_JSON,
-    SIMULATOR_UNAUTHORIZED_REQ,
+    SIMULATOR_OK, SIMULATOR_RESOURCE_CREATED, SIMULATOR_RESOURCE_DELETED, SIMULATOR_CONTINUE, SIMULATOR_INVALID_URI, SIMULATOR_INVALID_QUERY, SIMULATOR_INVALID_IP, SIMULATOR_INVALID_PORT, SIMULATOR_INVALID_CALLBACK, SIMULATOR_INVALID_METHOD, SIMULATOR_INVALID_PARAM, SIMULATOR_INVALID_OBSERVE_PARAM, SIMULATOR_NO_MEMORY, SIMULATOR_COMM_ERROR, SIMULATOR_TIMEOUT, SIMULATOR_ADAPTER_NOT_ENABLED, SIMULATOR_NOTIMPL, SIMULATOR_NO_RESOURCE, SIMULATOR_RESOURCE_ERROR, SIMULATOR_SLOW_RESOURCE, SIMULATOR_DUPLICATE_REQUEST, SIMULATOR_NO_OBSERVERS, SIMULATOR_OBSERVER_NOT_FOUND, SIMULATOR_VIRTUAL_DO_NOT_HANDLE, SIMULATOR_INVALID_OPTION, SIMULATOR_MALFORMED_RESPONSE, SIMULATOR_PERSISTENT_BUFFER_REQUIRED, SIMULATOR_INVALID_REQUEST_HANDLE, SIMULATOR_INVALID_DEVICE_INFO, SIMULATOR_INVALID_JSON, SIMULATOR_UNAUTHORIZED_REQ,
 
-    SIMULATOR_PRESENCE_STOPPED,
-    SIMULATOR_PRESENCE_TIMEOUT,
-    SIMULATOR_PRESENCE_DO_NOT_HANDLE,
+    SIMULATOR_PRESENCE_STOPPED, SIMULATOR_PRESENCE_TIMEOUT, SIMULATOR_PRESENCE_DO_NOT_HANDLE,
     /** STACK error codes - END */
 
     /** Simulator specific error codes - START */
-    SIMULATOR_INVALID_TYPE,
-    SIMULATOR_NOT_SUPPORTED,
-    SIMULATOR_OPERATION_NOT_ALLOWED,
-    SIMULATOR_OPERATION_IN_PROGRESS,
+    SIMULATOR_INVALID_TYPE, SIMULATOR_NOT_SUPPORTED, SIMULATOR_OPERATION_NOT_ALLOWED, SIMULATOR_OPERATION_IN_PROGRESS,
 
-    SIMULATOR_INVALID_RESPONSE_CODE,
-    SIMULATOR_UKNOWN_PROPERTY,
-    SIMULATOR_TYPE_MISMATCH,
-    SIMULATOR_BAD_VALUE,
+    SIMULATOR_INVALID_RESPONSE_CODE, SIMULATOR_UKNOWN_PROPERTY, SIMULATOR_TYPE_MISMATCH, SIMULATOR_BAD_VALUE, SIMULATOR_BAD_OBJECT, SIMULATOR_BAD_SCHEMA,
     /** Simulator specific error codes - END */
 
     SIMULATOR_ERROR;
 
+    /**
+     * This method returns the {@link SimulatorResult} at the given
+     * position(ordinal).
+     *
+     * @param ordinal
+     *            Index of the constant.
+     * @return {@link SimulatorResult} constant at the given index.
+     */
     public static SimulatorResult get(int ordinal) {
 
         SimulatorResult result;
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/StringProperty.java b/service/simulator/java/sdk/src/org/oic/simulator/StringProperty.java
new file mode 100644 (file)
index 0000000..2238a45
--- /dev/null
@@ -0,0 +1,129 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator;
+
+import java.util.Arrays;
+
+public class StringProperty extends AttributeProperty {
+
+    private String   mDefaultValue;
+    private int      mMin;
+    private int      mMax;
+    private String[] mValues;
+    private boolean  mHasRange = false;
+
+    private StringProperty(String value) {
+        super(Type.STRING);
+        mDefaultValue = value;
+    }
+
+    private StringProperty(String value, int min, int max) {
+        super(Type.STRING);
+        mDefaultValue = value;
+        mMin = min;
+        mMax = max;
+        mHasRange = true;
+    }
+
+    private StringProperty(String value, String[] values) {
+        super(Type.STRING);
+        mDefaultValue = value;
+        mValues = Arrays.copyOf(values, values.length);
+        Arrays.sort(mValues);
+    }
+
+    @Override
+    public boolean isString() {
+        return true;
+    }
+
+    @Override
+    public StringProperty asString() {
+        return this;
+    }
+
+    public String getDefaultValue() {
+        return mDefaultValue;
+    }
+
+    public boolean hasRange() {
+        return mHasRange;
+    }
+
+    public int min() {
+        return mMin;
+    }
+
+    public int max() {
+        return mMax;
+    }
+
+    public boolean hasValues() {
+        return (null != mValues && (mValues.length > 0));
+    }
+
+    public String[] getValues() {
+        return mValues;
+    }
+
+    @Override
+    public boolean validate(AttributeValue value) {
+        return new StringValueValidator(this).validate(value);
+    }
+
+    public boolean validate(String value) {
+        int length = value.length();
+        if (mHasRange && (length < mMin || length > mMax)) {
+            return false;
+        } else if (hasValues() && 0 > Arrays.binarySearch(mValues, value)) {
+            return false;
+        }
+
+        return true;
+    }
+
+    public static class Builder {
+        private String   mDefaultValue;
+        private int      mMin;
+        private int      mMax;
+        private String[] mValues;
+        private boolean  mHasRange = false;
+
+        public void setDefaultValue(String value) {
+            if (null != value)
+                mDefaultValue = value;
+        }
+
+        public void setRange(int min, int max) {
+            mMin = min;
+            mMax = max;
+            mHasRange = true;
+        }
+
+        public void setValues(String[] values) {
+            mValues = values;
+        }
+
+        public StringProperty build() {
+            if (mHasRange)
+                return new StringProperty(mDefaultValue, mMin, mMax);
+            if (null != mValues && (0 != mValues.length))
+                return new StringProperty(mDefaultValue, mValues);
+            return new StringProperty(mDefaultValue);
+        }
+    }
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/StringValueValidator.java b/service/simulator/java/sdk/src/org/oic/simulator/StringValueValidator.java
new file mode 100644 (file)
index 0000000..2ef06d2
--- /dev/null
@@ -0,0 +1,134 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator;
+
+class StringValueValidator implements
+        AttributeValueVisitor.VisitingMethods<Boolean> {
+
+    private StringProperty mProperty = null;
+
+    StringValueValidator(StringProperty property) {
+        mProperty = property;
+    }
+
+    public boolean validate(AttributeValue value) {
+        AttributeValueVisitor visitor = new AttributeValueVisitor(value, this);
+        return (Boolean) visitor.visit();
+    }
+
+    @Override
+    public Boolean visitingValue(Integer value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Double value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Boolean value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(String value) {
+        if (null != mProperty)
+            return mProperty.validate(value);
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(SimulatorResourceModel value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Integer[] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Double[] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Boolean[] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(String[] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(SimulatorResourceModel[] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Integer[][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Double[][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Boolean[][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(String[][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(SimulatorResourceModel[][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Integer[][][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Double[][][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Boolean[][][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(String[][][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(SimulatorResourceModel[][][] value) {
+        return false;
+    }
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/client/FindResourceListener.java b/service/simulator/java/sdk/src/org/oic/simulator/client/FindResourceListener.java
new file mode 100644 (file)
index 0000000..1faa369
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator.client;
+
+/**
+ * Listener for getting notification when resources are discovered in network.
+ */
+public interface FindResourceListener {
+    /**
+     * Method will be called when resource is discovered in the network.
+     *
+     * @param resource
+     *            {@link SimulatorRemoteResource} object representing the
+     *            resource discovered in the network.
+     */
+    public void onResourceFound(SimulatorRemoteResource resource);
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/client/SimulatorConnectivityType.java b/service/simulator/java/sdk/src/org/oic/simulator/client/SimulatorConnectivityType.java
new file mode 100644 (file)
index 0000000..108ecb2
--- /dev/null
@@ -0,0 +1,106 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator.client;
+
+/**
+ * Enum to represent the supported connectivity types.
+ */
+public enum SimulatorConnectivityType {
+    SIMULATOR_CT_DEFAULT(0),
+
+    /** IPv4 and IPv6, including 6LoWPAN. */
+    SIMULATOR_CT_ADAPTER_IP(1 << 16),
+
+    /** GATT over Bluetooth LE. */
+    SIMULATOR_CT_ADAPTER_GATT_BTLE(1 << 17),
+
+    /** RFCOMM over Bluetooth EDR. */
+    SIMULATOR_CT_ADAPTER_RFCOMM_BTEDR(1 << 18),
+
+    /** Remote Access over XMPP. */
+    SIMULATOR_CT_ADAPTER_REMOTE_ACCESS(1 << 19),
+
+    /** Insecure transport is the default (subject to change). */
+
+    /** secure the transport path. */
+    SIMULATOR_CT_FLAG_SECURE(1 << 4),
+
+    /** IPv4 & IPv6 autoselection is the default. */
+
+    /** IP adapter only. */
+    SIMULATOR_CT_IP_USE_V6(1 << 5),
+
+    /** IP adapter only. */
+    SIMULATOR_CT_IP_USE_V4(1 << 6),
+
+    /**
+     * Link-Local multicast is the default multicast scope for IPv6. These are
+     * placed here to correspond to the IPv6 address bits.
+     */
+
+    /** IPv6 Interface-Local scope(loopback). */
+    SIMULATOR_CT_SCOPE_INTERFACE(0x1),
+
+    /** IPv6 Link-Local scope (default). */
+    SIMULATOR_CT_SCOPE_LINK(0x2),
+
+    /** IPv6 Realm-Local scope. */
+    SIMULATOR_CT_SCOPE_REALM(0x3),
+
+    /** IPv6 Admin-Local scope. */
+    SIMULATOR_CT_SCOPE_ADMIN(0x4),
+
+    /** IPv6 Site-Local scope. */
+    SIMULATOR_CT_SCOPE_SITE(0x5),
+
+    /** IPv6 Organization-Local scope. */
+    SIMULATOR_CT_SCOPE_ORG(0x8),
+
+    /** IPv6 Global scope. */
+    SIMULATOR_CT_SCOPE_GLOBAL(0xE);
+
+    private int value;
+
+    private SimulatorConnectivityType(int value) {
+        this.value = value;
+    }
+
+    public int getValue() {
+        return this.value;
+    }
+
+    /**
+     * Method to get the {@link SimulatorConnectivityType} from an integer
+     * value.
+     *
+     * @param value
+     *            Integral value of {@link SimulatorConnectivityType}.
+     * @return {@link SimulatorConnectivityType} corresponding to the given
+     *         value.
+     */
+    public static SimulatorConnectivityType getConnectivityType(int value) {
+        SimulatorConnectivityType result = null;
+        SimulatorConnectivityType[] types = SimulatorConnectivityType.values();
+        for (SimulatorConnectivityType type : types) {
+            if (type.getValue() == value) {
+                result = type;
+                break;
+            }
+        }
+        return result;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/client/SimulatorRemoteResource.java b/service/simulator/java/sdk/src/org/oic/simulator/client/SimulatorRemoteResource.java
new file mode 100644 (file)
index 0000000..8e5e46e
--- /dev/null
@@ -0,0 +1,562 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator.client;
+
+import java.util.Map;
+import java.util.Vector;
+
+import org.oic.simulator.InvalidArgsException;
+import org.oic.simulator.NoSupportException;
+import org.oic.simulator.OperationInProgressException;
+import org.oic.simulator.SimulatorException;
+import org.oic.simulator.SimulatorResourceModel;
+import org.oic.simulator.SimulatorResult;
+
+/**
+ * SimulatorRemoteResource represents a Resource running in the remote Simulator
+ * Server. It comes with a well-defined contract or interface onto which you can
+ * perform different operations or subscribe for event notifications.
+ */
+public final class SimulatorRemoteResource {
+    private long           mNativeHandle;
+    private String         mUri;
+    private int            mConnType;
+    private String         mHost;
+    private String         mId;
+    private Vector<String> mResTypes;
+    private Vector<String> mResInterfaces;
+    private boolean        mIsObservable;
+
+    @Override
+    protected void finalize() throws Throwable {
+        try {
+            nativeDispose();
+        } catch (Throwable t) {
+            throw t;
+        } finally {
+            super.finalize();
+        }
+    }
+
+    /**
+     * Enum to represent the verification types which can be used by the client
+     * to verify the resource model of the remote resource.
+     */
+    public enum RequestType {
+        UKNOWN, GET, PUT, POST, DELETE;
+    }
+
+    /**
+     * API to get the URI for this resource.
+     *
+     * @return Resource URI.
+     */
+    public String getURI() {
+        return mUri;
+    }
+
+    /**
+     * API to get the address detail of the resource.
+     *
+     * @return Host address.
+     */
+    public String getHost() {
+        return mHost;
+    }
+
+    /**
+     * API to get a unique Id of the resource.
+     *
+     * @return Unique ID.
+     */
+    public String getId() {
+        return mId;
+    }
+
+    /**
+     * API to get the connectivity type for this resource.
+     *
+     * @return Connectivity type.
+     */
+    public SimulatorConnectivityType getConnectivityType() {
+        return SimulatorConnectivityType.getConnectivityType(mConnType);
+    }
+
+    /**
+     * API to get the list of resource types.
+     *
+     * @return Resource types.
+     */
+    public Vector<String> getResourceTypes() {
+        return mResTypes;
+    }
+
+    /**
+     * API to get the list of resource interfaces.
+     *
+     * @return Resource interfaces.
+     */
+    public Vector<String> getResourceInterfaces() {
+        return mResInterfaces;
+    }
+
+    /**
+     * API to get the observe policy of this resource.
+     *
+     * @return True if the resource is observable, otherwise false.
+     */
+    public boolean isObservable() {
+        return mIsObservable;
+    }
+
+    /**
+     * API to send GET request to the resource. Response will be notified
+     * asynchronously via callback set for {@link GetResponseListener}.
+     *
+     * @param queryParams
+     *            Map which can have the query parameter name and value.
+     * @param onGetListener
+     *            Event handler which will be invoked with the response for GET
+     *            request with a map of attribute name and values.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown if any parameter has invalid
+     *             values.
+     * @throws SimulatorException
+     *             This exception will be thrown for other errors.
+     */
+    public void get(Map<String, String> queryParams,
+            GetResponseListener onGetListener) throws InvalidArgsException,
+            SimulatorException {
+        nativeGet(null, queryParams, onGetListener);
+    }
+
+    /**
+     * API to send GET request to the resource. Response will be notified
+     * asynchronously via callback set for {@link GetResponseListener}.
+     *
+     * @param resourceInterface
+     *            Interface type of the resource to operate on.
+     * @param queryParams
+     *            Map which can have the query parameter name and value.
+     * @param onGetListener
+     *            Event handler which will be invoked with the response for GET
+     *            request with a map of attribute name and values.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown if any parameter has invalid
+     *             values.
+     * @throws SimulatorException
+     *             This exception will be thrown for other errors.
+     */
+    public void get(String resourceInterface, Map<String, String> queryParams,
+            GetResponseListener onGetListener) throws InvalidArgsException,
+            SimulatorException {
+        if (null == resourceInterface || resourceInterface.isEmpty())
+            throw new InvalidArgsException(
+                    SimulatorResult.SIMULATOR_INVALID_PARAM,
+                    "Invalid resource interface!");
+        nativeGet(resourceInterface, queryParams, onGetListener);
+    }
+
+    /**
+     * API to send PUT request to the resource. Response will be notified
+     * asynchronously via callback set for {@link PutResponseListener}.
+     *
+     * @param queryParams
+     *            Map which can have the query parameter name and value.
+     * @param representation
+     *            {@link SimulatorResourceModel} holding the representation of
+     *            the resource.
+     * @param onPutListener
+     *            Event handler which will be invoked with the response for PUT
+     *            request with a map of attribute name and values.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown if any parameter has invalid
+     *             value.
+     * @throws SimulatorException
+     *             This exception will be thrown for other errors.
+     */
+    public void put(Map<String, String> queryParams,
+            SimulatorResourceModel representation,
+            PutResponseListener onPutListener) throws InvalidArgsException,
+            SimulatorException {
+        nativePut(null, queryParams, representation, onPutListener);
+    }
+
+    /**
+     * API to send PUT request to the resource. Response will be notified
+     * asynchronously via callback set for {@link PutResponseListener}.
+     *
+     * @param resourceInterface
+     *            Interface type of the resource to operate on.
+     * @param queryParams
+     *            Map which can have the query parameter name and value.
+     * @param representation
+     *            {@link SimulatorResourceModel} holding the representation of
+     *            the resource.
+     * @param onPutListener
+     *            Event handler which will be invoked with the response for PUT
+     *            request with a map of attribute name and values.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown if any parameter has invalid
+     *             value.
+     * @throws SimulatorException
+     *             This exception will be thrown for other errors.
+     */
+    public void put(String resourceInterface, Map<String, String> queryParams,
+            SimulatorResourceModel representation,
+            PutResponseListener onPutListener) throws InvalidArgsException,
+            SimulatorException {
+        if (null == resourceInterface || resourceInterface.isEmpty())
+            throw new InvalidArgsException(
+                    SimulatorResult.SIMULATOR_INVALID_PARAM,
+                    "Invalid resource interface!");
+        nativePut(resourceInterface, queryParams, representation, onPutListener);
+    }
+
+    /**
+     * API to send POST request to the resource. Response will be notified
+     * asynchronously via callback set for {@link PostResponseListener}.
+     *
+     * @param queryParams
+     *            Map which can have the query parameter name and value.
+     * @param representation
+     *            {@link SimulatorResourceModel} holding the representation of
+     *            the resource.
+     * @param onPostListener
+     *            Event handler which will be invoked with the response for POST
+     *            request with a map of attribute name and values.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown if any parameter has invalid
+     *             value.
+     * @throws SimulatorException
+     *             This exception will be thrown for other errors.
+     */
+    public void post(Map<String, String> queryParams,
+            SimulatorResourceModel representation,
+            PostResponseListener onPostListener) throws InvalidArgsException,
+            SimulatorException {
+        nativePost(null, queryParams, representation, onPostListener);
+    }
+
+    /**
+     * API to send POST request to the resource. Response will be notified
+     * asynchronously via callback set for {@link PostResponseListener}.
+     *
+     * @param resourceInterface
+     *            Interface type of the resource to operate on.
+     * @param queryParams
+     *            Map which can have the query parameter name and value.
+     * @param representation
+     *            {@link SimulatorResourceModel} holding the representation of
+     *            the resource.
+     * @param onPostListener
+     *            Event handler which will be invoked with the response for POST
+     *            request with a map of attribute name and values.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown if any parameter has invalid
+     *             value.
+     * @throws SimulatorException
+     *             This exception will be thrown for other errors.
+     */
+    public void post(String resourceInterface, Map<String, String> queryParams,
+            SimulatorResourceModel representation,
+            PostResponseListener onPostListener) throws InvalidArgsException,
+            SimulatorException {
+        if (null == resourceInterface || resourceInterface.isEmpty())
+            throw new InvalidArgsException(
+                    SimulatorResult.SIMULATOR_INVALID_PARAM,
+                    "Invalid resource interface!");
+        nativePost(resourceInterface, queryParams, representation,
+                onPostListener);
+    }
+
+    /**
+     * API to start observing the resource.
+     *
+     * @param onObserveListener
+     *            The handler method which will be invoked with a map of
+     *            attribute names and values whenever there is a change in
+     *            resource model of the remote resource.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown if any parameter has invalid
+     *             values.
+     * @throws SimulatorException
+     *             This exception will be thrown for other errors.
+     */
+    public void observe(ObserveNotificationListener onObserveListener)
+            throws InvalidArgsException, SimulatorException {
+        nativeStartObserve(null, onObserveListener);
+    }
+
+    /**
+     * API to start observing the resource.
+     *
+     * @param queryParams
+     *            Map which can have the query parameter names and values.
+     * @param onObserveListener
+     *            The handler method which will be invoked with a map of
+     *            attribute names and values whenever there is a change in
+     *            resource model of the remote resource.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown if any parameter has invalid
+     *             values.
+     * @throws SimulatorException
+     *             This exception will be thrown for other errors.
+     */
+    public void observe(Map<String, String> queryParams,
+            ObserveNotificationListener onObserveListener)
+            throws InvalidArgsException, SimulatorException {
+        if (null == queryParams)
+            throw new InvalidArgsException(
+                    SimulatorResult.SIMULATOR_INVALID_PARAM,
+                    "Invalid Query Parameters!");
+        nativeStartObserve(queryParams, onObserveListener);
+    }
+
+    /**
+     * API to stop observing the resource.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown if the native remote resource
+     *             object is unavailable.
+     * @throws SimulatorException
+     *             This exception will be thrown for other errors.
+     */
+    public void stopObserve() throws InvalidArgsException, SimulatorException {
+        nativeStopObserve();
+    }
+
+    /**
+     * API to provide remote resource configure information, which is required
+     * for using automation feature.
+     *
+     * @param path
+     *            Path to RAML file.
+     *
+     * @return Representation {@link SimulatorResourceModel} holding the
+     *         representation of the remote resource.
+     *
+     * @throws InvalidArgsException
+     *             Thrown if the RAML configuration file path is invalid.
+     * @throws SimulatorException
+     *             Thrown for other errors.
+     */
+    public Map<RequestType, SimulatorRequestModel> setConfigInfo(String path)
+            throws InvalidArgsException, SimulatorException {
+        return nativeSetConfigInfo(path);
+    }
+
+    /**
+     * API to send multiple requests for the resource, based on the configure
+     * file provided from {@link setConfigInfo}. This verifies response received
+     * as well.
+     *
+     * @param type
+     *            Request type to verify.
+     * @param onVerifyListener
+     *            This event handler will be invoked with the current status of
+     *            the automation.
+     *
+     * @return Automation ID.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown if any parameter has invalid
+     *             value.
+     * @throws NoSupportException
+     *             Thrown either if the resource does not support the request
+     *             type or the resource is not configured with RAML.
+     * @throws OperationInProgressException
+     *             Thrown if another request generation session is already in
+     *             progress.
+     * @throws SimulatorException
+     *             This exception will be thrown for other errors.
+     */
+    public int startVerification(RequestType type,
+            VerificationListener onVerifyListener) throws InvalidArgsException,
+            NoSupportException, OperationInProgressException,
+            SimulatorException {
+        return nativeStartAutoRequesting(type, onVerifyListener);
+    }
+
+    /**
+     * API to stop sending requests which has been started using
+     * {@link startVerification}.
+     *
+     * @param id
+     *            Automation ID.
+     *
+     * @throws InvalidArgsException
+     *             Thrown if the automation ID is invalid.
+     * @throws SimulatorException
+     *             Thrown for other errors.
+     */
+    public void stopVerification(int id) throws InvalidArgsException,
+            SimulatorException {
+        nativeStopAutoRequesting(id);
+    }
+
+    /**
+     * Listener for receiving asynchronous response for GET request.
+     */
+    public interface GetResponseListener {
+        /**
+         * Method will be called when response for GET request arrives.
+         *
+         * @param uid
+         *            Unique Id of the resource.
+         * @param result
+         *            Error code {@link SimulatorResult}.
+         * @param resourceModel
+         *            {@link SimulatorResourceModel}.
+         */
+        public void onGetResponse(String uid, SimulatorResult result,
+                SimulatorResourceModel resourceModel);
+    }
+
+    /**
+     * Listener for receiving asynchronous response for PUT request.
+     */
+    public interface PutResponseListener {
+        /**
+         * Method will be called when response for PUT request arrives.
+         *
+         * @param uid
+         *            Unique Id of the resource.
+         * @param result
+         *            Error code {@link SimulatorResult}.
+         * @param resourceModel
+         *            {@link SimulatorResourceModel}.
+         */
+        public void onPutResponse(String uid, SimulatorResult result,
+                SimulatorResourceModel resourceModel);
+    }
+
+    /**
+     * Listener for receiving asynchronous response for POST request.
+     */
+    public interface PostResponseListener {
+        /**
+         * Method will be called when response for POST request arrives.
+         *
+         * @param uid
+         *            Unique Id of the resource.
+         * @param result
+         *            Error code {@link SimulatorResult}.
+         * @param resourceModel
+         *            {@link SimulatorResourceModel}.
+         */
+        public void onPostResponse(String uid, SimulatorResult result,
+                SimulatorResourceModel resourceModel);
+    }
+
+    /**
+     * Listener for getting asynchronous notification whenever remote resource's
+     * representation gets changed.
+     */
+    public interface ObserveNotificationListener {
+        /**
+         * This method will be called when there is a change in the resource
+         * model of the remote resource.
+         *
+         * @param uid
+         *            Unique Id of the resource.
+         * @param resourceModel
+         *            {@link SimulatorResourceModel}.
+         * @param sequenceNumber
+         *            Sequential number for ordering the model change
+         *            notifications.
+         */
+        public void onObserveNotification(String uid,
+                SimulatorResourceModel resourceModel, int sequenceNumber);
+    }
+
+    /**
+     * Listener for receiving the verification session status.
+     */
+    public interface VerificationListener {
+        /**
+         * Called when the verification request is accepted and started.
+         *
+         * @param uid
+         *            Unique Id of the resource.
+         * @param id
+         *            Verification Id.
+         */
+        public void onVerificationStarted(String uid, int id);
+
+        /**
+         * Called when the verification is stopped before its completion.
+         *
+         * @param uid
+         *            Unique Id of the resource.
+         * @param id
+         *            Verification Id.
+         */
+        public void onVerificationAborted(String uid, int id);
+
+        /**
+         * Called when the verification is done.
+         *
+         * @param uid
+         *            Unique Id of the resource.
+         * @param id
+         *            Verification Id.
+         */
+        public void onVerificationCompleted(String uid, int id);
+    }
+
+    private SimulatorRemoteResource(long nativeHandle) {
+        mNativeHandle = nativeHandle;
+    }
+
+    private native void nativeGet(String resourceInterface,
+            Map<String, String> queryParamsMap,
+            GetResponseListener onGetListener);
+
+    private native void nativePut(String resourceInterface,
+            Map<String, String> queryParams,
+            SimulatorResourceModel representation,
+            PutResponseListener onPutListener);
+
+    private native void nativePost(String resourceInterface,
+            Map<String, String> queryParams,
+            SimulatorResourceModel representation,
+            PostResponseListener onPostListener);
+
+    private native void nativeStartObserve(Map<String, String> queryParams,
+            ObserveNotificationListener onObserveListener);
+
+    private native void nativeStopObserve();
+
+    private native Map<RequestType, SimulatorRequestModel> nativeSetConfigInfo(
+            String path);
+
+    private native int nativeStartAutoRequesting(RequestType type,
+            VerificationListener onVerifyListener);
+
+    private native void nativeStopAutoRequesting(int id);
+
+    private native void nativeDispose();
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/client/SimulatorRequestModel.java b/service/simulator/java/sdk/src/org/oic/simulator/client/SimulatorRequestModel.java
new file mode 100644 (file)
index 0000000..e56d8c9
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ * 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.oic.simulator.client;
+
+import java.util.Map;
+import java.util.Vector;
+
+import org.oic.simulator.ModelProperty;
+import org.oic.simulator.client.SimulatorRemoteResource.RequestType;
+
+public class SimulatorRequestModel {
+    private RequestType                 mType         = RequestType.UKNOWN;
+    private Map<String, Vector<String>> mQueryParams  = null;
+    private ModelProperty               mReqBodyModel = null;
+
+    public SimulatorRequestModel(RequestType type) {
+        mType = type;
+    }
+
+    public SimulatorRequestModel(RequestType type,
+            Map<String, Vector<String>> queryParams) {
+        mType = type;
+        mQueryParams = queryParams;
+    }
+
+    public SimulatorRequestModel(RequestType type,
+            Map<String, Vector<String>> queryParams, ModelProperty reqBodyModel) {
+        mType = type;
+        mQueryParams = queryParams;
+        mReqBodyModel = reqBodyModel;
+    }
+
+    public RequestType getType() {
+        return mType;
+    }
+
+    public Map<String, Vector<String>> getQueryParams() {
+        return mQueryParams;
+    }
+
+    public ModelProperty getRequestBodyModel() {
+        return mReqBodyModel;
+    }
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IFindResourceListener.java b/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IFindResourceListener.java
deleted file mode 100644 (file)
index dcd9557..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.clientcontroller;
-
-import org.oic.simulator.clientcontroller.SimulatorRemoteResource;
-
-/**
- * Provides interface for getting notification when resources are discovered in
- * network.
- */
-public interface IFindResourceListener {
-    /**
-     * This callback method will be called when resource is discovered in the
-     * network.
-     *
-     * @param resource
-     *            {@link SimulatorRemoteResource} object representing the
-     *            resource discovered in the network.
-     */
-    public void onResourceCallback(SimulatorRemoteResource resource);
-}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IGetListener.java b/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IGetListener.java
deleted file mode 100644 (file)
index db3e63c..0000000
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.clientcontroller;
-
-import org.oic.simulator.SimulatorResourceModel;
-
-/**
- * Interface for receiving response for GET request. An IGetListener can be
- * registered via the resource get call. Event listeners are notified
- * asynchronously.
- */
-public interface IGetListener {
-    /**
-     * This method will be called when response from the remote resource for GET
-     * request arrives.
-     *
-     * @param uId
-     *            Unique Id of the resource.
-     * @param representation
-     *            {@link SimulatorResourceModel}.
-     */
-    public void onGetCompleted(String uId, SimulatorResourceModel representation);
-
-    /**
-     * Called when there is an error in GET request.
-     *
-     * @param ex
-     *            Error information.
-     */
-    public void onGetFailed(Throwable ex);
-}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IObserveListener.java b/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IObserveListener.java
deleted file mode 100644 (file)
index 30ed0fb..0000000
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.clientcontroller;
-
-import org.oic.simulator.SimulatorResourceModel;
-
-/**
- * Provides interface for getting notification when resource model of an
- * observed resource gets changed. An IObserveListener can be registered via the
- * SimulatorRemoteResource observe call. Event listeners are notified
- * asynchronously.
- */
-public interface IObserveListener {
-    /**
-     * This method will be called when there is a change in the resource model
-     * of the remote resource.
-     *
-     * @param uId
-     *            Unique Id of the resource.
-     * @param representation
-     *            {@link SimulatorResourceModel}.
-     * @param sequenceNumber
-     *            Sequential number for ordering the model change notifications.
-     */
-    public void onObserveCompleted(String uId,
-            SimulatorResourceModel representation, int sequenceNumber);
-
-    /**
-     * Called when there is an error in observe request.
-     *
-     * @param ex
-     *            Error information.
-     */
-    public void onObserveFailed(Throwable ex);
-}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IPostListener.java b/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IPostListener.java
deleted file mode 100644 (file)
index 9949ac9..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.clientcontroller;
-
-import org.oic.simulator.SimulatorResourceModel;
-
-/**
- * Interface for receiving response for POST request. An IPostListener can be
- * registered via the resource post call. Event listeners are notified
- * asynchronously.
- */
-public interface IPostListener {
-    /**
-     * This method will be called when response from the remote resource for
-     * POST request arrives.
-     *
-     * @param uId
-     *            Unique Id of the resource.
-     * @param representation
-     *            {@link SimulatorResourceModel}.
-     */
-    public void onPostCompleted(String uId,
-            SimulatorResourceModel representation);
-
-    /**
-     * Called when there is an error in POST request.
-     *
-     * @param ex
-     *            Error information.
-     */
-    public void onPostFailed(Throwable ex);
-}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IPutListener.java b/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IPutListener.java
deleted file mode 100644 (file)
index 91a44d9..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.clientcontroller;
-
-import org.oic.simulator.SimulatorResourceModel;
-
-/**
- * Interface for receiving response for PUT request. An IPutListener can be
- * registered via the resource put call. Event listeners are notified
- * asynchronously.
- */
-public interface IPutListener {
-    /**
-     * This method will be called when response from the remote resource for PUT
-     * request arrives.
-     *
-     * @param uId
-     *            Unique Id of the resource.
-     * @param representation
-     *            {@link SimulatorResourceModel}.
-     */
-    public void onPutCompleted(String uId, SimulatorResourceModel representation);
-
-    /**
-     * Called when there is an error in PUT request.
-     *
-     * @param ex
-     *            Error information.
-     */
-    public void onPutFailed(Throwable ex);
-}
-
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IVerificationListener.java b/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IVerificationListener.java
deleted file mode 100644 (file)
index e69cdd6..0000000
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.clientcontroller;
-
-/**
- * Interface for receiving the verification status via callback. An
- * IVerificationListener can be registered via the resource startVerification
- * call. Event listeners are notified asynchronously.
- */
-public interface IVerificationListener {
-    /**
-     * Called when the verification request is accepted and started.
-     *
-     * @param uId
-     *            Unique Id of the resource.
-     * @param id
-     *            Verification Id.
-     */
-    public void onVerificationStarted(String uId, int id);
-
-    /**
-     * Called when the verification is stopped before its completion.
-     *
-     * @param uId
-     *            Unique Id of the resource.
-     * @param id
-     *            Verification Id.
-     */
-    public void onVerificationAborted(String uId, int id);
-
-    /**
-     * Called when the verification is done.
-     *
-     * @param uId
-     *            Unique Id of the resource.
-     * @param id
-     *            Verification Id.
-     */
-    public void onVerificationCompleted(String uId, int id);
-}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorConnectivityType.java b/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorConnectivityType.java
deleted file mode 100644 (file)
index a751acb..0000000
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.clientcontroller;
-
-/**
- * Supported connectivity types.
- */
-public enum SimulatorConnectivityType {
-    SIMULATOR_CT_DEFAULT(0),
-
-    /** IPv4 and IPv6, including 6LoWPAN. */
-    SIMULATOR_CT_ADAPTER_IP(1 << 16),
-
-    /** GATT over Bluetooth LE. */
-    SIMULATOR_CT_ADAPTER_GATT_BTLE(1 << 17),
-
-    /** RFCOMM over Bluetooth EDR. */
-    SIMULATOR_CT_ADAPTER_RFCOMM_BTEDR(1 << 18),
-
-    /** Remote Access over XMPP. */
-    SIMULATOR_CT_ADAPTER_REMOTE_ACCESS(1 << 19),
-
-    /** Insecure transport is the default (subject to change). */
-
-    /** secure the transport path. */
-    SIMULATOR_CT_FLAG_SECURE(1 << 4),
-
-    /** IPv4 & IPv6 autoselection is the default. */
-
-    /** IP adapter only. */
-    SIMULATOR_CT_IP_USE_V6(1 << 5),
-
-    /** IP adapter only. */
-    SIMULATOR_CT_IP_USE_V4(1 << 6),
-
-    /**
-     * Link-Local multicast is the default multicast scope for IPv6. These are
-     * placed here to correspond to the IPv6 address bits.
-     */
-
-    /** IPv6 Interface-Local scope(loopback). */
-    SIMULATOR_CT_SCOPE_INTERFACE(0x1),
-
-    /** IPv6 Link-Local scope (default). */
-    SIMULATOR_CT_SCOPE_LINK(0x2),
-
-    /** IPv6 Realm-Local scope. */
-    SIMULATOR_CT_SCOPE_REALM(0x3),
-
-    /** IPv6 Admin-Local scope. */
-    SIMULATOR_CT_SCOPE_ADMIN(0x4),
-
-    /** IPv6 Site-Local scope. */
-    SIMULATOR_CT_SCOPE_SITE(0x5),
-
-    /** IPv6 Organization-Local scope. */
-    SIMULATOR_CT_SCOPE_ORG(0x8),
-
-    /** IPv6 Global scope. */
-    SIMULATOR_CT_SCOPE_GLOBAL(0xE);
-
-    private int value;
-
-    private SimulatorConnectivityType(int value) {
-        this.value = value;
-    }
-
-    public int getValue() {
-        return this.value;
-    }
-
-    /**
-     * Method to get the {@link SimulatorConnectivityType} from an integer
-     * value.
-     *
-     * @param value
-     *            Integral value of {@link SimulatorConnectivityType}.
-     * @return {@link SimulatorConnectivityType} corresponding to the given
-     *         value.
-     */
-    public static SimulatorConnectivityType getConnectivityType(int value) {
-        SimulatorConnectivityType result = null;
-        SimulatorConnectivityType[] types = SimulatorConnectivityType.values();
-        for (SimulatorConnectivityType type : types) {
-            if (type.getValue() == value) {
-                result = type;
-                break;
-            }
-        }
-        return result;
-    }
-}
\ No newline at end of file
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorObserveType.java b/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorObserveType.java
deleted file mode 100644 (file)
index 9f32d1c..0000000
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.clientcontroller;
-
-/**
- * Enum for observe types.
- */
-public enum SimulatorObserveType {
-    OBSERVE(0), OBSERVE_ALL(1);
-
-    private int value;
-
-    private SimulatorObserveType(int value) {
-        this.value = value;
-    }
-
-    public int getValue() {
-        return this.value;
-    }
-}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorRemoteResource.java b/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorRemoteResource.java
deleted file mode 100644 (file)
index 1697681..0000000
+++ /dev/null
@@ -1,435 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.clientcontroller;
-
-import java.util.LinkedList;
-import java.util.Map;
-
-import org.oic.simulator.InvalidArgsException;
-import org.oic.simulator.NoSupportException;
-import org.oic.simulator.OperationInProgressException;
-import org.oic.simulator.SimulatorException;
-import org.oic.simulator.SimulatorResourceModel;
-import org.oic.simulator.SimulatorResult;
-
-/**
- * SimulatorRemoteResource represents a Resource running in the remote Simulator
- * Server. It comes with a well-defined contract or interface onto which you can
- * perform different operations or subscribe for event notifications.
- */
-public class SimulatorRemoteResource {
-
-    private SimulatorRemoteResource(long nativeHandle) {
-        this.nativeHandle = nativeHandle;
-    }
-
-    /**
-     * API to get the URI for this resource.
-     *
-     * @return Resource URI
-     */
-    public String getUri() {
-        return mUri;
-    }
-
-    /**
-     * API to get the observe policy of this resource.
-     *
-     * @return True if the resource is observable, otherwise false.
-     */
-    public boolean getIsObservable() {
-        return mIsObservable;
-    }
-
-    /**
-     * API to get the connectivity type for this resource.
-     *
-     * @return Connectivity type.
-     */
-    public SimulatorConnectivityType getConnectivityType() {
-        return SimulatorConnectivityType.getConnectivityType(mConnType);
-    }
-
-    /**
-     * API to get the list of resource types.
-     *
-     * @return List of resource types.
-     */
-    public LinkedList<String> getResourceTypes() {
-        return mResTypes;
-    }
-
-    /**
-     * API to get the list of resource interfaces.
-     *
-     * @return List of resource interfaces.
-     */
-    public LinkedList<String> getResourceInterfaces() {
-        return mResInterfaces;
-    }
-
-    /**
-     * API to get host address and port information of the resource.
-     *
-     * @return Host address.
-     */
-    public String getHost() {
-        return mHost;
-    }
-
-    /**
-     * API to get a unique Id of the resource .
-     *
-     * @return Unique ID.
-     */
-    public String getId() {
-        return mId;
-    }
-
-    /**
-     * API to start observing the resource.
-     *
-     * @param observeType
-     *            Allows the client to specify how it wants to observe.
-     * @param queryParamsMap
-     *            Map which can have the query parameter names and values.
-     * @param onObserveListener
-     *            The handler method which will be invoked with a map of
-     *            attribute names and values whenever there is a change in
-     *            resource model of the remote resource.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if any parameter has invalid
-     *             values.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public native void startObserve(SimulatorObserveType observeType,
-            Map<String, String> queryParamsMap,
-            IObserveListener onObserveListener) throws InvalidArgsException,
-            SimulatorException;
-
-    /**
-     * API to stop observing the resource.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if the native remote resource
-     *             object is unavailable.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public native void stopObserve() throws InvalidArgsException,
-            SimulatorException;
-
-    /**
-     * API to send GET request to the resource. Response will be notified
-     * asynchronously via callback set for {@link IGetListener}.
-     *
-     * @param queryParamsMap
-     *            Map which can have the query parameter name and value.
-     * @param onGetListener
-     *            Event handler which will be invoked with the response for GET
-     *            request with a map of attribute name and values.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if any parameter has invalid
-     *             values.
-     * @throws NoSupportException
-     *             This exception will be thrown if we cannot send GET request
-     *             to the remote resource.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public void get(Map<String, String> queryParamsMap,
-            IGetListener onGetListener) throws InvalidArgsException,
-            NoSupportException, SimulatorException {
-        if (null == onGetListener)
-            throw new InvalidArgsException(
-                    SimulatorResult.SIMULATOR_INVALID_PARAM.ordinal(),
-                    "Parameter passed in invalid");
-        this.nativeGet(null, queryParamsMap, onGetListener);
-    }
-
-    /**
-     * API to send GET request to the resource. Response will be notified
-     * asynchronously via callback set for {@link IGetListener}.
-     *
-     * @param resourceInterface
-     *            Interface type of the resource to operate on.
-     * @param queryParamsMap
-     *            Map which can have the query parameter name and value.
-     * @param onGetListener
-     *            Event handler which will be invoked with the response for GET
-     *            request with a map of attribute name and values.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if any parameter has invalid
-     *             values.
-     * @throws NoSupportException
-     *             This exception will be thrown if we cannot send GET request
-     *             to the remote resource.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public void get(String resourceInterface,
-            Map<String, String> queryParamsMap, IGetListener onGetListener)
-            throws InvalidArgsException, NoSupportException, SimulatorException {
-        if (null == resourceInterface || resourceInterface.isEmpty() || null == onGetListener)
-            throw new InvalidArgsException(
-                    SimulatorResult.SIMULATOR_INVALID_PARAM.ordinal(),
-                    "Parameter passed in invalid");
-        this.nativeGet(resourceInterface, queryParamsMap, onGetListener);
-    }
-
-    private native void nativeGet(String resourceInterface,
-            Map<String, String> queryParamsMap, IGetListener onGetListener)
-            throws InvalidArgsException, NoSupportException, SimulatorException;
-
-    /**
-     * API to send PUT request to the resource. Response will be notified
-     * asynchronously via callback set for {@link IPutListener}.
-     *
-     * @param representation
-     *            {@link SimulatorResourceModel} holding the representation of
-     *            the resource.
-     * @param queryParamsMap
-     *            Map which can have the query parameter name and value.
-     * @param onPutListener
-     *            Event handler which will be invoked with the response for PUT
-     *            request with a map of attribute name and values.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if any parameter has invalid
-     *             value.
-     * @throws NoSupportException
-     *             This exception will be thrown if we cannot send PUT request
-     *             to the remote resource.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public void put(SimulatorResourceModel representation,
-            Map<String, String> queryParamsMap, IPutListener onPutListener)
-            throws InvalidArgsException, NoSupportException, SimulatorException {
-        if (null == representation || null == onPutListener)
-            throw new InvalidArgsException(
-                    SimulatorResult.SIMULATOR_INVALID_PARAM.ordinal(),
-                    "Parameter passed in invalid");
-        this.nativePut(null, representation, queryParamsMap, onPutListener);
-    }
-
-    /**
-     * API to send PUT request to the resource. Response will be notified
-     * asynchronously via callback set for {@link IPutListener}.
-     *
-     * @param resourceInterface
-     *            Interface type of the resource to operate on.
-     * @param representation
-     *            {@link SimulatorResourceModel} holding the representation of
-     *            the resource.
-     * @param queryParamsMap
-     *            Map which can have the query parameter name and value.
-     * @param onPutListener
-     *            Event handler which will be invoked with the response for PUT
-     *            request with a map of attribute name and values.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if any parameter has invalid
-     *             value.
-     * @throws NoSupportException
-     *             This exception will be thrown if we cannot send PUT request
-     *             to the remote resource.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public void put(String resourceInterface,
-            SimulatorResourceModel representation,
-            Map<String, String> queryParamsMap, IPutListener onPutListener)
-            throws InvalidArgsException, NoSupportException, SimulatorException {
-        if (null == resourceInterface || resourceInterface.isEmpty() ||
-            null == representation || null == onPutListener)
-            throw new InvalidArgsException(
-                    SimulatorResult.SIMULATOR_INVALID_PARAM.ordinal(),
-                    "Parameter passed in invalid");
-        this.nativePut(resourceInterface, representation, queryParamsMap, onPutListener);
-    }
-
-    private native void nativePut(String resourceInterface,
-            SimulatorResourceModel representation,
-            Map<String, String> queryParamsMap, IPutListener onPutListener)
-            throws InvalidArgsException, NoSupportException, SimulatorException;
-
-    /**
-     * API to send POST request to the resource. Response will be notified
-     * asynchronously via callback set for {@link IPostListener}.
-     *
-     * @param representation
-     *            {@link SimulatorResourceModel} holding the representation of
-     *            the resource
-     * @param queryParamsMap
-     *            Map which can have the query parameter name and value
-     * @param onPostListener
-     *            Event handler which will be invoked with the response for POST
-     *            request with a map of attribute name and values.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if any parameter has invalid
-     *             value.
-     * @throws NoSupportException
-     *             This exception will be thrown if we cannot send POST request
-     *             on the remote resource.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public void post(SimulatorResourceModel representation,
-            Map<String, String> queryParamsMap, IPostListener onPostListener)
-            throws InvalidArgsException, NoSupportException, SimulatorException {
-        if (null == representation || null == onPostListener)
-            throw new InvalidArgsException(
-                    SimulatorResult.SIMULATOR_INVALID_PARAM.ordinal(),
-                    "Parameter passed in invalid");
-        this.nativePost(null, representation, queryParamsMap, onPostListener);
-    }
-
-    /**
-     * API to send POST request to the resource. Response will be notified
-     * asynchronously via callback set for {@link IPostListener}.
-     *
-     * @param resourceInterface
-     *            Interface type of the resource to operate on.
-     * @param representation
-     *            {@link SimulatorResourceModel} holding the representation of
-     *            the resource.
-     * @param queryParamsMap
-     *            Map which can have the query parameter name and value.
-     * @param onPostListener
-     *            Event handler which will be invoked with the response for POST
-     *            request with a map of attribute name and values.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if any parameter has invalid
-     *             value.
-     * @throws NoSupportException
-     *             This exception will be thrown if we cannot send POST request
-     *             on the remote resource.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public void post(String resourceInterface,
-            SimulatorResourceModel representation,
-            Map<String, String> queryParamsMap, IPostListener onPostListener)
-            throws InvalidArgsException, NoSupportException, SimulatorException {
-        if (null == resourceInterface || resourceInterface.isEmpty() ||
-            null == representation || null == onPostListener)
-            throw new InvalidArgsException(
-                SimulatorResult.SIMULATOR_INVALID_PARAM.ordinal(),
-                "Parameter passed in invalid");
-        this.nativePost(resourceInterface, representation, queryParamsMap, onPostListener);
-    }
-
-    private native void nativePost(String resourceInterface,
-            SimulatorResourceModel representation,
-            Map<String, String> queryParamsMap, IPostListener onPostListener)
-            throws InvalidArgsException, NoSupportException, SimulatorException;
-
-    /**
-     * API to provide remote resource configure information,
-     * which is required for using automation feature.
-     *
-     * @param path
-     *            Path to RAML file.
-     *
-     * @throws InvalidArgsException
-     *             Thrown if the RAML configuration file path is invalid.
-     * @throws SimulatorException
-     *             Thrown for other errors.
-     */
-    public native void setConfigInfo(String path)
-            throws InvalidArgsException, SimulatorException;
-
-    /**
-     * API to send multiple requests for the resource, based on
-     * the configure file provided from {@link setConfigInfo}.
-     * This verifies response received as well.
-     *
-     * @param requestType
-     *            Request type to verify.
-     * @param onVerifyListener
-     *            This event handler will be invoked with the current status of
-     *            the automation.
-     *
-     * @return Automation ID.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if any parameter has invalid
-     *             value.
-     * @throws NoSupportException
-     *             Thrown either if the resource does not support the request
-     *             type or the resource is not configured with RAML.
-     * @throws OperationInProgressException
-     *             Thrown if another request generation session is already in
-     *             progress.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public int startVerification(SimulatorVerificationType requestType,
-            IVerificationListener onVerifyListener)
-            throws InvalidArgsException, NoSupportException,
-            OperationInProgressException, SimulatorException {
-        return startVerification(requestType.ordinal(), onVerifyListener);
-    }
-
-    /**
-     * API to stop sending requests which has been started using {@link setConfigInfo}.
-     *
-     * @param id
-     *            Automation ID.
-     *
-     * @throws InvalidArgsException
-     *             Thrown if the automation ID is invalid.
-     * @throws NoSupportException
-     *             Thrown if the resource is not configured with RAML.
-     * @throws SimulatorException
-     *             Thrown for other errors.
-     */
-    public native void stopVerification(int id) throws InvalidArgsException,
-            NoSupportException, SimulatorException;
-
-    private native int startVerification(int requestType,
-            IVerificationListener onVerifyListener)
-            throws InvalidArgsException, NoSupportException,
-            OperationInProgressException, SimulatorException;
-
-    @Override
-    protected void finalize() throws Throwable {
-        try {
-            dispose();
-        } finally {
-            super.finalize();
-        }
-    }
-
-    private native void dispose();
-
-    private long               nativeHandle;
-    private String             mUri;
-    private int                mConnType;
-    private String             mHost;
-    private String             mId;
-    private LinkedList<String> mResTypes;
-    private LinkedList<String> mResInterfaces;
-    private boolean            mIsObservable;
-}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorVerificationType.java b/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorVerificationType.java
deleted file mode 100644 (file)
index ccb0c36..0000000
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.clientcontroller;
-
-/**
- * Types of automatic verification.
- */
-public enum SimulatorVerificationType {
-    RQ_TYPE_GET(0), RQ_TYPE_PUT(1), RQ_TYPE_POST(2), RQ_TYPE_DELETE(3);
-
-    private int value;
-
-    private SimulatorVerificationType(int value) {
-        this.value = value;
-    }
-
-    public int getValue() {
-        return this.value;
-    }
-
-    /**
-     * Method to get the {@link SimulatorVerificationType} from an integer
-     * value.
-     *
-     * @param value
-     *            Integral value of {@link SimulatorVerificationType}.
-     * @return {@link SimulatorVerificationType} corresponding to the given
-     *         value.
-     */
-    public static SimulatorVerificationType getVerificationType(int value) {
-        SimulatorVerificationType result = null;
-        SimulatorVerificationType[] types = SimulatorVerificationType.values();
-        for (SimulatorVerificationType type : types) {
-            if (type.getValue() == value) {
-                result = type;
-                break;
-            }
-        }
-        return result;
-    }
-}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/server/Observer.java b/service/simulator/java/sdk/src/org/oic/simulator/server/Observer.java
new file mode 100644 (file)
index 0000000..26e3cca
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator.server;
+
+/**
+ * Class which represents the details of an observer.
+ */
+public class Observer {
+
+    private int    mId;
+    private String mAddress;
+    private int    mPort;
+
+    private Observer(int id, String address, int port) {
+        mId = id;
+        mAddress = address;
+        mPort = port;
+    }
+
+    /**
+     * This method is used to return the observer's id.
+     *
+     * @return Observer's Id.
+     */
+    public int getId() {
+        return mId;
+    }
+
+    /**
+     * This method is used to return the observer's address.
+     *
+     * @return Observer's device address.
+     */
+    public String getAddress() {
+        return mAddress;
+    }
+
+    /**
+     * This method is used to return the observer's port number.
+     *
+     * @return Observer's port number.
+     */
+    public int getPort() {
+        return mPort;
+    }
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/server/SimulatorCollectionResource.java b/service/simulator/java/sdk/src/org/oic/simulator/server/SimulatorCollectionResource.java
new file mode 100644 (file)
index 0000000..65ff45c
--- /dev/null
@@ -0,0 +1,107 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator.server;
+
+import java.util.Vector;
+
+import org.oic.simulator.InvalidArgsException;
+import org.oic.simulator.SimulatorException;
+
+/**
+ * This class represents a collection type resource which provides a set of APIs
+ * that are specific to collection resource for adding/removing child resources
+ * and obtaining all child resources from the collection.
+ */
+public final class SimulatorCollectionResource extends SimulatorResource {
+
+    /**
+     * API to add child resource to collection.
+     *
+     * @param resource
+     *            Child resource to be added to collection.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown on invalid input.
+     * @throws SimulatorException
+     *             This exception will be thrown on occurrence of error in
+     *             native.
+     */
+    public void addChildResource(SimulatorResource resource)
+            throws InvalidArgsException, SimulatorException {
+        nativeAddChildResource(resource);
+    }
+
+    /**
+     * API to remove child resource from collection.
+     *
+     * @param resource
+     *            Child resource to be removed from collection.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown on invalid input.
+     * @throws SimulatorException
+     *             This exception will be thrown on occurrence of error in
+     *             native.
+     */
+    public void removeChildResource(SimulatorResource resource)
+            throws InvalidArgsException, SimulatorException {
+        nativeRemoveChildResource(resource);
+    }
+
+    /**
+     * API to remove child resource from collection.
+     *
+     * @param uri
+     *            URI of child resource to be removed from collection.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown on invalid input.
+     * @throws SimulatorException
+     *             This exception will be thrown on occurrence of error in
+     *             native.
+     */
+    public void removeChildResourceByUri(String uri)
+            throws InvalidArgsException, SimulatorException {
+        nativeRemoveChildResourceByUri(uri);
+    }
+
+    /**
+     * API to get list of child resources.
+     *
+     * @return Vector of child resources {@link SimulatorResource}.
+     *
+     * @throws SimulatorException
+     *             This exception will be thrown on occurrence of error in
+     *             native.
+     */
+    public Vector<SimulatorResource> getChildResources()
+            throws SimulatorException {
+        return nativeGetChildResources();
+    }
+
+    private SimulatorCollectionResource(long nativeHandle) {
+        mNativeHandle = nativeHandle;
+    }
+
+    private native void nativeAddChildResource(SimulatorResource resource);
+
+    private native void nativeRemoveChildResource(SimulatorResource resource);
+
+    private native void nativeRemoveChildResourceByUri(String uri);
+
+    private native Vector<SimulatorResource> nativeGetChildResources();
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/server/SimulatorResource.java b/service/simulator/java/sdk/src/org/oic/simulator/server/SimulatorResource.java
new file mode 100644 (file)
index 0000000..be548d6
--- /dev/null
@@ -0,0 +1,546 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator.server;
+
+import java.util.Vector;
+
+import org.oic.simulator.InvalidArgsException;
+import org.oic.simulator.NoSupportException;
+import org.oic.simulator.SimulatorException;
+import org.oic.simulator.SimulatorResourceModel;
+
+/**
+ * This class serves as a base class type for all the resources in the
+ * simulator. It provides APIs to get and update the resource details, and
+ * register listeners to get notifications for resource model changes and
+ * observe requests from clients, and APIs to register/ unregister the resource
+ * with the platform.
+ */
+public class SimulatorResource {
+
+    protected long mNativeHandle;
+
+    @Override
+    protected void finalize() throws Throwable {
+        try {
+            nativeDispose();
+        } catch (Throwable t) {
+            throw t;
+        } finally {
+            super.finalize();
+        }
+    }
+
+    /**
+     * Enum to represent the type of resource.
+     */
+    public enum Type {
+        SINGLE, COLLECTION
+    }
+
+    /**
+     * Enum to represent the update type of automation.
+     */
+    public enum AutoUpdateType {
+        ONE_TIME, REPEAT
+    }
+
+    /**
+     * API which indicates whether the resource is collection or single
+     * resource.
+     *
+     * @return True if the resource is collection, otherwise false.
+     */
+    public boolean isCollection() {
+        return (this instanceof SimulatorCollectionResource);
+    }
+
+    /**
+     * API to get the type which indicates whether resource is single or
+     * collection resource.
+     *
+     * @return Type of resource.
+     */
+    public Type getType() {
+        if (this instanceof SimulatorSingleResource) {
+            return Type.SINGLE;
+        } else {
+            return Type.COLLECTION;
+        }
+    }
+
+    /**
+     * API to get the name of the resource.
+     *
+     * @return Name of the resource.
+     *
+     * @throws SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or for some general errors.
+     */
+    public String getName() throws SimulatorException {
+        return nativeGetName();
+    }
+
+    /**
+     * API to get the resource URI.
+     *
+     * @return Resource URI.
+     *
+     * @throws SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or for some general errors.
+     */
+    public String getURI() throws SimulatorException {
+        return nativeGetURI();
+    }
+
+    /**
+     * API to get the resource type.
+     *
+     * @return Resource type.
+     *
+     * @throws SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or for some general errors.
+     */
+    public String getResourceType() throws SimulatorException {
+        return nativeGetResourceType();
+    }
+
+    /**
+     * API to get the interfaces resource is bound with.
+     *
+     * @return Interface types.
+     *
+     * @throws SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or for some general errors.
+     */
+    public Vector<String> getInterface() throws SimulatorException {
+        return nativeGetInterface();
+    }
+
+    /**
+     * API to get the observable state of resource.
+     *
+     * @return Observable state - true if resource is observable, otherwise
+     *         false.
+     *
+     * @throws SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or for some general errors.
+     */
+    public boolean isObservable() throws SimulatorException {
+        return nativeIsObservable();
+    }
+
+    /**
+     * API to get the discoverable state of resource.
+     *
+     * @return Discoverable state - true if resource is discoverable, otherwise
+     *         false.
+     *
+     * @throws SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or for some general errors.
+     */
+    public boolean isDiscoverable() throws SimulatorException {
+        return nativeIsDiscoverable();
+    }
+
+    /**
+     * API to get the start state of resource.
+     *
+     * @return Start state - true if resource is started, otherwise false.
+     *
+     * @throws SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or for some general errors.
+     */
+    public boolean isStarted() throws SimulatorException {
+        return nativeIsStarted();
+    }
+
+    /**
+     * API to set the name of the resource.
+     *
+     * @param name
+     *            Name to be set.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown if the resource name is
+     *             invalid.
+     * @throws SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or for some general errors.
+     */
+    public void setName(String name) throws InvalidArgsException,
+            SimulatorException {
+        nativeSetName(name);
+    }
+
+    /**
+     * API to set the resource URI.
+     *
+     * @param uri
+     *            URI to be set.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown if the resource URI is invalid.
+     * @throws SimulatorException
+     *             A resource needs to be stopped by calling the stop() before
+     *             calling this API. This exception will be thrown if the native
+     *             resource object has not yet been stopped.
+     */
+    public void setURI(String uri) throws InvalidArgsException,
+            SimulatorException {
+        nativeSetURI(uri);
+    }
+
+    /**
+     * API to set the resource type.
+     *
+     * @param resourceType
+     *            Resource type string.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown if the resource type is
+     *             invalid.
+     * @throws SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or for some general errors.
+     */
+    public void setResourceType(String resourceType)
+            throws InvalidArgsException, SimulatorException {
+        nativeSetResourceType(resourceType);
+    }
+
+    /**
+     * API to set interface to resource. Resource should be stopped before
+     * calling this API.
+     *
+     * @param interfaceType
+     *            Interface to be set.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown if the interface type is
+     *             invalid.
+     * @throws SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or resource is still running or for some
+     *             general errors.
+     */
+    public void setInterface(String interfaceType) throws InvalidArgsException,
+            SimulatorException {
+        nativeSetInterface(interfaceType);
+    }
+
+    /**
+     * API to set a list of interfaces to resource. Resource should be stopped
+     * before calling this API.
+     *
+     * @param interfaceTypes
+     *            Interfaces to be set.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown if the interface type is
+     *             invalid.
+     * @throws SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or resource is still running or for some
+     *             general errors.
+     */
+    public void setInterface(Vector<String> interfaceTypes)
+            throws InvalidArgsException, SimulatorException {
+        nativeSetInterfaces(interfaceTypes);
+    }
+
+    /**
+     * API to add interface type for resource.
+     *
+     * @param interfaceType
+     *            Interface to be added for resource.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown if the interface type is
+     *             invalid.
+     * @throws NoSupportException
+     *             This exception will be thrown if the interface type is not
+     *             supported by the resource.
+     * @throws SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or for some general errors.
+     */
+    public void addInterface(String interfaceType) throws InvalidArgsException,
+            NoSupportException, SimulatorException {
+        nativeAddInterface(interfaceType);
+    }
+
+    /**
+     * API to make the resource observable or not observable.
+     *
+     * @param state
+     *            True makes the resource observable, otherwise non-observable.
+     *
+     * @throws SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or for some general errors.
+     */
+    public void setObservable(boolean state) throws SimulatorException {
+        nativeSetObservable(state);
+    }
+
+    /**
+     * API to make the resource discoverable or not discoverable.
+     *
+     * @param state
+     *            True makes the resource discoverable, otherwise
+     *            non-discoverable.
+     *
+     * @throws SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or for some general errors.
+     */
+    public void setDiscoverable(boolean state) throws SimulatorException {
+        nativeSetDiscoverable(state);
+    }
+
+    /**
+     * API to set the listener for receiving the notifications when observer is
+     * registered or unregistered with resource.
+     *
+     * @param listener
+     *            Callback to be set for receiving the notifications.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown if the listener is invalid.
+     * @throws SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or for some general errors.
+     */
+    public void setObserverListener(ObserverListener listener)
+            throws InvalidArgsException, SimulatorException {
+        nativeSetObserverListener(listener);
+    }
+
+    /**
+     * API to set listener for receiving notifications when resource's model
+     * gets changed.
+     *
+     * @param listener
+     *            {@link ResourceModelChangeListener}.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown on invalid input.
+     * @throws SimulatorException
+     *             This exception will be thrown for other errors.
+     */
+    public void setResourceModelChangeListener(
+            ResourceModelChangeListener listener) throws InvalidArgsException,
+            SimulatorException {
+        nativeSetResourceModelChangeListener(listener);
+    }
+
+    /**
+     * API to start(register) the resource.
+     *
+     * @throws SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or for some general errors.
+     */
+    public void start() throws SimulatorException {
+        nativeStart();
+    }
+
+    /**
+     * API to stop(unregister) the resource.
+     *
+     * @throws SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or for some general errors.
+     */
+    public void stop() throws SimulatorException {
+        nativeStop();
+    }
+
+    /**
+     * API to get the {@link SimulatorResourceModel} of the simulated resource.
+     *
+     * @return {@link SimulatorResourceModel} object on success, otherwise null.
+     *
+     * @throws SimulatorException
+     *             This exception will be thrown if simulated resource is not
+     *             proper.
+     */
+    public SimulatorResourceModel getResourceModel() throws SimulatorException {
+        return nativeGetResourceModel();
+    }
+
+    /**
+     * API to get observers which are registered with resource.
+     *
+     * @return observers as an array of {@link Observer}.
+     *
+     * @throws SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or for some general errors.
+     */
+    public Vector<Observer> getObservers() throws SimulatorException {
+        return nativeGetObservers();
+    }
+
+    /**
+     * API to notify current resource model to a specific observer.
+     *
+     * @param observerId
+     *            Observer ID to notify.
+     *
+     * @throws SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or for some general errors.
+     */
+    public void notifyObserver(int observerId) throws SimulatorException {
+        nativeNotify(observerId);
+    }
+
+    /**
+     * API to notify current resource model to all registered observers.
+     *
+     * @throws SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or for some general errors.
+     */
+    public void notifyAllObservers() throws SimulatorException {
+        nativeNotifyAll();
+    }
+
+    /**
+     * Listener for receiving notification when observer is registered or
+     * unregistered with the resource.
+     */
+    public interface ObserverListener {
+        /**
+         * Method will be invoked when an observer is registered with resource.
+         *
+         * @param resourceURI
+         *            URI of the resource.
+         * @param observer
+         *            {@link Observer} object containing the details of
+         *            observer.
+         */
+        public void onObserverAdded(String resourceURI, Observer observer);
+
+        /**
+         * Method will be invoked when an observer is unregistered from the
+         * resource.
+         *
+         * @param resourceURI
+         *            URI of the resource.
+         * @param observer
+         *            {@link Observer} object containing the details of
+         *            observer.
+         */
+        public void onObserverRemoved(String resourceURI, Observer observer);
+    }
+
+    /**
+     * Listener for receiving notification on completion of automatically
+     * updating attribute value from its range or value set property.
+     */
+    public interface AutoUpdateListener {
+        /**
+         * Method for receiving automation complete notifications.
+         *
+         * @param uri
+         *            URI of resource.
+         * @param id
+         *            Identifier for auto resource/attribute update session.
+         */
+        public void onUpdateComplete(String uri, int id);
+    }
+
+    /**
+     * Listener for receiving notifications whenever there is a change in the
+     * resource model.
+     */
+    public interface ResourceModelChangeListener {
+        /**
+         * Method will be invoked to notify about the changes in the resource
+         * model.
+         *
+         * @param uri
+         *            URI of resource.
+         * @param resourceModel
+         *            {@link SimulatorResourceModel} of the resource.
+         */
+        public void onResourceModelChanged(String uri,
+                SimulatorResourceModel resourceModel);
+    }
+
+    protected SimulatorResource() {
+    }
+
+    private native String nativeGetName();
+
+    private native String nativeGetURI();
+
+    private native String nativeGetResourceType();
+
+    private native Vector<String> nativeGetInterface();
+
+    private native boolean nativeIsObservable();
+
+    private native boolean nativeIsDiscoverable();
+
+    private native boolean nativeIsStarted();
+
+    private native void nativeSetName(String name);
+
+    private native void nativeSetURI(String uri);
+
+    private native void nativeSetResourceType(String resourceType);
+
+    private native void nativeSetInterface(String interfaceType);
+
+    private native void nativeSetInterfaces(Vector<String> interfaceTypes);
+
+    private native void nativeAddInterface(String interfaceType);
+
+    private native void nativeSetObservable(boolean state);
+
+    private native void nativeSetDiscoverable(boolean state);
+
+    private native void nativeSetObserverListener(ObserverListener listener);
+
+    private native void nativeSetResourceModelChangeListener(
+            ResourceModelChangeListener listener);
+
+    private native void nativeStart();
+
+    private native void nativeStop();
+
+    private native SimulatorResourceModel nativeGetResourceModel();
+
+    private native Vector<Observer> nativeGetObservers();
+
+    private native void nativeNotify(int observerId);
+
+    private native void nativeNotifyAll();
+
+    private native void nativeDispose();
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/server/SimulatorSingleResource.java b/service/simulator/java/sdk/src/org/oic/simulator/server/SimulatorSingleResource.java
new file mode 100644 (file)
index 0000000..157668d
--- /dev/null
@@ -0,0 +1,222 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator.server;
+
+import java.util.Map;
+
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.InvalidArgsException;
+import org.oic.simulator.SimulatorException;
+import org.oic.simulator.SimulatorResourceAttribute;
+
+/**
+ * This class represents a single type resource(Non-collection resource). It
+ * provides APIs specific to single resource for manipulating the resource model
+ * by adding/removing the attributes, and updating the attribute values manually
+ * and automatically.
+ */
+public final class SimulatorSingleResource extends SimulatorResource {
+
+    /**
+     * API to get attribute of resource.
+     *
+     * @param attrName
+     *            Name of the attribute
+     *
+     * @return An object of {@link SimulatorResourceAttribute}, or null if
+     *         resource does not have attribute of this name.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown if the attribute name is
+     *             invalid.
+     * @throws SimulatorException
+     *             This exception will be thrown either if the resource model is
+     *             not found or for some general errors.
+     */
+    public SimulatorResourceAttribute getAttribute(String attrName)
+            throws InvalidArgsException, SimulatorException {
+        return nativeGetAttribute(attrName);
+    }
+
+    /**
+     * API to get all the attributes of the resource.
+     *
+     * @return Map of attributes with attribute name as key and its
+     *         corresponding {@link SimulatorResourceAttribute} as value.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown if the attribute name is
+     *             invalid.
+     * @throws SimulatorException
+     *             This exception will be thrown either if the resource model is
+     *             not found or for some general errors.
+     */
+    public Map<String, SimulatorResourceAttribute> getAttributes()
+            throws InvalidArgsException, SimulatorException {
+        return nativeGetAttributes();
+    }
+
+    /**
+     * API to add an attribute to resource's representation model. Observers
+     * will be notified on success.
+     *
+     * @param attribute
+     *            Attribute to be added to resource's representation model.
+     *
+     * @return True if the attribute is added properly.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown on invalid input.
+     * @throws SimulatorException
+     *             This exception will be thrown for other errors.
+     */
+    public boolean addAttribute(SimulatorResourceAttribute attribute)
+            throws InvalidArgsException, SimulatorException {
+        return nativeAddAttribute(attribute);
+    }
+
+    /**
+     * API to remove an attribute from the simulated resource. Observers will be
+     * notified on success.
+     *
+     * @param attrName
+     *            Name of the attribute to be deleted.
+     *
+     * @return True if the attribute is removed properly.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown on invalid input.
+     * @throws SimulatorException
+     *             This exception will be thrown for other errors.
+     */
+    public boolean removeAttribute(String attrName)
+            throws InvalidArgsException, SimulatorException {
+        return nativeRemoveAttribute(attrName);
+    }
+
+    /**
+     * API to update the value of an attribute. Observers will be notified on
+     * success.
+     *
+     * @param attrName
+     *            Name of the attribute.
+     * @param value
+     *            New value of the attribute.
+     *
+     * @return True if the attribute's value is updated properly.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown on invalid input.
+     * @throws SimulatorException
+     *             This exception will be thrown for other errors.
+     */
+    public boolean updateAttribute(String attrName, AttributeValue value)
+            throws InvalidArgsException, SimulatorException {
+        return nativeUpdateAttribute(attrName, value);
+    }
+
+    /**
+     * API to start the resource level automation. This automation involves
+     * automatically updating all the possible values for all the attributes
+     * sequentially.
+     *
+     * @param type
+     *            {@link AutoUpdateType} indicating whether the automation is
+     *            one-time or recursive.
+     * @param interval
+     *            Interval time in milliseconds.
+     * @param listener
+     *            Listener to be notified when automation ends.
+     *
+     * @return Automation ID using which the automation can be stopped.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown on invalid input.
+     * @throws SimulatorException
+     *             This exception will be thrown for other errors.
+     */
+    public int startResourceUpdation(AutoUpdateType type, int interval,
+            AutoUpdateListener listener) throws InvalidArgsException,
+            SimulatorException {
+        return nativeStartResourceUpdation(type, interval, listener);
+    }
+
+    /**
+     * API to start the attribute level automation. This automation involves
+     * automatically updating all the possible values for a given attribute
+     * sequentially.
+     *
+     * @param attrName
+     *            Name of the attribute to be automated.
+     * @param type
+     *            {@link AutoUpdateType} indicating whether the automation is
+     *            one-time or recursive.
+     * @param interval
+     *            Interval time in milliseconds.
+     * @param listener
+     *            Listener to be notified when automation ends.
+     *
+     * @return Automation ID using which the automation can be stopped.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown on invalid input.
+     * @throws SimulatorException
+     *             This exception will be thrown for other errors.
+     */
+    public int startAttributeUpdation(String attrName, AutoUpdateType type,
+            int interval, AutoUpdateListener listener)
+            throws InvalidArgsException, SimulatorException {
+        return nativeStartAttributeUpdation(attrName, type, interval, listener);
+    }
+
+    /**
+     * API to stop the automation based on automation id.
+     *
+     * @param id
+     *            Using which a specific automation can be stopped.
+     *
+     * @throws SimulatorException
+     *             This exception will be thrown for general errors.
+     */
+    public void stopUpdation(int id) throws SimulatorException {
+        nativeStopUpdation(id);
+    }
+
+    private SimulatorSingleResource(long nativeHandle) {
+        mNativeHandle = nativeHandle;
+    }
+
+    private native SimulatorResourceAttribute nativeGetAttribute(String attrName);
+
+    private native Map<String, SimulatorResourceAttribute> nativeGetAttributes();
+
+    private native boolean nativeAddAttribute(
+            SimulatorResourceAttribute attribute);
+
+    private native boolean nativeRemoveAttribute(String attrName);
+
+    private native boolean nativeUpdateAttribute(String attrName,
+            AttributeValue value);
+
+    private native int nativeStartResourceUpdation(AutoUpdateType type,
+            int interval, AutoUpdateListener listener);
+
+    private native int nativeStartAttributeUpdation(String attrName,
+            AutoUpdateType type, int interval, AutoUpdateListener listener);
+
+    private native void nativeStopUpdation(int id);
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/AutomationType.java b/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/AutomationType.java
deleted file mode 100644 (file)
index 06409ff..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.serviceprovider;
-
-/**
- * This enum contains the different levels of server side automation which are
- * supported by the simulator.
- */
-public enum AutomationType {
-    NORMAL(0), RECURRENT(1);
-
-    private int value;
-
-    private AutomationType(int value) {
-        this.value = value;
-    }
-
-    public int getValue() {
-        return this.value;
-    }
-}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/IObserver.java b/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/IObserver.java
deleted file mode 100644 (file)
index 0dceda2..0000000
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.serviceprovider;
-
-/**
- * Interface for receiving the observe notifications.
- */
-public interface IObserver {
-    /**
-     * This callback method will be called when a new observer is added or an
-     * existing observer is removed.
-     *
-     * @param resourceURI
-     *            URI of the resource.
-     * @param state
-     *            Indicates whether an observer is added or removed.
-     * @param observer
-     *            {@link ObserverInfo} object containing the details of
-     *            observer.
-     */
-    public void onObserverChanged(String resourceURI, int state,
-            ObserverInfo observer);
-}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/IResourceModelChangedListener.java b/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/IResourceModelChangedListener.java
deleted file mode 100644 (file)
index 744116b..0000000
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.serviceprovider;
-
-import org.oic.simulator.SimulatorResourceModel;
-
-/**
- * Interface for receiving notifications whenever there is a change in the
- * resource model.
- */
-public interface IResourceModelChangedListener {
-    /**
-     * This callback method will be called to notify about the changes in the
-     * resource model.
-     *
-     * @param resourceURI
-     *            URI of resource.
-     * @param resourceModel
-     *            {@link SimulatorResourceModel} of the resource.
-     */
-    public void onResourceModelChanged(String resourceURI,
-            SimulatorResourceModel resourceModel);
-}
\ No newline at end of file
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/ObserverInfo.java b/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/ObserverInfo.java
deleted file mode 100644 (file)
index 1672abc..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.serviceprovider;
-
-/**
- * Class which represents the details of an observer.
- */
-public class ObserverInfo {
-
-    private int    id;
-    private String address;
-    private int    port;
-
-    private ObserverInfo(int id, String address, int port) {
-        this.id = id;
-        this.address = address;
-        this.port = port;
-    }
-
-    /**
-     * This method is used to return the observer's id.
-     *
-     * @return Observer's Id.
-     */
-    public int getId() {
-        return id;
-    }
-
-    /**
-     * This method is used to return the observer's address.
-     *
-     * @return Observer's device address.
-     */
-    public String getAddress() {
-        return address;
-    }
-
-    /**
-     * This method is used to return the observer's port number.
-     *
-     * @return Observer's port number.
-     */
-    public int getPort() {
-        return port;
-    }
-}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/SimulatorResourceServer.java b/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/SimulatorResourceServer.java
deleted file mode 100644 (file)
index d601b53..0000000
+++ /dev/null
@@ -1,488 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.serviceprovider;
-
-import java.util.Vector;
-
-import org.oic.simulator.IAutomation;
-import org.oic.simulator.InvalidArgsException;
-import org.oic.simulator.SimulatorException;
-import org.oic.simulator.SimulatorResourceModel;
-
-/**
- * This class represents a resource in the simulator. It provides a set of
- * native methods for manipulating the simulated resource by adding and removing
- * attributes to its model, automating the attribute value updates, and changing
- * the range of acceptable values of the attributes.
- */
-public class SimulatorResourceServer {
-
-    private String resourceName;
-    private String resourceURI;
-    private String resourceType;
-    private String interfaceType;
-
-    private long   nativeHandle;
-
-    private SimulatorResourceServer(long nativeHandle) {
-        this.nativeHandle = nativeHandle;
-    }
-
-    /**
-     * API to get the resource name. Example: Light, Fan, etc.
-     *
-     * @return Resource name.
-     */
-    public String getName() {
-        return resourceName;
-    }
-
-    /**
-     * API to get the resource URI. Example: /oic/light, /oic/fan, etc.
-     *
-     * @return Resource URI.
-     */
-    public String getURI() {
-        return resourceURI;
-    }
-
-    /**
-     * API to get the resource Type. Example: oic.light, oic.fan, etc.
-     *
-     * @return Resource type.
-     */
-    public String getResourceType() {
-        return resourceType;
-    }
-
-    /**
-     * API to get the interface type of the resource. Example: oic.if.baseline,
-     * oic.if.b, etc.
-     *
-     * @return Interface type of the resource.
-     */
-    public String getInterfaceType() {
-        return interfaceType;
-    }
-
-   /**
-     * API to get the {@link SimulatorResourceModel} of the
-     * simulated resource.
-     *
-     * @return {@link SimulatorResourceModel} object on success, otherwise null.
-     *
-     * @throws SimulatorException
-     *             This exception will be thrown if simulated resource is not proper.
-     */
-    public native SimulatorResourceModel getModel()
-            throws SimulatorException;
-
-    /**
-     * API to add an attribute whose value is of type int.
-     *
-     * @param key
-     *            Name of the attribute.
-     * @param value
-     *            Initial value of the attribute.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if any parameter has invalid
-     *             values.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public native void addAttributeInteger(String key, int value)
-            throws InvalidArgsException, SimulatorException;
-
-    /**
-     * API to  add an attribute whose value is of type double.
-     *
-     * @param key
-     *            Name of the attribute.
-     * @param value
-     *            Initial value of the attribute.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if any parameter has invalid
-     *             values.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public native void addAttributeDouble(String key, double value)
-            throws InvalidArgsException, SimulatorException;
-
-    /**
-     * API to  add an attribute whose value is of type boolean.
-     *
-     * @param key
-     *            Name of the attribute.
-     * @param value
-     *            Initial value of the attribute.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if any parameter has invalid
-     *             values.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public native void addAttributeBoolean(String key, boolean value)
-            throws InvalidArgsException, SimulatorException;
-
-    /**
-     * API to  add an attribute whose value is of type String.
-     *
-     * @param key
-     *            Name of the attribute.
-     * @param value
-     *            Initial value of the attribute.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if any parameter has invalid
-     *             values.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public native void addAttributeString(String key, String value)
-            throws InvalidArgsException, SimulatorException;
-
-    /**
-     * API to  update the value of an attribute whose value is of
-     * type int.
-     *
-     * @param key
-     *            Name of the attribute.
-     * @param value
-     *            New value of the attribute.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if any parameter has invalid
-     *             values.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public native void updateAttributeInteger(String key, int value)
-            throws InvalidArgsException, SimulatorException;
-
-    /**
-     * API to  update the value of an attribute whose value is of
-     * type double.
-     *
-     * @param key
-     *            Name of the attribute.
-     * @param value
-     *            New value of the attribute.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if any parameter has invalid
-     *             values.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public native void updateAttributeDouble(String key, double value)
-            throws InvalidArgsException, SimulatorException;
-
-    /**
-     * API to  update the value of an attribute whose value is of
-     * type boolean.
-     *
-     * @param key
-     *            Name of the attribute.
-     * @param value
-     *            New value of the attribute.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if any parameter has invalid
-     *             values.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public native void updateAttributeBoolean(String key, boolean value)
-            throws InvalidArgsException, SimulatorException;
-
-    /**
-     * API to  update the value of an attribute whose value is of
-     * type String.
-     *
-     * @param key
-     *            Name of the attribute.
-     * @param value
-     *            New value of the attribute.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if any parameter has invalid
-     *             values.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public native void updateAttributeString(String key, String value)
-            throws InvalidArgsException, SimulatorException;
-
-    /**
-     * API to update the value of an attribute from
-     * its allowed values.
-     *
-     * @param key
-     *            Name of the attribute.
-     * @param index
-     *            Index of the value in the allowed values.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if any parameter has invalid
-     *             values.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public native void updateAttributeFromAllowedValues(String key,
-            int index) throws InvalidArgsException, SimulatorException;
-
-    /**
-     * API to  set the range of allowed values. This function is
-     * intended to be used for integer type attributes.
-     *
-     * @param key
-     *            Name of the attribute.
-     * @param min
-     *            Minimum value in the range.
-     * @param max
-     *            Maximum value in the range.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if any parameter has invalid
-     *             values.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public native void setRange(String key, int min, int max)
-            throws InvalidArgsException, SimulatorException;
-
-    /**
-     * API to  set the allowed values of attribute whose value is of
-     * type int.
-     *
-     * @param key
-     *            Name of the attribute.
-     * @param allowedValues
-     *            Allowed values of the attribute.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if any parameter has invalid
-     *             values.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public native void setAllowedValuesInteger(String key,
-            Vector<Integer> allowedValues) throws InvalidArgsException,
-            SimulatorException;
-
-    /**
-     * API to  set the allowed values of attribute whose value is of
-     * type double.
-     *
-     * @param key
-     *            Name of the attribute.
-     * @param allowedValues
-     *            Allowed values of the attribute.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if any parameter has invalid
-     *             values.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public native void setAllowedValuesDouble(String key,
-            Vector<Double> allowedValues) throws InvalidArgsException,
-            SimulatorException;
-
-    /**
-     * API to  set the allowed values of attribute whose value is of
-     * type String.
-     *
-     * @param key
-     *            Name of the attribute.
-     * @param allowedValues
-     *            Allowed values of the attribute.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if any parameter has invalid
-     *             values.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public native void setAllowedValuesString(String key,
-            Vector<String> allowedValues) throws InvalidArgsException,
-            SimulatorException;
-
-    /**
-     * API to  start the resource level automation. This automation
-     * involves automatically updating all the possible values for all the
-     * attributes sequentially.
-     *
-     * @param typeOfAutomation
-     *            {@link AutomationType} indicating whether the automation is
-     *            one-time or recursive.
-     * @param updateInterval
-     *            Interval time in milliseconds for attribute value update automation.
-     * @param listener
-     *            Listener to be notified when automation ends.
-     *
-     * @return Automation ID using which the automation can be stopped.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if any parameter has invalid
-     *             values.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public int startResourceAutomation(AutomationType typeOfAutomation,
-            int updateInterval, IAutomation listener) throws InvalidArgsException,
-            SimulatorException {
-        return startResourceAutomation(typeOfAutomation.getValue(), updateInterval, listener);
-    }
-
-    /**
-     * API to  start the attribute level automation. This automation
-     * involves automatically updating all the possible values for a given
-     * attribute sequentially.
-     *
-     * @param attrName
-     *            Name of the attribute to be automated.
-     * @param typeOfAutomation
-     *            {@link AutomationType} indicating whether the automation is
-     *            one-time or recursive.
-     * @param updateInterval
-     *            Interval time in milliseconds for attribute value update automation.
-     * @param listener
-     *            Listener to be notified when automation ends.
-     *
-     * @return Automation ID using which the automation can be stopped.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if any parameter has invalid
-     *             values.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public int startAttributeAutomation(String attrName,
-            AutomationType typeOfAutomation, int updateInterval,
-            IAutomation listener)
-            throws InvalidArgsException, SimulatorException {
-        return startAttributeAutomation(attrName, typeOfAutomation.getValue(),
-                updateInterval, listener);
-    }
-
-    /**
-     * API to  stop the automation based on automation id.
-     *
-     * @param automationId
-     *            Using which a specific automation can be stopped.
-     *
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public native void stopAutomation(int automationId)
-            throws SimulatorException;
-
-    /**
-     * API to remove an attribute from the simulated resource.
-     *
-     * @param key
-     *            Name of the attribute to be deleted.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown either if the parameter has
-     *             invalid value or the native resource object does not exist.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public native void removeAttribute(String key) throws InvalidArgsException,
-            SimulatorException;
-
-    /**
-     * API to get observers  information.
-     *
-     * @return An array of {@link ObserverInfo} objects.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if the native resource object
-     *             does not exist.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public native ObserverInfo[] getObserversList()
-            throws InvalidArgsException, SimulatorException;
-
-    /**
-     * API to set callback to receive notifications when observer is added/removed.
-     *
-     * @param observer
-     *            Listener to be notified when clients start/stop observing.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown either if the parameter has
-     *             invalid value or the native resource object does not exist.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public native void setObserverCallback(IObserver observer)
-            throws InvalidArgsException, SimulatorException;
-
-    /**
-     * API to notify simulated resource's state to a specific observer.
-     *
-     * @param id
-     *            Observer's Id.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if the native resource object
-     *             does not exist.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public native void notifyObserver(int id) throws InvalidArgsException,
-            SimulatorException;
-
-    /**
-     * API to notify simualted resource's state to all observers.
-     *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if the native resource object
-     *             does not exist.
-     * @throws SimulatorException
-     *             This exception will be thrown for other errors.
-     */
-    public native void notifyAllObservers() throws InvalidArgsException,
-            SimulatorException;
-
-    private native int startResourceAutomation(int typeOfAutomation,
-            int updateInterval, IAutomation listener) throws InvalidArgsException,
-            SimulatorException;
-
-    private native int startAttributeAutomation(String attrName,
-        int typeOfAutomation, int updateInterval, IAutomation listener)
-        throws InvalidArgsException, SimulatorException;
-
-    @Override
-    protected void finalize() throws Throwable {
-        try {
-            dispose();
-        } finally {
-            super.finalize();
-        }
-    }
-
-    private native void dispose();
-}
index 38fe308..7e1504c 100755 (executable)
@@ -32,8 +32,10 @@ raml_env.AppendUnique(CPPPATH = ['raml/model','raml/jsonSchemaParser','raml', '.
 raml_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])\r
 raml_env.AppendUnique(CPPDEFINES = ['LINUX'])\r
 \r
+raml_env.Append( RPATH = env.Literal('\\$$ORIGIN'))\r
+\r
 raml_env.AppendUnique(CPPPATH = ['../../../extlibs/cjson/'])\r
-raml_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'libcoap','YamlParser'])\r
+raml_env.PrependUnique(LIBS = ['octbstack', 'YamlParser'])\r
 raml_env.AppendUnique(LIBS = ['pthread'])\r
 \r
 raml_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])\r
@@ -47,4 +49,3 @@ ramlsdk = raml_env.SharedLibrary('RamlParser', raml_src)
 raml_env.InstallTarget(ramlsdk, 'libRaml')\r
 \r
 SConscript('../../../extlibs/yaml/SConscript')\r
-SConscript('example/SConscript')\r
diff --git a/service/simulator/ramlparser/example/SConscript b/service/simulator/ramlparser/example/SConscript
deleted file mode 100755 (executable)
index 41ee9a0..0000000
+++ /dev/null
@@ -1,49 +0,0 @@
-#******************************************************************\r
-#\r
-# Copyright 2015 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
-import os\r
-Import('env')\r
-lib_env = env.Clone()\r
-SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')\r
-raml_env = lib_env.Clone()\r
-\r
-######################################################################\r
-# Build flags\r
-######################################################################\r
-raml_env.AppendUnique(CPPPATH = ['../../../../extlibs/timer'])\r
-raml_env.AppendUnique(CPPPATH = ['../raml/model','../raml/jsonSchemaParser', '../raml' , '../../../../extlibs/yaml/yaml/src' , '../../../../extlibs/yaml/yaml/include'])\r
-raml_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])\r
-raml_env.AppendUnique(CPPDEFINES = ['LINUX'])\r
-\r
-raml_env.AppendUnique(CPPPATH = ['../../../../extlibs/cjson/'])\r
-raml_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'libcoap'])\r
-raml_env.AppendUnique(LIBS = ['pthread'])\r
-raml_env.PrependUnique(LIBS = ['RamlParser','YamlParser'])\r
-\r
-raml_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])\r
-raml_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])\r
-\r
-if raml_env.get('SECURED') == '1':\r
-    raml_env.AppendUnique(LIBS = ['tinydtls'])\r
-######################################################################\r
-# Source files and Targets\r
-######################################################################\r
-raml_parser = raml_env.Program('raml-parser', 'raml_parser.cpp')\r
-\r
-env.AppendTarget('raml_parser')\r
diff --git a/service/simulator/ramlparser/example/raml_parser.cpp b/service/simulator/ramlparser/example/raml_parser.cpp
deleted file mode 100755 (executable)
index 068e643..0000000
+++ /dev/null
@@ -1,555 +0,0 @@
-/******************************************************************\r
- *\r
- * Copyright 2015 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
-#include "RamlParser.h"\r
-#include "Helpers.h"\r
-#include <iostream>\r
-#include <string>\r
-#include <memory>\r
-\r
-//#define PRINT_PARAMS\r
-//#define PRINT_PROTOCOLS\r
-//#define PRINT_BASEURI\r
-//#define PRINT_DOCUMENTATION\r
-//#define PRINT_TYPES\r
-//#define PRINT_TRAITS\r
-//#define PRINT_RESOURCE_URI_BASEURI\r
-//#define PRINT_ACTION_QUERY_PARAM\r
-//#define PRINT_RESPONSE_HEADER\r
-//#define PRINT_REQUEST_RESPONSE_BODY_PARAMS\r
-//#define PRINT_ACTION_HEADERS\r
-//#define PRINT_SCHEMAS\r
-#define PRINT_RAML\r
-#define PRINT_JSON\r
-//#define PRINT_JSON_PROPERTIES\r
-\r
-using namespace RAML;\r
-\r
-void printParameters(AbstractParam abstractParam)\r
-{\r
-\r
-#ifdef PRINT_PARAMS\r
-    std::cout << "Description : "  << abstractParam.getDescription()  << std::endl;\r
-    std::cout << "DefaultValue : "  << abstractParam.getDefaultValue()  << std::endl;\r
-    std::cout << "Example : " << abstractParam.getExample()  << std::endl;\r
-    std::cout << "displayName : "  << abstractParam.getDisplayName()  << std::endl;\r
-    std::cout << "Maxlength : "  << abstractParam.getMaxLength()  << std::endl;\r
-    std::cout << "Max : "  << abstractParam.getMaximum()  << std::endl;\r
-    std::cout << "Minlength : "  << abstractParam.getMinLength()  << std::endl;\r
-    std::cout << "Min : "  << abstractParam.getMinimum()  << std::endl;\r
-    std::cout << "Pattern : "  << abstractParam.getPattern()  << std::endl;\r
-    std::cout << "Type : "  << abstractParam.getType()  << std::endl;\r
-    std::cout << "Repeat : "  << abstractParam.isRepeat()  << std::endl;\r
-    std::cout << "Required : "  << abstractParam.isRequired()  << std::endl;\r
-    std::cout << "Enum : "   ;\r
-    for (auto elem : abstractParam.getEnumeration())\r
-        std::cout << elem   << "       ";\r
-    std::cout << std::endl;\r
-#endif\r
-}\r
-\r
-void printRequestResponseBody(const RequestResponseBodyPtr &body)\r
-{\r
-    std::cout << "Body : Type : " << body->getType() << std::endl;\r
-    if ( body->getSchema() == NULL ) return;\r
-    std::cout << "Body : Schema : " << body->getSchema()->getSchema() << std::endl;\r
-    std::cout << "Body : Schema : PROPERTIES :" << std::endl;\r
-\r
-    for ( auto pro : body->getSchema()->getProperties()->getProperties() )\r
-    {\r
-        std::cout << "-----------------------------" << std::endl;\r
-        std::cout << "Name : " << pro.second->getName() << std::endl;\r
-        std::cout << "-----------------------------" << std::endl;\r
-        try\r
-        {\r
-            switch (pro.second->getVariantType())\r
-            {\r
-                case VariantType::INT : // Integer\r
-                    std::cout << "Defaut: " << pro.second->getValueInt() << std::endl;\r
-                    for (auto tt : pro.second->getAllowedValuesInt())\r
-                    {\r
-                        std::cout << "enum value : " << tt << std::endl;\r
-                    }\r
-                    {\r
-                        int min = 0, max = 0, mul = 0;\r
-                        pro.second->getRange(min, max, mul);\r
-                        std::cout << "Minimum: " << min << std::endl;\r
-                        std::cout << "Maximum: " << max << std::endl;\r
-                    }\r
-                    break;\r
-\r
-                case VariantType::DOUBLE : // Double\r
-                    std::cout << "Defaut: " << pro.second->getValueDouble() << std::endl;\r
-                    for (auto tt : pro.second->getAllowedValuesDouble())\r
-                    {\r
-                        std::cout << "enum value : " << tt << std::endl;\r
-                    }\r
-                    {\r
-                        double min = 0, max = 0;\r
-                        int mul = 0;\r
-                        pro.second->getRangeDouble(min, max, mul);\r
-                        std::cout << "MinimumDouble: " << min << std::endl;\r
-                        std::cout << "MaximumDouble: " << max << std::endl;\r
-                    }\r
-                    break;\r
-\r
-                case VariantType::BOOL : // Boolean\r
-                    std::cout << "Defaut: " << std::boolalpha << pro.second->getValueBool() << std::noboolalpha <<\r
-                              std::endl;\r
-                    for (auto tt : pro.second->getAllowedValuesBool())\r
-                    {\r
-                        std::cout << "enum value : " << tt << std::endl;\r
-                    }\r
-                    break;\r
-\r
-                case VariantType::STRING : // String\r
-                    std::cout << "Defaut: " << pro.second->getValueString() << std::endl;\r
-                    for (auto tt : pro.second->getAllowedValuesString())\r
-                    {\r
-                        std::cout << "enum value : " << tt << std::endl;\r
-                    }\r
-                    {\r
-                        int min = 0, max = 0, mul = 0;\r
-                        pro.second->getRange(min, max, mul);\r
-                        std::cout << "MinimumLength: " << min << std::endl;\r
-                        std::cout << "MaximumLength: " << max << std::endl;\r
-                    }\r
-                    break;\r
-                default:\r
-                    break;\r
-\r
-            }\r
-        }\r
-        catch (const boost::bad_lexical_cast &e)\r
-        {\r
-            std::cout << e.what() << std::endl;\r
-        }\r
-        catch ( ... )\r
-        {\r
-            std::cout << "Unknown exception caught!" << std::endl;\r
-        }\r
-\r
-    }\r
-    std::cout << "-----------------------------" << std::endl;\r
-    std::cout << "Body : example : " << body->getExample() << std::endl;\r
-\r
-#ifdef PRINT_REQUEST_RESPONSE_BODY_PARAMS\r
-    std::cout << "Body : FormParameters        "  << std::endl;\r
-    for (auto  tw : body->getFormParameters())\r
-    {\r
-        std::cout << "-----------------------------" << std::endl;\r
-        std::cout << tw.first << " : "  << std::endl;\r
-        std::cout << "-----------------------------" << std::endl;\r
-        FormParameter formParameter = *tw.second;\r
-        printParameters((AbstractParam)formParameter);\r
-    }\r
-#endif\r
-}\r
-\r
-\r
-void printResponse(const ResponsePtr &response)\r
-{\r
-    std::cout << "#############################################" << std::endl;\r
-    std::cout << "Response : Description : " << response->getDescription() << std::endl;\r
-\r
-    for (auto  tv :  response->getResponseBody())\r
-        printRequestResponseBody(tv.second);\r
-#ifdef PRINT_RESPONSE_HEADER\r
-    std::cout << "Header" << std::endl;\r
-    for (auto  tw :  response->getHeaders())\r
-    {\r
-        std::cout << "-----------------------------" << std::endl;\r
-        std::cout << tw.first << " : "  << std::endl;\r
-        std::cout << "-----------------------------" << std::endl;\r
-\r
-        Header header = *tw.second;\r
-        printParameters((AbstractParam)header);\r
-    }\r
-#endif\r
-}\r
-\r
-void printAction(const ActionPtr &action)\r
-{\r
-    std::cout << "Description : " << action->getDescription() << std::endl;\r
-    std::cout << "----Action Body--------------" << std::endl;\r
-    for (auto  tv :  action->getRequestBody())\r
-        printRequestResponseBody(tv.second);\r
-    std::cout << "-----------------------------" << std::endl;\r
-    std::cout << "Responses    " << std::endl;\r
-    for (auto  tu :  action->getResponses())\r
-    {\r
-        std::cout << "Response : " << tu.first << std::endl;\r
-        printResponse(tu.second);\r
-    }\r
-#ifdef PRINT_ACTION_QUERY_PARAM\r
-    std::cout << "QueryParameter" << std::endl;\r
-    for (auto  tw :  action->getQueryParameters())\r
-    {\r
-        std::cout << "-----------------------------" << std::endl;\r
-        std::cout << tw.first << " : "  << std::endl;\r
-        std::cout << "-----------------------------" << std::endl;\r
-        QueryParameter queryParam = *tw.second;\r
-        printParameters((AbstractParam)queryParam);\r
-    }\r
-#endif\r
-#ifdef PRINT_ACTION_HEADERS\r
-    std::cout << "Headers" << std::endl;\r
-    for (auto  tw :  action->getHeaders())\r
-    {\r
-        std::cout << "-----------------------------" << std::endl;\r
-        std::cout << tw.first << " : "  << std::endl;\r
-        std::cout << "-----------------------------" << std::endl;\r
-        Header header = *tw.second;\r
-        printParameters((AbstractParam)header);\r
-    }\r
-#endif\r
-\r
-#ifdef PRINT_TRAITS\r
-\r
-    std::cout << "Traits  " << std::endl;\r
-    std::cout << "-----------------------------" << std::endl;\r
-    for (auto  tt :  action->getTraits())\r
-    {\r
-        std::cout << tt  << "     ";\r
-    }\r
-    std::cout << std::endl << "-----------------------------" << std::endl;\r
-#endif\r
-}\r
-\r
-void printResource(const RamlResourcePtr &resource)\r
-{\r
-    std::cout << "Displayname : " << resource->getDisplayName()   << std::endl;\r
-    std::cout << "Description : " << resource->getDescription()   << std::endl;\r
-#ifdef PRINT_RESOURCE_URI_BASEURI\r
-    std::cout << "#############################################" << std::endl;\r
-    std::cout << "ResourceURI  "   << resource->getResourceUri() << std::endl;\r
-    std::cout << "UriParameters        "    << std::endl;\r
-    for (auto  tt :  resource->getUriParameters())\r
-    {\r
-        std::cout << "-----------------------------" << std::endl;\r
-        std::cout << tt.first << " : "  << std::endl;\r
-        std::cout << "-----------------------------" << std::endl;\r
-        UriParameter uriParameter = *tt.second;\r
-        printParameters((AbstractParam)uriParameter);\r
-    }\r
-    std::cout << "#############################################" << std::endl;\r
-    std::cout << "BaseUriParameters    "    << std::endl;\r
-    for (auto  tt :  resource->getBaseUriParameters())\r
-    {\r
-        std::cout << "-----------------------------" << std::endl;\r
-        std::cout << tt.first << " : "  << std::endl;\r
-        std::cout << "-----------------------------" << std::endl;\r
-\r
-        UriParameter uriParameter = *tt.second;\r
-        printParameters((AbstractParam)uriParameter);\r
-    }\r
-#endif\r
-    std::cout << "Actions  " << std::endl;\r
-    for (auto  tt :  resource->getActions())\r
-    {\r
-        std::cout << "#############################################" << std::endl;\r
-        std::cout << "ActionsType  " << std::endl;\r
-        printAction(tt.second);\r
-    }\r
-#ifdef PRINT_TRAITS\r
-    std::cout << "Traits  " << std::endl;\r
-    std::cout << "-----------------------------" << std::endl;\r
-    for (auto  tt :  resource->getTraits())\r
-    {\r
-        std::cout << tt  << "     ";\r
-    }\r
-    std::cout << std::endl << "-----------------------------" << std::endl;\r
-#endif\r
-    std::cout << "Number of Child Resource for " << resource->getDisplayName() << " : " <<\r
-              resource->getResources().size() << std::endl;\r
-\r
-    for (auto  tt :  resource->getResources())\r
-    {\r
-        std::cout << "Child Resource" << std::endl;\r
-        std::cout << "-----------------------------" << std::endl;\r
-        std::cout << "ResourceName :" << tt.first << std::endl;\r
-        printResource(tt.second);\r
-    }\r
-\r
-}\r
-void printProperties(const PropertiesPtr &prop)\r
-{\r
-#ifdef PRINT_JSON_PROPERTIES\r
-    std::cout << "-------------------------------" << std::endl;\r
-#endif\r
-    std::cout << "Name: " << prop->getName() << std::endl;\r
-#ifdef PRINT_JSON_PROPERTIES\r
-    std::cout << "-------------------------------" << std::endl;\r
-    std::cout << "Type: " << prop->getType() << std::endl;\r
-    std::cout << "Description: " << prop->getDescription() << std::endl;\r
-    try\r
-    {\r
-        switch (prop->getVariantType())\r
-        {\r
-            case VariantType::INT : // Integer\r
-                std::cout << "Defaut: " << prop->getValueInt() << std::endl;\r
-                for (auto tt : prop->getAllowedValuesInt())\r
-                {\r
-                    std::cout << "enum value : " << tt << std::endl;\r
-                }\r
-                {\r
-                    int min = 0, max = 0, mul = 0;\r
-                    prop->getRange(min, max, mul);\r
-                    std::cout << "Minimum: " << min << std::endl;\r
-                    std::cout << "Maximum: " << max << std::endl;\r
-                }\r
-                break;\r
-\r
-            case VariantType::DOUBLE : // Double\r
-                std::cout << "Defaut: " << prop->getValueDouble() << std::endl;\r
-                for (auto tt : prop->getAllowedValuesDouble())\r
-                {\r
-                    std::cout << "enum value : " << tt << std::endl;\r
-                }\r
-                {\r
-                    double min = 0, max = 0;\r
-                    int mul = 0;\r
-                    prop->getRangeDouble(min, max, mul);\r
-                    std::cout << "MinimumDouble: " << min << std::endl;\r
-                    std::cout << "MaximumDouble: " << max << std::endl;\r
-                }\r
-                break;\r
-\r
-            case VariantType::BOOL : // Boolean\r
-                std::cout << "Defaut: " << std::boolalpha << prop->getValueBool() << std::noboolalpha << std::endl;\r
-                for (auto tt : prop->getAllowedValuesBool())\r
-                {\r
-                    std::cout << std::boolalpha << "enum value : " << tt << std::noboolalpha << std::endl;\r
-                }\r
-                break;\r
-\r
-            case VariantType::STRING : // String\r
-                std::cout << "Defaut: " << prop->getValueString() << std::endl;\r
-                for (auto tt : prop->getAllowedValuesString())\r
-                {\r
-                    std::cout << "enum value : " << tt << std::endl;\r
-                }\r
-                {\r
-                    int min = 0, max = 0, mul = 0;\r
-                    prop->getRange(min, max, mul);\r
-                    std::cout << "MinimumLength: " << min << std::endl;\r
-                    std::cout << "MaximumLength: " << max << std::endl;\r
-                }\r
-                break;\r
-            default:\r
-                break;\r
-\r
-        }\r
-    }\r
-    catch (const boost::bad_lexical_cast &e)\r
-    {\r
-        std::cout << e.what() << std::endl;\r
-    }\r
-    catch ( ... )\r
-    {\r
-        std::cout << "Unknown exception caught!" << std::endl;\r
-    }\r
-\r
-    if (prop->getType() == "array")\r
-    {\r
-        for (auto it : prop->getItems())\r
-        {\r
-            std::cout << "items Type : " << it->getType() << std::endl;\r
-            if (it->getType() == "string")\r
-                for (auto tt : it->getAllowedValuesString())\r
-                {\r
-                    std::cout << "enum value : " << tt << std::endl;\r
-                }\r
-            for (auto tt : it->getProperties())\r
-            {\r
-                printProperties(tt.second);\r
-            }\r
-            std::cout << "Item Required Values : " << std::endl;\r
-            for (auto tt : it->getRequiredValues())\r
-            {\r
-                std::cout << tt << std::endl;\r
-            }\r
-        }\r
-    }\r
-#endif\r
-\r
-}\r
-void printJsonSchema(JsonSchemaPtr js)\r
-{\r
-    std::cout << "##############################" << std::endl;\r
-    std::cout << "------JSON Schema Parser------" << std::endl;\r
-    std::cout << "##############################" << std::endl;\r
-\r
-    std::cout << "Id: " << js->getId() << std::endl;\r
-    std::cout << "Schema: " << js->getSchema() << std::endl;\r
-    std::cout << "Title: " << js->getTitle() << std::endl;\r
-    std::cout << "Type: " << js->getType() << std::endl;\r
-    std::cout << "Description: " << js->getDescription() << std::endl;\r
-    std::cout << "AdditionalProperties: " << js->getAdditionalProperties() << std::endl;\r
-\r
-    std::cout << "-------------------------------" << std::endl;\r
-    std::cout << "Definitions." << std::endl;\r
-    for (auto  tt : js->getDefinitions())\r
-    {\r
-        std::cout << "-------------------------------" << std::endl;\r
-        std::cout << tt.first << std::endl;\r
-        for (auto  it : tt.second->getProperties())\r
-        {\r
-            printProperties(it.second);\r
-        }\r
-    }\r
-\r
-    std::cout << "##############################" << std::endl;\r
-    std::cout << "Properties." << std::endl;\r
-    for (auto  it : js->getProperties())\r
-    {\r
-        printProperties(it.second);\r
-    }\r
-    std::cout << "-------------------------------" << std::endl;\r
-    std::cout << "Required." << std::endl;\r
-    std::cout << "-------------------------------" << std::endl;\r
-    for (auto it : js->getRequiredValues())\r
-    {\r
-        std::cout << it << std::endl;\r
-    }\r
-    std::cout << "-------------------------------" << std::endl;\r
-}\r
-\r
-int main(int argc, char *argv[])\r
-{\r
-    if (argc == 1)\r
-    {\r
-        return 0;\r
-    }\r
-    char *value = argv[1];\r
-    std::string s(value);\r
-\r
-    try\r
-    {\r
-        std::shared_ptr<RamlParser> ramlParser = std::make_shared<RamlParser>(s);\r
-        RamlPtr m_raml = ramlParser->getRamlPtr();\r
-#ifdef PRINT_RAML\r
-\r
-        std::cout << "#############################################" << std::endl;\r
-        std::cout << "Test Raml Parser" << std::endl;\r
-        std::cout << "#############################################" << std::endl;\r
-\r
-        std::cout << "Title : " << m_raml->getTitle() << std::endl;\r
-        std::cout << "Version : " <<  m_raml->getVersion() << std::endl;\r
-#ifdef PRINT_PROTOCOLS\r
-        std::cout << "Protocols : "   ;\r
-        for (auto  it : m_raml->getProtocols())\r
-        {\r
-            std::cout << it  << "     ";\r
-        }\r
-\r
-        std::cout << std::endl;\r
-#endif\r
-#ifdef PRINT_BASEURI\r
-        std::cout << "BaseUri : " <<  m_raml->getBaseUri() << std::endl;\r
-\r
-        std::cout << "BaseUriParameters : " << std::endl;\r
-        for (auto  it : m_raml->getBaseUriParameters())\r
-        {\r
-            std::cout << "-----------------------------" << std::endl;\r
-            std::cout << it.first << " : "  << std::endl;\r
-            std::cout << "-----------------------------" << std::endl;\r
-            UriParameter uriParameter = *it.second;\r
-            printParameters((AbstractParam)uriParameter);\r
-        }\r
-#endif\r
-#ifdef PRINT_SCHEMAS\r
-        std::cout << "#############################################" << std::endl;\r
-        std::cout << "Schemas" << std::endl;\r
-        std::cout << "-----------------------------" << std::endl;\r
-        for (auto  it : m_raml->getSchemas())\r
-        {\r
-            std::cout << it.first   << " : " << it.second->getSchema() << std::endl;\r
-        }\r
-#endif\r
-        std::cout << "MediaType : " <<  m_raml->getMediaType() << std::endl;\r
-        std::cout << "#############################################" << std::endl;\r
-#ifdef PRINT_DOCUMENTATION\r
-        std::cout << "#############################################" << std::endl;\r
-\r
-        std::cout << "Documentation" << std::endl;\r
-        std::cout << "-----------------------------" << std::endl;\r
-        for (auto  it : m_raml->getDocumentation())\r
-        {\r
-            std::cout << it->getTitle() << " : " << it->getContent() << std::endl;\r
-        }\r
-        std::cout << "#############################################" << std::endl;\r
-#endif\r
-\r
-        std::cout << "Resources" << std::endl;\r
-        for (auto  it : m_raml->getResources())\r
-        {\r
-            std::cout << "-----------------------------" << std::endl;\r
-            std::cout << "ResourceName :" << it.first << std::endl;\r
-            printResource(it.second);\r
-        }\r
-#ifdef PRINT_TYPES\r
-\r
-        std::cout << "#############################################" << std::endl;\r
-\r
-        std::cout << "ResourceTypes " << std::endl;\r
-        for (auto  it : m_raml->getResourceTypes())\r
-        {\r
-            std::cout << "------------" << it.first << "-----------------" << std::endl;\r
-            printResource(it.second);\r
-        }\r
-#endif\r
-#ifdef PRINT_TRAITS\r
-\r
-        std::cout << "#############################################" << std::endl;\r
-\r
-        std::cout << "Traits " << std::endl;\r
-        for (auto  it : m_raml->getTraits())\r
-        {\r
-            std::cout << "-------------" << it.first << "----------------" << std::endl;\r
-            printAction(it.second);\r
-        }\r
-#endif\r
-#endif\r
-#ifdef PRINT_JSON\r
-        for (auto  it : m_raml->getResources())\r
-        {\r
-            for (auto  tt :  it.second->getActions())\r
-            {\r
-                for (auto  tu :  tt.second->getResponses())\r
-                {\r
-                    for (auto  tv :  tu.second->getResponseBody())\r
-                    {\r
-                        auto pro = tv.second->getSchema()->getProperties();\r
-                        printJsonSchema(pro);\r
-                        break;\r
-                    }\r
-                }\r
-            }\r
-        }\r
-#endif\r
-    }\r
-    catch (RamlException &e)\r
-    {\r
-        std::cout << e.what() << std::endl;\r
-    }\r
-\r
-}\r
-\r
index 2bd5ab2..6bb66fc 100755 (executable)
 #ifndef INCLUDE_RESOLVER_H\r
 #define INCLUDE_RESOLVER_H\r
 \r
-#include "yaml-cpp/yaml.h"\r
-#include "cJSON.h"\r
-#include "Utils.h"\r
 #include <fstream>\r
+#include <algorithm>\r
+#include "cJSON.h"\r
+#include "yaml-cpp/yaml.h"\r
 #include "yaml-cpp/exceptions.h"\r
+#include "RamlUtils.h"\r
 #include "RamlExceptions.h"\r
 \r
 namespace RAML\r
index 38ed45d..07a57c9 100755 (executable)
@@ -45,17 +45,17 @@ namespace RAML
         {\r
             return;\r
         }\r
-        for (auto const & it : resource)\r
+        for (auto const &it : resource)\r
         {\r
             std::string type = getRamlPtr()->getMediaType();\r
 \r
-            for (auto const & action :  it.second->getActions())\r
+            for (auto const &action :  it.second->getActions())\r
             {\r
                 if (action.second->getRequestBody().empty())\r
                 {\r
                     action.second->setRequestBody(type);\r
                 }\r
-                for (auto const & response : action.second->getResponses())\r
+                for (auto const &response : action.second->getResponses())\r
                 {\r
                     if (response.second->getResponseBody().empty())\r
                     {\r
@@ -72,11 +72,11 @@ namespace RAML
         {\r
             return;\r
         }\r
-        for (auto const & it : resource)\r
+        for (auto const &it : resource)\r
         {\r
-            for (auto const & action :  it.second->getActions())\r
+            for (auto const &action :  it.second->getActions())\r
             {\r
-                for (auto const & body :  action.second->getRequestBody())\r
+                for (auto const &body :  action.second->getRequestBody())\r
                 {\r
                     SchemaPtr schema = body.second->getSchema();\r
 \r
@@ -94,9 +94,9 @@ namespace RAML
                         }\r
                     }\r
                 }\r
-                for (auto const & response : action.second->getResponses())\r
+                for (auto const &response : action.second->getResponses())\r
                 {\r
-                    for (auto const & body :  response.second->getResponseBody())\r
+                    for (auto const &body :  response.second->getResponseBody())\r
                     {\r
                         SchemaPtr schema = body.second->getSchema();\r
                         if (schema != NULL)\r
@@ -127,7 +127,7 @@ namespace RAML
         {\r
             return;\r
         }\r
-        for (auto const & it : resource)\r
+        for (auto const &it : resource)\r
         {\r
             auto const &resourceTypes = getRamlPtr()->getResourceTypes();\r
             std::string typeValue = it.second->getResourceType();\r
@@ -158,12 +158,12 @@ namespace RAML
         {\r
             return;\r
         }\r
-        for (auto const & it : resource)\r
+        for (auto const &it : resource)\r
         {\r
             auto const &trait = getRamlPtr()->getTraits();\r
-            for (auto const & act : it.second->getActions())\r
+            for (auto const &act : it.second->getActions())\r
             {\r
-                for (const std::string & traitValue :  act.second->getTraits())\r
+                for (const std::string &traitValue :  act.second->getTraits())\r
                 {\r
                     auto iter = trait.begin();\r
                     for (; iter != trait.end(); iter++)\r
@@ -191,7 +191,7 @@ namespace RAML
                     }\r
                 }\r
             }\r
-            for (const std::string & traitValue :  it.second->getTraits())\r
+            for (const std::string &traitValue :  it.second->getTraits())\r
             {\r
                 auto iter = trait.begin();\r
                 for (; iter != trait.end(); iter++)\r
index 3949234..2cf1446 100755 (executable)
@@ -29,7 +29,7 @@
 \r
 #include "yaml-cpp/yaml.h"\r
 #include "Raml.h"\r
-#include "Utils.h"\r
+#include "RamlUtils.h"\r
 #include "RequestResponseBody.h"\r
 #include "RamlResource.h"\r
 #include "Action.h"\r
diff --git a/service/simulator/ramlparser/raml/RamlUtils.h b/service/simulator/ramlparser/raml/RamlUtils.h
new file mode 100755 (executable)
index 0000000..c019632
--- /dev/null
@@ -0,0 +1,198 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 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
+ * @file   Utils.h\r
+ *\r
+ * @brief   This file provides utilities for RamlParser.\r
+ */\r
+\r
+#ifndef RAML_UTILS_H\r
+#define RAML_UTILS_H\r
+\r
+#include "yaml-cpp/yaml.h"\r
+#include "ActionType.h"\r
+\r
+namespace RAML\r
+{\r
+    namespace Keys\r
+    {\r
+        /** Title - Raml title key.*/\r
+        const std::string Title = "title";\r
+        /** Version - Raml Version key.*/\r
+        const std::string Version = "version";\r
+        /** BaseUri - Raml BaseUri key.*/\r
+        const std::string BaseUri = "baseUri";\r
+        /** Protocols - Raml Protocols key.*/\r
+        const std::string Protocols = "protocols";\r
+        /** MediaType - Raml MediaType key.*/\r
+        const std::string MediaType = "mediaType";\r
+        /** Schemas - Raml Schemas key.*/\r
+        const std::string Schemas = "schemas";\r
+        /** ResourceTypes - Raml ResourceTypes key.*/\r
+        const std::string ResourceTypes = "resourceTypes";\r
+        /** Traits - Raml Traits key.*/\r
+        const std::string Traits = "traits";\r
+        /** IsTrait - Raml is key.*/\r
+        const std::string IsTrait = "is";\r
+\r
+        /** Resource - Raml Resource key.*/\r
+        const std::string Resource = "/";\r
+        /** ActionType - Raml allowed ActionType key.*/\r
+        const std::vector<std::string> ActionType = {"get", "post", "put", "delete",\r
+                                                     "head", "patch", "options", "trace"\r
+                                                    };\r
+\r
+        /** Responses - Raml Responses key.*/\r
+        const std::string Responses = "responses";\r
+        /** Body - Raml Body key.*/\r
+        const std::string Body = "body";\r
+        /** Schema - Raml Schema key.*/\r
+        const std::string Schema = "schema";\r
+        /** Example - Raml Example key.*/\r
+        const std::string Example = "example";\r
+\r
+        /** BaseUriParameters - Raml BaseUriParameters key.*/\r
+        const std::string BaseUriParameters = "baseUriParameters";\r
+        /** UriParameters - Raml UriParameters key.*/\r
+        const std::string UriParameters = "uriParameters";\r
+        /** Headers - Raml title Headers.*/\r
+        const std::string Headers = "headers";\r
+        /** QueryParameters - Raml QueryParameters key.*/\r
+        const std::string QueryParameters = "queryParameters";\r
+        /** FormParameters - Raml FormParameters key.*/\r
+        const std::string FormParameters = "formParameters";\r
+        /** DisplayName - Raml DisplayName key.*/\r
+        const std::string DisplayName = "displayName";\r
+        /** Description - Raml Description key.*/\r
+        const std::string Description = "description";\r
+        /** Type - Raml Type key.*/\r
+        const std::string Type = "type";\r
+        /** Enum - Raml Enum key.*/\r
+        const std::string Enum = "enum";\r
+        /** Pattern - Raml Pattern key.*/\r
+        const std::string Pattern = "pattern";\r
+        /** MinLength - Raml MinLength key.*/\r
+        const std::string MinLength = "minLength";\r
+        /** MaxLength - Raml MaxLength key.*/\r
+        const std::string MaxLength = "maxLength";\r
+        /** Minimum - Raml Minimum key.*/\r
+        const std::string Minimum = "minimum";\r
+        /** Maximum - Raml Maximum key.*/\r
+        const std::string Maximum = "maximum";\r
+        /** Repeat - Raml Repeat key.*/\r
+        const std::string Repeat = "repeat";\r
+        /** Required - Raml Required key.*/\r
+        const std::string Required = "required";\r
+        /** Default - Raml Default key.*/\r
+        const std::string Default = "default";\r
+        /** Title - Raml title key.*/\r
+\r
+        /** Documentation - Raml Documentation key.*/\r
+        const std::string Documentation = "documentation";\r
+        /** Content - Raml Content key.*/\r
+        const std::string Content = "content";\r
+\r
+        /** Json - Raml Json key.*/\r
+        const std::string Json = "json";\r
+        /** AllowedRamlYamlTypes - Raml AllowedRamlYamlTypes key.*/\r
+        const std::vector<std::string> AllowedRamlYamlTypes = {"raml", "yaml", "yml"};\r
+\r
+    }\r
+\r
+    /**\r
+    * This macro is reading yamlNode as String.\r
+    *\r
+    * @param yamlNode - reference to yamlNode\r
+    *\r
+    * @return value as string\r
+    */\r
+\r
+#define READ_NODE_AS_STRING(yamlNode)                   \\r
+({                                                      \\r
+(yamlNode).as<std::string>();                           \\r
+})\r
+\r
+    /**\r
+    * This macro is reading yamlNode as int.\r
+    *\r
+    * @param yamlNode - reference to yamlNode\r
+    *\r
+    * @return value as int\r
+    */\r
+#define READ_NODE_AS_INT(yamlNode)                      \\r
+({                                                      \\r
+    (yamlNode).as<int>();                               \\r
+})\r
+\r
+    /**\r
+    * This macro is reading yamlNode as long.\r
+    *\r
+    * @param yamlNode - reference to yamlNode\r
+    *\r
+    * @return value as long\r
+    */\r
+#define READ_NODE_AS_LONG(yamlNode)                     \\r
+({                                                      \\r
+    (yamlNode).as<long>();                              \\r
+})\r
+    /**\r
+     * This macro is reading yamlNode as bool.\r
+     *\r
+     * @param yamlNode - reference to yamlNode\r
+     *\r
+     * @return value as bool\r
+      */\r
+#define READ_NODE_AS_BOOL(yamlNode)                     \\r
+({                                                      \\r
+        (yamlNode).as<bool>();                          \\r
+})\r
+    /**\r
+    * This macro is getting ActionType\r
+    *\r
+    * @param key - string\r
+    *\r
+    * @return ActionType\r
+    */\r
+\r
+#define GET_ACTION_TYPE(key)                            \\r
+({                                                      \\r
+    ActionType actionType = ActionType::GET;            \\r
+    if (key == "get" )                                  \\r
+        actionType = ActionType::GET;                   \\r
+    else if (key == "post" )                            \\r
+        actionType = ActionType::POST;                  \\r
+    else if (key == "put" )                             \\r
+        actionType = ActionType::PUT;                   \\r
+    else if (key == "delete" )                          \\r
+        actionType = ActionType::DELETE;                \\r
+    else if (key == "head" )                            \\r
+        actionType = ActionType::HEAD;                  \\r
+    else if (key == "patch" )                           \\r
+        actionType = ActionType::PATCH;                 \\r
+    else if (key == "options" )                         \\r
+        actionType = ActionType::OPTIONS;               \\r
+    else if (key == "trace" )                           \\r
+        actionType = ActionType::TRACE;                 \\r
+    actionType;                                         \\r
+})\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/Utils.h b/service/simulator/ramlparser/raml/Utils.h
deleted file mode 100755 (executable)
index 0895f36..0000000
+++ /dev/null
@@ -1,198 +0,0 @@
-/******************************************************************\r
- *\r
- * Copyright 2015 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
- * @file   Utils.h\r
- *\r
- * @brief   This file provides utilities for RamlParser.\r
- */\r
-\r
-#ifndef UTILS_H\r
-#define UTILS_H\r
-\r
-#include "yaml-cpp/yaml.h"\r
-#include "ActionType.h"\r
-\r
-namespace RAML\r
-{\r
-    namespace Keys\r
-    {\r
-        /** Title - Raml title key.*/\r
-        const std::string Title = "title";\r
-        /** Version - Raml Version key.*/\r
-        const std::string Version = "version";\r
-        /** BaseUri - Raml BaseUri key.*/\r
-        const std::string BaseUri = "baseUri";\r
-        /** Protocols - Raml Protocols key.*/\r
-        const std::string Protocols = "protocols";\r
-        /** MediaType - Raml MediaType key.*/\r
-        const std::string MediaType = "mediaType";\r
-        /** Schemas - Raml Schemas key.*/\r
-        const std::string Schemas = "schemas";\r
-        /** ResourceTypes - Raml ResourceTypes key.*/\r
-        const std::string ResourceTypes = "resourceTypes";\r
-        /** Traits - Raml Traits key.*/\r
-        const std::string Traits = "traits";\r
-        /** IsTrait - Raml is key.*/\r
-        const std::string IsTrait = "is";\r
-\r
-        /** Resource - Raml Resource key.*/\r
-        const std::string Resource = "/";\r
-        /** ActionType - Raml allowed ActionType key.*/\r
-        const std::vector<std::string> ActionType = {"get", "post", "put", "delete",\r
-                                                     "head", "patch", "options", "trace"\r
-                                                    };\r
-\r
-        /** Responses - Raml Responses key.*/\r
-        const std::string Responses = "responses";\r
-        /** Body - Raml Body key.*/\r
-        const std::string Body = "body";\r
-        /** Schema - Raml Schema key.*/\r
-        const std::string Schema = "schema";\r
-        /** Example - Raml Example key.*/\r
-        const std::string Example = "example";\r
-\r
-        /** BaseUriParameters - Raml BaseUriParameters key.*/\r
-        const std::string BaseUriParameters = "baseUriParameters";\r
-        /** UriParameters - Raml UriParameters key.*/\r
-        const std::string UriParameters = "uriParameters";\r
-        /** Headers - Raml title Headers.*/\r
-        const std::string Headers = "headers";\r
-        /** QueryParameters - Raml QueryParameters key.*/\r
-        const std::string QueryParameters = "queryParameters";\r
-        /** FormParameters - Raml FormParameters key.*/\r
-        const std::string FormParameters = "formParameters";\r
-        /** DisplayName - Raml DisplayName key.*/\r
-        const std::string DisplayName = "displayName";\r
-        /** Description - Raml Description key.*/\r
-        const std::string Description = "description";\r
-        /** Type - Raml Type key.*/\r
-        const std::string Type = "type";\r
-        /** Enum - Raml Enum key.*/\r
-        const std::string Enum = "enum";\r
-        /** Pattern - Raml Pattern key.*/\r
-        const std::string Pattern = "pattern";\r
-        /** MinLength - Raml MinLength key.*/\r
-        const std::string MinLength = "minLength";\r
-        /** MaxLength - Raml MaxLength key.*/\r
-        const std::string MaxLength = "maxLength";\r
-        /** Minimum - Raml Minimum key.*/\r
-        const std::string Minimum = "minimum";\r
-        /** Maximum - Raml Maximum key.*/\r
-        const std::string Maximum = "maximum";\r
-        /** Repeat - Raml Repeat key.*/\r
-        const std::string Repeat = "repeat";\r
-        /** Required - Raml Required key.*/\r
-        const std::string Required = "required";\r
-        /** Default - Raml Default key.*/\r
-        const std::string Default = "default";\r
-        /** Title - Raml title key.*/\r
-\r
-        /** Documentation - Raml Documentation key.*/\r
-        const std::string Documentation = "documentation";\r
-        /** Content - Raml Content key.*/\r
-        const std::string Content = "content";\r
-\r
-        /** Json - Raml Json key.*/\r
-        const std::string Json = "json";\r
-        /** AllowedRamlYamlTypes - Raml AllowedRamlYamlTypes key.*/\r
-        const std::vector<std::string> AllowedRamlYamlTypes = {"raml", "yaml", "yml"};\r
-\r
-    }\r
-\r
-    /**\r
-    * This macro is reading yamlNode as String.\r
-    *\r
-    * @param yamlNode - reference to yamlNode\r
-    *\r
-    * @return value as string\r
-    */\r
-\r
-#define READ_NODE_AS_STRING(yamlNode)                   \\r
-({                                                      \\r
-(yamlNode).as<std::string>();                           \\r
-})\r
-\r
-    /**\r
-    * This macro is reading yamlNode as int.\r
-    *\r
-    * @param yamlNode - reference to yamlNode\r
-    *\r
-    * @return value as int\r
-    */\r
-#define READ_NODE_AS_INT(yamlNode)                      \\r
-({                                                      \\r
-    (yamlNode).as<int>();                               \\r
-})\r
-\r
-    /**\r
-    * This macro is reading yamlNode as long.\r
-    *\r
-    * @param yamlNode - reference to yamlNode\r
-    *\r
-    * @return value as long\r
-    */\r
-#define READ_NODE_AS_LONG(yamlNode)                     \\r
-({                                                      \\r
-    (yamlNode).as<long>();                              \\r
-})\r
-    /**\r
-     * This macro is reading yamlNode as bool.\r
-     *\r
-     * @param yamlNode - reference to yamlNode\r
-     *\r
-     * @return value as bool\r
-      */\r
-#define READ_NODE_AS_BOOL(yamlNode)                     \\r
-({                                                      \\r
-        (yamlNode).as<bool>();                          \\r
-})\r
-    /**\r
-    * This macro is getting ActionType\r
-    *\r
-    * @param key - string\r
-    *\r
-    * @return ActionType\r
-    */\r
-\r
-#define GET_ACTION_TYPE(key)                            \\r
-({                                                      \\r
-    ActionType actionType = ActionType::GET;            \\r
-    if (key == "get" )                                  \\r
-        actionType = ActionType::GET;                   \\r
-    else if (key == "post" )                            \\r
-        actionType = ActionType::POST;                  \\r
-    else if (key == "put" )                             \\r
-        actionType = ActionType::PUT;                   \\r
-    else if (key == "delete" )                          \\r
-        actionType = ActionType::DELETE;                \\r
-    else if (key == "head" )                            \\r
-        actionType = ActionType::HEAD;                  \\r
-    else if (key == "patch" )                           \\r
-        actionType = ActionType::PATCH;                 \\r
-    else if (key == "options" )                         \\r
-        actionType = ActionType::OPTIONS;               \\r
-    else if (key == "trace" )                           \\r
-        actionType = ActionType::TRACE;                 \\r
-    actionType;                                         \\r
-})\r
-\r
-}\r
-#endif\r
diff --git a/service/simulator/ramlparser/raml/jsonSchemaParser/AllowedValues.h b/service/simulator/ramlparser/raml/jsonSchemaParser/AllowedValues.h
deleted file mode 100755 (executable)
index b0946ae..0000000
+++ /dev/null
@@ -1,168 +0,0 @@
-/******************************************************************\r
- *\r
- * Copyright 2015 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
- * @file   AllowedValues.h\r
- *\r
- * @brief   This file provides data Model for Json Schema AllowedValues.\r
- */\r
-\r
-#ifndef ALLOWED_VALUES_H_\r
-#define ALLOWED_VALUES_H_\r
-\r
-#include <string>\r
-#include <vector>\r
-#include <map>\r
-#include <boost/variant.hpp>\r
-#include <boost/lexical_cast.hpp>\r
-#include "Helpers.h"\r
-\r
-namespace RAML\r
-{\r
-    /**\r
-     * @class   AllowedValues\r
-     * @brief   This class provides data Model for Json Schema AllowedValues.\r
-     */\r
-    class AllowedValues\r
-    {\r
-        public:\r
-            /**\r
-                 * This method is for setting AllowedValues\r
-                 *\r
-                 * @param value - Allowed Value to set.\r
-                 */\r
-            template <typename T>\r
-            void addValue(const T &value)\r
-            {\r
-                ValueVariant temp = value;\r
-                m_values.push_back(temp);\r
-            }\r
-\r
-            /**\r
-                 * This method is for setting AllowedValues\r
-                 *\r
-                 * @param values - list of Allowed Values to set.\r
-                 */\r
-            template <typename T>\r
-            void addValues(const std::vector<T> &values)\r
-            {\r
-                for (auto value : values)\r
-                {\r
-                    ValueVariant vValue = value;\r
-                    m_values.push_back(vValue);\r
-                }\r
-            }\r
-\r
-            /**\r
-                 * This method is for getting AllowedValues\r
-                 *\r
-                 * @param index - Allowed Values at index to be fetched\r
-                 */\r
-            inline ValueVariant &at(int index)\r
-            {\r
-                return m_values.at(index);\r
-            }\r
-\r
-            /**\r
-                 * This method is for getting size of AllowedValues\r
-                 *\r
-                 * @return size of Allowed Values list\r
-                 */\r
-            inline int size() const\r
-            {\r
-                return m_values.size();\r
-            }\r
-\r
-            /**\r
-                 * This method is for getting AllowedValues.\r
-                 *\r
-                 * @return list of AllowedValues\r
-                 */\r
-            inline std::vector<ValueVariant> getValues()\r
-            {\r
-                return m_values;\r
-            }\r
-\r
-            /**\r
-                 * This method is for getting AllowedValues as integer.\r
-                 *\r
-                 * @return list of AllowedValues as integer.\r
-                 */\r
-            inline std::vector<int> getValuesInt()\r
-            {\r
-                std::vector<int> values;\r
-                for (auto value : m_values)\r
-                {\r
-                    values.push_back(boost::lexical_cast<int> (value));\r
-                }\r
-                return values;\r
-            }\r
-\r
-            /**\r
-                 * This method is for getting AllowedValues as string.\r
-                 *\r
-                 * @return list of AllowedValues as string.\r
-                 */\r
-            inline std::vector<std::string> getValuesString()\r
-            {\r
-                std::vector<std::string> values;\r
-                for (auto value : m_values)\r
-                {\r
-                    values.push_back(boost::lexical_cast<std::string> (value));\r
-                }\r
-                return values;\r
-            }\r
-\r
-            /**\r
-                 * This method is for getting AllowedValues as Double.\r
-                 *\r
-                 * @return list of AllowedValues as Double.\r
-                 */\r
-            inline std::vector<double> getValuesDouble()\r
-            {\r
-                std::vector<double> values;\r
-                for (auto value : m_values)\r
-                {\r
-                    values.push_back(boost::lexical_cast<double> (value));\r
-                }\r
-                return values;\r
-            }\r
-\r
-            /**\r
-                 * This method is for getting AllowedValues as Bool.\r
-                 *\r
-                 * @return list of AllowedValues as Bool.\r
-                 */\r
-            inline std::vector<bool> getValuesBool()\r
-            {\r
-                std::vector<bool> values;\r
-                for (auto value : m_values)\r
-                {\r
-                    values.push_back(boost::lexical_cast<bool> (value));\r
-                }\r
-                return values;\r
-            }\r
-\r
-        private:\r
-            std::vector<ValueVariant> m_values;\r
-    };\r
-\r
-}\r
-#endif\r
diff --git a/service/simulator/ramlparser/raml/jsonSchemaParser/Definitions.cpp b/service/simulator/ramlparser/raml/jsonSchemaParser/Definitions.cpp
new file mode 100755 (executable)
index 0000000..f662469
--- /dev/null
@@ -0,0 +1,91 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 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
+ * @file   Definitions.cpp\r
+ *\r
+ * @brief   This file provides data Model for Json Schema Definitions.\r
+ */\r
+\r
+#include "Definitions.h"\r
+\r
+namespace RAML\r
+{\r
+    std::string Definitions::getName() const\r
+    {\r
+        return m_defName;\r
+    }\r
+\r
+    void Definitions::setName(const std::string &name)\r
+    {\r
+        m_defName = name;\r
+    }\r
+\r
+    std::string Definitions::getType() const\r
+    {\r
+        return m_type;\r
+    }\r
+\r
+    void Definitions::setType(const std::string &type)\r
+    {\r
+        m_type = type;\r
+    }\r
+\r
+    std::vector<std::string> const &Definitions::getRequiredValues() const\r
+    {\r
+        return m_required;\r
+    }\r
+\r
+    void Definitions::setRequiredValue(const std::string &reqValue)\r
+    {\r
+        auto it = m_required.begin();\r
+        for (; it != m_required.end(); ++it)\r
+        {\r
+            if (*it == reqValue)\r
+                break;\r
+        }\r
+        if (m_required.end() == it)\r
+        {\r
+            m_required.push_back(reqValue);\r
+        }\r
+    }\r
+\r
+    PropertiesPtr Definitions::getproperty(const std::string &propName )\r
+    {\r
+        if (m_properties.end() != m_properties.find(propName))\r
+        {\r
+            return m_properties[propName];\r
+        }\r
+        return nullptr;\r
+    }\r
+\r
+    std::map<std::string, PropertiesPtr> const  &Definitions::getProperties()\r
+    {\r
+        return m_properties;\r
+    }\r
+\r
+    void Definitions::addProperty(const std::string &propName, const PropertiesPtr &property)\r
+    {\r
+        if (m_properties.end() == m_properties.find(propName))\r
+        {\r
+            m_properties[propName] =  property;\r
+        }\r
+    }\r
+}\r
index 401e448..b6afe8a 100755 (executable)
@@ -47,6 +47,30 @@ namespace RAML
                   * Constructor of Definitions.\r
                   */\r
             Definitions() = default;\r
+            /**\r
+                  * Copy Constructor of Definitions.\r
+                  *\r
+                  * @param Definitions\r
+                  */\r
+            Definitions(const Definitions &) = default;\r
+            /**\r
+                  * Assignment operator for Definitions.\r
+                  *\r
+                  * @param Definitions\r
+                  */\r
+            Definitions &operator=(const Definitions &) = default;\r
+            /**\r
+                  * Copy Constructor of Definitions.\r
+                  *\r
+                  * @param Definitions\r
+                  */\r
+            Definitions(Definitions &&) = default;\r
+            /**\r
+                  * Assignment operator for Definitions.\r
+                  *\r
+                  * @param Definitions\r
+                  */\r
+            Definitions &operator=(Definitions &&) = default;\r
 \r
             /**\r
                   * Constructor of Definitions.\r
@@ -60,69 +84,40 @@ namespace RAML
                  *\r
                  * @return Definitions name as string\r
                  */\r
-            inline std::string getName(void) const\r
-            {\r
-                return m_defName;\r
-            }\r
-\r
+            std::string getName() const;\r
             /**\r
                  * This method is for setting name to Definitions\r
                  *\r
                  * @param name - Definitions name as string.\r
                  */\r
-            inline void setName(const std::string &name)\r
-            {\r
-                m_defName = name;\r
-            }\r
+            void setName(const std::string &name);\r
 \r
             /**\r
                  * This method is for getting Type from Definitions.\r
                  *\r
                  * @return Definitions Type as string\r
                  */\r
-            inline std::string getType(void) const\r
-            {\r
-                return m_type;\r
-            }\r
+            std::string getType() const;\r
 \r
             /**\r
                  * This method is for setting Type to Definitions\r
                  *\r
                  * @param type - Definitions Type as string.\r
                  */\r
-            inline void setType(const std::string &type)\r
-            {\r
-                m_type = type;\r
-            }\r
-\r
+            void setType(const std::string &type);\r
             /**\r
                  * This method is for getting RequiredValue from Definitions.\r
                  *\r
                  * @return list of RequiredValue as string\r
                  */\r
-            std::vector<std::string> const &getRequiredValues() const\r
-            {\r
-                return m_required;\r
-            }\r
+            std::vector<std::string> const &getRequiredValues() const;\r
 \r
             /**\r
                  * This method is for setting RequiredValue to Definitions\r
                  *\r
                  * @param reqValue - RequiredValue as string.\r
                  */\r
-            void setRequiredValue(const std::string &reqValue)\r
-            {\r
-                auto it = m_required.begin();\r
-                for (; it != m_required.end(); ++it)\r
-                {\r
-                    if (*it == reqValue)\r
-                        break;\r
-                }\r
-                if (m_required.end() != it)\r
-                {\r
-                    m_required.push_back(reqValue);\r
-                }\r
-            }\r
+            void setRequiredValue(const std::string &reqValue);\r
 \r
             /**\r
                  * This method is for getting size of Properties from Definitions.\r
@@ -138,24 +133,14 @@ namespace RAML
                  *\r
                  * @return pointer to Properties.\r
                  */\r
-            inline PropertiesPtr getproperty(const std::string &propName )\r
-            {\r
-                if (m_properties.end() != m_properties.find(propName))\r
-                {\r
-                    return m_properties[propName];\r
-                }\r
-                return nullptr;\r
-            }\r
+            PropertiesPtr getproperty(const std::string &propName );\r
 \r
             /**\r
                  * This method is for getting Properties from Definitions.\r
                  *\r
                  * @return map of Property name and pointer to Properties\r
                  */\r
-            inline std::map<std::string, PropertiesPtr> const  &getProperties()\r
-            {\r
-                return m_properties;\r
-            }\r
+            std::map<std::string, PropertiesPtr> const  &getProperties();\r
 \r
             /**\r
                  * This method is for setting Properties to Definitions\r
@@ -163,13 +148,8 @@ namespace RAML
                  * @param propName - Definitions Type as string.\r
                  * @param property - pointer to Properties.\r
                  */\r
-            void addProperty(const std::string &propName, const PropertiesPtr &property)\r
-            {\r
-                if (m_properties.end() == m_properties.find(propName))\r
-                {\r
-                    m_properties[propName] =  property;\r
-                }\r
-            }\r
+            void addProperty(const std::string &propName, const PropertiesPtr &property);\r
+\r
         private:\r
             std::map<std::string, PropertiesPtr > m_properties;\r
             std::string m_defName;\r
diff --git a/service/simulator/ramlparser/raml/jsonSchemaParser/Helpers.h b/service/simulator/ramlparser/raml/jsonSchemaParser/Helpers.h
deleted file mode 100755 (executable)
index d5ceb68..0000000
+++ /dev/null
@@ -1,55 +0,0 @@
-/******************************************************************\r
- *\r
- * Copyright 2015 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
- * @file   Helpers.h\r
- *\r
- * @brief   This file provides helper definitions for Json Schema parser.\r
- */\r
-\r
-#ifndef HELPERS_H_\r
-#define HELPERS_H_\r
-\r
-#include <string>\r
-#include <vector>\r
-#include <map>\r
-#include <boost/variant.hpp>\r
-#include <boost/lexical_cast.hpp>\r
-\r
-namespace RAML\r
-{\r
-\r
-    /** ValueVariant - Boost Variant to hold type of int, string, double and bool*/\r
-    typedef boost::variant <\r
-    int,\r
-    double,\r
-    bool,\r
-    std::string\r
-    > ValueVariant;\r
-\r
-    /** VariantType - enumeration for variant types*/\r
-    enum class VariantType\r
-    {\r
-        INT, DOUBLE, BOOL, STRING\r
-    };\r
-\r
-\r
-}\r
-#endif\r
diff --git a/service/simulator/ramlparser/raml/jsonSchemaParser/Items.h b/service/simulator/ramlparser/raml/jsonSchemaParser/Items.h
deleted file mode 100755 (executable)
index b0a0e50..0000000
+++ /dev/null
@@ -1,205 +0,0 @@
-/******************************************************************\r
- *\r
- * Copyright 2015 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
- * @file   Items.h\r
- *\r
- * @brief   This file provides data Model for Json Schema Array Items.\r
- */\r
-\r
-#ifndef ITEMS_H_\r
-#define ITEMS_H_\r
-\r
-#include <string>\r
-#include <vector>\r
-#include <map>\r
-#include "Properties.h"\r
-#include "Helpers.h"\r
-#include "AllowedValues.h"\r
-#include <memory>\r
-\r
-namespace RAML\r
-{\r
-    class Properties;\r
-    class AllowedValues;\r
-    /**\r
-     * @class   Items\r
-     * @brief   This class provides data Model for Json Schema Array Items.\r
-     */\r
-    class Items\r
-    {\r
-        public:\r
-            /**\r
-                  * Constructor of Items.\r
-                  */\r
-            Items() {}\r
-\r
-            /**\r
-                 * This method is for setting Properties to Items\r
-                 *\r
-                 * @param propName - Properties name as string.\r
-                 * @param property - pointer to Properties.\r
-                 */\r
-            void addProperty(const std::string &propName, const std::shared_ptr<Properties> &property)\r
-            {\r
-                if (m_properties.end() == m_properties.find(propName))\r
-                {\r
-                    m_properties[propName] =  property;\r
-                }\r
-            }\r
-\r
-            /**\r
-                 * This method is for getting Properties from Items.\r
-                 *\r
-                 * @param propName - Properties name as string.\r
-                 *\r
-                 * @return  pointer to Properties to put the value got\r
-                 */\r
-            std::shared_ptr<Properties> getproperty(const std::string &propName)\r
-            {\r
-                if (m_properties.end() != m_properties.find(propName))\r
-                {\r
-                    return m_properties[propName];\r
-                }\r
-                return nullptr;\r
-            }\r
-\r
-            /**\r
-                 * This method is for getting Properties from Items.\r
-                 *\r
-                 * @return map of Properties name as string and pointer to Properties\r
-                 */\r
-            std::map<std::string, std::shared_ptr<Properties> > const &getProperties()\r
-            {\r
-                return m_properties;\r
-            }\r
-\r
-            /**\r
-                 * This method is for setting Type to Items\r
-                 *\r
-                 * @param type - Type as string.\r
-                 */\r
-            void setType(const std::string &type)\r
-            {\r
-                m_type = type;\r
-            }\r
-\r
-            /**\r
-                 * This method is for getting Type from Items.\r
-                 *\r
-                 * @return Type as string\r
-                 */\r
-            std::string getType()\r
-            {\r
-                return m_type;\r
-            }\r
-\r
-            /**\r
-                 * This method is for setting RequiredValue to Items\r
-                 *\r
-                 * @param reqValue - RequiredValue as string.\r
-                 */\r
-            void setRequiredValue(const std::string &reqValue)\r
-            {\r
-                auto it = m_required.begin();\r
-                for (; it != m_required.end(); ++it)\r
-                {\r
-                    if (*it == reqValue)\r
-                        break;\r
-                }\r
-                if (m_required.end() != it)\r
-                {\r
-                    m_required.push_back(reqValue);\r
-                }\r
-            }\r
-\r
-            /**\r
-                 * This method is for getting RequiredValue from Items.\r
-                 *\r
-                 * @return list of RequiredValue as string\r
-                 */\r
-            std::vector<std::string> const &getRequiredValues()\r
-            {\r
-                return m_required;\r
-            }\r
-\r
-            /**\r
-                 * This method is for setting AllowedValues to Items\r
-                 *\r
-                 * @param values -list of AllowedValues.\r
-                 */\r
-            template <typename T>\r
-            bool setAllowedValues(const std::vector<T> &values)\r
-            {\r
-                m_allowedValues.addValues(values);\r
-                return true;\r
-            }\r
-\r
-            /**\r
-                 * This method is for getting size of AllowedValues from Items.\r
-                 *\r
-                 * @return size of AllowedValues\r
-                 */\r
-            inline int getAllowedValuesSize() const\r
-            {\r
-                return m_allowedValues.size();\r
-            }\r
-\r
-            /**\r
-                 * This method is for getting AllowedValues from Items.\r
-                 *\r
-                 * @return list of AllowedValues\r
-                 */\r
-            inline std::vector<ValueVariant> getAllowedValues()\r
-            {\r
-                return m_allowedValues.getValues();\r
-            }\r
-\r
-            /**\r
-                 * This method is for getting AllowedValues as Integer from Items.\r
-                 *\r
-                 * @return list of AllowedValues as Integer\r
-                 */\r
-            inline std::vector<int> getAllowedValuesInt()\r
-            {\r
-                return m_allowedValues.getValuesInt();\r
-            }\r
-\r
-            /**\r
-                 * This method is for getting AllowedValues as String from Items.\r
-                 *\r
-                 * @return list of AllowedValues as String\r
-                 */\r
-            inline std::vector<std::string> getAllowedValuesString()\r
-            {\r
-                return m_allowedValues.getValuesString();\r
-            }\r
-        private:\r
-            std::map<std::string, std::shared_ptr<Properties> > m_properties;\r
-            std::string m_type;\r
-            std::vector<std::string>  m_required;\r
-            AllowedValues m_allowedValues;\r
-    };\r
-\r
-    /** ItemsPtr - shared Ptr to Items.*/\r
-    typedef std::shared_ptr<Items> ItemsPtr;\r
-}\r
-#endif\r
-\r
index 67968e2..826e67d 100755 (executable)
  *\r
  ******************************************************************/\r
 \r
-#include "JsonSchema.h"\r
-using namespace std;\r
+/**\r
+ * @file   JsonSchema.cpp\r
+ *\r
+ * @brief   This file reads data from Json Schema.\r
+ */\r
 \r
+#include "JsonSchema.h"\r
+#include <iostream>\r
 namespace RAML\r
 {\r
 \r
@@ -78,26 +83,11 @@ namespace RAML
         }\r
         if (m_type == "array")\r
         {\r
-            cJSON *jsonItems = cJSON_GetObjectItem(m_cjson, "items");\r
-            if (jsonItems)\r
-            {\r
-                if (jsonItems->type == 5)\r
-                {\r
-                    int item_size = cJSON_GetArraySize(jsonItems);\r
-                    int item_index = 0;\r
-                    do\r
-                    {\r
-                        cJSON *item = cJSON_GetArrayItem(jsonItems, item_index);\r
-                        setItem(readItems(item));\r
-                    }\r
-                    while ( ++item_index < item_size);\r
-                }\r
-                else\r
-                {\r
-                    setItem(readItems(jsonItems));\r
-                }\r
-            }\r
+            PropertiesPtr property = std::make_shared<Properties>("array");\r
+            readArray(m_cjson, property);\r
+            addProperty("array" , property);\r
         }\r
+\r
         cJSON *jsonAdditionalProperties = cJSON_GetObjectItem(m_cjson, "additionalProperties");\r
         if (jsonAdditionalProperties)\r
             m_additionalProperties = jsonAdditionalProperties->type;\r
@@ -107,12 +97,37 @@ namespace RAML
         cJSON *jsonReference = cJSON_GetObjectItem(m_cjson, "$ref");\r
         if (jsonReference)\r
         {\r
-            readJsonRef(jsonReference);\r
+            JsonParameters param;\r
+            readJsonRef(jsonReference, param);\r
+\r
+            for (auto it : param.getProperties())\r
+            {\r
+                addProperty(it.first, it.second);\r
+            }\r
+            for ( auto it : param.getRequired())\r
+            {\r
+                setRequiredValue(it);\r
+            }\r
+            if (m_type.empty())\r
+                m_type = param.getType();\r
         }\r
         cJSON *jsonAllOf = cJSON_GetObjectItem(m_cjson, "allOf");\r
         if (jsonAllOf)\r
         {\r
-            readAllOf(jsonAllOf);\r
+            JsonParameters param;\r
+\r
+            readAllOf(jsonAllOf, param);\r
+\r
+            for (auto it : param.getProperties())\r
+            {\r
+                addProperty(it.first, it.second);\r
+            }\r
+            for ( auto it : param.getRequired())\r
+            {\r
+                setRequiredValue(it);\r
+            }\r
+            if (m_type.empty())\r
+                m_type = param.getType();\r
         }\r
         cJSON *jsonRequiredValues = cJSON_GetObjectItem(m_cjson, "required");\r
         if (jsonRequiredValues)\r
@@ -136,6 +151,12 @@ namespace RAML
         {\r
             std::string type = defType->valuestring;\r
             definition->setType(type);\r
+            if (type == "array")\r
+            {\r
+                PropertiesPtr property = std::make_shared<Properties>("array");\r
+                readArray(childDefinitions, property);\r
+                definition->addProperty("array" , property);\r
+            }\r
         }\r
         cJSON *defProperties = cJSON_GetObjectItem(childDefinitions, "properties");\r
         if (defProperties)\r
@@ -162,12 +183,36 @@ namespace RAML
         cJSON *defReference = cJSON_GetObjectItem(childDefinitions, "$ref");\r
         if (defReference)\r
         {\r
-            readDefRef(defReference, definition);\r
+            JsonParameters param;\r
+            readJsonRef(defReference, param);\r
+\r
+            for (auto it : param.getProperties())\r
+            {\r
+                definition->addProperty(it.first, it.second);\r
+            }\r
+            for ( auto it : param.getRequired())\r
+            {\r
+                definition->setRequiredValue(it);\r
+            }\r
+            if (definition->getType().empty())\r
+                definition->setType(param.getType());\r
         }\r
         cJSON *defAllOf = cJSON_GetObjectItem(childDefinitions, "allOf");\r
         if (defAllOf)\r
         {\r
-            readDefAllOf(defAllOf, definition);\r
+            JsonParameters param;\r
+            readAllOf(defAllOf, param);\r
+\r
+            for (auto it : param.getProperties())\r
+            {\r
+                definition->addProperty(it.first, it.second);\r
+            }\r
+            for ( auto it : param.getRequired())\r
+            {\r
+                definition->setRequiredValue(it);\r
+            }\r
+            if (definition->getType().empty())\r
+                definition->setType(param.getType());\r
         }\r
         return definition;\r
     }\r
@@ -182,106 +227,125 @@ namespace RAML
             property->setDescription(propertyDescription->valuestring);\r
         }\r
         cJSON *propertyType = cJSON_GetObjectItem(childProperties, "type");\r
+        std::string attType;\r
         if (propertyType)\r
         {\r
-            std::string attType;\r
             if (propertyType->type == 4)\r
             {\r
                 attType = propertyType->valuestring;\r
-                property->setType(attType);\r
             }\r
             else if (propertyType->type == 5)\r
             {\r
                 attType = cJSON_GetArrayItem(propertyType, 0)->valuestring;\r
-                property->setType(attType);\r
             }\r
-            readValues(childProperties, property, attType);\r
         }\r
-        cJSON *defaultValue = cJSON_GetObjectItem(childProperties, "default");\r
-        if (defaultValue)\r
+        if (!(attType == "array") && !(attType == "object"))\r
         {\r
-            if (defaultValue->type == 4)\r
+            cJSON *defaultValue = cJSON_GetObjectItem(childProperties, "default");\r
+            if (defaultValue)\r
             {\r
-                property->setValue((std::string)defaultValue->valuestring);\r
+                readDefaultValue(defaultValue, property, attType);\r
             }\r
-            else if (defaultValue->type == 3)\r
-            {\r
-                if (property->getType() == "number")\r
-                    property->setValue((double)defaultValue->valuedouble);\r
-                else\r
-                    property->setValue((int)defaultValue->valueint );\r
-            }\r
-            else if (defaultValue->type == 1)\r
-            {\r
-                property->setValue((bool)true);\r
-            }\r
-            else if (defaultValue->type == 0)\r
-            {\r
-                property->setValue((bool)false);\r
-            }\r
-\r
         }\r
+        readValues(childProperties, property, attType);\r
         cJSON *allowedvalues = cJSON_GetObjectItem(childProperties, "enum");\r
         if (allowedvalues)\r
         {\r
-            if ((cJSON_GetArrayItem(allowedvalues, 0)->type) == 4)\r
+            readAllowedValues(allowedvalues, property, attType);\r
+        }\r
+        property->setTypeString(attType);\r
+        return property;\r
+    }\r
+\r
+    void JsonSchema::readDefaultValue(cJSON *defaultValue,  PropertiesPtr &property,\r
+                                      const std::string &attType)\r
+    {\r
+        if (defaultValue->type == 4)\r
+        {\r
+            property->setValue((std::string)defaultValue->valuestring);\r
+        }\r
+        else if (defaultValue->type == 3)\r
+        {\r
+            if (attType == "number")\r
+                property->setValue((double)defaultValue->valuedouble);\r
+            else\r
+                property->setValue((int)defaultValue->valueint );\r
+        }\r
+        else if (defaultValue->type == 1)\r
+        {\r
+            property->setValue((bool)true);\r
+        }\r
+        else if (defaultValue->type == 0)\r
+        {\r
+            property->setValue((bool)false);\r
+        }\r
+    }\r
+\r
+    void JsonSchema::readAllowedValues(cJSON *allowedvalues,  PropertiesPtr &property,\r
+                                       std::string &attType)\r
+    {\r
+        if ((cJSON_GetArrayItem(allowedvalues, 0)->type) == 4)\r
+        {\r
+            int size = cJSON_GetArraySize(allowedvalues);\r
+            int idx = 0;\r
+            std::vector<std::string> allwdValues;\r
+            do\r
             {\r
-                int size = cJSON_GetArraySize(allowedvalues);\r
-                int idx = 0;\r
-                std::vector<std::string> allwdValues;\r
-                do\r
-                {\r
-                    allwdValues.push_back(cJSON_GetArrayItem(allowedvalues, idx)->valuestring);\r
-                }\r
-                while ( ++idx < size);\r
-                property->setAllowedValues(allwdValues);\r
+                allwdValues.push_back(cJSON_GetArrayItem(allowedvalues, idx)->valuestring);\r
             }\r
-            else if ((cJSON_GetArrayItem(allowedvalues, 0)->type) == 3)\r
+            while ( ++idx < size);\r
+            property->setValueProperty(std::make_shared<ValueProperty>(allwdValues));\r
+            if (attType.empty())\r
+                attType = "string";\r
+        }\r
+        else if ((cJSON_GetArrayItem(allowedvalues, 0)->type) == 3)\r
+        {\r
+            int size = cJSON_GetArraySize(allowedvalues);\r
+            int idx = 0;\r
+            if (attType == "number")\r
             {\r
-                int size = cJSON_GetArraySize(allowedvalues);\r
-                int idx = 0;\r
-                if (property->getType() == "number")\r
-                {\r
-                    std::vector<double> allwdValues;\r
-                    do\r
-                    {\r
-                        allwdValues.push_back(cJSON_GetArrayItem(allowedvalues, idx)->valuedouble);\r
-                    }\r
-                    while ( ++idx < size);\r
-                    property->setAllowedValues(allwdValues);\r
-                }\r
-                else\r
+                std::vector<double> allwdValues;\r
+                do\r
                 {\r
-                    std::vector<int> allwdValues;\r
-                    do\r
-                    {\r
-                        allwdValues.push_back(cJSON_GetArrayItem(allowedvalues, idx)->valueint);\r
-                    }\r
-                    while ( ++idx < size);\r
-                    property->setAllowedValues(allwdValues);\r
+                    allwdValues.push_back(cJSON_GetArrayItem(allowedvalues, idx)->valuedouble);\r
                 }\r
+                while ( ++idx < size);\r
+                property->setValueProperty(std::make_shared<ValueProperty>(allwdValues));\r
             }\r
-            else if (((cJSON_GetArrayItem(allowedvalues, 0)->type) == 1)\r
-                     || ((cJSON_GetArrayItem(allowedvalues, 0)->type) == 0))\r
+            else\r
             {\r
-                int size = cJSON_GetArraySize(allowedvalues);\r
-                int idx = 0;\r
-                std::vector<bool> allwdValues;\r
+                std::vector<int> allwdValues;\r
                 do\r
                 {\r
-                    if (cJSON_GetArrayItem(allowedvalues, idx)->type)\r
-                        allwdValues.push_back(true);\r
-                    else\r
-                        allwdValues.push_back(false);\r
+                    allwdValues.push_back(cJSON_GetArrayItem(allowedvalues, idx)->valueint);\r
                 }\r
                 while ( ++idx < size);\r
-                property->setAllowedValues(allwdValues);\r
+                property->setValueProperty(std::make_shared<ValueProperty>(allwdValues));\r
+                if (attType.empty())\r
+                    attType = "integer";\r
             }\r
         }\r
-        return property;\r
+        else if (((cJSON_GetArrayItem(allowedvalues, 0)->type) == 1)\r
+                 || ((cJSON_GetArrayItem(allowedvalues, 0)->type) == 0))\r
+        {\r
+            int size = cJSON_GetArraySize(allowedvalues);\r
+            int idx = 0;\r
+            std::vector<bool> allwdValues;\r
+            do\r
+            {\r
+                if (cJSON_GetArrayItem(allowedvalues, idx)->type)\r
+                    allwdValues.push_back(true);\r
+                else\r
+                    allwdValues.push_back(false);\r
+            }\r
+            while ( ++idx < size);\r
+            property->setValueProperty(std::make_shared<ValueProperty>(allwdValues));\r
+            if (attType.empty())\r
+                attType = "boolean";\r
+        }\r
     }\r
 \r
-    void JsonSchema::readValues(cJSON *childProperties,  PropertiesPtr property ,\r
+    void JsonSchema::readValues(cJSON *childProperties,  PropertiesPtr &property ,\r
                                 const std::string &attType)\r
     {\r
         if (attType == "string")\r
@@ -292,31 +356,36 @@ namespace RAML
         {\r
             readInteger(childProperties, property);\r
         }\r
+        else if (attType == "number")\r
+        {\r
+            readDouble(childProperties, property);\r
+        }\r
         else if (attType == "array")\r
         {\r
             readArray(childProperties, property);\r
         }\r
-        else if (attType == "number")\r
+        else if (attType == "object")\r
         {\r
-            readDouble(childProperties, property);\r
+            readObject(childProperties, property);\r
         }\r
     }\r
 \r
-    void JsonSchema::readString(cJSON *childProperties, PropertiesPtr property)\r
+    void JsonSchema::readString(cJSON *childProperties, PropertiesPtr &property)\r
     {\r
         cJSON *stringMax = cJSON_GetObjectItem(childProperties, "maxLength");\r
+        int min = INT_MIN, max = INT_MAX;\r
         if (stringMax)\r
         {\r
             cJSON *exclusiveMax = cJSON_GetObjectItem(childProperties, "exclusiveMaximum");\r
             if (exclusiveMax)\r
             {\r
                 if (exclusiveMax->type == cJSON_True)\r
-                    property->setMax (--(stringMax->valueint));\r
+                    max = --(stringMax->valueint);\r
                 else\r
-                    property->setMax(stringMax->valueint);\r
+                    max = stringMax->valueint;\r
             }\r
             else\r
-                property->setMax(stringMax->valueint);\r
+                max = stringMax->valueint;\r
         }\r
         cJSON *stringMin = cJSON_GetObjectItem(childProperties, "minLength");\r
         if (stringMin)\r
@@ -325,109 +394,89 @@ namespace RAML
             if (exclusiveMin)\r
             {\r
                 if (exclusiveMin->type == cJSON_True)\r
-                    property->setMin( ++(stringMin->valueint));\r
+                    min = ++(stringMin->valueint);\r
                 else\r
-                    property->setMin(stringMin->valueint);\r
+                    min = stringMin->valueint;\r
             }\r
             else\r
-                property->setMin(stringMin->valueint);\r
+                min = stringMin->valueint;\r
         }\r
+        if (min != INT_MIN || max != INT_MAX)\r
+            property->setValueProperty(std::make_shared<ValueProperty>(min, max, 0));\r
+\r
         cJSON *stringFormat = cJSON_GetObjectItem(childProperties, "format");\r
         if (stringFormat)\r
         {\r
-            property->setFormat(stringFormat->valuestring);\r
+            property->setValueProperty(std::make_shared<ValueProperty>\r
+                                       (ValueProperty::Type::FORMAT, (stringFormat->valuestring)));\r
         }\r
+\r
         cJSON *stringPattern = cJSON_GetObjectItem(childProperties, "pattern");\r
         if (stringPattern)\r
         {\r
-            property->setPattern(stringPattern->valuestring);\r
+            property->setValueProperty(std::make_shared<ValueProperty>\r
+                                       (ValueProperty::Type::PATTERN, (stringPattern->valuestring)));\r
         }\r
     }\r
 \r
-    void JsonSchema::readArray(cJSON *childProperties,  PropertiesPtr property)\r
+    void JsonSchema::readInteger(cJSON *childProperties,  PropertiesPtr &property)\r
     {\r
-        cJSON *itemValues = cJSON_GetObjectItem(childProperties, "items");\r
-        if (itemValues)\r
-        {\r
-            if (itemValues->type == 5)\r
-            {\r
-                int item_size = cJSON_GetArraySize(itemValues);\r
-                int item_index = 0;\r
-                do\r
-                {\r
-                    cJSON *item = cJSON_GetArrayItem(itemValues, item_index);\r
-                    property->setItem(readItems(item));\r
-                }\r
-                while ( ++item_index < item_size);\r
-            }\r
-            else\r
-            {\r
-                property->setItem(readItems(itemValues));\r
-            }\r
-        }\r
-        cJSON *itemsMax = cJSON_GetObjectItem(childProperties, "maxItems");\r
-        if (itemsMax)\r
+        cJSON *Max = cJSON_GetObjectItem(childProperties, "maximum");\r
+        int min = INT_MIN, max = INT_MAX, multipleOf = INT_MAX;\r
+        if (Max)\r
         {\r
             cJSON *exclusiveMax = cJSON_GetObjectItem(childProperties, "exclusiveMaximum");\r
             if (exclusiveMax)\r
             {\r
                 if (exclusiveMax->type == cJSON_True)\r
-                    property->setMax( --(itemsMax->valueint));\r
+                    max = --(Max->valueint);\r
                 else\r
-                    property->setMax(itemsMax->valueint);\r
+                    max = Max->valueint;\r
             }\r
             else\r
-                property->setMax(itemsMax->valueint);\r
+                max = Max->valueint;\r
         }\r
-        cJSON *itemsMin = cJSON_GetObjectItem(childProperties, "minLength");\r
-        if (itemsMin)\r
+        cJSON *Min = cJSON_GetObjectItem(childProperties, "minimum");\r
+        if (Min)\r
         {\r
             cJSON *exclusiveMin = cJSON_GetObjectItem(childProperties, "exclusiveMinimum");\r
             if (exclusiveMin)\r
             {\r
                 if (exclusiveMin->type == cJSON_True)\r
-                    property->setMin( ++(itemsMin->valueint));\r
+                    min = ++(Min->valueint);\r
                 else\r
-                    property->setMin(itemsMin->valueint);\r
+                    min = Min->valueint;\r
             }\r
             else\r
-                property->setMin(itemsMin->valueint);\r
-        }\r
-        cJSON *uniqueItems = cJSON_GetObjectItem(childProperties, "uniqueItems");\r
-        if (uniqueItems)\r
-        {\r
-            property->setUnique(uniqueItems->type);\r
-        }\r
-        else\r
-        {\r
-            property->setUnique(cJSON_True);\r
+                min = Min->valueint;\r
         }\r
-        cJSON *additionalItems = cJSON_GetObjectItem(childProperties, "additionalItems");\r
-        if (additionalItems)\r
-        {\r
-            property->setAdditionalItems(additionalItems->type);\r
-        }\r
-        else\r
+        cJSON *MultipleOff = cJSON_GetObjectItem(childProperties, "multipleOf");\r
+        if (MultipleOff)\r
         {\r
-            property->setAdditionalItems(cJSON_True);\r
+            multipleOf = MultipleOff->valueint;\r
         }\r
+        if (min != INT_MIN || max != INT_MAX)\r
+            property->setValueProperty(std::make_shared<ValueProperty>(min, max, multipleOf));\r
+\r
     }\r
 \r
-    void JsonSchema::readInteger(cJSON *childProperties,  PropertiesPtr property)\r
+    void JsonSchema::readDouble(cJSON *childProperties,  PropertiesPtr &property)\r
     {\r
         cJSON *Max = cJSON_GetObjectItem(childProperties, "maximum");\r
+        double min = INT_MIN, max = INT_MAX;\r
+        int multipleOf = INT_MAX;\r
         if (Max)\r
         {\r
             cJSON *exclusiveMax = cJSON_GetObjectItem(childProperties, "exclusiveMaximum");\r
             if (exclusiveMax)\r
             {\r
                 if (exclusiveMax->type == cJSON_True)\r
-                    property->setMax( --(Max->valueint));\r
+                    max = --(Max->valuedouble);\r
                 else\r
-                    property->setMax(Max->valueint);\r
+                    max = Max->valuedouble;\r
             }\r
             else\r
-                property->setMax(Max->valueint);\r
+                max = Max->valuedouble;\r
         }\r
         cJSON *Min = cJSON_GetObjectItem(childProperties, "minimum");\r
         if (Min)\r
@@ -436,423 +485,395 @@ namespace RAML
             if (exclusiveMin)\r
             {\r
                 if (exclusiveMin->type == cJSON_True)\r
-                    property->setMin( ++(Min->valueint));\r
+                    min = ++(Min->valuedouble);\r
                 else\r
-                    property->setMin(Min->valueint);\r
+                    min = Min->valuedouble;\r
             }\r
             else\r
-                property->setMin(Min->valueint);\r
+                min = Min->valuedouble;\r
         }\r
-        cJSON *multipleOf = cJSON_GetObjectItem(childProperties, "multipleOf");\r
-        if (multipleOf)\r
+\r
+        cJSON *MultipleOff = cJSON_GetObjectItem(childProperties, "multipleOf");\r
+        if (MultipleOff)\r
         {\r
-            property->setMultipleOf(multipleOf->valueint);\r
+            multipleOf = MultipleOff->valueint;\r
         }\r
+        if (min != INT_MIN || max != INT_MAX)\r
+            property->setValueProperty(std::make_shared<ValueProperty>(min, max, multipleOf));\r
 \r
     }\r
 \r
-    void JsonSchema::readDouble(cJSON *childProperties,  PropertiesPtr property)\r
+    void JsonSchema::readArray(cJSON *childProperties,  PropertiesPtr &property)\r
     {\r
-        cJSON *Max = cJSON_GetObjectItem(childProperties, "maximum");\r
-        if (Max)\r
+        cJSON *itemValues = cJSON_GetObjectItem(childProperties, "items");\r
+        if (itemValues)\r
+        {\r
+            if (itemValues->type == 5)\r
+            {\r
+                //int item_size = cJSON_GetArraySize(itemValues);\r
+                int item_index = 0;\r
+                //do\r
+                //{\r
+                cJSON *item = cJSON_GetArrayItem(itemValues, item_index);\r
+                readItems(item, property);\r
+                //break;\r
+                //}\r
+                //while ( ++item_index < item_size);\r
+            }\r
+            else\r
+            {\r
+                readItems(itemValues, property);\r
+            }\r
+        }\r
+        cJSON *itemsMax = cJSON_GetObjectItem(childProperties, "maxItems");\r
+        int min = INT_MIN, max = INT_MAX;\r
+        bool unique = cJSON_False, addItems = cJSON_False;\r
+        if (itemsMax)\r
         {\r
             cJSON *exclusiveMax = cJSON_GetObjectItem(childProperties, "exclusiveMaximum");\r
             if (exclusiveMax)\r
             {\r
                 if (exclusiveMax->type == cJSON_True)\r
-                    property->setMaxDouble( --(Max->valuedouble));\r
+                    max = --(itemsMax->valueint);\r
                 else\r
-                    property->setMaxDouble(Max->valuedouble);\r
+                    max = itemsMax->valueint;\r
             }\r
             else\r
-                property->setMaxDouble(Max->valuedouble);\r
+                max = itemsMax->valueint;\r
         }\r
-        cJSON *Min = cJSON_GetObjectItem(childProperties, "minimum");\r
-        if (Min)\r
+        cJSON *itemsMin = cJSON_GetObjectItem(childProperties, "minItems");\r
+        if (itemsMin)\r
         {\r
             cJSON *exclusiveMin = cJSON_GetObjectItem(childProperties, "exclusiveMinimum");\r
             if (exclusiveMin)\r
             {\r
                 if (exclusiveMin->type == cJSON_True)\r
-                    property->setMinDouble( ++(Min->valuedouble));\r
+                    min = ++(itemsMin->valueint);\r
                 else\r
-                    property->setMinDouble(Min->valuedouble);\r
+                    min = itemsMin->valueint;\r
             }\r
             else\r
-                property->setMinDouble(Min->valuedouble);\r
+                min = itemsMin->valueint;\r
         }\r
-        cJSON *multipleOf = cJSON_GetObjectItem(childProperties, "multipleOf");\r
-        if (multipleOf)\r
+        cJSON *uniqueItems = cJSON_GetObjectItem(childProperties, "uniqueItems");\r
+        if (uniqueItems)\r
         {\r
-            property->setMultipleOf(multipleOf->valueint);\r
+            unique = uniqueItems->type;\r
         }\r
-\r
+        cJSON *additionalItems = cJSON_GetObjectItem(childProperties, "additionalItems");\r
+        if (additionalItems)\r
+        {\r
+            addItems = additionalItems->type;\r
+        }\r
+        property->setValueProperty(std::make_shared<ValueProperty>\r
+                                   (ValueProperty::Type::ARRAY, min, max, unique, addItems));\r
     }\r
 \r
-    DefinitionsPtr JsonSchema::readRef(std::string m_ref)\r
+    void JsonSchema::readItems(cJSON *item, PropertiesPtr &property)\r
     {\r
-        std::string delimiter1 = "#";\r
-        std::string delimiter2 = "/";\r
-        std::string fileName;\r
-        if (! m_ref.empty())\r
+        std::string type;\r
+        JsonParameters param;\r
+        cJSON *itemType = cJSON_GetObjectItem(item, "type");\r
+        if (itemType)\r
         {\r
-            std::size_t pos = m_ref.find(delimiter1);\r
-            if ( (pos = m_ref.find(delimiter1)) != std::string::npos)\r
-            {\r
-                fileName = m_ref.substr(0, pos);\r
-                m_ref.erase(0, pos);\r
-            }\r
-            m_ref.erase(0, delimiter1 .length());\r
-            std::string defName;\r
+            type = itemType->valuestring;\r
+        }\r
 \r
-            if (! m_ref.empty())\r
+        cJSON *itemAllOf = cJSON_GetObjectItem(item, "allOf");\r
+        if (itemAllOf)\r
+        {\r
+            readAllOf(itemAllOf , param);\r
+        }\r
+        else\r
+        {\r
+            cJSON *itemOneOf = cJSON_GetObjectItem(item, "oneOf");\r
+            if (itemOneOf)\r
             {\r
-                m_ref.erase(0, delimiter2 .length());\r
-                std::string keyName;\r
-                if ( (pos = m_ref.find(delimiter2)) != std::string::npos)\r
-                {\r
-                    keyName = m_ref.substr(0, pos);\r
-                    m_ref.erase(0, pos + delimiter2.length());\r
-                    if (keyName == "definitions")\r
-                    {\r
-                        if ( (pos = m_ref.find(delimiter2)) != std::string::npos)\r
-                        {\r
-                            defName = m_ref.substr(0, pos);\r
-                        }\r
-                        else if (! m_ref.empty())\r
-                        {\r
-                            defName = m_ref;\r
-                        }\r
-                    }\r
-                }\r
+                readAllOf(itemOneOf , param);\r
             }\r
-            if (!fileName.empty())\r
+        }\r
+\r
+        cJSON *itemReference = cJSON_GetObjectItem(item, "$ref");\r
+        if (itemReference)\r
+        {\r
+            readJsonRef(itemReference , param);\r
+        }\r
+\r
+        if (type == "object")\r
+        {\r
+            cJSON *itemProperties = cJSON_GetObjectItem(item, "properties");\r
+            if (itemProperties)\r
             {\r
-                if (!(defName.empty()))\r
+                cJSON *childProperties = itemProperties->child;\r
+                std::vector<Properties> propertyVector;\r
+                while (childProperties)\r
                 {\r
-                    cJSON *m_json = m_includeResolver->readToJson(fileName);\r
-                    JsonSchemaPtr Refparser = std::make_shared<JsonSchema>(m_json, m_includeResolver);\r
-                    DefinitionsPtr definition = Refparser->getDefinition(defName);\r
-                    if (definition == nullptr)\r
-                        throw JsonException("Definition Name Incorrect");\r
-                    return definition;\r
+                    std::string attName = childProperties->string;\r
+                    PropertiesPtr prop = std::make_shared<Properties>(attName);\r
+                    readProp(childProperties, attName);\r
+                    propertyVector.push_back(*prop);\r
+                    childProperties = childProperties->next;\r
                 }\r
+                property->setValue(propertyVector);\r
             }\r
-            else\r
+\r
+            cJSON *itemRequiredValues = cJSON_GetObjectItem(item, "required");\r
+            if (itemRequiredValues)\r
             {\r
-                if (!(defName.empty()))\r
+                int size = cJSON_GetArraySize(itemRequiredValues);\r
+                int index = 0;\r
+                do\r
                 {\r
-                    if (getDefinition(defName) == nullptr)\r
-                        throw JsonException("Definition Name Incorrect");\r
-                    return getDefinition(defName);\r
+                    property->setRequiredValue(cJSON_GetArrayItem(itemRequiredValues, index)->valuestring);\r
                 }\r
+                while ( ++index < size);\r
             }\r
         }\r
-        throw JsonException("Definition Name Empty");\r
-        return nullptr;\r
-    }\r
-    void JsonSchema::readAllOf(cJSON *allofValues)\r
-    {\r
-        int size = cJSON_GetArraySize(allofValues);\r
-        int index = 0;\r
-        do\r
+\r
+        else if (param.getType() == "object")\r
         {\r
-            cJSON *childAllOf = cJSON_GetArrayItem(allofValues, index);\r
-            cJSON *jsonReference = cJSON_GetObjectItem(childAllOf, "$ref");\r
-            if (jsonReference)\r
+            std::vector<Properties> propertyVector;\r
+            for (auto prop : param.getProperties())\r
             {\r
-                readJsonRef(jsonReference );\r
+                propertyVector.push_back(*(prop.second));\r
             }\r
-            cJSON *jsonRequiredValues = cJSON_GetObjectItem(childAllOf, "required");\r
-            if (jsonRequiredValues)\r
+            property->setValue(propertyVector);\r
+\r
+            for (auto req : param.getRequired())\r
             {\r
-                int len = cJSON_GetArraySize(jsonRequiredValues);\r
-                int idx = 0;\r
-                do\r
-                {\r
-                    setRequiredValue(cJSON_GetArrayItem(jsonRequiredValues, idx)->valuestring);\r
-                }\r
-                while ( ++idx < len);\r
+                property->setRequiredValue(req);\r
             }\r
         }\r
-        while ( ++index < size);\r
-    }\r
-    void JsonSchema::readJsonRef(cJSON *jsonReference)\r
-    {\r
-        std::string m_ref = jsonReference->valuestring;\r
-        std::map<std::string, PropertiesPtr > properties;\r
-        std::vector<std::string> required;\r
-\r
-        std::string web = "http://";\r
-        std::string delimiter = "#";\r
-        std::size_t pos = m_ref.find(web);\r
-\r
-        if (pos == std::string::npos)   // If Web Link Is GIVEN TO READ\r
+        else\r
         {\r
-            pos = m_ref.find(delimiter);\r
-            if ( pos ==  (m_ref.length() - 1) )\r
-            {\r
-                std::string fileName = m_ref.substr(0, pos);\r
-                cJSON *m_json = m_includeResolver->readToJson(fileName);\r
-                JsonSchemaPtr Refparser = std::make_shared<JsonSchema>(m_json, m_includeResolver);\r
+            PropertiesPtr prop = std::make_shared<Properties>("property");\r
 \r
-                properties = Refparser->getProperties();\r
-                required = Refparser->getRequiredValues();\r
-            }\r
-            else\r
+            cJSON *defaultValue = cJSON_GetObjectItem(item, "default");\r
+            if (defaultValue)\r
             {\r
-                DefinitionsPtr definition = readRef(m_ref);\r
-                properties = definition->getProperties();\r
-                required = definition->getRequiredValues();\r
+                readDefaultValue(defaultValue, prop, type);\r
             }\r
-            for ( auto it : properties)\r
+            cJSON *allowedvalues = cJSON_GetObjectItem(item, "enum");\r
+            if (allowedvalues)\r
             {\r
-                std:: string name = it.first;\r
-                addProperty(name, it.second);\r
+                readAllowedValues(allowedvalues, prop, type);\r
             }\r
-            for (auto it : required )\r
-            {\r
-                setRequiredValue(it);\r
-            }\r
-\r
+            readValues(item, prop, type);\r
+            prop->setTypeString(type);\r
+            property->setValue(*prop);\r
         }\r
     }\r
-    void JsonSchema::readDefAllOf(cJSON *allofValues, DefinitionsPtr definition)\r
+\r
+    void JsonSchema::readObject(cJSON *childProperties,  PropertiesPtr &property)\r
     {\r
-        int size = cJSON_GetArraySize(allofValues);\r
-        int index = 0;\r
-        do\r
+        property->setTypeString("object");\r
+\r
+        cJSON *subProperties = cJSON_GetObjectItem(childProperties, "properties");\r
+        cJSON *itemRequiredValues = cJSON_GetObjectItem(childProperties, "required");\r
+        if (subProperties)\r
         {\r
-            cJSON *childAllOf = cJSON_GetArrayItem(allofValues, index);\r
-            cJSON *defReference = cJSON_GetObjectItem(childAllOf, "$ref");\r
-            if (defReference)\r
+            cJSON *childProperties = subProperties->child;\r
+            std::vector<Properties> propertyVector;\r
+            while (childProperties)\r
             {\r
-                readDefRef(defReference , definition);\r
+                std::string attName = childProperties->string;\r
+                PropertiesPtr prop = std::make_shared<Properties>(attName);\r
+                readProp(childProperties, attName);\r
+                propertyVector.push_back(*prop);\r
+                childProperties = childProperties->next;\r
             }\r
-            cJSON *defRequiredValues = cJSON_GetObjectItem(allofValues, "required");\r
-            if (defRequiredValues)\r
+            property->setValue(propertyVector);\r
+            if (itemRequiredValues)\r
             {\r
-                int len = cJSON_GetArraySize(defRequiredValues);\r
-                int idx = 0;\r
+                int size = cJSON_GetArraySize(itemRequiredValues);\r
+                int index = 0;\r
                 do\r
                 {\r
-                    definition->setRequiredValue(cJSON_GetArrayItem(defRequiredValues, idx)->valuestring);\r
+                    property->setRequiredValue(cJSON_GetArrayItem(itemRequiredValues, index)->valuestring);\r
                 }\r
-                while ( ++idx < len);\r
+                while ( ++index < size);\r
             }\r
         }\r
-        while ( ++index < size);\r
-    }\r
-    void JsonSchema::readDefRef(cJSON *defReference, DefinitionsPtr definition)\r
-    {\r
-        std::string m_ref = defReference->valuestring;\r
-        std::map<std::string, PropertiesPtr > properties;\r
-        std::vector<std::string> required;\r
-        std::string type;\r
-\r
-        std::string web = "http://";\r
-        std::string delimiter = "#";\r
-        std::size_t pos = m_ref.find(web);\r
-\r
-        if (pos == std::string::npos)   // If Web Link Is GIVEN TO READ\r
+        else\r
         {\r
-            pos = m_ref.find(delimiter);\r
-            if ( pos ==  (m_ref.length() - 1) )\r
-            {\r
-                std::string fileName = m_ref.substr(0, pos);\r
-                cJSON *m_json = m_includeResolver->readToJson(fileName);\r
-                JsonSchemaPtr Refparser = std::make_shared<JsonSchema>(m_json, m_includeResolver);\r
+            JsonParameters param;\r
 \r
-                properties = Refparser->getProperties();\r
-                required = Refparser->getRequiredValues();\r
-                type =    Refparser->getType();\r
-            }\r
-            else\r
+            cJSON *itemAllOf = cJSON_GetObjectItem(childProperties, "allOf");\r
+            if (itemAllOf)\r
             {\r
-                DefinitionsPtr definitionRef = readRef(m_ref);\r
-                properties = definitionRef->getProperties();\r
-                required = definitionRef->getRequiredValues();\r
-                type =    definitionRef->getType();\r
+                readAllOf(itemAllOf , param);\r
             }\r
-            for (auto it : properties)\r
+            cJSON *itemReference = cJSON_GetObjectItem(childProperties, "$ref");\r
+            if (itemReference)\r
             {\r
-                definition->addProperty(it.first, it.second);\r
+                readJsonRef(itemReference , param);\r
             }\r
-            for ( auto it : required)\r
+\r
+            if (param.getType() == "object")\r
             {\r
-                definition->setRequiredValue(it);\r
+                std::vector<Properties> propertyVector;\r
+                for (auto prop : param.getProperties())\r
+                {\r
+                    propertyVector.push_back(*(prop.second));\r
+                }\r
+                property->setValue(propertyVector);\r
+\r
+                for (auto req : param.getRequired())\r
+                {\r
+                    property->setRequiredValue(req);\r
+                }\r
             }\r
-            definition->setType(type);\r
         }\r
     }\r
-    ItemsPtr JsonSchema::readItems(cJSON *item)\r
+\r
+    void JsonSchema::readFile(std::string &fileName ,  JsonParameters &param)\r
     {\r
-        ItemsPtr newItem = std::make_shared<Items>();\r
-        cJSON *itemType = cJSON_GetObjectItem(item, "type");\r
-        if (itemType)\r
-        {\r
-            std::string type = itemType->valuestring;\r
-            newItem->setType(type);\r
-        }\r
+        std::string name = fileName;\r
+        std::transform(name.begin(), name.end(), name.begin(), ::tolower);\r
+        if (name.compare("oic.baseresource.json") == 0)\r
+            return;\r
+\r
+        cJSON *json = m_includeResolver->readToJson(fileName);\r
+        JsonSchemaPtr Refparser = std::make_shared<JsonSchema>(json, m_includeResolver);\r
 \r
-        cJSON *itemProperties = cJSON_GetObjectItem(item, "properties");\r
-        if (itemProperties)\r
+        param.addProperties(Refparser->getProperties());\r
+        param.addRequired(Refparser->getRequiredValues());\r
+        param.setType(Refparser->getType());\r
+    }\r
+\r
+    void JsonSchema::readFile(std::string &fileName , std::string &defName ,  JsonParameters &param)\r
+    {\r
+        std::string name = fileName;\r
+        std::transform(name.begin(), name.end(), name.begin(), ::tolower);\r
+        if (name.compare("oic.baseresource.json") == 0)\r
+            return;\r
+\r
+        cJSON *json = m_includeResolver->readToJson(fileName);\r
+        JsonSchemaPtr Refparser = std::make_shared<JsonSchema>(json, m_includeResolver);\r
+\r
+        DefinitionsPtr definition = Refparser->getDefinition(defName);\r
+        if (definition == nullptr)\r
+            throw JsonException("Definition Name Incorrect");\r
+\r
+        param.addProperties(definition->getProperties());\r
+        param.addRequired(definition->getRequiredValues());\r
+        param.setType(definition->getType());\r
+    }\r
+\r
+    void JsonSchema::readRef(std::string ref ,  JsonParameters &param)\r
+    {\r
+        std::string delimiter1 = "#";\r
+        std::string delimiter2 = "/";\r
+        std::string fileName;\r
+        if (! ref.empty())\r
         {\r
-            cJSON *childProperties = itemProperties->child;\r
-            while (childProperties)\r
+            std::size_t pos = std::string::npos;\r
+            if ( (pos = ref.find(delimiter1)) != std::string::npos)\r
             {\r
-                std::string attName = childProperties->string;\r
-\r
-                newItem->addProperty(attName, readProp(childProperties, attName));\r
-                childProperties = childProperties->next;\r
+                fileName = ref.substr(0, pos);\r
+                ref.erase(0, pos);\r
             }\r
-        }\r
+            ref.erase(0, delimiter1 .length());\r
+            std::string defName;\r
 \r
-        cJSON *allowedvalues = cJSON_GetObjectItem(item, "enum");\r
-        if (allowedvalues)\r
-        {\r
-            if ((cJSON_GetArrayItem(allowedvalues, 0)->type) == 4)\r
+            if (! ref.empty())\r
             {\r
-                int size = cJSON_GetArraySize(allowedvalues);\r
-                int idx = 0;\r
-                std::vector<std::string> allwdValues;\r
-                do\r
+                ref.erase(0, delimiter2 .length());\r
+                std::string keyName;\r
+                if ( (pos = ref.find(delimiter2)) != std::string::npos)\r
                 {\r
-                    allwdValues.push_back(cJSON_GetArrayItem(allowedvalues, idx)->valuestring);\r
+                    keyName = ref.substr(0, pos);\r
+                    ref.erase(0, pos + delimiter2.length());\r
+                    if (keyName == "definitions")\r
+                    {\r
+                        if ( (pos = ref.find(delimiter2)) != std::string::npos)\r
+                        {\r
+                            defName = ref.substr(0, pos);\r
+                        }\r
+                        else if (! ref.empty())\r
+                        {\r
+                            defName = ref;\r
+                        }\r
+                    }\r
                 }\r
-                while ( ++idx < size);\r
-                newItem->setAllowedValues(allwdValues);\r
             }\r
-            else if ((cJSON_GetArrayItem(allowedvalues, 0)->type) == 3)\r
+            if (!fileName.empty())\r
             {\r
-                int size = cJSON_GetArraySize(allowedvalues);\r
-                int idx = 0;\r
-                if (newItem->getType() == "number")\r
+                if (!(defName.empty()))\r
                 {\r
-                    std::vector<double> allwdValues;\r
-                    do\r
-                    {\r
-                        allwdValues.push_back(cJSON_GetArrayItem(allowedvalues, idx)->valuedouble);\r
-                    }\r
-                    while ( ++idx < size);\r
-                    newItem->setAllowedValues(allwdValues);\r
+                    readFile(fileName, defName, param);\r
                 }\r
                 else\r
                 {\r
-                    std::vector<int> allwdValues;\r
-                    do\r
-                    {\r
-                        allwdValues.push_back(cJSON_GetArrayItem(allowedvalues, idx)->valueint);\r
-                    }\r
-                    while ( ++idx < size);\r
-                    newItem->setAllowedValues(allwdValues);\r
+                    throw JsonException("Definition Name Empty");\r
                 }\r
             }\r
-            else if (((cJSON_GetArrayItem(allowedvalues, 0)->type) == 1)\r
-                     || ((cJSON_GetArrayItem(allowedvalues, 0)->type) == 0))\r
+            else\r
             {\r
-                int size = cJSON_GetArraySize(allowedvalues);\r
-                int idx = 0;\r
-                std::vector<bool> allwdValues;\r
-                do\r
+                if (!(defName.empty()))\r
                 {\r
-                    if (cJSON_GetArrayItem(allowedvalues, idx)->type)\r
-                        allwdValues.push_back(true);\r
-                    else\r
-                        allwdValues.push_back(false);\r
+                    if (getDefinition(defName) == nullptr)\r
+                        throw JsonException("Definition Name Incorrect");\r
+                    param.addProperties(getDefinition(defName)->getProperties());\r
+                    param.addRequired(getDefinition(defName)->getRequiredValues());\r
+                    param.setType(getDefinition(defName)->getType());\r
+                }\r
+                else\r
+                {\r
+                    throw JsonException("Definition Name Empty");\r
                 }\r
-                while ( ++idx < size);\r
-                newItem->setAllowedValues(allwdValues);\r
-            }\r
-        }\r
-        cJSON *itemRequiredValues = cJSON_GetObjectItem(item, "required");\r
-        if (itemRequiredValues)\r
-        {\r
-            int size = cJSON_GetArraySize(itemRequiredValues);\r
-            int index = 0;\r
-            do\r
-            {\r
-                newItem->setRequiredValue(cJSON_GetArrayItem(itemRequiredValues, index)->valuestring);\r
             }\r
-            while ( ++index < size);\r
         }\r
-        cJSON *itemReference = cJSON_GetObjectItem(item, "$ref");\r
-        if (itemReference)\r
-        {\r
-            readItemRef(itemReference , newItem);\r
-        }\r
-        cJSON *itemAllOf = cJSON_GetObjectItem(item, "allOf");\r
-        if (itemAllOf)\r
-        {\r
-            readItemAllOf(itemAllOf , newItem);\r
-        }\r
-        return newItem;\r
     }\r
 \r
-    void JsonSchema::readItemRef(cJSON *itemReference, ItemsPtr item)\r
+    void JsonSchema::readJsonRef(cJSON *jsonReference , JsonParameters &param)\r
     {\r
-        std::string m_ref = itemReference->valuestring;\r
-        std::map<std::string, PropertiesPtr > properties;\r
-        std::vector<std::string> required;\r
-        std::string type;\r
+        std::string ref = jsonReference->valuestring;\r
 \r
         std::string web = "http://";\r
         std::string delimiter = "#";\r
-        std::size_t pos = m_ref.find(web);\r
+        std::size_t pos = ref.find(web);\r
 \r
         if (pos == std::string::npos)   // If Web Link Is GIVEN TO READ\r
         {\r
-            pos = m_ref.find(delimiter);\r
-            if ( pos ==  (m_ref.length() - 1 ) )\r
+            pos = ref.find(delimiter);\r
+            if ( pos ==  (ref.length() - 1) )\r
             {\r
-                std::string fileName = m_ref.substr(0, pos);\r
-                cJSON *m_json = m_includeResolver->readToJson(fileName);\r
-                JsonSchemaPtr Refparser = std::make_shared<JsonSchema>(m_json, m_includeResolver);\r
-\r
-                properties = Refparser->getProperties();\r
-                required = Refparser->getRequiredValues();\r
-                type =    Refparser->getType();\r
+                std::string fileName = ref.substr(0, pos);\r
+                readFile(fileName, param);\r
             }\r
             else\r
             {\r
-                DefinitionsPtr definitionRef = readRef(m_ref);\r
-                properties = definitionRef->getProperties();\r
-                required = definitionRef->getRequiredValues();\r
-                type =    definitionRef->getType();\r
-            }\r
-            for ( auto it : properties)\r
-            {\r
-                std:: string name = it.first;\r
-                item->addProperty(name, it.second);\r
-            }\r
-            for ( auto it : required)\r
-            {\r
-                item->setRequiredValue(it);\r
+                readRef(ref, param);\r
             }\r
-            item->setType(type);\r
         }\r
     }\r
 \r
-    void JsonSchema::readItemAllOf(cJSON *allofValues, ItemsPtr item)\r
+    void JsonSchema::readAllOf(cJSON *allofValues ,  JsonParameters &allParams)\r
     {\r
         int size = cJSON_GetArraySize(allofValues);\r
         int index = 0;\r
         do\r
         {\r
+            JsonParameters param;\r
+\r
             cJSON *childAllOf = cJSON_GetArrayItem(allofValues, index);\r
-            cJSON *itemReference = cJSON_GetObjectItem(childAllOf, "$ref");\r
-            if (itemReference)\r
+            cJSON *jsonReference = cJSON_GetObjectItem(childAllOf, "$ref");\r
+            if (jsonReference)\r
             {\r
-                readItemRef(itemReference, item);\r
+                readJsonRef(jsonReference, param);\r
+                allParams.addProperties(param.getProperties());\r
+                allParams.addRequired(param.getRequired());\r
+                allParams.setType(param.getType());\r
             }\r
-            cJSON *itemRequiredValues = cJSON_GetObjectItem(allofValues, "required");\r
-            if (itemRequiredValues)\r
+            cJSON *jsonRequiredValues = cJSON_GetObjectItem(childAllOf, "required");\r
+            if (jsonRequiredValues)\r
             {\r
-                int len = cJSON_GetArraySize(itemRequiredValues);\r
+                int len = cJSON_GetArraySize(jsonRequiredValues);\r
                 int idx = 0;\r
                 do\r
                 {\r
-                    item->setRequiredValue(cJSON_GetArrayItem(itemRequiredValues, idx)->valuestring);\r
+                    allParams.addRequired(cJSON_GetArrayItem(jsonRequiredValues, idx)->valuestring);\r
                 }\r
                 while ( ++idx < len);\r
             }\r
index c52a145..333e571 100755 (executable)
 #include <vector>\r
 #include <map>\r
 #include "Properties.h"\r
-#include "Items.h"\r
 #include "Definitions.h"\r
 #include "cJSON.h"\r
-#include "Helpers.h"\r
-#include "AllowedValues.h"\r
 #include <memory>\r
 \r
 #include "IncludeResolver.h"\r
@@ -52,14 +49,15 @@ namespace RAML
             /**\r
                   * Constructor of JsonSchema.\r
                   */\r
-            JsonSchema() : m_cjson(NULL), m_includeResolver(NULL)  {}\r
+            JsonSchema() : m_additionalProperties(cJSON_True), m_cjson(NULL), m_includeResolver(NULL)  {}\r
 \r
             /**\r
                   * Constructor of JsonSchema.\r
                   *\r
                   * @param includeResolver - Reference to IncludeResolver for reading external files\r
                   */\r
-            JsonSchema(const IncludeResolverPtr &includeResolver) : m_cjson(NULL),\r
+            JsonSchema(const IncludeResolverPtr &includeResolver) : m_additionalProperties(cJSON_True),\r
+                m_cjson(NULL),\r
                 m_includeResolver(includeResolver) {}\r
 \r
             /**\r
@@ -68,7 +66,8 @@ namespace RAML
                   * @param cjson - pointer to cjson\r
                   * @param includeResolver - Reference to IncludeResolver for reading external files\r
                   */\r
-            JsonSchema(cJSON *cjson , const IncludeResolverPtr &includeResolver) : m_cjson(cjson),\r
+            JsonSchema(cJSON *cjson , const IncludeResolverPtr &includeResolver) : m_additionalProperties(\r
+                    cJSON_True), m_cjson(cjson),\r
                 m_includeResolver(includeResolver)  { readJson(); }\r
 \r
 \r
@@ -96,7 +95,7 @@ namespace RAML
                  *\r
                  * @return pointer to Properties\r
                  */\r
-            inline PropertiesPtr getProperty(const std::string &name)\r
+            PropertiesPtr getProperty(const std::string &name)\r
             {\r
                 if (m_properties.end() != m_properties.find(name))\r
                 {\r
@@ -110,7 +109,7 @@ namespace RAML
                  *\r
                  * @return map of Properties name and pointer to Properties\r
                  */\r
-            inline std::map<std::string, PropertiesPtr > const &getProperties()\r
+            std::map<std::string, PropertiesPtr > const &getProperties()\r
             {\r
                 return m_properties;\r
             }\r
@@ -120,7 +119,7 @@ namespace RAML
                  *\r
                  * @return map of Definitions name and pointer to Definitions\r
                  */\r
-            inline std::map<std::string, DefinitionsPtr > const &getDefinitions()\r
+            std::map<std::string, DefinitionsPtr > const &getDefinitions()\r
             {\r
                 return m_definition;\r
             }\r
@@ -252,46 +251,56 @@ namespace RAML
                 return  m_additionalProperties;\r
             }\r
 \r
-            /**\r
-                 * This method is for setting Items to JsonSchema.\r
-                 *\r
-                 * @param item -pointer to Items\r
-                 */\r
-            void setItem(const ItemsPtr &item)\r
-            {\r
-                m_items.push_back(item);\r
-            }\r
-\r
-            /**\r
-                 * This method is for getting Items from JsonSchema.\r
-                 *\r
-                 * @return vector of Items\r
-                 */\r
-            std::vector<ItemsPtr> const &getItems()\r
+        private:\r
+            class JsonParameters\r
             {\r
-                return m_items;\r
-            }\r
+                public:\r
+                    std::map<std::string, PropertiesPtr > getProperties() const { return m_properties; }\r
+                    void addProperties(const std::string &name, const PropertiesPtr &prop) { m_properties[name] = prop; }\r
+                    void addProperties(const std::map<std::string, PropertiesPtr > &properties)\r
+                    {\r
+                        for (auto prop : properties)\r
+                            m_properties[prop.first] = prop.second;\r
+                    }\r
+                    std::vector<std::string> getRequired() const { return m_required; }\r
+                    void addRequired(const std::string &req) { m_required.push_back(req); }\r
+                    void addRequired(const std::vector<std::string> &required)\r
+                    {\r
+                        for (auto req : required)\r
+                            m_required.push_back(req);\r
+                    }\r
+                    std::string getType() const { return m_type; }\r
+                    void setType(const std::string &type)\r
+                    {\r
+                        if (m_type.empty())\r
+                            m_type = type;\r
+                    }\r
+\r
+                private:\r
+                    std::map<std::string, PropertiesPtr > m_properties;\r
+                    std::vector<std::string> m_required;\r
+                    std::string m_type;\r
+            };\r
 \r
-        private:\r
             void readJson();\r
             DefinitionsPtr readDef(cJSON *childDefinitions, const std::string &defName);\r
             PropertiesPtr readProp(cJSON *childProperties, const std::string &attName );\r
-            void readValues( cJSON *childProperties,  PropertiesPtr property ,\r
+            void readDefaultValue(cJSON *defaultValue,  PropertiesPtr &property, const std::string &attType);\r
+            void readAllowedValues(cJSON *allowedvalues,  PropertiesPtr &property, std::string &attType);\r
+            void readValues( cJSON *childProperties,  PropertiesPtr &property ,\r
                              const std::string &attType);\r
-            void readString( cJSON *childProperties, PropertiesPtr property);\r
-            void readArray( cJSON *childProperties,  PropertiesPtr property);\r
-            void readInteger( cJSON *childProperties,  PropertiesPtr property);\r
-            void readDouble( cJSON *childProperties,  PropertiesPtr property);\r
-            DefinitionsPtr readRef(std::string m_ref);\r
-\r
-\r
-            void readJsonRef(cJSON *jsonReference);\r
-            void readDefRef(cJSON *defReference, DefinitionsPtr definition);\r
-            void readAllOf(cJSON *allofValues);\r
-            void readDefAllOf(cJSON *allofValues, DefinitionsPtr definition);\r
-            ItemsPtr readItems(cJSON *item);\r
-            void readItemRef(cJSON *itemReference, ItemsPtr item);\r
-            void readItemAllOf(cJSON *allofValues,  ItemsPtr item);\r
+            void readString( cJSON *childProperties, PropertiesPtr &property);\r
+            void readInteger( cJSON *childProperties,  PropertiesPtr &property);\r
+            void readDouble( cJSON *childProperties,  PropertiesPtr &property);\r
+            void readArray( cJSON *childProperties,  PropertiesPtr &property);\r
+            void readItems(cJSON *item, PropertiesPtr &property);\r
+            void readObject(cJSON *childProperties,  PropertiesPtr &property);\r
+\r
+            void readFile(std::string &fileName , JsonParameters &param);\r
+            void readFile(std::string &fileName , std::string &defName , JsonParameters &param);\r
+            void readRef(std::string ref , JsonParameters &param);\r
+            void readJsonRef(cJSON *jsonReference , JsonParameters &param);\r
+            void readAllOf(cJSON *allofValues ,  JsonParameters &allParams);\r
 \r
         private:\r
             std::map<std::string, PropertiesPtr > m_properties;\r
@@ -304,8 +313,9 @@ namespace RAML
             std::string m_type;\r
             cJSON *m_cjson;\r
             std::vector<std::string>  m_required;\r
-            std::vector<ItemsPtr > m_items;\r
+            PropertiesPtr m_property;\r
             IncludeResolverPtr m_includeResolver;\r
+\r
     };\r
 \r
     /** JsonSchemaPtr - shared Ptr to JsonSchema.*/\r
diff --git a/service/simulator/ramlparser/raml/jsonSchemaParser/Properties.cpp b/service/simulator/ramlparser/raml/jsonSchemaParser/Properties.cpp
new file mode 100755 (executable)
index 0000000..8905525
--- /dev/null
@@ -0,0 +1,409 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 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
+ * @file   Properties.cpp\r
+ *\r
+ * @brief   This file provides data Model for Json Schema Properties.\r
+ */\r
+\r
+#include "Properties.h"\r
+#include <boost/lexical_cast.hpp>\r
+#include <boost/variant/static_visitor.hpp>\r
+#include "RamlExceptions.h"\r
+\r
+namespace RAML\r
+{\r
+    template <typename T>\r
+    struct TypeConverter {};\r
+\r
+    template <>\r
+    struct TypeConverter<int>\r
+    {\r
+        constexpr static VariantType type =\r
+            VariantType::INTEGER;\r
+    };\r
+\r
+    template <>\r
+    struct TypeConverter<double>\r
+    {\r
+        constexpr static VariantType type =\r
+            VariantType::DOUBLE;\r
+    };\r
+\r
+    template <>\r
+    struct TypeConverter<bool>\r
+    {\r
+        constexpr static VariantType type =\r
+            VariantType::BOOLEAN;\r
+    };\r
+\r
+    template <>\r
+    struct TypeConverter<std::string>\r
+    {\r
+        constexpr static VariantType type =\r
+            VariantType::STRING;\r
+    };\r
+\r
+    template <>\r
+    struct TypeConverter<Properties>\r
+    {\r
+        constexpr static VariantType type =\r
+            VariantType::PROPERTY;\r
+    };\r
+\r
+    template <typename T>\r
+    struct TypeDetails\r
+    {\r
+        constexpr static VariantType type =\r
+            TypeConverter<T>::type;\r
+        constexpr static VariantType baseType =\r
+            TypeConverter<T>::type;\r
+        constexpr static int depth = 0;\r
+    };\r
+\r
+    template <typename T>\r
+    struct TypeDetails<std::vector<T>>\r
+    {\r
+        constexpr static VariantType type =\r
+            VariantType::ARRAY;\r
+        constexpr static VariantType baseType =\r
+            TypeDetails<T>::baseType;\r
+        constexpr static int depth = 1 + TypeDetails<T>::depth;\r
+    };\r
+\r
+    class PropertyTypeVisitor : public boost::static_visitor<>\r
+    {\r
+        public:\r
+            PropertyTypeVisitor() : m_type(VariantType::UNKNOWN),\r
+                m_baseType(VariantType::UNKNOWN), m_depth(0) {}\r
+\r
+            template <typename T>\r
+            void operator ()(const T &)\r
+            {\r
+                m_type = TypeDetails<T>::type;\r
+                m_baseType = TypeDetails<T>::baseType;\r
+                m_depth = TypeDetails<T>::depth;\r
+            }\r
+\r
+            VariantType m_type;\r
+            VariantType m_baseType;\r
+            int m_depth;\r
+    };\r
+\r
+    Properties::TypeInfo Properties::getType() const\r
+    {\r
+        if (m_value)\r
+        {\r
+            RAML::PropertyTypeVisitor typeVisitor;\r
+            boost::apply_visitor(typeVisitor, *(m_value.get()));\r
+            Properties::TypeInfo typeInfo(typeVisitor.m_type, typeVisitor.m_baseType,\r
+                                          typeVisitor.m_depth);\r
+            return typeInfo;\r
+        }\r
+        else if (!m_typeString.empty()) //to read properties even if default value is not present\r
+        {\r
+            if (m_typeString == "string")\r
+                return Properties::TypeInfo(VariantType::STRING, VariantType::STRING, 0);\r
+            else if (m_typeString == "integer")\r
+                return Properties::TypeInfo(VariantType::INTEGER, VariantType::INTEGER, 0);\r
+            else if (m_typeString == "number")\r
+                return Properties::TypeInfo(VariantType::DOUBLE, VariantType::DOUBLE, 0);\r
+            else if (m_typeString == "boolean")\r
+                return Properties::TypeInfo(VariantType::BOOLEAN, VariantType::BOOLEAN, 0);\r
+        }\r
+        return Properties::TypeInfo();\r
+    }\r
+\r
+    void Properties::setTypeString(const std::string &type)\r
+    {\r
+        m_typeString = type;\r
+    }\r
+\r
+    Properties::TypeInfo::TypeInfo(VariantType type,\r
+                                   VariantType baseType, int depth)\r
+        :   m_type (type), m_baseType(baseType), m_depth(depth) {}\r
+\r
+    VariantType Properties::TypeInfo::type() const\r
+    {\r
+        return m_type;\r
+    }\r
+\r
+    VariantType Properties::TypeInfo::baseType() const\r
+    {\r
+        return m_baseType;\r
+    }\r
+\r
+    int Properties::TypeInfo::depth() const\r
+    {\r
+        return m_depth;\r
+    }\r
+\r
+    bool Properties::TypeInfo::operator==(\r
+        const Properties::TypeInfo &rhs ) const\r
+    {\r
+        if (m_type == rhs.type() && m_baseType == rhs.baseType()\r
+            && m_depth == rhs.depth())\r
+            return true;\r
+        return false;\r
+    }\r
+\r
+    bool Properties::TypeInfo::operator!=(\r
+        const Properties::TypeInfo &rhs ) const\r
+    {\r
+        if (m_type != rhs.type() || m_baseType != rhs.baseType()\r
+            || m_depth != rhs.depth())\r
+            return true;\r
+        return false;\r
+    }\r
+\r
+    ValueVariant Properties::getValue() const\r
+    {\r
+        if (!isDefaultValue())\r
+            throw JsonException("Reading Empty Property Value");\r
+        return *m_value;\r
+    }\r
+\r
+    std::string Properties::getName() const\r
+    {\r
+        return m_name;\r
+    }\r
+\r
+    void Properties::setName(const std::string &name)\r
+    {\r
+        m_name = name;\r
+    }\r
+    std::string Properties::getDescription() const\r
+    {\r
+        return m_description;\r
+    }\r
+\r
+    void Properties::setDescription(const std::string &description)\r
+    {\r
+        m_description = description;\r
+    }\r
+    std::vector<std::shared_ptr<ValueProperty> > const &Properties::getValueProperties()\r
+    const\r
+    {\r
+        return m_valueProperty;\r
+    }\r
+    void Properties::setValueProperty(const std::shared_ptr<ValueProperty> &value)\r
+    {\r
+        m_valueProperty.push_back(value);\r
+    }\r
+    std::vector<std::string> const &Properties::getRequiredValues() const\r
+    {\r
+        return m_required;\r
+    }\r
+    void Properties::setRequiredValue(const std::string &reqValue)\r
+    {\r
+        auto it = m_required.begin();\r
+        for (; it != m_required.end(); ++it)\r
+        {\r
+            if (*it == reqValue)\r
+                break;\r
+        }\r
+        if (m_required.end() == it)\r
+        {\r
+            m_required.push_back(reqValue);\r
+        }\r
+    }\r
+    ValueProperty::ValueProperty()\r
+        :   m_type(ValueProperty::Type::UNKNOWN),\r
+            m_min(INT_MIN),\r
+            m_max(INT_MAX),\r
+            m_multipleOf(INT_MAX),\r
+            m_minItems(INT_MIN),\r
+            m_maxItems(INT_MAX),\r
+            m_unique(false),\r
+            m_additionalItems(false) {}\r
+\r
+    ValueProperty::ValueProperty(double min, double max, int multipleOf)\r
+        :   m_type(ValueProperty::Type::RANGE),\r
+            m_min(min),\r
+            m_max(max),\r
+            m_multipleOf(multipleOf),\r
+            m_minItems(INT_MIN),\r
+            m_maxItems(INT_MAX),\r
+            m_unique(false),\r
+            m_additionalItems(false) {}\r
+\r
+    ValueProperty::ValueProperty(\r
+        const std::vector<int> &valueSet)\r
+        :   m_type(ValueProperty::Type::VALUE_SET),\r
+            m_min(INT_MIN),\r
+            m_max(INT_MAX),\r
+            m_multipleOf(INT_MAX),\r
+            m_valueSet(valueSet.begin(), valueSet.end()),\r
+            m_minItems(INT_MIN),\r
+            m_maxItems(INT_MAX),\r
+            m_unique(false),\r
+            m_additionalItems(false)  {}\r
+\r
+    ValueProperty::ValueProperty(\r
+        const std::vector<double> &valueSet)\r
+        :   m_type(ValueProperty::Type::VALUE_SET),\r
+            m_min(INT_MIN),\r
+            m_max(INT_MAX),\r
+            m_multipleOf(INT_MAX),\r
+            m_valueSet(valueSet.begin(), valueSet.end()),\r
+            m_minItems(INT_MIN),\r
+            m_maxItems(INT_MAX),\r
+            m_unique(false),\r
+            m_additionalItems(false)  {}\r
+\r
+    ValueProperty::ValueProperty(\r
+        const std::vector<bool> &valueSet)\r
+        :   m_type(ValueProperty::Type::VALUE_SET),\r
+            m_min(INT_MIN),\r
+            m_max(INT_MAX),\r
+            m_multipleOf(INT_MAX),\r
+            m_valueSet(valueSet.begin(), valueSet.end()),\r
+            m_minItems(INT_MIN),\r
+            m_maxItems(INT_MAX),\r
+            m_unique(false),\r
+            m_additionalItems(false)  {}\r
+\r
+    ValueProperty::ValueProperty(\r
+        const std::vector<std::string> &valueSet)\r
+        :   m_type(ValueProperty::Type::VALUE_SET),\r
+            m_min(INT_MIN),\r
+            m_max(INT_MAX),\r
+            m_multipleOf(INT_MAX),\r
+            m_valueSet(valueSet.begin(), valueSet.end()),\r
+            m_minItems(INT_MIN),\r
+            m_maxItems(INT_MAX),\r
+            m_unique(false),\r
+            m_additionalItems(false)  {}\r
+\r
+    ValueProperty::ValueProperty(\r
+        const std::vector<ValueVariant> &valueSet)\r
+        :   m_type(ValueProperty::Type::VALUE_SET),\r
+            m_min(INT_MIN),\r
+            m_max(INT_MAX),\r
+            m_multipleOf(INT_MAX),\r
+            m_valueSet(valueSet.begin(), valueSet.end()),\r
+            m_minItems(INT_MIN),\r
+            m_maxItems(INT_MAX),\r
+            m_unique(false),\r
+            m_additionalItems(false)  {}\r
+\r
+    ValueProperty::ValueProperty(Type type, std::string value)\r
+        :   m_min(INT_MIN),\r
+            m_max(INT_MAX),\r
+            m_multipleOf(INT_MAX),\r
+            m_minItems(INT_MIN),\r
+            m_maxItems(INT_MAX),\r
+            m_unique(false),\r
+            m_additionalItems(false)\r
+    {\r
+        if (type == ValueProperty::Type::PATTERN)\r
+        {\r
+            m_type = ValueProperty::Type::PATTERN;\r
+            m_pattern = value;\r
+        }\r
+        else if (type == ValueProperty::Type::FORMAT)\r
+        {\r
+            m_type = ValueProperty::Type::FORMAT;\r
+            m_format = value;\r
+        }\r
+        else\r
+        {\r
+            m_type = ValueProperty::Type::UNKNOWN;\r
+        }\r
+    }\r
+\r
+    ValueProperty::ValueProperty(Type type, int minItems, int maxItems, bool unique,\r
+                                 bool additionalItems)\r
+        :   m_type(ValueProperty::Type::UNKNOWN),\r
+            m_min(INT_MIN),\r
+            m_max(INT_MAX),\r
+            m_multipleOf(INT_MAX),\r
+            m_minItems(1),\r
+            m_maxItems(20),\r
+            m_unique(false),\r
+            m_additionalItems(false)\r
+    {\r
+        if (type == ValueProperty::Type::ARRAY)\r
+        {\r
+            m_type = ValueProperty::Type::ARRAY;\r
+\r
+            if (minItems > 0)\r
+                m_minItems = minItems;\r
+\r
+            if (maxItems != INT_MAX && maxItems > m_minItems)\r
+                m_maxItems = maxItems;\r
+\r
+            m_unique = unique;\r
+            m_additionalItems = additionalItems;\r
+        }\r
+    }\r
+\r
+    ValueProperty::Type ValueProperty::type() const\r
+    {\r
+        return m_type;\r
+    }\r
+\r
+    double ValueProperty::min() const\r
+    {\r
+        return m_min;\r
+    }\r
+\r
+    double ValueProperty::max() const\r
+    {\r
+        return m_max;\r
+    }\r
+\r
+    int ValueProperty::multipleOf() const\r
+    {\r
+        return m_multipleOf;\r
+    }\r
+\r
+    std::string ValueProperty::pattern() const\r
+    {\r
+        return m_pattern;\r
+    }\r
+\r
+    std::string ValueProperty::format() const\r
+    {\r
+        return m_format;\r
+    }\r
+\r
+    int ValueProperty::valueSetSize() const\r
+    {\r
+        return m_valueSet.size();\r
+    }\r
+\r
+    std::vector<ValueVariant> ValueProperty::valueSet() const\r
+    {\r
+        return m_valueSet;\r
+    }\r
+\r
+    void ValueProperty::valueArray(int &minItems, int &maxItems, bool &unique,\r
+                                   bool &additionalItems) const\r
+    {\r
+        minItems = m_minItems;\r
+        maxItems = m_maxItems;\r
+        unique = m_unique;\r
+        additionalItems = m_additionalItems;\r
+    }\r
+\r
+\r
+}\r
index 7291635..dd784d8 100755 (executable)
 #include <boost/variant.hpp>\r
 #include <boost/lexical_cast.hpp>\r
 #include <limits>\r
-#include "Items.h"\r
-#include "AllowedValues.h"\r
 #include "cJSON.h"\r
 #include <memory>\r
 \r
 namespace RAML\r
 {\r
+    class Properties;\r
+\r
+    /** ValueVariant - Boost Variant to hold type of property*/\r
+    typedef boost::variant <\r
+    int,\r
+    double,\r
+    bool,\r
+    std::string,\r
+    Properties,\r
+    std::vector<Properties>\r
+\r
+    > ValueVariant;\r
+\r
+    /** VariantType - enumeration for variant types*/\r
+    enum class VariantType\r
+    {\r
+        UNKNOWN,\r
+        INTEGER,\r
+        DOUBLE,\r
+        BOOLEAN,\r
+        STRING,\r
+        PROPERTY,\r
+        ARRAY,\r
+        OBJECT\r
+    };\r
+\r
     /**\r
-     * @class   Properties\r
-     * @brief   This class provides data Model for Json Schema Properties.\r
+     * @class   ValueProperty\r
+     * @brief   This class provides data Model for Json Schema Value Property.\r
      */\r
-    class Properties\r
+    class ValueProperty\r
     {\r
         public:\r
-            /**\r
-                  * Constructor of Properties.\r
-                  */\r
-            Properties(): m_min(INT_MAX), m_max(INT_MAX), m_doubleMin(INT_MAX), m_doubleMax(INT_MAX),\r
-                m_multipleOf(INT_MAX), m_unique(false), m_additionalItems(false) {}\r
+            /** Type - enumeration for ValueProperty types*/\r
+            enum class Type\r
+            {\r
+                UNKNOWN,\r
+                RANGE,\r
+                VALUE_SET,\r
+                PATTERN,\r
+                FORMAT,\r
+                ARRAY\r
+            };\r
 \r
             /**\r
-                  * Constructor of Properties.\r
-                  *\r
-                  * @param name - Properties name as string.\r
-                  */\r
-            Properties(const std::string &name) : m_name(name), m_min(INT_MAX), m_max(INT_MAX),\r
-                m_doubleMin(INT_MAX), m_doubleMax(INT_MAX), m_multipleOf(INT_MAX),\r
-                m_unique(false), m_additionalItems(false) {}\r
+             * Constructor of ValueProperty.\r
+             */\r
+            ValueProperty();\r
 \r
-            /**\r
-                 * This method is for getting Name from Properties.\r
-                 *\r
-                 * @return Properties name as string\r
-                 */\r
-            inline std::string getName(void) const\r
-            {\r
-                return m_name;\r
-            }\r
+            ValueProperty(const ValueProperty &) = default;\r
 \r
-            /**\r
-                 * This method is for setting name to Properties\r
-                 *\r
-                 * @param name - Properties name as string.\r
-                 */\r
-            inline void setName(const std::string &name)\r
-            {\r
-                m_name = name;\r
-            }\r
+            ValueProperty &operator=(const ValueProperty &) = default;\r
 \r
-            /**\r
-                 * This method is for getting Value from Properties.\r
-                 *\r
-                 * @return Properties Value\r
-                 */\r
-            template <typename T>\r
-            T getValue() const\r
-            {\r
-                return boost::get<T>(m_value);\r
-            }\r
+            ValueProperty(ValueProperty &&) = default;\r
 \r
-            /**\r
-                 * This method is for getting Value from Properties.\r
-                 *\r
-                 * @return Properties Value\r
-                 */\r
-            ValueVariant &getValue()\r
-            {\r
-                return m_value;\r
-            }\r
+            ValueProperty &operator=(ValueProperty &&) = default;\r
 \r
             /**\r
-                 * This method is for getting ValueVariant type from Properties.\r
-                 *\r
-                 * @return Properties Value type as Int\r
-                 */\r
-            int getValueType() const\r
-            {\r
-                return m_value.which();\r
-            }\r
+             * explicit Constructor of ValueProperty for Type RANGE.\r
+             *\r
+             * @param min - minimum value of property.\r
+             * @param max- maximum value of property.\r
+             * @param multipleOf- multipleOf value of property.\r
+             */\r
+            explicit ValueProperty(double min, double max, int multipleOf);\r
 \r
             /**\r
-                 * This method is for getting ValueVariant type from Properties.\r
-                 *\r
-                 * @return Properties VariantType type\r
-                 */\r
-            VariantType getVariantType() const\r
-            {\r
-                if (m_value.which() == 3)\r
-                    return VariantType::STRING;\r
-                else if (m_value.which() == 2)\r
-                    return VariantType::BOOL;\r
-                else if (m_value.which() == 1)\r
-                    return VariantType::DOUBLE;\r
-                else\r
-                    return VariantType::INT;\r
-            }\r
+             * explicit Constructor of ValueProperty for Type VALUE_SET.\r
+             *\r
+             * @param valueSet - allowed values in the Properties.\r
+             */\r
+            explicit ValueProperty(const std::vector<int> &valueSet);\r
 \r
             /**\r
-                 * This method is for getting Value type as Integer from Properties.\r
-                 *\r
-                 * @return Properties Value type as Integer\r
-                 */\r
-            int getValueInt()\r
-            {\r
-                return boost::lexical_cast<int> (m_value);\r
-            }\r
+             * explicit Constructor of ValueProperty for Type VALUE_SET.\r
+             *\r
+             * @param valueSet - allowed values in the Properties.\r
+             */\r
+            explicit ValueProperty(const std::vector<double> &valueSet);\r
 \r
             /**\r
-                 * This method is for getting Value type as String from Properties.\r
-                 *\r
-                 * @return Properties Value type as String\r
-                 */\r
-            std::string getValueString()\r
-            {\r
-                return boost::lexical_cast<std::string> (m_value);\r
-            }\r
+             * explicit Constructor of ValueProperty for Type VALUE_SET.\r
+             *\r
+             * @param valueSet - allowed values in the Properties.\r
+             */\r
+            explicit ValueProperty(const std::vector<bool> &valueSet);\r
 \r
             /**\r
-                 * This method is for getting Value type as double from Properties.\r
-                 *\r
-                 * @return Properties Value type as double\r
-                 */\r
-            double getValueDouble()\r
-            {\r
-                return boost::lexical_cast<double> (m_value);\r
-            }\r
+             * explicit Constructor of ValueProperty for Type VALUE_SET.\r
+             *\r
+             * @param valueSet - allowed values in the Properties.\r
+             */\r
+            explicit ValueProperty(const std::vector<std::string> &valueSet);\r
 \r
             /**\r
-                 * This method is for getting Value type as bool from Properties.\r
-                 *\r
-                 * @return Properties Value type as bool\r
-                 */\r
-            bool getValueBool()\r
-            {\r
-                return boost::lexical_cast<bool> (m_value);\r
-            }\r
+             * explicit Constructor of ValueProperty for Type VALUE_SET.\r
+             *\r
+             * @param valueSet - allowed values in the Properties.\r
+             */\r
+            explicit ValueProperty(const std::vector<ValueVariant> &valueSet);\r
 \r
             /**\r
-                 * This method is for setting Value to Properties\r
-                 *\r
-                 * @param value - Properties Value.\r
-                 */\r
-            template <typename T>\r
-            void setValue(const T &value)\r
-            {\r
-                m_value = value;\r
-            }\r
+             * explicit Constructor of ValueProperty for Type PATTERN or FORMAT.\r
+             *\r
+             * @param type - ValueProperty Type.\r
+             * @param value - value for the pattern or format.\r
+             */\r
+            explicit ValueProperty(Type type, std::string value);\r
 \r
             /**\r
-                 * This method is for getting Range from Properties.\r
-                 *\r
-                 * @param min - reference to hold Minimum value of Properties.\r
-                 * @param max -  reference to hold Maximum value of Properties.\r
-                 * @param multipleOf -  reference to hold multipleOf value of Properties.\r
-                 */\r
-            inline void getRange(int &min, int &max, int &multipleOf) const\r
-            {\r
-                min = m_min;\r
-                max = m_max;\r
-                multipleOf = m_multipleOf;\r
-            }\r
+             * explicit Constructor of ValueProperty for Type ARRAY.\r
+             *\r
+             * @param type - ValueProperty Type.\r
+             * @param minItems - minimum elements in the Array property.\r
+             * @param maxItems - maximum elements in the Array property.\r
+             * @param unique - unique elements in the Array property.\r
+             * @param additionalItems - additional elements in the Array property.\r
+             */\r
+            explicit ValueProperty(Type type, int minItems, int maxItems, bool unique, bool additionalItems);\r
 \r
             /**\r
-                 * This method is for getting Range from Properties.\r
-                 *\r
-                 * @param min - reference to hold Minimum value of Properties.\r
-                 * @param max -  reference to hold Maximum value of Properties.\r
-                 * @param multipleOf -  reference to hold multipleOf value of Properties.\r
-                 */\r
-            inline void getRangeDouble(double &min, double &max, int &multipleOf) const\r
-            {\r
-                min = m_doubleMin;\r
-                max = m_doubleMax;\r
-                multipleOf = m_multipleOf;\r
-            }\r
-            /**\r
-                 * This method is for setting Minimum to Properties\r
-                 *\r
-                 * @param min - Minimum value of Properties.\r
-                 */\r
-            inline void setMin(const int &min)\r
-            {\r
-                m_min = min;\r
-            }\r
+             * This method is for getting type of ValueProperty.\r
+             *\r
+             * @return Type of ValueProperty\r
+             */\r
+            Type type() const;\r
 \r
             /**\r
-                 * This method is for setting Maximum to Properties\r
-                 *\r
-                 * @param max - Maximum value of Properties.\r
-                 */\r
-            inline void setMax(const int &max)\r
-            {\r
-                m_max = max;\r
-            }\r
+             * This method is for getting minimum value of ValueProperty.\r
+             *\r
+             * @return min value of ValueProperty\r
+             */\r
+            double min() const;\r
 \r
             /**\r
-                 * This method is for setting Minimum to Properties\r
-                 *\r
-                 * @param min - Minimum value of Properties.\r
-                 */\r
-            inline void setMinDouble(const double &min)\r
-            {\r
-                m_doubleMin = min;\r
-            }\r
+             * This method is for getting maximum value of ValueProperty.\r
+             *\r
+             * @return max value of ValueProperty\r
+             */\r
+            double max() const;\r
 \r
             /**\r
-                 * This method is for setting Maximum to Properties\r
-                 *\r
-                 * @param max - Maximum value of Properties.\r
-                 */\r
-            inline void setMaxDouble(const double &max)\r
-            {\r
-                m_doubleMax = max;\r
-            }\r
-            /**\r
-                 * This method is for setting multipleOf to Properties\r
-                 *\r
-                 * @param multipleOf - multipleOf value of Properties.\r
-                 */\r
-            inline void setMultipleOf(const int &multipleOf)\r
-            {\r
-                m_multipleOf = multipleOf;\r
-            }\r
+             * This method is for getting multipleOf value of ValueProperty.\r
+             *\r
+             * @return multipleOf value of ValueProperty\r
+             */\r
+            int multipleOf() const;\r
 \r
             /**\r
-                 * This method is for setting AllowedValues to Properties\r
-                 *\r
-                 * @param values - list of AllowedValues of Properties.\r
-                 */\r
-            template <typename T>\r
-            bool setAllowedValues(const std::vector<T> &values)\r
-            {\r
-                ValueVariant temp = values.at(0);\r
-                if (temp.which() != m_value.which())\r
-                {\r
-                    return false;\r
-                }\r
-\r
-                m_allowedValues.addValues(values);\r
-                return true;\r
-            }\r
+             * This method is for getting pattern value of ValueProperty.\r
+             *\r
+             * @return pattern value of ValueProperty\r
+             */\r
+            std::string pattern() const;\r
 \r
             /**\r
-                 * This method is for getting size of AllowedValues from Properties.\r
-                 *\r
-                 * @return  size of AllowedValues\r
-                 */\r
-            inline int getAllowedValuesSize() const\r
-            {\r
-                return m_allowedValues.size();\r
-            }\r
+             * This method is for getting format value of ValueProperty.\r
+             *\r
+             * @return format value of ValueProperty\r
+             */\r
+            std::string format() const;\r
 \r
             /**\r
-                 * This method is for getting AllowedValues from Properties.\r
-                 *\r
-                 * @return list of AllowedValues of Properties.\r
-                 */\r
-            inline std::vector<ValueVariant> getAllowedValues()\r
-            {\r
-                return m_allowedValues.getValues();\r
-            }\r
+             * This method is for getting valueSet of ValueProperty.\r
+             *\r
+             * @return valueSet of ValueProperty\r
+             */\r
+            int valueSetSize() const;\r
 \r
             /**\r
-                 * This method is for getting AllowedValues as integer from Properties.\r
-                 *\r
-                 * @return list of AllowedValues as integer\r
-                 */\r
-            inline std::vector<int> getAllowedValuesInt()\r
-            {\r
-                return m_allowedValues.getValuesInt();\r
-            }\r
+             * This method is for getting valueSet of ValueProperty.\r
+             *\r
+             * @return valueSet of ValueProperty\r
+             */\r
+            std::vector<ValueVariant> valueSet() const;\r
 \r
             /**\r
-                 * This method is for getting AllowedValues as String from Properties.\r
-                 *\r
-                 * @return list of AllowedValues as String\r
-                 */\r
-            inline std::vector<std::string> getAllowedValuesString()\r
-            {\r
-                return m_allowedValues.getValuesString();\r
-            }\r
+             * This method is for getting valueArray of ValueProperty.\r
+             *\r
+             * @param minItems - reference to get minimum elements in the Array property.\r
+             * @param maxItems - reference to get maximum elements in the Array property.\r
+             * @param unique - reference to get unique elements in the Array property.\r
+             * @param additionalItems - reference to get additional elements in the Array property.\r
+             */\r
+            void valueArray(int &minItems, int &maxItems, bool &unique, bool &additionalItems) const;\r
 \r
-            /**\r
-                 * This method is for getting AllowedValues as Double from Properties.\r
-                 *\r
-                 * @return list of AllowedValues as Double\r
-                 */\r
-            inline std::vector<double> getAllowedValuesDouble()\r
-            {\r
-                return m_allowedValues.getValuesDouble();\r
-            }\r
+        private:\r
+            Type m_type;\r
+            double m_min;\r
+            double m_max;\r
+            int m_multipleOf;\r
+            std::vector<ValueVariant> m_valueSet;\r
+            std::string m_pattern;\r
+            std::string m_format;\r
+            int m_minItems;\r
+            int m_maxItems;\r
+            bool m_unique;\r
+            bool m_additionalItems;\r
+    };\r
 \r
+    /**\r
+     * @class   Properties\r
+     * @brief   This class provides data Model for Json Schema Properties.\r
+     */\r
+    class Properties\r
+    {\r
+        public:\r
             /**\r
-                 * This method is for getting AllowedValues as Bool from Properties.\r
-                 *\r
-                 * @return list of AllowedValues as Bool\r
-                 */\r
-            inline std::vector<bool> getAllowedValuesBool()\r
+             * @class   TypeInfo\r
+             * @brief   This class provides type information of Json Properties.\r
+             */\r
+            class TypeInfo\r
             {\r
-                return m_allowedValues.getValuesBool();\r
-            }\r
+                public:\r
+                    /**\r
+                     * Constructor of TypeInfo.\r
+                     *\r
+                     * @param VariantType - type of property.\r
+                     * @param VariantType - type of parent property.\r
+                     * @param int - depth of property.\r
+                     */\r
+                    TypeInfo(VariantType type = VariantType::UNKNOWN,\r
+                             VariantType baseType = VariantType::UNKNOWN,\r
+                             int depth = 0);\r
+\r
+                    TypeInfo(const TypeInfo &) = default;\r
+\r
+                    TypeInfo &operator=(const TypeInfo &) = default;\r
+\r
+                    TypeInfo(TypeInfo &&) = default;\r
+\r
+                    TypeInfo &operator=(TypeInfo &&) = default;\r
+\r
+                    /**\r
+                     * This method is for getting type of properties.\r
+                     *\r
+                     * @return VariantType of Property\r
+                     */\r
+                    VariantType type() const;\r
+\r
+                    /**\r
+                     * This method is for getting base or parent type of properties.\r
+                     *\r
+                     * @return VariantType of parent Property\r
+                     */\r
+                    VariantType baseType() const;\r
+\r
+                    /**\r
+                     * This method is for getting depth of properties.\r
+                     *\r
+                     * @return depth as int\r
+                     */\r
+                    int depth() const;\r
+\r
+                    /**\r
+                     *  operator for TypeInfo to check equality.\r
+                     *\r
+                     * @param TypeInfo.\r
+                     */\r
+                    bool operator ==(const TypeInfo &) const;\r
+\r
+                    /**\r
+                     *  operator for TypeInfo to check inequality.\r
+                     *\r
+                     * @param TypeInfo.\r
+                     */\r
+                    bool operator !=(const TypeInfo &) const;\r
+\r
+                private:\r
+                    VariantType m_type;\r
+                    VariantType m_baseType;\r
+                    int m_depth;\r
+            };\r
 \r
             /**\r
-                 * This method is for setting Description to Properties\r
-                 *\r
-                 * @param description - Description as string.\r
-                 */\r
-            inline void setDescription(const std::string &description)\r
-            {\r
-                m_description = description;\r
-            }\r
+              * Constructor of Properties.\r
+              *\r
+              * @param name - Properties name as string.\r
+              */\r
+            Properties(const std::string &name) : m_name(name) {}\r
+\r
+            Properties() = default;\r
+\r
+            Properties(const Properties &) = default;\r
+\r
+            Properties &operator=(const Properties &) = default;\r
+\r
+            Properties(Properties &&) = default;\r
+\r
+            Properties &operator=(Properties &&) = default;\r
 \r
             /**\r
-                 * This method is for getting Description from Properties.\r
-                 *\r
-                 * @return Description as string\r
-                 */\r
-            inline std::string getDescription()\r
-            {\r
-                return m_description;\r
-            }\r
+             * This method is for getting TypeInfo of Properties.\r
+             *\r
+             * @return Properties TypeInfo\r
+             */\r
+            TypeInfo getType() const;\r
 \r
             /**\r
-                 * This method is for setting Type to Properties\r
-                 *\r
-                 * @param type - Type as string.\r
-                 */\r
-            void setType(const std::string &type)\r
-            {\r
-                m_type = type;\r
-            }\r
+             * This method is for setting type of Properties.\r
+             *\r
+             * @param type -Propertie's Type\r
+             */\r
+            void setTypeString(const std::string &type);\r
 \r
             /**\r
-                 * This method is for getting Type from Properties.\r
-                 *\r
-                 * @return Type as string\r
-                 */\r
-            std::string getType()\r
-            {\r
-                return m_type;\r
-            }\r
+             * This method is for getting Name from Properties.\r
+             *\r
+             * @return Properties name as string\r
+             */\r
+            std::string getName() const;\r
 \r
             /**\r
-                 * This method is for setting Pattern to Properties\r
-                 *\r
-                 * @param pattern - Pattern as string.\r
-                 */\r
-            void setPattern(const std::string &pattern)\r
-            {\r
-                m_pattern = pattern;\r
-            }\r
+             * This method is for setting name to Properties\r
+             *\r
+             * @param name - Properties name as string.\r
+             */\r
+            void setName(const std::string &name);\r
 \r
+            /**\r
+             * This method is for getting Description from Properties.\r
+             *\r
+             * @return Description as string\r
+             */\r
+            std::string getDescription() const;\r
 \r
             /**\r
-                 * This method is for getting Pattern from Properties.\r
-                 *\r
-                 * @return Pattern as string\r
-                 */\r
-            std::string getPattern()\r
-            {\r
-                return m_pattern;\r
-            }\r
+             * This method is for setting Description to Properties\r
+             *\r
+             * @param description - Description as string.\r
+             */\r
+            void setDescription(const std::string &description);\r
 \r
             /**\r
-                 * This method is for setting Format to Properties\r
-                 *\r
-                 * @param format - Format as string.\r
-                 */\r
-            void setFormat(const std::string &format)\r
+             * This method is for setting Value to Properties.\r
+             *\r
+             * @param value -  Value of Properties\r
+             */\r
+            template <typename T>\r
+            void setValue(const T &value)\r
             {\r
-                m_format = format;\r
+                m_value = std::make_shared<ValueVariant>(value);\r
             }\r
 \r
             /**\r
-                 * This method is for getting Format from Properties.\r
-                 *\r
-                 * @return Format as string\r
-                 */\r
-            std::string getFormat()\r
-            {\r
-                return m_format;\r
-            }\r
+             * This method is for getting Value from Properties.\r
+             *\r
+             * @return Properties Value\r
+             */\r
+            ValueVariant getValue() const;\r
 \r
             /**\r
-                 * This method is for setting Items to Properties\r
-                 *\r
-                 * @param item - pointer to Items\r
-                 */\r
-            void setItem(const ItemsPtr &item)\r
+             * This method is for getting Value from Properties.\r
+             *\r
+             * @return Properties Value\r
+             */\r
+            template <typename T>\r
+            T getValue() const\r
             {\r
-                m_items.push_back(item);\r
+                return boost::get<T>(*(m_value.get()));\r
             }\r
 \r
             /**\r
-                 * This method is for getting Items from Properties.\r
-                 *\r
-                 * @return list of pointer to Items\r
-                 */\r
-            std::vector<ItemsPtr> const &getItems() const\r
-            {\r
-                return m_items;\r
-            }\r
+             * This method is for checking if default Value exists in the Properties.\r
+             *\r
+             * @return true if present and false if not present\r
+             */\r
+            bool isDefaultValue() const { return ((m_value != nullptr) ? true : false); }\r
 \r
             /**\r
-                 * This method is for setting Unique to Properties\r
-                 *\r
-                 * @param value - Unique as bool\r
-                 */\r
-            void setUnique( int value)\r
-            {\r
-                if (value == cJSON_True) m_unique = true;\r
-                else m_unique = false;\r
-            }\r
+             * This method is for getting ValueProperty from Properties.\r
+             *\r
+             * @return vector of pointer to ValueProperty\r
+             */\r
+            std::vector<std::shared_ptr<ValueProperty> > const &getValueProperties() const;\r
 \r
             /**\r
-                 * This method is for getting isUnique from Properties.\r
-                 *\r
-                 * @return isUnique as bool\r
-                 */\r
-            bool getUnique()\r
-            {\r
-                return m_unique;\r
-            }\r
+             * This method is for setting ValueProperty to Properties\r
+             *\r
+             * @param value - pointer to ValueProperty\r
+             */\r
+            void setValueProperty(const std::shared_ptr<ValueProperty> &value);\r
+\r
 \r
             /**\r
-                 * This method is for setting AdditionalItems to Properties\r
-                 *\r
-                 * @param value - AdditionalItems as bool\r
-                 */\r
-            void setAdditionalItems(int value)\r
-            {\r
-                if (value == cJSON_True) m_additionalItems = true;\r
-                else m_additionalItems = false;\r
-            }\r
+             * This method is for getting RequiredValue from Properties.\r
+             *\r
+             * @return list of RequiredValue as string\r
+             */\r
+            std::vector<std::string> const &getRequiredValues() const;\r
 \r
             /**\r
-                 * This method is for getting AdditionalItems from Properties.\r
-                 *\r
-                 * @return AdditionalItems as bool\r
-                 */\r
-            bool getAdditionalItems()\r
-            {\r
-                return m_additionalItems;\r
-            }\r
+             * This method is for setting RequiredValue to Properties\r
+             *\r
+             * @param reqValue - RequiredValue as string.\r
+             */\r
+            void setRequiredValue(const std::string &reqValue);\r
+\r
         private:\r
+            TypeInfo m_type;\r
+            std::string m_typeString;\r
             std::string m_name;\r
-            ValueVariant m_value;\r
-            int m_min;\r
-            int m_max;\r
-            double m_doubleMin;\r
-            double m_doubleMax;\r
-            int m_multipleOf;\r
-            AllowedValues m_allowedValues;\r
-            std::string m_type;\r
-            std::string m_pattern;\r
-            std::string m_format;\r
             std::string m_description;\r
-            bool m_unique;\r
-            bool m_additionalItems;\r
-            std::vector<ItemsPtr > m_items;\r
+            std::shared_ptr<ValueVariant> m_value;\r
+            std::vector<std::shared_ptr<ValueProperty> > m_valueProperty;\r
+            std::vector<std::string> m_required;\r
     };\r
 \r
     /** PropertiesPtr - shared Ptr to Properties.*/\r
     typedef std::shared_ptr<Properties> PropertiesPtr;\r
 \r
+    /** ValuePropertyPtr - shared Ptr to ValueProperty.*/\r
+    typedef std::shared_ptr<ValueProperty> ValuePropertyPtr;\r
+\r
 }\r
 #endif\r
index dd33564..dafba13 100755 (executable)
@@ -31,7 +31,7 @@
 #include <map>\r
 #include <list>\r
 #include <string>\r
-#include "Utils.h"\r
+#include "RamlUtils.h"\r
 \r
 \r
 namespace RAML\r
index 6ee2abb..ff829c5 100755 (executable)
@@ -36,7 +36,7 @@
 #include "RequestResponseBody.h"\r
 #include "UriParameter.h"\r
 #include "Response.h"\r
-#include "Utils.h"\r
+#include "RamlUtils.h"\r
 #include "IncludeResolver.h"\r
 \r
 namespace RAML\r
index f90fdea..855d8f4 100755 (executable)
@@ -48,7 +48,7 @@
 #include "yaml-cpp/yaml.h"\r
 #include "yaml-cpp/exceptions.h"\r
 #include "RamlExceptions.h"\r
-#include "Utils.h"\r
+#include "RamlUtils.h"\r
 #include "cJSON.h"\r
 \r
 \r
index cac949d..1b4d748 100755 (executable)
@@ -33,7 +33,7 @@
 #include "UriParameter.h"\r
 #include "ActionType.h"\r
 #include "Action.h"\r
-#include "Utils.h"\r
+#include "RamlUtils.h"\r
 #include "IncludeResolver.h"\r
 \r
 namespace RAML\r
index 78aaee9..929f915 100755 (executable)
@@ -30,7 +30,7 @@
 #include <map>\r
 #include <list>\r
 #include "FormParameter.h"\r
-#include "Utils.h"\r
+#include "RamlUtils.h"\r
 #include "IncludeResolver.h"\r
 #include "Schema.h"\r
 \r
index 5d3ed62..be41192 100755 (executable)
@@ -32,7 +32,7 @@
 #include <string>\r
 #include "RequestResponseBody.h"\r
 #include "Header.h"\r
-#include "Utils.h"\r
+#include "RamlUtils.h"\r
 #include "IncludeResolver.h"\r
 \r
 namespace RAML\r
index c1c95d3..b50233e 100755 (executable)
@@ -43,61 +43,66 @@ namespace RAML
     {\r
         public:\r
             /**\r
-                 * This method is for getting CJson object of schema.\r
-                 *\r
-                 * @return pointer to cJSON.\r
-                 */\r
+             * This method is for getting CJson object of schema.\r
+             *\r
+             * @return pointer to cJSON.\r
+             */\r
             virtual cJSON *getJson() const;\r
 \r
             /**\r
-                 * This method is for setting schema as CJson object.\r
-                 *\r
-                 * @param cjson - Cjson pointer.\r
-                 */\r
+             * This method is for setting schema as CJson object.\r
+             *\r
+             * @param cjson - Cjson pointer.\r
+             */\r
             virtual void setJson(cJSON *cjson);\r
 \r
             /**\r
-                 * This method is for getting schema as string.\r
-                 *\r
-                 * @return string.\r
-                 */\r
+             * This method is for getting schema as string.\r
+             *\r
+             * @return string.\r
+             */\r
             virtual std::string getSchema() const;\r
 \r
             /**\r
-                  * This method is for setting schema as string.\r
-                  *\r
-                  * @param schema - schema string.\r
-                  */\r
+             * This method is for setting schema as string.\r
+             *\r
+             * @param schema - schema string.\r
+             */\r
             virtual void setSchema(const std::string &schema);\r
 \r
             /**\r
-                 * This method is for getting Properties from JsonSchema.\r
-                 *\r
-                 * @return pointer to JsonSchema.\r
-                 */\r
+             * This method is for getting Properties from JsonSchema.\r
+             *\r
+             * @return pointer to JsonSchema.\r
+             */\r
             virtual JsonSchemaPtr const &getProperties() const;\r
 \r
             /**\r
-                   * Constructor of Schema.\r
-                   *\r
-                   * @param schema - contents of schema to be parsed\r
-                   * @param includeResolver - Reference to IncludeResolver for reading external files\r
-                   *\r
-                   */\r
+             * Constructor of Schema.\r
+             *\r
+             * @param schema - contents of schema to be parsed\r
+             * @param includeResolver - Reference to IncludeResolver for reading external files\r
+             *\r
+             */\r
             Schema(const std::string &schema, const IncludeResolverPtr &includeResolver):\r
                 m_schema(schema) , m_cjson(cJSON_Parse(schema.c_str())),\r
                 m_resProperties(std::make_shared<JsonSchema>(m_cjson, includeResolver) ) ,\r
                 m_includeResolver(includeResolver) {}\r
 \r
             /**\r
-                  * Constructor of Schema.\r
-                  */\r
+             * Constructor of Schema.\r
+             */\r
             Schema(): m_cjson(NULL), m_resProperties(std::make_shared<JsonSchema>()),\r
                 m_includeResolver(NULL) {}\r
 \r
+            Schema(const Schema&) = delete;\r
+            Schema& operator=(const Schema&) = delete;\r
+            Schema(Schema&&) = delete;\r
+            Schema& operator=(Schema&&) = delete;\r
+\r
             /**\r
-                  * Destructor of Schema.\r
-                  */\r
+             * Destructor of Schema.\r
+             */\r
             ~Schema() { cJSON_Delete(m_cjson); }\r
 \r
         private:\r
diff --git a/service/simulator/src/client-controller/attribute_generator.cpp b/service/simulator/src/client-controller/attribute_generator.cpp
deleted file mode 100644 (file)
index 03abd64..0000000
+++ /dev/null
@@ -1,187 +0,0 @@
-/******************************************************************
- *
- * 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 "attribute_generator.h"
-
-AttributeGenerator::AttributeGenerator(const SimulatorResourceModel::Attribute &attribute)
-    :   m_name(attribute.getName()),
-        m_min(INT_MIN),
-        m_max(INT_MAX),
-        m_rangeIndex(-1),
-        m_allowedValueIndex(0),
-        m_hasRange(false),
-        m_hasAllowedValue(false)
-{
-    if (attribute.getValueType() ==
-        SimulatorResourceModel::Attribute::ValueType::INTEGER)
-    {
-        attribute.getRange(m_min, m_max);
-        if (INT_MIN != m_min && INT_MAX != m_max)
-        {
-            m_hasRange = true;
-            m_rangeIndex = m_min;
-        }
-    }
-    else
-    {
-        m_allowedValues = attribute.getAllowedValues();
-        if (0 != m_allowedValues.size())
-        {
-            m_hasAllowedValue = true;
-        }
-    }
-}
-
-bool AttributeGenerator::hasNext()
-{
-    if (m_hasRange && m_rangeIndex <= m_max)
-    {
-        return true;
-    }
-
-    if (m_hasAllowedValue && m_allowedValueIndex < m_allowedValues.size())
-    {
-        return true;
-    }
-
-    return false;
-}
-
-bool AttributeGenerator::next(SimulatorResourceModel::Attribute &attribute)
-{
-    attribute.setName(m_name);
-
-    if (m_hasRange)
-    {
-        attribute.setValue(m_rangeIndex++);
-        return true;
-    }
-    else if (m_hasAllowedValue)
-    {
-        attribute.setValue(m_allowedValues[m_allowedValueIndex++]);
-        return true;
-    }
-
-    return false;
-}
-
-SimulatorResourceModel::Attribute AttributeGenerator::current()
-{
-    SimulatorResourceModel::Attribute attribute;
-
-    attribute.setName(m_name);
-    if (m_hasRange)
-    {
-        attribute.setValue(m_rangeIndex);
-    }
-    else if (m_hasAllowedValue)
-    {
-        attribute.setValue(m_allowedValues[m_allowedValueIndex]);
-    }
-
-    return attribute;
-}
-
-void AttributeGenerator::reset()
-{
-    if (m_hasRange)
-    {
-        m_rangeIndex = m_min;
-    }
-    else if (m_hasAllowedValue)
-    {
-        m_allowedValueIndex = 0;
-    }
-}
-
-AttributeCombinationGen::AttributeCombinationGen(
-        const std::vector<SimulatorResourceModel::Attribute> &attributes)
-{
-    for (auto &attr : attributes)
-    {
-        AttributeGenerator attrGen(attr);
-        m_attrGenList.push_back(attr);
-    }
-
-    m_index = -1;
-}
-
-bool AttributeCombinationGen::next(SimulatorResourceModel &resModel)
-{
-    if (!m_attrGenList.size())
-    {
-        return false;
-    }
-
-    std::lock_guard<std::mutex> lock(m_lock);
-
-    // This block will execute for only first time
-    if (-1 == m_index)
-    {
-        for (int index = 0; index < m_attrGenList.size(); index++)
-        {
-            // Add the attribute on resource model
-            addAttributeToModel(index);
-        }
-
-        m_index = m_attrGenList.size() - 1;
-        resModel = m_resModel;
-        return true;
-    }
-
-    // Get the next attribute from statck top element
-    if (m_attrGenList[m_index].hasNext())
-    {
-        addAttributeToModel(m_index);
-        resModel = m_resModel;
-        return true;
-    }
-    else
-    {
-        for (int index = m_index; index >= 0; index--)
-        {
-            if (!m_attrGenList[index].hasNext())
-            {
-                if (!index)
-                    return false;
-
-                m_attrGenList[index].reset();
-                addAttributeToModel(index);
-            }
-            else
-            {
-                addAttributeToModel(index);
-                break;
-            }
-        }
-
-        resModel = m_resModel;
-        return true;
-    }
-
-    return false;
-}
-
-void AttributeCombinationGen::addAttributeToModel(int index)
-{
-    SimulatorResourceModel::Attribute attribute;
-    m_attrGenList[index].next(attribute);
-    m_resModel.addAttribute(attribute, true);
-}
diff --git a/service/simulator/src/client-controller/attribute_generator.h b/service/simulator/src/client-controller/attribute_generator.h
deleted file mode 100644 (file)
index fab888f..0000000
+++ /dev/null
@@ -1,64 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-#ifndef ATTRIBUTE_GENERATOR_H_
-#define ATTRIBUTE_GENERATOR_H_
-
-#include <map>
-#include <vector>
-#include "simulator_resource_model.h"
-
-class AttributeGenerator
-{
-    public:
-        AttributeGenerator(const SimulatorResourceModel::Attribute &attribute);
-        bool hasNext();
-        bool next(SimulatorResourceModel::Attribute &attribute);
-        SimulatorResourceModel::Attribute current();
-        void reset();
-
-    private:
-        std::string m_name;
-        int m_min;
-        int m_max;
-        int m_rangeIndex;
-        int m_allowedValueIndex;
-        bool m_hasRange;
-        bool m_hasAllowedValue;
-        std::vector<SimulatorResourceModel::Attribute::ValueVariant> m_allowedValues;
-};
-
-class AttributeCombinationGen
-{
-    public:
-        AttributeCombinationGen(const std::vector<SimulatorResourceModel::Attribute> &attributes);
-        bool next(SimulatorResourceModel &resModel);
-
-    private:
-        void addAttributeToModel(int index);
-
-        std::mutex m_lock;
-        std::vector<AttributeGenerator> m_attrGenList;
-        int m_index;
-        SimulatorResourceModel m_resModel;
-};
-
-#endif
-
diff --git a/service/simulator/src/client-controller/auto_request_gen.cpp b/service/simulator/src/client-controller/auto_request_gen.cpp
deleted file mode 100644 (file)
index 2ab450d..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
-/******************************************************************
- *
- * 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 "auto_request_gen.h"
-
-AutoRequestGeneration::AutoRequestGeneration(RequestType type, int id,
-        RequestSenderSP &requestSender, ProgressStateCallback callback)
-    :   m_type(type),
-        m_id(id),
-        m_requestSender(requestSender),
-        m_callback(callback),
-        m_requestsSent(false),
-        m_requestCnt(0),
-        m_responseCnt(0) {}
-
-void AutoRequestGeneration::start()
-{
-    startSending();
-}
-
-void AutoRequestGeneration::stop()
-{
-    stopSending();
-}
diff --git a/service/simulator/src/client-controller/auto_request_gen.h b/service/simulator/src/client-controller/auto_request_gen.h
deleted file mode 100644 (file)
index c296f4e..0000000
+++ /dev/null
@@ -1,51 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-#ifndef AUTO_REQUEST_GEN_H_
-#define AUTO_REQUEST_GEN_H_
-
-#include "request_sender.h"
-
-class AutoRequestGeneration
-{
-    public:
-        typedef std::function<void (int, OperationState)> ProgressStateCallback;
-
-        AutoRequestGeneration(RequestType type, int id,
-                              RequestSenderSP &requestSender, ProgressStateCallback callback);
-        RequestType type() const { return m_type;}
-        int id() const {return m_id;}
-        void start();
-        void stop();
-
-    protected:
-        virtual void startSending() = 0;
-        virtual void stopSending() = 0;
-
-        RequestType m_type;
-        int m_id;
-        RequestSenderSP m_requestSender;
-        ProgressStateCallback m_callback;
-        bool m_requestsSent;
-        int m_requestCnt;
-        int m_responseCnt;
-};
-
-#endif
diff --git a/service/simulator/src/client-controller/auto_request_gen_mngr.cpp b/service/simulator/src/client-controller/auto_request_gen_mngr.cpp
deleted file mode 100644 (file)
index 56adc4a..0000000
+++ /dev/null
@@ -1,225 +0,0 @@
-/******************************************************************
- *
- * 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 "auto_request_gen_mngr.h"
-#include "get_request_generator.h"
-#include "put_request_generator.h"
-#include "post_request_generator.h"
-#include "simulator_exceptions.h"
-#include "logger.h"
-
-#define TAG "AUTO_REQ_GEN_MNGR"
-
-int AutoRequestGenMngr::startOnGET(RequestSenderSP requestSender,
-                                   const std::map<std::string, std::vector<std::string>> &queryParams,
-                                   AutoRequestGeneration::ProgressStateCallback callback)
-{
-    // Input validation
-    if (!requestSender)
-    {
-        throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Invalid request sender given!");
-    }
-
-    if (!callback)
-    {
-        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-    }
-
-    // Check is there auto request generation session already going on for GET requests
-    if (isInProgress(RequestType::RQ_TYPE_GET))
-    {
-        throw OperationInProgressException("Another GET request generation session is already in progress!");
-    }
-
-    // Create request generation session
-    AutoRequestGeneration::ProgressStateCallback localCallback = std::bind(
-                &AutoRequestGenMngr::onProgressChange, this,
-                std::placeholders::_1, std::placeholders::_2, callback);
-
-    std::lock_guard<std::mutex> lock(m_lock);
-    std::shared_ptr<AutoRequestGeneration> requestGen(
-        new GETRequestGenerator(m_id, requestSender, queryParams, localCallback));
-    m_requestGenList[m_id] = requestGen;
-
-    try
-    {
-        requestGen->start();
-    }
-    catch (OperationInProgressException &e)
-    {
-        m_requestGenList.erase(m_requestGenList.find(m_id));
-        throw;
-    }
-
-    return m_id++;
-}
-
-int AutoRequestGenMngr::startOnPUT(RequestSenderSP requestSender,
-                                   const std::map<std::string, std::vector<std::string>> &queryParams,
-                                   SimulatorResourceModelSP resModel,
-                                   AutoRequestGeneration::ProgressStateCallback callback)
-{
-    // Input validation
-    if (!requestSender)
-    {
-        throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Invalid request sender given!");
-    }
-
-    if (!callback)
-    {
-        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-    }
-
-    // Check is there auto request generation session already going on for GET requests
-    if (isInProgress(RequestType::RQ_TYPE_PUT))
-    {
-        throw OperationInProgressException("Another GET request generation session is already in progress!");
-    }
-
-    // Create request generation session
-    AutoRequestGeneration::ProgressStateCallback localCallback = std::bind(
-                &AutoRequestGenMngr::onProgressChange, this,
-                std::placeholders::_1, std::placeholders::_2, callback);
-
-    // Create and make the entry in list
-    std::lock_guard<std::mutex> lock(m_lock);
-    std::shared_ptr<AutoRequestGeneration> requestGen(
-        new PUTRequestGenerator(m_id, requestSender, queryParams, resModel, localCallback));
-    m_requestGenList[m_id] = requestGen;
-
-    try
-    {
-        requestGen->start();
-    }
-    catch (OperationInProgressException &e)
-    {
-        m_requestGenList.erase(m_requestGenList.find(m_id));
-        throw;
-    }
-
-    return m_id++;
-}
-
-int AutoRequestGenMngr::startOnPOST(RequestSenderSP requestSender,
-                                    const std::map<std::string, std::vector<std::string>> &queryParams,
-                                    SimulatorResourceModelSP resModel,
-                                    AutoRequestGeneration::ProgressStateCallback callback)
-{
-    // Input validation
-    if (!requestSender)
-    {
-        throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Invalid request sender given!");
-    }
-
-    if (!callback)
-    {
-        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-    }
-
-    // Check is there auto request generation session already going on for GET requests
-    if (isInProgress(RequestType::RQ_TYPE_POST))
-    {
-        throw OperationInProgressException("Another GET request generation session is already in progress!");
-    }
-
-    // Create request generation session
-    AutoRequestGeneration::ProgressStateCallback localCallback = std::bind(
-                &AutoRequestGenMngr::onProgressChange, this,
-                std::placeholders::_1, std::placeholders::_2, callback);
-
-    // Create and make the entry in list
-    std::lock_guard<std::mutex> lock(m_lock);
-    std::shared_ptr<AutoRequestGeneration> requestGen(
-        new POSTRequestGenerator(m_id, requestSender, queryParams, resModel, localCallback));
-    m_requestGenList[m_id] = requestGen;
-
-    try
-    {
-        requestGen->start();
-    }
-    catch (OperationInProgressException &e)
-    {
-        m_requestGenList.erase(m_requestGenList.find(m_id));
-        throw;
-    }
-
-    return m_id++;
-}
-
-void AutoRequestGenMngr::stop(int id)
-{
-    std::lock_guard<std::mutex> lock(m_lock);
-    if (m_requestGenList.end() != m_requestGenList.find(id))
-    {
-        m_requestGenList[id]->stop();
-        OC_LOG_V(INFO, TAG, "Auto request generation session stopped [%d]", id);
-        return;
-    }
-
-    OC_LOG_V(ERROR, TAG, "Invalid verification id : %d", id);
-}
-
-void AutoRequestGenMngr::onProgressChange(int sessionId, OperationState state,
-        AutoRequestGeneration::ProgressStateCallback clientCallback)
-{
-    if (!isValid(sessionId))
-        return;
-
-    // Remove the request generator from list if it is completed
-    if (state == OP_COMPLETE || state == OP_ABORT)
-    {
-        remove(sessionId);
-    }
-
-    // Delegate notification to app callback
-    clientCallback(sessionId, state);
-}
-
-bool AutoRequestGenMngr::isValid(int id)
-{
-    std::lock_guard<std::mutex> lock(m_lock);
-    if (m_requestGenList.end() != m_requestGenList.find(id))
-    {
-        return true;
-    }
-
-    return false;
-}
-
-bool AutoRequestGenMngr::isInProgress(RequestType type)
-{
-    std::lock_guard<std::mutex> lock(m_lock);
-    for (auto & session : m_requestGenList)
-    {
-        if ((session.second)->type() == type)
-            return true;
-    }
-
-    return false;
-}
-
-void AutoRequestGenMngr::remove(int id)
-{
-    std::lock_guard<std::mutex> lock(m_lock);
-    if (m_requestGenList.end() != m_requestGenList.find(id))
-    {
-        m_requestGenList.erase(m_requestGenList.find(id));
-    }
-}
diff --git a/service/simulator/src/client-controller/auto_request_gen_mngr.h b/service/simulator/src/client-controller/auto_request_gen_mngr.h
deleted file mode 100644 (file)
index ced67a7..0000000
+++ /dev/null
@@ -1,68 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-/**
- * @file auto_request_gen_mngr.h
- *
- * @brief This file provides class for managing auto request generation sessions.
- *
- */
-
-#ifndef AUTO_REQUEST_GEN_MNGR_H_
-#define AUTO_REQUEST_GEN_MNGR_H_
-
-#include "auto_request_gen.h"
-
-class AutoRequestGenMngr
-{
-    public:
-        AutoRequestGenMngr() : m_id(0) {};
-
-        int startOnGET(RequestSenderSP requestSender,
-                       const std::map<std::string, std::vector<std::string>> &queryParams,
-                       AutoRequestGeneration::ProgressStateCallback callback);
-
-        int startOnPUT(RequestSenderSP requestSender,
-                       const std::map<std::string, std::vector<std::string>> &queryParams,
-                       SimulatorResourceModelSP resModel,
-                       AutoRequestGeneration::ProgressStateCallback callback);
-
-        int startOnPOST(RequestSenderSP requestSender,
-                        const std::map<std::string, std::vector<std::string>> &queryParams,
-                        SimulatorResourceModelSP resModel,
-                        AutoRequestGeneration::ProgressStateCallback callback);
-
-        void stop(int id);
-
-    private:
-        void onProgressChange(int sessionId, OperationState state,
-                              AutoRequestGeneration::ProgressStateCallback clientCallback);
-        bool isValid(int id);
-        bool isInProgress(RequestType type);
-        void remove(int id);
-
-        std::mutex m_lock;
-        std::map<int, std::shared_ptr<AutoRequestGeneration>> m_requestGenList;
-        int m_id;
-};
-
-typedef std::shared_ptr<AutoRequestGenMngr> AutoRequestGenMngrSP;
-
-#endif
diff --git a/service/simulator/src/client-controller/get_request_generator.cpp b/service/simulator/src/client-controller/get_request_generator.cpp
deleted file mode 100644 (file)
index 1a6aa17..0000000
+++ /dev/null
@@ -1,118 +0,0 @@
-/******************************************************************
- *
- * 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 "get_request_generator.h"
-#include "simulator_resource_model.h"
-#include "logger.h"
-
-#define TAG "GET_REQUEST_GEN"
-
-GETRequestGenerator::GETRequestGenerator(int id, RequestSenderSP &requestSender,
-        AutoRequestGeneration::ProgressStateCallback callback)
-    :   AutoRequestGeneration(RequestType::RQ_TYPE_GET, id, requestSender, callback),
-        m_status(false),
-        m_stopRequested(false) {}
-
-GETRequestGenerator::GETRequestGenerator(int id, RequestSenderSP &requestSender,
-        const std::map<std::string, std::vector<std::string>> &queryParams,
-        AutoRequestGeneration::ProgressStateCallback callback)
-    :   AutoRequestGeneration(RequestType::RQ_TYPE_GET, id, requestSender, callback),
-        m_queryParamGen(queryParams),
-        m_status(false),
-        m_stopRequested(false) {}
-
-void GETRequestGenerator::startSending()
-{
-    // Check if the operation is already in progress
-    std::lock_guard<std::mutex> lock(m_statusLock);
-    if (m_status)
-    {
-        OC_LOG(ERROR, TAG, "Operation already in progress !");
-        throw OperationInProgressException("Another GET request generation session is already in progress!");
-    }
-
-    // Create thread and start sending requests in dispatched thread
-    m_thread = std::make_shared<std::thread>(&GETRequestGenerator::SendAllRequests, this);
-    m_status = true;
-    m_thread->detach();
-}
-
-void GETRequestGenerator::stopSending()
-{
-    m_stopRequested = true;
-}
-
-void GETRequestGenerator::SendAllRequests()
-{
-    // Notify the progress status
-    OC_LOG(DEBUG, TAG, "Sending OP_START event");
-    m_callback(m_id, OP_START);
-
-    do
-    {
-        if (!m_stopRequested)
-        {
-            // Get the next possible queryParameter
-            std::map<std::string, std::string> queryParam = m_queryParamGen.next();
-
-            // Send the request
-            try
-            {
-                m_requestSender->sendRequest(queryParam, std::bind(&GETRequestGenerator::onResponseReceived, this,
-                                             std::placeholders::_1, std::placeholders::_2), true);
-                m_requestCnt++;
-            }
-            catch (SimulatorException &e)
-            {
-                m_stopRequested = true;
-                return completed();
-            }
-        }
-    }
-    while (m_queryParamGen.hasNext());
-
-    m_requestsSent = true;
-    completed();
-}
-
-void GETRequestGenerator::onResponseReceived(SimulatorResult result,
-        SimulatorResourceModelSP repModel)
-{
-    OC_LOG_V(INFO, TAG, "Response recieved result:%d", result);
-    m_responseCnt++;
-    completed();
-}
-
-void GETRequestGenerator::completed()
-{
-    if (m_requestCnt == m_responseCnt)
-    {
-        if (m_stopRequested)
-        {
-            OC_LOG(DEBUG, TAG, "Sending OP_ABORT event");
-            m_callback(m_id, OP_ABORT);
-        }
-        else
-        {
-            OC_LOG(DEBUG, TAG, "Sending OP_COMPLETE event");
-            m_callback(m_id, OP_COMPLETE);
-        }
-    }
-}
\ No newline at end of file
diff --git a/service/simulator/src/client-controller/get_request_generator.h b/service/simulator/src/client-controller/get_request_generator.h
deleted file mode 100644 (file)
index bb23caa..0000000
+++ /dev/null
@@ -1,53 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-#ifndef GET_REQUEST_GEN_H_
-#define GET_REQUEST_GEN_H_
-
-#include "auto_request_gen.h"
-#include "query_param_generator.h"
-
-class GETRequestGenerator : public AutoRequestGeneration
-{
-    public:
-        GETRequestGenerator(int id, RequestSenderSP &requestSender, ProgressStateCallback callback);
-
-        GETRequestGenerator(int id, RequestSenderSP &requestSender,
-                            const std::map<std::string, std::vector<std::string>> &queryParams,
-                            ProgressStateCallback callback);
-
-        void startSending();
-        void stopSending();
-
-    private:
-        void SendAllRequests();
-        void onResponseReceived(SimulatorResult result, SimulatorResourceModelSP repModel);
-        void completed();
-
-        QPGenerator m_queryParamGen;
-        std::mutex m_statusLock;
-        bool m_status;
-        bool m_stopRequested;
-        std::shared_ptr<std::thread> m_thread;
-};
-
-typedef std::shared_ptr<GETRequestGenerator> GETRequestGeneratorSP;
-
-#endif
diff --git a/service/simulator/src/client-controller/post_request_generator.cpp b/service/simulator/src/client-controller/post_request_generator.cpp
deleted file mode 100644 (file)
index b8c8ebb..0000000
+++ /dev/null
@@ -1,145 +0,0 @@
-/******************************************************************
- *
- * 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 "post_request_generator.h"
-#include "simulator_resource_model.h"
-#include "logger.h"
-
-#define TAG "POST_REQUEST_GEN"
-
-POSTRequestGenerator::POSTRequestGenerator(int id, RequestSenderSP &requestSender,
-        SimulatorResourceModelSP &representation,
-        AutoRequestGeneration::ProgressStateCallback callback)
-    :   AutoRequestGeneration(RequestType::RQ_TYPE_GET, id, requestSender, callback),
-        m_rep(representation),
-        m_status(false),
-        m_stopRequested(false) {}
-
-POSTRequestGenerator::POSTRequestGenerator(int id, RequestSenderSP &requestSender,
-        const std::map<std::string, std::vector<std::string>> &queryParams,
-        SimulatorResourceModelSP &representation,
-        AutoRequestGeneration::ProgressStateCallback callback)
-    :   AutoRequestGeneration(RequestType::RQ_TYPE_GET, id, requestSender, callback),
-        m_queryParamGen(queryParams),
-        m_rep(representation),
-        m_status(false),
-        m_stopRequested(false) {}
-
-void POSTRequestGenerator::startSending()
-{
-    // Check the representation
-    if (!m_rep)
-    {
-        OC_LOG(ERROR, TAG, "Invalid Representation given!");
-        throw SimulatorException(SIMULATOR_ERROR, "Invalid representation detected!");
-    }
-
-    // Check if the operation is already in progress
-    std::lock_guard<std::mutex> lock(m_statusLock);
-    if (m_status)
-    {
-        OC_LOG(ERROR, TAG, "Operation already in progress !");
-        throw OperationInProgressException("Another POST request generation session is already in progress!");
-    }
-
-    // Create thread and start sending requests in dispatched thread
-    m_thread = std::make_shared<std::thread>(&POSTRequestGenerator::SendAllRequests, this);
-    m_status = true;
-    m_thread->detach();
-}
-
-void POSTRequestGenerator::stopSending()
-{
-    m_stopRequested = true;
-}
-
-void POSTRequestGenerator::SendAllRequests()
-{
-    // Notify the progress status
-    OC_LOG(DEBUG, TAG, "Sending OP_START event");
-    m_callback(m_id, OP_START);
-
-    // Create attribute generator for value manipulation
-    std::vector<AttributeGenerator> attributeGenList;
-    for (auto &attributeElement : m_rep->getAttributes())
-        attributeGenList.push_back(AttributeGenerator(attributeElement.second));
-
-    if (!attributeGenList.size())
-    {
-        OC_LOG(ERROR, TAG, "Zero attribute found from resource model!");
-        return;
-    }
-
-    do
-    {
-        if (!m_stopRequested)
-        {
-            // Get the next possible queryParameter
-            std::map<std::string, std::string> queryParam = m_queryParamGen.next();
-
-            for (auto & attributeGen : attributeGenList)
-            {
-                while (attributeGen.hasNext())
-                {
-                    SimulatorResourceModelSP repModel(new SimulatorResourceModel);
-                    SimulatorResourceModel::Attribute attribute;
-                    if (true == attributeGen.next(attribute))
-                        repModel->addAttribute(attribute);
-
-                    // Send the request
-                    m_requestSender->sendRequest(queryParam, repModel,
-                            std::bind(&POSTRequestGenerator::onResponseReceived,
-                            this, std::placeholders::_1, std::placeholders::_2), true);
-
-                    m_requestCnt++;
-                }
-            }
-        }
-    }
-    while (m_queryParamGen.hasNext());
-
-    m_requestsSent = true;
-    completed();
-}
-
-void POSTRequestGenerator::onResponseReceived(SimulatorResult result,
-        SimulatorResourceModelSP repModel)
-{
-    OC_LOG_V(INFO, TAG, "Response recieved result:%d", result);
-    m_responseCnt++;
-    completed();
-}
-
-void POSTRequestGenerator::completed()
-{
-    if (m_requestCnt == m_responseCnt)
-    {
-        if (m_stopRequested)
-        {
-            OC_LOG(DEBUG, TAG, "Sending OP_ABORT event");
-            m_callback(m_id, OP_ABORT);
-        }
-        else
-        {
-            OC_LOG(DEBUG, TAG, "Sending OP_COMPLETE event");
-            m_callback(m_id, OP_COMPLETE);
-        }
-    }
-}
\ No newline at end of file
diff --git a/service/simulator/src/client-controller/post_request_generator.h b/service/simulator/src/client-controller/post_request_generator.h
deleted file mode 100644 (file)
index ddfbac5..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-#ifndef POST_REQUEST_GEN_H_
-#define POST_REQUEST_GEN_H_
-
-#include "auto_request_gen.h"
-#include "query_param_generator.h"
-#include "attribute_generator.h"
-
-class POSTRequestGenerator : public AutoRequestGeneration
-{
-    public:
-        POSTRequestGenerator(int id, RequestSenderSP &requestSender,
-                             SimulatorResourceModelSP &representation,
-                             ProgressStateCallback callback);
-
-        POSTRequestGenerator(int id, RequestSenderSP &requestSender,
-                             const std::map<std::string, std::vector<std::string>> &queryParams,
-                             SimulatorResourceModelSP &representation,
-                             ProgressStateCallback callback);
-
-        void startSending();
-        void stopSending();
-
-    private:
-        void SendAllRequests();
-        void onResponseReceived(SimulatorResult result, SimulatorResourceModelSP repModel);
-        void completed();
-
-        QPGenerator m_queryParamGen;
-        SimulatorResourceModelSP m_rep;
-        std::mutex m_statusLock;
-        bool m_status;
-        bool m_stopRequested;
-        std::shared_ptr<std::thread> m_thread;
-};
-
-typedef std::shared_ptr<POSTRequestGenerator> POSTRequestGeneratorSP;
-
-#endif
-
-
diff --git a/service/simulator/src/client-controller/put_request_generator.cpp b/service/simulator/src/client-controller/put_request_generator.cpp
deleted file mode 100644 (file)
index 56bee77..0000000
+++ /dev/null
@@ -1,147 +0,0 @@
-/******************************************************************
- *
- * 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 "put_request_generator.h"
-#include "simulator_resource_model.h"
-#include "logger.h"
-
-#define TAG "PUT_REQUEST_GEN"
-
-PUTRequestGenerator::PUTRequestGenerator(int id, RequestSenderSP &requestSender,
-        SimulatorResourceModelSP &representation,
-        AutoRequestGeneration::ProgressStateCallback callback)
-    :   AutoRequestGeneration(RequestType::RQ_TYPE_GET, id, requestSender, callback),
-        m_rep(representation),
-        m_status(false),
-        m_stopRequested(false) {}
-
-PUTRequestGenerator::PUTRequestGenerator(int id, RequestSenderSP &requestSender,
-        const std::map<std::string, std::vector<std::string>> &queryParams,
-        SimulatorResourceModelSP &representation,
-        AutoRequestGeneration::ProgressStateCallback callback)
-    :   AutoRequestGeneration(RequestType::RQ_TYPE_GET, id, requestSender, callback),
-        m_queryParamGen(queryParams),
-        m_rep(representation),
-        m_status(false),
-        m_stopRequested(false) {}
-
-void PUTRequestGenerator::startSending()
-{
-    // Check the representation
-    if (!m_rep)
-    {
-        OC_LOG(ERROR, TAG, "Invalid Representation given!");
-        throw SimulatorException(SIMULATOR_ERROR, "Invalid representation detected!");
-    }
-
-    // Check if the operation is already in progress
-    std::lock_guard<std::mutex> lock(m_statusLock);
-    if (m_status)
-    {
-        OC_LOG(ERROR, TAG, "Operation already in progress !");
-        throw OperationInProgressException("Another PUT request generation session is already in progress!");
-    }
-
-    // Create thread and start sending requests in dispatched thread
-    m_thread = std::make_shared<std::thread>(&PUTRequestGenerator::SendAllRequests, this);
-    m_status = true;
-    m_thread->detach();
-}
-
-void PUTRequestGenerator::stopSending()
-{
-    m_stopRequested = true;
-}
-
-void PUTRequestGenerator::SendAllRequests()
-{
-    OC_LOG(DEBUG, TAG, "Sending OP_START event");
-    m_callback(m_id, OP_START);
-
-    // Create attribute combination generator for generating resource model
-    // with different attribute values
-    std::vector<SimulatorResourceModel::Attribute> attributes;
-    for (auto &attributeElement : m_rep->getAttributes())
-    {
-        attributes.push_back(attributeElement.second);
-    }
-
-    if (!attributes.size())
-    {
-        OC_LOG(ERROR, TAG, "Zero attribute found from resource model!");
-        return;
-    }
-
-    do
-    {
-        if (m_stopRequested)
-        {
-            break;
-        }
-
-        // Get the next possible queryParameter
-        std::map<std::string, std::string> queryParam = m_queryParamGen.next();
-
-        AttributeCombinationGen attrCombGen(attributes);
-
-        // Get the new model from attribute combination generator
-        SimulatorResourceModel resModel;
-        while (!m_stopRequested && attrCombGen.next(resModel))
-        {
-            SimulatorResourceModelSP repModel(new SimulatorResourceModel(resModel));
-
-            // Send the request
-            m_requestSender->sendRequest(queryParam, repModel,
-                    std::bind(&PUTRequestGenerator::onResponseReceived, this,
-                    std::placeholders::_1, std::placeholders::_2), true);
-
-            m_requestCnt++;
-        }
-    }
-    while (m_queryParamGen.hasNext());
-
-    m_requestsSent = true;
-    completed();
-}
-
-void PUTRequestGenerator::onResponseReceived(SimulatorResult result,
-        SimulatorResourceModelSP repModel)
-{
-    OC_LOG_V(INFO, TAG, "Response recieved result:%d", result);
-    m_responseCnt++;
-    completed();
-}
-
-void PUTRequestGenerator::completed()
-{
-    if (m_requestCnt == m_responseCnt)
-    {
-        if (m_stopRequested)
-        {
-            OC_LOG(DEBUG, TAG, "Sending OP_ABORT event");
-            m_callback(m_id, OP_ABORT);
-        }
-        else
-        {
-            OC_LOG(DEBUG, TAG, "Sending OP_COMPLETE event");
-            m_callback(m_id, OP_COMPLETE);
-        }
-    }
-}
\ No newline at end of file
diff --git a/service/simulator/src/client-controller/put_request_generator.h b/service/simulator/src/client-controller/put_request_generator.h
deleted file mode 100644 (file)
index 471af60..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-#ifndef PUT_REQUEST_GEN_H_
-#define PUT_REQUEST_GEN_H_
-
-#include "auto_request_gen.h"
-#include "query_param_generator.h"
-#include "attribute_generator.h"
-
-class PUTRequestGenerator : public AutoRequestGeneration
-{
-    public:
-        PUTRequestGenerator(int id, RequestSenderSP &requestSender,
-                            SimulatorResourceModelSP &representation,
-                            ProgressStateCallback callback);
-
-        PUTRequestGenerator(int id, RequestSenderSP &requestSender,
-                            const std::map<std::string, std::vector<std::string>> &queryParams,
-                            SimulatorResourceModelSP &representation,
-                            ProgressStateCallback callback);
-
-        void startSending();
-        void stopSending();
-
-    private:
-        void SendAllRequests();
-        void onResponseReceived(SimulatorResult result, SimulatorResourceModelSP repModel);
-        void completed();
-
-        QPGenerator m_queryParamGen;
-        SimulatorResourceModelSP m_rep;
-        std::mutex m_statusLock;
-        bool m_status;
-        bool m_stopRequested;
-        std::shared_ptr<std::thread> m_thread;
-};
-
-typedef std::shared_ptr<PUTRequestGenerator> PUTRequestGeneratorSP;
-
-#endif
-
-
diff --git a/service/simulator/src/client-controller/request_sender.cpp b/service/simulator/src/client-controller/request_sender.cpp
deleted file mode 100644 (file)
index 4e5ba75..0000000
+++ /dev/null
@@ -1,151 +0,0 @@
-/******************************************************************
- *
- * 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 "request_sender.h"
-#include "simulator_logger.h"
-#include "simulator_utils.h"
-#include "logger.h"
-
-#define TAG "GET_REQUEST_SNDR"
-
-RequestSender::RequestSender(RequestType type, std::shared_ptr<OC::OCResource> &ocResource)
-    :   m_type(type), m_ocResource(ocResource) {}
-
-void RequestSender::sendRequest(const std::map<std::string, std::string> &queryParam,
-                                ResponseCallback responseCb, bool verifyResponse)
-{
-    sendRequest(std::string(), queryParam, nullptr, responseCb, verifyResponse);
-}
-
-void RequestSender::sendRequest(const std::string &interfaceType,
-                                const std::map<std::string, std::string> &queryParam,
-                                ResponseCallback responseCb, bool verifyResponse)
-{
-    sendRequest(interfaceType, queryParam, nullptr, responseCb, verifyResponse);
-}
-
-void RequestSender::sendRequest(const std::map<std::string, std::string> &queryParam,
-                                SimulatorResourceModelSP repModel,
-                                ResponseCallback responseCb, bool verifyResponse)
-{
-    sendRequest(std::string(), queryParam, repModel, responseCb, verifyResponse);
-}
-
-void RequestSender::sendRequest(const std::string &interfaceType,
-                                const std::map<std::string, std::string> &queryParam,
-                                SimulatorResourceModelSP repModel,
-                                ResponseCallback responseCb, bool verifyResponse)
-{
-    // Add query paramter "if" if interfaceType is not empty
-    OC::QueryParamsMap queryParamCpy(queryParam);
-    if (!interfaceType.empty())
-        queryParamCpy["if"] = interfaceType;
-
-    // Add the request into request list
-    RequestDetailSP requestDetail(new RequestDetail);
-    requestDetail->type = m_type;
-    requestDetail->queryParam = queryParamCpy;
-    requestDetail->body = repModel;
-    requestDetail->verifyResponse = verifyResponse;
-    requestDetail->responseCb = responseCb;
-
-    int requestId = m_requestList.add(requestDetail);
-
-    OCStackResult ocResult = send(queryParamCpy, repModel, std::bind(
-                                      &RequestSender::onResponseReceived, this,
-                                      std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, requestId));
-    if (OC_STACK_OK != ocResult)
-    {
-        OC_LOG_V(ERROR, TAG, "Sending request failed [errorcode: %d]", ocResult);
-        m_requestList.remove(requestId);
-        throw SimulatorException(static_cast<SimulatorResult>(ocResult), "Failed to send request!");
-    }
-}
-
-void RequestSender::setRequestModel(const RequestModelSP &requestModel)
-{
-    m_requestModel = requestModel;
-}
-
-void RequestSender::onResponseReceived(const OC::HeaderOptions &headerOptions,
-                                       const OC::OCRepresentation &rep, const int errorCode, int requestId)
-{
-    SIM_LOG(ILogger::INFO, "Response recieved..." << "\n" << getPayloadString(rep));
-
-    // Ignore the response recieved for invalid requests
-    RequestDetailSP request = m_requestList.remove(requestId);
-    if (!request)
-    {
-        return;
-    }
-
-    // Validate the response as per the schema given by RAML
-    ValidationStatus validationStatus {false, SIMULATOR_ERROR};
-    if (request->verifyResponse && m_requestModel
-        && !errorCode) // TODO: Validate responses other than "200"
-    {
-        validationStatus.errorCode = m_requestModel->validateResponse(200, rep);
-        validationStatus.isVerified = true;
-    }
-
-    SimulatorResourceModelSP repModel = SimulatorResourceModel::create(rep);
-    request->responseCb(static_cast<SimulatorResult>(errorCode), repModel);
-}
-
-GETRequestSender::GETRequestSender(std::shared_ptr<OC::OCResource> &ocResource)
-    :   RequestSender(RequestType::RQ_TYPE_GET, ocResource) {}
-
-OCStackResult GETRequestSender::send(OC::QueryParamsMap &queryParams,
-                                     SimulatorResourceModelSP &repModel, OC::GetCallback callback)
-{
-    SIM_LOG(ILogger::INFO, "Sending GET request..." << "\n" << getRequestString(queryParams));
-
-    return m_ocResource->get(queryParams, callback);
-}
-
-PUTRequestSender::PUTRequestSender(std::shared_ptr<OC::OCResource> &ocResource)
-    :   RequestSender(RequestType::RQ_TYPE_PUT, ocResource) {}
-
-OCStackResult PUTRequestSender::send(OC::QueryParamsMap &queryParams,
-                                     SimulatorResourceModelSP &repModel, OC::GetCallback callback)
-{
-    OC::OCRepresentation ocRep;
-    if (repModel)
-    {
-        ocRep = repModel->getOCRepresentation();
-    }
-
-    SIM_LOG(ILogger::INFO, "Sending PUT request..." << "\n" << getRequestString(queryParams, ocRep));
-    return m_ocResource->put(ocRep, queryParams, callback);
-}
-
-POSTRequestSender::POSTRequestSender(std::shared_ptr<OC::OCResource> &ocResource)
-    :   RequestSender(RequestType::RQ_TYPE_POST, ocResource) {}
-
-OCStackResult POSTRequestSender::send(OC::QueryParamsMap &queryParams,
-                                      SimulatorResourceModelSP &repModel, OC::GetCallback callback)
-{
-    OC::OCRepresentation ocRep;
-    if (repModel)
-        ocRep = repModel->getOCRepresentation();
-
-    SIM_LOG(ILogger::INFO, "Sending POST request..." << "\n" << getRequestString(queryParams, ocRep));
-    return m_ocResource->post(ocRep, queryParams, callback);
-}
diff --git a/service/simulator/src/client-controller/request_sender.h b/service/simulator/src/client-controller/request_sender.h
deleted file mode 100644 (file)
index 46457e9..0000000
+++ /dev/null
@@ -1,113 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-#ifndef REQUEST_SENDER_H_
-#define REQUEST_SENDER_H_
-
-#include "request_list.h"
-#include "simulator_resource_model.h"
-#include "request_model.h"
-#include "simulator_exceptions.h"
-#include "simulator_error_codes.h"
-
-struct RequestDetail;
-class RequestSender
-{
-    public:
-        typedef std::function<void (SimulatorResult, SimulatorResourceModelSP)> ResponseCallback;
-
-        RequestSender(RequestType type, std::shared_ptr<OC::OCResource> &ocResource);
-        virtual ~RequestSender() {}
-
-        void sendRequest(const std::map<std::string, std::string> &queryParam,
-                         ResponseCallback responseCb, bool verifyResponse = false);
-
-        void sendRequest(const std::string &interfaceType,
-                         const std::map<std::string, std::string> &queryParam,
-                         ResponseCallback responseCb, bool verifyResponse = false);
-
-        void sendRequest(const std::map<std::string, std::string> &queryParam,
-                         SimulatorResourceModelSP repModel,
-                         ResponseCallback responseCb, bool verifyResponse = false);
-
-        void sendRequest(const std::string &interfaceType,
-                         const std::map<std::string, std::string> &queryParam,
-                         SimulatorResourceModelSP repModel,
-                         ResponseCallback responseCb, bool verifyResponse = false);
-
-        void setRequestModel(const RequestModelSP &requestModel);
-
-    protected:
-        virtual OCStackResult send(OC::QueryParamsMap &queryParams,
-                                   SimulatorResourceModelSP &repModel, OC::GetCallback callback) = 0;
-
-        void onResponseReceived(const OC::HeaderOptions &headerOptions,
-                                const OC::OCRepresentation &rep, const int errorCode, int requestId);
-
-        RequestType m_type;
-        RequestList<std::shared_ptr<RequestDetail>> m_requestList;
-        RequestModelSP m_requestModel;
-        std::shared_ptr<OC::OCResource> m_ocResource;
-};
-
-struct RequestDetail
-{
-    RequestType type;
-    std::map<std::string, std::string> queryParam;
-    SimulatorResourceModelSP body;
-    bool verifyResponse;
-    RequestSender::ResponseCallback responseCb;
-};
-
-typedef std::shared_ptr<RequestDetail> RequestDetailSP;
-
-class GETRequestSender : public RequestSender
-{
-    public:
-        GETRequestSender(std::shared_ptr<OC::OCResource> &ocResource);
-
-        OCStackResult send(OC::QueryParamsMap &queryParams,
-                           SimulatorResourceModelSP &repModel, OC::GetCallback callback);
-};
-
-class PUTRequestSender : public RequestSender
-{
-    public:
-        PUTRequestSender(std::shared_ptr<OC::OCResource> &ocResource);
-
-        OCStackResult send(OC::QueryParamsMap &queryParams,
-                           SimulatorResourceModelSP &repModel, OC::GetCallback callback);
-};
-
-class POSTRequestSender : public RequestSender
-{
-    public:
-        POSTRequestSender(std::shared_ptr<OC::OCResource> &ocResource);
-
-        OCStackResult send(OC::QueryParamsMap &queryParams,
-                           SimulatorResourceModelSP &repModel, OC::GetCallback callback);
-};
-
-typedef std::shared_ptr<RequestSender> RequestSenderSP;
-typedef std::shared_ptr<GETRequestSender> GETRequestSenderSP;
-typedef std::shared_ptr<PUTRequestSender> PUTRequestSenderSP;
-typedef std::shared_ptr<POSTRequestSender> POSTRequestSenderSP;
-
-#endif
diff --git a/service/simulator/src/client-controller/simulator_client.cpp b/service/simulator/src/client-controller/simulator_client.cpp
deleted file mode 100644 (file)
index 71645c9..0000000
+++ /dev/null
@@ -1,93 +0,0 @@
-/******************************************************************
- *
- * 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 "simulator_client.h"
-#include "simulator_remote_resource_impl.h"
-#include "simulator_logger.h"
-#include "simulator_utils.h"
-#include "logger.h"
-
-#define TAG "SIMULATOR_CLIENT"
-
-SimulatorClient *SimulatorClient::getInstance()
-{
-    static SimulatorClient s_instance;
-    return &s_instance;
-}
-
-void SimulatorClient::findResources(ResourceFindCallback callback)
-{
-    if (!callback)
-        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-
-    typedef OCStackResult (*FindResource)(const std::string &, const std::string &,
-                                          OCConnectivityType, OC::FindCallback);
-
-    invokeocplatform(static_cast<FindResource>(OC::OCPlatform::findResource), "",
-                     OC_MULTICAST_DISCOVERY_URI,
-                     CT_DEFAULT,
-                     static_cast<OC::FindCallback>(std::bind(&SimulatorClient::onResourceFound, this,
-                             std::placeholders::_1, callback)));
-}
-
-void SimulatorClient::findResources(const std::string &resourceType,
-                                    ResourceFindCallback callback)
-{
-    if (resourceType.empty())
-        throw InvalidArgsException(SIMULATOR_INVALID_TYPE, "resource type is empty!");
-
-    if (!callback)
-        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-
-    std::ostringstream query;
-    query << OC_MULTICAST_DISCOVERY_URI << "?rt=" << resourceType;
-
-    typedef OCStackResult (*FindResource)(const std::string &, const std::string &,
-                                          OCConnectivityType, OC::FindCallback);
-
-    invokeocplatform(static_cast<FindResource>(OC::OCPlatform::findResource), "", query.str(),
-                     CT_DEFAULT,
-                     static_cast<OC::FindCallback>(std::bind(&SimulatorClient::onResourceFound,
-                             this, std::placeholders::_1, callback)));
-}
-
-void SimulatorClient::onResourceFound(std::shared_ptr<OC::OCResource> ocResource,
-                                      ResourceFindCallback callback)
-{
-    if (!ocResource)
-    {
-        OC_LOG(ERROR, TAG, "Invalid OCResource !");
-        return;
-    }
-
-    // Construct SimulatorRemoteResource
-    SimulatorRemoteResourceSP simulatorResource =
-        std::make_shared<SimulatorRemoteResourceImpl>(ocResource);
-    if (!simulatorResource)
-    {
-        OC_LOG(ERROR, TAG, "Failed to create simulator remote resource !");
-        return;
-    }
-
-    OC_LOG(DEBUG, TAG, "Invoking resource found client callback !");
-    callback(simulatorResource);
-}
-
-
diff --git a/service/simulator/src/client-controller/simulator_client.h b/service/simulator/src/client-controller/simulator_client.h
deleted file mode 100644 (file)
index ed669b3..0000000
+++ /dev/null
@@ -1,87 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-/**
- * @file simulator_client.h
- *
- * @brief This file provides a class for realizing simulator client functionality.
- *
- */
-
-#ifndef SIMULATOR_CLIENT_H_
-#define SIMULATOR_CLIENT_H_
-
-#include "simulator_client_types.h"
-#include "simulator_remote_resource.h"
-#include "simulator_exceptions.h"
-
-/**
- * @class   SimulatorClient
- * @brief   This class provides a set of functions for discovering the resources over the network.
- */
-class SimulatorClient
-{
-    public:
-
-        /**
-         * API for getting singleton instance of SimulatorClient class.
-         *
-         * @return Singleton instance of SimulatorClient class.
-         *
-         */
-        static SimulatorClient *getInstance(void);
-
-        /**
-         * API for discovering all type of resources.
-         * Discovered resources will be notified through the callback set using @callback parameter.
-         *
-         * @param callback - Method of type @ResourceFindCallback through which discoverd resources
-         *                                   will be notified.
-         *
-         * NOTE: API throws @InvalidArgsException and @SimulatorException.
-         */
-        void findResources(ResourceFindCallback callback);
-
-        /**
-         * API for discovering resources of a particular resource type.
-         * Discovered resources will be notified through the callback set using @callback parameter.
-         *
-         * @param resourceType - Type of resource to be searched for
-         * @param callback - Method of type @ResourceFindCallback through which discoverd resources
-         *                                   will be notified.
-         *
-         * NOTE: API throws @InvalidArgsException and @SimulatorException.
-         */
-        void findResources(const std::string &resourceType, ResourceFindCallback callback);
-
-    private:
-        SimulatorClient() = default;
-        ~SimulatorClient() = default;
-        SimulatorClient(const SimulatorClient &) = delete;
-        SimulatorClient &operator=(const SimulatorClient &) = delete;
-        SimulatorClient(const SimulatorClient &&) = delete;
-        SimulatorClient &operator=(const SimulatorClient && ) = delete;
-
-        void onResourceFound(std::shared_ptr<OC::OCResource> resource,
-                             ResourceFindCallback callback);
-};
-
-#endif
-
diff --git a/service/simulator/src/client-controller/simulator_remote_resource_impl.cpp b/service/simulator/src/client-controller/simulator_remote_resource_impl.cpp
deleted file mode 100644 (file)
index 178dccb..0000000
+++ /dev/null
@@ -1,426 +0,0 @@
-/******************************************************************
- *
- * 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 "simulator_remote_resource_impl.h"
-#include "request_model_builder.h"
-#include "simulator_exceptions.h"
-#include "logger.h"
-
-#define TAG "SIMULATOR_REMOTE_RESOURCE"
-
-SimulatorRemoteResourceImpl::SimulatorRemoteResourceImpl(std::shared_ptr<OC::OCResource>
-        &ocResource)
-    :   m_observeState(false),
-        m_getRequestSender(new GETRequestSender(ocResource)),
-        m_putRequestSender(new PUTRequestSender(ocResource)),
-        m_postRequestSender(new POSTRequestSender(ocResource)),
-        m_autoRequestGenMngr(nullptr),
-        m_ocResource(ocResource)
-{
-    m_id = m_ocResource->sid().append(m_ocResource->uri());
-}
-
-std::string SimulatorRemoteResourceImpl::getURI() const
-{
-    return m_ocResource->uri();
-}
-
-std::string SimulatorRemoteResourceImpl::getHost() const
-{
-    return m_ocResource->host();
-}
-
-std::string SimulatorRemoteResourceImpl::getID() const
-{
-    return m_id;
-}
-
-SimulatorConnectivityType SimulatorRemoteResourceImpl::getConnectivityType() const
-{
-    return convertConnectivityType(m_ocResource->connectivityType());
-}
-
-std::vector < std::string > SimulatorRemoteResourceImpl::getResourceTypes() const
-{
-    return m_ocResource->getResourceTypes();
-}
-
-std::vector < std::string > SimulatorRemoteResourceImpl::getResourceInterfaces() const
-{
-    return m_ocResource->getResourceInterfaces();
-}
-
-bool SimulatorRemoteResourceImpl::isObservable() const
-{
-    return m_ocResource->isObservable();
-}
-
-void SimulatorRemoteResourceImpl::observe(ObserveType type,
-        ObserveNotificationCallback callback)
-{
-    if (!callback)
-    {
-        OC_LOG(ERROR, TAG, "Invalid callback!");
-        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-    }
-
-    std::lock_guard<std::mutex> lock(m_observeMutex);
-    if (m_observeState)
-    {
-        OC_LOG(WARNING, TAG, "Resource already in observe state !");
-        throw SimulatorException(SIMULATOR_ERROR, "Resource is already being observed!");
-    }
-
-    OC::ObserveCallback observeCallback = [this, callback](const OC::HeaderOptions & headerOptions,
-                                          const OC::OCRepresentation & rep, const int errorCode,
-                                          const int sequenceNum)
-    {
-        // Convert OCRepresentation to SimulatorResourceModel
-        SimulatorResourceModelSP repModel = SimulatorResourceModel::create(rep);
-        callback(m_id, static_cast<SimulatorResult>(errorCode), repModel, sequenceNum);
-    };
-
-    OC::ObserveType observeType = OC::ObserveType::Observe;
-    if (type == ObserveType::OBSERVE_ALL)
-    {
-        observeType = OC::ObserveType::ObserveAll;
-    }
-
-    try
-    {
-        OCStackResult ocResult = m_ocResource->observe(observeType, OC::QueryParamsMap(), observeCallback);
-        if (OC_STACK_OK != ocResult)
-        {
-            throw SimulatorException(static_cast<SimulatorResult>(ocResult), OC::OCException::reason(ocResult));
-        }
-    }
-    catch (OC::OCException &e)
-    {
-        throw SimulatorException(static_cast<SimulatorResult>(e.code()), e.reason());
-    }
-
-    m_observeState = true;
-}
-
-void SimulatorRemoteResourceImpl::cancelObserve()
-{
-    try
-    {
-        OCStackResult ocResult = m_ocResource->cancelObserve(OC::QualityOfService::HighQos);
-        if (OC_STACK_OK != ocResult)
-        {
-            throw SimulatorException(static_cast<SimulatorResult>(ocResult), OC::OCException::reason(ocResult));
-        }
-    }
-    catch (OC::OCException &e)
-    {
-        throw SimulatorException(static_cast<SimulatorResult>(e.code()), e.reason());
-    }
-
-    std::lock_guard<std::mutex> lock(m_observeMutex);
-    m_observeState = false;
-}
-
-void SimulatorRemoteResourceImpl::get(const std::string &interfaceType,
-                                      const std::map<std::string, std::string> &queryParams,
-                                      ResponseCallback callback)
-{
-    if (!callback)
-    {
-        OC_LOG(ERROR, TAG, "Invalid callback!");
-        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-    }
-
-    if (!m_getRequestSender)
-    {
-        OC_LOG(ERROR, TAG, "Invalid GET request sender!");
-        throw NoSupportException("Can not send GET request on this resource!");
-    }
-
-    m_getRequestSender->sendRequest(interfaceType, queryParams,
-                                    nullptr, std::bind(
-                                        &SimulatorRemoteResourceImpl::onResponseReceived,
-                                        this, std::placeholders::_1, std::placeholders::_2, callback));
-}
-
-void SimulatorRemoteResourceImpl::get(const std::map<std::string, std::string> &queryParams,
-                                      ResponseCallback callback)
-{
-    if (!callback)
-    {
-        OC_LOG(ERROR, TAG, "Invalid callback!");
-        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-    }
-
-    if (!m_getRequestSender)
-    {
-        OC_LOG(ERROR, TAG, "Invalid GET request sender !");
-        throw NoSupportException("Can not send GET request on this resource!");
-    }
-
-    m_getRequestSender->sendRequest(std::string(), queryParams,
-                                    nullptr, std::bind(
-                                        &SimulatorRemoteResourceImpl::onResponseReceived,
-                                        this, std::placeholders::_1, std::placeholders::_2, callback));
-}
-
-void SimulatorRemoteResourceImpl::put(const std::string &interfaceType,
-                                      const std::map<std::string, std::string> &queryParams,
-                                      SimulatorResourceModelSP representation,
-                                      ResponseCallback callback)
-{
-    if (!callback)
-    {
-        OC_LOG(ERROR, TAG, "Invalid callback!");
-        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-    }
-
-    if (!m_putRequestSender)
-    {
-        OC_LOG(ERROR, TAG, "Invalid PUT request sender !");
-        throw NoSupportException("Can not send PUT request on this resource!");
-    }
-
-    m_putRequestSender->sendRequest(interfaceType, queryParams,
-                                    representation, std::bind(
-                                        &SimulatorRemoteResourceImpl::onResponseReceived,
-                                        this, std::placeholders::_1, std::placeholders::_2, callback));
-}
-
-void SimulatorRemoteResourceImpl::put(const std::map<std::string, std::string> &queryParams,
-                                      SimulatorResourceModelSP representation,
-                                      ResponseCallback callback)
-{
-    if (!callback)
-    {
-        OC_LOG(ERROR, TAG, "Invalid callback!");
-        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-    }
-
-    if (!m_putRequestSender)
-    {
-        OC_LOG(ERROR, TAG, "Invalid PUT request sender !");
-        throw NoSupportException("Can not send PUT request on this resource!");
-    }
-
-    m_putRequestSender->sendRequest(std::string(), queryParams,
-                                    representation, std::bind(
-                                        &SimulatorRemoteResourceImpl::onResponseReceived,
-                                        this, std::placeholders::_1, std::placeholders::_2, callback));
-}
-
-void SimulatorRemoteResourceImpl::post(const std::string &interfaceType,
-                                       const std::map<std::string, std::string> &queryParams,
-                                       SimulatorResourceModelSP representation,
-                                       ResponseCallback callback)
-{
-    if (!callback)
-    {
-        OC_LOG(ERROR, TAG, "Invalid callback!");
-        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-    }
-
-    if (!m_postRequestSender)
-    {
-        OC_LOG(ERROR, TAG, "Invalid POST request sender !");
-        throw NoSupportException("Can not send POST request on this resource!");
-    }
-
-    m_postRequestSender->sendRequest(interfaceType, queryParams,
-                                     representation, std::bind(
-                                         &SimulatorRemoteResourceImpl::onResponseReceived,
-                                         this, std::placeholders::_1, std::placeholders::_2, callback));
-}
-
-void SimulatorRemoteResourceImpl::post(const std::map<std::string, std::string> &queryParams,
-                                       SimulatorResourceModelSP representation,
-                                       ResponseCallback callback)
-{
-    if (!callback)
-    {
-        OC_LOG(ERROR, TAG, "Invalid callback!");
-        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-    }
-
-    if (!m_postRequestSender)
-    {
-        OC_LOG(ERROR, TAG, "Invalid POST request sender !");
-        throw NoSupportException("Can not send POST request on this resource!");
-    }
-
-    m_postRequestSender->sendRequest(std::string(), queryParams,
-                                     representation, std::bind(
-                                         &SimulatorRemoteResourceImpl::onResponseReceived,
-                                         this, std::placeholders::_1, std::placeholders::_2, callback));
-}
-
-int SimulatorRemoteResourceImpl::startVerification(RequestType type,
-        StateCallback callback)
-{
-    if (!callback)
-    {
-        OC_LOG(ERROR, TAG, "Invalid callback!");
-        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-    }
-
-    if (!m_autoRequestGenMngr)
-    {
-        OC_LOG(ERROR, TAG, "Invalid auto request generation manager !");
-        throw NoSupportException("Resource is not configured with RAML!");
-    }
-
-    if (m_requestModelList.end() == m_requestModelList.find(type))
-        throw NoSupportException("Resource does not support this request type!");
-
-    // Local callback for handling progress sate callback
-    AutoRequestGeneration::ProgressStateCallback localCallback = [this, callback](
-                int sessionId, OperationState state)
-    {
-        callback(m_id, sessionId, state);
-    };
-
-    switch (type)
-    {
-        case RequestType::RQ_TYPE_GET:
-            if (m_getRequestSender)
-            {
-                return m_autoRequestGenMngr->startOnGET(m_getRequestSender,
-                                    m_requestModelList[RequestType::RQ_TYPE_GET]->getQueryParams(),
-                                    localCallback);
-            }
-            break;
-
-        case RequestType::RQ_TYPE_PUT:
-            if (m_putRequestSender)
-            {
-                return m_autoRequestGenMngr->startOnPUT(m_putRequestSender,
-                                    m_requestModelList[RequestType::RQ_TYPE_PUT]->getQueryParams(),
-                                    m_requestModelList[RequestType::RQ_TYPE_PUT]->getRepSchema(),
-                                    localCallback);
-            }
-            break;
-
-        case RequestType::RQ_TYPE_POST:
-            if (m_postRequestSender)
-            {
-                return m_autoRequestGenMngr->startOnPOST(m_putRequestSender,
-                                    m_requestModelList[RequestType::RQ_TYPE_POST]->getQueryParams(),
-                                    m_requestModelList[RequestType::RQ_TYPE_POST]->getRepSchema(),
-                                    localCallback);
-            }
-            break;
-
-        case RequestType::RQ_TYPE_DELETE:
-        default:
-            throw NoSupportException("Resource does not support this request type!");
-    }
-
-    return -1; // Code should not reach here
-}
-
-void SimulatorRemoteResourceImpl::stopVerification(int id)
-{
-    if (id < 0)
-    {
-        OC_LOG(ERROR, TAG, "Invalid session id!");
-        throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Invalid ID!");
-    }
-
-    if (!m_autoRequestGenMngr)
-    {
-        OC_LOG(ERROR, TAG, "Invalid auto request generation manager !");
-        throw NoSupportException("Resource is not configured with RAML!");
-    }
-
-    m_autoRequestGenMngr->stop(id);
-}
-
-void SimulatorRemoteResourceImpl::configure(const std::string &path)
-{
-    if (path.empty())
-    {
-        OC_LOG(ERROR, TAG, "Invalid path given for configuration!");
-        throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Empty path string!");
-    }
-
-    std::shared_ptr<RAML::RamlParser> ramlParser = std::make_shared<RAML::RamlParser>(path);
-    RAML::RamlPtr raml = ramlParser->getRamlPtr();
-
-    configure(raml);
-}
-
-void SimulatorRemoteResourceImpl::configure(std::shared_ptr<RAML::Raml> &raml)
-{
-    m_requestModelList = RequestModelBuilder(raml).build(m_ocResource->uri());
-    if (m_getRequestSender &&
-        m_requestModelList.end() != m_requestModelList.find(RequestType::RQ_TYPE_GET))
-    {
-        m_getRequestSender->setRequestModel(m_requestModelList[RequestType::RQ_TYPE_GET]);
-    }
-
-    if (m_putRequestSender &&
-        m_requestModelList.end() != m_requestModelList.find(RequestType::RQ_TYPE_PUT))
-    {
-        m_putRequestSender->setRequestModel(m_requestModelList[RequestType::RQ_TYPE_PUT]);
-    }
-
-    if (m_postRequestSender &&
-        m_requestModelList.end() != m_requestModelList.find(RequestType::RQ_TYPE_POST))
-    {
-        m_postRequestSender->setRequestModel(m_requestModelList[RequestType::RQ_TYPE_POST]);
-    }
-
-    if (!m_autoRequestGenMngr)
-    {
-        m_autoRequestGenMngr = std::make_shared<AutoRequestGenMngr>();
-    }
-}
-
-void SimulatorRemoteResourceImpl::onResponseReceived(SimulatorResult result,
-        SimulatorResourceModelSP repModel,
-        ResponseCallback clientCallback)
-{
-    clientCallback(m_id, result, repModel);
-}
-
-SimulatorConnectivityType SimulatorRemoteResourceImpl::convertConnectivityType(
-    OCConnectivityType type) const
-{
-    switch (type)
-    {
-        case CT_ADAPTER_IP:
-            return SIMULATOR_CT_ADAPTER_IP;
-
-        case CT_IP_USE_V4:
-            return SIMULATOR_CT_IP_USE_V4 ;
-
-        case CT_IP_USE_V6:
-            return SIMULATOR_CT_IP_USE_V6;
-
-        case CT_ADAPTER_GATT_BTLE:
-            return SIMULATOR_CT_ADAPTER_GATT_BTLE;
-
-        case CT_ADAPTER_RFCOMM_BTEDR:
-            return SIMULATOR_CT_ADAPTER_RFCOMM_BTEDR;
-
-        default:
-            return SIMULATOR_CT_DEFAULT;
-    }
-}
\ No newline at end of file
diff --git a/service/simulator/src/client-controller/simulator_remote_resource_impl.h b/service/simulator/src/client-controller/simulator_remote_resource_impl.h
deleted file mode 100644 (file)
index bd64e98..0000000
+++ /dev/null
@@ -1,100 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-/**
- * @file simulator_remote_resource_impl.h
- *
- * @brief This file provides internal implementation of simulator remote resource functionalities.
- *
- */
-
-#ifndef SIMULATOR_REMOTE_RESOURCE_IMPL_H_
-#define SIMULATOR_REMOTE_RESOURCE_IMPL_H_
-
-#include "simulator_remote_resource.h"
-#include "auto_request_gen_mngr.h"
-#include "RamlParser.h"
-#include "request_model.h"
-
-#include <mutex>
-
-class SimulatorRemoteResourceImpl : public SimulatorRemoteResource
-{
-    public:
-        SimulatorRemoteResourceImpl(std::shared_ptr<OC::OCResource> &ocResource);
-        std::string getURI() const;
-        std::string getHost() const;
-        std::string getID() const;
-        SimulatorConnectivityType getConnectivityType() const;
-        std::vector < std::string > getResourceTypes() const;
-        std::vector < std::string > getResourceInterfaces() const;
-        bool isObservable() const;
-
-        void observe(ObserveType type, ObserveNotificationCallback callback);
-
-        void cancelObserve();
-
-        void get(const std::map<std::string, std::string> &queryParams,
-                 ResponseCallback callback);
-
-        void get(const std::string &interfaceType,
-                 const std::map<std::string, std::string> &queryParams,
-                 ResponseCallback callback);
-
-        void put(const std::map<std::string, std::string> &queryParams,
-                 SimulatorResourceModelSP representation,
-                 ResponseCallback callback);
-
-        void put(const std::string &interfaceType,
-                 const std::map<std::string, std::string> &queryParams,
-                 SimulatorResourceModelSP representation,
-                 ResponseCallback callback);
-
-        void post(const std::map<std::string, std::string> &queryParams,
-                  SimulatorResourceModelSP representation,
-                  ResponseCallback callback);
-
-        void post(const std::string &interfaceType,
-                  const std::map<std::string, std::string> &queryParams,
-                  SimulatorResourceModelSP representation,
-                  ResponseCallback callback);
-
-        int startVerification(RequestType type, StateCallback callback);
-        void stopVerification(int id);
-        void configure(const std::string &path);
-
-    private:
-        void configure(std::shared_ptr<RAML::Raml> &raml);
-        void onResponseReceived(SimulatorResult result, SimulatorResourceModelSP repModel,
-                                ResponseCallback clientCallback);
-        SimulatorConnectivityType convertConnectivityType(OCConnectivityType type) const;
-
-        std::string m_id;
-        std::mutex m_observeMutex;
-        bool m_observeState;
-        GETRequestSenderSP m_getRequestSender;
-        PUTRequestSenderSP m_putRequestSender;
-        POSTRequestSenderSP m_postRequestSender;
-        AutoRequestGenMngrSP m_autoRequestGenMngr;
-        std::map<RequestType, RequestModelSP> m_requestModelList;
-        std::shared_ptr<OC::OCResource> m_ocResource;
-};
-
-#endif
diff --git a/service/simulator/src/client/get_request_generator.cpp b/service/simulator/src/client/get_request_generator.cpp
new file mode 100644 (file)
index 0000000..6e1e330
--- /dev/null
@@ -0,0 +1,102 @@
+/******************************************************************
+ *
+ * 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 "get_request_generator.h"
+#include "request_model.h"
+#include "simulator_exceptions.h"
+#include "logger.h"
+
+#define TAG "GET_REQUEST_GEN"
+
+GETRequestGenerator::GETRequestGenerator(int id,
+        const std::shared_ptr<OC::OCResource> &ocResource,
+        const std::shared_ptr<RequestModel> &requestSchema,
+        RequestGeneration::ProgressStateCallback callback)
+    :   RequestGeneration(RequestType::RQ_TYPE_GET, id, callback),
+        m_stopRequested(false),
+        m_requestSchema(requestSchema),
+        m_requestSender(ocResource) {}
+
+void GETRequestGenerator::startSending()
+{
+    // Create thread and start sending requests in dispatched thread
+    m_thread.reset(new std::thread(&GETRequestGenerator::SendAllRequests, this));
+    m_thread->detach();
+}
+
+void GETRequestGenerator::stopSending()
+{
+    m_stopRequested = true;
+}
+
+void GETRequestGenerator::SendAllRequests()
+{
+    // Notify the progress status
+    OIC_LOG(DEBUG, TAG, "Sending OP_START event");
+    m_callback(m_id, OP_START);
+
+    QPGenerator queryParamGen(m_requestSchema->getQueryParams());
+    do
+    {
+        // Get the next possible queryParameter
+        auto queryParam = queryParamGen.next();
+
+        try
+        {
+            // Send the request
+            m_requestSender.send(queryParam, std::bind(&GETRequestGenerator::onResponseReceived, this,
+                                 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
+            m_requestCnt++;
+        }
+        catch (SimulatorException &e)
+        {
+            m_stopRequested = true;
+            break;
+        }
+    }
+    while (!m_stopRequested && queryParamGen.hasNext());
+
+    completed();
+}
+
+void GETRequestGenerator::onResponseReceived(SimulatorResult result,
+        const SimulatorResourceModel &repModel, const RequestInfo &reqInfo)
+{
+    OIC_LOG(DEBUG, TAG, "Response recieved");
+    m_responseCnt++;
+    completed();
+}
+
+void GETRequestGenerator::completed()
+{
+    if (m_requestCnt == m_responseCnt)
+    {
+        if (m_stopRequested)
+        {
+            OIC_LOG(DEBUG, TAG, "Sending OP_ABORT event");
+            m_callback(m_id, OP_ABORT);
+        }
+        else
+        {
+            OIC_LOG(DEBUG, TAG, "Sending OP_COMPLETE event");
+            m_callback(m_id, OP_COMPLETE);
+        }
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/src/client/get_request_generator.h b/service/simulator/src/client/get_request_generator.h
new file mode 100644 (file)
index 0000000..bd64036
--- /dev/null
@@ -0,0 +1,53 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_GET_REQUEST_GEN_H_
+#define SIMULATOR_GET_REQUEST_GEN_H_
+
+#include "request_generation.h"
+#include "query_param_generator.h"
+#include "request_sender.h"
+
+class RequestModel;
+class GETRequestGenerator : public RequestGeneration
+{
+    public:
+        GETRequestGenerator(int id, const std::shared_ptr<OC::OCResource> &ocResource,
+                            const std::shared_ptr<RequestModel> &requestSchema,
+                            ProgressStateCallback callback);
+
+        void startSending();
+        void stopSending();
+
+    private:
+        void SendAllRequests();
+        void onResponseReceived(SimulatorResult result,
+                                const SimulatorResourceModel &repModel, const RequestInfo &reqInfo);
+        void completed();
+
+        bool m_stopRequested;
+        std::unique_ptr<std::thread> m_thread;
+        std::shared_ptr<RequestModel> m_requestSchema;
+        GETRequestSender m_requestSender;
+};
+
+typedef std::shared_ptr<GETRequestGenerator> GETRequestGeneratorSP;
+
+#endif
diff --git a/service/simulator/src/client/post_request_generator.cpp b/service/simulator/src/client/post_request_generator.cpp
new file mode 100644 (file)
index 0000000..bc0cda0
--- /dev/null
@@ -0,0 +1,131 @@
+/******************************************************************
+ *
+ * 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 "post_request_generator.h"
+#include "request_model.h"
+#include "simulator_exceptions.h"
+#include "logger.h"
+
+#define TAG "POST_REQUEST_GEN"
+
+POSTRequestGenerator::POSTRequestGenerator(int id,
+        const std::shared_ptr<OC::OCResource> &ocResource,
+        const std::shared_ptr<RequestModel> &requestSchema,
+        RequestGeneration::ProgressStateCallback callback)
+    :   RequestGeneration(RequestType::RQ_TYPE_GET, id, callback),
+        m_stopRequested(false),
+        m_requestSchema(requestSchema),
+        m_requestSender(ocResource) {}
+
+void POSTRequestGenerator::startSending()
+{
+    // Create thread and start sending requests in dispatched thread
+    m_thread.reset(new std::thread(&POSTRequestGenerator::SendAllRequests, this));
+    m_thread->detach();
+}
+
+void POSTRequestGenerator::stopSending()
+{
+    m_stopRequested = true;
+}
+
+void POSTRequestGenerator::SendAllRequests()
+{
+    // Notify the progress status
+    OIC_LOG(DEBUG, TAG, "Sending OP_START event");
+    m_callback(m_id, OP_START);
+
+    std::shared_ptr<SimulatorResourceModelSchema> repSchema =
+        m_requestSchema->getRequestRepSchema();
+
+    if (!repSchema)
+    {
+        OIC_LOG(ERROR, TAG, "Request representation model is null!");
+        m_callback(m_id, OP_COMPLETE);
+        return;
+    }
+
+    // Create attribute generator for value manipulation
+    std::vector<AttributeGenerator> attributeGenList;
+    for (auto &propertyElement : repSchema->getChildProperties())
+        attributeGenList.push_back(AttributeGenerator(propertyElement.first, propertyElement.second));
+
+    if (!attributeGenList.size())
+    {
+        OIC_LOG(ERROR, TAG, "Zero attribute found from resource model!");
+        return;
+    }
+
+    QPGenerator queryParamGen(m_requestSchema->getQueryParams());
+
+    do
+    {
+        // Get the next possible queryParameter
+        std::map<std::string, std::string> queryParam = queryParamGen.next();
+
+        for (auto &attributeGen : attributeGenList)
+        {
+            if (m_stopRequested) break;
+
+            while (!m_stopRequested && attributeGen.hasNext())
+            {
+                SimulatorResourceModel repModel;
+                SimulatorResourceAttribute attribute;
+                if (true == attributeGen.next(attribute))
+                    repModel.add(attribute.getName(), attribute.getValue());
+
+                // Send the request
+                m_requestSender.send(queryParam, repModel,
+                                     std::bind(&POSTRequestGenerator::onResponseReceived,
+                                               this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
+
+                m_requestCnt++;
+            }
+        }
+    }
+    while (!m_stopRequested && queryParamGen.hasNext());
+
+    completed();
+}
+
+void POSTRequestGenerator::onResponseReceived(SimulatorResult result,
+        const SimulatorResourceModel &repModel, const RequestInfo &reqInfo)
+{
+    OIC_LOG(DEBUG, TAG, "Response recieved");
+    m_responseCnt++;
+    completed();
+}
+
+void POSTRequestGenerator::completed()
+{
+    if (m_requestCnt == m_responseCnt)
+    {
+        if (m_stopRequested)
+        {
+            OIC_LOG(DEBUG, TAG, "Sending OP_ABORT event");
+            m_callback(m_id, OP_ABORT);
+        }
+        else
+        {
+            OIC_LOG(DEBUG, TAG, "Sending OP_COMPLETE event");
+            m_callback(m_id, OP_COMPLETE);
+        }
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/src/client/post_request_generator.h b/service/simulator/src/client/post_request_generator.h
new file mode 100644 (file)
index 0000000..92a23b2
--- /dev/null
@@ -0,0 +1,56 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_POST_REQUEST_GEN_H_
+#define SIMULATOR_POST_REQUEST_GEN_H_
+
+#include "request_generation.h"
+#include "query_param_generator.h"
+#include "attribute_generator.h"
+#include "request_sender.h"
+
+class RequestModel;
+class POSTRequestGenerator : public RequestGeneration
+{
+    public:
+        POSTRequestGenerator(int id, const std::shared_ptr<OC::OCResource> &ocResource,
+                             const std::shared_ptr<RequestModel> &requestSchema,
+                             ProgressStateCallback callback);
+
+        void startSending();
+        void stopSending();
+
+    private:
+        void SendAllRequests();
+        void onResponseReceived(SimulatorResult result,
+                                const SimulatorResourceModel &repModel, const RequestInfo &reqInfo);
+        void completed();
+
+        bool m_stopRequested;
+        std::unique_ptr<std::thread> m_thread;
+        std::shared_ptr<RequestModel> m_requestSchema;
+        POSTRequestSender m_requestSender;
+};
+
+typedef std::shared_ptr<POSTRequestGenerator> POSTRequestGeneratorSP;
+
+#endif
+
+
diff --git a/service/simulator/src/client/put_request_generator.cpp b/service/simulator/src/client/put_request_generator.cpp
new file mode 100644 (file)
index 0000000..65ae77d
--- /dev/null
@@ -0,0 +1,133 @@
+/******************************************************************
+ *
+ * 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 "put_request_generator.h"
+#include "request_model.h"
+#include "simulator_exceptions.h"
+#include "logger.h"
+
+#define TAG "PUT_REQUEST_GEN"
+
+PUTRequestGenerator::PUTRequestGenerator(int id,
+        const std::shared_ptr<OC::OCResource> &ocResource,
+        const std::shared_ptr<RequestModel> &requestSchema,
+        RequestGeneration::ProgressStateCallback callback)
+    :   RequestGeneration(RequestType::RQ_TYPE_GET, id, callback),
+        m_stopRequested(false),
+        m_requestSchema(requestSchema),
+        m_requestSender(ocResource) {}
+
+void PUTRequestGenerator::startSending()
+{
+    // Create thread and start sending requests in dispatched thread
+    m_thread.reset(new std::thread(&PUTRequestGenerator::SendAllRequests, this));
+    m_thread->detach();
+}
+
+void PUTRequestGenerator::stopSending()
+{
+    m_stopRequested = true;
+}
+
+void PUTRequestGenerator::SendAllRequests()
+{
+    OIC_LOG(DEBUG, TAG, "Sending OP_START event");
+    m_callback(m_id, OP_START);
+
+    std::shared_ptr<SimulatorResourceModelSchema> repSchema =
+        m_requestSchema->getRequestRepSchema();
+
+    if (!repSchema)
+    {
+        OIC_LOG(ERROR, TAG, "Request representation model is null!");
+        m_callback(m_id, OP_ABORT);
+        return;
+    }
+
+    SimulatorResourceModel representation = repSchema->buildResourceModel();
+
+    // Create attribute combination generator for generating resource model
+    // with different attribute values
+    std::vector<SimulatorResourceAttribute> attributes;
+    for (auto &attributeElement : representation.getAttributeValues())
+    {
+        SimulatorResourceAttribute attribute;
+        attribute.setName(attributeElement.first);
+        attribute.setValue(attributeElement.second);
+        attribute.setProperty(repSchema->get(attributeElement.first));
+        attributes.push_back(attribute);
+    }
+
+    if (!attributes.size())
+    {
+        OIC_LOG(ERROR, TAG, "Zero attribute found from resource model!");
+        m_callback(m_id, OP_COMPLETE);
+        return;
+    }
+
+    QPGenerator queryParamGen(m_requestSchema->getQueryParams());
+    do
+    {
+        // Get the next possible queryParameter
+        std::map<std::string, std::string> queryParam = queryParamGen.next();
+
+        AttributeCombinationGen attrCombGen(attributes);
+
+        // Get the new model from attribute combination generator
+        SimulatorResourceModel resModel;
+        while (!m_stopRequested && attrCombGen.next(resModel))
+        {
+            // Send the request
+            m_requestSender.send(queryParam, resModel,
+                                 std::bind(&PUTRequestGenerator::onResponseReceived, this,
+                                           std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
+
+            m_requestCnt++;
+        }
+    }
+    while (!m_stopRequested && queryParamGen.hasNext());
+
+    completed();
+}
+
+void PUTRequestGenerator::onResponseReceived(SimulatorResult result,
+        const SimulatorResourceModel &repModel, const RequestInfo &reqInfo)
+{
+    OIC_LOG(DEBUG, TAG, "Response recieved");
+    m_responseCnt++;
+    completed();
+}
+
+void PUTRequestGenerator::completed()
+{
+    if (m_requestCnt == m_responseCnt)
+    {
+        if (m_stopRequested)
+        {
+            OIC_LOG(DEBUG, TAG, "Sending OP_ABORT event");
+            m_callback(m_id, OP_ABORT);
+        }
+        else
+        {
+            OIC_LOG(DEBUG, TAG, "Sending OP_COMPLETE event");
+            m_callback(m_id, OP_COMPLETE);
+        }
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/src/client/put_request_generator.h b/service/simulator/src/client/put_request_generator.h
new file mode 100644 (file)
index 0000000..b6e49d9
--- /dev/null
@@ -0,0 +1,56 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_PUT_REQUEST_GEN_H_
+#define SIMULATOR_PUT_REQUEST_GEN_H_
+
+#include "request_generation.h"
+#include "query_param_generator.h"
+#include "attribute_generator.h"
+#include "request_sender.h"
+
+class RequestModel;
+class PUTRequestGenerator : public RequestGeneration
+{
+    public:
+        PUTRequestGenerator(int id, const std::shared_ptr<OC::OCResource> &ocResource,
+                            const std::shared_ptr<RequestModel> &requestModel,
+                            ProgressStateCallback callback);
+
+        void startSending();
+        void stopSending();
+
+    private:
+        void SendAllRequests();
+        void onResponseReceived(SimulatorResult result,
+                                const SimulatorResourceModel &repModel, const RequestInfo &reqInfo);
+        void completed();
+
+        bool m_stopRequested;
+        std::unique_ptr<std::thread> m_thread;
+        std::shared_ptr<RequestModel> m_requestSchema;
+        PUTRequestSender m_requestSender;
+};
+
+typedef std::shared_ptr<PUTRequestGenerator> PUTRequestGeneratorSP;
+
+#endif
+
+
diff --git a/service/simulator/src/client/request_automation_manager.cpp b/service/simulator/src/client/request_automation_manager.cpp
new file mode 100644 (file)
index 0000000..7749ab5
--- /dev/null
@@ -0,0 +1,231 @@
+/******************************************************************
+ *
+ * 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 "request_automation_manager.h"
+#include "get_request_generator.h"
+#include "put_request_generator.h"
+#include "post_request_generator.h"
+#include "request_model.h"
+#include "simulator_exceptions.h"
+#include "logger.h"
+
+#define TAG "AUTO_REQ_GEN_MNGR"
+
+RequestAutomationMngr::RequestAutomationMngr(
+    const std::shared_ptr<OC::OCResource> &ocResource)
+    :   m_id(0), m_ocResource(ocResource) {}
+
+int RequestAutomationMngr::startOnGET(
+    const std::shared_ptr<RequestModel> &requestSchema,
+    RequestGeneration::ProgressStateCallback callback)
+{
+    if (!requestSchema)
+    {
+        OIC_LOG(ERROR, TAG, "Request schema is null!");
+        throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Request model is null!");
+    }
+
+    if (!callback)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid callback!");
+        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+    }
+
+    // Check is there auto request generation session already going on for GET requests
+    if (isInProgress(RequestType::RQ_TYPE_GET))
+    {
+        OIC_LOG(ERROR, TAG, "Auto requesting for GET is already in progress!");
+        throw OperationInProgressException(
+            "Another GET request generation session is already in progress!");
+    }
+
+    // Create request generation session
+    RequestGeneration::ProgressStateCallback localCallback = std::bind(
+                &RequestAutomationMngr::onProgressChange, this,
+                std::placeholders::_1, std::placeholders::_2, callback);
+
+    std::lock_guard<std::mutex> lock(m_lock);
+    std::shared_ptr<RequestGeneration> requestGen(
+        new GETRequestGenerator(m_id, m_ocResource, requestSchema, localCallback));
+    m_requestGenList[m_id] = requestGen;
+
+    try
+    {
+        requestGen->start();
+    }
+    catch (OperationInProgressException &e)
+    {
+        m_requestGenList.erase(m_requestGenList.find(m_id));
+        throw;
+    }
+
+    return m_id++;
+}
+
+int RequestAutomationMngr::startOnPUT(const std::shared_ptr<RequestModel> &requestSchema,
+                                      RequestGeneration::ProgressStateCallback callback)
+{
+    if (!requestSchema)
+    {
+        OIC_LOG(ERROR, TAG, "Request schema is null!");
+        throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Request model is null!");
+    }
+
+    if (!callback)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid callback!");
+        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+    }
+
+    // Check is there auto request generation session already going on for GET requests
+    if (isInProgress(RequestType::RQ_TYPE_PUT))
+    {
+        OIC_LOG(ERROR, TAG, "Auto requesting for PUT is already in progress!");
+        throw OperationInProgressException(
+            "Another PUT request generation session is already in progress!");
+    }
+
+    // Create request generation session
+    RequestGeneration::ProgressStateCallback localCallback = std::bind(
+                &RequestAutomationMngr::onProgressChange, this,
+                std::placeholders::_1, std::placeholders::_2, callback);
+
+    // Create and make the entry in list
+    std::lock_guard<std::mutex> lock(m_lock);
+    std::shared_ptr<RequestGeneration> requestGen(
+        new PUTRequestGenerator(m_id, m_ocResource, requestSchema, localCallback));
+    m_requestGenList[m_id] = requestGen;
+
+    try
+    {
+        requestGen->start();
+    }
+    catch (OperationInProgressException &e)
+    {
+        m_requestGenList.erase(m_requestGenList.find(m_id));
+        throw;
+    }
+
+    return m_id++;
+}
+
+int RequestAutomationMngr::startOnPOST(const std::shared_ptr<RequestModel> &requestSchema,
+                                       RequestGeneration::ProgressStateCallback callback)
+{
+    if (!requestSchema)
+    {
+        OIC_LOG(ERROR, TAG, "Request schema is null!");
+        throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Request model is null!");
+    }
+
+    if (!callback)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid callback!");
+        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+    }
+
+    // Check is there auto request generation session already going on for GET requests
+    if (isInProgress(RequestType::RQ_TYPE_POST))
+    {
+        OIC_LOG(ERROR, TAG, "Auto requesting for POST is already in progress!");
+        throw OperationInProgressException(
+            "Another POST request generation session is already in progress!");
+    }
+
+    // Create request generation session
+    RequestGeneration::ProgressStateCallback localCallback = std::bind(
+                &RequestAutomationMngr::onProgressChange, this,
+                std::placeholders::_1, std::placeholders::_2, callback);
+
+    // Create and make the entry in list
+    std::lock_guard<std::mutex> lock(m_lock);
+    std::shared_ptr<RequestGeneration> requestGen(
+        new POSTRequestGenerator(m_id, m_ocResource, requestSchema, localCallback));
+    m_requestGenList[m_id] = requestGen;
+
+    try
+    {
+        requestGen->start();
+    }
+    catch (OperationInProgressException &e)
+    {
+        m_requestGenList.erase(m_requestGenList.find(m_id));
+        throw;
+    }
+
+    return m_id++;
+}
+
+void RequestAutomationMngr::stop(int id)
+{
+    std::lock_guard<std::mutex> lock(m_lock);
+    if (m_requestGenList.end() != m_requestGenList.find(id))
+    {
+        m_requestGenList[id]->stop();
+    }
+}
+
+void RequestAutomationMngr::onProgressChange(int sessionId, OperationState state,
+        RequestGeneration::ProgressStateCallback clientCallback)
+{
+    if (!isValid(sessionId))
+        return;
+
+    // Remove the request generator from list if it is completed
+    if (state == OP_COMPLETE || state == OP_ABORT)
+    {
+        remove(sessionId);
+    }
+
+    // Delegate notification to app callback
+    clientCallback(sessionId, state);
+}
+
+bool RequestAutomationMngr::isValid(int id)
+{
+    std::lock_guard<std::mutex> lock(m_lock);
+    if (m_requestGenList.end() != m_requestGenList.find(id))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+bool RequestAutomationMngr::isInProgress(RequestType type)
+{
+    std::lock_guard<std::mutex> lock(m_lock);
+    for (auto &session : m_requestGenList)
+    {
+        if ((session.second)->type() == type)
+            return true;
+    }
+
+    return false;
+}
+
+void RequestAutomationMngr::remove(int id)
+{
+    std::lock_guard<std::mutex> lock(m_lock);
+    if (m_requestGenList.end() != m_requestGenList.find(id))
+    {
+        m_requestGenList.erase(m_requestGenList.find(id));
+    }
+}
diff --git a/service/simulator/src/client/request_automation_manager.h b/service/simulator/src/client/request_automation_manager.h
new file mode 100644 (file)
index 0000000..8a6a5c5
--- /dev/null
@@ -0,0 +1,71 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file request_automation_manager.h
+ *
+ * @brief This file provides class for managing auto request generation sessions.
+ *
+ */
+
+#ifndef SIMULATOR_REQUEST_AUTOMATION_MNGR_H_
+#define SIMULATOR_REQUEST_AUTOMATION_MNGR_H_
+
+#include <mutex>
+#include <unordered_map>
+
+#include "request_generation.h"
+
+namespace OC
+{
+    class OCResource;
+}
+
+class RequestModel;
+class RequestAutomationMngr
+{
+    public:
+        RequestAutomationMngr(const std::shared_ptr<OC::OCResource> &ocResource);
+
+        int startOnGET(const std::shared_ptr<RequestModel> &requestSchema,
+                       RequestGeneration::ProgressStateCallback callback);
+
+        int startOnPUT(const std::shared_ptr<RequestModel> &requestSchema,
+                       RequestGeneration::ProgressStateCallback callback);
+
+        int startOnPOST(const std::shared_ptr<RequestModel> &requestSchema,
+                        RequestGeneration::ProgressStateCallback callback);
+
+        void stop(int id);
+
+    private:
+        void onProgressChange(int sessionId, OperationState state,
+                              RequestGeneration::ProgressStateCallback clientCallback);
+        bool isValid(int id);
+        bool isInProgress(RequestType type);
+        void remove(int id);
+
+        std::mutex m_lock;
+        std::unordered_map<int, std::shared_ptr<RequestGeneration>> m_requestGenList;
+        int m_id;
+        std::shared_ptr<OC::OCResource> m_ocResource;
+};
+
+#endif
diff --git a/service/simulator/src/client/request_generation.cpp b/service/simulator/src/client/request_generation.cpp
new file mode 100644 (file)
index 0000000..cec92ed
--- /dev/null
@@ -0,0 +1,40 @@
+/******************************************************************
+ *
+ * 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 "request_generation.h"
+
+RequestGeneration::RequestGeneration(RequestType type, int id,
+                                     ProgressStateCallback callback)
+    :   m_type(type),
+        m_id(id),
+        m_callback(callback),
+        m_requestsSent(false),
+        m_requestCnt(0),
+        m_responseCnt(0) {}
+
+void RequestGeneration::start()
+{
+    startSending();
+}
+
+void RequestGeneration::stop()
+{
+    stopSending();
+}
diff --git a/service/simulator/src/client/request_generation.h b/service/simulator/src/client/request_generation.h
new file mode 100644 (file)
index 0000000..eae6082
--- /dev/null
@@ -0,0 +1,50 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_REQUEST_GENERATION_H_
+#define SIMULATOR_REQUEST_GENERATION_H_
+
+#include "simulator_client_types.h"
+
+class RequestGeneration
+{
+    public:
+        typedef std::function<void (int, OperationState)> ProgressStateCallback;
+
+        RequestGeneration(RequestType type, int id,
+                          ProgressStateCallback callback);
+        RequestType type() const { return m_type;}
+        int id() const {return m_id;}
+        void start();
+        void stop();
+
+    protected:
+        virtual void startSending() = 0;
+        virtual void stopSending() = 0;
+
+        RequestType m_type;
+        int m_id;
+        ProgressStateCallback m_callback;
+        bool m_requestsSent;
+        int m_requestCnt;
+        int m_responseCnt;
+};
+
+#endif
diff --git a/service/simulator/src/client/request_sender.cpp b/service/simulator/src/client/request_sender.cpp
new file mode 100644 (file)
index 0000000..4337a8d
--- /dev/null
@@ -0,0 +1,136 @@
+/******************************************************************
+ *
+ * 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 "request_sender.h"
+#include "simulator_logger.h"
+#include "simulator_utils.h"
+#include "logger.h"
+
+#define TAG "GET_REQUEST_SNDR"
+
+GETRequestSender::GETRequestSender(const std::shared_ptr<OC::OCResource> &ocResource)
+    :   m_ocResource(ocResource) {}
+
+SimulatorResult GETRequestSender::send(const ResponseCallback &callback)
+{
+    std::map<std::string, std::string> queryParams;
+    return send(queryParams, callback);
+}
+
+SimulatorResult GETRequestSender::send(const std::map<std::string, std::string> &queryParams,
+                                       const ResponseCallback &callback)
+{
+    // Create request info
+    RequestInfo requestInfo;
+    requestInfo.type = RequestType::RQ_TYPE_GET;
+    requestInfo.queryParams = queryParams;
+
+    SIM_LOG(ILogger::INFO, "Sending GET request." << "\n" << getRequestString(queryParams))
+
+    OCStackResult ocResult =  m_ocResource->get(queryParams,
+                              std::bind(&GETRequestSender::onResponseReceived, this, std::placeholders::_1,
+                                        std::placeholders::_2, std::placeholders::_3, requestInfo, callback));
+    return static_cast<SimulatorResult>(ocResult);
+}
+
+void GETRequestSender::onResponseReceived(const OC::HeaderOptions &headerOptions,
+        const OC::OCRepresentation &rep, const int errorCode, RequestInfo &requestInfo,
+        ResponseCallback callback)
+{
+    SIM_LOG(ILogger::INFO, "Response received for GET." << "\n" << getPayloadString(rep));
+    SimulatorResourceModel resourceModel = SimulatorResourceModel::build(rep);
+    callback(static_cast<SimulatorResult>(errorCode), resourceModel, requestInfo);
+}
+
+PUTRequestSender::PUTRequestSender(const std::shared_ptr<OC::OCResource> &ocResource)
+    :   m_ocResource(ocResource) {}
+
+SimulatorResult PUTRequestSender::send(const SimulatorResourceModel &representation,
+                                       const ResponseCallback &callback)
+{
+    std::map<std::string, std::string> queryParams;
+    return send(queryParams, representation, callback);
+}
+
+SimulatorResult PUTRequestSender::send(const std::map<std::string, std::string> &queryParams,
+                                       const SimulatorResourceModel &representation, const ResponseCallback &callback)
+{
+    // Create request info
+    RequestInfo requestInfo;
+    requestInfo.type = RequestType::RQ_TYPE_PUT;
+    requestInfo.queryParams = queryParams;
+    requestInfo.payLoad = representation;
+
+    OC::OCRepresentation ocRep = representation.asOCRepresentation();
+    SIM_LOG(ILogger::INFO, "Sending PUT request." << "\n**Payload Details**\n" << getRequestString(
+                queryParams, ocRep));
+
+    OCStackResult ocResult =  m_ocResource->put(ocRep, queryParams,
+                              std::bind(&PUTRequestSender::onResponseReceived, this, std::placeholders::_1,
+                                        std::placeholders::_2, std::placeholders::_3, requestInfo, callback));
+    return static_cast<SimulatorResult>(ocResult);
+}
+
+void PUTRequestSender::onResponseReceived(const OC::HeaderOptions &headerOptions,
+        const OC::OCRepresentation &rep, const int errorCode, RequestInfo &requestInfo,
+        ResponseCallback callback)
+{
+    SIM_LOG(ILogger::INFO, "Response received for PUT." << "\n" << getPayloadString(rep));
+    SimulatorResourceModel resourceModel = SimulatorResourceModel::build(rep);
+    callback(static_cast<SimulatorResult>(errorCode), resourceModel, requestInfo);
+}
+
+POSTRequestSender::POSTRequestSender(const std::shared_ptr<OC::OCResource> &ocResource)
+    :   m_ocResource(ocResource) {}
+
+SimulatorResult POSTRequestSender::send(const SimulatorResourceModel &representation,
+                                        const ResponseCallback &callback)
+{
+    std::map<std::string, std::string> queryParams;
+    return send(queryParams, representation, callback);
+}
+
+SimulatorResult POSTRequestSender::send(const std::map<std::string, std::string> &queryParams,
+                                        const SimulatorResourceModel &representation, const ResponseCallback &callback)
+{
+    // Create request info
+    RequestInfo requestInfo;
+    requestInfo.type = RequestType::RQ_TYPE_POST;
+    requestInfo.queryParams = queryParams;
+    requestInfo.payLoad = representation;
+
+    OC::OCRepresentation ocRep = representation.asOCRepresentation();
+    SIM_LOG(ILogger::INFO, "Sending POST request." << "\n**Payload Details**\n" << getRequestString(
+                queryParams, ocRep));
+
+    OCStackResult ocResult =  m_ocResource->post(ocRep, queryParams,
+                              std::bind(&POSTRequestSender::onResponseReceived, this, std::placeholders::_1,
+                                        std::placeholders::_2, std::placeholders::_3, requestInfo, callback));
+    return static_cast<SimulatorResult>(ocResult);
+}
+
+void POSTRequestSender::onResponseReceived(const OC::HeaderOptions &headerOptions,
+        const OC::OCRepresentation &rep, const int errorCode, RequestInfo &requestInfo,
+        ResponseCallback callback)
+{
+    SIM_LOG(ILogger::INFO, "Response received for POST." << "\n" << getPayloadString(rep));
+    SimulatorResourceModel resourceModel = SimulatorResourceModel::build(rep);
+    callback(static_cast<SimulatorResult>(errorCode), resourceModel, requestInfo);
+}
diff --git a/service/simulator/src/client/request_sender.h b/service/simulator/src/client/request_sender.h
new file mode 100644 (file)
index 0000000..542423d
--- /dev/null
@@ -0,0 +1,102 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_REQUEST_SENDER_H_
+#define SIMULATOR_REQUEST_SENDER_H_
+
+#include "simulator_client_types.h"
+#include "simulator_resource_model.h"
+#include "simulator_error_codes.h"
+
+struct RequestInfo
+{
+    RequestType type;
+    std::map<std::string, std::string> queryParams;
+    SimulatorResourceModel payLoad;
+};
+
+class GETRequestSender
+{
+    public:
+        typedef std::function<void (SimulatorResult result, const SimulatorResourceModel &resModel,
+                                    const RequestInfo &reqInfo)> ResponseCallback;
+
+        GETRequestSender(const std::shared_ptr<OC::OCResource> &ocResource);
+
+        SimulatorResult send(const ResponseCallback &callback);
+
+        SimulatorResult send(const std::map<std::string, std::string> &queryParams,
+                             const ResponseCallback &callback);
+
+        void onResponseReceived(const OC::HeaderOptions &headerOptions,
+                                const OC::OCRepresentation &rep, const int errorCode, RequestInfo &requestInfo,
+                                ResponseCallback callback);
+
+    private:
+        std::shared_ptr<OC::OCResource> m_ocResource;
+};
+
+class PUTRequestSender
+{
+    public:
+        typedef std::function<void (SimulatorResult result, const SimulatorResourceModel &resModel,
+                                    const RequestInfo &reqInfo)> ResponseCallback;
+
+        PUTRequestSender(const std::shared_ptr<OC::OCResource> &ocResource);
+
+        SimulatorResult send(const SimulatorResourceModel &representation,
+                             const ResponseCallback &callback);
+
+        SimulatorResult send(const std::map<std::string, std::string> &queryParams,
+                             const SimulatorResourceModel &representation,
+                             const ResponseCallback &callback);
+
+        void onResponseReceived(const OC::HeaderOptions &headerOptions,
+                                const OC::OCRepresentation &rep, const int errorCode, RequestInfo &requestInfo,
+                                ResponseCallback callback);
+
+    private:
+        std::shared_ptr<OC::OCResource> m_ocResource;
+};
+
+class POSTRequestSender
+{
+    public:
+        typedef std::function<void (SimulatorResult result, const SimulatorResourceModel &resModel,
+                                    const RequestInfo &reqInfo)> ResponseCallback;
+
+        POSTRequestSender(const std::shared_ptr<OC::OCResource> &ocResource);
+
+        SimulatorResult send(const SimulatorResourceModel &representation,
+                             const ResponseCallback &callback);
+
+        SimulatorResult send(const std::map<std::string, std::string> &queryParams,
+                             const SimulatorResourceModel &representation,
+                             const ResponseCallback &callback);
+
+        void onResponseReceived(const OC::HeaderOptions &headerOptions,
+                                const OC::OCRepresentation &rep, const int errorCode, RequestInfo &requestInfo,
+                                ResponseCallback callback);
+
+    private:
+        std::shared_ptr<OC::OCResource> m_ocResource;
+};
+
+#endif
diff --git a/service/simulator/src/client/simulator_remote_resource_impl.cpp b/service/simulator/src/client/simulator_remote_resource_impl.cpp
new file mode 100644 (file)
index 0000000..3473eda
--- /dev/null
@@ -0,0 +1,487 @@
+/******************************************************************
+ *
+ * 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 "simulator_remote_resource_impl.h"
+#include "request_model_builder.h"
+#include "simulator_exceptions.h"
+#include "simulator_utils.h"
+#include "simulator_logger.h"
+#include "logger.h"
+
+#define TAG "SIMULATOR_REMOTE_RESOURCE"
+
+static std::string requestTypeToString(RequestType type)
+{
+    switch (type)
+    {
+        case RequestType::RQ_TYPE_GET:
+            return "GET";
+        case RequestType::RQ_TYPE_PUT:
+            return "PUT";
+        case RequestType::RQ_TYPE_POST:
+            return "POST";
+        case RequestType::RQ_TYPE_DELETE:
+            return "DELETE";
+        default:
+            return "";
+    }
+
+    return ""; // Control should not reach here
+}
+
+static RequestType requestTypeToEnum(const std::string &type)
+{
+    if (type == "GET")
+    {
+        return RequestType::RQ_TYPE_GET;
+    }
+    else if (type == "PUT")
+    {
+        return RequestType::RQ_TYPE_PUT;
+    }
+    else if (type == "POST")
+    {
+        return RequestType::RQ_TYPE_POST;
+    }
+    else if (type == "DELETE")
+    {
+        return RequestType::RQ_TYPE_DELETE;
+    }
+
+    return RequestType::RQ_TYPE_UNKNOWN;
+}
+
+SimulatorRemoteResourceImpl::SimulatorRemoteResourceImpl(
+    const std::shared_ptr<OC::OCResource> &ocResource)
+    :   m_observeState(false),
+        m_getRequestSender(ocResource),
+        m_putRequestSender(ocResource),
+        m_postRequestSender(ocResource),
+        m_requestAutomationMngr(ocResource),
+        m_ocResource(ocResource)
+{
+    m_id = m_ocResource->sid().append(m_ocResource->uri());
+}
+
+std::string SimulatorRemoteResourceImpl::getURI() const
+{
+    return m_ocResource->uri();
+}
+
+std::string SimulatorRemoteResourceImpl::getHost() const
+{
+    return m_ocResource->host();
+}
+
+std::string SimulatorRemoteResourceImpl::getID() const
+{
+    return m_id;
+}
+
+SimulatorConnectivityType SimulatorRemoteResourceImpl::getConnectivityType() const
+{
+    return convertConnectivityType(m_ocResource->connectivityType());
+}
+
+std::vector < std::string > SimulatorRemoteResourceImpl::getResourceTypes() const
+{
+    return m_ocResource->getResourceTypes();
+}
+
+std::vector < std::string > SimulatorRemoteResourceImpl::getInterface() const
+{
+    return m_ocResource->getResourceInterfaces();
+}
+
+bool SimulatorRemoteResourceImpl::isObservable() const
+{
+    return m_ocResource->isObservable();
+}
+
+void SimulatorRemoteResourceImpl::observe(ObserveType type,
+        ObserveNotificationCallback callback)
+{
+    VALIDATE_CALLBACK(callback)
+
+    std::lock_guard<std::mutex> lock(m_observeLock);
+    if (m_observeState)
+    {
+        OIC_LOG(ERROR, TAG, "Resource is already being observed!");
+        SIM_LOG(ILogger::ERROR, "[URI: " << getURI() << "] Resource is already being observed!")
+
+        throw SimulatorException(SIMULATOR_ERROR, "Resource is already being observed!");
+    }
+
+    OC::ObserveCallback observeCallback = std::bind(
+            [](const OC::HeaderOptions & headerOptions, const OC::OCRepresentation & ocRep,
+               const int errorCode, const int sqNum, std::string id, ObserveNotificationCallback callback)
+    {
+        SIM_LOG(ILogger::INFO, "Response received for OBSERVE request."
+                << "\n" << getPayloadString(ocRep))
+
+        SimulatorResourceModel resourceModel = SimulatorResourceModel::build(ocRep);
+        callback(id, static_cast<SimulatorResult>(errorCode), resourceModel, sqNum);
+    }, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4,
+    m_id, callback);
+
+    OC::ObserveType observeType = OC::ObserveType::Observe;
+    if (type == ObserveType::OBSERVE_ALL)
+        observeType = OC::ObserveType::ObserveAll;
+
+    try
+    {
+        OCStackResult ocResult = m_ocResource->observe(observeType, OC::QueryParamsMap(), observeCallback);
+        if (OC_STACK_OK != ocResult)
+            throw SimulatorException(static_cast<SimulatorResult>(ocResult), OC::OCException::reason(ocResult));
+
+        SIM_LOG(ILogger::INFO, "[URI: " << getURI() << "] Sent OBSERVE request.")
+    }
+    catch (OC::OCException &e)
+    {
+        throw SimulatorException(static_cast<SimulatorResult>(e.code()), e.reason());
+    }
+
+    m_observeState = true;
+}
+
+void SimulatorRemoteResourceImpl::cancelObserve()
+{
+    try
+    {
+        OCStackResult ocResult = m_ocResource->cancelObserve(OC::QualityOfService::HighQos);
+        if (OC_STACK_OK != ocResult)
+        {
+            OIC_LOG(ERROR, TAG, "Cancelling observe failed!");
+            SIM_LOG(ILogger::INFO, "[URI: " << getURI() << "] Sending OBSERVE cancel request failed!")
+
+            throw SimulatorException(static_cast<SimulatorResult>(ocResult),
+                                     OC::OCException::reason(ocResult));
+        }
+
+        SIM_LOG(ILogger::INFO, "[URI: " << getURI() << "] Sent OBSERVE cancel request.")
+    }
+    catch (OC::OCException &e)
+    {
+        throw SimulatorException(static_cast<SimulatorResult>(e.code()), e.reason());
+    }
+
+    std::lock_guard<std::mutex> lock(m_observeLock);
+    m_observeState = false;
+}
+
+void SimulatorRemoteResourceImpl::get(const GetResponseCallback &callback)
+{
+    VALIDATE_CALLBACK(callback)
+
+    SimulatorResult result = m_getRequestSender.send(std::bind(
+                                 &SimulatorRemoteResourceImpl::onResponseReceived, this, std::placeholders::_1,
+                                 std::placeholders::_2, std::placeholders::_3, callback));
+
+    if (SIMULATOR_OK != result)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to send GET request!");
+        SIM_LOG(ILogger::ERROR, "[URI: " << getURI() << "] Failed to send GET request!")
+
+        throw SimulatorException(result, "Failed to send GET request!");
+    }
+}
+
+void SimulatorRemoteResourceImpl::get(const std::map<std::string, std::string> &queryParams,
+                                      const GetResponseCallback &callback)
+{
+    VALIDATE_CALLBACK(callback)
+
+    SimulatorResult result = m_getRequestSender.send(queryParams, std::bind(
+                                 &SimulatorRemoteResourceImpl::onResponseReceived, this, std::placeholders::_1,
+                                 std::placeholders::_2, std::placeholders::_3, callback));
+
+    if (SIMULATOR_OK != result)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to send GET request!");
+        SIM_LOG(ILogger::ERROR, "[URI: " << getURI() << "] Failed to send GET request!")
+
+        throw SimulatorException(result, "Failed to send GET request!");
+    }
+}
+
+void SimulatorRemoteResourceImpl::get(const std::string &interfaceType,
+                                      const std::map<std::string, std::string> &queryParams,
+                                      const GetResponseCallback &callback)
+{
+    VALIDATE_CALLBACK(callback)
+
+    std::map<std::string, std::string> queryParamsCpy = queryParams;
+    if (!interfaceType.empty() && queryParamsCpy.end() == queryParamsCpy.find("if"))
+    {
+        queryParamsCpy["if"] = interfaceType;
+    }
+
+    SimulatorResult result = m_getRequestSender.send(queryParamsCpy, std::bind(
+                                 &SimulatorRemoteResourceImpl::onResponseReceived, this, std::placeholders::_1,
+                                 std::placeholders::_2, std::placeholders::_3, callback));
+
+    if (SIMULATOR_OK != result)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to send GET request!");
+        SIM_LOG(ILogger::ERROR, "[URI: " << getURI() << "] Failed to send GET request!")
+
+        throw SimulatorException(result, "Failed to send GET request!");
+    }
+}
+
+void SimulatorRemoteResourceImpl::put(const SimulatorResourceModel &representation,
+                                      const PutResponseCallback &callback)
+{
+    VALIDATE_CALLBACK(callback)
+
+    SimulatorResult result = m_putRequestSender.send(representation, std::bind(
+                                 &SimulatorRemoteResourceImpl::onResponseReceived, this, std::placeholders::_1,
+                                 std::placeholders::_2, std::placeholders::_3, callback));
+
+    if (SIMULATOR_OK != result)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to send PUT request!");
+        SIM_LOG(ILogger::ERROR, "[URI: " << getURI() << "] Failed to send PUT request!")
+
+        throw SimulatorException(result, "Failed to send PUT request!");
+    }
+}
+
+void SimulatorRemoteResourceImpl::put(const std::map<std::string, std::string> &queryParams,
+                                      const SimulatorResourceModel &representation,
+                                      const PutResponseCallback &callback)
+{
+    VALIDATE_CALLBACK(callback)
+
+    SimulatorResult result = m_putRequestSender.send(queryParams, representation, std::bind(
+                                 &SimulatorRemoteResourceImpl::onResponseReceived, this, std::placeholders::_1,
+                                 std::placeholders::_2, std::placeholders::_3, callback));
+
+    if (SIMULATOR_OK != result)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to send PUT request!");
+        SIM_LOG(ILogger::ERROR, "[URI: " << getURI() << "] Failed to send PUT request!")
+
+        throw SimulatorException(result, "Failed to send PUT request!");
+    }
+}
+
+void SimulatorRemoteResourceImpl::put(const std::string &interfaceType,
+                                      const std::map<std::string, std::string> &queryParams,
+                                      const SimulatorResourceModel &representation,
+                                      const PutResponseCallback &callback)
+{
+    VALIDATE_CALLBACK(callback)
+
+    std::map<std::string, std::string> queryParamsCpy = queryParams;
+    if (!interfaceType.empty() && queryParamsCpy.end() == queryParamsCpy.find("if"))
+    {
+        queryParamsCpy["if"] = interfaceType;
+    }
+
+    SimulatorResult result = m_putRequestSender.send(queryParamsCpy, representation, std::bind(
+                                 &SimulatorRemoteResourceImpl::onResponseReceived, this, std::placeholders::_1,
+                                 std::placeholders::_2, std::placeholders::_3, callback));
+
+    if (SIMULATOR_OK != result)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to send PUT request!");
+        SIM_LOG(ILogger::ERROR, "[URI: " << getURI() << "] Failed to send PUT request!")
+
+        throw SimulatorException(result, "Failed to send PUT request!");
+    }
+}
+
+void SimulatorRemoteResourceImpl::post(const SimulatorResourceModel &representation,
+                                       const PostResponseCallback &callback)
+{
+    VALIDATE_CALLBACK(callback)
+
+    SimulatorResult result = m_postRequestSender.send(representation, std::bind(
+                                 &SimulatorRemoteResourceImpl::onResponseReceived, this, std::placeholders::_1,
+                                 std::placeholders::_2, std::placeholders::_3, callback));
+
+    if (SIMULATOR_OK != result)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to send POST request!");
+        SIM_LOG(ILogger::ERROR, "[URI: " << getURI() << "] Failed to send POST request!")
+
+        throw SimulatorException(result, "Failed to send POST request!");
+    }
+}
+
+void SimulatorRemoteResourceImpl::post(const std::map<std::string, std::string> &queryParams,
+                                       const SimulatorResourceModel &representation,
+                                       const PostResponseCallback &callback)
+{
+    VALIDATE_CALLBACK(callback)
+
+    SimulatorResult result = m_postRequestSender.send(queryParams, representation, std::bind(
+                                 &SimulatorRemoteResourceImpl::onResponseReceived, this, std::placeholders::_1,
+                                 std::placeholders::_2, std::placeholders::_3, callback));
+
+    if (SIMULATOR_OK != result)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to send POST request!");
+        SIM_LOG(ILogger::ERROR, "[URI: " << getURI() << "] Failed to send POST request!")
+
+        throw SimulatorException(result, "Failed to send POST request!");
+    }
+}
+
+void SimulatorRemoteResourceImpl::post(const std::string &interfaceType,
+                                       const std::map<std::string, std::string> &queryParams,
+                                       const SimulatorResourceModel &representation,
+                                       const PostResponseCallback &callback)
+{
+    VALIDATE_CALLBACK(callback)
+
+    std::map<std::string, std::string> queryParamsCpy = queryParams;
+    if (!interfaceType.empty() && queryParamsCpy.end() == queryParamsCpy.find("if"))
+    {
+        queryParamsCpy["if"] = interfaceType;
+    }
+
+    SimulatorResult result = m_postRequestSender.send(queryParamsCpy, representation, std::bind(
+                                 &SimulatorRemoteResourceImpl::onResponseReceived, this, std::placeholders::_1,
+                                 std::placeholders::_2, std::placeholders::_3, callback));
+
+    if (SIMULATOR_OK != result)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to send POST request!");
+        SIM_LOG(ILogger::ERROR, "[URI: " << getURI() << "] Failed to send POST request!")
+
+        throw SimulatorException(result, "Failed to send POST request!");
+    }
+}
+
+std::map<RequestType, SimulatorRequestModel>
+SimulatorRemoteResourceImpl::configure(const std::string &path)
+{
+    VALIDATE_INPUT(path.empty(), "Path is empty!")
+
+    try
+    {
+        std::shared_ptr<RAML::RamlParser> ramlParser =
+            std::make_shared<RAML::RamlParser>(path);
+        RAML::RamlPtr raml = ramlParser->getRamlPtr();
+
+        m_requestModels = RequestModelBuilder().build(raml, m_ocResource->uri());
+    }
+    catch (RAML::RamlException &e)
+    {
+        throw SimulatorException(SIMULATOR_ERROR, "Failed to configure resource!");
+    }
+
+    std::map<RequestType, SimulatorRequestModel> requestModels;
+    for (auto &requestModelEntry : m_requestModels)
+    {
+        RequestType requestType = requestTypeToEnum(requestModelEntry.first);
+        SimulatorRequestModel requestModel(requestType);
+        requestModel.setQueryParams((requestModelEntry.second)->getQueryParams());
+        requestModel.setRequestBodySchema((requestModelEntry.second)->getRequestRepSchema());
+
+        requestModels[requestType] = requestModel;
+    }
+
+    return requestModels;
+}
+
+int SimulatorRemoteResourceImpl::startAutoRequesting(RequestType type,
+        AutoRequestGenerationCallback callback)
+{
+    VALIDATE_CALLBACK(callback)
+
+    // Check if resource supports request type
+    std::string requestType = requestTypeToString(type);
+    if (m_requestModels.end() == m_requestModels.find(requestType))
+    {
+        OIC_LOG(ERROR, TAG, "Resource is not configured for this request type!");
+        throw NoSupportException("Resource is not configured for this request type!");
+    }
+
+    std::shared_ptr<RequestModel> requestModel = m_requestModels[requestType];
+    switch (type)
+    {
+        case RequestType::RQ_TYPE_GET:
+            return m_requestAutomationMngr.startOnGET(requestModel,
+                    std::bind(&SimulatorRemoteResourceImpl::onAutoRequestingState, this,
+                              std::placeholders::_1, std::placeholders::_2, callback));
+
+        case RequestType::RQ_TYPE_PUT:
+            return m_requestAutomationMngr.startOnPUT(requestModel,
+                    std::bind(&SimulatorRemoteResourceImpl::onAutoRequestingState, this,
+                              std::placeholders::_1, std::placeholders::_2, callback));
+
+        case RequestType::RQ_TYPE_POST:
+            return m_requestAutomationMngr.startOnPOST(requestModel,
+                    std::bind(&SimulatorRemoteResourceImpl::onAutoRequestingState, this,
+                              std::placeholders::_1, std::placeholders::_2, callback));
+
+        case RequestType::RQ_TYPE_DELETE:
+        default:
+            throw NoSupportException("Not implemented!");
+    }
+
+    return -1; // Code should not reach here
+}
+
+void SimulatorRemoteResourceImpl::stopAutoRequesting(int id)
+{
+    m_requestAutomationMngr.stop(id);
+}
+
+void SimulatorRemoteResourceImpl::onResponseReceived(SimulatorResult result,
+        const SimulatorResourceModel &resourceModel, const RequestInfo &reqInfo,
+        ResponseCallback callback)
+{
+    callback(m_id, result, resourceModel);
+}
+
+void SimulatorRemoteResourceImpl::onAutoRequestingState(int sessionId, OperationState state,
+        AutoRequestGenerationCallback callback)
+{
+    callback(m_id, sessionId, state);
+}
+
+SimulatorConnectivityType SimulatorRemoteResourceImpl::convertConnectivityType(
+    OCConnectivityType type) const
+{
+    switch (type)
+    {
+        case CT_ADAPTER_IP:
+            return SIMULATOR_CT_ADAPTER_IP;
+
+        case CT_IP_USE_V4:
+            return SIMULATOR_CT_IP_USE_V4 ;
+
+        case CT_IP_USE_V6:
+            return SIMULATOR_CT_IP_USE_V6;
+
+        case CT_ADAPTER_GATT_BTLE:
+            return SIMULATOR_CT_ADAPTER_GATT_BTLE;
+
+        case CT_ADAPTER_RFCOMM_BTEDR:
+            return SIMULATOR_CT_ADAPTER_RFCOMM_BTEDR;
+
+        default:
+            return SIMULATOR_CT_DEFAULT;
+    }
+}
diff --git a/service/simulator/src/client/simulator_remote_resource_impl.h b/service/simulator/src/client/simulator_remote_resource_impl.h
new file mode 100644 (file)
index 0000000..2e75ab0
--- /dev/null
@@ -0,0 +1,106 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file simulator_remote_resource_impl.h
+ *
+ * @brief This file provides internal implementation of simulator remote resource functionalities.
+ *
+ */
+
+#ifndef SIMULATOR_REMOTE_RESOURCE_IMPL_H_
+#define SIMULATOR_REMOTE_RESOURCE_IMPL_H_
+
+#include "simulator_remote_resource.h"
+#include "request_automation_manager.h"
+#include "RamlParser.h"
+#include "request_model.h"
+#include "request_sender.h"
+
+#include <mutex>
+
+class SimulatorRemoteResourceImpl : public SimulatorRemoteResource
+{
+    public:
+        SimulatorRemoteResourceImpl(const std::shared_ptr<OC::OCResource> &ocResource);
+        std::string getURI() const;
+        std::string getHost() const;
+        std::string getID() const;
+        SimulatorConnectivityType getConnectivityType() const;
+        std::vector < std::string > getResourceTypes() const;
+        std::vector < std::string > getInterface() const;
+        bool isObservable() const;
+
+        void observe(ObserveType type, ObserveNotificationCallback callback);
+        void cancelObserve();
+
+        void get(const GetResponseCallback &callback);
+        void get(const std::map<std::string, std::string> &queryParams,
+                 const GetResponseCallback &callback);
+        void get(const std::string &interfaceType,
+                 const std::map<std::string, std::string> &queryParams,
+                 const GetResponseCallback &callback);
+
+        void put(const SimulatorResourceModel &representation,
+                 const PutResponseCallback &callback);
+        void put(const std::map<std::string, std::string> &queryParams,
+                 const SimulatorResourceModel &representation,
+                 const PutResponseCallback &callback);
+        void put(const std::string &interfaceType,
+                 const std::map<std::string, std::string> &queryParams,
+                 const SimulatorResourceModel &representation,
+                 const PutResponseCallback &callback);
+
+        void post(const SimulatorResourceModel &resourceModel,
+                  const PostResponseCallback &callback);
+        void post(const std::map<std::string, std::string> &queryParams,
+                  const SimulatorResourceModel &representation,
+                  const PostResponseCallback &callback);
+        void post(const std::string &interfaceType,
+                  const std::map<std::string, std::string> &queryParams,
+                  const SimulatorResourceModel &representation,
+                  const PostResponseCallback &callback);
+
+        std::map<RequestType, SimulatorRequestModel> configure(
+            const std::string &path);
+        int startAutoRequesting(RequestType type, AutoRequestGenerationCallback callback);
+        void stopAutoRequesting(int id);
+
+    private:
+        void configure(const std::shared_ptr<RAML::Raml> &raml);
+        void onResponseReceived(SimulatorResult result, const SimulatorResourceModel &resourceModel,
+                                const RequestInfo &reqInfo, ResponseCallback callback);
+        void onAutoRequestingState(int sessionId, OperationState state,
+                                   AutoRequestGenerationCallback callback);
+        SimulatorConnectivityType convertConnectivityType(OCConnectivityType type) const;
+
+        std::string m_id;
+        std::mutex m_observeLock;
+        bool m_observeState;
+        GETRequestSender m_getRequestSender;
+        PUTRequestSender m_putRequestSender;
+        POSTRequestSender m_postRequestSender;
+
+        RequestAutomationMngr m_requestAutomationMngr;
+        std::unordered_map<std::string, std::shared_ptr<RequestModel>> m_requestModels;
+        std::shared_ptr<OC::OCResource> m_ocResource;
+};
+
+#endif
diff --git a/service/simulator/src/client/simulator_request_model.cpp b/service/simulator/src/client/simulator_request_model.cpp
new file mode 100644 (file)
index 0000000..ebc56c6
--- /dev/null
@@ -0,0 +1,55 @@
+/******************************************************************
+ *
+ * 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 "simulator_request_model.h"
+
+SimulatorRequestModel::SimulatorRequestModel()
+    : m_type(RequestType::RQ_TYPE_UNKNOWN),
+        m_reqBodySchema(nullptr) {}
+
+SimulatorRequestModel::SimulatorRequestModel(RequestType type)
+    : m_type(type) {}
+
+RequestType SimulatorRequestModel::getType() const
+{
+    return m_type;
+}
+
+std::map<std::string, std::vector<std::string>> SimulatorRequestModel::getQueryParams() const
+{
+    return m_queryParams;
+}
+
+std::shared_ptr<SimulatorResourceModelSchema> SimulatorRequestModel::getRequestBodySchema() const
+{
+    return m_reqBodySchema;
+}
+
+void SimulatorRequestModel::setQueryParams(
+    const std::map<std::string, std::vector<std::string>> &queryParams)
+{
+    m_queryParams = queryParams;
+}
+
+void SimulatorRequestModel::setRequestBodySchema(
+    const std::shared_ptr<SimulatorResourceModelSchema> &repSchema)
+{
+    m_reqBodySchema = repSchema;
+}
+
diff --git a/service/simulator/src/common/attribute_generator.cpp b/service/simulator/src/common/attribute_generator.cpp
new file mode 100644 (file)
index 0000000..50a18ca
--- /dev/null
@@ -0,0 +1,152 @@
+/******************************************************************
+ *
+ * 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 "attribute_generator.h"
+
+AttributeGenerator::AttributeGenerator(const SimulatorResourceAttribute &attribute)
+{
+    m_name = attribute.getName();
+    if (attribute.getProperty())
+    {
+        m_valueGen = AttributeValueGenFactory::create(attribute.getProperty());
+    }
+}
+
+AttributeGenerator::AttributeGenerator(const std::string &name,
+                                       const std::shared_ptr<AttributeProperty> &property)
+    :   m_name(name)
+{
+    if (property)
+    {
+        m_valueGen = AttributeValueGenFactory::create(property);
+    }
+}
+
+bool AttributeGenerator::hasNext()
+{
+    if (m_valueGen)
+        return m_valueGen->hasNext();
+    return false;
+}
+
+bool AttributeGenerator::next(SimulatorResourceAttribute &attribute)
+{
+    if (!hasNext())
+        return false;
+
+    if (m_valueGen)
+    {
+        attribute.setName(m_name);
+        attribute.setValue(m_valueGen->next());
+        return true;
+    }
+
+    return false;
+}
+
+SimulatorResourceAttribute AttributeGenerator::current()
+{
+    if (m_valueGen)
+    {
+        return SimulatorResourceAttribute(m_name, m_valueGen->value());
+    }
+
+    return SimulatorResourceAttribute(m_name);
+}
+
+void AttributeGenerator::reset()
+{
+    if (m_valueGen)
+        m_valueGen->reset();
+}
+
+AttributeCombinationGen::AttributeCombinationGen(
+    const std::vector<SimulatorResourceAttribute> &attributes)
+{
+    for (auto &attr : attributes)
+    {
+        AttributeGenerator attrGen(attr);
+        m_attrGenList.push_back(attr);
+        m_resModel.add(attr.getName(), attr.getValue());
+    }
+
+    m_index = -1;
+}
+
+bool AttributeCombinationGen::next(SimulatorResourceModel &resModel)
+{
+    if (!m_attrGenList.size())
+    {
+        return false;
+    }
+
+    std::lock_guard<std::mutex> lock(m_lock);
+
+    // This block will execute for only first time
+    if (-1 == m_index)
+    {
+        for (size_t index = 0; index < m_attrGenList.size(); index++)
+        {
+            // Add the attribute on resource model
+            updateAttributeInModel(index);
+        }
+
+        m_index = m_attrGenList.size() - 1;
+        resModel = m_resModel;
+        return true;
+    }
+
+    // Get the next attribute from statck top element
+    if (m_attrGenList[m_index].hasNext())
+    {
+        updateAttributeInModel(m_index);
+        resModel = m_resModel;
+    }
+    else
+    {
+        for (int index = m_index; index >= 0; index--)
+        {
+            if (!m_attrGenList[index].hasNext())
+            {
+                if (!index)
+                    return false;
+
+                m_attrGenList[index].reset();
+                updateAttributeInModel(index);
+            }
+            else
+            {
+                updateAttributeInModel(index);
+                break;
+            }
+        }
+
+        resModel = m_resModel;
+    }
+
+    return true;
+}
+
+void AttributeCombinationGen::updateAttributeInModel(int index)
+{
+    SimulatorResourceAttribute attribute;
+    if (m_attrGenList[index].next(attribute))
+        m_resModel.update(attribute.getName(), attribute.getValue());
+}
diff --git a/service/simulator/src/common/attribute_generator.h b/service/simulator/src/common/attribute_generator.h
new file mode 100644 (file)
index 0000000..3c45cff
--- /dev/null
@@ -0,0 +1,61 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_ATTRIBUTE_GENERATOR_H_
+#define SIMULATOR_ATTRIBUTE_GENERATOR_H_
+
+#include <vector>
+#include "simulator_resource_model.h"
+#include "attribute_value_generator.h"
+
+class AttributeGenerator
+{
+    public:
+        AttributeGenerator(const SimulatorResourceAttribute &attribute);
+        AttributeGenerator(const std::string &name,
+                           const std::shared_ptr<AttributeProperty> &property);
+
+        bool hasNext();
+        bool next(SimulatorResourceAttribute &attribute);
+        SimulatorResourceAttribute current();
+        void reset();
+
+    private:
+        std::string m_name;
+        std::unique_ptr<AttributeValueGen> m_valueGen;
+};
+
+class AttributeCombinationGen
+{
+    public:
+        AttributeCombinationGen(const std::vector<SimulatorResourceAttribute> &attributes);
+        bool next(SimulatorResourceModel &resModel);
+
+    private:
+        void updateAttributeInModel(int index);
+
+        std::mutex m_lock;
+        std::vector<AttributeGenerator> m_attrGenList;
+        int m_index;
+        SimulatorResourceModel m_resModel;
+};
+
+#endif
+
diff --git a/service/simulator/src/common/attribute_value_generator.cpp b/service/simulator/src/common/attribute_value_generator.cpp
new file mode 100644 (file)
index 0000000..188b615
--- /dev/null
@@ -0,0 +1,84 @@
+/******************************************************************
+ *
+ * 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 "attribute_value_generator.h"
+
+std::unique_ptr<AttributeValueGen> AttributeValueGenFactory::create(
+    const std::shared_ptr<AttributeProperty> &property)
+{
+    if (!property)
+        return nullptr;
+
+    if (property->isInteger())
+    {
+        std::shared_ptr<IntegerProperty> intProperty = property->asInteger();
+        if (intProperty->hasRange())
+        {
+            int min = 0;
+            int max = 0;
+            intProperty->getRange(min, max);
+            return std::unique_ptr<AttributeValueGen>(
+                       new RangeValueGen<int>(min, max));
+        }
+        else if (intProperty->hasValues())
+        {
+            std::vector<int> values;
+            intProperty->getValues(values);
+            return std::unique_ptr<AttributeValueGen>(
+                       new ValuesSetGen<int>(values));
+        }
+    }
+    else if (property->isDouble())
+    {
+        std::shared_ptr<DoubleProperty> doubleProperty = property->asDouble();
+        if (doubleProperty->hasRange())
+        {
+            double min = 0.0;
+            double max = 0.0;
+            doubleProperty->getRange(min, max);
+            return std::unique_ptr<AttributeValueGen>(
+                       new RangeValueGen<double>(min, max));
+        }
+        else if (doubleProperty->hasValues())
+        {
+            std::vector<double> values;
+            doubleProperty->getValues(values);
+            return std::unique_ptr<AttributeValueGen>(
+                       new ValuesSetGen<double>(values));
+        }
+    }
+    else if (property->isBoolean())
+    {
+        return std::unique_ptr<AttributeValueGen>(new ValuesSetGen<bool>({true, false}));
+    }
+    else if (property->isString())
+    {
+        std::shared_ptr<StringProperty> stringProperty = property->asString();
+        if (stringProperty->hasValues())
+        {
+            std::vector<std::string> values;
+            stringProperty->getValues(values);
+            return std::unique_ptr<AttributeValueGen>(
+                       new ValuesSetGen<std::string>(values));
+        }
+    }
+
+    return nullptr;
+}
diff --git a/service/simulator/src/common/attribute_value_generator.h b/service/simulator/src/common/attribute_value_generator.h
new file mode 100644 (file)
index 0000000..e55af62
--- /dev/null
@@ -0,0 +1,107 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_ATTRIBUTE_VALUE_GENERATOR_H_
+#define SIMULATOR_ATTRIBUTE_VALUE_GENERATOR_H_
+
+#include "simulator_resource_model_schema.h"
+
+class AttributeValueGen
+{
+    public:
+        virtual bool hasNext() = 0;
+        virtual AttributeValueVariant next() = 0;
+        virtual AttributeValueVariant value() = 0;
+        virtual void reset() = 0;
+};
+
+template <typename TYPE>
+class RangeValueGen : public AttributeValueGen
+{
+    private:
+        TYPE m_min;
+        TYPE m_max;
+        TYPE m_cur;
+
+    public:
+        RangeValueGen(TYPE min, TYPE max) : m_min(min), m_max(max), m_cur(min) {}
+
+        bool hasNext()
+        {
+            return (m_cur <= m_max);
+        }
+
+        AttributeValueVariant next()
+        {
+            TYPE value = m_cur;
+            m_cur++;
+            return value;
+        }
+
+        AttributeValueVariant value()
+        {
+            return m_cur - 1;
+        }
+
+        void reset()
+        {
+            m_cur = m_min;
+        }
+};
+
+template <typename TYPE>
+class ValuesSetGen : public AttributeValueGen
+{
+    private:
+        std::vector<TYPE> m_values;
+        size_t m_index;
+
+    public:
+        ValuesSetGen(const std::vector<TYPE> &values) : m_values(values), m_index(0) {}
+
+        bool hasNext()
+        {
+            return (m_index < m_values.size());
+        }
+
+        AttributeValueVariant next()
+        {
+            return m_values[m_index++];
+        }
+
+        AttributeValueVariant value()
+        {
+            return m_values[m_index - 1];
+        }
+
+        void reset()
+        {
+            m_index = 0;
+        }
+};
+
+class AttributeValueGenFactory
+{
+    public:
+        static std::unique_ptr<AttributeValueGen> create(
+            const std::shared_ptr<AttributeProperty> &property);
+};
+
+#endif
index 4a522c2..b277b1a 100644 (file)
 #include "request_model.h"
 #include "logger.h"
 
-RequestModel::RequestModel(RequestType type) : m_type(type) {}
+RequestModel::RequestModel(const std::string &type)
+    : m_type(type) {}
 
-RequestType RequestModel::type() const
+std::string RequestModel::getType() const
 {
     return m_type;
 }
@@ -43,13 +44,25 @@ std::vector<std::string> RequestModel::getQueryParams(const std::string &key)
     return std::vector<std::string>();
 }
 
-void RequestModel::setQueryParams(
-    const SupportedQueryParams &queryParams)
+std::shared_ptr<SimulatorResourceModelSchema> RequestModel::getRequestRepSchema()
 {
-    m_queryParams = queryParams;
+    return m_repSchema;
+}
+
+ResponseModelSP RequestModel::getResponseModel(int code)
+{
+    if (m_responseList.end() != m_responseList.find(code))
+        return m_responseList[code];
+
+    return nullptr;
+}
+
+void RequestModel::setType(const std::string &type)
+{
+    m_type = type;
 }
 
-void RequestModel::addQueryParams(const std::string &key,
+void RequestModel::setQueryParams(const std::string &key,
                                   const std::vector<std::string> &values)
 {
     if (0 != values.size())
@@ -61,29 +74,25 @@ void RequestModel::addQueryParam(const std::string &key, const std::string &valu
     m_queryParams[key].push_back(value);
 }
 
-void RequestModel::addResponseModel(int code, ResponseModelSP &responseModel)
+void RequestModel::setResponseModel(int code, ResponseModelSP &responseModel)
 {
-    if (!responseModel)
+    if (responseModel)
         m_responseList[code] = responseModel;
 }
 
-void RequestModel::setRepSchema(SimulatorResourceModelSP &repSchema)
+void RequestModel::setRequestBodyModel(const std::shared_ptr<SimulatorResourceModelSchema>
+                                       &repSchema)
 {
     m_repSchema = repSchema;
 }
 
-SimulatorResourceModelSP RequestModel::getRepSchema()
-{
-    return m_repSchema;
-}
-
-SimulatorResult RequestModel::validateResponse(int responseCode, const OC::OCRepresentation &rep)
+SimulatorResult RequestModel::validateResponse(int code, const SimulatorResourceModel &resModel)
 {
-    if (m_responseList.end() == m_responseList.find(responseCode))
+    if (m_responseList.end() == m_responseList.find(code))
     {
         return SIMULATOR_INVALID_RESPONSE_CODE;
     }
 
-    return m_responseList[responseCode]->verifyResponse(rep);
+    return m_responseList[code]->verifyResponse(resModel);
 }
 
index e47c82e..c2223b9 100644 (file)
 #ifndef REQUEST_MODEL_H_
 #define REQUEST_MODEL_H_
 
-#include "simulator_client_types.h"
-#include "simulator_resource_model.h"
+#include "simulator_resource_model_schema.h"
 #include "response_model.h"
-#include "Raml.h"
 
 typedef std::map<std::string, std::vector<std::string>> SupportedQueryParams;
 
@@ -34,24 +32,26 @@ class RequestModel
     public:
         friend class RequestModelBuilder;
 
-        RequestType type() const;
+        std::string getType() const;
         SupportedQueryParams getQueryParams();
         std::vector<std::string> getQueryParams(const std::string &key);
-        SimulatorResourceModelSP getRepSchema();
-        SimulatorResult validateResponse(int responseCode, const OC::OCRepresentation &rep);
+        std::shared_ptr<SimulatorResourceModelSchema> getRequestRepSchema();
+        ResponseModelSP getResponseModel(int code);
+        SimulatorResult validateResponse(int code, const SimulatorResourceModel &resModel);
 
     private:
-        RequestModel(RequestType type);
-        void setQueryParams(const SupportedQueryParams &queryParams);
-        void addQueryParams(const std::string &key, const std::vector<std::string> &values);
+        RequestModel() = default;
+        RequestModel(const std::string &type);
+        void setType(const std::string &type);
+        void setQueryParams(const std::string &key, const std::vector<std::string> &values);
         void addQueryParam(const std::string &key, const std::string &value);
-        void addResponseModel(int code, ResponseModelSP &responseModel);
-        void setRepSchema(SimulatorResourceModelSP &repSchema);
+        void setResponseModel(int code, ResponseModelSP &responseModel);
+        void setRequestBodyModel(const std::shared_ptr<SimulatorResourceModelSchema> &repSchema);
 
-        RequestType m_type;
+        std::string m_type;
         SupportedQueryParams m_queryParams;
         std::map<int, ResponseModelSP> m_responseList;
-        SimulatorResourceModelSP m_repSchema;
+        std::shared_ptr<SimulatorResourceModelSchema> m_repSchema;
 };
 
 typedef std::shared_ptr<RequestModel> RequestModelSP;
old mode 100644 (file)
new mode 100755 (executable)
index 9a20021..ff62586
  ******************************************************************/
 
 #include "request_model_builder.h"
+#include "resource_model_schema_builder.h"
 #include "logger.h"
+#include "Raml.h"
 
 #define TAG "REQ_MODEL_BUILDER"
 
-RequestModelBuilder::RequestModelBuilder(std::shared_ptr<RAML::Raml> &raml)
-    : m_raml (raml) {}
+static std::string getRequestType(RAML::ActionType actionType)
+{
+    switch (actionType)
+    {
+        case RAML::ActionType::GET:
+            return "GET";
+        case RAML::ActionType::PUT:
+            return "PUT";
+        case RAML::ActionType::POST:
+            return "POST";
+        case RAML::ActionType::DELETE:
+            return "DELETE";
+    }
+
+    return ""; // This code should never reach
+}
 
-std::map<RequestType, RequestModelSP> RequestModelBuilder::build(const std::string &uri)
+std::unordered_map<std::string, RequestModelSP> RequestModelBuilder::build(
+    const std::shared_ptr<RAML::Raml> &raml, const std::string &uri)
 {
-    std::map<RequestType, RequestModelSP> modelList;
-    if (!m_raml)
+    std::unordered_map<std::string, RequestModelSP> requestModels;
+
+    if (!raml)
     {
-        return modelList;
+        OIC_LOG(ERROR, TAG, "Raml pointer is null!");
+        return requestModels;
     }
 
-    for (auto  & resource : m_raml->getResources())
+    for (auto &resource : raml->getResources())
     {
         // Pick the resource based on the resource uri.
         if (std::string::npos == uri.find((resource.second)->getResourceUri()))
             continue;
 
-        // Construcut Request and Response Model from RAML::Action
-        for (auto  & action :  (resource.second)->getActions())
+        // Construct Request and Response Model from RAML::Action
+        for (auto &action :  (resource.second)->getActions())
         {
             RequestModelSP requestModel = createRequestModel(action.second);
             if (requestModel)
-                modelList[requestModel->type()] = requestModel;
+            {
+                requestModels[requestModel->getType()] = requestModel;
+            }
         }
+
+        break;
     }
 
-    return modelList;
+    return requestModels;
 }
 
-RequestModelSP RequestModelBuilder::createRequestModel(const RAML::ActionPtr &action)
+std::unordered_map<std::string, RequestModelSP> RequestModelBuilder::build(
+    const std::shared_ptr<RAML::RamlResource> &resource)
 {
-    OC_LOG(DEBUG, TAG, "Creating request model");
+    std::unordered_map<std::string, RequestModelSP> requestModels;
+
+    if (!resource)
+    {
+        OIC_LOG(ERROR, TAG, "Resource pointer is null!");
+        return requestModels;
+    }
+
+    // Construct Request and Response Model from RAML::Action
+    for (auto &action :  resource->getActions())
+    {
+        RequestModelSP requestModel = createRequestModel(action.second);
+        if (requestModel)
+        {
+            requestModels[requestModel->getType()] = requestModel;
+        }
+    }
 
+    return requestModels;
+}
+
+RequestModelSP RequestModelBuilder::createRequestModel(const RAML::ActionPtr &action)
+{
     // Validate the action type. Only GET, PUT, POST and DELETE are supported.
     RAML::ActionType actionType = action->getType();
     if (actionType != RAML::ActionType::GET
@@ -63,35 +108,34 @@ RequestModelSP RequestModelBuilder::createRequestModel(const RAML::ActionPtr &ac
         && actionType != RAML::ActionType::POST
         && actionType != RAML::ActionType::DELETE)
     {
-        OC_LOG(ERROR, TAG, "Failed to create request model as it is of unknown type!");
+        OIC_LOG(ERROR, TAG, "Request model is of unknown type!");
         return nullptr;
     }
 
-    // Construct RequestModel
     RequestModelSP requestModel(new RequestModel(getRequestType(actionType)));
 
     // Get the allowed query parameters of the request
-    for (auto & qpEntry : action->getQueryParameters())
+    for (auto &qpEntry : action->getQueryParameters())
     {
-        for (auto & value :  (qpEntry.second)->getEnumeration())
+        for (auto &value :  (qpEntry.second)->getEnumeration())
         {
             requestModel->addQueryParam(qpEntry.first, value);
         }
     }
 
+    // Set the request body schema
     RAML::RequestResponseBodyPtr requestBody = action->getRequestBody("application/json");
-    SimulatorResourceModelSP repSchema = createRepSchema(requestBody);
-    requestModel->setRepSchema(repSchema);
+    requestModel->setRequestBodyModel(createRepSchema(requestBody));
 
-    // Corresponsing responses
-    for (auto  responseEntry :  action->getResponses())
+    // Corresponsing responses for this request
+    for (auto   &responseEntry :  action->getResponses())
     {
         std::string codeStr = responseEntry.first;
         int code = boost::lexical_cast<int>(codeStr);
         ResponseModelSP responseModel = createResponseModel(code, responseEntry.second);
         if (nullptr != responseModel)
         {
-            requestModel->addResponseModel(code, responseModel);
+            requestModel->setResponseModel(code, responseModel);
         }
     }
 
@@ -103,120 +147,19 @@ ResponseModelSP RequestModelBuilder::createResponseModel(int code,
 {
     ResponseModelSP responseModel(new ResponseModel(code));
     RAML::RequestResponseBodyPtr responseBody = response->getResponseBody("application/json");
-    SimulatorResourceModelSP repSchema = createRepSchema(responseBody);
-    responseModel->setRepSchema(repSchema);
+    responseModel->setResponseBodyModel(createRepSchema(responseBody));
     return responseModel;
 }
 
-SimulatorResourceModelSP RequestModelBuilder::createRepSchema(const RAML::RequestResponseBodyPtr
-        &rep)
+std::shared_ptr<SimulatorResourceModelSchema> RequestModelBuilder::createRepSchema(
+    const RAML::RequestResponseBodyPtr &responseBody)
 {
-    if (!rep)
-    {
-        return nullptr;
-    }
-    RAML::SchemaPtr schema = rep->getSchema();
-    if (!schema)
+    if (!responseBody)
     {
+        OIC_LOG(ERROR, TAG, "Response body is null!");
         return nullptr;
     }
 
-    RAML::JsonSchemaPtr properties = schema->getProperties();
-    if (!properties || 0 == properties->getProperties().size())
-        return nullptr;
-
-    SimulatorResourceModelSP repSchema = std::make_shared<SimulatorResourceModel>();
-    for (auto & propertyEntry : properties->getProperties())
-    {
-        std::string propName = propertyEntry.second->getName();
-        if ("rt" == propName || "resourceType" == propName || "if" == propName
-            || "p" == propName || "n" == propName || "id" == propName)
-            continue;
-
-        int valueType = propertyEntry.second->getValueType();
-        switch (valueType)
-        {
-            case 0: // Integer
-                {
-                    // Add the attribute with value
-                    repSchema->addAttribute(propertyEntry.second->getName(), propertyEntry.second->getValue<int>());
-
-                    // Set the range
-                    int min, max, multipleof;
-                    propertyEntry.second->getRange(min, max, multipleof);
-                    repSchema->setRange(propertyEntry.second->getName(), min, max);
-                }
-                break;
-
-            case 1: // Double
-                {
-                    // Add the attribute with value
-                    repSchema->addAttribute(propertyEntry.second->getName(), propertyEntry.second->getValue<double>());
-
-                    std::vector<SimulatorResourceModel::Attribute::ValueVariant> propValues =
-                        propertyEntry.second->getAllowedValues();
-
-                    // TODO: Use RAML function once available
-                    if (0 < propertyEntry.second->getAllowedValuesSize())
-                    {
-                        std::vector<double> allowedValues;
-                        for (auto & propValue : propValues)
-                        {
-                            double value = boost::lexical_cast<double> (propValue);
-                            allowedValues.push_back(value);
-                        }
-                        repSchema->setAllowedValues(propertyEntry.second->getName(), allowedValues);
-                    }
-                }
-                break;
-
-            case 2: // Boolean
-                {
-                    // Add the attribute with value
-                    repSchema->addAttribute(propertyEntry.second->getName(), propertyEntry.second->getValue<bool>());
-                }
-                break;
-
-            case 3: // String
-                {
-                    // Add the attribute with value
-                    repSchema->addAttribute(propertyEntry.second->getName(),
-                                            propertyEntry.second->getValue<std::string>());
-
-                    std::vector<SimulatorResourceModel::Attribute::ValueVariant> propValues =
-                        propertyEntry.second->getAllowedValues();
-
-                    // TODO: Use RAML function once available
-                    if (0 < propertyEntry.second->getAllowedValuesSize())
-                    {
-                        std::vector<std::string> allowedValues;
-                        for (auto & propValue : propValues)
-                        {
-                            std::string value = boost::lexical_cast<std::string> (propValue);
-                            allowedValues.push_back(value);
-                        }
-                        repSchema->setAllowedValues(propertyEntry.second->getName(), allowedValues);
-                    }
-                }
-                break;
-        }
-    }
-
-    return repSchema;
-}
-
-RequestType RequestModelBuilder::getRequestType(RAML::ActionType actionType)
-{
-    switch (actionType)
-    {
-        case RAML::ActionType::GET:
-            return RequestType::RQ_TYPE_GET;
-        case RAML::ActionType::PUT:
-            return RequestType::RQ_TYPE_PUT;
-        case RAML::ActionType::POST:
-            return RequestType::RQ_TYPE_POST;
-        case RAML::ActionType::DELETE:
-            return RequestType::RQ_TYPE_DELETE;
-    }
+    return ResourceModelSchemaBuilder(responseBody).build();
 }
 
old mode 100644 (file)
new mode 100755 (executable)
index f212252..0bfbf1f
  *
  ******************************************************************/
 
-#ifndef REQUEST_MODEL_BUILDER_H_
-#define REQUEST_MODEL_BUILDER_H_
+#ifndef SIMULATOR_REQUEST_MODEL_BUILDER_H_
+#define SIMULATOR_REQUEST_MODEL_BUILDER_H_
 
 #include "request_model.h"
 #include "response_model.h"
 
+namespace RAML
+{
+    class Raml;
+    class RamlResource;
+    class Action;
+    class Response;
+    class RequestResponseBody;
+}
+
 class RequestModelBuilder
 {
     public:
-        RequestModelBuilder(std::shared_ptr<RAML::Raml> &raml);
-        std::map<RequestType, RequestModelSP> build(const std::string &uri);
+        std::unordered_map<std::string, RequestModelSP> build(
+            const std::shared_ptr<RAML::Raml> &raml, const std::string &uri);
+        std::unordered_map<std::string, RequestModelSP> build(
+            const std::shared_ptr<RAML::RamlResource> &resource);
 
     private:
-        RequestModelSP createRequestModel(const RAML::ActionPtr &action);
-        ResponseModelSP createResponseModel(int code, const RAML::ResponsePtr &response);
-        SimulatorResourceModelSP createRepSchema(const RAML::RequestResponseBodyPtr &rep);
-        RequestType getRequestType(RAML::ActionType actionType);
-
-        std::shared_ptr<RAML::Raml> m_raml;
+        RequestModelSP createRequestModel(const std::shared_ptr<RAML::Action> &action);
+        ResponseModelSP createResponseModel(int code,
+                                            const std::shared_ptr<RAML::Response> &response);
+        std::shared_ptr<SimulatorResourceModelSchema> createRepSchema(
+            const std::shared_ptr<RAML::RequestResponseBody> &rep);
 };
 
 #endif
diff --git a/service/simulator/src/common/resource_model_schema_builder.cpp b/service/simulator/src/common/resource_model_schema_builder.cpp
new file mode 100644 (file)
index 0000000..d584a2d
--- /dev/null
@@ -0,0 +1,329 @@
+/******************************************************************
+ *
+ * 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 "resource_model_schema_builder.h"
+#include "simulator_resource_model_schema.h"
+#include "Raml.h"
+#include "Properties.h"
+#include "logger.h"
+
+#define TAG "RES_MODEL_BUILDER"
+
+ResourceModelSchemaBuilder::ResourceModelSchemaBuilder(
+    const std::shared_ptr<RAML::RequestResponseBody> &ramlSchema)
+    :   m_ramlSchema (ramlSchema) {}
+
+std::shared_ptr<SimulatorResourceModelSchema> ResourceModelSchemaBuilder::build()
+{
+    if (!m_ramlSchema)
+    {
+        OIC_LOG(ERROR, TAG, "RAML schema pointer is null!");
+        return nullptr;
+    }
+
+    std::shared_ptr<SimulatorResourceModelSchema> modelSchema =
+        SimulatorResourceModelSchema::build();
+
+    auto jsonSchema = m_ramlSchema->getSchema()->getProperties();
+    for (auto &propertyElement : jsonSchema->getProperties())
+    {
+        auto property = propertyElement.second;
+        auto attributeProperty = buildAttribute(property);
+
+        if (!attributeProperty)
+            return nullptr;
+
+        modelSchema->add(property->getName(), attributeProperty);
+    }
+
+    return modelSchema;
+}
+
+std::shared_ptr<AttributeProperty> ResourceModelSchemaBuilder::buildAttribute(
+    const std::shared_ptr<RAML::Properties> &property)
+{
+    switch (property->getType().type())
+    {
+        case RAML::VariantType::INTEGER:
+            return buildIntegerAttribute(property);
+
+        case RAML::VariantType::DOUBLE:
+            return buildDoubleAttribute(property);
+
+        case RAML::VariantType::BOOLEAN:
+            return buildBooleanAttribute(property);
+
+        case RAML::VariantType::STRING:
+            return buildStringAttribute(property);
+
+        case RAML::VariantType::PROPERTY:
+            return buildArrayAttribute(property);
+
+        case RAML::VariantType::ARRAY:
+            return buildModelArrayAttribute(property);
+
+        case RAML::VariantType::OBJECT:
+            return buildModelAttribute(property);
+
+        default:
+            OIC_LOG(ERROR, TAG, "Unknown type!");
+            return nullptr;
+    }
+
+    return nullptr;
+}
+
+std::shared_ptr<IntegerProperty> ResourceModelSchemaBuilder::buildIntegerAttribute(
+    const std::shared_ptr<RAML::Properties> &property)
+{
+    std::shared_ptr<IntegerProperty> integerProperty = IntegerProperty::build();
+
+    // Set Default value
+    if (property->isDefaultValue())
+    {
+        integerProperty->setDefaultValue(property->getValue<int>());
+    }
+
+    // Set the Range/Enum property
+    for (auto &valueProperty : property->getValueProperties())
+    {
+        if (RAML::ValueProperty::Type::RANGE == valueProperty->type())
+        {
+            integerProperty->setRange(valueProperty->min(), valueProperty->max());
+            break;
+        }
+        else if (RAML::ValueProperty::Type::VALUE_SET == valueProperty->type())
+        {
+            std::vector<int> values;
+            for (auto &value : valueProperty->valueSet())
+                values.push_back(boost::get<int>(value));
+            integerProperty->setValues(values);
+            break;
+        }
+    }
+
+    return integerProperty;
+}
+
+std::shared_ptr<DoubleProperty> ResourceModelSchemaBuilder::buildDoubleAttribute(
+    const std::shared_ptr<RAML::Properties> &property)
+{
+    std::shared_ptr<DoubleProperty> doubleProperty = DoubleProperty::build();
+
+    // Set Default value
+    if (property->isDefaultValue())
+    {
+        doubleProperty->setDefaultValue(property->getValue<double>());
+    }
+
+    // Set the Range/Enum property
+    for (auto &valueProperty : property->getValueProperties())
+    {
+        if (RAML::ValueProperty::Type::RANGE == valueProperty->type())
+        {
+            doubleProperty->setRange(valueProperty->min(), valueProperty->max());
+            break;
+        }
+        else if (RAML::ValueProperty::Type::VALUE_SET == valueProperty->type())
+        {
+            std::vector<double> values;
+            for (auto &value : valueProperty->valueSet())
+                values.push_back(boost::get<double>(value));
+            doubleProperty->setValues(values);
+            break;
+        }
+    }
+
+    return doubleProperty;
+}
+
+std::shared_ptr<BooleanProperty> ResourceModelSchemaBuilder::buildBooleanAttribute(
+    const std::shared_ptr<RAML::Properties> &property)
+{
+    std::shared_ptr<BooleanProperty> boolProperty = BooleanProperty::build();
+
+    // Set Default value
+    if (property->isDefaultValue())
+    {
+        boolProperty->setDefaultValue(property->getValue<bool>());
+    }
+
+    return boolProperty;
+}
+
+std::shared_ptr<StringProperty> ResourceModelSchemaBuilder::buildStringAttribute(
+    const std::shared_ptr<RAML::Properties> &property)
+{
+    std::shared_ptr<StringProperty> stringProperty = StringProperty::build();
+
+    // Set Default value
+    if (property->isDefaultValue())
+    {
+        stringProperty->setDefaultValue(property->getValue<std::string>());
+    }
+
+    // Set the Range/Enum property
+    for (auto &valueProperty : property->getValueProperties())
+    {
+        if (RAML::ValueProperty::Type::RANGE == valueProperty->type())
+        {
+            stringProperty->setRange(valueProperty->min(), valueProperty->max());
+            break;
+        }
+        else if (RAML::ValueProperty::Type::VALUE_SET == valueProperty->type())
+        {
+            std::vector<std::string> values;
+            for (auto &value : valueProperty->valueSet())
+                values.push_back(boost::get<std::string>(value));
+            stringProperty->setValues(values);
+            break;
+        }
+    }
+
+    return stringProperty;
+}
+
+std::shared_ptr<ArrayProperty> ResourceModelSchemaBuilder::buildArrayAttribute(
+    const std::shared_ptr<RAML::Properties> &property)
+{
+    std::shared_ptr<ArrayProperty> arrayProperty = ArrayProperty::build();
+
+    auto arrayAttribute = boost::get<RAML::Properties>(property->getValue());
+    switch (arrayAttribute.getType().type())
+    {
+        case RAML::VariantType::INTEGER:
+            {
+                std::shared_ptr<RAML::Properties> elementAttribute =
+                    std::make_shared<RAML::Properties>(arrayAttribute);
+
+                std::shared_ptr<IntegerProperty> elementProperty =
+                    buildIntegerAttribute(elementAttribute);
+
+                setArrayProperties(property, arrayProperty);
+                arrayProperty->setElementProperty(elementProperty);
+            }
+            break;
+
+        case RAML::VariantType::DOUBLE :
+            {
+                std::shared_ptr<RAML::Properties> elementAttribute =
+                    std::make_shared<RAML::Properties>(arrayAttribute);
+
+                std::shared_ptr<DoubleProperty> elementProperty =
+                    buildDoubleAttribute(elementAttribute);
+
+                setArrayProperties(property, arrayProperty);
+                arrayProperty->setElementProperty(elementProperty);
+            }
+            break;
+
+        case RAML::VariantType::BOOLEAN :
+            {
+                std::shared_ptr<RAML::Properties> elementAttribute =
+                    std::make_shared<RAML::Properties>(arrayAttribute);
+
+                std::shared_ptr<BooleanProperty> elementProperty =
+                    buildBooleanAttribute(elementAttribute);
+
+                setArrayProperties(property, arrayProperty);
+                arrayProperty->setElementProperty(elementProperty);
+            }
+            break;
+
+        case RAML::VariantType::STRING :
+            {
+                std::shared_ptr<RAML::Properties> elementAttribute =
+                    std::make_shared<RAML::Properties>(arrayAttribute);
+
+                std::shared_ptr<StringProperty> elementProperty =
+                    buildStringAttribute(elementAttribute);
+
+                setArrayProperties(property, arrayProperty);
+                arrayProperty->setElementProperty(elementProperty);
+            }
+            break;
+
+        default:
+            OIC_LOG(ERROR, TAG, "Unknown array element type!");
+            return nullptr;
+    }
+
+    return arrayProperty;
+}
+
+std::shared_ptr<ArrayProperty> ResourceModelSchemaBuilder::buildModelArrayAttribute(
+    const std::shared_ptr<RAML::Properties> &property)
+{
+    std::vector<RAML::Properties> attributes =
+        boost::get<std::vector<RAML::Properties> >(property->getValue());
+
+    std::shared_ptr<ModelProperty> modelProperty = ModelProperty::build();
+
+    for (auto attributeProp : attributes)
+    {
+        auto elementProperty = std::make_shared<RAML::Properties>(attributeProp);
+        modelProperty->add(elementProperty->getName(), buildAttribute(elementProperty));
+    }
+
+    std::shared_ptr<ArrayProperty> arrayProperty = ArrayProperty::build();
+    setArrayProperties(property, arrayProperty);
+    arrayProperty->setElementProperty(modelProperty);
+
+    return arrayProperty;
+}
+
+std::shared_ptr<ModelProperty> ResourceModelSchemaBuilder::buildModelAttribute(
+    const std::shared_ptr<RAML::Properties> &property)
+{
+    std::shared_ptr<ModelProperty> modelProperty = ModelProperty::build();
+
+    std::vector<RAML::Properties> attributes =
+        boost::get<std::vector<RAML::Properties> >(property->getValue());
+
+    for (auto attributeProp : attributes)
+    {
+        auto elementProperty = std::make_shared<RAML::Properties>(attributeProp);
+        modelProperty->add(elementProperty->getName(), buildAttribute(elementProperty));
+    }
+
+    return modelProperty;
+}
+
+void ResourceModelSchemaBuilder::setArrayProperties(
+    const std::shared_ptr<RAML::Properties> &property,
+    const std::shared_ptr<ArrayProperty> &arrayProperty)
+{
+    for (auto &valueProperty : property->getValueProperties())
+    {
+        if (RAML::ValueProperty::Type::ARRAY == valueProperty->type())
+        {
+            int minItems = 0;
+            int maxItems = 0;
+            bool unique = false;
+            bool additionalItems = false;
+
+            valueProperty->valueArray(minItems, maxItems, unique, additionalItems);
+            arrayProperty->setRange(minItems, maxItems);
+            arrayProperty->setUnique(unique);
+            arrayProperty->setVariable(additionalItems);
+            break;
+        }
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/src/common/resource_model_schema_builder.h b/service/simulator/src/common/resource_model_schema_builder.h
new file mode 100644 (file)
index 0000000..fee7751
--- /dev/null
@@ -0,0 +1,72 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_RESOURCE_MODEL_SCHEMA_BUILDER_H_
+#define SIMULATOR_RESOURCE_MODEL_SCHEMA_BUILDER_H_
+
+#include "simulator_resource_model_schema.h"
+
+namespace RAML
+{
+    class RequestResponseBody;
+    class Properties;
+    class ValueProperty;
+    enum class VariantType;
+}
+
+class ResourceModelSchemaBuilder
+{
+    public:
+        ResourceModelSchemaBuilder(const std::shared_ptr<RAML::RequestResponseBody> &ramlSchema);
+        std::shared_ptr<SimulatorResourceModelSchema> build();
+
+    private:
+        std::shared_ptr<AttributeProperty> buildAttribute(
+            const std::shared_ptr<RAML::Properties> &property);
+
+        std::shared_ptr<IntegerProperty> buildIntegerAttribute(
+            const std::shared_ptr<RAML::Properties> &property);
+
+        std::shared_ptr<DoubleProperty> buildDoubleAttribute(
+            const std::shared_ptr<RAML::Properties> &property);
+
+        std::shared_ptr<BooleanProperty> buildBooleanAttribute(
+            const std::shared_ptr<RAML::Properties> &property);
+
+        std::shared_ptr<StringProperty> buildStringAttribute(
+            const std::shared_ptr<RAML::Properties> &property);
+
+        std::shared_ptr<ArrayProperty> buildArrayAttribute(
+            const std::shared_ptr<RAML::Properties> &property);
+
+        std::shared_ptr<ArrayProperty> buildModelArrayAttribute(
+            const std::shared_ptr<RAML::Properties> &property);
+
+        std::shared_ptr<ModelProperty> buildModelAttribute(
+            const std::shared_ptr<RAML::Properties> &property);
+
+        void setArrayProperties(
+            const std::shared_ptr<RAML::Properties> &property,
+            const std::shared_ptr<ArrayProperty> &arrayProperty);
+
+        std::shared_ptr<RAML::RequestResponseBody> m_ramlSchema;
+};
+
+#endif
index 8398a18..de0c8a4 100644 (file)
  ******************************************************************/
 
 #include "response_model.h"
+#include "simulator_resource_model_schema.h"
 
 ResponseModel::ResponseModel(int code) : m_code(code) {}
 
-void ResponseModel::setRepSchema(SimulatorResourceModelSP &repSchema)
+std::shared_ptr<SimulatorResourceModelSchema> ResponseModel::getSchema()
 {
-    m_repSchema = repSchema;
+    return m_repSchema;
 }
 
-SimulatorResult ResponseModel::verifyResponse(const OC::OCRepresentation &rep)
+SimulatorResult ResponseModel::verifyResponse(const SimulatorResourceModel &resModel)
 {
-    for (auto & ocAttribute : rep)
-    {
-        SimulatorResourceModel::Attribute attribute;
-        if (false == m_repSchema->getAttribute(ocAttribute.attrname(), attribute))
-        {
-            return SIMULATOR_UKNOWN_PROPERTY;
-        }
-
-        switch (attribute.getValueType())
-        {
-            case SimulatorResourceModel::Attribute::ValueType::INTEGER : // Integer
-                {
-                    SimulatorResult result = validateAttributeInteger(attribute, ocAttribute);
-                    if (SIMULATOR_OK != result)
-                    {
-                        return result;
-                    }
-                }
-                break;
-
-            case SimulatorResourceModel::Attribute::ValueType::DOUBLE : // Double
-                {
-                    SimulatorResult result = validateAttributeDouble(attribute, ocAttribute);
-                    if (SIMULATOR_OK != result)
-                    {
-                        return result;
-                    }
-                }
-                break;
-
-            case SimulatorResourceModel::Attribute::ValueType::STRING : // String
-                {
-                    SimulatorResult result = validateAttributeString(attribute, ocAttribute);
-                    if (SIMULATOR_OK != result)
-                    {
-                        return result;
-                    }
-                }
-                break;
-        }
-    }
-
-    return SIMULATOR_OK;
-}
-
-SimulatorResult ResponseModel::validateAttributeInteger(
-    SimulatorResourceModel::Attribute &attrSchema,
-    const OC::OCRepresentation::AttributeItem &ocAttribute)
-{
-    // Check the value type
-    if (OC::AttributeType::Integer != ocAttribute.type())
-    {
-        return SIMULATOR_TYPE_MISMATCH;
-    }
-
-    // Check value if it is in range
-    int min, max, value;
-    attrSchema.getRange(min, max);
-    value = ocAttribute.getValue<int>();
-    if (value < min || value > max)
+    if (m_repSchema->validate(resModel))
     {
-        return SIMULATOR_BAD_VALUE;
+        return SIMULATOR_OK;
     }
 
-    return SIMULATOR_OK;
+    return SIMULATOR_ERROR;
 }
 
-SimulatorResult ResponseModel::validateAttributeDouble(
-    SimulatorResourceModel::Attribute &attrSchema,
-    const OC::OCRepresentation::AttributeItem &ocAttribute)
+void ResponseModel::setResponseBodyModel(const std::shared_ptr<SimulatorResourceModelSchema>
+        &repSchema)
 {
-    // Check the value type
-    if (OC::AttributeType::Double != ocAttribute.type())
-    {
-        return SIMULATOR_TYPE_MISMATCH;
-    }
-
-    return SIMULATOR_OK;
+    m_repSchema = repSchema;
 }
-
-SimulatorResult ResponseModel::validateAttributeString(
-    SimulatorResourceModel::Attribute &attrSchema,
-    const OC::OCRepresentation::AttributeItem &ocAttribute)
-{
-    // Check the value type
-    if (OC::AttributeType::String != ocAttribute.type())
-    {
-        return SIMULATOR_TYPE_MISMATCH;
-    }
-
-    // TODO: Check the allowed values
-    return SIMULATOR_OK;
-}
\ No newline at end of file
index 77cb2bb..6a78748 100644 (file)
@@ -21,8 +21,8 @@
 #ifndef RESPONSE_MODEL_H_
 #define RESPONSE_MODEL_H_
 
-#include "simulator_client_types.h"
-#include "simulator_resource_model.h"
+#include "simulator_resource_model_schema.h"
+#include "simulator_error_codes.h"
 
 class RequestModelBuilder;
 class ResponseModel
@@ -30,20 +30,15 @@ class ResponseModel
     public:
         friend class RequestModelBuilder;
 
-        SimulatorResult verifyResponse(const OC::OCRepresentation &rep);
+        std::shared_ptr<SimulatorResourceModelSchema> getSchema();
+        SimulatorResult verifyResponse(const SimulatorResourceModel &resModel);
 
     private:
         ResponseModel(int code);
-        void setRepSchema(SimulatorResourceModelSP &repSchema);
-        SimulatorResult validateAttributeInteger(SimulatorResourceModel::Attribute &attrSchema,
-                const OC::OCRepresentation::AttributeItem &ocAttribute);
-        SimulatorResult validateAttributeDouble(SimulatorResourceModel::Attribute &attrSchema,
-                                                const OC::OCRepresentation::AttributeItem &ocAttribute);
-        SimulatorResult validateAttributeString(SimulatorResourceModel::Attribute &attrSchema,
-                                                const OC::OCRepresentation::AttributeItem &ocAttribute);
+        void setResponseBodyModel(const std::shared_ptr<SimulatorResourceModelSchema> &repSchema);
 
         int m_code;
-        SimulatorResourceModelSP m_repSchema;
+        std::shared_ptr<SimulatorResourceModelSchema> m_repSchema;
 };
 
 typedef std::shared_ptr<ResponseModel> ResponseModelSP;
index 2a1a67d..7aa00e0 100644 (file)
  ******************************************************************/
 
 #include "simulator_resource_model.h"
+#include "simulator_resource_model_schema.h"
 #include "simulator_exceptions.h"
 #include "logger.h"
-#include "OCPlatform.h"
-#include <sstream>
+
 #include <boost/lexical_cast.hpp>
+#include <cfloat>
+
+#define TAG "SIM_RESOURCE_MODEL"
 
 template <typename T>
-struct TypeConverter
-{
-    constexpr static SimulatorResourceModel::Attribute::ValueType type =
-            SimulatorResourceModel::Attribute::ValueType::UNKNOWN;
-};
+struct TypeConverter {};
 
 template <>
 struct TypeConverter<int>
 {
-    constexpr static SimulatorResourceModel::Attribute::ValueType type =
-            SimulatorResourceModel::Attribute::ValueType::INTEGER;
+    constexpr static AttributeValueType type =
+        AttributeValueType::INTEGER;
 };
 
 template <>
 struct TypeConverter<double>
 {
-    constexpr static SimulatorResourceModel::Attribute::ValueType type =
-            SimulatorResourceModel::Attribute::ValueType::DOUBLE;
+    constexpr static AttributeValueType type =
+        AttributeValueType::DOUBLE;
 };
 
 template <>
 struct TypeConverter<bool>
 {
-    constexpr static SimulatorResourceModel::Attribute::ValueType type =
-            SimulatorResourceModel::Attribute::ValueType::BOOLEAN;
+    constexpr static AttributeValueType type =
+        AttributeValueType::BOOLEAN;
 };
 
 template <>
 struct TypeConverter<std::string>
 {
-    constexpr static SimulatorResourceModel::Attribute::ValueType type =
-            SimulatorResourceModel::Attribute::ValueType::STRING;
+    constexpr static AttributeValueType type =
+        AttributeValueType::STRING;
 };
 
-class attribute_type_visitor : public boost::static_visitor<
-        SimulatorResourceModel::Attribute::ValueType>
+template <>
+struct TypeConverter<SimulatorResourceModel>
+{
+    constexpr static AttributeValueType type =
+        AttributeValueType::RESOURCE_MODEL;
+};
+
+template <typename T>
+struct TypeDetails
+{
+    constexpr static AttributeValueType type =
+        TypeConverter<T>::type;
+    constexpr static AttributeValueType baseType =
+        TypeConverter<T>::type;
+    constexpr static int depth = 0;
+};
+
+template <typename T>
+struct TypeDetails<std::vector<T>>
+{
+    constexpr static AttributeValueType type =
+        AttributeValueType::VECTOR;
+    constexpr static AttributeValueType baseType =
+        TypeDetails<T>::baseType;
+    constexpr static int depth = 1 + TypeDetails<T>::depth;
+};
+
+class AttributeTypeVisitor : public boost::static_visitor<>
 {
     public:
+        AttributeTypeVisitor() : m_type(AttributeValueType::UNKNOWN),
+            m_baseType(AttributeValueType::UNKNOWN), m_depth(0) {}
+
         template <typename T>
-        result_type operator ()(const T &)
+        void operator ()(const T &)
         {
-            return TypeConverter<T>::type;
+            m_type = TypeDetails<T>::type;
+            m_baseType = TypeDetails<T>::baseType;
+            m_depth = TypeDetails<T>::depth;
         }
+
+        AttributeValueType m_type;
+        AttributeValueType m_baseType;
+        int m_depth;
 };
 
-class to_string_visitor : public boost::static_visitor<std::string>
+class OCRepresentationBuilder
 {
     public:
-        template <typename T>
-        result_type operator ()(const T &value)
+        class ValueConverter : public boost::static_visitor<>
         {
-            try
-            {
-                return boost::lexical_cast<std::string>(value);
-            }
-            catch (const boost::bad_lexical_cast &e)
+            public:
+                ValueConverter(OC::OCRepresentation &rep, const std::string &name)
+                    : m_rep(rep), m_name(name) {}
+
+                template <typename T>
+                void operator ()(const T &value)
+                {
+                    m_rep.setValue(m_name, value);
+                }
+
+                void operator ()(const SimulatorResourceModel &value)
+                {
+                    OC::OCRepresentation ocRep;
+                    for (auto &element : value.getAttributeValues())
+                    {
+                        ValueConverter visitor(ocRep, element.first);
+                        boost::apply_visitor(visitor, element.second);
+                    }
+
+                    m_rep.setValue(m_name, ocRep);
+                }
+
+                template <typename T>
+                void operator ()(const std::vector<T> &values)
+                {
+                    m_rep.setValue(m_name, values);
+                }
+
+                void operator ()(const std::vector<SimulatorResourceModel> &values)
+                {
+                    std::vector<OC::OCRepresentation> ocRepArray(values.size());
+                    for (size_t i = 0; i < values.size(); i++)
+                    {
+                        for (auto &element : values[i].getAttributeValues())
+                        {
+                            ValueConverter visitor(ocRepArray[i], element.first);
+                            boost::apply_visitor(visitor, element.second);
+                        }
+                    }
+
+                    m_rep.setValue(m_name, ocRepArray);
+                }
+
+                template <typename T>
+                void operator ()(const std::vector<std::vector<T>> &values)
+                {
+                    m_rep.setValue(m_name, values);
+                }
+
+                void operator ()(const std::vector<std::vector<SimulatorResourceModel>> &values)
+                {
+                    std::vector<std::vector<OC::OCRepresentation>> ocRepArray;
+                    for (size_t i = 0; i < values.size(); i++)
+                    {
+                        for (size_t j = 0; j < values[i].size(); j++)
+                        {
+                            for (auto &element : values[i][j].getAttributeValues())
+                            {
+                                ValueConverter visitor(ocRepArray[i][j], element.first);
+                                boost::apply_visitor(visitor, element.second);
+                            }
+                        }
+                    }
+
+                    m_rep.setValue(m_name, ocRepArray);
+                }
+
+                template <typename T>
+                void operator ()(const std::vector<std::vector<std::vector<T>>> &values)
+                {
+                    m_rep.setValue(m_name, values);
+                }
+
+                void operator ()(const std::vector<std::vector<std::vector<SimulatorResourceModel>>> &values)
+                {
+                    std::vector<std::vector<std::vector<OC::OCRepresentation>>> ocRepArray;
+                    for (size_t i = 0; i < values.size(); i++)
+                    {
+                        for (size_t j = 0; j < values[i].size(); j++)
+                        {
+                            for (size_t k = 0; j < values[i][j].size(); k++)
+                            {
+                                for (auto &element : values[i][j][k].getAttributeValues())
+                                {
+                                    ValueConverter visitor(ocRepArray[i][j][k], element.first);
+                                    boost::apply_visitor(visitor, element.second);
+                                }
+                            }
+                        }
+                    }
+
+                    m_rep.setValue(m_name, ocRepArray);
+                }
+
+            private:
+                OC::OCRepresentation &m_rep;
+                std::string m_name;
+        };
+
+        OC::OCRepresentation build(const SimulatorResourceModel &model)
+        {
+            OC::OCRepresentation ocRep;
+            for (auto &element : model.getAttributeValues())
             {
-                return "";
+                ValueConverter visitor(ocRep, element.first);
+                boost::apply_visitor(visitor, element.second);
             }
+
+            return std::move(ocRep);
         }
 };
 
-class add_to_representation : public boost::static_visitor<>
+// TODO: Class is very heavy, revisit again to clean
+class SimulatorResourceModelBuilder
 {
     public:
-        add_to_representation(OC::OCRepresentation &rep, const std::string &key)
-            : m_rep(rep), m_key(key) {}
-
-        template <typename T>
-        void operator ()(const T &value)
+        SimulatorResourceModel build(const OC::OCRepresentation &ocRep)
         {
-            m_rep.setValue(m_key, value);
+            SimulatorResourceModel resModel;
+            handleRepresentationType(resModel, ocRep);
+            return std::move(resModel);
         }
 
-        OC::OCRepresentation &&getRep()
+    private:
+        void handleRepresentationType(SimulatorResourceModel &resModel,
+                                      const OC::OCRepresentation &ocRep)
         {
-            return std::move(m_rep);
+            for (auto &ocAttribute : ocRep)
+            {
+                if (OC::AttributeType::Integer == ocAttribute.type())
+                {
+                    resModel.add<int>(ocAttribute.attrname(), ocAttribute.getValue<int>());
+                }
+                else if (OC::AttributeType::Double == ocAttribute.type())
+                {
+                    resModel.add<double>(ocAttribute.attrname(), ocAttribute.getValue<double>());
+                }
+                else if (OC::AttributeType::Boolean == ocAttribute.type())
+                {
+                    resModel.add<bool>(ocAttribute.attrname(), ocAttribute.getValue<bool>());
+                }
+                else if (OC::AttributeType::String == ocAttribute.type())
+                {
+                    resModel.add<std::string>(ocAttribute.attrname(), ocAttribute.getValue<std::string>());
+                }
+                else if (OC::AttributeType::OCRepresentation == ocAttribute.type())
+                {
+                    SimulatorResourceModel subResModel;
+                    OC::OCRepresentation ocSubRep = ocAttribute.getValue<OC::OCRepresentation>();
+                    handleRepresentationType(subResModel, ocSubRep);
+                    resModel.add<SimulatorResourceModel>(ocAttribute.attrname(), subResModel);
+                }
+                else if (OC::AttributeType::Vector == ocAttribute.type())
+                {
+                    handleVectorType(resModel, ocAttribute);
+                }
+            }
         }
 
-    private:
-        OC::OCRepresentation m_rep;
-        std::string m_key;
-};
-
-class range_validation : public boost::static_visitor<bool>
-{
-    public:
-        range_validation (SimulatorResourceModel::Attribute &attrItem)
-            : m_attrItem(attrItem) {}
-
-        bool operator ()(int &value)
+        void handleVectorType(SimulatorResourceModel &resModel,
+                              const OC::OCRepresentation::AttributeItem &ocAttribute)
         {
-            int min, max;
-            m_attrItem.getRange(min, max);
-            if (value >= min && value <= max)
-                return true;
-            return false;
+            if (1 == ocAttribute.depth())
+            {
+                handleVectorTypeDepth1(resModel, ocAttribute);
+            }
+            else if (2 == ocAttribute.depth())
+            {
+                handleVectorTypeDepth2(resModel, ocAttribute);
+            }
+            else if (3 == ocAttribute.depth())
+            {
+                handleVectorTypeDepth3(resModel, ocAttribute);
+            }
         }
 
-        bool operator ()(double &value)
+        void handleVectorTypeDepth1(SimulatorResourceModel &resModel,
+                                    const OC::OCRepresentation::AttributeItem &ocAttribute)
         {
-            std::vector<SimulatorResourceModel::Attribute::ValueVariant> values
-                = m_attrItem.getAllowedValues();
-            if(0 == values.size())
-                return true;
-            for (SimulatorResourceModel::Attribute::ValueVariant & val : values)
+            if (OC::AttributeType::Integer == ocAttribute.base_type())
+            {
+                resModel.add(ocAttribute.attrname(), ocAttribute.getValue<std::vector<int>>());
+            }
+            else if (OC::AttributeType::Double == ocAttribute.base_type())
+            {
+                resModel.add(ocAttribute.attrname(), ocAttribute.getValue<std::vector<double>>());
+            }
+            else if (OC::AttributeType::Boolean == ocAttribute.base_type())
+            {
+                resModel.add(ocAttribute.attrname(), ocAttribute.getValue<std::vector<bool>>());
+            }
+            else if (OC::AttributeType::String == ocAttribute.base_type())
+            {
+                resModel.add(ocAttribute.attrname(), ocAttribute.getValue<std::vector<std::string>>());
+            }
+            else if (OC::AttributeType::OCRepresentation == ocAttribute.base_type())
             {
-                SimulatorResourceModel::Attribute::ValueVariant vVal = value;
-                if (val == vVal)
-                    return true;
+                std::vector<OC::OCRepresentation> ocSubRepArray =
+                    ocAttribute.getValue<std::vector<OC::OCRepresentation>>();
+
+                std::vector<SimulatorResourceModel> subResModelArray(ocSubRepArray.size());
+                for  (size_t i = 0; i < ocSubRepArray.size(); i++)
+                {
+                    handleRepresentationType(subResModelArray[i], ocSubRepArray[i]);
+                }
+
+                resModel.add<std::vector<SimulatorResourceModel>>(ocAttribute.attrname(), subResModelArray);
             }
-            return false;
         }
 
-        bool operator ()(bool &value)
+        void handleVectorTypeDepth2(SimulatorResourceModel &resModel,
+                                    const OC::OCRepresentation::AttributeItem &ocAttribute)
         {
-            return true;
+            if (OC::AttributeType::Integer == ocAttribute.base_type())
+            {
+                resModel.add(ocAttribute.attrname(), ocAttribute.getValue<std::vector<std::vector<int>>>());
+            }
+            else if (OC::AttributeType::Double == ocAttribute.base_type())
+            {
+                resModel.add(ocAttribute.attrname(), ocAttribute.getValue<std::vector<std::vector<double>>>());
+            }
+            else if (OC::AttributeType::Boolean == ocAttribute.base_type())
+            {
+                resModel.add(ocAttribute.attrname(), ocAttribute.getValue<std::vector<std::vector<bool>>>());
+            }
+            else if (OC::AttributeType::String == ocAttribute.base_type())
+            {
+                resModel.add(ocAttribute.attrname(), ocAttribute.getValue<std::vector<std::vector<std::string>>>());
+            }
+            else if (OC::AttributeType::OCRepresentation == ocAttribute.base_type())
+            {
+                std::vector<std::vector<OC::OCRepresentation>> ocSubRepArray =
+                            ocAttribute.getValue<std::vector<std::vector<OC::OCRepresentation>>>();
+
+                std::vector<std::vector<SimulatorResourceModel>> subResModelArray(ocSubRepArray.size());
+                for  (size_t i = 0; i < ocSubRepArray.size(); i++)
+                {
+                    std::vector<SimulatorResourceModel> innerArray1(ocSubRepArray[i].size());
+                    for  (size_t j = 0; j < ocSubRepArray[i].size(); j++)
+                        handleRepresentationType(innerArray1[j], ocSubRepArray[i][j]);
+                    subResModelArray[i] = innerArray1;
+                }
+
+                resModel.add<std::vector<std::vector<SimulatorResourceModel>>>(
+                    ocAttribute.attrname(), subResModelArray);
+            }
         }
 
-        bool operator ()(std::string &value)
+        void handleVectorTypeDepth3(SimulatorResourceModel &resModel,
+                                    const OC::OCRepresentation::AttributeItem &ocAttribute)
         {
-            std::vector<SimulatorResourceModel::Attribute::ValueVariant> values
-                = m_attrItem.getAllowedValues();
-            if(0 == values.size())
-                return true;
-            for (SimulatorResourceModel::Attribute::ValueVariant & vVal : values)
+            if (OC::AttributeType::Integer == ocAttribute.base_type())
+            {
+                resModel.add(ocAttribute.attrname(),
+                             ocAttribute.getValue<std::vector<std::vector<std::vector<int>>>>());
+            }
+            else if (OC::AttributeType::Double == ocAttribute.base_type())
+            {
+                resModel.add(ocAttribute.attrname(),
+                             ocAttribute.getValue<std::vector<std::vector<std::vector<double>>>>());
+            }
+            else if (OC::AttributeType::Boolean == ocAttribute.base_type())
             {
-                std::string val = boost::get<std::string>(vVal);
-                if (val == value)
-                    return true;
+                resModel.add(ocAttribute.attrname(),
+                             ocAttribute.getValue<std::vector<std::vector<std::vector<bool>>>>());
             }
+            else if (OC::AttributeType::String == ocAttribute.base_type())
+            {
+                resModel.add(ocAttribute.attrname(),
+                             ocAttribute.getValue<std::vector<std::vector<std::vector<std::string>>>>());
+            }
+            else if (OC::AttributeType::OCRepresentation == ocAttribute.base_type())
+            {
+                std::vector<std::vector<std::vector<OC::OCRepresentation>>> ocSubRepArray =
+                    ocAttribute.getValue<std::vector<std::vector<std::vector<OC::OCRepresentation>>>>();
+
+                std::vector<std::vector<std::vector<SimulatorResourceModel>>> subResModelArray(
+                    ocSubRepArray.size());
+                for  (size_t i = 0; i < ocSubRepArray.size(); i++)
+                {
+                    std::vector<std::vector<SimulatorResourceModel>> innerArray1(ocSubRepArray[i].size());
+                    for  (size_t j = 0; j < ocSubRepArray[i].size(); j++)
+                    {
+                        std::vector<SimulatorResourceModel> innerArray2(ocSubRepArray[i][j].size());
+                        for  (size_t k = 0; k < ocSubRepArray[i][j].size(); k++)
+                        {
+                            handleRepresentationType(innerArray2[k], ocSubRepArray[i][j][k]);
+                        }
+                        innerArray1[j] = innerArray2;
+                    }
+                    subResModelArray[i] = innerArray1;
+                }
+
+                resModel.add<std::vector<std::vector<std::vector<SimulatorResourceModel>>>>(
+                    ocAttribute.attrname(), subResModelArray);
+            }
+        }
+};
 
-            return false;
+class ToStringConverter
+{
+    public:
+        class ValueVisitor : public boost::static_visitor<std::string>
+        {
+            public:
+
+                template <typename T>
+                std::string operator ()(const T &value)
+                {
+                    try
+                    {
+                        return boost::lexical_cast<std::string>(value);
+                    }
+                    catch (const boost::bad_lexical_cast &e)
+                    {
+                        return "CONVERSION_FAILED!";
+                    }
+                }
+
+                std::string operator ()(const SimulatorResourceModel &value)
+                {
+                    std::ostringstream out;
+                    out << "{ ";
+                    for (auto &element : value.getAttributeValues())
+                    {
+                        out << "\"" << element.first << "\" : ";
+
+                        ValueVisitor visitor;
+                        out << boost::apply_visitor(visitor, element.second);
+
+                        out << ", ";
+                    }
+                    out << "}";
+                    return out.str();
+                }
+
+                template <typename T>
+                std::string operator ()(const std::vector<T> &values)
+                {
+                    std::ostringstream out;
+                    out << "[ ";
+
+                    for (size_t i = 0; i < values.size(); i++)
+                    {
+                        out << operator ()(values[i]);
+                        out << " ";
+                    }
+
+                    out << "]";
+                    return out.str();
+                }
+
+                template <typename T>
+                std::string operator ()(const std::vector<std::vector<T>> &values)
+                {
+                    std::ostringstream out;
+                    out << "[ ";
+
+                    for (size_t i = 0; i < values.size(); i++)
+                    {
+                        out << operator ()(values[i]);
+                        out << " ";
+                    }
+
+                    out << "]";
+                    return out.str();
+                }
+
+                template <typename T>
+                std::string operator ()(const std::vector<std::vector<std::vector<T>>> &values)
+                {
+                    std::ostringstream out;
+                    out << "[ ";
+
+                    for (size_t i = 0; i < values.size(); i++)
+                    {
+                        out << operator ()(values[i]);
+                        out << " ";
+                    }
+
+                    out << "]";
+                    return out.str();
+                }
+        };
+
+        std::string getStringRepresentation(const SimulatorResourceModel &resModel)
+        {
+            ValueVisitor visitor;
+            AttributeValueVariant value = resModel;
+            return boost::apply_visitor(visitor, value);
         }
 
-    private:
-        SimulatorResourceModel::Attribute &m_attrItem;
+        std::string getStringRepresentation(const AttributeValueVariant &value)
+        {
+            ValueVisitor visitor;
+            return boost::apply_visitor(visitor, value);
+        }
 };
 
-SimulatorResourceModel::Attribute::ValueVariant
-&SimulatorResourceModel::Attribute::AllowedValues::at(unsigned int index)
-{
-    return m_values.at(index);
-}
+SimulatorResourceModel::TypeInfo::TypeInfo(
+    AttributeValueType type, AttributeValueType baseType, int depth)
+    :   m_type (type), m_baseType(baseType), m_depth(depth) {}
 
-int SimulatorResourceModel::Attribute::AllowedValues::size() const
+AttributeValueType SimulatorResourceModel::TypeInfo::type() const
 {
-    return m_values.size();
+    return m_type;
 }
 
-std::vector<std::string> SimulatorResourceModel::Attribute::AllowedValues::toString() const
+AttributeValueType SimulatorResourceModel::TypeInfo::baseType() const
 {
-    std::vector<std::string> values;
-
-    for (auto & value : m_values)
-    {
-        to_string_visitor visitor;
-        values.push_back(boost::apply_visitor(visitor, value));
-    }
-    return values;
+    return m_baseType;
 }
 
-std::vector<SimulatorResourceModel::Attribute::ValueVariant>
-SimulatorResourceModel::Attribute::AllowedValues::getValues() const
+int SimulatorResourceModel::TypeInfo::depth() const
 {
-    return m_values;
+    return m_depth;
 }
 
-std::string SimulatorResourceModel::Attribute::getName(void) const
+bool SimulatorResourceModel::TypeInfo::operator==(
+    const SimulatorResourceModel::TypeInfo &rhs) const
 {
-    return m_name;
+    if (m_type == rhs.m_type && m_baseType == rhs.m_baseType
+        && m_depth == rhs.m_depth)
+        return true;
+    return false;
 }
 
-void SimulatorResourceModel::Attribute::setName(const std::string &name)
-{
-    m_name = name;
-}
+SimulatorResourceAttribute::SimulatorResourceAttribute(const std::string &name)
+    : m_name(name) {}
 
-void SimulatorResourceModel::Attribute::getRange(int &min, int &max) const
+SimulatorResourceAttribute::SimulatorResourceAttribute(const std::string &name,
+        const AttributeValueVariant &value) : m_name(name)
 {
-    min = m_min;
-    max = m_max;
+    m_value = std::make_shared<AttributeValueVariant>(value);
 }
 
-void SimulatorResourceModel::Attribute::setRange(const int &min, const int &max)
+void SimulatorResourceAttribute::setName(const std::string &name)
 {
-    m_min = min;
-    m_max = max;
+    m_name = name;
 }
 
-int SimulatorResourceModel::Attribute::getAllowedValuesSize() const
+std::string SimulatorResourceAttribute::getName() const
 {
-    return m_allowedValues.size();
+    return m_name;
 }
 
-void SimulatorResourceModel::Attribute::setFromAllowedValue(unsigned int index)
+const SimulatorResourceModel::TypeInfo SimulatorResourceAttribute::getType() const
 {
-    m_value = m_allowedValues.at(index);
+    if (m_value)
+    {
+        AttributeTypeVisitor typeVisitor;
+        boost::apply_visitor(typeVisitor, *(m_value.get()));
+        return SimulatorResourceModel::TypeInfo(typeVisitor.m_type, typeVisitor.m_baseType,
+                                                typeVisitor.m_depth);
+    }
+
+    return SimulatorResourceModel::TypeInfo();
 }
 
-SimulatorResourceModel::Attribute::ValueType SimulatorResourceModel::Attribute::getValueType() const
+void SimulatorResourceAttribute::setProperty(const std::shared_ptr<AttributeProperty> &property)
 {
-    attribute_type_visitor typeVisitor;
-    return boost::apply_visitor(typeVisitor, m_value);
+    m_property = property;
 }
 
-std::string SimulatorResourceModel::Attribute::valueToString() const
+std::shared_ptr<AttributeProperty> SimulatorResourceAttribute::getProperty() const
 {
-    to_string_visitor visitor;
-    return boost::apply_visitor(visitor, m_value);
+    return m_property;
 }
 
-std::vector<std::string> SimulatorResourceModel::Attribute::allowedValuesToString() const
+AttributeValueVariant SimulatorResourceAttribute::getValue() const
 {
-    return m_allowedValues.toString();
+    return *m_value;
 }
 
-void SimulatorResourceModel::Attribute::addValuetoRepresentation(OC::OCRepresentation &rep,
-        const std::string &key) const
+std::string SimulatorResourceAttribute::asString() const
 {
-    add_to_representation visitor(rep, key);
-    boost::apply_visitor(visitor, m_value);
-    rep = visitor.getRep();
+    return ToStringConverter().getStringRepresentation(*m_value);
 }
 
-bool SimulatorResourceModel::Attribute::compare(SimulatorResourceModel::Attribute &attribute)
+bool SimulatorResourceModel::remove(const std::string &name)
 {
-    // Check the value types
-    if (m_value.which() != attribute.getValue().which())
+    if (m_attributes.end() == m_attributes.find(name))
     {
         return false;
     }
 
-    // Check the value in allowed range
-    range_validation visitor(*this);
-    return boost::apply_visitor(visitor, attribute.getValue());
-}
-
-std::vector<SimulatorResourceModel::Attribute::ValueVariant>
-SimulatorResourceModel::Attribute::getAllowedValues() const
-{
-    return m_allowedValues.getValues();
+    m_attributes.erase(m_attributes.find(name));
+    return true;
 }
 
-bool SimulatorResourceModel::getAttribute(const std::string &attrName, Attribute &value)
+bool SimulatorResourceModel::contains(const std::string &name) const
 {
-    if (m_attributes.end() != m_attributes.find(attrName))
+    if (m_attributes.end() != m_attributes.find(name))
     {
-        value = m_attributes[attrName];
         return true;
     }
 
     return false;
 }
 
-std::map<std::string, SimulatorResourceModel::Attribute> SimulatorResourceModel::getAttributes()
-const
+size_t SimulatorResourceModel::size() const
 {
-    return m_attributes;
+    return m_attributes.size();
 }
 
-void SimulatorResourceModel::addAttribute(const SimulatorResourceModel::Attribute &attribute, bool overwrite)
+SimulatorResourceModel::TypeInfo SimulatorResourceModel::getType(const std::string &name) const
 {
-    if (!attribute.getName().empty() &&
-        (m_attributes.end() == m_attributes.find(attribute.getName()) || overwrite))
+    if (m_attributes.end() != m_attributes.find(name))
     {
-        m_attributes[attribute.getName()] = attribute;
+        return getTypeInfo(m_attributes.find(name)->second);
     }
-}
-
-void SimulatorResourceModel::setRange(const std::string &attrName, const int min, const int max)
-{
-    if (m_attributes.end() != m_attributes.find(attrName))
-        m_attributes[attrName].setRange(min, max);
-}
 
-void SimulatorResourceModel::setUpdateInterval(const std::string &attrName, int interval)
-{
-    if (m_attributes.end() != m_attributes.find(attrName))
-        m_attributes[attrName].setUpdateFrequencyTime(interval);
+    return SimulatorResourceModel::TypeInfo();
 }
 
-void SimulatorResourceModel::updateAttributeFromAllowedValues(const std::string &attrName,
-        unsigned int index)
+std::map<std::string, AttributeValueVariant> SimulatorResourceModel::getAttributeValues() const
 {
-    if (m_attributes.end() != m_attributes.find(attrName))
-        m_attributes[attrName].setFromAllowedValue(index);
+    return m_attributes;
 }
 
-void SimulatorResourceModel::removeAttribute(const std::string &attrName)
+AttributeValueVariant SimulatorResourceModel::getAttributeValue(const std::string &name) const
 {
-   if (attrName.empty() || m_attributes.end() == m_attributes.find(attrName))
-   {
-       OC_LOG(ERROR, TAG, "Attribute name is empty or not found in model!");
-       throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Attribute not found in model!");
-   }
+    auto ite = m_attributes.find(name);
+    if (m_attributes.end() != ite)
+    {
+        return (*ite).second;
+    }
 
-    m_attributes.erase(attrName);
-    return;
+    return AttributeValueVariant();
 }
 
-OC::OCRepresentation SimulatorResourceModel::getOCRepresentation() const
+std::set<std::string> SimulatorResourceModel::getAttributeNameSet() const
 {
-    OC::OCRepresentation rep;
-    for (auto & attribute : m_attributes)
+    std::set<std::string> nameSet;
+    for (auto &attributeEntry : m_attributes)
     {
-        (attribute.second).addValuetoRepresentation(rep, attribute.first);
+        nameSet.insert(attributeEntry.first);
     }
 
-    return rep;
+    return nameSet;
 }
 
-bool SimulatorResourceModel::update(OC::OCRepresentation &ocRep)
+SimulatorResourceModel::TypeInfo SimulatorResourceModel::getTypeInfo(const AttributeValueVariant
+        &value) const
 {
-    if (0 == ocRep.size())
-        return true;
-
-    // Convert OCRepresentation to SimulatorResourceModel
-    SimulatorResourceModelSP resModel = create(ocRep);
-
-    return update(resModel);
+    AttributeTypeVisitor typeVisitor;
+    boost::apply_visitor(typeVisitor, value);
+    SimulatorResourceModel::TypeInfo typeInfo(typeVisitor.m_type, typeVisitor.m_baseType,
+            typeVisitor.m_depth);
+    return typeInfo;
 }
 
-bool SimulatorResourceModel::update(SimulatorResourceModelSP &repModel)
+bool SimulatorResourceModel::updateValue(const std::string &name,
+        const AttributeValueVariant &value)
 {
-    std::map<std::string, SimulatorResourceModel::Attribute> attributes = repModel->getAttributes();
-    for (auto & attributeItem : attributes)
+    if (name.empty())
     {
-        // Check the attribute presence
-        SimulatorResourceModel::Attribute attribute;
-        if (false == getAttribute((attributeItem.second).getName(), attribute))
-        {
-            return false;
-        }
+        return false;
+    }
 
-        // Check the validity of the value to be set
-        if (false == attribute.compare(attributeItem.second))
-        {
-            return false;
-        }
-        m_attributes[(attributeItem.second).getName()].setValue((attributeItem.second).getValue());
+    if (m_attributes.end() == m_attributes.find(name))
+    {
+        return false;
+    }
+
+    if (!(getTypeInfo(m_attributes[name]) == getTypeInfo(value)))
+    {
+        return false;
     }
 
+    m_attributes[name] = value;
     return true;
 }
 
-SimulatorResourceModelSP SimulatorResourceModel::create(const OC::OCRepresentation &ocRep)
+OC::OCRepresentation SimulatorResourceModel::asOCRepresentation() const
 {
-    SimulatorResourceModelSP resModel(new SimulatorResourceModel);
-    for (auto & attributeItem : ocRep)
-    {
-        SimulatorResourceModel::Attribute attribute;
-        if (attributeItem.type() == OC::AttributeType::Integer)
-            attribute.setValue(attributeItem.getValue<int>());
-        if (attributeItem.type() == OC::AttributeType::Double)
-            attribute.setValue(attributeItem.getValue<double>());
-        if (attributeItem.type() == OC::AttributeType::String)
-            attribute.setValue(attributeItem.getValue<std::string>());
-        if (attributeItem.type() == OC::AttributeType::Boolean)
-            attribute.setValue(attributeItem.getValue<bool>());
-
-        attribute.setName(attributeItem.attrname());
-        resModel->m_attributes[attributeItem.attrname()] = attribute;
-    }
-    return resModel;
+    return OCRepresentationBuilder().build(*this);
+}
+
+std::string SimulatorResourceModel::asString() const
+{
+    return ToStringConverter().getStringRepresentation(*this);
+}
+
+SimulatorResourceModel SimulatorResourceModel::build(const OC::OCRepresentation &ocRep)
+{
+    return SimulatorResourceModelBuilder().build(ocRep);
 }
 
diff --git a/service/simulator/src/common/simulator_resource_model_schema.cpp b/service/simulator/src/common/simulator_resource_model_schema.cpp
new file mode 100644 (file)
index 0000000..f17a22b
--- /dev/null
@@ -0,0 +1,860 @@
+/******************************************************************
+ *
+ * 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 "simulator_resource_model_schema.h"
+#include "simulator_exceptions.h"
+
+template <typename TYPE>
+static AttributeValueVariant buildArrayValue(int depth, AttributeValueVariant &childValue)
+{
+    if (1 == depth)
+    {
+        std::vector<TYPE> arrayValue {boost::get<TYPE>(childValue)};
+        return arrayValue;
+    }
+    else if (2 == depth)
+    {
+        std::vector<std::vector<TYPE>> arrayValue {{boost::get<TYPE>(childValue)}};
+        return arrayValue;
+    }
+
+    // This for handling array values of depth 3
+    // NOTE: Caller of this method should validate and pass the depth information.
+    // on invalid depth information this method might throw boost exception.
+    std::vector<std::vector<std::vector<TYPE>>> arrayValue {{{boost::get<TYPE>(childValue)}}};
+    return arrayValue;
+}
+
+template <typename T, typename=void>
+struct UniquenessChecker
+{
+    static bool get(const std::vector<T> &/*value*/)
+    {
+        return true;
+    }
+};
+
+template <typename T>
+struct UniquenessChecker<T, typename std::enable_if<
+    std::is_same<T, int>::value
+    || std::is_same<T, double>::value
+    || std::is_same<T, bool>::value
+    || std::is_same<T, std::string>::value
+    >::type >
+{
+    static bool get(const std::vector<T> &value)
+    {
+        std::vector<T> valueCopy = value;
+        std::sort(valueCopy.begin(), valueCopy.end());
+        if(valueCopy.end() != std::unique(valueCopy.begin(), valueCopy.end()))
+            return false;
+        return true;
+    }
+};
+
+class IntegerValidator : public boost::static_visitor<bool>
+{
+    public:
+        IntegerValidator(const std::shared_ptr<IntegerProperty> &property) :
+            m_property(property) {}
+
+        template <typename T>
+        bool operator ()(const T &)
+        {
+            return false;
+        }
+
+        bool operator ()(const int &value)
+        {
+            return m_property->validate(value);
+        }
+
+    private:
+        std::shared_ptr<IntegerProperty> m_property;
+};
+
+class DoubleValidator : public boost::static_visitor<bool>
+{
+    public:
+        DoubleValidator(const std::shared_ptr<DoubleProperty> &property) :
+            m_property(property) {}
+
+        template <typename T>
+        bool operator ()(const T &)
+        {
+            return false;
+        }
+
+        bool operator ()(const double &value)
+        {
+            return m_property->validate(value);
+        }
+
+    private:
+        std::shared_ptr<DoubleProperty> m_property;
+};
+
+class StringValidator : public boost::static_visitor<bool>
+{
+    public:
+        StringValidator(const std::shared_ptr<StringProperty> &property) :
+            m_property(property) {}
+
+        template <typename T>
+        bool operator ()(const T &)
+        {
+            return false;
+        }
+
+        bool operator ()(const std::string &value)
+        {
+            return m_property->validate(value);
+        }
+
+    private:
+        std::shared_ptr<StringProperty> m_property;
+};
+
+class ArrayValidator : public boost::static_visitor<bool>
+{
+    public:
+        ArrayValidator(const std::shared_ptr<ArrayProperty> &property) :
+            m_property(property) {}
+
+        template <typename T>
+        bool operator ()(const T &)
+        {
+            return false;
+        }
+
+        template <typename T>
+        bool operator ()(const std::vector<T> &value)
+        {
+            // Validating length of array
+            if (!checkLength(value))
+            {
+                return false;
+            }
+
+            // Validate the uniqueness of elements of array
+            if (!checkUniqueness(value))
+            {
+                return false;
+            }
+
+            // Validating elements of array
+            std::shared_ptr<AttributeProperty> elementProperty =
+                m_property->getElementProperty();
+            if (elementProperty)
+            {
+                for (size_t index = 0; index < value.size(); index++)
+                {
+                    AttributeValueVariant element = value[index];
+                    if (!elementProperty->validate(element))
+                        return false;
+                }
+            }
+
+            return true;
+        }
+
+    private:
+        template <typename T>
+        bool checkLength(const std::vector<T> &value)
+        {
+            if (m_property->hasRange())
+            {
+                if (value.size() < m_property->getMinItems()
+                    || (value.size() > m_property->getMaxItems() && !m_property->isVariable()))
+                {
+                    return false;
+                }
+            }
+
+            return true;
+        }
+
+        template <typename T>
+        bool checkUniqueness(const std::vector<T> &value)
+        {
+            if (m_property->isUnique())
+            {
+                return UniquenessChecker<T>::get(value);
+            }
+
+            return true;
+        }
+
+        std::shared_ptr<ArrayProperty> m_property;
+};
+
+class ModelValidator : public boost::static_visitor<bool>
+{
+    public:
+        ModelValidator(const std::shared_ptr<ModelProperty> &property) :
+            m_property(property) {}
+
+        template <typename T>
+        bool operator ()(const T &)
+        {
+            return false;
+        }
+
+        bool operator ()(const SimulatorResourceModel &value)
+        {
+            return m_property->validate(value);
+        }
+
+    private:
+        std::shared_ptr<ModelProperty> m_property;
+};
+
+AttributeProperty::AttributeProperty(Type type) : m_type(type) {}
+
+AttributeProperty::Type AttributeProperty::getType() const
+{
+    return m_type;
+}
+
+IntegerProperty::IntegerProperty(int defaultValue)
+    : AttributeProperty(AttributeProperty::Type::INTEGER),
+      m_defaultValue(defaultValue),
+      m_min(0),
+      m_max(0),
+      m_hasRange(false) {}
+
+std::shared_ptr<IntegerProperty> IntegerProperty::build(int defaultValue)
+{
+    return std::shared_ptr<IntegerProperty>(new IntegerProperty(defaultValue));
+}
+
+bool IntegerProperty::isInteger() const
+{
+    return true;
+}
+
+std::shared_ptr<IntegerProperty> IntegerProperty::asInteger()
+{
+    return shared_from_this();
+}
+
+bool IntegerProperty::hasRange() const
+{
+    return m_hasRange;
+}
+
+bool IntegerProperty::hasValues() const
+{
+    return m_values.size() > 0;
+}
+
+int IntegerProperty::getDefaultValue() const
+{
+    return m_defaultValue;
+}
+
+bool IntegerProperty::getRange(int &min, int &max) const
+{
+    if (!m_hasRange)
+        return false;
+
+    min = m_min;
+    max = m_max;
+    return true;
+}
+
+bool IntegerProperty::getValues(std::vector<int> &values) const
+{
+    if (!m_values.size())
+        return false;
+
+    values  = m_values;
+    return true;
+}
+
+void IntegerProperty::setDefaultValue(int value)
+{
+    if(m_hasRange && !(value >= m_min && value <= m_max))
+    {
+        m_defaultValue = m_min;
+    }
+    else if(m_values.size() > 0
+        && m_values.end() == std::find(m_values.begin(), m_values.end(), value))
+    {
+        m_defaultValue = m_values[0];
+    }
+    else
+        m_defaultValue = value;
+}
+
+void IntegerProperty::setRange(int min, int max)
+{
+    m_min = min;
+    m_max = max;
+    m_hasRange = true;
+    setDefaultValue(m_defaultValue);
+}
+
+void IntegerProperty::setValues(const std::vector<int> &values)
+{
+    m_values = values;
+    setDefaultValue(m_defaultValue);
+}
+
+bool IntegerProperty::validate(const AttributeValueVariant &value)
+{
+    IntegerValidator integerValidator(shared_from_this());
+    return boost::apply_visitor(integerValidator, value);
+}
+
+bool IntegerProperty::validate(const int &value)
+{
+    if (m_hasRange && (value < m_min || value > m_max))
+    {
+        return false;
+    }
+    else if (m_values.size() > 0)
+    {
+        if (m_values.end() == std::find(m_values.begin(), m_values.end(), value))
+            return false;
+    }
+
+    return true;
+}
+
+AttributeValueVariant IntegerProperty::buildValue()
+{
+    return m_defaultValue;
+}
+
+DoubleProperty::DoubleProperty(double defaultValue)
+    : AttributeProperty(AttributeProperty::Type::DOUBLE),
+      m_defaultValue(defaultValue),
+      m_min(0),
+      m_max(0),
+      m_hasRange(false) {}
+
+std::shared_ptr<DoubleProperty> DoubleProperty::build(double defaultValue)
+{
+    return std::shared_ptr<DoubleProperty>(new DoubleProperty(defaultValue));
+}
+
+bool DoubleProperty::isDouble() const
+{
+    return true;
+}
+
+std::shared_ptr<DoubleProperty> DoubleProperty::asDouble()
+{
+    return shared_from_this();
+}
+
+bool DoubleProperty::hasRange() const
+{
+    return m_hasRange;
+}
+
+bool DoubleProperty::hasValues() const
+{
+    return m_values.size() > 0;
+}
+
+double DoubleProperty::getDefaultValue() const
+{
+    return m_defaultValue;
+}
+
+bool DoubleProperty::getRange(double &min, double &max) const
+{
+    if (!m_hasRange)
+        return false;
+
+    min = m_min;
+    max = m_max;
+    return true;
+}
+
+bool DoubleProperty::getValues(std::vector<double> &values) const
+{
+    if (!m_values.size())
+        return false;
+
+    values  = m_values;
+    return true;
+}
+
+void DoubleProperty::setDefaultValue(double value)
+{
+    if(m_hasRange && !(value >= m_min && value <= m_max))
+    {
+        m_defaultValue = m_min;
+    }
+    else if(m_values.size() > 0
+        && m_values.end() == std::find(m_values.begin(), m_values.end(), value))
+    {
+        m_defaultValue = m_values[0];
+    }
+    else
+        m_defaultValue = value;
+}
+
+void DoubleProperty::setRange(double min, double max)
+{
+    m_min = min;
+    m_max = max;
+    m_hasRange = true;
+    setDefaultValue(m_defaultValue);
+}
+
+void DoubleProperty::setValues(const std::vector<double> &values)
+{
+    m_values = values;
+    setDefaultValue(m_defaultValue);
+}
+
+bool DoubleProperty::validate(const AttributeValueVariant &value)
+{
+    DoubleValidator doubleValidator(shared_from_this());
+    return boost::apply_visitor(doubleValidator, value);
+}
+
+bool DoubleProperty::validate(const double &value)
+{
+    if (m_hasRange && (value < m_min || value > m_max))
+    {
+        return false;
+    }
+    else if (m_values.size() > 0)
+    {
+        if (m_values.end() == std::find(m_values.begin(), m_values.end(), value))
+            return false;
+    }
+
+    return true;
+}
+
+AttributeValueVariant DoubleProperty::buildValue()
+{
+    return m_defaultValue;
+}
+
+BooleanProperty::BooleanProperty(bool defaultValue)
+    : AttributeProperty(AttributeProperty::Type::BOOLEAN),
+      m_defaultValue(defaultValue) {}
+
+std::shared_ptr<BooleanProperty> BooleanProperty::build(bool defaultValue)
+{
+    return std::shared_ptr<BooleanProperty>(new BooleanProperty(defaultValue));
+}
+
+bool BooleanProperty::isBoolean() const
+{
+    return true;
+}
+
+std::shared_ptr<BooleanProperty> BooleanProperty::asBoolean()
+{
+    return shared_from_this();
+}
+
+void BooleanProperty::setDefaultValue(bool value)
+{
+    m_defaultValue = value;
+}
+
+bool BooleanProperty::getDefaultValue() const
+{
+    return m_defaultValue;
+}
+
+bool BooleanProperty::validate(const AttributeValueVariant &)
+{
+    return true;
+}
+
+AttributeValueVariant BooleanProperty::buildValue()
+{
+    return m_defaultValue;
+}
+
+StringProperty::StringProperty(const std::string &defaultValue)
+    : AttributeProperty(AttributeProperty::Type::STRING),
+      m_defaultValue(defaultValue),
+      m_min(0),
+      m_max(0),
+      m_hasRange(false) {}
+
+std::shared_ptr<StringProperty> StringProperty::build(const std::string &defaultValue)
+{
+    return std::shared_ptr<StringProperty>(new StringProperty(defaultValue));
+}
+
+bool StringProperty::isString() const
+{
+    return true;
+}
+
+std::shared_ptr<StringProperty> StringProperty::asString()
+{
+    return shared_from_this();
+}
+
+bool StringProperty::hasRange() const
+{
+    return m_hasRange;
+}
+
+bool StringProperty::hasValues() const
+{
+    return m_values.size() > 0;
+}
+
+std::string StringProperty::getDefaultValue() const
+{
+    return m_defaultValue;
+}
+
+bool StringProperty::getRange(size_t &min, size_t &max) const
+{
+    if (!m_hasRange)
+        return false;
+
+    min = m_min;
+    max = m_max;
+    return true;
+}
+
+bool StringProperty::getValues(std::vector<std::string> &values) const
+{
+    if (!m_values.size())
+        return false;
+
+    values  = m_values;
+    return true;
+}
+
+void StringProperty::setDefaultValue(const std::string &value)
+{
+    if(m_values.size() > 0
+        && m_values.end() == std::find(m_values.begin(), m_values.end(), value))
+    {
+        m_defaultValue = m_values[0];
+    }
+    else if(m_hasRange)
+    {
+        if(value.length() >= m_min && value.length() <= m_max)
+            m_defaultValue = value;
+        else
+            m_defaultValue.clear();
+    }
+    else
+        m_defaultValue = value;
+}
+
+void StringProperty::setRange(size_t min, size_t max)
+{
+    m_min = min;
+    m_max = max;
+    m_hasRange = true;
+    setDefaultValue(m_defaultValue);
+}
+
+void StringProperty::setValues(const std::vector<std::string> &values)
+{
+    m_values = values;
+    setDefaultValue(m_defaultValue);
+}
+
+bool StringProperty::validate(const AttributeValueVariant &value)
+{
+    StringValidator stringValidator(shared_from_this());
+    return boost::apply_visitor(stringValidator, value);
+}
+
+bool StringProperty::validate(const std::string &value)
+{
+    size_t length = value.length();
+    if (m_hasRange && (length < m_min || length > m_max))
+    {
+        return false;
+    }
+    else if (m_values.size() > 0)
+    {
+        if (m_values.end() == std::find(m_values.begin(), m_values.end(), value))
+        {
+            return false;
+        }
+    }
+
+    return true;
+}
+
+AttributeValueVariant StringProperty::buildValue()
+{
+    return m_defaultValue;
+}
+
+ArrayProperty::ArrayProperty()
+    :   AttributeProperty(AttributeProperty::Type::ARRAY),
+        m_min(0),
+        m_max(0),
+        m_isVariableSize(false),
+        m_isUnique(false),
+        m_hasRange(false) {}
+
+std::shared_ptr<ArrayProperty> ArrayProperty::build()
+{
+    return std::shared_ptr<ArrayProperty>(new ArrayProperty());
+}
+
+bool ArrayProperty::isArray() const
+{
+    return true;
+}
+
+std::shared_ptr<ArrayProperty> ArrayProperty::asArray()
+{
+    return shared_from_this();
+}
+
+void ArrayProperty::setRange(size_t minItems, size_t maxItems)
+{
+    m_min = minItems;
+    m_max = maxItems;
+    m_hasRange = true;
+}
+
+void ArrayProperty::setVariable(bool state)
+{
+    m_isVariableSize = state;
+}
+
+void ArrayProperty::setUnique(bool state)
+{
+    m_isUnique = state;
+}
+
+bool ArrayProperty::setElementProperty(const std::shared_ptr<AttributeProperty> &property)
+{
+    if (!property)
+        return false;
+
+    m_elementProperty = property;
+    return true;
+}
+
+bool ArrayProperty::hasRange() const
+{
+    return  m_hasRange;
+}
+
+bool ArrayProperty::isVariable() const
+{
+    return m_isVariableSize;
+}
+
+bool ArrayProperty::isUnique() const
+{
+    return m_isUnique;
+}
+
+size_t ArrayProperty::getMinItems() const
+{
+    return m_min;
+}
+
+size_t ArrayProperty::getMaxItems() const
+{
+    return m_max;
+}
+
+std::shared_ptr<AttributeProperty> ArrayProperty::getElementProperty()
+{
+    return m_elementProperty;
+}
+
+bool ArrayProperty::validate(const AttributeValueVariant &value)
+{
+    ArrayValidator arrayValidator(shared_from_this());
+    return boost::apply_visitor(arrayValidator, value);
+}
+
+AttributeValueVariant ArrayProperty::buildValue()
+{
+    // Find the depth and element property
+    std::shared_ptr<AttributeProperty> elementProperty;
+    int depth = findDepth(elementProperty);
+
+    if (depth < 1 || depth > 3)
+    {
+        throw SimulatorException(SIMULATOR_BAD_SCHEMA,
+                                 "No support for array of depth more than 3!");
+    }
+
+    AttributeValueVariant elementValue  = elementProperty->buildValue();
+    if (elementProperty->isInteger())
+    {
+        return buildArrayValue<int>(depth, elementValue);
+    }
+    else if (elementProperty->isDouble())
+    {
+        return buildArrayValue<double>(depth, elementValue);
+    }
+    else if (elementProperty->isBoolean())
+    {
+        return buildArrayValue<bool>(depth, elementValue);
+    }
+    else if (elementProperty->isString())
+    {
+        return buildArrayValue<std::string>(depth, elementValue);
+    }
+    else if (elementProperty->isModel())
+    {
+        return buildArrayValue<SimulatorResourceModel>(depth, elementValue);
+    }
+
+    throw SimulatorException(SIMULATOR_ERROR,
+                             "Failed to build value from property of type array!");
+}
+
+int ArrayProperty::findDepth(std::shared_ptr<AttributeProperty> &elementProperty)
+{
+    if (!m_elementProperty)
+    {
+        throw SimulatorException(SIMULATOR_BAD_SCHEMA, "Invalid Array property!");
+    }
+
+    if (!m_elementProperty->isArray())
+    {
+        elementProperty = m_elementProperty;
+        return 1;
+    }
+
+    return (1 + m_elementProperty->asArray()->findDepth(elementProperty));
+}
+
+ModelProperty::ModelProperty()
+    : AttributeProperty(AttributeProperty::Type::MODEL) {}
+
+std::shared_ptr<ModelProperty> ModelProperty::build()
+{
+    return std::shared_ptr<ModelProperty>(new ModelProperty());
+}
+
+bool ModelProperty::isModel() const
+{
+    return true;
+}
+
+std::shared_ptr<ModelProperty> ModelProperty::asModel()
+{
+    return shared_from_this();
+}
+
+bool ModelProperty::add(const std::string &name,
+                        const std::shared_ptr<AttributeProperty> &property, bool required)
+{
+    if (name.empty() || !property)
+        return false;
+
+    m_childProperties[name] = property;
+    m_requiredAttributes[name] = required;
+    return true;
+}
+
+std::shared_ptr<AttributeProperty> ModelProperty::get(
+    const std::string &name)
+{
+    if (m_childProperties.end() != m_childProperties.find(name))
+        return m_childProperties[name];
+    return nullptr;
+}
+
+std::unordered_map<std::string, std::shared_ptr<AttributeProperty> >
+ModelProperty::getChildProperties()
+{
+    return m_childProperties;
+}
+
+bool ModelProperty::isRequired(const std::string &name)
+{
+    if (m_requiredAttributes.end() == m_requiredAttributes.find(name))
+        return false;
+
+    return m_requiredAttributes[name];
+}
+
+void ModelProperty::remove(const std::string &name)
+{
+    if (m_requiredAttributes.end() != m_requiredAttributes.find(name))
+        m_requiredAttributes.erase(m_requiredAttributes.find(name));
+
+    if (m_childProperties.end() != m_childProperties.find(name))
+        m_childProperties.erase(m_childProperties.find(name));
+}
+
+void ModelProperty::setRequired(const std::string &name)
+{
+    if (m_requiredAttributes.end() != m_requiredAttributes.find(name))
+        m_requiredAttributes[name] = true;
+}
+
+void ModelProperty::unsetRequired(const std::string &name)
+{
+    if (m_requiredAttributes.end() != m_requiredAttributes.find(name))
+        m_requiredAttributes[name] = false;
+}
+
+bool ModelProperty::validate(const AttributeValueVariant &value)
+{
+    ModelValidator modelValidator(shared_from_this());
+    return boost::apply_visitor(modelValidator, value);
+}
+
+bool ModelProperty::validate(const SimulatorResourceModel &model)
+{
+    for (auto &attributeEntry : model.getAttributeValues())
+    {
+        std::shared_ptr<AttributeProperty> childProperty = get(attributeEntry.first);
+        if (childProperty)
+        {
+            if (!childProperty->validate(attributeEntry.second))
+                return false;
+        }
+    }
+
+    return true;
+}
+
+AttributeValueVariant ModelProperty::buildValue()
+{
+    return buildResourceModel();
+}
+
+SimulatorResourceModel ModelProperty::buildResourceModel()
+{
+    SimulatorResourceModel resourceModel;
+    for (auto &propertyElement : m_childProperties)
+    {
+        resourceModel.add(propertyElement.first, (propertyElement.second)->buildValue());
+    }
+
+    return resourceModel;
+}
index 08ca59f..b512d22 100644 (file)
 
 std::string getPayloadString(const OC::OCRepresentation &rep)
 {
-    std::ostringstream data;
     OCRepPayload *payload = rep.getPayload();
     if (!payload)
+        return "Empty payload";
+
+    std::ostringstream payLoadString;
+    while (payload)
     {
-        return "Payload: No payload";
+        // Payload type
+        std::string payloadType;
+        payloadType = getPayloadTypeString(payload->base.type);
+        payLoadString << "Payload type: " << payloadType << std::endl;
+
+        // URI
+        if (NULL != payload->uri && strlen(payload->uri) > 0)
+            payLoadString << "URI: " << payload->uri << std::endl;
+
+        // Types
+        std::ostringstream typeString;
+        OCStringLL *ocTypes = payload->types;
+        while (ocTypes)
+        {
+            if (NULL != ocTypes->value)
+            {
+                typeString << ocTypes->value;
+                if (ocTypes->next)
+                    typeString << ", ";
+            }
+
+            ocTypes = ocTypes->next;
+        }
+
+        if (!typeString.str().empty())
+        {
+            payLoadString << "Types: " << typeString.str() << std::endl;
+        }
+
+        // Interfaces
+        std::ostringstream interfaceString;
+        OCStringLL *ocInterfaces = payload->interfaces;
+        while (ocInterfaces)
+        {
+            if (NULL != ocInterfaces->value)
+            {
+                interfaceString << ocInterfaces->value;
+                if (ocInterfaces->next)
+                    interfaceString << ", ";
+            }
+
+            ocInterfaces = ocInterfaces->next;
+        }
+
+        if (!interfaceString.str().empty())
+        {
+            payLoadString << "Interfaces: " << interfaceString.str() << std::endl;
+        }
+
+        // Values
+        std::ostringstream valueString;
+        OCRepPayloadValue *ocValues = payload->values;
+        while (ocValues)
+        {
+            valueString << "\t" << ocValues->name << ":" << rep.getValueToString(ocValues->name) <<
+                        std::endl;
+            ocValues = ocValues->next;
+        }
+
+        if (!valueString.str().empty())
+        {
+            payLoadString << "Values:" << std::endl;
+            payLoadString << valueString.str();
+        }
+
+        payload = payload->next;
+        if (payload)
+            payLoadString << "----------------" << std::endl;
     }
 
-    // URI
-    data << "URI: " << payload->uri << std::endl;
+    return payLoadString.str();
+}
 
-    // Attributes
-    data << "Attributes:" << std::endl;
-    OCRepPayloadValue *values = payload->values;
-    while (NULL != values)
+std::string getPayloadTypeString(OCPayloadType type)
+{
+    std::string typeStr;
+    switch (type)
     {
-        data << values->name << ":" << rep.getValueToString(values->name) << std::endl;
-        values = values->next;
+        case PAYLOAD_TYPE_INVALID:
+            typeStr = "PAYLOAD_TYPE_INVALID";
+            break;
+        case PAYLOAD_TYPE_DISCOVERY:
+            typeStr = "PAYLOAD_TYPE_DISCOVERY";
+            break;
+        case PAYLOAD_TYPE_DEVICE:
+            typeStr = "PAYLOAD_TYPE_DEVICE";
+            break;
+        case PAYLOAD_TYPE_PLATFORM:
+            typeStr = "PAYLOAD_TYPE_PLATFORM";
+            break;
+        case PAYLOAD_TYPE_REPRESENTATION:
+            typeStr = "PAYLOAD_TYPE_REPRESENTATION";
+            break;
+        case PAYLOAD_TYPE_SECURITY:
+            typeStr = "PAYLOAD_TYPE_SECURITY";
+            break;
+        case PAYLOAD_TYPE_PRESENCE:
+            typeStr = "PAYLOAD_TYPE_PRESENCE";
+            break;
+        case PAYLOAD_TYPE_RD:
+            typeStr = "PAYLOAD_TYPE_RD";
+            break;
     }
-
-    return data.str();
+    return typeStr;
 }
 
 std::string getRequestString(const std::map<std::string, std::string> &queryParams,
                              const OC::OCRepresentation &rep)
 {
-    std::ostringstream data;
-    data << "qp: ";
+    std::ostringstream requestString;
     if (queryParams.size() > 0)
     {
-        for (auto & qp : queryParams)
-            data << qp.second << ",";
+        requestString << "qp: ";
+        for (auto &qp : queryParams)
+            requestString << qp.first << "=" << qp.second << ";";
     }
 
-    data << getPayloadString(rep);
-    return data.str();
+    requestString << std::endl;
+    requestString << getPayloadString(rep);
+    return requestString.str();
 }
 
 std::string getRequestString(const std::map<std::string, std::string> &queryParams)
 {
-    std::ostringstream data;
-    data << "qp: ";
+    std::ostringstream requestString;
     if (queryParams.size() > 0)
     {
-        for (auto & qp : queryParams)
-            data << qp.second << ",";
+        requestString << "qp: ";
+        for (auto &qp : queryParams)
+            requestString << qp.first << "=" << qp.second << ";";
     }
 
-    data << "Payload:  No payload";
-    return data.str();
-}
\ No newline at end of file
+    requestString << std::endl;
+    return requestString.str();
+}
index 23dd47f..1a4bc1c 100644 (file)
@@ -34,7 +34,7 @@
 #include <map>
 
 /**
- * Utilities for Invokation of OC platfrom level APIs.
+ * Utilities for Invocation of OC platfrom level APIs.
  */
 template <typename FnT, typename... ArgsT>
 typename std::enable_if<std::is_same<OCStackResult, decltype(std::declval<FnT>()(std::declval<ArgsT>()...))>::value>::type
@@ -62,8 +62,13 @@ namespace OC
 }
 
 std::string getPayloadString(const OC::OCRepresentation &);
+std::string getPayloadTypeString(OCPayloadType type);
 std::string getRequestString(const std::map<std::string, std::string> &queryParams,
                              const OC::OCRepresentation &rep);
 std::string getRequestString(const std::map<std::string, std::string> &queryParams);
 
-#endif
\ No newline at end of file
+
+#define VALIDATE_INPUT(CONDITION, MSG) if (CONDITION) {throw InvalidArgsException(SIMULATOR_INVALID_PARAM, MSG);}
+#define VALIDATE_CALLBACK(CALLBACK) if (!CALLBACK){throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");}
+
+#endif
diff --git a/service/simulator/src/server/oc_interface_details.cpp b/service/simulator/src/server/oc_interface_details.cpp
new file mode 100644 (file)
index 0000000..b32f1f6
--- /dev/null
@@ -0,0 +1,57 @@
+/******************************************************************
+ *
+ * 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 "oc_interface_details.h"
+
+OCInterfaceDetails::OCInterfaceDetails()
+{
+    m_interfaces[OC::DEFAULT_INTERFACE] = {"GET", "PUT", "POST"};
+    m_interfaces[OC::READ_INTERFACE] = {"GET"};
+    m_interfaces[OC::READWRITE_INTERFACE] = {"GET", "PUT", "POST"};
+    m_interfaces[OC::ACTUATOR_INTERFACE] = {"GET", "PUT", "POST"};
+    m_interfaces[OC::SENSOR_INTERFACE] = {"GET"};
+}
+
+OCInterfaceDetails *OCInterfaceDetails::getInstance()
+{
+    static OCInterfaceDetails instance;
+    return &instance;
+}
+
+bool OCInterfaceDetails::isInterface(const std::string &interfaceType)
+{
+    if (m_interfaces.end() != m_interfaces.find(interfaceType))
+        return true;
+    return true;
+}
+
+bool OCInterfaceDetails::isRequestSupported(const std::string &interfaceType,
+        const std::string &requestType)
+{
+    if (m_interfaces.end() != m_interfaces.find(interfaceType))
+    {
+        std::vector<std::string> requests = m_interfaces[interfaceType];
+        if (requests.end() != std::find(requests.begin(), requests.end(), requestType))
+            return true;
+    }
+
+    return false;
+}
+
diff --git a/service/simulator/src/server/oc_interface_details.h b/service/simulator/src/server/oc_interface_details.h
new file mode 100644 (file)
index 0000000..02d764b
--- /dev/null
@@ -0,0 +1,65 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file oc_interface_details.h
+ *
+ * @brief This file provides OIC definded interfaces and thier supported method types.
+ */
+
+#ifndef SIMULATOR_INTERFACE_DETAILS_H__
+#define SIMULATOR_INTERFACE_DETAILS_H__
+
+#include <iostream>
+#include <unordered_map>
+#include <vector>
+
+#include "OCApi.h"
+
+namespace OC
+{
+    // Read-Only interface
+    const std::string READ_INTERFACE = "oic.if.r";
+
+    // Read-Write Interface
+    const std::string READWRITE_INTERFACE = "oic.if.rw";
+
+    // Actuator Interface
+    const std::string ACTUATOR_INTERFACE = "oic.if.a";
+
+    // Sensor Interface
+    const std::string SENSOR_INTERFACE = "oic.if.s";
+}
+
+class OCInterfaceDetails
+{
+    public:
+        static OCInterfaceDetails *getInstance();
+        bool isInterface(const std::string &interfaceType);
+        bool isRequestSupported(const std::string &interfaceType, const std::string &requestType);
+
+    private:
+        OCInterfaceDetails();
+        ~OCInterfaceDetails() = default;
+
+        std::unordered_map<std::string, std::vector<std::string>> m_interfaces;
+};
+
+#endif
diff --git a/service/simulator/src/server/resource_update_automation.cpp b/service/simulator/src/server/resource_update_automation.cpp
new file mode 100644 (file)
index 0000000..8ccf78e
--- /dev/null
@@ -0,0 +1,232 @@
+/******************************************************************
+ *
+ * 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 "resource_update_automation.h"
+#include "simulator_single_resource_impl.h"
+#include "attribute_generator.h"
+#include "simulator_exceptions.h"
+#include "simulator_logger.h"
+#include "logger.h"
+
+#define ATAG "ATTRIBUTE_AUTOMATION"
+#define RTAG "RESOURCE_AUTOMATION"
+
+AttributeUpdateAutomation::AttributeUpdateAutomation(
+    int id, std::shared_ptr<SimulatorSingleResourceImpl> resource, const std::string &name,
+    AutoUpdateType type, int interval,
+    const SimulatorSingleResource::AutoUpdateCompleteCallback &callback,
+    std::function<void (const int)> finishedCallback)
+    :   m_id(id),
+        m_attrName(name),
+        m_type(type),
+        m_updateInterval(interval),
+        m_stopRequested(false),
+        m_resource(resource),
+        m_callback(callback),
+        m_finishedCallback(finishedCallback),
+        m_thread(nullptr)
+{
+    if (m_updateInterval < 0)
+        m_updateInterval = 0;
+}
+
+AttributeUpdateAutomation::~AttributeUpdateAutomation()
+{
+    if (!m_stopRequested)
+        m_thread->detach();
+}
+
+void AttributeUpdateAutomation::start()
+{
+    SimulatorResourceAttribute attribute;
+    if (false == m_resource->getAttribute(m_attrName, attribute))
+    {
+        OIC_LOG(ERROR, ATAG, "Attribute is not present in resource!");
+        throw SimulatorException(SIMULATOR_ERROR, "Attribute is not present in resource!");
+    }
+
+    m_thread.reset(new std::thread(&AttributeUpdateAutomation::updateAttribute, this, attribute));
+}
+
+void AttributeUpdateAutomation::stop()
+{
+    {
+        std::lock_guard<std::mutex> lock(m_lock);
+        m_stopRequested = true;
+    }
+
+    m_condVariable.notify_one();
+    if (m_thread)
+        m_thread->join();
+}
+
+void AttributeUpdateAutomation::updateAttribute(SimulatorResourceAttribute attribute)
+{
+    std::unique_lock<std::mutex> lock(m_lock);
+    std::chrono::system_clock::time_point now;
+
+    AttributeGenerator attributeGen(attribute);
+    do
+    {
+        try
+        {
+            SimulatorResourceAttribute attribute;
+            while (!m_stopRequested && true == attributeGen.next(attribute))
+            {
+                if (false == m_resource->updateAttributeValue(attribute))
+                    break;
+
+                // Wait for interval
+                now = std::chrono::system_clock::now();
+                m_condVariable.wait_until(lock, now + std::chrono::milliseconds(m_updateInterval),
+                                          [this] { return m_stopRequested; });
+            }
+
+            attributeGen.reset();
+        }
+        catch (SimulatorException &e)
+        {
+            break;
+        }
+    }
+    while (!m_stopRequested && AutoUpdateType::REPEAT == m_type);
+
+    if (!m_stopRequested)
+    {
+        OIC_LOG_V(DEBUG, ATAG, "Attribute:%s automation is completed!", m_attrName.c_str());
+        SIM_LOG(ILogger::INFO, "Attribute automation completed [Name: \"" << m_attrName
+                    << "\", id: " << m_id <<"].");
+    }
+    else
+    {
+        SIM_LOG(ILogger::INFO, "Attribute automation stopped [Name: \"" << m_attrName
+                    << "\", id: " << m_id <<"].");
+    }
+
+    // Notify application through callback
+    if (m_callback)
+        m_callback(m_resource->getURI(), m_id);
+
+    if (m_finishedCallback && !m_stopRequested)
+    {
+        std::thread notifyManager(m_finishedCallback, m_id);
+        notifyManager.detach();
+    }
+}
+
+ResourceUpdateAutomation::ResourceUpdateAutomation(
+    int id, std::shared_ptr<SimulatorSingleResourceImpl> resource, AutoUpdateType type, int interval,
+    const SimulatorSingleResource::AutoUpdateCompleteCallback &callback,
+    std::function<void (const int)> finishedCallback)
+    :   m_id(id),
+        m_type(type),
+        m_updateInterval(interval),
+        m_stopRequested(false),
+        m_resource(resource),
+        m_callback(callback),
+        m_finishedCallback(finishedCallback),
+        m_thread(nullptr)
+{
+    if (m_updateInterval < 0)
+        m_updateInterval = 0;
+}
+
+ResourceUpdateAutomation::~ResourceUpdateAutomation()
+{
+    if (!m_stopRequested)
+        m_thread->detach();
+}
+
+void ResourceUpdateAutomation::start()
+{
+    std::vector<SimulatorResourceAttribute> attributes;
+    for (auto &attributeEntry : m_resource->getAttributes())
+    {
+        attributes.push_back(attributeEntry.second);
+    }
+
+    if (0 == attributes.size())
+    {
+        OIC_LOG(ERROR, RTAG, "Resource has zero attributes!");
+        throw SimulatorException(SIMULATOR_ERROR, "Resource has zero attributes!");
+    }
+
+    m_thread.reset(new std::thread(&ResourceUpdateAutomation::updateAttributes, this, attributes));
+}
+
+void ResourceUpdateAutomation::stop()
+{
+    {
+        std::lock_guard<std::mutex> lock(m_lock);
+        m_stopRequested = true;
+    }
+
+    m_condVariable.notify_one();
+    if (m_thread)
+        m_thread->join();
+}
+
+void ResourceUpdateAutomation::updateAttributes(
+    std::vector<SimulatorResourceAttribute> attributes)
+{
+    std::unique_lock<std::mutex> lock(m_lock);
+    std::chrono::system_clock::time_point now;
+
+    do
+    {
+        AttributeCombinationGen attrCombGen(attributes);
+        SimulatorResourceModel newResModel;
+        while (!m_stopRequested && attrCombGen.next(newResModel))
+        {
+            SimulatorResourceModel updatedResModel;
+            m_resource->updateResourceModel(newResModel, updatedResModel);
+
+            // Wait for interval
+            now = std::chrono::system_clock::now();
+            m_condVariable.wait_until(lock, now + std::chrono::milliseconds(m_updateInterval),
+                                      [this] { return m_stopRequested; });
+        }
+    }
+    while (!m_stopRequested && AutoUpdateType::REPEAT == m_type);
+
+    if (!m_stopRequested)
+    {
+        OIC_LOG_V(DEBUG, RTAG, "Resource update automation complete [id: %d]!", m_id);
+        SIM_LOG(ILogger::INFO, "Resource automation completed [URI: \"" << m_resource->getURI()
+                << "\", id: " << m_id << "].");
+    }
+    else
+    {
+        SIM_LOG(ILogger::INFO, "Resource automation stopped [URI: \"" << m_resource->getURI()
+                << "\", id: " << m_id <<"].");
+    }
+
+    // Notify application
+    if (m_callback)
+        m_callback(m_resource->getURI(), m_id);
+
+    if (m_finishedCallback)
+    {
+        std::thread notifyManager(m_finishedCallback, m_id);
+        notifyManager.detach();
+    }
+
+}
+
diff --git a/service/simulator/src/server/resource_update_automation.h b/service/simulator/src/server/resource_update_automation.h
new file mode 100644 (file)
index 0000000..11839af
--- /dev/null
@@ -0,0 +1,93 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef RESOURCE_UPDATE_AUTOMATION_H_
+#define RESOURCE_UPDATE_AUTOMATION_H_
+
+#include <thread>
+#include <condition_variable>
+#include <atomic>
+
+#include "attribute_generator.h"
+#include "simulator_single_resource.h"
+
+class SimulatorSingleResourceImpl;
+class AttributeUpdateAutomation
+{
+    public:
+        AttributeUpdateAutomation(int id, std::shared_ptr<SimulatorSingleResourceImpl> resource,
+                                  const std::string &name, AutoUpdateType type, int interval,
+                                  const SimulatorSingleResource::AutoUpdateCompleteCallback &callback,
+                                  std::function<void (const int)> finishedCallback);
+
+        ~AttributeUpdateAutomation();
+        void start();
+        void stop();
+
+    private:
+        void updateAttribute(SimulatorResourceAttribute attribute);
+
+        int m_id;
+        std::string m_attrName;
+        AutoUpdateType m_type;
+        int m_updateInterval;
+        bool m_stopRequested;
+        std::shared_ptr<SimulatorSingleResourceImpl> m_resource;
+        SimulatorSingleResource::AutoUpdateCompleteCallback m_callback;
+        std::function<void (const int)> m_finishedCallback;
+        std::unique_ptr<std::thread> m_thread;
+
+        std::mutex m_lock;
+        std::condition_variable m_condVariable;
+};
+
+typedef std::shared_ptr<AttributeUpdateAutomation> AttributeUpdateAutomationSP;
+
+class ResourceUpdateAutomation
+{
+    public:
+        ResourceUpdateAutomation(int id, std::shared_ptr<SimulatorSingleResourceImpl> resource,
+                                 AutoUpdateType type, int interval,
+                                 const SimulatorSingleResource::AutoUpdateCompleteCallback &callback,
+                                 std::function<void (const int)> finishedCallback);
+
+        ~ResourceUpdateAutomation();
+        void start();
+        void stop();
+
+    private:
+        void updateAttributes(std::vector<SimulatorResourceAttribute> attributes);
+
+        int m_id;
+        AutoUpdateType m_type;
+        int m_updateInterval;
+        bool m_stopRequested;
+        std::shared_ptr<SimulatorSingleResourceImpl> m_resource;
+        SimulatorSingleResource::AutoUpdateCompleteCallback m_callback;
+        std::function<void (const int)> m_finishedCallback;
+        std::unique_ptr<std::thread> m_thread;
+
+        std::mutex m_lock;
+        std::condition_variable m_condVariable;
+};
+
+typedef std::shared_ptr<ResourceUpdateAutomation> ResourceUpdateAutomationSP;
+
+#endif
diff --git a/service/simulator/src/server/resource_update_automation_mngr.cpp b/service/simulator/src/server/resource_update_automation_mngr.cpp
new file mode 100644 (file)
index 0000000..98aa30e
--- /dev/null
@@ -0,0 +1,135 @@
+/******************************************************************
+ *
+ * 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 "resource_update_automation_mngr.h"
+#include "simulator_single_resource_impl.h"
+#include "simulator_exceptions.h"
+#include "simulator_logger.h"
+#include "logger.h"
+
+#define TAG "UPDATE_AUTOMATION_MNGR"
+
+int UpdateAutomationMngr::startResourceAutomation(
+    std::shared_ptr<SimulatorSingleResourceImpl> resource,
+    AutoUpdateType type, int interval,
+    const SimulatorSingleResource::AutoUpdateCompleteCallback &callback)
+{
+    ResourceUpdateAutomationSP resourceAutomation(new ResourceUpdateAutomation(
+                m_id, resource, type, interval, callback,
+                std::bind(&UpdateAutomationMngr::automationCompleted, this, std::placeholders::_1)));
+
+    std::lock_guard<std::mutex> lock(m_lock);
+    resourceAutomation->start();
+
+    SIM_LOG(ILogger::INFO, "Resource automation started [URI: \"" << resource->getURI()
+            << "\", id: " << m_id << "].");
+
+    m_resourceUpdationList[m_id] = resourceAutomation;
+    return m_id++;
+}
+
+int UpdateAutomationMngr::startAttributeAutomation(
+    std::shared_ptr<SimulatorSingleResourceImpl> resource,
+    const std::string &attrName, AutoUpdateType type, int interval,
+    const SimulatorSingleResource::AutoUpdateCompleteCallback &callback)
+{
+    AttributeUpdateAutomationSP attributeAutomation(new AttributeUpdateAutomation(
+                m_id, resource, attrName, type, interval, callback,
+                std::bind(&UpdateAutomationMngr::automationCompleted, this, std::placeholders::_1)));
+
+    std::lock_guard<std::mutex> lock(m_lock);
+    attributeAutomation->start();
+
+    SIM_LOG(ILogger::INFO, "Attribute automation started [Name: \"" << attrName << "\", id: "
+            << m_id << "].");
+
+    m_attrUpdationList[m_id] = attributeAutomation;
+    return m_id++;
+}
+
+std::vector<int> UpdateAutomationMngr::getResourceAutomationIds()
+{
+    std::vector<int> ids;
+    std::lock_guard<std::mutex> lock(m_lock);
+    for (auto &automation : m_resourceUpdationList)
+        ids.push_back(automation.first);
+
+    return ids;
+}
+
+std::vector<int> UpdateAutomationMngr::getAttributeAutomationIds()
+{
+    std::vector<int> ids;
+    std::lock_guard<std::mutex> lock(m_lock);
+    for (auto &automation : m_attrUpdationList)
+        ids.push_back(automation.first);
+
+    return ids;
+}
+
+void UpdateAutomationMngr::stop(int id)
+{
+    std::lock_guard<std::mutex> lock(m_lock);
+    if (m_resourceUpdationList.end() != m_resourceUpdationList.find(id))
+    {
+        m_resourceUpdationList[id]->stop();
+        m_resourceUpdationList.erase(m_resourceUpdationList.find(id));
+        return;
+    }
+    else if (m_attrUpdationList.end() != m_attrUpdationList.find(id))
+    {
+        m_attrUpdationList[id]->stop();
+        m_attrUpdationList.erase(m_attrUpdationList.find(id));
+        return;
+    }
+}
+
+void UpdateAutomationMngr::stopAll()
+{
+    std::lock_guard<std::mutex> lock(m_lock);
+    std::for_each(m_resourceUpdationList.begin(),
+                  m_resourceUpdationList.end(), [] (std::pair<int, ResourceUpdateAutomationSP> element)
+    {
+        element.second->stop();
+    });
+    m_resourceUpdationList.clear();
+
+    std::for_each(m_attrUpdationList.begin(),
+                  m_attrUpdationList.end(), [] (std::pair<int, AttributeUpdateAutomationSP> element)
+    {
+        element.second->stop();
+    });
+
+    m_attrUpdationList.clear();
+}
+
+void UpdateAutomationMngr::automationCompleted(int id)
+{
+    std::lock_guard<std::mutex> lock(m_lock);
+    if (m_resourceUpdationList.end() != m_resourceUpdationList.find(id))
+    {
+        m_resourceUpdationList.erase(m_resourceUpdationList.find(id));
+    }
+    else if (m_attrUpdationList.end() != m_attrUpdationList.find(id))
+    {
+        m_attrUpdationList.erase(m_attrUpdationList.find(id));
+    }
+}
+
diff --git a/service/simulator/src/server/resource_update_automation_mngr.h b/service/simulator/src/server/resource_update_automation_mngr.h
new file mode 100644 (file)
index 0000000..dcf2419
--- /dev/null
@@ -0,0 +1,58 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_RESOURCE_UPDATE_AUTOMATION_MNGR_H_
+#define SIMULATOR_RESOURCE_UPDATE_AUTOMATION_MNGR_H_
+
+#include "resource_update_automation.h"
+#include <unordered_map>
+
+class SimulatorSingleResourceImpl;
+class UpdateAutomationMngr
+{
+    public:
+        UpdateAutomationMngr() : m_id(0) {}
+
+        int startResourceAutomation(std::shared_ptr<SimulatorSingleResourceImpl> resource,
+                                    AutoUpdateType type, int interval,
+                                    const SimulatorSingleResource::AutoUpdateCompleteCallback &callback);
+
+        int startAttributeAutomation(std::shared_ptr<SimulatorSingleResourceImpl> resource,
+                                     const std::string &attrName, AutoUpdateType type, int interval,
+                                     const SimulatorSingleResource::AutoUpdateCompleteCallback &callback);
+
+        std::vector<int> getResourceAutomationIds();
+
+        std::vector<int> getAttributeAutomationIds();
+
+        void stop(int updationID);
+
+        void stopAll();
+
+    private:
+        void automationCompleted(int id);
+
+        int m_id;
+        std::mutex m_lock;
+        std::unordered_map<int, ResourceUpdateAutomationSP> m_resourceUpdationList;
+        std::unordered_map<int, AttributeUpdateAutomationSP> m_attrUpdationList;
+};
+
+#endif
diff --git a/service/simulator/src/server/simulator_collection_resource_impl.cpp b/service/simulator/src/server/simulator_collection_resource_impl.cpp
new file mode 100755 (executable)
index 0000000..f7b1a2a
--- /dev/null
@@ -0,0 +1,669 @@
+/******************************************************************
+ *
+ * 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 "simulator_collection_resource_impl.h"
+#include "simulator_utils.h"
+#include "oc_interface_details.h"
+#include "simulator_logger.h"
+#include "logger.h"
+
+#define TAG "SIMULATOR_COLLECTION_RESOURCE"
+
+SimulatorCollectionResourceImpl::SimulatorCollectionResourceImpl()
+{
+    m_type = SimulatorResource::Type::COLLECTION_RESOURCE;
+    m_interfaces.push_back(OC::LINK_INTERFACE);
+    m_property = static_cast<OCResourceProperty>(OC_DISCOVERABLE | OC_OBSERVABLE);
+
+    // Add empty vector of OIC Links
+    std::vector<SimulatorResourceModel> links;
+    m_resModel.add("links", links);
+
+    m_resourceHandle = nullptr;
+}
+
+bool SimulatorCollectionResourceImpl::isCollection() const
+{
+    return true;
+}
+
+void SimulatorCollectionResourceImpl::setName(const std::string &name)
+{
+    VALIDATE_INPUT(name.empty(), "Name is empty!")
+    m_name = name;
+}
+
+void SimulatorCollectionResourceImpl::setURI(const std::string &uri)
+{
+    VALIDATE_INPUT(uri.empty(), "Uri is empty!")
+
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (m_resourceHandle)
+    {
+        throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED,
+                                 "URI can not be set when resource is started!");
+    }
+
+    m_uri = uri;
+}
+
+void SimulatorCollectionResourceImpl::setResourceType(const std::string &resourceType)
+{
+    VALIDATE_INPUT(resourceType.empty(), "Resource type is empty!")
+
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (m_resourceHandle)
+    {
+        throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED,
+                                 "Resource type can not be set when resource is started!");
+    }
+
+    m_resourceType = resourceType;
+}
+
+void SimulatorCollectionResourceImpl::setInterface(const std::string &interfaceType)
+{
+    VALIDATE_INPUT(interfaceType.empty(), "Interface type list is empty!")
+
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (m_resourceHandle)
+    {
+        throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED,
+                                 "Resource interface can not be reset when resource is started!");
+    }
+
+    m_interfaces = {interfaceType};
+}
+
+void SimulatorCollectionResourceImpl::setInterface(const std::vector<std::string> &interfaceTypes)
+{
+    VALIDATE_INPUT(interfaceTypes.empty(), "Interface type list is empty!")
+
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (m_resourceHandle)
+    {
+        throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED,
+                                 "Resource interface can not be reset when resource is started!");
+    }
+
+    m_interfaces = interfaceTypes;
+    auto lastElement = std::unique(m_interfaces.begin(), m_interfaces.end());
+    m_interfaces.erase(lastElement, m_interfaces.end());
+}
+
+void SimulatorCollectionResourceImpl::addInterface(const std::string &interfaceType)
+{
+    VALIDATE_INPUT(interfaceType.empty(), "Interface type is empty!")
+
+    if (interfaceType == OC::LINK_INTERFACE
+        || interfaceType == OC::BATCH_INTERFACE
+        || interfaceType == OC::DEFAULT_INTERFACE)
+    {
+        if (m_interfaces.end() != std::find(m_interfaces.begin(), m_interfaces.end(), interfaceType))
+        {
+            SIM_LOG(ILogger::ERROR, "Resource already supporting this Interface: " << interfaceType);
+            return;
+        }
+
+        std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+        typedef OCStackResult (*bindInterfaceToResource)(const OCResourceHandle &,
+                const std::string &);
+
+        invokeocplatform(static_cast<bindInterfaceToResource>(
+                             OC::OCPlatform::bindInterfaceToResource), m_resourceHandle,
+                         interfaceType);
+    }
+    else
+    {
+        throw NoSupportException("Invalid interface type for a collection type resource!");
+    }
+
+    m_interfaces.push_back(interfaceType);
+}
+
+void SimulatorCollectionResourceImpl::setObservable(bool state)
+{
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (m_resourceHandle)
+    {
+        throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED,
+                                 "Observation state can not be changed when resource is started!");
+    }
+
+    if (state)
+        m_property = static_cast<OCResourceProperty>(m_property | OC_OBSERVABLE);
+    else
+        m_property = static_cast<OCResourceProperty>(m_property ^ OC_OBSERVABLE);
+}
+
+void SimulatorCollectionResourceImpl::setDiscoverable(bool state)
+{
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (m_resourceHandle)
+    {
+        throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED,
+                                 "Discoverable state can not be changed when resource is started!");
+    }
+
+    if (state)
+        m_property = static_cast<OCResourceProperty>(m_property | OC_DISCOVERABLE);
+    else
+        m_property = static_cast<OCResourceProperty>(m_property ^ OC_DISCOVERABLE);
+}
+
+void SimulatorCollectionResourceImpl::setObserverCallback(ObserverCallback callback)
+{
+    VALIDATE_CALLBACK(callback)
+    m_observeCallback = callback;
+}
+
+void SimulatorCollectionResourceImpl::setModelChangeCallback(ResourceModelUpdateCallback callback)
+{
+    VALIDATE_CALLBACK(callback)
+    m_modelCallback = callback;
+}
+
+bool SimulatorCollectionResourceImpl::isObservable() const
+{
+    return ((m_property & OC_OBSERVABLE) == OC_OBSERVABLE);
+}
+
+bool SimulatorCollectionResourceImpl::isDiscoverable() const
+{
+    return ((m_property & OC_DISCOVERABLE) == OC_DISCOVERABLE);
+}
+
+bool SimulatorCollectionResourceImpl::isStarted() const
+{
+    return (nullptr != m_resourceHandle);
+}
+
+void SimulatorCollectionResourceImpl::start()
+{
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (m_resourceHandle)
+    {
+        SIM_LOG(ILogger::INFO, "[" << m_name << "] " << "Resource already started!")
+        return;
+    }
+
+    if (m_uri.empty() || m_resourceType.empty())
+    {
+        throw SimulatorException(SIMULATOR_ERROR, "Incomplete data to start resource!");
+    }
+
+    typedef OCStackResult (*RegisterResource)(OCResourceHandle &, std::string &, const std::string &,
+            const std::string &, OC::EntityHandler, uint8_t);
+
+    invokeocplatform(static_cast<RegisterResource>(OC::OCPlatform::registerResource),
+                     m_resourceHandle, m_uri, m_resourceType, m_interfaces[0],
+                     std::bind(&SimulatorCollectionResourceImpl::handleRequests,
+                               this, std::placeholders::_1), m_property);
+
+    for (size_t index = 1; m_interfaces.size() > 1 && index < m_interfaces.size(); index++)
+    {
+        typedef OCStackResult (*bindInterfaceToResource)(const OCResourceHandle &,
+                const std::string &);
+
+        try
+        {
+            invokeocplatform(static_cast<bindInterfaceToResource>(
+                                 OC::OCPlatform::bindInterfaceToResource), m_resourceHandle,
+                             m_interfaces[index]);
+        }
+        catch (SimulatorException &e)
+        {
+            stop();
+            throw;
+        }
+    }
+}
+
+void SimulatorCollectionResourceImpl::stop()
+{
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (!m_resourceHandle)
+    {
+        SIM_LOG(ILogger::INFO, "[" << m_name << "] " << "Resource is not started yet!")
+        return;
+    }
+
+    // Unregister the resource from stack
+    typedef OCStackResult (*UnregisterResource)(const OCResourceHandle &);
+
+    invokeocplatform(static_cast<UnregisterResource>(OC::OCPlatform::unregisterResource),
+                     m_resourceHandle);
+
+    m_resourceHandle = nullptr;
+}
+
+SimulatorResourceModel SimulatorCollectionResourceImpl::getResourceModel()
+{
+    std::lock_guard<std::mutex> lock(m_modelLock);
+    return m_resModel;
+}
+
+std::vector<ObserverInfo> SimulatorCollectionResourceImpl::getObservers() const
+{
+    return m_observersList;
+}
+
+void SimulatorCollectionResourceImpl::notify(int observerID)
+{
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (!m_resourceHandle)
+        return;
+
+    OC::ObservationIds observers {static_cast<OCObservationId>(observerID)};
+    sendNotification(observers);
+}
+
+void SimulatorCollectionResourceImpl::notifyAll()
+{
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (!m_resourceHandle)
+        return;
+
+    if (!m_observersList.size())
+        return;
+
+    OC::ObservationIds observers;
+    for (auto &observer : m_observersList)
+        observers.push_back(observer.id);
+    sendNotification(observers);
+}
+
+std::vector<std::string> SimulatorCollectionResourceImpl::getSupportedResources()
+{
+    return m_supportedTypes;
+}
+
+void SimulatorCollectionResourceImpl::addChildResource(const SimulatorResourceSP &resource)
+{
+    VALIDATE_INPUT(!resource, "Invalid child resource!")
+
+    std::lock_guard<std::mutex> lock(m_childResourcesLock);
+    if (m_childResources.end() != m_childResources.find(resource->getURI()))
+    {
+        throw SimulatorException(SIMULATOR_ERROR, "Child resource with same URI is already exisit!");
+    }
+
+    m_childResources[resource->getURI()] = resource;
+    addLink(resource);
+
+    // Notify application and observers
+    if (m_modelCallback)
+        m_modelCallback(m_uri, m_resModel);
+    notifyAll();
+}
+
+void SimulatorCollectionResourceImpl::removeChildResource(const SimulatorResourceSP &resource)
+{
+    VALIDATE_INPUT(!resource, "Invalid child resource!")
+
+    std::lock_guard<std::mutex> lock(m_childResourcesLock);
+    if (m_childResources.end() == m_childResources.find(resource->getURI()))
+    {
+        throw SimulatorException(SIMULATOR_ERROR, "Child resource not found in collection!");
+    }
+
+    removeLink(resource->getURI());
+    m_childResources.erase(m_childResources.find(resource->getURI()));
+
+    // Notify application and observers
+    if (m_modelCallback)
+        m_modelCallback(m_uri, m_resModel);
+    notifyAll();
+}
+
+void SimulatorCollectionResourceImpl::removeChildResource(const std::string &uri)
+{
+    VALIDATE_INPUT(uri.empty(), "Uri is empty!")
+
+    std::lock_guard<std::mutex> lock(m_childResourcesLock);
+    if (m_childResources.end() == m_childResources.find(uri))
+    {
+        throw SimulatorException(SIMULATOR_ERROR, "Child resource not found in collection!");
+    }
+
+    removeLink(uri);
+    m_childResources.erase(m_childResources.find(uri));
+
+    // Notify application and observers
+    if (m_modelCallback)
+        m_modelCallback(m_uri, m_resModel);
+    notifyAll();
+}
+
+std::vector<SimulatorResourceSP> SimulatorCollectionResourceImpl::getChildResources()
+{
+    std::lock_guard<std::mutex> lock(m_childResourcesLock);
+
+    std::vector<SimulatorResourceSP> result;
+    for (auto &entry : m_childResources)
+        result.push_back(entry.second);
+
+    return result;
+}
+
+void SimulatorCollectionResourceImpl::setResourceModel(const SimulatorResourceModel &resModel)
+{
+    std::lock_guard<std::mutex> lock(m_modelLock);
+    m_resModel = resModel;
+}
+
+void SimulatorCollectionResourceImpl::setResourceModelSchema(
+    const std::shared_ptr<SimulatorResourceModelSchema> &resModelSchema)
+{
+    std::lock_guard<std::mutex> lock(m_modelSchemaLock);
+    m_resModelSchema = resModelSchema;
+}
+
+void SimulatorCollectionResourceImpl::setRequestModel(
+    const std::unordered_map<std::string, std::shared_ptr<RequestModel>> &requestModels)
+{
+    m_requestModels = requestModels;
+}
+
+OCEntityHandlerResult SimulatorCollectionResourceImpl::handleRequests(
+    std::shared_ptr<OC::OCResourceRequest> request)
+{
+    if (!request)
+    {
+        OIC_LOG(ERROR, TAG, "Request received from stack is null!");
+        return OC_EH_ERROR;
+    }
+
+    // Handle GET, PUT, POST and DELETE requests
+    if (OC::RequestHandlerFlag::RequestFlag & request->getRequestHandlerFlag())
+    {
+        {
+            OC::OCRepresentation rep = request->getResourceRepresentation();
+            std::string payload = getPayloadString(rep);
+            SIM_LOG(ILogger::INFO, "[" << m_name << "] " << request->getRequestType()
+                    << " request received. \n**Payload details**\n" << payload)
+        }
+
+        // Check if resource support GET request
+        if (m_requestModels.end() == m_requestModels.find(request->getRequestType()))
+        {
+            SIM_LOG(ILogger::INFO, "Resource does not support GET request!")
+            return sendResponse(request, 405, OC_EH_ERROR);
+        }
+
+        // Handling interface query parameter "if"
+        auto interfaceType = m_interfaces[0];
+        auto requestQueryParams = request->getQueryParameters();
+        if (requestQueryParams.end() != requestQueryParams.find("if"))
+        {
+            interfaceType = requestQueryParams["if"];
+        }
+
+        if (!isValidInterface(interfaceType, request->getRequestType()))
+        {
+            SIM_LOG(ILogger::INFO, "Invalid interface type: " << interfaceType)
+            return OC_EH_ERROR;
+        }
+
+        // Handover the request to appropriate interface handler
+        std::shared_ptr<OC::OCResourceResponse> response;
+        if (interfaceType == OC::DEFAULT_INTERFACE)
+        {
+            response = requestOnBaseLineInterface(request);
+        }
+        else if (interfaceType == OC::LINK_INTERFACE)
+        {
+            response = requestOnLinkListInterface(request);
+        }
+        else if (interfaceType == OC::BATCH_INTERFACE)
+        {
+            response = requestOnBatchInterface(request);
+        }
+
+        // Send response if the request handled by resource
+        if (response)
+        {
+            if (OC_STACK_OK != OC::OCPlatform::sendResponse(response))
+                return OC_EH_ERROR;
+        }
+        else
+        {
+            SIM_LOG(ILogger::ERROR, "[" << m_name << "] " << "Unsupported request received!")
+            return OC_EH_ERROR;
+        }
+    }
+
+    if (OC::RequestHandlerFlag::ObserverFlag & request->getRequestHandlerFlag())
+    {
+        if (!isObservable())
+        {
+            SIM_LOG(ILogger::INFO, "[" << m_uri << "] Resource is not observable, sending error response!")
+            return OC_EH_ERROR;
+        }
+
+        OC::ObservationInfo observationInfo = request->getObservationInfo();
+        if (OC::ObserveAction::ObserveRegister == observationInfo.action)
+        {
+            SIM_LOG(ILogger::INFO, "[" << m_uri << "] OBSERVE REGISTER request received");
+
+            ObserverInfo info {observationInfo.obsId, observationInfo.address, observationInfo.port};
+            m_observersList.push_back(info);
+
+            if (m_observeCallback)
+                m_observeCallback(m_uri, ObservationStatus::REGISTER, info);
+        }
+        else if (OC::ObserveAction::ObserveUnregister == observationInfo.action)
+        {
+            SIM_LOG(ILogger::INFO, "[" << m_uri << "] OBSERVE UNREGISTER request received");
+
+            ObserverInfo info;
+            for (auto iter = m_observersList.begin(); iter != m_observersList.end(); iter++)
+            {
+                if ((info = *iter), info.id == observationInfo.obsId)
+                {
+                    m_observersList.erase(iter);
+                    break;
+                }
+            }
+
+            if (m_observeCallback)
+                m_observeCallback(m_uri, ObservationStatus::UNREGISTER, info);
+        }
+    }
+
+    return OC_EH_OK;
+}
+
+std::shared_ptr<OC::OCResourceResponse> SimulatorCollectionResourceImpl::requestOnBaseLineInterface(
+    std::shared_ptr<OC::OCResourceRequest> request)
+{
+    std::shared_ptr<OC::OCResourceResponse> response;
+    if ("GET" == request->getRequestType())
+    {
+        // Construct the representation
+        OC::OCRepresentation ocRep = m_resModel.asOCRepresentation();
+        response = std::make_shared<OC::OCResourceResponse>();
+        response->setErrorCode(200);
+        response->setResponseResult(OC_EH_OK);
+        response->setResourceRepresentation(ocRep);
+        std::string resPayload = getPayloadString(ocRep);
+        SIM_LOG(ILogger::INFO, "[" << m_uri <<
+                "] Sending response for GET request. \n**Payload details**" << resPayload)
+    }
+
+    if (response)
+    {
+        response->setRequestHandle(request->getRequestHandle());
+        response->setResourceHandle(request->getResourceHandle());
+    }
+
+    return response;
+}
+
+std::shared_ptr<OC::OCResourceResponse> SimulatorCollectionResourceImpl::requestOnLinkListInterface(
+    std::shared_ptr<OC::OCResourceRequest> request)
+{
+    std::lock_guard<std::mutex> lock(m_childResourcesLock);
+    std::shared_ptr<OC::OCResourceResponse> response;
+
+    if ("GET" == request->getRequestType())
+    {
+        // Construct the representation
+        OC::OCRepresentation ocRep;
+        std::vector<OC::OCRepresentation> links;
+        for (auto &entry : m_childResources)
+        {
+            OC::OCRepresentation oicLink;
+            oicLink.setValue("href", entry.second->getURI());
+            oicLink.setValue("rt", entry.second->getResourceType());
+            oicLink.setValue("if", entry.second->getInterface()[0]);
+            links.push_back(oicLink);
+        }
+
+        ocRep.setValue("links", links);
+
+        response = std::make_shared<OC::OCResourceResponse>();
+        response->setRequestHandle(request->getRequestHandle());
+        response->setResourceHandle(request->getResourceHandle());
+        response->setErrorCode(200);
+        response->setResponseResult(OC_EH_OK);
+        response->setResourceRepresentation(ocRep);
+        std::string resPayload = getPayloadString(ocRep);
+        SIM_LOG(ILogger::INFO, "[" << m_uri <<
+                "] Sending response for GET request. \n**Payload details**" << resPayload)
+    }
+
+    return nullptr;
+}
+
+std::shared_ptr<OC::OCResourceResponse> SimulatorCollectionResourceImpl::requestOnBatchInterface(
+    std::shared_ptr<OC::OCResourceRequest>)
+{
+    return nullptr;
+}
+
+void SimulatorCollectionResourceImpl::sendNotification(OC::ObservationIds &observers)
+{
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    std::shared_ptr<OC::OCResourceResponse> response(new OC::OCResourceResponse());
+    response->setErrorCode(200);
+    response->setResponseResult(OC_EH_OK);
+
+    OC::OCRepresentation ocRep = m_resModel.asOCRepresentation();
+    response->setResourceRepresentation(ocRep, OC::DEFAULT_INTERFACE);
+
+    typedef OCStackResult (*NotifyListOfObservers)(OCResourceHandle, OC::ObservationIds &,
+            const std::shared_ptr<OC::OCResourceResponse>);
+
+    invokeocplatform(static_cast<NotifyListOfObservers>(OC::OCPlatform::notifyListOfObservers),
+                     m_resourceHandle, observers, response);
+}
+
+void SimulatorCollectionResourceImpl::addLink(const SimulatorResourceSP &resource)
+{
+    std::lock_guard<std::mutex> lock(m_modelLock);
+    if (!m_resModel.contains("links"))
+        return;
+
+    // Create new OIC Link
+    SimulatorResourceModel newLink;
+    newLink.add("href", resource->getURI());
+    newLink.add("rt", resource->getResourceType());
+    newLink.add("if", resource->getInterface()[0]);
+
+    // Add OIC Link if it is not present
+    bool found = false;
+    std::vector<SimulatorResourceModel> links =
+        m_resModel.get<std::vector<SimulatorResourceModel>>("links");
+    for (auto &link : links)
+    {
+        std::string linkURI = link.get<std::string>("href");
+        if (linkURI == resource->getURI())
+        {
+            found = true;
+            break;
+        }
+    }
+
+    if (false ==  found)
+    {
+        links.push_back(newLink);
+        m_resModel.update("links", links);
+    }
+}
+
+void SimulatorCollectionResourceImpl::removeLink(std::string uri)
+{
+    std::lock_guard<std::mutex> lock(m_modelLock);
+    if (!m_resModel.contains("links"))
+        return;
+
+    // Add OIC Link if it is not present
+    std::vector<SimulatorResourceModel> links =
+        m_resModel.get<std::vector<SimulatorResourceModel>>("links");
+    for (size_t i = 0; i < links.size(); i++)
+    {
+        std::string linkURI = links[i].get<std::string>("href");
+        if (linkURI == uri)
+        {
+            links.erase(links.begin() + i);
+            m_resModel.update("links", links);
+            break;
+        }
+    }
+}
+
+OCEntityHandlerResult SimulatorCollectionResourceImpl::sendResponse(
+    const std::shared_ptr<OC::OCResourceRequest> &request, const int errorCode,
+    OCEntityHandlerResult responseResult)
+{
+    std::shared_ptr<OC::OCResourceResponse> response(new OC::OCResourceResponse());
+    response->setRequestHandle(request->getRequestHandle());
+    response->setResourceHandle(request->getResourceHandle());
+    response->setErrorCode(errorCode);
+    response->setResponseResult(responseResult);
+    if (OC_STACK_OK != OC::OCPlatform::sendResponse(response))
+    {
+        return OC_EH_ERROR;
+    }
+
+    return OC_EH_OK;
+}
+
+bool SimulatorCollectionResourceImpl::isValidInterface(const std::string &interfaceType,
+        const std::string &requestType)
+{
+    // Is this OIC defined interface ?
+    if (false ==
+        OCInterfaceDetails::getInstance()->isRequestSupported(interfaceType, requestType))
+    {
+        return false;
+    }
+
+    // Does resource support this interface ?
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (m_interfaces.end() ==
+        std::find(m_interfaces.begin(), m_interfaces.end(), interfaceType))
+    {
+        return false;
+    }
+
+    return true;
+}
\ No newline at end of file
diff --git a/service/simulator/src/server/simulator_collection_resource_impl.h b/service/simulator/src/server/simulator_collection_resource_impl.h
new file mode 100755 (executable)
index 0000000..bf22985
--- /dev/null
@@ -0,0 +1,102 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_COLLECTION_RESOURCE_IMPL_H_
+#define SIMULATOR_COLLECTION_RESOURCE_IMPL_H_
+
+#include "simulator_collection_resource.h"
+#include "simulator_resource_model_schema.h"
+#include "request_model.h"
+#include "RamlParser.h"
+
+class SimulatorResourceFactory;
+class SimulatorCollectionResourceImpl : public SimulatorCollectionResource
+{
+    public:
+        friend class SimulatorResourceFactory;
+
+        bool isCollection() const;
+        void setName(const std::string &name);
+        void setURI(const std::string &uri);
+        void setResourceType(const std::string &resourceType);
+        void setInterface(const std::string &interfaceType);
+        void setInterface(const std::vector<std::string> &interfaceTypes);
+        void addInterface(const std::string &interfaceType);
+        void setObservable(bool state);
+        void setDiscoverable(bool state);
+        void setObserverCallback(ObserverCallback callback);
+        void setModelChangeCallback(ResourceModelUpdateCallback callback);
+        bool isObservable() const;
+        bool isDiscoverable() const;
+        bool isStarted() const;
+        void start();
+        void stop();
+        SimulatorResourceModel getResourceModel();
+        std::vector<ObserverInfo> getObservers() const;
+        void notify(int observerID);
+        void notifyAll();
+
+        std::vector<std::string> getSupportedResources();
+        void addChildResource(const std::shared_ptr<SimulatorResource> &resource);
+        void removeChildResource(const std::shared_ptr<SimulatorResource> &resource);
+        void removeChildResource(const std::string &uri);
+        std::vector<SimulatorResourceSP> getChildResources();
+
+    private:
+        SimulatorCollectionResourceImpl();
+        void setResourceModel(const SimulatorResourceModel &resModel);
+        void setResourceModelSchema(
+            const std::shared_ptr<SimulatorResourceModelSchema> &resModelSchema);
+        void setRequestModel(
+            const std::unordered_map<std::string, std::shared_ptr<RequestModel>> &requestModels);
+
+        OCEntityHandlerResult handleRequests(std::shared_ptr<OC::OCResourceRequest> request);
+        std::shared_ptr<OC::OCResourceResponse> requestOnBaseLineInterface(
+            std::shared_ptr<OC::OCResourceRequest> request);
+        std::shared_ptr<OC::OCResourceResponse> requestOnLinkListInterface(
+            std::shared_ptr<OC::OCResourceRequest> request);
+        std::shared_ptr<OC::OCResourceResponse> requestOnBatchInterface(
+            std::shared_ptr<OC::OCResourceRequest> request);
+        OCEntityHandlerResult sendResponse(const std::shared_ptr<OC::OCResourceRequest> &request,
+                                           const int errorCode, OCEntityHandlerResult responseResult);
+        void sendNotification(OC::ObservationIds &observers);
+        void addLink(const std::shared_ptr<SimulatorResource> &resource);
+        void removeLink(std::string uri);
+        bool isValidInterface(const std::string &interfaceType, const std::string &requestType);
+
+        std::recursive_mutex m_objectLock;
+        std::mutex m_modelLock;
+        std::mutex m_childResourcesLock;
+        std::mutex m_modelSchemaLock;
+        SimulatorResourceModel m_resModel;
+        std::shared_ptr<SimulatorResourceModelSchema> m_resModelSchema;
+        std::unordered_map<std::string, std::shared_ptr<RequestModel>> m_requestModels;
+        std::map<std::string, SimulatorResourceSP> m_childResources;
+        std::vector<std::string> m_supportedTypes;
+        std::vector<ObserverInfo> m_observersList;
+
+        ObserverCallback m_observeCallback;
+        ResourceModelUpdateCallback m_modelCallback;
+
+        OCResourceProperty m_property;
+        OCResourceHandle m_resourceHandle;
+};
+
+#endif
diff --git a/service/simulator/src/server/simulator_resource.cpp b/service/simulator/src/server/simulator_resource.cpp
new file mode 100644 (file)
index 0000000..4a9a775
--- /dev/null
@@ -0,0 +1,52 @@
+/******************************************************************
+ *
+ * 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 "simulator_resource.h"
+
+bool SimulatorResource::isCollection() const
+{
+    return false;
+}
+
+SimulatorResource::Type SimulatorResource::getType() const
+{
+    return m_type;
+}
+
+std::string SimulatorResource::getName() const
+{
+    return m_name;
+}
+
+std::string SimulatorResource::getURI() const
+{
+    return m_uri;
+}
+
+std::string SimulatorResource::getResourceType() const
+{
+    return m_resourceType;
+}
+
+std::vector<std::string> SimulatorResource::getInterface() const
+{
+    return m_interfaces;
+}
+
diff --git a/service/simulator/src/server/simulator_resource_factory.cpp b/service/simulator/src/server/simulator_resource_factory.cpp
new file mode 100644 (file)
index 0000000..15bc6ff
--- /dev/null
@@ -0,0 +1,324 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 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
+#include "simulator_resource_factory.h"\r
+#include "simulator_single_resource_impl.h"\r
+#include "simulator_collection_resource_impl.h"\r
+#include "simulator_logger.h"\r
+#include "logger.h"\r
+#include "request_model_builder.h"\r
+\r
+#define TAG "SIM_RESOURCE_FACTORY"\r
+\r
+SimulatorResourceFactory *SimulatorResourceFactory::getInstance()\r
+{\r
+    static SimulatorResourceFactory s_instance;\r
+    return &s_instance;\r
+}\r
+\r
+std::shared_ptr<SimulatorResource> SimulatorResourceFactory::createResource(\r
+    const std::string &configPath)\r
+{\r
+    // Parse the RAML file\r
+    std::shared_ptr<RAML::RamlParser> ramlParser = std::make_shared<RAML::RamlParser>(configPath);\r
+    if (!ramlParser)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "RAML parser returned NULL!");\r
+        return nullptr;\r
+    }\r
+\r
+    RAML::RamlPtr raml = ramlParser->getRamlPtr();\r
+    if (!raml)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "RAML pointer is NULL!");\r
+        return nullptr;\r
+    }\r
+\r
+    // Get the first resource model from RAML\r
+    RAML::RamlResourcePtr ramlResource;\r
+    if (0 == raml->getResources().size()\r
+        || nullptr == (ramlResource = raml->getResources().begin()->second))\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Zero resources detected from RAML!");\r
+        return nullptr;\r
+    }\r
+\r
+    return buildResource(ramlResource);\r
+}\r
+\r
+std::vector<std::shared_ptr<SimulatorResource> > SimulatorResourceFactory::createResource(\r
+    const std::string &configPath, unsigned int count)\r
+{\r
+    std::vector<std::shared_ptr<SimulatorResource>> resources;\r
+\r
+    // Parse the RAML file\r
+    std::shared_ptr<RAML::RamlParser> ramlParser = std::make_shared<RAML::RamlParser>(configPath);\r
+    if (!ramlParser)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "RAML parser returned NULL!");\r
+        return resources;\r
+    }\r
+\r
+    RAML::RamlPtr raml = ramlParser->getRamlPtr();\r
+    if (!raml)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "RAML pointer is NULL!");\r
+        return resources;\r
+    }\r
+\r
+    // Get the first resource model from RAML\r
+    RAML::RamlResourcePtr ramlResource;\r
+    if (0 == raml->getResources().size()\r
+        || nullptr == (ramlResource = raml->getResources().begin()->second))\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Zero resources detected from RAML!");\r
+        return resources;\r
+    }\r
+\r
+    while (count--)\r
+    {\r
+        std::shared_ptr<SimulatorResource> resource = buildResource(ramlResource);\r
+        if (!resource)\r
+        {\r
+            OIC_LOG(ERROR, TAG, "Failed to create resource!");\r
+            return resources;\r
+        }\r
+\r
+        resources.push_back(resource);\r
+    }\r
+\r
+    return resources;\r
+}\r
+\r
+std::shared_ptr<SimulatorSingleResource> SimulatorResourceFactory::createSingleResource(\r
+    const std::string &name, const std::string &uri, const std::string &resourceType)\r
+{\r
+    SimulatorSingleResourceImpl *simpleResource = new SimulatorSingleResourceImpl();\r
+    simpleResource->setName(name);\r
+    simpleResource->setURI(uri);\r
+    simpleResource->setResourceType(resourceType);\r
+    return std::shared_ptr<SimulatorSingleResource>(simpleResource);\r
+}\r
+\r
+std::shared_ptr<SimulatorCollectionResource> SimulatorResourceFactory::createCollectionResource(\r
+    const std::string &name, const std::string &uri, const std::string &resourceType)\r
+{\r
+    SimulatorCollectionResourceImpl *collectionResource = new SimulatorCollectionResourceImpl();\r
+    collectionResource->setName(name);\r
+    collectionResource->setURI(uri);\r
+    collectionResource->setResourceType(resourceType);\r
+    return std::shared_ptr<SimulatorCollectionResource>(collectionResource);\r
+}\r
+\r
+std::shared_ptr<SimulatorResource> SimulatorResourceFactory::buildResource(\r
+    const std::shared_ptr<RAML::RamlResource> &ramlResource)\r
+{\r
+    // Build resource request and respone model schema\r
+    RequestModelBuilder requestModelBuilder;\r
+    std::unordered_map<std::string, RequestModelSP> requestModels =\r
+        requestModelBuilder.build(ramlResource);\r
+\r
+    // Build SimulatorResourceModel from "GET" response schema\r
+    if (requestModels.end() == requestModels.find("GET"))\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Resource's RAML does not have GET request model!");\r
+        return nullptr;\r
+    }\r
+\r
+    RequestModelSP getRequestModel = requestModels["GET"];\r
+    ResponseModelSP getResponseModel = getRequestModel->getResponseModel(200);\r
+    if (!getResponseModel)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Resource's RAML does not have response for GET request!");\r
+        return nullptr;\r
+    }\r
+\r
+    std::shared_ptr<SimulatorResourceModelSchema> responseSchema =\r
+        getResponseModel->getSchema();\r
+    if (!responseSchema)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Failed to get schema from response model!");\r
+        return nullptr;\r
+    }\r
+\r
+    SimulatorResourceModel resourceModel = responseSchema->buildResourceModel();\r
+\r
+    // Remove the common properties from  resource Model\r
+    std::string resourceURI = ramlResource->getResourceUri();\r
+    std::string resourceName = ramlResource->getDisplayName();\r
+    std::string resourceType;\r
+\r
+    // Extracting resource type.\r
+    if (resourceModel.contains("rt"))\r
+    {\r
+        resourceType = resourceModel.get<std::string>("rt");\r
+        resourceModel.remove("rt");\r
+    }\r
+    else if (resourceModel.contains("resourceType"))\r
+    {\r
+        resourceType = resourceModel.get<std::string>("resourceType");\r
+        resourceModel.remove("resourceType");\r
+    }\r
+\r
+    // Construct resource type from uri\r
+    if(resourceType.empty())\r
+    {\r
+        std::ostringstream rtString;\r
+        rtString << "oic.r.";\r
+\r
+        size_t pos = resourceURI.rfind("/");\r
+        if (pos == std::string::npos)\r
+            pos = -1;\r
+\r
+        std::string rtName = resourceURI.substr(pos+1);\r
+        std::transform(rtName.begin(), rtName.end(), rtName.begin(), ::tolower);\r
+        rtString << rtName;\r
+        resourceType = rtString.str();\r
+    }\r
+\r
+    // Extracting interface type.\r
+    std::vector<std::string> interfaceTypes;\r
+    if (resourceModel.contains("if"))\r
+    {\r
+        SimulatorResourceModel::TypeInfo typeInfo = resourceModel.getType("if");\r
+        if(AttributeValueType::STRING == typeInfo.type())\r
+        {\r
+            interfaceTypes.push_back(resourceModel.get<std::string>("if"));\r
+        }\r
+        else if(AttributeValueType::VECTOR == typeInfo.type()\r
+            && AttributeValueType::STRING == typeInfo.baseType()\r
+            && typeInfo.depth() == 1)\r
+        {\r
+            interfaceTypes = resourceModel.get<std::vector<std::string>>("if");\r
+            if (interfaceTypes.size() > 1)\r
+                interfaceTypes.erase(interfaceTypes.begin()+1, interfaceTypes.end());\r
+        }\r
+\r
+        resourceModel.remove("if");\r
+    }\r
+\r
+    for (auto &requestModel : requestModels)\r
+    {\r
+        if (requestModel.second)\r
+        {\r
+            addInterfaceFromQueryParameter((requestModel.second)->getQueryParams("if"),\r
+                interfaceTypes);\r
+        }\r
+    }\r
+\r
+    // Remove properties which are not part of resource representation\r
+    resourceModel.remove("p");\r
+    resourceModel.remove("n");\r
+    resourceModel.remove("id");\r
+\r
+    // Create simple/collection resource\r
+    std::shared_ptr<SimulatorResource> simResource;\r
+    if (resourceModel.contains("links"))\r
+    {\r
+        std::shared_ptr<SimulatorCollectionResourceImpl> collectionRes(\r
+            new SimulatorCollectionResourceImpl());\r
+\r
+        collectionRes->setName(resourceName);\r
+        collectionRes->setResourceType(resourceType);\r
+        if (interfaceTypes.size() > 0)\r
+            collectionRes->setInterface(interfaceTypes);\r
+        collectionRes->setURI(ResourceURIFactory::getInstance()->makeUniqueURI(resourceURI));\r
+\r
+        // Set the resource model and its schema to simulated resource\r
+        collectionRes->setResourceModel(resourceModel);\r
+        collectionRes->setResourceModelSchema(responseSchema);\r
+        collectionRes->setRequestModel(requestModels);\r
+\r
+        simResource = collectionRes;\r
+    }\r
+    else\r
+    {\r
+        std::shared_ptr<SimulatorSingleResourceImpl> singleRes(\r
+            new SimulatorSingleResourceImpl());\r
+\r
+        singleRes->setName(resourceName);\r
+        singleRes->setResourceType(resourceType);\r
+        if (interfaceTypes.size() > 0)\r
+            singleRes->setInterface(interfaceTypes);\r
+        singleRes->setURI(ResourceURIFactory::getInstance()->makeUniqueURI(resourceURI));\r
+\r
+        // Set the resource model and its schema to simulated resource\r
+        singleRes->setResourceModel(resourceModel);\r
+        singleRes->setResourceModelSchema(responseSchema);\r
+        singleRes->setRequestModel(requestModels);\r
+\r
+        simResource = singleRes;\r
+    }\r
+\r
+    return simResource;\r
+}\r
+\r
+void SimulatorResourceFactory::addInterfaceFromQueryParameter(\r
+    std::vector<std::string> queryParamValue, std::vector<std::string> &interfaceTypes)\r
+{\r
+    for (auto &interfaceType : queryParamValue)\r
+    {\r
+        if (interfaceTypes.end() ==\r
+            std::find(interfaceTypes.begin(), interfaceTypes.end(), interfaceType))\r
+        {\r
+            interfaceTypes.push_back(interfaceType);\r
+        }\r
+    }\r
+}\r
+\r
+ResourceURIFactory *ResourceURIFactory::getInstance()\r
+{\r
+    static ResourceURIFactory s_instance;\r
+    return &s_instance;\r
+}\r
+\r
+ResourceURIFactory::ResourceURIFactory()\r
+    : m_id(0) {}\r
+\r
+std::string ResourceURIFactory::makeUniqueURI(const std::string &uri)\r
+{\r
+    std::lock_guard<std::mutex> lock(m_lock);\r
+    if (isUnique(uri))\r
+    {\r
+        updateUri(uri);\r
+        return uri;\r
+    }\r
+    std::ostringstream os;\r
+    os << uri;\r
+    if (!uri.empty() && '/' != uri[uri.length() - 1])\r
+        os << '/';\r
+    os << m_id++;\r
+    updateUri(os.str());\r
+    return os.str();\r
+}\r
+\r
+void ResourceURIFactory::updateUri(const std::string &uri)\r
+{\r
+    m_uriList.insert(std::pair<std::string, bool>(uri, true));\r
+}\r
+\r
+bool ResourceURIFactory::isUnique(const std::string &uri)\r
+{\r
+    if (m_uriList.end() == m_uriList.find(uri))\r
+        return true;\r
+    else\r
+        return false;\r
+}\r
+\r
diff --git a/service/simulator/src/server/simulator_resource_factory.h b/service/simulator/src/server/simulator_resource_factory.h
new file mode 100755 (executable)
index 0000000..7e489e3
--- /dev/null
@@ -0,0 +1,139 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_RESOURCE_FACTORY_H_
+#define SIMULATOR_RESOURCE_FACTORY_H_
+
+#include "simulator_single_resource.h"
+#include "simulator_collection_resource.h"
+#include "RamlParser.h"
+
+namespace RAML
+{
+    class RamlResource;
+    class Properties;
+    class JsonSchema;
+    class RamlParser;
+}
+
+class SimulatorResourceFactory
+{
+    public:
+        /**
+         * API for getting singleton instance of SimulatorClient class.
+         *
+         * @return Singleton instance of SimulatorClient class.
+         *
+         */
+        static SimulatorResourceFactory *getInstance();
+
+        /**
+         * API to create resource based on the given RAML file.
+         *
+         * @param configPath - RAML file path.
+         *
+         * @return SimulatorResource shared object created using RAML file.
+         */
+        std::shared_ptr<SimulatorResource> createResource(const std::string &configPath);
+
+        /**
+         * API to create resource based on the given RAML file.
+         *
+         * @param configPath - RAML file path.
+         *
+         * @return SimulatorResource shared object created using RAML file.
+         */
+        std::vector<std::shared_ptr<SimulatorResource> > createResource(
+            const std::string &configPath, unsigned int count);
+
+        /**
+         * API to create simple resource.
+         *
+         * @param name - Name of resource.
+         * @param uri - URI of resource.
+         * @param resourceType - ResourceType of resource.
+         *
+         * @return SimulatorSimpleResource.
+         */
+        std::shared_ptr<SimulatorSingleResource> createSingleResource(
+            const std::string &name, const std::string &uri, const std::string &resourceType);
+
+        /**
+         * API to create collection resource.
+         *
+         * @param name - Name of collection resource.
+         * @param uri - URI of resource.
+         * @param resourceType - ResourceType of collection resource.
+         *
+         * @return SimulatorCollectionResource.
+         */
+        std::shared_ptr<SimulatorCollectionResource> createCollectionResource(
+            const std::string &name, const std::string &uri, const std::string &resourceType);
+
+    private:
+        std::shared_ptr<SimulatorResource> buildResource(
+            const std::shared_ptr<RAML::RamlResource> &ramlResource);
+
+        void addInterfaceFromQueryParameter(
+            std::vector<std::string> queryParamValue, std::vector<std::string> &interfaceTypes);
+
+        SimulatorResourceFactory() = default;
+        SimulatorResourceFactory(const SimulatorResourceFactory &) = delete;
+        SimulatorResourceFactory &operator=(const SimulatorResourceFactory &) = delete;
+        SimulatorResourceFactory(SimulatorResourceFactory &&) = delete;
+        SimulatorResourceFactory &operator=(SimulatorResourceFactory && ) = delete;
+};
+
+class ResourceURIFactory
+{
+    public:
+        /**
+         * API for getting singleton instance of SimulatorClient class.
+         *
+         * @return Singleton instance of SimulatorClient class.
+         *
+         */
+        static ResourceURIFactory *getInstance();
+
+        /**
+         * API to construct unique URI from the given base @uri.
+         *
+         * @param uri - Base uri to be used to construct unique uri.
+         *
+         * @return Unique uri.
+         */
+        std::string makeUniqueURI(const std::string &uri);
+
+    private:
+        ResourceURIFactory();
+        ResourceURIFactory(const ResourceURIFactory &) = delete;
+        ResourceURIFactory &operator=(const ResourceURIFactory &) = delete;
+        ResourceURIFactory(ResourceURIFactory &&) = delete;
+        ResourceURIFactory &operator=(ResourceURIFactory && ) = delete;
+
+        bool isUnique(const std::string &uri);
+        void updateUri(const std::string &uri);
+
+        unsigned int m_id;
+        std::mutex m_lock;
+        std::map<std::string, bool> m_uriList;
+};
+
+#endif
diff --git a/service/simulator/src/server/simulator_single_resource_impl.cpp b/service/simulator/src/server/simulator_single_resource_impl.cpp
new file mode 100755 (executable)
index 0000000..5cc5c87
--- /dev/null
@@ -0,0 +1,958 @@
+/******************************************************************
+ *
+ * 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 "simulator_single_resource_impl.h"
+#include "simulator_utils.h"
+#include "oc_interface_details.h"
+#include "simulator_logger.h"
+#include "logger.h"
+
+#define TAG "SIMULATOR_SINGLE_RESOURCE"
+
+SimulatorSingleResourceImpl::SimulatorSingleResourceImpl()
+{
+    m_type = SimulatorResource::Type::SINGLE_RESOURCE;
+    m_interfaces.push_back(OC::DEFAULT_INTERFACE);
+    m_property = static_cast<OCResourceProperty>(OC_DISCOVERABLE | OC_OBSERVABLE);
+    m_resModelSchema = SimulatorResourceModelSchema::build();
+
+    // Set resource supports GET, PUT and POST by default
+    m_requestModels["GET"] = nullptr;
+    m_requestModels["POST"] = nullptr;
+    m_requestModels["PUT"] = nullptr;
+
+    m_resourceHandle = nullptr;
+}
+
+void SimulatorSingleResourceImpl::setName(const std::string &name)
+{
+    VALIDATE_INPUT(name.empty(), "Name is empty!")
+    m_name = name;
+}
+
+void SimulatorSingleResourceImpl::setURI(const std::string &uri)
+{
+    VALIDATE_INPUT(uri.empty(), "Uri is empty!")
+
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (m_resourceHandle)
+    {
+        throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED,
+                                 "URI can not be set when resource is started!");
+    }
+
+    m_uri = uri;
+}
+
+void SimulatorSingleResourceImpl::setResourceType(const std::string &resourceType)
+{
+    VALIDATE_INPUT(resourceType.empty(), "Resource type is empty!")
+
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (m_resourceHandle)
+    {
+        throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED,
+                                 "Resource type cannot be set when resource is started!");
+    }
+
+    m_resourceType = resourceType;
+}
+
+void SimulatorSingleResourceImpl::setInterface(const std::string &interfaceType)
+{
+    VALIDATE_INPUT(interfaceType.empty(), "Interface type list is empty!")
+
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (m_resourceHandle)
+    {
+        throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED,
+                                 "Resource interface can not be reset when resource is started!");
+    }
+
+    m_interfaces = {interfaceType};
+}
+
+void SimulatorSingleResourceImpl::setInterface(const std::vector<std::string> &interfaceTypes)
+{
+    VALIDATE_INPUT(interfaceTypes.empty(), "Interface type list is empty!")
+
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (m_resourceHandle)
+    {
+        throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED,
+                                 "Resource interface can not be reset when resource is started!");
+    }
+
+    m_interfaces.clear();
+    for (auto &interfaceType : interfaceTypes)
+    {
+        if (m_interfaces.end() ==
+            std::find(m_interfaces.begin(), m_interfaces.end(), interfaceType))
+        {
+            m_interfaces.push_back(interfaceType);
+        }
+    }
+}
+
+void SimulatorSingleResourceImpl::addInterface(const std::string &interfaceType)
+{
+    VALIDATE_INPUT(interfaceType.empty(), "Interface type is empty!")
+
+    if (m_interfaces.end() != std::find(m_interfaces.begin(), m_interfaces.end(), interfaceType))
+    {
+        SIM_LOG(ILogger::ERROR, "[" << m_uri << "] "
+                << "Resource already supporting this Interface: " << interfaceType)
+        return;
+    }
+
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (m_resourceHandle)
+    {
+        typedef OCStackResult (*bindInterfaceToResource)(const OCResourceHandle &,
+                const std::string &);
+
+        invokeocplatform(static_cast<bindInterfaceToResource>(
+                             OC::OCPlatform::bindInterfaceToResource), m_resourceHandle,
+                         interfaceType);
+    }
+
+    m_interfaces.push_back(interfaceType);
+}
+
+void SimulatorSingleResourceImpl::setObservable(bool state)
+{
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (m_resourceHandle)
+    {
+        throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED,
+                                 "Observation state can not be changed when resource is started!");
+    }
+
+    if (state)
+        m_property = static_cast<OCResourceProperty>(m_property | OC_OBSERVABLE);
+    else
+        m_property = static_cast<OCResourceProperty>(m_property ^ OC_OBSERVABLE);
+}
+
+void SimulatorSingleResourceImpl::setDiscoverable(bool state)
+{
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (m_resourceHandle)
+    {
+        throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED,
+                                 "Discoverable state can not be changed when resource is started!");
+    }
+
+    if (state)
+        m_property = static_cast<OCResourceProperty>(m_property | OC_DISCOVERABLE);
+    else
+        m_property = static_cast<OCResourceProperty>(m_property ^ OC_DISCOVERABLE);
+}
+
+void SimulatorSingleResourceImpl::setObserverCallback(ObserverCallback callback)
+{
+    VALIDATE_CALLBACK(callback)
+    m_observeCallback = callback;
+}
+
+void SimulatorSingleResourceImpl::setModelChangeCallback(ResourceModelUpdateCallback callback)
+{
+    VALIDATE_CALLBACK(callback)
+    m_modelCallback = callback;
+}
+
+bool SimulatorSingleResourceImpl::isObservable() const
+{
+    return ((m_property & OC_OBSERVABLE) == OC_OBSERVABLE);
+}
+
+bool SimulatorSingleResourceImpl::isDiscoverable() const
+{
+    return ((m_property & OC_DISCOVERABLE) == OC_DISCOVERABLE);
+}
+
+bool SimulatorSingleResourceImpl::isStarted() const
+{
+    return (nullptr != m_resourceHandle);
+}
+
+void SimulatorSingleResourceImpl::start()
+{
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (m_resourceHandle)
+    {
+        SIM_LOG(ILogger::ERROR, "[" << m_uri << "] " << "Resource already started!")
+        return;
+    }
+
+    if (m_uri.empty() || m_resourceType.empty())
+    {
+        throw SimulatorException(SIMULATOR_ERROR, "Incomplete data to start resource!");
+    }
+
+    typedef OCStackResult (*RegisterResource)(OCResourceHandle &, std::string &,
+            const std::string &, const std::string &, OC::EntityHandler, uint8_t);
+
+    invokeocplatform(static_cast<RegisterResource>(OC::OCPlatform::registerResource),
+                     m_resourceHandle, m_uri, m_resourceType, m_interfaces[0],
+                     std::bind(&SimulatorSingleResourceImpl::handleRequests,
+                               this, std::placeholders::_1), m_property);
+
+    for (size_t index = 1; m_interfaces.size() > 1 && index < m_interfaces.size(); index++)
+    {
+        typedef OCStackResult (*bindInterfaceToResource)(const OCResourceHandle &,
+                const std::string &);
+
+        try
+        {
+            invokeocplatform(static_cast<bindInterfaceToResource>(
+                                 OC::OCPlatform::bindInterfaceToResource), m_resourceHandle,
+                             m_interfaces[index]);
+        }
+        catch (SimulatorException &e)
+        {
+            stop();
+            throw;
+        }
+    }
+}
+
+void SimulatorSingleResourceImpl::stop()
+{
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (!m_resourceHandle)
+    {
+        SIM_LOG(ILogger::ERROR, "[" << m_uri << "] " << "Resource is not started yet!")
+        return;
+    }
+
+    // Stop all the update automation of this resource
+    m_updateAutomationMgr.stopAll();
+
+    // Clear all the observers
+    removeAllObservers();
+
+    // Unregister the resource from stack
+    typedef OCStackResult (*UnregisterResource)(const OCResourceHandle &);
+
+    invokeocplatform(static_cast<UnregisterResource>(OC::OCPlatform::unregisterResource),
+                     m_resourceHandle);
+
+    m_resourceHandle = nullptr;
+}
+
+SimulatorResourceModel SimulatorSingleResourceImpl::getResourceModel()
+{
+    std::lock_guard<std::recursive_mutex> lock(m_modelLock);
+    return m_resModel;
+}
+
+std::vector<ObserverInfo> SimulatorSingleResourceImpl::getObservers() const
+{
+    return m_observersList;
+}
+
+void SimulatorSingleResourceImpl::notify(int observerID)
+{
+    SimulatorResourceModel resModel;
+    {
+        std::lock_guard<std::recursive_mutex> lock(m_modelLock);
+        resModel = m_resModel;
+    }
+
+    notify(observerID, resModel);
+}
+
+void SimulatorSingleResourceImpl::notifyAll()
+{
+    SimulatorResourceModel resModel;
+    {
+        std::lock_guard<std::recursive_mutex> lock(m_modelLock);
+        resModel = m_resModel;
+    }
+
+    notifyAll(resModel);
+}
+
+bool SimulatorSingleResourceImpl::getAttribute(const std::string &attrName,
+        SimulatorResourceAttribute &attribute)
+{
+    std::lock_guard<std::recursive_mutex> modelLock(m_modelLock);
+    std::lock_guard<std::mutex> schemaLock(m_modelSchemaLock);
+
+    if (m_resModel.contains(attrName))
+    {
+        attribute.setName(attrName);
+        attribute.setValue(m_resModel.getAttributeValue(attrName));
+        attribute.setProperty(m_resModelSchema->get(attrName));
+        return true;
+    }
+
+    return false;
+}
+
+std::map<std::string, SimulatorResourceAttribute>
+SimulatorSingleResourceImpl::getAttributes()
+{
+    std::lock_guard<std::recursive_mutex> modelLock(m_modelLock);
+    std::lock_guard<std::mutex> schemaLock(m_modelSchemaLock);
+
+    std::map<std::string, SimulatorResourceAttribute> attributes;
+    for (auto &attributeEntry : m_resModel.getAttributeValues())
+    {
+        SimulatorResourceAttribute attribute(attributeEntry.first);
+        attribute.setValue(attributeEntry.second);
+
+        attribute.setProperty(m_resModelSchema->get(attributeEntry.first));
+        attributes[attributeEntry.first] = attribute;
+    }
+
+    return attributes;
+}
+
+bool SimulatorSingleResourceImpl::addAttribute(
+    const SimulatorResourceAttribute &attribute, bool notify)
+{
+    if (attribute.getName().empty() || nullptr == attribute.getProperty())
+    {
+        return false;
+    }
+
+    // Add attribute to resource representation and its schema
+    std::lock_guard<std::recursive_mutex> modelLock(m_modelLock);
+    std::lock_guard<std::mutex> schemaLock(m_modelSchemaLock);
+
+    if (!m_resModel.add(attribute.getName(), attribute.getValue()))
+    {
+        return false;
+    }
+
+    m_resModelSchema->add(attribute.getName(), attribute.getProperty());
+
+    if (notify && isStarted())
+    {
+        try
+        {
+            notifyAll();
+        }
+        catch (SimulatorException &e)
+        {
+            SIM_LOG(ILogger::ERROR, "[" << m_uri << "] " << "Error when notifying the observers!")
+        }
+        notifyApp();
+    }
+
+    return true;
+}
+
+bool SimulatorSingleResourceImpl::updateAttributeValue(
+    const SimulatorResourceAttribute &attribute, bool notify)
+{
+    if (attribute.getName().empty())
+    {
+        return false;
+    }
+
+    // Validate the new value against attribute schema property
+    std::lock_guard<std::mutex> schemaLock(m_modelSchemaLock);
+    auto property = m_resModelSchema->get(attribute.getName());
+    if (!(property->validate(attribute.getValue())))
+    {
+        return false;
+    }
+
+    // Update the attribute value
+    std::lock_guard<std::recursive_mutex> modelLock(m_modelLock);
+    if (!m_resModel.update(attribute.getName(), attribute.getValue()))
+    {
+        return false;
+    }
+
+    if (notify && isStarted())
+    {
+        try
+        {
+            notifyAll();
+        }
+        catch (SimulatorException &e)
+        {
+            SIM_LOG(ILogger::ERROR, "[" << m_uri << "] " << "Error when notifying the observers!")
+        }
+        notifyApp();
+    }
+
+    return true;
+}
+
+bool SimulatorSingleResourceImpl::removeAttribute(
+    const std::string &attrName, bool notify)
+{
+    if (attrName.empty())
+    {
+        return false;
+    }
+
+    // Remove attribute from resource representation and its schema
+    std::lock_guard<std::recursive_mutex> modelLock(m_modelLock);
+    std::lock_guard<std::mutex> schemaLock(m_modelSchemaLock);
+
+    m_resModelSchema->remove(attrName);
+    if (!m_resModel.remove(attrName))
+    {
+        return false;
+    }
+
+    if (notify && isStarted())
+    {
+        try
+        {
+            notifyAll();
+        }
+        catch (SimulatorException &e)
+        {
+            SIM_LOG(ILogger::ERROR, "[" << m_uri << "] " << "Error when notifying the observers!")
+        }
+        notifyApp();
+    }
+
+    return true;
+}
+
+int SimulatorSingleResourceImpl::startResourceUpdation(AutoUpdateType type,
+        int updateInterval, AutoUpdateCompleteCallback callback)
+{
+    VALIDATE_CALLBACK(callback)
+
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (!m_resourceHandle)
+    {
+        throw SimulatorException(SIMULATOR_NO_RESOURCE, "Resource is not started!");
+    }
+
+    return m_updateAutomationMgr.startResourceAutomation(shared_from_this(), type,
+            updateInterval, callback);
+}
+
+int SimulatorSingleResourceImpl::startAttributeUpdation(const std::string &attrName,
+        AutoUpdateType type, int updateInterval, AutoUpdateCompleteCallback callback)
+{
+    VALIDATE_CALLBACK(callback)
+
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (!m_resourceHandle)
+    {
+        throw SimulatorException(SIMULATOR_NO_RESOURCE, "Resource is not started!");
+    }
+
+    return m_updateAutomationMgr.startAttributeAutomation(shared_from_this(), attrName,
+            type, updateInterval, callback);
+}
+
+std::vector<int> SimulatorSingleResourceImpl::getResourceUpdations()
+{
+    return m_updateAutomationMgr.getResourceAutomationIds();
+}
+
+std::vector<int> SimulatorSingleResourceImpl::getAttributeUpdations()
+{
+    return m_updateAutomationMgr.getAttributeAutomationIds();
+}
+
+void SimulatorSingleResourceImpl::stopUpdation(const int id)
+{
+    m_updateAutomationMgr.stop(id);
+}
+
+void SimulatorSingleResourceImpl::notifyApp()
+{
+    if (m_modelCallback)
+    {
+        m_modelCallback(m_uri, m_resModel);
+    }
+}
+
+void SimulatorSingleResourceImpl::notifyApp(const SimulatorResourceModel &resModel)
+{
+    if (m_modelCallback)
+    {
+        m_modelCallback(m_uri, resModel);
+    }
+}
+
+void SimulatorSingleResourceImpl::setResourceModel(const SimulatorResourceModel &resModel)
+{
+    std::lock_guard<std::recursive_mutex> lock(m_modelLock);
+    m_resModel = resModel;
+}
+
+void SimulatorSingleResourceImpl::setResourceModelSchema(
+    const std::shared_ptr<SimulatorResourceModelSchema> &resModelSchema)
+{
+    std::lock_guard<std::mutex> lock(m_modelSchemaLock);
+    m_resModelSchema = resModelSchema;
+}
+
+void SimulatorSingleResourceImpl::setRequestModel(
+    const std::unordered_map<std::string, std::shared_ptr<RequestModel>> &requestModels)
+{
+    m_requestModels = requestModels;
+}
+
+bool SimulatorSingleResourceImpl::updateResourceModel(const SimulatorResourceModel &reqResModel,
+        SimulatorResourceModel &updatedResModel, bool overwrite, bool notify)
+{
+    std::lock_guard<std::mutex> schemaLock(m_modelSchemaLock);
+    std::lock_guard<std::recursive_mutex> modelLock(m_modelLock);
+
+    size_t reqModelSize = reqResModel.size();
+    SimulatorResourceModel tempResModel;
+
+    for (auto &attributeName : m_resModel.getAttributeNameSet())
+    {
+        // Break the loop if update request model has no more attributes for validation.
+        if (!reqModelSize)
+        {
+            break;
+        }
+
+        // Check attribute presence criteria
+        if (!reqResModel.contains(attributeName))
+        {
+            if (overwrite)
+                return false;
+            continue;
+        }
+
+        reqModelSize--;
+
+        // Value type check
+        if (!(m_resModel.getType(attributeName) == reqResModel.getType(attributeName)))
+        {
+            return false;
+        }
+
+        // Validate the new value against attribute schema property
+        auto property = m_resModelSchema->get(attributeName);
+        if (!(property->validate(reqResModel.getAttributeValue(attributeName))))
+        {
+            return false;
+        }
+
+        tempResModel.add(attributeName, reqResModel.getAttributeValue(attributeName));
+    }
+
+    // Validation is success, now update the attribute values.
+    for (auto &valueEntry : tempResModel.getAttributeValues())
+    {
+        m_resModel.update(valueEntry.first, valueEntry.second);
+    }
+
+    updatedResModel = m_resModel;
+
+    if (notify && isStarted())
+    {
+        try
+        {
+            notifyAll();
+        }
+        catch (SimulatorException &e)
+        {
+            SIM_LOG(ILogger::ERROR, "[" << m_uri << "] " << "Error when notifying the observers!")
+        }
+        notifyApp();
+    }
+
+    return true;
+}
+
+void SimulatorSingleResourceImpl::notify(int observerID, const SimulatorResourceModel &resModel)
+{
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (!m_resourceHandle)
+        return;
+
+    std::shared_ptr<OC::OCResourceResponse> response(new OC::OCResourceResponse);
+    response->setErrorCode(200);
+    response->setResponseResult(OC_EH_OK);
+    response->setResourceRepresentation(resModel.asOCRepresentation(), m_interfaces[0]);
+
+    OC::ObservationIds observers;
+    observers.push_back(observerID);
+
+    typedef OCStackResult (*NotifyListOfObservers)(OCResourceHandle, OC::ObservationIds &,
+            const std::shared_ptr<OC::OCResourceResponse>);
+
+    invokeocplatform(static_cast<NotifyListOfObservers>(OC::OCPlatform::notifyListOfObservers),
+                     m_resourceHandle, observers, response);
+}
+
+void SimulatorSingleResourceImpl::notifyAll(const SimulatorResourceModel &resModel)
+{
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (!m_resourceHandle)
+        return;
+
+    if (!m_observersList.size())
+        return;
+
+    std::shared_ptr<OC::OCResourceResponse> response(new OC::OCResourceResponse);
+    response->setErrorCode(200);
+    response->setResponseResult(OC_EH_OK);
+    response->setResourceRepresentation(resModel.asOCRepresentation(), m_interfaces[0]);
+
+    OC::ObservationIds observers;
+    for (auto &observer : m_observersList)
+        observers.push_back(observer.id);
+
+    typedef OCStackResult (*NotifyListOfObservers)(OCResourceHandle, OC::ObservationIds &,
+            const std::shared_ptr<OC::OCResourceResponse>);
+
+    invokeocplatform(static_cast<NotifyListOfObservers>(OC::OCPlatform::notifyListOfObservers),
+                     m_resourceHandle, observers, response);
+}
+
+void SimulatorSingleResourceImpl::setCommonProperties(OC::OCRepresentation &ocResRep)
+{
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    ocResRep.setValue("rt", m_resourceType);
+    ocResRep.setValue("if", m_interfaces);
+    ocResRep.setValue("n", m_name);
+}
+
+OCEntityHandlerResult SimulatorSingleResourceImpl::handleRequests(
+    std::shared_ptr<OC::OCResourceRequest> request)
+{
+    if (!request)
+    {
+        OIC_LOG(ERROR, TAG, "Request received from stack is null!");
+        return OC_EH_ERROR;
+    }
+
+    OCEntityHandlerResult result = OC_EH_OK;
+
+    // Handle GET, PUT, POST and DELETE requests
+    if (OC::RequestHandlerFlag::RequestFlag & request->getRequestHandlerFlag())
+    {
+        {
+            OC::OCRepresentation rep = request->getResourceRepresentation();
+            std::string payload = getPayloadString(rep);
+            SIM_LOG(ILogger::INFO, "[" << m_uri << "] " << request->getRequestType()
+                    << " request received. \n**Payload details**\n" << payload)
+        }
+
+        if ("GET" == request->getRequestType())
+        {
+            result = handleGET(request);
+        }
+        else if ("PUT" == request->getRequestType())
+        {
+            result = handlePUT(request);
+        }
+        else if ("POST" == request->getRequestType())
+        {
+            result = handlePOST(request);
+        }
+        else if ("DELETE" == request->getRequestType())
+        {
+            result = handleDELETE(request);
+        }
+    }
+
+    // Handle OBSERVE requests
+    if ((OC::RequestHandlerFlag::ObserverFlag & request->getRequestHandlerFlag())
+        && isObservable())
+    {
+        OC::ObservationInfo observationInfo = request->getObservationInfo();
+        if (OC::ObserveAction::ObserveRegister == observationInfo.action)
+        {
+            addObserver(observationInfo);
+            SIM_LOG(ILogger::INFO, "[" << m_uri << "] Observer added [id: "
+                    << (int)observationInfo.obsId << ", address: " << observationInfo.address
+                    << ", port: " << observationInfo.port << "].");
+        }
+        else if (OC::ObserveAction::ObserveUnregister == observationInfo.action)
+        {
+            removeObserver(observationInfo);
+            SIM_LOG(ILogger::INFO, "[" << m_uri << "] Observer removed [id: "
+                    << (int)observationInfo.obsId << ", address: " << observationInfo.address
+                    << ", port: " << observationInfo.port << "].");
+        }
+    }
+
+    return result;
+}
+
+void SimulatorSingleResourceImpl::addObserver(const OC::ObservationInfo &ocObserverInfo)
+{
+    ObserverInfo info {ocObserverInfo.obsId, ocObserverInfo.address, ocObserverInfo.port};
+    m_observersList.push_back(info);
+
+    if (m_observeCallback)
+        m_observeCallback(m_uri, ObservationStatus::REGISTER, info);
+}
+
+void SimulatorSingleResourceImpl::removeObserver(const OC::ObservationInfo &ocObserverInfo)
+{
+    bool found = false;
+    ObserverInfo info;
+    for (auto iter = m_observersList.begin(); iter != m_observersList.end(); iter++)
+    {
+        if ((*iter).id == ocObserverInfo.obsId)
+        {
+            info = *iter;
+            found = true;
+            m_observersList.erase(iter);
+            break;
+        }
+    }
+
+    if (found && m_observeCallback)
+        m_observeCallback(m_uri, ObservationStatus::UNREGISTER, info);
+}
+
+void SimulatorSingleResourceImpl::removeAllObservers()
+{
+    std::vector<ObserverInfo> observerList = m_observersList;
+    m_observersList.clear();
+    for (size_t index = 0; index < observerList.size(); index++)
+    {
+        if (m_observeCallback)
+            m_observeCallback(m_uri, ObservationStatus::UNREGISTER, observerList[index]);
+    }
+}
+
+OCEntityHandlerResult SimulatorSingleResourceImpl::handleGET(
+    const std::shared_ptr<OC::OCResourceRequest> &request)
+{
+    // Check if resource support GET request
+    if (m_requestModels.end() == m_requestModels.find("GET"))
+    {
+        SIM_LOG(ILogger::ERROR, "[" << m_uri << "] "
+                << "Resource does not support GET request!")
+        return sendResponse(request, 405, OC_EH_ERROR);
+    }
+
+    // Handling interface query parameter "if"
+    auto interfaceType = m_interfaces[0];
+    auto requestQueryParams = request->getQueryParameters();
+    if (requestQueryParams.end() != requestQueryParams.find("if"))
+    {
+        interfaceType = requestQueryParams["if"];
+    }
+
+    if (!isValidInterface(interfaceType, "GET"))
+    {
+        SIM_LOG(ILogger::ERROR, "[" << m_uri << "] "
+                << "GET request received on invalid interface : " << interfaceType)
+        return OC_EH_ERROR;
+    }
+
+    OC::OCRepresentation resourceRep = getResourceModel().asOCRepresentation();
+
+    // Add common properties to resource representation if interface is
+    // neither "oic.if.a" nor "oic.if.s".
+    if (OC::ACTUATOR_INTERFACE != interfaceType &&
+        OC::SENSOR_INTERFACE != interfaceType)
+    {
+        setCommonProperties(resourceRep);
+    }
+
+    return sendResponse(request, 200, OC_EH_OK, resourceRep, interfaceType);
+}
+
+OCEntityHandlerResult SimulatorSingleResourceImpl::handlePUT(
+    const std::shared_ptr<OC::OCResourceRequest> &request)
+{
+    // Check if resource support PUT request
+    if (m_requestModels.end() == m_requestModels.find("PUT"))
+    {
+        SIM_LOG(ILogger::ERROR, "[" << m_uri << "] "
+                << "Resource does not support PUT request!")
+        return sendResponse(request, 405, OC_EH_ERROR);
+    }
+
+    // Handling interface query parameter "if"
+    auto interfaceType = m_interfaces[0];
+    auto requestQueryParams = request->getQueryParameters();
+    if (requestQueryParams.end() != requestQueryParams.find("if"))
+    {
+        interfaceType = requestQueryParams["if"];
+    }
+
+    if (!isValidInterface(interfaceType, "PUT"))
+    {
+        SIM_LOG(ILogger::ERROR, "[" << m_uri << "] "
+                << "PUT request received on invalid interface : " << interfaceType)
+        return OC_EH_ERROR;
+    }
+
+    OC::OCRepresentation reqOcRep = request->getResourceRepresentation();
+    SimulatorResourceModel reqResModel = SimulatorResourceModel::build(reqOcRep);
+    SimulatorResourceModel updatedResModel;
+    if (true == updateResourceModel(reqResModel, updatedResModel, true, false))
+    {
+        auto ocRep = updatedResModel.asOCRepresentation();
+        auto result = sendResponse(request, 200, OC_EH_OK,
+                                   ocRep, m_interfaces[0]);
+        notifyApp(updatedResModel);
+        try
+        {
+            notifyAll();
+        }
+        catch (SimulatorException &e)
+        {
+            SIM_LOG(ILogger::ERROR, "[" << m_uri << "] "
+                    << "Error when notifying the observers!")
+        }
+
+        return result;
+    }
+
+    SIM_LOG(ILogger::ERROR, "[" << m_uri << "] " << "Updating resource representation failed!")
+    return sendResponse(request, 400, OC_EH_ERROR);
+}
+
+OCEntityHandlerResult SimulatorSingleResourceImpl::handlePOST(
+    const std::shared_ptr<OC::OCResourceRequest> &request)
+{
+    // Check if resource support PUT request
+    if (m_requestModels.end() == m_requestModels.find("POST"))
+    {
+        SIM_LOG(ILogger::ERROR, "[" << m_uri << "] "
+                << "Resource does not support POST request!")
+        return sendResponse(request, 405, OC_EH_ERROR);
+    }
+
+    // Handling interface query parameter "if"
+    auto interfaceType = m_interfaces[0];
+    auto requestQueryParams = request->getQueryParameters();
+    if (requestQueryParams.end() != requestQueryParams.find("if"))
+    {
+        interfaceType = requestQueryParams["if"];
+    }
+
+    if (!isValidInterface(interfaceType, "POST"))
+    {
+        SIM_LOG(ILogger::ERROR, "[" << m_uri << "] "
+                << "POST request received on invalid interface : " << interfaceType)
+        return OC_EH_ERROR;
+    }
+
+    OC::OCRepresentation reqOcRep = request->getResourceRepresentation();
+    SimulatorResourceModel reqResModel = SimulatorResourceModel::build(reqOcRep);
+    SimulatorResourceModel updatedResModel;
+    if (true == updateResourceModel(reqResModel, updatedResModel, false, false))
+    {
+        auto ocRep = updatedResModel.asOCRepresentation();
+        auto result = sendResponse(request, 200, OC_EH_OK,
+                                   ocRep, m_interfaces[0]);
+        notifyApp(updatedResModel);
+        try
+        {
+            notifyAll();
+        }
+        catch (SimulatorException &e)
+        {
+            SIM_LOG(ILogger::ERROR, "[" << m_uri << "] "
+                    << "Error when notifying the observers!")
+        }
+
+        return result;
+    }
+
+    SIM_LOG(ILogger::ERROR, "[" << m_uri << "] " << "Updating resource representation failed!")
+    return sendResponse(request, 400, OC_EH_ERROR);
+}
+
+OCEntityHandlerResult SimulatorSingleResourceImpl::handleDELETE(
+    const std::shared_ptr<OC::OCResourceRequest> &request)
+{
+    SIM_LOG(ILogger::ERROR, "[" << m_uri << "] "
+            << "Resource does not support DELETE request!")
+    return sendResponse(request, 405, OC_EH_ERROR);;
+}
+
+bool SimulatorSingleResourceImpl::isValidInterface(const std::string &interfaceType,
+        const std::string &requestType)
+{
+    // Is this OIC defined interface ?
+    if (false ==
+        OCInterfaceDetails::getInstance()->isRequestSupported(interfaceType, requestType))
+    {
+        return false;
+    }
+
+    // Does resource support this interface ?
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (m_interfaces.end() ==
+        std::find(m_interfaces.begin(), m_interfaces.end(), interfaceType))
+    {
+        return false;
+    }
+
+    return true;
+}
+
+OCEntityHandlerResult SimulatorSingleResourceImpl::sendResponse(
+    const std::shared_ptr<OC::OCResourceRequest> &request, const int errorCode,
+    OCEntityHandlerResult responseResult)
+{
+    std::shared_ptr<OC::OCResourceResponse> response(new OC::OCResourceResponse());
+    response->setRequestHandle(request->getRequestHandle());
+    response->setResourceHandle(request->getResourceHandle());
+    response->setErrorCode(errorCode);
+    response->setResponseResult(responseResult);
+    if (OC_STACK_OK != OC::OCPlatform::sendResponse(response))
+    {
+        SIM_LOG(ILogger::ERROR, "[" << m_uri << "] Failed to send response for " <<
+            request->getRequestType() <<" request!")
+        return OC_EH_ERROR;
+    }
+
+    SIM_LOG(ILogger::INFO, "[" << m_uri << "] Sent response for " <<
+        request->getRequestType() << " request.")
+
+    return OC_EH_OK;
+}
+
+OCEntityHandlerResult SimulatorSingleResourceImpl::sendResponse(
+    const std::shared_ptr<OC::OCResourceRequest> &request, const int errorCode,
+    OCEntityHandlerResult responseResult, OC::OCRepresentation &payload,
+    const std::string &interfaceType)
+{
+    std::shared_ptr<OC::OCResourceResponse> response(new OC::OCResourceResponse());
+    response->setRequestHandle(request->getRequestHandle());
+    response->setResourceHandle(request->getResourceHandle());
+    response->setErrorCode(errorCode);
+    response->setResponseResult(responseResult);
+    response->setResourceRepresentation(payload, interfaceType);
+    if (OC_STACK_OK != OC::OCPlatform::sendResponse(response))
+    {
+        SIM_LOG(ILogger::ERROR, "[" << m_uri << "] Failed to send response for " <<
+            request->getRequestType() <<" request!")
+        return OC_EH_ERROR;
+    }
+
+    SIM_LOG(ILogger::INFO, "[" << m_uri << "] Sent response for " <<
+        request->getRequestType() << " request \n\n" <<
+        "**Payload details**" << getPayloadString(payload))
+
+    return OC_EH_OK;
+}
diff --git a/service/simulator/src/server/simulator_single_resource_impl.h b/service/simulator/src/server/simulator_single_resource_impl.h
new file mode 100755 (executable)
index 0000000..81ea2f8
--- /dev/null
@@ -0,0 +1,120 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_SINGLE_RESOURCE_IMPL_H_
+#define SIMULATOR_SINGLE_RESOURCE_IMPL_H_
+
+#include "simulator_single_resource.h"
+#include "simulator_resource_model_schema.h"
+#include "request_model.h"
+#include "resource_update_automation_mngr.h"
+#include "RamlParser.h"
+
+class SimulatorResourceFactory;
+class SimulatorSingleResourceImpl : public SimulatorSingleResource,
+    public std::enable_shared_from_this<SimulatorSingleResourceImpl>
+{
+    public:
+        friend class SimulatorResourceFactory;
+
+        void setName(const std::string &name);
+        void setURI(const std::string &uri);
+        void setResourceType(const std::string &resourceType);
+        void setInterface(const std::string &interfaceType);
+        void setInterface(const std::vector<std::string> &interfaceTypes);
+        void addInterface(const std::string &interfaceType);
+        void setObservable(bool state);
+        void setDiscoverable(bool state);
+        void setObserverCallback(ObserverCallback callback);
+        void setModelChangeCallback(ResourceModelUpdateCallback callback);
+        bool isObservable() const;
+        bool isDiscoverable() const;
+        bool isStarted() const;
+        void start();
+        void stop();
+        SimulatorResourceModel getResourceModel();
+        std::vector<ObserverInfo> getObservers() const;
+        void notify(int observerID);
+        void notifyAll();
+
+        bool getAttribute(const std::string &attrName, SimulatorResourceAttribute &attribute);
+        std::map<std::string, SimulatorResourceAttribute> getAttributes();
+        bool addAttribute(const SimulatorResourceAttribute &attribute, bool notify = true);
+        bool updateAttributeValue(const SimulatorResourceAttribute &attribute,
+                                  bool notify = true);
+        bool removeAttribute(const std::string &attrName, bool notify = true);
+        int startResourceUpdation(AutoUpdateType type, int updateInterval,
+                                  AutoUpdateCompleteCallback callback);
+        int startAttributeUpdation(const std::string &attrName, AutoUpdateType type,
+                                   int updateInterval, AutoUpdateCompleteCallback callback);
+        std::vector<int> getResourceUpdations();
+        std::vector<int> getAttributeUpdations();
+        void stopUpdation(const int id);
+
+        bool updateResourceModel(const SimulatorResourceModel &reqResModel,
+                                 SimulatorResourceModel &updatedResModel, bool overwrite = false,
+                                 bool notify = true);
+        void notifyApp();
+        void notifyApp(const SimulatorResourceModel &resModel);
+
+    private:
+        SimulatorSingleResourceImpl();
+        void setResourceModel(const SimulatorResourceModel &resModel);
+        void setResourceModelSchema(
+            const std::shared_ptr<SimulatorResourceModelSchema> &resModelSchema);
+        void setRequestModel(
+            const std::unordered_map<std::string, std::shared_ptr<RequestModel>> &requestModels);
+        void notify(int observerID, const SimulatorResourceModel &resModel);
+        void notifyAll(const SimulatorResourceModel &resModel);
+        void addObserver(const OC::ObservationInfo &ocObserverInfo);
+        void removeObserver(const OC::ObservationInfo &ocObserverInfo);
+        void removeAllObservers();
+        void setCommonProperties(OC::OCRepresentation &ocResRep);
+        OCEntityHandlerResult handleRequests(std::shared_ptr<OC::OCResourceRequest> request);
+        OCEntityHandlerResult handleGET(const std::shared_ptr<OC::OCResourceRequest> &request);
+        OCEntityHandlerResult handlePOST(const std::shared_ptr<OC::OCResourceRequest> &request);
+        OCEntityHandlerResult handlePUT(const std::shared_ptr<OC::OCResourceRequest> &request);
+        OCEntityHandlerResult handleDELETE(const std::shared_ptr<OC::OCResourceRequest> &request);
+        bool isValidInterface(const std::string &interfaceType, const std::string &requestType);
+        OCEntityHandlerResult sendResponse(const std::shared_ptr<OC::OCResourceRequest> &request,
+                                           const int errorCode, OCEntityHandlerResult responseResult);
+        OCEntityHandlerResult sendResponse(const std::shared_ptr<OC::OCResourceRequest> &request,
+                                           const int errorCode, OCEntityHandlerResult responseResult, OC::OCRepresentation &Payload,
+                                           const std::string &interfaceType);
+
+        std::recursive_mutex m_objectLock;
+        std::recursive_mutex m_modelLock;
+        std::mutex m_modelSchemaLock;
+        SimulatorResourceModel m_resModel;
+        std::shared_ptr<SimulatorResourceModelSchema> m_resModelSchema;
+        std::unordered_map<std::string, std::shared_ptr<RequestModel>> m_requestModels;
+        UpdateAutomationMngr m_updateAutomationMgr;
+        std::vector<ObserverInfo> m_observersList;
+
+        ResourceModelUpdateCallback m_modelCallback;
+        ObserverCallback m_observeCallback;
+
+        OCResourceProperty m_property;
+        OCResourceHandle m_resourceHandle;
+};
+
+typedef std::shared_ptr<SimulatorSingleResourceImpl> SimulatorSingleResourceImplSP;
+
+#endif
diff --git a/service/simulator/src/service-provider/resource_manager.cpp b/service/simulator/src/service-provider/resource_manager.cpp
deleted file mode 100644 (file)
index 54c5e8b..0000000
+++ /dev/null
@@ -1,215 +0,0 @@
-/******************************************************************
- *
- * 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 "resource_manager.h"
-#include "simulator_logger.h"
-#include "logger.h"
-
-#define TAG "RESOURCE_MANAGER"
-
-ResourceManager *ResourceManager::getInstance()
-{
-    static ResourceManager s_instance;
-    return &s_instance;
-}
-
-SimulatorResourceServerSP ResourceManager::createResource(const std::string &configPath,
-        SimulatorResourceServer::ResourceModelChangedCB callback)
-{
-    OC_LOG_V(INFO, "Create resource request : config=%s", configPath.c_str());
-
-    // Input validation
-    if (configPath.empty())
-    {
-        OC_LOG(ERROR, TAG, "Invalid config file path!");
-        throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Invalid RAML file path!");
-    }
-
-    if (!callback)
-    {
-        OC_LOG(ERROR, TAG, "Invalid callback!");
-        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-    }
-
-    return buildResource(configPath, callback);
-}
-
-std::vector<SimulatorResourceServerSP> ResourceManager::createResource(
-    const std::string &configPath, unsigned short count,
-    SimulatorResourceServer::ResourceModelChangedCB callback)
-{
-    OC_LOG_V(INFO, "Create multiple resource request : config=%s, count=%d", configPath.c_str(),
-             count);
-
-    // Input validation
-    if (configPath.empty())
-    {
-        OC_LOG(ERROR, TAG, "Invalid config file path!");
-        throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Invalid RAML file path!");
-    }
-
-    if (0 == count)
-    {
-        OC_LOG(ERROR, TAG, "Invalid count value!");
-        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid count value!");
-    }
-
-    if (!callback)
-    {
-        OC_LOG(ERROR, TAG, "Invalid callback!");
-        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-    }
-
-    std::vector<SimulatorResourceServerSP> resourceList;
-
-    // Create resources
-    for (unsigned short i = 0; i < count; i++)
-    {
-        OC_LOG_V(INFO, TAG, "Creating resource [%d]", i + 1);
-        SIM_LOG(ILogger::INFO, "Creating resource [" << i + 1 << "]");
-
-        SimulatorResourceServerSP resource = buildResource(configPath, callback);
-        if (!resource)
-        {
-            break;
-        }
-
-        resourceList.push_back(resource);
-    }
-
-    SIM_LOG(ILogger::INFO, "[" << resourceList.size() << " out of " << count <<
-            "] resource(s) created successfully.");
-
-    return resourceList;
-}
-
-std::vector<SimulatorResourceServerSP> ResourceManager::getResources(
-    const std::string &resourceType)
-{
-    std::lock_guard<std::recursive_mutex> lock(m_lock);
-
-    std::vector<SimulatorResourceServerSP> resourceList;
-    for (auto resourceTableEntry : m_resources)
-    {
-        if (!resourceType.empty() && resourceType.compare(resourceTableEntry.first))
-            continue;
-
-        for (auto resourceEntry : resourceTableEntry.second)
-        {
-            resourceList.push_back(resourceEntry.second);
-        }
-    }
-
-    return resourceList;
-}
-
-void ResourceManager::deleteResource(const SimulatorResourceServerSP &resource)
-{
-    if (!resource)
-    {
-        OC_LOG(ERROR, TAG, "Invalid resource object!");
-        throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Invalid resource object!");
-    }
-
-    std::lock_guard<std::recursive_mutex> lock(m_lock);
-    auto resourceTableEntry = m_resources.find(resource->getResourceType());
-    if (m_resources.end() != resourceTableEntry)
-    {
-        auto resourceEntry = resourceTableEntry->second.find(resource->getURI());
-        if (resourceTableEntry->second.end() != resourceEntry)
-        {
-            SimulatorResourceServerImplSP resourceImpl =
-                std::dynamic_pointer_cast<SimulatorResourceServerImpl>(resource);
-            resourceImpl->stop();
-            resourceTableEntry->second.erase(resourceEntry);
-            SIM_LOG(ILogger::INFO, "Resource (" << resource->getURI() <<
-                    ") deleted successfully.");
-        }
-    }
-}
-
-void ResourceManager::deleteResources(const std::string &resourceType)
-{
-    std::lock_guard<std::recursive_mutex> lock(m_lock);
-    for (auto & resourceTableEntry : m_resources)
-    {
-        if (!resourceType.empty() && resourceType.compare(resourceTableEntry.first))
-            continue;
-
-        for (auto & resourceEntry : resourceTableEntry.second)
-        {
-            SimulatorResourceServerSP resource = resourceEntry.second;
-            SimulatorResourceServerImplSP resourceImpl =
-                std::dynamic_pointer_cast<SimulatorResourceServerImpl>(resource);
-            resourceImpl->stop();
-            SIM_LOG(ILogger::INFO, "Resource (" << resource->getURI() <<
-                    ") deleted successfully.");
-        }
-
-        // Erase the entry for resource type from resources list
-        m_resources.erase(resourceTableEntry.first);
-    }
-}
-
-/**
- * This method does not validate the input given, thus Caller of this method must validate
- * the inputs before invoking this private method.
- */
-SimulatorResourceServerSP ResourceManager::buildResource(const std::string &configPath,
-        SimulatorResourceServer::ResourceModelChangedCB callback)
-{
-    // Create resource based on the RAML file.
-    SimulatorResourceServerImplSP resourceImpl = m_resourceCreator.createResource(configPath);
-    if (!resourceImpl)
-    {
-        OC_LOG(ERROR, TAG, "Failed to create resource!");
-        throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!");
-    }
-
-    resourceImpl->setModelChangeCallback(callback);
-    resourceImpl->start();
-
-    // Add the resource to resource list table
-    std::lock_guard<std::recursive_mutex> lock(m_lock);
-    SimulatorResourceServerSP resource =
-        std::dynamic_pointer_cast<SimulatorResourceServer>(resourceImpl);
-    m_resources[resourceImpl->getResourceType()].insert(
-        std::pair<std::string, SimulatorResourceServerSP>(resourceImpl->getURI(), resourceImpl));
-
-    SIM_LOG(ILogger::INFO, "Created an OIC resource of type [" <<
-            resourceImpl->getResourceType() << "]");
-    return resourceImpl;
-}
-
-/**
- * This method appends a unique key to the given URI to make the URI unique in simulator.
- * Example: If input is "/a/light", then the output will be "/a/light/simulator/0" for the first resource
- * and "/a/light/simulator/1" for the second resource and so on.
- */
-std::string ResourceManager::constructURI(const std::string &uri)
-{
-    std::ostringstream os;
-    os << uri;
-    if (!uri.empty() && '/' != uri[uri.length() - 1])
-        os << '/';
-    os << "simulator/" << m_id++;
-    return os.str();
-}
-
diff --git a/service/simulator/src/service-provider/resource_manager.h b/service/simulator/src/service-provider/resource_manager.h
deleted file mode 100644 (file)
index ddb63f3..0000000
+++ /dev/null
@@ -1,119 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-/**
- * @file   resource_manager.h
- *
- * @brief   This file provides APIs for simulated resource management.
- */
-
-#ifndef RESOURCE_MANAGER_H_
-#define RESOURCE_MANAGER_H_
-
-#include "simulator_resource_server_impl.h"
-#include "simulator_resource_creator.h"
-#include "simulator_error_codes.h"
-
-/**
- * @class   ResourceManager
- * @brief   This class provides a set of APIs for managing the simulated resource(s).
- */
-class ResourceManager
-{
-    public:
-        /**
-             *  This method is to create/obtain the singleton instance of ResourceManager.
-             */
-        static ResourceManager *getInstance(void);
-
-        /**
-             * This method is for simulating/creating a resource based on the input data provided from
-             * RAML file.
-             *
-             * @param configPath - RAML configuration file path.
-             * @param callback - Callback method for receiving notifications when resource model changes.
-             *
-             * @return SimulatorResourceServer shared object representing simulated/created resource.
-             */
-        SimulatorResourceServerSP createResource(const std::string &configPath,
-                SimulatorResourceServer::ResourceModelChangedCB callback);
-
-        /**
-             * This method is for creating multiple resources of same type based on the input data
-             * provided from RAML file.
-             *
-             * @param configPath - RAML configuration file path.
-             * @param count - Number of resource to be created.
-             * @param callback - Callback method for receiving notifications when resource model changes.
-             *
-             * @return vector of SimulatorResourceServer shared objects representing simulated/created
-             * resources.
-             */
-        std::vector<SimulatorResourceServerSP> createResource(const std::string &configPath,
-                unsigned short count, SimulatorResourceServer::ResourceModelChangedCB callback);
-
-        /**
-             * This method is for obtaining a list of created resources.
-             *
-             * @param resourceType - Resource type. Empty value will fetch all resources.
-             *                                          Default value is empty string.
-             *
-             * @return vector of SimulatorResourceServer shared objects representing simulated/created
-             */
-        std::vector<SimulatorResourceServerSP> getResources(const std::string &resourceType = "");
-
-        /**
-             * This method is for deleting/unregistering resource.
-             *
-             * @param resource - SimulatorResourceServer shared object.
-             *
-             */
-        void deleteResource(const SimulatorResourceServerSP &resource);
-
-        /**
-             * This method is for deleting multiple resources based on resource type.
-             *
-             * @param resourceType - Resource type. Empty value will delete all the resources.
-             *                                          Default value is empty string.
-             *
-             */
-        void deleteResources(const std::string &resourceType = "");
-
-    private:
-        ResourceManager(): m_id(0) {}
-        ~ResourceManager() = default;
-        ResourceManager(const ResourceManager &) = delete;
-        ResourceManager &operator=(const ResourceManager &) = delete;
-        ResourceManager(const ResourceManager &&) = delete;
-        ResourceManager &operator=(const ResourceManager && ) = delete;
-
-        SimulatorResourceServerSP buildResource(const std::string &configPath,
-                                                SimulatorResourceServer::ResourceModelChangedCB callback);
-        std::string constructURI(const std::string &uri);
-
-        /*Member variables*/
-        int m_id;
-        SimulatorResourceCreator m_resourceCreator;
-        std::recursive_mutex m_lock;
-        std::map<std::string, std::map<std::string, SimulatorResourceServerSP>> m_resources;
-};
-
-#endif
-
diff --git a/service/simulator/src/service-provider/resource_update_automation.cpp b/service/simulator/src/service-provider/resource_update_automation.cpp
deleted file mode 100644 (file)
index f2f2bc0..0000000
+++ /dev/null
@@ -1,203 +0,0 @@
-/******************************************************************
- *
- * 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 "resource_update_automation.h"
-#include "simulator_resource_server_impl.h"
-#include "attribute_generator.h"
-#include "simulator_exceptions.h"
-#include "simulator_logger.h"
-#include "logger.h"
-
-#define ATAG "ATTRIBUTE_AUTOMATION"
-#define RTAG "RESOURCE_AUTOMATION"
-
-#define SLEEP_FOR(X) if (X > 0) std::this_thread::sleep_for(std::chrono::milliseconds(X));
-
-AttributeUpdateAutomation::AttributeUpdateAutomation(int id, SimulatorResourceServer *resource,
-        const std::string &attrName, AutomationType type, int interval,
-        updateCompleteCallback callback, std::function<void (const int)> finishedCallback)
-    :   m_resource(resource),
-        m_attrName(attrName),
-        m_type(type),
-        m_id(id),
-        m_stopRequested(false),
-        m_updateInterval(interval),
-        m_callback(callback),
-        m_finishedCallback(finishedCallback),
-        m_thread(nullptr) {}
-
-void AttributeUpdateAutomation::start()
-{
-    // Check the validity of attribute
-    SimulatorResourceModel resModel = m_resource->getModel();
-    if (false == resModel.getAttribute(m_attrName, m_attribute))
-    {
-        OC_LOG_V(ERROR, ATAG, "Attribute:%s not present in resource!", m_attrName.c_str());
-        throw SimulatorException(SIMULATOR_ERROR, "Attribute is not present in resource!");
-    }
-
-    if (m_updateInterval < 0)
-    {
-        m_updateInterval = m_attribute.getUpdateFrequencyTime();
-        if (0 > m_updateInterval)
-            m_updateInterval = 0;
-    }
-
-    m_thread = new std::thread(&AttributeUpdateAutomation::updateAttribute, this);
-}
-
-void AttributeUpdateAutomation::stop()
-{
-    m_stopRequested = true;
-    if (m_thread)
-        m_thread->join();
-}
-
-void AttributeUpdateAutomation::updateAttribute()
-{
-    do
-    {
-        try
-        {
-            setAttributeValue();
-        }
-        catch (SimulatorException &e)
-        {
-            break;
-        }
-        if (m_stopRequested)
-            break;
-    }
-    while (AutomationType::RECURRENT == m_type);
-
-    if (!m_stopRequested)
-    {
-        OC_LOG_V(DEBUG, ATAG, "Attribute:%s automation is completed!", m_attrName.c_str());
-        SIM_LOG(ILogger::INFO, "Automation of " << m_attrName << " attribute is completed.");
-    }
-
-    // Notify application
-    if (m_callback)
-        m_callback(m_resource->getURI(), m_id);
-
-    if (m_finishedCallback && !m_stopRequested)
-        m_finishedCallback(m_id);
-}
-
-void AttributeUpdateAutomation::setAttributeValue()
-{
-    SimulatorResourceServerImpl *resourceImpl =
-        dynamic_cast<SimulatorResourceServerImpl *>(m_resource);
-    if (!resourceImpl)
-        return;
-
-    if (SimulatorResourceModel::Attribute::ValueType::INTEGER ==
-            m_attribute.getValueType()) // For integer type values
-    {
-        int min;
-        int max;
-
-        m_attribute.getRange(min, max);
-        for (int value = min; value <= max; value++)
-        {
-            if (m_stopRequested)
-                break;
-            resourceImpl->updateAttributeValue(m_attribute.getName(), value);
-            resourceImpl->notifyApp();
-            SLEEP_FOR(m_updateInterval);
-        }
-    }
-    else
-    {
-        for (int index = 0; index < m_attribute.getAllowedValuesSize(); index++)
-        {
-            if (m_stopRequested)
-                break;
-            resourceImpl->updateFromAllowedValues(m_attribute.getName(), index);
-            resourceImpl->notifyApp();
-            SLEEP_FOR(m_updateInterval);
-        }
-    }
-}
-
-ResourceUpdateAutomation::ResourceUpdateAutomation(int id, SimulatorResourceServer *resource,
-        AutomationType type, int interval, updateCompleteCallback callback,
-        std::function<void (const int)> finishedCallback)
-    :   m_resource(resource),
-        m_type(type),
-        m_id(id),
-        m_stopRequested(false),
-        m_updateInterval(interval),
-        m_callback(callback),
-        m_finishedCallback(finishedCallback),
-        m_thread(nullptr) {}
-
-void ResourceUpdateAutomation::start()
-{
-    SimulatorResourceModel resModel = m_resource->getModel();
-    std::map<std::string, SimulatorResourceModel::Attribute> attributesTable =
-            resModel.getAttributes();
-    if (0 == attributesTable.size())
-    {
-        OC_LOG(ERROR, RTAG, "Resource has zero attributes!");
-        throw SimulatorException(SIMULATOR_ERROR, "Resource has zero attributes!");
-    }
-
-    std::vector<SimulatorResourceModel::Attribute> attributes;
-    for (auto &attributeEntry : attributesTable)
-        attributes.push_back(attributeEntry.second);
-
-    m_thread = new std::thread(&ResourceUpdateAutomation::updateAttributes, this, attributes);
-}
-
-void ResourceUpdateAutomation::stop()
-{
-    m_stopRequested = true;
-    if (m_thread)
-        m_thread->join();
-}
-
-void ResourceUpdateAutomation::updateAttributes(
-        std::vector<SimulatorResourceModel::Attribute> attributes)
-{
-    SimulatorResourceServerImpl *resourceImpl =
-        dynamic_cast<SimulatorResourceServerImpl *>(m_resource);
-
-    AttributeCombinationGen attrCombGen(attributes);
-    SimulatorResourceModel resModel;
-    while (!m_stopRequested && attrCombGen.next(resModel))
-    {
-        for (auto &attributeEntry : resModel.getAttributes())
-        {
-            resourceImpl->updateAttributeValue(attributeEntry.first, attributeEntry.second.getValue());
-        }
-
-        resourceImpl->notifyApp();
-        SLEEP_FOR(m_updateInterval);
-    }
-
-    // Notify application
-    if (m_callback)
-        m_callback(m_resource->getURI(), m_id);
-
-    if (m_finishedCallback && !m_stopRequested)
-        m_finishedCallback(m_id);
-}
-
diff --git a/service/simulator/src/service-provider/resource_update_automation.h b/service/simulator/src/service-provider/resource_update_automation.h
deleted file mode 100644 (file)
index 6ae1f0e..0000000
+++ /dev/null
@@ -1,84 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-#ifndef RESOURCE_UPDATE_AUTOMATION_H_
-#define RESOURCE_UPDATE_AUTOMATION_H_
-
-#include "simulator_resource_server.h"
-#include <thread>
-
-class AttributeUpdateAutomation
-{
-    public:
-        AttributeUpdateAutomation(int id, SimulatorResourceServer *resource,
-                                  const std::string &attrName, AutomationType type, int interval,
-                                  updateCompleteCallback callback,
-                                  std::function<void (const int)> finishedCallback);
-
-        void start();
-
-        void stop();
-
-    private:
-        void updateAttribute();
-        void setAttributeValue();
-
-        SimulatorResourceServer *m_resource;
-        std::string m_attrName;
-        AutomationType m_type;
-        int m_id;
-        bool m_stopRequested;
-        int m_updateInterval;
-        SimulatorResourceModel::Attribute m_attribute;
-        updateCompleteCallback m_callback;
-        std::function<void (const int)> m_finishedCallback;
-        std::thread *m_thread;
-};
-
-typedef std::shared_ptr<AttributeUpdateAutomation> AttributeUpdateAutomationSP;
-
-class ResourceUpdateAutomation
-{
-    public:
-        ResourceUpdateAutomation(int id, SimulatorResourceServer *resource,
-                                 AutomationType type, int interval,
-                                 updateCompleteCallback callback,
-                                 std::function<void (const int)> finishedCallback);
-
-        void start();
-
-        void stop();
-
-    private:
-        void updateAttributes(std::vector<SimulatorResourceModel::Attribute> attributes);
-
-        SimulatorResourceServer *m_resource;
-        AutomationType m_type;
-        int m_id;
-        bool m_stopRequested;
-        int m_updateInterval;
-        updateCompleteCallback m_callback;
-        std::function<void (const int)> m_finishedCallback;
-        std::thread *m_thread;
-};
-
-typedef std::shared_ptr<ResourceUpdateAutomation> ResourceUpdateAutomationSP;
-
-#endif
diff --git a/service/simulator/src/service-provider/resource_update_automation_mngr.cpp b/service/simulator/src/service-provider/resource_update_automation_mngr.cpp
deleted file mode 100644 (file)
index 94eb2c5..0000000
+++ /dev/null
@@ -1,151 +0,0 @@
-/******************************************************************
- *
- * 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 "resource_update_automation_mngr.h"
-#include "simulator_exceptions.h"
-#include "simulator_logger.h"
-#include "logger.h"
-
-#define TAG "UPDATE_AUTOMATION_MNGR"
-
-UpdateAutomationMngr::UpdateAutomationMngr()
-    :   m_id(0) {}
-
-int UpdateAutomationMngr::startResourceAutomation(SimulatorResourceServer *resource,
-        AutomationType type, int interval, updateCompleteCallback callback)
-{
-    if (!callback)
-    {
-        OC_LOG(ERROR, TAG, "Invalid callback!");
-        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-    }
-
-    ResourceUpdateAutomationSP resourceAutomation(new ResourceUpdateAutomation(
-                m_id, resource, type, interval, callback,
-                std::bind(&UpdateAutomationMngr::automationCompleted, this, std::placeholders::_1)));
-
-    std::lock_guard<std::mutex> lock(m_lock);
-    resourceAutomation->start();
-
-    OC_LOG_V(DEBUG, TAG, "Resource automation successfully started [id: %d]", m_id);
-    SIM_LOG(ILogger::INFO, "Resource automation successfully started [ id: " << m_id << " ]");
-
-    m_resourceUpdationList[m_id] = resourceAutomation;
-    return m_id++;
-}
-
-int UpdateAutomationMngr::startAttributeAutomation(SimulatorResourceServer *resource,
-        const std::string &attrName, AutomationType type, int interval,
-        updateCompleteCallback callback)
-{
-    if (!callback)
-    {
-        OC_LOG(ERROR, TAG, "Invalid callback!");
-        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-    }
-
-    AttributeUpdateAutomationSP attributeAutomation(new AttributeUpdateAutomation(
-                m_id, resource, attrName, type, interval, callback,
-                std::bind(&UpdateAutomationMngr::automationCompleted, this, std::placeholders::_1)));
-
-    std::lock_guard<std::mutex> lock(m_lock);
-    attributeAutomation->start();
-
-    OC_LOG_V(DEBUG, TAG, "Attribute automation successfully started [name: %s, id: %d]",
-             attrName.c_str(), m_id);
-    SIM_LOG(ILogger::INFO, "Automation for " << attrName << " attribute has successfully started [ id: "
-            <<
-            m_id << " ]");
-
-    m_attrUpdationList[m_id] = attributeAutomation;
-    return m_id++;
-}
-
-std::vector<int> UpdateAutomationMngr::getResourceAutomationIds()
-{
-    std::vector<int> ids;
-    std::lock_guard<std::mutex> lock(m_lock);
-    for (auto & automation : m_resourceUpdationList)
-        ids.push_back(automation.first);
-
-    return ids;
-}
-
-std::vector<int> UpdateAutomationMngr::getAttributeAutomationIds()
-{
-    std::vector<int> ids;
-    std::lock_guard<std::mutex> lock(m_lock);
-    for (auto & automation : m_attrUpdationList)
-        ids.push_back(automation.first);
-
-    return ids;
-}
-
-void UpdateAutomationMngr::stop(int id)
-{
-    std::lock_guard<std::mutex> lock(m_lock);
-    if (m_resourceUpdationList.end() != m_resourceUpdationList.find(id))
-    {
-        m_resourceUpdationList[id]->stop();
-        m_resourceUpdationList.erase(m_resourceUpdationList.find(id));
-        return;
-    }
-    else if (m_attrUpdationList.end() != m_attrUpdationList.find(id))
-    {
-        m_attrUpdationList[id]->stop();
-        m_attrUpdationList.erase(m_attrUpdationList.find(id));
-        return;
-    }
-
-    //Throw SimulatorException
-    throw SimulatorException(SIMULATOR_ERROR, "No automation is currently in progress for the given automation Id!");
-}
-
-void UpdateAutomationMngr::stopAll()
-{
-    std::lock_guard<std::mutex> lock(m_lock);
-    std::for_each(m_resourceUpdationList.begin(),
-                  m_resourceUpdationList.end(), [] (std::pair<int, ResourceUpdateAutomationSP> element)
-    {
-        element.second->stop();
-    });
-    m_resourceUpdationList.clear();
-
-    std::for_each(m_attrUpdationList.begin(),
-                  m_attrUpdationList.end(), [] (std::pair<int, AttributeUpdateAutomationSP> element)
-    {
-        element.second->stop();
-    });
-
-    m_attrUpdationList.clear();
-}
-
-void UpdateAutomationMngr::automationCompleted(int id)
-{
-    std::lock_guard<std::mutex> lock(m_lock);
-    if (m_resourceUpdationList.end() != m_resourceUpdationList.find(id))
-    {
-        m_resourceUpdationList.erase(m_resourceUpdationList.find(id));
-    }
-    else if (m_attrUpdationList.end() != m_attrUpdationList.find(id))
-    {
-        m_attrUpdationList.erase(m_attrUpdationList.find(id));
-    }
-}
diff --git a/service/simulator/src/service-provider/resource_update_automation_mngr.h b/service/simulator/src/service-provider/resource_update_automation_mngr.h
deleted file mode 100644 (file)
index 985d79c..0000000
+++ /dev/null
@@ -1,56 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-#ifndef RESOURCE_UPDATE_AUTOMATION_MNGR_H_
-#define RESOURCE_UPDATE_AUTOMATION_MNGR_H_
-
-#include "simulator_resource_server.h"
-#include "resource_update_automation.h"
-
-class UpdateAutomationMngr
-{
-    public:
-        UpdateAutomationMngr();
-
-        int startResourceAutomation(SimulatorResourceServer *resource,
-                                    AutomationType type, int interval, updateCompleteCallback callback);
-
-        int startAttributeAutomation(SimulatorResourceServer *resource,
-                                     const std::string &attrName, AutomationType type, int interval,
-                                     updateCompleteCallback callback);
-
-        std::vector<int> getResourceAutomationIds();
-
-        std::vector<int> getAttributeAutomationIds();
-
-        void stop(int id);
-
-        void stopAll();
-
-    private:
-        void automationCompleted(int id);
-
-        int m_id;
-        std::mutex m_lock;
-        std::map<int, ResourceUpdateAutomationSP> m_resourceUpdationList;
-        std::map<int, AttributeUpdateAutomationSP> m_attrUpdationList;
-};
-
-#endif
diff --git a/service/simulator/src/service-provider/simulator_resource_creator.cpp b/service/simulator/src/service-provider/simulator_resource_creator.cpp
deleted file mode 100755 (executable)
index 18bd97a..0000000
+++ /dev/null
@@ -1,154 +0,0 @@
-/******************************************************************
- *
- * 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 "simulator_resource_creator.h"
-#include "simulator_logger.h"
-#include <RamlParser.h>
-#include "logger.h"
-
-#define TAG "SIM_RESOURCE_CREATOR"
-
-unsigned int SimulatorResourceCreator::s_id;
-SimulatorResourceServerImplSP SimulatorResourceCreator::createResource(
-    const std::string &configPath)
-{
-    RAML::RamlPtr raml;
-
-    try
-    {
-        std::shared_ptr<RAML::RamlParser> ramlParser = std::make_shared<RAML::RamlParser>(configPath);
-        raml = ramlParser->getRamlPtr();
-    }
-    catch (RAML::RamlException &e)
-    {
-        OC_LOG_V(ERROR, TAG, "RAML Exception occured! [%s]", e.what());
-        throw;
-    }
-
-    std::map<std::string, RAML::RamlResourcePtr> ramlResources = raml->getResources();
-    RAML::RamlResourcePtr ramlResource;
-    if (0 == ramlResources.size() || (ramlResource = ramlResources.begin()->second) == nullptr)
-    {
-        OC_LOG(ERROR, TAG, "Zero resources detected from RAML!");
-        return nullptr;
-    }
-
-    if (ramlResource)
-    {
-        SimulatorResourceServerImplSP simResource(new SimulatorResourceServerImpl());
-        simResource->setName(ramlResource->getDisplayName());
-        simResource->setURI(ramlResource->getResourceUri());
-
-        // Get the resource representation schema from GET response body
-        RAML::ActionPtr action = ramlResource->getAction(RAML::ActionType::GET);
-        if (!action)
-        {
-            OC_LOG(ERROR, TAG, "Failed to create resource representation schema as it does not"
-                   "posess the GET request!");
-            return nullptr;
-        }
-
-        RAML::ResponsePtr getResponse = action->getResponse("200");
-        if (!getResponse)
-        {
-            OC_LOG(ERROR, TAG, "Resource does not provide valid GET response!");
-            return nullptr;
-        }
-
-        RAML::RequestResponseBodyPtr responseBody = getResponse->getResponseBody("application/json");
-        if (responseBody)
-        {
-            RAML::JsonSchemaPtr resourceProperties = responseBody->getSchema()->getProperties();
-            for ( auto & propertyElement : resourceProperties->getProperties())
-            {
-                if (!propertyElement.second)
-                    continue;
-
-                std::string propName = propertyElement.second->getName();
-                if ("rt" == propName || "resourceType" == propName)
-                {
-                    simResource->setResourceType(propertyElement.second->getValueString());
-                    continue;
-                }
-                else if ("if" == propName)
-                {
-                    simResource->setInterfaceType(propertyElement.second->getValueString());
-                    continue;
-                }
-                else if ("p" == propName || "n" == propName || "id" == propName)
-                {
-                    continue;
-                }
-
-                // Build representation attribute
-                SimulatorResourceModel::Attribute attribute(propName);
-                switch (propertyElement.second->getValueType())
-                {
-                    case 0: // Integer
-                        attribute.setValue(propertyElement.second->getValue<int>());
-                        break;
-
-                    case 1: // Double
-                        attribute.setValue(propertyElement.second->getValue<double>());
-                        break;
-
-                    case 2: // Boolean
-                        attribute.setValue(propertyElement.second->getValue<bool>());
-                        break;
-
-                    case 3: // String
-                        attribute.setValue(propertyElement.second->getValue<std::string>());
-                        break;
-                }
-
-                // Set range/supported values set
-                int min = 0, max = 0, multipleof = 0;
-                propertyElement.second->getRange(min, max, multipleof);
-                attribute.setRange(min, max);
-
-                if (propertyElement.second->getAllowedValuesSize() > 0)
-                    attribute.setAllowedValues(propertyElement.second->getAllowedValues());
-
-                simResource->addAttribute(attribute);
-            }
-        }
-
-        simResource->setURI(constructURI(simResource->getURI()));
-        return simResource;
-    }
-
-    return nullptr;
-}
-
-/**
- * This method appends a unique key to the given URI to make the URI unique in simulator.
- * Example: If input is "/a/light", then the output will be "/a/light/simulator/0" for the first resource
- * and "/a/light/simulator/1" for the second resource and so on.
- */
-std::string SimulatorResourceCreator::constructURI(const std::string &uri)
-{
-    std::ostringstream os;
-    os << uri;
-    if (!uri.empty() && '/' != uri[uri.length() - 1])
-        os << '/';
-    os << "simulator/" << s_id++;
-    return os.str();
-}
-
diff --git a/service/simulator/src/service-provider/simulator_resource_creator.h b/service/simulator/src/service-provider/simulator_resource_creator.h
deleted file mode 100644 (file)
index 7a9a87d..0000000
+++ /dev/null
@@ -1,36 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-#ifndef SIMULATOR_RESOURCE_CREATOR_H_
-#define SIMULATOR_RESOURCE_CREATOR_H_
-
-#include "simulator_resource_server_impl.h"
-
-class SimulatorResourceCreator
-{
-    public:
-        SimulatorResourceServerImplSP createResource(const std::string &configPath);
-
-    private:
-        std::string constructURI(const std::string &uri);
-        static unsigned int s_id;
-};
-
-#endif
diff --git a/service/simulator/src/service-provider/simulator_resource_server.cpp b/service/simulator/src/service-provider/simulator_resource_server.cpp
deleted file mode 100644 (file)
index a4ae6a7..0000000
+++ /dev/null
@@ -1,75 +0,0 @@
-/******************************************************************
- *
- * 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 "simulator_resource_server.h"
-
-SimulatorResourceServer::SimulatorResourceServer()
-{
-}
-
-std::string SimulatorResourceServer::getURI() const
-{
-    return m_uri;
-}
-
-std::string SimulatorResourceServer::getResourceType() const
-{
-    return m_resourceType;
-}
-
-std::string SimulatorResourceServer::getInterfaceType() const
-{
-    return m_interfaceType;
-}
-
-std::string SimulatorResourceServer::getName() const
-{
-    return m_name;
-}
-
-void SimulatorResourceServer::addAttribute(SimulatorResourceModel::Attribute &attribute)
-{
-    m_resModel.addAttribute(attribute);
-}
-
-void SimulatorResourceServer::setRange(const std::string &attrName, const int min, const int max)
-{
-    m_resModel.setRange(attrName, min, max);
-}
-
-SimulatorResourceModel SimulatorResourceServer::getModel() const
-{
-    return m_resModel;
-}
-
-void SimulatorResourceServer::updateFromAllowedValues(const std::string &attrName,
-        unsigned int index)
-{
-    m_resModel.updateAttributeFromAllowedValues(attrName, index);
-
-    // Notify all the subscribers
-    notifyAll();
-}
-
-void SimulatorResourceServer::removeAttribute(const std::string &attrName)
-{
-    m_resModel.removeAttribute(attrName);
-}
-
diff --git a/service/simulator/src/service-provider/simulator_resource_server_impl.cpp b/service/simulator/src/service-provider/simulator_resource_server_impl.cpp
deleted file mode 100644 (file)
index 4f3b042..0000000
+++ /dev/null
@@ -1,438 +0,0 @@
-/******************************************************************
- *
- * 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 "simulator_resource_server_impl.h"
-#include "simulator_utils.h"
-#include "simulator_logger.h"
-#include "logger.h"
-
-#define TAG "SIM_RESOURCE_SERVER"
-
-SimulatorResourceServerImpl::SimulatorResourceServerImpl()
-    :   m_resourceHandle(NULL)
-{
-    m_property = static_cast<OCResourceProperty>(OC_DISCOVERABLE | OC_OBSERVABLE);
-    m_interfaceType.assign(OC::DEFAULT_INTERFACE);
-}
-
-bool SimulatorResourceServerImpl::isObservable() const
-{
-    return (m_property & OC_OBSERVABLE);
-}
-
-void SimulatorResourceServerImpl::setURI(const std::string &uri)
-{
-    m_uri = uri;
-}
-
-void SimulatorResourceServerImpl::setResourceType(const std::string &resourceType)
-{
-    m_resourceType = resourceType;
-}
-
-void SimulatorResourceServerImpl::setInterfaceType(const std::string &interfaceType)
-{
-    m_interfaceType = interfaceType;
-}
-
-void SimulatorResourceServerImpl::setName(const std::string &name)
-{
-    m_name = name;
-}
-
-void SimulatorResourceServerImpl::setObservable(bool state)
-{
-    if (true == state)
-        m_property = static_cast<OCResourceProperty>(m_property | OC_OBSERVABLE);
-    else
-        m_property = static_cast<OCResourceProperty>(m_property ^ OC_OBSERVABLE);
-}
-
-int SimulatorResourceServerImpl::startUpdateAutomation(AutomationType type,
-        int updateInterval, updateCompleteCallback callback)
-{
-    if (!callback)
-    {
-        OC_LOG(ERROR, TAG, "Invalid callback!");
-        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-    }
-
-    if (!m_resourceHandle)
-    {
-        OC_LOG(ERROR, TAG, "Invalid resource!");
-        throw SimulatorException(SIMULATOR_NO_RESOURCE, "Invalid resource!");
-    }
-
-    return m_updateAutomationMgr.startResourceAutomation(this, type, updateInterval, callback);
-}
-
-int SimulatorResourceServerImpl::startUpdateAutomation(const std::string &attrName,
-        AutomationType type, int updateInterval,
-        updateCompleteCallback callback)
-{
-    if (!callback)
-    {
-        OC_LOG(ERROR, TAG, "Invalid callback!");
-        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-    }
-
-    if (!m_resourceHandle)
-    {
-        OC_LOG(ERROR, TAG, "Invalid resource!");
-        throw SimulatorException(SIMULATOR_NO_RESOURCE, "Invalid resource!");
-    }
-
-    return m_updateAutomationMgr.startAttributeAutomation(this, attrName, type, updateInterval, callback);
-}
-
-std::vector<int> SimulatorResourceServerImpl::getResourceAutomationIds()
-{
-    return m_updateAutomationMgr.getResourceAutomationIds();
-}
-
-std::vector<int> SimulatorResourceServerImpl::getAttributeAutomationIds()
-{
-    return m_updateAutomationMgr.getAttributeAutomationIds();
-}
-
-void SimulatorResourceServerImpl::stopUpdateAutomation(const int id)
-{
-    m_updateAutomationMgr.stop(id);
-}
-
-void SimulatorResourceServerImpl::setModelChangeCallback(ResourceModelChangedCB callback)
-{
-    m_callback = callback;
-}
-
-void SimulatorResourceServerImpl::setObserverCallback(ObserverCB callback)
-{
-    m_observeCallback = callback;
-}
-
-std::vector<ObserverInfo> SimulatorResourceServerImpl::getObserversList()
-{
-    return m_observersList;
-}
-
-void SimulatorResourceServerImpl::notify(uint8_t id)
-{
-    if (!m_resourceHandle)
-    {
-        OC_LOG(ERROR, TAG, "Invalid resource!");
-        throw SimulatorException(SIMULATOR_NO_RESOURCE, "Invalid resource!");
-    }
-
-    std::shared_ptr<OC::OCResourceResponse> resourceResponse =
-    {std::make_shared<OC::OCResourceResponse>()};
-
-    resourceResponse->setErrorCode(200);
-    resourceResponse->setResponseResult(OC_EH_OK);
-    resourceResponse->setResourceRepresentation(getOCRepresentation(), OC::DEFAULT_INTERFACE);
-
-    OC::ObservationIds observers;
-    observers.push_back(id);
-
-    SIM_LOG(ILogger::INFO, "[" << m_uri << "] Sending notification to observer with id " << id);
-
-    typedef OCStackResult (*NotifyListOfObservers)(OCResourceHandle, OC::ObservationIds &,
-            const std::shared_ptr<OC::OCResourceResponse>);
-
-    invokeocplatform(static_cast<NotifyListOfObservers>(OC::OCPlatform::notifyListOfObservers),
-                     m_resourceHandle,
-                     observers,
-                     resourceResponse);
-}
-
-void SimulatorResourceServerImpl::notifyAll()
-{
-    if (!m_resourceHandle)
-    {
-        OC_LOG(ERROR, TAG, "Invalid resource!");
-        throw SimulatorException(SIMULATOR_NO_RESOURCE, "Invalid resource!");
-    }
-
-    if (!m_observersList.size())
-    {
-        OC_LOG(ERROR, TAG, "Observers list is empty!");
-        return;
-    }
-
-    std::shared_ptr<OC::OCResourceResponse> resourceResponse =
-    {std::make_shared<OC::OCResourceResponse>()};
-
-    resourceResponse->setErrorCode(200);
-    resourceResponse->setResponseResult(OC_EH_OK);
-    resourceResponse->setResourceRepresentation(getOCRepresentation(), OC::DEFAULT_INTERFACE);
-
-    OC::ObservationIds observers;
-    for (auto & observer : m_observersList)
-        observers.push_back(observer.id);
-
-    SIM_LOG(ILogger::INFO, "[" << m_uri << "] Sending notification to all observers");
-
-    typedef OCStackResult (*NotifyListOfObservers)(OCResourceHandle, OC::ObservationIds &,
-            const std::shared_ptr<OC::OCResourceResponse>);
-
-    invokeocplatform(static_cast<NotifyListOfObservers>(OC::OCPlatform::notifyListOfObservers),
-                     m_resourceHandle,
-                     observers,
-                     resourceResponse);
-}
-
-void SimulatorResourceServerImpl::start()
-{
-    if (m_uri.empty() || m_resourceType.empty() ||
-        m_interfaceType.empty() || m_name.empty() || !m_callback)
-    {
-        OC_LOG(ERROR, TAG, "Invalid data found to register the resource!");
-        throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Invalid data found to register the resource!");
-    }
-
-    if (m_resourceHandle)
-    {
-        OC_LOG(ERROR, TAG, "Resource already registered!");
-        throw SimulatorException(SIMULATOR_ERROR, "Resource already registered!");
-    }
-
-    typedef OCStackResult (*RegisterResource)(OCResourceHandle &, std::string &, const std::string &,
-            const std::string &, OC::EntityHandler, uint8_t);
-
-    invokeocplatform(static_cast<RegisterResource>(OC::OCPlatform::registerResource),
-                     m_resourceHandle, m_uri, m_resourceType, m_interfaceType,
-                     std::bind(&SimulatorResourceServerImpl::entityHandler,
-                               this, std::placeholders::_1), m_property);
-}
-
-void SimulatorResourceServerImpl::stop()
-{
-    if (!m_resourceHandle)
-    {
-        OC_LOG(ERROR, TAG, "Invalid resource!");
-        throw SimulatorException(SIMULATOR_NO_RESOURCE, "Invalid resource!");
-    }
-
-    typedef OCStackResult (*UnregisterResource)(const OCResourceHandle &);
-
-    invokeocplatform(static_cast<UnregisterResource>(OC::OCPlatform::unregisterResource),
-                     m_resourceHandle);
-
-    m_resourceHandle = nullptr;
-}
-
-void SimulatorResourceServerImpl::notifyApp()
-{
-    // Notify the application callback
-    if (m_callback)
-    {
-        m_callback(m_uri, m_resModel);
-    }
-}
-
-OC::OCRepresentation SimulatorResourceServerImpl::getOCRepresentation()
-{
-    return m_resModel.getOCRepresentation();
-}
-
-bool SimulatorResourceServerImpl::modifyResourceModel(OC::OCRepresentation &ocRep)
-{
-    bool status = m_resModel.update(ocRep);
-    if (true == status)
-    {
-        resourceModified();
-    }
-    return status;
-}
-
-void SimulatorResourceServerImpl::resourceModified()
-{
-    if (!m_resourceHandle)
-    {
-        return;
-    }
-
-    // Notify all the subscribers
-    notifyAll();
-
-    // Notify the application callback
-    if (m_callback)
-    {
-        m_callback(m_uri, m_resModel);
-    }
-}
-
-OCEntityHandlerResult SimulatorResourceServerImpl::entityHandler(
-    std::shared_ptr<OC::OCResourceRequest>
-    request)
-{
-    OCEntityHandlerResult errCode = OC_EH_ERROR;
-    if (!request)
-    {
-        return OC_EH_ERROR;
-    }
-
-    if (OC::RequestHandlerFlag::RequestFlag & request->getRequestHandlerFlag())
-    {
-        auto response = std::make_shared<OC::OCResourceResponse>();
-        response->setRequestHandle(request->getRequestHandle());
-        response->setResourceHandle(request->getResourceHandle());
-
-        if ("GET" == request->getRequestType())
-        {
-            OC::OCRepresentation rep = request->getResourceRepresentation();
-            std::string payload = getPayloadString(rep);
-            SIM_LOG(ILogger::INFO, "[" << m_uri <<
-                    "] GET request received. \n**Payload details**" << payload)
-
-            response->setErrorCode(200);
-            response->setResponseResult(OC_EH_OK);
-            response->setResourceRepresentation(getOCRepresentation());
-
-            if (OC_STACK_OK == OC::OCPlatform::sendResponse(response))
-            {
-                errCode = OC_EH_OK;
-            }
-        }
-        else if ("PUT" == request->getRequestType())
-        {
-            OC::OCRepresentation rep = request->getResourceRepresentation();
-            std::string payload = getPayloadString(rep);
-            SIM_LOG(ILogger::INFO, "[" << m_uri <<
-                    "] PUT request received. \n**Payload details**" << payload)
-
-            if (true == modifyResourceModel(rep))
-            {
-                response->setErrorCode(200);
-                response->setResponseResult(OC_EH_OK);
-                response->setResourceRepresentation(getOCRepresentation());
-            }
-            else
-            {
-                response->setErrorCode(400);
-                response->setResponseResult(OC_EH_ERROR);
-            }
-
-            if (OC_STACK_OK == OC::OCPlatform::sendResponse(response))
-            {
-                errCode = OC_EH_OK;
-            }
-        }
-        else if ("POST" == request->getRequestType())
-        {
-            OC::OCRepresentation rep = request->getResourceRepresentation();
-            std::string payload = getPayloadString(rep);
-            SIM_LOG(ILogger::INFO, "[" << m_uri <<
-                    "] POST request received. \n**Payload details**" << payload)
-
-            if (true == modifyResourceModel(rep))
-            {
-                response->setErrorCode(200);
-                response->setResponseResult(OC_EH_OK);
-                response->setResourceRepresentation(getOCRepresentation());
-            }
-            else
-            {
-                response->setErrorCode(400);
-                response->setResponseResult(OC_EH_ERROR);
-            }
-
-            if (OC_STACK_OK == OC::OCPlatform::sendResponse(response))
-            {
-                errCode = OC_EH_OK;
-            }
-        }
-        else if ("DELETE" == request->getRequestType())
-        {
-            OC::OCRepresentation rep = request->getResourceRepresentation();
-            std::string payload = getPayloadString(rep);
-            SIM_LOG(ILogger::INFO, "[" << m_uri <<
-                    "] DELETE request received. \n**Payload details**" << payload)
-
-            // DELETE request handling not supported right now
-            response->setErrorCode(400);
-            response->setResponseResult(OC_EH_ERROR);
-            if (OC_STACK_OK == OC::OCPlatform::sendResponse(response))
-            {
-                errCode = OC_EH_OK;
-            }
-        }
-        else
-        {
-            OC::OCRepresentation rep = request->getResourceRepresentation();
-            std::string payload = getPayloadString(rep);
-            SIM_LOG(ILogger::INFO, "[" << m_uri <<
-                    "] UNKNOWN type request received. \n**Payload details**" << payload)
-
-            response->setResponseResult(OC_EH_ERROR);
-            if (OC_STACK_OK == OC::OCPlatform::sendResponse(response))
-            {
-                errCode = OC_EH_ERROR;
-            }
-        }
-    }
-
-    if (OC::RequestHandlerFlag::ObserverFlag & request->getRequestHandlerFlag())
-    {
-        if (false == isObservable())
-        {
-            SIM_LOG(ILogger::INFO, "[" << m_uri << "] OBSERVE request received")
-            SIM_LOG(ILogger::INFO, "[" << m_uri << "] Sending error as resource is in unobservable state")
-            return OC_EH_ERROR;
-        }
-
-        OC::ObservationInfo observationInfo = request->getObservationInfo();
-        if (OC::ObserveAction::ObserveRegister == observationInfo.action)
-        {
-            SIM_LOG(ILogger::INFO, "[" << m_uri << "] OBSERVE REGISTER request received");
-
-            ObserverInfo info {observationInfo.obsId, observationInfo.address, observationInfo.port};
-            m_observersList.push_back(info);
-
-            //Inform about addition of observer
-            if (m_observeCallback)
-            {
-                m_observeCallback(m_uri, ObservationStatus::OBSERVE_REGISTER, info);
-            }
-        }
-        else if (OC::ObserveAction::ObserveUnregister == observationInfo.action)
-        {
-            SIM_LOG(ILogger::INFO, "[" << m_uri << "] OBSERVE UNREGISTER request received");
-
-            ObserverInfo info;
-            for (auto iter = m_observersList.begin(); iter != m_observersList.end(); iter++)
-            {
-                if ((info = *iter), info.id == observationInfo.obsId)
-                {
-                    m_observersList.erase(iter);
-                    break;
-                }
-            }
-
-            // Inform about cancellation of observer
-            if (m_observeCallback)
-            {
-                m_observeCallback(m_uri, ObservationStatus::OBSERVE_UNREGISTER, info);
-            }
-        }
-        errCode = OC_EH_OK;
-    }
-
-    return errCode;
-}
diff --git a/service/simulator/src/service-provider/simulator_resource_server_impl.h b/service/simulator/src/service-provider/simulator_resource_server_impl.h
deleted file mode 100644 (file)
index 010865c..0000000
+++ /dev/null
@@ -1,89 +0,0 @@
-/******************************************************************
- *
- * 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.
- *
- ******************************************************************/
-
-#ifndef SIMULATOR_RESOURCE_SERVER_IMPL_H_
-#define SIMULATOR_RESOURCE_SERVER_IMPL_H_
-
-#include "simulator_resource_server.h"
-#include "resource_update_automation_mngr.h"
-
-class SimulatorResourceServerImpl : public SimulatorResourceServer
-{
-    public:
-        SimulatorResourceServerImpl();
-
-        void setURI(const std::string &uri);
-
-        void setResourceType(const std::string &resourceType);
-
-        void setInterfaceType(const std::string &interfaceType);
-
-        void setName(const std::string &name);
-
-        void setObservable(bool state);
-
-        bool isObservable() const;
-
-        int startUpdateAutomation(AutomationType type, int updateInterval,
-                                  updateCompleteCallback callback);
-
-        int startUpdateAutomation(const std::string &attrName, AutomationType type,
-                                  int updateInterval, updateCompleteCallback callback);
-
-        std::vector<int> getResourceAutomationIds();
-
-        std::vector<int> getAttributeAutomationIds();
-
-        void stopUpdateAutomation(const int id);
-
-        void setModelChangeCallback(ResourceModelChangedCB callback);
-
-        void setObserverCallback(ObserverCB callback);
-
-        std::vector<ObserverInfo> getObserversList();
-
-        void notify(uint8_t id);
-
-        void notifyAll();
-
-        void start();
-
-        void stop();
-
-        void notifyApp();
-
-    private:
-        OC::OCRepresentation getOCRepresentation();
-        bool modifyResourceModel(OC::OCRepresentation &ocRep);
-        OCEntityHandlerResult entityHandler(std::shared_ptr<OC::OCResourceRequest> request);
-        void resourceModified();
-
-        ResourceModelChangedCB m_callback;
-        ObserverCB m_observeCallback;
-        UpdateAutomationMngr m_updateAutomationMgr;
-        std::vector<ObserverInfo> m_observersList;
-
-        OCResourceProperty m_property;
-        OCResourceHandle m_resourceHandle;
-};
-
-typedef std::shared_ptr<SimulatorResourceServerImpl> SimulatorResourceServerImplSP;
-
-#endif
index 38e5269..2f0fb29 100644 (file)
@@ -19,8 +19,8 @@
  ******************************************************************/
 
 #include "simulator_manager.h"
-#include "resource_manager.h"
-#include "simulator_client.h"
+#include "simulator_resource_factory.h"
+#include "simulator_remote_resource_impl.h"
 #include "simulator_utils.h"
 
 SimulatorManager *SimulatorManager::getInstance()
@@ -43,54 +43,118 @@ SimulatorManager::SimulatorManager()
     OC::OCPlatform::Configure(conf);
 }
 
-std::shared_ptr<SimulatorResourceServer> SimulatorManager::createResource(
-    const std::string &configPath,
-    SimulatorResourceServer::ResourceModelChangedCB callback)
+std::shared_ptr<SimulatorResource> SimulatorManager::createResource(
+    const std::string &configPath)
 {
-    return ResourceManager::getInstance()->createResource(configPath, callback);
-}
+    VALIDATE_INPUT(configPath.empty(), "Empty path!")
 
-std::vector<std::shared_ptr<SimulatorResourceServer>> SimulatorManager::createResource(
-            const std::string &configPath, unsigned short count,
-            SimulatorResourceServer::ResourceModelChangedCB callback)
-{
-    return ResourceManager::getInstance()->createResource(configPath, count, callback);
+    std::shared_ptr<SimulatorResource> resource;
+    try
+    {
+        resource = SimulatorResourceFactory::getInstance()->createResource(configPath);
+        if (!resource)
+            throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!");
+    }
+    catch (RAML::RamlException &e)
+    {
+        throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!");
+    }
+
+    return resource;
 }
 
-std::vector<std::shared_ptr<SimulatorResourceServer>> SimulatorManager::getResources(
-            const std::string &resourceType)
+std::vector<std::shared_ptr<SimulatorResource>> SimulatorManager::createResource(
+            const std::string &configPath, unsigned int count)
 {
-    return ResourceManager::getInstance()->getResources(resourceType);
+    VALIDATE_INPUT(configPath.empty(), "Empty path!")
+    VALIDATE_INPUT(!count, "Count is zero!")
+
+    std::vector<std::shared_ptr<SimulatorResource>> resources;
+    try
+    {
+        resources = SimulatorResourceFactory::getInstance()->createResource(configPath, count);
+        if (!resources.size())
+            throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!");
+    }
+    catch (RAML::RamlException &e)
+    {
+        throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!");
+    }
+
+    return resources;
 }
 
-void SimulatorManager::deleteResource(
-    const std::shared_ptr<SimulatorResourceServer> &resource)
+std::shared_ptr<SimulatorSingleResource> SimulatorManager::createSingleResource(
+    const std::string &name, const std::string &uri, const std::string &resourceType)
 {
-    ResourceManager::getInstance()->deleteResource(resource);
+    VALIDATE_INPUT(name.empty(), "Empty resource name!")
+    VALIDATE_INPUT(uri.empty(), "Empty URI!")
+    VALIDATE_INPUT(resourceType.empty(), "Empty resource type!")
+
+    return SimulatorResourceFactory::getInstance()->createSingleResource(name, uri, resourceType);
 }
 
-void SimulatorManager::deleteResource(const std::string &resourceType)
+std::shared_ptr<SimulatorCollectionResource> SimulatorManager::createCollectionResource(
+    const std::string &name, const std::string &uri, const std::string &resourceType)
 {
-    ResourceManager::getInstance()->deleteResources(resourceType);
+    VALIDATE_INPUT(name.empty(), "Empty resource name!")
+    VALIDATE_INPUT(uri.empty(), "Empty URI!")
+    VALIDATE_INPUT(resourceType.empty(), "Empty resource type!")
+
+    return SimulatorResourceFactory::getInstance()->createCollectionResource(name, uri, resourceType);
 }
 
 void SimulatorManager::findResource(ResourceFindCallback callback)
 {
-    SimulatorClient::getInstance()->findResources(callback);
+    VALIDATE_CALLBACK(callback)
+
+    OC::FindCallback findCallback = std::bind(
+                                        [](std::shared_ptr<OC::OCResource> ocResource, ResourceFindCallback callback)
+    {
+        if (!ocResource)
+            return;
+
+        callback(std::make_shared<SimulatorRemoteResourceImpl>(ocResource));
+    }, std::placeholders::_1, callback);
+
+    typedef OCStackResult (*FindResource)(const std::string &, const std::string &,
+                                          OCConnectivityType, OC::FindCallback);
+
+    invokeocplatform(static_cast<FindResource>(OC::OCPlatform::findResource), "",
+                     OC_MULTICAST_DISCOVERY_URI, CT_DEFAULT, findCallback);
 }
 
 void SimulatorManager::findResource(const std::string &resourceType,
-                                     ResourceFindCallback callback)
+                                    ResourceFindCallback callback)
 {
-    SimulatorClient::getInstance()->findResources(resourceType, callback);
+    VALIDATE_INPUT(resourceType.empty(), "Empty resource type!")
+    VALIDATE_CALLBACK(callback)
+
+    OC::FindCallback findCallback = std::bind(
+                                        [](std::shared_ptr<OC::OCResource> ocResource, ResourceFindCallback callback)
+    {
+        if (!ocResource)
+            return;
+
+        callback(std::make_shared<SimulatorRemoteResourceImpl>(ocResource));
+    }, std::placeholders::_1, callback);
+
+    std::ostringstream query;
+    query << OC_MULTICAST_DISCOVERY_URI << "?rt=" << resourceType;
+
+    typedef OCStackResult (*FindResource)(const std::string &, const std::string &,
+                                          OCConnectivityType, OC::FindCallback);
+
+    invokeocplatform(static_cast<FindResource>(OC::OCPlatform::findResource), "", query.str(),
+                     CT_DEFAULT, findCallback);
 }
 
-void SimulatorManager::getDeviceInfo(DeviceInfoCallback callback)
+void SimulatorManager::getDeviceInfo(const std::string &host, DeviceInfoCallback callback)
 {
-    if (!callback)
-        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+    VALIDATE_CALLBACK(callback)
 
-    OC::FindDeviceCallback deviceCallback = [this, callback](const OC::OCRepresentation & rep)
+    OC::FindDeviceCallback deviceCallback = std::bind(
+            [](const OC::OCRepresentation & rep, const std::string & hostUri, DeviceInfoCallback callback)
     {
         std::string deviceName = rep.getValue<std::string>("n");
         std::string deviceID = rep.getValue<std::string>("di");
@@ -98,41 +162,34 @@ void SimulatorManager::getDeviceInfo(DeviceInfoCallback callback)
         std::string deviceDMV = rep.getValue<std::string>("dmv");
 
         DeviceInfo deviceInfo(deviceName, deviceID, deviceSpecVersion, deviceDMV);
-        callback(deviceInfo);
-    };
-
-    std::ostringstream uri;
-    uri << OC_MULTICAST_PREFIX << OC_RSRVD_DEVICE_URI;
+        callback(hostUri, deviceInfo);
+    }, std::placeholders::_1, host, callback);
 
     typedef OCStackResult (*GetDeviceInfo)(const std::string &, const std::string &,
                                            OCConnectivityType, OC::FindDeviceCallback);
 
-    invokeocplatform(static_cast<GetDeviceInfo>(OC::OCPlatform::getDeviceInfo), "",
-                     uri.str(),
-                     CT_DEFAULT,
-                     deviceCallback);
+    invokeocplatform(static_cast<GetDeviceInfo>(OC::OCPlatform::getDeviceInfo), host.c_str(),
+                     "/oic/d", CT_DEFAULT, deviceCallback);
 }
 
 void SimulatorManager::setDeviceInfo(const std::string &deviceName)
 {
-    if (deviceName.empty())
-        throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Device name is empty!");
-
+    VALIDATE_INPUT(deviceName.empty(), "Empty resource type!")
 
     typedef OCStackResult (*RegisterDeviceInfo)(const OCDeviceInfo);
 
-    OCDeviceInfo ocDeviceInfo;
+    OCDeviceInfo ocDeviceInfo {nullptr, nullptr};
     ocDeviceInfo.deviceName = const_cast<char *>(deviceName.c_str());
     invokeocplatform(static_cast<RegisterDeviceInfo>(OC::OCPlatform::registerDeviceInfo),
                      ocDeviceInfo);
 }
 
-void SimulatorManager::getPlatformInfo(PlatformInfoCallback callback)
+void SimulatorManager::getPlatformInfo(const std::string &host, PlatformInfoCallback callback)
 {
-    if (!callback)
-        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+    VALIDATE_CALLBACK(callback)
 
-    OC::FindPlatformCallback platformCallback = [this, callback](const OC::OCRepresentation & rep)
+    OC::FindPlatformCallback platformCallback = std::bind(
+                [](const OC::OCRepresentation & rep, const std::string & hostUri, PlatformInfoCallback callback)
     {
         PlatformInfo platformInfo;
         platformInfo.setPlatformID(rep.getValue<std::string>("pi"));
@@ -147,19 +204,14 @@ void SimulatorManager::getPlatformInfo(PlatformInfoCallback callback)
         platformInfo.setSupportUrl(rep.getValue<std::string>("mnsl"));
         platformInfo.setSystemTime(rep.getValue<std::string>("st"));
 
-        callback(platformInfo);
-    };
-
-    std::ostringstream uri;
-    uri << OC_MULTICAST_PREFIX << OC_RSRVD_PLATFORM_URI;
+        callback(hostUri, platformInfo);
+    }, std::placeholders::_1, host, callback);
 
     typedef OCStackResult (*GetPlatformInfo)(const std::string &, const std::string &,
             OCConnectivityType, OC::FindPlatformCallback);
 
-    invokeocplatform(static_cast<GetPlatformInfo>(OC::OCPlatform::getPlatformInfo), "",
-                     uri.str(),
-                     CT_DEFAULT,
-                     platformCallback);
+    invokeocplatform(static_cast<GetPlatformInfo>(OC::OCPlatform::getPlatformInfo), host.c_str(),
+                     "/oic/p", CT_DEFAULT, platformCallback);
 }
 
 void SimulatorManager::setPlatformInfo(PlatformInfo &platformInfo)
diff --git a/service/simulator/unittests/SimulatorTest/.gitignore b/service/simulator/unittests/SimulatorTest/.gitignore
new file mode 100644 (file)
index 0000000..ae3c172
--- /dev/null
@@ -0,0 +1 @@
+/bin/
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/client/test/SimulatorRemoteResourceTest.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/client/test/SimulatorRemoteResourceTest.java
new file mode 100644 (file)
index 0000000..a37f65b
--- /dev/null
@@ -0,0 +1,1138 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator.client.test;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.InvalidArgsException;
+import org.oic.simulator.SimulatorException;
+import org.oic.simulator.SimulatorManager;
+import org.oic.simulator.SimulatorResourceAttribute;
+import org.oic.simulator.SimulatorResourceModel;
+import org.oic.simulator.SimulatorResult;
+import org.oic.simulator.client.FindResourceListener;
+import org.oic.simulator.client.SimulatorRemoteResource;
+import org.oic.simulator.server.SimulatorSingleResource;
+import org.oic.simulator.test.ExceptionType;
+import org.oic.simulator.utils.ObjectHolder;
+
+import junit.framework.TestCase;
+
+/**
+ * This class tests the APIs of SimulatorRemoteResource class.
+ */
+public class SimulatorRemoteResourceTest extends TestCase {
+    private static final String            SINGLE_RES_RAML = "./ramls/oic.r.light.raml";
+    private static SimulatorSingleResource singleResource  = null;
+    private static SimulatorRemoteResource remoteResource  = null;
+
+    protected void setUp() throws Exception {
+        super.setUp();
+
+        // Create single resource for first time
+        if (null == singleResource) {
+            singleResource = (SimulatorSingleResource) SimulatorManager
+                    .createResource(SINGLE_RES_RAML);
+            singleResource.start();
+        }
+
+        // Find the created resource for first time
+        if (null != singleResource && null == remoteResource) {
+            CountDownLatch lockObject = new CountDownLatch(1);
+            ObjectHolder<SimulatorRemoteResource> resourceHolder = new ObjectHolder<>();
+            FindResourceCallbackListener listener = new FindResourceCallbackListener(
+                    lockObject, resourceHolder);
+
+            try {
+                SimulatorManager.findResource(singleResource.getResourceType(),
+                        listener);
+
+                try {
+                    lockObject.await(10, TimeUnit.SECONDS);
+                } catch (InterruptedException e) {
+                }
+
+            } catch (InvalidArgsException e) {
+                e.printStackTrace();
+            } catch (SimulatorException e) {
+                e.printStackTrace();
+            }
+
+            remoteResource = resourceHolder.get();
+        }
+    }
+
+    protected void tearDown() throws Exception {
+        super.tearDown();
+    }
+
+    public void testGetUri_P01() {
+        String serverURI = null;
+        try {
+            serverURI = singleResource.getURI();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertNotNull(remoteResource.getURI());
+        assertEquals(serverURI, remoteResource.getURI());
+    }
+
+    public void testGetConnectivityType_P01() {
+        assertNotNull(remoteResource.getConnectivityType());
+    }
+
+    public void testGetResourceTypes_P01() {
+        assertNotNull(remoteResource.getResourceTypes());
+        assertTrue(remoteResource.getResourceTypes().size() > 0);
+    }
+
+    public void testGetResourceInterfaces_P01() {
+        assertNotNull(remoteResource.getResourceInterfaces());
+        assertTrue(remoteResource.getResourceInterfaces().size() > 0);
+    }
+
+    public void testGetHost_P01() {
+        assertNotNull(remoteResource.getHost());
+    }
+
+    public void testGetId_P01() {
+        assertNotNull(remoteResource.getId());
+    }
+
+    public void testIsObservable_P01() {
+        boolean serverObserveState = false;
+        try {
+            serverObserveState = singleResource.isObservable();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(serverObserveState, remoteResource.isObservable());
+    }
+
+    public void testGet_P01() {
+        CountDownLatch lockObject = new CountDownLatch(1);
+        boolean syncResult = false;
+        ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
+        GetResponseCallbackListener listener = new GetResponseCallbackListener(
+                lockObject, response);
+
+        try {
+            remoteResource.get(null, listener);
+
+            try {
+                lockObject.await(10, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+            }
+
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(syncResult);
+        assertNotNull(response.get());
+        assertEquals(remoteResource.getId(), response.get().uid());
+    }
+
+    public void testGet_P02() {
+        CountDownLatch lockObject = new CountDownLatch(1);
+        boolean syncResult = false;
+        ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
+        GetResponseCallbackListener listener = new GetResponseCallbackListener(
+                lockObject, response);
+
+        try {
+            Map<String, String> queryParams = new HashMap<>();
+            remoteResource.get(queryParams, listener);
+
+            try {
+                lockObject.await(10, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+            }
+
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(syncResult);
+        assertNotNull(response.get());
+        assertEquals(remoteResource.getId(), response.get().uid());
+    }
+
+    public void testGet_P03() {
+        CountDownLatch lockObject = new CountDownLatch(1);
+        boolean syncResult = false;
+        ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
+        GetResponseCallbackListener listener = new GetResponseCallbackListener(
+                lockObject, response);
+
+        try {
+            remoteResource.get(remoteResource.getResourceInterfaces().get(0),
+                    null, listener);
+
+            try {
+                lockObject.await(10, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+            }
+
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(syncResult);
+        assertNotNull(response.get());
+        assertEquals(remoteResource.getId(), response.get().uid());
+    }
+
+    public void testGet_P04() {
+        CountDownLatch lockObject = new CountDownLatch(1);
+        boolean syncResult = false;
+        ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
+        GetResponseCallbackListener listener = new GetResponseCallbackListener(
+                lockObject, response);
+
+        try {
+            Map<String, String> queryParams = new HashMap<>();
+            remoteResource.get(remoteResource.getResourceInterfaces().get(0),
+                    queryParams, listener);
+
+            try {
+                lockObject.await(10, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+            }
+
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(syncResult);
+        assertNotNull(response.get());
+        assertEquals(remoteResource.getId(), response.get().uid());
+    }
+
+    public void testGet_N01() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            remoteResource.get(null, null);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
+    }
+
+    public void testGet_N02() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            remoteResource.get(remoteResource.getResourceInterfaces().get(0),
+                    null, null);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
+    }
+
+    public void testGet_N03() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            Map<String, String> queryParams = new HashMap<>();
+            remoteResource.get(null, queryParams,
+                    new SimulatorRemoteResource.GetResponseListener() {
+                        @Override
+                        public void onGetResponse(String uid,
+                                SimulatorResult result,
+                                SimulatorResourceModel resourceModel) {
+                        }
+                    });
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
+    }
+
+    public void testPut_P01() {
+        CountDownLatch lockObject = new CountDownLatch(1);
+        boolean syncResult = false;
+        ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
+        PutResponseCallbackListener listener = new PutResponseCallbackListener(
+                lockObject, response);
+
+        try {
+            SimulatorResourceModel resModel = singleResource.getResourceModel();
+            remoteResource.put(null, resModel, listener);
+
+            try {
+                lockObject.await(10, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+            }
+
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(syncResult);
+        assertNotNull(response.get());
+        assertNotNull(response.get().resourceModel());
+        assertEquals(remoteResource.getId(), response.get().uid());
+    }
+
+    public void testPut_P02() {
+        CountDownLatch lockObject = new CountDownLatch(1);
+        boolean syncResult = false;
+        ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
+        PutResponseCallbackListener listener = new PutResponseCallbackListener(
+                lockObject, response);
+
+        try {
+            SimulatorResourceModel resModel = singleResource.getResourceModel();
+            Map<String, String> queryParams = new HashMap<>();
+            remoteResource.put(queryParams, resModel, listener);
+
+            try {
+                lockObject.await(10, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+            }
+
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(syncResult);
+        assertNotNull(response.get());
+        assertNotNull(response.get().resourceModel());
+        assertEquals(remoteResource.getId(), response.get().uid());
+    }
+
+    public void testPut_P03() {
+        CountDownLatch lockObject = new CountDownLatch(1);
+        boolean syncResult = false;
+        ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
+        PutResponseCallbackListener listener = new PutResponseCallbackListener(
+                lockObject, response);
+
+        try {
+            SimulatorResourceModel resModel = singleResource.getResourceModel();
+            remoteResource.put(remoteResource.getResourceInterfaces().get(0),
+                    null, resModel, listener);
+
+            try {
+                lockObject.await(10, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+            }
+
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(syncResult);
+        assertNotNull(response.get());
+        assertNotNull(response.get().resourceModel());
+        assertEquals(remoteResource.getId(), response.get().uid());
+    }
+
+    public void testPut_P05() {
+        CountDownLatch lockObject = new CountDownLatch(1);
+        boolean syncResult = false;
+        ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
+        PutResponseCallbackListener listener = new PutResponseCallbackListener(
+                lockObject, response);
+
+        try {
+            SimulatorResourceModel resModel = singleResource.getResourceModel();
+            Map<String, String> queryParams = new HashMap<>();
+            remoteResource.put(remoteResource.getResourceInterfaces().get(0),
+                    queryParams, resModel, listener);
+
+            try {
+                lockObject.await(10, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+            }
+
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(syncResult);
+        assertNotNull(response.get());
+        assertNotNull(response.get().resourceModel());
+        assertEquals(remoteResource.getId(), response.get().uid());
+    }
+
+    public void testPut_P04() {
+        CountDownLatch lockObject = new CountDownLatch(1);
+        boolean syncResult = false;
+        ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
+        PutResponseCallbackListener listener = new PutResponseCallbackListener(
+                lockObject, response);
+
+        try {
+            Map<String, String> queryParams = new HashMap<>();
+            remoteResource.put(queryParams, null, listener);
+
+            try {
+                lockObject.await(10, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+            }
+
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(syncResult);
+        assertNotNull(response.get());
+        assertNotNull(response.get().resourceModel());
+        assertEquals(remoteResource.getId(), response.get().uid());
+    }
+
+    public void testPut_N01() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            SimulatorResourceModel resModel = singleResource.getResourceModel();
+            remoteResource.put(null, resModel, null);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
+    }
+
+    public void testPut_N02() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            SimulatorResourceModel resModel = singleResource.getResourceModel();
+            remoteResource.put(remoteResource.getResourceInterfaces().get(0),
+                    null, resModel, null);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
+    }
+
+    public void testPut_N03() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            SimulatorResourceModel resModel = singleResource.getResourceModel();
+            Map<String, String> queryParams = new HashMap<>();
+            remoteResource.put(null, queryParams, resModel,
+                    new SimulatorRemoteResource.PutResponseListener() {
+                        @Override
+                        public void onPutResponse(String uid,
+                                SimulatorResult result,
+                                SimulatorResourceModel resourceModel) {
+                        }
+                    });
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
+    }
+
+    public void testPost_P01() {
+        CountDownLatch lockObject = new CountDownLatch(1);
+        boolean syncResult = false;
+        ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
+        PostResponseCallbackListener listener = new PostResponseCallbackListener(
+                lockObject, response);
+
+        try {
+            SimulatorResourceModel resModel = singleResource.getResourceModel();
+            remoteResource.post(null, resModel, listener);
+
+            try {
+                lockObject.await(10, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+            }
+
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(syncResult);
+        assertNotNull(response.get());
+        assertNotNull(response.get().resourceModel());
+        assertEquals(remoteResource.getId(), response.get().uid());
+    }
+
+    public void testPost_P02() {
+        CountDownLatch lockObject = new CountDownLatch(1);
+        boolean syncResult = false;
+        ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
+        PostResponseCallbackListener listener = new PostResponseCallbackListener(
+                lockObject, response);
+
+        try {
+            SimulatorResourceModel resModel = singleResource.getResourceModel();
+            Map<String, String> queryParams = new HashMap<>();
+            remoteResource.post(queryParams, resModel, listener);
+
+            try {
+                lockObject.await(10, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+            }
+
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(syncResult);
+        assertNotNull(response.get());
+        assertNotNull(response.get().resourceModel());
+        assertEquals(remoteResource.getId(), response.get().uid());
+    }
+
+    public void testPost_P03() {
+        CountDownLatch lockObject = new CountDownLatch(1);
+        boolean syncResult = false;
+        ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
+        PostResponseCallbackListener listener = new PostResponseCallbackListener(
+                lockObject, response);
+
+        try {
+            SimulatorResourceModel resModel = singleResource.getResourceModel();
+            remoteResource.post(remoteResource.getResourceInterfaces().get(0),
+                    null, resModel, listener);
+
+            try {
+                lockObject.await(10, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+            }
+
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(syncResult);
+        assertNotNull(response.get());
+        assertNotNull(response.get().resourceModel());
+        assertEquals(remoteResource.getId(), response.get().uid());
+    }
+
+    public void testPost_P04() {
+        CountDownLatch lockObject = new CountDownLatch(1);
+        boolean syncResult = false;
+        ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
+        PostResponseCallbackListener listener = new PostResponseCallbackListener(
+                lockObject, response);
+
+        try {
+            SimulatorResourceModel resModel = singleResource.getResourceModel();
+            Map<String, String> queryParams = new HashMap<>();
+            remoteResource.post(remoteResource.getResourceInterfaces().get(0),
+                    queryParams, resModel, listener);
+
+            try {
+                lockObject.await(10, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+            }
+
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(syncResult);
+        assertNotNull(response.get());
+        assertNotNull(response.get().resourceModel());
+        assertEquals(remoteResource.getId(), response.get().uid());
+    }
+
+    public void testPost_P05() {
+        CountDownLatch lockObject = new CountDownLatch(1);
+        boolean syncResult = false;
+        ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
+        PostResponseCallbackListener listener = new PostResponseCallbackListener(
+                lockObject, response);
+
+        try {
+            Map<String, String> queryParams = new HashMap<>();
+            remoteResource.post(queryParams, null, listener);
+
+            try {
+                lockObject.await(10, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+            }
+
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(syncResult);
+        assertNotNull(response.get());
+        assertNotNull(response.get().resourceModel());
+        assertEquals(remoteResource.getId(), response.get().uid());
+    }
+
+    public void testPost_N01() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            SimulatorResourceModel resModel = singleResource.getResourceModel();
+            remoteResource.post(null, resModel, null);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
+    }
+
+    public void testPost_N02() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            SimulatorResourceModel resModel = singleResource.getResourceModel();
+            remoteResource.post(remoteResource.getResourceInterfaces().get(0),
+                    null, resModel, null);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
+    }
+
+    public void testPost_N03() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            SimulatorResourceModel resModel = singleResource.getResourceModel();
+            Map<String, String> queryParams = new HashMap<>();
+            remoteResource.post(null, queryParams, resModel,
+                    new SimulatorRemoteResource.PostResponseListener() {
+                        @Override
+                        public void onPostResponse(String uid,
+                                SimulatorResult result,
+                                SimulatorResourceModel resourceModel) {
+                        }
+                    });
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
+    }
+
+    public void testStartObserve_P01() {
+        CountDownLatch lockObject = new CountDownLatch(1);
+        boolean syncResult = false;
+        ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
+        ObserveNotificationCallbackListener listener = new ObserveNotificationCallbackListener(
+                lockObject, response);
+
+        try {
+            Map<String, String> queryParams = new HashMap<>();
+            remoteResource.observe(queryParams, listener);
+            singleResource.addAttribute(new SimulatorResourceAttribute(
+                    "boolean", new AttributeValue(true), null));
+            singleResource.removeAttribute("boolean");
+
+            try {
+                lockObject.await(10, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+            }
+
+            remoteResource.stopObserve();
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(syncResult);
+        assertNotNull(response.get());
+        assertNotNull(response.get().resourceModel());
+        assertEquals(remoteResource.getId(), response.get().uid());
+    }
+
+    public void testStartObserve_P02() {
+        CountDownLatch lockObject = new CountDownLatch(1);
+        boolean syncResult = false;
+        ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
+        ObserveNotificationCallbackListener listener = new ObserveNotificationCallbackListener(
+                lockObject, response);
+
+        try {
+            remoteResource.observe(listener);
+            singleResource.addAttribute(new SimulatorResourceAttribute(
+                    "boolean", new AttributeValue(true), null));
+            singleResource.removeAttribute("boolean");
+
+            try {
+                lockObject.await(10, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+            }
+
+            remoteResource.stopObserve();
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(syncResult);
+        assertNotNull(response.get());
+        assertNotNull(response.get().resourceModel());
+        assertEquals(remoteResource.getId(), response.get().uid());
+    }
+
+    public void testStartObserve_N01() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            Map<String, String> queryParams = new HashMap<>();
+            remoteResource.observe(queryParams, null);
+
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
+    }
+
+    public void testStopObserve_P01() {
+        CountDownLatch lockObject = new CountDownLatch(1);
+        boolean syncResult = false;
+        ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
+        ObserveNotificationCallbackListener listener = new ObserveNotificationCallbackListener(
+                lockObject, response);
+
+        try {
+            Map<String, String> queryParams = new HashMap<>();
+            remoteResource.observe(queryParams, listener);
+
+            try {
+                lockObject.await(10, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+            }
+
+            response.set(null);
+            remoteResource.stopObserve();
+            singleResource.addAttribute(new SimulatorResourceAttribute(
+                    "boolean", new AttributeValue(true), null));
+            singleResource.removeAttribute("boolean");
+
+            try {
+                lockObject.await(10, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+            }
+
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(syncResult);
+        assertNull(response.get());
+    }
+
+    public void testSetConfigInfo_P01() {
+        boolean syncResult = false;
+        try {
+            remoteResource.setConfigInfo(SINGLE_RES_RAML);
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(syncResult);
+    }
+
+    public void testSetConfigInfo_N01() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            remoteResource.setConfigInfo("");
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
+    }
+
+    public void testSetConfigInfo_N02() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            remoteResource.setConfigInfo(null);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
+    }
+
+    public void testStartVerification_P01() {
+        CountDownLatch lockObject = new CountDownLatch(1);
+        boolean syncResult = false;
+        ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
+        VerificationCallbackListener listener = new VerificationCallbackListener(
+                lockObject, response);
+
+        try {
+            remoteResource.setConfigInfo(SINGLE_RES_RAML);
+            remoteResource.startVerification(
+                    SimulatorRemoteResource.RequestType.GET, listener);
+
+            try {
+                lockObject.await(10, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+            }
+
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(syncResult);
+        assertNotNull(response.get());
+        assertEquals(remoteResource.getId(), response.get().uid());
+    }
+
+    public void testStartVerification_P02() {
+        CountDownLatch lockObject = new CountDownLatch(1);
+        boolean syncResult = false;
+        ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
+        VerificationCallbackListener listener = new VerificationCallbackListener(
+                lockObject, response);
+
+        try {
+            remoteResource.setConfigInfo(SINGLE_RES_RAML);
+            remoteResource.startVerification(
+                    SimulatorRemoteResource.RequestType.PUT, listener);
+
+            try {
+                lockObject.await(10, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+            }
+
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(syncResult);
+        assertNotNull(response.get());
+        assertEquals(remoteResource.getId(), response.get().uid());
+    }
+
+    public void testStartVerification_P03() {
+        CountDownLatch lockObject = new CountDownLatch(1);
+        boolean syncResult = false;
+        ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
+        VerificationCallbackListener listener = new VerificationCallbackListener(
+                lockObject, response);
+
+        try {
+            remoteResource.setConfigInfo(SINGLE_RES_RAML);
+            remoteResource.startVerification(
+                    SimulatorRemoteResource.RequestType.POST, listener);
+
+            try {
+                lockObject.await(10, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+            }
+
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(syncResult);
+        assertNotNull(response.get());
+        assertEquals(remoteResource.getId(), response.get().uid());
+    }
+
+    public void testStartVerification_N01() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            remoteResource.setConfigInfo(SINGLE_RES_RAML);
+            remoteResource.startVerification(
+                    SimulatorRemoteResource.RequestType.GET, null);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
+    }
+
+    public void testStopVerification_N01() {
+        CountDownLatch lockObject = new CountDownLatch(1);
+        boolean syncResult = false;
+        ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
+        VerificationCallbackListener listener = new VerificationCallbackListener(
+                lockObject, response);
+
+        try {
+            remoteResource.setConfigInfo(SINGLE_RES_RAML);
+            int id = remoteResource.startVerification(
+                    SimulatorRemoteResource.RequestType.POST, listener);
+            remoteResource.stopVerification(id);
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(syncResult);
+    }
+}
+
+class ResponseDetails {
+    private String                 mUid      = null;
+    private SimulatorResourceModel mResModel = null;
+    private SimulatorResult        mResult   = SimulatorResult.SIMULATOR_ERROR;
+
+    ResponseDetails(String uid, SimulatorResult result,
+            SimulatorResourceModel resModel) {
+        mUid = uid;
+        mResModel = resModel;
+        mResult = result;
+    }
+
+    String uid() {
+        return mUid;
+    }
+
+    SimulatorResourceModel resourceModel() {
+        return mResModel;
+    }
+
+    SimulatorResult errorCode() {
+        return mResult;
+    }
+}
+
+class GetResponseCallbackListener
+        implements SimulatorRemoteResource.GetResponseListener {
+    private CountDownLatch                mLockObject;
+    private ObjectHolder<ResponseDetails> mResponse;
+
+    public GetResponseCallbackListener(CountDownLatch lockObject,
+            ObjectHolder<ResponseDetails> response) {
+        mLockObject = lockObject;
+        mResponse = response;
+    }
+
+    @Override
+    public void onGetResponse(String uid, SimulatorResult result,
+            SimulatorResourceModel resourceModel) {
+        mResponse.set(new ResponseDetails(uid, result, resourceModel));
+        mLockObject.countDown();
+    }
+}
+
+class PutResponseCallbackListener
+        implements SimulatorRemoteResource.PutResponseListener {
+    private CountDownLatch                mLockObject;
+    private ObjectHolder<ResponseDetails> mResponse;
+
+    public PutResponseCallbackListener(CountDownLatch lockObject,
+            ObjectHolder<ResponseDetails> response) {
+        mLockObject = lockObject;
+        mResponse = response;
+    }
+
+    @Override
+    public void onPutResponse(String uid, SimulatorResult result,
+            SimulatorResourceModel resourceModel) {
+        mResponse.set(new ResponseDetails(uid, result, resourceModel));
+        mLockObject.countDown();
+    }
+}
+
+class PostResponseCallbackListener
+        implements SimulatorRemoteResource.PostResponseListener {
+    private CountDownLatch                mLockObject;
+    private ObjectHolder<ResponseDetails> mResponse;
+
+    public PostResponseCallbackListener(CountDownLatch lockObject,
+            ObjectHolder<ResponseDetails> response) {
+        mLockObject = lockObject;
+        mResponse = response;
+    }
+
+    @Override
+    public void onPostResponse(String uid, SimulatorResult result,
+            SimulatorResourceModel resourceModel) {
+        mResponse.set(new ResponseDetails(uid, result, resourceModel));
+        mLockObject.countDown();
+    }
+}
+
+class ObserveNotificationCallbackListener
+        implements SimulatorRemoteResource.ObserveNotificationListener {
+    private CountDownLatch                mLockObject;
+    private ObjectHolder<ResponseDetails> mResponse;
+
+    public ObserveNotificationCallbackListener(CountDownLatch lockObject,
+            ObjectHolder<ResponseDetails> response) {
+        mLockObject = lockObject;
+        mResponse = response;
+    }
+
+    @Override
+    public void onObserveNotification(String uid,
+            SimulatorResourceModel resourceModel, int sequenceNumber) {
+        mResponse.set(new ResponseDetails(uid, SimulatorResult.SIMULATOR_OK,
+                resourceModel));
+        mLockObject.countDown();
+    }
+}
+
+class VerificationCallbackListener
+        implements SimulatorRemoteResource.VerificationListener {
+    private CountDownLatch                mLockObject;
+    private ObjectHolder<ResponseDetails> mResponse;
+
+    public VerificationCallbackListener(CountDownLatch lockObject,
+            ObjectHolder<ResponseDetails> response) {
+        mLockObject = lockObject;
+        mResponse = response;
+    }
+
+    @Override
+    public void onVerificationStarted(String uid, int id) {
+        mResponse.set(
+                new ResponseDetails(uid, SimulatorResult.SIMULATOR_OK, null));
+        mLockObject.countDown();
+    }
+
+    @Override
+    public void onVerificationAborted(String uid, int id) {
+        mResponse.set(
+                new ResponseDetails(uid, SimulatorResult.SIMULATOR_OK, null));
+        mLockObject.countDown();
+    }
+
+    @Override
+    public void onVerificationCompleted(String uid, int id) {
+        mResponse.set(
+                new ResponseDetails(uid, SimulatorResult.SIMULATOR_OK, null));
+        mLockObject.countDown();
+    }
+}
+
+class FindResourceCallbackListener implements FindResourceListener {
+    private CountDownLatch                        mLockObject;
+    private ObjectHolder<SimulatorRemoteResource> mResourceHolder;
+
+    public FindResourceCallbackListener(CountDownLatch lockObject,
+            ObjectHolder<SimulatorRemoteResource> resourceHolder) {
+        mLockObject = lockObject;
+        mResourceHolder = resourceHolder;
+    }
+
+    @Override
+    public void onResourceFound(SimulatorRemoteResource resource) {
+        mResourceHolder.set(resource);
+        mLockObject.countDown();
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/GetListener.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/GetListener.java
deleted file mode 100644 (file)
index ed9fd7e..0000000
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.clientcontroller.test;
-
-import java.util.concurrent.CountDownLatch;
-
-import org.oic.simulator.SimulatorResourceModel;
-import org.oic.simulator.clientcontroller.IGetListener;
-
-/**
- * This class implements methods for receiving notification when
- * response is received for GET request.
- */
-public class GetListener implements IGetListener
-{
-
-    private CountDownLatch lockObject;
-    private ListenerObject getListenerObject;
-
-    public GetListener(CountDownLatch lockObject, ListenerObject getListenerObject)
-    {
-        this.lockObject = lockObject;
-        this.getListenerObject = getListenerObject;
-    }
-
-    @Override
-    public void onGetCompleted(String uId, SimulatorResourceModel representation)
-    {
-        if (null != getListenerObject) {
-            getListenerObject.setuId(uId);
-            getListenerObject.setRepresentation(representation);
-        }
-
-        lockObject.countDown();
-    }
-
-    @Override
-    public void onGetFailed(Throwable ex)
-    {
-        if (null != getListenerObject)
-            getListenerObject.setEx(ex);
-
-        lockObject.countDown();
-    }
-}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/ListenerObject.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/ListenerObject.java
deleted file mode 100644 (file)
index 860cf6a..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.clientcontroller.test;
-
-import org.oic.simulator.SimulatorResourceModel;
-
-/**
- * This class implements methods for setting/getting UID and
- * resource representation.
- */
-public class ListenerObject
-{
-
-    private String uId;
-    private SimulatorResourceModel representation;
-    private Throwable ex;
-
-    public void setuId(String uId)
-    {
-        this.uId = uId;
-    }
-
-    public String getuId()
-    {
-        return uId;
-    }
-
-    public void setRepresentation(SimulatorResourceModel representation)
-    {
-        this.representation = representation;
-    }
-
-    public SimulatorResourceModel getRepresentation()
-    {
-        return representation;
-    }
-
-    public void setEx(Throwable ex)
-    {
-        this.ex = ex;
-    }
-
-    public Throwable getEx()
-    {
-        return ex;
-    }
-}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/ObserveListener.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/ObserveListener.java
deleted file mode 100644 (file)
index ecc6c10..0000000
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.clientcontroller.test;
-
-import java.util.concurrent.CountDownLatch;
-
-import org.oic.simulator.SimulatorResourceModel;
-import org.oic.simulator.clientcontroller.IObserveListener;
-
-/**
- * This class implements methods for receiving notification when
- * response is received for Observe request.
- */
-public class ObserveListener implements IObserveListener
-{
-
-    private CountDownLatch lockObject;
-    private ObserveListenerObject observeListenerObject;
-
-    public ObserveListener(CountDownLatch lockObject, ObserveListenerObject observeListenerObject)
-    {
-        this.lockObject = lockObject;
-        this.observeListenerObject = observeListenerObject;
-    }
-
-    @Override
-    public void onObserveCompleted(String uId, SimulatorResourceModel representation, int sequenceNumber)
-    {
-        observeListenerObject.setuId(uId);
-        observeListenerObject.setRepresentation(representation);
-        observeListenerObject.setSequenceNumber(sequenceNumber);
-
-        lockObject.countDown();
-    }
-
-    @Override
-    public void onObserveFailed(Throwable ex)
-    {
-        observeListenerObject.setEx(ex);
-        lockObject.countDown();
-    }
-}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/ObserveListenerObject.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/ObserveListenerObject.java
deleted file mode 100644 (file)
index 6bcca0c..0000000
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.clientcontroller.test;
-
-import org.oic.simulator.SimulatorResourceModel;
-
-/**
- * This class implements methods for setting/getting UID,
- * resource representation and sequence number for observe.
- */
-public class ObserveListenerObject
-{
-    private String uId;
-    private SimulatorResourceModel representation;
-    private int sequenceNumber;
-    private Throwable ex;
-
-    public void setuId(String uId)
-    {
-        this.uId = uId;
-    }
-
-    public String getuId()
-    {
-        return uId;
-    }
-
-    public void setRepresentation(SimulatorResourceModel representation)
-    {
-        this.representation = representation;
-    }
-
-    public SimulatorResourceModel getRepresentation()
-    {
-        return representation;
-    }
-
-    public void setSequenceNumber(int sequenceNumber)
-    {
-        this.sequenceNumber = sequenceNumber;
-    }
-
-    public int getSequenceNumber()
-    {
-        return sequenceNumber;
-    }
-
-    public void setEx(Throwable ex)
-    {
-        this.ex = ex;
-    }
-
-    public Throwable getEx()
-    {
-        return ex;
-    }
-}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/PostListener.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/PostListener.java
deleted file mode 100644 (file)
index 3942b51..0000000
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.clientcontroller.test;
-
-import java.util.concurrent.CountDownLatch;
-
-import org.oic.simulator.SimulatorResourceModel;
-import org.oic.simulator.clientcontroller.IPostListener;
-
-/**
- * This class implements methods for receiving notification when
- * response is received for POST request.
- */
-public class PostListener implements IPostListener
-{
-
-    private CountDownLatch lockObject;
-    private ListenerObject postListenerObject;
-
-    public PostListener(CountDownLatch lockObject, ListenerObject postListenerObject)
-    {
-        this.lockObject = lockObject;
-        this.postListenerObject = postListenerObject;
-    }
-
-    @Override
-    public void onPostCompleted(String uId, SimulatorResourceModel representation)
-    {
-        if (null != postListenerObject) {
-            postListenerObject.setuId(uId);
-            postListenerObject.setRepresentation(representation);
-        }
-
-        lockObject.countDown();
-    }
-
-    @Override
-    public void onPostFailed(Throwable ex)
-    {
-        if (null != postListenerObject)
-            postListenerObject.setEx(ex);
-
-        lockObject.countDown();
-    }
-}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/PutListener.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/PutListener.java
deleted file mode 100644 (file)
index 1dafed3..0000000
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.clientcontroller.test;
-
-import java.util.concurrent.CountDownLatch;
-
-import org.oic.simulator.SimulatorResourceModel;
-import org.oic.simulator.clientcontroller.IPutListener;
-
-/**
- * This class implements methods for receiving notification when
- * response is received for PUT request.
- */
-public class PutListener implements IPutListener
-{
-    private CountDownLatch lockObject;
-    private ListenerObject putListenerObject;
-
-    public PutListener(CountDownLatch lockObject, ListenerObject putListenerObject)
-    {
-        this.lockObject = lockObject;
-        this.putListenerObject = putListenerObject;
-    }
-
-    @Override
-    public void onPutCompleted(String uId, SimulatorResourceModel representation)
-    {
-        if (null != putListenerObject) {
-            putListenerObject.setuId(uId);
-            putListenerObject.setRepresentation(representation);
-        }
-
-        lockObject.countDown();
-    }
-
-    @Override
-    public void onPutFailed(Throwable ex)
-    {
-        if (null != putListenerObject)
-            putListenerObject.setEx(ex);
-
-        lockObject.countDown();
-    }
-}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/SimulatorRemoteResourceTest.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/SimulatorRemoteResourceTest.java
deleted file mode 100644 (file)
index 6cc820a..0000000
+++ /dev/null
@@ -1,915 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.clientcontroller.test;
-
-import java.util.HashMap;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import junit.framework.TestCase;
-
-import org.oic.simulator.SimulatorException;
-import org.oic.simulator.SimulatorManager;
-import org.oic.simulator.SimulatorResourceModel;
-import org.oic.simulator.clientcontroller.SimulatorObserveType;
-import org.oic.simulator.clientcontroller.SimulatorRemoteResource;
-import org.oic.simulator.clientcontroller.SimulatorVerificationType;
-import org.oic.simulator.serviceprovider.SimulatorResourceServer;
-import org.oic.simulator.test.FindResourceListener;
-import org.oic.simulator.test.ResourceModelChangeListener;
-import org.oic.simulator.test.ResourceModelObject;
-import org.oic.simulator.test.SimulatorRemoteResourceObject;
-
-/**
- * This class tests the functionality of Simulator Remote Resource
- * class APIs.
- */
-public class SimulatorRemoteResourceTest extends TestCase
-{
-    private static final String CONFIG_PATH = "./ramls/simple-light.raml";
-    //  private static final String RESOURCE_TYPE = "oic.light";
-
-    private CountDownLatch lockObject;
-    private ResourceModelObject resourceModelObject;
-    private ResourceModelChangeListener resourceModelChangeListener;
-
-    private SimulatorRemoteResourceObject simulatorRemoteResourceObject;
-    private SimulatorRemoteResource simulatorRemoteResource;
-
-    private SimulatorResourceServer simulatorResourceServer;
-
-    private FindResourceListener findResourceListener;
-
-    static
-    {
-        System.loadLibrary("SimulatorManager");
-        System.loadLibrary("RamlParser");
-        System.loadLibrary("oc");
-        System.loadLibrary("oc_logger");
-        System.loadLibrary("octbstack");
-    }
-
-    protected void setUp() throws Exception
-    {
-        super.setUp();
-
-        lockObject = new CountDownLatch(1);
-        resourceModelObject = new ResourceModelObject();
-        resourceModelChangeListener = new ResourceModelChangeListener(resourceModelObject);
-
-        simulatorResourceServer = SimulatorManager.createResource(CONFIG_PATH, resourceModelChangeListener);
-
-        simulatorRemoteResourceObject = new SimulatorRemoteResourceObject();
-
-        findResourceListener = new FindResourceListener(lockObject, simulatorRemoteResourceObject);
-
-        SimulatorManager.findResource(findResourceListener);
-
-        try
-        {
-            lockObject.await(10, TimeUnit.SECONDS);
-        }
-        catch (InterruptedException e)
-        {
-        }
-
-        simulatorRemoteResource = simulatorRemoteResourceObject.getSimulatorRemoteResource();
-    }
-
-    protected void tearDown() throws Exception
-    {
-        super.tearDown();
-
-        SimulatorManager.deleteResource(simulatorResourceServer);
-
-        lockObject = null;
-        resourceModelObject = null;
-        resourceModelChangeListener = null;
-
-        simulatorRemoteResourceObject = null;
-        findResourceListener = null;
-
-        simulatorRemoteResource = null;
-    }
-
-    public void testGetUri_P01()
-    {
-        assertNotNull(simulatorRemoteResource.getUri());
-    }
-
-    public void testGetIsObservable_P01()
-    {
-        assertTrue(simulatorRemoteResource.getIsObservable());
-    }
-
-    public void testGetConnectivityType_P01()
-    {
-        assertNotNull(simulatorRemoteResource.getConnectivityType());
-    }
-
-    public void testGetResourceTypes_P01()
-    {
-        assertTrue(simulatorRemoteResource.getResourceTypes() != null && simulatorRemoteResource.getResourceTypes().size() > 0);
-    }
-
-    public void testGetResourceInterfaces_P01()
-    {
-        assertTrue(simulatorRemoteResource.getResourceInterfaces() != null && simulatorRemoteResource.getResourceInterfaces().size() > 0);
-    }
-
-    public void testGetId_P01()
-    {
-        assertNotNull(simulatorRemoteResource.getId());
-    }
-
-    public void testStartObserve_P01()
-    {
-        boolean result = true;
-        HashMap<String, String> queryParamMap = new HashMap<String, String>();
-
-        lockObject = new CountDownLatch(1);
-
-        ObserveListenerObject observeListenerObject = new ObserveListenerObject();
-        ObserveListener observeListener = new ObserveListener(lockObject, observeListenerObject);
-
-        try
-        {
-            simulatorRemoteResource.startObserve(SimulatorObserveType.OBSERVE, queryParamMap, observeListener);
-            simulatorResourceServer.addAttributeString("test", "test");
-        }
-        catch (Exception e1)
-        {
-            result = false;
-        }
-
-        try
-        {
-            lockObject.await(10, TimeUnit.SECONDS);
-        }
-        catch (InterruptedException e)
-        {
-        }
-
-        assertTrue(observeListenerObject.getRepresentation() != null && result);
-
-        try
-        {
-            simulatorRemoteResource.stopObserve();
-        }
-        catch (Exception e)
-        {
-            e.printStackTrace();
-        }
-
-        observeListenerObject = null;
-        observeListener = null;
-    }
-
-    public void testStopObserve_P01()
-    {
-        boolean result = true;
-
-        HashMap<String, String> queryParamMap = new HashMap<String, String>();
-        lockObject = new CountDownLatch(1);
-        ObserveListenerObject observeListenerObject = new ObserveListenerObject();
-        ObserveListener observeListener = new ObserveListener(lockObject, observeListenerObject);
-
-        try
-        {
-            simulatorRemoteResource.startObserve(SimulatorObserveType.OBSERVE, queryParamMap, observeListener);
-            simulatorResourceServer.addAttributeString("test", "test");
-        }
-        catch (Exception e1)
-        {
-            e1.printStackTrace();
-            result = false;
-        }
-
-        try
-        {
-            lockObject.await(10, TimeUnit.SECONDS);
-        }
-        catch (InterruptedException e)
-        {
-        }
-
-        result = result && observeListenerObject.getRepresentation() != null;
-
-        try
-        {
-            simulatorRemoteResource.stopObserve();
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        assertTrue(result);
-
-        observeListenerObject = null;
-        observeListener = null;
-    }
-
-    public void testGetQueryParamGetListener_P01()
-    {
-        boolean result = true;
-        lockObject = new CountDownLatch(1);
-        HashMap<String, String> queryParamMap = new HashMap<String, String>();
-
-        ListenerObject getListenerObject = new ListenerObject();
-        GetListener getListener = new GetListener(lockObject, getListenerObject);
-
-        try
-        {
-            simulatorRemoteResource.get(queryParamMap, getListener);
-        }
-        catch (Exception e1)
-        {
-            e1.printStackTrace();
-            result = false;
-        }
-
-        try
-        {
-            lockObject.await(10, TimeUnit.SECONDS);
-        }
-        catch (InterruptedException e)
-        {
-        }
-
-        if(getListenerObject.getEx() == null)
-        {
-            try
-            {
-                result = result && getListenerObject.getRepresentation() != null && getListenerObject.getRepresentation().size() > 0;
-            }
-            catch (SimulatorException e)
-            {
-                result = false;
-                e.printStackTrace();
-            }
-        }
-        else
-            result = false;
-
-        assertTrue(result);
-    }
-
-    public void testGetStringMapOfStringStringIGetListener_P01()
-    {
-        boolean result = true;
-        lockObject = new CountDownLatch(1);
-        HashMap<String, String> queryParamMap = new HashMap<String, String>();
-
-        String resourceInterface = "oic.if.baseline";
-
-        ListenerObject getListenerObject = new ListenerObject();
-        GetListener getListener = new GetListener(lockObject, getListenerObject);
-
-        try
-        {
-            simulatorRemoteResource.get(resourceInterface, queryParamMap, getListener);
-        }
-        catch (Exception e1)
-        {
-            e1.printStackTrace();
-            result = false;
-        }
-
-        try
-        {
-            lockObject.await(10, TimeUnit.SECONDS);
-        }
-        catch (InterruptedException e)
-        {
-        }
-
-        if(getListenerObject.getEx() == null)
-        {
-            try
-            {
-                result = result && getListenerObject.getRepresentation() != null && getListenerObject.getRepresentation().size() > 0;
-            }
-            catch (SimulatorException e)
-            {
-                result = false;
-                e.printStackTrace();
-            }
-        }
-        else
-            result = false;
-
-        assertTrue(result);
-    }
-
-    public void testPut_P01()
-    {
-        boolean result = true;
-        SimulatorResourceModel model = new SimulatorResourceModel();
-
-        lockObject = new CountDownLatch(1);
-
-        ListenerObject listenerObject = null;
-
-        try
-        {
-            listenerObject = new ListenerObject();
-            PutListener putListener = new PutListener(lockObject, listenerObject);
-
-            model.addAttributeInt("intensity", 5);
-            model.addAttributeString("power", "off");
-
-            simulatorRemoteResource.put(model, null, putListener);
-        }
-        catch(Exception e)
-        {
-            result = false;
-        }
-
-        try
-        {
-            lockObject.await(10, TimeUnit.SECONDS);
-        }
-        catch (InterruptedException e)
-        {
-        }
-
-        assertTrue(result && listenerObject != null && listenerObject.getRepresentation() != null && listenerObject.getuId() != null);
-    }
-
-    /**
-     * model as null
-     */
-
-    public void testPut_N01() {
-        boolean result = true;
-        ListenerObject listenerObject = new ListenerObject();
-        PutListener putListener = new PutListener(lockObject, listenerObject);
-
-        try {
-            simulatorRemoteResource.put(null, null, putListener);
-            result = false;
-        } catch (Exception e1) {
-            result = true;
-        }
-
-        try {
-            lockObject.await(10, TimeUnit.SECONDS);
-        } catch (InterruptedException e) {
-        }
-
-        assertTrue(result && listenerObject.getRepresentation() == null && listenerObject.getuId() == null);
-    }
-
-    public void testPost_P01()
-    {
-        boolean result = true;
-        ListenerObject listenerObject = null;
-        lockObject = new CountDownLatch(1);
-
-        SimulatorResourceModel model = new SimulatorResourceModel();
-        try
-        {
-            model.addAttributeInt("intensity", 8);
-
-            listenerObject = new ListenerObject();
-            PostListener postListener = new PostListener(lockObject, listenerObject);
-
-            simulatorRemoteResource.post(model, null, postListener);
-        }
-        catch(Exception e)
-        {
-            result = false;
-        }
-
-        try
-        {
-            lockObject.await(10, TimeUnit.SECONDS);
-        }
-        catch (InterruptedException e)
-        {
-        }
-
-        assertTrue(result && listenerObject != null && listenerObject.getRepresentation() != null && listenerObject.getuId() != null);
-    }
-
-    /**
-     * Model is set to null
-     */
-
-    public void testPost_N01() {
-        boolean result = true;
-
-        lockObject = new CountDownLatch(1);
-
-        ListenerObject listenerObject = new ListenerObject();
-        PostListener postListener = new PostListener(lockObject, listenerObject);
-
-        try {
-            simulatorRemoteResource.post(null, null, postListener);
-            result = false;
-        } catch (Exception e1) {
-            result = true;
-        }
-
-        try {
-            lockObject.await(10, TimeUnit.SECONDS);
-        } catch (InterruptedException e) {
-        }
-
-        assertTrue(result && listenerObject.getRepresentation() == null && listenerObject.getuId() == null);
-    }
-
-    public void testGet_P01()
-    {
-        boolean result = true;
-        ListenerObject listenerObject = null;
-        lockObject = new CountDownLatch(1);
-
-        try
-        {
-            listenerObject = new ListenerObject();
-            GetListener onGetListener = new GetListener(lockObject, listenerObject);
-
-            String resInterface = simulatorRemoteResource.getResourceInterfaces().get(0);
-
-            if(resInterface != null)
-                simulatorRemoteResource.get(resInterface,null, onGetListener);
-            else
-                result = false;
-        }
-        catch(Exception e)
-        {
-            result = false;
-        }
-
-        try
-        {
-            lockObject.await(10, TimeUnit.SECONDS);
-        }
-        catch (InterruptedException e)
-        {
-        }
-
-        assertTrue(result && listenerObject != null && listenerObject.getRepresentation() != null && listenerObject.getuId() != null);
-    }
-
-    /**
-     * null resInterface
-     */
-    public void testGet_N01()
-    {
-        boolean result = false;
-        ListenerObject listenerObject = null;
-        lockObject = new CountDownLatch(1);
-
-        try
-        {
-            listenerObject = new ListenerObject();
-            GetListener onGetListener = new GetListener(lockObject, listenerObject);
-
-            simulatorRemoteResource.get(null, null, onGetListener);
-            result = false;
-        }
-        catch(Exception e)
-        {
-            result = true;
-        }
-
-        try
-        {
-            lockObject.await(10, TimeUnit.SECONDS);
-        }
-        catch (InterruptedException e)
-        {
-        }
-
-        assertTrue(result);
-    }
-
-    /**
-     * null listener
-     */
-    public void testGet_N02()
-    {
-        boolean result = false;
-        try
-        {
-            String resInterface = simulatorRemoteResource.getResourceInterfaces().get(0);
-
-            if(resInterface != null)
-            {
-                simulatorRemoteResource.get( resInterface,null, null);
-            }
-
-            result = false;
-        }
-        catch(Exception e)
-        {
-            result = true;
-        }
-
-        assertTrue(result);
-    }
-
-    /**
-     * all params as null
-     */
-    public void testGet_N03()
-    {
-        boolean result = false;
-        try
-        {
-            simulatorRemoteResource.get(null, null, null);
-            result = false;
-        }
-        catch(Exception e)
-        {
-            result = true;
-        }
-
-        assertTrue(result);
-    }
-
-    public void testGetWithoutResInterface_P01()
-    {
-        boolean result = true;
-        ListenerObject listenerObject = null;
-        lockObject = new CountDownLatch(1);
-
-        try
-        {
-            listenerObject = new ListenerObject();
-            GetListener onGetListener = new GetListener(lockObject, listenerObject);
-
-            simulatorRemoteResource.get(null, onGetListener);
-        }
-        catch(Exception e)
-        {
-            result = false;
-        }
-
-        try
-        {
-            lockObject.await(10, TimeUnit.SECONDS);
-        }
-        catch (InterruptedException e)
-        {
-        }
-
-        assertTrue(result && listenerObject != null && listenerObject.getRepresentation() != null && listenerObject.getuId() != null);
-    }
-
-    /**
-     * null listener
-     */
-    public void testGetWithoutResInterface_N01()
-    {
-        boolean result = false;
-        try
-        {
-            simulatorRemoteResource.get(null, null);
-            result = false;
-        }
-        catch(Exception e)
-        {
-            result = true;
-        }
-
-        assertTrue(result);
-    }
-
-    public void testSetConfigInfo_P01()
-    {
-        boolean result = true;
-        try
-        {
-            simulatorRemoteResource.setConfigInfo(CONFIG_PATH);
-        }
-        catch (Exception e2)
-        {
-            e2.printStackTrace();
-            result = false;
-        }
-
-        lockObject = new CountDownLatch(1);
-        VerifyListenerObject verifyListenerObject = new VerifyListenerObject();
-        VerifyListener verifyListener = new VerifyListener(lockObject, verifyListenerObject);
-
-        try
-        {
-            simulatorRemoteResource.startVerification(SimulatorVerificationType.RQ_TYPE_POST, verifyListener);
-        }
-        catch (Exception e1)
-        {
-            e1.printStackTrace();
-            result = false;
-        }
-
-        try
-        {
-            lockObject.await(10, TimeUnit.MILLISECONDS);
-        }
-        catch (InterruptedException e)
-        {
-        }
-
-        assertTrue(result && verifyListenerObject.getWhichOne().equals("started")&&
-                   verifyListenerObject.getuId() != null &&
-                   verifyListenerObject.getId() != -1);
-    }
-
-    /**
-     * Passing empty
-     */
-    public void testSetConfigInfo_N01()
-    {
-        boolean result = true;
-        try
-        {
-            simulatorRemoteResource.setConfigInfo("");
-            result = false;
-        }
-        catch (Exception e2)
-        {
-            result = true;
-        }
-
-        assertTrue(result);
-    }
-
-    public void testStartVerification_P01()
-    {
-        boolean result = true;
-        lockObject = new CountDownLatch(1);
-        try
-        {
-            simulatorRemoteResource.setConfigInfo(CONFIG_PATH);
-        }
-        catch (Exception e1)
-        {
-            e1.printStackTrace();
-            result = false;
-        }
-
-        VerifyListenerObject verifyListenerObject = new VerifyListenerObject();
-        VerifyListener verifyListener = new VerifyListener(lockObject, verifyListenerObject);
-        try
-        {
-            result =  result && simulatorRemoteResource.startVerification(SimulatorVerificationType.RQ_TYPE_POST, verifyListener) != -1;
-        }
-        catch (Exception e1)
-        {
-            e1.printStackTrace();
-            result = false;
-        }
-
-        try
-        {
-            lockObject.await(10, TimeUnit.MILLISECONDS);
-        }
-        catch (InterruptedException e)
-        {
-        }
-
-        assertTrue(result && verifyListenerObject.getWhichOne().equals("started") &&
-                   verifyListenerObject.getuId() != null &&
-                   verifyListenerObject.getId() != -1);
-    }
-
-    public void testStartVerification_P02()
-    {
-        boolean result = true;
-        lockObject = new CountDownLatch(1);
-        try
-        {
-            simulatorRemoteResource.setConfigInfo(CONFIG_PATH);
-        }
-        catch (Exception e1)
-        {
-            e1.printStackTrace();
-            result = false;
-        }
-
-        VerifyListenerObject verifyListenerObject = new VerifyListenerObject();
-        VerifyListener verifyListener = new VerifyListener(lockObject, verifyListenerObject);
-        try
-        {
-            result =  result && simulatorRemoteResource.startVerification(SimulatorVerificationType.RQ_TYPE_PUT, verifyListener) != -1;
-        }
-        catch (Exception e1)
-        {
-            e1.printStackTrace();
-            result = false;
-        }
-
-        try
-        {
-            lockObject.await(10, TimeUnit.MILLISECONDS);
-        }
-        catch (InterruptedException e)
-        {
-        }
-
-        assertTrue(result && verifyListenerObject.getWhichOne().equals("started") &&
-                   verifyListenerObject.getuId() != null &&
-                   verifyListenerObject.getId() != -1);
-    }
-
-    public void testStartVerification_P03()
-    {
-        boolean result = true;
-        lockObject = new CountDownLatch(1);
-        try
-        {
-            simulatorRemoteResource.setConfigInfo(CONFIG_PATH);
-        }
-        catch (Exception e1)
-        {
-            e1.printStackTrace();
-            result = false;
-        }
-
-        VerifyListenerObject verifyListenerObject = new VerifyListenerObject();
-        VerifyListener verifyListener = new VerifyListener(lockObject, verifyListenerObject);
-        try
-        {
-            result =  result && simulatorRemoteResource.startVerification(SimulatorVerificationType.RQ_TYPE_GET, verifyListener) != -1;
-        }
-        catch (Exception e1)
-        {
-            e1.printStackTrace();
-            result = false;
-        }
-
-        try
-        {
-            lockObject.await(10, TimeUnit.MILLISECONDS);
-        }
-        catch (InterruptedException e)
-        {
-        }
-
-        assertTrue(result && verifyListenerObject.getWhichOne().equals("started") &&
-                   verifyListenerObject.getuId() != null &&
-                   verifyListenerObject.getId() != -1);
-    }
-
-    /**
-     * setting listener to null
-     */
-    public void testStartVerification_N01()
-    {
-        boolean result = true;
-        try
-        {
-            simulatorRemoteResource.setConfigInfo(CONFIG_PATH);
-        }
-        catch (Exception e)
-        {
-            e.printStackTrace();
-            result = false;
-        }
-
-        try
-        {
-            result = result && (simulatorRemoteResource.startVerification(SimulatorVerificationType.RQ_TYPE_POST, null) == -1);
-            result = false;
-        }
-        catch (Exception e)
-        {
-            result = true;
-        }
-        assertTrue(result);
-    }
-
-    public void testStopVerification_P01()
-    {
-        boolean result = true;
-        lockObject = new CountDownLatch(2);
-        try
-        {
-            simulatorRemoteResource.setConfigInfo(CONFIG_PATH);
-        }
-        catch (Exception e1)
-        {
-            e1.printStackTrace();
-            result = false;
-        }
-
-        VerifyListenerObject verifyListenerObject = new VerifyListenerObject();
-        VerifyListener verifyListener = new VerifyListener(lockObject, verifyListenerObject);
-        try
-        {
-            result =  result && simulatorRemoteResource.startVerification(SimulatorVerificationType.RQ_TYPE_POST, verifyListener) != -1;
-        }
-        catch (Exception e1)
-        {
-            e1.printStackTrace();
-            result = false;
-        }
-
-        try
-        {
-            lockObject.await(10, TimeUnit.MILLISECONDS);
-        }
-        catch (InterruptedException e)
-        {
-        }
-
-        result = result && verifyListenerObject.getWhichOne().equals("started") &&
-                 verifyListenerObject.getuId() != null &&
-                 verifyListenerObject.getId() != -1;
-
-        try
-        {
-            simulatorRemoteResource.stopVerification(verifyListenerObject.getId());
-        }
-        catch (Exception e1)
-        {
-            e1.printStackTrace();
-            result = false;
-        }
-
-        try
-        {
-            lockObject.await(100, TimeUnit.MILLISECONDS);
-        }
-        catch (InterruptedException e)
-        {
-        }
-
-        assertTrue(result && verifyListenerObject.getWhichOne().equals("aborted") &&
-                   verifyListenerObject.getuId() != null &&
-                   verifyListenerObject.getId() != -1);
-    }
-
-    /**
-     * Random id. This is just to check the crash
-     */
-    public void testStopVerification_N01()
-    {
-        boolean result = true;
-        lockObject = new CountDownLatch(1);
-        try
-        {
-            simulatorRemoteResource.setConfigInfo(CONFIG_PATH);
-        }
-        catch (Exception e2)
-        {
-            result = false;
-            e2.printStackTrace();
-        }
-
-        VerifyListenerObject verifyListenerObject = new VerifyListenerObject();
-        VerifyListener verifyListener = new VerifyListener(lockObject, verifyListenerObject);
-        try
-        {
-            result =  result && simulatorRemoteResource.startVerification(SimulatorVerificationType.RQ_TYPE_POST, verifyListener) != -1;
-        }
-        catch (Exception e1)
-        {
-            e1.printStackTrace();
-            result = false;
-        }
-
-        try
-        {
-            lockObject.await(10, TimeUnit.SECONDS);
-        }
-        catch (InterruptedException e)
-        {
-        }
-
-        result = result && verifyListenerObject.getWhichOne().equals("started") &&
-                 verifyListenerObject.getuId() != null &&
-                 verifyListenerObject.getId() != -1;
-
-        try
-        {
-            simulatorRemoteResource.stopVerification(123435);
-            result = false;
-        }
-        catch (Exception e)
-        {
-            result = true;
-        }
-
-        assertTrue(result);
-    }
-}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/VerifyListener.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/VerifyListener.java
deleted file mode 100644 (file)
index 2e16ef5..0000000
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.clientcontroller.test;
-
-import java.util.concurrent.CountDownLatch;
-
-import org.oic.simulator.clientcontroller.IVerificationListener;
-
-/**
- * This class implements listeners for getting verification
- * status callbacks.
- */
-public class VerifyListener implements IVerificationListener
-{
-
-    private CountDownLatch lockObject;
-    private VerifyListenerObject verifyListenerObject;
-
-    public VerifyListener(CountDownLatch lockObject, VerifyListenerObject verifyListenerObject)
-    {
-        this.lockObject = lockObject;
-        this.verifyListenerObject = verifyListenerObject;
-    }
-
-    @Override
-    public void onVerificationStarted(String uId, int id)
-    {
-        verifyListenerObject.setId(id);
-        verifyListenerObject.setuId(uId);
-        verifyListenerObject.setWhichOne("started");
-
-        lockObject.countDown();
-    }
-
-    @Override
-    public void onVerificationAborted(String uId, int id)
-    {
-        verifyListenerObject.setId(id);
-        verifyListenerObject.setuId(uId);
-        verifyListenerObject.setWhichOne("aborted");
-
-        lockObject.countDown();
-    }
-
-    @Override
-    public void onVerificationCompleted(String uId, int id)
-    {
-        verifyListenerObject.setId(id);
-        verifyListenerObject.setuId(uId);
-        verifyListenerObject.setWhichOne("completed");
-
-        lockObject.countDown();
-    }
-}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/VerifyListenerObject.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/VerifyListenerObject.java
deleted file mode 100644 (file)
index 45a2eaf..0000000
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.clientcontroller.test;
-
-/**
- * This class tests the functionality of getting/setting
- * verification ID.
- */
-public class VerifyListenerObject
-{
-
-    private String uId;
-    private int id;
-    private String whichOne;
-
-    public void setuId(String uId)
-    {
-        this.uId = uId;
-    }
-
-    public String getuId()
-    {
-        return uId;
-    }
-
-    public void setId(int id)
-    {
-        this.id = id;
-    }
-
-    public int getId()
-    {
-        return id;
-    }
-
-    public void setWhichOne(String whichOne)
-    {
-        this.whichOne = whichOne;
-    }
-
-    public String getWhichOne()
-    {
-        return whichOne;
-    }
-}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/server/test/SimulatorCollectionResourceTest.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/server/test/SimulatorCollectionResourceTest.java
new file mode 100644 (file)
index 0000000..d3cf462
--- /dev/null
@@ -0,0 +1,294 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator.server.test;
+
+import java.util.Vector;
+
+import org.oic.simulator.InvalidArgsException;
+import org.oic.simulator.SimulatorException;
+import org.oic.simulator.SimulatorManager;
+import org.oic.simulator.SimulatorResourceModel;
+import org.oic.simulator.server.SimulatorCollectionResource;
+import org.oic.simulator.server.SimulatorResource;
+import org.oic.simulator.test.ExceptionType;
+
+import junit.framework.TestCase;
+
+public class SimulatorCollectionResourceTest extends TestCase {
+
+    private static final String         COLLECTION_RES_RAML = "./ramls/oic.d.airconditioner.raml";
+    private SimulatorCollectionResource collectionResource  = null;
+
+    protected void setUp() throws Exception {
+        super.setUp();
+        collectionResource = (SimulatorCollectionResource) SimulatorManager
+                .createResource(COLLECTION_RES_RAML);
+    }
+
+    protected void tearDown() throws Exception {
+        super.tearDown();
+        collectionResource = null;
+    }
+
+    public void testAddChildResource_P01() {
+        SimulatorResource childResource = null;
+
+        try {
+            String name = "child-resource";
+            String uri = "/child/resource";
+            String resType = "child.resource";
+
+            childResource = SimulatorManager.createResource(
+                    SimulatorResource.Type.SINGLE, name, uri, resType);
+        } catch (InvalidArgsException e1) {
+            e1.printStackTrace();
+        } catch (SimulatorException e1) {
+            e1.printStackTrace();
+        }
+
+        if (null == childResource)
+            return;
+
+        Vector<SimulatorResource> result = null;
+        try {
+            collectionResource.addChildResource(childResource);
+            result = collectionResource.getChildResources();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertNotNull(result);
+        assertEquals(1, result.size());
+    }
+
+    public void testAddChildResource_P02() {
+        SimulatorResource childResource = null;
+
+        try {
+            String name = "child-resource";
+            String uri = "/child/resource";
+            String resType = "child.resource";
+
+            childResource = SimulatorManager.createResource(
+                    SimulatorResource.Type.COLLECTION, name, uri, resType);
+        } catch (InvalidArgsException e1) {
+            e1.printStackTrace();
+        } catch (SimulatorException e1) {
+            e1.printStackTrace();
+        }
+
+        if (null == childResource)
+            return;
+
+        Vector<SimulatorResource> result = null;
+        try {
+            collectionResource.addChildResource(childResource);
+            result = collectionResource.getChildResources();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertNotNull(result);
+        assertEquals(1, result.size());
+    }
+
+    public void testAddChildResource_P03() {
+        SimulatorResource childResource1 = null;
+        SimulatorResource childResource2 = null;
+
+        try {
+            String name = "child-resource";
+            String uri = "/child/resource";
+            String resType = "child.resource";
+
+            childResource1 = SimulatorManager.createResource(
+                    SimulatorResource.Type.SINGLE, name, uri, resType);
+            childResource2 = SimulatorManager.createResource(
+                    SimulatorResource.Type.COLLECTION, name + "-2", uri + "/2",
+                    resType);
+        } catch (InvalidArgsException e1) {
+            e1.printStackTrace();
+        } catch (SimulatorException e1) {
+            e1.printStackTrace();
+        }
+
+        if (null == childResource1 || null == childResource2)
+            return;
+
+        Vector<SimulatorResource> result = null;
+        try {
+            collectionResource.addChildResource(childResource1);
+            collectionResource.addChildResource(childResource2);
+            result = collectionResource.getChildResources();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertNotNull(result);
+        assertEquals(2, result.size());
+    }
+
+    public void testAddChildResource_N01() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            collectionResource.addChildResource(null);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
+    }
+
+    public void testRemoveChildResource_P01() {
+        SimulatorResource childResource = null;
+        Vector<SimulatorResource> result = null;
+
+        try {
+            String name = "child-resource";
+            String uri = "/child/resource";
+            String resType = "child.resource";
+
+            childResource = SimulatorManager.createResource(
+                    SimulatorResource.Type.COLLECTION, name, uri, resType);
+            collectionResource.addChildResource(childResource);
+            result = collectionResource.getChildResources();
+        } catch (InvalidArgsException e1) {
+            e1.printStackTrace();
+        } catch (SimulatorException e1) {
+            e1.printStackTrace();
+        }
+
+        if (null == childResource || null == result)
+            return;
+
+        int count = result.size();
+        try {
+            collectionResource.removeChildResource(childResource);
+            result = collectionResource.getChildResources();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue((count == 1 && result == null)
+                || (count > 1 && result.size() == count - 1));
+    }
+
+    public void testRemoveChildResource_N01() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            collectionResource.removeChildResource(null);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
+    }
+
+    public void testRemoveChildResourceByUri_P01() {
+        SimulatorResource childResource = null;
+        Vector<SimulatorResource> result = null;
+
+        try {
+            String name = "child-resource";
+            String uri = "/child/resource";
+            String resType = "child.resource";
+
+            childResource = SimulatorManager.createResource(
+                    SimulatorResource.Type.COLLECTION, name, uri, resType);
+            collectionResource.addChildResource(childResource);
+            result = collectionResource.getChildResources();
+        } catch (InvalidArgsException e1) {
+            e1.printStackTrace();
+        } catch (SimulatorException e1) {
+            e1.printStackTrace();
+        }
+
+        if (null == childResource || null == result)
+            return;
+
+        int count = result.size();
+        try {
+            collectionResource.removeChildResourceByUri(childResource.getURI());
+            result = collectionResource.getChildResources();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue((count == 1 && result == null)
+                || (count > 1 && result.size() == count - 1));
+    }
+
+    public void testRemoveChildResourceByUri_N01() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            collectionResource.removeChildResourceByUri(null);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
+    }
+
+    public void testRemoveChildResourceByUri_N02() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            String uri = "";
+            collectionResource.removeChildResourceByUri(uri);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
+    }
+
+    public void testGetResourceModel_P01() {
+        SimulatorResourceModel result = null;
+
+        try {
+            result = collectionResource.getResourceModel();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertNotNull(result);
+        assertTrue(result.size() > 0);
+    }
+}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/server/test/SimulatorResourceTest.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/server/test/SimulatorResourceTest.java
new file mode 100644 (file)
index 0000000..4508d2f
--- /dev/null
@@ -0,0 +1,702 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator.server.test;
+
+import java.util.Vector;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import org.oic.simulator.InvalidArgsException;
+import org.oic.simulator.NoSupportException;
+import org.oic.simulator.SimulatorException;
+import org.oic.simulator.SimulatorManager;
+import org.oic.simulator.SimulatorResourceModel;
+import org.oic.simulator.client.FindResourceListener;
+import org.oic.simulator.client.SimulatorRemoteResource;
+import org.oic.simulator.server.SimulatorResource;
+import org.oic.simulator.server.SimulatorSingleResource;
+import org.oic.simulator.test.ExceptionType;
+import org.oic.simulator.utils.ObjectHolder;
+
+import junit.framework.TestCase;
+
+/**
+ * This class tests the APIs of SimulatorResource class
+ */
+public class SimulatorResourceTest extends TestCase {
+    private static final String RES_NAME = "test-resource";
+    private static final String RES_URI  = "/test/resource";
+    private static final String RES_TYPE = "test.resource";
+    private SimulatorResource   resource = null;
+
+    protected void setUp() throws Exception {
+        super.setUp();
+        resource = SimulatorManager.createResource(
+                SimulatorResource.Type.SINGLE, RES_NAME, RES_URI, RES_TYPE);
+    }
+
+    protected void tearDown() throws Exception {
+        super.tearDown();
+        resource = null;
+    }
+
+    public void testIsCollection_P01() {
+        boolean isCollection = false;
+        isCollection = resource.isCollection();
+        assertFalse(isCollection);
+    }
+
+    public void testIsCollection_P02() {
+        boolean isCollection = true;
+
+        try {
+            SimulatorResource res = SimulatorManager.createResource(
+                    SimulatorResource.Type.COLLECTION, RES_NAME, RES_URI,
+                    RES_TYPE);
+            isCollection = res.isCollection();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(isCollection);
+    }
+
+    public void testGetName_P01() {
+        String name = null;
+
+        try {
+            name = resource.getName();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(RES_NAME, name);
+    }
+
+    public void testGetType_P01() {
+        SimulatorResource.Type type = SimulatorResource.Type.SINGLE;
+        type = resource.getType();
+        assertEquals(SimulatorResource.Type.SINGLE, type);
+    }
+
+    public void testGetURI_P01() {
+        String uri = null;
+
+        try {
+            uri = resource.getURI();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(RES_URI, uri);
+    }
+
+    public void testGetResourceType_P01() {
+        String resType = null;
+
+        try {
+            resType = resource.getResourceType();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(RES_TYPE, resType);
+    }
+
+    public void testGetInterface_P01() {
+        Vector<String> interfaces = null;
+
+        try {
+            interfaces = resource.getInterface();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertNotNull(interfaces);
+        assertTrue(interfaces.size() > 0);
+    }
+
+    public void testSetName_P01() {
+        String name = "new-name";
+        String newName = null;
+
+        try {
+            resource.setName(name);
+            newName = resource.getName();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(name, newName);
+    }
+
+    public void testSetName_N01() {
+        String newName = "";
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            resource.setName(newName);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertEquals(ExceptionType.INVALID_ARGS, exType);
+    }
+
+    public void testSetName_N02() {
+        String newName = null;
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            resource.setName(newName);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertEquals(ExceptionType.INVALID_ARGS, exType);
+    }
+
+    public void testSetURI_P01() {
+        String newUri = "/test/newuri/1";
+        String uri = null;
+
+        try {
+            resource.setURI(newUri);
+            uri = resource.getURI();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(newUri, uri);
+    }
+
+    public void testSetURI_N01() {
+        String newUri = "";
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            resource.setURI(newUri);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertEquals(ExceptionType.INVALID_ARGS, exType);
+    }
+
+    public void testSetURI_N02() {
+        String newUri = null;
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            resource.setURI(newUri);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertEquals(ExceptionType.INVALID_ARGS, exType);
+    }
+
+    public void testSetResourceType_P01() {
+        String newResType = "test.newresource";
+        String resType = null;
+
+        try {
+            resource.setResourceType(newResType);
+            resType = resource.getResourceType();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(newResType, resType);
+    }
+
+    public void testSetResourceType_N01() {
+        String newResType = "";
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            resource.setResourceType(newResType);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertEquals(ExceptionType.INVALID_ARGS, exType);
+    }
+
+    public void testSetResourceType_N02() {
+        String newResType = null;
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            resource.setResourceType(newResType);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertEquals(ExceptionType.INVALID_ARGS, exType);
+    }
+
+    public void testSetInterface_P01() {
+        String newInterface = "oic.if.r";
+        Vector<String> interfaces = null;
+
+        try {
+            resource.setInterface(newInterface);
+            interfaces = resource.getInterface();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertNotNull(interfaces);
+        assertTrue(interfaces.size() == 1
+                && interfaces.get(0).equals(newInterface));
+    }
+
+    public void testSetInterface_N01() {
+        String newInterface = "";
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            resource.setInterface(newInterface);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertEquals(ExceptionType.INVALID_ARGS, exType);
+    }
+
+    public void testSetInterface_N02() {
+        String newInterface = null;
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            resource.setInterface(newInterface);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertEquals(ExceptionType.INVALID_ARGS, exType);
+    }
+
+    public void testSetInterface_N03() {
+        String newInterface = "oic.if.s";
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            resource.start();
+            resource.setInterface(newInterface);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        try {
+            resource.stop();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(ExceptionType.SIMULATOR, exType);
+    }
+
+    public void testSetInterfaces_P01() {
+        String interface1 = "oic.if.s";
+        String interface2 = "oic.if.a";
+        Vector<String> interfaces = null;
+        Vector<String> newInterfaces = new Vector<String>();
+        newInterfaces.add(interface1);
+        newInterfaces.add(interface2);
+        try {
+            resource.setInterface(newInterfaces);
+            interfaces = resource.getInterface();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertNotNull(interfaces);
+        assertTrue(interfaces.size() == 2 && interfaces.contains(interface1)
+                && interfaces.contains(interface2));
+    }
+
+    public void testSetInterfaces_N01() {
+        Vector<String> newInterfaces = new Vector<String>();
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            resource.setInterface(newInterfaces);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertEquals(ExceptionType.INVALID_ARGS, exType);
+    }
+
+    public void testSetInterfaces_N02() {
+        Vector<String> newInterfaces = null;
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            resource.setInterface(newInterfaces);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertEquals(ExceptionType.INVALID_ARGS, exType);
+    }
+
+    public void testSetInterfaces_N03() {
+        String interface1 = "oic.if.s";
+        String interface2 = "oic.if.a";
+        ExceptionType exType = ExceptionType.UNKNOWN;
+        Vector<String> newInterfaces = new Vector<String>();
+        newInterfaces.add(interface1);
+        newInterfaces.add(interface2);
+
+        try {
+            resource.start();
+            resource.setInterface(newInterfaces);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        try {
+            resource.stop();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(ExceptionType.SIMULATOR, exType);
+    }
+
+    public void testAddInterface_P01() {
+        String newInterface = "oic.if.rw";
+        Vector<String> interfaces = null;
+
+        try {
+            resource.addInterface(newInterface);
+            interfaces = resource.getInterface();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (NoSupportException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertNotNull(interfaces);
+        assertTrue(interfaces.contains(newInterface));
+    }
+
+    public void testAddInterface_N01() {
+        String newInterface = "";
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            resource.addInterface(newInterface);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (NoSupportException e) {
+            exType = ExceptionType.NOT_SUPPORTED;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertEquals(ExceptionType.INVALID_ARGS, exType);
+    }
+
+    public void testAddInterface_N02() {
+        String newInterface = null;
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            resource.addInterface(newInterface);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (NoSupportException e) {
+            exType = ExceptionType.NOT_SUPPORTED;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertEquals(ExceptionType.INVALID_ARGS, exType);
+    }
+
+    public void testAddInterface_N03() {
+        String newInterface = "oic.if.a";
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            SimulatorResource res = SimulatorManager.createResource(
+                    SimulatorResource.Type.COLLECTION, RES_NAME, RES_URI,
+                    RES_TYPE);
+            res.addInterface(newInterface);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (NoSupportException e) {
+            exType = ExceptionType.NOT_SUPPORTED;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertEquals(ExceptionType.NOT_SUPPORTED, exType);
+    }
+
+    public void testSetObservable_P01() {
+        boolean newState = true;
+        boolean state = false;
+        try {
+            resource.setObservable(newState);
+            state = resource.isObservable();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(newState, state);
+    }
+
+    public void testSetObservable_P02() {
+        boolean newState = false;
+        boolean state = true;
+        try {
+            resource.setObservable(newState);
+            state = resource.isObservable();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(newState, state);
+    }
+
+    public void testSetDiscoverable_P01() {
+        boolean newState = true;
+        boolean state = false;
+        try {
+            resource.setDiscoverable(newState);
+            state = resource.isDiscoverable();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(newState, state);
+    }
+
+    public void testSetDiscoverable_P02() {
+        boolean newState = false;
+        boolean state = true;
+        try {
+            resource.setDiscoverable(newState);
+            state = resource.isDiscoverable();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(newState, state);
+    }
+
+    public void testIsObservable_P01() {
+        boolean state = false;
+
+        try {
+            state = resource.isObservable();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(true, state);
+    }
+
+    public void testIsDiscoverable_P01() {
+        boolean state = false;
+
+        try {
+            state = resource.isDiscoverable();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(true, state);
+    }
+
+    public void testGetResourceModel_P01() {
+        SimulatorResourceModel resModel = null;
+        String singleResourceRaml = "./ramls/oic.r.light.raml";
+        try {
+            SimulatorSingleResource resource = (SimulatorSingleResource) SimulatorManager
+                    .createResource(singleResourceRaml);
+            resModel = resource.getResourceModel();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertNotNull(resModel);
+        assertTrue(resModel.size() > 0);
+    }
+
+    public void testIsStarted_P01() {
+        boolean state = true;
+
+        try {
+            state = resource.isStarted();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(false, state);
+    }
+
+    public void testIsStarted_P02() {
+        boolean state = false;
+
+        try {
+            resource.start();
+            state = resource.isStarted();
+            resource.stop();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(true, state);
+    }
+
+    public void testIsStarted_P03() {
+        boolean state = true;
+
+        try {
+            resource.start();
+            resource.stop();
+            state = resource.isStarted();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(false, state);
+    }
+
+    public void testStart_P01() {
+        CountDownLatch lockObject = new CountDownLatch(1);
+        ObjectHolder<SimulatorRemoteResource> resourceHolder = new ObjectHolder<>();
+        FindResourceCallbackListener listener = new FindResourceCallbackListener(
+                lockObject, resourceHolder);
+
+        try {
+            resource.start();
+            SimulatorManager.findResource(resource.getResourceType(), listener);
+
+            // Wait for the resource to found
+            try {
+                lockObject.await(10, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+            }
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        try {
+            resource.stop();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertNotNull(resourceHolder.get());
+    }
+
+    public void testStop_P01() {
+        CountDownLatch lockObject = new CountDownLatch(1);
+        ObjectHolder<SimulatorRemoteResource> resourceHolder = new ObjectHolder<>();
+        FindResourceCallbackListener listener = new FindResourceCallbackListener(
+                lockObject, resourceHolder);
+
+        try {
+            resource.start();
+            resource.stop();
+            SimulatorManager.findResource(resource.getResourceType(), listener);
+
+            // Wait for the resource to found
+            try {
+                lockObject.await(10, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+            }
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        try {
+            resource.stop();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertNull(resourceHolder.get());
+    }
+}
+
+class FindResourceCallbackListener implements FindResourceListener {
+
+    private CountDownLatch                        mLockObject;
+    private ObjectHolder<SimulatorRemoteResource> mResourceHolder;
+
+    public FindResourceCallbackListener(CountDownLatch lockObject,
+            ObjectHolder<SimulatorRemoteResource> resourceHolder) {
+        mLockObject = lockObject;
+        mResourceHolder = resourceHolder;
+    }
+
+    @Override
+    public void onResourceFound(SimulatorRemoteResource resource) {
+        mResourceHolder.set(resource);
+        mLockObject.countDown();
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/server/test/SimulatorSingleResourceTest.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/server/test/SimulatorSingleResourceTest.java
new file mode 100644 (file)
index 0000000..842fb72
--- /dev/null
@@ -0,0 +1,564 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator.server.test;
+
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.BooleanProperty;
+import org.oic.simulator.DoubleProperty;
+import org.oic.simulator.IntegerProperty;
+import org.oic.simulator.InvalidArgsException;
+import org.oic.simulator.SimulatorException;
+import org.oic.simulator.SimulatorManager;
+import org.oic.simulator.SimulatorResourceAttribute;
+import org.oic.simulator.StringProperty;
+import org.oic.simulator.server.SimulatorResource;
+import org.oic.simulator.server.SimulatorResource.AutoUpdateListener;
+import org.oic.simulator.server.SimulatorSingleResource;
+import org.oic.simulator.test.ExceptionType;
+import org.oic.simulator.utils.ObjectHolder;
+
+import junit.framework.TestCase;
+
+public class SimulatorSingleResourceTest extends TestCase {
+    private static final String     SINGLE_RES_RAML = "./ramls/oic.r.light.raml";
+    private static final String     INT_KEY         = "Integer";
+    private static final String     DOUBLE_KEY      = "Double";
+    private static final String     BOOL_KEY        = "Boolean";
+    private static final String     STRING_KEY      = "String";
+    private SimulatorSingleResource singleResource  = null;
+
+    protected void setUp() throws Exception {
+        super.setUp();
+        singleResource = (SimulatorSingleResource) SimulatorManager
+                .createResource(SimulatorResource.Type.SINGLE, "test-resource",
+                        "/test/resource", "test.resource");
+    }
+
+    protected void tearDown() throws Exception {
+        super.tearDown();
+        singleResource = null;
+    }
+
+    public void testGetAttribute_P01() {
+        SimulatorResourceAttribute attribute = null;
+
+        try {
+            IntegerProperty property = new IntegerProperty.Builder().build();
+            SimulatorResourceAttribute intAttribute = new SimulatorResourceAttribute(
+                    INT_KEY, new AttributeValue(2), property);
+
+            assertTrue(singleResource.addAttribute(intAttribute));
+            attribute = singleResource.getAttribute(INT_KEY);
+            assertTrue(singleResource.removeAttribute(INT_KEY));
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertNotNull(attribute);
+    }
+
+    public void testGetAttribute_N01() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            singleResource.getAttribute(null);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertEquals(ExceptionType.INVALID_ARGS, exType);
+    }
+
+    public void testGetAttribute_N02() {
+        SimulatorResourceAttribute att = null;
+
+        try {
+            att = singleResource.getAttribute("PQRS");
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertNull(att);
+    }
+
+    public void testAddAttributeInteger_P01() {
+        int result = -1;
+
+        try {
+            IntegerProperty property = new IntegerProperty.Builder().build();
+            SimulatorResourceAttribute intAttribute = new SimulatorResourceAttribute(
+                    INT_KEY, new AttributeValue(2), property);
+
+            assertTrue(singleResource.addAttribute(intAttribute));
+
+            SimulatorResourceAttribute attribute = singleResource
+                    .getAttribute(INT_KEY);
+            assertNotNull(attribute);
+
+            result = ((Integer) attribute.value().get()).intValue();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(2, result);
+    }
+
+    public void testAddAttributeDouble_P01() {
+        double result = 0.0;
+
+        try {
+            DoubleProperty property = new DoubleProperty.Builder().build();
+            SimulatorResourceAttribute doubleAttribute = new SimulatorResourceAttribute(
+                    DOUBLE_KEY, new AttributeValue(4.0), property);
+
+            assertTrue(singleResource.addAttribute(doubleAttribute));
+
+            SimulatorResourceAttribute attribute = singleResource
+                    .getAttribute(DOUBLE_KEY);
+            assertNotNull(attribute);
+
+            result = ((Double) attribute.value().get()).doubleValue();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(4.0, result);
+    }
+
+    public void testAddAttributeBoolean_P01() {
+        boolean result = false;
+
+        try {
+            BooleanProperty property = new BooleanProperty.Builder().build();
+            SimulatorResourceAttribute boolAttribute = new SimulatorResourceAttribute(
+                    BOOL_KEY, new AttributeValue(true), property);
+
+            assertTrue(singleResource.addAttribute(boolAttribute));
+
+            SimulatorResourceAttribute attribute = singleResource
+                    .getAttribute(BOOL_KEY);
+            assertNotNull(attribute);
+
+            result = ((Boolean) attribute.value().get()).booleanValue();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(true, result);
+    }
+
+    public void testAddAttributeString_P01() {
+        String result = null;
+
+        try {
+            StringProperty property = new StringProperty.Builder().build();
+            SimulatorResourceAttribute stringAttribute = new SimulatorResourceAttribute(
+                    STRING_KEY, new AttributeValue("string-value"), property);
+
+            assertTrue(singleResource.addAttribute(stringAttribute));
+
+            SimulatorResourceAttribute attribute = singleResource
+                    .getAttribute(STRING_KEY);
+            assertNotNull(attribute);
+
+            result = (String) attribute.value().get();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals("string-value", result);
+    }
+
+    public void testRemoveAttribute_P01() {
+        SimulatorResourceAttribute result = null;
+
+        try {
+            StringProperty property = new StringProperty.Builder().build();
+            SimulatorResourceAttribute stringAttribute = new SimulatorResourceAttribute(
+                    STRING_KEY, new AttributeValue("friday"), property);
+
+            assertTrue(singleResource.addAttribute(stringAttribute));
+            assertTrue(singleResource.removeAttribute(STRING_KEY));
+
+            result = singleResource.getAttribute(STRING_KEY);
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertNull(result);
+    }
+
+    public void testRemoveAttribute_N02() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            StringProperty property = new StringProperty.Builder().build();
+            SimulatorResourceAttribute stringAttribute = new SimulatorResourceAttribute(
+                    STRING_KEY, new AttributeValue("friday"), property);
+
+            assertTrue(singleResource.addAttribute(stringAttribute));
+            singleResource.removeAttribute(null);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertEquals(ExceptionType.INVALID_ARGS, exType);
+    }
+
+    public void testRemoveAttribute_N03() {
+        boolean result = false;
+        try {
+            result = singleResource.removeAttribute("");
+        } catch (InvalidArgsException e) {
+        } catch (SimulatorException e) {
+        }
+
+        assertFalse(result);
+    }
+
+    public void testUpdateAttributeInteger_P01() {
+        int result = -1;
+
+        try {
+            IntegerProperty property = new IntegerProperty.Builder().build();
+            SimulatorResourceAttribute intAttribute = new SimulatorResourceAttribute(
+                    INT_KEY, new AttributeValue(10), property);
+
+            assertTrue(singleResource.addAttribute(intAttribute));
+            assertTrue(singleResource.updateAttribute(INT_KEY,
+                    new AttributeValue(12)));
+
+            SimulatorResourceAttribute attribute = singleResource
+                    .getAttribute(INT_KEY);
+            assertNotNull(attribute);
+
+            result = ((Integer) attribute.value().get()).intValue();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(12, result);
+    }
+
+    public void testUpdateAttributeDouble_P01() {
+        double result = 0.0;
+
+        try {
+            DoubleProperty property = new DoubleProperty.Builder().build();
+            SimulatorResourceAttribute doubleAttribute = new SimulatorResourceAttribute(
+                    DOUBLE_KEY, new AttributeValue(22.0), property);
+
+            assertTrue(singleResource.addAttribute(doubleAttribute));
+            assertTrue(singleResource.updateAttribute(DOUBLE_KEY,
+                    new AttributeValue(25.3)));
+
+            SimulatorResourceAttribute attribute = singleResource
+                    .getAttribute(DOUBLE_KEY);
+            assertNotNull(attribute);
+
+            result = ((Double) attribute.value().get()).doubleValue();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(25.3, result);
+    }
+
+    public void testUpdateAttributeBoolean_P01() {
+        boolean result = true;
+
+        try {
+            BooleanProperty property = new BooleanProperty.Builder().build();
+            SimulatorResourceAttribute boolAttribute = new SimulatorResourceAttribute(
+                    BOOL_KEY, new AttributeValue(true), property);
+
+            assertTrue(singleResource.addAttribute(boolAttribute));
+            assertTrue(singleResource.updateAttribute(BOOL_KEY,
+                    new AttributeValue(false)));
+
+            SimulatorResourceAttribute attribute = singleResource
+                    .getAttribute(BOOL_KEY);
+            assertNotNull(attribute);
+
+            result = ((Boolean) attribute.value().get()).booleanValue();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(false, result);
+    }
+
+    public void testupdateAttributeString_P01() {
+        String result = null;
+
+        try {
+            StringProperty property = new StringProperty.Builder().build();
+            SimulatorResourceAttribute stringAttribute = new SimulatorResourceAttribute(
+                    STRING_KEY, new AttributeValue("old-value"), property);
+
+            assertTrue(singleResource.addAttribute(stringAttribute));
+            assertTrue(singleResource.updateAttribute(STRING_KEY,
+                    new AttributeValue("new-value")));
+
+            SimulatorResourceAttribute attribute = singleResource
+                    .getAttribute(STRING_KEY);
+            assertNotNull(attribute);
+
+            result = (String) attribute.value().get();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals("new-value", result);
+    }
+
+    public void testStartResourceAutomation_P01() {
+        SimulatorSingleResource resource = createResourceFromRAML();
+        if (null == resource)
+            return;
+
+        CountDownLatch lockObject = new CountDownLatch(1);
+        ObjectHolder<AutoUpdateInfo> autoUpdateHolder = new ObjectHolder<>();
+        AutoUpdateCompleteListener automationListener = new AutoUpdateCompleteListener(
+                lockObject, autoUpdateHolder);
+        int id = -1;
+
+        try {
+            resource.start();
+            id = resource.startResourceUpdation(
+                    SimulatorResource.AutoUpdateType.REPEAT, 1000,
+                    automationListener);
+
+            try {
+                lockObject.await(3, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+            }
+
+            resource.stopUpdation(id);
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        try {
+            resource.stop();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertNotNull(autoUpdateHolder.get());
+        assertEquals(id, autoUpdateHolder.get().getId());
+    }
+
+    public void testStartResourceAutomation_N01() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            singleResource.startResourceUpdation(
+                    SimulatorResource.AutoUpdateType.ONE_TIME, 500, null);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertEquals(ExceptionType.INVALID_ARGS, exType);
+    }
+
+    public void testStartAttributeAutomation_P01() {
+        SimulatorSingleResource resource = createResourceFromRAML();
+        if (null == resource)
+            return;
+
+        String attributeName = null;
+        try {
+            for (Map.Entry<String, AttributeValue> entry : resource
+                    .getResourceModel().get().entrySet()) {
+                attributeName = entry.getKey();
+                if (null != attributeName && !attributeName.isEmpty()) {
+                    break;
+                }
+            }
+        } catch (SimulatorException e1) {
+            e1.printStackTrace();
+        }
+
+        if (null == attributeName)
+            return;
+
+        CountDownLatch lockObject = new CountDownLatch(1);
+        ObjectHolder<AutoUpdateInfo> autoUpdateHolder = new ObjectHolder<>();
+        AutoUpdateCompleteListener automationListener = new AutoUpdateCompleteListener(
+                lockObject, autoUpdateHolder);
+        int id = -1;
+
+        try {
+            resource.start();
+            id = resource.startAttributeUpdation(attributeName,
+                    SimulatorResource.AutoUpdateType.REPEAT, 1000,
+                    automationListener);
+
+            try {
+                lockObject.await(3, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+            }
+
+            resource.stopUpdation(id);
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        try {
+            resource.stop();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertNotNull(autoUpdateHolder.get());
+        assertEquals(id, autoUpdateHolder.get().getId());
+    }
+
+    public void testStartAttributeAutomation_N01() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            singleResource.startAttributeUpdation("intensity",
+                    SimulatorResource.AutoUpdateType.ONE_TIME, 1000, null);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertEquals(ExceptionType.INVALID_ARGS, exType);
+    }
+
+    public void testStopUpdation_P01() {
+        SimulatorSingleResource resource = createResourceFromRAML();
+        if (null == resource)
+            return;
+
+        CountDownLatch lockObject = new CountDownLatch(1);
+        ObjectHolder<AutoUpdateInfo> autoUpdateHolder = new ObjectHolder<>();
+        AutoUpdateCompleteListener automationListener = new AutoUpdateCompleteListener(
+                lockObject, autoUpdateHolder);
+        boolean result = false;
+        try {
+            resource.start();
+            int id = resource.startResourceUpdation(
+                    SimulatorResource.AutoUpdateType.REPEAT, 1000,
+                    automationListener);
+            resource.stopUpdation(id);
+            result = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        try {
+            resource.stop();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(result);
+    }
+
+    private SimulatorSingleResource createResourceFromRAML() {
+        try {
+            return (SimulatorSingleResource) SimulatorManager
+                    .createResource(SINGLE_RES_RAML);
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        return null;
+    }
+}
+
+class AutoUpdateInfo {
+    private String uri = null;
+    private int    id  = -1;
+
+    AutoUpdateInfo(String uri, int id) {
+        this.uri = uri;
+        this.id = id;
+    }
+
+    public String getUri() {
+        return uri;
+    }
+
+    public int getId() {
+        return id;
+    }
+}
+
+class AutoUpdateCompleteListener implements AutoUpdateListener {
+    private CountDownLatch               lock;
+    private ObjectHolder<AutoUpdateInfo> autoUpdateHolder;
+
+    public AutoUpdateCompleteListener(CountDownLatch lock,
+            ObjectHolder<AutoUpdateInfo> autoUpdateHolder) {
+        this.lock = lock;
+        this.autoUpdateHolder = autoUpdateHolder;
+    }
+
+    @Override
+    public void onUpdateComplete(String uri, int id) {
+        autoUpdateHolder.set(new AutoUpdateInfo(uri, id));
+        lock.countDown();
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/AutomationListener.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/AutomationListener.java
deleted file mode 100644 (file)
index cb545db..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.serviceprovider.test;
-
-import java.util.concurrent.CountDownLatch;
-import org.oic.simulator.IAutomation;
-
-/**
- * This class implements methods for receiving notifications on
- * completion of automation.
- */
-public class AutomationListener implements IAutomation
-{
-
-    private CountDownLatch lockObject;
-    private AutomationObject automationObject;
-
-    public AutomationListener(CountDownLatch lockObject, AutomationObject automationObject)
-    {
-        this.lockObject = lockObject;
-        this.automationObject = automationObject;
-    }
-
-    @Override
-    public void onAutomationComplete(String resourceURI, int automationId)
-    {
-        automationObject.setAutomationId(automationId);
-        automationObject.setResourceURI(resourceURI);
-
-        lockObject.countDown();
-    }
-}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/AutomationObject.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/AutomationObject.java
deleted file mode 100644 (file)
index 9ada5d8..0000000
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.serviceprovider.test;
-
-/**
- * This class implements methods for setting/getting URI
- * and automation ID.
- */
-public class AutomationObject
-{
-
-    private String resourceURI;
-    private int automationId;
-
-    public void setResourceURI(String resourceURI)
-    {
-        this.resourceURI = resourceURI;
-    }
-
-    public String getResourceURI()
-    {
-        return resourceURI;
-    }
-
-    public void setAutomationId(int automationId)
-    {
-        this.automationId = automationId;
-    }
-
-    public int getAutomationId()
-    {
-        return automationId;
-    }
-}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/Observer.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/Observer.java
deleted file mode 100644 (file)
index ca69964..0000000
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.serviceprovider.test;
-
-import java.util.concurrent.CountDownLatch;
-
-import org.oic.simulator.serviceprovider.IObserver;
-import org.oic.simulator.serviceprovider.ObserverInfo;
-
-/**
- * This class implements methods for receiving observer
- * change callbacks.
- */
-public class Observer implements IObserver
-{
-    private CountDownLatch lockObject;
-    private ObserverObject observerObject;
-
-    public Observer(CountDownLatch lockObject, ObserverObject observerObject)
-    {
-        this.lockObject = lockObject;
-        this.observerObject = observerObject;
-    }
-
-    @Override
-    public void onObserverChanged(String resourceURI, int state, ObserverInfo observer)
-    {
-        observerObject.setState(state);
-        observerObject.setResourceURI(resourceURI);
-        observerObject.setObserver(observer);
-
-        lockObject.countDown();
-    }
-}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/ObserverObject.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/ObserverObject.java
deleted file mode 100644 (file)
index 14bd6a1..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.serviceprovider.test;
-
-import org.oic.simulator.serviceprovider.ObserverInfo;
-
-/**
- * This class provides methods to set/get observers and state
- * information.
- */
-public class ObserverObject
-{
-    private String resourceURI;
-    private int state;
-    private ObserverInfo observer;
-
-    public void setResourceURI(String resourceURI)
-    {
-        this.resourceURI = resourceURI;
-    }
-
-    public String getResourceURI()
-    {
-        return resourceURI;
-    }
-
-    public void setState(int state)
-    {
-        this.state = state;
-    }
-
-    public int getState()
-    {
-        return state;
-    }
-
-    public void setObserver(ObserverInfo observer)
-    {
-        this.observer = observer;
-    }
-
-    public ObserverInfo getObserver()
-    {
-        return observer;
-    }
-}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/SimlatorResourceServerTest.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/SimlatorResourceServerTest.java
deleted file mode 100644 (file)
index cfbe5d2..0000000
+++ /dev/null
@@ -1,936 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.serviceprovider.test;
-
-import java.util.Vector;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import junit.framework.TestCase;
-
-import org.oic.simulator.InvalidArgsException;
-import org.oic.simulator.ResourceAttribute;
-import org.oic.simulator.SimulatorException;
-import org.oic.simulator.SimulatorManager;
-import org.oic.simulator.SimulatorResourceModel;
-import org.oic.simulator.serviceprovider.AutomationType;
-import org.oic.simulator.serviceprovider.SimulatorResourceServer;
-import org.oic.simulator.test.ResourceModelChangeListener;
-import org.oic.simulator.test.ResourceModelObject;
-
-/**
- * This class tests the functionality of Simulator Resource Server
- * class APIs.
- */
-public class SimlatorResourceServerTest extends TestCase
-{
-
-    private static final String CONFIG_PATH = "./ramls/simple-light.raml";
-
-    private static final String KEY = "testkey";
-
-    private CountDownLatch lockObject;
-    private ResourceModelObject resourceModelObject;
-    private ResourceModelChangeListener resourceModelChangeListener;
-
-    private SimulatorResourceServer simulatorResourceServer;
-
-    static
-    {
-        System.loadLibrary("SimulatorManager");
-        System.loadLibrary("RamlParser");
-        System.loadLibrary("oc");
-        System.loadLibrary("oc_logger");
-        System.loadLibrary("octbstack");
-    }
-
-    protected void setUp() throws Exception
-    {
-        super.setUp();
-        lockObject= new CountDownLatch(1);
-        resourceModelObject = new ResourceModelObject();
-        resourceModelChangeListener = new ResourceModelChangeListener(resourceModelObject);
-        simulatorResourceServer = SimulatorManager.createResource(CONFIG_PATH, resourceModelChangeListener);
-    }
-
-    protected void tearDown() throws Exception
-    {
-        super.tearDown();
-
-        SimulatorManager.deleteResource(simulatorResourceServer);
-
-        lockObject = null;
-        resourceModelObject = null;
-        resourceModelChangeListener = null;
-
-        simulatorResourceServer = null;
-    }
-
-    public void testGetURI_P01()
-    {
-        assertNotNull(simulatorResourceServer.getURI());
-    }
-
-    public void testGetResourceType_P01()
-    {
-        assertNotNull(simulatorResourceServer.getResourceType());
-    }
-
-    public void testGetInterfaceType_P01()
-    {
-        assertNotNull(simulatorResourceServer.getInterfaceType());
-    }
-
-    public void testGetModel_P01()
-    {
-        boolean result = false;
-
-        try
-        {
-            if(simulatorResourceServer.getModel() != null && simulatorResourceServer.getModel().size() > 0)
-                result = true;
-        }
-        catch (InvalidArgsException e)
-        {
-            e.printStackTrace();
-        }
-        catch (SimulatorException e)
-        {
-            e.printStackTrace();
-        }
-
-        assertTrue(result);
-    }
-
-    public void testAddAttributeInteger_P01()
-    {
-        try
-        {
-            simulatorResourceServer.addAttributeInteger(KEY, 2);
-        }
-        catch (Exception e)
-        {
-            e.printStackTrace();
-        }
-        assertEquals(Integer.parseInt(getValue(KEY) + ""), 2);
-    }
-
-    public void testAddAttributeDouble_P01()
-    {
-        try
-        {
-            simulatorResourceServer.addAttributeDouble(KEY, 4.0);
-        }
-        catch (Exception e)
-        {
-            e.printStackTrace();
-        }
-        assertEquals(Double.parseDouble(getValue(KEY) + ""), 4.0);
-    }
-
-    public void testAddAttributeBoolean_P01()
-    {
-        try
-        {
-            simulatorResourceServer.addAttributeBoolean(KEY, Boolean.parseBoolean("true"));
-        }
-        catch (Exception e)
-        {
-            e.printStackTrace();
-        }
-        assertEquals(Boolean.parseBoolean(getValue(KEY).toString() + ""), true);
-    }
-
-    public void testaddAttributeString_P01()
-    {
-        try
-        {
-            simulatorResourceServer.addAttributeString(KEY, "test");
-        }
-        catch (Exception e)
-        {
-            e.printStackTrace();
-        }
-        assertEquals(getValue(KEY) + "", "test");
-    }
-
-    public void testUpdateAttributeInteger_P01()
-    {
-        boolean result = true;
-
-        try
-        {
-            simulatorResourceServer.addAttributeInteger(KEY, 10);
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        result = result && Integer.parseInt(getValue(KEY) + "") == 10;
-
-        try
-        {
-            simulatorResourceServer.updateAttributeInteger(KEY, 12);
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-        result = result && Integer.parseInt(getValue(KEY) + "") == 12;
-
-        assertTrue(result);
-    }
-
-    public void testUpdateAttributeDouble_P01()
-    {
-        boolean result = true;
-
-        try
-        {
-            simulatorResourceServer.addAttributeDouble(KEY, 22.0);
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        result = result && Double.parseDouble(getValue(KEY) + "") == 22.0;
-
-        try
-        {
-            simulatorResourceServer.updateAttributeDouble(KEY, 25.3);
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        result = result && Double.parseDouble(getValue(KEY) + "") == 25.3;
-
-        assertTrue(result);
-    }
-
-    public void testUpdateAttributeBoolean_P01()
-    {
-        boolean result = true;
-
-        try
-        {
-            simulatorResourceServer.addAttributeBoolean(KEY, Boolean.parseBoolean("true"));
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        result = result && Boolean.parseBoolean(getValue(KEY) + "")==true;
-
-        try
-        {
-            simulatorResourceServer.updateAttributeBoolean(KEY, Boolean.parseBoolean("false"));
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        result = result && !Boolean.parseBoolean(getValue(KEY) + "");
-
-        assertTrue(result);
-    }
-
-    public void testupdateAttributeString_P01()
-    {
-        boolean result = true;
-
-        try
-        {
-            simulatorResourceServer.addAttributeString(KEY, "old");
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        result = result && getValue(KEY).equals("old");
-
-        try
-        {
-            simulatorResourceServer.updateAttributeString(KEY, "new");
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        result = result && getValue(KEY).equals("new");
-
-        assertTrue(result);
-    }
-
-    public void testSetRange_P01()
-    {
-        boolean result = true;
-
-        try
-        {
-            simulatorResourceServer.addAttributeInteger(KEY, 10);
-            simulatorResourceServer.setRange(KEY, 1, 12);
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        result = result && Integer.parseInt(getValue(KEY) + "") == 10;
-
-        try
-        {
-            simulatorResourceServer.updateAttributeInteger(KEY, 3);
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        result = result && Integer.parseInt(getValue(KEY) + "") == 3;
-
-        assertTrue(result);
-    }
-
-    /**
-     * Try to set the value out of range
-     */
-    public void testSetRange_N01()
-    {
-        boolean result = true;
-
-        try
-        {
-            simulatorResourceServer.addAttributeInteger(KEY, 10);
-            simulatorResourceServer.setRange(KEY, 1, 12);
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        result = result && Integer.parseInt(getValue(KEY) + "") == 10;
-
-        try
-        {
-            simulatorResourceServer.updateAttributeInteger(KEY, 13);
-            result = false;
-        }
-        catch (Exception e)
-        {
-            result = true;
-        }
-
-        result = result && Integer.parseInt(getValue(KEY) + "") == 10;
-
-        assertTrue(result);
-    }
-
-    public void testSetAllowedValuesInteger_P01()
-    {
-        boolean result = true;
-
-        try
-        {
-            simulatorResourceServer.addAttributeInteger(KEY, 10);
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        Vector<Integer> values = new Vector<Integer>();
-        values.add(1);
-        values.add(10);
-        values.add(20);
-        values.add(50);
-
-        try
-        {
-            simulatorResourceServer.setAllowedValuesInteger(KEY, values);
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        result = result && Integer.parseInt(getValue(KEY) + "") == 10;
-
-        try
-        {
-            simulatorResourceServer.updateAttributeInteger(KEY, 20);
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        result = result && Integer.parseInt(getValue(KEY) + "") == 20;
-
-        assertTrue(result);
-    }
-
-    /**
-     * Try setting with out of range
-     */
-    public void testSetAllowedValuesInteger_N01()
-    {
-        boolean result = true;
-
-        try
-        {
-            simulatorResourceServer.addAttributeInteger(KEY, 10);
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        Vector<Integer> values = new Vector<Integer>();
-        values.add(1);
-        values.add(10);
-        values.add(20);
-        values.add(50);
-
-        try
-        {
-            simulatorResourceServer.setAllowedValuesInteger(KEY, values);
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        result = result && Integer.parseInt(getValue(KEY) + "") == 10;
-
-        try
-        {
-            simulatorResourceServer.updateAttributeInteger(KEY, 2);
-            result = false;
-        }
-        catch (Exception e)
-        {
-            result = true;
-        }
-
-        result = result && Integer.parseInt(getValue(KEY) + "") == 10;
-
-        assertTrue(result);
-    }
-
-    /**
-     * Try setting values multiple times
-     */
-    public void testSetAllowedValuesDouble_P01()
-    {
-        boolean result = true;
-
-        try
-        {
-            simulatorResourceServer.addAttributeDouble(KEY, 11.5);
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        Vector<Double> values = new Vector<Double>();
-        values.add(11.5);
-        values.add(10.5);
-        values.add(20.5);
-        values.add(50.5);
-
-        try
-        {
-            simulatorResourceServer.setAllowedValuesDouble(KEY, values);
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        result = result && Double.parseDouble(getValue(KEY) + "") == 11.5;
-
-        try
-        {
-            simulatorResourceServer.updateAttributeDouble(KEY, 10.5);
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        result = result && Double.parseDouble(getValue(KEY) + "") == 10.5;
-
-        assertTrue(result);
-    }
-
-    /**
-     * Try setting with out of range
-     */
-    public void testSetAllowedValuesDouble_N01()
-    {
-        boolean result = true;
-
-        try
-        {
-            simulatorResourceServer.addAttributeDouble(KEY, 10.5);
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        Vector<Double> values = new Vector<Double>();
-        values.add(11.5);
-        values.add(10.5);
-        values.add(20.5);
-        values.add(50.5);
-
-        try
-        {
-            simulatorResourceServer.setAllowedValuesDouble(KEY, values);
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        result = result && Double.parseDouble(getValue(KEY) + "") == 10.5;
-
-        try
-        {
-            simulatorResourceServer.updateAttributeDouble(KEY, 2.2);
-            result = false;
-        }
-        catch (Exception e)
-        {
-            result = true;
-        }
-
-        result = result && Double.parseDouble(getValue(KEY) + "") == 10.5;
-
-        assertTrue(result);
-    }
-
-    public void testsetAllowedValuesString_P01()
-    {
-        boolean result = true;
-
-        try
-        {
-            simulatorResourceServer.addAttributeString(KEY, "mon");
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        Vector<String> values = new Vector<String>();
-        values.add("mon");
-        values.add("tue");
-        values.add("wed");
-
-        try
-        {
-            simulatorResourceServer.setAllowedValuesString(KEY, values);
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        result = result && getValue(KEY).equals("mon");
-
-        try
-        {
-            simulatorResourceServer.updateAttributeString(KEY, "tue");
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        result = result && getValue(KEY).equals("tue");
-
-        assertTrue(result);
-    }
-
-    /**
-     * Set the value that is not in allowed values
-     */
-    public void testsetAllowedValuesString_N01()
-    {
-        boolean result = true;
-
-        try
-        {
-            simulatorResourceServer.addAttributeString(KEY, "mon");
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        Vector<String> values = new Vector<String>();
-        values.add("mon");
-        values.add("tue");
-        values.add("wed");
-
-        try
-        {
-            simulatorResourceServer.setAllowedValuesString(KEY, values);
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        result = result && getValue(KEY).equals("mon");
-
-        try
-        {
-            simulatorResourceServer.updateAttributeString(KEY, "thu");
-            result = false;
-        }
-        catch (Exception e)
-        {
-            result = true;
-        }
-
-        result = result && getValue(KEY).equals("mon");
-
-        assertTrue(result);
-    }
-
-    public void testRemoveAttribute_P01()
-    {
-        boolean result = true;
-
-        try
-        {
-            simulatorResourceServer.addAttributeString(KEY, "fri");
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        result = result && getValue(KEY).equals("fri");
-
-        try
-        {
-            simulatorResourceServer.removeAttribute(KEY);
-            result = result && !simulatorResourceServer.getModel().getAttributes().containsKey(KEY);
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        assertTrue(result);
-    }
-
-    /**
-     * Try removing the attribute thats not present
-     */
-    public void testRemoveAttribute_N01()
-    {
-        boolean result = false;
-
-        try
-        {
-            simulatorResourceServer.removeAttribute("something");
-        }
-        catch (Exception e)
-        {
-            result = true;
-        }
-
-        assertTrue(result);
-    }
-
-    /**
-     * Try removing when null is passed
-     */
-    public void testRemoveAttribute_N02()
-    {
-        boolean result = false;
-
-        try
-        {
-            simulatorResourceServer.removeAttribute(null);
-        }
-        catch (Exception e)
-        {
-            result = true;
-        }
-
-        assertTrue(result);
-    }
-
-    /**
-     * Try removing when attribute is empty
-     */
-    public void testRemoveAttribute_N03()
-    {
-        boolean result = false;
-
-        try
-        {
-            simulatorResourceServer.removeAttribute("");
-        }
-        catch (Exception e)
-        {
-            result = true;
-        }
-
-        assertTrue(result);
-    }
-
-    public void testStartResourceAutomation_P01()
-    {
-        boolean result = true;
-        lockObject = new CountDownLatch(1);
-        AutomationObject automationObject = new AutomationObject();
-        AutomationListener automationListener = new AutomationListener(lockObject, automationObject);
-        int id = 0;
-        try
-        {
-            id = simulatorResourceServer.startResourceAutomation(AutomationType.NORMAL, automationListener);
-        }
-        catch (Exception e)
-        {
-            result = false;
-            e.printStackTrace();
-        }
-
-        try
-        {
-            lockObject.await(15,TimeUnit.SECONDS);
-        }
-        catch (InterruptedException e)
-        {
-            e.printStackTrace();
-        }
-
-        assertTrue(result && automationObject.getResourceURI() != null && automationObject.getAutomationId() != -1 && id != -1);
-
-        try
-        {
-            simulatorResourceServer.stopAutomation(id);
-        }
-        catch (Exception e)
-        {
-            e.printStackTrace();
-        }
-    }
-
-    /**
-     * null listener
-     */
-    public void testStartResourceAutomation_N01()
-    {
-        boolean result = true;
-        int id = 0;
-        try
-        {
-            id = simulatorResourceServer.startResourceAutomation(AutomationType.NORMAL, null);
-        }
-        catch (Exception e)
-        {
-            result = false;
-        }
-        assertTrue(!result && id == 0);
-    }
-
-    public void testStartAttributeAutomation_P01()
-    {
-        boolean result = true;
-        lockObject = new CountDownLatch(1);
-        AutomationObject automationObject = new AutomationObject();
-        AutomationListener automationListener = new AutomationListener(lockObject, automationObject);
-        int id = 0;
-        try
-        {
-            simulatorResourceServer.addAttributeInteger(KEY, 10);
-            id = simulatorResourceServer.startAttributeAutomation(KEY,
-                    AutomationType.NORMAL, automationListener);
-        }
-        catch (Exception e)
-        {
-            result = false;
-        }
-
-        try
-        {
-            lockObject.await(10, TimeUnit.SECONDS);
-        }
-        catch (InterruptedException e)
-        {
-        }
-
-        assertTrue(result && automationObject.getResourceURI() != null && automationObject.getAutomationId() != -1 && id != -1);
-
-        try
-        {
-            simulatorResourceServer.stopAutomation(id);
-        }
-        catch (Exception e)
-        {
-            e.printStackTrace();
-        }
-    }
-
-    /**
-     * null listener
-     */
-    public void testStartAttributeAutomation_N01()
-    {
-        boolean result = false;
-        int id = 0;
-        try
-        {
-            id = simulatorResourceServer.startAttributeAutomation(simulatorResourceServer.getModel().getAttributes().get(0).getName(),
-                    AutomationType.NORMAL, null);
-            result = false;
-        }
-        catch (Exception e)
-        {
-            result = true;
-        }
-
-        assertTrue(result && id != -1);
-    }
-
-    public void testStopAutomation_P01()
-    {
-        boolean result = true;
-
-        lockObject = new CountDownLatch(1);
-
-        AutomationObject automationObject = new AutomationObject();
-        AutomationListener automationListener = new AutomationListener(lockObject, automationObject);
-
-        int id = 0;
-        try
-        {
-            id = simulatorResourceServer.startResourceAutomation(AutomationType.NORMAL, automationListener);
-        }
-        catch(Exception e)
-        {
-            result = false;
-        }
-
-        try
-        {
-            lockObject.await(05, TimeUnit.SECONDS);
-        }
-        catch (InterruptedException e)
-        {
-        }
-
-        try
-        {
-            simulatorResourceServer.stopAutomation(id);
-        }
-        catch(Exception e)
-        {
-            result = false;
-        }
-
-        assertTrue(result);
-    }
-
-    /**
-     * checking for crash
-     * random id
-     */
-    public void testStopAutomation_N01()
-    {
-        boolean result = false;
-        try
-        {
-            simulatorResourceServer.stopAutomation(144353544);
-        }
-        catch (Exception e)
-        {
-            result = true;
-            e.printStackTrace();
-        }
-        assertTrue(result);
-    }
-
-    private Object getValue(Object key)
-    {
-        SimulatorResourceModel simulatorResourceModel = null;
-        try
-        {
-            simulatorResourceModel = simulatorResourceServer.getModel();
-        }
-        catch (Exception e)
-        {
-            e.printStackTrace();
-        }
-
-        ResourceAttribute resourceAttribute = null;
-        try
-        {
-            resourceAttribute = simulatorResourceModel.getAttributes().get(key);
-        }
-        catch (SimulatorException e)
-        {
-            e.printStackTrace();
-        }
-        return resourceAttribute.getValue();
-    }
-}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ArrayPropertyTest.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ArrayPropertyTest.java
new file mode 100644 (file)
index 0000000..f74b439
--- /dev/null
@@ -0,0 +1,601 @@
+/*
+ * 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.oic.simulator.test;
+
+import org.oic.simulator.ArrayProperty;
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.BooleanProperty;
+import org.oic.simulator.DoubleProperty;
+import org.oic.simulator.IntegerProperty;
+import org.oic.simulator.InvalidArgsException;
+import org.oic.simulator.ModelProperty;
+import org.oic.simulator.SimulatorResourceModel;
+import org.oic.simulator.StringProperty;
+
+import junit.framework.TestCase;
+
+public class ArrayPropertyTest extends TestCase {
+
+    protected void setUp() throws Exception {
+        super.setUp();
+    }
+
+    protected void tearDown() throws Exception {
+        super.tearDown();
+    }
+
+    public void testArrayProperty_P01() {
+        ArrayProperty.Builder builder = new ArrayProperty.Builder();
+        builder.setElementProperty(new IntegerProperty.Builder().build());
+        ArrayProperty property = builder.build();
+
+        assertNotNull(property);
+    }
+
+    public void testArrayProperty_N01() {
+        ArrayProperty.Builder builder = new ArrayProperty.Builder();
+        ArrayProperty property = builder.build();
+
+        assertNull(property);
+    }
+
+    public void testIsInteger_P01() {
+        ArrayProperty.Builder builder = new ArrayProperty.Builder();
+        builder.setElementProperty(new IntegerProperty.Builder().build());
+        ArrayProperty property = builder.build();
+
+        assertNotNull(property);
+        assertTrue(property.isArray());
+    }
+
+    public void testHasRange_P01() {
+        ArrayProperty.Builder builder = new ArrayProperty.Builder();
+        builder.setElementProperty(new IntegerProperty.Builder().build());
+        builder.setRange(1, 2);
+
+        ArrayProperty property = builder.build();
+
+        assertNotNull(property);
+        assertTrue(property.hasRange());
+    }
+
+    public void testGetRange_P01() {
+        ArrayProperty.Builder builder = new ArrayProperty.Builder();
+        builder.setElementProperty(new IntegerProperty.Builder().build());
+        builder.setRange(1, 2);
+
+        ArrayProperty property = builder.build();
+
+        assertNotNull(property);
+        assertEquals(property.minItems(), 1);
+        assertEquals(property.maxItems(), 2);
+    }
+
+    public void testIsVariable_P01() {
+        ArrayProperty.Builder builder = new ArrayProperty.Builder();
+        builder.setElementProperty(new IntegerProperty.Builder().build());
+        builder.setVariableSize(true);
+
+        ArrayProperty property = builder.build();
+
+        assertNotNull(property);
+        assertTrue(property.isVariable());
+    }
+
+    public void testIsUnique_P01() {
+        ArrayProperty.Builder builder = new ArrayProperty.Builder();
+        builder.setElementProperty(new IntegerProperty.Builder().build());
+        builder.setUnique(true);
+
+        ArrayProperty property = builder.build();
+
+        assertNotNull(property);
+        assertTrue(property.isUnique());
+    }
+
+    public void testValidateInt1DArray_P01() {
+        ArrayProperty.Builder arrayBuilder = new ArrayProperty.Builder();
+        IntegerProperty.Builder intBuilder = new IntegerProperty.Builder();
+        intBuilder.setRange(1, 10);
+        arrayBuilder.setElementProperty(intBuilder.build());
+
+        ArrayProperty property = arrayBuilder.build();
+
+        int[] value = { 1, 5, 7 };
+
+        assertNotNull(property);
+        assertTrue(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateInt1DArray_N01() {
+        ArrayProperty.Builder arrayBuilder = new ArrayProperty.Builder();
+        IntegerProperty.Builder intBuilder = new IntegerProperty.Builder();
+        intBuilder.setRange(1, 10);
+        arrayBuilder.setElementProperty(intBuilder.build());
+
+        ArrayProperty property = arrayBuilder.build();
+
+        int[] value = { 1, 15 };
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateInt1DArray_N02() {
+        ArrayProperty.Builder arrayBuilder = new ArrayProperty.Builder();
+        IntegerProperty.Builder intBuilder = new IntegerProperty.Builder();
+        intBuilder.setRange(1, 10);
+        arrayBuilder.setElementProperty(intBuilder.build());
+        arrayBuilder.setRange(1, 2);
+
+        ArrayProperty property = arrayBuilder.build();
+
+        int[] value = { 1, 5, 7 };
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateInt2DArray_P01() {
+        ArrayProperty.Builder arrayBuilder1 = new ArrayProperty.Builder();
+        ArrayProperty.Builder arrayBuilder2 = new ArrayProperty.Builder();
+        IntegerProperty.Builder intBuilder = new IntegerProperty.Builder();
+        intBuilder.setRange(1, 10);
+        arrayBuilder2.setElementProperty(intBuilder.build());
+        arrayBuilder1.setElementProperty(arrayBuilder2.build());
+
+        ArrayProperty property = arrayBuilder1.build();
+
+        int[][] value = { { 1 } };
+
+        assertNotNull(property);
+        assertTrue(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateInt2DArray_N01() {
+        ArrayProperty.Builder arrayBuilder1 = new ArrayProperty.Builder();
+        ArrayProperty.Builder arrayBuilder2 = new ArrayProperty.Builder();
+        IntegerProperty.Builder intBuilder = new IntegerProperty.Builder();
+        intBuilder.setRange(1, 10);
+        arrayBuilder2.setElementProperty(intBuilder.build());
+        arrayBuilder1.setElementProperty(arrayBuilder2.build());
+
+        ArrayProperty property = arrayBuilder1.build();
+
+        int[][] value = { { 15 } };
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateInt2DArray_N02() {
+        ArrayProperty.Builder arrayBuilder1 = new ArrayProperty.Builder();
+        ArrayProperty.Builder arrayBuilder2 = new ArrayProperty.Builder();
+        IntegerProperty.Builder intBuilder = new IntegerProperty.Builder();
+        intBuilder.setRange(1, 10);
+        arrayBuilder2.setElementProperty(intBuilder.build());
+        arrayBuilder2.setRange(1, 1);
+        arrayBuilder1.setElementProperty(arrayBuilder2.build());
+        arrayBuilder1.setRange(1, 1);
+
+        ArrayProperty property = arrayBuilder1.build();
+
+        int[][] value = { { 1, 2 } };
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateInt2DArray_N03() {
+        ArrayProperty.Builder arrayBuilder1 = new ArrayProperty.Builder();
+        ArrayProperty.Builder arrayBuilder2 = new ArrayProperty.Builder();
+        IntegerProperty.Builder intBuilder = new IntegerProperty.Builder();
+        intBuilder.setRange(1, 10);
+        arrayBuilder2.setElementProperty(intBuilder.build());
+        arrayBuilder2.setRange(1, 1);
+        arrayBuilder1.setElementProperty(arrayBuilder2.build());
+        arrayBuilder1.setRange(1, 1);
+
+        ArrayProperty property = arrayBuilder1.build();
+
+        int[][] value = { { 1 }, { 2 } };
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateDouble1DArray_P01() {
+        ArrayProperty.Builder arrayBuilder = new ArrayProperty.Builder();
+        DoubleProperty.Builder doubleBuilder = new DoubleProperty.Builder();
+        doubleBuilder.setRange(1.2, 10.5);
+        arrayBuilder.setElementProperty(doubleBuilder.build());
+
+        ArrayProperty property = arrayBuilder.build();
+
+        double[] value = { 1.3, 5.2, 10.4 };
+
+        assertNotNull(property);
+        assertTrue(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateDouble1DArray_N01() {
+        ArrayProperty.Builder arrayBuilder = new ArrayProperty.Builder();
+        DoubleProperty.Builder doubleBuilder = new DoubleProperty.Builder();
+        doubleBuilder.setRange(1.2, 10.5);
+        arrayBuilder.setElementProperty(doubleBuilder.build());
+
+        ArrayProperty property = arrayBuilder.build();
+
+        double[] value = { 5.5, 10.9 };
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateDouble1DArray_N02() {
+        ArrayProperty.Builder arrayBuilder = new ArrayProperty.Builder();
+        DoubleProperty.Builder doubleBuilder = new DoubleProperty.Builder();
+        doubleBuilder.setRange(1.2, 10.5);
+        arrayBuilder.setElementProperty(doubleBuilder.build());
+        arrayBuilder.setRange(1, 2);
+
+        ArrayProperty property = arrayBuilder.build();
+
+        double[] value = { 1.3, 5.2, 10.4 };
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateDouble2DArray_P01() {
+        ArrayProperty.Builder arrayBuilder1 = new ArrayProperty.Builder();
+        ArrayProperty.Builder arrayBuilder2 = new ArrayProperty.Builder();
+        DoubleProperty.Builder doubleBuilder = new DoubleProperty.Builder();
+        doubleBuilder.setRange(1.2, 10.5);
+        arrayBuilder2.setElementProperty(doubleBuilder.build());
+        arrayBuilder1.setElementProperty(arrayBuilder2.build());
+
+        ArrayProperty property = arrayBuilder1.build();
+
+        double[][] value = { { 5.5 } };
+
+        assertNotNull(property);
+        assertTrue(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateDouble2DArray_N01() {
+        ArrayProperty.Builder arrayBuilder1 = new ArrayProperty.Builder();
+        ArrayProperty.Builder arrayBuilder2 = new ArrayProperty.Builder();
+        DoubleProperty.Builder doubleBuilder = new DoubleProperty.Builder();
+        doubleBuilder.setRange(1.2, 10.5);
+        arrayBuilder2.setElementProperty(doubleBuilder.build());
+        arrayBuilder1.setElementProperty(arrayBuilder2.build());
+
+        ArrayProperty property = arrayBuilder1.build();
+
+        double[][] value = { { 10.9 } };
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateDouble2DArray_N02() {
+        ArrayProperty.Builder arrayBuilder1 = new ArrayProperty.Builder();
+        ArrayProperty.Builder arrayBuilder2 = new ArrayProperty.Builder();
+        DoubleProperty.Builder doubleBuilder = new DoubleProperty.Builder();
+        doubleBuilder.setRange(1.2, 10.5);
+        arrayBuilder2.setElementProperty(doubleBuilder.build());
+        arrayBuilder2.setRange(1, 1);
+        arrayBuilder1.setElementProperty(arrayBuilder2.build());
+        arrayBuilder1.setRange(1, 1);
+
+        ArrayProperty property = arrayBuilder1.build();
+
+        double[][] value = { { 1.5, 2.5 } };
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateDouble2DArray_N03() {
+        ArrayProperty.Builder arrayBuilder1 = new ArrayProperty.Builder();
+        ArrayProperty.Builder arrayBuilder2 = new ArrayProperty.Builder();
+        DoubleProperty.Builder doubleBuilder = new DoubleProperty.Builder();
+        doubleBuilder.setRange(1.2, 10.5);
+        arrayBuilder2.setElementProperty(doubleBuilder.build());
+        arrayBuilder2.setRange(1, 1);
+        arrayBuilder1.setElementProperty(arrayBuilder2.build());
+        arrayBuilder1.setRange(1, 1);
+
+        ArrayProperty property = arrayBuilder1.build();
+
+        double[][] value = { { 1.5 }, { 2.5 } };
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateBoolean1DArray_P01() {
+        ArrayProperty.Builder arrayBuilder = new ArrayProperty.Builder();
+        BooleanProperty.Builder booleanBuilder = new BooleanProperty.Builder();
+        arrayBuilder.setElementProperty(booleanBuilder.build());
+
+        ArrayProperty property = arrayBuilder.build();
+
+        boolean[] value = { true, false };
+
+        assertNotNull(property);
+        assertTrue(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateBoolean1DArray_N01() {
+        ArrayProperty.Builder arrayBuilder = new ArrayProperty.Builder();
+        BooleanProperty.Builder booleanBuilder = new BooleanProperty.Builder();
+        arrayBuilder.setElementProperty(booleanBuilder.build());
+        arrayBuilder.setRange(1, 1);
+
+        ArrayProperty property = arrayBuilder.build();
+
+        boolean[] value = { true, false };
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateBoolean2DArray_P01() {
+        ArrayProperty.Builder arrayBuilder1 = new ArrayProperty.Builder();
+        ArrayProperty.Builder arrayBuilder2 = new ArrayProperty.Builder();
+        BooleanProperty.Builder booleanBuilder = new BooleanProperty.Builder();
+        arrayBuilder2.setElementProperty(booleanBuilder.build());
+        arrayBuilder1.setElementProperty(arrayBuilder2.build());
+
+        ArrayProperty property = arrayBuilder1.build();
+
+        boolean[][] value = { { true, false } };
+
+        assertNotNull(property);
+        assertTrue(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateBoolean2DArray_N01() {
+        ArrayProperty.Builder arrayBuilder1 = new ArrayProperty.Builder();
+        ArrayProperty.Builder arrayBuilder2 = new ArrayProperty.Builder();
+        BooleanProperty.Builder booleanBuilder = new BooleanProperty.Builder();
+        arrayBuilder2.setElementProperty(booleanBuilder.build());
+        arrayBuilder2.setRange(1, 1);
+        arrayBuilder1.setElementProperty(arrayBuilder2.build());
+
+        ArrayProperty property = arrayBuilder1.build();
+
+        boolean[][] value = { { true, false } };
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateBoolean2DArray_N02() {
+        ArrayProperty.Builder arrayBuilder1 = new ArrayProperty.Builder();
+        ArrayProperty.Builder arrayBuilder2 = new ArrayProperty.Builder();
+        BooleanProperty.Builder booleanBuilder = new BooleanProperty.Builder();
+        arrayBuilder2.setElementProperty(booleanBuilder.build());
+        arrayBuilder2.setRange(1, 1);
+        arrayBuilder1.setElementProperty(arrayBuilder2.build());
+        arrayBuilder1.setRange(1, 1);
+
+        ArrayProperty property = arrayBuilder1.build();
+
+        boolean[][] value = { { true }, { false } };
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateString1DArray_P01() {
+        ArrayProperty.Builder arrayBuilder = new ArrayProperty.Builder();
+        StringProperty.Builder stringBuilder = new StringProperty.Builder();
+        stringBuilder.setRange(1, 5);
+        arrayBuilder.setElementProperty(stringBuilder.build());
+
+        ArrayProperty property = arrayBuilder.build();
+
+        String[] value = { "12345" };
+
+        assertNotNull(property);
+        assertTrue(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateString1DArray_N01() {
+        ArrayProperty.Builder arrayBuilder = new ArrayProperty.Builder();
+        StringProperty.Builder stringBuilder = new StringProperty.Builder();
+        stringBuilder.setRange(1, 5);
+        arrayBuilder.setElementProperty(stringBuilder.build());
+
+        ArrayProperty property = arrayBuilder.build();
+
+        String[] value = { "123456" };
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateString1DArray_N02() {
+        ArrayProperty.Builder arrayBuilder = new ArrayProperty.Builder();
+        StringProperty.Builder stringBuilder = new StringProperty.Builder();
+        stringBuilder.setRange(1, 5);
+        arrayBuilder.setElementProperty(stringBuilder.build());
+        arrayBuilder.setRange(1, 2);
+
+        ArrayProperty property = arrayBuilder.build();
+
+        String[] value = { "1", "2", "3", "4" };
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateString2DArray_P01() {
+        ArrayProperty.Builder arrayBuilder1 = new ArrayProperty.Builder();
+        ArrayProperty.Builder arrayBuilder2 = new ArrayProperty.Builder();
+        StringProperty.Builder stringBuilder = new StringProperty.Builder();
+        stringBuilder.setRange(1, 5);
+        arrayBuilder2.setElementProperty(stringBuilder.build());
+        arrayBuilder1.setElementProperty(arrayBuilder2.build());
+
+        ArrayProperty property = arrayBuilder1.build();
+
+        String[][] value = { { "12345" } };
+
+        assertNotNull(property);
+        assertTrue(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateString2DArray_N01() {
+        ArrayProperty.Builder arrayBuilder1 = new ArrayProperty.Builder();
+        ArrayProperty.Builder arrayBuilder2 = new ArrayProperty.Builder();
+        StringProperty.Builder stringBuilder = new StringProperty.Builder();
+        stringBuilder.setRange(1, 5);
+        arrayBuilder2.setElementProperty(stringBuilder.build());
+        arrayBuilder1.setElementProperty(arrayBuilder2.build());
+
+        ArrayProperty property = arrayBuilder1.build();
+
+        String[][] value = { { "123456" } };
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateString2DArray_N02() {
+        ArrayProperty.Builder arrayBuilder1 = new ArrayProperty.Builder();
+        ArrayProperty.Builder arrayBuilder2 = new ArrayProperty.Builder();
+        StringProperty.Builder stringBuilder = new StringProperty.Builder();
+        stringBuilder.setRange(1, 5);
+        arrayBuilder2.setElementProperty(stringBuilder.build());
+        arrayBuilder2.setRange(1, 1);
+        arrayBuilder1.setElementProperty(arrayBuilder2.build());
+        arrayBuilder1.setRange(1, 1);
+
+        ArrayProperty property = arrayBuilder1.build();
+
+        String[][] value = { { "1", "2" } };
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateString2DArray_N03() {
+        ArrayProperty.Builder arrayBuilder1 = new ArrayProperty.Builder();
+        ArrayProperty.Builder arrayBuilder2 = new ArrayProperty.Builder();
+        StringProperty.Builder stringBuilder = new StringProperty.Builder();
+        stringBuilder.setRange(1, 5);
+        arrayBuilder2.setElementProperty(stringBuilder.build());
+        arrayBuilder2.setRange(1, 1);
+        arrayBuilder1.setElementProperty(arrayBuilder2.build());
+        arrayBuilder1.setRange(1, 1);
+
+        ArrayProperty property = arrayBuilder1.build();
+
+        String[][] value = { { "1", "2" } };
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateModel1DArray_P01() {
+        ArrayProperty.Builder arrayBuilder = new ArrayProperty.Builder();
+
+        {
+            ModelProperty modelProperty = new ModelProperty();
+
+            IntegerProperty.Builder intBuilder = new IntegerProperty.Builder();
+            intBuilder.setRange(1, 10);
+            modelProperty.add("int", intBuilder.build(), true);
+
+            DoubleProperty.Builder doubleBuilder = new DoubleProperty.Builder();
+            doubleBuilder.setRange(1.5, 5.5);
+            modelProperty.add("double", doubleBuilder.build(), true);
+
+            BooleanProperty.Builder booleanBuilder = new BooleanProperty.Builder();
+            modelProperty.add("boolean", booleanBuilder.build(), true);
+
+            StringProperty.Builder stringBuilder = new StringProperty.Builder();
+            stringBuilder.setRange(1, 5);
+            modelProperty.add("string", stringBuilder.build(), true);
+
+            arrayBuilder.setElementProperty(modelProperty);
+        }
+
+        ArrayProperty property = arrayBuilder.build();
+
+        SimulatorResourceModel value = new SimulatorResourceModel();
+        try {
+            value.set("int", new AttributeValue(5));
+            value.set("double", new AttributeValue(3.5));
+            value.set("boolean", new AttributeValue(true));
+            value.set("string", new AttributeValue("12345"));
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        }
+
+        SimulatorResourceModel[] values = { value };
+
+        assertNotNull(property);
+        assertTrue(property.validate(new AttributeValue(values)));
+    }
+
+    public void testValidateModel1DArray_N01() {
+        ArrayProperty.Builder arrayBuilder = new ArrayProperty.Builder();
+
+        {
+            ModelProperty modelProperty = new ModelProperty();
+
+            IntegerProperty.Builder intBuilder = new IntegerProperty.Builder();
+            intBuilder.setRange(1, 10);
+            modelProperty.add("int", intBuilder.build(), true);
+
+            DoubleProperty.Builder doubleBuilder = new DoubleProperty.Builder();
+            doubleBuilder.setRange(1.5, 5.5);
+            modelProperty.add("double", doubleBuilder.build(), true);
+
+            BooleanProperty.Builder booleanBuilder = new BooleanProperty.Builder();
+            modelProperty.add("boolean", booleanBuilder.build(), true);
+
+            StringProperty.Builder stringBuilder = new StringProperty.Builder();
+            stringBuilder.setRange(1, 5);
+            modelProperty.add("string", stringBuilder.build(), true);
+
+            arrayBuilder.setElementProperty(modelProperty);
+        }
+
+        ArrayProperty property = arrayBuilder.build();
+
+        SimulatorResourceModel value = new SimulatorResourceModel();
+        try {
+            value.set("int", new AttributeValue(5));
+            value.set("double", new AttributeValue(3.5));
+            value.set("boolean", new AttributeValue(true));
+            value.set("string", new AttributeValue("123456"));
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        }
+
+        SimulatorResourceModel[] values = { value };
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue(values)));
+    }
+}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/AttributeValueTest.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/AttributeValueTest.java
new file mode 100644 (file)
index 0000000..754c2f3
--- /dev/null
@@ -0,0 +1,482 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator.test;
+
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.InvalidArgsException;
+import org.oic.simulator.SimulatorResourceModel;
+
+import junit.framework.TestCase;
+
+public class AttributeValueTest extends TestCase {
+    private static final String INT_KEY    = "Interger";
+    private static final String DOUBLE_KEY = "Double";
+    private static final String BOOL_KEY   = "Boolean";
+    private static final String STRING_KEY = "String";
+
+    protected void setUp() throws Exception {
+        super.setUp();
+    }
+
+    protected void tearDown() throws Exception {
+        super.tearDown();
+    }
+
+    public void testAttributeValueInt_P01() {
+        AttributeValue value = new AttributeValue(5);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.INTEGER
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.INTEGER
+                && value.typeInfo().mDepth == 0);
+    }
+
+    public void testAttributeValueInt_P02() {
+        AttributeValue attribute = new AttributeValue(new Integer(5));
+        assertNotNull(attribute);
+        assertTrue(attribute.typeInfo() != null
+                && attribute
+                        .typeInfo().mType == AttributeValue.ValueType.INTEGER
+                && attribute
+                        .typeInfo().mBaseType == AttributeValue.ValueType.INTEGER
+                && attribute.typeInfo().mDepth == 0);
+    }
+
+    public void testAttributeValueDouble_P01() {
+        AttributeValue value = new AttributeValue(5.00);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.DOUBLE
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.DOUBLE
+                && value.typeInfo().mDepth == 0);
+    }
+
+    public void testAttributeValueDouble_P02() {
+        AttributeValue value = new AttributeValue(new Double(5.00));
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.DOUBLE
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.DOUBLE
+                && value.typeInfo().mDepth == 0);
+    }
+
+    public void testAttributeValueBoolean_P01() {
+        AttributeValue value = new AttributeValue(true);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.BOOLEAN
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.BOOLEAN
+                && value.typeInfo().mDepth == 0);
+    }
+
+    public void testAttributeValueBoolean_P02() {
+        AttributeValue value = new AttributeValue(new Boolean(true));
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.BOOLEAN
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.BOOLEAN
+                && value.typeInfo().mDepth == 0);
+    }
+
+    public void testAttributeValueString_P01() {
+        AttributeValue value = new AttributeValue("String");
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.STRING
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.STRING
+                && value.typeInfo().mDepth == 0);
+    }
+
+    public void testAttributeValueString_P02() {
+        AttributeValue value = new AttributeValue(new String("String"));
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.STRING
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.STRING
+                && value.typeInfo().mDepth == 0);
+    }
+
+    public void testAttributeValueSimulatorResourceModel() {
+        SimulatorResourceModel model = new SimulatorResourceModel();
+        try {
+            model.set(INT_KEY, new AttributeValue(1));
+            model.set(DOUBLE_KEY, new AttributeValue(1.00));
+            model.set(BOOL_KEY, new AttributeValue(true));
+            model.set(STRING_KEY, new AttributeValue("string"));
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        }
+
+        if (model.size() != 4)
+            fail("Failed to construct model for continuing test!");
+
+        AttributeValue value = new AttributeValue(model);
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.RESOURCEMODEL
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.RESOURCEMODEL
+                && value.typeInfo().mDepth == 0);
+    }
+
+    public void testAttributeValueIntArray_P01() {
+        int[] array = { 1, 2, 3 };
+        AttributeValue value = new AttributeValue(array);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.INTEGER
+                && value.typeInfo().mDepth == 1);
+    }
+
+    public void testAttributeValueIntArray_P02() {
+        Integer[] array = { new Integer(1), new Integer(2), new Integer(3) };
+        AttributeValue value = new AttributeValue(array);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.INTEGER
+                && value.typeInfo().mDepth == 1);
+    }
+
+    public void testAttributeValueDoubleArray_P01() {
+        double[] array = { 1.00, 2.00, 3.00 };
+        AttributeValue value = new AttributeValue(array);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.DOUBLE
+                && value.typeInfo().mDepth == 1);
+    }
+
+    public void testAttributeValueDoubleArray_P02() {
+        Double[] array = { new Double(1.00), new Double(2.00),
+                new Double(3.00) };
+        AttributeValue value = new AttributeValue(array);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.DOUBLE
+                && value.typeInfo().mDepth == 1);
+    }
+
+    public void testAttributeValueBooleanArray_P01() {
+        boolean[] array = { true };
+        AttributeValue value = new AttributeValue(array);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.BOOLEAN
+                && value.typeInfo().mDepth == 1);
+    }
+
+    public void testAttributeValueBooleanArray_P02() {
+        boolean[] array = { new Boolean(true) };
+        AttributeValue value = new AttributeValue(array);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.BOOLEAN
+                && value.typeInfo().mDepth == 1);
+    }
+
+    public void testAttributeValueStringArray_P01() {
+        String[] array = { "string1", "string2" };
+        AttributeValue value = new AttributeValue(array);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.STRING
+                && value.typeInfo().mDepth == 1);
+    }
+
+    public void testAttributeValueStringArray_P02() {
+        String[] array = { new String("string1"), new String("string2") };
+        AttributeValue value = new AttributeValue(array);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.STRING
+                && value.typeInfo().mDepth == 1);
+    }
+
+    public void testAttributeValueSimulatorResourceModelArray() {
+        SimulatorResourceModel childModel = new SimulatorResourceModel();
+        try {
+            childModel.set(INT_KEY, new AttributeValue(1));
+            childModel.set(DOUBLE_KEY, new AttributeValue(1.00));
+            childModel.set(BOOL_KEY, new AttributeValue(true));
+            childModel.set(STRING_KEY, new AttributeValue("string"));
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        }
+
+        if (childModel.size() != 4)
+            fail("Failed to construct model for continuing test!");
+
+        SimulatorResourceModel[] array = { childModel };
+
+        AttributeValue value = new AttributeValue(array);
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.RESOURCEMODEL
+                && value.typeInfo().mDepth == 1);
+    }
+
+    public void testAttributeValueIntArrayArray_P01() {
+        int[][] array = { { 1, 2, 3 } };
+        AttributeValue value = new AttributeValue(array);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.INTEGER
+                && value.typeInfo().mDepth == 2);
+    }
+
+    public void testAttributeValueIntArrayArray_P02() {
+        Integer[][] array = {
+                { new Integer(1), new Integer(2), new Integer(3) } };
+        AttributeValue value = new AttributeValue(array);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.INTEGER
+                && value.typeInfo().mDepth == 2);
+    }
+
+    public void testAttributeValueDoubleArrayArray_P01() {
+        double[][] array = { { 1.00, 2.00, 3.00 } };
+        AttributeValue value = new AttributeValue(array);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.DOUBLE
+                && value.typeInfo().mDepth == 2);
+    }
+
+    public void testAttributeValueDoubleArrayArray_P02() {
+        Double[][] array = {
+                { new Double(1.00), new Double(2.00), new Double(3.00) } };
+        AttributeValue value = new AttributeValue(array);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.DOUBLE
+                && value.typeInfo().mDepth == 2);
+    }
+
+    public void testAttributeValueBooleanArrayArray_P01() {
+        boolean[][] array = { { true } };
+        AttributeValue value = new AttributeValue(array);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.BOOLEAN
+                && value.typeInfo().mDepth == 2);
+    }
+
+    public void testAttributeValueBooleanArrayArray_P02() {
+        Boolean[][] array = { { new Boolean(true) } };
+        AttributeValue value = new AttributeValue(array);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.BOOLEAN
+                && value.typeInfo().mDepth == 2);
+    }
+
+    public void testAttributeValueStringArrayArray_P01() {
+        String[][] array = { { "string" } };
+        AttributeValue value = new AttributeValue(array);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.STRING
+                && value.typeInfo().mDepth == 2);
+    }
+
+    public void testAttributeValueStringArrayArray_P02() {
+        String[][] array = { { new String("string") } };
+        AttributeValue value = new AttributeValue(array);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.STRING
+                && value.typeInfo().mDepth == 2);
+    }
+
+    public void testAttributeValueSimulatorResourceModelArrayArray() {
+        SimulatorResourceModel childModel = new SimulatorResourceModel();
+        try {
+            childModel.set(INT_KEY, new AttributeValue(1));
+            childModel.set(DOUBLE_KEY, new AttributeValue(1.00));
+            childModel.set(BOOL_KEY, new AttributeValue(true));
+            childModel.set(STRING_KEY, new AttributeValue("string"));
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        }
+
+        if (childModel.size() != 4)
+            fail("Failed to construct model for continuing test!");
+
+        SimulatorResourceModel[][] array = { { childModel } };
+
+        AttributeValue value = new AttributeValue(array);
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.RESOURCEMODEL
+                && value.typeInfo().mDepth == 2);
+    }
+
+    public void testAttributeValueIntArrayArrayArray_P01() {
+        int[][][] array = { { { 1, 2, 3 } } };
+        AttributeValue value = new AttributeValue(array);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.INTEGER
+                && value.typeInfo().mDepth == 3);
+    }
+
+    public void testAttributeValueIntArrayArrayArray_P02() {
+        Integer[][][] array = {
+                { { new Integer(1), new Integer(2), new Integer(3) } } };
+        AttributeValue value = new AttributeValue(array);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.INTEGER
+                && value.typeInfo().mDepth == 3);
+    }
+
+    public void testAttributeValueDoubleArrayArrayArray_P01() {
+        double[][][] array = { { { 1.00, 2.00, 3.00 } } };
+        AttributeValue value = new AttributeValue(array);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.DOUBLE
+                && value.typeInfo().mDepth == 3);
+    }
+
+    public void testAttributeValueDoubleArrayArrayArray_P02() {
+        Double[][][] array = {
+                { { new Double(1.00), new Double(2.00), new Double(3.00) } } };
+        AttributeValue value = new AttributeValue(array);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.DOUBLE
+                && value.typeInfo().mDepth == 3);
+    }
+
+    public void testAttributeValueBooleanArrayArrayArray_P01() {
+        boolean[][][] array = { { { true } } };
+        AttributeValue value = new AttributeValue(array);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.BOOLEAN
+                && value.typeInfo().mDepth == 3);
+    }
+
+    public void testAttributeValueBooleanArrayArrayArray_P02() {
+        Boolean[][][] array = { { { new Boolean(true) } } };
+        AttributeValue value = new AttributeValue(array);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.BOOLEAN
+                && value.typeInfo().mDepth == 3);
+    }
+
+    public void testAttributeValueStringArrayArrayArray_P01() {
+        String[][][] array = { { { "string" } } };
+        AttributeValue value = new AttributeValue(array);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.STRING
+                && value.typeInfo().mDepth == 3);
+    }
+
+    public void testAttributeValueStringArrayArrayArray_P02() {
+        String[][][] array = { { { new String("string") } } };
+        AttributeValue value = new AttributeValue(array);
+
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.STRING
+                && value.typeInfo().mDepth == 3);
+    }
+
+    public void testAttributeValueSimulatorResourceModelArrayArrayArray() {
+        SimulatorResourceModel childModel = new SimulatorResourceModel();
+        try {
+            childModel.set(INT_KEY, new AttributeValue(1));
+            childModel.set(DOUBLE_KEY, new AttributeValue(1.00));
+            childModel.set(BOOL_KEY, new AttributeValue(true));
+            childModel.set(STRING_KEY, new AttributeValue("string"));
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        }
+
+        if (childModel.size() != 4)
+            fail("Failed to construct model for continuing test!");
+
+        SimulatorResourceModel[][][] array = { { { childModel } } };
+
+        AttributeValue value = new AttributeValue(array);
+        assertNotNull(value);
+        assertTrue(value.typeInfo() != null
+                && value.typeInfo().mType == AttributeValue.ValueType.ARRAY
+                && value.typeInfo().mBaseType == AttributeValue.ValueType.RESOURCEMODEL
+                && value.typeInfo().mDepth == 3);
+    }
+}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/BooleanPropertyTest.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/BooleanPropertyTest.java
new file mode 100644 (file)
index 0000000..ff568ad
--- /dev/null
@@ -0,0 +1,77 @@
+/*
+ * 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.oic.simulator.test;
+
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.BooleanProperty;
+
+import junit.framework.TestCase;
+
+public class BooleanPropertyTest extends TestCase {
+
+    protected void setUp() throws Exception {
+        super.setUp();
+    }
+
+    protected void tearDown() throws Exception {
+        super.tearDown();
+    }
+
+    public void testBooleanProperty_P01() {
+        BooleanProperty property = new BooleanProperty.Builder().build();
+
+        assertNotNull(property);
+        assertEquals(property.getDefaultValue(), true);
+    }
+
+    public void testIsBoolean_P01() {
+        BooleanProperty property = new BooleanProperty.Builder().build();
+
+        assertNotNull(property);
+        assertTrue(property.isBoolean());
+    }
+
+    public void testGetDefaultValue_P02() {
+        BooleanProperty.Builder builder = new BooleanProperty.Builder();
+        builder.setDefaultValue(true);
+
+        BooleanProperty property = builder.build();
+
+        assertNotNull(property);
+        assertEquals(property.getDefaultValue(), true);
+    }
+
+    public void testValidate_P01() {
+        BooleanProperty.Builder builder = new BooleanProperty.Builder();
+        builder.setDefaultValue(true);
+
+        BooleanProperty property = builder.build();
+
+        assertNotNull(property);
+        assertTrue(property.validate(new AttributeValue(false)));
+    }
+
+    public void testValidate_P02() {
+        BooleanProperty.Builder builder = new BooleanProperty.Builder();
+        builder.setDefaultValue(true);
+
+        BooleanProperty property = builder.build();
+
+        assertNotNull(property);
+        assertTrue(property.validate(false));
+    }
+}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/DoublePropertyTest.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/DoublePropertyTest.java
new file mode 100644 (file)
index 0000000..26c1573
--- /dev/null
@@ -0,0 +1,185 @@
+/*
+ * 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.oic.simulator.test;
+
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.DoubleProperty;
+
+import junit.framework.TestCase;
+
+public class DoublePropertyTest extends TestCase {
+
+    protected void setUp() throws Exception {
+        super.setUp();
+    }
+
+    protected void tearDown() throws Exception {
+        super.tearDown();
+    }
+
+    public void testDoubleProperty_P01() {
+        DoubleProperty property = new DoubleProperty.Builder().build();
+
+        assertNotNull(property);
+        assertEquals(property.getDefaultValue(), 0.0);
+    }
+
+    public void testIsDouble_P01() {
+        DoubleProperty property = new DoubleProperty.Builder().build();
+
+        assertNotNull(property);
+        assertTrue(property.isDouble());
+    }
+
+    public void testGetDefaultValue_P02() {
+        DoubleProperty.Builder builder = new DoubleProperty.Builder();
+        builder.setDefaultValue(3.142);
+
+        DoubleProperty property = builder.build();
+
+        assertNotNull(property);
+        assertEquals(property.getDefaultValue(), 3.142);
+    }
+
+    public void testHasRange_P01() {
+        DoubleProperty.Builder builder = new DoubleProperty.Builder();
+        builder.setRange(1.0, 10.25);
+
+        DoubleProperty property = builder.build();
+
+        assertNotNull(property);
+        assertTrue(property.hasRange());
+    }
+
+    public void testGetRange_P03() {
+        DoubleProperty.Builder builder = new DoubleProperty.Builder();
+        builder.setRange(1.0, 10.25);
+
+        DoubleProperty property = builder.build();
+
+        assertNotNull(property);
+        assertEquals(property.min(), 1.0);
+        assertEquals(property.max(), 10.25);
+    }
+
+    public void testHasValues_P01() {
+        DoubleProperty.Builder builder = new DoubleProperty.Builder();
+        double[] values = { 1.5, 2, 3.2 };
+        builder.setValues(values);
+
+        DoubleProperty property = builder.build();
+
+        assertNotNull(property);
+        assertTrue(property.hasValues());
+    }
+
+    public void testGetValues_P04() {
+        DoubleProperty.Builder builder = new DoubleProperty.Builder();
+        double[] values = { 1.5, 2, 3.2 };
+        builder.setValues(values);
+
+        DoubleProperty property = builder.build();
+
+        assertNotNull(property);
+        assertNotNull(property.getValues());
+        assertEquals(property.getValues().length, 3);
+    }
+
+    public void testValidate_P04() {
+        DoubleProperty.Builder builder = new DoubleProperty.Builder();
+        builder.setRange(1.0, 10.25);
+
+        DoubleProperty property = builder.build();
+
+        assertNotNull(property);
+        assertTrue(property.validate(new AttributeValue(3.25)));
+    }
+
+    public void testValidate_P05() {
+        DoubleProperty.Builder builder = new DoubleProperty.Builder();
+        builder.setRange(1.0, 10.25);
+
+        DoubleProperty property = builder.build();
+
+        assertNotNull(property);
+        assertTrue(property.validate(3.25));
+    }
+
+    public void testValidate_P06() {
+        DoubleProperty.Builder builder = new DoubleProperty.Builder();
+        double[] values = { 1.5, 2, 3.2 };
+        builder.setValues(values);
+
+        DoubleProperty property = builder.build();
+
+        assertNotNull(property);
+        assertTrue(property.validate(new AttributeValue(3.2)));
+    }
+
+    public void testValidate_P07() {
+        DoubleProperty.Builder builder = new DoubleProperty.Builder();
+        double[] values = { 1.5, 2, 3.2 };
+        builder.setValues(values);
+
+        DoubleProperty property = builder.build();
+
+        assertNotNull(property);
+        assertTrue(property.validate(3.2));
+    }
+
+    public void testValidate_N01() {
+        DoubleProperty.Builder builder = new DoubleProperty.Builder();
+        builder.setRange(1.0, 10.25);
+
+        DoubleProperty property = builder.build();
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue(11.5)));
+    }
+
+    public void testValidate_N02() {
+        DoubleProperty.Builder builder = new DoubleProperty.Builder();
+        builder.setRange(1.0, 10.25);
+
+        DoubleProperty property = builder.build();
+
+        assertNotNull(property);
+        assertFalse(property.validate(11.5));
+    }
+
+    public void testValidate_N04() {
+        DoubleProperty.Builder builder = new DoubleProperty.Builder();
+        double[] values = { 1.5, 2, 3.2 };
+        builder.setValues(values);
+
+        DoubleProperty property = builder.build();
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue(11.25)));
+    }
+
+    public void testValidate_N05() {
+        DoubleProperty.Builder builder = new DoubleProperty.Builder();
+        double[] values = { 1.5, 2, 3.2 };
+        builder.setValues(values);
+
+        DoubleProperty property = builder.build();
+
+        assertNotNull(property);
+        assertFalse(property.validate(11.25));
+    }
+}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ExceptionType.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ExceptionType.java
new file mode 100644 (file)
index 0000000..3429ea5
--- /dev/null
@@ -0,0 +1,21 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator.test;
+
+public enum ExceptionType {
+    UNKNOWN, INVALID_ARGS, NOT_SUPPORTED, OPERATION_IN_PROGRESS, SIMULATOR
+}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/FindResourceListener.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/FindResourceListener.java
deleted file mode 100644 (file)
index a8469aa..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.test;
-
-import java.util.concurrent.CountDownLatch;
-
-import org.oic.simulator.clientcontroller.IFindResourceListener;
-import org.oic.simulator.clientcontroller.SimulatorRemoteResource;
-
-/**
- * This class implements methods for receiving notification when
- * resources are discovered in network.
- */
-public class FindResourceListener implements IFindResourceListener
-{
-
-    private CountDownLatch lockObject;
-    private SimulatorRemoteResourceObject simulatorRemoteResource;
-
-    public FindResourceListener(CountDownLatch lockObject, SimulatorRemoteResourceObject simulatorRemoteResource)
-    {
-        this.lockObject = lockObject;
-        this.simulatorRemoteResource = simulatorRemoteResource;
-    }
-
-    @Override
-    public void onResourceCallback(SimulatorRemoteResource resource)
-    {
-        simulatorRemoteResource.setSimulatorRemoteResource(resource);
-
-        lockObject.countDown();
-    }
-}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/IntegerPropertyTest.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/IntegerPropertyTest.java
new file mode 100644 (file)
index 0000000..e952dfe
--- /dev/null
@@ -0,0 +1,186 @@
+/*
+ * 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.oic.simulator.test;
+
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.IntegerProperty;
+
+import junit.framework.TestCase;
+
+public class IntegerPropertyTest extends TestCase {
+
+    protected void setUp() throws Exception {
+        super.setUp();
+    }
+
+    protected void tearDown() throws Exception {
+        super.tearDown();
+    }
+
+    public void testIntegerProperty_P01() {
+        IntegerProperty property = new IntegerProperty.Builder().build();
+
+        assertNotNull(property);
+        assertEquals(property.getDefaultValue(), 0);
+    }
+
+    public void testIsInteger_P01() {
+        IntegerProperty property = new IntegerProperty.Builder().build();
+
+        assertNotNull(property);
+        assertTrue(property.isInteger());
+    }
+
+    public void testGetDefaultValue_P02() {
+        IntegerProperty.Builder builder = new IntegerProperty.Builder();
+        builder.setDefaultValue(10);
+
+        IntegerProperty property = builder.build();
+
+        assertNotNull(property);
+        assertEquals(property.getDefaultValue(), 10);
+    }
+
+    public void testHasRange_P01() {
+        IntegerProperty.Builder builder = new IntegerProperty.Builder();
+        builder.setRange(1, 10);
+
+        IntegerProperty property = builder.build();
+
+        assertNotNull(property);
+        assertTrue(property.hasRange());
+    }
+
+    public void testGetRange_P03() {
+        IntegerProperty.Builder builder = new IntegerProperty.Builder();
+        builder.setRange(1, 10);
+
+        IntegerProperty property = builder.build();
+
+        assertNotNull(property);
+        assertEquals(property.min(), 1);
+        assertEquals(property.max(), 10);
+    }
+
+    public void testHasValues_P01() {
+        IntegerProperty.Builder builder = new IntegerProperty.Builder();
+        int[] values = { 1, 2, 3 };
+        builder.setValues(values);
+
+        IntegerProperty property = builder.build();
+
+        assertNotNull(property);
+        assertTrue(property.hasValues());
+    }
+
+    public void testGetValues_P04() {
+        IntegerProperty.Builder builder = new IntegerProperty.Builder();
+        int[] values = { 1, 2, 3 };
+        builder.setValues(values);
+
+        IntegerProperty property = builder.build();
+
+        assertNotNull(property);
+        assertEquals(property.getDefaultValue(), 0);
+        assertNotNull(property.getValues());
+        assertEquals(property.getValues().length, 3);
+    }
+
+    public void testValidate_P04() {
+        IntegerProperty.Builder builder = new IntegerProperty.Builder();
+        builder.setRange(1, 10);
+
+        IntegerProperty property = builder.build();
+
+        assertNotNull(property);
+        assertTrue(property.validate(new AttributeValue(3)));
+    }
+
+    public void testValidate_P05() {
+        IntegerProperty.Builder builder = new IntegerProperty.Builder();
+        builder.setRange(1, 10);
+
+        IntegerProperty property = builder.build();
+
+        assertNotNull(property);
+        assertTrue(property.validate(3));
+    }
+
+    public void testValidate_P06() {
+        IntegerProperty.Builder builder = new IntegerProperty.Builder();
+        int[] values = { 1, 2, 3 };
+        builder.setValues(values);
+
+        IntegerProperty property = builder.build();
+
+        assertNotNull(property);
+        assertTrue(property.validate(new AttributeValue(3)));
+    }
+
+    public void testValidate_P07() {
+        IntegerProperty.Builder builder = new IntegerProperty.Builder();
+        int[] values = { 1, 2, 3 };
+        builder.setValues(values);
+
+        IntegerProperty property = builder.build();
+
+        assertNotNull(property);
+        assertTrue(property.validate(3));
+    }
+
+    public void testValidate_N01() {
+        IntegerProperty.Builder builder = new IntegerProperty.Builder();
+        builder.setRange(1, 10);
+
+        IntegerProperty property = builder.build();
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue(11)));
+    }
+
+    public void testValidate_N02() {
+        IntegerProperty.Builder builder = new IntegerProperty.Builder();
+        builder.setRange(1, 10);
+
+        IntegerProperty property = builder.build();
+
+        assertNotNull(property);
+        assertFalse(property.validate(11));
+    }
+
+    public void testValidate_N04() {
+        IntegerProperty.Builder builder = new IntegerProperty.Builder();
+        int[] values = { 1, 2, 3 };
+        builder.setValues(values);
+
+        IntegerProperty property = builder.build();
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue(11)));
+    }
+
+    public void testValidate_N05() {
+        IntegerProperty.Builder builder = new IntegerProperty.Builder();
+        int[] values = { 1, 2, 3 };
+        builder.setValues(values);
+
+        IntegerProperty property = builder.build();
+
+        assertNotNull(property);
+        assertFalse(property.validate(11));
+    }
+}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ModelPropertyTest.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ModelPropertyTest.java
new file mode 100644 (file)
index 0000000..b3549f9
--- /dev/null
@@ -0,0 +1,240 @@
+/*
+ * 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.oic.simulator.test;
+
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.BooleanProperty;
+import org.oic.simulator.DoubleProperty;
+import org.oic.simulator.IntegerProperty;
+import org.oic.simulator.InvalidArgsException;
+import org.oic.simulator.ModelProperty;
+import org.oic.simulator.SimulatorResourceModel;
+import org.oic.simulator.StringProperty;
+
+import junit.framework.TestCase;
+
+public class ModelPropertyTest extends TestCase {
+
+    protected void setUp() throws Exception {
+        super.setUp();
+    }
+
+    protected void tearDown() throws Exception {
+        super.tearDown();
+    }
+
+    public void testModelProperty_P01() {
+        ModelProperty property = new ModelProperty();
+
+        assertNotNull(property);
+    }
+
+    public void testIsModel_P01() {
+        ModelProperty property = new ModelProperty();
+
+        assertNotNull(property);
+        assertTrue(property.isModel());
+    }
+
+    public void testAdd_P01() {
+        ModelProperty property = new ModelProperty();
+        boolean result = property.add("int",
+                new IntegerProperty.Builder().build(), true);
+
+        assertTrue(result);
+        assertNotNull(property.get("int"));
+    }
+
+    public void testAdd_N01() {
+        ModelProperty property = new ModelProperty();
+        boolean result = property.add(null,
+                new IntegerProperty.Builder().build(), true);
+
+        assertFalse(result);
+        assertNull(property.get("int"));
+    }
+
+    public void testAdd_N02() {
+        ModelProperty property = new ModelProperty();
+        boolean result = property.add("int", null, true);
+
+        assertFalse(result);
+        assertNull(property.get("int"));
+    }
+
+    public void testRemove_P01() {
+        ModelProperty property = new ModelProperty();
+        boolean result = property.add("int",
+                new IntegerProperty.Builder().build(), true);
+        assertTrue(result);
+
+        property.remove("int");
+        assertNull(property.get("int"));
+    }
+
+    public void testRemove_N01() {
+        ModelProperty property = new ModelProperty();
+        boolean result = property.add("int",
+                new IntegerProperty.Builder().build(), true);
+        assertTrue(result);
+
+        property.remove("wrong-key");
+        assertNotNull(property.get("int"));
+    }
+
+    public void testRemove_N02() {
+        ModelProperty property = new ModelProperty();
+        boolean result = property.add("int",
+                new IntegerProperty.Builder().build(), true);
+        assertTrue(result);
+
+        property.remove(null);
+        assertNotNull(property.get("int"));
+    }
+
+    public void testGet_P01() {
+        ModelProperty property = new ModelProperty();
+        boolean result = property.add("int",
+                new IntegerProperty.Builder().build(), true);
+        assertTrue(result);
+
+        assertNotNull(property.get("int"));
+    }
+
+    public void testGetChildProperties_P01() {
+        ModelProperty property = new ModelProperty();
+
+        boolean result = property.add("int",
+                new IntegerProperty.Builder().build(), true);
+        assertTrue(result);
+
+        result = property.add("double", new DoubleProperty.Builder().build(),
+                true);
+        assertTrue(result);
+
+        assertNotNull(property.getChildProperties());
+        assertEquals(property.getChildProperties().size(), 2);
+    }
+
+    public void testIsRequired_P01() {
+        ModelProperty property = new ModelProperty();
+
+        boolean result = property.add("int",
+                new IntegerProperty.Builder().build(), true);
+        assertTrue(result);
+
+        result = property.add("double", new DoubleProperty.Builder().build(),
+                false);
+        assertTrue(result);
+
+        assertEquals(property.isRequired("int"), true);
+        assertEquals(property.isRequired("double"), false);
+    }
+
+    public void testValidate_P01() {
+        ModelProperty modelProperty = new ModelProperty();
+
+        IntegerProperty.Builder intBuilder = new IntegerProperty.Builder();
+        intBuilder.setRange(1, 10);
+        modelProperty.add("int", intBuilder.build(), true);
+
+        DoubleProperty.Builder doubleBuilder = new DoubleProperty.Builder();
+        doubleBuilder.setRange(1.5, 5.5);
+        modelProperty.add("double", doubleBuilder.build(), true);
+
+        BooleanProperty.Builder booleanBuilder = new BooleanProperty.Builder();
+        modelProperty.add("boolean", booleanBuilder.build(), true);
+
+        StringProperty.Builder stringBuilder = new StringProperty.Builder();
+        stringBuilder.setRange(1, 5);
+        modelProperty.add("string", stringBuilder.build(), true);
+
+        SimulatorResourceModel value = new SimulatorResourceModel();
+        try {
+            value.set("int", new AttributeValue(5));
+            value.set("double", new AttributeValue(3.5));
+            value.set("boolean", new AttributeValue(true));
+            value.set("string", new AttributeValue("12345"));
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(modelProperty.validate(new AttributeValue(value)));
+    }
+
+    public void testValidate_P02() {
+        ModelProperty modelProperty = new ModelProperty();
+
+        IntegerProperty.Builder intBuilder = new IntegerProperty.Builder();
+        intBuilder.setRange(1, 10);
+        modelProperty.add("int", intBuilder.build(), true);
+
+        DoubleProperty.Builder doubleBuilder = new DoubleProperty.Builder();
+        doubleBuilder.setRange(1.5, 5.5);
+        modelProperty.add("double", doubleBuilder.build(), true);
+
+        BooleanProperty.Builder booleanBuilder = new BooleanProperty.Builder();
+        modelProperty.add("boolean", booleanBuilder.build(), true);
+
+        StringProperty.Builder stringBuilder = new StringProperty.Builder();
+        stringBuilder.setRange(1, 5);
+        modelProperty.add("string", stringBuilder.build(), true);
+
+        SimulatorResourceModel value = new SimulatorResourceModel();
+        try {
+            value.set("int", new AttributeValue(5));
+            value.set("double", new AttributeValue(3.5));
+            value.set("boolean", new AttributeValue(true));
+            value.set("string", new AttributeValue("12345"));
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(modelProperty.validate(value));
+    }
+
+    public void testValidate_N01() {
+        ModelProperty modelProperty = new ModelProperty();
+
+        IntegerProperty.Builder intBuilder = new IntegerProperty.Builder();
+        intBuilder.setRange(1, 10);
+        modelProperty.add("int", intBuilder.build(), true);
+
+        DoubleProperty.Builder doubleBuilder = new DoubleProperty.Builder();
+        doubleBuilder.setRange(1.5, 5.5);
+        modelProperty.add("double", doubleBuilder.build(), true);
+
+        BooleanProperty.Builder booleanBuilder = new BooleanProperty.Builder();
+        modelProperty.add("boolean", booleanBuilder.build(), true);
+
+        StringProperty.Builder stringBuilder = new StringProperty.Builder();
+        stringBuilder.setRange(1, 5);
+        modelProperty.add("string", stringBuilder.build(), true);
+
+        SimulatorResourceModel value = new SimulatorResourceModel();
+        try {
+            value.set("int", new AttributeValue(5));
+            value.set("double", new AttributeValue(3.5));
+            value.set("boolean", new AttributeValue(true));
+            value.set("string", new AttributeValue("123456"));
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        }
+
+        assertFalse(modelProperty.validate(new AttributeValue(value)));
+    }
+}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ResourceModelChangeListener.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ResourceModelChangeListener.java
deleted file mode 100644 (file)
index 9c199b8..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.test;
-
-import org.oic.simulator.SimulatorResourceModel;
-import org.oic.simulator.serviceprovider.IResourceModelChangedListener;
-
-/**
- * This class implements methods for receiving notification when
- *  resource model is changed.
- */
-public class ResourceModelChangeListener implements IResourceModelChangedListener
-{
-
-    private ResourceModelObject toReturn;
-
-    public ResourceModelChangeListener(Object toReturn)
-    {
-        this.toReturn = (ResourceModelObject)toReturn;
-    }
-
-    @Override
-    public void onResourceModelChanged(String resourceURI, SimulatorResourceModel resourceModel)
-    {
-        toReturn.setResourceURI(resourceURI);
-        toReturn.setResourceModel(resourceModel);
-    }
-}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ResourceModelObject.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ResourceModelObject.java
deleted file mode 100644 (file)
index b636d6a..0000000
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.test;
-
-import org.oic.simulator.SimulatorResourceModel;
-
-/**
- * This class implements methods for setting/getting
- * resource model.
- */
-public class ResourceModelObject
-{
-    private String resourceURI;
-    private SimulatorResourceModel resourceModel;
-
-    public void setResourceURI(String resourceURI)
-    {
-        this.resourceURI = resourceURI;
-    }
-
-    public String getResourceURI()
-    {
-        return resourceURI;
-    }
-
-    public void setResourceModel(SimulatorResourceModel resourceModel)
-    {
-        this.resourceModel = resourceModel;
-    }
-
-    public SimulatorResourceModel getResourceModel()
-    {
-        return resourceModel;
-    }
-}
index 7fb25db..1014320 100644 (file)
 
 package org.oic.simulator.test;
 
+import java.util.Vector;
 import java.util.concurrent.CountDownLatch;
-import junit.framework.TestCase;
+import java.util.concurrent.TimeUnit;
 
+import org.oic.simulator.DeviceInfo;
+import org.oic.simulator.DeviceListener;
+import org.oic.simulator.InvalidArgsException;
 import org.oic.simulator.PlatformInfo;
+import org.oic.simulator.PlatformListener;
+import org.oic.simulator.SimulatorException;
 import org.oic.simulator.SimulatorManager;
-import org.oic.simulator.serviceprovider.SimulatorResourceServer;
+import org.oic.simulator.client.FindResourceListener;
+import org.oic.simulator.client.SimulatorRemoteResource;
+import org.oic.simulator.server.SimulatorResource;
+import org.oic.simulator.utils.ObjectHolder;
+import org.oic.simulator.utils.SampleSingleResource;
+
+import junit.framework.TestCase;
 
 /**
- * This class tests the functionality of Simulator Manager
- * class APIs.
+ * This class tests the functionality of Simulator Manager class APIs.
  */
-public class SimulatorManagerTest extends TestCase
-{
-
-    private static final String CONFIG_PATH = "./ramls/simple-light.raml";
-    private static final String RESOURCE_TYPE = "oic.r.light";
-
-    private CountDownLatch lockObject;
-    private ResourceModelObject resourceModelObject;
-    private ResourceModelChangeListener resourceModelChangeListener;
-
-
-    static
-    {
-        System.loadLibrary("SimulatorManager");
-    }
+public class SimulatorManagerTest extends TestCase {
+    private static final String SINGLE_RES_RAML     = "./ramls/oic.r.light.raml";
+    private static final String COLLECTION_RES_RAML = "./ramls/oic.d.airconditioner.raml";
 
     @Override
-    protected void setUp() throws Exception
-    {
+    protected void setUp() throws Exception {
         super.setUp();
-
-        lockObject = new CountDownLatch(1);
     }
 
     @Override
-    protected void tearDown() throws Exception
-    {
+    protected void tearDown() throws Exception {
         super.tearDown();
-
-        resourceModelObject = null;
-        resourceModelChangeListener = null;
-        lockObject = null;
     }
 
-    private SimulatorResourceServer createResource()
-    {
-        resourceModelObject = new ResourceModelObject();
-        resourceModelChangeListener = new ResourceModelChangeListener(resourceModelObject);
+    public void testCreateResource_P01() {
+        SimulatorResource resource = null;
+        SimulatorResource.Type resType = SimulatorResource.Type.SINGLE;
 
-        SimulatorResourceServer simulatorResourceServer = null;
-        try
-        {
-            simulatorResourceServer = SimulatorManager.createResource(CONFIG_PATH, resourceModelChangeListener);
-        }
-        catch (Exception e)
-        {
+        try {
+            resource = SimulatorManager.createResource(SINGLE_RES_RAML);
+            resType = resource.getType();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
             e.printStackTrace();
         }
 
-        return simulatorResourceServer;
+        assertNotNull(resource);
+        assertTrue(resType == SimulatorResource.Type.SINGLE);
     }
 
-    private SimulatorResourceServer[] createResources(int n)
-    {
-        resourceModelObject = new ResourceModelObject();
-        resourceModelChangeListener = new ResourceModelChangeListener(resourceModelObject);
+    public void testCreateResource_P02() {
+        SimulatorResource resource = null;
+        SimulatorResource.Type resType = SimulatorResource.Type.COLLECTION;
 
-        SimulatorResourceServer[] simulatorResourceServers = null;
-        try
-        {
-            simulatorResourceServers = SimulatorManager.createResource(CONFIG_PATH, n, resourceModelChangeListener);
-        }
-        catch (Exception e)
-        {
+        try {
+            resource = SimulatorManager.createResource(COLLECTION_RES_RAML);
+            resType = resource.getType();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
             e.printStackTrace();
         }
 
-        return simulatorResourceServers;
+        assertNotNull(resource);
+        assertTrue(resType == SimulatorResource.Type.COLLECTION);
     }
 
-    private void deleteResource(SimulatorResourceServer sim)
-    {
-        try
-        {
-            SimulatorManager.deleteResource(sim);
-        }
-        catch (Exception e)
-        {
-            e.printStackTrace();
+    public void testCreateResource_N01() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            String configPath = "";
+            SimulatorManager.createResource(configPath);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
         }
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
     }
 
-    public void testCreateResource_P01()
-    {
-        SimulatorResourceServer simulatorResourceServer = createResource();
+    public void testCreateResource_N02() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
 
-        assertNotNull(simulatorResourceServer);
+        try {
+            SimulatorManager.createResource(null);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
 
-        deleteResource(simulatorResourceServer);
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
     }
 
-    /**
-     * When config path is empty
-     */
-    public void testCreateResource_N01()
-    {
-        String configPath = "";
-        boolean result = false;
+    public void testCreateResourceWithCount_P01() {
+        Vector<SimulatorResource> resources = null;
+        SimulatorResource.Type resType = SimulatorResource.Type.SINGLE;
 
-        resourceModelObject = new ResourceModelObject();
-        resourceModelChangeListener = new ResourceModelChangeListener(resourceModelObject);
-
-        SimulatorResourceServer simulatorResourceServer = null;
-        try
-        {
-            simulatorResourceServer = SimulatorManager.createResource(configPath, resourceModelChangeListener);
+        try {
+            resources = SimulatorManager.createResource(SINGLE_RES_RAML, 1);
+            resType = resources.elementAt(0).getType();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
         }
-        catch (Exception e)
-        {
-            result = true;
+
+        assertNotNull(resources);
+        assertTrue(resources.size() == 1);
+        assertTrue(resType == SimulatorResource.Type.SINGLE);
+    }
+
+    public void testCreateResourceWithCount_P02() {
+        Vector<SimulatorResource> resources = null;
+        SimulatorResource.Type resType = SimulatorResource.Type.COLLECTION;
+
+        try {
+            resources = SimulatorManager.createResource(COLLECTION_RES_RAML, 1);
+            resType = resources.elementAt(0).getType();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
         }
 
-        assertTrue(simulatorResourceServer == null && result);
+        assertNotNull(resources);
+        assertTrue(resources.size() == 1);
+        assertTrue(resType == SimulatorResource.Type.COLLECTION);
     }
 
-    /**
-     * When listener is not set. Passed null
-     */
-    public void testCreateResource_N02()
-    {
-        boolean result = false;
-        SimulatorResourceServer simulatorResourceServer = null;
-        try
-        {
-            simulatorResourceServer = SimulatorManager.createResource(CONFIG_PATH, null);
+    public void testCreateResourceWithCount_N01() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            String configPath = "";
+            SimulatorManager.createResource(configPath, 1);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
         }
-        catch (Exception e)
-        {
-            result = true;
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
+    }
+
+    public void testCreateResourceWithCount_N02() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            SimulatorManager.createResource(null, 1);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
         }
-        assertTrue(simulatorResourceServer == null && result);
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
     }
 
-    /**
-     * When listener and config path are set to null
-     */
-    public void testCreateResource_N03()
-    {
-        boolean result = false;
-        SimulatorResourceServer simulatorResourceServer = null;
-        try
-        {
-            simulatorResourceServer = SimulatorManager.createResource(null, null);
+    public void testCreateResourceWithCount_N03() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            SimulatorManager.createResource(SINGLE_RES_RAML, 0);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
         }
-        catch (Exception e)
-        {
-            result = true;
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
+    }
+
+    public void testCreateResourceWithCount_N04() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            SimulatorManager.createResource(SINGLE_RES_RAML, -1);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
         }
-        assertTrue(simulatorResourceServer == null && result);
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
     }
 
-    public void testCreateResourceCount_P01()
-    {
-        int count = 5;
+    public void testCreateResourceByType_P01() {
+        SimulatorResource resource = null;
+        SimulatorResource.Type resType = SimulatorResource.Type.SINGLE;
 
-        SimulatorResourceServer[] simulatorResourceServers = createResources(count);
+        try {
+            String name = "test-singleresource";
+            String uri = "/test/singleresource";
+            String resourceType = "test.singleresource";
 
-        assertTrue(simulatorResourceServers != null && simulatorResourceServers.length == 5);
+            resource = SimulatorManager.createResource(
+                    SimulatorResource.Type.SINGLE, name, uri, resourceType);
+            resType = resource.getType();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
 
-        for(SimulatorResourceServer srs : simulatorResourceServers)
-            deleteResource(srs);
+        assertNotNull(resource);
+        assertTrue(resType == SimulatorResource.Type.SINGLE);
     }
 
-    /**
-     * When config path is empty
-     */
-    public void testCreateResourceCount_N01()
-    {
-        int count = 5;
-        String configPath = "";
-        boolean result = false;
+    public void testCreateResourceByType_P02() {
+        SimulatorResource resource = null;
+        SimulatorResource.Type resType = SimulatorResource.Type.COLLECTION;
 
-        resourceModelObject = new ResourceModelObject();
-        resourceModelChangeListener = new ResourceModelChangeListener(resourceModelObject);
+        try {
+            String name = "test-collectionresource";
+            String uri = "/test/collectionresource";
+            String resourceType = "test.collectionresource";
 
-        SimulatorResourceServer[] simulatorResourceServers = null;
-        try
-        {
-            SimulatorManager.setDeviceInfo("test");
-            simulatorResourceServers = SimulatorManager.createResource(configPath, count, resourceModelChangeListener);
-        }
-        catch (Exception e)
-        {
-            result = true;
+            resource = SimulatorManager.createResource(
+                    SimulatorResource.Type.COLLECTION, name, uri, resourceType);
+            resType = resource.getType();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
         }
 
-        assertTrue(simulatorResourceServers == null && result);
+        assertNotNull(resource);
+        assertTrue(resType == SimulatorResource.Type.COLLECTION);
     }
 
-    /**
-     * When listener is not set
-     */
-    public void testCreateResourceCount_N02()
-    {
-        int count = 5;
-        boolean result = false;
+    public void testCreateResourceByType_N01() {
+        ExceptionType exType = ExceptionType.INVALID_ARGS;
 
-        SimulatorResourceServer[] simulatorResourceServers = null;
-        try
-        {
-            simulatorResourceServers = SimulatorManager.createResource(CONFIG_PATH, count, null);
-        }
-        catch (Exception e)
-        {
-            result = true;
+        try {
+            String name = "";
+            String uri = "/test/resource";
+            String resourceType = "test.resource";
+
+            SimulatorManager.createResource(SimulatorResource.Type.SINGLE,
+                    name, uri, resourceType);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
         }
 
-        assertTrue(simulatorResourceServers == null && result);
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
     }
 
-    /**
-     * When configPath and listener are set to null
-     */
-    public void testCreateResourceCount_N03()
-    {
-        int count = 5;
-        boolean result = false;
+    public void testCreateResourceByType_N02() {
+        ExceptionType exType = ExceptionType.INVALID_ARGS;
 
-        SimulatorResourceServer[] simulatorResourceServers = null;
-        try
-        {
-            simulatorResourceServers = SimulatorManager.createResource(null, count, null);
-        }
-        catch (Exception e)
-        {
-            result = true;
+        try {
+            String name = null;
+            String uri = "/test/resource";
+            String resourceType = "test.resource";
+
+            SimulatorManager.createResource(SimulatorResource.Type.SINGLE,
+                    name, uri, resourceType);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
         }
 
-        assertTrue(simulatorResourceServers == null && result);
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
     }
 
-    /**
-     * When count is set to 0
-     */
-    public void testCreateResourceCount_N04()
-    {
-        int count = 0;
+    public void testCreateResourceByType_N03() {
+        ExceptionType exType = ExceptionType.INVALID_ARGS;
 
-        SimulatorResourceServer[] simulatorResourceServers = createResources(count);
+        try {
+            String name = "test-resource";
+            String uri = "";
+            String resourceType = "test.resource";
 
-        assertTrue(simulatorResourceServers == null);
+            SimulatorManager.createResource(SimulatorResource.Type.SINGLE,
+                    name, uri, resourceType);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
     }
 
-    /**
-     * When count is set to -ve
-     */
+    public void testCreateResourceByType_N04() {
+        ExceptionType exType = ExceptionType.INVALID_ARGS;
 
-    public void testCreateResourceCount_N05()
-    {
-        int count = -10;
+        try {
+            String name = "test-resource";
+            String uri = null;
+            String resourceType = "test.resource";
 
-        SimulatorResourceServer[] simulatorResourceServers = createResources(count);
+            SimulatorManager.createResource(SimulatorResource.Type.SINGLE,
+                    name, uri, resourceType);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
 
-        assertTrue(simulatorResourceServers == null  );
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
     }
 
-    public void testDeleteResource_P01()
-    {
-        boolean result = true;
+    public void testCreateResourceByType_N05() {
+        ExceptionType exType = ExceptionType.INVALID_ARGS;
 
-        SimulatorResourceServer simRes = createResource();
+        try {
+            String name = "test-resource";
+            String uri = "/test/resource";;
+            String resourceType = "";
 
-        try
-        {
-            SimulatorManager.deleteResource(simRes);
-        }
-        catch (Exception e)
-        {
-            result = false;
+            SimulatorManager.createResource(SimulatorResource.Type.SINGLE,
+                    name, uri, resourceType);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
         }
 
-        assertTrue(result);
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
     }
 
-    public void testDeleteResource_P02()
-    {
-        boolean result = true;
+    public void testCreateResourceByType_N06() {
+        ExceptionType exType = ExceptionType.INVALID_ARGS;
 
-        SimulatorResourceServer[] simResoruces = createResources(4);
+        try {
+            String name = "test-resource";
+            String uri = "/test/resource";;
+            String resourceType = null;
 
-        try
-        {
-            SimulatorManager.deleteResource(simResoruces[0]);
+            SimulatorManager.createResource(SimulatorResource.Type.SINGLE,
+                    name, uri, resourceType);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
         }
-        catch (Exception e)
-        {
-            result = false;
-        }
-
-        for(SimulatorResourceServer simResServer : simResoruces)
-            deleteResource(simResServer);
 
-        assertTrue(result);
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
     }
 
-    public void testDeleteResources_P01()
-    {
-        boolean result = true;
+    public void testFindResource_P01() {
+        // Creating sample single resource to test this API
+        SampleSingleResource testResource = new SampleSingleResource();
+        if (false == testResource.start())
+            return;
+
+        CountDownLatch lockObject = new CountDownLatch(1);
+        boolean syncResult = false;
+        ObjectHolder<SimulatorRemoteResource> resourceHolder = new ObjectHolder<>();
+        FindResourceCallbackListener listener = new FindResourceCallbackListener(
+                lockObject, resourceHolder);
+
+        try {
+            String resourceType = testResource.mResourceType;
+            SimulatorManager.findResource(resourceType, listener);
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        if (false == syncResult)
+            testResource.stop();
 
-        createResources(4);
+        assertTrue(syncResult);
 
-        try
-        {
-            SimulatorManager.deleteResources(RESOURCE_TYPE);
-        }
-        catch (Exception e)
-        {
-            result = false;
+        // Wait for the resource to found
+        try {
+            lockObject.await(10, TimeUnit.SECONDS);
+        } catch (InterruptedException e) {
         }
 
-        assertTrue(result);
+        testResource.stop();
+        assertNotNull(resourceHolder.get());
     }
 
-    public void testFindResouce_P01()
-    {
-        boolean result = true;
+    public void testFindResource_N01() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
 
-        SimulatorResourceServer simulatorResourceServer = createResource();
+        try {
+            String resourceType = "test.singleresource";
+            SimulatorManager.findResource(resourceType, null);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
 
-        SimulatorRemoteResourceObject simulatorRemoteResource = new SimulatorRemoteResourceObject();
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
+    }
 
-        FindResourceListener findResourceListener = new FindResourceListener(lockObject, simulatorRemoteResource);
+    public void testFindResource_N02() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            String resourceType = "";
+            SimulatorManager.findResource(resourceType,
+                    new FindResourceListener() {
+                        @Override
+                        public void onResourceFound(
+                                SimulatorRemoteResource resource) {
+                        }
+                    });
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
+    }
 
-        try
-        {
-            SimulatorManager.findResource(findResourceListener);
-        }
-        catch (Exception e)
-        {
-            result = false;
+    public void testFindResource_N03() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            String resourceType = null;
+            SimulatorManager.findResource(resourceType,
+                    new FindResourceListener() {
+                        @Override
+                        public void onResourceFound(
+                                SimulatorRemoteResource resource) {
+                        }
+                    });
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
+    }
+
+    public void testFindResourceAll_P01() {
+        // Creating sample single resource to test this API
+        SampleSingleResource testResource = new SampleSingleResource();
+        if (false == testResource.start())
+            return;
+
+        CountDownLatch lockObject = new CountDownLatch(1);
+        boolean syncResult = false;
+        ObjectHolder<SimulatorRemoteResource> resourceHolder = new ObjectHolder<>();
+        FindResourceCallbackListener listener = new FindResourceCallbackListener(
+                lockObject, resourceHolder);
+
+        try {
+            SimulatorManager.findResource(listener);
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
         }
 
-        assertTrue(result);
+        if (false == syncResult)
+            testResource.stop();
 
-        deleteResource(simulatorResourceServer);
-    }
+        assertTrue(syncResult);
 
-    /**
-     * Pass null to listener
-     */
-    public void testFindResouce_N01()
-    {
-        boolean result = true;
+        // Wait for the resource to found
+        try {
+            lockObject.await(10, TimeUnit.SECONDS);
+        } catch (InterruptedException e) {
+        }
 
-        SimulatorResourceServer simulatorResourceServer = createResource();
+        testResource.stop();
+        assertNotNull(resourceHolder.get());
+    }
+
+    public void testFindResourceAll_N01() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
 
-        try
-        {
+        try {
             SimulatorManager.findResource(null);
-            result = false;
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
         }
-        catch (Exception e)
-        {
-            result = true;
-        }
-
-        assertTrue(result);
 
-        deleteResource(simulatorResourceServer);
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
     }
 
-    /**
-     *  checking for crash
-     */
-    public void testSetDeviceInfo_P01()
-    {
-        SimulatorManager.setDeviceInfo("test");
+    public void testregisterDeviceInfo_P01() {
+        boolean syncResult = false;
+
+        try {
+            String deviceName = "test-device";
+            SimulatorManager.setDeviceInfo(deviceName);
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertTrue(syncResult);
     }
 
-    /**
-     *  checking for crash
-     *  Pass empty
-     */
-    public void testSetDeviceInfo_N01()
-    {
-        try
-        {
-            SimulatorManager.setDeviceInfo("");
+    public void testregisterDeviceInfo_N01() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            String deviceName = "";
+            SimulatorManager.setDeviceInfo(deviceName);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
         }
-        catch(Exception e)
-        {
-            System.out.println("Exception hit");
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
+    }
+
+    public void testregisterDeviceInfo_N02() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            String deviceName = null;
+            SimulatorManager.setDeviceInfo(deviceName);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
         }
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
     }
 
-    /**
-    *  checking for crash
-    * pass null
-    */
-    public void testSetDeviceInfo_N02()
-    {
-        try
-        {
-            SimulatorManager.setDeviceInfo(null);
+    public void testregisterPlatformInfo_P01() {
+        boolean syncResult = false;
+
+        try {
+            PlatformInfo platformInfo = new PlatformInfo();
+            platformInfo.setManufacturerName("Samsung");
+
+            SimulatorManager.setPlatformInfo(platformInfo);
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
         }
-        catch(Exception e)
-        {
-            System.out.println("Exception hit");
+
+        assertTrue(syncResult);
+    }
+
+    public void testregisterPlatformInfo_N01() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            PlatformInfo platformInfo = null;
+            SimulatorManager.setPlatformInfo(platformInfo);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
         }
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
     }
 
-    public void testGetDeviceInfo_N01()
-    {
-        try
-        {
-            SimulatorManager.getDeviceInfo(null);
+    public void testFindDevices_P01() {
+        CountDownLatch lockObject = new CountDownLatch(1);
+        boolean syncResult = false;
+        ObjectHolder<DeviceInfo> infoHolder = new ObjectHolder<>();
+        DeviceInfoListener listener = new DeviceInfoListener(lockObject,
+                infoHolder);
+
+        try {
+            SimulatorManager.setDeviceInfo("Samsung");
+            SimulatorManager.findDevices(null, listener);
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
         }
-        catch(Exception e)
-        {
-            System.out.println(" Exception hit");
+
+        assertTrue(syncResult);
+
+        // Wait for the asynchronous response
+        try {
+            lockObject.await(10, TimeUnit.SECONDS);
+        } catch (InterruptedException e) {
         }
+
+        assertNotNull(infoHolder.get());
     }
 
-    /**
-     * Checking for crash
-     */
-    public void testSetPlatformInfo_P01()
-    {
-        PlatformInfo platformInfo = new PlatformInfo();
-        platformInfo.setDateOfManufacture("asdf");
-        platformInfo.setFirmwareVersion("asdf");
-        platformInfo.setHardwareVersion("asdf");
-        platformInfo.setManufacturerName("asdfdfg");
-        platformInfo.setManufacturerUrl("asdffdg");
-        platformInfo.setModelNumber("fddfg");
-        platformInfo.setOperationSystemVersion("sadfg");
-        platformInfo.setPlatformID("asdf");
-        platformInfo.setPlatformVersion("asdfgfdg");
-        platformInfo.setSupportUrl("adfgg");
-        platformInfo.setSystemTime("adsfgfg");
+    public void testFindDevices_N01() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            SimulatorManager.findDevices(null, null);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
 
-        SimulatorManager.setPlatformInfo(platformInfo);
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
     }
 
-    /**
-     * Checking for crash
-     */
-    public void testSetPlatformInfo_N01()
-    {
-        try
-        {
-            SimulatorManager.setPlatformInfo(null);
+    public void testGetPlatformInfo_P01() {
+        CountDownLatch lockObject = new CountDownLatch(1);
+        boolean syncResult = false;
+        ObjectHolder<PlatformInfo> infoHolder = new ObjectHolder<>();
+        PlatformInfoListener listener = new PlatformInfoListener(lockObject,
+                infoHolder);
+
+        try {
+            SimulatorManager.getPlatformInformation(null, listener);
+            syncResult = true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
         }
-        catch(Exception e)
-        {
-          System.out.println("Exception Hit");
+
+        assertTrue(syncResult);
+
+        // Wait for the asynchronous response
+        try {
+            lockObject.await(10, TimeUnit.SECONDS);
+        } catch (InterruptedException e) {
         }
+
+        assertNotNull(infoHolder.get());
     }
 
-    public void testGetPlatformInfo_N01()
-    {
-        try
-        {
-            SimulatorManager.getPlatformInfo(null);
-        }
-        catch (Exception e)
-        {
-            System.out.println("Exception Hit");
+    public void testGetPlatformInfo_N01() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            SimulatorManager.getPlatformInformation(null, null);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
         }
+
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
+    }
+}
+
+class FindResourceCallbackListener implements FindResourceListener {
+    private CountDownLatch                        mLockObject;
+    private ObjectHolder<SimulatorRemoteResource> mResourceHolder;
+
+    public FindResourceCallbackListener(CountDownLatch lockObject,
+            ObjectHolder<SimulatorRemoteResource> resourceHolder) {
+        mLockObject = lockObject;
+        mResourceHolder = resourceHolder;
+    }
+
+    @Override
+    public void onResourceFound(SimulatorRemoteResource resource) {
+        mResourceHolder.set(resource);
+        mLockObject.countDown();
+    }
+}
+
+class DeviceInfoListener implements DeviceListener {
+    private CountDownLatch           mLockObject;
+    private ObjectHolder<DeviceInfo> mInfoHolder;
+
+    public DeviceInfoListener(CountDownLatch lockObject,
+            ObjectHolder<DeviceInfo> infoHolder) {
+        mLockObject = lockObject;
+        mInfoHolder = infoHolder;
+    }
+
+    @Override
+    public void onDeviceFound(String hostUri, DeviceInfo devInfo) {
+        mInfoHolder.set(devInfo);
+        mLockObject.countDown();
+    }
+}
+
+class PlatformInfoListener implements PlatformListener {
+
+    private CountDownLatch             mLockObject;
+    private ObjectHolder<PlatformInfo> mInfoHolder;
+
+    public PlatformInfoListener(CountDownLatch lockObject,
+            ObjectHolder<PlatformInfo> infoHolder) {
+        mLockObject = lockObject;
+        mInfoHolder = infoHolder;
+    }
+
+    @Override
+    public void onPlatformFound(String hostUri, PlatformInfo platformInfo) {
+        mInfoHolder.set(platformInfo);
+        mLockObject.countDown();
     }
 }
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/SimulatorRemoteResourceObject.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/SimulatorRemoteResourceObject.java
deleted file mode 100644 (file)
index 17c5196..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * 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.
- */
-
-package org.oic.simulator.test;
-
-import org.oic.simulator.clientcontroller.SimulatorRemoteResource;
-
-/**
- * This class provides methods to set/get remote resource objects.
- */
-public class SimulatorRemoteResourceObject
-{
-
-    private SimulatorRemoteResource simulatorRemoteResource;
-
-    public void setSimulatorRemoteResource(SimulatorRemoteResource simulatorRemoteResource)
-    {
-        this.simulatorRemoteResource = simulatorRemoteResource;
-    }
-
-    public SimulatorRemoteResource getSimulatorRemoteResource()
-    {
-        return simulatorRemoteResource;
-    }
-}
index 2748e09..45fc7fb 100644 (file)
@@ -20,315 +20,201 @@ import java.util.Map;
 
 import junit.framework.TestCase;
 
-import org.oic.simulator.ResourceAttribute;
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.InvalidArgsException;
 import org.oic.simulator.SimulatorResourceModel;
 
 /**
- * This class tests the functionality of Simulator Resource Model
- * class APIs.
+ * This class tests the APIs of SimulatorResourceModel class.
  */
-public class SimulatorResourceModelTest extends TestCase
-{
-
-    private SimulatorResourceModel simulatorResourceModel;
-
-    private static final String KEY = "test";
-
-    static
-    {
-        System.loadLibrary("SimulatorManager");
-        System.loadLibrary("RamlParser");
-        System.loadLibrary("oc");
-        System.loadLibrary("oc_logger");
-        System.loadLibrary("octbstack");
-    }
+public class SimulatorResourceModelTest extends TestCase {
+    private static final String INT_KEY    = "Interger";
+    private static final String DOUBLE_KEY = "Double";
+    private static final String BOOL_KEY   = "Boolean";
+    private static final String STRING_KEY = "String";
 
     @Override
-    protected void setUp() throws Exception
-    {
+    protected void setUp() throws Exception {
         super.setUp();
-
-        simulatorResourceModel = new SimulatorResourceModel();
     }
 
     @Override
-    protected void tearDown() throws Exception
-    {
+    protected void tearDown() throws Exception {
         super.tearDown();
-
-        simulatorResourceModel = null;
     }
 
-    public void testAddAttributeInt_P01()
-    {
-        int val = 100;
-
-        boolean result = true;
-        try
-        {
-            simulatorResourceModel.addAttributeInt(KEY, val);
-            result = result && Integer.parseInt(simulatorResourceModel.getAttribute(KEY).getValue().toString()) == val;
-        }
-        catch(Exception e)
-        {
-            result = false;
-        }
-
-        assertTrue(result);
+    public void testSimulatorResourceModel_P01() {
+        SimulatorResourceModel resModel = new SimulatorResourceModel();
+        assertNotNull(resModel);
     }
 
-    public void testAddAttributeInt_N01()
-    {
-        int val = -10;
+    public void testSetInt_P01() {
+        int result = -1;
 
-        boolean result = true;
-        try
-        {
-            simulatorResourceModel.addAttributeInt(KEY, val);
-            result = result && Integer.parseInt(simulatorResourceModel.getAttribute(KEY).getValue().toString()) == val;
-        }
-        catch(Exception e)
-        {
-            result = false;
+        try {
+            SimulatorResourceModel resModel = new SimulatorResourceModel();
+            resModel.set(INT_KEY, new AttributeValue(10));
+            result = ((Integer) resModel.get(INT_KEY).get()).intValue();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
         }
 
-        assertTrue(result);
+        assertEquals(10, result);
     }
 
-    public void testAddAttributeInt_N02()
-    {
-        int val = 666666;
+    public void testSetInt_P02() {
+        int result = -1;
 
-        boolean result = true;
-        try
-        {
-            simulatorResourceModel.addAttributeInt(KEY, val);
-            result = result && Integer.parseInt(simulatorResourceModel.getAttribute(KEY).getValue().toString()) == val;
-        }
-        catch(Exception e)
-        {
-            result = false;
+        try {
+            SimulatorResourceModel resModel = new SimulatorResourceModel();
+            resModel.set(INT_KEY, new AttributeValue(-10));
+            result = ((Integer) resModel.get(INT_KEY).get()).intValue();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
         }
 
-        assertTrue(result);
+        assertEquals(-10, result);
     }
 
-    public void testAddAttributeDouble_P01()
-    {
-        double val = 10.11;
+    public void testSetDouble_P01() {
+        double result = 0.0;
 
-        boolean result = true;
-        try
-        {
-            simulatorResourceModel.addAttributeDouble(KEY, val);
-            result = result && Double.parseDouble(simulatorResourceModel.getAttribute(KEY).getValue().toString()) == val;
-        }
-        catch(Exception e)
-        {
-            result = false;
+        try {
+            SimulatorResourceModel resModel = new SimulatorResourceModel();
+            resModel.set(DOUBLE_KEY, new AttributeValue(4.0));
+            result = ((Double) resModel.get(DOUBLE_KEY).get()).doubleValue();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
         }
 
-        assertTrue(result);
+        assertEquals(4.0, result);
     }
 
-    public void testAddAttributeDouble_N01()
-    {
-        double val = -11.12;
+    public void testSetDouble_P02() {
+        double result = 0.0;
 
-        boolean result = true;
-        try
-        {
-            simulatorResourceModel.addAttributeDouble(KEY, val);
-            result = result && Double.parseDouble(simulatorResourceModel.getAttribute(KEY).getValue().toString()) == val;
-        }
-        catch(Exception e)
-        {
-            result = false;
+        try {
+            SimulatorResourceModel resModel = new SimulatorResourceModel();
+            resModel.set(DOUBLE_KEY, new AttributeValue(-4.0));
+            result = ((Double) resModel.get(DOUBLE_KEY).get()).doubleValue();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
         }
 
-        assertTrue(result);
+        assertEquals(-4.0, result);
     }
 
-    public void testAddAttributeDouble_N02()
-    {
-        double val = 0.0044444444444;
+    public void testSetBoolean_P01() {
+        boolean result = false;
 
-        boolean result = true;
-        try
-        {
-            simulatorResourceModel.addAttributeDouble(KEY, val);
-            result = result && Double.parseDouble(simulatorResourceModel.getAttribute(KEY).getValue().toString()) == val;
-        }
-        catch(Exception e)
-        {
-            result = false;
+        try {
+            SimulatorResourceModel resModel = new SimulatorResourceModel();
+            resModel.set(BOOL_KEY, new AttributeValue(true));
+            result = ((Boolean) resModel.get(BOOL_KEY).get()).booleanValue();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
         }
 
-        assertTrue(result);
+        assertEquals(true, result);
     }
 
-    public void testAddAttributeString_P01()
-    {
-        String val = "asdf";
+    public void testSetString_P01() {
+        String result = null;
 
-        boolean result = true;
-        try
-        {
-            simulatorResourceModel.addAttributeString(KEY, val);
-            result = result && simulatorResourceModel.getAttribute(KEY).getValue().toString().equals(val);
-        }
-        catch(Exception e)
-        {
-            result = false;
+        try {
+            SimulatorResourceModel resModel = new SimulatorResourceModel();
+            resModel.set(STRING_KEY, new AttributeValue("string-value"));
+            result = (String) resModel.get(STRING_KEY).get();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
         }
 
-        assertTrue(result);
+        assertEquals("string-value", result);
     }
 
-    public void testAddAttributeString_N01()
-    {
-        String val = "";
+    public void testSetString_P02() {
+        String result = null;
 
-        boolean result = true;
-        try
-        {
-            simulatorResourceModel.addAttributeString(KEY, val);
-            result = result && simulatorResourceModel.getAttribute(KEY).getValue().toString().equals(val);
-        }
-        catch(Exception e)
-        {
-            result = false;
+        try {
+            SimulatorResourceModel resModel = new SimulatorResourceModel();
+            resModel.set(STRING_KEY, new AttributeValue(""));
+            result = (String) resModel.get(STRING_KEY).get();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
         }
 
-        assertTrue(result);
+        assertEquals("", result);
     }
 
-   public void testAddAttributeString_N02() {
-        String val = null;
+    public void testSetString_P03() {
+        String result = null;
 
-        boolean result = false;
         try {
-
-            simulatorResourceModel.addAttributeString(KEY, val);
-
-            result = result && simulatorResourceModel.getAttribute(KEY).getValue().toString().equals(val);
-
-        } catch(Exception e) {
-            result = true;
+            SimulatorResourceModel resModel = new SimulatorResourceModel();
+            resModel.set(STRING_KEY, new AttributeValue("@#$$&^*^(*^&"));
+            result = (String) resModel.get(STRING_KEY).get();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
         }
 
-        assertTrue(result);
+        assertEquals("@#$$&^*^(*^&", result);
     }
 
-    public void testAddAttributeString_N03()
-    {
-        String val = "@#$$&^*^(*^&";
+    public void testSize_P01() {
+        int result = -1;
 
-        boolean result = true;
-        try
-        {
-            simulatorResourceModel.addAttributeString(KEY, val);
-            result = result && simulatorResourceModel.getAttribute(KEY).getValue().toString().equals(val);
-        }
-        catch(Exception e)
-        {
-            result = false;
-        }
+        SimulatorResourceModel resModel = new SimulatorResourceModel();
+        result = resModel.size();
 
-        assertTrue(result);
+        assertEquals(0, result);
     }
 
-    public void testAddAttributeBoolean_P01()
-    {
-        boolean result = true;
-
-        boolean val;
-
-        try
-        {
-            val=Boolean.parseBoolean("true");
-            simulatorResourceModel.addAttributeBoolean(KEY, val);
-
-            result = result && ((Boolean.parseBoolean(simulatorResourceModel.getAttribute(KEY).getValue().toString()+"")));
+    public void testSize_P02() {
+        int result = -1;
 
-            val = Boolean.parseBoolean("false");
-
-            simulatorResourceModel.addAttributeBoolean(KEY, val);
-
-            result = result && !((Boolean.parseBoolean(simulatorResourceModel.getAttribute(KEY).getValue().toString()+"")));
-        }
-        catch (Exception e)
-        {
-            result = false;
+        SimulatorResourceModel resModel = new SimulatorResourceModel();
+        try {
+            resModel.set(INT_KEY, new AttributeValue(1234));
+            resModel.set(DOUBLE_KEY, new AttributeValue(1.234));
+            resModel.set(BOOL_KEY, new AttributeValue(true));
+            resModel.set(STRING_KEY, new AttributeValue("string-value"));
+            result = resModel.size();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
         }
 
-        assertTrue(result);
+        assertEquals(4, result);
     }
 
-    public void testSize_P01()
-    {
-        boolean result = true;
-
-        try
-        {
-            simulatorResourceModel.addAttributeInt("test1", 1234);
-
-            result = result && (simulatorResourceModel.size() == 1);
-
-            simulatorResourceModel.addAttributeString("test2", "asdf");
-            simulatorResourceModel.addAttributeBoolean("test3", Boolean.parseBoolean("true"));
-            simulatorResourceModel.addAttributeDouble("test4", 22.435234);
+    public void testGet_P01() {
+        AttributeValue result = null;
 
-            result = result && (simulatorResourceModel.size() == 4);
-        }
-        catch(Exception e)
-        {
-            result = false;
+        SimulatorResourceModel resModel = new SimulatorResourceModel();
+        try {
+            resModel.set(INT_KEY, new AttributeValue(10));
+            result = resModel.get(INT_KEY);
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
         }
-        assertTrue(result);
-    }
-
-    public void testGetAttributes_P01()
-    {
-        boolean result = true;
 
-        try
-        {
-            simulatorResourceModel.addAttributeInt("test1", 1234);
-            simulatorResourceModel.addAttributeString("test2", "asdf");
-            simulatorResourceModel.addAttributeBoolean("test3", Boolean.parseBoolean("true"));
-            simulatorResourceModel.addAttributeDouble("test4", 22.435234);
-
-            Map<String, ResourceAttribute> attributes = simulatorResourceModel.getAttributes();
-
-            result = result && (((Integer)attributes.get("test1").getValue()) == 1234) &&
-                     (((String)attributes.get("test2").getValue()).equals("asdf")) &&
-                     ((Boolean.parseBoolean(attributes.get("test3").getValue().toString() + "")==true)) &&
-                     (((Double)attributes.get("test4").getValue()) == 22.435234);
-        }
-        catch(Exception e)
-        {
-            result = false;
-        }
-        assertTrue(result);
+        assertNotNull(result);
     }
 
-    public void testGetAttribute_P01()
-    {
-        int val = 100;
-
-        boolean result = true;
-
-        try
-        {
-            simulatorResourceModel.addAttributeInt(KEY, val);
+    public void testGet_P02() {
+        Map<String, AttributeValue> result = null;
 
-            result = result && Integer.parseInt(simulatorResourceModel.getAttribute(KEY).getValue().toString()) == val;
-        }
-        catch(Exception e)
-        {
-            result = false;
+        SimulatorResourceModel resModel = new SimulatorResourceModel();
+        try {
+            resModel.set(INT_KEY, new AttributeValue(1234));
+            resModel.set(DOUBLE_KEY, new AttributeValue(1.234));
+            resModel.set(BOOL_KEY, new AttributeValue(true));
+            resModel.set(STRING_KEY, new AttributeValue("string-value"));
+            result = resModel.get();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
         }
-        assertTrue(result);
+
+        assertNotNull(result);
+        assertEquals(4, result.size());
     }
 }
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/StringPropertyTest.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/StringPropertyTest.java
new file mode 100644 (file)
index 0000000..824f622
--- /dev/null
@@ -0,0 +1,194 @@
+/*
+ * 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.oic.simulator.test;
+
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.StringProperty;
+
+import junit.framework.TestCase;
+
+public class StringPropertyTest extends TestCase {
+
+    protected void setUp() throws Exception {
+        super.setUp();
+    }
+
+    protected void tearDown() throws Exception {
+        super.tearDown();
+    }
+
+    public void testStringProperty_P01() {
+        StringProperty property = new StringProperty.Builder().build();
+
+        assertNotNull(property);
+    }
+
+    public void testIsString_P01() {
+        StringProperty property = new StringProperty.Builder().build();
+
+        assertNotNull(property);
+        assertTrue(property.isString());
+    }
+
+    public void testHasRange_P01() {
+        StringProperty.Builder builder = new StringProperty.Builder();
+        builder.setRange(1, 5);
+
+        StringProperty property = builder.build();
+
+        assertNotNull(property);
+        assertTrue(property.hasRange());
+    }
+
+    public void testGetRange_P01() {
+        StringProperty.Builder builder = new StringProperty.Builder();
+        builder.setRange(1, 5);
+
+        StringProperty property = builder.build();
+
+        assertNotNull(property);
+        assertEquals(property.min(), 1);
+        assertEquals(property.max(), 5);
+    }
+
+    public void testHasValues_P01() {
+        StringProperty.Builder builder = new StringProperty.Builder();
+        String[] values = { "value1", "value2" };
+        builder.setValues(values);
+
+        StringProperty property = builder.build();
+
+        assertNotNull(property);
+        assertTrue(property.hasValues());
+    }
+
+    public void testGetValues_P01() {
+        StringProperty.Builder builder = new StringProperty.Builder();
+        String[] values = { "value1", "value2" };
+        builder.setValues(values);
+
+        StringProperty property = builder.build();
+
+        assertNotNull(property);
+        assertNotNull(property.getValues());
+        assertEquals(property.getValues().length, 2);
+    }
+
+    public void testValidate_P01() {
+        StringProperty.Builder builder = new StringProperty.Builder();
+        builder.setRange(1, 5);
+
+        StringProperty property = builder.build();
+
+        assertNotNull(property);
+        assertTrue(property.validate(new AttributeValue("12345")));
+    }
+
+    public void testValidate_P02() {
+        StringProperty.Builder builder = new StringProperty.Builder();
+        builder.setRange(1, 5);
+
+        StringProperty property = builder.build();
+
+        assertNotNull(property);
+        assertTrue(property.validate("12345"));
+    }
+
+    public void testValidate_P03() {
+        StringProperty.Builder builder = new StringProperty.Builder();
+        String[] values = { "value1", "value2" };
+        builder.setValues(values);
+
+        StringProperty property = builder.build();
+
+        assertNotNull(property);
+        assertTrue(property.validate(new AttributeValue("value1")));
+    }
+
+    public void testValidate_P04() {
+        StringProperty.Builder builder = new StringProperty.Builder();
+        String[] values = { "value1", "value2" };
+        builder.setValues(values);
+
+        StringProperty property = builder.build();
+
+        assertNotNull(property);
+        assertTrue(property.validate("value1"));
+    }
+
+    public void testValidate_N01() {
+        StringProperty.Builder builder = new StringProperty.Builder();
+        builder.setRange(1, 5);
+
+        StringProperty property = builder.build();
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue("123456")));
+    }
+
+    public void testValidate_N02() {
+        StringProperty.Builder builder = new StringProperty.Builder();
+        builder.setRange(1, 5);
+
+        StringProperty property = builder.build();
+
+        assertNotNull(property);
+        assertFalse(property.validate("123456"));
+    }
+
+    public void testValidate_N03() {
+        StringProperty.Builder builder = new StringProperty.Builder();
+        builder.setRange(3, 5);
+
+        StringProperty property = builder.build();
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue("12")));
+    }
+
+    public void testValidate_N04() {
+        StringProperty.Builder builder = new StringProperty.Builder();
+        builder.setRange(3, 5);
+
+        StringProperty property = builder.build();
+
+        assertNotNull(property);
+        assertFalse(property.validate("12"));
+    }
+
+    public void testValidate_N05() {
+        StringProperty.Builder builder = new StringProperty.Builder();
+        String[] values = { "value1", "value2" };
+        builder.setValues(values);
+
+        StringProperty property = builder.build();
+
+        assertNotNull(property);
+        assertFalse(property.validate(new AttributeValue("wrong-value")));
+    }
+
+    public void testValidate_N06() {
+        StringProperty.Builder builder = new StringProperty.Builder();
+        String[] values = { "value1", "value2" };
+        builder.setValues(values);
+
+        StringProperty property = builder.build();
+
+        assertNotNull(property);
+        assertFalse(property.validate("wrong-value"));
+    }
+}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/utils/ObjectHolder.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/utils/ObjectHolder.java
new file mode 100644 (file)
index 0000000..b0d3fe2
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator.utils;
+
+public class ObjectHolder<T> {
+    private T mObject;
+
+    public void set(T object) {
+        mObject = object;
+    }
+
+    public T get() {
+        return mObject;
+    }
+}
diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/utils/SampleSingleResource.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/utils/SampleSingleResource.java
new file mode 100644 (file)
index 0000000..fd88189
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+ * 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.
+ */
+
+package org.oic.simulator.utils;
+
+import org.oic.simulator.InvalidArgsException;
+import org.oic.simulator.SimulatorException;
+import org.oic.simulator.SimulatorManager;
+import org.oic.simulator.server.SimulatorResource;
+import org.oic.simulator.server.SimulatorSingleResource;
+
+public class SampleSingleResource {
+
+    private SimulatorSingleResource mResource;
+    public String                   mName         = "test-singleresource";
+    public String                   mUri          = "/test/singleresource";
+    public String                   mResourceType = "test.singleresource";
+
+    public boolean start() {
+        try {
+            mResource = (SimulatorSingleResource) SimulatorManager
+                    .createResource(SimulatorResource.Type.SINGLE, mName, mUri,
+                            mResourceType);
+            mResource.start();
+            return true;
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        return false;
+    }
+
+    public boolean stop() {
+        try {
+            mResource.stop();
+            mResource = null;
+            return true;
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        return false;
+    }
+}
index 76235f0..da66dbf 100644 (file)
@@ -60,6 +60,10 @@ tgmsdk_shared = things_manager_env.SharedLibrary('TGMSDKLibrary', tgm_src)
 
 things_manager_env.InstallTarget([tgmsdk_static,tgmsdk_shared], 'libTGMSDK')
 things_manager_env.UserInstallTargetLib([tgmsdk_static,tgmsdk_shared], 'libTGMSDK')
+things_manager_env.UserInstallTargetHeader('sdk/inc/ActionSet.h', 'service/things-manager', 'ActionSet.h')
+things_manager_env.UserInstallTargetHeader('sdk/inc/GroupManager.h', 'service/things-manager', 'GroupManager.h')
+things_manager_env.UserInstallTargetHeader('sdk/inc/ThingsConfiguration.h', 'service/things-manager', 'ThingsConfiguration.h')
+things_manager_env.UserInstallTargetHeader('sdk/inc/ThingsMaintenance.h', 'service/things-manager', 'ThingsMaintenance.h')
 
 # Build JNI layer
 #if target_os == 'android':
index c8fa61c..6f4d2ea 100644 (file)
@@ -40,5 +40,3 @@ target_os = env.get('TARGET_OS')
 if target_os == 'linux' :
        # Build linux sample app
        SConscript('linux/configuration/SConscript')
-       SConscript('linux/groupaction/SConscript')
-       SConscript('linux/groupsyncaction/SConscript')
old mode 100644 (file)
new mode 100755 (executable)
index 1b78dd8..d28ca48
@@ -111,7 +111,7 @@ void MaintenanceResource::maintenanceMonitor(int second)
             int res;
             std::cout << "Reboot will be soon..." << std::endl;
             m_reboot = defaultReboot;
-            res = system("sudo reboot"); // System reboot
+            res = system("/usr/bin/sudo /etc/init.d/reboot"); // System reboot for linux
 
             std::cout << "return: " << res << std::endl;
 
index b924733..d83e86d 100755 (executable)
@@ -220,7 +220,7 @@ void onFoundCandidateResource(std::vector< std::shared_ptr< OCResource > > resou
                 {
                     resourceTable[resource->host() + resource->uri()] = resource;
 
-                    OCResourceHandle foundResourceHandle;
+                    OCResourceHandle foundResourceHandle = NULL;
                     OCStackResult result = OCPlatform::registerResource(foundResourceHandle,
                             resource);
                     std::cout << "\tResource ( " << resource->host() << " ) is registed!\t"
@@ -334,6 +334,11 @@ int main()
                 std::cout << "Please put a digit, not string" << std::endl;
                 continue;
             }
+            catch(std::out_of_range&)
+            {
+                std::cout << "Please put a number within the supported range" << std::endl;
+                continue;
+            }
 
             if (g_Steps == 0)
             {
diff --git a/service/things-manager/sampleapp/linux/groupaction/SConscript b/service/things-manager/sampleapp/linux/groupaction/SConscript
deleted file mode 100644 (file)
index dd73a8a..0000000
+++ /dev/null
@@ -1,64 +0,0 @@
-#******************************************************************
-#
-# Copyright 2014 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.
-#
-#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-##
-# linux sample app  build script
-##
-
-Import('env')
-
-# Add third party libraries
-lib_env = env.Clone()
-SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
-linux_sample_env = lib_env.Clone()
-
-######################################################################
-# Build flags
-######################################################################
-linux_sample_env.AppendUnique(CPPPATH = ['include'])
-linux_sample_env.AppendUnique(CPPPATH = ['../../../../../extlibs/timer'])
-linux_sample_env.AppendUnique(CPPPATH = ['../../../sdk/inc'])
-linux_sample_env.AppendUnique(CPPPATH = ['../../../sdk/src'])
-linux_sample_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-DLINUX', '-pthread'])
-linux_sample_env.AppendUnique(CPPDEFINES = ['LINUX'])
-linux_sample_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-linux_sample_env.AppendUnique(LIBS = ['libTGMSDKLibrary', 'oc', 'octbstack',
-                                      'connectivity_abstraction',
-                                      'libcoap', 'liboc_logger', 'dl', 'pthread'])
-if env.get('SECURED') == '1':
-    linux_sample_env.AppendUnique(LIBS = ['tinydtls'])
-
-# On some platforms link order can miss functions so librt needs to be
-# re-scanned at the end if present. gcc 4.6 is one with this issue.
-if 'rt' in linux_sample_env.get('LIBS'):
-    linux_sample_env.Append(LIBS = ['rt'])
-
-######################################################################
-#build sampleapp
-######################################################################
-groupserver = linux_sample_env.Program('groupserver', 'groupserver.cpp')
-lightserver = linux_sample_env.Program('lightserver', 'lightserver.cpp')
-bookmark = linux_sample_env.Program('bookmark', 'bookmark.cpp')
-Alias("GroupServerApp", groupserver)
-Alias("LightServerApp", lightserver)
-Alias("BookmarkApp", bookmark)
-env.AppendTarget('GroupServerApp')
-env.AppendTarget('LightServerApp')
-env.AppendTarget('BookmarkApp')
diff --git a/service/things-manager/sampleapp/linux/groupaction/bookmark.cpp b/service/things-manager/sampleapp/linux/groupaction/bookmark.cpp
deleted file mode 100755 (executable)
index 18d1127..0000000
+++ /dev/null
@@ -1,229 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 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 <functional>
-#include <pthread.h>
-
-#include "OCPlatform.h"
-#include "OCApi.h"
-
-using namespace OC;
-using namespace std;
-
-namespace PH = std::placeholders;
-
-unsigned int startedThread;
-unsigned int gObservation;
-pthread_t threadId;
-
-void* ObserveHandler(void *param);
-
-class BookmarkResource
-{
-
-private:
-    OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request)
-    {
-        OCEntityHandlerResult ehResult = OC_EH_ERROR;
-
-        if (request)
-        {
-            // Get the request type and request flag
-            std::string requestType = request->getRequestType();
-            int requestFlag = request->getRequestHandlerFlag();
-
-            if (requestFlag & RequestHandlerFlag::RequestFlag)
-            {
-                auto pResponse = std::make_shared< OC::OCResourceResponse >();
-                pResponse->setRequestHandle(request->getRequestHandle());
-                pResponse->setResourceHandle(request->getResourceHandle());
-
-                // If the request type is GET
-                if (requestType == "GET")
-                {
-                }
-                else if (requestType == "PUT")
-                {
-                    cout << "\t\t\trequestType : PUT\n";
-                }
-                else if (requestType == "POST")
-                {
-                    // POST request operations
-                }
-                else if (requestType == "DELETE")
-                {
-                    // DELETE request operations
-                }
-
-                pResponse->setErrorCode(200);
-                pResponse->setResponseResult(OC_EH_OK);
-                pResponse->setResourceRepresentation(getRepresentation());
-                if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
-                {
-                    ehResult = OC_EH_OK;
-                }
-            }
-
-            if (requestFlag & RequestHandlerFlag::ObserverFlag)
-            {
-                cout << "\t\trequestFlag : Observer\n";
-
-                if (!startedThread)
-                {
-                    pthread_create(&threadId, NULL, ObserveHandler, (void *) NULL);
-                    startedThread = 1;
-                    gObservation = 1;
-                }
-
-                ehResult = OC_EH_OK;
-            }
-        }
-        else
-        {
-            std::cout << "Request invalid" << std::endl;
-        }
-
-        return ehResult;
-    }
-
-public:
-    /// Constructor
-    BookmarkResource()
-    {
-        m_pressure = 0;
-
-        m_BookmarkUri = "/core/bookmark"; // URI of the resource
-        m_BookmarkType = "core.bookmark"; // resource type name. In this case, it is light
-
-        m_BookmarkInterface = DEFAULT_INTERFACE; // resource interface.
-        m_BookmarkHandle = 0;
-    }
-
-    /// This function internally calls registerResource API.
-    void createResources()
-    {
-        EntityHandler cb = std::bind(&BookmarkResource::entityHandler, this, PH::_1);
-
-        // This will internally create and register the resource.
-        OCStackResult result = OC::OCPlatform::registerResource(m_BookmarkHandle, m_BookmarkUri,
-                m_BookmarkType, m_BookmarkInterface, cb, OC_DISCOVERABLE | OC_OBSERVABLE);
-
-        if (OC_STACK_OK != result)
-        {
-            cout << "Resource creation (bookmark) was unsuccessful\n";
-        }
-        else
-        {
-            cout << "Resource URI : " << m_BookmarkUri << endl;
-            cout << "\tResource Type Name : " << m_BookmarkType << endl;
-            cout << "\tResource Interface : " << DEFAULT_INTERFACE << endl;
-            cout << "\tResource creation is successful with resource handle : " << m_BookmarkHandle
-                    << endl;
-        }
-    }
-
-    void setRepresentation(OCRepresentation& /*rep*/)
-    {
-        // AttributeMap attributeMap = rep.getAttributeMap();
-        // if(rep.getValue("level", m_pressure) == true)
-        {
-            std::cout << m_pressure << endl;
-        }
-    }
-
-    OCRepresentation getRepresentation()
-    {
-        OCRepresentation rep;
-
-        rep.setValue("level", (int) m_pressure);
-
-        return rep;
-    }
-
-public:
-    // Members of Bookmark
-    std::string m_BookmarkUri;
-    std::string m_BookmarkType;
-    std::string m_BookmarkInterface;
-    unsigned int m_pressure;
-    OCResourceHandle m_BookmarkHandle;
-};
-
-// Create the instance of the resource class (in this case instance of class 'BookmarkResource').
-BookmarkResource myBookmarkResource;
-
-void* ObserveHandler(void* /*param*/)
-{
-    while (startedThread)
-    {
-        sleep(1);
-
-        cout << "input a integer(0:opened, 5:close) : ";
-        cin >> myBookmarkResource.m_pressure;
-
-        if (myBookmarkResource.m_pressure == 0 || // When your book opened.
-                myBookmarkResource.m_pressure == 5) // When your book closed.
-        {
-            cout << "notifyObservers call!" << endl;
-
-            OCStackResult result = OCPlatform::notifyAllObservers(
-                    myBookmarkResource.m_BookmarkHandle);
-
-            if (OC_STACK_NO_OBSERVERS == result)
-            {
-                cout << "No More observers, stopping notifications" << endl;
-                gObservation = 0;
-                startedThread = 0;
-            }
-        }
-    }
-
-    return NULL;
-}
-
-int main()
-{
-    // Create PlatformConfig object
-
-    OC::PlatformConfig cfg
-    { OC::ServiceType::InProc, OC::ModeType::Server, "0.0.0.0",
-    // By setting to "0.0.0.0", it binds to all available interfaces
-            0,// Uses randomly available port
-            OC::QualityOfService::LowQos };
-
-    // Create a OCPlatform instance.
-    // Note: Platform creation is synchronous call.
-    try
-    {
-
-        // Invoke createResource function of class bookmark.
-        myBookmarkResource.createResources();
-
-        // Perform app tasks
-        while (true)
-        {
-            // some tasks
-        }
-    }
-    catch (OCException e)
-    {
-        std::cout << "Exception: " << e.what() << std::endl;
-    }
-}
diff --git a/service/things-manager/sampleapp/linux/groupaction/groupserver.cpp b/service/things-manager/sampleapp/linux/groupaction/groupserver.cpp
deleted file mode 100755 (executable)
index 753c6f7..0000000
+++ /dev/null
@@ -1,590 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 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 <OCPlatform.h>
-#include <OCApi.h>
-
-#include <functional>
-#include <pthread.h>
-#include <iostream>
-
-#include "timer.h"
-
-#include <GroupManager.h>
-
-using namespace std;
-using namespace OC;
-using namespace OIC;
-namespace PH = std::placeholders;
-
-bool isReady = false;
-
-OCResourceHandle resourceHandle;
-std::vector<OCResourceHandle> resourceHandleVector;
-
-shared_ptr<OCResource> g_resource;
-vector<string> lights;
-
-GroupManager *groupMgr = new GroupManager();
-
-void onGet(const HeaderOptions& opt, const OCRepresentation &rep,
-        const int eCode);
-
-void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep,
-        const int eCode);
-
-void onPost(const HeaderOptions& headerOptions, const OCRepresentation& rep,
-        const int eCode);
-
-void onObserve(const HeaderOptions headerOptions, const OCRepresentation& rep,
-        const int& eCode, const int& sequenceNumber);
-
-void allBulbOn();
-void allBulbOff();
-
-shared_ptr<OCResource> g_light;
-
-void foundResources(
-        std::vector<std::shared_ptr<OC::OCResource> > listOfResource)
-{
-
-    for (auto rsrc = listOfResource.begin(); rsrc != listOfResource.end();
-            ++rsrc)
-    {
-        std::string resourceURI = (*rsrc)->uri();
-        std::string hostAddress = (*rsrc)->host();
-
-        if (resourceURI == "/a/light")
-        {
-            cout << "\tResource URI : " << resourceURI << endl;
-            cout << "\tResource Host : " << hostAddress << endl;
-
-            OCResourceHandle foundResourceHandle;
-            OCStackResult result = OCPlatform::registerResource(
-                    foundResourceHandle, (*rsrc));
-            cout << "\tresource registed!" << endl;
-            if (result == OC_STACK_OK)
-            {
-                OCPlatform::bindResource(resourceHandle, foundResourceHandle);
-                resourceHandleVector.push_back(foundResourceHandle);
-            }
-            else
-            {
-                cout << "\tresource Error!" << endl;
-            }
-
-            lights.push_back((hostAddress + resourceURI));
-
-            g_light = (*rsrc);
-        }
-    }
-
-    isReady = true;
-}
-
-void foundResource(std::shared_ptr<OCResource> resource)
-{
-    std::string resourceURI;
-    std::string hostAddress;
-
-    cout << "FOUND RESOURCE" << endl;
-
-    try
-    {
-        if (resource)
-        {
-            resourceURI = resource->uri();
-            hostAddress = resource->host();
-            if (resourceURI == "/core/a/collection")
-            {
-                g_resource = resource;
-
-                // g_resource->get("", DEFAULT_INTERFACE, QueryParamsMap(), onGet);
-
-                cout << "FOUND " << resourceURI << endl;
-                // printf("\tHOST :: %s\n", resource->host().c_str());
-            }
-            else if (resourceURI == "/core/bookmark")
-            {
-                resource->observe(ObserveType::Observe, QueryParamsMap(),
-                        &onObserve);
-            }
-        }
-    }
-    catch (std::exception& e)
-    {
-        std::cout << "Exception: " << e.what() << std::endl;
-    }
-}
-
-void onGet(const HeaderOptions& /*opt*/, const OCRepresentation &/*rep*/,
-        const int eCode)
-{
-    cout << "\nonGet" << endl;
-    if (eCode == OC_STACK_OK)
-        cout << "\tResult is OK." << endl;
-    else
-        cout << "\tInvalid parameter." << endl;
-}
-
-void onPut(const HeaderOptions& /*opt*/, const OCRepresentation &/*rep*/,
-        const int eCode)
-{
-    cout << "\nonPut" << endl;
-    if (eCode == OC_STACK_OK)
-        cout << "\tResult is OK." << endl;
-    else
-        cout << "\tInvalid parameter." << endl;
-}
-
-void onPost(const HeaderOptions& /*opt*/, const OCRepresentation &rep,
-        const int /*eCode*/)
-{
-    printf("\nonPost\n");
-
-    if (rep.hasAttribute("ActionSet"))
-    {
-        std::string plainText;
-
-        if (rep.getValue("ActionSet", plainText))
-        {
-            ActionSet *actionset = groupMgr->getActionSetfromString(plainText);
-            if (actionset != NULL)
-            {
-                cout << endl << "\tACTIONSET NAME :: "
-                        << actionset->actionsetName << endl;
-                for (auto actIter = actionset->listOfAction.begin();
-                        actIter != actionset->listOfAction.end(); ++actIter)
-                {
-                    cout << "\t\tTARGET :: " << (*actIter)->target << endl;
-
-                    for (auto capaIter = (*actIter)->listOfCapability.begin();
-                            capaIter != (*actIter)->listOfCapability.end();
-                            ++capaIter)
-                    {
-                        cout << "\t\t\t" << (*capaIter)->capability << " :: "
-                                << (*capaIter)->status << endl;
-                    }
-                }
-            }
-            delete actionset;
-        }
-
-        // printf( "\tPlain Text :: %s\n", plainText.c_str() );
-    }
-    else if (rep.hasAttribute("DoAction"))
-    {
-        std::string plainText;
-        if (rep.getValue("DoAction", plainText))
-        {
-            cout << "\t" << plainText << endl;
-        }
-    }
-    else
-    {
-
-    }
-}
-
-void allBulbOff()
-{
-    OCRepresentation rep;
-
-    rep.setValue("DoAction", std::string("AllBulbOff"));
-
-    if (g_resource)
-    {
-        g_resource->post("a.collection", GROUP_INTERFACE, rep, QueryParamsMap(),
-                &onPost);
-    }
-}
-
-void allBulbOn()
-{
-    OCRepresentation rep;
-
-    rep.setValue("DoAction", std::string("AllBulbOn"));
-
-    if (g_resource)
-    {
-        OCStackResult res = g_resource->post("a.collection", GROUP_INTERFACE,
-            rep, QueryParamsMap(), &onPost);
-
-        if( res != OC_STACK_OK )
-            cout << "failed" << endl;
-    }
-}
-
-void Scheduled_AllbulbOff()
-{
-    groupMgr->executeActionSet(g_resource, "AllBulbOffScheduledCall", &onPost);
-}
-void Scheduled_AllbulbOffEx()
-{
-    groupMgr->executeActionSet(g_resource, "AllBulbOffScheduledCall", 10, &onPost);
-}
-void CancelScheduled_AllBulbOff()
-{
-    groupMgr->cancelActionSet(g_resource, "AllBulbOffScheduledCall", &onPost);
-}
-void Recursive_allBulbOn()
-{
-    groupMgr->executeActionSet(g_resource, "AllBulbOnRecursiveCall", &onPost);
-}
-void Recursive_allBulbOnEx()
-{
-    groupMgr->executeActionSet(g_resource, "AllBulbOnRecursiveCall", 10, &onPost);
-}
-
-void CancelRecursive_allBulbOn()
-{
-
-    groupMgr->cancelActionSet(g_resource, "AllBulbOnRecursiveCall", &onPost);
-}
-
-void onObserve(const HeaderOptions /*headerOptions*/, const OCRepresentation& rep,
-        const int& eCode, const int& sequenceNumber)
-{
-    if (eCode == OC_STACK_OK)
-    {
-        int level;
-
-        std::cout << "OBSERVE RESULT:" << std::endl;
-        std::cout << "\tSequenceNumber: " << sequenceNumber << endl;
-
-        if (rep.getValue("level", level))
-        {
-            if (level == 0)
-            {
-                allBulbOn();
-            }
-            else
-            {
-                allBulbOff();
-            }
-        }
-        std::cout << "\tlevel: " << level << std::endl;
-    }
-    else
-    {
-        std::cout << "onObserve Response error: " << eCode << std::endl;
-        std::exit(-1);
-    }
-}
-
-void createActionSet_AllBulbOff()
-{
-    string actionsetDesc;
-    ActionSet *allBulbOff = new ActionSet();
-    allBulbOff->actionsetName = "AllBulbOff";
-
-    for (auto iter = lights.begin(); iter != lights.end(); ++iter)
-    {
-        Action *action = new Action();
-        action->target = (*iter);
-
-        Capability *capa = new Capability();
-        capa->capability = "power";
-        capa->status = "off";
-
-        action->listOfCapability.push_back(capa);
-        allBulbOff->listOfAction.push_back(action);
-    }
-    if (g_resource)
-    {
-        groupMgr->addActionSet(g_resource, allBulbOff, onPut);
-    }
-
-    delete allBulbOff;
-}
-
-void createActionSet_AllBulbOn()
-{
-    string actionsetDesc;
-    ActionSet *allBulbOff = new ActionSet();
-    allBulbOff->actionsetName = "AllBulbOn";
-
-    for (auto iter = lights.begin(); iter != lights.end(); ++iter)
-    {
-        Action *action = new Action();
-        action->target = (*iter);
-
-        Capability *capa = new Capability();
-        capa->capability = "power";
-        capa->status = "on";
-
-        action->listOfCapability.push_back(capa);
-        allBulbOff->listOfAction.push_back(action);
-    }
-    if (g_resource)
-    {
-        groupMgr->addActionSet(g_resource, allBulbOff, onPut);
-    }
-
-    delete allBulbOff;
-}
-
-void createScheduledActionSet_AllBulbOff()
-{
-    string actionsetDesc;
-    ActionSet *allBulbOff = new ActionSet();
-    allBulbOff->type = OIC::ACTIONSET_TYPE::SCHEDULED;
-    allBulbOff->actionsetName = "AllBulbOffScheduledCall";
-
-    printf("ENTER(YYYY-MM-DD hh:mm:ss) :: ");
-    int res = scanf("%d-%d-%d %d:%d:%d", &allBulbOff->mTime.tm_year,
-            &allBulbOff->mTime.tm_mon, &allBulbOff->mTime.tm_mday,
-            &allBulbOff->mTime.tm_hour, &allBulbOff->mTime.tm_min,
-            &allBulbOff->mTime.tm_sec);
-    if( res < 0 )
-    {
-        printf("Invalid Input. try again.");
-        delete allBulbOff;
-        return;
-    }
-
-    allBulbOff->setDelay(allBulbOff->getSecondsFromAbsoluteTime());
-    printf("DELAY :: %ld\n", allBulbOff->getSecondsFromAbsoluteTime());
-
-    for (auto iter = lights.begin(); iter != lights.end(); ++iter)
-    {
-        Action *action = new Action();
-        action->target = (*iter);
-
-        Capability *capa = new Capability();
-        capa->capability = "power";
-        capa->status = "off";
-
-        action->listOfCapability.push_back(capa);
-        allBulbOff->listOfAction.push_back(action);
-    }
-    if (g_resource)
-    {
-        groupMgr->addActionSet(g_resource, allBulbOff, onPut);
-    }
-
-    delete allBulbOff;
-}
-
-void createRecursiveActionSet_AllBulbOn()
-{
-    string actionsetDesc;
-    ActionSet *allBulbOn = new ActionSet();
-    allBulbOn->type = OIC::ACTIONSET_TYPE::RECURSIVE;
-
-    allBulbOn->actionsetName = "AllBulbOnRecursiveCall";
-    allBulbOn->mTime.tm_year = 0;
-    allBulbOn->mTime.tm_mon = 0;
-    allBulbOn->mTime.tm_mday = 0;
-    allBulbOn->mTime.tm_hour = 0;
-    allBulbOn->mTime.tm_min = 0;
-    allBulbOn->mTime.tm_sec = 5;
-
-    allBulbOn->setDelay(allBulbOn->getSecAbsTime());
-
-    for (auto iter = lights.begin(); iter != lights.end(); ++iter)
-    {
-        Action *action = new Action();
-        action->target = (*iter);
-
-        Capability *capa = new Capability();
-        capa->capability = "power";
-        capa->status = "on";
-
-        action->listOfCapability.push_back(capa);
-        allBulbOn->listOfAction.push_back(action);
-    }
-    if (g_resource)
-    {
-        groupMgr->addActionSet(g_resource, allBulbOn, onPut);
-    }
-
-    delete allBulbOn;
-}
-
-int main()
-{
-    PlatformConfig config
-    { OC::ServiceType::InProc, ModeType::Both, "0.0.0.0", 0,
-            OC::QualityOfService::LowQos };
-
-    try
-    {
-        string resourceURI = "/core/a/collection";
-        string resourceTypeName = "a.collection";
-        string resourceInterface = BATCH_INTERFACE;
-        OCPlatform::Configure(config);
-
-        // Find lights for group creation.
-        vector<string> types;
-        types.push_back("core.light");
-        groupMgr->findCandidateResources(types, &foundResources, 5);
-
-        OCStackResult res = OCPlatform::registerResource(resourceHandle, resourceURI,
-                resourceTypeName, resourceInterface, NULL, OC_DISCOVERABLE);
-
-        if( res != OC_STACK_OK )
-        {
-            cout << "Resource registeration failed." << endl;
-            return 0;
-        }
-
-        cout << "registerResource is called." << endl;
-
-        OCPlatform::bindInterfaceToResource(resourceHandle, GROUP_INTERFACE);
-        OCPlatform::bindInterfaceToResource(resourceHandle, DEFAULT_INTERFACE);
-
-        bool isRun = true;
-
-        while (isRun)
-        {
-            while (isReady)
-            {
-                int n;
-
-                cout << endl;
-                cout << "1 :: CREATE ACTIONSET" << endl;
-                cout << "2 :: EXECUTE ACTIONSET(ALLBULBON)" << endl;
-                cout << "3 :: EXECUTE ACTIONSET(ALLBULBOFF)" << endl;
-                cout << "4 :: CREATE ACTIONSET(R_ALLBULBON)" << endl;
-                cout << "\t41 :: EXECUTE ACTIONSET 42 :: CANCEL ACTIONSET" << endl;
-                cout << "5 :: CREATE ACTIONSET(S_ALLBULBON)" << endl;
-                cout << "\t51 :: EXECUTE ACTIONSET 52 :: CANCEL ACTIONSET" << endl;
-                cout << "6 :: GET ACTIONSET" << endl;
-                cout << "7 :: DELETE ACTIONSET" << endl;
-                cout << "8 :: QUIT" << endl;
-                cout << "9 :: FIND GROUP" << endl;
-                cout << "0 :: FIND BOOKMARK TO OBSERVE"
-                        << endl;
-
-                //fflush(stdin);
-                cin >> n;
-
-                if (n == 9)
-                {
-                    std::string query = OC_RSRVD_WELL_KNOWN_URI;
-                    query.append("?rt=");
-                    query.append(resourceTypeName);
-
-                    OCPlatform::findResource("",
-                            query,
-                            CT_DEFAULT,
-                            &foundResource);
-
-                    // OCPlatform::findResource("",
-                    //         query,
-                    //         OC_WIFI,
-                    //         &foundResource);
-                }
-                else if (n == 0)
-                {
-                    std::string query = OC_RSRVD_WELL_KNOWN_URI;
-                    query.append("?rt=");
-                    query.append("core.bookmark");
-
-                    OCPlatform::findResource("",
-                            query,
-                            CT_DEFAULT,
-                            &foundResource);
-                    // OCPlatform::findResource("",
-                    //         query,
-                    //         OC_WIFI,
-                    //         &foundResource);
-                }
-                else if (n == 1)
-                {
-                    createActionSet_AllBulbOff();
-                    createActionSet_AllBulbOn();
-                }
-                else if (n == 2)
-                {
-                    allBulbOn();
-                }
-                else if (n == 3)
-                {
-                    allBulbOff();
-                }
-                else if (n == 4)
-                {
-                    createRecursiveActionSet_AllBulbOn();
-                }
-                else if (n == 41)
-                {
-                    Recursive_allBulbOn();
-                }
-                else if (n == 42)
-                {
-                    CancelRecursive_allBulbOn();
-                }
-                // Exampel of
-                else if (n == 43)
-                {
-                    Recursive_allBulbOnEx();
-                }
-                else if (n == 5)
-                {
-                    createScheduledActionSet_AllBulbOff();
-                }
-                else if (n == 51)
-                {
-                    Scheduled_AllbulbOff();
-                }
-                else if (n == 52)
-                {
-                    CancelScheduled_AllBulbOff();
-                }
-                else if (n == 53)
-                {
-                    Scheduled_AllbulbOffEx();
-                }
-                else if (n == 6)
-                {
-                    groupMgr->getActionSet(g_resource, "AllBulbOff", onPost);
-                }
-                else if (n == 7)
-                {
-                    groupMgr->deleteActionSet(g_resource, "AllBulbOff", onPut);
-                }
-                else if (n == 8)
-                {
-                    isRun = false;
-                    break;
-                }
-                else if(n == 100)
-                {
-
-                    OCRepresentation rep;
-
-                    rep.setValue("power", std::string("on"));
-
-                    g_light->put(rep, QueryParamsMap(), &onPut);
-
-                }
-            }
-        }
-        usleep(500*1000);
-    }
-    catch (OCException& e)
-    {
-        cout << "ERROR :: " << e.reason() << endl;
-    }
-
-    return 0;
-}
old mode 100644 (file)
new mode 100755 (executable)
index a4fea0c..1e84422 100755 (executable)
@@ -48,8 +48,6 @@ typedef std::function< void(const HeaderOptions&, const OCRepresentation&, const
 typedef std::function< void(const HeaderOptions&, const OCRepresentation&, const int) > PutCallback;
 
 /**
- * @class GroupManager
- * @brief
  * This APIs provide functions for application to find appropriate devices (i.e. things) in network,
  * create a group of the devices, check a presence of member devices in the group, and actuate a
  * group action in a more convenient way.
@@ -75,9 +73,9 @@ public:
      * @param callback callback with OCResource vector.
      * @param waitsec time to wait to finish finding resources
      *
-     * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+     * @return Returns ::OC_STACK_OK if success, some other value upon failure.
      *
-     * NOTE: OCStackResult is defined in ocstack.h.
+     * @note OCStackResult is defined in ocstack.h.
      */
     OCStackResult findCandidateResources(std::vector< std::string > resourceTypes,
             CandidateCallback callback, int waitsec = -1);
@@ -85,7 +83,7 @@ public:
     /**
      * API for Collection member's state subscribe.
      *
-     * NOTE: NOT IMPLEMENT YET
+     * @note NOT IMPLEMENT YET
      */
     OCStackResult subscribeCollectionPresence(std::shared_ptr< OCResource > resource,
             CollectionPresenceCallback);
@@ -118,7 +116,6 @@ public:
      *
      * @return std::string return value of this API.
      *                     It returns an action set String.
-     * @note OCStackResult is defined in ocstack.h.
      */
     std::string getStringFromActionSet(const ActionSet *newActionSet);
 
@@ -140,7 +137,7 @@ public:
      * @param newActionSet pointer of ActionSet class instance
      * @param cb callback for PUT operation.
      *
-     * @return Returns ::OC_STACK_OK if success.
+     * @return Returns ::OC_STACK_OK if success, some other value upon failure.
      *
      * @note OCStackResult is defined in ocstack.h.
      */
@@ -155,7 +152,7 @@ public:
      * @param actionsetName the action set name for executing the action set
      * @param cb callback for POST operation.
      *
-     * @return Returns ::OC_STACK_OK if success.
+     * @return Returns ::OC_STACK_OK if success, some other value upon failure.
      * @note OCStackResult is defined in ocstack.h.
      */
     OCStackResult executeActionSet(std::shared_ptr< OCResource > resource,
@@ -170,7 +167,7 @@ public:
      * @param delay waiting time for until the action set run.
      * @param cb callback for POST operation.
      *
-     * @return Returns ::OC_STACK_OK if success.
+     * @return Returns ::OC_STACK_OK if success, some other value upon failure.
      * @note OCStackResult is defined in ocstack.h.
      */
     OCStackResult executeActionSet(std::shared_ptr< OCResource > resource,
@@ -184,7 +181,7 @@ public:
      * @param actionsetName the action set name for executing the action set
      * @param cb callback for POST operation.
      *
-     * @return Returns ::OC_STACK_OK if success.
+     * @return Returns ::OC_STACK_OK if success, some other value upon failure.
      * @note OCStackResult is defined in ocstack.h.
      */
     OCStackResult cancelActionSet(std::shared_ptr< OCResource > resource,
@@ -198,7 +195,7 @@ public:
      * @param actionsetName the action set name for reading the action set
      * @param cb callback for GET operation.
      *
-     * @return Returns ::OC_STACK_OK if success.
+     * @return Returns ::OC_STACK_OK if success, some other value upon failure.
      * @note OCStackResult is defined in ocstack.h.
      */
     OCStackResult getActionSet(std::shared_ptr< OCResource > resource, std::string actionsetName,
@@ -212,7 +209,7 @@ public:
      * @param actionsetName the action set name for removing the action set
      * @param cb callback for POST operation.
      *
-     * @return Returns ::OC_STACK_OK if success.
+     * @return Returns ::OC_STACK_OK if success, some other value upon failure.
      * @note OCStackResult is defined in ocstack.h.
      */
     OCStackResult deleteActionSet(std::shared_ptr< OCResource > resource, std::string actionsetName,
index ef3cbe3..2960136 100644 (file)
@@ -49,7 +49,6 @@ namespace OIC
     typedef std::string ConfigurationValue;
 
     /**
-     * @brief
      * The following class is used as a item stacking in request queue. The class stores a request
      * and referential information (e.g., a configuration name, a target resource object, a callback
      * function passed from the applications, and a update value). When the function for updating/
@@ -75,7 +74,6 @@ namespace OIC
     };
 
     /**
-     * @brief
      * The following class is used to store providing configuration name and its relevant
      * information. The relevant information includes a brief description, uri, and attribute key.
      * Note that a developer only specifies a configuration name, not URI nor attribute key, to
@@ -102,12 +100,11 @@ namespace OIC
     typedef std::string ConfigurationValue;
 
     /**
-     * @class ThingsConfiguration
-     * @brief
-     * There are two main usages of this class: (1) On a server side, bootstrapping requisite
-     * information (i.e. system configuration parameters) from a bootstrap server to access other
-     * IoT services, (2) On a client side, getting/updating the system configuration parameters
-     * from/to multiple remote things.
+     * @par There are two main usages of this class:
+     * -# On a server side, bootstrapping requisite information (i.e. system configuration parameters)
+     * from a bootstrap server to access other IoT services,
+     * -# On a client side, getting/updating the system configuration parameters from/to multiple remote things.
+     * @par
      */
     class ThingsConfiguration
     {
@@ -142,22 +139,25 @@ namespace OIC
          * by Things Configuration class and what the configuration name means.
          * To get a list of supported configuration names, use getListOfSupportedConfigurationUnits(
          * ) function, which provides the list in JSON format.
+         *
          * NOTICE: A series of callback functions is called from updateConfigurations() function:
-         * (1) For a collection resource
+         * @par
+         * -# For a collection resource
          * updateConfiguration()->onDeleteActionSet()->onGetChildInfoForUpdate()->onCreateActionSet(
          * )->...(CoAP msg. is transmitted)->OnExecuteForGroupAction()->callback function in APP.
-         * (2) For a simple resource
+         * -# For a simple resource
          * updateConfiguration()->...(CoAP msg. is transmitted)->OnPut()->callback function in APP.
+         * @par
          *
-         * @param resource resource pointer representing the target group or the single thing.
-         * @param configurations ConfigurationUnit: an attribute key of target resource
+         * @param resource resource pointer representing the target group or the single thing.
+         * @param configurations ConfigurationUnit: an attribute key of target resource
          *                         (e.g., loc, st, c, r)
          *                         Value : a value to be updated
-         * @param callback callback.
+         * @param callback callback.
          *
-         * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+         * @return Returns ::OC_STACK_OK if success, some other value upon failure.
          *
-         * NOTE: OCStackResult is defined in ocstack.h.
+         * @note OCStackResult is defined in ocstack.h.
          */
         OCStackResult updateConfigurations(std::shared_ptr< OCResource > resource,
                 std::map< ConfigurationName, ConfigurationValue > configurations,
@@ -167,20 +167,23 @@ namespace OIC
          * API for getting configuration value of multiple things of a target group or a single
          * thing.
          * Callback is called when a response arrives.
+         *
          * NOTICE: A series of callback functions is called from getConfigurations() function:
-         * (1) For a collection resource
+         * @par
+         * -# For a collection resource
          * getConfigurations()->onGetChildInfoForGet()->...(CoAP msg. is transmitted)
          * ->callback function in APP.
-         * (2) For a simple resource
+         * -# For a simple resource
          * getConfigurations()->...(CoAP msg. is transmitted)->onGet()->callback function in APP.
+         * @par
          *
-         * @param resource resource pointer representing the target group or the single thing.
-         * @param configurations ConfigurationUnit: an attribute key of target resource.
-         * @param callback callback.
+         * @param resource resource pointer representing the target group or the single thing.
+         * @param configurations ConfigurationUnit: an attribute key of target resource.
+         * @param callback callback.
          *
-         * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+         * @return Returns ::OC_STACK_OK if success, some other value upon failure.
          *
-         * NOTE: OCStackResult is defined in ocstack.h.
+         * @note OCStackResult is defined in ocstack.h.
          */
         OCStackResult getConfigurations(std::shared_ptr< OCResource > resource,
                 std::vector< ConfigurationName > configurations, ConfigurationCallback callback);
@@ -198,11 +201,11 @@ namespace OIC
          * information from the bootstrap server. With the information, make a configuration
          * resource.
          *
-         * @param callback callback.
+         * @param callback callback.
          *
-         * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+         * @return Returns ::OC_STACK_OK if success, some other value upon failure.
          *
-         * NOTE: OCStackResult is defined in ocstack.h.
+         * @note OCStackResult is defined in ocstack.h.
          */
         OCStackResult doBootstrap(ConfigurationCallback callback);
 
index 1ebda05..d4797c5 100644 (file)
@@ -45,7 +45,6 @@ namespace OIC
             > MaintenanceCallback;
 
     /**
-     *  @brief
      *  The following class is used as a item stacking in request queue. The class stores a request
      *  and referential information (e.g., a maintenance name, a target resource object, a callback
      *  function passed from the applications, and a update value). When the function for updating/
@@ -74,7 +73,6 @@ namespace OIC
     };
 
     /**
-     *  @brief
      *  The following class is used to store providing maintenance name and its relevant information
      *  The relevant information includes a brief description, uri, and attribute key.
      *  Note that a developer only specifies a maintenance name, not URI nor attribute key, to
@@ -100,10 +98,12 @@ namespace OIC
     typedef std::string MaintenanceValue;
 
     /**
-     * @class ThingsMaintenance
-     * @brief
-     * There are two functionalities in Things Maintenance; (1) FactoryReset to restore all
-     * configuration parameters to default one, and (2) Reboot to request a system rebooting.
+     * There are two functionalities in Things Maintenance;
+     * @par
+     * -# FactoryReset to restore all configuration parameters to default one, and
+     * -# Reboot to request a system rebooting.
+     * @par
+     *
      */
     class ThingsMaintenance
     {
@@ -129,12 +129,12 @@ namespace OIC
          * API to make things reboot
          * Callback call when a response arrives.
          *
-         * @param resource resource pointer representing the target group
-         * @param callback callback.
+         * @param resource resource pointer representing the target group
+         * @param callback callback.
          *
-         * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+         * @return Returns ::OC_STACK_OK if success, some other value upon failure.
          *
-         * NOTE: OCStackResult is defined in ocstack.h.
+         * @note OCStackResult is defined in ocstack.h.
          */
         OCStackResult reboot(std::shared_ptr< OCResource > resource, MaintenanceCallback callback);
 
@@ -142,12 +142,12 @@ namespace OIC
          * API for factory reset on device
          * Callback call when a response arrives.
          *
-         * @param resource resource pointer representing the target group
-         * @param callback callback.
+         * @param resource resource pointer representing the target group
+         * @param callback callback.
          *
-         * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+         * @return Returns ::OC_STACK_OK if success, some other value upon failure.
          *
-         * NOTE: OCStackResult is defined in ocstack.h.
+         * @note OCStackResult is defined in ocstack.h.
          */
 
         OCStackResult factoryReset(std::shared_ptr< OCResource > resource,
index 2a59a1e..d6232a0 100644 (file)
@@ -37,7 +37,6 @@ tm_jni_src = [tm_jni_env.Glob('tm/src/*.cpp'), tm_jni_env.Glob('jniutil/src/*.cp
 tm_jni = tm_jni_env.SharedLibrary('things-manager-jni', tm_jni_src)
 
 tm_jni_env.InstallTarget(tm_jni, 'libthings-manager-jni')
-tm_jni_env.UserInstallTargetLib(tm_jni, 'libthings-manager-jni')
 
 # Install the libraries to /libs/<TARGET_ARCH> directory
 tm_jni_env.Install(tm_sdk+'/java/libs/'+tm_jni_env.get('TARGET_ARCH'),tm_jni_env.get('BUILD_DIR')+'/liboc_logger.so')
old mode 100644 (file)
new mode 100755 (executable)
index 910a5e6..e925ca9
@@ -23,7 +23,7 @@ using namespace std;
 
 namespace OIC
 {
-Time::Time()
+Time::Time() : mTime()
 {
     setTime(0, 0, 0, 0, 0, 0, 0);
 }
@@ -40,12 +40,9 @@ void Time::setTime(unsigned int yy, unsigned int mm, unsigned int dd,
         unsigned int h, unsigned int m, unsigned int s,
         int dayoftheweek = 0)
 {
-    yy -= 1900;
-    mm -= 1;
-
     mDelay = 0;
-    mTime.tm_year = yy;
-    mTime.tm_mon = mm;
+    mTime.tm_year = (int)yy - 1900;
+    mTime.tm_mon = (int)mm - 1;
     mTime.tm_mday = dd;
 
     mTime.tm_hour = h;
index 6249e31..8bbe52f 100755 (executable)
@@ -30,7 +30,6 @@
 
 #include "GroupManager.h"
 
-#define PLAIN_DELIMITER "\""
 #define ACTION_DELIMITER "*"
 #define DESC_DELIMITER "|"
 #define ATTR_DELIMITER "="
@@ -505,8 +504,10 @@ ActionSet* GroupManager::getActionSetfromString(std::string description)
     }
 
     plainText = new char[(description.length() + 1)];
-    strcpy(plainText, description.c_str());
+    strncpy(plainText, description.c_str(), description.length()+1);
 
+    // All tokens are seperated by "*" character.
+    // First token means an actionset name
     token = strtok_r(plainText, ACTION_DELIMITER, &plainPtr);
 
     if (token != NULL)
@@ -516,6 +517,7 @@ ActionSet* GroupManager::getActionSetfromString(std::string description)
         if((actionset->actionsetName).empty())
             goto exit;
 
+        // Find the second token
         token = strtok_r(NULL, ACTION_DELIMITER, &plainPtr);
     }
     else
@@ -525,8 +527,35 @@ ActionSet* GroupManager::getActionSetfromString(std::string description)
 
     if (token != NULL)
     {
-        sscanf(token, "%ld %d", &actionset->mDelay, (int*)&actionset->type);
+        // The second token consists of two digits: time delay and actionset Type.
+        // Time delay is used as a parameter to scheduled/recursive group action feature
+        // And actionset type indicates if the actionset is scheduled or recursive group action.
+        char *subText = NULL;
+        char *subToken = NULL;
+        char *subTextPtr = NULL;
 
+        subText = new char[strlen(token)+1];
+        strncpy(subText, token, strlen(token)+1);
+
+        subToken = strtok_r(subText, " ", &subTextPtr);
+        if(subToken == NULL)
+        {
+            DELETEARRAY(subText);
+            goto exit;
+        }
+        actionset->mDelay = atol(subToken);
+
+        subToken = strtok_r(NULL, " ", &subTextPtr);
+        if(subToken == NULL)
+        {
+            DELETEARRAY(subText);
+            goto exit;
+        }
+        actionset->type = (OIC::ACTIONSET_TYPE)atoi(subToken);
+
+        DELETEARRAY(subText);
+
+        // Find the third token
         token = strtok_r(NULL, ACTION_DELIMITER, &plainPtr);
     }
     else
@@ -536,25 +565,33 @@ ActionSet* GroupManager::getActionSetfromString(std::string description)
 
     while (token)
     {
+        // The third token consists of two sub-segement: host address plus URI and attribute key/value pair.
+        // These two segments can be divided by "|" character.
+        // The third token can be repeatively appeared.
+
         char *descPtr = NULL;
         desc = new char[(strlen(token) + 1)];
 
         if (desc != NULL)
         {
-            strcpy(desc, token);
+            // copy a host address plus URI string from the third token
+            strncpy(desc, token, (strlen(token) + 1));
+
+            // Find "|" character to find key/value pair
             token = strtok_r(desc, DESC_DELIMITER, &descPtr);
 
             while (token != NULL)
             {
                 char *attrPtr = NULL;
                 attr = new char[(strlen(token) + 1)];
-
+                // copy the host address plus URI string
                 strcpy(attr, token);
 
+                // Find "=" charactor to divide attribute key and value string.
                 token = strtok_r(attr, ATTR_DELIMITER, &attrPtr);
                 while (token != NULL)
                 {
-                    if ( (action == NULL) && strcmp(token, "uri") == 0)    //consider only first "uri" as uri, other as attribute.
+                    if ( (action == NULL) && strcmp(token, "uri") == 0)
                     {
                         token = strtok_r(NULL, ATTR_DELIMITER, &attrPtr);
                         if(token == NULL)
@@ -607,7 +644,6 @@ ActionSet* GroupManager::getActionSetfromString(std::string description)
         else
         {
             goto exit;
-
         }
 
         DELETEARRAY(desc);
index 2d018eb..980a075 100755 (executable)
@@ -558,7 +558,7 @@ void MaintenanceResource::maintenanceMonitor(int second)
             int res;
             std::cout << "Reboot will be soon..." << std::endl;
             m_reboot = defaultReboot;
-            res = system("sudo reboot");
+            res = system("/usr/bin/sudo /etc/init.d/reboot");
 
             std::cout << "return: " << res << std::endl;
 
index 8383446..1dfd837 100644 (file)
@@ -90,7 +90,7 @@ if target_os == 'android':
                lib_env.AppendUnique(CCFLAGS = ['-w'])
 
 elif target_os == 'ios':
-       lib_env.AppendUnique(FRAMEWORKS = ['boost', 'expat', 'openssl'])
+       lib_env.AppendUnique(FRAMEWORKS = ['boost', 'openssl'])
 elif target_os == 'darwin':
        lib_env.AppendUnique(CPPPATH = ['/usr/local/include'])
        lib_env.AppendUnique(LIBPATH = ['/usr/local/lib'])
index 474bb6b..dc94e18 100644 (file)
    fun:g_malloc0
    obj:/usr/lib/*/libgobject-2.0*.so.*
 }
+{
+   glib/g-dbus-connection-send-message-with-reply-sync
+   Memcheck:Leak
+   ...
+   fun:g_dbus_connection_send_message_with_reply_sync
+}
 # ************************************************************************